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

bool isValid(char[] cs) {
  int now;
  foreach (c; cs) {
    if (c == '(') {
      ++now;
    } else if (c == ')') {
      if (--now < 0) {
        return false;
      }
    } else {
      assert(false);
    }
  }
  return (now == 0);
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const S = readToken();

        auto as = new char[N];
        auto bs = new char[N];

        const cnt1 = cast(int)(S.count('1'));
        int pos0, pos1;
        foreach (i; 0 .. N) {
          if (S[i] == '0') {
            if (pos0 % 2 == 0) {
              as[i] = '(';
              bs[i] = ')';
            } else {
              as[i] = ')';
              bs[i] = '(';
            }
            ++pos0;
          } else {
            if (pos1 < cnt1 / 2) {
              as[i] = bs[i] = '(';
            } else {
              as[i] = bs[i] = ')';
            }
            ++pos1;
          }
        }
        debug {
          writeln("as = ", as);
          writeln("bs = ", bs);
        }

        bool ok = true;
        ok = ok && isValid(as);
        ok = ok && isValid(bs);
        if (ok) {
          writeln("YES");
          writeln(as);
          writeln(bs);
        } else {
          writeln("NO");
        }
      }
    }
  } catch (EOFException e) {
  }
}

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(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 string[][](t, 2);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!string;

		long cnt0, cnt1;
		foreach (i; 0..n)
		{
			if (s[i] == '0')
				++cnt0;
			else
				++cnt1;
		}

		long c0, c1;
		foreach (i; 0..n)
		{
			if (s[i] == '0')
			{
				ans[ti][0] ~= c0 % 2 ? ')' : '(';
				++c0;
			}
			else
			{
				ans[ti][0] ~= c1 < cnt1/2 ? '(' : ')';
				++c1;
			}
		}

		foreach (i; 0..n)
		{
			if (s[i] == '1')
				ans[ti][1] ~= ans[ti][0][i];
			else
				ans[ti][1] ~= ans[ti][0][i] == '(' ? ')' : '(';
		}

		bool ok = true;
		long cnt;
		foreach (i; 0..n)
		{
			if (ans[ti][1][i] == '(')
				++cnt;
			else
				--cnt;
			if (cnt < 0)
			{
				ok = false;
				break;
			}
		}
		if (cnt != 0)
			ok = false;
		if (!ok)
			ans[ti].length = 0;
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			writeln(e[0]);
			writeln(e[1]);
		}
	}
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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(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 string[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!string;

		foreach (i; 0..n)
		{
			if (s[i] == '1')
				ans[ti] ~= i % 2 ? ')' : '(';
			else
				ans[ti] ~= i % 2 ? '(' : ')';
		}

		bool ok = true;
		long cnt;
		foreach (i; 0..n)
		{
			if (ans[ti][i] == '(')
				++cnt;
			else
				--cnt;
			if (cnt < 0)
			{
				ok = false;
				break;
			}
		}
		if (cnt != 0)
			ok = false;
		if (!ok)
			ans[ti].length = 0;
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			foreach (i; 0..e.length)
				write(i % 2 ? ")" : "(");
			writeln;
			writeln(e);
		}
	}
	stdout.flush;
	debug readln;
}


import std.stdio;
import std.algorithm;
import std.typecons;
import std.container;

immutable int inf = cast(int)1e9 + 5;
alias Node = Tuple!(int, "L", int, "R", long, "cnt", int, "len");

Node merge(in Node a, in Node b) {
	Node res;
	res.len = a.len + b.len;
	res.L = (a.len == a.L ? a.len + b.L : a.L);
	res.R = (b.len == b.R ? b.len + a.R : b.R);
	res.cnt = a.cnt + b.cnt + cast(long)a.R * b.L;
	return res;
}

class IT {
	Node[] T;
	int size;
	this(int _size = 0) {
		size = _size;
		T = new Node[4 * size];
		init(1, 1, size);
	}
	void init(int v, int l, int r) {
		if (l == r) { T[v].len = 1; return; }
		int mid = (l + r) >> 1;
		init(2 * v, l, mid); init(2 * v + 1, mid + 1, r);
		T[v].len = T[2 * v].len + T[2 * v + 1].len;
	}
	void up(int v, int l, int r, int pos) {
		int mid = (l + r) >> 1;
		if (l > pos || r < pos) return;
		if (l == r) {
			T[v].L = T[v].R = T[v].cnt = T[v].len = 1; return;
		}
		up(2 * v, l, mid, pos); up(2 * v + 1, mid + 1, r, pos);
		T[v] = merge(T[2 * v], T[2 * v + 1]);
	}
	Node get(int v, int l, int r, int i, int j) {
		int mid = (l + r) >> 1;
		if (l > j || r < i) return Node();
		if (i <= l && r <= j) return T[v];
		return merge(get(2 * v, l, mid, i, j), get(2 * v + 1, mid + 1, r, i, j));
	}
}

IT T;

int N;
int[] A, B;

int[] leftEq, rightSm;

void doStack() {
	auto st = SList!int();
	leftEq = new int[N + 2];
	rightSm = new int[N + 2];
	B[0] = B[N + 1] = -inf;
	st.insertFront(0);
	foreach (i; 1..N + 1) {
		while (B[i] <= B[st.front]) st.removeFront();
		leftEq[i] = st.front + 1; st.insertFront(i);
	}
	st = SList!int();
	st.insertFront(N + 1);
	for (int i = N; i >= 1; --i) {
		while (B[i] < B[st.front]) st.removeFront();
		rightSm[i] = st.front - 1; st.insertFront(i);
	}
}

int[] Aidx, Bidx;

long get(int i, int k, int j) {
	return T.get(1, 1, N, i, j).cnt - T.get(1, 1, N, i, k - 1).cnt - T.get(1, 1, N, k + 1, j).cnt;
}

void main() {
	readf("%d", &N);
	A = new int[N + 2];
	B = new int[N + 2];
	Aidx = new int[N + 2];
	Bidx = new int[N + 2];
	T = new IT(N);
	foreach (i; 1..N + 1) readf(" %d", &A[i]);
	foreach (i; 1..N + 1) readf(" %d", &B[i]);
	doStack();
	foreach (i; 1..N + 1) Aidx[i] = Bidx[i] = i;
	sort!((a, b) => (A[a] < A[b]))(Aidx[1..N+1]);
	sort!((a, b) => (B[a] < B[b]))(Bidx[1..N+1]);
	long ans = 0; int cur = 1;
	for (int i = 1; i <= N; ++i) {
		int st = i, j = i;
		while (cur <= N && A[Aidx[cur]] < B[Bidx[st]]) T.up(1, 1, N, Aidx[cur++]);
		while (j <= N && B[Bidx[st]] == B[Bidx[j]]) {
			int id = Bidx[j];
			ans -= get(leftEq[id], id, rightSm[id]);
			//writeln(id, ' ', leftEq[id], ' ', rightSm[id], ' ', ans);
			++j;
		}
		while (cur <= N && A[Aidx[cur]] <= B[Bidx[st]]) T.up(1, 1, N, Aidx[cur++]);
		while (i <= N && B[Bidx[st]] == B[Bidx[i]]) {
			int id = Bidx[i];
			ans += get(leftEq[id], id, rightSm[id]);
			//writeln(id, ' ', leftEq[id], ' ', rightSm[id], ' ', ans);
			++i;
		} --i;
	}
	writeln(ans);
}

import std.stdio, std.conv;
import std.algorithm, std.range, std.random;
import std.string, std.array, std.container, std.bigint;
import std.exception;

struct SparseRMQ(int S) {
    immutable int N = 1<<S;
    int[][] a, b;
    this(int[] _a, int[] _b) {
        a = new int[][](S, N);
         b = new int[][](S, N);
        _a.copy(a[0]);
        _b.copy(b[0]);
        int l = 1;
        for (int s = 1; s < S; s++) {
            for (int i = 0; i < N - l; i++) {
                a[s][i] = max(a[s-1][i], a[s-1][i + l]);
                b[s][i] = min(b[s-1][i], b[s-1][i + l]);
            }
            l <<= 1;
        }
    }
    int[2] query(int l, int r) {
        import core.bitop : bsr;
        if (l == r) return [-1, 10^^9+10^^8];
        int u = bsr(r-l);
        return [max(a[u][l], a[u][r-(1<<u)]), min(b[u][l], b[u][r-(1<<u)])];
    }
}

int main() {
    int n = readln.strip.to!int;
    int[] a = readln.split.map!(to!int).array;
    int[] b = readln.split.map!(to!int).array;

    SparseRMQ!(18) sp = SparseRMQ!(18)(a, b);

    long ans = 0;
    foreach (i; 0..n) {
        int X, Y, l, r;
        l = i; r = n+1;
        while (r-l > 1) {
            int md = (l+r)/2;
            int[2] q = sp.query(i, md);
            if (q[0] < q[1]) {
                l = md;
            } else {
                r = md;
            }
        }
        X = r;
        l = i; r = n+1;
        while (r-l > 1) {
            int md = (l+r)/2;
            int[2] q = sp.query(i, md);
            if (q[0] <= q[1]) {
                l = md;
            } else {
                r = md;
            }
        }
        Y = r;
        ans += cast(long)(Y-X);
    }
    writeln(ans);
	return 0;
}

string readToken() {
    import std.stdio : readln;
    import std.string : split;
    static size_t pos;
    static string[] tokens;
    while (!(pos < tokens.length)) {
        pos = 0;
        tokens = readln.split;
    }
    return tokens[pos++];
}
T read(T)() {
    import std.conv : to;
    return readToken.to!T;
}

import std.stdio;
import std.algorithm;
import std.typecons;
import std.container;

immutable int inf = cast(int)1e9;
alias Node = Tuple!(int, "L", int, "R", long, "cnt", int, "len");

Node merge(in Node a, in Node b) {
	Node res;
	res.len = a.len + b.len;
	res.L = (a.len == a.L ? a.len + b.L : a.L);
	res.R = (b.len == b.R ? b.len + a.R : b.R);
	res.cnt = a.cnt + b.cnt + cast(long)a.R * b.L;
	return res;
}

class IT {
	Node[] T;
	int size;
	this(int _size = 0) {
		size = _size;
		T = new Node[4 * size];
		for (int i = 1; i < 4 * size; ++i) T[i].len = 1;
	}
	void up(int v, int l, int r, int pos) {
		int mid = (l + r) >> 1;
		if (l > pos || r < pos) return;
		if (l == r) {
			T[v].L = T[v].R = T[v].cnt = T[v].len = 1; return;
		}
		up(2 * v, l, mid, pos); up(2 * v + 1, mid + 1, r, pos);
		T[v] = merge(T[2 * v], T[2 * v + 1]);
	}
	Node get(int v, int l, int r, int i, int j) {
		int mid = (l + r) >> 1;
		if (l > j || r < i) return Node();
		if (i <= l && r <= j) return T[v];
		return merge(get(2 * v, l, mid, i, j), get(2 * v + 1, mid + 1, r, i, j));
	}
}

IT T;

int N;
int[] A, B;

int[] leftEq, rightSm;

void doStack() {
	auto st = SList!int();
	leftEq = new int[N + 2];
	rightSm = new int[N + 2];
	B[0] = B[N + 1] = -inf;
	st.insertFront(0);
	foreach (i; 1..N + 1) {
		while (B[i] <= B[st.front]) st.removeFront();
		leftEq[i] = st.front + 1; st.insertFront(i);
	}
	st = SList!int();
	st.insertFront(N + 1);
	for (int i = N; i >= 1; --i) {
		while (B[i] < B[st.front]) st.removeFront();
		rightSm[i] = st.front - 1; st.insertFront(i);
	}
}

int[] Aidx, Bidx;

long get(int i, int k, int j) {
	return T.get(1, 1, N, i, j).cnt - T.get(1, 1, N, i, k - 1).cnt - T.get(1, 1, N, k + 1, j).cnt;
}

void main() {
	readf("%d", &N);
	A = new int[N + 2];
	B = new int[N + 2];
	Aidx = new int[N + 2];
	Bidx = new int[N + 2];
	T = new IT(N);
	foreach (i; 1..N + 1) readf(" %d", &A[i]);
	foreach (i; 1..N + 1) readf(" %d", &B[i]);
	doStack();
	foreach (i; 1..N + 1) Aidx[i] = Bidx[i] = i;
	sort!((a, b) => (A[a] < A[b]))(Aidx[1..N+1]);
	sort!((a, b) => (B[a] < B[b]))(Bidx[1..N+1]);
	long ans = 0; int cur = 0;
	for (int i = 1; i <= N; ++i) {
		int st = i, j = i;
		while (cur <= N && A[Aidx[cur]] < B[Bidx[st]]) T.up(1, 1, N, Aidx[cur++]);
		while (j <= N && B[Bidx[st]] == B[Bidx[j]]) {
			int id = Bidx[j];
			ans -= get(leftEq[id], id, rightSm[id]);
			//writeln(id, ' ', leftEq[id], ' ', rightSm[id], ' ', ans);
			++j;
		}
		while (cur <= N && A[Aidx[cur]] <= B[Bidx[st]]) T.up(1, 1, N, Aidx[cur++]);
		while (i <= N && B[Bidx[st]] == B[Bidx[i]]) {
			int id = Bidx[i];
			ans += get(leftEq[id], id, rightSm[id]);
			//writeln(id, ' ', leftEq[id], ' ', rightSm[id], ' ', ans);
			++i;
		} --i;
	}
	writeln(ans);
}

import std.stdio;
import std.algorithm;
import std.typecons;
import std.container;

immutable int inf = cast(int)1e9;
alias Node = Tuple!(int, "L", int, "R", long, "cnt", int, "len");

Node merge(in Node a, in Node b) {
	Node res;
	res.len = a.len + b.len;
	res.L = (a.len == a.L ? a.len + b.L : a.L);
	res.R = (b.len == b.R ? b.len + a.R : b.R);
	res.cnt = a.cnt + b.cnt + cast(long)a.R * b.L;
	return res;
}

class IT {
	Node[] T;
	int size;
	this(int _size = 0) {
		size = _size;
		T = new Node[4 * size];
		init(1, 1, size);
	}
	void init(int v, int l, int r) {
		if (l == r) { T[v].len = 1; return; }
		int mid = (l + r) >> 1;
		init(2 * v, l, mid); init(2 * v + 1, mid + 1, r);
		T[v].len = T[2 * v].len + T[2 * v + 1].len;
	}
	void up(int v, int l, int r, int pos) {
		int mid = (l + r) >> 1;
		if (l > pos || r < pos) return;
		if (l == r) {
			T[v].L = T[v].R = T[v].cnt = T[v].len = 1; return;
		}
		up(2 * v, l, mid, pos); up(2 * v + 1, mid + 1, r, pos);
		T[v] = merge(T[2 * v], T[2 * v + 1]);
	}
	Node get(int v, int l, int r, int i, int j) {
		int mid = (l + r) >> 1;
		if (l > j || r < i) return Node();
		if (i <= l && r <= j) return T[v];
		return merge(get(2 * v, l, mid, i, j), get(2 * v + 1, mid + 1, r, i, j));
	}
}

IT T;

int N;
int[] A, B;

int[] leftEq, rightSm;

void doStack() {
	auto st = SList!int();
	leftEq = new int[N + 2];
	rightSm = new int[N + 2];
	B[0] = B[N + 1] = -inf;
	st.insertFront(0);
	foreach (i; 1..N + 1) {
		while (B[i] <= B[st.front]) st.removeFront();
		leftEq[i] = st.front + 1; st.insertFront(i);
	}
	st = SList!int();
	st.insertFront(N + 1);
	for (int i = N; i >= 1; --i) {
		while (B[i] < B[st.front]) st.removeFront();
		rightSm[i] = st.front - 1; st.insertFront(i);
	}
}

int[] Aidx, Bidx;

long get(int i, int k, int j) {
	return T.get(1, 1, N, i, j).cnt - T.get(1, 1, N, i, k - 1).cnt - T.get(1, 1, N, k + 1, j).cnt;
}

void main() {
	readf("%d", &N);
	A = new int[N + 2];
	B = new int[N + 2];
	Aidx = new int[N + 2];
	Bidx = new int[N + 2];
	T = new IT(N);
	foreach (i; 1..N + 1) readf(" %d", &A[i]);
	foreach (i; 1..N + 1) readf(" %d", &B[i]);
	doStack();
	foreach (i; 1..N + 1) Aidx[i] = Bidx[i] = i;
	sort!((a, b) => (A[a] < A[b]))(Aidx[1..N+1]);
	sort!((a, b) => (B[a] < B[b]))(Bidx[1..N+1]);
	long ans = 0; int cur = 0;
	for (int i = 1; i <= N; ++i) {
		int st = i, j = i;
		while (cur <= N && A[Aidx[cur]] < B[Bidx[st]]) T.up(1, 1, N, Aidx[cur++]);
		while (j <= N && B[Bidx[st]] == B[Bidx[j]]) {
			int id = Bidx[j];
			ans -= get(leftEq[id], id, rightSm[id]);
			//writeln(id, ' ', leftEq[id], ' ', rightSm[id], ' ', ans);
			++j;
		}
		while (cur <= N && A[Aidx[cur]] <= B[Bidx[st]]) T.up(1, 1, N, Aidx[cur++]);
		while (i <= N && B[Bidx[st]] == B[Bidx[i]]) {
			int id = Bidx[i];
			ans += get(leftEq[id], id, rightSm[id]);
			//writeln(id, ' ', leftEq[id], ' ', rightSm[id], ' ', ans);
			++i;
		} --i;
	}
	writeln(ans);
}

import std.stdio;
import std.algorithm;
import std.typecons;
import std.container;

immutable int inf = cast(int)1e9 + 5;
alias Node = Tuple!(int, "L", int, "R", long, "cnt", int, "len");

Node merge(in Node a, in Node b) {
	Node res;
	res.len = a.len + b.len;
	res.L = (a.len == a.L ? a.len + b.L : a.L);
	res.R = (b.len == b.R ? b.len + a.R : b.R);
	res.cnt = a.cnt + b.cnt + cast(long)a.R * b.L;
	return res;
}

class IT {
	Node[] T;
	int size;
	this(int _size = 0) {
		size = _size;
		T = new Node[4 * size];
		init(1, 1, size);
	}
	void init(int v, int l, int r) {
		if (l == r) { T[v].len = 1; return; }
		int mid = (l + r) >> 1;
		init(2 * v, l, mid); init(2 * v + 1, mid + 1, r);
		T[v].len = T[2 * v].len + T[2 * v + 1].len;
	}
	void up(int v, int l, int r, int pos) {
		int mid = (l + r) >> 1;
		if (l > pos || r < pos) return;
		if (l == r) {
			T[v].L = T[v].R = T[v].cnt = T[v].len = 1; return;
		}
		up(2 * v, l, mid, pos); up(2 * v + 1, mid + 1, r, pos);
		T[v] = merge(T[2 * v], T[2 * v + 1]);
	}
	Node get(int v, int l, int r, int i, int j) {
		int mid = (l + r) >> 1;
		if (l > j || r < i) return Node();
		if (i <= l && r <= j) return T[v];
		return merge(get(2 * v, l, mid, i, j), get(2 * v + 1, mid + 1, r, i, j));
	}
}

IT T;

int N;
int[] A, B;

int[] leftEq, rightSm;

void doStack() {
	auto st = SList!int();
	leftEq = new int[N + 2];
	rightSm = new int[N + 2];
	B[0] = B[N + 1] = -inf;
	st.insertFront(0);
	foreach (i; 1..N + 1) {
		while (B[i] <= B[st.front]) st.removeFront();
		leftEq[i] = st.front + 1; st.insertFront(i);
	}
	st = SList!int();
	st.insertFront(N + 1);
	for (int i = N; i >= 1; --i) {
		while (B[i] < B[st.front]) st.removeFront();
		rightSm[i] = st.front - 1; st.insertFront(i);
	}
}

int[] Aidx, Bidx;

long get(int i, int k, int j) {
	return T.get(1, 1, N, i, j).cnt - T.get(1, 1, N, i, k - 1).cnt - T.get(1, 1, N, k + 1, j).cnt;
}

void main() {
	readf("%d", &N);
	A = new int[N + 2];
	B = new int[N + 2];
	Aidx = new int[N + 2];
	Bidx = new int[N + 2];
	T = new IT(N);
	foreach (i; 1..N + 1) readf(" %d", &A[i]);
	foreach (i; 1..N + 1) readf(" %d", &B[i]);
	doStack();
	foreach (i; 1..N + 1) Aidx[i] = Bidx[i] = i;
	sort!((a, b) => (A[a] < A[b]))(Aidx[1..N+1]);
	sort!((a, b) => (B[a] < B[b]))(Bidx[1..N+1]);
	long ans = 0; int cur = 0;
	for (int i = 1; i <= N; ++i) {
		int st = i, j = i;
		while (cur <= N && A[Aidx[cur]] < B[Bidx[st]]) T.up(1, 1, N, Aidx[cur++]);
		while (j <= N && B[Bidx[st]] == B[Bidx[j]]) {
			int id = Bidx[j];
			ans -= get(leftEq[id], id, rightSm[id]);
			//writeln(id, ' ', leftEq[id], ' ', rightSm[id], ' ', ans);
			++j;
		}
		while (cur <= N && A[Aidx[cur]] <= B[Bidx[st]]) T.up(1, 1, N, Aidx[cur++]);
		while (i <= N && B[Bidx[st]] == B[Bidx[i]]) {
			int id = Bidx[i];
			ans += get(leftEq[id], id, rightSm[id]);
			//writeln(id, ' ', leftEq[id], ' ', rightSm[id], ' ', ans);
			++i;
		} --i;
	}
	writeln(ans);
}


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

void main ()
{
	readln;
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		auto can0 = new int [k * 2 + 2];
		auto can1 = new int [k * 2 + 2];
		foreach (i; 0..n / 2)
		{
			auto u = a[i];
			auto v = a[n - i - 1];
			can0[u + v] += 1;
			can1[min (u, v) + 1] += 1;
			can1[max (u, v) + k + 1] -= 1;
		}

		auto sum1 = new int [k * 2 + 1];
		foreach (i; 1..k * 2 + 1)
		{
			sum1[i] = sum1[i - 1] + can1[i];
		}

		int res = n;
		foreach (i; 0..k * 2 + 1)
		{
			int cur0 = can0[i];
			int cur1 = sum1[i] - cur0;
			int cur2 = n / 2 - cur0 - cur1;
			res = min (res, 0 * cur0 + 1 * cur1 + 2 * cur2);
		}
		writeln (res);
	}
}

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 k = RD!int;
		auto a = RDA!int();

		auto cnt1 = new long[](k+1);
		auto cnt2 = new long[](k+1);
		auto cnt = new long[](k*2+1);
		foreach (i; 0..n/2)
		{
			auto x = cast(int)min(a[i], a[n-i-1]);
			auto y = cast(int)max(a[i], a[n-i-1]);
			auto z = a[i] + a[n-i-1];
			++cnt1[x];
			++cnt2[y];
			++cnt[z];
		}

		ans[ti] = long.max;
		{
			long c;
			foreach_reverse (i; 2..k+1)
			{
				c += cnt1[i];
				auto tmp = c*2 + ((n/2) - c - cnt[i]);
				ans[ti].chmin(tmp);
				debug writeln("i:", i, " c:", c, " cnt[i]:", cnt[i], " tmp:", tmp);
			}
		}
		{
			long c;
			foreach (i; k+1..k*2+1)
			{
				c += cnt2[i-k-1];
				auto tmp = c*2 + ((n/2) - c - cnt[i]);
				ans[ti].chmin(tmp);
				debug writeln("i:", i, " c:", c, " cnt[i]:", cnt[i], " tmp:", tmp);
			}
		}
	}

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

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 t;
    readf("%s", &t);
    readln;

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

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

        auto need = new int[2*k + 2];

        foreach (i; 0 .. n / 2) {
            int mn = min(arr[i], arr[n-1 - i]);
            int mx = max(arr[i], arr[n-1 - i]);

            need[2] += 2;
            need[mn + 1] -= 1;
            need[mn + mx] -= 1;
            need[mn + mx + 1] += 1;
            need[mx + k + 1] += 1;
        }

        debug { need.writeln; }

        foreach (i; 1 .. 2*k + 1) { need[i] += need[i-1]; }

        auto ans = need[2 ..  2*k + 1].minElement;

        ans.writeln;
    }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto nk = readln.split.to!(int[]);
        auto N = nk[0];
        auto K = nk[1];
        auto as = readln.split.to!(int[]);

        auto ns = new int[]((K*2+2).to!size_t);
        foreach (i; 0..N/2) {
            auto x = as[i.to!size_t];
            auto y = as[(N-i-1).to!size_t];
            if (x > y) swap(x, y);
            auto p = x+y;
            ns[0] += 2;
            ns[(x+1).to!size_t] -= 1;
            ns[p.to!size_t] -= 1;
            ns[(p+1).to!size_t] += 1;
            ns[(y+K+1).to!size_t] += 1;
        }
        foreach (i; 0..ns.length-1) {
            ns[i+1] += ns[i];
        }

        int min_n = int.max;
        foreach (i; 0..ns.length) {
            min_n = min(min_n, ns[i]);
        }
        writeln(min_n);
    }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto nk = readln.split.to!(long[]);
        auto N = nk[0];
        auto K = nk[1];
        auto as = readln.split.to!(long[]);

        auto ns = new long[]((N*2+2).to!size_t);
        foreach (i; 0..N/2) {
            auto x = as[i.to!size_t];
            auto y = as[(N-i-1).to!size_t];
            if (x > y) swap(x, y);
            auto p = x+y;
            ns[0] += 2;
            ns[(x+1).to!size_t] -= 1;
            ns[p.to!size_t] -= 1;
            ns[(p+1).to!size_t] += 1;
            ns[(y+K+1).to!size_t] += 1;
        }
        foreach (i; 0..(N*2+1).to!size_t) {
            ns[i+1] += ns[i];
        }

        long min_n = long.max;
        foreach (i; 0..(N+2+2).to!size_t) {
            min_n = min(min_n, ns[i]);
        }
        writeln(min_n);
    }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto nk = readln.split.to!(long[]);
        auto N = nk[0];
        auto K = nk[1];
        auto as = readln.split.to!(long[]);

        long solve(long p) {
            long r;
            foreach (i; 0..N/2) {
                auto x = as[i.to!size_t];
                auto y = as[(N-i-1).to!size_t];
                if (x > y) swap(x, y);
                if (x+y < p) {
                    r += K-x >= p-x-y ? 1 : 2;
                } else if (x+y > p) {
                    r += p-x > 0 ? 1 : 2;
                }
            }
            return r;
        }

        long[] bs;
        foreach (i; 0..N/2) {
            bs ~= as[i.to!size_t] + as[(N-i-1).to!size_t];
        }
        sort(bs);
        if ((N/2)%2 == 1) {
            writeln(solve(bs[(N/4).to!size_t]));
        } else {
            auto a = bs[(N/4-1).to!size_t];
            auto b = bs[(N/4).to!size_t];
            writeln(min(
                solve(a),
                solve(b),
                solve((a+b)/2),
                solve((a+b+1)/2)
            ));
        }
    }
}

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 k = RD!int;
		auto a = RDA!int();

		auto cnt1 = new long[](k+1);
		auto cnt2 = new long[](k+1);
		auto cnt = new long[](k*2+1);
		foreach (i; 0..n/2)
		{
			auto x = cast(int)min(a[i], a[n-i-1]);
			auto y = cast(int)max(a[i], a[n-i-1]);
			auto z = a[i] + a[n-i-1];
			++cnt1[x];
			++cnt2[y];
			++cnt[z];
		}

		ans[ti] = long.max;
		{
			long c;
			foreach_reverse (i; 2..k+1)
			{
				c += cnt1[i];
				auto tmp = c*2 + (n - c - cnt[i]);
				ans[ti].chmin(tmp);
			}
		}
		{
			long c;
			foreach (i; k+1..k*2+1)
			{
				c += cnt2[(i-1)/2-1];
				auto tmp = c*2 + ((n/2) - c - cnt[i]);
				ans[ti].chmin(tmp);
				debug writeln("i:", i, " c:", c, " cnt[i]:", cnt[i]);
			}
		}
	}

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 k = RD!int;
		auto a = RDA!int();

		auto cnt1 = new long[](k+1);
		auto cnt2 = new long[](k+1);
		auto cnt = new long[](k*2+1);
		foreach (i; 0..n/2)
		{
			auto x = cast(int)min(a[i], a[n-i-1]);
			auto y = cast(int)max(a[i], a[n-i-1]);
			auto z = a[i] + a[n-i-1];
			++cnt1[x];
			++cnt2[y];
			++cnt[z];
		}

		ans[ti] = long.max;
		{
			long c;
			foreach_reverse (i; 2..k+1)
			{
				c += cnt1[i];
				auto tmp = c*2 + ((n/2) - c - cnt[i]);
				ans[ti].chmin(tmp);
				debug writeln("i:", i, " c:", c, " cnt[i]:", cnt[i], " tmp:", tmp);
			}
		}
		{
			long c;
			foreach (i; k+1..k*2+1)
			{
				c += cnt2[(i-1)/2-1];
				auto tmp = c*2 + ((n/2) - c - cnt[i]);
				ans[ti].chmin(tmp);
				debug writeln("i:", i, " c:", c, " cnt[i]:", cnt[i], " tmp:", tmp);
			}
		}
	}

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


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)
	{
		int rows, cols, r, c;
		readf !(" %s %s %s %s") (rows, cols, r, c);
		readln;
		r -= 1;
		c -= 1;
		string [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip;
		}

		int res = int.max;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (board[row][col] == 'B')
				{
					res = min (res,
					    (r != row) + (c != col));
				}
			}
		}

		if (res == int.max)
		{
			res = -1;
		}
		writeln (res);
	}
}

import std;

T
read (alias T, string end) () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

void main () {
    immutable tests = read!(ubyte, "\n");
    foreach (test_index; 0 .. tests) {
        immutable n = read!(ubyte, " ");
        immutable m = read!(ubyte, " ");
        immutable r = read!(ubyte, " ");
        immutable c = read!(ubyte, "\n");

        immutable data = (){
            static assert(true);
            byte[] ret = new byte[n * m];
            foreach (i; 0 .. n) {
                foreach (j; 0 .. m)
                    ret[i * m + j] = read!(char, "");
                readf("\n");
            }

            return ret.assumeUnique;
        }();

        {
            immutable any_B = data.any!"a == 'B'";
            if (!any_B) {
                writeln("-1");
                continue;
            }
        }

        auto mat = data.chunks(m);

        if (mat[r - 1][c - 1] == 'B') {
            writeln("0");
            continue;
        }

        immutable on_line_or_column =
            mat[r - 1].any!"a == 'B'"
            || mat.transversal(c - 1).any!"a == 'B'";

        if (on_line_or_column)
            writeln("1");
        else
            writeln("2");
    }
}
// ""

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto M = scan!int;
      auto R = scan!int - 1;
      auto C = scan!int - 1;
      auto G = cast(char[][])scan!string(N);

      if (!G.joiner.canFind('B')) {
        return -1;
      }

      long ans;
      bool[GridPoint] visited;
      M: for(auto q = DList!GridPoint(GridPoint(C, R)); !q.empty;) {
        bool[GridPoint] nex;
        while(!q.empty) {
          auto p = q.front; q.removeFront;
          if (p in visited) continue;

          visited[p] = true;
          if (p.of(G) == 'B') break M;

          foreach(d; [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
            auto m = p;
            while(true) {
              m.x += d[0];
              m.y += d[1];
              if (m.x < 0 || m.y < 0 || m.x >= M || m.y >= N) break;

              if (!(m in visited)) nex[m] = true;
            }
          }
        }

        q.insert(nex.keys);
        ans++;
      }

      return ans;
    }

    foreach(_; 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;}}
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"];

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

struct GridPoint {
  static enum ZERO = GridPoint(0, 0);
  long x, y;

  static GridPoint reversed(long y, long x) {
    return GridPoint(x, y);
  }

  this(long x, long y) {
    this.x = x;
    this.y = y;
  }

  inout GridPoint left() { return GridPoint(x - 1, y); }
  inout GridPoint right() { return GridPoint(x + 1, y); }
  inout GridPoint up() { return GridPoint(x, y - 1); }
  inout GridPoint down() { return GridPoint(x, y + 1); }
  inout GridPoint leftUp() { return GridPoint(x - 1, y - 1); }
  inout GridPoint leftDown() { return GridPoint(x - 1, y + 1); }
  inout GridPoint rightUp() { return GridPoint(x + 1, y - 1); }
  inout GridPoint rightDown() { return GridPoint(x + 1, y + 1); }
  inout GridPoint[] around() { return [left(), up(), right(), down()]; }
  inout GridPoint[] around(GridPoint max) { GridPoint[] ret; if (x > 0) ret ~= left; if(x < max.x-1) ret ~= right; if(y > 0) ret ~= up; if(y < max.y-1) ret ~= down; return ret; }
  inout T of(T)(inout ref T[][] grid) { return grid[cast(int)y][cast(int)x]; }
}


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;

immutable int INF = 1 << 29;

void main() {
    auto N = readln.chomp.to!int;
    auto L = readln.split.map!(to!int).array;
    auto R = readln.split.map!(to!int).array;
    auto ans = new int[](N);

    auto LL = new int[](N);
    auto RR = new int[](N);

    foreach (i; 0..N) {
        if (L[i] > i) {
            writeln("NO");
            return;
        }
    }

    foreach (i; 0..N) {
        if (R[N-i-1] > i) {
            writeln("NO");
            return;
        }
    }

    int cnt = 0;
    foreach_reverse (k; 1..N+1) {
        int tmp = 0;
        int[] hoge;
        foreach (i; 0..N) {
            if (LL[i] == L[i] && RR[i] == R[i]) {
                ans[i] = k;
                tmp += 1;
                hoge ~= i;
            }
        }

        if (tmp == 0 && cnt < N) {
            writeln("NO");
            return;
        }

        for (int i = 0, p = 0; i < N; ++i) {
            if (p < hoge.length && i == hoge[p]) {
                p += 1;
            }
            LL[i] += p;
        }

        for (int i = N-1, p = hoge.length.to!int - 1; i >= 0; --i) {
            if (p >= 0 && i == hoge[p]) {
                p -= 1;
            }
            RR[i] += hoge.length.to!int - p - 1;
        }

        cnt += tmp;
    }

    writeln("YES");
    ans.map!(to!string).join(" ").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 lo = readln.splitter.map !(to !(int)).array;
		auto hi = readln.splitter.map !(to !(int)).array;
		auto v = new int [n];

		int cur = n;
		int num = 0;
		bool bad = false;
		while (!bad)
		{
			int prev = num;
			foreach (i; 0..n)
			{
				if (v[i] == 0 && lo[i] == 0 && hi[i] == 0)
				{
					v[i] = cur;
					num += 1;
				}
			}

			if (num == prev)
			{
				break;
			}

			foreach (i; 0..n)
			{
				if (v[i] == cur)
				{
					foreach (j; 0..n)
					{
						if (j < i && v[j] == 0)
						{
							hi[j] -= 1;
							bad |= (hi[j] < 0);
						}
						if (j > i && v[j] == 0)
						{
							lo[j] -= 1;
							bad |= (lo[j] < 0);
						}
					}
				}
			}

			cur -= 1;
		}

		if (!bad && num == n)
		{
			writeln ("YES");
			writefln ("%(%s %)", v);
		}
		else
		{
			writeln ("NO");
		}
	}
}

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 lo = readln.splitter.map !(to !(int)).array;
		auto hi = readln.splitter.map !(to !(int)).array;
		auto v = new int [n];

		int cur = n;
		int num = 0;
		bool bad = false;
		while (!bad)
		{
			int prev = num;
			foreach (i; 0..n)
			{
				if (v[i] == 0 && lo[i] == 0 && hi[i] == 0)
				{
					v[i] = cur;
					num += 1;
				}
			}

			if (num == prev)
			{
				break;
			}

			foreach (i; 0..n)
			{
				if (v[i] == cur)
				{
					foreach (j; 0..n)
					{
						if (j < i && lo[j] + hi[j] > 0)
						{
							hi[j] -= 1;
							bad |= (hi[j] < 0);
						}
						if (j > i && lo[j] + hi[j] > 0)
						{
							lo[j] -= 1;
							bad |= (lo[j] < 0);
						}
					}
				}
			}

			cur -= 1;
		}

		if (!bad && num == n)
		{
			writeln ("YES");
			writefln ("%(%s %)", v);
		}
		else
		{
			writeln ("NO");
		}
	}
}


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)
	{
		int n, q;
		readf !(" %s %s") (n, q);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		long total = 0;

		void mark (int i, int delta)
		{
			if (i < 0 || i >= n)
			{
				return;
			}
			if ((i == 0 || a[i] > a[i - 1]) &&
			    (i == n - 1 || a[i] > a[i + 1]))
			{
				total += a[i] * delta;
			}
			if ((i > 0 && a[i] < a[i - 1]) &&
			    (i < n - 1 && a[i] < a[i + 1]))
			{
				total -= a[i] * delta;
			}
		}

		foreach (i; 0..n)
		{
			mark (i, +1);
		}
		writeln (total);
		foreach (s; 0..q)
		{
			int l, r;
			readf !(" %s %s") (l, r);
			readln;
			l -= 1;
			r -= 1;
			auto p = chain (iota (l - 1, l + 2),
			    iota (max (l + 2, r - 1), r + 2)).array;
			foreach (i; p)
			{
				mark (i, -1);
			}
			swap (a[l], a[r]);
			foreach (i; p)
			{
				mark (i, +1);
			}
			writeln (total);
		}
	}
}

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
/*******************************It's a Me, Mario!*******************************************/

ll[] arr, stat;

ll resett(int l, int r){
    ll take = 0;
    foreach(i; l..r+1){
        take -= arr[i]*stat[i];
        stat[i] = 0;
    }
    return take;
}

ll sett(int l, int r){
    ll take = 0;
    foreach(i; l..r+1){
        if(arr[i] >= arr[i-1] && arr[i] >= arr[i+1]){
            stat[i] = 1;
        }else if(arr[i] <= arr[i-1] && arr[i] <= arr[i+1]){
            stat[i] = -1;
        }
        take += arr[i] * stat[i];
    }
    return take;
}

void play(){
    int n, q;
    n = rd!int;
    q = rd!int;

    // Reset
    arr = [];
    stat = [];

    arr ~= 0;
    arr ~= rdarr;
    arr ~= 0;
    stat.length = arr.length;
    /* if(n == 1){ writeln(arr[1]); return;} */

    ll ix = 0; ll pow = 0;
    bool side = 1, nside;
    foreach(i; 2..n+2){
        if(arr[i] > arr[i-1]){
            nside = 1;
        }else{
            nside = 0;
        }
        if(nside != side){
            if(ix % 2 == 0){
                pow += arr[i-1];
                stat[i-1] = 1;
            }else{
                pow -= arr[i-1];
                stat[i-1] = -1;
            }
            side = nside;
            ++ix;
        }
    }
    writeln(pow);
    int l, r;

    // Maxx.length > 1 always, was already a min
    foreach(k; 0..q){
        l = rd!int; r = rd!int;
        ll lval = arr[l]; ll rval = arr[r];
        /* show(arr, stat, pow); */
        pow += resett(max(l-1, 1), min(l+1, n));
        arr[l] = rval;
        pow += sett(max(l-1, 1), min(l+1, n));

        pow += resett(max(r-1, 1), min(r+1, n));
        arr[r] = lval;
        pow += sett(max(r-1, 1), min(r+1, n));
        /* show(arr, stat, pow); */
        writeln(pow);
    }
}

int main(){
    long t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}


import std.stdio;
import std.algorithm;

void main() { while (solve()) {} }
bool solve() {
	int n;
	if (readf(" %s", &n) != 1) return false;
	long r, sum;
	readf(" %s %s", &r, &sum);
	sum *= n;

	struct ex {
		long a, b;
	}
	ex[] a = new ex[n];
	foreach (ref e; a)
		readf(" %s %s", &e.a, &e.b);

	a.sort!q{ a.b < b.b };

	foreach (e; a) {
		sum -= e.a;
	}
	long ans = 0;
	foreach (e; a) {
		if (sum <= 0) break;
		long can = r - e.a;
		ans += e.b * min(can, sum);
		sum -= can;
	}

	writeln(ans);

	return true;
}

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

struct XD
{
    int a;
    int b;
}

void solve(XD[] xds, int n, int r, int avg)
{
    xds.sort!("a.b < b.b");
    long sum = 0;
    foreach (i; 0 .. n)
    {
        sum += xds[i].a;
    }
    auto need = cast(long)n * avg - sum;
    if (need <= 0)
    {
        writeln(0);
        return;
    }
    long ans = 0;
    foreach (i; 0 .. n)
    {
        long d = r - xds[i].a;
        if (need <= d)
        {
            ans += need * xds[i].b;
            break;
        }
        need -= d;
        ans += d * xds[i].b;
    }
    writeln(ans);
}

int main(string[] args)
{
    int n, r, avg;
    while (readf("%d %d %d\n", &n, &r, &avg) == 3)
    {
        auto xds = new XD[n];
        foreach (i; 0 .. n)
        {
            readf("%d %d\n", &xds[i].a, &xds[i].b);
        }
        solve(xds, n, r, avg);
    }
    return 0;
}


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

immutable long infinity = long.max / 2;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		auto board = new long [] [] (rows, cols);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf !(" %s") (board[row][col]);
			}
		}

		long solve (int rowPick, int colPick)
		{
			auto base = board[rowPick][colPick];
			base -= rowPick + colPick;
			auto cost = new long [] [] (rows, cols);
			foreach (row; 0..rows)
			{
				foreach (col; 0..cols)
				{
					cost[row][col] = (row || col) ?
					    infinity : 0;
					if (row > 0)
					{
						cost[row][col] = min
						    (cost[row][col],
						    cost[row - 1][col]);
					}
					if (col > 0)
					{
						cost[row][col] = min
						    (cost[row][col],
						    cost[row][col - 1]);
					}
					auto toDo = base + row + col;
					if (board[row][col] >= toDo)
					{
						cost[row][col] +=
						    board[row][col] - toDo;
						cost[row][col] = min
						    (cost[row][col], infinity);
					}
					else
					{
						cost[row][col] = infinity;
					}
				}
			}
			return cost[rows - 1][cols - 1];
		}

		long res = infinity;
		foreach (rowPick; 0..rows)
		{
			foreach (colPick; 0..cols)
			{
				res = min (res, solve (rowPick, colPick));
			}
		}
		writeln (res);
	}
}

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

immutable long infinity = long.max / 2;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		auto board = new long [] [] (rows, cols);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf !(" %s") (board[row][col]);
			}
		}
		auto cost = new long [] [] (rows, cols);

		long solve (int rowPick, int colPick)
		{
			auto base = board[rowPick][colPick];
			base -= rowPick + colPick;
			foreach (row; 0..rows)
			{
				foreach (col; 0..cols)
				{
					cost[row][col] = (row || col) ?
					    infinity : 0;
					if (row > 0)
					{
						cost[row][col] = min
						    (cost[row][col],
						    cost[row - 1][col]);
					}
					if (col > 0)
					{
						cost[row][col] = min
						    (cost[row][col],
						    cost[row][col - 1]);
					}
					auto toDo = base + row + col;
					if (board[row][col] >= toDo)
					{
						cost[row][col] +=
						    board[row][col] - toDo;
						cost[row][col] = min
						    (cost[row][col], infinity);
					}
					else
					{
						cost[row][col] = infinity;
					}
				}
			}
			return cost[rows - 1][cols - 1];
		}

		long res = infinity;
		foreach (rowPick; 0..rows)
		{
			foreach (colPick; 0..cols)
			{
				res = min (res, solve (rowPick, colPick));
			}
		}
		writeln (res);
	}
}

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

immutable long infinity = long.max / 2;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		auto board = new long [] [] (rows, cols);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf !(" %s") (board[row][col]);
			}
		}
		auto cost = new long [] [] (rows + 1, cols + 1);

		long solve (int rowPick, int colPick)
		{
			auto base = board[rowPick][colPick];
			base -= rowPick + colPick;
			foreach (ref line; cost)
			{
				line[] = infinity;
			}
			cost[0][1] = 0;
			foreach (row; 0..rows)
			{
				foreach (col; 0..cols)
				{
					auto toDo = base + row + col;
					if (board[row][col] >= toDo)
					{
						cost[row + 1][col + 1] =
						    board[row][col] - toDo +
						    min (cost[row][col + 1],
						    cost[row + 1][col]);
					}
				}
			}
			return cost[rows][cols];
		}

		long res = infinity;
		foreach (rowPick; 0..rows)
		{
			foreach (colPick; 0..cols)
			{
				res = min (res, solve (rowPick, colPick));
			}
		}
		writeln (res);
	}
}


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

bool can_do_h_damage(uint[] a, ulong k, ulong h)
{
  ulong dmg, olddmg;
  foreach (i ; 1 .. a.length) {
    olddmg = dmg;
    dmg += min(cast(ulong)(a[i] - a[i - 1]), k);
    if (dmg < olddmg) // overflow
      return true;
    if (dmg >= h)
      return true;
  }
  olddmg = dmg;
  dmg += k;
  if (dmg < olddmg) // overflow
    return true;
  return dmg >= h;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    ulong n, h;
    readf!" %d %d "(n, h);
    auto a = readln.splitter.map!(to!uint).array;
    ulong L = 1UL, R = h + 100, mid, ans = 0;
    while (L <= R) {
      mid = L + (R - L) / 2;
      if (!can_do_h_damage(a, mid, h)) {
        ans = mid;
        L = mid + 1;
      } else {
        R = mid - 1;
      }
    }
    writeln(ans + 1);
  }
}

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

void solve(){
    auto n = scan!int;
    auto h = scan;
    auto a = scanArray;
    long[] b;
    for(int i = 1; i < n; ++i){
        b ~= a[i] - a[i-1];
    }
    b ~= h;
    b.sort;
    long summ = 0;
    for(int i = 0; i < n; ++i){
        long left = h - summ;
        long bucks = n - i;
        long k = left/bucks + (left % bucks != 0);
        if(b[i] >= k){
            writeln(k);
            return;
        }
        summ += b[i];
    }
    assert(0);
}

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, "x",  long, "y");

immutable multi = true;

void solve(int tc)
{
  debug writeln("for test ", tc);
  auto n = readInt!int;
  auto h = readInt!long;
  auto a = ma(n, readInt!long);
  bool kills(long k)
  {
    debug writeln("kills ", k);
    long health = h;
    foreach(i, ai; a)
      {
	long lastTime = ai + k;
	if (i + 1 < n)
	  {
	    lastTime = min(lastTime, a[i + 1]);
	  }
	long length = lastTime - ai;
	debug writeln("for ", i, " length ", length);
	if (length >= health) { debug writeln("yes"); return true; }
	health -= length;
      }
    debug writeln("no"); return false;
  }
  long high = h;
  long low = 1;
  long ans = -1;
  while (low <= high)
    {
      long middle = low + (high - low)/2L;
      if (kills(middle))
	{
	  ans = middle;
	  high = middle - 1;
	}
      else
	{
	  low = middle + 1;
	}
    }
  ans.writeln;
}

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

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

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

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

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

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

bool can_do_h_damage(uint[] a, ulong k, ulong h)
{
  ulong dmg;
  foreach (i ; 1 .. a.length) {
    dmg += min(a[i] - a[i - 1], k);
    if (dmg >= h)
      return true;
  }
  dmg += k;
  return dmg >= h;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    ulong n, h;
    readf!" %d %d "(n, h);
    auto a = readln.splitter.map!(to!uint).array;
    writeln(iota(1UL, h + 1).map!(k => can_do_h_damage(a, k, h)).assumeSorted.lowerBound(true).length + 1);
  }
}

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

bool can_do_h_damage(uint[] a, ulong k, ulong h)
{
  ulong dmg;
  foreach (i ; 1 .. a.length) {
    dmg += min(a[i] - a[i - 1], k);
  }
  dmg += k;
  return dmg >= h;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    ulong n, h;
    readf!" %d %d "(n, h);
    auto a = readln.splitter.map!(to!uint).array;
    writeln(iota(1UL, h + 1).map!(k => can_do_h_damage(a, k, h)).assumeSorted.lowerBound(true).length + 1);
  }
}


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)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		int [] [] a;
		foreach (row; 0..n)
		{
			a ~= readln.splitter.map !(to !(int)).array;
		}

		auto c = new int [n + m - 1];
		auto d = new int [n + m - 1];
		foreach (row; 0..n)
		{
			foreach (col; 0..m)
			{
				c[row + col] += a[row][col];
				d[row + m - col - 1] += a[row][col];
			}
		}

		int res = 0;
		foreach (row; 0..n)
		{
			foreach (col; 0..m)
			{
				res = max (res, c[row + col] +
				    d[row + m - col - 1] - a[row][col]);
			}
		}
		writeln (res);
	}
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto M = scan!int;
      auto A = scan!long(N * M).chunks(M).array;

      auto lsum = new long[](N + M - 1);
      foreach(y; -M+1..N) {
        int tx = max(-y, 0);
        int ty = max(0, y);
        while(tx < M && ty < N) {
          lsum[y + M - 1] += A[ty++][tx++];
        }
      }

      auto rsum = new long[](N + M - 1);
      foreach(y; -M+1..N) {
        int tx = min(M - 1 + y , M - 1);
        int ty = max(0, y);
        while(tx >= 0 && ty < N) {
          rsum[y + M - 1] += A[ty++][tx--];
        }
      }

      // lsum.deb;
      // rsum.deb;
      long ans = 0;
      foreach(y; 0..N) foreach(x; 0..M) {
        long tans;
        tans += lsum[M - x + y - 1];
        tans += rsum[x + y];
        tans -= A[y][x];
        ans = max(ans, tans);
      }

      return ans;
    }

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

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, 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"];

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

module x_sum;

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

int[] rtln(T)() { return to!(T[])(strip(readln).split(" ")); }

int SD(int[][] matrix, int n, int m) {
    int sum = matrix[n][m];
    for ( {int i = n-1; int j = m-1; } i >= 0 && j >= 0; i--, j--)
        sum += matrix[i][j];
    for ( {int i = n+1; int j = m+1; } i < matrix.length && j < matrix[0].length; i++, j++)
        sum += matrix[i][j];
    for ( {int i = n-1; int j = m+1; } i >= 0 && j < matrix[0].length; i--, j++)
        sum += matrix[i][j];
    for ( {int i = n+1; int j = m-1; } i < matrix.length && j >= 0; i++, j--)
        sum += matrix[i][j];
    return sum;
}

void main() {
    int t, n, m;
    readf("%d\n", t);
    while(t--) {
        int sum = 0;
        readf("%d %d\n", n, m);
        int[][] matrix;
        int temp = n;
        while (temp--)
            matrix ~= rtln!int;
        if (m == 1)
            foreach (ln; matrix)
                sum = max(sum, ln[0]);
        else
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    sum = max(sum, SD(matrix, i, j));
        writeln(sum);
    }
}

module x_sum;

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

int[] rtln(T)() { return to!(T[])(strip(readln).split(" ")); }

int SD(int[][] matrix, int n, int m) {
    int sum = matrix[n][m];
    for ( {int i = n-1; int j = m-1; } i >= 0 && j >= 0; i--, j--)
        sum += matrix[i][j];
    for ( {int i = n+1; int j = m+1; } i < matrix.length && j < matrix[0].length; i++, j++)
        sum += matrix[i][j];
    for ( {int i = n-1; int j = m+1; } i >= 0 && j < matrix[0].length; i--, j++)
        sum += matrix[i][j];
    for ( {int i = n+1; int j = m-1; } i < matrix.length && j >= 0; i++, j--)
        sum += matrix[i][j];
    return sum;
}

void main() {
    int t, n, m;
    readf("%d\n", t);
    while(t--) {
        int sum = 0;
        readf("%d %d\n", n, m);
        int[][] matrix;
        int temp = n;
        while (temp--)
            matrix ~= rtln!int;
        if (m == 1)
            foreach (ln; matrix)
                sum = max(sum, ln[0]);
        else
            for (int i = 0; i < n; i++)
                for (int j = 1; j < m; j++)
                    sum = max(sum, SD(matrix, i, j));
        writeln(sum);
    }
}

module x_sum;

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

int[] rtln(T)() { return to!(T[])(strip(readln).split(" ")); }

int SD(int[][] matrix, int n, int m) {
    int sum = -(2 * matrix[n][m]);
    for ( {int i = 0; int j = 0; } i < n && j < m; i++, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i < matrix.length && j < matrix[0].length; i++, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i >= 0 && j < matrix[0].length; i--, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i < matrix.length && j >= 0; i++, j--)
        sum += matrix[i][j];
    return sum;
}

void main() {
    int t, n, m;
    readf("%d\n", t);
    while(t--) {
        int sum;
        readf("%d %d\n", n, m);
        int[][] matrix;
        int temp = n;
        while (temp--)
            matrix ~= rtln!int;
        if (m == 1)
            foreach (ln; matrix)
                sum = max(sum, ln[0]);
        else
            for (int i = 0; i < n; i++)
                for (int j = 1; j < m; j++)
                    sum = max(sum, SD(matrix, i, j));
        writeln(sum);
    }
}

module x_sum;

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

int[] rtln(T)() { return to!(T[])(strip(readln).split(" ")); }

int SD(int[][] matrix, int n, int m) {
    int sum = -(2 * matrix[n][m]);
    for ( {int i = 0; int j = 0; } i < n && j < m; i++, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i < matrix.length && j < matrix[0].length; i++, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i >= 0 && j < matrix[0].length; i--, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i < matrix.length && j >= 0; i++, j--)
        sum += matrix[i][j];
    return sum;
}

void main() {
    int t, n, m;
    readf("%d\n", t);
    while(t--) {
        int sum;
        readf("%d %d\n", n, m);
        int[][] matrix;
        int temp = n;
        while (temp--)
            matrix ~= rtln!int;
        for (int i = 0; i < n; i++)
            for (int j = 1; j < m; j++)
                sum = max(sum, SD(matrix, i, j));
        writeln(sum);
    }
}

module x_sum;

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

int[] rtln(T)() { return to!(T[])(strip(readln).split(" ")); }

int SD(int[][] matrix, int n, int m) {
    int sum = -(2 * matrix[n][m]);
    for ( {int i = 0; int j = 0; } i < n && j < m; i++, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i < matrix.length && j < matrix[0].length; i++, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i >= 0 && j < matrix[0].length; i--, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i < matrix.length && j >= 0; i++, j--)
        sum += matrix[i][j];
    return sum;
}

void main() {
    int t, n, m;
    readf("%d\n", t);
    while(t--) {
        int sum;
        readf("%d %d\n", n, m);
        int[][] matrix;
        int temp = n;
        while (temp--)
            matrix ~= rtln!int;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                sum = max(sum, SD(matrix, i, j));
        writeln(sum);
    }
}

module x_sum;

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

int[] rtln(T)() { return to!(T[])(strip(readln).split(" ")); }

int SD(int[][] matrix, int n, int m) {
    int sum = -(2 * matrix[n][m]);
    for ( {int i = 0; int j = 0; } i < n && j < m; i++, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i < matrix.length && j < matrix[0].length; i++, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i >= 0 && j < matrix[0].length; i--, j++)
        sum += matrix[i][j];
    for ( {int i = n; int j = m; } i < matrix.length && j >= 0; i++, j--)
        sum += matrix[i][j];
    return sum;
}

void main() {
    int t, n, m, sum;
    readf("%d\n", t);
    while(t--) {
        readf("%d %d\n", n, m);
        int[][] matrix;
        int temp = n;
        while (temp--)
            matrix ~= rtln!int;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                sum = max(sum, SD(matrix, i, j));
        writeln(sum);
    }
}


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

void main() {

	int n = readln.strip.to!int;

	auto t = stdin.byLine.take(n).
		map!(a => a.split.map!(to!int).any!"a == 1 || a == 3").array;

	int[] idx;
	foreach (i, el; t) {
		if (!el) {
			idx ~= i + 1;
		}
	}

	writeln(idx.length);
	writefln("%(%s %)", idx);
}

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

void main() {
    int n = readln.chomp.to!int;
    int[] ans;
    foreach (i; 0..n) {
        auto row = readln.chomp.split.map!(to!int);
        if (row.any!"a == 1 || a == 3") {
            continue;
        }

        ans ~= i + 1;
    }

    ans.length.writeln;
    if (ans.length > 0) {
        ans.map!(to!string).join(" ").writeln;
    }
}

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

void main() {

	int sum; int[] ans;
	foreach (i; 1 .. readln.strip.to!int + 1) {
		if (readln.split.map!(to!int).all!"a != 1 && a != 3") {
			++sum;
			ans ~= i;
		}
	}

	writeln(sum);

	if (sum > 0) {
		writefln("%(%s %)", ans);
	}
}

import std.math,
       std.conv,
       std.stdio,
       std.ascii,
       std.range,
       std.array,
       std.regex,
       std.format,
       std.bigint,
       std.traits,
       std.string,
       std.numeric,
       std.variant,
       std.typecons,
       std.algorithm,
       std.typetuple,
       std.exception;

void main() {

	int n = readln.strip.to!int;

	int[101][101] a; bool[int] hash;
	foreach (i; 1 .. n + 1) {
		foreach (j; 1 .. n + 1) {
			scanf("%d", &a[i][j]);
			if (a[i][j] != 0 && a[i][j] != -1) {
				if (a[i][j] == 1) {
					hash[i] = false;
				}
				if (a[i][j] == 2) {
					hash[j] = false;
				}
				if (a[i][j] == 3) {
					hash[i] = hash[j] = false;
				}
			}
		}
	}

	int[] ans; int sum;
	foreach (i; 1 .. n + 1) {
		if (i !in hash) {
			++sum;
			ans ~= i;
		}
	}

	writeln(sum);
	if (sum > 0) {
		writefln("%(%s %)", ans);
	}
}

import std.math,
       std.conv,
       std.stdio,
       std.ascii,
       std.range,
       std.array,
       std.regex,
       std.format,
       std.bigint,
       std.traits,
       std.string,
       std.numeric,
       std.variant,
       std.typecons,
       std.algorithm,
       std.typetuple,
       std.exception;

void main() {

	int n = readln.strip.to!int;

	int[101][101] a;
	foreach (i; 1 .. n + 1) {
		foreach (j; 1 .. n + 1) {
			scanf("%d", &a[i][j]);
		}
	}

	bool[int] hash;
	foreach (i; 1 .. n) {
		if (a[i][i + 1] != 0) {
			if (a[i][i + 1] == 1) {
				hash[i] = false;
			}
			if (a[i][i + 1] == 2) {
				hash[i + 1] = false;
			}
			if (a[i][i + 1] == 3) {
				hash[i] = hash[i + 1] = false;
			}
		}
		if (a[i + 1][i] != 0) {
			if (a[i + 1][i] == 1) {
				hash[i + 1] = false;
			}
			if (a[i + 1][i] == 2) {
				hash[i] = false;
			}
			if (a[i + 1][i] == 3) {
				hash[i] = hash[i + 1] = false;
			}
		}
	}

	if (a[1][n] != 0) {
		hash[n] = false;
	}

	if (a[n][1] != 0) {
		if (a[n][1] == 1) {
			hash[n] = false;
		}
		if (a[n][1] == 2) {
			hash[1] = false;
		}
		if (a[n][1] == 3) {
			hash[1] = hash[n] = false;
		}
	}

	int[] ans; int sum;
	foreach (i; 1 .. n + 1) {
		if (i !in hash) {
			++sum;
			ans ~= i;
		}
	}

	writeln(sum);
	if (sum > 0) {
		writefln("%(%s %)", ans);
	}
}

import std.math,
       std.conv,
       std.stdio,
       std.ascii,
       std.range,
       std.array,
       std.regex,
       std.format,
       std.bigint,
       std.traits,
       std.string,
       std.numeric,
       std.variant,
       std.typecons,
       std.algorithm,
       std.typetuple,
       std.exception;

void main() {

	int n = readln.strip.to!int;

	int[101][101] a;
	foreach (i; 1 .. n + 1) {
		foreach (j; 1 .. n + 1) {
			scanf("%d", &a[i][j]);
		}
	}

	bool[int] hash;
	foreach (i; 1 .. n) {
		if (a[i][i + 1] != 0) {
			if (a[i][i + 1] == 1) {
				hash[i] = false;
			}
			if (a[i][i + 1] == 2) {
				hash[i + 1] = false;
			}
			if (a[i][i + 1] == 3) {
				hash[i] = hash[i + 1] = false;
			}
		}
		if (a[i + 1][i] != 0) {
			if (a[i + 1][i] == 1) {
				hash[i + 1] = false;
			}
			if (a[i + 1][i] == 2) {
				hash[i] = false;
			}
			if (a[i + 1][i] == 3) {
				hash[i] = hash[i + 1] = false;
			}
		}
	}

	if (a[1][n] != 0) {
		if (a[1][n] == 1) {
			hash[1] = false;
		}
		if (a[1][n] == 2) {
			hash[n] = false;
		}
		if (a[1][n] == 3) {
			hash[1] = hash[n] = false;
		}
	}

	if (a[n][1] != 0) {
		if (a[n][1] == 1) {
			hash[n] = false;
		}
		if (a[n][1] == 2) {
			hash[1] = false;
		}
		if (a[n][1] == 3) {
			hash[1] = hash[n] = false;
		}
	}

	int[] ans; int sum;
	foreach (i; 1 .. n + 1) {
		if (i !in hash) {
			++sum;
			ans ~= i;
		}
	}

	writeln(sum);
	if (sum > 0) {
		writefln("%(%s %)", ans);
	}
}


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;
		if (a.stride (2).canFind !(q{a % 2 == 0}))
		{
			writeln (-1);
			continue;
		}

		int [] answer;

		void go (int pos)
		{
			answer ~= pos;
			reverse (a[0..pos]);
		}

		for ( ; n > 1; n -= 2)
		{
			go (a.countUntil (n).to !(int) + 1);
			go (a.countUntil (n - 1).to !(int) + 0);
			go (a.countUntil (n - 1).to !(int) + 2);
			go (3);
			go (n);
			debug {writeln (a);}
		}

		writeln (answer.length);
		writefln !("%(%s %)") (answer);
	}
}

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() {
  debug {
    for (int n = 3; n <= 7; n += 2) {
      writeln("n = ", n);
      int[string] vis;
      auto as = iota(n).array;
      void dfs(int last) {
        const key = as.to!string;
        if (key !in vis) {
          vis[key] = last;
          for (int m = 3; m <= n; m += 2) {
            as[0 .. m].reverse;
            dfs(m);
            as[0 .. m].reverse;
          }
        }
      }
      dfs(-1);
      foreach (key, val; vis) {
        writeln(key, " ", val);
      }
      writeln("|vis| = ", vis.length);
    }
  }

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

        bool ok = true;
        foreach (i; 0 .. N) {
          ok = ok && ((A[i] - i) % 2 == 0);
        }
        if (ok) {
          auto as = A.dup;
          int[] ans;
          for (int n = N; n > 1; n -= 2) {
            int p = -1, q = -1;
            foreach (i; 0 .. n) {
              if (as[i] == n - 2) p = i;
              if (as[i] == n - 1) q = i;
            }

            void oper(int m) {
              assert(m % 2 != 0);
              ans ~= m;
              as[0 .. m].reverse;
              if (p < m) p = m - 1 - p;
              if (q < m) q = m - 1 - q;
            }
            oper(q + 1);
            oper(p);
            oper(n);
            oper(q + 1);
            oper(n);
            assert(p == n - 2);
            assert(q == n - 1);
          }

          const ansLen = cast(int)(ans.length);
          writeln(ansLen);
          foreach (i; 0 .. ansLen) {
            if (i > 0) write(" ");
            write(ans[i]);
          }
          writeln;
          assert(2 * ansLen <= 5 * N);
        } else {
          writeln(-1);
        }
      }
    }
  } catch (EOFException e) {
  }
}


import std.stdio;
import std.conv;
import std.string;
import std.array;
import std.algorithm;
import std.container.dlist;

bool dcare(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return true;
  } else if (s[p] == 0){
    ans.insertFront("(0->");
    ans.insertBack(")");
    dcare(s, p + 1, ans);
    return true;
  } else {
    ans.insertFront("(1->");
    ans.insertBack(")");
    dcare(s, p + 1, ans);
    return true;
  }
}

bool exact_zero(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return false;
  } else if (s[p] == 1) {
    ans.insertFront("(1->");
    ans.insertBack(")");
    return exact_zero(s, p + 1, ans);
  } else {
    ans.insertFront("(0->");
    ans.insertBack(")");
    dcare(s, p + 1, ans);
    return true;
  }
}

bool one(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return true;
  } else if (s[p] == 0) {
    ans.insertBack("(0)");
    if (!exact_zero(s, p + 1, ans)) {
      return false;
    }
    return true;
  } else {
    ans.insertBack("(1)");
    dcare(s, p + 1, ans);
    return true;
  }
}

bool zero(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return false;
  } else if (s[p] == 1) {
    return false;
  } else {
    if (!one(s, p + 1, ans)) {
      return false;
    }
    if (p == s.length - 1) {
      ans.insertBack("(0)");
    } else {
      ans.insertFront("(");
      ans.insertBack("->0)");
    }
    return true;
  }
}

void main() {
  int n = readln().strip().to!int;
  auto a = readln().split().map!(to!int).array;
  a.reverse();
  DList!string ans;
  if (zero(a, 0, ans)) {
    writeln("YES");
    writeln(ans.array.join(""));
  } else {
    writeln("NO");
  }

}

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

int impl(int x, int y) {
  return (1 - x) | y;
}

string solve(int[] a) {
  auto n = a.length;
  if (a.back() != 0) {
    return "";
  }
  if (n == 1) {
    return "0";
  }
  int val = a[n - 2];
  foreach_reverse (i; 0..n-2) {
    val = impl(a[i], val);
  }
  if (val != 1) {
    return "";
  }
  char[] buf;
  foreach (i; 0..n-2) {
    buf ~= "(" ~ to!string(a[i]) ~ "->";
  }
  buf ~= "(" ~ to!string(a[a.length-2]);
  buf ~= ')'.repeat().take(a.length - 1).array;
  buf ~= "->0";
  return buf.dup;
}

void main() {
  int n = readln().strip().to!int;
  auto a = readln().split().map!(to!int).array;
  string ans = solve(a);
  if (!ans.empty()) {
    writeln("YES");
    writeln(ans);
  } else {
    writeln("NO");
  }

}

import std.stdio;
import std.conv;
import std.string;
import std.array;
import std.algorithm;
import std.container.dlist;

bool dcare(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return true;
  } else if (s[p] == 0){
    ans.insertFront("(0->");
    ans.insertBack(")");
    dcare(s, p + 1, ans);
    return true;
  } else {
    ans.insertFront("(1->");
    ans.insertBack(")");
    dcare(s, p + 1, ans);
    return true;
  }
}

bool one(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return true;
  } else if (s[p] == 0) {
    if (!zero(s, p + 1, ans)) {
      return false;
    }
    ans.insertFront("(");
    ans.insertBack("->0)");
    return true;
  } else {
    ans.insertBack("(1)");
    dcare(s, p + 1, ans);
    return true;
  }
}

bool zero(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return false;
  } else if (s[p] == 1) {
    return false;
  } else {
    if (!one(s, p + 1, ans)) {
      return false;
    }
    if (p == s.length - 1) {
      ans.insertBack("(0)");
    } else {
      ans.insertFront("(");
      ans.insertBack("->0)");
    }
    return true;
  }
}

void main() {
  int n = readln().strip().to!int;
  auto a = readln().split().map!(to!int).array;
  a.reverse();
  DList!string ans;
  if (zero(a, 0, ans)) {
    writeln("YES");
    writeln(ans.array.join(""));
  } else {
    writeln("NO");
  }

}

import std.stdio;
import std.conv;
import std.string;
import std.array;
import std.algorithm;
import std.container.dlist;

bool dcare(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return true;
  } else if (s[p] == 0){
    ans.insertFront("(0->");
    ans.insertBack(")");
    dcare(s, p + 1, ans);
    return true;
  } else {
    ans.insertFront("(1->");
    ans.insertBack(")");
    dcare(s, p + 1, ans);
    return true;
  }
}

bool exact_zero(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return false;
  } else if (s[p] == 1) {
    return false;
  } else {
    ans.insertBack("(0)");
    return true;
  }
}

bool one(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return true;
  } else if (s[p] == 0) {
    if (!exact_zero(s, p + 1, ans)) {
      return false;
    }
    ans.insertFront("(");
    ans.insertBack("->0)");
    dcare(s, p + 2, ans);
    return true;
  } else {
    ans.insertBack("(1)");
    dcare(s, p + 1, ans);
    return true;
  }
}

bool zero(int[] s, int p, ref DList!string ans) {
  if (p >= s.length) {
    return false;
  } else if (s[p] == 1) {
    return false;
  } else {
    if (!one(s, p + 1, ans)) {
      return false;
    }
    if (p == s.length - 1) {
      ans.insertBack("(0)");
    } else {
      ans.insertFront("(");
      ans.insertBack("->0)");
    }
    return true;
  }
}

void main() {
  int n = readln().strip().to!int;
  auto a = readln().split().map!(to!int).array;
  a.reverse();
  DList!string ans;
  if (zero(a, 0, ans)) {
    writeln("YES");
    writeln(ans.array.join(""));
  } else {
    writeln("NO");
  }

}