You are given a directed graph of $$$n$$$ vertices and $$$m$$$ edges. Vertices are numbered from $$$1$$$ to $$$n$$$. There is a token in vertex $$$1$$$.The following actions are allowed:   Token movement. To move the token from vertex $$$u$$$ to vertex $$$v$$$ if there is an edge $$$u \to v$$$ in the graph. This action takes $$$1$$$ second.  Graph transposition. To transpose all the edges in the graph: replace each edge $$$u \to v$$$ by an edge $$$v \to u$$$. This action takes increasingly more time: $$$k$$$-th transposition takes $$$2^{k-1}$$$ seconds, i.e. the first transposition takes $$$1$$$ second, the second one takes $$$2$$$ seconds, the third one takes $$$4$$$ seconds, and so on. The goal is to move the token from vertex $$$1$$$ to vertex $$$n$$$ in the shortest possible time. Print this time modulo $$$998\,244\,353$$$.

The first line of input contains two integers $$$n, m$$$ ($$$1 \le n, m \le 200\,000$$$). The next $$$m$$$ lines contain two integers each: $$$u, v$$$ ($$$1 \le u, v \le n; u \ne v$$$), which represent the edges of the graph. It is guaranteed that all ordered pairs $$$(u, v)$$$ are distinct. It is guaranteed that it is possible to move the token from vertex $$$1$$$ to vertex $$$n$$$ using the actions above.

Print one integer: the minimum required time modulo $$$998\,244\,353$$$.

NoteThe first example can be solved by transposing the graph and moving the token to vertex $$$4$$$, taking $$$2$$$ seconds.The best way to solve the second example is the following: transpose the graph, move the token to vertex $$$2$$$, transpose the graph again, move the token to vertex $$$3$$$, transpose the graph once more and move the token to vertex $$$4$$$.

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

immutable int mod = 998_244_353;
immutable int logLimit = 20;
immutable int limit = 1 << logLimit;

struct Dist
{
	int p;
	int q;

	int opCmp () (const auto ref Dist that) const
	{
		if (this.p == that.p)
		{
			return this.q - that.q;
		}
		if (this.p > logLimit || that.p > logLimit)
		{
			return this.p - that.p;
		}
		auto thisR = (1 << this.p) + this.q;
		auto thatR = (1 << that.p) + that.q;
		return thisR - thatR;
	}
}

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		auto adj = new int [] [2] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u][0] ~= v;
			adj[v][1] ~= u;
		}

		auto d = new Dist [2] [n];
		foreach (ref line; d)
		{
			line[] = Dist (mod, mod);
		}
		d[0][0] = Dist (0, 0);
		auto q = new int [2] [limit];
		int [2] qb;
		int [2] qe;

		void enQueue (int v, bool b)
		{
			q[qe[b]][b] = v;
			qe[b] = (qe[b] + 1) & (limit - 1);
		}

		int deQueue (int b)
		{
			auto res = q[qb[b]][b];
			qb[b] = (qb[b] + 1) & (limit - 1);
			return res;
		}

		bool b = 0;
		enQueue (0, b);
		foreach (k; 0..n)
		{
			while (qb[b] != qe[b])
			{
				auto v = deQueue (b);
				auto cur = d[v][b];

				cur.p += 1;
				if (d[v][!b] > cur)
				{
					d[v][!b] = cur;
					enQueue (v, !b);
				}
				cur.p -= 1;

				cur.q += 1;
				foreach (u; adj[v][b])
				{
					if (d[u][b] > cur)
					{
						d[u][b] = cur;
						enQueue (u, b);
					}
				}
				cur.q -= 1;
			}
			b = !b;
		}

		auto res = min (d[n - 1][0], d[n - 1][1]);
		int answer = 1;
		foreach (i; 0..res.p)
		{
			answer = (answer * 2) % mod;
		}
		answer = (answer + mod - 1) % mod;
		answer = (answer + res.q) % mod;
		writeln (answer);
	}
}


As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest.The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are n problems for the contest. The penalty time for each solved problem is set as the distance from the moment of solution submission to the New Year in minutes. For example, the problem submitted at 21:00 (9.00 P.M.) gets penalty time 180, as well as the problem submitted at 3:00 (3.00 A.M.). The total penalty time is calculated as the sum of penalty time for all solved problems. It is allowed to submit a problem exactly at the end of the contest, at 6:00 (6.00 A.M.).Gennady opened the problems exactly at 18:00 (6.00 P.M.) and managed to estimate their complexity during the first 10 minutes of the contest. He believes that writing a solution for the i-th problem will take ai minutes. Gennady can submit a solution for evaluation at any time after he completes writing it. Probably he will have to distract from writing some solution to send the solutions of other problems for evaluation. The time needed to send the solutions can be neglected, i.e. this time can be considered to equal zero. Gennady can simultaneously submit multiple solutions. Besides, he can move at any time from writing one problem to another, and then return to the first problem from the very same place, where he has left it. Thus the total solution writing time of the i-th problem always equals ai minutes. Of course, Gennady does not commit wrong attempts, and his solutions are always correct and are accepted from the first attempt. He can begin to write the solutions starting from 18:10 (6.10 P.M.).Help Gennady choose from the strategies that help him solve the maximum possible number of problems, the one with which his total penalty time will be minimum.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of the problems. The next line contains n space-separated integers ai (1 ≤ ai ≤ 720) — each number shows how much time in minutes Gennady will spend writing a solution to the problem.

Print two integers — the number of problems Gennady will solve and the total penalty time considering that he chooses the optimal strategy.

NoteIn the sample, one of Gennady's possible optimal strategies is as follows. At 18:10 (6:10 PM) he begins to write the first problem and solves it in 30 minutes (18:40 or 6.40 P.M.). At 18:40 (6.40 P.M.) he begins to write the second problem. There are 320 minutes left before the New Year, so Gennady does not have the time to finish writing the second problem before the New Year. At 0:00 (12.00 A.M.) he distracts from the second problem, submits the first one, and returns immediately to writing the second problem. At 0:10 (0.10 A.M.), he completes the solution for the second problem, submits it and gets 10 minute penalty time. Note that as the total duration of the contest is 720 minutes and Gennady has already spent 10 minutes on reading the problems, he will not have time to solve the third problem during the contest. Yes, such problems happen to exist.Competitions by the given rules are held annually on the site http://b23.ru/3wvc

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

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

    arr.sort();

    int pretime = 6 * 60 - 10, aftertime = 6 * 60;
    int tottime = pretime + aftertime;
    int sm = arr.sum;
    while (sm > tottime) {
        sm -= arr.back;
        arr.popBack();
    }

    debug { arr.writeln; }

    int ans = 0;
    int csum = 0;
    foreach (e; arr) {
        csum += e;
        if (csum > pretime) { ans += csum - pretime; }
    }

    writeln(arr.length, ' ', ans);
}


Given an integer sequence $$$a_1, a_2, \dots, a_n$$$ of length $$$n$$$, your task is to compute the number, modulo $$$998244353$$$, of ways to partition it into several non-empty continuous subsequences such that the sums of elements in the subsequences form a balanced sequence.A sequence $$$s_1, s_2, \dots, s_k$$$ of length $$$k$$$ is said to be balanced, if $$$s_{i} = s_{k-i+1}$$$ for every $$$1 \leq i \leq k$$$. For example, $$$[1, 2, 3, 2, 1]$$$ and $$$[1,3,3,1]$$$ are balanced, but $$$[1,5,15]$$$ is not. Formally, every partition can be described by a sequence of indexes $$$i_1, i_2, \dots, i_k$$$ of length $$$k$$$ with $$$1 = i_1 < i_2 < \dots < i_k \leq n$$$ such that   $$$k$$$ is the number of non-empty continuous subsequences in the partition;  For every $$$1 \leq j \leq k$$$, the $$$j$$$-th continuous subsequence starts with $$$a_{i_j}$$$, and ends exactly before $$$a_{i_{j+1}}$$$, where $$$i_{k+1} = n + 1$$$. That is, the $$$j$$$-th subsequence is $$$a_{i_j}, a_{i_j+1}, \dots, a_{i_{j+1}-1}$$$.  There are $$$2^{n-1}$$$ different partitions in total. Let $$$s_1, s_2, \dots, s_k$$$ denote the sums of elements in the subsequences with respect to the partition $$$i_1, i_2, \dots, i_k$$$. Formally, for every $$$1 \leq j \leq k$$$, $$$$$$ s_j = \sum_{i=i_{j}}^{i_{j+1}-1} a_i = a_{i_j} + a_{i_j+1} + \dots + a_{i_{j+1}-1}. $$$$$$ For example, the partition $$$[1\,|\,2,3\,|\,4,5,6]$$$ of sequence $$$[1,2,3,4,5,6]$$$ is described by the sequence $$$[1,2,4]$$$ of indexes, and the sums of elements in the subsequences with respect to the partition is $$$[1,5,15]$$$.Two partitions $$$i_1, i_2, \dots, i_k$$$ and $$$i'_1, i'_2, \dots, i'_{k'}$$$ (described by sequences of indexes) are considered to be different, if at least one of the following holds.   $$$k \neq k'$$$,  $$$i_j \neq i'_j$$$ for some $$$1 \leq j \leq \min\left\{ k, k' \right\}$$$.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$), indicating the length of the sequence $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$), indicating the elements of the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output the number of partitions with respect to which the sum of elements in each subsequence is balanced, modulo $$$998244353$$$.

NoteFor the first test case, there is only one way to partition a sequence of length $$$1$$$, which is itself and is, of course, balanced. For the second test case, there are $$$2$$$ ways to partition it:   The sequence $$$[1, 1]$$$ itself, then $$$s = [2]$$$ is balanced;  Partition into two subsequences $$$[1\,|\,1]$$$, then $$$s = [1, 1]$$$ is balanced. For the third test case, there are $$$3$$$ ways to partition it:   The sequence $$$[0, 0, 1, 0]$$$ itself, then $$$s = [1]$$$ is balanced;  $$$[0 \,|\, 0, 1 \,|\, 0]$$$, then $$$s = [0, 1, 0]$$$ is balanced;  $$$[0, 0 \,|\, 1 \,|\, 0]$$$, then $$$s = [0, 1, 0]$$$ is balanced. For the fourth test case, there are $$$4$$$ ways to partition it:   The sequence $$$[1, 2, 3, 2, 1]$$$ itself, then $$$s = [9]$$$ is balanced;  $$$[1, 2 \,|\, 3 \,|\, 2, 1]$$$, then $$$s = [3, 3, 3]$$$ is balanced;  $$$[1 \,|\, 2, 3, 2 \,|\, 1]$$$, then $$$s = [1, 7, 1]$$$ is balanced;  $$$[1 \,|\, 2 \,|\, 3 \,|\, 2 \,|\, 1]$$$, then $$$s = [1, 2, 3, 2, 1]$$$ is balanced. For the fifth test case, there are $$$2$$$ ways to partition it:   The sequence $$$[1, 3, 5, 7, 9]$$$ itself, then $$$s = [25]$$$ is balanced;  $$$[1, 3, 5 \,|\, 7 \,|\, 9]$$$, then $$$s = [9, 7, 9]$$$ is balanced. For the sixth test case, every possible partition should be counted. So the answer is $$$2^{32-1} \equiv 150994942 \pmod {998244353}$$$.

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

struct ModInt(uint M_) {
  import std.conv : to;
  alias M = M_;
  uint x;
  this(ModInt a) { x = a.x; }
  this(uint x_) { x = x_ % M; }
  this(ulong x_) { x = cast(uint)(x_ % M); }
  this(int x_) { x = ((x_ %= cast(int)(M)) < 0) ? (x_ + cast(int)(M)) : x_; }
  this(long x_) { x = cast(uint)(((x_ %= cast(long)(M)) < 0) ? (x_ + cast(long)(M)) : x_); }
  ref ModInt opAssign(T)(inout(T) a) if (is(T == uint) || is(T == ulong) || is(T == int) || is(T == long)) { return this = ModInt(a); }
  ref ModInt opOpAssign(string op, T)(T a) {
    static if (is(T == ModInt)) {
      static if (op == "+") { x = ((x += a.x) >= M) ? (x - M) : x; }
      else static if (op == "-") { x = ((x -= a.x) >= M) ? (x + M) : x; }
      else static if (op == "*") { x = cast(uint)((cast(ulong)(x) * a.x) % M); }
      else static if (op == "/") { this *= a.inv(); }
      else static assert(false);
      return this;
    } else static if (op == "^^") {
      if (a < 0) return this = inv()^^(-a);
      ModInt b = this, c = 1U;
      for (long e = a; e; e >>= 1) { if (e & 1) c *= b; b *= b; }
      return this = c;
    } else {
      return mixin("this " ~ op ~ "= ModInt(a)");
    }
  }
  ModInt inv() const {
    uint a = M, b = x; int y = 0, z = 1;
    for (; b; ) { const q = a / b; const c = a - q * b; a = b; b = c; const w = y - cast(int)(q) * z; y = z; z = w; }
    assert(a == 1); return ModInt(y);
  }
  ModInt opUnary(string op)() const {
    static if (op == "+") { return this; }
    else static if (op == "-") { ModInt a; a.x = x ? (M - x) : 0U; return a; }
    else static assert(false);
  }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op, T)(T a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  bool opCast(T: bool)() const { return (x != 0U); }
  string toString() const { return x.to!string; }
}

enum MO = 998244353;
alias Mint = ModInt!MO;

enum LIM_INV = 2 * 10^^5 + 10;
Mint[] inv, fac, invFac;
void prepare() {
  inv = new Mint[LIM_INV];
  fac = new Mint[LIM_INV];
  invFac = new Mint[LIM_INV];
  inv[1] = 1;
  foreach (i; 2 .. LIM_INV) {
    inv[i] = -((Mint.M / i) * inv[cast(size_t)(Mint.M % i)]);
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM_INV) {
    fac[i] = fac[i - 1] * i;
    invFac[i] = invFac[i - 1] * inv[i];
  }
}
Mint binom(long n, long k) {
  if (n < 0) {
    if (k >= 0) {
      return (-1)^^(k & 1) * binom(-n + k - 1, k);
    } else if (n - k >= 0) {
      return (-1)^^((n - k) & 1) * binom(-k - 1, n - k);
    } else {
      return Mint(0);
    }
  } else {
    if (0 <= k && k <= n) {
      assert(n < LIM_INV);
      return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] * invFac[cast(size_t)(n - k)];
    } else {
      return Mint(0);
    }
  }
}

void main() {
  prepare;

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

        auto ASum = new long[N + 1];
        foreach (i; 0 .. N) {
          ASum[i + 1] = ASum[i] + A[i];
        }
        debug {
          writeln("ASum = ", ASum);
        }

        Mint ans = 1;
        for (int i = 1, j = N - 1; i <= j; ) {
          const val = min(ASum[i], ASum[N] - ASum[j]);
          int cntI, cntJ;
          for (; i <= j && ASum[i] == val; ++i) ++cntI;
          for (; i <= j && ASum[N] - ASum[j] == val; --j) ++cntJ;
          debug {
            writeln(val, " ", cntI, " ", cntJ);
          }
          if (val == ASum[N] - val) {
            ans *= Mint(2)^^(cntI + cntJ);
          } else {
            Mint sum;
            foreach (k; 0 .. min(cntI, cntJ) + 1) {
              sum += binom(cntI, k) * binom(cntJ, k);
            }
            ans *= sum;
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

immutable int mod   = 998_244_353;
immutable int limit =     100_005;

int [] f;
int [] fi;

int powMod (int a, int p)
{
	int res = 1;
	for ( ; p > 0; p >>= 1)
	{
		if (p & 1)
		{
			res = (res * 1L * a) % mod;
		}
		a = (a * 1L * a) % mod;
	}
	return res;
}

int invMod (int a)
{
	return powMod (a, mod - 2);
}

void prepare (int limit)
{
	f = [1];
	foreach (i; 1..limit)
	{
		f ~= (f.back * 1L * i) % mod;
	}
	fi = f.map !(invMod).array;
}

long choose (int n, int k)
{
	if (!(0 <= k && k <= n))
	{
		return 0;
	}
	long res = f[n];
	res = (res * 1L * invMod (f[n - k])) % mod;
	res = (res * 1L * invMod (f[k])) % mod;
	return res;
}

void main ()
{
	prepare (limit);

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

		int lo = 0;
		int hi = n;
		long x = 0;
		long y = 0;
		long res = 1;
		while (lo < hi)
		{
			while (x < y && lo < hi)
			{
				x += a[lo];
				lo += 1;
			}
			while (y < x && lo < hi)
			{
				hi -= 1;
				y += a[hi];
			}
			if (x == y)
			{
				int lo2 = lo;
				int hi2 = hi;
				while (lo2 < hi2 && a[lo2] == 0)
				{
					lo2 += 1;
				}
				while (lo2 < hi2 && a[hi2 - 1] == 0)
				{
					hi2 -= 1;
				}
				bool inner = (hi - lo < n);
				long cur = 1;
				if (lo2 == hi2)
				{
					int len = lo2 - lo;
					len = len + inner - !inner;
					for (int i = 1; i <= len; i += 1)
					{
						long temp =
						    choose (len, i);
						cur = (cur + temp) % mod;
					}
				}
				else
				{
					int lenLo = lo2 - lo + inner;
					int lenHi = hi - hi2 + inner;
					for (int i = 1; i <= lenLo &&
					    i <= lenHi; i++)
					{
						long temp =
						    choose (lenLo, i);
						temp *=
						    choose (lenHi, i);
						cur = (cur + temp) % mod;
					}
				}
				res = (res * 1L * cur) % mod;
				if (lo2 < n)
				{
					x += a[lo2];
				}
				lo = lo2 + 1;
				hi = hi2;
			}
		}
		writeln (res);
	}
}


Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance between Moscow and Saratov is $$$n$$$ km. Let's say that Moscow is situated at the point with coordinate $$$0$$$ km, and Saratov — at coordinate $$$n$$$ km.Driving for a long time may be really difficult. Formally, if Leha has already covered $$$i$$$ kilometers since he stopped to have a rest, he considers the difficulty of covering $$$(i + 1)$$$-th kilometer as $$$a_{i + 1}$$$. It is guaranteed that for every $$$i \in [1, n - 1]$$$ $$$a_i \le a_{i + 1}$$$. The difficulty of the journey is denoted as the sum of difficulties of each kilometer in the journey.Fortunately, there may be some rest sites between Moscow and Saratov. Every integer point from $$$1$$$ to $$$n - 1$$$ may contain a rest site. When Leha enters a rest site, he may have a rest, and the next kilometer will have difficulty $$$a_1$$$, the kilometer after it — difficulty $$$a_2$$$, and so on.For example, if $$$n = 5$$$ and there is a rest site in coordinate $$$2$$$, the difficulty of journey will be $$$2a_1 + 2a_2 + a_3$$$: the first kilometer will have difficulty $$$a_1$$$, the second one — $$$a_2$$$, then Leha will have a rest, and the third kilometer will have difficulty $$$a_1$$$, the fourth — $$$a_2$$$, and the last one — $$$a_3$$$. Another example: if $$$n = 7$$$ and there are rest sites in coordinates $$$1$$$ and $$$5$$$, the difficulty of Leha's journey is $$$3a_1 + 2a_2 + a_3 + a_4$$$.Leha doesn't know which integer points contain rest sites. So he has to consider every possible situation. Obviously, there are $$$2^{n - 1}$$$ different distributions of rest sites (two distributions are different if there exists some point $$$x$$$ such that it contains a rest site in exactly one of these distributions). Leha considers all these distributions to be equiprobable. He wants to calculate $$$p$$$ — the expected value of difficulty of his journey.Obviously, $$$p \cdot 2^{n - 1}$$$ is an integer number. You have to calculate it modulo $$$998244353$$$.

The first line contains one number $$$n$$$ ($$$1 \le n \le 10^6$$$) — the distance from Moscow to Saratov. The second line contains $$$n$$$ integer numbers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_1 \le a_2 \le \dots \le a_n \le 10^6$$$), where $$$a_i$$$ is the difficulty of $$$i$$$-th kilometer after Leha has rested.

Print one number — $$$p \cdot 2^{n - 1}$$$, taken modulo $$$998244353$$$.

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 = 998244353;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    foreach (i; 0..N-1) (A[i+1] += A[i]) %= MOD;

    long a = 1;
    long b = 0;
    long ans = 0;

    foreach_reverse (i; 0..N) {
        (ans += A[i] * a % MOD) %= MOD;
        a = a * 2 % MOD;
        if (b > 0) a += powmod(2, b-1, MOD);
        a %= MOD;
        b += 1;
    }

    ans.writeln;
}

long powmod(long a, long x, long m) {
    long ret = 1;
    while (x) {
        if (x % 2) ret = ret * a % m;
        a = a * a % m;
        x /= 2;
    }
    return ret;
}

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.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

void main()
{
    immutable int MOD = 998244353;

    int mulmod(int a, int b) {
        return cast(long)a * b % MOD;
    }

    int addmod(int a, int b) {
        int c = a + b;
        if (c > MOD) c -= MOD;
        return c;
    }

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

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

    auto pws = recurrence!((a, n) => mulmod(a[n-1], 2))(1).take(n).array.retro.array;

    pws ~= 0;

    debug { pws.writeln; }

    auto ans = 0;
    foreach (i, e; arr) {
        auto opts = cast(int)(n-1 - i);
        auto cur = addmod(pws[i], mulmod(opts, pws[i+1]));
        cur = mulmod(cur, e);
        ans = addmod(ans, cur);
    }

    ans.writeln;
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;
import std.traits;
import std.variant;
import std.concurrency;

const mod = 998244353;

void main(string[] args)
{
  auto n = next!int;
  auto a = next!long(n);
  foreach(ref ai; a) ai %= mod;
  long leaves = 1;
  long sumA = 0;
  long sumB = 0;
  long res = 0;
  foreach(i; 0 .. n)
    {
      sumA = (2 * sumA + a[i]) % mod;
      res = (sumA + sumB) % mod;
      sumB += res;
    }
  res.writeln;
  return;
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}

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 = 998244353;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    foreach (i; 0..N-1) (A[i+1] += A[i]) %= MOD;

    long a = 1;
    long b = 0;
    long ans = 0;

    foreach_reverse (i; 0..N) {
        (ans += A[i] * a % MOD) %= MOD;
        long c = 2 * a + b;
        b = a;
        a = c;
    }

    ans.writeln;
}


Consider the following game for two players. There is one white token and some number of black tokens. Each token is placed on a plane in a point with integer coordinates x and y.The players take turn making moves, white starts. On each turn, a player moves all tokens of their color by 1 to up, down, left or right. Black player can choose directions for each token independently.After a turn of the white player the white token can not be in a point where a black token is located. There are no other constraints on locations of the tokens: positions of black tokens can coincide, after a turn of the black player and initially the white token can be in the same point with some black point. If at some moment the white player can't make a move, he loses. If the white player makes 10100500 moves, he wins.You are to solve the following problem. You are given initial positions of all black tokens. It is guaranteed that initially all these positions are distinct. In how many places can the white token be located initially so that if both players play optimally, the black player wins?

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of black points. The (i + 1)-th line contains two integers xi, yi ( - 105 ≤ xi, yi,  ≤ 105) — the coordinates of the point where the i-th black token is initially located. It is guaranteed that initial positions of black tokens are distinct.

Print the number of points where the white token can be located initially, such that if both players play optimally, the black player wins.

NoteIn the first and second examples initial positions of black tokens are shown with black points, possible positions of the white token (such that the black player wins) are shown with white points.The first example: The second example: In the third example the white tokens should be located in the inner square 2 × 2, to make the black player win.

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 bAdd(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    bit[x] += val;
  }
}

// sum of [0, pos)
T bSum(T)(T[] bit, int pos)
in {
  assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold");
}
do {
  T ret = 0;
  for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
    ret += bit[x];
  }
  return ret;
}

// min pos s.t. pred(sum of [0, pos))
//   assume pred(sum of [0, pos)) is non-decreasing
int bBinarySearch(alias pred, T)(T[] bit) {
  import core.bitop : bsr;
  import std.functional : unaryFun;
  alias predFun = unaryFun!pred;
  if (predFun(0)) return 0;
  int pos = 0;
  T sum = 0;
  foreach_reverse (e; 0 .. bsr(bit.length) + 1) {
    const x = (pos | 1 << e) - 1;
    if (x < bit.length && !predFun(sum + bit[x])) {
      pos |= 1 << e;
      sum += bit[x];
    }
  }
  return pos + 1;
}

alias Pt = Tuple!(int, "x", int, "y");

long solve(Pt[] ps) {
  const n = cast(int)(ps.length);
  int mn = int.max;
  foreach (i; 0 .. n) {
    chmin(mn, ps[i].x);
    chmin(mn, ps[i].y);
  }
  foreach (i; 0 .. n) {
    ps[i].x -= mn;
    ps[i].y -= mn;
  }
  int L;
  foreach (i; 0 .. n) {
    chmax(L, ps[i].x);
    chmax(L, ps[i].y);
  }
  ++L;
  debug {
    writeln("ps = ", ps);
    writeln("L = ", L);
  }

  int n0, n1;
  auto bit0 = new int[L];
  auto bit1 = new int[L];
  foreach (i; 0 .. n) {
    ++n1;
    bit1.bAdd(ps[i].y, +1);
  }

  auto adds = new int[][L];
  foreach (i; 0 .. n) {
    adds[ps[i].x] ~= i;
  }
  long ret;
  foreach (x; 0 .. L) {
    foreach (i; adds[x]) {
      ++n0;
      --n1;
      bit0.bAdd(ps[i].y, +1);
      bit1.bAdd(ps[i].y, -1);
    }
    /*
      sum0 of [0, y) >= 1
      sum0 of [y, L) >= 1
      sum1 of [0, y) >= 1
      sum1 of [y, L) >= 1
    */
    // [lb, ub)
    int lb = 1, ub = L;
    chmax(lb, bit0.bBinarySearch!(s => (s >= 1)));
    chmin(ub, bit0.bBinarySearch!(s => (n0 - s < 1)));
    chmax(lb, bit1.bBinarySearch!(s => (s >= 1)));
    chmin(ub, bit1.bBinarySearch!(s => (n1 - s < 1)));
    if (lb < ub) {
      ret += ub - lb;
    }
  }
  return ret;
}

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

      long ans;
      foreach (s; 0 .. 2) {
        Pt[] ps;
        foreach (i; 0 .. N) {
          if ((X[i] + Y[i] + s) % 2 == 0) {
            ps ~= Pt((X[i] + Y[i] + s) / 2, (X[i] - Y[i] + s) / 2);
          }
        }
        ans += solve(ps);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges).A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted.Destroy all vertices in the given tree or determine that it is impossible.

The first line contains integer n (1 ≤ n ≤ 2·105) — number of vertices in a tree. The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ n). If pi ≠ 0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree.

If it's possible to destroy all vertices, print "YES" (without quotes), otherwise print "NO" (without quotes). If it's possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any.

NoteIn the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order.

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

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

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

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

int N;
int[] P;
int[][] G;

int[] sz;

void dfs0(int u, int p) {
  sz[u] = 1;
  foreach (v; G[u]) {
    if (v != p) {
      dfs0(v, u);
      sz[u] += sz[v];
    }
  }
}

int[] ans;

void dfs1(int u, int p) {
  foreach (v; G[u]) {
    if (v != p) {
      if (sz[v] % 2 == 0) {
        dfs1(v, u);
      }
    }
  }
  ans ~= u;
  foreach (v; G[u]) {
    if (v != p) {
      if (sz[v] % 2 != 0) {
        dfs1(v, u);
      }
    }
  }
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      P = new int[N];
      foreach (u; 0 .. N) {
        P[u] = readInt() - 1;
      }

      if (N % 2 == 0) {
        writeln("NO");
      } else {
        G = new int[][N];
        foreach (u; 0 .. N) {
          if (P[u] != -1) {
            G[u] ~= P[u];
            G[P[u]] ~= u;
          }
        }
        sz = new int[N];
        dfs0(0, -1);
        ans = [];
        dfs1(0, -1);
        writeln("YES");
        foreach (u; ans) {
          writeln(u + 1);
        }
      }
    }
  } catch (EOFException e) {
  }
}

import std.algorithm, std.container, std.conv, std.math, std.range, std.typecons, std.stdio, std.string;

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  int[] p; readA(n, p); p[] -= 1;

  if (n%2 == 0) {
    writeln("NO");
    return;
  }

  auto g = Graph!int(n);
  foreach (int i, pi; p)
    if (pi != -1) g.addEdgeB(i, pi);
  auto t = g.makeTree.rootify(0);

  auto c = new int[](n), qu = DList!int([0]), st = SList!int();
  while (!qu.empty) {
    auto u = qu.front; qu.removeFront();
    st.insertFront(u);
    foreach (v; t.children(u)) qu.insertBack(v);
  }
  while (!st.empty) {
    auto u = st.front; st.removeFront();
    c[u] = 1;
    foreach (v; t.children(u)) c[u] += c[v];
  }

  writeln("YES");

  st.insertFront(0);
  while (!st.empty) {
    auto u = st.front; st.removeFront();
    if (u >= n) {
      writeln(u-n+1);
      continue;
    }
    foreach (v; t.children(u).filter!(v => c[v]%2 == 1))
      st.insertFront(v);
    st.insertFront(u+n);
    foreach (v; t.children(u).filter!(v => c[v]%2 == 0))
      st.insertFront(v);
  }
}

struct Graph(N = int)
{
  alias Node = N;
  Node n;
  Node[][] g;
  alias g this;
  this(Node n) { this.n = n; g = new Node[][](n); }
  void addEdge(Node u, Node v) { g[u] ~= v; }
  void addEdgeB(Node u, Node v) { g[u] ~= v; g[v] ~= u; }
}

struct Tree(Graph)
{
  import std.algorithm, std.container;
  alias Node = Graph.Node;
  Graph g;
  alias g this;
  Node root;
  Node[] parent;
  int[] size, depth;

  this(ref Graph g) { this.g = g; this.n = g.n; }

  ref auto rootify(Node r)
  {
    this.root = r;

    parent = new Node[](g.n);
    depth = new int[](g.n);
    depth[] = -1;

    struct UP { Node u, p; }
    auto st1 = SList!UP(UP(r, r));
    auto st2 = SList!UP();
    while (!st1.empty) {
      auto up = st1.front, u = up.u, p = up.p; st1.removeFront();

      parent[u] = p;
      depth[u] = depth[p] + 1;

      foreach (v; g[u])
        if (v != p) {
          st1.insertFront(UP(v, u));
          st2.insertFront(UP(v, u));
        }
    }

    size = new int[](g.n);
    size[] = 1;

    while (!st2.empty) {
      auto up = st2.front, u = up.u, p = up.p; st2.removeFront();
      size[p] += size[u];
    }

    return this;
  }

  auto children(Node u) { return g[u].filter!(v => v != parent[u]); }
}
ref auto makeTree(Graph)(ref Graph g) { return Tree!Graph(g); }

import std.algorithm, std.container, std.conv, std.math, std.range, std.typecons, std.stdio, std.string;

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  int[] p; readA(n, p); p[] -= 1;

  auto g = new bool[int][](n);
  foreach (int i, pi; p)
    if (pi != -1) g[i][pi] = g[pi][i] = true;

  auto c = new bool[int][](3);

  auto degType(int u)
  {
    auto deg = g[u].length;
    if (deg == 0)        return 0;
    else if (deg%2 == 0) return 1;
    else                 return 2;

  }

  foreach (i; 0..n) c[degType(i)][i] = true;

  while (c[1].length) {
    auto u = c[1].keys.front;
    c[1].remove(u);
    foreach (v; g[u].byKey) {
      c[degType(v)].remove(v);
      g[v].remove(u);
      c[degType(v)][v] = true;
    }
  }

  writeln(c[1].length ? "NO" : "YES");
}

import std.algorithm, std.container, std.conv, std.math, std.range, std.typecons, std.stdio, std.string;

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  int[] p; readA(n, p); p[] -= 1;

  auto g = new bool[int][](n);
  foreach (int i, pi; p)
    if (pi != -1) g[i][pi] = g[pi][i] = true;

  auto c = new bool[int][](3);

  auto degType(int u)
  {
    auto deg = g[u].length;
    if (deg == 0)        return 0;
    else if (deg%2 == 0) return 1;
    else                 return 2;

  }

  foreach (i; 0..n) c[degType(i)][i] = true;

  while (c[1].length) {
    auto u = c[1].keys.front;
    writeln(u);
    c[1].remove(u);
    foreach (v; g[u].byKey) {
      c[degType(v)].remove(v);
      g[v].remove(u);
      c[degType(v)][v] = true;
    }
  }

  writeln(c[1].length ? "NO" : "YES");
}

import std.algorithm, std.container, std.conv, std.math, std.range, std.typecons, std.stdio, std.string;

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  int[] p; readA(n, p); p[] -= 1;

  auto g = new bool[int][](n);
  foreach (int i, pi; p)
    if (pi != -1) g[i][pi] = g[pi][i] = true;

  auto c = new bool[int][](3);

  auto degType(int u)
  {
    auto deg = g[u].length;
    if (deg == 0)        return 0;
    else if (deg%2 == 0) return 1;
    else                 return 2;

  }

  foreach (i; 0..n) c[degType(i)][i] = true;

  int[] r;
  while (c[1].length) {
    auto u = c[1].keys.front;
    r ~= u;
    c[1].remove(u);
    foreach (v; g[u].byKey) {
      c[degType(v)].remove(v);
      g[v].remove(u);
      c[degType(v)][v] = true;
    }
  }

  if (c[2].length) {
    writeln("NO");
  } else {
    writeln("YES");
    foreach (ri; r) writeln(ri+1);
    foreach (u; c[0].byKey) writeln(u+1);
  }
}


Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that:  each student in the team scored at least l points and at most r points;  in total, all members of the team scored exactly sall points;  the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.

The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.

Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.string;
import std.range;
import std.range.primitives;
import std.conv;

void fillarr(int sum, int sz, int[] arr) {
    if (sz == 0) return;
    int rem = sum % sz;
    int quo = sum / sz;
    foreach ( i ; 0 .. sz ) {
        arr[i] = quo + (rem-- > 0 ? 1 : 0);
    }
}

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

    int n, k, l, r, sall, sk;
    readf("%s %s %s %s %s %s\n", &n, &k, &l, &r, &sall, &sk);
    int[] scores = new int[n];
    scores[0] = sall;
    fillarr(sk, k, scores[n - k .. $]);
    fillarr(sall - sk, n - k, scores[0 .. n - k]);
    writefln("%(%s %)", scores);

    return 0;
}


To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you.

The first input line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 107) — the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1, b2, ..., bm (1 ≤ bi ≤ 107) — the numbers that are multiplied to produce the denominator.

Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout, mout must satisfy the inequality 1 ≤ nout, mout ≤ 105, and the actual values in the sets aout, i and bout, i must satisfy the inequality 1 ≤ aout, i, bout, i ≤ 107.  Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (x > 1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them.

NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3.

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

int[] P;

const MAX = 10000005;

static this() {
    auto isPrime = new bool[MAX];
    isPrime[] = true;
    isPrime[0] = isPrime[1] = false;
    for (int i = 2; i < MAX; i++) {
        if (!isPrime[i]) continue;
        P ~= i;
        for (int j = i + i; j < MAX; j += i) {
            isPrime[j] = false;
        }
    }
}

int[int] factor(int x) {
    int[int] ret;
    for (int i = 0;  ; i++) {
        int p = P[i];
        if (p * p > x) break;
        while (x % p == 0) {
            x /= p;
            ret[p] += 1;
        }
    }
    if (x > 1) ret[x] += 1;
    return ret;
}

struct S {
    int index, count;
}

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto xs = readln.chomp.split(" ").map!(to!int).array;
    auto ys = readln.chomp.split(" ").map!(to!int).array;

    S[][int] z;
    foreach (int i, x; xs) {
        auto f = factor(x);
        foreach (k, v; f) {
            z[k] ~= S(i, v);
        }
    }
    foreach (int i, y; ys) {
        auto f = factor(y);
        foreach (k, v; f) {
            if (k !in z) { z[k] ~= S(i, 0); }
            while (v > 0) {
                if (z[k].back.count < 0) {
                    z[k] ~= S(i, -v);
                    break;
                } else if (z[k].back.count <= v) {
                    v -= z[k].back.count;
                    z[k].popBack;
                    if (z[k].empty) {
                        z[k] ~= S(i, -v);
                        break;
                    }
                } else {
                    z[k].back.count -= v;
                    v = 0;
                }
            }
        }
    }

    auto nans = new int[N];
    auto dans = new int[M];
    nans[] = 1;
    dans[] = 1;
    foreach (int k, v; z) {
        foreach (s; v) {
            (s.count > 0 ? nans : dans)[s.index] *= k ^^ abs(s.count);
        }
        //writeln(k, " -> ", v);
    }
    writefln("%d %d", N, M);
    writefln("%(%s %)", nans);
    writefln("%(%s %)", dans);
}

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

int[] P;

const MAX = 10000005;

static this() {
    auto isPrime = new bool[MAX];
    isPrime[] = true;
    isPrime[0] = isPrime[1] = false;
    for (int i = 2; i < MAX; i++) {
        if (!isPrime[i]) continue;
        P ~= i;
        for (int j = i + i; j < MAX; j += i) {
            isPrime[j] = false;
        }
    }
}

void factor(ref int[] ret, int x, int m) {
    for (int i = 0; i < P.length && P[i] * P[i] <= x ; i++) {
        uint p = P[i];
        if (P[i] > x) break;
        while (x % p == 0) {
            x /= p;
            ret[p] += m;
        }
    }
    if (x > 1) ret[x] += m;
    //return ret;
}

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto xs = readln.chomp.split(" ").map!(to!int).array;
    auto ys = readln.chomp.split(" ").map!(to!int).array;

    auto z = new int[MAX];
    foreach (x; xs) {
        factor(z, x, 1);
    }
    foreach (y; ys) {
        factor(z, y, -1);
    }

    const I = 10000000;
    long x = 1, y = 1;
    long[] ax, ay;

    ay.reserve(100000);
    ax.reserve(100000);

    for (int i = 2; i < I; i++) {
        while (z[i] != 0) {
            //writeln([i, z[i]]);
            if (z[i] < 0) {
                z[i]++;
                if (x * i > I) {
                    ax ~= x;
                    x = 1;
                }
                x *= i;
            } else {
                z[i]--;
                if (y * i > I) {
                    ay ~= y;
                    y = 1;
                }
                y *= i;
            }
        }
    }

    if (ay.empty || y > 1) ay ~= y;
    if (ax.empty || x > 1) ax ~= x;

    writefln("%d %d", ay.length, ax.length);
    writefln("%(%s %)", ay);
    writefln("%(%s %)", ax);

    //writeln(P.back);
}

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

int[] P;

const MAX = 10000005;

static this() {
    auto isPrime = new bool[MAX];
    isPrime[] = true;
    isPrime[0] = isPrime[1] = false;
    for (int i = 2; i < MAX; i++) {
        if (!isPrime[i]) continue;
        P ~= i;
        for (int j = i + i; j < MAX; j += i) {
            isPrime[j] = false;
        }
    }
}

int[int] factor(int x) {
    int[int] ret;
    for (int i = 0;  ; i++) {
        int p = P[i];
        if (p * p > x) break;
        while (x % p == 0) {
            x /= p;
            ret[p] += 1;
        }
    }
    if (x > 1) ret[x] += 1;
    return ret;
}

struct S {
    int index, count;
}

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto xs = readln.chomp.split(" ").map!(to!int).array;
    auto ys = readln.chomp.split(" ").map!(to!int).array;

    S[][int] z;
    foreach (int i, x; xs) {
        auto f = factor(x);
        foreach (k, v; f) {
            z[k] ~= S(i, v);
        }
    }
    foreach (int i, y; ys) {
        auto f = factor(y);
        foreach (k, v; f) {
            if (k !in z) { z[k] ~= S(i, 0); }
            while (v > 0) {
                if (z[k].back.count < 0) {
                    z[k] ~= S(i, -v);
                    break;
                } else if (z[k].back.count <= v) {
                    v -= z[k].back.count;
                    z[k].popBack;
                    if (z[k].empty) {
                        z[k] ~= S(i, -v);
                        break;
                    }
                } else {
                    z[k].back.count -= v;
                    v = 0;
                }
            }
        }
    }

    auto nans = new int[N];
    auto dans = new int[M];
    nans[] = 1;
    dans[] = 1;
    foreach (int k, v; z) {
        foreach (s; v) {
            (s.count > 0 ? nans : dans)[s.index] *= k ^^ abs(s.count);
        }
        //writeln(k, " -> ", v);
    }
    writefln("%d %d", N, N);
    writefln("%(%s %)", nans);
    writefln("%(%s %)", dans);
}

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

int[] P;

const MAX = 10000005;

static this() {
    auto isPrime = new bool[MAX];
    isPrime[] = true;
    isPrime[0] = isPrime[1] = false;
    for (int i = 2; i < MAX; i++) {
        if (!isPrime[i]) continue;
        P ~= i;
        for (int j = i + i; j < MAX; j += i) {
            isPrime[j] = false;
        }
    }
}

void factor(ref long[] ret, long x, long m) {
    //long[long] ret;
    for (int i = 0; i < P.length ; i++) {
        uint p = P[i];
        if (P[i] > x) break;
        while (x % p == 0) {
            x /= p;
            ret[p] += m;
        }
    }
    //return ret;
}

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto xs = readln.chomp.split(" ").map!(to!long).array;
    auto ys = readln.chomp.split(" ").map!(to!long).array;

    auto z = new long[MAX];
    foreach (x; xs) {
        factor(z, x, -1);
    }
    foreach (y; ys) {
        factor(z, y, 1);
    }

    const I = 10000000;
    long x = 1, y = 1;
    long[] ax, ay;
    for (int i = 2; i <= I; i++) {
        while (z[i] != 0) {
            if (z[i] < 0) {
                z[i]++;
                if (x > I) {
                    ax ~= x;
                    x = 1;
                }
                x *= i;
            } else {
                z[i]--;
                if (y > I) {
                    ay ~= y;
                    y = 1;
                }
                y *= i;
            }
        }
    }

    ay ~= y;
    ax ~= x;

    writefln("%d %d", ax.length, ay.length);
    writefln("%(%s %)", ax);
    writefln("%(%s %)", ay);
}

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

int[] P;

const MAX = 10000005;

static this() {
    auto isPrime = new bool[MAX];
    isPrime[] = true;
    isPrime[0] = isPrime[1] = false;
    for (int i = 2; i < MAX; i++) {
        if (!isPrime[i]) continue;
        P ~= i;
        for (int j = i + i; j < MAX; j += i) {
            isPrime[j] = false;
        }
    }
}

void factor(ref int[] ret, int x, int m) {
    for (int i = 0; i < P.length && P[i] * P[i] <= x ; i++) {
        uint p = P[i];
        if (P[i] > x) break;
        while (x % p == 0) {
            x /= p;
            ret[p] += m;
        }
    }
    if (x > 1) ret[x] += m;
    //return ret;
}

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto xs = readln.chomp.split(" ").map!(to!int).array;
    auto ys = readln.chomp.split(" ").map!(to!int).array;

    auto z = new int[MAX];
    foreach (x; xs) {
        factor(z, x, 1);
    }
    foreach (y; ys) {
        factor(z, y, -1);
    }

    const I = 10000000;
    long x = 1, y = 1;
    long[] ax, ay;

    //ay.reserve(100000);
    //ax.reserve(100000);

    for (int i = 2; i < I; i++) {
        while (z[i] != 0) {
            //writeln([i, z[i]]);
            if (z[i] < 0) {
                z[i]++;
                if (x * i > I) {
                    ax ~= x;
                    x = 1;
                }
                x *= i;
            } else {
                z[i]--;
                if (y * i > I) {
                    ay ~= y;
                    y = 1;
                }
                y *= i;
            }
        }
    }

    if (ay.empty || y > 1) ay ~= y;
    if (ax.empty || x > 1) ax ~= x;

    writefln("%d %d", ay.length, ax.length);
    writefln("%(%s %)", ay);
    writefln("%(%s %)", ax);

    //writeln(P.back);
}

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

int[] P;

const MAX = 10000005;

static this() {
    auto isPrime = new bool[MAX];
    isPrime[] = true;
    isPrime[0] = isPrime[1] = false;
    for (int i = 2; i < MAX; i++) {
        if (!isPrime[i]) continue;
        P ~= i;
        for (int j = i + i; j < MAX; j += i) {
            isPrime[j] = false;
        }
    }
}

int[int] factor(int x) {
    int[int] ret;
    for (int i = 0;  ; i++) {
        int p = P[i];
        if (p * p > x) break;
        while (x % p == 0) {
            x /= p;
            ret[p] += 1;
        }
    }
    if (x > 1) ret[x] += 1;
    return ret;
}

struct S {
    int index, count;
}

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto xs = readln.chomp.split(" ").map!(to!int).array;
    auto ys = readln.chomp.split(" ").map!(to!int).array;

    S[][int] z;
    foreach (int i, x; xs) {
        auto f = factor(x);
        foreach (k, v; f) {
            z[k] ~= S(i, v);
        }
    }
    foreach (int i, y; ys) {
        auto f = factor(y);
        foreach (k, v; f) {
            if (k !in z) { z[k] ~= S(i, 0); }
            while (v > 0) {
                if (z[k].back.count <= v) {
                    v -= z[k].back.count;
                    z[k].popBack;
                    if (z[k].empty) {
                        z[k] ~= S(i, -v);
                        break;
                    }
                } else {
                    z[k].back.count -= v;
                    v = 0;
                }
            }
        }
    }

    N = max(N, M);
    auto nans = new int[N];
    auto dans = new int[N];
    nans[] = 1;
    dans[] = 1;
    foreach (int k, v; z) {
        foreach (s; v) {
            (s.count > 0 ? nans : dans)[s.index] *= k ^^ abs(s.count);
        }
        //writeln(k, " -> ", v);
    }
    writefln("%d %d", N, N);
    writefln("%(%s %)", nans);
    writefln("%(%s %)", dans);
}

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

long[] P;

const MAX = 10000001;

static this() {
    auto isPrime = new bool[MAX];
    isPrime[] = true;
    isPrime[0] = isPrime[1] = false;
    for (int i = 2; i < MAX; i++) {
        if (!isPrime[i]) continue;
        P ~= i;
        for (int j = i + i; j < MAX; j += i) {
            isPrime[j] = false;
        }
    }
}

long[long] factor(long x) {
    long[long] ret;
    for (int i = 0; ; i++) {
        long p = P[i];
        if (P[i] > x) break;
        while (x % p == 0) {
            x /= p;
            ret[p] = ret.get(p, 0) + 1;
        }
    }
    return ret;
}

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto xs = readln.chomp.split(" ").map!(to!long).array;
    auto ys = readln.chomp.split(" ").map!(to!long).array;

    long[long] z;
    foreach (x; xs) {
        long[long] s = factor(x);
        foreach (k, v; s) {
            z[k] = z.get(k, 0) + v;
        }
    }
    foreach (y; ys) {
        long[long] s = factor(y);
        foreach (k, v; s) {
            z[k] = z.get(k, 0) - v;
        }
    }

    writeln("1 1");
    long y = 1, x = 1;

    foreach (k, v; z) {
        if (v >= 0) {
            foreach (i; 0 .. v) {
                y *= k;
            }
        } else {
            v = -v;
            foreach (i; 0 .. v) {
                x *= k;
            }
        }
    }

    writeln(y);
    writeln(x);

}

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

int[] P;

const MAX = 10000005;

static this() {
    auto isPrime = new bool[MAX];
    isPrime[] = true;
    isPrime[0] = isPrime[1] = false;
    for (int i = 2; i < MAX; i++) {
        if (!isPrime[i]) continue;
        P ~= i;
        for (int j = i + i; j < MAX; j += i) {
            isPrime[j] = false;
        }
    }
}

void factor(ref int[] ret, int x, int m) {
    for (int i = 0; i < P.length && P[i] * P[i] <= x ; i++) {
        uint p = P[i];
        if (P[i] > x) break;
        while (x % p == 0) {
            x /= p;
            ret[p] += m;
        }
    }
    if (x > 1) ret[x] += m;
    //return ret;
}

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto xs = readln.chomp.split(" ").map!(to!int).array;
    auto ys = readln.chomp.split(" ").map!(to!int).array;

    auto z = new int[MAX];
    foreach (x; xs) {
        factor(z, x, 1);
    }
    foreach (y; ys) {
        factor(z, y, -1);
    }

    const I = 10000000;
    long x = 1, y = 1;
    long[] ax, ay;

    ay.reserve(100000);
    ax.reserve(100000);

    for (int i = 2; i < I; i++) {
        while (z[i] != 0) {
            //writeln([i, z[i]]);
            if (z[i] < 0) {
                z[i]++;
                if (x * i > I) {
                    ax ~= x;
                    x = 1;
                }
                x *= i;
            } else {
                z[i]--;
                if (y * i > I) {
                    ay ~= y;
                    y = 1;
                }
                y *= i;
            }
        }
    }

    ay ~= y;
    ax ~= x;

    writefln("%d %d", ay.length, ax.length);
    writefln("%(%s %)", ay);
    writefln("%(%s %)", ax);

    //writeln(P.back);
}


This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java — call System.out.flush(), and in Pascal — flush(output).Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind.On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed.Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers — the number of "bulls" and the number of "cows". A try can contain equal digits.More formally, let's the secret string is s and the second player are trying to guess it with a string x. The number of "bulls" is a number of such positions i (1 ≤ i ≤ 4) where s[i] = x[i]. The number of "cows" is a number of such digits c that s contains c in the position i (i.e. s[i] = c), x contains c, but x[i] ≠ c.For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow.In this problem you are to guess the string s that the system has chosen. You only know that the chosen string consists of 4 distinct digits.You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons — the program either guessed the number x or made an invalid action (for example, printed letters instead of digits).Your program is allowed to do at most 50 queries.You can hack solutions of other participants providing a 4-digit string containing distinct digits — the secret string.

To read answers to the queries, the program must use the standard input. The program will receive pairs of non-negative integers in the input, one pair per line. The first number in a pair is a number of bulls and the second one is a number of cows of the string s and the string xi printed by your program. If the system response equals "4 0", then your solution should terminate. The testing system will let your program read the i-th pair of integers from the input only after your program displays the corresponding system query in the output: prints value xi in a single line and executes operation flush.

The program must use the standard output to print queries. Your program must output requests — 4-digit strings x1, x2, ..., one per line. After the output of each line the program must execute flush operation. The program should read the answer to the query from the standard input. Your program is allowed to do at most 50 queries.

NoteThe secret string s in the example is "0123".

import std.algorithm;
import std.stdio;

void main() {
    int a, b;
    int[ ] possible;
    possible.reserve(4);
    foreach (c; 0 .. 10) {
        writeln(c, c, c, c);
        stdout.flush();
        readf(" %s %s", &a, &b);
        if (a == 4)
            return;
        while (a--)
            possible ~= c;
    }
    foreach (p; permutations(possible)) {
        writefln("%(%s%)", p);
        stdout.flush();
        readf(" %s %s", &a, &b);
        if (a == 4)
            break;
    }
}


Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $$$(0, 0)$$$ on an infinite grid.You also have the sequence of instructions of this robot. It is written as the string $$$s$$$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $$$(x, y)$$$ right now, he can move to one of the adjacent cells (depending on the current instruction).  If the current instruction is 'L', then the robot can move to the left to $$$(x - 1, y)$$$;  if the current instruction is 'R', then the robot can move to the right to $$$(x + 1, y)$$$;  if the current instruction is 'U', then the robot can move to the top to $$$(x, y + 1)$$$;  if the current instruction is 'D', then the robot can move to the bottom to $$$(x, y - 1)$$$. You've noticed the warning on the last page of the manual: if the robot visits some cell (except $$$(0, 0)$$$) twice then it breaks.So the sequence of instructions is valid if the robot starts in the cell $$$(0, 0)$$$, performs the given instructions, visits no cell other than $$$(0, 0)$$$ two or more times and ends the path in the cell $$$(0, 0)$$$. Also cell $$$(0, 0)$$$ should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: "UD", "RL", "UUURULLDDDDLDDRRUU", and the following are considered invalid: "U" (the endpoint is not $$$(0, 0)$$$) and "UUDD" (the cell $$$(0, 1)$$$ is visited twice).The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain.Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric).You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^4$$$) — the number of test cases. The next $$$q$$$ lines contain test cases. The $$$i$$$-th test case is given as the string $$$s$$$ consisting of at least $$$1$$$ and no more than $$$10^5$$$ characters 'L', 'R', 'U' and 'D' — the initial sequence of instructions. It is guaranteed that the sum of $$$|s|$$$ (where $$$|s|$$$ is the length of $$$s$$$) does not exceed $$$10^5$$$ over all test cases ($$$\sum |s| \le 10^5$$$).

For each test case print the answer on it. In the first line print the maximum number of remaining instructions. In the second line print the valid sequence of remaining instructions $$$t$$$ the robot has to perform. The moves are performed from left to right in the order of the printed sequence. If there are several answers, you can print any. If the answer is $$$0$$$, you are allowed to print an empty line (but you can don't print it).

6
LRU
DURLDRUDRULRDURDDL
LRUDDLRUDRUL
LLLLRRRR
URDUR
LLL

2
LR
14
RUURDDDDLLLUUR
12
ULDDDRRRUULL
2
LR
2
UD
0

NoteThere are only two possible answers in the first test case: "LR" and "RL".The picture corresponding to the second test case:  Note that the direction of traverse does not matter Another correct answer to the third test case: "URDDLLLUURDR".

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
void main()
{
  int q; get(q);
  while(q--)
    {
      int[4] count = 0;
      string str; get(str);
      foreach(c; str)
	{
	  switch(c)
	    {
	    case 'L':
	      count[0]++;
	      break;
	    case 'R':
	      count[1]++;
	      break;
	    case 'U':
	      count[2]++;
	      break;
	    case 'D':
	      count[3]++;
	      break;
	    default:
	      assert(0);
	    }
	}
      int l = min(count[0], count[1]);
      int r = min(count[2], count[3]);
      if(l == 0 && r > 1)
	{
	  r = 1;
	}
      if(l > 1 && r == 0)
	{
	  l = 1;
	}
      wr(2 * (l + r));
      foreach(i; 0 .. r)
	write('U');
      foreach(i; 0 .. l)
	write('R');
      foreach(i; 0 .. r)
	write('D');
      foreach(i; 0 .. l)
	write('L');
      if(l + r)
	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;

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        auto S = readln.chomp;
        auto N = S.length.to!int;
        auto U = S.count('U').to!int;
        auto D = S.count('D').to!int;
        auto L = S.count('L').to!int;
        auto R = S.count('R').to!int;
        auto x = min(U, D);
        auto y = min(L, R);
        auto ans = new dchar[](x + y + x + y);
        if (x == 0 && y == 0) {
            0.writeln;
            writeln;
        } else if (x == 0) {
            2.writeln;
            "LR".writeln;
        } else if (y == 0) {
            2.writeln;
            "UD".writeln;
        } else {
            foreach (i; 0..x+x+y+y) {
                if (i < x) ans[i] = 'U';
                else if (i < x + y) ans[i] = 'L';
                else if (i < 2 * x + y) ans[i] = 'D';
                else ans[i] = 'R';
            }
            ans.length.writeln;
            ans.writeln;
        }
    }
}

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 rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	int q = rint;
	foreach(_; 0 .. q){
		string s = rstring;
		int[char] cnt = ['L': 0, 'R': 0, 'U': 0, 'D': 0];
		foreach(c; s) cnt[c] += 1;

		int x = min(cnt['L'], cnt['R']), y = min(cnt['U'], cnt['D']);
		if(x == 0 && y >= 2) y = 1;
		if(y == 0 && x >= 2) x = 1;
		(x + x + y + y).writeln;
		foreach(i; 0 .. x) "L".write;
		foreach(j; 0 .. y) "U".write;
		foreach(i; 0 .. x) "R".write;
		foreach(j; 0 .. y) "D".write;
		writeln;

	}
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 q = RD!int;
	auto ans = new string[](q);
	foreach (i; 0..q)
	{
		auto s = RD!string;
		long cnt_u, cnt_d, cnt_l, cnt_r;
		foreach (c; s)
		{
			if (c == 'U')
				++cnt_u;
			else if (c == 'D')
				++cnt_d;
			else if (c == 'L')
				++cnt_l;
			else
				++cnt_r;
		}
		auto y = min(cnt_u, cnt_d);
		auto x = min(cnt_l, cnt_r);
		if (y == 0)
			x.chmin(1);
		else if (x == 0)
			y.chmin(1);
		foreach (_; 0..y)
			ans[i] ~= 'U';
		foreach (_; 0..x)
			ans[i] ~= 'R';
		foreach (_; 0..y)
			ans[i] ~= 'D';
		foreach (_; 0..x)
			ans[i] ~= 'L';
	}

	foreach (e; ans)
	{
		writeln(e.length);
		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 q = RD!int;
	auto ans = new string[](q);
	foreach (i; 0..q)
	{
		auto s = RD!string;
		long cnt_u, cnt_d, cnt_l, cnt_r;
		foreach (c; s)
		{
			if (c == 'U')
				++cnt_u;
			else if (c == 'D')
				++cnt_d;
			else if (c == 'L')
				++cnt_l;
			else
				++cnt_r;
		}
		auto y = min(cnt_u, cnt_d);
		auto x = min(cnt_l, cnt_r);
		if (y == 0)
			x.chmin(1);
		else if (x == 1)
			y.chmin(1);
		foreach (_; 0..y)
			ans[i] ~= 'U';
		foreach (_; 0..x)
			ans[i] ~= 'R';
		foreach (_; 0..y)
			ans[i] ~= 'D';
		foreach (_; 0..x)
			ans[i] ~= 'L';
	}

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


One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:  Find the number that goes k-th in the current sequence and add the same number to the end of the sequence;  Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.

Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.

NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.

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

void main() {
    int N, K; scanf("%d %d\n", &N, &K);
    auto xs = readln.chomp.split(" ").map!(to!int).array;

    K--;

    int a = xs[K];
    bool check() {
        foreach (x; xs[K .. $]) {
            if (a != x) return false;
        }
        return true;
    }
    if (!check()) {
        writeln(-1); return;
    }

    auto ys = xs[0 .. K];
    int c = 0;
    for (int i = K - 1; i >= 0; i--) {
        if (ys[i] == a) c++;
        else break;
    }
    /*
    writeln([c]);
    writeln([N, K]);
    writeln(xs);
    writeln(ys);
    */
    writeln(K - c);

}


You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree.

Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$.

NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$.

import std.array;
import std.stdio;
import std.string;
import std.range;
import std.conv;
import std.algorithm.iteration;
import std.algorithm.comparison;

void main(string[] args)
{
  auto inf = cast(int) float.infinity;
  const int n = to!int(readln().chomp());
  auto white = stdin.readln().split().map!(to!int);
  auto score = array((-inf).repeat(n+1));
  score[0] = 0;
  int[][] adj;
  adj.length = n+1;

  int u, v;
  for (int i=1; i<n; i++) {
    stdin.readf!"%d %d\n"(u, v);
    adj[u] ~= v;
    adj[v] ~= u;
  }

  void dfs(int i, int parent) {
    score[i] = white[i-1] ? 1 : -1;
    foreach (child; adj[i])
    {
      if (child == parent) continue;
      dfs(child, i);
      score[i] = max(score[i], score[i] + score[child]);
    }
  }
  dfs(1, 0);

  void dfs2(int i, int parent) {
    score[i] = max(score[i], score[parent] + min(0, score[i]));
    foreach (child; adj[i])
    {
      if (child == parent) continue;
      dfs2(child, i);
    }
  }
  dfs2(1, 0);

  writeln(score[1..$].map!(to!string).joiner(" "));
}

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

void main()
{
    auto N = readln.chomp.to!int;
    auto CS = readln.split.to!(int[]);
    int[][] T;
    T.length = N;
    foreach (_; 0..N-1) {
        auto ab = readln.split.to!(int[]);
        auto a = ab[0]-1;
        auto b = ab[1]-1;
        T[a] ~= b;
        T[b] ~= a;
    }

    auto MD = new int[](N);
    int paint(int i, int p) {
        auto d = CS[i] ? 1 : -1;
        foreach (j; T[i]) if (j != p) d += max(0, paint(j, i));
        MD[i] = d;
        return d;
    }
    paint(0, -1);
    void solve(int i, int p) {
        if (p >= 0) {
            if (CS[i]) {
                MD[i] = max(MD[i], MD[p]);
            } else if (MD[i] <= 0) {
                MD[i] = max(MD[i], MD[p] + MD[i]);
            } else {
                MD[i] = max(MD[i], MD[p]);
            }
        }
        foreach (j; T[i]) if (j != p) solve(j, i);
    }
    solve(0, -1);

    writeln(MD.to!(string[]).join(" "));
}

import std.array;
import std.stdio;
import std.string;
import std.range;
import std.conv;
import std.algorithm.iteration;
import std.algorithm.comparison;

void main(string[] args)
{
  auto inf = cast(int) float.infinity;
  const int n = to!int(readln().chomp());
  auto white = stdin.readln().split().map!(to!int);
  auto score = array((-inf).repeat(n+1));
  score[0] = 0;
  int[][] adj;
  adj.length = n+1;

  int u, v;
  for (int i=1; i<n; i++) {
    stdin.readf!"%d %d\n"(u, v);
    adj[u] ~= v;
    adj[v] ~= u;
  }
  writeln(adj);

  void dfs(int i, int parent) {
    score[i] = white[i-1] ? 1 : -1;
    foreach (child; adj[i])
    {
      if (child == parent) continue;
      dfs(child, i);
      score[i] = max(score[i], score[i] + score[child]);
    }
  }
  dfs(1, 0);
  writeln(score);

  void dfs2(int i, int parent) {
    score[i] = max(score[i], score[parent] + min(0, score[i]));
    foreach (child; adj[i])
    {
      if (child == parent) continue;
      dfs2(child, i);
    }
  }
  dfs2(1, 0);

  writeln(score[1..$].map!(to!string).joiner(" "));
}

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

void main()
{
    auto N = readln.chomp.to!int;
    auto CS = readln.split.to!(int[]);
    int[][] T;
    T.length = N;
    foreach (_; 0..N-1) {
        auto ab = readln.split.to!(int[]);
        auto a = ab[0]-1;
        auto b = ab[1]-1;
        T[a] ~= b;
        T[b] ~= a;
    }

    auto MD = new int[](N);
    int paint(int i, int p) {
        int d = CS[i] ? 1 : -1;
        foreach (j; T[i]) if (j != p) d += max(0, paint(j, i));
        MD[i] = d;
        return d;
    }
    paint(0, -1);
    void solve(int i, int p) {
        if (p >= 0) {
            if (CS[i]) {
                MD[i] = max(MD[i], MD[p]);
            } else {
                MD[i] += MD[p];
            }
        }
        foreach (j; T[i]) if (j != p) solve(j, i);
    }
    solve(0, -1);

    writeln(MD.to!(string[]).join(" "));
}