There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j < t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) — the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.

Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.

NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.outbuffer;
import std.typecons;
import std.algorithm.mutation;
import std.container.array;

string[] tokens;

string readToken()
{
    while (tokens.empty)
    {
        tokens = readln.split;
    }
    auto token = tokens.front;
    tokens.popFront;
    return token;
}

int readInt()
{
    return readToken.to!int;
}

void main()
{
    int T = readInt;
    while (T--)
    {
        int n = readInt;
        auto a = new Tuple!(int, int)[n + 1];
        for (int i = 1; i <= n; ++i)
            a[i][0] = readInt, a[i][1] = readInt;
        sort(a);
        bool ok = true;
        for (int i = 1; i <= n; ++i)
            ok &= a[i - 1][1] <= a[i][1];
        if (ok)
        {
            writeln("YES");
            OutBuffer buf = new OutBuffer();
            for (int i = 1; i <= n; ++i)
            {
                for (int y = a[i - 1][0]; y < a[i][0]; ++y)
                    buf.write('R');
                for (int y = a[i - 1][1]; y < a[i][1]; ++y)
                    buf.write('U');
            }
            writeln(buf);
        }
        else
        {
            writeln("NO");
        }
    }
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value = E.init)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

void main()
{
  int t;
  read(t);
  foreach(tc; 0 .. t)
    {
      int n;
      read(n);
      auto points = makeArray!(Tuple!(int, int))(n + 1);
      points[0] = tuple(0, 0);
      foreach(ref point; points[1 .. $])
        point = tuple(next!int, next!int);
      sort(points[]);
      if (points[].map!(t => t[1]).isSorted)
        {
          writeln("YES");
          foreach(i; 1 .. points.length)
            {
              auto delta = tuple(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]);
              assert(delta[0] >= 0 && delta[1] >= 0);
              foreach(j; 0 .. delta[0])
                write('R');
              foreach(j; 0 .. delta[1])
                write('U');
            }
          writeln;
        }
      else
        {
          writeln("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)); }

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

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

		xy.sort!"a[0] == b[0] ? a[1] < b[1] : a[0] < b[0]"();

		long x, y;
		foreach (i; 0..n)
		{
			if (xy[i][1] < y)
			{
				ans[ti] = "";
				break;
			}
			foreach (j; 0..xy[i][0]-x)
				ans[ti] ~= "R";
			foreach (j; 0..xy[i][1]-y)
				ans[ti] ~= "U";
			x = xy[i][0];
			y = xy[i][1];
		}
	}

	foreach (e; ans)
	{
		if (e == "")
			writeln("NO");
		else
		{
			writeln("YES");
			writeln(e);
		}
	}
	stdout.flush;
	debug readln;
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		alias Point = Tuple !(int, q{x}, int, q{y});
		auto a = new Point [n];
		foreach (ref c; a)
		{
			readf !(" %s %s") (c.x, c.y);
		}

		a.schwartzSort !(c => c.x + c.y);
		auto cur = Point (0, 0);
		bool ok = true;
		string res;
		foreach (ref c; a)
		{
			if (c.x < cur.x || c.y < cur.y)
			{
				ok = false;
				break;
			}
			res ~= 'R'.repeat (c.x - cur.x).text;
			res ~= 'U'.repeat (c.y - cur.y).text;
			cur = c;
		}
		writeln (ok ? "YES" : "NO");
		if (ok)
		{
			writeln (res);
		}
	}
}


You are given two strings of equal length $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.For example, if $$$s$$$ is "acbc" you can get the following strings in one operation:   "aabc" (if you perform $$$s_2 = s_1$$$);  "ccbc" (if you perform $$$s_1 = s_2$$$);  "accc" (if you perform $$$s_3 = s_2$$$ or $$$s_3 = s_4$$$);  "abbc" (if you perform $$$s_2 = s_3$$$);  "acbb" (if you perform $$$s_4 = s_3$$$); Note that you can also apply this operation to the string $$$t$$$.Please determine whether it is possible to transform $$$s$$$ into $$$t$$$, applying the operation above any number of times.Note that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query is represented by two consecutive lines. The first line of each query contains the string $$$s$$$ ($$$1 \le |s| \le 100$$$) consisting of lowercase Latin letters. The second line of each query contains the string $$$t$$$ ($$$1 \le |t| \leq 100$$$, $$$|t| = |s|$$$) consisting of lowercase Latin letters.

For each query, print "YES" if it is possible to make $$$s$$$ equal to $$$t$$$, and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes", and "YES" will all be recognized as positive answer).

NoteIn the first query, you can perform two operations $$$s_1 = s_2$$$ (after it $$$s$$$ turns into "aabb") and $$$t_4 = t_3$$$ (after it $$$t$$$ turns into "aabb"). In the second query, the strings are equal initially, so the answer is "YES".In the third query, you can not make strings $$$s$$$ and $$$t$$$ equal. Therefore, the answer is "NO".

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 q = RD!int;
	auto ans = new bool[](q);
	foreach (i; 0..q)
	{
		auto s = RD!string;
		auto t = RD!string;
		auto f1 = new bool[](26);
		auto f2 = new bool[](26);
		foreach (c; s)
			f1[c-'a'] = true;
		foreach (c; t)
			f2[c-'a'] = true;

		foreach (j; 0..26)
		{
			if (f1[j] && f2[j])
			{
				ans[i] = true;
				break;
			}
		}
	}

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


You've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≤ li ≤ ri ≤ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≤ l ≤ r ≤ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.

The first line contains string s (1 ≤ |s| ≤ 5000). The second line contains a single integer q (1 ≤ q ≤ 106) — the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the description of the i-th query. It is guaranteed that the given string consists only of lowercase English letters.

Print q integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.

NoteConsider the fourth query in the first test case. String s[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba».

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

void main()
{
    auto s = readln.chomp;

    auto isP = new bool[][] (s.length+1, s.length+1);
    isP.each!(rw => rw[] = false);
    auto ans = new int[][] (s.length+1, s.length+1);

    foreach (len; 1 .. s.length+1) {
        foreach (st; 0 .. s.length - len + 1) {
            int le = st.to!int + 1;
            int r = st.to!int + 1 + len.to!int - 1;
            isP[le][r] = len == 1 ||
                (s[st] == s[st + len - 1] && (len == 2 || isP[le+1][r-1]));

            if (len == 1) { ans[le][r] = 1; }
            else if (len == 2) { ans[le][r] = 2 + (isP[le][r] ? 1 : 0); }
            else {
                ans[le][r] = ans[le][r-1] - ans[le+1][r-1]
                    + ans[le+1][r] - ans[le+1][r-1]
                    + ans[le+1][r-1]
                    + (isP[le][r] ? 1 : 0);
            }
        }
    }

    debug { isP.each!writeln; }

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

    while (q--) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        ans[le][r].writeln;
    }
}

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

void main()
{
    auto s = readln.chomp;

    auto isP = new bool[][] (s.length+1, s.length+1);
    isP.each!(rw => rw[] = false);
    auto starts = new int[] (s.length+1);
    starts[] = 0;
    auto ends = new int[] (s.length+1);
    ends[] = 0;

    foreach (len; 1 .. s.length) {
        foreach (st; 0 .. s.length - len + 1) {
            isP[st+1][len] = len == 1 ||
                (s[st] == s[st + len - 1] && (len == 2 || isP[st+2][len-2]));
            if (isP[st+1][len]) {
                starts[st+1] += 1;
                ends[st+1 + len - 1] += 1;
            }
        }
    }

    starts = starts.cumulativeFold!((a, b) => a + b).array;
    ends = ends.cumulativeFold!((a, b) => a + b).array;

    debug { isP.each!writeln; }
    debug { writeln(starts, ends); }

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

    while (q--) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        int ans = ends[r] - starts[le-1];
        ans.writeln;
    }
}

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

void main()
{
    auto s = readln.chomp;

    auto isP = new bool[][] (s.length+1, s.length+1);
    isP.each!(rw => rw[] = false);
    auto ans = new int[][] (s.length+1, s.length+1);

    foreach (len; 1 .. s.length) {
        foreach (st; 0 .. s.length - len + 1) {
            int le = st.to!int + 1;
            int r = st.to!int + 1 + len.to!int - 1;
            isP[le][r] = len == 1 ||
                (s[st] == s[st + len - 1] && (len == 2 || isP[le+1][r-1]));

            if (len == 1) { ans[le][r] = 1; }
            else if (len == 2) { ans[le][r] = 2 + (isP[le][r] ? 1 : 0); }
            else {
                ans[le][r] = ans[le][r-1] - ans[le+1][r-1]
                    + ans[le+1][r] - ans[le+1][r-1]
                    + ans[le+1][r-1]
                    + (isP[le][r] ? 1 : 0);
            }
        }
    }

    debug { isP.each!writeln; }

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

    while (q--) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        ans[le][r].writeln;
    }
}

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

void main()
{
    auto s = readln.chomp;

    auto isP = new bool[][] (s.length+1, s.length+1);
    auto starts = new int[] (s.length+1);
    auto ends = new int[] (s.length+1);

    foreach (len; 1 .. s.length) {
        foreach (st; 0 .. s.length - len + 1) {
            isP[st+1][len] = len == 1 ||
                (s[st] == s[st + len - 1] && (len == 2 || isP[st+2][len-2]));
            if (isP[st+1][len]) {
                starts[st+1] += 1;
                ends[st+1 + len - 1] += 1;
            }
        }
    }

    starts = starts.cumulativeFold!((a, b) => a + b).array;
    ends = ends.cumulativeFold!((a, b) => a + b).array;

    debug { isP.each!writeln; }
    debug { writeln(starts, ends); }

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

    while (q--) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        int ans = ends[r] - starts[le-1];
        ans.writeln;
    }
}


You might have remembered Theatre square from the problem 1A. Now it's finally getting repaved.The square still has a rectangular shape of $$$n \times m$$$ meters. However, the picture is about to get more complicated now. Let $$$a_{i,j}$$$ be the $$$j$$$-th square in the $$$i$$$-th row of the pavement.You are given the picture of the squares:  if $$$a_{i,j} = $$$ "*", then the $$$j$$$-th square in the $$$i$$$-th row should be black;  if $$$a_{i,j} = $$$ ".", then the $$$j$$$-th square in the $$$i$$$-th row should be white. The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles:  $$$1 \times 1$$$ tiles — each tile costs $$$x$$$ burles and covers exactly $$$1$$$ square;  $$$1 \times 2$$$ tiles — each tile costs $$$y$$$ burles and covers exactly $$$2$$$ adjacent squares of the same row. Note that you are not allowed to rotate these tiles or cut them into $$$1 \times 1$$$ tiles. You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.What is the smallest total price of the tiles needed to cover all the white squares?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of testcases. Then the description of $$$t$$$ testcases follow. The first line of each testcase contains four integers $$$n$$$, $$$m$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 100$$$; $$$1 \le m \le 1000$$$; $$$1 \le x, y \le 1000$$$) — the size of the Theatre square, the price of the $$$1 \times 1$$$ tile and the price of the $$$1 \times 2$$$ tile. Each of the next $$$n$$$ lines contains $$$m$$$ characters. The $$$j$$$-th character in the $$$i$$$-th line is $$$a_{i,j}$$$. If $$$a_{i,j} = $$$ "*", then the $$$j$$$-th square in the $$$i$$$-th row should be black, and if $$$a_{i,j} = $$$ ".", then the $$$j$$$-th square in the $$$i$$$-th row should be white. It's guaranteed that the sum of $$$n \times m$$$ over all testcases doesn't exceed $$$10^5$$$.

For each testcase print a single integer — the smallest total price of the tiles needed to cover all the white squares in burles.

NoteIn the first testcase you are required to use a single $$$1 \times 1$$$ tile, even though $$$1 \times 2$$$ tile is cheaper. So the total price is $$$10$$$ burles.In the second testcase you can either use two $$$1 \times 1$$$ tiles and spend $$$20$$$ burles or use a single $$$1 \times 2$$$ tile and spend $$$1$$$ burle. The second option is cheaper, thus the answer is $$$1$$$.The third testcase shows that you can't rotate $$$1 \times 2$$$ tiles. You still have to use two $$$1 \times 1$$$ tiles for the total price of $$$20$$$.In the fourth testcase the cheapest way is to use $$$1 \times 1$$$ tiles everywhere. The total cost is $$$6 \cdot 3 = 18$$$.

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm, std.array, std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
int isz(long t){ return to!int(t); }
static string[] tempstr;
T rd(T = long)() { while(!tempstr.length) tempstr = readln.chomp.split; string res = tempstr[0]; tempstr.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    int n, m, x, y;
    n = rd!int; m = rd!int; x = rd!int; y = rd!int;
    char[][] tiles;
    foreach(i; 0..n){
        auto tilerow = rd!(char[]);
        tiles ~= tilerow;
    }
    auto num = new int[][](n, m);
    foreach(i; 0..n){
        int cnt = 0;
        char prev = tiles[i][m-1];
        foreach_reverse(j; 0..m){
            if(tiles[i][j] == '.'){
                ++cnt;
            }else{
                cnt = 0;
            }
            num[i][j] = cnt;
        }
    }
    int take2 = 0, take = 0;
    foreach(i; 0 .. n){
        int j = 0;
        while(j < m){
            if(num[i][j] >= 2){
                ++take2;
                j += 2;
            }else if(num[i][j]){
                ++take;
                ++j;
            }else{
                ++j;
            }
        }
    }
    debug writeln(num);
    ll cost = take2 * min(2*x, y) + take * x;
    writeln(cost);
}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m, x, y;
		readf !(" %s %s %s %s") (n, m, x, y);
		y = min (y, 2 * x);
		readln;
		int res = 0;
		foreach (row; 0..n)
		{
			auto line = readln.strip;
			int col = 0;
			while (col < m)
			{
				if (line[col] == '*')
				{
					res += 0;
					col += 1;
				}
				else if (col + 1 >= m || line[col + 1] == '*')
				{
					res += x;
					col += 1;
				}
				else
				{
					res += y;
					col += 2;
				}
			}
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int cnt;
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				if (s[i][j] == '.')
					++cnt;
			}
		}
		if (x*2 <= y)
		{
			ans[ti] = cnt*x;
		}
		else
		{
			foreach (i; 0..n)
			{
				int j = 1;
				while (j < m)
				{
					if (s[i][j] == '.' && s[i][j-1] == '.')
					{
						ans[ti] += y;
						cnt -= 2;
						j += 2;
					}
					else
						++j;
				}
			}
			ans[ti] += x * cnt;
		}
	}

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

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm, std.array, std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
int isz(long t){ return to!int(t); }
static string[] tempstr;
T rd(T = long)() { while(!tempstr.length) tempstr = readln.chomp.split; string res = tempstr[0]; tempstr.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    int n, m, x, y;
    n = rd!int; m = rd!int; x = rd!int; y = rd!int;
    char[][] tiles;
    foreach(i; 0..n){
        auto tilerow = rd!(char[]);
        tiles ~= tilerow;
    }
    auto num = new int[][](n, m);
    foreach(i; 0..n){
        int cnt = 0;
        char prev = tiles[i][m-1];
        foreach_reverse(j; 0..m){
            if(tiles[i][j] == prev && prev == '.'){
                ++cnt;
            }else if(prev == '.'){
                cnt = 1;
            }else{
                cnt = 0;
            }
            num[i][j] = cnt;
        }
    }
    int take2 = 0, take = 0;
    foreach(i; 0 .. n){
        int j = 0;
        while(j < m){
            if(num[i][j] >= 2){
                ++take2;
                j += 2;
            }else if(num[i][j]){
                ++take;
                ++j;
            }else{
                ++j;
            }
        }
    }
    debug writeln(num);
    int cost = take2 * min(2*x, y) + take * x;
    writeln(cost);
}

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


You are given a grid with $$$n$$$ rows and $$$m$$$ columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number $$$k > 0$$$ written on it, then exactly $$$k$$$ of its neighboring cells have a number greater than $$$0$$$ written on them. Note that if the number in the cell is $$$0$$$, there is no such restriction on neighboring cells.You are allowed to take any number in the grid and increase it by $$$1$$$. You may apply this operation as many times as you want, to any numbers you want. Perform some operations (possibly zero) to make the grid good, or say that it is impossible. If there are multiple possible answers, you may find any of them.Two cells are considered to be neighboring if they have a common edge.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 300$$$)  — the number of rows and columns, respectively. The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line $$$a_{i, j}$$$ is the number written in the $$$j$$$-th cell of the $$$i$$$-th row ($$$0 \le a_{i, j} \le 10^9$$$). It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^5$$$.

If it is impossible to obtain a good grid, print a single line containing "NO". Otherwise, print a single line containing "YES", followed by $$$n$$$ lines each containing $$$m$$$ integers, which describe the final state of the grid. This final grid should be obtainable from the initial one by applying some operations (possibly zero). If there are multiple possible answers, you may print any of them.

NoteIn the first test case, we can obtain the resulting grid by increasing the number in row $$$2$$$, column $$$3$$$ once. Both of the cells that contain $$$1$$$ have exactly one neighbor that is greater than zero, so the grid is good. Many other solutions exist, such as the grid $$$$$$0\;1\;0\;0$$$$$$ $$$$$$0\;2\;1\;0$$$$$$ $$$$$$0\;0\;0\;0$$$$$$ All of them are accepted as valid answers.In the second test case, it is impossible to make the grid good.In the third test case, notice that no cell has a number greater than zero on it, so the grid is automatically good.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		auto a = new int [] [] (rows, cols);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf !(" %s") (a[row][col]);
			}
		}

		bool ok = true;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				auto cur = (row > 0) + (row + 1 < rows);
				cur += (col > 0) + (col + 1 < cols);
				ok &= (a[row][col] <= cur);
				a[row][col] = cur;
			}
		}

		if (ok)
		{
			writeln ("YES");
			writefln !("%(%(%s %)\n%)") (a);
		}
		else
		{
			writeln ("NO");
		}
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const M = readInt();
        const N = readInt();
        auto A = new int[][](M, N);
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          A[x][y] = readInt();
        }

        auto deg = new int[][](M, N);
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          if (x - 1 >= 0) {
            ++deg[x - 1][y];
            ++deg[x][y];
          }
          if (y - 1 >= 0) {
            ++deg[x][y - 1];
            ++deg[x][y];
          }
        }

        bool ans = true;
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          ans = ans && (A[x][y] <= deg[x][y]);
        }
        if (ans) {
          writeln("YES");
          foreach (x; 0 .. M) {
            foreach (y; 0 .. N) {
              if (y > 0) write(" ");
              write(deg[x][y]);
            }
            writeln;
          }
        } else {
          writeln("NO");
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = m;
		bool ok = true;
		(){
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				auto x = 4;
				if (i == 0 || i == n-1)
					--x;
				if (j == 0 || j == m-1)
					--x;

				if (a[i][j] > x)
				{
					ok = false;
					return;
				}
				ans[ti][i][j] = x;
			}
		}}();

		if (!ok)
		{
			ans[ti].length = 0;
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			foreach (ee; e)
			{
				ee.map!(to!string).join(" ").writeln;
			}
		}
	}
	stdout.flush;
	debug readln;
}


Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the $$$i$$$-th of them will start during the $$$x_i$$$-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes $$$x_1, x_2, \dots, x_n$$$, so he will be awake during each of these minutes (note that it does not matter if his alarm clock will ring during any other minute).Ivan can choose two properties for the alarm clock — the first minute it will ring (let's denote it as $$$y$$$) and the interval between two consecutive signals (let's denote it by $$$p$$$). After the clock is set, it will ring during minutes $$$y, y + p, y + 2p, y + 3p$$$ and so on.Ivan can choose any minute as the first one, but he cannot choose any arbitrary value of $$$p$$$. He has to pick it among the given values $$$p_1, p_2, \dots, p_m$$$ (his phone does not support any other options for this setting).So Ivan has to choose the first minute $$$y$$$ when the alarm clock should start ringing and the interval between two consecutive signals $$$p_j$$$ in such a way that it will ring during all given minutes $$$x_1, x_2, \dots, x_n$$$ (and it does not matter if his alarm clock will ring in any other minutes).Your task is to tell the first minute $$$y$$$ and the index $$$j$$$ such that if Ivan sets his alarm clock with properties $$$y$$$ and $$$p_j$$$ it will ring during all given minutes $$$x_1, x_2, \dots, x_n$$$ or say that it is impossible to choose such values of the given properties. If there are multiple answers, you can print any.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 3 \cdot 10^5, 1 \le m \le 3 \cdot 10^5$$$) — the number of events and the number of possible settings for the interval between signals. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^{18}$$$), where $$$x_i$$$ is the minute when $$$i$$$-th event starts. It is guaranteed that all $$$x_i$$$ are given in increasing order (i. e. the condition $$$x_1 < x_2 < \dots < x_n$$$ holds). The third line of the input contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_j \le 10^{18}$$$), where $$$p_j$$$ is the $$$j$$$-th option for the interval between two consecutive signals.

If it's impossible to choose such values $$$y$$$ and $$$j$$$ so all constraints are satisfied, print "NO" in the first line. Otherwise print "YES" in the first line. Then print two integers $$$y$$$ ($$$1 \le y \le 10^{18}$$$) and $$$j$$$ ($$$1 \le j \le m$$$) in the second line, where $$$y$$$ is the first minute Ivan's alarm clock should start ringing and $$$j$$$ is the index of the option for the interval between two consecutive signals (options are numbered from $$$1$$$ to $$$m$$$ in the order they are given input). These values should be chosen in such a way that the alarm clock will ring during all given minutes $$$x_1, x_2, \dots, x_n$$$. If there are multiple answers, you can print any.

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

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

    auto B = (N-1).iota.map!(i => A[i+1] - A[i]).array;
    auto G = B.reduce!((a, b) => gcd(a, b));

    foreach (i; 0..M) {
        if (G % P[i] == 0) {
            writeln("YES");
            writeln(A.front, " ", i + 1);
            return;
        }
    }

    writeln("NO");
}

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

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

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

void main() {
  auto r = new InputReader;
  immutable n = r.next!int;
  immutable m = r.next!int;
  auto x = r.nextA!long (n);
  immutable x0 = x[0];
  long g;
  debug stderr.writeln(x);
  foreach (i; 1 .. n) {
    immutable dx = x[i] - x0;
    if (i == 1) {
      g = dx;
    } else {
      debug stderr.writeln(g, ' ', dx);
      g = gcd (g, dx);
    }
  }
  auto p = r.nextA!long (m);
  foreach (i; 0 .. m) {
    if (!(g % p[i])) {
      writeln ("YES");
      writeln (x[0], ' ', i + 1);
      return;
    }
  }
  writeln ("NO");
}

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

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

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
}

void main() {
  auto r = new InputReader;
  immutable n = r.next!int;
  immutable m = r.next!int;
  auto x = uninitializedArray!(long[]) (n);
  foreach (i; 0 .. n) x[i] = r.next!long;
  immutable x0 = x[0];
  long g;
  foreach (i; 1 .. n) {
    immutable dx = x[i] - x0;
    if (i == 1) {
      g = dx;
    } else {
      g = gcd (g, dx);
    }
  }
  auto p = uninitializedArray!(long[]) (n);
  foreach (i; 0 .. m) {
    p[i] = r.next!long;
    if (!(g % p[i])) {
      writeln ("YES");
      writeln (x[0], ' ', i + 1);
      return;
    }
  }
  writeln ("NO");
}

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

/*

Find gcd of given minutes.
If any p is divisor of the gcd, then YES.
Otherwise NO.

*/

void solve(){
	int n = read!int;
	int m = read!int;
	long[] xs = read!long(n);
	long[] ps = read!long(m);

	long d = xs[1] - xs[0];
	foreach(i; 0 .. n - 1) d = gcd(d, xs[i + 1] - xs[i]);

	bool f;
	int ans;
	foreach(int j, p; ps) if(d % p == 0) f = 1, ans = j;

	if(! f) writeln("NO");
	else writeln("YES"), writeln(xs[0], " ", ans + 1);
}

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

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.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; }
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; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
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 N = RD!int;
	auto M = RD!int;
	auto x = RDR.ARR;
	auto p = RDR.ARR;

	long g = x[1] - x[0];
	foreach (i; 2..N)
	{
		g = gcd(g, x[i] - x[i-1]);
	}

	long ans;
	foreach (i; 0..M)
	{
		if (g % p[i] == 0)
		{
			ans = i+1;
			break;
		}
	}

	if (ans == 0)
		writeln("NO");
	else
	{
		writeln("YES");
		writeln(x[0], " ", ans);
	}
	stdout.flush();
	debug readln();
}

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

/*

Find gcd of given minutes.
If any p is divisor of the gcd, then YES.
Otherwise NO.

*/

void solve(){
	int n = read!int;
	int m = read!int;
	long[] xs = read!long(n);
	long[] ps = read!long(m);

	long d = xs[0];
	foreach(x; xs) d = gcd(d, x);

	bool f;
	int ans;
	foreach(int j, p; ps) if(d % p == 0) f = 1, ans = j;

	if(! f) writeln("NO");
	else writeln("YES"), writeln(xs[0], " ", ans + 1);
}

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


There are $$$n$$$ houses numbered from $$$1$$$ to $$$n$$$ on a circle. For each $$$1 \leq i \leq n - 1$$$, house $$$i$$$ and house $$$i + 1$$$ are neighbours; additionally, house $$$n$$$ and house $$$1$$$ are also neighbours.Initially, $$$m$$$ of these $$$n$$$ houses are infected by a deadly virus. Each morning, Cirno can choose a house which is uninfected and protect the house from being infected permanently.Every day, the following things happen in order:  Cirno chooses an uninfected house, and protect it permanently.  All uninfected, unprotected houses which have at least one infected neighbor become infected. Cirno wants to stop the virus from spreading. Find the minimum number of houses that will be infected in the end, if she optimally choose the houses to protect.Note that every day Cirno always chooses a house to protect before the virus spreads. Also, a protected house will not be infected forever.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of test cases follows. The first line of each test case consists of two positive integers $$$n, m$$$ ($$$5 \leq n \leq 10^9$$$, $$$1 \leq m \leq \min(n, 10^5)$$$) — the number of houses on the circle, and the number of houses that are initially infected.  The second line of each test case consists of $$$m$$$ distinct positive integers $$$a_1, a_2, \cdots , a_m$$$ ($$$1 \leq a_i \leq n$$$) — the indices of the houses infected initially. It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output an integer on a separate line, which is the minimum number of infected houses in the end.

NoteIn the first test case:At the start of the first day, house $$$3$$$, $$$6$$$, $$$8$$$ are infected. Choose house $$$2$$$ to protect.At the start of the second day, house $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$, $$$7$$$, $$$8$$$, $$$9$$$ are infected. Choose house $$$10$$$ to protect.At the start of the third day, no more houses are infected.In the second test case:At the start of the first day, house $$$2$$$, $$$5$$$ are infected. Choose house $$$1$$$ to protect.At the start of the second day, house $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$ are infected. No more available houses can be protected.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		if (m == n)
		{
			writeln (m);
			continue;
		}

		sort (a);
		a ~= a[0] + n;
		int [] c;
		c.reserve (m);
		foreach (j; 0..m)
		{
			c ~= a[j + 1] - a[j] - 1;
		}

		sort !(q{a > b}) (c);
		int res = m;
		foreach (i; 0..m)
		{
			res += min (c[i], i * 4 + (c[i] > i * 4 + 1));
		}

		writeln (res);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const L = readLong;
        const M = readInt;
        auto A = new long[M];
        foreach (i; 0 .. M) {
          A[i] = readLong;
        }
        A.sort;

        auto ds = new long[M];
        foreach (i; 0 .. M - 1) {
          ds[i] = A[i + 1] - A[i];
        }
        ds[M - 1] = L + A[0] - A[M - 1];
        ds.sort!"a > b";
        debug {
          writeln("ds = ", ds);
        }

        long ans;
        foreach (j; 0 .. M) {
          long d = ds[j] - 1;
          d -= 4 * j;
          if (d > 0) {
            ans += max(d - 1, 1);
          }
        }
        ans = L - ans;
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		if (m == n)
		{
			writeln (m);
			continue;
		}

		sort (a);
		a ~= a[0] + n;
		int [] c;
		c.reserve (m);
		foreach (j; 0..m)
		{
			if (a[j + 1] - a[j] > 1)
			{
				c ~= a[j + 1] - a[j] - 1;
			}
		}

		sort (c);
		int res = m;
		int span = 0;
		bool half = false;

		int getC ()
		{
			int temp = c.front;
			if (c.length == 1 && half)
			{
				temp -= 1;
			}
			return temp;
		}

		while (!c.empty)
		{
			if (half)
			{
				res += span - 1;
				c.popBack ();
			}
			span += 2;
			half ^= true;
			while (!c.empty && getC () <= span)
			{
				res += getC ();
				c.popFront ();
			}
		}

		writeln (res);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        const M = readInt;
        auto C = new long[][](N, M);
        foreach (i; 0 .. N) {
          foreach (j; 0 .. M) {
            C[i][j] = readLong;
          }
        }

        auto fs = new long[N];
        foreach (i; 0 .. N) {
          foreach (j; 0 .. M) {
            fs[i] += j * C[i][j];
          }
        }
        debug {
          writeln("fs = ", fs);
        }
        const minF = fs.minElement;
        const maxF = fs.maxElement;

        int im = -1;
        foreach (i; 0 .. N) {
          if (maxF == fs[i]) {
            im = i;
            break;
          }
        }
        writeln(im + 1, " ", maxF - minF);
      }
    }
  } catch (EOFException e) {
  }
}


Ayush and Ashish play a game on an unrooted tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$. Players make the following move in turns:   Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to $$$1$$$. A tree is a connected undirected graph without cycles.There is a special node numbered $$$x$$$. The player who removes this node wins the game. Ayush moves first. Determine the winner of the game if each player plays optimally.

The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10)$$$ — the number of testcases. The description of the test cases follows. The first line of each testcase contains two integers $$$n$$$ and $$$x$$$ $$$(1\leq n \leq 1000, 1 \leq x \leq n)$$$ — the number of nodes in the tree and the special node respectively. Each of the next $$$n-1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.

For every test case, if Ayush wins the game, print "Ayush", otherwise print "Ashish" (without quotes).

NoteFor the $$$1$$$st test case, Ayush can only remove node $$$2$$$ or $$$3$$$, after which node $$$1$$$ becomes a leaf node and Ashish can remove it in his turn.For the $$$2$$$nd test case, Ayush can remove node $$$2$$$ in the first move itself.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, x;
		readf !(" %s %s") (n, x);
		x -= 1;
		auto d = new int [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			d[u] += 1;
			d[v] += 1;
		}

		bool win = true;
		if (d[x] >= 2)
		{
			win = !(n & 1);
		}
		writeln (win ? "Ayush" : "Ashish");
	}
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n, x;
  @Dim("n - 1") long[2][] edges;

  void solve(long tc = -1)
  {
    long degx = 0;
    foreach(edge; edges)
      {
        if (edge[0] == x || edge[1] == x)
          degx++;
      }
    if (degx <= 1)
      return writeln("Ayush");
    if (n % 2 == 0)
      return writeln("Ayush");
    writeln("Ashish");
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n, x;
  @Dim("n - 1") long[2][] edges;

  void solve(long tc = -1)
  {
    long degx = 0;
    foreach(edge; edges)
      {
        if (edge[0] == x || edge[1] == x)
          degx++;
      }
    if (degx == 1)
      return writeln("Ayush");
    if (n % 2 == 0)
      return writeln("Ayush");
    writeln("Ashish");
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}


Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group.

The first line contains a single integer n (2 ≤ n ≤ 60 000) — the number of integers Petya has.

Print the smallest possible absolute difference in the first line. In the second line print the size of the first group, followed by the integers in that group. You can print these integers in arbitrary order. If there are multiple answers, print any of them.

NoteIn the first example you have to put integers 1 and 4 in the first group, and 2 and 3 in the second. This way the sum in each group is 5, and the absolute difference is 0.In the second example there are only two integers, and since both groups should be non-empty, you have to put one integer in the first group and one in the second. This way the absolute difference of sums of integers in each group is 1.

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

void main() {
    int n;
    scan(n);

    long x = 1L * n * (n + 1) / 4;

    int k = 1;

    while (1L * k * (k + 1) / 2 < x) k++;

    long d = 1L * k * (k + 1) / 2 - x;

    auto ans = new long[](0);

    foreach (i ; 1 .. k + 1) {
        if (i == d) continue;
        ans ~= i;
    }

    long dif = abs(ans.sum(0L) - (1L * n * (n + 1) / 2 - ans.sum(0L)));
    writeln(dif);
    writef("%d ", ans.length);
    writefln("%(%s %)", 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);
        }
    }
}


In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.

The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≤ pi ≤ 105) and an integer qi (1 ≤ qi ≤ 104) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.

Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.

NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.

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

void main ()
{
	int n, s;
	while (readf (" %s %s", &n, &s) > 0)
	{
		readln;
		alias type = int [int];
		type [string] data;
		foreach (i; 0..n)
		{
			auto temp = readln.split.array;
			data[temp[0]][temp[1].to !(int)] += temp[2].to !(int);
		}

		alias Pair = Tuple !(int, q{val}, int, q{num});

		auto sell = new BinaryHeap !(Array !(Pair), q{a > b});
		foreach (val, num; data.get ("S", type.init))
		{
			sell.insert (Pair (val, num));
		}
		sell.take (s).array.retro.each !(x => writeln ("S ", x.val, ' ', x.num));

		auto buy = new BinaryHeap !(Array !(Pair));
		foreach (val, num; data.get ("B", type.init))
		{
			buy.insert (Pair (val, num));
		}
		buy.take (s).each !(x => writeln ("B ", x.val, ' ', x.num));
	}
}

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

void main ()
{
	int n, s;
	while (readf (" %s %s", &n, &s) > 0)
	{
		readln;
		alias type = int [int];
		type [string] data;
		foreach (i; 0..n)
		{
			auto temp = readln.split.array;
			data[temp[0]][temp[1].to !(int)] += temp[2].to !(int);
		}

		alias Pair = Tuple !(int, q{val}, int, q{num});

		auto sell = new BinaryHeap !(Array !(Pair));
		foreach (val, num; data.get ("S", type.init))
		{
			sell.insert (Pair (val, num));
		}
		sell.take (s).each !(x => writeln ("S ", x.val, ' ', x.num));

		auto buy = new BinaryHeap !(Array !(Pair));
		foreach (val, num; data.get ("B", type.init))
		{
			buy.insert (Pair (val, num));
		}
		buy.take (s).each !(x => writeln ("B ", x.val, ' ', x.num));
	}
}


An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.

The single line of the input contains integer k (1 ≤ k ≤ 100) — the required degree of the vertices of the regular graph.

Print "NO" (without quotes), if such graph doesn't exist.  Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines. The description of the made graph must start with numbers n and m — the number of vertices and edges respectively.  Each of the next m lines must contain two integers, a and b (1 ≤ a, b ≤ n, a ≠ b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order. The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).

NoteIn the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.

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

int K, L;

void solve(int s) {
  foreach (i; 0..L*L) {
    foreach (j; 1..L/2+1) {
      writeln(s + i, ' ', (s + (i + j) % (L * L)));
    }
  }
  int t = s + L * L;
  foreach (i; 0..L*L) {
    writeln(t + (i / L), ' ', s + i);
  }
  int u = t + L;
  foreach (i; 0..L) {
    writeln(u, ' ', t + i);
  }
}

void main() {
  K = readln().strip().to!int;
  L = K - 1;
  int[] vs;
  if (K == 1) {
    writeln("YES");
    writeln(2, ' ', 1);
    writeln(1, ' ', 2);
  } else if (K % 2 == 0) {
    writeln("NO");
  } else {
    writeln("YES");
    int V = 2 * (L * L + L + 1);
    writeln(V, ' ', V * K / 2);
    solve(1);
    solve(L * L + L + 1 + 1);
    writeln(1 + L * L + L, ' ', (L * L + L + 2) + L * L + L);
  }

}

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

void main() {
  int K = readln().strip().to!int;
  if (K == 1) {
    writeln("YES");
    writeln(2, ' ', 1);
    writeln(1, ' ', 2);
  } else {
    writeln("NO");
  }
}

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

int K, L;

void solve(int s) {
  foreach (i; 0..L*L) {
    foreach (j; 1..L/2+1) {
      writeln(s + i, ' ', (s + (i + j) % (L * L)));
    }
  }
  int t = s + L * L;
  foreach (i; 0..L*L) {
    writeln(t + (i / L), ' ', s + i);
  }
  int u = t + L;
  foreach (i; 0..L) {
    writeln(u, ' ', t + i);
  }
}

void main() {
  K = readln().strip().to!int;
  L = K - 1;
  int[] vs;
  if (K == 1) {
    writeln("YES");
    writeln(2, ' ', 1);
    writeln(1, ' ', 2);
  } else if (K % 2 == 0) {
    writeln("NO");
  } else {
    writeln("YES");
    int V = 2 * (L * L + L + 1);
    writeln(V, ' ', V * K / 2);
    solve(1);
    solve(L * L + L + 1);
    writeln(1 + L * L + L, ' ', 2 * (L * L + L + 1));
  }

}


You have got a shelf and want to put some books on it.You are given $$$q$$$ queries of three types:  L $$$id$$$ — put a book having index $$$id$$$ on the shelf to the left from the leftmost existing book;  R $$$id$$$ — put a book having index $$$id$$$ on the shelf to the right from the rightmost existing book;  ? $$$id$$$ — calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index $$$id$$$ will be leftmost or rightmost. You can assume that the first book you will put can have any position (it does not matter) and queries of type $$$3$$$ are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so $$$id$$$s don't repeat in queries of first two types.Your problem is to answer all the queries of type $$$3$$$ in order they appear in the input.Note that after answering the query of type $$$3$$$ all the books remain on the shelf and the relative order of books does not change.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow. The $$$i$$$-th line contains the $$$i$$$-th query in format as in the problem statement. It is guaranteed that queries are always valid (for query type $$$3$$$, it is guaranteed that the book in each such query is already placed, and for other types, it is guaranteed that the book was not placed before). It is guaranteed that there is at least one query of type $$$3$$$ in the input. In each query the constraint $$$1 \le id \le 2 \cdot 10^5$$$ is met.

Print answers to queries of the type $$$3$$$ in order they appear in the input.

NoteLet's take a look at the first example and let's consider queries:   The shelf will look like $$$[1]$$$;  The shelf will look like $$$[1, 2]$$$;  The shelf will look like $$$[1, 2, 3]$$$;  The shelf looks like $$$[1, \textbf{2}, 3]$$$ so the answer is $$$1$$$;  The shelf will look like $$$[4, 1, 2, 3]$$$;  The shelf looks like $$$[4, \textbf{1}, 2, 3]$$$ so the answer is $$$1$$$;  The shelf will look like $$$[5, 4, 1, 2, 3]$$$;  The shelf looks like $$$[5, 4, \textbf{1}, 2, 3]$$$ so the answer is $$$2$$$. Let's take a look at the second example and let's consider queries:   The shelf will look like $$$[100]$$$;  The shelf will look like $$$[100, 100000]$$$;  The shelf will look like $$$[100, 100000, 123]$$$;  The shelf will look like $$$[101, 100, 100000, 123]$$$;  The shelf looks like $$$[101, 100, 100000, \textbf{123}]$$$ so the answer is $$$0$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123]$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123, 115]$$$;  The shelf looks like $$$[10, 101, \textbf{100}, 100000, 123, 115]$$$ so the answer is $$$2$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123, 115, 110]$$$;  The shelf looks like $$$[10, 101, 100, 100000, 123, \textbf{115}, 110]$$$ so the answer is $$$1$$$.

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

  int q;
  rd(q);
  int l = 0, r = 0; // [l, r)
  auto pos = new int[](2 * 10 ^^ 5 + 1);
  while (q--) {
    char t;
    int x;
    rd(t, x);
    if (t == 'L') {
      pos[x] = --l;
    } else if (t == 'R') {
      pos[x] = r++;
    } else {
      writeln(min(pos[x] - l, r - pos[x] - 1));
    }
  }
}

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 main() {
  import std.stdio, std.string, std.conv, std.algorithm;

  int q;
  rd(q);
  int l = 0, r = 1; // [l, r)
  auto pos = new int[](2 * 10 ^^ 5 + 1);
  while (q--) {
    char t;
    int x;
    rd(t, x);
    if (t == 'L') {
      pos[x] = --l;
    } else if (t == 'R') {
      pos[x] = r++;
    } else {
      writeln(min(pos[x] - l, r - pos[x] - 1));
    }
  }
}

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