Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) — who knows? Every one of them has an integer sequences a and b of length n. Being given a query of the form of pair of integers (l, r), Mike can instantly tell the value of  while !Mike can instantly tell the value of .Now suppose a robot (you!) asks them all possible different queries of pairs of integers (l, r) (1 ≤ l ≤ r ≤ n) (so he will make exactly n(n + 1) / 2 queries) and counts how many times their answers coincide, thus for how many pairs  is satisfied.How many occasions will the robot count?

The first line contains only integer n (1 ≤ n ≤ 200 000). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the sequence a. The third line contains n integer numbers b1, b2, ..., bn ( - 109 ≤ bi ≤ 109) — the sequence b.

Print the only integer number — the number of occasions the robot will count, thus for how many pairs  is satisfied.

NoteThe occasions in the first sample case are:1.l = 4,r = 4 since max{2} = min{2}.2.l = 4,r = 5 since max{2, 1} = min{2, 3}.There are no occasions in the second sample case since Mike will answer 3 to any query pair, but !Mike will always answer 1.

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


You are given a positive integer $$$n$$$.The weight of a permutation $$$p_1, p_2, \ldots, p_n$$$ is the number of indices $$$1\le i\le n$$$ such that $$$i$$$ divides $$$p_i$$$. Find a permutation $$$p_1,p_2,\dots, p_n$$$ with the minimum possible weight (among all permutations of length $$$n$$$).A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a line containing $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ so that the permutation $$$p$$$ has the minimum possible weight. If there are several possible answers, you can print any of them.

NoteIn the first test case, the only valid permutation is $$$p=[1]$$$. Its weight is $$$1$$$.In the second test case, one possible answer is the permutation $$$p=[2,1,4,3]$$$. One can check that $$$1$$$ divides $$$p_1$$$ and $$$i$$$ does not divide $$$p_i$$$ for $$$i=2,3,4$$$, so the weight of this permutation is $$$1$$$. It is impossible to find a permutation of length $$$4$$$ with a strictly smaller weight.

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)); }
T euDist2(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return c.sum; }
double euDist(T)(T[] a, T[] b) { return sqrt(cast(double)euDist2(a,b)); }
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;

		ans[ti] ~= n;
		foreach (i; 1..n)
			ans[ti] ~= i;
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}


Burenka and Tonya are playing an old Buryat game with a chip on a board of $$$n \times m$$$ cells.At the beginning of the game, the chip is located in the lower left corner of the board. In one move, the player can move the chip to the right or up by any odd number of cells (but you cannot move the chip both to the right and up in one move). The one who cannot make a move loses.Burenka makes the first move, the players take turns. Burenka really wants to win the game, but she is too lazy to come up with a strategy, so you are invited to solve the difficult task of finding it. Name the winner of the game (it is believed that Burenka and Tonya are masters of playing with chips, so they always move in the optimal way).    Chip's starting cell is green, the only cell from which chip can't move is red. if the chip is in the yellow cell, then blue cells are all options to move the chip in one move.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following is a description of the input data sets. The only line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^9$$$) — the dimensions of the game board.

For each test case print a single line — the name of the winner of the game ("Burenka" or "Tonya").

Tonya
Burenka
Burenka
Tonya
Burenka
Burenka

NoteIn the first case, Burenka has no move, so Tonya wins.In the second case, Burenka can move $$$3$$$ cells to the right, after which Tony will not be able to make a move, which means that Burenka wins.In the third case, Burenka can move $$$5$$$ squares to the right. Then we can say that we have a game on a board of $$$1 \times 5$$$ cells, and Tonya is the first player. In such game the second player wins, so in the original one Burenka will win.

import std;

enum b = "Burenka";
enum t = "Tonya";

void main()
{
    int w;
    scanf("%d", &w);
    getchar();
    foreach(_; 0..w)
    {
        long n,m;
        scanf("%lld %lld\n", &n, &m);
        if (n == 1)
            if (m % 2 == 0)
                writeln(b);
            else
                writeln(t);
        else if (m == 1)
            if (n % 2 == 0)
                writeln(b);
            else
                writeln(t);
        else {
            if ((n % 2 == 0) && (m % 2 != 0))
                writeln(b);
            else if ((n % 2 != 0) && (m % 2 == 0))
                writeln(b);
            else
                writeln(t);
        }
    }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers (it is guaranteed that $$$n$$$ is even, i.e. divisible by $$$2$$$). All $$$a_i$$$ does not exceed some integer $$$k$$$.Your task is to replace the minimum number of elements (replacement is the following operation: choose some index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$a_i$$$ with some integer in range $$$[1; k]$$$) to satisfy the following conditions:  after all replacements, all $$$a_i$$$ are positive integers not greater than $$$k$$$;  for all $$$i$$$ from $$$1$$$ to $$$\frac{n}{2}$$$ the following equation is true: $$$a_i + a_{n - i + 1} = x$$$, where $$$x$$$ should be the same for all $$$\frac{n}{2}$$$ pairs of elements. You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le k \le 2 \cdot 10^5$$$) — the length of $$$a$$$ and the maximum possible value of some $$$a_i$$$ correspondingly. It is guratanteed that $$$n$$$ is even (i.e. divisible by $$$2$$$). The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$k$$$) over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum k \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of elements you have to replace in $$$a$$$ to satisfy the conditions from the problem statement.

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


This is an hard version of the problem. The only difference between an easy and a hard version is the constraints on $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$.You are given $$$4$$$ positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ with $$$a < c$$$ and $$$b < d$$$. Find any pair of numbers $$$x$$$ and $$$y$$$ that satisfies the following conditions: $$$a < x \leq c$$$, $$$b < y \leq d$$$, $$$x \cdot y$$$ is divisible by $$$a \cdot b$$$.Note that required $$$x$$$ and $$$y$$$ may not exist.

The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10$$$), the number of test cases. The descriptions of the test cases follow. The only line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$1 \leq a < c \leq 10^9$$$, $$$1 \leq b < d \leq 10^9$$$).

For each test case print a pair of numbers $$$a < x \leq c$$$ and $$$b < y \leq d$$$ such that $$$x \cdot y$$$ is divisible by $$$a \cdot b$$$. If there are multiple answers, print any of them. If there is no such pair of numbers, then print -1 -1.

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

long[long] factor(long x) {
    long[long] ret;
    for (long k = 2; k*k <= x; k++) {
        int c = 0;
        while (x % k == 0) {
            c++;
            x /= k;
        }
        if (c > 0) {
            ret[k] = c;
        }
    }
    if (x > 1) {
        ret[x] = 1;
    }
    return ret;
}

void solve() {
    auto as = readarray!long;
    long a = as[0], b = as[1];
    long c = as[2], d = as[3];
    auto pa = factor(a);
    auto pb = factor(b);
    long[long] p;
    foreach (k, v; pa) { p[k] = p.get(k, 0) + v; }
    foreach (k, v; pb) { p[k] = p.get(k, 0) + v; }
    auto ks = p.keys;
    auto vs = p.values;

    long[] ans = [-1, -1];
    void dfs(int n, long bx, long by) {
        if (n == ks.length) {
            long x = (a / bx + 1L) * bx;
            long y = (b / by + 1L) * by;
            if (a < x && x <= c && b < y && y <= d) {
                ans[0] = x;
                ans[1] = y;
            }
        } else {
            long k = ks[n];
            long x = 1;
            long y = pow(k, vs[n]);
            for (int v = 0; v <= vs[n]; v++) {
                dfs(n + 1, bx * x, by * y);
                x *= k;
                y /= k;
            }
        }
    }
    dfs(0, 1, 1);
    writefln("%(%s %)", ans);
}


Let's call two numbers similar if their binary representations contain the same number of digits equal to $$$1$$$. For example:  $$$2$$$ and $$$4$$$ are similar (binary representations are $$$10$$$ and $$$100$$$);  $$$1337$$$ and $$$4213$$$ are similar (binary representations are $$$10100111001$$$ and $$$1000001110101$$$);  $$$3$$$ and $$$2$$$ are not similar (binary representations are $$$11$$$ and $$$10$$$);  $$$42$$$ and $$$13$$$ are similar (binary representations are $$$101010$$$ and $$$1101$$$). You are given an array of $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. You may choose a non-negative integer $$$x$$$, and then get another array of $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$, where $$$b_i = a_i \oplus x$$$ ($$$\oplus$$$ denotes bitwise XOR).Is it possible to obtain an array $$$b$$$ where all numbers are similar to each other?

If it is impossible to choose $$$x$$$ so that all elements in the resulting array are similar to each other, print one integer $$$-1$$$. Otherwise, print any non-negative integer not exceeding $$$2^{30} - 1$$$ that can be used as $$$x$$$ so that all elements in the resulting array are similar.

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

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

    auto B = A.map!(higher_bits).array;
    auto C = A.map!(lower_bits).array;

    int[immutable int[]] dict;
    auto tmp = new int[](N);

    foreach (mask; 0..1<<15) {
        foreach (i, a; B) tmp[i] = popcnt(mask ^ a);
        foreach (i; 1..N) tmp[i] -= tmp[0];
        tmp[0] = 0;
        dict[to!(immutable int[])(tmp)] = mask;
    }

    foreach (mask; 0..1<<15) {
        foreach (i, a; C) tmp[i] = popcnt(mask ^ a);
        foreach (i; 1..N) tmp[i] -= tmp[0], tmp[i] *= -1;
        tmp[0] = 0;

        auto key = to!(immutable int[])(tmp);
        if (key !in dict) continue;

        writeln((dict[key] << 15) + mask);
        return;
    }

    writeln(-1);
}

int higher_bits(int n) {
    return n >> 15;
}

int lower_bits(int n) {
    return n & ((1 << 15) - 1);
}


There is a grid with $$$n$$$ rows and $$$m$$$ columns. Some cells are colored black, and the rest of the cells are colored white.In one operation, you can select some black cell and do exactly one of the following:   color all cells in its row black, or  color all cells in its column black. You are given two integers $$$r$$$ and $$$c$$$. Find the minimum number of operations required to make the cell in row $$$r$$$ and column $$$c$$$ black, or determine that it is impossible.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$n$$$, $$$m$$$, $$$r$$$, and $$$c$$$ ($$$1 \leq n, m \leq 50$$$; $$$1 \leq r \leq n$$$; $$$1 \leq c \leq m$$$) — the number of rows and the number of columns in the grid, and the row and column of the cell you need to turn black, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either 'B' or 'W' — a black and a white cell, respectively.

For each test case, if it is impossible to make the cell in row $$$r$$$ and column $$$c$$$ black, output $$$-1$$$.  Otherwise, output a single integer — the minimum number of operations required to make the cell in row $$$r$$$ and column $$$c$$$ black.

9

3 5 1 4

WBWWW

BBBWB

WWBBB

4 3 2 1

BWW

BBW

WBB

WWB

2 3 2 2

WWW

WWW

2 2 1 1

WW

WB

5 9 5 9

WWWWWWWWW

WBWBWBBBW

WBBBWWBWW

WBWBWBBBW

WWWWWWWWW

1 1 1 1

B

1 1 1 1

W

1 2 1 1

WB

2 1 1 1

W

B

NoteThe first test case is pictured below.  We can take the black cell in row $$$1$$$ and column $$$2$$$, and make all cells in its row black. Therefore, the cell in row $$$1$$$ and column $$$4$$$ will become black.  In the second test case, the cell in row $$$2$$$ and column $$$1$$$ is already black.In the third test case, it is impossible to make the cell in row $$$2$$$ and column $$$2$$$ black.The fourth test case is pictured below.  We can take the black cell in row $$$2$$$ and column $$$2$$$ and make its column black.   Then, we can take the black cell in row $$$1$$$ and column $$$2$$$ and make its row black.   Therefore, the cell in row $$$1$$$ and column $$$1$$$ will become black.

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.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");
    }
}
// ""


There are $$$n$$$ children numbered from $$$1$$$ to $$$n$$$ in a kindergarten. Kindergarten teacher gave $$$a_i$$$ ($$$1 \leq a_i \leq n$$$) candies to the $$$i$$$-th child. Children were seated in a row in order from $$$1$$$ to $$$n$$$ from left to right and started eating candies. While the $$$i$$$-th child was eating candies, he calculated two numbers $$$l_i$$$ and $$$r_i$$$ — the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively.Formally, $$$l_i$$$ is the number of indices $$$j$$$ ($$$1 \leq j < i$$$), such that $$$a_i < a_j$$$ and $$$r_i$$$ is the number of indices $$$j$$$ ($$$i < j \leq n$$$), such that $$$a_i < a_j$$$.Each child told to the kindergarten teacher the numbers $$$l_i$$$ and $$$r_i$$$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $$$l$$$ and $$$r$$$ determine whether she could have given the candies to the children such that all children correctly calculated their values $$$l_i$$$ and $$$r_i$$$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.

On the first line there is a single integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the number of children in the kindergarten. On the next line there are $$$n$$$ integers $$$l_1, l_2, \ldots, l_n$$$ ($$$0 \leq l_i \leq n$$$), separated by spaces. On the next line, there are $$$n$$$ integer numbers $$$r_1, r_2, \ldots, r_n$$$ ($$$0 \leq r_i \leq n$$$), separated by spaces.

If there is no way to distribute the candies to the children so that all of them calculated their numbers correctly, print «NO» (without quotes). Otherwise, print «YES» (without quotes) on the first line. On the next line, print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, separated by spaces — the numbers of candies the children $$$1, 2, \ldots, n$$$ received, respectively. Note that some of these numbers can be equal, but all numbers should satisfy the condition $$$1 \leq a_i \leq n$$$. The number of children seating to the left of the $$$i$$$-th child that got more candies than he should be equal to $$$l_i$$$ and the number of children seating to the right of the $$$i$$$-th child that got more candies than he should be equal to $$$r_i$$$. If there is more than one solution, find any of them.

NoteIn the first example, if the teacher distributed $$$1$$$, $$$3$$$, $$$1$$$, $$$2$$$, $$$1$$$ candies to $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$4$$$-th, $$$5$$$-th child, respectively, then all the values calculated by the children are correct. For example, the $$$5$$$-th child was given $$$1$$$ candy, to the left of him $$$2$$$ children were given $$$1$$$ candy, $$$1$$$ child was given $$$2$$$ candies and $$$1$$$ child — $$$3$$$ candies, so there are $$$2$$$ children to the left of him that were given more candies than him.In the second example it is impossible to distribute the candies, because the $$$4$$$-th child made a mistake in calculating the value of $$$r_4$$$, because there are no children to the right of him, so $$$r_4$$$ should be equal to $$$0$$$.In the last example all children may have got the same number of candies, that's why all the numbers are $$$0$$$. Note that each child should receive at least one candy.

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


A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.

The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.

For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.

NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.

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

alias Tuple!(int, "y", int, "x") P;

string[8] F;

void formatWrite(in int[8][8] k) {
    foreach (r; k) {
        foreach (c; r) {
            if (c == int.min) {
                write(" # ");
            } else {
                write(" " ~ c.to!string ~ " ");
            }
        }
        writeln;
    }
}

P[] findPos() {
    P[] pos = new P[2];
    int c = 0;
    foreach (i; 0 .. 8) {
        foreach (j; 0 .. 8) {
            if (F[i][j] == 'K') {
                pos[c].y = i;
                pos[c].x = j;
                c++;
                if (c == 2) {
                    return pos;
                }
            }
        }
    }
    throw new Exception("not found");
}

bool check() {
    auto ps = findPos;
    int[8][8] k1, k2;
    foreach (i; 0 .. 8) {
        foreach (j; 0 .. 8) {
            k1[i][j] = k2[i][j] = int.min;
        }
    }
    void dfs(ref int[8][8] k, P pos) {
        static int[] dy = [2,  2, -2, -2],
                     dx = [2, -2,  2, -2];
        if (k[pos.y][pos.x] == int.min) return;
        foreach (i; 0 .. 4) {
            int y = pos.y + dy[i];
            int x = pos.x + dx[i];
            if ( 0 <= y && y < 8 &&
                 0 <= x && x < 8 ) {
                int c = k[pos.y][pos.x] + 1;
                if ( k[y][x] == int.min ||
                     k[y][x] > c ) {
                    k[y][x] = c;
                    dfs(k, P(y, x));
                }
            }
        }
    }
    k1[ps[0].y][ps[0].x] = 0;
    k2[ps[1].y][ps[1].x] = 0;
    dfs(k1, ps[0]);
    dfs(k2, ps[1]);
    //k1.formatWrite;
    //writeln;
    //k2.formatWrite;
    foreach (i; 0 .. 8) {
        foreach (j; 0 .. 8) {
            if (k1[i][j] == int.min) continue;
            if (k2[i][j] == int.min) continue;
            if (F[i][j] == '#') continue;
            if (k1[i][j] - k2[i][j] % 2 == 0) {
                return true;
            }
        }
    }
    return false;
}

void main() {
    int t; readf("%d\n", &t);
    foreach (i; 0 .. t) {
        foreach (j; 0 .. 8) {
            F[j] = stdin.readln.chomp;
        }
        readln; // skip empty line
        //F.writeln;
        //findPos.writeln;
        (check ? "YES" : "NO").writeln;
    }
}

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

alias Tuple!(int, "y", int, "x") P;

string[8] F;

void formatWrite(in int[8][8] k) {
    foreach (r; k) {
        foreach (c; r) {
            if (c == int.min) {
                write(" # ");
            } else {
                write(" " ~ c.to!string ~ " ");
            }
        }
        writeln;
    }
}

P[] findPos() {
    P[] pos = new P[2];
    int c = 0;
    foreach (i; 0 .. 8) {
        foreach (j; 0 .. 8) {
            if (F[i][j] == 'K') {
                pos[c].y = i;
                pos[c].x = j;
                c++;
                if (c == 2) {
                    return pos;
                }
            }
        }
    }
    throw new Exception("not found");
}

bool check() {
    auto ps = findPos;
    int[8][8] k1, k2;
    foreach (i; 0 .. 8) {
        foreach (j; 0 .. 8) {
            k1[i][j] = k2[i][j] = int.min;
        }
    }
    void dfs(ref int[8][8] k, P pos) {
        static int[] dy = [2,  2, -2, -2],
                     dx = [2, -2,  2, -2];
        if (k[pos.y][pos.x] == int.min) return;
        foreach (i; 0 .. 4) {
            int y = pos.y + dy[i];
            int x = pos.x + dx[i];
            if ( 0 <= y && y < 8 &&
                 0 <= x && x < 8 ) {
                int c = k[pos.y][pos.x] + 1;
                if ( k[y][x] == int.min ||
                     k[y][x] > c ) {
                    k[y][x] = c;
                    dfs(k, P(y, x));
                }
            }
        }
    }
    k1[ps[0].y][ps[0].x] = 0;
    k2[ps[1].y][ps[1].x] = 0;
    dfs(k1, ps[0]);
    dfs(k2, ps[1]);
    //k1.formatWrite;
    //k2.formatWrite;
    foreach (i; 0 .. 8) {
        foreach (j; 0 .. 8) {
            if (k1[i][j] == int.min) continue;
            if (k2[i][j] == int.min) continue;
            if (F[i][j] == '#') continue;
            if (k1[i][j] == k2[i][j]) {
                return true;
            }
        }
    }
    return false;
}

void main() {
    int t; readf("%d\n", &t);
    foreach (i; 0 .. t) {
        foreach (j; 0 .. 8) {
            F[j] = stdin.readln.chomp;
        }
        readln; // skip empty line
        //F.writeln;
        //findPos.writeln;
        (check ? "YES" : "NO").writeln;
    }
}

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

alias Tuple!(int, "y", int, "x") P;

string[8] F;

void formatWrite(in int[8][8] k) {
    foreach (r; k) {
        foreach (c; r) {
            if (c == int.min) {
                write(" # ");
            } else {
                write(" " ~ c.to!string ~ " ");
            }
        }
        writeln;
    }
}

P[] findPos() {
    P[] pos = new P[2];
    int c = 0;
    foreach (i; 0 .. 8) {
        foreach (j; 0 .. 8) {
            if (F[i][j] == 'K') {
                pos[c].y = i;
                pos[c].x = j;
                c++;
                if (c == 2) {
                    return pos;
                }
            }
        }
    }
    throw new Exception("not found");
}

bool check() {
    auto ps = findPos;
    int[8][8] k1, k2;
    foreach (i; 0 .. 8) {
        foreach (j; 0 .. 8) {
            k1[i][j] = k2[i][j] = int.min;
        }
    }
    void dfs(ref int[8][8] k, P pos) {
        static int[] dy = [2,  2, -2, -2],
                     dx = [2, -2,  2, -2];
        if (k[pos.y][pos.x] == int.min) return;
        foreach (i; 0 .. 4) {
            int y = pos.y + dy[i];
            int x = pos.x + dx[i];
            if ( 0 <= y && y < 8 &&
                 0 <= x && x < 8 &&
                 F[y][x] != '#' ) {
                int c = k[pos.y][pos.x] + 1;
                if ( k[y][x] == int.min ||
                     k[y][x] > c ) {
                    k[y][x] = c;
                    dfs(k, P(y, x));
                }
            }
        }
    }
    k1[ps[0].y][ps[0].x] = 0;
    k2[ps[1].y][ps[1].x] = 0;
    dfs(k1, ps[0]);
    dfs(k2, ps[1]);
    //k1.formatWrite;
    //k2.formatWrite;
    foreach (i; 0 .. 8) {
        foreach (j; 0 .. 8) {
            if (k1[i][j] == int.min) continue;
            if (k2[i][j] == int.min) continue;
            if (k1[i][j] == k2[i][j]) {
                return true;
            }
        }
    }
    return false;
}

void main() {
    int t; readf("%d\n", &t);
    foreach (i; 0 .. t) {
        foreach (j; 0 .. 8) {
            F[j] = stdin.readln.chomp;
        }
        readln; // skip empty line
        //F.writeln;
        //findPos.writeln;
        (check ? "YES" : "NO").writeln;
    }
}


This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le q \le 3 \cdot 10^5$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.

NoteLet's look at the third test case:Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5-3+7=9$$$.After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be $$$2-1+5-3+7=10$$$.After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be $$$2-1+5-3+7=10$$$.After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be $$$2-1+5-3+7=10$$$.After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be $$$5-3+7=9$$$.After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be $$$4-2+5-3+7=11$$$.

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


Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi essays. He can raise the exam grade multiple times.What is the minimum number of essays that Vanya needs to write to get scholarship?

The first line contains three integers n, r, avg (1 ≤ n ≤ 105, 1 ≤ r ≤ 109, 1 ≤ avg ≤ min(r, 106)) — the number of exams, the maximum grade and the required grade point average, respectively. Each of the following n lines contains space-separated integers ai and bi (1 ≤ ai ≤ r, 1 ≤ bi ≤ 106).

In the first line print the minimum number of essays.

NoteIn the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.In the second sample, Vanya doesn't need to write any essays as his general point average already is above average.

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


Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally:Let a0, a1, ..., an denote the coefficients, so . Then, a polynomial P(x) is valid if all the following conditions are satisfied:  ai is integer for every i;  |ai| ≤ k for every i;  an ≠ 0. Limak has recently got a valid polynomial P with coefficients a0, a1, a2, ..., an. He noticed that P(2) ≠ 0 and he wants to change it. He is going to change one coefficient to get a valid polynomial Q of degree n that Q(2) = 0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.

The first line contains two integers n and k (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 109) — the degree of the polynomial and the limit for absolute values of coefficients. The second line contains n + 1 integers a0, a1, ..., an (|ai| ≤ k, an ≠ 0) — describing a valid polynomial . It's guaranteed that P(2) ≠ 0.

Print the number of ways to change one coefficient to get a valid polynomial Q that Q(2) = 0.

NoteIn the first sample, we are given a polynomial P(x) = 10 - 9x - 3x2 + 5x3.Limak can change one coefficient in three ways:  He can set a0 =  - 10. Then he would get Q(x) =  - 10 - 9x - 3x2 + 5x3 and indeed Q(2) =  - 10 - 18 - 12 + 40 = 0.  Or he can set a2 =  - 8. Then Q(x) = 10 - 9x - 8x2 + 5x3 and indeed Q(2) = 10 - 18 - 32 + 40 = 0.  Or he can set a1 =  - 19. Then Q(x) = 10 - 19x - 3x2 + 5x3 and indeed Q(2) = 10 - 38 - 12 + 40 = 0. In the second sample, we are given the same polynomial. This time though, k is equal to 12 instead of 109. Two first of ways listed above are still valid but in the third way we would get |a1| > k what is not allowed. Thus, the answer is 2 this time.

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

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

		auto b = new long [n + 1 + 100];
		foreach (i; 0..n + 1)
		{
			b[i] += a[i];
			int j = i;
			while (b[j])
			{
				long delta = b[j] / 2;
				debug {writeln (b[j], " ", delta);}
				b[j + 1] += delta;
				b[j] -= delta * 2;
				j++;
			}
		}
		debug {writeln (b);}

		int lo = b.countUntil !(q{a != 0});
		int hi = b.length - b.retro.countUntil !(q{a != 0});
		debug {writeln (lo, ' ', hi);}

		long cur = 0;
		int res = 0;
		foreach_reverse (i; 0..hi)
		{
			cur = cur * 2 + b[i];
			if (abs (cur) > k * 100)
			{
				break;
			}
			if (i > n)
			{
				continue;
			}
			if (i > lo)
			{
				continue;
			}
			auto next = a[i] - cur;
			debug {writeln (i, ": ", next);}
			if (i == n && next == 0)
			{
				continue;
			}
			if (abs (next) <= k)
			{
				res++;
			}
		}

		writeln (res);
	}
}


You are playing one famous sandbox game with the three-dimensional world. The map of the world can be represented as a matrix of size $$$n \times m$$$, where the height of the cell $$$(i, j)$$$ is $$$a_{i, j}$$$.You are in the cell $$$(1, 1)$$$ right now and want to get in the cell $$$(n, m)$$$. You can move only down (from the cell $$$(i, j)$$$ to the cell $$$(i + 1, j)$$$) or right (from the cell $$$(i, j)$$$ to the cell $$$(i, j + 1)$$$). There is an additional restriction: if the height of the current cell is $$$x$$$ then you can move only to the cell with height $$$x+1$$$.Before the first move you can perform several operations. During one operation, you can decrease the height of any cell by one. I.e. you choose some cell $$$(i, j)$$$ and assign (set) $$$a_{i, j} := a_{i, j} - 1$$$. Note that you can make heights less than or equal to zero. Also note that you can decrease the height of the cell $$$(1, 1)$$$.Your task is to find the minimum number of operations you have to perform to obtain at least one suitable path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the number of rows and the number of columns in the map of the world. The next $$$n$$$ lines contain $$$m$$$ integers each, where the $$$j$$$-th integer in the $$$i$$$-th line is $$$a_{i, j}$$$ ($$$1 \le a_{i, j} \le 10^{15}$$$) — the height of the cell $$$(i, j)$$$. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) over all test cases does not exceed $$$100$$$ ($$$\sum n \le 100; \sum m \le 100$$$).

For each test case, print the answer — the minimum number of operations you have to perform to obtain at least one suitable path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. It is guaranteed that the answer exists.

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

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


Vova plans to go to the conference by train. Initially, the train is at the point $$$1$$$ and the destination point of the path is the point $$$L$$$. The speed of the train is $$$1$$$ length unit per minute (i.e. at the first minute the train is at the point $$$1$$$, at the second minute — at the point $$$2$$$ and so on).There are lanterns on the path. They are placed at the points with coordinates divisible by $$$v$$$ (i.e. the first lantern is at the point $$$v$$$, the second is at the point $$$2v$$$ and so on).There is also exactly one standing train which occupies all the points from $$$l$$$ to $$$r$$$ inclusive.Vova can see the lantern at the point $$$p$$$ if $$$p$$$ is divisible by $$$v$$$ and there is no standing train at this position ($$$p \not\in [l; r]$$$). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to $$$t$$$ different conferences, so you should answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of queries. Then $$$t$$$ lines follow. The $$$i$$$-th line contains four integers $$$L_i, v_i, l_i, r_i$$$ ($$$1 \le L, v \le 10^9$$$, $$$1 \le l \le r \le L$$$) — destination point of the $$$i$$$-th path, the period of the lantern appearance and the segment occupied by the standing train.

Print $$$t$$$ lines. The $$$i$$$-th line should contain one integer — the answer for the $$$i$$$-th query.

NoteFor the first example query, the answer is $$$3$$$. There are lanterns at positions $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$ and $$$10$$$, but Vova didn't see the lanterns at positions $$$4$$$ and $$$6$$$ because of the standing train.For the second example query, the answer is $$$0$$$ because the only lantern is at the point $$$51$$$ and there is also a standing train at this point.For the third example query, the answer is $$$1134$$$ because there are $$$1234$$$ lanterns, but Vova didn't see the lanterns from the position $$$100$$$ to the position $$$199$$$ inclusive.For the fourth example query, the answer is $$$0$$$ because the standing train covers the whole path.

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

  int t;
  rd(t);
  while (t--) {
    long n, v, l, r;
    rd(n, v, l, r);
    auto num = (l - 1) / v;
    num += n / v - r / v;
    writeln(num);
  }
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}


Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $$$100^{500}$$$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $$$i$$$-th attack is performed at the beginning of the $$$a_i$$$-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals $$$1$$$ damage during each of the next $$$k$$$ seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).For example, suppose $$$k = 4$$$, and Monocarp stabs the dragon during the seconds $$$2$$$, $$$4$$$ and $$$10$$$. Then the poison effect is applied at the start of the $$$2$$$-nd second and deals $$$1$$$ damage during the $$$2$$$-nd and $$$3$$$-rd seconds; then, at the beginning of the $$$4$$$-th second, the poison effect is reapplied, so it deals exactly $$$1$$$ damage during the seconds $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$; then, during the $$$10$$$-th second, the poison effect is applied again, and it deals $$$1$$$ damage during the seconds $$$10$$$, $$$11$$$, $$$12$$$ and $$$13$$$. In total, the dragon receives $$$10$$$ damage.Monocarp knows that the dragon has $$$h$$$ hit points, and if he deals at least $$$h$$$ damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of $$$k$$$ (the number of seconds the poison effect lasts) that is enough to deal at least $$$h$$$ damage to the dragon.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$h$$$ ($$$1 \le n \le 100; 1 \le h \le 10^{18}$$$) — the number of Monocarp's attacks and the amount of damage that needs to be dealt. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9; a_i < a_{i + 1}$$$), where $$$a_i$$$ is the second when the $$$i$$$-th attack is performed.

For each test case, print a single integer — the minimum value of the parameter $$$k$$$, such that Monocarp will cause at least $$$h$$$ damage to the dragon.

NoteIn the first example, for $$$k=3$$$, damage is dealt in seconds $$$[1, 2, 3, 5, 6, 7]$$$.In the second example, for $$$k=4$$$, damage is dealt in seconds $$$[2, 3, 4, 5, 6, 7, 10, 11, 12, 13]$$$.In the third example, for $$$k=1$$$, damage is dealt in seconds $$$[1, 2, 4, 5, 7]$$$.

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