Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.

The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise. Consider the secretaries indexed from 1 to n in some way.

Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.

NoteIn the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.In the second test sample the described situation is impossible as conferences aren't allowed.

import std.stdio, std.conv, std.string;
void main()
{
    uint n;
    readf("%d\n", &n);
    uint[uint] sessions;
    uint session;
    uint pairs;
    string sessionString;
    sessionString = readln();
    foreach(i;0..n)
    {
        session = parse!uint(sessionString);
        munch(sessionString, " ");
        if (session == 0) continue;
        if (session !in sessions)
        {
            sessions[session] = 1;
        }
        else
        {
            ++sessions[session];
            ++pairs;
            if (sessions[session] > 2)
            {
                write(-1);
                return;
            }
        }
    }
    write(pairs);
}

import std.stdio;
import std.algorithm;

void main() {
	int n;
	readf(" %s", &n);
	int[] a;
	a.length = n;
	for (int i = 0; i < n; i++) {
		readf(" %s", &a[i]);
	}

	sort(a);
	int cnt = 0;
	int ans = 0;
	for (int i = 0; i < n; i++) {
		if (a[i] == 0)
			continue;
		if (i > 0 && a[i] == a[i - 1])
			++cnt;
		else
			cnt = 1;

		if (cnt > 2) {
			ans = -1;
			break;
		}
		if (cnt == 2)
			++ans;
	}
	writeln(ans);
}

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

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

    int[int] cnt;
    readln.chomp.split.each!(x => ++cnt[x.to!int]);

    debug { cnt.writeln; }

    cnt.remove(0);
    if (cnt.values.any!(x => x > 2)) {
        writeln(-1);
        return;
    }

    cnt.values.count!(x => x == 2).writeln;
}

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int [int] v;
		foreach (i; 0..n)
		{
			int id;
			readf (" %s", &id);
			if (id != 0)
			{
				v[id]++;
			}
		}
		int res = 0;
		foreach (u; v)
		{
			if (u > 2)
			{
				res = -1;
				break;
			}
			else if (u == 2)
			{
				res++;
			}
		}
		writeln (res);
	}
}

module sigod.codeforces.p291A;

import std.algorithm;
import std.stdio;

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

	int[] d = new int[n];
	foreach (i; 0 .. n) {
		stdin.readf(" %s", &d[i]);
	}

	stdout.writeln(solve(d));
}

//*

int solve(int[] d)
{
	d.sort();

	int start = -1;
	foreach (i, di; d) {
		if (di != 0) {
			start = i;
			break;
		}
	}

	if (start != -1) {
		d = d[start .. $];
	}
	else if (d[d.length - 1] == 0) {
		return 0;
	}

	int count = 0;

	foreach (tuple; d.group()) {
		if (tuple[1] == 2) {
			++count;
		}
		else if (tuple[1] > 2) {
			return -1;
		}
	}

	return count;
}

unittest {
	assert(solve([0, 1, 7, 1, 7, 10]) == 2);
	assert(solve([1, 1, 1]) == -1);
	assert(solve([0]) == 0);
}

import std.stdio, std.conv, std.string;
void main()
{
	uint n;
	readf("%d\n", &n);
	uint[uint] sessions;
	uint session;
	uint pairs;
	string sessionString;
	sessionString = readln();
	foreach(i;0..n)
	{
		session = parse!uint(sessionString);
		munch(sessionString, " ");
		if (session !in sessions)
		{
			sessions[session] = 1;
		}
		else
		{
			++sessions[session];
			++pairs;
			if (sessions[session] > 2)
			{
				write(-1);
				return;
			}
		}
	}
	write(pairs);
}

import std.stdio;
import std.algorithm;

void main() {
	int n;
	readf(" %s", &n);
	int[] a;
	a.length = n;
	for (int i = 0; i < n; i++) {
		readf(" %s", &a[i]);
	}

	sort(a);
	int cnt = 1;
	int ans = 0;
	for (int i = 1; i < n; i++) {
		if (a[i] == a[i - 1])
			++cnt;
		else
			cnt = 1;

		if (cnt > 2) {
			ans = -1;
			break;
		}
		if (cnt == 2)
			++ans;
	}
	writeln(ans);
}


Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.Suppose you are given a positive integer $$$a$$$. You want to choose some integer $$$b$$$ from $$$1$$$ to $$$a - 1$$$ inclusive in such a way that the greatest common divisor (GCD) of integers $$$a \oplus b$$$ and $$$a \> \& \> b$$$ is as large as possible. In other words, you'd like to compute the following function:$$$$$$f(a) = \max_{0 < b < a}{gcd(a \oplus b, a \> \& \> b)}.$$$$$$Here $$$\oplus$$$ denotes the bitwise XOR operation, and $$$\&$$$ denotes the bitwise AND operation.The greatest common divisor of two integers $$$x$$$ and $$$y$$$ is the largest integer $$$g$$$ such that both $$$x$$$ and $$$y$$$ are divided by $$$g$$$ without remainder.You are given $$$q$$$ integers $$$a_1, a_2, \ldots, a_q$$$. For each of these integers compute the largest possible value of the greatest common divisor (when $$$b$$$ is chosen optimally).

The first line contains an integer $$$q$$$ ($$$1 \le q \le 10^3$$$) — the number of integers you need to compute the answer for. After that $$$q$$$ integers are given, one per line: $$$a_1, a_2, \ldots, a_q$$$ ($$$2 \le a_i \le 2^{25} - 1$$$) — the integers you need to compute the answer for.

For each integer, print the answer in the same order as the integers are given in input.

NoteFor the first integer the optimal choice is $$$b = 1$$$, then $$$a \oplus b = 3$$$, $$$a \> \& \> b = 0$$$, and the greatest common divisor of $$$3$$$ and $$$0$$$ is $$$3$$$.For the second integer one optimal choice is $$$b = 2$$$, then $$$a \oplus b = 1$$$, $$$a \> \& \> b = 2$$$, and the greatest common divisor of $$$1$$$ and $$$2$$$ is $$$1$$$.For the third integer the optimal choice is $$$b = 2$$$, then $$$a \oplus b = 7$$$, $$$a \> \& \> b = 0$$$, and the greatest common divisor of $$$7$$$ and $$$0$$$ is $$$7$$$.

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

void main ()
{
	int tests;
	readf (" %s", &tests);
	foreach (test; 0..tests)
	{
		int n;
		readf (" %s", &n);
		long res = 1;
		if ((n & (n + 1)) == 0)
		{
			for (int i = 2; i * i <= n; i++)
			{
				if (n % i == 0)
				{
					res = n / i;
					break;
				}
			}
		}
		else
		{
			res = (1 << (bsr (n) + 1)) - 1;
		}
		writeln (res);
	}
}


This is an interactive problem.This is a hard version of the problem. The difference from the easy version is that in the hard version $$$1 \le t \le \min(n, 10^4)$$$ and the total number of queries is limited to $$$6 \cdot 10^4$$$.Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the $$$k$$$-th zero from the left $$$t$$$ times.Polycarp can make no more than $$$6 \cdot 10^4$$$ requests totally of the following type:   ? $$$l$$$ $$$r$$$ — find out the sum of all elements in positions from $$$l$$$ to $$$r$$$ ($$$1 \le l \le r \le n$$$) inclusive. To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the $$$k$$$-th zero was $$$x$$$, then after Polycarp guesses this position, the $$$x$$$-th element of the array will be replaced from $$$0$$$ to $$$1$$$.Help Polycarp win the game.

NoteIn the first test, the array $$$[1, 0, 1, 1, 0, 1]$$$ is hidden. After answering the query $$$k=2$$$, the array changed to $$$[1, 0, 1, 1, 1, 1]$$$.

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

string FMT_F = "%.10f";

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

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

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

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

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

struct SegTree(T)
{
	T delegate(const(T), const(T)) f;
	T[] data;
	T init;
    this(T[] _data, T delegate(const(T), const(T)) _f, T _init)
    {
		f = _f; init = _init;
		size_t n = 1; while (n < _data.length) n *= 2; data.length = n*2-1;
		foreach (i; 0.._data.length) data[i+n-1] = _data[i];
		foreach (i; _data.length..n) data[i+n-1] = _init;
		foreach_reverse (i; 0..n-1) data[i] = f(data[i*2+1], data[i*2+2]);
	}
    T query(size_t l, size_t r)
	{
        size_t n = (data.length+1) / 2; l += n-1; r += n-1; T res = init;
        while (l < r)
		{
            if ((l & 1) == 0) res = f(res, data[l]);
            if ((r & 1) == 0) res = f(res, data[r-1]);
            l = l/2; r = (r-1)/2;
        }
        return res;
    }
	void update(size_t i, T v)
	{
		i += (data.length+1) / 2 - 1; data[i] = v;
		while (i != 0) { i = (i-1)/2; data[i] = f(data[i*2+1], data[i*2+2]); }
    }
}

void main()
{
	auto n = RD!int;
	auto t = RD!int;
	auto data = new int[](n+1);
	auto pos = new SegTree!(int)(data, (in int a, in int b)=>a+b, 0);
	bool g(in long[] a, in long[] b)
	{
		auto ca = pos.query(0, cast(int)(a[1]+1));
		auto cb = pos.query(0, cast(int)(b[1]+1));
		return a[0]-ca < b[0]-cb;
	}
	auto rbt = new RedBlackTree!(long[], g, true);
	auto cnt = new long[](n+1);
	cnt[] = -1;
	foreach (ti; 0..t)
	{
		auto k = RD!int;

		bool f(int x)
		{
			auto c = pos.query(0, x+1);
			if (cnt[x] != -1)
			{
				return cnt[x]-c >= k;
			}
			writeln("? 1 ", x);
			stdout.flush;
			auto r = RD;
			auto zero = x - r;
			rbt.insert([zero+c, x]);
			cnt[x] = zero+c;
			return zero >= k;
		}

		auto ans = binarySearch!(f)(n+1, 0);
		pos.update(ans, 1);
		writeln("! ", ans);
		stdout.flush;
	}

	//stdout.flush;
	debug readln;
}


You are given a graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges in the graph, respectively. The next $$$m$$$ lines describe edges of the graph. The $$$i$$$-th edge is described with three integers $$$t_i$$$, $$$x_i$$$ and $$$y_i$$$ ($$$t_i \in [0; 1]$$$, $$$1 \le x_i, y_i \le n$$$) — the type of the edge ($$$t_i = 0$$$ if the edge is undirected and $$$t_i = 1$$$ if the edge is directed) and vertices this edge connects (the undirected edge connects vertices $$$x_i$$$ and $$$y_i$$$ and directed edge is going from the vertex $$$x_i$$$ to the vertex $$$y_i$$$). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair ($$$x_i, y_i$$$) there are no other pairs ($$$x_i, y_i$$$) or ($$$y_i, x_i$$$)). It is guaranteed that both sum $$$n$$$ and sum $$$m$$$ do not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$; $$$\sum m \le 2 \cdot 10^5$$$).

For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and $$$m$$$ lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any.

NoteExplanation of the second test case of the example:Explanation of the third test case of the example:

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto t = new int [m];
		auto u = new int [m];
		auto v = new int [m];
		auto adj = new int [] [n];
		foreach (j; 0..m)
		{
			readf !(" %s %s %s") (t[j], u[j], v[j]);
			u[j] -= 1;
			v[j] -= 1;
			if (t[j])
			{
				adj[v[j]] ~= u[j];
			}
		}

		auto used = new int [n];
		auto d = new int [n];
		int cur = 0;
		bool ok = true;

		void recur (int v)
		{
			if (used[v] > 0)
			{
				ok &= (used[v] == 2);
				return;
			}
			used[v] = 1;
			foreach (u; adj[v])
			{
				recur (u);
			}
			d[v] = cur;
			cur += 1;
			used[v] = 2;
		}

		foreach (i; 0..n)
		{
			if (!used[i])
			{
				recur (i);
			}
		}

		foreach (j; 0..m)
		{
			if (!t[j])
			{
				if (d[u[j]] > d[v[j]])
				{
					swap (u[j], v[j]);
				}
			}
		}

		if (ok)
		{
			writeln ("YES");
			foreach (j; 0..m)
			{
				writeln (u[j] + 1, " ", v[j] + 1);
			}
		}
		else
		{
			writeln ("NO");
		}
	}
}


A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k.For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t.

The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ 5) — the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≤ ai, bi ≤ n) — the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree.

Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t.

NoteIn the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself).  There are  pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5·2 + 10·1 = 20.In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3·1 = 3.

import core.bitop;
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;

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

		auto c = new int [] [] (n, k);
		auto d = new long [] [] (n, k);
		long res = 0;

		void recur (int v, int p)
		{
			c[v][0] = 1;
			c[v][1..$] = 0;
			d[v][0] = 0;
			d[v][1..$] = 0;
			foreach (u; a[v])
			{
				if (u == p)
				{
					continue;
				}
				recur (u, v);
				foreach (i; 0..k)
				{
					foreach (j; 0..k)
					{
						int carry = (i + j + 1 > 0) +
						    (i + j + 1 > k);
						res += d[v][i] * c[u][j];
						res += d[u][j] * c[v][i];
						res += carry * c[u][j] * 1L *
						    c[v][i];
					}
				}
				foreach (i; 0..k)
				{
					int j = i + 1;
					if (j == k)
					{
						j = 0;
					}
					c[v][j] += c[u][i];
					d[v][j] += d[u][i];
					if (j == 0)
					{
						d[v][j] += c[u][i];
					}
				}
			}
		}

		recur (0, -1);
		debug {writeln (c); writeln (d);}

		writeln (res);
	}
}

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

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

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

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

int N, K;
int[] A, B;

int[][] G;
long ans;

void solveCentroidDecomp() {
  auto sz = new int[N];
  auto del = new bool[N];
  void dfsSz(int u, int p) {
    sz[u] = 1;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (v != p) {
        dfsSz(v, u);
        sz[u] += sz[v];
      }
    }
  }
  dfsSz(0, -1);

  // r: centroid
  void solveSubtree(int r) {
    debug {
      string dfsDebug(int u, int p) {
        string ret = u.to!string;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v] && v != p) {
            ret ~= "(" ~ dfsDebug(v, u) ~ ")";
          }
        }
        return ret;
      }
      writeln("solveSubtree ", dfsDebug(r, -1));
    }

    int[] vs;
    foreach (i; G[r]) {
      const v = A[i] ^ B[i] ^ r;
      if (!del[v]) {
        vs ~= v;
      }
    }

    const len = cast(int)(vs.length);
    auto fs0 = new long[K];
    auto fs1 = new long[K];
    auto gs0 = new long[][](len, K);
    auto gs1 = new long[][](len, K);

    void dfs(int j, int u, int p, int d) {
      fs0[d % K] += 1;
      fs1[d % K] += d;
      gs0[j][d % K] += 1;
      gs1[j][d % K] += d;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs(j, v, u, d + 1);
        }
      }
    }
    fs0[0] += 1;
    fs1[0] += 0;
    foreach (j; 0 .. len) {
      dfs(j, vs[j], r, 1);
    }

    debug {
      writeln("fs0 = ", fs0);
      writeln("gs1 = ", fs1);
      writeln("fs0 = ", gs0);
      writeln("gs1 = ", gs1);
    }
    foreach (x; 0 .. K) foreach (y; 0 .. K) {
      const z = (K - (x + y) % K) % K;
      ans += fs1[x] * fs0[y];
      ans += fs0[x] * fs1[y];
      ans += fs0[x] * fs0[y] * z;
      foreach (j; 0 .. len) {
        ans -= gs1[j][x] * gs0[j][y];
        ans -= gs0[j][x] * gs1[j][y];
        ans -= gs0[j][x] * gs0[j][y] * z;
      }
    }
  }

  void solveRec(int u) {
    for (; ; ) {
      int vm = -1;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v]) {
          if (vm == -1 || sz[vm] < sz[v]) {
            vm = v;
          }
        }
      }
      if (vm == -1 || sz[u] >= 2 * sz[vm]) {
        solveSubtree(u);
        del[u] = true;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            solveRec(v);
          }
        }
        break;
      } else {
        sz[u] -= sz[vm];
        sz[vm] += sz[u];
        u = vm;
      }
    }
  }
  solveRec(0);
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }

      ans = 0;
      solveCentroidDecomp;
      ans /= K;
      ans /= 2;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array a with indices from [l, r) can be implemented as follows:  If the segment [l, r) is already sorted in non-descending order (that is, for any i such that l ≤ i < r - 1 a[i] ≤ a[i + 1]), then end the function call;  Let ;  Call mergesort(a, l, mid);  Call mergesort(a, mid, r);  Merge segments [l, mid) and [mid, r), making the segment [l, r) sorted in non-descending order. The merge algorithm doesn't call any other functions. The array in this problem is 0-indexed, so to sort the whole array, you need to call mergesort(a, 0, n).The number of calls of function mergesort is very important, so Ivan has decided to calculate it while sorting the array. For example, if a = {1, 2, 3, 4}, then there will be 1 call of mergesort — mergesort(0, 4), which will check that the array is sorted and then end. If a = {2, 1, 3}, then the number of calls is 3: first of all, you call mergesort(0, 3), which then sets mid = 1 and calls mergesort(0, 1) and mergesort(1, 3), which do not perform any recursive calls because segments (0, 1) and (1, 3) are sorted.Ivan has implemented the program that counts the number of mergesort calls, but now he needs to test it. To do this, he needs to find an array a such that a is a permutation of size n (that is, the number of elements in a is n, and every integer number from [1, n] can be found in this array), and the number of mergesort calls when sorting the array is exactly k.Help Ivan to find an array he wants!

The first line contains two numbers n and k (1 ≤ n ≤ 100000, 1 ≤ k ≤ 200000) — the size of a desired permutation and the number of mergesort calls required to sort it.

If a permutation of size n such that there will be exactly k calls of mergesort while sorting it doesn't exist, output  - 1. Otherwise output n integer numbers a[0], a[1], ..., a[n - 1] — the elements of a permutation that would meet the required conditions. If there are multiple answers, print any of them.

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

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

    if (k % 2 == 0) {
        writeln(-1);
        return;
    }

    auto nodes = new int[] (n+1);
    nodes[1] = 1;
    foreach (i; 2 .. n+1) {
        int lft = i/2;
        int rt = i - lft;
        nodes[i] = nodes[lft] + 1 + nodes[rt];
    }

    if (nodes[n] < k) {
        writeln(-1);
        return;
    }

    auto arr = (n+1).iota.dropOne.array;

    void go(int le, int r, int need) {
        if (le+1 == r) { return; }

        if (need == 0) { return; }

        int md = (le + r) / 2;

        swap(arr[md-1], arr[md]);
        need -= 2;

        int capLft = nodes[md - le] - 1;
        int needLft = min(need, capLft);
        go(le, md, needLft);
        go(md, r, need - needLft);
    }

    go(0, n, k-1);

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

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto k = next!int - 1;
  auto perm = new int[](n);
  void solve(int i, int j, int l)
  {
    debug writeln(i, " ", j, " ", l, " ", k);
    if (k == 0 || j - i == 1)
      {
	int v = l;
	foreach(k; i .. j)
	  {
	    perm[k] = v;
	    v++;
	  }
	return;
      }
    int mid = (i + j) / 2;
    auto ls = mid - i;
    auto rs = j - i - ls;
    k -= 2;
    solve(i, mid, l + rs);
    solve(mid, j, l);
  }
  solve(0, n, 1);
  if (k != 0) return (-1).writeln;
  perm.each!(p => p.write(" ")), writeln;
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

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

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

    if (k % 2 == 0) {
        writeln(-1);
        return;
    }

    auto szCap = new int[] (n+1);

    int getCap(int sz) {
        if (szCap[sz] != 0) { return szCap[sz]; }

        foreach (i; 1 .. 20) {
            int val = 1 << i;
            if (val > n) { break; }

            if (! (val & sz) ) { continue; }

            szCap[sz] += val * 2 - 1;
        }

        return szCap[sz];
    }

    if (getCap(n) < k) {
        writeln(-1);
        return;
    }

    auto arr = (n+1).iota.dropOne.array;

    void go(int le, int r, int need) {
        if (le+1 == r) { return; }

        if (need == 0) { return; }

        int md = (le + r) / 2;

        swap(arr[md-1], arr[md]);
        need -= 2;

        int capLft = getCap(md - le);
        int needLft = min(need, capLft);
        go(le, md, needLft);
        go(md, r, need - needLft);
    }

    go(0, n, k-1);

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

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

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

    if (k % 2 == 0) {
        writeln(-1);
        return;
    }

    auto nodes = new int[] (n+1);

    int getNodes(int sz) {
        if (nodes[sz] != 0) { return nodes[sz]; }

        foreach (i; 0 .. 20) {
            int val = 1 << i;
            if (val > n) { break; }

            if (! (val & sz) ) { continue; }

            nodes[sz] += val * 2 - 1;
        }

        return nodes[sz];
    }

    if (getNodes(n) < k) {
        writeln(-1);
        return;
    }

    auto arr = (n+1).iota.dropOne.array;

    void go(int le, int r, int need) {
        if (le+1 == r) { return; }

        if (need == 0) { return; }

        int md = (le + r) / 2;

        swap(arr[md-1], arr[md]);
        need -= 2;

        int capLft = getNodes(md - le) - 1;
        int needLft = min(need, capLft);
        go(le, md, needLft);
        go(md, r, need - needLft);
    }

    go(0, n, k-1);

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


Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)You have completed many programming projects. In fact, there are exactly $$$n$$$ types of programming projects, and you have completed $$$a_i$$$ projects of type $$$i$$$. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired:$$$$$$ f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). $$$$$$Here, $$$b_i$$$ denotes the number of projects of type $$$i$$$ you include in your résumé. Of course, you cannot include more projects than you have completed, so you require $$$0\le b_i \le a_i$$$ for all $$$i$$$.Your résumé only has enough room for $$$k$$$ projects, and you will absolutely not be hired if your résumé has empty space, so you require $$$\sum\limits_{i=1}^n b_i=k$$$.Find values for $$$b_1,\ldots, b_n$$$ that maximize the value of $$$f(b_1,\ldots,b_n)$$$ while satisfying the above two constraints.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1\le n\le 10^5$$$, $$$1\le k\le \sum\limits_{i=1}^n a_i$$$) — the number of types of programming projects and the résumé size, respectively. The next line contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$) — $$$a_i$$$ is equal to the number of completed projects of type $$$i$$$.

In a single line, output $$$n$$$ integers $$$b_1,\ldots, b_n$$$ that achieve the maximum value of $$$f(b_1,\ldots,b_n)$$$, while satisfying the requirements $$$0\le b_i\le a_i$$$ and $$$\sum\limits_{i=1}^n b_i=k$$$. If there are multiple solutions, output any. Note that you do not have to output the value $$$f(b_1,\ldots,b_n)$$$.

NoteFor the first test, the optimal answer is $$$f=-269$$$. Note that a larger $$$f$$$ value is possible if we ignored the constraint $$$\sum\limits_{i=1}^n b_i=k$$$.For the second test, the optimal answer is $$$f=9$$$.

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

immutable long infinity = 3 * 10L ^^ 18;

long fun (int a, int b) {
	return b * 3L * (b - 1) - a + 1;
}

int lastB (long border, int a) {
	int lo = 0;
	int hi = a;
	while (lo < hi) {
		int me = (lo + hi + 1) / 2;
		long cur = fun (a, me);
		if (cur > border)
			hi = me - 1;
		else
			lo = me;
	}
	return lo;
}

void main () {
	int n;
	long k;
	while (readf !(" %s %s") (n, k) > 0) {
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		long lo = -infinity;
		long hi = +infinity;
		while (lo < hi) {
			long me = lo + (hi - lo) / 2;
			long cur = 0;
			foreach (i; 0..n)
				cur += lastB (me, a[i]);
			if (cur >= k)
				hi = me;
			else
				lo = me + 1;
		}

		auto b = a.dup;
		foreach (i; 0..n) {
			b[i] = lastB (lo, a[i]);
			k -= b[i];
		}
		foreach (i; 0..n) {
			if (k < 0 && fun (a[i], b[i]) == lo) {
				k += 1;
				b[i] -= 1;
			}
		}
		writefln !("%(%s %)") (b);
	}
}

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

immutable long infinity = 3 * 10L ^^ 18;

long fun (int a, int b)
{
	return b * 3L * (b - 1) - a + 1;
}

int lastB (long border, int a)
{
	int lo = 0;
	int hi = a;
	while (lo < hi)
	{
		int me = (lo + hi + 1) / 2;
		long cur = fun (a, me);
		if (cur > border)
		{
			hi = me - 1;
		}
		else
		{
			lo = me;
		}
	}
	return lo;
}

void main ()
{
	int n;
	long k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		long total = a.sum (0L);
		long lo = -infinity;
		long hi = +infinity;
		while (lo < hi)
		{
			long me = lo + (hi - lo) / 2;
			long cur = 0;
			foreach (i; 0..n)
			{
				cur += lastB (me, a[i]);
			}
//			writeln (lo, " ", me, " ", hi, " ", cur);
			if (cur >= k)
			{
				hi = me;
			}
			else
			{
				lo = me + 1;
			}
		}

		auto b = a.dup;
		foreach (i; 0..n)
		{
			b[i] = lastB (lo, a[i]);
			k -= b[i];
		}
		foreach (i; 0..n)
		{
//			writeln (i, " ", k, " ", fun (a[i], b[i]), " ", lo);
			if (k < 0 && fun (a[i], b[i]) == lo)
			{
				k += 1;
				b[i] -= 1;
			}
		}
		writefln !("%(%s %)") (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)); }

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readLong();
      auto A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }

      long df(int i, long b) {
        return A[i] - 1 - 3 * b * (1 + b);
      }

      long calc(int i, long val) {
        // >= val, < val
        long lo = -1, hi = A[i];
        for (; lo + 1 < hi; ) {
          const mid = (lo + hi) / 2;
          ((df(i, mid) >= val) ? lo : hi) = mid;
        }
        return hi;
      }

      // >= K, < K
      long lo = -4 * 10L^^18, hi = 2 * 10L^^9;
      for (; lo + 1 < hi; ) {
        const mid = (lo + hi) / 2;
        long num;
        foreach (i; 0 .. N) {
          num += calc(i, mid);
        }
        ((num >= K) ? lo : hi) = mid;
      }
      debug {
        // writeln("lo = ", lo, ", hi = ", hi);
      }

      auto bs = new long[N];
      long now;
      foreach (i; 0 .. N) {
        now += bs[i] = calc(i, hi);
      }
      foreach (i; 0 .. N) {
        if (now < K && bs[i] < A[i] && df(i, bs[i]) == lo) {
          ++now;
          ++bs[i];
        }
      }
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(bs[i]);
      }
      writeln();

      debug {
        auto brt = new long[N];
        foreach (k; 0 .. K) {
          long mx = long.min;
          int im = -1;
          foreach (i; 0 .. N) {
            if (brt[i] < A[i]) {
              if (chmax(mx, df(i, brt[i]))) {
                im = i;
              }
            }
          }
          assert(im != -1);
          // writeln(im, " ", mx);
          ++brt[im];
        }
        writeln(brt);
        assert(brt == bs);
      }
    }
  } catch (EOFException e) {
  }
}

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

immutable long infinity = 4 * 10L ^^ 18;

long fun (int a, int b)
{
	return b * 3L * (b - 1) - a + 1;
}

int lastB (long border, int a)
{
	int lo = 0;
	int hi = a;
	while (lo < hi)
	{
		int me = (lo + hi + 1) / 2;
		long cur = fun (a, me);
		if (cur > border)
		{
			hi = me - 1;
		}
		else
		{
			lo = me;
		}
	}
	return lo;
}

void main ()
{
	int n;
	long k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		long total = a.sum (0L);
		long lo = 0;
		long hi = infinity;
		while (lo < hi)
		{
			long me = (lo + hi) / 2;
			long cur = 0;
			foreach (i; 0..n)
			{
				cur += lastB (me, a[i]);
			}
//			writeln (lo, " ", me, " ", hi, " ", cur);
			if (cur >= k)
			{
				hi = me;
			}
			else
			{
				lo = me + 1;
			}
		}

		auto b = a.dup;
		foreach (i; 0..n)
		{
			b[i] = lastB (lo, a[i]);
			k -= b[i];
		}
		foreach (i; 0..n)
		{
//			writeln (i, " ", k, " ", fun (a[i], b[i]), " ", lo);
			if (k < 0 && fun (a[i], b[i]) == lo)
			{
				k += 1;
				b[i] -= 1;
			}
		}
		writefln !("%(%s %)") (b);
	}
}


William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing $$$n$$$ cells, with each cell either being alive or dead.Evolution of the array in William's cellular automaton occurs iteratively in the following way:  If the element is dead and it has exactly $$$1$$$ alive neighbor in the current state of the array, then on the next iteration it will become alive. For an element at index $$$i$$$ the neighbors would be elements with indices $$$i - 1$$$ and $$$i + 1$$$. If there is no element at that index, it is considered to be a dead neighbor.  William is a humane person so all alive elements stay alive. Check the note section for examples of the evolution.You are given some initial state of all elements and you need to help William find the state of the array after $$$m$$$ iterations of evolution.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^3, 1 \le m \le 10^9$$$), which are the total number of cells in the array and the number of iterations. The second line of each test case contains a string of length $$$n$$$ made up of characters "0" and "1" and defines the initial state of the array. "1" means a cell is alive and "0" means it is dead. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

In each test case output a string of length $$$n$$$, made up of characters "0" and "1"  — the state of the array after $$$m$$$ iterations of evolution.

NoteSequence of iterations of evolution for the first test case   01000000001  — initial state  11100000011  — first iteration of evolution  11110000111  — second iteration of evolution  11111001111  — third iteration of evolution Sequence of iterations of evolution for the second test case   0110100101  — initial state  1110111101  — first iteration of evolution  1110111101  — second iteration of evolution

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

void main()
{
  int t, n, m;
  readf!" %d "(t);
  foreach (i ; 0 .. t) {
    readf!" %d %d"(n, m);
    readln;
    auto a = readln.chomp.split("").map!(to!int).array;
    for (int j = 0; j < a.length; j++) {
      if (a[j] == 1) {
        a[j] = 0;
      } else {
        a[j] = -1;
      }
    }
    int step = 0;
    bool progress = true;
    while (progress) {
      progress = false;
      for (int j = 0; j < a.length; j++) {
        if (a[j] != -1)
          continue;
        int left = -1;
        if (j - 1 >= 0)
          left = a[j - 1];
        int right = -1;
        if (j + 1 < a.length)
          right = a[j + 1];
        if (left == step && right != step) {
          a[j] = step + 1;
          progress = true;
        } else if (left != step && right == step) {
          a[j] = step + 1;
          progress = true;
        }
      }
      step++;
    }
    auto b = a.map!(x => (x >= 0 && x <= m) ? "1" : "0").joiner("");
    writeln(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)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		long x;
		long[] cnt;
		foreach (i; 0..n-1)
		{
			++x;
			if (s[i] != s[i+1])
			{
				cnt ~= x;
				x = 0;
			}
		}
		cnt ~= x+1;

		long p = s[0] == '0' ? 0 : 1;
		if (cnt.length != 1)
		{
			foreach (i; 0..cnt.length)
			{
				if (i % 2 != p) continue;

				if (i == 0)
				{
					cnt[i+1] += min(cnt[i], m);
					cnt[i] = max(cnt[i]-m, 0);
				}
				else if (i == cnt.length-1)
				{
					cnt[i-1] += min(cnt[i], m);
					cnt[i] = max(cnt[i]-m, 0);
				}
				else
				{
					cnt[i-1] += min(cnt[i]/2, m);
					cnt[i+1] += min(cnt[i]/2, m);
					cnt[i] = max(cnt[i]-m*2, cnt[i]%2);
				}
			}
		}

		foreach (i; 0..cnt.length)
		{
			foreach (e; 0..cnt[i])
				ans[ti] ~= cast(char)('0'+p);
			p ^= 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;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto s = '#' ~ readln.strip.dup ~ '#';
		m = min (m, n);
		foreach (step; 0..m)
		{
			auto t = s.dup;
			foreach (i; 1..n + 1)
			{
				if ((s[i - 1] == '1') ^ (s[i + 1] == '1'))
				{
					t[i] = '1';
				}
			}
			s = t;
		}
		writeln (s[1..$ - 1]);
	}
}


Consider a sequence of digits of length $$$2^k$$$ $$$[a_1, a_2, \ldots, a_{2^k}]$$$. We perform the following operation with it: replace pairs $$$(a_{2i+1}, a_{2i+2})$$$ with $$$(a_{2i+1} + a_{2i+2})\bmod 10$$$ for $$$0\le i<2^{k-1}$$$. For every $$$i$$$ where $$$a_{2i+1} + a_{2i+2}\ge 10$$$ we get a candy! As a result, we will get a sequence of length $$$2^{k-1}$$$.Less formally, we partition sequence of length $$$2^k$$$ into $$$2^{k-1}$$$ pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth $$$\ldots$$$, the last pair consists of the ($$$2^k-1$$$)-th and ($$$2^k$$$)-th numbers. For every pair such that sum of numbers in it is at least $$$10$$$, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by $$$10$$$ (and don't change the order of the numbers).Perform this operation with a resulting array until it becomes of length $$$1$$$. Let $$$f([a_1, a_2, \ldots, a_{2^k}])$$$ denote the number of candies we get in this process. For example: if the starting sequence is $$$[8, 7, 3, 1, 7, 0, 9, 4]$$$ then:After the first operation the sequence becomes $$$[(8 + 7)\bmod 10, (3 + 1)\bmod 10, (7 + 0)\bmod 10, (9 + 4)\bmod 10]$$$ $$$=$$$ $$$[5, 4, 7, 3]$$$, and we get $$$2$$$ candies as $$$8 + 7 \ge 10$$$ and $$$9 + 4 \ge 10$$$.After the second operation the sequence becomes $$$[(5 + 4)\bmod 10, (7 + 3)\bmod 10]$$$ $$$=$$$ $$$[9, 0]$$$, and we get one more candy as $$$7 + 3 \ge 10$$$. After the final operation sequence becomes $$$[(9 + 0) \bmod 10]$$$ $$$=$$$ $$$[9]$$$. Therefore, $$$f([8, 7, 3, 1, 7, 0, 9, 4]) = 3$$$ as we got $$$3$$$ candies in total.You are given a sequence of digits of length $$$n$$$ $$$s_1, s_2, \ldots s_n$$$. You have to answer $$$q$$$ queries of the form $$$(l_i, r_i)$$$, where for $$$i$$$-th query you have to output $$$f([s_{l_i}, s_{l_i+1}, \ldots, s_{r_i}])$$$. It is guaranteed that $$$r_i-l_i+1$$$ is of form $$$2^k$$$ for some nonnegative integer $$$k$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the sequence. The second line contains $$$n$$$ digits $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \le s_i \le 9$$$). The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — $$$i$$$-th query. It is guaranteed that $$$r_i-l_i+1$$$ is a nonnegative integer power of $$$2$$$.

Output $$$q$$$ lines, in $$$i$$$-th line output single integer — $$$f([s_{l_i}, s_{l_i + 1}, \ldots, s_{r_i}])$$$, answer to the $$$i$$$-th query.

NoteThe first example illustrates an example from the statement.$$$f([7, 3, 1, 7]) = 1$$$: sequence of operations is $$$[7, 3, 1, 7] \to [(7 + 3)\bmod 10, (1 + 7)\bmod 10]$$$ $$$=$$$ $$$[0, 8]$$$ and one candy as $$$7 + 3 \ge 10$$$ $$$\to$$$ $$$[(0 + 8) \bmod 10]$$$ $$$=$$$ $$$[8]$$$, so we get only $$$1$$$ candy.$$$f([9]) = 0$$$ as we don't perform operations with it.

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

void solve(){
	int n = read.to!int;

	int[] ss;
	foreach(i; 0 .. n) ss ~= read.to!int;

	S[int][] xs = new S[int][](n);

	for(int k = 1; k <= n; k *= 2){
		foreach(i; 0 .. n - k + 1){
			if(k > 1) xs[i][k] = getS(xs[i][k / 2], xs[i + k / 2][k / 2]);
			else xs[i][k] = S(ss[i], 0);
		}
	}

	int q = read.to!int;
	foreach(t; 0 .. q){

		int l = read.to!int - 1;
		int r = read.to!int - 1;

		xs[l][r - l + 1].value.writeln;
	}

}
struct S{
	int number;
	long value;
}
S getS(S a, S b){
	int number = (a.number + b.number) % 10;
	long value = a.value + b.value + ((a.number + b.number >= 10)? 1: 0);
	return S(number, value);
}


Andrew plays a game called "Civilization". Dima helps him.The game has n cities and m bidirectional roads. The cities are numbered from 1 to n. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities v1, v2, ..., vk, that there is a road between any contiguous cities vi and vi + 1 (1 ≤ i < k). The length of the described path equals to (k - 1). We assume that two cities lie in the same region if and only if, there is a path connecting these two cities.During the game events of two types take place:  Andrew asks Dima about the length of the longest path in the region where city x lies.  Andrew asks Dima to merge the region where city x lies with the region where city y lies. If the cities lie in the same region, then no merging is needed. Otherwise, you need to merge the regions as follows: choose a city from the first region, a city from the second region and connect them by a road so as to minimize the length of the longest path in the resulting region. If there are multiple ways to do so, you are allowed to choose any of them. Dima finds it hard to execute Andrew's queries, so he asks you to help him. Help Dima.

The first line contains three integers n, m, q (1 ≤ n ≤ 3·105; 0 ≤ m < n; 1 ≤ q ≤ 3·105) — the number of cities, the number of the roads we already have and the number of queries, correspondingly. Each of the following m lines contains two integers, ai and bi (ai ≠ bi; 1 ≤ ai, bi ≤ n). These numbers represent the road between cities ai and bi. There can be at most one road between two cities. Each of the following q lines contains one of the two events in the following format:   1 xi. It is the request Andrew gives to Dima to find the length of the maximum path in the region that contains city xi (1 ≤ xi ≤ n).  2 xi yi. It is the request Andrew gives to Dima to merge the region that contains city xi and the region that contains city yi (1 ≤ xi, yi ≤ n). Note, that xi can be equal to yi.

For each event of the first type print the answer on a separate line.

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;

immutable int NA = -1;

void main ()
{
	int n, m, q;
	while (readf (" %s %s %s", &n, &m, &q) > 0)
	{
		auto a = new int [] [n];

		foreach (i; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u] ~= v;
			a[v] ~= u;
		}

		auto b = new int [n];

		auto d = new int [n];
		auto p = new int [n];
		foreach (k; 0..n)
		{
			if (b[k] > 0)
			{
				continue;
			}

			Tuple !(int, int) recur (int v, int c, int r)
			{
				if (b[v] >= c)
				{
					return Tuple !(int, int) (0, 0);
				}
				b[v] = c;
				p[v] = k;

				auto res = Tuple !(int, int) (r, v);
				foreach (u; a[v])
				{
					res = max (res, recur (u, c, r + 1));
				}
				return res;
			}

			int diameter (int v)
			{
				auto p = recur (v, 1, 0);
				auto q = recur (p[1], 2, 0);
				return q[0];
			}

			d[k] = diameter (k);
			debug {writeln (k, ' ', d[k]);}
		}

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

		void unite (int x, int y)
		{
			x = root (x);
			y = root (y);
			if (x == y)
			{
				return;
			}
			d[x] = max (d[x], d[y],
			 ((d[x] + 1) >> 1) + ((d[y] + 1) >> 1) + 1);
			debug {writeln (x, ' ', y, ' ', d[x]);}
			p[y] = x;
		}

		foreach (j; 0..q)
		{
			int t;
			readf (" %s", &t);
			if (t == 1)
			{
				int x;
				readf (" %s", &x);
				x--;
				x = root (x);
				writeln (d[x]);
			}
			else if (t == 2)
			{
				int x, y;
				readf (" %s %s", &x, &y);
				x--;
				y--;
				unite (x, y);
			}
			else
			{
				assert (false);
			}
		}
	}
}

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;

immutable int NA = -1;

void main ()
{
	int n, m, q;
	while (readf (" %s %s %s", &n, &m, &q) > 0)
	{
		auto a = new int [] [n];

		foreach (i; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u] ~= v;
			a[v] ~= u;
		}

		auto b = new int [n];

		auto d = new int [n];
		auto p = new int [n];
		foreach (k; 0..n)
		{
			if (b[k] > 0)
			{
				continue;
			}

			Tuple !(int, int) recur (int v, int c, int r)
			{
				if (b[v] >= c)
				{
					return Tuple !(int, int) (0, 0);
				}
				b[v] = c;
				p[v] = k;

				auto res = Tuple !(int, int) (r, v);
				foreach (u; a[v])
				{
					res = max (res, recur (u, c, r + 1));
				}
				return res;
			}

			int diameter (int v)
			{
				auto p = recur (v, 1, 0);
				auto q = recur (p[1], 2, 0);
				return q[0];
			}

			d[k] = diameter (k);
			debug {writeln (k, ' ', d[k]);}
		}

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

		void unite (int x, int y)
		{
			x = root (x);
			y = root (y);
			if (x == y)
			{
				return;
			}
			int rx = (d[x] + 1) >> 1;
			int ry = (d[y] + 1) >> 1;
			int dx = rx + max (d[x] - rx, 1 + ry);
			int dy = ry + max (d[y] - ry, 1 + rx);
			d[x] = max (dx, dy);
			debug {writeln (x, ' ', y, ' ', d[x]);}
			p[y] = x;
		}

		foreach (j; 0..q)
		{
			int t;
			readf (" %s", &t);
			if (t == 1)
			{
				int x;
				readf (" %s", &x);
				x--;
				x = root (x);
				writeln (d[x]);
			}
			else if (t == 2)
			{
				int x, y;
				readf (" %s %s", &x, &y);
				x--;
				y--;
				unite (x, y);
			}
			else
			{
				assert (false);
			}
		}
	}
}

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;

immutable int NA = -1;

void main ()
{
	int n, m, q;
	while (readf (" %s %s %s", &n, &m, &q) > 0)
	{
		auto a = new int [] [n];

		foreach (i; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u] ~= v;
			a[v] ~= u;
		}

		auto b = new int [n];

		auto d = new int [n];
		auto p = new int [n];
		foreach (k; 0..n)
		{
			if (b[k] > 0)
			{
				continue;
			}

			Tuple !(int, int) recur (int v, int c, int r)
			{
				if (b[v] >= c)
				{
					return Tuple !(int, int) (0, 0);
				}
				b[v] = c;
				p[v] = k;

				auto res = Tuple !(int, int) (r, v);
				foreach (u; a[v])
				{
					res = max (res, recur (u, c, r + 1));
				}
				return res;
			}

			int diameter (int v)
			{
				auto p = recur (v, 1, 0);
				auto q = recur (p[1], 2, 0);
				return q[0];
			}

			d[k] = diameter (k);
			debug {writeln (k, ' ', d[k]);}
		}

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

		void unite (int x, int y)
		{
			x = root (x);
			y = root (y);
			if (x == y)
			{
				return;
			}
			int rx = (d[x] + 1) >> 1;
			int ry = (d[y] + 1) >> 1;
			int dx = rx + max (d[x] - rx, 1 + ry);
			int dy = ry + max (d[y] - ry, 1 + rx);
			d[x] = min (dx, dy);
			debug {writeln (x, ' ', y, ' ', d[x]);}
			p[y] = x;
		}

		foreach (j; 0..q)
		{
			int t;
			readf (" %s", &t);
			if (t == 1)
			{
				int x;
				readf (" %s", &x);
				x--;
				x = root (x);
				writeln (d[x]);
			}
			else if (t == 2)
			{
				int x, y;
				readf (" %s %s", &x, &y);
				x--;
				y--;
				unite (x, y);
			}
			else
			{
				assert (false);
			}
		}
	}
}


It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k ≥ 0, 0 < r ≤ 2k. Let's call that representation prairie partition of x.For example, the prairie partitions of 12, 17, 7 and 1 are:  12 = 1 + 2 + 4 + 5,17 = 1 + 2 + 4 + 8 + 2,7 = 1 + 2 + 4,1 = 1. Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of numbers given from Alice to Borys. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1012; a1 ≤ a2 ≤ ... ≤ an) — the numbers given from Alice to Borys.

Output, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input. If there are no such values of m, output a single integer -1.

NoteIn the first example, Alice could get the input sequence from [6, 20] as the original sequence.In the second example, Alice's original sequence could be either [4, 5] or [3, 3, 3].

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

/*
  1: 1-1
  1+2: 1-3
  1+2+4: 1-7
  1+2+4+8: 1-15
*/
enum E = 45;

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

      auto bs = new int[E];
      auto cs = new int[E];
      foreach (i; 0 .. N) {
        const e = bsr(A[i]);
        if (A[i] == 1L << e) {
          ++bs[e];
        } else {
          ++cs[e];
        }
      }
      debug {
        writeln("bs = ", bs);
        writeln("cs = ", cs);
      }

      int[] ans;
      auto ds = new int[E];
      for (int n = 1; ; ++n) {
        int l;
        for (l = 0; ; ++l) {
          if (bs[l] == 0) {
            break;
          }
          --bs[l];
        }
        if (l == 0) {
          break;
        }
        ++ds[l - 1];
        auto bcs = new int[E];
        bcs[] += bs[];
        bcs[] += cs[];
        int f = E;
        foreach_reverse (e; 0 .. E) {
          chmin(f, e);
          int d = ds[e];
          for (; ; ) {
            if (d == 0) {
              break;
            }
            for (; f >= 0 && bcs[f] == 0; --f) {}
            if (f < 0) {
              break;
            }
            const tmp = min(d, bcs[f]);
            d -= tmp;
            bcs[f] -= tmp;
          }
        }
        if (bcs.all!"a == 0") {
          ans ~= n;
        }
      }

      if (ans.empty) {
        writeln(-1);
      } else {
        foreach (index, n; ans) {
          if (index > 0) write(" ");
          write(n);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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

/*
  1: 1-1
  1+2: 1-3
  1+2+4: 1-7
  1+2+4+8: 1-15
*/
enum E = 45;

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

      auto bs = new int[E];
      auto cs = new int[E];
      foreach (i; 0 .. N) {
        const e = bsr(A[i]);
        if (A[i] == 1L << e) {
          ++bs[e];
        } else {
          ++cs[e];
        }
      }
      debug {
        writeln("bs = ", bs);
        writeln("cs = ", cs);
      }

      int[] ans;
      auto ds = new int[E];
      for (int n = 1; ; ++n) {
        int l;
        for (l = 0; ; ++l) {
          if (bs[l] == 0) {
            break;
          }
          --bs[l];
        }
        if (l == 0) {
          break;
        }
        ++ds[l];
        auto bcs = new int[E];
        bcs[] += bs[];
        bcs[] += cs[];
        int f = E;
        foreach_reverse (e; 0 .. E) {
          chmin(f, e);
          int d = ds[e];
          for (; ; ) {
            if (d == 0) {
              break;
            }
            for (; f >= 0 && bcs[f] == 0; --f) {}
            if (f < 0) {
              break;
            }
            --d;
            --bcs[f];
          }
        }
        if (bcs.all!"a == 0") {
          ans ~= n;
        }
      }

      if (ans.empty) {
        writeln(-1);
      } else {
        foreach (index, n; ans) {
          if (index > 0) write(" ");
          write(n);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}


This is an interactive problem.Jury initially had a sequence $$$a$$$ of length $$$n$$$, such that $$$a_i = i$$$.The jury chose three integers $$$i$$$, $$$j$$$, $$$k$$$, such that $$$1 \leq i < j < k \leq n$$$, $$$j - i > 1$$$. After that, Jury reversed subsegments $$$[i, j - 1]$$$ and $$$[j, k]$$$ of the sequence $$$a$$$.Reversing a subsegment $$$[l, r]$$$ of the sequence $$$a$$$ means reversing the order of elements $$$a_l, a_{l+1}, \ldots, a_r$$$ in the sequence, i. e. $$$a_l$$$ is swapped with $$$a_r$$$, $$$a_{l+1}$$$ is swapped with $$$a_{r-1}$$$, etc.You are given the number $$$n$$$ and you should find $$$i$$$, $$$j$$$, $$$k$$$ after asking some questions.In one question you can choose two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) and ask the number of inversions on the subsegment $$$[l, r]$$$ of the sequence $$$a$$$. You will be given the number of pairs $$$(i, j)$$$ such that $$$l \leq i < j \leq r$$$, and $$$a_i > a_j$$$.Find the chosen numbers $$$i$$$, $$$j$$$, $$$k$$$ after at most $$$40$$$ questions.The numbers $$$i$$$, $$$j$$$, and $$$k$$$ are fixed before the start of your program and do not depend on your queries.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Description of the test cases follows. The single line of each test case contains a single integer $$$n$$$ ($$$4 \leq n \leq 10^9$$$). After reading it you should start an interaction process by asking questions for that test case. After giving an answer you should:   Terminate your program if that is the last test case.  Proceed to the next test case otherwise.

immutable multi = true;

void solve(int tc)
{
	import std.functional;
	import core.stdc.stdlib;
	auto n = readInt!long;
	long[long] cache;
	long getInvs(long k)
	{
		if (k in cache) return cache[k];
		writeln("? ", 1, " ", k);
		stdout.flush;
		auto ans = readInt!long;
		if (ans == -1) exit(0);
		return cache[k] = ans;
	}
	long total = getInvs(n);
	long k = -1;
	long low = 1;
	long high = n;
	while (low <= high)
	{
		long mid = (low + high) / 2;
		if (getInvs(mid) == total)
		{
			k = mid;
			high = mid - 1;
		}
		else
		{
			low = mid + 1;
		}
	}
	assert (k != -1);
	long diffK = getInvs(k) - getInvs(k-1);
	long j = k - diffK;
	auto diffJ = getInvs(j-1) - getInvs(j-2);
	long i = j - 1 - diffJ;
	writeln("! ", i, " ", j, " ", k);
	stdout.flush;
}

//{{{
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;
import std.conv;
import std.range;
import std.stdio;
import std.string;

long ask (int lo, int hi)
{
	writeln ("? ", lo, " ", hi);
	stdout.flush ();
	return readln.strip.to !(long);
}

void solve (int n)
{
	auto total = ask (1, n);

	int lo = 1;
	int hi = n;
	while (lo < hi)
	{
		int me = (lo + hi) / 2;
		auto cur = ask (1, me);
		if (cur < total)
		{
			lo = me + 1;
		}
		else
		{
			hi = me;
		}
	}

	int k = hi;
	auto all1 = ask (1, k);
	auto cut1 = ask (1, k - 1);
	auto delta1 = cast (int) (all1 - cut1);

	int j = k - delta1;
	auto all2 = ask (1, j - 1);
	auto cut2 = ask (1, j - 2);
	auto delta2 = cast (int) (all2 - cut2);

	int i = j - 1 - delta2;
	writeln ("! ", i, " ", j, " ", k);
	stdout.flush ();
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		solve (n);
	}
}


Sereja loves integer sequences very much. He especially likes stairs.Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met: a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?

The first line contains integer m (1 ≤ m ≤ 105) — the number of Sereja's cards. The second line contains m integers bi (1 ≤ bi ≤ 5000) — the numbers on the Sereja's cards.

In the first line print the number of cards you can put on the table. In the second line print the resulting stairs.

#!/usr/bin/env rdmd
import std.stdio, std.string, std.conv;
import std.algorithm, std.array;

void main()
{
    for(string S; (S=readln().chomp()).length; )
    {
        int[] a = array(readln().split().map!(to!int)()).sort;
        int[] r = array(uniq(a));
        int[] l = array(uniq(setDifference(filterBidirectional!(x=>x!=r.back)(a),r)));
        reverse(r);
        int[] s = l~r;
        writeln(s.length);
        writeln(join(map!(to!string)(s)," "));
    }
}

#!/usr/bin/env rdmd
import std.stdio, std.string, std.conv;
import std.algorithm, std.array;

void main()
{
    for(string S; (S=readln().chomp()).length; )
    {
        int[] a = array(readln().split().map!(to!int)()).sort;
        int[] r = array(uniq(a));
        int[] l = array(setDifference(filterBidirectional!(x=>x!=r.back)(a),r));
        reverse(r);
        int[] s = l~r;
        writeln(s.length);
        writeln(join(map!(to!string)(s)," "));
    }
}


There are $$$n$$$ slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists). When a slime with a value $$$x$$$ eats a slime with a value $$$y$$$, the eaten slime disappears, and the value of the remaining slime changes to $$$x - y$$$.The slimes will eat each other until there is only one slime left. Find the maximum possible value of the last slime.

The first line of the input contains an integer $$$n$$$ ($$$1 \le n \le 500\,000$$$) denoting the number of slimes. The next line contains $$$n$$$ integers $$$a_i$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ is the value of $$$i$$$-th slime.

Print an only integer — the maximum possible value of the last slime.

NoteIn the first example, a possible way of getting the last slime with value $$$4$$$ is:  Second slime eats the third slime, the row now contains slimes $$$2, -1, 1$$$ Second slime eats the third slime, the row now contains slimes $$$2, -2$$$ First slime eats the second slime, the row now contains $$$4$$$ In the second example, the first slime can keep eating slimes to its right to end up with a value of $$$4$$$.

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

immutable long MOD = 10^^9 + 7;
immutable long INF = 1L << 59;

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

    if (N == 1) {
        writeln(A[0]);
        return;
    }

    long S = A.map!(a => abs(a)).sum;
    long ans = -INF;

    foreach (i; 0..N-1) {
        auto sub = abs(A[i] - A[i+1]);
        ans = max(ans, S - abs(A[i]) - abs(A[i+1]) + sub);
    }

    ans.writeln;
}

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

long saiki(int idx, int s, int n, int[] a, long[][] dp)
{
    if (dp[idx][s] != -1)
    {
        return dp[idx][s];
    }
    if (idx == n)
    {
        dp[idx][s] = (s == 3) ? 0 : long.min;
        return dp[idx][s];
    }
    auto ret0 = saiki(idx + 1, s | 1, n, a, dp);
    auto ret1 = saiki(idx + 1, s | 2, n, a, dp);
    auto res = long.min;
    if (ret0 != long.min) res = max(res, ret0 + a[idx]);
    if (ret1 != long.min) res = max(res, ret1 - a[idx]);
    dp[idx][s] = res;
    return res;
}

void solve(int[] a, int n)
{
    if (n == 1)
    {
        writeln(a[0]);
        return;
    }
    auto dp = new long[][](n + 1, 4);
    foreach (i; 0 .. n + 1)
    {
        fill(dp[i], -1);
    }
    auto res = saiki(0, 0, n, a, dp);
    writeln(res);
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            readf(" %d", &a[i]);
        }
        readln;
        solve(a, n);
    }
    return 0;
}

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

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

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

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

    auto s = arr.map!abs.sum(0L);

    debug { s.writeln; }

    int[] mnle;
    mnle ~= arr.front;
    foreach (e; arr.dropOne) mnle ~= min(mnle.back, e);
    int[] mnr;
    mnr ~= arr.back;
    foreach (e; arr.retro.dropOne) mnr ~= min(mnr.back, e);
    reverse(mnr);

    debug { mnle.writeln; mnr.writeln; }

    auto ans = arr.front.to!long - mnr[1] + (s - abs(arr.front) - abs(mnr[1]));
    ans = max(ans, arr.back.to!long - mnle[$-1] + (s - abs(arr.back) - abs(mnle[$-1])));

    foreach (i, e; arr.dropOne.dropBackOne.enumerate(1)) {
        auto cur = e.to!long - mnle[i-1] - mnr[i+1] + (s - abs(e) - abs(mnle[i-1]) - abs(mnr[i+1]));
        ans = max(ans, cur);
    }

    ans.writeln;
}

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

immutable long MOD = 10^^9 + 7;
immutable long INF = 1L << 59;

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

    if (N == 1) {
        writeln(A[0]);
        return;
    }

    auto S = A.sum;
    long ans = -INF;

    foreach (i; 0..N-1) {
        auto sub = abs(A[i] - A[i+1]);
        ans = max(ans, S - A[i] - A[i+1] + sub);
    }

    ans.writeln;
}

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

immutable long MOD = 10^^9 + 7;
immutable long INF = 1L << 59;

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

    auto dp = new long[][](N+1, 2);
    foreach (i; 0..N+1) dp[i][0] = -INF;
    foreach (i; 0..N+1) dp[i][1] =  INF;
    dp[1][0] = dp[1][1] = A[0];

    foreach (i; 1..N) {
        dp[i+1][0] = max(dp[i+1][0], dp[i][0] - A[i]);
        dp[i+1][0] = max(dp[i+1][0], A[i] - dp[i][0]);
        dp[i+1][0] = max(dp[i+1][0], dp[i][1] - A[i]);
        dp[i+1][0] = max(dp[i+1][0], A[i] - dp[i][1]);
        dp[i+1][1] = min(dp[i+1][1], dp[i][0] - A[i]);
        dp[i+1][1] = min(dp[i+1][1], A[i] - dp[i][0]);
        dp[i+1][1] = min(dp[i+1][1], dp[i][1] - A[i]);
        dp[i+1][1] = min(dp[i+1][1], A[i] - dp[i][1]);
    }

    dp[N][0].writeln;
}


You are given two strings $$$s$$$ and $$$t$$$ both of length $$$n$$$ and both consisting of lowercase Latin letters.In one move, you can choose any length $$$len$$$ from $$$1$$$ to $$$n$$$ and perform the following operation:   Choose any contiguous substring of the string $$$s$$$ of length $$$len$$$ and reverse it;  at the same time choose any contiguous substring of the string $$$t$$$ of length $$$len$$$ and reverse it as well. Note that during one move you reverse exactly one substring of the string $$$s$$$ and exactly one substring of the string $$$t$$$.Also note that borders of substrings you reverse in $$$s$$$ and in $$$t$$$ can be different, the only restriction is that you reverse the substrings of equal length. For example, if $$$len=3$$$ and $$$n=5$$$, you can reverse $$$s[1 \dots 3]$$$ and $$$t[3 \dots 5]$$$, $$$s[2 \dots 4]$$$ and $$$t[2 \dots 4]$$$, but not $$$s[1 \dots 3]$$$ and $$$t[1 \dots 2]$$$.Your task is to say if it is possible to make strings $$$s$$$ and $$$t$$$ equal after some (possibly, empty) sequence of moves.You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$ and $$$t$$$. The second line of the test case contains one string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of the test case contains one string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer on it — "YES" (without quotes) if it is possible to make strings $$$s$$$ and $$$t$$$ equal after some (possibly, empty) sequence of moves and "NO" otherwise.

4
4
abcd
abdc
5
ababa
baaba
4
asdf
asdg
4
abcd
badc

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;

immutable long MOD = 998244353;

void main() {
    auto t = readln.chomp.to!int;
    auto cnt = new long[](26);

    long count(const dchar[] S) {
        cnt[] = 0;
        long ans = 0;
        foreach_reverse (i; 0..S.length) {
            foreach (j; 0..S[i]-'a') ans += cnt[j];
            cnt[S[i]-'a'] += 1;
        }
        return ans;
    }

    while (t--) {
        auto N = readln.chomp.to!int;
        auto S = readln.chomp.to!(dchar[]);
        auto T = readln.chomp.to!(dchar[]);
        auto A = S.dup.sort().array;
        auto B = T.dup.sort().array;

        if (A != B) {
            writeln("NO");
            continue;
        }

        cnt[] = 0;
        foreach (s; S) cnt[s- 'a'] += 1;

        if (cnt.map!(a => a > 1).any) {
            writeln("YES");
            continue;
        }

        if ((count(S) + count(T)) % 2 == 0) {
            writeln("YES");
        } else {
            writeln("NO");
        }
    }
}


The Fair Nut found a string $$$s$$$. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences $$$p_1, p_2, \ldots, p_k$$$, such that:   For each $$$i$$$ ($$$1 \leq i \leq k$$$), $$$s_{p_i} =$$$ 'a'.  For each $$$i$$$ ($$$1 \leq i < k$$$), there is such $$$j$$$ that $$$p_i < j < p_{i + 1}$$$ and $$$s_j =$$$ 'b'. The Nut is upset because he doesn't know how to find the number. Help him.This number should be calculated modulo $$$10^9 + 7$$$.

The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 10^5$$$) consisting of lowercase Latin letters.

In a single line print the answer to the problem — the number of such sequences $$$p_1, p_2, \ldots, p_k$$$ modulo $$$10^9 + 7$$$.

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

int solve(string s)
{
    static int mod = 1000000007;
    auto n = to!int(s.length);
    auto dp = new int[n];
    auto next = new int[][](n, 2);
    next[n - 1][0] = next[n - 1][1] = n;
    if (s[n - 1] == 'a') dp[n - 1] = 1;
    foreach_reverse (i; 0 .. n - 1)
    {
        foreach (j; 0 .. 2) next[i][j] = next[i + 1][j];
        if (s[i + 1] == 'a') next[i][0] = i + 1;
        else if (s[i + 1] == 'b') next[i][1] = i + 1;
        if (s[i] == 'a')
        {
            dp[i] = 1;
            auto idx = next[i][1];
            if (idx < n)
            {
                idx = next[idx][0];
                if (idx < n) dp[i] = (dp[i] + dp[idx]) % mod;
            }
            idx = next[i][0];
            if (idx < n) dp[i] = (dp[i] + dp[idx]) % mod;
        }
    }
    if (s[0] == 'a') return dp[0];
    auto idx = next[0][0];
    if (idx < n) return dp[idx];
    return 0;
}

int main(string[] args)
{
    auto s = readln.strip;
    auto ret = solve(s);
    writeln(ret);
    return 0;
}

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

void main()
{
    immutable int MD = 10 ^^ 9 + 7;

    auto s = readln.chomp;

    s ~= 'b';
    int ans = 0;
    int cur = 0;
    foreach (c; s) {
        if (c == 'a') ++cur;
        else if (c == 'b') {
            auto toadd = (cast(long)cur * ans % MD + cur) % MD;
            ans = (ans + toadd) % MD;
            cur = 0;
        }
    }

    ans.writeln;
}

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

void main()
{
    immutable int MD = 10 ^^ 9 + 7;

    auto s = readln.chomp;

    s ~= 'b';
    int ans = 0;
    int cur = 0;
    foreach (c; s) {
        if (c == 'a') ++cur;
        else if (c == 'b') {
            auto toadd = (cur * ans % MD + cur) % MD;
            ans = (ans + toadd) % MD;
            cur = 0;
        }
    }

    ans.writeln;
}


Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.

In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server b in the similar format.

NoteConsider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.

import std.stdio;

int main() {
    debug stdin = File("in.txt", "r");

    int[2][3] table;
    int n;
    readf(" %s\n", &n);
    foreach(i; 0 .. n) {
        int a, b, c;
        readf(" %s %s %s\n", &a, &b, &c);
        table[a][0] += b;
        table[a][1] += c;
    }
    if (table[1][0] >= table[1][1]) writeln("LIVE");
    else writeln("DEAD");
    if (table[2][0] >= table[2][1]) writeln("LIVE");
    else writeln("DEAD");

    return 0;
}

module cf_245A;

import std.stdio;

void main() {
    int n, t, x, y;
    int lostPCA = 0, acceptPCA = 0;
    int lostPCB = 0, acceptPCB = 0;

    readf("%d", &n);
    for (int i = 0; i < n; ++i) {
        readf(" %d %d %d", &t, &x, &y);

        if (t == 1) {
            acceptPCA += x;
            lostPCA += y;
        } else {
            acceptPCB += x;
            lostPCB += y;
        }
    }

    lostPCA += acceptPCA;
    lostPCB += acceptPCB;

    writeln((acceptPCA >= lostPCA / 2)? "LIVE": "DEAD");
    writeln((acceptPCB >= lostPCB / 2)? "LIVE": "DEAD");
}

import std.stdio;
int main()
{
	int n=0;
	readf(" %d", &n);
	int l1=0;
	int l2=0;
	int d1=0;
	int d2=0;
	for (int i=0; i<n; i++)
	{
		int a=0;
		int b=0;
		int c=0;
		readf(" %d", &a);
		readf(" %d", &b);
		readf(" %d", &c);
		if (a==1)
		{
			l1=l1+b;
			d1=d1+c;
		}
		else
		{
			l2=l2+b;
			d2=d2+c;
		}
	}
	if (l1>=d1)
	{
		writeln("LIVE");
	}
	else
	{
		writeln("DEAD");
	}
	if (l2>=d2)
	{
		writeln("LIVE");
	}
	else
	{
		writeln("DEAD");
	}
	return 0;
}