After you had helped Fedor to find friends in the «Call of Soldiers 3» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all. Now Fedor is going to change the essay using the synonym dictionary of the English language.Fedor does not want to change the meaning of the essay. So the only change he would do: change a word from essay to one of its synonyms, basing on a replacement rule from the dictionary. Fedor may perform this operation any number of times.As a result, Fedor wants to get an essay which contains as little letters «R» (the case doesn't matter) as possible. If there are multiple essays with minimum number of «R»s he wants to get the one with minimum length (length of essay is the sum of the lengths of all the words in it). Help Fedor get the required essay.Please note that in this problem the case of letters doesn't matter. For example, if the synonym dictionary says that word cat can be replaced with word DOG, then it is allowed to replace the word Cat with the word doG.

The first line contains a single integer m (1 ≤ m ≤ 105) — the number of words in the initial essay. The second line contains words of the essay. The words are separated by a single space. It is guaranteed that the total length of the words won't exceed 105 characters. The next line contains a single integer n (0 ≤ n ≤ 105) — the number of pairs of words in synonym dictionary. The i-th of the next n lines contains two space-separated non-empty words xi and yi. They mean that word xi can be replaced with word yi (but not vise versa). It is guaranteed that the total length of all pairs of synonyms doesn't exceed 5·105 characters. All the words at input can only consist of uppercase and lowercase letters of the English alphabet.

Print two integers — the minimum number of letters «R» in an optimal essay and the minimum length of an optimal essay.

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

immutable int N = 300001;

alias pair = Tuple!(long, long);

int id = 0;
int top = 0, sccCounter = 0;
pair[N] a;
pair[N] data;
pair[N] memo;
int[N] num;
int[N] low;
int[][N] re;
int[][N] adj;
int[N] stack;
int[N] sccID;
bool[N] visit;
int[string] map;

pair f(int u) {
  if (memo[u][0] != -1) {
    return memo[u];
  } else {
    pair res = data[u];
    foreach (v; re[u]) {
      res = min(res, f(v));
    }
    memo[u] = res;
    return memo[u];
  }
}

int getID(string s) {
  if (s !in map) {
    map[s] = id++;
  }
  return map[s];
}

int timer = 0;
void dfs(int u) {
  num[u] = low[u] = timer++;
  visit[u] = true;
  stack[top++] = u;
  foreach (v; adj[u]) {
    if (num[v] == -1) {
      dfs(v);
      low[u] = min(low[u], low[v]);
    } else if (visit[v]) {
      low[u] = min(low[u], num[v]);
    }
  }
  if (low[u] == num[u]) {
    while (true) {
      int v = stack[top-1]; top--;
      visit[v] = false;
      sccID[v] = sccCounter;
      if (v == u) {
        break;
      }
    }
    sccCounter++;
  }
}

void main() {
  int m; readf(" %s ", &m);
  char[][] essay = readln.strip.dup.split;
  auto word = new int[m];
  foreach (i, w; essay) {
    toLowerInPlace(w);
    word[i] = getID(w.idup);
    int rCount = 0;
    foreach (l; w) {
      rCount += l == 'r';
    }
    a[word[i]] = pair(to!(long)(rCount), to!(long)(w.length));
  }
  int n; readf(" %s ", &n);
  for (int i = 0; i < n; i++) {
    char[][] d = readln.strip.dup.split;
    toLowerInPlace(d[0]);
    toLowerInPlace(d[1]);
    int u = getID(d[0].idup);
    int v = getID(d[1].idup);
    adj[u] ~= v;
    for (int j = 0; j < 2; j++) {
      int rCount = 0;
      foreach (l; d[j]) {
        rCount += l == 'r';
      }
      a[getID(d[j].idup)] = pair(to!(long)(rCount), to!(long)(d[j].length));
    }
  }
  num[] = -1;
  low[] = -1;
  for (int i = 0; i < id; i++) {
    if (num[i] == -1) {
      dfs(i);
    }
  }
  data[] = pair(int.max, int.max);
  for (int u = 0; u < id; u++) {
    data[sccID[u]] = min(data[sccID[u]], a[u]);
    foreach (v; adj[u]) {
      if (sccID[u] != sccID[v]) {
        re[sccID[u]] ~= sccID[v];
      }
    }
  }
  long ansR = 0;
  long ansL = 0;
  memo[] = pair(-1, -1);
  foreach (w; word) {
    pair res = f(sccID[w]);
    ansR += res[0];
    ansL += res[1];
  }
  writeln(ansR, ' ', ansL);
}


While discussing a proper problem A for a Codeforces Round, Kostya created a cyclic array of positive integers $$$a_1, a_2, \ldots, a_n$$$. Since the talk was long and not promising, Kostya created a new cyclic array $$$b_1, b_2, \ldots, b_{n}$$$ so that $$$b_i = (a_i \mod a_{i + 1})$$$, where we take $$$a_{n+1} = a_1$$$. Here $$$mod$$$ is the modulo operation. When the talk became interesting, Kostya completely forgot how array $$$a$$$ had looked like. Suddenly, he thought that restoring array $$$a$$$ from array $$$b$$$ would be an interesting problem (unfortunately, not A).

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 140582$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_{n}$$$ ($$$0 \le b_i \le 187126$$$).

If it is possible to restore some array $$$a$$$ of length $$$n$$$ so that $$$b_i = a_i \mod a_{(i \mod n) + 1}$$$ holds for all $$$i = 1, 2, \ldots, n$$$, print «YES» in the first line and the integers $$$a_1, a_2, \ldots, a_n$$$ in the second line. All $$$a_i$$$ should satisfy $$$1 \le a_i \le 10^{18}$$$. We can show that if an answer exists, then an answer with such constraint exists as well. It it impossible to restore any valid $$$a$$$, print «NO» in one line. You can print each letter in any case (upper or lower).

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 (arr.maxElement == arr.minElement) {
        if (arr.front == 0) {
            writeln("YES");
            (1).repeat(n).writefln!("%(%s %)");
        } else {
            writeln("NO");
        }
        return;
    }

    auto mx = arr.maxElement;
    auto p = 0;
    for (int i = 1; i < n; ++i) {
        if (arr[i] == mx && arr[i-1] < mx) p = i;
    }
    auto ans = new long[] (n);
    ans[p] = arr[p];
    ans[(p-1+n)%n] = arr[p] * 2 + arr[(p-1+n)%n];
    for (auto i = (p-2+n) % n, cnt = 0; cnt < n-2; i = (i-1+n) % n, ++cnt) {
        auto nxt = (i+1) % n;
        ans[i] = ans[nxt] + arr[i];
    }

    writeln("YES");
    ans.writefln!("%(%s %)");
}

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 (arr.maxElement == arr.minElement) {
        if (arr.front == 0) {
            writeln("YES");
            (1).repeat(n).writefln!("%(%s %)");
        } else {
            writeln("NO");
        }
        return;
    }

    auto ans = new long[] (n);

    auto p = arr.maxIndex;
    ans[p] = arr[p];
    ans[(p-1+n)%n] = arr[p] * 2 + arr[(p-1+n)%n];
    for (auto i = (p-2+n) % n, cnt = 0; cnt < n-2; i = (i-1+n) % n, ++cnt) {
        auto nxt = (i+1) % n;
        ans[i] = ans[nxt] + arr[i];
    }

    writeln("YES");
    ans.writefln!("%(%s %)");
}

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 (arr.maxElement == arr.minElement) {
        if (arr.front == 0) {
            writeln("YES");
            (1).repeat(n).writefln!("%(%s %)");
        } else {
            writeln("NO");
        }
        return;
    }

    auto ans = new int[] (n);
    ans[] = arr.maxElement * 2;

    auto p = arr.maxIndex;
    ans[p] = arr[p];
    for (auto i = (p-1+n) % n, cnt = 0; cnt < n-1; i = (i-1+n) % n, ++cnt) {
        auto nxt = (i+1) % n;
        ans[i] = ans[nxt] + arr[i];
    }

    writeln("YES");
    ans.writefln!("%(%s %)");
}

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 (arr.maxElement == arr.minElement) {
        if (arr.front == 0) {
            writeln("YES");
            (1).repeat(n).writefln!("%(%s %)");
        } else {
            writeln("NO");
        }
        return;
    }

    auto mx = arr.maxElement;
    auto p = 0;
    for (int i = 1; i < n; ++i) {
        if (arr[i] == mx && arr[i] < mx) p = i;
    }
    auto ans = new long[] (n);
    ans[p] = arr[p];
    ans[(p-1+n)%n] = arr[p] * 2 + arr[(p-1+n)%n];
    for (auto i = (p-2+n) % n, cnt = 0; cnt < n-2; i = (i-1+n) % n, ++cnt) {
        auto nxt = (i+1) % n;
        ans[i] = ans[nxt] + arr[i];
    }

    writeln("YES");
    ans.writefln!("%(%s %)");
}

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 (arr.maxElement == arr.minElement) {
        if (arr.front == 0) {
            writeln("YES");
            (1).repeat(n).writefln!("%(%s %)");
        } else {
            writeln("NO");
        }
        return;
    }

    auto ans = new int[] (n);
    ans[] = arr.maxElement * 2;

    auto p = arr.maxIndex;
    ans[p] = arr[p];
    for (auto i = p - 1, cnt = 0; cnt < n-1; i = (i-1+n) % n, ++cnt) {
        auto nxt = (i+1) % n;
        ans[i] = ans[nxt] + arr[i];
    }

    writeln("YES");
    ans.writefln!("%(%s %)");
}

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 (arr.maxElement == arr.minElement) {
        if (arr.front == 0) {
            writeln("YES");
            (1).repeat(n).writefln!("%(%s %)");
        } else {
            writeln("NO");
        }
        return;
    }

    auto ans = new long[] (n);
    ans[] = arr.maxElement * 2;

    auto p = arr.maxIndex;
    ans[p] = arr[p];
    for (auto i = (p-1+n) % n, cnt = 0; cnt < n-1; i = (i-1+n) % n, ++cnt) {
        auto nxt = (i+1) % n;
        ans[i] = ans[nxt] + arr[i];
    }

    writeln("YES");
    ans.writefln!("%(%s %)");
}


This problem is interactive.We have hidden an array $$$a$$$ of $$$n$$$ pairwise different numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon. This device can answer queries of the following form: in response to the positions of $$$k$$$ different elements of the array, it will return the position and value of the $$$m$$$-th among them in the ascending order.Unfortunately, the instruction for the device was lost during delivery. However, you remember $$$k$$$, but don't remember $$$m$$$. Your task is to find $$$m$$$ using queries to this device. You can ask not more than $$$n$$$ queries.Note that the array $$$a$$$ and number $$$m$$$ are fixed before the start of the interaction and don't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries, and you don't need to guess array $$$a$$$. You just have to guess $$$m$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1\le k < n \le 500$$$) — the length of the array and the number of the elements in the query. It is guaranteed that number $$$m$$$ satisfies $$$1\le m \le k$$$, elements $$$a_1, a_2, \dots, a_n$$$ of the array satisfy $$$0\le a_i \le 10^9$$$, and all of them are different.

import std.stdio;
import std.array;
import std.range : iota;

void main() {
  int n, k;
  readf!"%d %d\n"(n, k);

  auto a = iota(1, k+2).array;

  auto b1 = -1, b2 = -1;
  auto c1 = 0, c2 = 0;

  // make k+1 queries, omitting i in each
  foreach (i; 0..k+1) {
    auto x = a[0..i] ~ a[i+1..$];

    // write query string
    write("? ");
    foreach (e; x) {
      writef("%d ", e);
    }
    writeln;
    stdout.flush;

    // read response
    int pos, b;
    readf!"%d %d\n"(pos, b);

    if (b1 == -1) {
      b1 = b;
    } else if (b2 == -1 && b1 != b) {
      b2 = b;
    }

    if (b1 == b) {
      c1++;
    } else {
      c2++;
    }
  }

  // there'll be m occurrences of the larger element
  // and k + 1 - m of the smaller
  writefln("! %d\n", b1 > b2 ? c1 : c2);
}

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 n = rint, k = rint;

	int[int] cnt;
	long[int] vm;
	foreach(i; 0 .. k + 1){
		int[] js;
		foreach(j; 0 .. k + 1) if(j != i) js ~= j;
		S s = ask(js);
		vm[s.pos] = s.value;
		if(s.pos !in cnt) cnt[s.pos] = 0;
		cnt[s.pos] += 1;
	}

	int[] ks = cnt.keys;
	int a = ks[0], b = ks[1];
	if(vm[a] < vm[b]) answer(cnt[b]);
	else answer(cnt[a]);

}
struct S{
	int pos;
	long value;
}
S ask(int[] js){
	writeln("? ", js.map!(x => (x + 1).to!string).array.join(" "));
	stdout.flush;
	return S(rint, rlong);
}
void answer(int ans){
	writeln("! ", ans);
}


This is an easier version of the problem with smaller constraints.Korney Korneevich dag up an array $$$a$$$ of length $$$n$$$. Korney Korneevich has recently read about the operation bitwise XOR, so he wished to experiment with it. For this purpose, he decided to find all integers $$$x \ge 0$$$ such that there exists an increasing subsequence of the array $$$a$$$, in which the bitwise XOR of numbers is equal to $$$x$$$.It didn't take a long time for Korney Korneevich to find all such $$$x$$$, and he wants to check his result. That's why he asked you to solve this problem!A sequence $$$s$$$ is a subsequence of a sequence $$$b$$$ if $$$s$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.A sequence $$$s_1, s_2, \ldots , s_m$$$ is called increasing if $$$s_1 < s_2 < \ldots < s_m$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 500$$$) — the elements of the array $$$a$$$.

In the first line print a single integer $$$k$$$ — the number of found $$$x$$$ values. In the second line print $$$k$$$ integers in increasing order $$$x_1, x_2, \ldots x_k$$$ ($$$0 \le x_1 < \ldots < x_k$$$) — found $$$x$$$ values.

NoteIn the first test case:  To get value $$$x = 0$$$ it is possible to choose and empty subsequence  To get value $$$x = 2$$$ it is possible to choose a subsequence $$$[2]$$$  To get value $$$x = 4$$$ it is possible to choose a subsequence $$$[4]$$$  To get value $$$x = 6$$$ it is possible to choose a subsequence $$$[2, 4]$$$

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

int[] solve(int[] a)
{
    auto n = to!int(a.length);
    const int m = 512;
    auto pdp = new bool[m];
    auto ndp = new bool[m];
    auto mi = new int[m];
    fill(mi, int.max);
    mi[0] = 0;
    pdp[0] = true;
    foreach (i; 0 .. n)
    {
        fill(ndp, false);
        foreach (j; 0 .. m) if (pdp[j])
        {
            ndp[j] = true;
            if (mi[j] < a[i])
            {
                ndp[j ^ a[i]] = true;
                mi[j ^ a[i]] = min(mi[j ^ a[i]], a[i]);
            }
        }
        ndp.copy(pdp);
    }
    int[] res;
    foreach (i; 0 .. m) if (pdp[i]) res ~= i;
    return res;
}

int main(string[] args)
{
    readln;
    auto a = map!(to!int)(readln.strip.split(" ")).array;
    auto ret = solve(a);
    writeln(ret.length);
    writeln(join(map!(to!string)(ret), " "));
    return 0;
}

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

	auto dp = new long[](2^^9);
	dp[] = long.max;
	dp[0] = 0;
	foreach (i; 0..n)
	{
		auto ndp = dp.dup;
		foreach (j; 0..2^^9)
		{
			if (dp[j] >= a[i]) continue;
			auto nj = j ^ a[i];
			ndp[nj].chmin(a[i]);
			debug writeln("j:", j, " nj:", nj);
		}
		dp = ndp;
		debug
		{
			foreach (j; 0..20)
			{
				if (dp[j])
					write(" ", j);
			}
			writeln;
		}
	}

	long[] ans;
	foreach (i; 0..2^^9)
	{
		if (dp[i] != long.max)
			ans ~= i;
	}

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

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

int[] solve(int[] a)
{
    auto n = to!int(a.length);
    const int m = 512;
    auto pdp = new bool[m];
    auto ndp = new bool[m];
    auto mi = new int[m];
    fill(mi, int.max);
    mi[0] = 0;
    pdp[0] = true;
    foreach (i; 0 .. n)
    {
        fill(ndp, false);
        foreach (j; 0 .. m) if (pdp[j])
        {
            ndp[j] = true;
            if (mi[j] < a[i])
            {
                ndp[j ^ a[i]] = true;
                mi[j ^ a[i]] = min(mi[j ^ a[i]], a[i]);
            }
        }
        ndp.copy(pdp);
    }
    int[] res;
    foreach (i; 0 .. m) if (pdp[i]) res ~= i;
    return res;
}

int main(string[] args)
{
    readln;
    auto a = map!(to!int)(readln.strip.split(" ")).array;
    auto ret = solve(a);
    writeln(join(map!(to!string)(ret), " "));
    return 0;
}


The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:  Operation ++ increases the value of variable x by 1.  Operation -- decreases the value of variable x by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).

The first line contains a single integer n (1 ≤ n ≤ 150) — the number of statements in the programme. Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order.

Print a single integer — the final value of x.

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int x=0;
    int n=readln.chomp.to!int;
    string s;
    while(n--){
        s=readln.strip;
        if(s[0]=='+'||s[2]=='+')
            x++;
        else x--;
    }
    writeln(x);
}

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

void main() {
  readln;

  int ans = 0;

  foreach (string line; stdin.lines) {
    if (!match(line, regex(`\+\+`)).empty) {
      ans++;
    } else {
      ans--;
    }
  }

  ans.writeln;
}

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

void main() {
  immutable n = readln.chomp.to!int;
  immutable p = stdin.byLine.take(n).count! (s => s[1] == '+').to!int;
  writeln (p - (n - p));
}

import std.stdio;
import std.conv:to;
import std.string:chomp, countchars;

void main() {
    int num = to!int(chomp(stdin.readln()));
    int res;
    foreach (a; 0..num) {
        string buf = chomp(stdin.readln());
        res += buf.countchars("+");
    }
    writeln(res-num);
}

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

void main(){
  int X;
  int n = readln.chomp.to!int;
  foreach(i; 0..n){
    if(readln.chomp.find("+").length) X++;
    else X--;
  }
  X.writeln;
}

import std.stdio;
import std.algorithm;

void main()
{
    readln;
    int x;
    foreach(line; stdin.byLine)
    {
        if(line.any!(a => a=='-')) --x;
        else ++x;
    }

    x.writeln;
}

import std.stdio;

void main() {
    int n;
    readf("%d\n", &n);

    int result = 0;
    for (int i = 0; i < n; ++i) {
        string s = readln();

        if (s[0] == '+' || s[1] == '+') {
            result++;
        } else {
            result--;
        }
    }

    writefln("%d", result);
}

import std.stdio, std.string;

void main()
{
    int n, x = 0;

    readf("%s\n", &n);

    while(--n >= 0) {
        string str;
        readf("%s\n", &str);
        if(str.indexOf("+") != -1){ ++x; } else { --x; }
    }

    writeln(x);
}

import std.stdio;
import std.algorithm;

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

	string[] ops;
	for (int i=0; i<count; i++){
		ops ~= readln();
	}

	for (int i=0; i<count; i++){
		if (ops[i].canFind("++")) {
			x++;
		}
		if (ops[i].canFind("--")) {
			x--;
		}
	}

	/* for (int i=0; i<count; i++){ */
	/* 	writeln("$$" ~ ops[i]); */
	/* } */
	writeln(x);
}

import std.stdio;
import std.conv;
import core.stdc.stdio;
import std.string;

int main(string[] argv)
{
	int n;
	string line;
	int x = 0;
	scanf("%d", &n);
	line = std.stdio.stdin.readln();
	for (int i = 0; i < n; i++)
	{
		line = std.stdio.stdin.readln();
		if (indexOf(line, "++") != -1)
		{
			x++;
		} else
		if (indexOf(line, "--") != -1)
		{
			x--;
		}
	}
	printf("%d", x);
	return 0;
}

// https://codeforces.com/problemset/problem/282/A
import std.algorithm;
import std.stdio;

void main() {
    readln;
    int answer = 0;
    foreach(line; stdin.byLine)
        if(canFind(line,"++"))
            answer++;
        else
            answer--;
    answer.writeln;
}

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

void main() {
  immutable n = readln.chomp.to!int;
  immutable p = stdin.byLine.take(n).count! (s => s[1] == '+');
  writeln (p - (n - p));
}

import std.stdio, std.string;

void main()
{
    int n, x = 0;

    readf("%s", &n);

    while(--n >= 0) {
        string str;
        readf("%s\n", &str);
        if(str.indexOf("+") != -1){ ++x; } else { --x; }
    }

    writeln(x);
}

import std.stdio, std.string;

void main()
{
    int n, x = 0;

    stdin.readf("%s", &n);

    while(n > 0) {
        string str;
        readf("%s", &str);
        if(str.indexOf("+") != -1){ ++x; } else { --x; }
        --n;
    }

    write("", x);
}

import std.stdio;
import std.conv;
import core.stdc.stdio;
import std.string;

int main(string[] argv)
{
	int n;
	string line;
	int x = 0;
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		line = readln();
		if (indexOf(line, "++") != -1)
		{
			x++;
		} else
		if (indexOf(line, "--") != -1)
		{
			x--;
		}
	}
	printf("%d", x);
	return 0;
}

// https://codeforces.com/problemset/problem/282/A
import std.algorithm;
import std.stdio;

void main() {
    readln;
    int answer = 0;
    foreach(line; stdin.byLine)
        if(!canFind(line,"++"))
            answer++;
        else
            answer--;
    answer.writeln;
}


Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the only hope of the organizers, so they don't want to work for free: the i-th student wants to get ci 'passes' in his subjects (regardless of the volume of his work).Bugs, like students, are not the same: every bug is characterized by complexity aj, and every student has the level of his abilities bi. Student i can fix a bug j only if the level of his abilities is not less than the complexity of the bug: bi ≥ aj, and he does it in one day. Otherwise, the bug will have to be fixed by another student. Of course, no student can work on a few bugs in one day. All bugs are not dependent on each other, so they can be corrected in any order, and different students can work simultaneously.The university wants to fix all the bugs as quickly as possible, but giving the students the total of not more than s passes. Determine which students to use for that and come up with the schedule of work saying which student should fix which bug.

The first line contains three space-separated integers: n, m and s (1 ≤ n, m ≤ 105, 0 ≤ s ≤ 109) — the number of students, the number of bugs in the system and the maximum number of passes the university is ready to give the students. The next line contains m space-separated integers a1, a2, ..., am (1 ≤ ai ≤ 109) — the bugs' complexities. The next line contains n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ 109) — the levels of the students' abilities. The next line contains n space-separated integers c1, c2, ..., cn (0 ≤ ci ≤ 109) — the numbers of the passes the students want to get for their help.

If the university can't correct all bugs print "NO". Otherwise, on the first line print "YES", and on the next line print m space-separated integers: the i-th of these numbers should equal the number of the student who corrects the i-th bug in the optimal answer. The bugs should be corrected as quickly as possible (you must spend the minimum number of days), and the total given passes mustn't exceed s. If there are multiple optimal answers, you can output any of them.

NoteConsider the first sample.The third student (with level 3) must fix the 2nd and 4th bugs (complexities 3 and 2 correspondingly) and the second student (with level 1) must fix the 1st and 3rd bugs (their complexity also equals 1). Fixing each bug takes one day for each student, so it takes 2 days to fix all bugs (the students can work in parallel).The second student wants 3 passes for his assistance, the third student wants 6 passes. It meets the university's capabilities as it is ready to give at most 9 passes.

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;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto m = next!int;
  auto s = next!int;

  auto a = next!int(m);
  auto b = next!int(n);
  auto c = next!int(n);

  auto sa = a.dup.sort;
  auto rank = iota(0, n).map!(i => cast(int) sa.lowerBound(b[i] + 1).length).array;
  auto stperrank = new int[][](m + 1);
  foreach(i, r; rank) stperrank[r] ~= cast(int) i;
  debug writeln("stperrank ", stperrank);

  bool canInTime(int days, int[] assignment = null)
  {
    if (assignment !is null) assert(assignment.length == m);
    int spend = 0;
    auto sts = redBlackTree!((i, j) => c[i] < c[j], true, int)();
    int lastused = -1;
    int avdays = 0;
    foreach_reverse(i; 0 .. m + 1)
      {
	if (i == 0) break;
	sts.insert(stperrank[i]);
	if (avdays == 0)
	  {
	    if (sts.empty) return false;
	    spend += c[sts.front]; lastused = sts.front; sts.removeFront;
	    if (spend > s) return false;
	    avdays = days;
	  }
	if (assignment !is null) assignment[i - 1] = lastused;
	avdays--;
      }
    return true;
  }

  int l = 1;
  int h = m;
  int lowesttime = int.max;
  while(l <= h)
    {
      int mid = (l + h) / 2;
      auto can = canInTime(mid);
      if (can)
	{
	  lowesttime = mid;
	  h = mid - 1;
	}
      else
	{
	  l = mid + 1;
	}
    }
  if (lowesttime == int.max) return "NO".writeln;
  "YES".writeln;
  auto assignment = new int[](m);
  auto sbugs = iota(0, m).map!(i => tuple(a[i], i)).array.sort;
  auto trueassignment = new int[](m);
  canInTime(lowesttime, assignment);
  foreach(i, as; assignment)
    {
      trueassignment[sbugs[i][1]] = as;
    }
  foreach(ta; trueassignment)
    write(ta + 1, " ");
  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 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;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto m = next!int;
  auto s = next!int;

  auto a = next!int(m);
  auto b = next!int(n);
  auto c = next!int(n);

  auto sa = a.dup.sort;
  auto rank = iota(0, n).map!(i => cast(int) sa.lowerBound(b[i] + 1).length).array;
  auto stperrank = new int[][](m + 1);
  foreach(i, r; rank) stperrank[r] ~= cast(int) i;
  debug writeln("stperrank ", stperrank);

  bool canInTime(int days, int[] assignment = null)
  {
    if (assignment !is null) assert(assignment.length == m);
    int spend = 0;
    auto sts = redBlackTree!((i, j) => c[i] < c[j], true, int)();
    int lastused = -1;
    int avdays = 0;
    foreach_reverse(i; 0 .. m + 1)
      {
	if (i == 0) break;
	sts.insert(stperrank[i]);
	if (avdays == 0)
	  {
	    if (sts.empty) return false;
	    spend += c[sts.front]; lastused = sts.front; sts.removeFront;
	    if (spend > s) return false;
	    avdays = days;
	  }
	if (assignment !is null) assignment[i - 1] = lastused;
	avdays--;
      }
    return true;
  }

  int l = 1;
  int h = m;
  int lowesttime = int.max;
  while(l <= h)
    {
      int mid = (l + h) / 2;
      auto can = canInTime(mid);
      if (can)
	{
	  lowesttime = mid;
	  h = mid - 1;
	}
      else
	{
	  l = mid + 1;
	}
    }
  if (lowesttime == int.max) return "NO".writeln;
  "YES".writeln;
  auto assignment = new int[](m);
  canInTime(lowesttime, assignment);
  foreach(as; assignment)
    write(as + 1, " ");
  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;
    }
}


You have a card deck of $$$n$$$ cards, numbered from top to bottom, i. e. the top card has index $$$1$$$ and bottom card — index $$$n$$$. Each card has its color: the $$$i$$$-th card has color $$$a_i$$$.You should process $$$q$$$ queries. The $$$j$$$-th query is described by integer $$$t_j$$$. For each query you should:   find the highest card in the deck with color $$$t_j$$$, i. e. the card with minimum index;  print the position of the card you found;  take the card and place it on top of the deck.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 3 \cdot 10^5$$$; $$$1 \le q \le 3 \cdot 10^5$$$) — the number of cards in the deck and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 50$$$) — the colors of cards. The third line contains $$$q$$$ integers $$$t_1, t_2, \dots, t_q$$$ ($$$1 \le t_j \le 50$$$) — the query colors. It's guaranteed that queries ask only colors that are present in the deck.

Print $$$q$$$ integers — the answers for each query.

NoteDescription of the sample:   the deck is $$$[2, 1, 1, 4, \underline{3}, 3, 1]$$$ and the first card with color $$$t_1 = 3$$$ has position $$$5$$$;  the deck is $$$[3, \underline{2}, 1, 1, 4, 3, 1]$$$ and the first card with color $$$t_2 = 2$$$ has position $$$2$$$;  the deck is $$$[2, 3, \underline{1}, 1, 4, 3, 1]$$$ and the first card with color $$$t_3 = 1$$$ has position $$$3$$$;  the deck is $$$[\underline{1}, 2, 3, 1, 4, 3, 1]$$$ and the first card with color $$$t_4 = 1$$$ has position $$$1$$$;  the deck is $$$[1, 2, 3, 1, \underline{4}, 3, 1]$$$ and the first card with color $$$t_5 = 4$$$ has position $$$5$$$.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto q = RD!int;
	auto a = RDA(-1);
	auto t = RDA(-1);

	auto pos = new int[](50);
	pos[] = int.max;
	foreach (i; 0..n)
	{
		pos[a[i]].chmin(i);
	}

	auto ans = new int[](q);
	foreach (i; 0..q)
	{
		auto p = pos[t[i]];
		ans[i] = p+1;
		foreach (j; 0..50)
		{
			if (pos[j] < p)
				++pos[j];
		}
		pos[t[i]] = 0;
	}

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


An array is beautiful if both of the following two conditions meet:  there are at least $$$l_1$$$ and at most $$$r_1$$$ elements in the array equal to its minimum;  there are at least $$$l_2$$$ and at most $$$r_2$$$ elements in the array equal to its maximum. For example, the array $$$[2, 3, 2, 4, 4, 3, 2]$$$ has $$$3$$$ elements equal to its minimum ($$$1$$$-st, $$$3$$$-rd and $$$7$$$-th) and $$$2$$$ elements equal to its maximum ($$$4$$$-th and $$$5$$$-th).Another example: the array $$$[42, 42, 42]$$$ has $$$3$$$ elements equal to its minimum and $$$3$$$ elements equal to its maximum.Your task is to calculate the minimum possible number of elements in a beautiful array.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing four integers $$$l_1$$$, $$$r_1$$$, $$$l_2$$$ and $$$r_2$$$ ($$$1 \le l_1 \le r_1 \le 50$$$; $$$1 \le l_2 \le r_2 \le 50$$$).

For each test case, print one integer — the minimum possible number of elements in a beautiful array.

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto L1 = scan!int;
      auto R1 = scan!int;
      auto L2 = scan!int;
      auto R2 = scan!int;

      if (R1 >= L2 && L2 >= L1) {
        return L2;
      }
      if (R2 >= L1 && L1 >= L2) {
        return L1;
      }

      return L1 + L2;
    }

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

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto a = readln.splitter.map !(to !(int)).array;
		int res = a[0] + a[2];
		if (max (a[0], a[2]) <= min (a[1], a[3]))
		{
			res = min (res, max (a[0], a[2]));
		}
		writeln (res);
	}
}


There is a new attraction in Singapore Zoo: The Infinite Zoo.The Infinite Zoo can be represented by a graph with an infinite number of vertices labeled $$$1,2,3,\ldots$$$. There is a directed edge from vertex $$$u$$$ to vertex $$$u+v$$$ if and only if $$$u\&v=v$$$, where $$$\&$$$ denotes the bitwise AND operation. There are no other edges in the graph.Zookeeper has $$$q$$$ queries. In the $$$i$$$-th query she will ask you if she can travel from vertex $$$u_i$$$ to vertex $$$v_i$$$ by going through directed edges.

The first line contains an integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$) — the number of queries. The $$$i$$$-th of the next $$$q$$$ lines will contain two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i < 2^{30}$$$) — a query made by Zookeeper.

For the $$$i$$$-th of the $$$q$$$ queries, output "YES" in a single line if Zookeeper can travel from vertex $$$u_i$$$ to vertex $$$v_i$$$. Otherwise, output "NO". You can print your answer in any case. For example, if the answer is "YES", then the output "Yes" or "yeS" will also be considered as correct answer.

NoteThe subgraph on vertices $$$1,2,3,4,5,6$$$ is shown below.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (qi; 0..q)
	{
		auto u = RD;
		auto v = RD;

		auto uc = popcnt(u);
		auto vc = popcnt(v);
		if (v >= u && vc <= uc)
		{
			int c1, c2;
			bool ok = true;
			foreach (i; 0..32)
			{
				auto bit = 1L << i;
				if (u & bit)
					++c1;
				if (v & bit)
					++c2;
				if (c2 > c1)
					ok = false;
			}
			ans[qi] = ok;
		}
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	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 u, v;
		readf !(" %s %s") (u, v);
		int cur = 0;
		bool ok = (u <= v);
		foreach (d; 0..30)
		{
			auto x = (u >> d) & 1;
			auto y = (v >> d) & 1;
			cur += x - y;
			ok &= (cur >= 0);
		}
		writeln (ok ? "YES" : "NO");
	}
}

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

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

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

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

bool solve(const(long) A, const(long) B) {
  if (!(A <= B)) {
    return false;
  }
  int[] xs, ys;
  foreach (e; 0 .. bsr(A)) if ((A >> e) & 1) xs ~= e;
  foreach (e; 0 .. bsr(B)) if ((B >> e) & 1) ys ~= e;
  const xsLen = cast(int)(xs.length);
  const ysLen = cast(int)(ys.length);
  if (!(xsLen >= ysLen)) {
    return false;
  }
  foreach (i; 0 .. ysLen) {
    if (!(xs[i] <= ys[i])) {
      return false;
    }
  }
  return true;
}

void main() {
  debug {
    enum V = 1 << 8;
    auto d = new bool[][](V, V);
    foreach (u; 1 .. V) {
      d[u][u] = true;
    }
    foreach (u; 1 .. V) {
      foreach (v; 1 .. V - u) {
        if ((u & v) == v) {
          d[u][u + v] = true;
        }
      }
    }
    foreach (w; 1 .. V) foreach (u; 1 .. V) if (d[u][w]) foreach (v; 1 .. V) if (d[w][v]) {
      d[u][v] = true;
    }
    foreach (u; 1 .. V) foreach (v; 1 .. V) {
      const res = solve(u, v);
      assert(d[u][v] == res, format("%s %s: %s %s", u, v, d[u][v], res));
    }
  }

  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const A = readLong();
        const B = readLong();
        const ans = solve(A, B);
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (qi; 0..q)
	{
		auto u = RD!int;
		auto v = RD!int;

		auto uc = popcnt(u);
		auto vc = popcnt(v);
		if (v >= u && vc <= uc)
			ans[qi] = true;
	}

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


A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $$$l$$$ nanoseconds, where $$$l$$$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take $$$2$$$ nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of Dima's sequence. The second line contains string of length $$$n$$$, consisting of characters "(" and ")" only.

Print a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.

NoteIn the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is $$$4 + 2 = 6$$$ nanoseconds.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto s = readln.strip;
		if (s.count ('(') != s.count (')'))
		{
			writeln (-1);
			continue;
		}

		int balance = 0;
		int res = 0;
		foreach (c; s)
		{
			bool ok = (balance >= 0);
			balance += (c == '(') ? +1 : -1;
			ok &= (balance >= 0);
			res += !ok;
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto s = RD!string;
	int l, cnt, ans;
	foreach (i; 0..n)
	{
		if (s[i] == ')')
			--cnt;
		else
		{
			if (cnt == -1)
			{
				ans += i - l + 1;
			}
			++cnt;
		}
		if (cnt == 0)
		{
			l = i+1;
		}
	}
	if (cnt != 0)
		writeln(-1);
	else
		writeln(ans);
	stdout.flush;
	debug readln;
}


As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i).Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?

The first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ n) — the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≤ ai ≤ n). It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.

Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime.

NoteThe first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one.

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

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

    auto conf = new int[][] (n+1);
    auto deny = new int[][] (n+1);
    auto totdeny = 0;
    foreach (i, e; arr) {
        if (e > 0) {
            conf[e] ~= i.to!int;
        } else {
            deny[-e] ~= i.to!int;
            totdeny += 1;
        }
    }

    auto isSuspect = new bool[] (n+1);
    isSuspect[] = false;
    int totSuspects = 0;
    foreach (i; 1 .. n+1) {
        if (conf[i].length + totdeny - deny[i].length == m) {
            isSuspect[i] = true;
            totSuspects += 1;
        }
    }

    auto ans = new int[] (n);
    ans[] = -1;
    if (totSuspects > 0) {
        foreach (i, e; arr) {
            if (e > 0) {
                if (isSuspect[e] && totSuspects == 1) { ans[i] = 1; }
                if (!isSuspect[e]) { ans[i] = 0; }
            } else {
                if (!isSuspect[-e]) { ans[i] = 1; }
                if (isSuspect[-e] && totSuspects == 1) { ans[i] = 0; }
            }
        }
    }

    foreach (e; ans) {
        writeln(e == -1 ? "Not defined" : e == 0 ? "Lie" : "Truth");
    }
}


Egor came up with a new chips puzzle and suggests you to play.The puzzle has the form of a table with $$$n$$$ rows and $$$m$$$ columns, each cell can contain several black or white chips placed in a row. Thus, the state of the cell can be described by a string consisting of characters '0' (a white chip) and '1' (a black chip), possibly empty, and the whole puzzle can be described as a table, where each cell is a string of zeros and ones. The task is to get from one state of the puzzle some other state.To do this, you can use the following operation.  select 2 different cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$: the cells must be in the same row or in the same column of the table, and the string in the cell $$$(x_1, y_1)$$$ must be non-empty;  in one operation you can move the last character of the string at the cell $$$(x_1, y_1)$$$ to the beginning of the string at the cell $$$(x_2, y_2)$$$. Egor came up with two states of the table for you: the initial state and the final one. It is guaranteed that the number of zeros and ones in the tables are the same. Your goal is with several operations get the final state from the initial state. Of course, Egor does not want the number of operations to be very large. Let's denote as $$$s$$$ the number of characters in each of the tables (which are the same). Then you should use no more than $$$4 \cdot s$$$ operations.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n, m \leq 300$$$) — the number of rows and columns of the table, respectively. The following $$$n$$$ lines describe the initial state of the table in the following format: each line contains $$$m$$$ non-empty strings consisting of zeros and ones. In the $$$i$$$-th of these lines, the $$$j$$$-th string is the string written at the cell $$$(i, j)$$$. The rows are enumerated from $$$1$$$ to $$$n$$$, the columns are numerated from $$$1$$$ to $$$m$$$. The following $$$n$$$ lines describe the final state of the table in the same format. Let's denote the total length of strings in the initial state as $$$s$$$. It is guaranteed that $$$s \leq 100\, 000$$$. It is also guaranteed that the numbers of zeros and ones coincide in the initial and final states.

On the first line print $$$q$$$ — the number of operations used. You should find such a solution that $$$0 \leq q \leq 4 \cdot s$$$.  In each the next $$$q$$$ lines print 4 integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$. On the $$$i$$$-th line you should print the description of the $$$i$$$-th operation. These integers should satisfy the conditions $$$1 \leq x_1, x_2 \leq n$$$, $$$1 \leq y_1, y_2 \leq m$$$, $$$(x_1, y_1) \neq (x_2, y_2)$$$, $$$x_1 = x_2$$$ or $$$y_1 = y_2$$$. The string in the cell $$$(x_1, y_1)$$$ should be non-empty. This sequence of operations should transform the initial state of the table to the final one. We can show that a solution exists. If there is more than one solution, find any of them.

NoteConsider the first example.  The current state of the table:00 1001 11The first operation. The cell $$$(2, 1)$$$ contains the string $$$01$$$. Applying the operation to cells $$$(2, 1)$$$ and $$$(1, 1)$$$, we move the $$$1$$$ from the end of the string $$$01$$$ to the beginning of the string $$$00$$$ and get the string $$$100$$$. The current state of the table:100 100   11The second operation. The cell $$$(1, 1)$$$ contains the string $$$100$$$. Applying the operation to cells $$$(1, 1)$$$ and $$$(1, 2)$$$, we move the $$$0$$$ from the end of the string $$$100$$$ to the beginning of the string $$$10$$$ and get the string $$$010$$$. The current state of the table:10 0100  11The third operation. The cell $$$(1, 2)$$$ contains the string $$$010$$$. Applying the operation to cells $$$(1, 2)$$$ and $$$(2, 2)$$$, we move the $$$0$$$ from the end of the string $$$010$$$ to the beginning of the string $$$11$$$ and get the string $$$011$$$. The current state of the table:10 010  011The fourth operation. The cell $$$(2, 2)$$$ contains the string $$$011$$$. Applying the operation to cells $$$(2, 2)$$$ and $$$(2, 1)$$$, we move the $$$1$$$ from the end of the string $$$011$$$ to the beginning of the string $$$0$$$ and get the string $$$10$$$. The current state of the table:10 0110 01 It's easy to see that we have reached the final state of the table.

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

struct Record
{
	int rowA;
	int colA;
	int rowB;
	int colB;
}

Record [] go (int rows, int cols, string [] [] a)
{
	Record [] ans;

	void act (int rowA, int colA, int rowB, int colB)
	{
		ans ~= Record (rowA + 1, colA + 1, rowB + 1, colB + 1);
	}

	auto v0 = new int [] [] (rows, cols);
	auto v1 = new int [] [] (rows, cols);

	void goSquare (int row, int col)
	{
		int dRow0 = 0;
		int dCol0 = (row == dRow0) ? !col : col;
		int dRow1 = rows - 1;
		int dCol1 = (row == dRow1) ? !col : col;
		foreach (c; a[row][col].retro)
		{
			if (c == '0')
			{
				act (row, col, dRow0, dCol0);
				v0[dRow0][dCol0] += 1;
			}
			else
			{
				act (row, col, dRow1, dCol1);
				v1[dRow1][dCol1] += 1;
			}
		}
	}

	foreach (row; 0..rows)
	{
		foreach (col; 0..cols)
		{
			goSquare (row, col);
		}
	}

	foreach (row; 0..rows)
	{
		foreach (col; 0..cols)
		{
			if (row == 0 && col != 0)
			{
				foreach (k0; 0..v0[row][col])
				{
					act (row, col, 0, 0);
				}
			}
			if (row == rows - 1 && col != cols - 1)
			{
				foreach (k1; 0..v1[row][col])
				{
					act (row, col, rows - 1, cols - 1);
				}
			}
		}
	}

	return ans;
}

void main ()
{
	int rows;
	int cols;
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		readln;

		string [] [] a;
		foreach (row; 0..rows)
		{
			a ~= readln.split;
		}

		string [] [] b;
		foreach (row; 0..rows)
		{
			b ~= readln.splitter.map !(s => s.retro.text).array;
		}

		auto lo = go (rows, cols, a);
		auto hi = go (rows, cols, b);

		writeln (lo.length + hi.length);
		foreach (ref e; lo)
		{
			writeln (e.rowA, " ", e.colA, " ",
			    e.rowB, " ", e.colB);
		}
		foreach (ref e; hi.retro)
		{
			writeln (e.rowB, " ", e.colB, " ",
			    e.rowA, " ", e.colA);
		}
	}
}


You are given two arrays $$$a_1, a_2, \dots , a_n$$$ and $$$b_1, b_2, \dots , b_m$$$. Array $$$b$$$ is sorted in ascending order ($$$b_i < b_{i + 1}$$$ for each $$$i$$$ from $$$1$$$ to $$$m - 1$$$).You have to divide the array $$$a$$$ into $$$m$$$ consecutive subarrays so that, for each $$$i$$$ from $$$1$$$ to $$$m$$$, the minimum on the $$$i$$$-th subarray is equal to $$$b_i$$$. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of $$$a$$$ compose the first subarray, the next several elements of $$$a$$$ compose the second subarray, and so on.For example, if $$$a = [12, 10, 20, 20, 25, 30]$$$ and $$$b = [10, 20, 30]$$$ then there are two good partitions of array $$$a$$$:   $$$[12, 10, 20], [20, 25], [30]$$$;  $$$[12, 10], [20, 20, 25], [30]$$$. You have to calculate the number of ways to divide the array $$$a$$$. Since the number can be pretty large print it modulo 998244353.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of arrays $$$a$$$ and $$$b$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. The third line contains $$$m$$$ integers $$$b_1, b_2, \dots , b_m$$$ ($$$1 \le b_i \le 10^9; b_i < b_{i+1}$$$) — the array $$$b$$$.

In only line print one integer — the number of ways to divide the array $$$a$$$ modulo 998244353.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto a = RDA;
	auto b = RDA;
	a.reverse;
	b.reverse;

	auto dp = new long[](m+1);
	dp[0] = 1;
	int ai;
	(){
	foreach (bi; 0..m)
	{
		debug writeln("bi:", bi, " ai:", ai);
		int l = -1;
		while (ai < n)
		{
			if (a[ai] < b[bi])
			{
				if (l == -1) return;
				dp[bi+1] = dp[bi];
				dp[bi+1].modm(ai - l);
				break;
			}
			else if (a[ai] == b[bi])
			{
				if (l == -1)
					l = ai;
			}
			++ai;
		}
		if (ai == n)
		{
			if (l == -1) return;
			dp[bi+1] = dp[bi];
		}
	}}();

	if (ai != n)
		dp[m] = 0;

	debug writeln(dp);

	writeln(dp[m]);
	stdout.flush;
	debug readln;
}


Note: The XOR-sum of set $$$\{s_1,s_2,\ldots,s_m\}$$$ is defined as $$$s_1 \oplus s_2 \oplus \ldots \oplus s_m$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.After almost winning IOI, Victor bought himself an $$$n\times n$$$ grid containing integers in each cell. $$$n$$$ is an even integer. The integer in the cell in the $$$i$$$-th row and $$$j$$$-th column is $$$a_{i,j}$$$.Sadly, Mihai stole the grid from Victor and told him he would return it with only one condition: Victor has to tell Mihai the XOR-sum of all the integers in the whole grid.Victor doesn't remember all the elements of the grid, but he remembers some information about it: For each cell, Victor remembers the XOR-sum of all its neighboring cells.Two cells are considered neighbors if they share an edge — in other words, for some integers $$$1 \le i, j, k, l \le n$$$, the cell in the $$$i$$$-th row and $$$j$$$-th column is a neighbor of the cell in the $$$k$$$-th row and $$$l$$$-th column if $$$|i - k| = 1$$$ and $$$j = l$$$, or if $$$i = k$$$ and $$$|j - l| = 1$$$.To get his grid back, Victor is asking you for your help. Can you use the information Victor remembers to find the XOR-sum of the whole grid?It can be proven that the answer is unique.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single even integer $$$n$$$ ($$$2 \leq n \leq 1000$$$) — the size of the grid. Then follows $$$n$$$ lines, each containing $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th of these lines represents the XOR-sum of the integers in all the neighbors of the cell in the $$$i$$$-th row and $$$j$$$-th column. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$1000$$$ and in the original grid $$$0 \leq a_{i, j} \leq 2^{30} - 1$$$. Hack Format To hack a solution, use the following format: The first line should contain a single integer t ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case should contain a single even integer $$$n$$$ ($$$2 \leq n \leq 1000$$$) — the size of the grid. Then $$$n$$$ lines should follow, each containing $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th of these lines is $$$a_{i,j}$$$ in Victor's original grid. The values in the grid should be integers in the range $$$[0, 2^{30}-1]$$$ The sum of $$$n$$$ over all test cases must not exceed $$$1000$$$.

For each test case, output a single integer — the XOR-sum of the whole grid.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		int [] [] a;
		foreach (row; 0..n)
		{
			a ~= readln.splitter.map !(to !(int)).array;
		}

		auto m = n / 2;
		auto z = new int [m];
		foreach (row; 0..n)
		{
			foreach (col; 0..n)
			{
				int d = min (row, n - 1 - row,
				    col, n - 1 - col);
				z[d] ^= a[row][col];
			}
		}
		foreach_reverse (d; 1..m)
		{
			z[d - 1] ^= z[d];
		}
		foreach (d; 1..m)
		{
			z[d] ^= z[d - 1];
		}

		int x = 0;
		int y = 0;
		foreach (row; 0..n)
		{
			foreach (col; 0..n)
			{
				if (row % 2 == 0 && col % 2 == 0 &&
				    row + col < n)
				{
					x ^= a[row][col];
				}
				if ((n - 1 - row) % 2 == 0 && col % 2 == 0 &&
				    (n - 1 - row) + col < n)
				{
					y ^= a[row][col];
				}
			}
		}

		writeln (x ^ y ^ z.fold !(q{a ^ b}));
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		int [] [] a;
		foreach (row; 0..n)
		{
			a ~= readln.splitter.map !(to !(int)).array;
		}

		auto m = n / 2;
		auto z = new int [m];
		foreach (row; 0..n)
		{
			foreach (col; 0..n)
			{
				int d = min (row, n - 1 - row,
				    col, n - 1 - col);
				z[d] ^= a[row][col];
			}
		}
		foreach (d; 1..m)
		{
			z[d] ^= z[d - 1];
		}

		int x = 0;
		int y = 0;
		foreach (row; 0..n)
		{
			foreach (col; 0..n)
			{
				if (row % 2 == 0 && col % 2 == 0 &&
				    row + col < n)
				{
					x ^= a[row][col];
				}
				if ((n - 1 - row) % 2 == 0 && col % 2 == 0 &&
				    (n - 1 - row) + col < n)
				{
					y ^= a[row][col];
				}
			}
		}

		writeln (x ^ y ^ z.fold !(q{a ^ b}));
	}
}


Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid.Each test case consists of an integer $$$n$$$ and two arrays $$$a$$$ and $$$b$$$, of size $$$n$$$. If after some (possibly zero) operations described below, array $$$a$$$ can be transformed into array $$$b$$$, the input is said to be valid. Otherwise, it is invalid.An operation on array $$$a$$$ is:   select an integer $$$k$$$ $$$(1 \le k \le \lfloor\frac{n}{2}\rfloor)$$$  swap the prefix of length $$$k$$$ with the suffix of length $$$k$$$ For example, if array $$$a$$$ initially is $$$\{1, 2, 3, 4, 5, 6\}$$$, after performing an operation with $$$k = 2$$$, it is transformed into $$$\{5, 6, 3, 4, 1, 2\}$$$.Given the set of test cases, help them determine if each one is valid or invalid.

The first line contains one integer $$$t$$$ $$$(1 \le t \le 500)$$$ — the number of test cases. The description of each test case is as follows. The first line of each test case contains a single integer $$$n$$$ $$$(1 \le n \le 500)$$$ — the size of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — elements of array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le 10^9)$$$ — elements of array $$$b$$$.

For each test case, print "Yes" if the given input is valid. Otherwise print "No". You may print the answer in any case.

NoteFor the first test case, we can swap prefix $$$a[1:1]$$$ with suffix $$$a[2:2]$$$ to get $$$a=[2, 1]$$$.For the second test case, $$$a$$$ is already equal to $$$b$$$.For the third test case, it is impossible since we cannot obtain $$$3$$$ in $$$a$$$.For the fourth test case, we can first swap prefix $$$a[1:1]$$$ with suffix $$$a[4:4]$$$ to obtain $$$a=[2, 2, 3, 1]$$$. Now we can swap prefix $$$a[1:2]$$$ with suffix $$$a[3:4]$$$ to obtain $$$a=[3, 1, 2, 2]$$$.For the fifth test case, it is impossible to convert $$$a$$$ to $$$b$$$.

import std.algorithm, std.conv, std.range, std.stdio, std.string;
alias i = () => readln.strip.to!int, z = () => readln.split.map!(to!int).array;
void main() {
	foreach (t; 0..i()) {
		auto n = i(), a = z(), b = z(), p = a.retro, q = b.retro;
		int [int [2]] x, y;
		foreach (i; 0..n) x[[a[i], p[i]]]++, y[[b[i], q[i]]]++;
		writeln (x == y ? "Yes" : "No");
	}
}

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

void main ()
{
	foreach (test; 0..readln.strip.to !(int))
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		auto ar = a.retro;
		auto br = b.retro;
		int [int [2]] x;
		int [int [2]] y;
		foreach (i; 0..n)
		{
			x[[min (a[i], ar[i]), max (a[i], ar[i])]] += 1;
			y[[min (b[i], br[i]), max (b[i], br[i])]] += 1;
		}
		writeln (x == y ? "Yes" : "No");
	}
}

import std.algorithm, std.conv, std.range, std.stdio, std.string;
void main () {
	foreach (test; 0..readln.strip.to !(int)) {
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		auto ar = a.retro, br = b.retro;
		int [int [2]] x, y;
		foreach (i; 0..n) {
			x[[a[i], ar[i]]] += 1;
			y[[b[i], br[i]]] += 1;
		}
		writeln (x == y ? "Yes" : "No");
	}
}


You have an array of integers (initially empty).You have to perform $$$q$$$ queries. Each query is of one of two types:   "$$$1$$$ $$$x$$$" — add the element $$$x$$$ to the end of the array;  "$$$2$$$ $$$x$$$ $$$y$$$" — replace all occurrences of $$$x$$$ in the array with $$$y$$$. Find the resulting array after performing all the queries.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — the number of queries. Next $$$q$$$ lines contain queries (one per line). Each query is of one of two types:    "$$$1$$$ $$$x$$$" ($$$1 \le x \le 5 \cdot 10^5$$$);  "$$$2$$$ $$$x$$$ $$$y$$$" ($$$1 \le x, y \le 5 \cdot 10^5$$$).  It's guaranteed that there is at least one query of the first type.

In a single line, print $$$k$$$ integers — the resulting array after performing all the queries, where $$$k$$$ is the number of queries of the first type.

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

enum int MAX = 500_000;

class Node(T) {
    Node prev, next;
    T value;
    this(T x) {
        this.value = x;
        this.prev = null;
        this.next = null;
    }
}
struct List(T) {
    Node!T first = null, last = null;
    int len = 0;
    void insert(Node!T n) {
        if (len == 0) {
            first = n;
            last = n;
            n.prev = null;
            n.next = null;
        } else {
            last.next = n;
            n.prev = last;
            last = n;
        }
        len++;
    }
    void insert(List rhs) {
        if (rhs.len == 0) return;
        if (len == 0) {
            first = rhs.first;
            last = rhs.last;
            len = rhs.len;
        } else {
            last.next = rhs.first;
            rhs.first.prev = last;
            last = rhs.last;
            len += rhs.len;
        }
    }
}

void main() {
    int Q; readf("%d\n", &Q);
    auto es = new int[3][Q];
    foreach (q; 0 .. Q) {
        readf("%d", &es[q][0]);
        if (es[q][0] == 1) {
            readf(" %d\n", &es[q][1]);
        } else {
            readf(" %d %d\n", &es[q][1], &es[q][2]);
        }
    }

    auto I = new List!int[MAX+1];
    int k = 0;
    for (int q = 0; q < Q; q++) {
        auto e = es[q];
        if (e[0] == 1) {
            int x = e[1];
            I[x].insert(new Node!int(k++));
        } else {
            int x = e[1];
            int y = e[2];
            if (x == y) continue;
            I[y].insert(I[x]);
            I[x] = List!int();
        }
    }
    int[] A = new int[k];
    for (int x = 0; x <= MAX; x++) {
        auto n = I[x].first;
        while (n !is null) {
            int i = n.value;
            A[i] = x;
            n = n.next;
        }
    }
    writefln("%(%s %)", A);
}

import std;

enum operation:bool { add, map };
union data_t {
    int a;
    struct {
        int x, y;
    }
}

struct query {
    operation t;
    data_t data;
}

int[500_010] ans;

void main () {
    int q;
    readf("%s\n", q);

    query[] vec = new query[q];

    foreach (ref e; vec) {
        char t;
        readf("%s ", t);
        if (t == '1') {
            readf("%s\n", e.data.a);
            e.t = operation.add;
        } else if (t == '2') {
            readf("%s %s\n", e.data.x, e.data.y);
            e.t = operation.map;
        } else
            assert(0);
    }

    foreach (int i, _; ans)
        ans[i] = i;

    int[] ret;
    ret.reserve(q);
    for (int i = q - 1; i > -1; -- i) {
        if (vec[i].t == operation.add)
            ret ~= ans[vec[i].data.a];
        else
            ans[vec[i].data.x] = ans[vec[i].data.y];
    }

    writefln("%(%s %)", ret.retro);
}

// ""

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

void main()
{
  int q;
  readf!" %d "(q);
  int[] a;
  int[][] qlist;
  int[int] subst;
  while (q--) {
    qlist ~= readln.splitter.map!(to!int).array;
  }
  foreach_reverse (req ; qlist) {
    if (req[0] == 1) {
      int val = req[1];
      if (val in subst)
        val = subst[val];
      a ~= val;
    }
    else if (req[0] == 2) {
      if (req[2] in subst)
        req[2] = subst[req[2]];
      subst[req[1]] = req[2];
    }
  }
  writeln(a.retro.map!text.joiner(" "));
}

import std;

enum operation:bool { add, map };
union data_t {
    int a;
    struct {
        int x, y;
    }
}

struct query {
    operation t;
    data_t data;
}

int[500_010] jumpback;
int[500_010] ans;

int
root (in int value) {
    if (jumpback[value] != value)
        jumpback[value] = root(jumpback[value]);
    return jumpback[value];
}

void
map (int what, int to) {
    jumpback[what] = ans[what] = root(to);
}

void main () {
    int q;
    readf("%s\n", q);

    query[] vec = new query[q];

    foreach (ref e; vec) {
        char t;
        readf("%s ", t);
        if (t == '1') {
            readf("%s\n", e.data.a);
            e.t = operation.add;
        } else if (t == '2') {
            readf("%s %s\n", e.data.x, e.data.y);
            e.t = operation.map;
        } else
            assert(0);
    }

    foreach (int i, _; jumpback)
        ans[i] = jumpback[i] = i;

    int[] ret;
    ret.reserve(q);
    for (int i = q - 1; i > -1; -- i) {
        if (vec[i].t == operation.add)
            ret ~= ans[vec[i].data.a];
        else
            map(vec[i].data.x, vec[i].data.y);
    }

    writefln("%(%s %)", ret.retro);
}

// ""

import std;

enum operation:bool { add, map };
union data_t {
    int a;
    struct {
        int x, y;
    }
}

struct query {
    operation t;
    data_t data;
}

int[500_010] jumpback;

int
root (in int value) {
    if (jumpback[value] != value)
        jumpback[value] = root(jumpback[value]);
    return jumpback[value];
}

void
map (int what, int to) {
    jumpback[what] = root(to);
}

void main () {
    int q;
    readf("%s\n", q);

    query[] vec = new query[q];

    foreach (ref e; vec) {
        char t;
        readf("%s ", t);
        if (t == '1') {
            readf("%s\n", e.data.a);
            e.t = operation.add;
        } else if (t == '2') {
            readf("%s %s\n", e.data.x, e.data.y);
            e.t = operation.map;
        } else
            assert(0);
    }

    foreach (int i, _; jumpback)
        jumpback[i] = i;

    int[] ret;
    ret.reserve(q);
    for (int i = q - 1; i > -1; -- i) {
        if (vec[i].t == operation.add)
            ret ~= root(vec[i].data.a);
        else
            map(vec[i].data.x, vec[i].data.y);
    }

    writefln("%(%s %)", ret.retro);
}

// ""


Denis came to Nastya and discovered that she was not happy to see him... There is only one chance that she can become happy. Denis wants to buy all things that Nastya likes so she will certainly agree to talk to him. The map of the city where they live has a lot of squares, some of which are connected by roads. There is exactly one way between each pair of squares which does not visit any vertex twice. It turns out that the graph of the city is a tree.Denis is located at vertex $$$1$$$ at the time $$$0$$$. He wants to visit every vertex at least once and get back as soon as possible.Denis can walk one road in $$$1$$$ time. Unfortunately, the city is so large that it will take a very long time to visit all squares. Therefore, Denis took a desperate step. He pulled out his pocket time machine, which he constructed in his basement. With its help, Denis can change the time to any non-negative time, which is less than the current time.But the time machine has one feature. If the hero finds himself in the same place and at the same time twice, there will be an explosion of universal proportions and Nastya will stay unhappy. Therefore, Denis asks you to find him a route using a time machine that he will get around all squares and will return to the first and at the same time the maximum time in which he visited any square will be minimal.Formally, Denis's route can be represented as a sequence of pairs: $$$\{v_1, t_1\}, \{v_2, t_2\}, \{v_3, t_3\}, \ldots, \{v_k, t_k\}$$$, where $$$v_i$$$ is number of square, and $$$t_i$$$ is time in which the boy is now.The following conditions must be met:  The route starts on square $$$1$$$ at time $$$0$$$, i.e. $$$v_1 = 1, t_1 = 0$$$ and ends on the square $$$1$$$, i.e. $$$v_k = 1$$$.  All transitions are divided into two types:   Being in the square change the time: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \} : v_{i+1} = v_i, 0 \leq t_{i+1} < t_i$$$.  Walk along one of the roads: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \}$$$. Herewith, $$$v_i$$$ and $$$v_{i+1}$$$ are connected by road, and $$$t_{i+1} = t_i + 1$$$   All pairs $$$\{ v_i, t_i \}$$$ must be different.  All squares are among $$$v_1, v_2, \ldots, v_k$$$. You need to find a route such that the maximum time in any square will be minimal, that is, the route for which $$$\max{(t_1, t_2, \ldots, t_k)}$$$ will be the minimum possible.

The first line contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — the number of squares in the city.  The next $$$n - 1$$$ lines contain two integers $$$u$$$ and $$$v$$$ $$$(1 \leq v, u \leq n, u \neq v)$$$ - the numbers of the squares connected by the road.  It is guaranteed that the given graph is a tree.

In the first line output the integer $$$k$$$ $$$(1 \leq k \leq 10^6)$$$  — the length of the path of Denis. In the next $$$k$$$ lines output pairs $$$v_i, t_i$$$  — pairs that describe Denis's route (as in the statement). All route requirements described in the statements must be met. It is guaranteed that under given restrictions there is at least one route and an answer whose length does not exceed $$$10^6$$$. If there are several possible answers, print any.

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[] A, B;

int[][] G;
int T, now;
int[][] ans;

void dfs(int u, int p) {
  debug {
    writeln("dfs ", u, " ", p, "; now = ", now);
  }
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
    }
  }
  const vsLen = cast(int)(vs.length);
  const start = now;
  foreach (j; 0 .. vsLen) {
    if (now == T) {
      assert(p != -1);
      ans ~= [u, now];
      now = start - 1 - (vsLen - j);
    }
    ans ~= [u, now];
    ++now;
    dfs(vs[j], u);
  }
  if (p != -1 && now > start - 1) {
    ans ~= [u, now];
    now = start - 1;
  }
  ans ~= [u, now];
  ++now;
}

void main() {
  try {
    for (; ; ) {
      N = 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;
      }
      T = 0;
      foreach (u; 0 .. N) {
        chmax(T, cast(int)(G[u].length));
      }
      now = 0;
      ans = [];
      dfs(0, -1);
      writeln(ans.length);
      foreach (row; ans) {
        writeln(row[0] + 1, " ", row[1]);
      }
    }
  } catch (EOFException e) {
  }
}