Tanya has $$$n$$$ candies numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th candy has the weight $$$a_i$$$.She plans to eat exactly $$$n-1$$$ candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.Your task is to find the number of such candies $$$i$$$ (let's call these candies good) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one.For example, $$$n=4$$$ and weights are $$$[1, 4, 3, 3]$$$. Consider all possible cases to give a candy to dad:  Tanya gives the $$$1$$$-st candy to dad ($$$a_1=1$$$), the remaining candies are $$$[4, 3, 3]$$$. She will eat $$$a_2=4$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$4+3=7$$$ and in even days she will eat $$$3$$$. Since $$$7 \ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $$$2$$$-nd candy to dad ($$$a_2=4$$$), the remaining candies are $$$[1, 3, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$3$$$. Since $$$4 \ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $$$3$$$-rd candy to dad ($$$a_3=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good).  Tanya gives the $$$4$$$-th candy to dad ($$$a_4=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_3=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good). In total there $$$2$$$ cases which should counted (these candies are good), so the answer is $$$2$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the weight of the $$$i$$$-th candy.

Print one integer — the number of such candies $$$i$$$ (good candies) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days.

NoteIn the first example indices of good candies are $$$[1, 2]$$$.In the second example indices of good candies are $$$[2, 3]$$$.In the third example indices of good candies are $$$[4, 5, 9]$$$.

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

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

  long s1 = 0, s2 = 0;
  foreach (i; 1 .. n) {
    if (i & 1) {
      s1 += a[i];
    } else {
      s2 += a[i];
    }
  }
  int ans = 0;
  if (s1 == s2) {
    ans++;
  }
  foreach (i; 1 .. n) {
    if (i & 1) {
      s1 -= a[i];
      s1 += a[i - 1];
    } else {
      s2 -= a[i];
      s2 += a[i - 1];
    }
    if (s1 == s2) {
      ans++;
    }
  }
  writeln(ans);
}

// 1, 2, 3, 4, 5
// ., 2, 3, 4, 5
// 1, ., 3, 4, 5
// 1, 2, ., 4, 5

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


You are given a set of $$$n$$$ ($$$n$$$ is always a power of $$$2$$$) elements containing all integers $$$0, 1, 2, \ldots, n-1$$$ exactly once.Find $$$\frac{n}{2}$$$ pairs of elements such that:  Each element in the set is in exactly one pair.  The sum over all pairs of the bitwise AND of its elements must be exactly equal to $$$k$$$. Formally, if $$$a_i$$$ and $$$b_i$$$ are the elements of the $$$i$$$-th pair, then the following must hold: $$$$$$\sum_{i=1}^{n/2}{a_i \& b_i} = k,$$$$$$ where $$$\&$$$ denotes the bitwise AND operation. If there are many solutions, print any of them, if there is no solution, print $$$-1$$$ instead.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 400$$$) — the number of test cases. Description of the test cases follows. Each test case consists of a single line with two integers $$$n$$$ and $$$k$$$ ($$$4 \leq n \leq 2^{16}$$$, $$$n$$$ is a power of $$$2$$$, $$$0 \leq k \leq n-1$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2^{16}$$$. All test cases in each individual input will be pairwise different.

For each test case, if there is no solution, print a single line with the integer $$$-1$$$. Otherwise, print $$$\frac{n}{2}$$$ lines, the $$$i$$$-th of them must contain $$$a_i$$$ and $$$b_i$$$, the elements in the $$$i$$$-th pair.  If there are many solutions, print any of them. Print the pairs and the elements in the pairs in any order.

NoteIn the first test, $$$(0\&3)+(1\&2) = 0$$$.In the second test, $$$(0\&2)+(1\&3) = 1$$$.In the third test, $$$(0\&1)+(2\&3) = 2$$$.In the fourth test, there is no solution.

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (n == 4 && k == 3) continue;

		foreach (i; 0..n/2)
		{
			ans[ti] ~= [i, n-i-1];
		}

		auto x = k & (n/2-1);
		swap(ans[ti][x][1], ans[ti][0][1]);
		if (k & (n/2))
		{
			if (x != n/2-1)
				swap(ans[ti][n/2-1][1], ans[ti][0][0]);
			else
				swap(ans[ti][n/2-2][1], ans[ti][0][0]);
		}
		debug
		{
			long tot;
			foreach (ee; ans[ti])
				tot += ee[0] & ee[1];
			if (tot != k)
				writeln("wa:n=", n, " k=", k);
		}
	}
	debug writeln("done");
	debug readln;

	foreach (e; ans)
	{
		if (e.empty)
			writeln(-1);
		foreach (ee; e)
			writeln(ee[0], " ", ee[1]);
	}
	stdout.flush;
	debug readln;
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int T = readln.chomp.to!int;
    foreach (t; 0 .. T) {
        int N, K; scanf("%d %d\n", &N, &K);
        int[] xs, ys;
        if (K == 0) {
            for (int i = 0; i < N/2; i++) {
                xs ~= i;
                ys ~= (N - 1) - i;
            }
        } else if (K <= N - 2) {
            for (int i = 1; i < N/2; i++) {
                if (i == K || i == N-1-K) continue;
                xs ~= i;
                ys ~= (N - 1) - i;
            }
            xs ~= N - 1;
            ys ~= K;
            xs ~= 0;
            ys ~= N - 1 - K;
        } else {
            // K == N - 1
            if (N >= 8) {
                xs ~= N-1; ys ~= N-2;
                xs ~= 1;   ys ~= 3;
                xs ~= 0;   ys ~= N-4;
                xs ~= N-3; ys ~= 2;
                for (int i = 4; i < N/2; i++) {
                    xs ~= i;
                    ys ~= (N - 1) - i;
                }
            } else {
                writeln(-1);
                continue;
            }
        }
        DBG!N;
        DBG!K;
        long s = 0;
        for (int i = 0; i < N/2; i++) {
            s += xs[i] & ys[i];
        }
        DBG!s;
        assert(xs.length == N/2 && ys.length == N/2);
        assert(s == K);
        for (int i = 0; i < N/2; i++) {
            writefln("%d %d", xs[i], ys[i]);
        }

    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		int [2] [] a;
		foreach (i; 0..n / 2)
		{
			a ~= [i, n - 1 - i];
		}
		if (n == 4 && k == 3)
		{
			writeln (-1);
			continue;
		}
		int t = min (k, n - 2);
		int pos = (t >= n / 2) ? (n - 1 - t) : (t);
		int qos = (t >= n / 2);
		swap (a[0][0], a[pos][qos]);
		if (k > t)
		{
			swap (a[pos][qos], a[$ - 1][0]);
		}
		writefln !("%(%(%s %)\n%)") (a);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (n == 4 && k == 3) break;

		foreach (i; 0..n/2)
		{
			ans[ti] ~= [i, n-i-1];
		}

		auto x = k & (n/2-1);
		swap(ans[ti][x][1], ans[ti][0][1]);
		if (k & (n/2))
		{
			if (x != n/2-1)
				swap(ans[ti][n/2-1][1], ans[ti][0][0]);
			else
				swap(ans[ti][n/2-2][1], ans[ti][0][0]);
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln(-1);
		foreach (ee; e)
			writeln(ee[0], " ", ee[1]);
	}
	stdout.flush;
	debug readln;
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int T = readln.chomp.to!int;
    foreach (t; 0 .. T) {
        int N, K; scanf("%d %d\n", &N, &K);
        int[] xs, ys;
        if (K == 0) {
            for (int i = 0; i < N/2; i++) {
                xs ~= i;
                ys ~= (N - 1) - i;
            }
        } else if (K <= N - 2) {
            for (int i = 1; i < N/2; i++) {
                if (i == K || i == N-1-K) continue;
                xs ~= i;
                ys ~= (N - 1) - i;
            }
            xs ~= N - 1;
            ys ~= K;
            xs ~= 0;
            ys ~= N - 1 - K;
        } else {
            // K == N - 1
            if (N >= 8) {
                xs ~= N-1; ys ~= N-2;
                xs ~= 1;   ys ~= 3;
                xs ~= 0;   ys ~= N-4;
                xs ~= N-3; ys ~= 2;
                for (int i = 4; i < N/2; i++) {
                    xs ~= i;
                    ys ~= (N - 1) - i;
                }
            } else {
                writeln(-1);
                return;
            }
        }
        DBG!N;
        DBG!K;
        long s = 0;
        for (int i = 0; i < N/2; i++) {
            s += xs[i] & ys[i];
        }
        DBG!s;
        assert(xs.length == N/2 && ys.length == N/2);
        assert(s == K);
        for (int i = 0; i < N/2; i++) {
            writefln("%d %d", xs[i], ys[i]);
        }

    }
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int T = readln.chomp.to!int;
    foreach (t; 0 .. T) {
        int N, K; scanf("%d %d\n", &N, &K);
        int[] xs, ys;
        if (K == 0) {
            for (int i = 0; i < N/2; i++) {
                xs ~= i;
                ys ~= (N - 1) - i;
            }
        } else if (K <= N - 2) {
            for (int i = 1; i < N/2; i++) {
                if (i == K || i == N-1-K) continue;
                xs ~= i;
                ys ~= (N - 1) - i;
            }
            xs ~= N - 1;
            ys ~= K;
            xs ~= 0;
            ys ~= N - 1 - K;
        } else {
            // K == N - 1
            if (N >= 8) {
                xs ~= N-1;
                ys ~= N-2;
                xs ~= 1;
                ys ~= 3;
                xs ~= 0;
                ys ~= N-4;
                xs ~= N - 3;
                ys ~= 2;
                for (int i = 5; i < N/2; i++) {
                    xs ~= i;
                    ys ~= (N - 1) - i;
                }
            } else {
                writeln(-1);
                return;
            }
        }
        assert(xs.length == N/2 && ys.length == N/2);
        long s = 0;
        for (int i = 0; i < N/2; i++) {
            s += xs[i] & ys[i];
        }
        assert(s == K);
        for (int i = 0; i < N/2; i++) {
            writefln("%d %d", xs[i], ys[i]);
        }

    }
}


Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where  is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.

The first line contains integers n, m, dx, dy(1 ≤ n ≤ 106, 1 ≤ m ≤ 105, 1 ≤ dx, dy ≤ n) — the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≤ xi, yi ≤ n - 1) — the coordinates of apples. One cell may contain multiple apple trees.

Print two space-separated numbers — the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.

NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)

import std.stdio;
import std.algorithm;

void main() { while (solve()) {} }
bool solve() {
	int n, m, dx, dy;
	if (readf(" %s %s %s %s", &n, &m, &dx, &dy) != 4)
		return false;

	auto genP(int n, int d) {
		auto res = new int[n];
		foreach (i; 0..n)
			res[i] = cast(int)(((cast(long) i) * d) % n);
		return res;
	}

	auto x = genP(n, dx);
	auto y = genP(n, dy);

	auto genPos(int[] x) {
		auto pos = new int[x.length];
		foreach (i; 0..x.length)
			pos[x[i]] = cast(int)i;
		return pos;
	}
	auto posx = genPos(x), posy = genPos(y);

	auto ans = new int[n];
	foreach (_; 0..m) {
		int px, py;
		readf(" %s %s", &px, &py);
		int i = posx[px], j = posy[py];
		ans[(j - i + n) % n]++;
	}

	int mxI = 0;
	foreach (i; 0..n)
		if (ans[i] > ans[mxI])
			mxI = i;
	writefln("%s %s", x[0], y[mxI]);

	return true;
}


Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t - 1 gestures (if the icon is on the screen t), and then make another gesture — press the icon of the required application exactly once to launch it.After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.

The first line of the input contains three numbers n, m, k (1 ≤ n, m, k ≤ 105) — the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen. The next line contains n integers, permutation a1, a2, ..., an — the initial order of icons from left to right in the menu (from the first to the last one), ai —  is the id of the application, whose icon goes i-th in the menu. Each integer from 1 to n occurs exactly once among ai. The third line contains m integers b1, b2, ..., bm(1 ≤ bi ≤ n) — the ids of the launched applications in the planned order. One application may be launched multiple times.

Print a single number — the number of gestures that Anya needs to make to launch all the applications in the desired order.

NoteIn the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1, 2, 3, the second screen contains icons 4, 5, 6, the third screen contains icons 7, 8. After application 7 is launched, we get the new arrangement of the icons — (123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture.In total, Anya makes 7 gestures.

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

void main ()
{
	int n, m, k;
	while (readf (" %s %s %s", &n, &m, &k) > 0)
	{
		auto p = new int [n];
		auto q = new int [n];
		foreach (i, ref x; p)
		{
			readf (" %s", &x);
			x--;
			q[x] = i;
		}

		long res = 0;
		foreach (i; 0..m)
		{
			int x;
			readf (" %s", &x);
			x--;
			int d = q[x];
			res += d / k + 1;
			if (d > 0)
			{
				swap (p[d], p[d - 1]);
				swap (q[p[d]], q[p[d - 1]]);
			}
		}
		writeln (res);
	}
}


Vasya has an array $$$a_1, a_2, \dots, a_n$$$.You don't know this array, but he told you $$$m$$$ facts about this array. The $$$i$$$-th fact is a triple of numbers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$) and it means:  if $$$t_i=1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is sorted in non-decreasing order;  if $$$t_i=0$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter. For example if $$$a = [2, 1, 1, 3, 2]$$$ then he could give you three facts: $$$t_1=1, l_1=2, r_1=4$$$ (the subarray $$$[a_2, a_3, a_4] = [1, 1, 3]$$$ is sorted), $$$t_2=0, l_2=4, r_2=5$$$ (the subarray $$$[a_4, a_5] = [3, 2]$$$ is not sorted), and $$$t_3=0, l_3=3, r_3=5$$$ (the subarray $$$[a_3, a_5] = [1, 3, 2]$$$ is not sorted).You don't know the array $$$a$$$. Find any array which satisfies all the given facts.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 1000, 1 \le m \le 1000$$$). Each of the next $$$m$$$ lines contains three integers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$). If $$$t_i = 1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is sorted. Otherwise (if $$$t_i = 0$$$) subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is not sorted.

If there is no array that satisfies these facts in only line print NO (in any letter case). If there is a solution, print YES (in any letter case). In second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$, satisfying all the given facts. If there are multiple satisfying arrays you can print any of them.

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

class DisjointSet {
  private:
    int [] p, h;
    int n;
  public:
  this (int _n) {
    n = _n;
    p = iota (0, n).array;
    h = new int[n];
  }
  int findSet (int x) pure nothrow @nogc {
    if (p[x] == x) {
      return x;
    }
    return p[x] = findSet (p[x]);
  }
  bool merge (int i, int j) pure nothrow @nogc {
    i = findSet (i);
    j = findSet (j);
    if (i != j) {
      if (h[i] < h[j]) {
        p[i] = j;
      } else if (h[i] > h[j]) {
        p[j] = i;
      } else {
        p[i] = j;
        ++h[j];
      }
      return true;
    }
    return false;
  }
}

alias T = Tuple!(uint, uint, uint);

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

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

void main() {
  auto r = new InputReader;
  immutable n = r.next!uint;
  immutable nq = r.next!uint;
  T[] a;
  foreach (q; 0 .. nq) {
    auto t = r.next!uint;
    auto u = r.next!uint;
    auto v = r.next!uint;
    a ~= tuple (u, v, t);
  }
  auto ds = new DisjointSet (n);
  foreach (p; a) {
    if (p[2] == 1) {
      foreach (o; p[0] .. p[1]) {
        ds.merge (o - 1, o);
      }
    }
  }

  auto x = new int[n];
  int cur;
  x[n - 1] = ++cur;
  foreach_reverse (i; 0 .. n - 1) {
    if (ds.findSet (i) == ds.findSet (i + 1)) {
      x[i] = x[i+1];
    } else {
      x[i] = ++cur;
    }
  }
  debug stderr.writeln (x);
  foreach (p; a) {
    if (p[2] == 0) {
      bool ok;
      foreach (o; p[0] .. p[1]) {
        if (x[o-1] > x[o]) {
          ok = true;
          break;
        }
      }
      if (!ok) {
        writeln ("NO");
        return;
      }
    }
  }
  writeln ("YES");
  writefln ("%(%d %)", x);
}


Stanley and Megan decided to shop in the "Crossmarket" grocery store, which can be represented as a matrix with $$$n$$$ rows and $$$m$$$ columns. Stanley and Megan can move to an adjacent cell using $$$1$$$ unit of power. Two cells are considered adjacent if they share an edge. To speed up the shopping process, Megan brought her portals with her, and she leaves one in each cell she visits (if there is no portal yet). If a person (Stanley or Megan) is in a cell with a portal, that person can use $$$1$$$ unit of power to teleport to any other cell with a portal, including Megan's starting cell.They decided to split up: Stanley will go from the upper-left cell (cell with coordinates $$$(1, 1)$$$) to the lower-right cell (cell with coordinates $$$(n, m)$$$), whilst Megan needs to get from the lower-left cell (cell with coordinates $$$(n, 1)$$$) to the upper-right cell (cell with coordinates $$$(1, m)$$$).What is the minimum total energy needed for them both to do that?Note that they can choose the time they move. Time does not affect energy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The only line in the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$).

For each test case print a single integer on a new line – the answer.

Note  In the first test case they can stick to the following plan:   Megan (red circle) moves to the cell $$$(7, 3)$$$. Then she goes to the cell $$$(1, 3)$$$, and Stanley (blue circle) does the same.  Stanley uses the portal in that cell (cells with portals are grey) to get to the cell $$$(7, 3)$$$. Then he moves to his destination — cell $$$(7, 5)$$$.  Megan also finishes her route and goes to the cell $$$(1, 5)$$$. The total energy spent is $$$(2 + 6) + (2 + 1 + 2) + (2)= 15$$$, which is our final answer.

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void solve() {
    int n, m; readf("%d %d\n", &n, &m);
    if (n == 1 && m == 1) {
        writeln(0);
        return;
    }
    if (n <= m) swap(n, m);
    writeln(n + m - 2 + m);
}

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


Let's call a sequence of integers $$$x_1, x_2, \dots, x_k$$$ MEX-correct if for all $$$i$$$ ($$$1 \le i \le k$$$) $$$|x_i - \operatorname{MEX}(x_1, x_2, \dots, x_i)| \le 1$$$ holds. Where $$$\operatorname{MEX}(x_1, \dots, x_k)$$$ is the minimum non-negative integer that doesn't belong to the set $$$x_1, \dots, x_k$$$. For example, $$$\operatorname{MEX}(1, 0, 1, 3) = 2$$$ and $$$\operatorname{MEX}(2, 1, 5) = 0$$$.You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. Calculate the number of non-empty MEX-correct subsequences of a given array. The number of subsequences can be very large, so print it modulo $$$998244353$$$. Note: a subsequence of an array $$$a$$$ is a sequence $$$[a_{i_1}, a_{i_2}, \dots, a_{i_m}]$$$ meeting the constraints $$$1 \le i_1 < i_2 < \dots < i_m \le n$$$. If two different ways to choose the sequence of indices $$$[i_1, i_2, \dots, i_m]$$$ yield the same subsequence, the resulting subsequence should be counted twice (i. e. two subsequences are different if their sequences of indices $$$[i_1, i_2, \dots, i_m]$$$ are not the same).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$5 \cdot 10^5$$$.

For each test case, print a single integer — the number of non-empty MEX-correct subsequences of a given array, taken modulo $$$998244353$$$.

NoteIn the first example, the valid subsequences are $$$[0]$$$, $$$[1]$$$, $$$[0,1]$$$ and $$$[0,2]$$$.In the second example, the valid subsequences are $$$[0]$$$ and $$$[1]$$$.In the third example, any non-empty subsequence is valid.

immutable multi = true;

long p = 998244353;
long[100_000+1] twoPow;

static this()
{
  twoPow[0] = 1;
  foreach(i; 1 .. twoPow.length)
    {
      twoPow[i] = (twoPow[i-1]<<1)%p;
    }
}

void solve(int tc)
{
  auto n = readInt!int;
  auto a = ma(n, readInt!int) ~ 0;
  auto posS = new int[](n+1);
  posS[] = n;
  auto dpV = new bool[][][](n, 3, 2);
  auto dp = new long[][][](n, 3, 2);
  int getNxtI(int i, int mex)
  {
    int ans = n;
    foreach(v; mex - 1 .. mex + 2)
      {
	if (v >= 0 && v <= n)
	  {
	    ans = min(ans, posS[v]);
	  }
      }
    return ans;
  }
  long getDp(int i, int dlt, int upper)
  {
    if (i == n) return 0;
    bool* valid = &dpV[i][dlt][upper];
    long* value = &dp[i][dlt][upper];
    dlt--;
    if (*valid) return *value;
    int mex = a[i] + dlt;
    debug writeln("at ", i, " with mex ", mex, " upper ", upper);
    *value = 0;
    // take
    {
      debug writeln("if take");
      int nmex = mex;
      int nupper = upper;
      if (a[i] == mex) { debug writeln("mex updated"); nmex = mex + 1 + upper; nupper = 0; }
      else
	{
	  nmex = mex;
	  nupper = upper || (a[i] == mex + 1);
	}
      int nxtI = getNxtI(i, nmex);
      if (abs(nmex - a[i]) > 1) goto notake;
      *value += getDp(nxtI, nmex - a[nxtI] + 1, nupper) + 1;
      *value %= p;
    }
    // notake
  notake:
    {
      debug writeln("if no take");
      int nxtI = getNxtI(i, mex);
      assert(nxtI > i);
      *value += getDp(nxtI, mex - a[nxtI] + 1, upper);
      *value %= p;
      debug writeln("end if no take");
    }
    *valid = true;
    debug writeln("at ", i, " with mex ", mex, " value ", *value);
    return *value;
  }

  foreach_reverse(i; 0 .. n)
    {
      foreach(dlt; 0 .. 3)
	foreach(upper; 0 .. 2)
	  getDp(i, dlt, upper);

      posS[a[i]] = cast(int)i;
    }

  auto i = getNxtI(-1, 0);
  debug writeln("index is ", i);
  getDp(i, 1-a[i], 0).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;
// }}}


Let's call a string good if its length is at least $$$2$$$ and all of its characters are $$$\texttt{A}$$$ except for the last character which is $$$\texttt{B}$$$. The good strings are $$$\texttt{AB},\texttt{AAB},\texttt{AAAB},\ldots$$$. Note that $$$\texttt{B}$$$ is not a good string.You are given an initially empty string $$$s_1$$$.You can perform the following operation any number of times:   Choose any position of $$$s_1$$$ and insert some good string in that position. Given a string $$$s_2$$$, can we turn $$$s_1$$$ into $$$s_2$$$ after some number of operations?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single string $$$s_2$$$ ($$$1 \leq |s_2| \leq 2 \cdot 10^5$$$). It is guaranteed that $$$s_2$$$ consists of only the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$. It is guaranteed that the sum of $$$|s_2|$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" (without quotes) if we can turn $$$s_1$$$ into $$$s_2$$$ after some number of operations, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAB}} \to \texttt{A}\color{red}{\texttt{AB}}\texttt{AB}$$$.In the third test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAAAAAAAB}}$$$.In the second and fourth test case, it can be shown that it is impossible to turn $$$s_1$$$ into $$$s_2$$$.

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

bool solve (string s)
{
	if (s.back != 'B')
	{
		return false;
	}
	int b = 0;
	foreach (ref c; s)
	{
		b += (c == 'A') ? +1 : -1;
		if (b < 0)
		{
			return false;
		}
	}
	return true;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		writeln (solve (s) ? "YES" : "NO");
	}
}

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

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

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

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

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

        bool ans = true;
        int now;
        foreach (s; S) {
          (s == 'A') ? ++now : --now;
          ans = ans && (now >= 0);
        }
        ans = ans && (S[$ - 1] == 'B');
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}

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

bool solve (string s)
{
	if (!s.canFind ('B'))
	{
		return false;
	}
	int b = 0;
	foreach (ref c; s)
	{
		b += (c == 'A') ? +1 : -1;
		if (b < 0)
		{
			return false;
		}
	}
	return true;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		writeln (solve (s) ? "YES" : "NO");
	}
}


The polar bears have discovered a gigantic circular piece of floating ice with some mystic carvings on it. There are n lines carved on the ice. Each line connects two points on the boundary of the ice (we call these points endpoints). The endpoints are numbered 1, 2, ..., 2n counter-clockwise along the circumference. No two lines share an endpoint.Now a group of 6 polar bears (Alice, Bob, Carol, Dave, Eve, Frank) are going to build caves on the endpoints. Each polar bear would build a cave and live in it. No two polar bears can build a cave on the same endpoints. Alice and Bob is a pair of superstitious lovers. They believe the lines are carved by aliens (or humans, which are pretty much the same thing to polar bears), and have certain spiritual power. Therefore they want to build their caves on two endpoints which are connected by a line. The same for Carol and Dave, Eve and Frank.The distance between two caves X and Y is defined as one plus minimum number of other caves one need to pass through in order to travel from X to Y along the boundary of the ice (endpoints without caves are not counted).To ensure fairness, the distances between the three pairs of lovers have to be the same (that is, the distance between Alice and Bob, the distance between Carol and Dave, and the distance between Eve and Frank are the same).The figures below show two different configurations, where the dots on the circle are the endpoints. The configuration on the left is not valid. Although each pair of lovers (A and B, C and D, E and F) is connected a line, the distance requirement is not satisfied. The distance between A and B is 2 (one can go from A to B in the clockwise direction passing through F). The distance between E and F is also 2. However, the distance between C and D is 1 (one can go from C to D in the counter-clockwise direction without passing through any other caves). The configuration on the right is valid. All three pairs have the same distance 1.  Count the number of ways to build the caves under the requirements. Two configurations are considered the same if the same set of 6 endpoints are used.

The first line contains integer n(3 ≤ n ≤ 105) — the number of lines. Each of the following n lines contains two integers ai, bi (1 ≤ ai, bi ≤ 2n), which means that there is a line carved on the ice connecting the ai–th and bi–th endpoint.  It's guaranteed that each endpoints touches exactly one line.

Print the number of ways to build the caves. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteThe second sample corresponds to the figure in the problem statement.

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

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

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

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

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

void bitAdd(long[] bit, int pos, long val) {
	for (int x = pos; x < bit.length; x |= x + 1) {
		bit[x] += val;
	}
}
long bitSum(long[] bit, int pos) {
	long ret;
	for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
		ret += bit[x];
	}
	return ret;
}

int N;
int[] A, B;

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

		int[] fr = new int[N * 2 * 2];
		foreach (i; 0 .. N) {
			fr[A[i]] = B[i];
			fr[B[i]] = A[i];
		}
		foreach (x; 0 .. N * 2) {
			for (; fr[x] > x; ) {
				fr[x] -= N * 2;
			}
		}
		foreach (x; N * 2 .. N * 2 * 2) {
			fr[x] = fr[x - N * 2] + N * 2;
		}
debug{
writeln("fr = ",fr);
}

		long[] ss = new long[N * 2];
		long total;
		long[] bit = new long[N * 2 * 2];
		foreach (x; 0 .. N * 2 * 2) {
			if (0 <= fr[x] && fr[x] < N * 2) {
				ss[fr[x]] = total - bit.bitSum(fr[x]);
			}
			if (0 <= fr[x]) {
				++total;
				bit.bitAdd(fr[x], +1);
			}
		}
debug{
writeln("ss = ",ss);
}
		const long n = N;
		long f0, f1, f2, f3;
		foreach (i; 0 .. N) {
			const sA = ss[A[i]];
			const sB = ss[B[i]];
			const t = n - 1 - sA - sB;
debug{
writeln(sA," ",sB," ",t);
}
			f0 += sA * sB;
			f1 += sA * (sA - 1) / 2 + sB * (sB - 1) / 2;
			f2 += (sA + sB) * t;
			f3 += t * (t - 1) / 2;
		}
debug{
writeln("f = ",f0," ",f1," ",f2," ",f3);
}

		/*
			f0 = a
			f1 = 2 a + 3 b + c
			f2 = 2 c + 2 d
			f3 = d + 3 e
		*/
assert(f0+f1+f2+f3==n*(n-1)*(n-2)/6*3);
		assert(f2 % 2 == 0);
		long ans = f1 - f0 * 2 + f3 - f2 / 2;
		assert(ans % 3 == 0);
		ans /= 3;
		writeln(ans);
	}
	} catch (EOFException) {}
}


Vlad and Nastya live in a city consisting of $$$n$$$ houses and $$$n-1$$$ road. From each house, you can get to the other by moving only along the roads. That is, the city is a tree.Vlad lives in a house with index $$$x$$$, and Nastya lives in a house with index $$$y$$$. Vlad decided to visit Nastya. However, he remembered that he had postponed for later $$$k$$$ things that he has to do before coming to Nastya. To do the $$$i$$$-th thing, he needs to come to the $$$a_i$$$-th house, things can be done in any order. In $$$1$$$ minute, he can walk from one house to another if they are connected by a road.Vlad does not really like walking, so he is interested what is the minimum number of minutes he has to spend on the road to do all things and then come to Nastya. Houses $$$a_1, a_2, \dots, a_k$$$ he can visit in any order. He can visit any house multiple times (if he wants).

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. There is an empty line before each test case. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — the number of houses and things, respectively. The second line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) — indices of the houses where Vlad and Nastya live, respectively. The third line of each test case contains $$$k$$$ integers $$$a_1, a_2, \dots, a_k$$$ ($$$1 \le a_i \le n$$$) — indices of houses Vlad need to come to do things. The following $$$n-1$$$ lines contain description of city, each line contains two integers $$$v_j$$$ and $$$u_j$$$ ($$$1 \le u_j, v_j \le n$$$) — indices of houses connected by road $$$j$$$. It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2\cdot10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer output single integer — the minimum number of minutes Vlad needs on the road to do all the things and come to Nastya.

NoteTree and best path for the first test case:  $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$ Tree and best path for the second test case:  $$$3 \rightarrow 1 \rightarrow 3 \rightarrow 5 \rightarrow 2 \rightarrow 5 \rightarrow 6 \rightarrow 5$$$ Tree and best path for the third test case:  $$$3 \rightarrow 5 \rightarrow 2$$$

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

enum int INF = 1<<29;

void solve() {
    readln;
    int N, K; readf("%d %d\n", &N, &K);
    int X, Y; readf("%d %d\n", &X, &Y); X--; Y--;
    auto _A = readln.chomp.split(" ").map!(to!int).array;
    auto A = new bool[N];
    foreach (a; _A) {
        a--;
        A[a] = true;
    }
    auto G = new int[][N];
    foreach (i; 0 .. (N-1)) {
        int u, v; readf("%d %d\n", &u, &v);
        u--; v--;
        G[u] ~= v;
        G[v] ~= u;
    }

    alias P = Tuple!(bool,"g", int,"v", int,"p");
    alias S = Tuple!(int,bool);
    S[P] cache;
    S f(bool g, int v, int p) {
        auto key = P(g, v, p);
        if (key in cache) return cache[key];
        int ans = 0;
        bool a_exist = A[v];
        foreach (nv; G[v]) {
            if (nv == p) continue;
            auto c = f(g, nv, v);
            if (c[1]) {
                ans += c[0] + (g ? 1 : 2);
                a_exist = true;
            }
        }
        return cache[key] = S(ans, a_exist);
    }

    auto dx = new int[N]; dx[] = INF;
    auto dy = new int[N]; dy[] = INF;
    void filld(int v, int p, int d, int[] ds) {
        ds[v] = d;
        foreach (nv; G[v]) {
            if (nv == p) continue;
            filld(nv, v, d+1, ds);
        }
    }
    filld(X, -1, 0, dx);
    filld(Y, -1, 0, dy);

    int total = f(false, X, -1)[0];
    int ans = INF;
    for (int z = 0; z < N; z++) {
        if (A[z]) {
            ans = min(ans, total - dx[z] + dy[z]);
        }
    }
    writeln(ans);
}

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

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

immutable int NA = -1;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		int x, y;
		readf !(" %s %s") (x, y);
		x -= 1;
		y -= 1;
		readln;

		auto a = readln.splitter.map !(to !(int)).array;
		a[] -= 1;
		auto imp = new bool [n];
		foreach (ref c; a)
		{
			imp[c] = true;
		}
		imp[y] = true;

		auto adj = new int [] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}
		readln;

		auto d = new int [n];

		void recur (int v, int p, int depth)
		{
			d[v] = depth;
			foreach (ref u; adj[v])
			{
				if (u != p)
				{
					recur (u, v, depth + 1);
					imp[v] |= imp[u];
				}
			}
		}

		recur (x, NA, 0);

		writeln ((imp.sum - 1) * 2 - d[y]);
	}
}


A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are  roads in total. It takes exactly y seconds to traverse any single road.A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads.Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y.You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once.

The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 109). Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree.

Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once.

NoteIn the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is .In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is .

import std.algorithm;
import std.range;
import std.stdio;

immutable int INF = int.max / 4;
immutable int NA  = -1;

void main ()
{
	int n, x, y;
	while (readf (" %s %s %s", &n, &x, &y) > 0)
	{
		auto a = new int [] [n];
		auto d = new int [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u] ~= v;
			a[v] ~= u;
			d[u]++;
			d[v]++;
		}

		long res;
		if (x < y)
		{
			auto f = new int [3] [n];

			void recur (int v, int p)
			{
				int [3] [2] g;
				int b = 0;
				g[b][] = 1;
				foreach (u; a[v])
				{
					if (u == p)
					{
						continue;
					}
					recur (u, v);

					b ^= 1;
					g[b][] = INF;
					// skip
					foreach (i; 0..3)
					{
						g[b][i] = min (g[b][i],
						    g[!b][i] + f[u][2]);
					}
					// take
					foreach (i; 0..2)
					{
						g[b][i + 1] = min (g[b][i + 1],
						    g[!b][i] + f[u][1] - 1);
					}
				}
				f[v][] = g[b][];
				f[v][1] = min (f[v][1], f[v][0]);
				f[v][2] = min (f[v][2], f[v][1]);
				debug {writeln (v + 1, " ", f[v][]);}
			}

			recur (0, NA);

			int num = f[0][2] - 1;
			res = num * 1L * y + (n - num - 1) * 1L * x;
		}
		else
		{
			if (d.minPos !(q{a > b}).front == n - 1)
			{
				res = (n - 2) * 1L * y + x;
			}
			else
			{
				res = (n - 1) * 1L * y;
			}
		}
		writeln (res);
	}
}


Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $$$M$$$ with $$$n$$$ rows and $$$n$$$ columns such that $$$M_{ij}=a_i \cdot a_j$$$ where $$$a_1, \dots, a_n$$$ is some sequence of positive integers.Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $$$a_1, \dots, a_n$$$. Help Sasha restore the array!

The first line contains a single integer $$$n$$$ ($$$3 \leqslant n \leqslant 10^3$$$), the size of the table.  The next $$$n$$$ lines contain $$$n$$$ integers each. The $$$j$$$-th number of the $$$i$$$-th line contains the number $$$M_{ij}$$$ ($$$1 \leq M_{ij} \leq 10^9$$$). The table has zeroes on the main diagonal, that is, $$$M_{ii}=0$$$.

In a single line print $$$n$$$ integers, the original array $$$a_1, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that an answer exists. If there are multiple answers, print any.

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

int gcd(int a, int b) {
    if (b == 0) return a;
    else return gcd(b,a%b);
}

void main() {
    int n;
    readf!" %s"(n);

    int[][] a = new int[][](n,n);

    foreach (i; 0 .. n) {
        foreach (j; 0 .. n) {
            readf!" %s"(a[i][j]);
        }
    }

    int g = 0;
    foreach(j; 0 .. n) {
        g = gcd(g,a[0][j]);
    }

    int ans;
    for (long i = 1; i*i <= g; i++) {
        if (g % i == 0) {
            if ((a[0][1]/i) * (a[0][2]/i) == a[1][2]){
                ans = to!int(i);
                break;
            }
            if ((a[0][1]/(g/i)) * (a[0][2]/(g/i)) == a[1][2]) {
                ans = g/i;
                break;
            }
        }
    }

    writef!"%d "(ans);
    foreach (i; 1 .. n) {
        writef!"%d "(a[0][i]/ans);
    }
    writeln();
}

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

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

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

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

int N;
long[][] M;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      M = new long[][](N, N);
      foreach (x; 0 .. N) foreach (y; 0 .. N) {
        M[x][y] = readLong();
      }

      auto ans = new long[N];
      foreach (i; 0 .. N) {
        const j = (i + 1) % N;
        const k = (i + 2) % N;
        const b = M[i][j] * M[i][k] / M[j][k];
        long lo = 0, hi = 2 * cast(long)(sqrt(cast(real)(b))) + 10;
        for (; lo + 1 < hi; ) {
          const mid = (lo + hi) / 2;
          (mid * mid >= b) ? (hi = mid) : (lo = mid);
        }
        ans[i] = hi;
      }
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

int N;
long[][] M;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      M = new long[][](N, N);
      foreach (x; 0 .. N) foreach (y; 0 .. N) {
        M[x][y] = readLong();
      }

      auto ans = new long[N];
      foreach (i; 0 .. N) {
        const j = (i + 1) % N;
        const k = (i + 2) % N;
        const b = M[i][j] * M[i][k] / M[j][k];
        long lo = 0, hi = b;
        for (; lo + 1 < hi; ) {
          const mid = (lo + hi) / 2;
          (mid * mid >= b) ? (hi = mid) : (lo = mid);
        }
        ans[i] = hi;
      }
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


You came to the exhibition and one exhibit has drawn your attention. It consists of $$$n$$$ stacks of blocks, where the $$$i$$$-th stack consists of $$$a_i$$$ blocks resting on the surface.The height of the exhibit is equal to $$$m$$$. Consequently, the number of blocks in each stack is less than or equal to $$$m$$$.There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks. Find the maximum number of blocks you can remove such that the views for both the cameras would not change.Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$1 \le m \le 10^9$$$) — the number of stacks and the height of the exhibit. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the number of blocks in each stack from left to right.

Print exactly one integer — the maximum number of blocks that can be removed.

NoteThe following pictures illustrate the first example and its possible solution.Blue cells indicate removed blocks. There are $$$10$$$ blue cells, so the answer is $$$10$$$.

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

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

    long m = A.back + 1;
    long ans = 0;

    foreach_reverse (a; A) {
        if (a == 0) {
            if (m > 1) {
                ans -= m - 1;
            }
        } else if (m == 1) {
            ans += a - 1;
        } else if (m <= a + 1) {
            ans += a - 1;
            m -= 1;
        } else {
            ans -= m - a - 1;
            ans += a - 1;
            m = a;
        }
    }

    ans.writeln;
}


There are $$$n$$$ lamps on a line, numbered from $$$1$$$ to $$$n$$$. Each one has an initial state off ($$$0$$$) or on ($$$1$$$).You're given $$$k$$$ subsets $$$A_1, \ldots, A_k$$$ of $$$\{1, 2, \dots, n\}$$$, such that the intersection of any three subsets is empty. In other words, for all $$$1 \le i_1 < i_2 < i_3 \le k$$$, $$$A_{i_1} \cap A_{i_2} \cap A_{i_3} = \varnothing$$$.In one operation, you can choose one of these $$$k$$$ subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let $$$m_i$$$ be the minimum number of operations you have to do in order to make the $$$i$$$ first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between $$$i+1$$$ and $$$n$$$), they can be either off or on.You have to compute $$$m_i$$$ for all $$$1 \le i \le n$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 3 \cdot 10^5$$$). The second line contains a binary string of length $$$n$$$, representing the initial state of each lamp (the lamp $$$i$$$ is off if $$$s_i = 0$$$, on if $$$s_i = 1$$$). The description of each one of the $$$k$$$ subsets follows, in the following format: The first line of the description contains a single integer $$$c$$$ ($$$1 \le c \le n$$$)  — the number of elements in the subset. The second line of the description contains $$$c$$$ distinct integers $$$x_1, \ldots, x_c$$$ ($$$1 \le x_i \le n$$$)  — the elements of the subset. It is guaranteed that:    The intersection of any three subsets is empty;  It's possible to make all lamps be simultaneously on using some operations.

You must output $$$n$$$ lines. The $$$i$$$-th line should contain a single integer $$$m_i$$$  — the minimum number of operations required to make the lamps $$$1$$$ to $$$i$$$ be simultaneously on.

NoteIn the first example:   For $$$i = 1$$$, we can just apply one operation on $$$A_1$$$, the final states will be $$$1010110$$$;  For $$$i = 2$$$, we can apply operations on $$$A_1$$$ and $$$A_3$$$, the final states will be $$$1100110$$$;  For $$$i \ge 3$$$, we can apply operations on $$$A_1$$$, $$$A_2$$$ and $$$A_3$$$, the final states will be $$$1111111$$$. In the second example:   For $$$i \le 6$$$, we can just apply one operation on $$$A_2$$$, the final states will be $$$11111101$$$;  For $$$i \ge 7$$$, we can apply operations on $$$A_1, A_3, A_4, A_6$$$, the final states will be $$$11111111$$$.

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

void main ()
{
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto toDo = readln.strip.map !(x => x == '0').array;
		auto a = new int [] [n];
		auto s = new int [] [k];
		foreach (j; 0..k)
		{
			int len;
			readf !(" %s") (len);
			foreach (i; 0..len)
			{
				int elem;
				readf !(" %s") (elem);
				elem -= 1;
				a[elem] ~= j;
				s[j] ~= elem;
			}
		}

		auto p = k.iota.array;
		auto comp = new int [] [k];
		auto cost = new int [k];
		auto state = new int [k];
		auto stateRoot = new int [k];
		auto isFixed = new bool [k];

		foreach (j; 0..k)
		{
			comp[j] ~= j;
		}

		int root (int v)
		{
			if (p[v] != v)
			{
				p[v] = root (p[v]);
			}
			return p[v];
		}

		int getState (int u)
		{
			return state[u] ^ stateRoot[root (u)];
		}

		int totalCost = 0;

		void switchComp (int u)
		{
			auto x = root (u);
			debug {writeln ("switchComp ", u, " ", x);}
			stateRoot[x] ^= 1;
			auto newCostX = comp[x].length.to !(int) - cost[x];
			debug {writeln (cost[x], " -> ", newCostX);}
			totalCost -= cost[x];
			cost[x] = newCostX;
			totalCost += cost[x];
		}

		bool unite (int u, int v, bool toDoHere)
		{
			auto x = root (u);
			auto y = root (v);
			debug {writeln ("unite ", u, " ", v, " ",
			    toDoHere, " ", x, " ", y);}
			auto hasWork = toDoHere ^ getState (u) ^ getState (v);
			debug {writeln (toDoHere, " ", getState (u), " ",
			    getState (v));}
			if (hasWork)
			{
				debug {writeln ("hasWork ", x, " ", y);}
				if (x == y)
				{
					assert (false);
				}
				auto newCostX =
				    comp[x].length.to !(int) - cost[x];
				auto newCostY =
				    comp[y].length.to !(int) - cost[y];
				if (!isFixed[x] && (isFixed[y] ||
				    cost[x] + newCostY > newCostX + cost[y]))
				{
					swap (u, v);
					swap (x, y);
				}
				if (isFixed[y])
				{
					assert (false);
				}
				switchComp (y);
			}

			if (x == y)
			{
				return false;
			}
			if (comp[y].length < comp[x].length)
			{
				swap (x, y);
			}
			if (stateRoot[x] != stateRoot[y])
			{
				foreach (w; comp[x])
				{
					state[w] ^= 1;
				}
			}
			p[x] = y;
			comp[y] ~= comp[x];
			cost[y] += cost[x];
			isFixed[y] |= isFixed[x];
			return true;
		}

		foreach (i; 0..n)
		{
			debug {writeln (i + 1, ": type ", a[i].length);}
			debug {writeln ("state: ", state);}
			debug {writeln ("stateRoot: ", stateRoot);}
			debug {writeln ("getState: ", k.iota.map !(getState));}
			debug {writeln ("isFixed: ", isFixed);}
			if (a[i].length == 0)
			{
			}
			else if (a[i].length == 1)
			{
				auto u = a[i][0];
				auto x = root (u);
				auto hasWork = toDo[i] ^ getState (u);
				if (hasWork)
				{
					if (isFixed[x])
					{
						assert (false);
					}
					switchComp (x);
				}
				isFixed[x] = true;
			}
			else if (a[i].length == 2)
			{
				unite (a[i][0], a[i][1], toDo[i]);
			}
			else
			{
				assert (false);
			}

			writeln (totalCost);
		}
	}
}

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

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

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

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

int M, K;
string S;
int[] C;
int[][] X;

int[][] uss;
int[][] graph;
int[] colors;

void dfs(int u) {
  foreach (i; graph[u]) {
    const v = uss[i][0] ^ uss[i][1] ^ u;
    if (colors[v] == -1) {
      colors[v] = (colors[u] ^ ('1' - S[i]));
      dfs(v);
    }
    assert(colors[v] == (colors[u] ^ ('1' - S[i])));
  }
}

void main() {
  try {
    for (; ; ) {
      M = readInt();
      K = readInt();
      S = readToken();
      C = new int[K];
      X = new int[][K];
      foreach (u; 0 .. K) {
        C[u] = readInt();
        X[u] = new int[C[u]];
        foreach (j; 0 .. C[u]) {
          X[u][j] = readInt() - 1;
        }
      }

      uss = new int[][M];
      foreach (u; 0 .. K) {
        foreach (j; 0 .. C[u]) {
          uss[X[u][j]] ~= u;
        }
      }
      graph = new int[][K + 1];
      foreach (i; 0 .. M) {
        switch (uss[i].length) {
          case 0: {
            // no edge
          } break;
          case 1: {
            uss[i] ~= K;
            graph[uss[i][0]] ~= i;
            graph[uss[i][1]] ~= i;
          } break;
          case 2: {
            graph[uss[i][0]] ~= i;
            graph[uss[i][1]] ~= i;
          } break;
          default: assert(false);
        }
      }
      debug {
        writeln("uss = ", uss);
      }
      colors = new int[K + 1];
      colors[] = -1;
      foreach_reverse (u; 0 .. K + 1) {
        if (colors[u] == -1) {
          colors[u] = 0;
          dfs(u);
        }
      }
      debug {
        writeln("colors = ", colors);
      }

      int ans;
      auto nums = new int[][](K + 1, 2);
      foreach (u; 0 .. K + 1) {
        ++nums[u][colors[u]];
      }
      auto uf = new int[K + 1];
      uf[] = -1;
      int get(int r) {
        if (uf.root(K) == r) {
          return nums[r][1];
        } else {
          return min(nums[r][0], nums[r][1]);
        }
      }

      foreach (i; 0 .. M) {
        if (uss[i]) {
          int ru = uf.root(uss[i][0]);
          int rv = uf.root(uss[i][1]);
          if (ru != rv) {
            ans -= get(ru);
            ans -= get(rv);
            uf.connect(ru, rv);
            if (ru != uf.root(ru)) {
              swap(ru, rv);
            }
            nums[ru][] += nums[rv][];
            ans += get(ru);
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.

The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 106). Each character in s will be either "l" or "r".

Output n lines — on the i-th line you should print the i-th stone's number from the left.

NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1.

import std.stdio;

int len, p1, p2;
int[] ans;
char[] s;

int main() {
  readln(s);
  ans.length = s.length;
  len = s.length - 1;
  p1 = 0, p2 = len - 1;
  for (int i = 0; i < len; ++ i) {
    if (s[i] == 'l') ans[p2 --] = i + 1;
    else ans[p1 ++] = i + 1;
  }
  for (int i = 0; i < len; ++ i) writeln(ans[i]);
  return 0;
}

import std.stdio;
import std.c.stdio;
import std.typecons;

void output (Tuple !(int, int, int) v [], int i)
{
	if (i == -1)
	{
		return;
	}
	output (v, v[i][0]);
	printf ("%d\n", v[i][2]);
	output (v, v[i][1]);
}

int main ()
{
	string s;
	while ((s = readln ()) != null)
	{
		auto n = s.length - 1;
		Tuple !(int, int, int) v [];
		v ~= tuple (-1, -1, 1);
		foreach (int i; 0..n - 1)
		{
			if (s[i] == 'l')
			{
				v[$ - 1][0] = i + 1;
			}
			else
			{
				v[$ - 1][1] = i + 1;
			}
			v ~= tuple (-1, -1, i + 2);
		}

		output (v, 0);
	}
	return 0;
}

import std.stdio;
import std.c.stdio;
import std.typecons;

int main ()
{
	string s;
	while ((s = readln ()) != null)
	{
		auto n = s.length - 1;
		Tuple !(int, int, int) v [];
		v ~= tuple (-1, -1, 1);
		foreach (int i; 0..n - 1)
		{
			if (s[i] == 'l')
			{
				v[$ - 1][0] = i + 1;
			}
			else
			{
				v[$ - 1][1] = i + 1;
			}
			v ~= tuple (-1, -1, i + 2);
		}

		void output (int i)
		{
			if (i == -1)
			{
				return;
			}
			output (v[i][0]);
			printf ("%d\n", v[i][2]);
			output (v[i][1]);
		}

		output (0);
	}
	return 0;
}

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 S = readln.chomp;
    auto N = S.length.to!int;
    auto A = new int[](N);
    int l = 0, r = N - 1;

    foreach (i; 0..N) {
        if (S[i] == 'l') {
            A[i] = r;
            r--;
        } else {
            A[i] = l;
            l++;
        }
    }

    auto B = new int[](N);
    foreach (i; 0..N) B[A[i]] = i;
    B.each!(b => (b + 1).writeln);
}

import std.array;
import std.stdio;
import std.string;

void main() {
	string commands = strip(stdin.readln());

	auto array = appender!(int[])();

	foreach (i, c; commands) {
		if (c == 'r') {
			stdout.writeln(i + 1);
		} else {
			array.put(i + 1);
		}
	}

	auto end = array.data;

	for (int i = end.length - 1; i >= 0; --i) {
		stdout.writeln(end[i]);
	}
}


There are $$$n$$$ candles on a Hanukkah menorah, and some of its candles are initially lit. We can describe which candles are lit with a binary string $$$s$$$, where the $$$i$$$-th candle is lit if and only if $$$s_i=1$$$.  Initially, the candle lights are described by a string $$$a$$$. In an operation, you select a candle that is currently lit. By doing so, the candle you selected will remain lit, and every other candle will change (if it was lit, it will become unlit and if it was unlit, it will become lit).You would like to make the candles look the same as string $$$b$$$. Your task is to determine if it is possible, and if it is, find the minimum number of operations required.

The first line contains an integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) — the number of candles. The second line contains a string $$$a$$$ of length $$$n$$$ consisting of symbols 0 and 1 — the initial pattern of lights. The third line contains a string $$$b$$$ of length $$$n$$$ consisting of symbols 0 and 1 — the desired pattern of lights. It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^5$$$.

For each test case, output the minimum number of operations required to transform $$$a$$$ to $$$b$$$, or $$$-1$$$ if it's impossible.

NoteIn the first test case, the two strings are already equal, so we don't have to perform any operations.In the second test case, we can perform a single operation selecting the second candle to transform $$$01$$$ into $$$11$$$.In the third test case, it's impossible to perform any operations because there are no lit candles to select.In the fourth test case, we can perform the following operations to transform $$$a$$$ into $$$b$$$:   Select the $$$7$$$-th candle: $$$100010{\color{red}1}11\to 011101{\color{red} 1}00$$$.  Select the $$$2$$$-nd candle: $$$0{\color{red} 1}1101100\to 1{\color{red} 1}0010011$$$.  Select the $$$1$$$-st candle: $$${\color{red}1}10010011\to {\color{red}1}01101100$$$. In the fifth test case, we can perform the following operations to transform $$$a$$$ into $$$b$$$:   Select the $$$6$$$-th candle: $$$00101{\color{red}1}011\to 11010{\color{red}1}100$$$  Select the $$$2$$$-nd candle: $$$1{\color{red}1}0101100\to 0{\color{red}1}1010011$$$  Select the $$$8$$$-th candle: $$$0110100{\color{red}1}1\to 1001011{\color{red}1}0$$$  Select the $$$7$$$-th candle: $$$100101{\color{red}1}10\to 011010{\color{red}1}01$$$

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto s1 = cast(byte[]) readString;
  auto s2 = cast(byte[]) readString;
  int[2][2] cnt;
  foreach(i; 0 .. n)
    {
      cnt[s1[i]-'0'][s2[i]-'0']++;
    }
  debug {
    foreach(r; cnt) writeln(r);
  }
  int minops = int.max;
  int k = cnt[1][0];
  if (cnt[0][1] == k) minops = min(minops, 2 * k);
  k = cnt[0][0];
  if (cnt[1][1] - k - 1 == 0) minops = min(minops, 2 * k + 1);
  if (minops != int.max) return writeln(minops);
  return writeln(-1);
}

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

int solve(int c00, int c01, int c10, int c11, int depth, bool flag)
{
  if (depth > 1000001)
    return int.max;

  if (c01 + c10 == 0)
    return 0;

  int ans1 = int.max, ans2 = int.max;

  if (flag) {
    if (c11 > 0) {
      int x = solve(c10, c11 - 1, c00, c01 + 1, depth + 1, !flag);
      if (x != int.max)
        ans1 = 1 + x;
    }
  }

  if (!flag) {
    if (c10 > 0) {
      int x = solve(c10 - 1, c11, c00 + 1, c01, depth + 1, !flag);
      if (x != int.max)
        ans2 = 1 + x;
    }
  }

  return min(ans1, ans2);
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip;
    auto b = readln.strip;
    int c00, c01, c10, c11;
    foreach (i ; 0 .. n) {
      if (a[i] == '0' && b[i] == '0')
        c00++;
      if (a[i] == '0' && b[i] == '1')
        c01++;
      if (a[i] == '1' && b[i] == '0')
        c10++;
      if (a[i] == '1' && b[i] == '1')
        c11++;
    }
    int ans1 = solve(c00, c01, c10, c11, 0, true);
    int ans2 = solve(c00, c01, c10, c11, 0, false);
    int ans = min(ans1, ans2);
    writeln(ans == int.max ? -1 : ans);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long x0, x1, y0, y1;
		foreach (i; 0..n)
		{
			if (a[i] == b[i])
			{
				if (a[i] == '0')
					++x0;
				else
					++x1;
			}
			else
			{
				if (a[i] == '0')
					++y0;
				else
					++y1;
			}
		}
		ans[ti] = long.max;
		if ((x0+x1) % 2 == 1 && (x0+x1+1)/2 == x1)
			ans[ti].chmin(x0+x1);
		if ((y0+y1) % 2 == 0 && (y0+y1+1)/2 == y1)
			ans[ti].chmin(y0+y1);
		if (ans[ti] == long.max)
			ans[ti] = -1;
	}

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

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

int solve (int n, bool [] a, bool [] b)
{
	auto aOnes = a.sum.to !(int);
	auto bOnes = b.sum.to !(int);
	auto same = n.iota.count !(i => a[i] == b[i]).to !(int);
	auto diff = n - same;
	int res = int.max;
	if (aOnes == bOnes)
	{
		res = min (res, diff);
	}
	if (aOnes + bOnes == n + 1)
	{
		res = min (res, same);
	}
	if (res == int.max)
	{
		res = -1;
	}
	return res;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.strip.map !(q{a == '1'}).array;
		auto b = readln.strip.map !(q{a == '1'}).array;
		writeln (solve (n, a, b));
	}
}

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

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

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

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

enum INF = 10^^9;

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

        int ans = INF;
        if (A == B) {
          ans = 0;
        } else {
          const a = cast(int)(A.count('1'));
          const b = cast(int)(B.count('1'));
          if (a >= 1 && b >= 1 && a == b) {
            int d;
            foreach (i; 0 .. N) {
              if (A[i] != B[i]) {
                ++d;
              }
            }
            chmin(ans, d);
          }
          if (a >= 1 && b >= 1 && (a - 1) + (b - 1) == N - 1) {
            int d;
            foreach (i; 0 .. N) {
              if (A[i] == B[i]) {
                ++d;
              }
            }
            chmin(ans, d);
          }
        }

        writeln((ans >= INF) ? -1 : ans);
      }
    }
  } catch (EOFException e) {
  }
}


For a given array $$$a$$$ consisting of $$$n$$$ integers and a given integer $$$m$$$ find if it is possible to reorder elements of the array $$$a$$$ in such a way that $$$\sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}}$$$ equals $$$m$$$? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, $$$\frac{5}{2}=2.5$$$.

The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 100$$$). The test cases follow, each in two lines. The first line of a test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le 10^6$$$). The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$) — the elements of the array.

For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.

NoteIn the first test case one of the reorders could be $$$[1, 2, 5]$$$. The sum is equal to $$$(\frac{1}{1} + \frac{2}{2} + \frac{5}{3}) + (\frac{2}{2} + \frac{5}{3}) + (\frac{5}{3}) = 8$$$. The brackets denote the inner sum $$$\sum_{j=i}^{n}{\frac{a_j}{j}}$$$, while the summation of brackets corresponds to the sum over $$$i$$$.

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

void play(){
    int n, m;
    n = rd!int;
    m = rd!int;
    int summ = 0, el;
    foreach(i; 0..n){
        el = rd!int;
        summ += el;
    }
    if(summ == m){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

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

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
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)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, "x",  long, "y");
T max(T = long)(T a, T b){ return (a > b) ? a : b; }
T min(T = long)(T a, T b){ return (a < b) ? a : b; }

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

string FMT_F = "%.10f";

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

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

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

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

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

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush;
	debug readln;
}


You are given two integers $$$a$$$ and $$$b$$$. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by $$$1$$$; during the second operation you choose one of these numbers and increase it by $$$2$$$, and so on. You choose the number of these operations yourself.For example, if $$$a = 1$$$ and $$$b = 3$$$, you can perform the following sequence of three operations:   add $$$1$$$ to $$$a$$$, then $$$a = 2$$$ and $$$b = 3$$$;  add $$$2$$$ to $$$b$$$, then $$$a = 2$$$ and $$$b = 5$$$;  add $$$3$$$ to $$$a$$$, then $$$a = 5$$$ and $$$b = 5$$$. Calculate the minimum number of operations required to make $$$a$$$ and $$$b$$$ equal.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case print one integer — the minimum numbers of operations required to make $$$a$$$ and $$$b$$$ equal.

NoteFirst test case considered in the statement.In the second test case integers $$$a$$$ and $$$b$$$ are already equal, so you don't need to perform any operations.In the third test case you have to apply the first, the second, the third and the fourth operation to $$$b$$$ ($$$b$$$ turns into $$$20 + 1 + 2 + 3 + 4 = 30$$$).

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 T = readln.chomp.to!int;

    while (T--) {
        auto s = readln.split.map!(to!long);
        auto A = s[0];
        auto B = s[1];
        auto D = abs(A - B);
        long tmp = 0;
        for (long i = 0; ; ++i) {
            tmp += i;
            if (tmp >= D && tmp % 2 == D % 2) {
                i.writeln;
                break;
            }
        }
    }

}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto d = max(a, b) - min(a, b);
		long x, j;
		foreach (i; 1..10^^5)
		{
			if (x >= d && (x - d) % 2 == 0) break;
			x = cast(long)i * (i+1) / 2;
			j = i;
		}
		ans[ti] = j;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto d = max(a, b) - min(a, b);
		long x, j;
		foreach (i; 1..10^^5)
		{
			if (x >= d) break;
			x = i * (i+1) / 2;
			j = i;
		}
		if (x == d)
			ans[ti] = j;
		else
			ans[ti] = j+1;
	}

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