On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.

The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.

Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.

NoteIn the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.

import std.stdio;

void main ()
{
	int n;
	real d;
	real v1;
	real v2;
	int k;
	while (readf (" %s %s %s %s %s", &n, &d, &v1, &v2, &k) > 0)
	{
		int w = (n + k - 1) / k;
		real x = 1.0;
		real y = x * (v2 - v1) / (v2 + v1);
		real z = w * x - (w - 1) * y;
		real mult = d / z;
		real t = (x - y) * (w - 1) / v1 + x / v2;
		t *= mult;
		writefln ("%.10f", t);
	}
}


Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.  Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si = A + (i - 1) × B.For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence sl, sl + 1, ..., sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.

The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 106, 1 ≤ n ≤ 105). Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 106) for i-th query.

For each query, print its answer in a single line.

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

immutable int INF = 10L ^^ 9 + 23;

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

    foreach (_; 0 .. n) {
        int le, t, m;
        readf("%s %s %s", &le, &t, &m);
        readln;

        bool isOk(int md) {
            long lo = (le - 1).to!long * B + A;
            long hgh = (md - 1).to!long * B + A;

            int len = md - le + 1;
            long sm = A.to!long * len + B.to!long * ((le-1 + md-1).to!long * len / 2);

            return hgh <= t && sm <= t.to!long * m;
        }

        int rle = le, rr = le + t;
        while (rle < rr) {
            int md = (rle + rr) / 2 + 1;
            if (isOk(md)) { rle = md; }
            else { rr = md - 1; }
        }

        writeln(isOk(rr) ? rr : -1);
    }
}

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

immutable int INF = 10L ^^ 9 + 23;

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

    foreach (_; 0 .. n) {
        int le, t, m;
        readf("%s %s %s", &le, &t, &m);
        readln;

        bool isOk(int md) {
            long lo = (le - 1).to!long * B + A;
            long hgh = (md - 1).to!long * B + A;

            int len = md - le + 1;
            long sm = A.to!long * len + B.to!long * ((le-1 + md-1).to!long * len / 2);

            return hgh <= t && sm <= t.to!long * m;
        }

        int rle = le, rr = t;
        while (rle < rr) {
            int md = (rle + rr) / 2 + 1;
            if (isOk(md)) { rle = md; }
            else { rr = md - 1; }
        }

        writeln(isOk(rr) ? rr : -1);
    }
}


Ridhiman challenged Ashish to find the maximum valued subsequence of an array $$$a$$$ of size $$$n$$$ consisting of positive integers. The value of a non-empty subsequence of $$$k$$$ elements of $$$a$$$ is defined as $$$\sum 2^i$$$ over all integers $$$i \ge 0$$$ such that at least $$$\max(1, k - 2)$$$ elements of the subsequence have the $$$i$$$-th bit set in their binary representation (value $$$x$$$ has the $$$i$$$-th bit set in its binary representation if $$$\lfloor \frac{x}{2^i} \rfloor \mod 2$$$ is equal to $$$1$$$). Recall that $$$b$$$ is a subsequence of $$$a$$$, if $$$b$$$ can be obtained by deleting some(possibly zero) elements from $$$a$$$.Help Ashish find the maximum value he can get by choosing some subsequence of $$$a$$$.

The first line of the input consists of a single integer $$$n$$$ $$$(1 \le n \le 500)$$$ — the size of $$$a$$$. The next line consists of $$$n$$$ space-separated integers — the elements of the array $$$(1 \le a_i \le 10^{18})$$$.

Print a single integer — the maximum value Ashish can get by choosing some subsequence of $$$a$$$.

NoteFor the first test case, Ashish can pick the subsequence $$$\{{2, 3}\}$$$ of size $$$2$$$. The binary representation of $$$2$$$ is 10 and that of $$$3$$$ is 11. Since $$$\max(k - 2, 1)$$$ is equal to $$$1$$$, the value of the subsequence is $$$2^0 + 2^1$$$ (both $$$2$$$ and $$$3$$$ have $$$1$$$-st bit set in their binary representation and $$$3$$$ has $$$0$$$-th bit set in its binary representation). Note that he could also pick the subsequence $$$\{{3\}}$$$ or $$$\{{2, 1, 3\}}$$$.For the second test case, Ashish can pick the subsequence $$$\{{3, 4\}}$$$ with value $$$7$$$.For the third test case, Ashish can pick the subsequence $$$\{{1\}}$$$ with value $$$1$$$.For the fourth test case, Ashish can pick the subsequence $$$\{{7, 7\}}$$$ with value $$$7$$$.

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 a = readln.splitter.map !(to !(long)).array;
		long res = 0;
		foreach (i; 0..n)
		{
			res = max (res, a[i]);
			foreach (j; 0..n)
			{
				res = max (res, a[i] | a[j]);
				foreach (k; 0..n)
				{
					res = max (res, a[i] | a[j] | a[k]);
				}
			}
		}
		writeln (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;
import std.numeric;
import std.traits;

void main(string[] args)
{
  auto n = next!int;
  auto a = next!long(n);
  long mx = long.min;
  foreach(i; 0 .. n)
    {
      auto ai = a[i];
      foreach(j; i .. n)
	{
	  auto aij = ai | a[j];
	  foreach(k; j .. n)
	    mx = max(mx, aij | a[k]);
	}
    }
  mx.writeln;
}

static this()
{
  popChar;
}

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

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

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

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

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

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


Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $$$n$$$ last days: $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the price of berPhone on the day $$$i$$$.Polycarp considers the price on the day $$$i$$$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $$$n=6$$$ and $$$a=[3, 9, 4, 6, 7, 5]$$$, then the number of days with a bad price is $$$3$$$ — these are days $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) and $$$5$$$ ($$$a_5=7$$$).Print the number of days with a bad price.You have to answer $$$t$$$ independent data sets.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of sets of input data in the test. Input data sets must be processed independently, one after another. Each input data set consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of days. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the price on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ over all data sets in the test does not exceed $$$150000$$$.

Print $$$t$$$ integers, the $$$j$$$-th of which should be equal to the number of days with a bad price in the $$$j$$$-th input data set.

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

string FMT_F = "%.10f";

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; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
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; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * y / gcd(x, y); }

//long mod = 10^^9 + 7;
long mod = 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 main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto b = new long[](n+1);
		b[n] = long.max;
		foreach_reverse (j; 0..n)
		{
			b[j] = min(b[j+1], a[j]);
		}
		long cnt;
		foreach (j; 0..n)
		{
			if (a[j] > b[j+1])
				++cnt;
		}
		ans[i] = cnt;
	}

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


The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.

The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.

In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem.

NoteIn the first sample the best strategy is to delete the second digit. That results in number 112 = 310.In the second sample the best strategy is to delete the third or fourth digits — that results in number 110102 = 2610.

import std.stdio;
import std.string;

int main() {
	auto s = chomp(readln());
	int idx, n = s.length;
	for (int i=0; i<n; i++) {
		if (s[i]!='1') {
			idx = i;
			break;
		}
	}
	writeln(s[0..idx], s[idx+1..$]);
	return 0;
}

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

immutable MN = 100_000;
char[MN+5] s;

int main() {
	scanf("%s", s.ptr);
	int n = strlen(s.ptr);

	auto ms = s[1..n];
	for (int i=1; i<n; i++) {
		auto cur = s[0..i]~s[i+1..n];
		if (ms<cur) ms = cur;
	}

	writeln(ms);

	return 0;
}

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

immutable MN = 100_000;
char[MN+5] s;

int main() {
	scanf("%s", s.ptr);
	int n = strlen(s.ptr);

	char[] ms = s[1..n];
	char[] cur;
	for (int i=1; i<n; i++) {
		cur = s[0..i]~s[i+1..n];
		if (ms<cur) ms = cur;
	}

	writeln(ms);

	return 0;
}

import std.stdio;

char[100_100] s;

int main() {
	scanf("%s", s.ptr);
	int idx = 0;
	while (s[idx]=='1') idx++;
	if (!s[idx]) idx--;
	s[idx] = 0;
	printf("%s%s\n", s.ptr, s.ptr+idx+1);
	return 0;
}

import std.stdio;

char[100_005] s;

int main() {
	scanf("%s", s.ptr);
	int idx = 0;
	while (s[idx]=='1') idx++;
	if (!s[idx]) idx--;
	s[idx] = 0;
	printf("%s%s\n", s.ptr, s.ptr+idx+1);
	return 0;
}

import std.stdio;
import std.string;

int main() {
	auto s = chomp(readln());
	int idx, n = s.length;
	for (int i=0; i<n; i++) {
		if (s[i]!='1') break;
		idx = i;
	}

	auto sol = s[0..idx];
	if (idx<n) sol ~= s[idx+1..n];
	writeln(sol);
	return 0;
}


Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph.So the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops.

The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct. Then q lines follow, i-th line contains one positive integer ni (1 ≤ ni ≤ 2·109) — the number of vertices in i-th graph. Note that in hacks you have to use q = 1.

Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph.

NoteIn the first example it is possible to construct these graphs:  1 - 2, 1 - 3;  1 - 2, 1 - 3, 2 - 4;  1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6.

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;

int q;

void main() {
    scan(q);

    int n;

    while (q--) {
        scan(n);
        solve(n).writeln;
    }
}

long solve(int n) {
    int btm = 2, top = n, mid;

    while (top - btm > 1) {
        mid = btm + (top - btm) / 2;
        long e = 1L * mid * (mid - 1) / 2L;

        (e <= n - mid ? btm : top) = mid;
    }

    long ans = max(n - btm + 1L * btm * (btm - 1) / 2L, 2L * (n - btm - 1));

    return ans;
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;

int q;

void main() {
    scan(q);

    int n;

    while (q--) {
        scan(n);
        solve(n).writeln;
    }
}

long solve(int n) {
    if (n <= 5) {
        return n - 1;
    }

    long btm = 2, top = n - 1, mid;

    while (top - btm > 1) {
        mid = (btm + top) / 2;

        if (n + (mid - 1) * (mid - 2) / 2L <= 2L * (n - 1 - mid)) {
            btm = mid;
        }
        else {
            top = mid;
        }
    }

    return min(n - 1 + btm * (btm - 1) / 2L, 2L * (n - 1 - btm));
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;

int q;

void main() {
    scan(q);

    long n;

    while (q--) {
        scan(n);
        solve(n);
    }
}

void solve(long n) {
    long btm = 0, top = n*n, mid;

    while (top - btm > 1) {
        mid = btm + (top - btm) / 2;

        if (check(n, mid)) {
            btm = mid;
        }
        else {
            top = mid;
        }
    }

    writeln(n - 1 + btm);
}

bool check(long n, long K) {
    long btm = 0, top = K*K, mid;

    while (top - btm > 1) {
        mid = btm + (top - btm) / 2;

        if (K <= mid * (mid + 1) / 2) {
            top = mid;
        }
        else {
            btm = mid;
        }
    }

    long tot = n - 1 + K;
    long bri = n - 1 - (top + 1);

    return 2*bri >= tot;
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers.

First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018).

You have to output q lines, each containing a single integer, the answer to the corresponding query.

NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get:   4 = 1002,  5 = 1012,  6 = 1102,  7 = 1112,  8 = 10002,  9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1.

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

  int[] n;
  auto memo = new long[][][][](11, 64, 1 << 10, 2);
  afill(memo, -1L);
  long f(const int base, int i, bool less, int used, bool zero) {
    if (i < 0) {
      return used == 0 && !zero;
    } else {
      if (less && memo[base][i][used][zero] >= 0) {
        return memo[base][i][used][zero];
      }
      long ret = 0;
      auto digit = less ? base - 1 : n[i];
      for (int d = 0; d <= digit; d++) {
        auto l = less || (d < digit);
        auto z = zero && (d == 0);
        auto u = used ^ (z ? 0 : (1 << d));
        ret += f(base, i - 1, l, u, z);
      }
      if (less) {
        return memo[base][i][used][zero] = ret;
      } else {
        return ret;
      }
    }
  }

  int q;
  rd(q);
  while (q--) {
    int b;
    long l, r;
    rd(b, l, r);
    long res = 0;
    n = digit(r, b).dup;
    res += f(b, (n.length - 1).to!(int), 0, 0, true);
    n = digit(l - 1, b).dup;
    res -= f(b, (n.length - 1).to!(int), 0, 0, true);
    writeln(res);
  }
}

int[] digit(long n, int base) {
  int[] ret;
  do {
    ret ~= n % base;
    n /= base;
  }
  while (n);
  return ret;
}

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

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

void afill(Range, Type)(Range r, Type value) {
  static if (is(typeof(r) == Type[])) {
    foreach (ref elem; r)
      elem = value;
  } else {
    foreach (ref arr; r)
      afill(arr, value);
  }
}

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

  int[] n;
  auto memo = new long[][][][](11, 64, 1 << 10, 2);
  afill(memo, -1L);
  long f(const int base, size_t i, bool less, int used, bool zero) {
    if (i == n.length) {
      return used == 0 && zero;
    } else {
      if (less && zero && memo[base][n.length-i-1][used][zero] >= 0) {
        return memo[base][n.length-i-1][used][zero];
      }
      long ret = 0;
      auto digit = less ? base - 1 : n[i];
      for (int d = 0; d <= digit; d++) {
        auto l = less || (d < digit);
        auto z = zero || (d > 0);
        auto u = !z ? used : (used ^ (1 << d));
        ret += f(base, i + 1, l, u, z);
      }
      if (less && zero) {
        memo[base][n.length-i-1][used][zero] = ret;
      }
      return ret;
    }
  }

  int q;
  rd(q);
  while (q--) {
    int b;
    long l, r;
    rd(b, l, r);
    long res = 0;
    n = digit(r, b).dup;
    res += f(b, 0, 0, 0, 0);
    n = digit(l - 1, b).dup;
    res -= f(b, 0, 0, 0, 0);
    writeln(res);
  }
}

int[] digit(long n, int base) {
  int[] ret;
  do {
    ret = n % base ~ ret;
    n /= base;
  }
  while (n);
  return ret;
}

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

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

void afill(Range, Type)(Range r, Type value) {
  static if (is(typeof(r) == Type[])) {
    foreach (ref elem; r)
      elem = value;
  } else {
    foreach (ref arr; r)
      afill(arr, value);
  }
}

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

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

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

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

enum LIM_B = 10;
enum LIM_L = 100;

void main() {
  auto dp = new long[][][LIM_B + 1];
  foreach (B; 2 .. LIM_B + 1) {
    dp[B] = new long[][](LIM_L + 1, 1 << B);
    dp[B][0][0] = 1;
    foreach (l; 0 .. LIM_L) {
      foreach (p; 0 .. 1 << B) {
        foreach (x; 0 .. B) {
          dp[B][l + 1][p ^ 1 << x] += dp[B][l][p];
        }
      }
    }
  }

  long solve(const(int) B, const(long) N) {
    int[] as;
    for (long n = N; n; n /= B) {
      as ~= cast(int)(n % B);
    }
    as.reverse;
    const asLen = cast(int)(as.length);
    long ans;
    // short
    foreach (l; 1 .. asLen) {
      foreach (x; 1 .. B) {
        ans += dp[B][l - 1][1 << x];
      }
    }
    // as long
    int p;
    foreach (i; 0 .. asLen) {
      foreach (x; 0 .. as[i]) {
        if (i > 0 || x > 0) {
          debug {
            // writeln("  ", B, " ", asLen - 1 - i, " ", p ^ 1 << x, ": ", dp[B][asLen - 1 - i][p ^ 1 << x]);
          }
          ans += dp[B][asLen - 1 - i][p ^ 1 << x];
        }
      }
      p ^= 1 << as[i];
    }
    debug {
      writeln("solve ", B, " ", as, " = ", ans);
    }
    debug {
      long brt;
      foreach (n; 1 .. N) {
        int q;
        for (long nn = n; nn; nn /= B) {
          q ^= 1 << cast(int)(nn % B);
        }
        if (q == 0) {
          ++brt;
        }
      }
      writeln("brt = ", brt);
      assert(brt == ans);
    }
    return ans;
  }

  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const B = readInt();
        const L = readLong();
        const R = readLong();

        long ans;
        ans -= solve(B, L);
        ans += solve(B, R + 1);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

  int[] n;
  auto memo = new long[][][][](11, 64, 1 << 10, 2);
  afill(memo, -1L);
  long f(const int base, int i, bool less, int used, bool zero) {
    if (i < 0) {
      return used == 0 && !zero;
    } else {
      if (less && memo[base][i][used][zero] >= 0) {
        return memo[base][i][used][zero];
      }
      long ret = 0;
      auto digit = less ? base - 1 : n[i];
      for (int d = 0; d <= digit; d++) {
        auto l = less || (d < digit);
        auto z = zero && (d == 0);
        auto u = used ^ (z ? 0 : (1 << d));
        ret += f(base, i - 1, l, u, z);
      }
      return memo[base][i][used][zero] = ret;
    }
  }

  int q;
  rd(q);
  while (q--) {
    int b;
    long l, r;
    rd(b, l, r);
    long res = 0;
    n = digit(r, b).dup;
    res += f(b, (n.length - 1).to!(int), 0, 0, true);
    n = digit(l - 1, b).dup;
    res -= f(b, (n.length - 1).to!(int), 0, 0, true);
    writeln(res);
  }
}

int[] digit(long n, int base) {
  int[] ret;
  do {
    ret ~= n % base;
    n /= base;
  }
  while (n);
  return ret;
}

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

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

void afill(Range, Type)(Range r, Type value) {
  static if (is(typeof(r) == Type[])) {
    foreach (ref elem; r)
      elem = value;
  } else {
    foreach (ref arr; r)
      afill(arr, value);
  }
}

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

  int[] n;
  auto memo = new long[][][][](11, 64, 1 << 10, 2);
  afill(memo, -1L);
  long f(const int base, size_t i, bool less, int used, bool zero) {
    if (i == n.length) {
      return used == 0;
    } else {
      if (less && zero && memo[base][i][used][zero] >= 0) {
        return memo[base][i][used][zero];
      }
      long ret = 0;
      auto digit = less ? base - 1 : n[i];
      for (int d = 0; d <= digit; d++) {
        auto l = less || (d < digit);
        auto z = zero || (d > 0) || (i + 1 == n.length);
        auto u = !z ? used : (used ^ (1 << d));
        auto tmp = ret;
        ret += f(base, i + 1, l, u, z);
      }
      if (less && zero) { // leading zeros抜けるまでは分からないので
        memo[base][i][used][zero] = ret;
      }
      return ret;
    }
  }

  int q;
  rd(q);
  while (q--) {
    int b;
    long l, r;
    rd(b, l, r);
    long res = 0;
    n = digit(r, b).dup;
    res += f(b, 0, 0, 0, 0);
    n = digit(l - 1, b).dup;
    res -= f(b, 0, 0, 0, 0);
    writeln(res);
  }
}

int[] digit(long n, int base) {
  int[] ret;
  do {
    ret = n % base ~ ret;
    n /= base;
  }
  while (n);
  return ret;
}

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

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

void afill(Range, Type)(Range r, Type value) {
  static if (is(typeof(r) == Type[])) {
    foreach (ref elem; r)
      elem = value;
  } else {
    foreach (ref arr; r)
      afill(arr, value);
  }
}

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

  int[] n;
  auto memo = new long[][][][](11, 64, 1 << 10, 2);
  afill(memo, -1L);
  long f(const int base, int i, bool less, int used, bool zero) {
    if (i < 0) {
      return used == 0;
    } else {
      if (less && memo[base][i][used][zero] >= 0) {
        return memo[base][i][used][zero];
      }
      long ret = 0;
      auto digit = less ? base - 1 : n[i];
      for (int d = 0; d <= digit; d++) {
        auto l = less || (d < digit);
        auto z = zero && (d == 0);
        auto u = used ^ (z ? 0 : (1 << d));
        ret += f(base, i - 1, l, u, z);
      }
      return memo[base][i][used][zero] = ret;
    }
  }

  int q;
  rd(q);
  while (q--) {
    int b;
    long l, r;
    rd(b, l, r);
    long res = 0;
    n = digit(r, b).dup;
    res += f(b, (n.length - 1).to!(int), 0, 0, true);
    n = digit(l - 1, b).dup;
    res -= f(b, (n.length - 1).to!(int), 0, 0, true);
    writeln(res);
  }
}

int[] digit(long n, int base) {
  int[] ret;
  do {
    ret ~= n % base;
    n /= base;
  }
  while (n);
  return ret;
}

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

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

void afill(Range, Type)(Range r, Type value) {
  static if (is(typeof(r) == Type[])) {
    foreach (ref elem; r)
      elem = value;
  } else {
    foreach (ref arr; r)
      afill(arr, value);
  }
}

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

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

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

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

enum LIM_B = 10;
enum LIM_L = 100;

void main() {
  auto dp = new long[][][LIM_B + 1];
  foreach (B; 2 .. LIM_B + 1) {
    dp[B] = new long[][](LIM_L + 1, 1 << B);
    dp[B][0][0] = 1;
    foreach (l; 0 .. LIM_L) {
      foreach (p; 0 .. 1 << B) {
        foreach (x; 0 .. B) {
          dp[B][l + 1][p ^ 1 << x] += dp[B][l][p];
        }
      }
    }
  }

  long solve(const(int) B, const(long) N) {
    int[] as;
    for (long n = N; n; n /= B) {
      as ~= cast(int)(n % B);
    }
    as.reverse;
    const asLen = cast(int)(as.length);
    long ans;
    // short
    foreach (l; 1 .. asLen) {
      foreach (x; 1 .. B) {
        ans += dp[B][l - 1][1 << x];
      }
    }
    // as long
    int p;
    foreach (i; 0 .. asLen) {
      foreach (x; 0 .. as[i]) {
        if (i > 0 || x > 0) {
          debug {
            writeln("  ", B, " ", asLen - 1 - i, " ", p ^ 1 << x, ": ", dp[B][asLen - 1 - i][p ^ 1 << x]);
          }
          ans += dp[B][asLen - 1 - i][p ^ 1 << x];
        }
      }
      p ^= 1 << as[i];
    }
    debug {
      writeln("solve ", B, " ", as, " = ", ans);
    }
    return ans;
  }

  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const B = readInt();
        const L = readLong();
        const R = readLong();

        long ans;
        ans -= solve(B, L + 1);
        ans += solve(B, R + 1);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


Sam is a kindergartener, and there are $$$n$$$ children in his group. He decided to create a team with some of his children to play "brawl:go 2".Sam has $$$n$$$ power-ups, the $$$i$$$-th has type $$$a_i$$$. A child's strength is equal to the number of different types among power-ups he has.For a team of size $$$k$$$, Sam will distribute all $$$n$$$ power-ups to $$$k$$$ children in such a way that each of the $$$k$$$ children receives at least one power-up, and each power-up is given to someone.For each integer $$$k$$$ from $$$1$$$ to $$$n$$$, find the minimum sum of strengths of a team of $$$k$$$ children Sam can get.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$).  The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — types of Sam's power-ups. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For every test case print $$$n$$$ integers. The $$$k$$$-th integer should be equal to the minimum sum of strengths of children in the team of size $$$k$$$ that Sam can get.

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!long;
      auto A = scan!long(N);

      auto uniqSize = A.sort.uniq.array.length;
      return N.iota.map!(k => max(k + 1, uniqSize)).toAnswerString;
    }

    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.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

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

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

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

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

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

		bool[long] set;
		foreach (i; 0..n)
			set[a[i]] = true;

		auto cnt = cast(int)set.length;
		ans[ti].length = n;
		foreach (i; 0..n)
		{
			auto k = i + 1;
			ans[ti][i] = k + max(0, cnt - k);
		}
	}

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


You have $$$n$$$ rectangles, the $$$i$$$-th rectangle has height $$$h_i$$$ and width $$$w_i$$$.You are asked $$$q$$$ queries of the form $$$h_s \ w_s \ h_b \ w_b$$$. For each query output, the total area of rectangles you own that can fit a rectangle of height $$$h_s$$$ and width $$$w_s$$$ while also fitting in a rectangle of height $$$h_b$$$ and width $$$w_b$$$. In other words, print $$$\sum h_i \cdot w_i$$$ for $$$i$$$ such that $$$h_s < h_i < h_b$$$ and $$$w_s < w_i < w_b$$$. Please note, that if two rectangles have the same height or the same width, then they cannot fit inside each other. Also note that you cannot rotate rectangles.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case two integers $$$n, q$$$ ($$$1 \leq n \leq 10^5$$$; $$$1 \leq q \leq 10^5$$$) — the number of rectangles you own and the number of queries. Then $$$n$$$ lines follow, each containing two integers $$$h_i, w_i$$$ ($$$1 \leq h_i, w_i \leq 1000$$$) — the height and width of the $$$i$$$-th rectangle. Then $$$q$$$ lines follow, each containing four integers $$$h_s, w_s, h_b, w_b$$$ ($$$1 \leq h_s < h_b,\ w_s < w_b \leq 1000$$$) — the description of each query. The sum of $$$q$$$ over all test cases does not exceed $$$10^5$$$, and the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output $$$q$$$ lines, the $$$i$$$-th line containing the answer to the $$$i$$$-th query.

Note  In the first test case, there is only one query. We need to find the sum of areas of all rectangles that can fit a $$$1 \times 1$$$ rectangle inside of it and fit into a $$$3 \times 4$$$ rectangle.Only the $$$2 \times 3$$$ rectangle works, because $$$1 < 2$$$ (comparing heights) and $$$1 < 3$$$ (comparing widths), so the $$$1 \times 1$$$ rectangle fits inside, and $$$2 < 3$$$ (comparing heights) and $$$3 < 4$$$ (comparing widths), so it fits inside the $$$3 \times 4$$$ rectangle. The $$$3 \times 2$$$ rectangle is too tall to fit in a $$$3 \times 4$$$ rectangle. The total area is $$$2 \cdot 3 = 6$$$.

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

void solve() {
    int N, Q; readf("%d %d\n", &N, &Q);
    int L = 1001;
    auto F = new long[][](1001, 1001);
    auto S = new long[][](1002, 1002);
    foreach (i; 0 .. N) {
        int H, W; readf("%d %d\n", &H, &W);
        F[H][W] += H * W;
    }
    for (int i = 0; i < L; i++) {
        for (int j = 0; j < L; j++) {
            S[i + 1][j + 1] = F[i][j] + S[i][j + 1] + S[i + 1][j] - S[i][j];
        }
    }
    foreach (q; 0 .. Q) {
        int hs, ws, hb, wb; readf("%d %d %d %d\n", &hs, &ws, &hb, &wb);
        writeln(S[hb][wb] - S[hb][ws + 1] - S[hs + 1][wb] + S[hs + 1][ws + 1]);
    }
}

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


There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.

The first line contains two positive space-separated integers, n and k (1 ≤ k ≤ n ≤ 2·105) — the initial number of cities in Westeros and the number of cities at which the game ends.  The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 106), which represent the population of each city in Westeros.

Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.

NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins.

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

bool solve (int n, int k, int even, int odd)
{
	int moves = n - k;
	int dmoves = moves / 2;
	int smoves = moves - dmoves;
	if (n == k)
	{
		return odd % 2 == 0;
	}
	if (odd <= dmoves)
	{
		return true;
	}
	if (even <= smoves && k % 2 == 1)
	{
		return false;
	}
	if (even <= dmoves && k % 2 == 0)
	{
		return true;
	}
	if (even == 0)
	{
		return k % 2 == 0;
	}
	return dmoves >= smoves;
}

void main ()
{
	int n, k;
	while (readf (" %s %s ", &n, &k) > 0)
	{
		auto a = readln.split.map !(to !(int)).array;
		int even = a.count !(q{a % 2 == 0});
		int odd = a.count !(q{a % 2 == 1});
		debug {writeln (a, ' ', even, ' ', odd);}
		writeln (solve (n, k, even, odd) ? "Daenerys" : "Stannis");
	}
}

import std.stdio;
import std.string;
import std.array;
import std.functional;
import std.algorithm;
import std.container;
import std.conv;
import std.random;

const int maxn = 100;
int n, a, b, k, fm; // a -- even, b -- odd, fm -- final turn player
int data[maxn][maxn];

void input() {
	readf("%s %s", &n, &k);
	for (int i = 0; i < n; ++i) {
		int t;
		readf(" %s", &t);
		if (t % 2) ++b; else ++a;
	}
	fm = (n - k) % 2;
}

int solve() {
	for (int chet = 0; chet < maxn; ++chet)
		for (int nech = 0; nech < maxn; ++nech) {
			if (chet + nech <= k)
				data[chet][nech] = nech % 2;
			else {
				int cp = fm ^ 1 ^ ((chet + nech - k) % 2);
				if (cp == 0) {
					data[chet][nech] = 1;
					if (chet) data[chet][nech] &= data[chet - 1][nech];
					if (nech) data[chet][nech] &= data[chet][nech - 1];
				} else {
					data[chet][nech] = 0;
					if (chet) data[chet][nech] |= data[chet - 1][nech];
					if (nech) data[chet][nech] |= data[chet][nech - 1];
				}
			}
		}
	return data[a][b];
}

int megasolve() {
	if (a < maxn && b < maxn && k < maxn)
		return solve();
	if (n == k)
		return b % 2;
	if (k % 2 == 0 && fm == 0)
		return 0;
	if (k % 2 == 1 && fm == 0)
		return b - a >= k;
	if (k % 2 == 0 && fm == 1)
		return (b - a < k) && (a - b < k);
	return a - b < k;
}

void main() {
	input();
	writeln(megasolve() ? "Stannis" : "Daenerys");
}

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

bool solve (int n, int k, int even, int odd)
{
	int moves = n - k;
	int dmoves = moves / 2;
	int smoves = moves - dmoves;
	if (odd <= dmoves)
	{
		return true;
	}
	if (even <= smoves && k % 2 == 1)
	{
		return false;
	}
	if (even <= dmoves && k % 2 == 0)
	{
		return true;
	}
	if (even == 0)
	{
		return k % 2 == 0;
	}
	return dmoves >= smoves;
}

void main ()
{
	int n, k;
	while (readf (" %s %s ", &n, &k) > 0)
	{
		auto a = readln.split.map !(to !(int)).array;
		int even = a.count !(q{a % 2 == 0});
		int odd = a.count !(q{a % 2 == 1});
		debug {writeln (a, ' ', even, ' ', odd);}
		writeln (solve (n, k, even, odd) ? "Daenerys" : "Stannis");
	}
}


This is an interactive problem.Bob lives in a square grid of size $$$n \times n$$$, with rows numbered $$$1$$$ through $$$n$$$ from top to bottom, and columns numbered $$$1$$$ through $$$n$$$ from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer $$$n$$$.Bob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move down or right to an adjacent cell, if it is allowed.You can ask at most $$$4 \cdot n$$$ queries of form "? $$$r_1$$$ $$$c_1$$$ $$$r_2$$$ $$$c_2$$$" ($$$1 \le r_1 \le r_2 \le n$$$, $$$1 \le c_1 \le c_2 \le n$$$). The answer will be "YES" if Bob can get from a cell $$$(r_1, c_1)$$$ to a cell $$$(r_2, c_2)$$$, and "NO" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is "NO" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least $$$n - 1$$$, i.e. the following condition must be satisfied: $$$(r_2 - r_1) + (c_2 - c_1) \ge n - 1$$$.It's guaranteed that Bob can get from the top-left corner $$$(1, 1)$$$ to the bottom-right corner $$$(n, n)$$$ and your task is to find a way to do it. You should print the answer in form "! S" where $$$S$$$ is a string of length $$$2 \cdot n - 2$$$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by $$$1$$$, the right move increases the second coordinate by $$$1$$$. If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution.

The only line of the input contains an integer $$$n$$$ ($$$2 \le n \le 500$$$) — the size of the grid.

When you are ready to print the answer, print a single line containing "! S" where where $$$S$$$ is a string of length $$$2 \cdot n - 2$$$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The path should be a valid path going from the cell $$$(1, 1)$$$ to the cell $$$(n, n)$$$ passing only through allowed cells.

NoteThe first example is shown on the picture below.  To hack, use the following input format:The first line should contain a single integer $$$n$$$ ($$$2 \le n \le 500$$$) — the size of the grid.Each of the next $$$n$$$ lines should contain a string of $$$n$$$ characters '#' or '.', where '#' denotes a blocked cell, and '.' denotes an allowed cell.For example, the following text encodes the example shown above:4..#.#...###.....

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

immutable int INF = 1 << 29;

bool ask(int r1, int c1, int r2, int c2) {
    if (r1 > r2 && c2 > c1) return false;
    if (r2 > r1 && c1 > c2) return false;
    if (r1 > r2 || c1 > c2) swap(r1, r2), swap(c1, c2);
    writeln("? ", r1+1, " ", c1+1, " ", r2+1, " ", c2+1);
    stdout.flush;
    return readln.chomp == "YES";
}

int dist(int r1, int c1, int r2, int c2) {
    return abs(r1 - r2) + abs(c1 - c2);
}

void main() {
    auto N = readln.chomp.to!int;
    Tuple!(int, int)[] ans = [tuple(0, 0)];
    Tuple!(int, int)[] ans2 = [tuple(N-1, N-1)];

    for (int r = 0, c = 0; dist(r, c, N-1, N-1) >= N; ) {
        if (ask(r+1, c, N-1, N-1)) {
            ++r;
        } else {
            ++c;
        }
        ans ~= tuple(r, c);
    }

    for (int r = N-1, c = N-1, p = ans.length.to!int-2; r != ans.back[0] || c != ans.back[1]; --p) {
        if (r == ans.back[0]) {
            --c;
        } else if (c == ans.back[1]) {
            --r;
        } else if (ask(r, c-1, ans[p][0], ans[p][1])) {
            --c;
        } else {
            --r;
        }
        ans2 ~= tuple(r, c);
    }

    ans2.reverse;
    ans = ans ~ ans2;
    string ans_s = "! ";

    foreach (i; 0..ans.length.to!int-1) {
        int r1 = ans[i][0];
        int c1 = ans[i][1];
        int r2 = ans[i+1][0];
        int c2 = ans[i+1][1];
        if (r1 == r2 && c1 == c2) continue;
        if (r1 != r2) ans_s ~= "D";
        else ans_s ~= "R";
    }

    writeln(ans_s);
    stdout.flush;
}

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

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

    auto currw = 1, curcol = 1;
    dchar[] anspref;
    foreach (_; 0 .. n-1) {
        writeln(format("? %s %s %s %s", currw, curcol+1, n, n));
        stdout.flush();

        auto msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anspref ~= 'R';
            curcol += 1;
        } else {
            anspref ~= 'D';
            currw += 1;
        }
    }

    dchar[] anssuf;
    currw = n, curcol = n;
    foreach (_; 0 .. n-1) {
        writeln(format("? 1 1 %s %s", currw-1, curcol));
        stdout.flush();

        auto msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anssuf ~= 'D';
            currw -= 1;
        } else {
            anssuf ~= 'R';
            curcol -= 1;
        }
    }
    reverse(anssuf);

    auto ans = anspref ~ anssuf;

    writeln("! ", ans);
    stdout.flush();
}

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

bool ask (int row1, int col1, int row2, int col2)
{
	writeln ("? ", row1, " ", col1, " ", row2, " ", col2);
	stdout.flush ();
	auto res = readln.strip;
	return (res == "YES");
}

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

		int [2] [] a;
		{
			int row1 = 1;
			int col1 = 1;
			int row2 = n;
			int col2 = n;
			a ~= [row1, col1];
			foreach (step; 0..n - 1)
			{
				row1 += 1;
				if (!ask (row1, col1, row2, col2))
				{
					row1 -= 1;
					col1 += 1;
				}
				a ~= [row1, col1];
			}
		}

		int [2] [] b;
		{
			int row1 = 1;
			int col1 = 1;
			int row2 = n;
			int col2 = n;
			b ~= [row2, col2];
			foreach (step; 0..n - 1)
			{
				col2 -= 1;
				if (!ask (row1, col1, row2, col2))
				{
					col2 += 1;
					row2 -= 1;
				}
				b ~= [row2, col2];
			}
		}

		assert (a.back == b.back);
		auto c = a ~ b.retro.drop (1).array;
		write ("! ");
		foreach (i; 1..c.length)
		{
			write ((c[i][0] == c[i - 1][0]) ? 'R' : 'D');
		}
		writeln;
		stdout.flush ();
	}
}

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

struct seg
{
    int l = int.max;
    int r;
}

bool ask(int r, int c, int r1, int c1)
{
    writefln("? %d %d %d %d", r, c, r1, c1);
    stdout.flush;
    return "YES" == readln.chomp;
}

void main()
{
    int n;
    readf("%d\n", &n);
    bool[] a;
    a.length = 2 * n - 2;
    int r = 1, c = 1;
    foreach (i; 0..n - 1) {
        ++r;
        a[i] = ask(r, c, n, n);
        if (!a[i]) {
            --r;
            ++c;
        }
    }
    r = c = n;
    foreach (i; 1..n) {
        --c;
        a[$ - i] = !ask(1, 1, r, c);
        if (a[$ - i]) {
            ++c;
            --r;
        }
    }
    write("! ");
    foreach (down; a) {
        write(down ? 'D' : 'R');
    }
    writeln;
    stdout.flush;
}

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.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;
debug {
  string[] A;
}

bool Ask(int x0, int y0, int x1, int y1) {
  assert((x1 - x0) + (y1 - y0) >= N - 1);
  bool ret;
  debug {
    if (A[x0][y0] == '.' && A[x1][y1] == '.') {
      auto dp = new bool[][](N, N);
      dp[x0][y0] = true;
      foreach (x; 0 .. N) foreach (y; 0 .. N) {
        if (dp[x][y]) {
          if (x + 1 < N && A[x + 1][y] == '.') {
            dp[x + 1][y] = true;
          }
          if (y + 1 < N && A[x][y + 1] == '.') {
            dp[x][y + 1] = true;
          }
        }
      }
      ret = dp[x1][y1];
      writefln("Ask %s %s %s %s = %s", x0, y0, x1, y1, ret);
    } else {
      ret = false;
    }
  } else {
    writefln("? %s %s %s %s", x0 + 1, y0 + 1, x1 + 1, y1 + 1);
    stdout.flush;
    ret = (readToken() == "YES");
  }
  return ret;
}

void main() {
  N = readInt();
  debug {
    A = new string[N];
    foreach (x; 0 .. N) {
      A[x] = readToken();
    }
  }

  auto diagS = new bool[N];
  auto diagT = new bool[N];
  foreach (x; 0 .. N) {
    diagS[x] = Ask(0, 0, x, N - 1 - x);
    diagT[x] = Ask(x, N - 1 - x, N - 1, N - 1);
  }
  int xm = -1;
  foreach (x; 0 .. N) {
    if (diagS[x] && diagT[x]) {
      xm = x;
      break;
    }
  }
  debug {
    writeln("diagS = ", diagS);
    writeln("diagT = ", diagT);
    writeln("xm = ", xm);
  }

  string ansS, ansT;
  for (int x = 0, y = 0; !(x == xm && y == N - 1 - xm); ) {
    if (y + 1 <= N - 1 - xm && Ask(x, y + 1, N - 1, N - 1)) {
      ++y;
      ansS = ansS ~ 'R';
    } else {
      ++x;
      ansS = ansS ~ 'D';
    }
  }
  for (int x = N - 1, y = N - 1; !(x == xm && y == N - 1 - xm); ) {
    if (x - 1 >= xm && Ask(0, 0, x - 1, y)) {
      --x;
      ansT = 'D' ~ ansT;
    } else {
      --y;
      ansT = 'R' ~ ansT;
    }
  }

  writefln("! %s%s", ansS, ansT);
  stdout.flush;
}

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

immutable int INF = 1 << 29;

bool ask(int r1, int c1, int r2, int c2) {
    if (r1 > r2 && c2 > c1) return false;
    if (r2 > r1 && c1 > c2) return false;
    if (r1 > r2 || c1 > c2) swap(r1, r2), swap(c1, c2);
    writeln("? ", r1+1, " ", c1+1, " ", r2+1, " ", c2+1);
    stdout.flush;
    return readln.chomp == "YES";
}

int dist(int r1, int c1, int r2, int c2) {
    return abs(r1 - r2) + abs(c1 - c2);
}

void main() {
    auto N = readln.chomp.to!int;
    Tuple!(int, int)[] ans = [tuple(0, 0)];
    Tuple!(int, int)[] ans2 = [tuple(N-1, N-1)];

    for (int r = 0, c = 0; dist(r, c, N-1, N-1) >= N; ) {
        if (ask(r+1, c, N-1, N-1)) {
            ++r;
        } else {
            ++c;
        }
        ans ~= tuple(r, c);
    }

    for (int r = N-1, c = N-1, p = ans.length.to!int-2; r != ans.back[0] || c != ans.back[1]; --p) {
        if (r == ans.back[0]) {
            --c;
        } else if (c == ans.back[1]) {
            --r;
        } else if (ask(r-1, c, ans[p][0], ans[p][1])) {
            --r;
        } else {
            --c;
        }
        ans2 ~= tuple(r, c);
    }

    ans2.reverse;
    ans = ans ~ ans2;
    string ans_s = "! ";

    foreach (i; 0..ans.length.to!int-1) {
        int r1 = ans[i][0];
        int c1 = ans[i][1];
        int r2 = ans[i+1][0];
        int c2 = ans[i+1][1];
        if (r1 == r2 && c1 == c2) continue;
        if (r1 != r2) ans_s ~= "D";
        else ans_s ~= "R";
    }

    writeln(ans_s);
    stdout.flush;
}

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

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

    int rw = 1;
    foreach (x; 1 .. n+1) {
        writeln(format("? 1 1 %s %s", x, n+1 - x));
        stdout.flush();

        auto msg1 = readln.chomp;

        if (msg1 == "BAD") return;

        writeln(format("? %s %s %s %s", x, n+1 - x, n, n));
        stdout.flush();

        auto msg2 = readln.chomp;

        if (msg2 == "BAD") return;

        if (msg1 == "YES" && msg2 == "YES") {
            rw = x;
            break;
        }
    }

    dchar[] anssuf;
    int currw = rw, curcol = n+1 - rw;
    foreach (_; 0 .. n-1) {
        if (curcol + 1 > n) {
            anssuf ~= 'D';
            continue;
        }

        writeln(format("? 1 1 %s %s", currw, curcol+1));
        stdout.flush();

        auto msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anssuf ~= 'R';
            curcol += 1;
        } else {
            anssuf ~= 'D';
            currw += 1;
        }
    }

    currw = rw, curcol = n+1 - rw;
    dchar[] anspref;
    foreach (_; 0 .. n-1) {
        if (currw == 1) {
            anspref ~= 'R';
            continue;
        }

        writeln(format("? %s %s %s %s", currw-1, curcol, n, n));
        stdout.flush();

        auto msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anspref ~= 'D';
            currw -= 1;
        } else {
            anspref ~= 'R';
            curcol -= 1;
        }
    }
    reverse(anspref);

    auto ans = anspref ~ anssuf;

    writeln("! ", ans);
    stdout.flush();
}

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

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

    string msg;
    int rw = 1;
    foreach (x; 1 .. n+1) {
        writeln(format("? 1 1 %s %s", x, n+1 - x));
        stdout.flush();

        msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            rw = x;
            break;
        }
    }

    dchar[] anssuf;
    int currw = rw, curcol = n+1 - rw;
    foreach (_; 0 .. n-1) {
        if (currw + 1 > n) {
            anssuf ~= 'R';
            continue;
        }

        writeln(format("? 1 1 %s %s", currw+1, curcol));
        stdout.flush();

        msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anssuf ~= 'D';
            currw += 1;
        } else {
            anssuf ~= 'R';
            curcol += 1;
        }
    }

    currw = rw, curcol = n+1 - rw;
    dchar[] anspref;
    foreach (_; 0 .. n-1) {
        if (currw == 1) {
            anspref ~= 'R';
            continue;
        }

        writeln(format("? %s %s %s %s", currw-1, curcol, n, n));
        stdout.flush();

        msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anspref ~= 'D';
            currw -= 1;
        } else {
            anspref ~= 'R';
            curcol -= 1;
        }
    }
    reverse(anspref);

    auto ans = anspref ~ anssuf;

    writeln("! ", ans);
    stdout.flush();
}

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

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

    string msg;
    int rw = 1;
    foreach (x; 1 .. n+1) {
        writeln(format("? 1 1 %s %s", x, n+1 - x));
        stdout.flush();

        msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            rw = x;
            break;
        }
    }

    dchar[] anssuf;
    int currw = rw, curcol = n+1 - rw;
    foreach (_; 0 .. n-1) {
        if (currw + 1 > n) {
            anssuf ~= 'R';
            continue;
        }

        writeln(format("? 1 1 %s %s", currw+1, curcol));
        stdout.flush();

        msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anssuf ~= 'D';
            currw += 1;
        } else {
            anssuf ~= 'R';
            curcol += 1;
        }
    }

    currw = rw, curcol = n+1 - rw;
    dchar[] anspref;
    foreach (_; 0 .. n-1) {
        if (currw == 1) {
            anspref ~= 'R';
            continue;
        }

        writeln(format("? %s %s %s %s", currw-1, curcol, n, n));
        stdout.flush();

        msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anspref ~= 'D';
            currw -= 1;
        } else {
            anspref ~= 'R';
            curcol -= 1;
        }
    }
    reverse(anspref);

    auto ans = anspref ~ anssuf;

    ans.writeln;
}

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

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

    int rw = 1;
    foreach (x; 1 .. n+1) {
        writeln(format("? 1 1 %s %s", x, n+1 - x));
        stdout.flush();

        auto msg1 = readln.chomp;

        if (msg1 == "BAD") return;

        writeln(format("? %s %s %s %s", x, n+1 - x, n, n));
        stdout.flush();

        auto msg2 = readln.chomp;

        if (msg2 == "BAD") return;

        if (msg1 == "YES" && msg2 == "YES") {
            rw = x;
            break;
        }
    }

    dchar[] anssuf;
    int currw = rw, curcol = n+1 - rw;
    foreach (_; 0 .. n-1) {
        if (currw + 1 > n) {
            anssuf ~= 'R';
            continue;
        }

        writeln(format("? 1 1 %s %s", currw+1, curcol));
        stdout.flush();

        auto msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anssuf ~= 'D';
            currw += 1;
        } else {
            anssuf ~= 'R';
            curcol += 1;
        }
    }

    currw = rw, curcol = n+1 - rw;
    dchar[] anspref;
    foreach (_; 0 .. n-1) {
        if (curcol == 1) {
            anspref ~= 'D';
            continue;
        }

        writeln(format("? %s %s %s %s", currw, curcol-1, n, n));
        stdout.flush();

        auto msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anspref ~= 'R';
            curcol -= 1;
        } else {
            anspref ~= 'D';
            currw -= 1;
        }
    }
    reverse(anspref);

    auto ans = anspref ~ anssuf;

    writeln("! ", ans);
    stdout.flush();
}

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

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

    auto currw = 1, curcol = 1;
    dchar[] anspref;
    foreach (_; 0 .. n-1) {
        writeln(format("? %s %s %s %s", currw, curcol+1, n, n));
        stdout.flush();

        auto msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anspref ~= 'R';
            curcol -= 1;
        } else {
            anspref ~= 'D';
            currw -= 1;
        }
    }

    dchar[] anssuf;
    currw = n, curcol = n;
    foreach (_; 0 .. n-1) {
        writeln(format("? 1 1 %s %s", currw-1, curcol));
        stdout.flush();

        auto msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anssuf ~= 'D';
            currw += 1;
        } else {
            anssuf ~= 'R';
            curcol += 1;
        }
    }
    reverse(anssuf);

    auto ans = anspref ~ anssuf;

    writeln("! ", ans);
    stdout.flush();
}

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

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

    string msg;
    int rw = 1;
    foreach (x; 1 .. n+1) {
        writeln(format("? 1 1 %s %s", x, n+1 - x));
        stdout.flush();

        auto msg1 = readln.chomp;

        if (msg1 == "BAD") return;

        writeln(format("? %s %s %s %s", x, n+1 - x, n, n));
        stdout.flush();

        auto msg2 = readln.chomp;

        if (msg2 == "BAD") return;

        if (msg1 == "YES" && msg2 == "YES") {
            rw = x;
            break;
        }
    }

    dchar[] anssuf;
    int currw = rw, curcol = n+1 - rw;
    foreach (_; 0 .. n-1) {
        if (currw + 1 > n) {
            anssuf ~= 'R';
            continue;
        }

        writeln(format("? 1 1 %s %s", currw+1, curcol));
        stdout.flush();

        msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anssuf ~= 'D';
            currw += 1;
        } else {
            anssuf ~= 'R';
            curcol += 1;
        }
    }

    currw = rw, curcol = n+1 - rw;
    dchar[] anspref;
    foreach (_; 0 .. n-1) {
        if (currw == 1) {
            anspref ~= 'R';
            continue;
        }

        writeln(format("? %s %s %s %s", currw-1, curcol, n, n));
        stdout.flush();

        msg = readln.chomp;

        if (msg == "BAD") return;

        if (msg == "YES") {
            anspref ~= 'D';
            currw -= 1;
        } else {
            anspref ~= 'R';
            curcol -= 1;
        }
    }
    reverse(anspref);

    auto ans = anspref ~ anssuf;

    writeln("! ", ans);
    stdout.flush();
}

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

struct seg
{
    int l = int.max;
    int r;
}

bool ask(int r, int c, int r1, int c1)
{
    writefln("? %d %d %d %d", r, c, r1, c1);
    stdout.flush;
    return "YES" == readln.chomp;
}

void main()
{
    int n;
    readf("%d\n", &n);
    bool[] a;
    a.length = 2 * n - 2;
    int r = 1, c = 1;
    foreach (i; 0..n - 1) {
        ++r;
        a[i] = ask(r, c, n, n);
        if (!a[i]) {
            --r;
            ++c;
        }
    }
    r = c = n;
    foreach (i; 1..n) {
        --c;
        a[$ - i] = !ask(1, 1, r, c);
        if (a[$ - i]) {
            ++c;
            --r;
        }
    }
    foreach (down; a) {
        write(down ? 'D' : 'R');
    }
    writeln;
    stdout.flush;
}

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.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;
debug {
  string[] A;
}

int Ask(int x0, int y0, int x1, int y1) {
  bool ret;
  debug {
    if (A[x0][y0] == '.' && A[x1][y1] == '.') {
      auto dp = new bool[][](N, N);
      dp[x0][y0] = true;
      foreach (x; 0 .. N) foreach (y; 0 .. N) {
        if (dp[x][y]) {
          if (x + 1 < N && A[x + 1][y] == '.') {
            dp[x + 1][y] = true;
          }
          if (y + 1 < N && A[x][y + 1] == '.') {
            dp[x][y + 1] = true;
          }
        }
      }
      ret = dp[x1][y1];
    } else {
      ret = false;
    }
  } else {
    writefln("? %s %s %s %s", x0 + 1, y0 + 1, x1 + 1, y1 + 1);
    stdout.flush;
    ret = (readToken() == "YES");
  }
  return ret;
}

void main() {
  N = readInt();
  debug {
    A = new string[N];
    foreach (x; 0 .. N) {
      A[x] = readToken();
    }
  }

  string ans;
  for (int x = 0, y = 0; !(x == N - 1 && y == N - 1); ) {
    if (x + y + 1 <= N - 1) {
      if (x + 1 < N && Ask(x + 1, y, N - 1, N - 1)) {
        ++x;
        ans ~= 'D';
      } else {
        ++y;
        ans ~= 'R';
      }
    } else {
      if (x + 1 < N && Ask(0, 0, x + 1, y)) {
        ++x;
        ans ~= 'D';
      } else {
        ++y;
        ans ~= 'R';
      }
    }
  }
  writefln("! %s", ans);
  stdout.flush;
}


In this problem you will have to help Berland army with organizing their command delivery system.There are $$$n$$$ officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer $$$a$$$ is the direct superior of officer $$$b$$$, then we also can say that officer $$$b$$$ is a direct subordinate of officer $$$a$$$.Officer $$$x$$$ is considered to be a subordinate (direct or indirect) of officer $$$y$$$ if one of the following conditions holds:  officer $$$y$$$ is the direct superior of officer $$$x$$$;  the direct superior of officer $$$x$$$ is a subordinate of officer $$$y$$$. For example, on the picture below the subordinates of the officer $$$3$$$ are: $$$5, 6, 7, 8, 9$$$.The structure of Berland army is organized in such a way that every officer, except for the commander, is a subordinate of the commander of the army.Formally, let's represent Berland army as a tree consisting of $$$n$$$ vertices, in which vertex $$$u$$$ corresponds to officer $$$u$$$. The parent of vertex $$$u$$$ corresponds to the direct superior of officer $$$u$$$. The root (which has index $$$1$$$) corresponds to the commander of the army.Berland War Ministry has ordered you to give answers on $$$q$$$ queries, the $$$i$$$-th query is given as $$$(u_i, k_i)$$$, where $$$u_i$$$ is some officer, and $$$k_i$$$ is a positive integer.To process the $$$i$$$-th query imagine how a command from $$$u_i$$$ spreads to the subordinates of $$$u_i$$$. Typical DFS (depth first search) algorithm is used here.Suppose the current officer is $$$a$$$ and he spreads a command. Officer $$$a$$$ chooses $$$b$$$ — one of his direct subordinates (i.e. a child in the tree) who has not received this command yet. If there are many such direct subordinates, then $$$a$$$ chooses the one having minimal index. Officer $$$a$$$ gives a command to officer $$$b$$$. Afterwards, $$$b$$$ uses exactly the same algorithm to spread the command to its subtree. After $$$b$$$ finishes spreading the command, officer $$$a$$$ chooses the next direct subordinate again (using the same strategy). When officer $$$a$$$ cannot choose any direct subordinate who still hasn't received this command, officer $$$a$$$ finishes spreading the command.Let's look at the following example:  If officer $$$1$$$ spreads a command, officers receive it in the following order: $$$[1, 2, 3, 5 ,6, 8, 7, 9, 4]$$$.If officer $$$3$$$ spreads a command, officers receive it in the following order: $$$[3, 5, 6, 8, 7, 9]$$$.If officer $$$7$$$ spreads a command, officers receive it in the following order: $$$[7, 9]$$$.If officer $$$9$$$ spreads a command, officers receive it in the following order: $$$[9]$$$.To answer the $$$i$$$-th query $$$(u_i, k_i)$$$, construct a sequence which describes the order in which officers will receive the command if the $$$u_i$$$-th officer spreads it. Return the $$$k_i$$$-th element of the constructed list or -1 if there are fewer than $$$k_i$$$ elements in it.You should process queries independently. A query doesn't affect the following queries.

The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le q \le 2 \cdot 10^5$$$) — the number of officers in Berland army and the number of queries. The second line of the input contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$), where $$$p_i$$$ is the index of the direct superior of the officer having the index $$$i$$$. The commander has index $$$1$$$ and doesn't have any superiors. The next $$$q$$$ lines describe the queries. The $$$i$$$-th query is given as a pair ($$$u_i, k_i$$$) ($$$1 \le u_i, k_i \le n$$$), where $$$u_i$$$ is the index of the officer which starts spreading a command, and $$$k_i$$$ is the index of the required officer in the command spreading sequence.

Print $$$q$$$ numbers, where the $$$i$$$-th number is the officer at the position $$$k_i$$$ in the list which describes the order in which officers will receive the command if it starts spreading from officer $$$u_i$$$. Print "-1" if the number of officers which receive the command is less than $$$k_i$$$. You should process queries independently. They do not affect each other.

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

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

    auto g = new int[][] (n+1);
    readln.chomp.split.map!(to!int).map!(x => x-1).enumerate(1).each!(t => g[t[1]] ~= t[0]);

    debug { g.writeln; }

    auto sz = new int[] (n);

    int getSz(int v) {
        sz[v] = 1;
        foreach (u; g[v]) sz[v] += getSz(u);
        return sz[v];
    }

    getSz(0);

    int[] sq;

    void dfs(int v) {
        sq ~= v;
        foreach (u; g[v]) dfs(u);
    }

    dfs(0);

    auto idcs = new int[] (n);
    sq.enumerate.each!(t => idcs[t[1]] = cast(int)t[0]);

    debug { sq.writeln; idcs.writeln; }

    while (q--) {
        int u, k;
        readf("%s %s", &u, &k);
        readln;

        --u;
        if (sz[u] < k) {
            writeln(-1);
            continue;
        }

        auto ans = sq[idcs[u] + k-1] + 1;

        ans.writeln;
    }
}


The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.Vladimir wants to rename the files with tests so that their names are distinct integers starting from 1 without any gaps, namely, "1", "2", ..., "n', where n is the total number of tests.Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only.The only operation Vladimir can perform is the "move" command. Vladimir wants to write a script file, each of the lines in which is "move file_1 file_2", that means that the file "file_1" is to be renamed to "file_2". If there is a file "file_2" at the moment of this line being run, then this file is to be rewritten. After the line "move file_1 file_2" the file "file_1" doesn't exist, but there is a file "file_2" with content equal to the content of "file_1" before the "move" command.Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run:  all examples are the first several tests having filenames "1", "2", ..., "e", where e is the total number of examples;  all other files contain regular tests with filenames "e + 1", "e + 2", ..., "n", where n is the total number of all tests.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of files with tests. n lines follow, each describing a file with test. Each line has a form of "name_i type_i", where "name_i" is the filename, and "type_i" equals "1", if the i-th file contains an example test, and "0" if it contains a regular test. Filenames of each file are strings of digits and small English letters with length from 1 to 6 characters. The filenames are guaranteed to be distinct.

In the first line print the minimum number of lines in Vladimir's script file. After that print the script file, each line should be "move file_1 file_2", where "file_1" is an existing at the moment of this line being run filename, and "file_2" — is a string of digits and small English letters with length from 1 to 6.

4
move 3 1
move 01 5
move 2extra 4
move 99 3

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto name = new string [n];
		auto isExample = new bool [n];
		foreach (i; 0..n)
		{
			auto t = readln.split;
			name[i] = t[0];
			isExample[i] = t[1].to !(int).to !(bool);
		}

		bool [string] [2] p;
		foreach (i; 0..n)
		{
			p[!isExample[i]][name[i]] = true;
		}
		int examples = isExample.sum;

		string [] [4] [2] e;
		string temp = "";
		string tempDefault = (n + 1).text;
		foreach (num; 1..examples + 1)
		{
			auto str = num.text;
			if (str in p[0])
			{
				e[0][0] ~= str;
				p[0][str] = false;
			}
			else if (str in p[1])
			{
				e[1][1] ~= str;
				p[1][str] = false;
			}
			else
			{
				e[0][3] ~= str;
				temp = str;
			}
		}
		foreach (num; examples + 1..n + 1)
		{
			auto str = num.text;
			if (str in p[1])
			{
				e[1][0] ~= str;
				p[1][str] = false;
			}
			else if (str in p[0])
			{
				e[0][1] ~= str;
				p[0][str] = false;
			}
			else
			{
				e[1][3] ~= str;
				temp = str;
			}
		}
		if (temp == "")
		{
			temp = tempDefault;
		}
		assert (temp != "" && !name.canFind (temp));
		foreach (k, v; p[0])
		{
			if (v)
			{
				e[0][2] ~= k;
			}
		}
		foreach (k, v; p[1])
		{
			if (v)
			{
				e[1][2] ~= k;
			}
		}

		string [] [] ans;
		while (!e[0][1].empty || !e[0][2].empty ||
		    !e[1][1].empty || !e[1][2].empty)
		{
			debug {writefln ("%(%s\n%)\n%s", e, temp);}
			if (e[0][3].empty && e[1][3].empty)
			{
				assert (temp == tempDefault);
				if (!e[0][1].empty)
				{
					ans ~= [e[0][1].front, temp];
					e[0][2].assumeSafeAppend ();
					e[0][2] ~= temp;
					e[1][3].assumeSafeAppend ();
					e[1][3] ~= e[0][1].front;
					e[0][1].popFront ();
				}
				else if (!e[1][1].empty)
				{
					ans ~= [e[1][1].front, temp];
					e[1][2].assumeSafeAppend ();
					e[1][2] ~= temp;
					e[0][3].assumeSafeAppend ();
					e[0][3] ~= e[1][1].front;
					e[1][1].popFront ();
				}
				else
				{
					assert (false);
				}
			}
			else
			{
				if (!e[0][3].empty)
				{
					if (!e[0][1].empty)
					{
						ans ~= [e[0][1].front,
						    e[0][3].front];
						e[0][0].assumeSafeAppend ();
						e[0][0] ~= e[0][3].front;
						e[1][3].assumeSafeAppend ();
						e[1][3] ~= e[0][1].front;
						e[0][1].popFront ();
						e[0][3].popFront ();
					}
					else
					{
						ans ~= [e[0][2].front,
						    e[0][3].front];
						e[0][0].assumeSafeAppend ();
						e[0][0] ~= e[0][3].front;
						e[0][2].popFront ();
						e[0][3].popFront ();
					}
				}
				else if (!e[1][3].empty)
				{
					if (!e[1][1].empty)
					{
						ans ~= [e[1][1].front,
						    e[1][3].front];
						e[1][0].assumeSafeAppend ();
						e[1][0] ~= e[1][3].front;
						e[0][3].assumeSafeAppend ();
						e[0][3] ~= e[1][1].front;
						e[1][1].popFront ();
						e[1][3].popFront ();
					}
					else
					{
						ans ~= [e[1][2].front,
						    e[1][3].front];
						e[1][0].assumeSafeAppend ();
						e[1][0] ~= e[1][3].front;
						e[1][2].popFront ();
						e[1][3].popFront ();
					}
				}
				else
				{
					assert (false);
				}
	        	}
		}
		debug {writefln ("%(%s\n%)\n%s", e, temp);}

		writeln (ans.length);
		foreach (c; ans)
		{
			writefln ("move %-(%s %)", c);
		}
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new string[N];
      auto B = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readToken();
        B[i] = readInt();
      }

      bool[string] app;
      foreach (i; 0 .. N) {
        app[A[i]] = true;
      }
      string dummy;
      for (int a = 10^^5 + 1; ; ++a) {
        if (a.to!string !in app) {
          dummy = a.to!string;
          break;
        }
      }

      const E = B.sum;
      auto ss = new string[N];
      int[string] tr;
      foreach (u; 0 .. N) {
        ss[u] = (u + 1).to!string;
        tr[ss[u]] = u;
      }

      // 0: vacant, 1: done, 2: need change
      auto status = new int[N];
      auto iss = new int[][2];
      foreach (i; 0 .. N) {
        if (A[i] in tr) {
          const u = tr[A[i]];
          status[u] = ((B[i] == 1) == (u < E)) ? 1 : 2;
        } else {
          iss[B[i]] ~= i;
        }
      }
      debug {
        writeln("status = ", status);
        writeln("iss = ", iss);
      }

      auto vacant = new DList!int[2];
      auto change = new DList!int[2];
      foreach (u; 0 .. N) {
        const b = (u < E) ? 1 : 0;
        if (status[u] == 0) vacant[b] ~= u;
        if (status[u] == 2) change[b] ~= u;
      }

      string[][] ans;
      int b0 = -1;

      if (vacant[0].empty && vacant[1].empty) {
        foreach (b; 0 .. 2) {
          if (!change[b].empty) {
            const u = change[b].back;
            change[b].removeBack;
            vacant[b] ~= u;
            ans ~= [ss[u], dummy];
            b0 = b;
            break;
          }
        }
      }

      for (; ; ) {
        bool upd;
        foreach (b; 0 .. 2) {
          if (!change[b].empty) {
            const u = change[b].back;
            if (!vacant[b ^ 1].empty) {
              const v = vacant[b ^ 1].back;
              change[b].removeBack;
              vacant[b ^ 1].removeBack;
              vacant[b] ~= u;
              ans ~= [ss[u], ss[v]];
              upd = true;
              break;
            }
          }
        }
        if (!upd) {
          break;
        }
      }

      if (b0 != -1) {
        assert(!vacant[b0 ^ 1].empty);
        const v = vacant[b0 ^ 1].back;
        vacant[b0 ^ 1].removeBack;
        ans ~= [dummy, ss[v]];
      }

      foreach (b; 0 .. 2) {
        foreach (i; iss[b]) {
          assert(!vacant[b].empty);
          const v = vacant[b].back;
          vacant[b].removeBack;
          ans ~= [A[i], ss[v]];
        }
      }

      writeln(ans.length);
      foreach (row; ans) {
        writeln("move ", row[0], " ", row[1]);
      }
    }
  } catch (EOFException e) {
  }
}