Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions:   Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units;  Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.

The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100).

In the single line print a single number — the answer to the problem.

NoteConsider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units.The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units.

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

void main()
{
    for(string S; (S=readln().chomp()).length; )
    {
        auto m = S.split().map!(to!int)();
        auto n = m[0], l=m[1], r=m[2], Ql=m[3], Qr=m[4];
        auto w = array(readln().split().map!(to!int)());
        auto sl = new int[n+1];
        auto sr = new int[n+1];
        foreach(i;0..n)
            sl[i+1] = sl[i]+w[i]*l,
            sr[n-i-1] = sr[n-i]+w[n-i-1]*r;
        auto s = int.max;
        foreach(i;0..n+1)
            s = min(s,sl[i]+max(0,Ql*(i*2-n-1))+sr[i]+max(0,Qr*(n-i*2-1)));
        writeln(s);
    }
}


You are given four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$. Timur and three other people are running a marathon. The value $$$a$$$ is the distance that Timur has run and $$$b$$$, $$$c$$$, $$$d$$$ correspond to the distances the other three participants ran. Output the number of participants in front of Timur.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of each test case consists of four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \leq a, b, c, d \leq 10^4$$$).

For each test case, output a single integer — the number of participants in front of Timur.

NoteFor the first test case, there are $$$2$$$ people in front of Timur, specifically the participants who ran distances of $$$3$$$ and $$$4$$$. The other participant is not in front of Timur because he ran a shorter distance than Timur.For the second test case, no one is in front of Timur, since he ran a distance of $$$10000$$$ while all others ran a distance of $$$0$$$, $$$1$$$, and $$$2$$$ respectively.For the third test case, only the second person is in front of Timur, who ran a total distance of $$$600$$$ while Timur ran a distance of $$$500$$$.

void main() { runSolver(); }

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

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

      return BCD.count!(x => x > A);
    }

    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"];

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


You are given two integers $$$n$$$ and $$$m$$$. You have to construct the array $$$a$$$ of length $$$n$$$ consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly $$$m$$$ and the value $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ is the maximum possible. Recall that $$$|x|$$$ is the absolute value of $$$x$$$.In other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array $$$a=[1, 3, 2, 5, 5, 0]$$$ then the value above for this array is $$$|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$$$. Note that this example doesn't show the optimal answer but it shows how the required value for some array is calculated.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — the length of the array and its sum correspondingly.

For each test case, print the answer — the maximum possible value of $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ for the array $$$a$$$ consisting of $$$n$$$ non-negative integers with the sum $$$m$$$.

NoteIn the first test case of the example, the only possible array is $$$[100]$$$ and the answer is obviously $$$0$$$.In the second test case of the example, one of the possible arrays is $$$[2, 0]$$$ and the answer is $$$|2-0| = 2$$$.In the third test case of the example, one of the possible arrays is $$$[0, 2, 0, 3, 0]$$$ and the answer is $$$|0-2| + |2-0| + |0-3| + |3-0| = 10$$$.

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;
		readf !(" %s %s") (n, m);
		writeln (n == 1 ? 0 : n == 2 ? m : 2 * m);
	}
}

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 int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;

		if (n == 1) continue;
		else if (n == 2)
			ans[ti] = m;
		else
			ans[ti] = m * 2;
	}

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


Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.There were $$$n$$$ classes of that subject during the semester and on $$$i$$$-th class professor mentioned some non-negative integer $$$a_i$$$ to the students. It turned out, the exam was to tell the whole sequence back to the professor. Sounds easy enough for those who attended every class, doesn't it?Obviously Mishka didn't attend any classes. However, professor left some clues on the values of $$$a$$$ to help out students like Mishka:   $$$a$$$ was sorted in non-decreasing order ($$$a_1 \le a_2 \le \dots \le a_n$$$);  $$$n$$$ was even;  the following sequence $$$b$$$, consisting of $$$\frac n 2$$$ elements, was formed and given out to students: $$$b_i = a_i + a_{n - i + 1}$$$. Professor also mentioned that any sequence $$$a$$$, which produces sequence $$$b$$$ with the presented technique, will be acceptable.Help Mishka to pass that last exam. Restore any sorted sequence $$$a$$$ of non-negative integers, which produces sequence $$$b$$$ with the presented technique. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of sequence $$$a$$$. $$$n$$$ is always even. The second line contains $$$\frac n 2$$$ integers $$$b_1, b_2, \dots, b_{\frac n 2}$$$ ($$$0 \le b_i \le 10^{18}$$$) — sequence $$$b$$$, where $$$b_i = a_i + a_{n - i + 1}$$$. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.

Print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{18}$$$) in a single line. $$$a_1 \le a_2 \le \dots \le a_n$$$ should be satisfied. $$$b_i = a_i + a_{n - i + 1}$$$ should be satisfied for all valid $$$i$$$.

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 N = readln.chomp.to!int;
    auto B = readln.split.map!(to!long).array;
    auto A = new long[](N);
    A[0] = 0;
    A[N-1] = B[0];

    for (int i = 1, j = N - 2; i < j; ++i, --j) {
        long x = min(B[i]-A[i-1], A[j+1]);
        A[i] = B[i] - x;
        A[j] = x;
    }

    A.map!(to!string).join(" ").writeln;
}


After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.

The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one.  The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1.

Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.

import std.conv;
import std.ascii;
import std.stdio;
import std.string;

void main() {
	auto n = readln.strip.to!uint;
	auto s = readln.strip;

	uint res;
	uint[char] aa;

	while(s.length) {
		aa[std.ascii.toUpper(s[0])]++;

		if(aa.get(s[1], 0)) aa[s[1]]--;
		else res++;

		s = s[2..$];
	}

	res.write;
}


There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then:  if he enters 00 two numbers will show up: 100000000 and 100123456,  if he enters 123 two numbers will show up 123456789 and 100123456,  if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.

The first line contains single integer n (1 ≤ n ≤ 70000) — the total number of phone contacts in Polycarp's contacts. The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.

Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.

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

void main() {
    auto N = readln.chomp.to!int;
    auto S = N.iota.map!(_ => readln.chomp).array;
    int[string] cnt;

    foreach (s; S) {
        bool[string] used;
        foreach (i; 0..9) {
            foreach (j; i..10) {
                if (s[i..j] in used)
                    continue;
                cnt[s[i..j]] += 1;
                used[s[i..j]] = true;
            }
        }
    }

    void solve(int ind) {
        foreach (len; 1..10)
            foreach (i; 0..10-len)
                if (cnt[S[ind][i..i+len]] == 1) {
                    writeln(S[ind][i..i+len]);
                    return;
                }
    }

    foreach (i; 0..N)
        solve(i);

}

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;

immutable int letters = 10;

struct Node
{
	string mark;
	int p;
	int visits;
	int [letters] next;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = new string [n];
		foreach (ref c; s)
		{
			c = readln.strip;
		}

		Node [] t;
		t.reserve (1 + n * 9);
		t ~= Node ();
		foreach (int i, b; s)
		{
			foreach (int j; 0..b.length)
			{
				auto c = b[j..$];
				int v = 0;
				while (!c.empty)
				{
					int d = c.front - '0';
					c.popFront ();
					if (!t[v].next[d])
					{
						t[v].next[d] =
						    t.length.to !(int);
						t ~= Node (s[i][j..$ -
						    c.length], i, 1);
					}
					v = t[v].next[d];
					t[v].visits += (t[v].p != i);
				}
			}
		}

		foreach (ref w; t)
		{
			debug {writeln (w);}
			if (w.visits == 1 &&
			    s[w.p].length > w.mark.length)
			{
				s[w.p] = w.mark;
			}
		}

		writefln ("%-(%s\n%)", s);
	}
}

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 L = 9;

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

      alias Entry = Tuple!(int, "val", int, "i");
      auto ess = new Entry[][L + 1];
      foreach (i; 0 .. N) {
        foreach (x; 0 .. L) {
          int val;
          foreach (y; x .. L) {
            val = val * 10 + (A[i][y] - '0');
            ess[y + 1 - x] ~= Entry(val, i);
          }
        }
      }

      auto opt = new int[N];
      opt[] = L + 1;
      auto ans = new int[N];
      foreach (l; 1 .. L + 1) {
        auto es = ess[l];
        es.sort;
        const esLen = cast(int)(es.length);
        for (int j = 0, k; j < esLen; j = k) {
          for (k = j; k < esLen && es[j].val == es[k].val; ++k) {}
          if (es[j].i == es[k - 1].i) {
            const i = es[j].i;
            if (chmin(opt[i], l)) {
              ans[i] = es[j].val;
            }
          }
        }
      }

      foreach (i; 0 .. N) {
        writefln("%0*d", opt[i], ans[i]);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto S = N.iota.map!(_ => readln.chomp).array;
    int[string] cnt;
    foreach (s; S)
        foreach (i; 0..9)
            foreach (j; i..10)
                cnt[s[i..j]] += 1;

    void solve(int ind) {
        foreach (len; 1..10)
            foreach (i; 0..10-len)
                if (cnt[S[ind][i..i+len]] == 1) {
                    writeln(S[ind][i..i+len]);
                    return;
                }
    }

    foreach (i; 0..N)
        solve(i);
}


Suppose you have two polynomials  and . Then polynomial  can be uniquely represented in the following way:This can be done using long division. Here,  denotes the degree of polynomial P(x).  is called the remainder of division of polynomial  by polynomial , it is also denoted as . Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials . If the polynomial  is zero, the result is , otherwise the result is the value the algorithm returns for pair . On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question. You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair  to pair .

You are given a single integer n (1 ≤ n ≤ 150) — the number of steps of the algorithm you need to reach.

Print two polynomials in the following format. In the first line print a single integer m (0 ≤ m ≤ n) — the degree of the polynomial.  In the second line print m + 1 integers between  - 1 and 1 — the coefficients of the polynomial, from constant to leading.  The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly n steps when called using these polynomials. If there is no answer for the given n, print -1. If there are multiple answer, print any of them.

NoteIn the second example you can print polynomials x2 - 1 and x. The sequence of transitions is(x2 - 1, x) → (x,  - 1) → ( - 1, 0).There are two steps in it.

/+ dub.sdl:
    name "B"
    dependency "dcomp" version=">=0.9.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner;

import std.typecons;

int main() {
    Scanner sc = new Scanner(stdin);
    int n;
    sc.read(n);
    int[] a = [1];
    int[] b = [];
    foreach (_; 0..n) {
        swap(a, b);
        auto c = [0] ~ b.dup;
        foreach (i; 0..a.length) {
            c[i] += a[i]; c[i] %= 2;
        }
        a = c;
    }
    writeln(a.length - 1);
    writeln(a.map!(to!string).join(" "));
    writeln(b.length - 1);
    writeln(b.map!(to!string).join(" "));
    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/foundation.d */

// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

// import dcomp.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/container/stackpayload.d */
// module dcomp.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/*
This source code generated by dcomp and include dcomp's source code.
dcomp's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dcomp)
dcomp's License: MIT License(https://github.com/yosupo06/dcomp/blob/master/LICENSE.txt)
*/

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();
      int[] fs = [0, 1];
      int[] gs = [1];
      foreach (i; 1 .. N) {
        // g + X f
        auto hs = gs.dup;
        hs ~= [0, 0];
        hs[1 .. $] += fs[];
        if (hs.any!"abs(a) > 1") {
          hs[1 .. $] -= fs[];
          hs[1 .. $] -= fs[];
        }
        if (hs.any!"abs(a) > 1") {
          assert(false);
        }
        gs = fs;
        fs = hs;
      }

      if (fs[$ - 1] < 0) {
        fs[] *= -1;
      }
      if (gs[$ - 1] < 0) {
        gs[] *= -1;
      }

      writeln(N);
      foreach (j; 0 .. N) {
        write(fs[j], " ");
      }
      writeln(fs[N]);
      writeln(N - 1);
      foreach (j; 0 .. N - 1) {
        write(gs[j], " ");
      }
      writeln(gs[N - 1]);
    }
  } catch (EOFException e) {
  }
}


You are given a sequence of n positive integers d1, d2, ..., dn (d1 < d2 < ... < dn). Your task is to construct an undirected graph such that:  there are exactly dn + 1 vertices;  there are no self-loops;  there are no multiple edges;  there are no more than 106 edges;  its degree set is equal to d. Vertices should be numbered 1 through (dn + 1).Degree sequence is an array a with length equal to the number of vertices in a graph such that ai is the number of vertices adjacent to i-th vertex.Degree set is a sorted in increasing order sequence of all distinct values from the degree sequence.It is guaranteed that there exists such a graph that all the conditions hold, and it contains no more than 106 edges.Print the resulting graph.

The first line contains one integer n (1 ≤ n ≤ 300) — the size of the degree set. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 1000, d1 < d2 < ... < dn) — the degree set.

In the first line print one integer m (1 ≤ m ≤ 106) — the number of edges in the resulting graph. It is guaranteed that there exists such a graph that all the conditions hold and it contains no more than 106 edges. Each of the next m lines should contain two integers vi and ui (1 ≤ vi, ui ≤ dn + 1) — the description of the i-th edge.

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

uint solve(uint[] d, ref uint[][] e, ref uint m)
{
  // zero-length degree set, just a single vertex
  if (d.length == 0) {
    return 1;
  }

  // connected clique of d[0]+1 vertices
  // this is a base case, so we can start at the
  // beginning of the edge list
  if (d.length == 1) {
    auto n = d[0]+1;
    foreach (i; 0..n) {
      foreach (j; 0..i) {
	e[j] ~= i;
	m++;
      }
    }

    return n;
  }

  // length of previous vertex set
  uint[] dt = d[1..$-1].dup;
  dt[] -= d[0];
  auto s = solve(dt, e, m);
  auto t = d[$-1] - d[$-2];
  // add t vertices not connected to anything
  s += t;
  // add d[0] vertices connected to all previous vertices
  foreach (i; 0..d[0]) {
    foreach (j; 0..s+i) {
      e[j] ~= s+i;
      m++;
    }
  }

  return s+d[0];
}

void main()
{
  uint n;
  readf!"%d\n"(n);

  auto d = readln.stripRight.split.map!(a => a.parse!uint).array;
  auto e = new uint[][](d[$-1]+1);
  uint m = 0;
  solve(d, e, m);

  writeln(m);

  foreach (i; 0..e.length) {
    foreach (j; e[i]) {
      writefln("%d %d", i+1, j+1);
    }
  }
}


Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so that all brothers got the same number of candies.

The single line contains a single integer n (n is even, 2 ≤ n ≤ 100) — the number of Gerald's brothers.

Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers — the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n2. You can print the numbers in the lines in any order.  It is guaranteed that the solution exists at the given limits.

NoteThe sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.

module A;

import std.stdio: readln, writeln, write;
import std.string: strip;
import std.array: split;
import std.conv: to;
import std.math: pow;

/**
 * User: Jior
 * Date: 27.07.13
 * Time: 12:30
 */

enum target {
    next,
    back
}

void main(string[] args) {
    auto br = strip(readln()).to!(int); //количество братьев
    auto pak = pow(br, 2); // количество пакетиков
    auto kon = (1 + pak) / 2.0 * pak; // количество конфет в пакетиках

    int[][] pks = new int[][br];

    int cur_br;
    target t = target.back;
    foreach(int p; 1..pak+1) {
        if(t == target.next)
            ++cur_br;
        if (t == target.back)
            --cur_br;

        if(cur_br >= br) {
            --cur_br;
            t = target.back;
        }

        if(cur_br < 0) {
            ++cur_br;
            t = target.next;
        }

        pks[cur_br] ~= p;
    }

    foreach(line; pks) {
        foreach(i; line) {
            write(i, " ");
        }
        writeln();
    }
}


There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to n where n is the total number of messages in the chat.Each message might contain a link to an earlier message which it is a reply to. When opening a message x or getting a link to it, the dialogue is shown in such a way that k previous messages, message x and k next messages are visible (with respect to message x). In case there are less than k messages somewhere, they are yet all shown.Digging deep into your message history, you always read all visible messages and then go by the link in the current message x (if there is one) and continue reading in the same manner.Determine the number of messages you'll read if your start from message number t for all t from 1 to n. Calculate these numbers independently. If you start with message x, the initial configuration is x itself, k previous and k next messages. Messages read multiple times are considered as one.

The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ n) — the total amount of messages and the number of previous and next messages visible. The second line features a sequence of integers a1, a2, ..., an (0 ≤ ai < i), where ai denotes the i-th message link destination or zero, if there's no link from i. All messages are listed in chronological order. It's guaranteed that the link from message x goes to message with number strictly less than x.

Print n integers with i-th denoting the number of distinct messages you can read starting from message i and traversing the links while possible.

NoteConsider i = 6 in sample case one. You will read message 6, then 2, then 1 and then there will be no link to go.In the second sample case i = 6 gives you messages 5, 6, 7 since k = 1, then 4, 5, 6, then 2, 3, 4 and then the link sequence breaks. The number of distinct messages here is equal to 6.

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

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

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

    auto ans = new int[n];
    foreach (i, e; arr) {
        if (e == 0) {
            ans[i] = min(k, i) + 1;
        } else {
            ans[i] = ans[e-1] + 1 + min(2*k, i - e);
        }
    }

    foreach (i, e; arr) {
        ans[i] += min(n-1 - i, k);
    }

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


Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n > 1$$$)  — $$$\min\limits_{1 \leq i < j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.

The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).

Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.

NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, 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)); }

struct ModInt(long M) {
  long x;
  this(in ModInt a) { x = a.x; }
  this(in long a) { x = a % M; if (x < 0) x += M; }
  ModInt opUnary(string op)() if (op == "-") { return ModInt(-x); }
  ref ModInt opOpAssign(string op)(in ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x *= a.x; x %= M; }
    else static assert(false);
    return this;
  }
  ModInt opOpAssign(string op)(in long a) { return mixin("this " ~ op ~ "= ModInt(a)"); }
  ModInt opBinary(string op, T)(in T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(in long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

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

int N, K;
int[] A;

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

      A.sort;
      Mint ans;

      auto dp = new Mint[N];
      auto dpSum = new Mint[N + 1];
      foreach (d; 1 .. (A[$ - 1] - A[0]) / (K - 1) + 1) {
        dp[] = Mint(1);
        foreach (k; 1 .. K) {
          foreach (i; 0 .. N) {
            dpSum[i + 1] = dpSum[i] + dp[i];
          }
          int j = 0;
          foreach (i; 0 .. N) {
            for (; j < N && A[i] - A[j] >= d; ++j) {}
            dp[i] = dpSum[j];
          }
        }
        foreach (i; 0 .. N) {
          ans += dp[i];
        }
      }

      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, 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)); }

struct ModInt(long M) {
  long x;
  this(in ModInt a) { x = a.x; }
  this(in long a) { x = a % M; if (x < 0) x += M; }
  ModInt opUnary(string op)() if (op == "-") { return ModInt(-x); }
  ref ModInt opOpAssign(string op)(in ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x *= a.x; x %= M; }
    else static assert(false);
    return this;
  }
  ModInt opOpAssign(string op)(in long a) { return mixin("this " ~ op ~ "= ModInt(a)"); }
  ModInt opBinary(string op, T)(in T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(in long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

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

int N, K;
int[] A;

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

      A.sort;
      Mint ans;

      auto dp = new Mint[N];
      auto dpSum = new Mint[N + 1];
      foreach (d; 1 .. (A[$ - 1] - A[0]) / K + 1) {
        dp[] = Mint(1);
        foreach (k; 1 .. K) {
          foreach (i; 0 .. N) {
            dpSum[i + 1] = dpSum[i] + dp[i];
          }
          int j = 0;
          foreach (i; 0 .. N) {
            for (; j < N && A[i] - A[j] >= d; ++j) {}
            dp[i] = dpSum[j];
          }
        }
        foreach (i; 0 .. N) {
          ans += dp[i];
        }
      }

      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.

The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied.

If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example.

NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique".

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

immutable int DIRS = 4;
immutable int [DIRS] DROW = [-1,  0, +1,  0];
immutable int [DIRS] DCOL = [ 0, -1,  0, +1];
immutable char [DIRS] DNAME = ['^', '<', 'v', '>'];

void main ()
{
	int n, m;
	while (readf (" %s %s ", &n, &m) > 0)
	{
		char [] [] a;
		a ~= '*'.repeat (m + 2).array ();
		foreach (row; 1..n + 1)
		{
			a ~= '*' ~ readln ().strip ().dup ~ '*';
		}
		a ~= '*'.repeat (m + 2).array ();
		debug {writeln (a);}

		alias Coord = Tuple !(int, "row", int, "col");
		Coord [] q;
		q.reserve ((n + 2) * (m + 2) + 1);

		auto g = new int [] [] (n + 2, m + 2);
		foreach (row; 1..n + 1)
		{
			foreach (col; 1..m + 1)
			{
				if (a[row][col] == '.')
				{
					g[row][col] = sum (DIRS.iota.map
					    !(dir => a[row + DROW[dir]]
					    [col + DCOL[dir]] == '.'));
					if (g[row][col] == 1)
					{
						q ~= Coord (row, col);
					}
				}
			}
		}
		debug {writeln (q);}

		void recalc (int row, int col)
		{
			foreach (dir; 0..DIRS)
			{
				int nrow = row + DROW[dir];
				int ncol = col + DCOL[dir];
				if (a[nrow][ncol] == '.')
				{
					g[nrow][ncol]--;
					if (g[nrow][ncol] == 1)
					{
						q ~= Coord (nrow, ncol);
					}
				}
			}
		}

		while (q.length > 0)
		{
			int row = q.front.row;
			int col = q.front.col;
			q.popFront ();
			q.assumeSafeAppend ();
			if (g[row][col] != 1 || a[row][col] != '.')
			{
				continue;
			}

			foreach (dir; 0..DIRS)
			{
				int nrow = row + DROW[dir];
				int ncol = col + DCOL[dir];
				if (a[nrow][ncol] == '.')
				{
					a[row][col] = DNAME[dir ^ 2];
					a[nrow][ncol] = DNAME[dir ^ 0];
					recalc (row, col);
					recalc (nrow, ncol);
					break;
				}
			}
		}

		if (any !(b => b.find ('.').length > 0) (a))
		{
			writeln ("Not unique");
		}
		else
		{
			writefln ("%-(%-(%s%)\n%)",
			    a[1..n + 1].map !(b => b[1..m + 1]));
		}
	}
}

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

//	Input
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[0]; tokens.popFront; return token; }
int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

//	chmin/chmax
void chmin(T)(ref T t, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

immutable DX = [ +1, 0, -1, 0, ];
immutable DY = [ 0, +1, 0, -1, ];

int M, N;
char[][] A;

bool solve() {
	int[][] deg = new int[][](M, N);
	foreach (x; 0 .. M) foreach (y; 0 .. N) if (A[x][y] == '.') {
		foreach (dir; 0 .. 4) {
			const xx = x + DX[dir];
			const yy = y + DY[dir];
			if (0 <= xx && xx < M && 0 <= yy && yy < N) {
				if (A[xx][yy] == '.') {
					++deg[x][y];
				}
			}
		}
	}
	Pair!(int, int)[] q;
	foreach (x; 0 .. M) foreach (y; 0 .. N) if (A[x][y] == '.') {
		if (deg[x][y] == 1) {
			q ~= pair(x, y);
		}
	}
	for (; !q.empty; ) {
debug{
writeln;
foreach(x;0..M)writeln(A[x].to!string);
}
		const x = q.front.x;
		const y = q.front.y;
		q.popFront;
		if (A[x][y] == '.' && deg[x][y] == 1) {
debug{
writeln(x," ",y);
}
			foreach (dir; 0 .. 4) {
				const xx = x + DX[dir];
				const yy = y + DY[dir];
				if (0 <= xx && xx < M && 0 <= yy && yy < N) {
					if (A[xx][yy] == '.') {
						A[x][y]   = "^<v>"[dir];
						A[xx][yy] = "v>^<"[dir];
						foreach (dir1; 0 .. 4) {
							const xxx = xx + DX[dir1];
							const yyy = yy + DY[dir1];
							if (0 <= xxx && xxx < M && 0 <= yyy && yyy < N) {
								if (A[xxx][yyy] == '.') {
									if (--deg[xxx][yyy] == 1) {
										q ~= pair(xxx, yyy);
									}
								}
							}
						}
						break;
					}
				}
			}
		}
	}
	foreach (x; 0 .. M) foreach (y; 0 .. N) {
		if (A[x][y] == '.') {
			return false;
		}
	}
	foreach (x; 0 .. M) {
		writeln(A[x].to!string);
	}
	return true;
}

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = new char[][M];
		foreach (x; 0 .. M) {
			A[x] = readToken.to!(char[]);
		}

		const res = solve;
		if (!res) {
			writeln("Not unique");
		}

	}
	} catch (EOFException) {}
}


Vasya is reading a e-book. The file of the book consists of $$$n$$$ pages, numbered from $$$1$$$ to $$$n$$$. The screen is currently displaying the contents of page $$$x$$$, and Vasya wants to read the page $$$y$$$. There are two buttons on the book which allow Vasya to scroll $$$d$$$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $$$10$$$ pages, and $$$d = 3$$$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.Help Vasya to calculate the minimum number of times he needs to press a button to move to page $$$y$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases. Each testcase is denoted by a line containing four integers $$$n$$$, $$$x$$$, $$$y$$$, $$$d$$$ ($$$1\le n, d \le 10^9$$$, $$$1 \le x, y \le n$$$) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively.

Print one line for each test. If Vasya can move from page $$$x$$$ to page $$$y$$$, print the minimum number of times he needs to press a button to do it. Otherwise print $$$-1$$$.

NoteIn the first test case the optimal sequence is: $$$4 \rightarrow 2 \rightarrow 1 \rightarrow 3 \rightarrow 5$$$.In the second test case it is possible to get to pages $$$1$$$ and $$$5$$$.In the third test case the optimal sequence is: $$$4 \rightarrow 7 \rightarrow 10 \rightarrow 13 \rightarrow 16 \rightarrow 19$$$.

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

immutable long INF = 1L << 59;

void main() {
    auto T = readln.chomp.to!int;

    while (T--) {
        auto s = readln.split.map!(to!long);
        auto N = s[0];
        auto X = s[1];
        auto Y = s[2];
        auto D = s[3];
        long tmp1 = INF;
        long tmp2 = INF;
        long tmp3 = INF;
        if (abs(X - Y) % D == 0) {
            tmp1 = abs(X - Y) / D;
        }
        if (abs(Y - 1) % D == 0) {
            tmp2 = abs(X - 1) / D + (abs(X - 1) % D > 0) + abs(Y - 1) / D;
        }
        if (abs(Y - N) % D == 0) {
            tmp3 = abs(X - N) / D + (abs(X - N) % D > 0) + abs(Y - N) / D;
        }

        long ans = min(tmp1, tmp2, tmp3);
        writeln(ans == INF ? -1 : ans);
    }
}


"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.With that begins the watch of Jon Snow. He is assigned the task to support the stewards.This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.Can you find how many stewards will Jon support?

First line consists of a single integer n (1 ≤ n ≤ 105) — the number of stewards with Jon Snow. Second line consists of n space separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) representing the values assigned to the stewards.

Output a single integer representing the number of stewards which Jon will feed.

NoteIn the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5.In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		sort (a);
		while (a.length > 2 && a[0] == a[1])
		{
			a = a[1..$];
		}
		while (a.length > 2 && a[$ - 2] == a[$ - 1])
		{
			a = a[0..$ - 1];
		}
		writeln (max (0, cast (int) (a.length) - 2));
	}
}


You are given three integers $$$a$$$, $$$b$$$ and $$$c$$$.Find two positive integers $$$x$$$ and $$$y$$$ ($$$x > 0$$$, $$$y > 0$$$) such that:   the decimal representation of $$$x$$$ without leading zeroes consists of $$$a$$$ digits;  the decimal representation of $$$y$$$ without leading zeroes consists of $$$b$$$ digits;  the decimal representation of $$$gcd(x, y)$$$ without leading zeroes consists of $$$c$$$ digits. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.Output $$$x$$$ and $$$y$$$. If there are multiple answers, output any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 285$$$) — the number of testcases. Each of the next $$$t$$$ lines contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b \le 9$$$, $$$1 \le c \le min(a, b)$$$) — the required lengths of the numbers. It can be shown that the answer exists for all testcases under the given constraints. Additional constraint on the input: all testcases are different.

For each testcase print two positive integers — $$$x$$$ and $$$y$$$ ($$$x > 0$$$, $$$y > 0$$$) such that    the decimal representation of $$$x$$$ without leading zeroes consists of $$$a$$$ digits;  the decimal representation of $$$y$$$ without leading zeroes consists of $$$b$$$ digits;  the decimal representation of $$$gcd(x, y)$$$ without leading zeroes consists of $$$c$$$ digits.

import std.stdio;

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

  for(int k = 0; k < t; ++k) {
    int a, b, c;
    readf("%d %d %d\n", &a, &b, &c);

    write("1");
    for(int i = 0; i < a-1; ++i) write("0");
    write(" ");
    for(int i = 0; i < b-c+1; ++i) write("1");
    for(int i = 0; i < c-1; ++i) write("0");
    writeln();
  }
}

// Yo lo quiero más rápido

import std.stdio;

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

  for(int k = 0; k < t; ++k) {
    int a, b, c;
    readf("%d %d %d\n", &a, &b, &c);

    if(a > b) {
      write("1");
      for(int i = 0; i < a-1; ++i) write("0");
      write(" ");
      for(int i = 0; i < b-c+1; ++i) write("1");
      for(int i = 0; i < b-(b-c+1); ++i) write("0");
      writeln();
    } else {
      for(int i = 0; i < a-c+1; ++i) write("1");
      for(int i = 0; i < a-(a-c+1); ++i) write("0");
      write(" ");
      write("1");
      for(int i = 0; i < b-1; ++i) write("0");
      writeln();
    }
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new string[][](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto c = RD;

		ans[ti].length = 2;
		if (a >= b)
		{
			ans[ti][0] ~= '1';
			foreach (i; 0..a-1)
				ans[ti][0] ~= '0';
			if (b == c)
			{
				ans[ti][1] ~= '1';
				foreach (i; 0..b-1)
					ans[ti][1] ~= '0';
			}
			else
			{
				ans[ti][1] ~= '1';
				foreach (i; 1..b)
				{
					if (i == b-c)
						ans[ti][1] ~= '1';
					else
						ans[ti][1] ~= '0';
				}
			}
		}
		else
		{
			ans[ti][1] ~= '1';
			foreach (i; 0..b-1)
				ans[ti][1] ~= '0';
			if (a == c)
			{
				ans[ti][0] ~= '1';
				foreach (i; 0..a-1)
					ans[ti][0] ~= '0';
			}
			else
			{
				ans[ti][0] ~= '1';
				foreach (i; 1..a)
				{
					if (i == a-c)
						ans[ti][0] ~= '1';
					else
						ans[ti][0] ~= '0';
				}
			}
		}
		debug writeln("gcd:", gcd(ans[ti][0].to!long, ans[ti][1].to!long));
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1]);
	stdout.flush;
	debug readln;
}

import std.stdio;

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

  for(int k = 0; k < t; ++k) {
    int a, b, c;
    readf("%d %d %d\n", &a, &b, &c);

    if(a > b) {
      write("1");
      for(int i = 0; i < a-1; ++i) write("0");
      write(" ");
      for(int i = 0; i < b-c+1; ++i) write("1");
      for(int i = 0; i < b-(b-c+1); ++i) write("0");
      writeln();
    } else {
      for(int i = 0; i < b-c+1; ++i) write("1");
      for(int i = 0; i < b-(b-c+1); ++i) write("0");
      write(" ");
      write("1");
      for(int i = 0; i < a-1; ++i) write("0");
      writeln();
    }
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new string[][](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto c = RD;

		ans[ti].length = 2;
		if (a >= b)
		{
			ans[ti][0] ~= '1';
			foreach (i; 0..a-1)
				ans[ti][0] ~= '0';
			if (b == c)
				ans[ti][1] = ans[ti][0];
			else
			{
				ans[ti][1] ~= '1';
				foreach (i; 1..b)
				{
					if (i == b-c)
						ans[ti][1] ~= '1';
					else
						ans[ti][1] ~= '0';
				}
			}
		}
		else
		{
			ans[ti][1] ~= '1';
			foreach (i; 0..b-1)
				ans[ti][1] ~= '0';
			if (a == c)
				ans[ti][0] = ans[ti][1];
			else
			{
				ans[ti][0] ~= '1';
				foreach (i; 1..a)
				{
					if (i == a-c)
						ans[ti][0] ~= '1';
					else
						ans[ti][0] ~= '0';
				}
			}
		}
		debug writeln("gcd:", gcd(ans[ti][0].to!long, ans[ti][1].to!long));
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1]);
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	writeln(gcd(1010, 1111));
	auto t = RD!int;
	auto ans = new string[][](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto c = RD;

		ans[ti].length = 2;
		if (a >= b)
		{
			foreach (i; 0..a)
				ans[ti][0] ~= '1';
			if (b == c)
				ans[ti][1] = ans[ti][0];
			else
			{
				foreach (i; 0..b)
				{
					if (i == b-c)
						ans[ti][1] ~= '0';
					else
						ans[ti][1] ~= '1';
				}
			}
		}
		else
		{
			foreach (i; 0..b)
				ans[ti][1] ~= '1';
			if (a == c)
				ans[ti][0] = ans[ti][1];
			else
			{
				foreach (i; 0..a)
				{
					if (i == a-c)
						ans[ti][0] ~= '0';
					else
						ans[ti][0] ~= '1';
				}
			}
		}
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1]);
	stdout.flush;
	debug readln;
}


Inna and Dima bought a table of size n × m in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A".Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows:  initially, Inna chooses some cell of the table where letter "D" is written;  then Inna can move to some side-adjacent table cell that contains letter "I"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter "M"; then she can go to a side-adjacent cell that contains letter "A". Then Inna assumes that she has gone through her sweetheart's name;  Inna's next move can be going to one of the side-adjacent table cells that contains letter "D" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter "D" she always goes to the letter "I", from the letter "I" she always goes the to letter "M", from the letter "M" she always goes to the letter "A", and from the letter "A" she always goes to the letter "D". Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 103).  Then follow n lines that describe Inna and Dima's table. Each line contains m characters. Each character is one of the following four characters: "D", "I", "M", "A".  Note that it is not guaranteed that the table contains at least one letter "D".

If Inna cannot go through name DIMA once, print on a single line "Poor Dima!" without the quotes. If there is the infinite number of names DIMA Inna can go through, print "Poor Inna!" without the quotes. Otherwise print a single integer — the maximum number of times Inna can go through name DIMA.

NoteNotes to the samples:In the first test sample, Inna cannot go through name DIMA a single time.In the second test sample, Inna can go through the infinite number of words DIMA. For that, she should move in the clockwise direction starting from the lower right corner.In the third test sample the best strategy is to start from the cell in the upper left corner of the table. Starting from this cell, Inna can go through name DIMA four times.

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

bool solve(ref int[] ans, ref int[][] G, ref int[] vis, int x) {
    if(vis[x]) return false;
    if(ans[x] != -1) return true;
    ans[x] =1;
    vis[x] =true;
    for(int i =0; i < G[x].length; i++)
        if(!solve(ans,G,vis,G[x][i])) return false;
    for(int i =0; i < G[x].length; i++) ans[x] =max(ans[x],ans[G[x][i]]+1);
    vis[x] =false;
    return true;}

void main() {
    int N,M;
    scanf(" %d %d\n",&N,&M);
    string A[]; A.length =N;
    for(int i =0; i < N; i++) A[i] =chomp(readln());

    int G[][]; G.length =N*M;
    int dx[] =[1,-1,0,0];
    int dy[] =[0,0,1,-1];
    for(int i =0; i < N; i++) for(int j =0; j < M; j++)
        for(int k =0; k < 4; k++) {
            int x =i+dx[k], y =j+dy[k];
            if(x < 0 || y < 0 || x >= N || y >= M) continue;
            if(A[i][j] == 'D' && A[x][y] == 'I') G[i*M+j] ~=(x*M+y);
            else if(A[i][j] == 'I' && A[x][y] == 'M') G[i*M+j] ~=(x*M+y);
            else if(A[i][j] == 'M' && A[x][y] == 'A') G[i*M+j] ~=(x*M+y);
            else if(A[i][j] == 'A' && A[x][y] == 'D') G[i*M+j] ~=(x*M+y);}

    int ans[]; ans.length =N*M;
    int vis[]; vis.length =N*M;
    for(int i =0; i < N*M; i++) ans[i] =-1, vis[i] =false;
    for(int i =0; i < N*M; i++) if(ans[i] == -1)
        if(!solve(ans,G,vis,i)) {
            writeln("Poor Inna!");
            return;}
    int ansR =0;
    for(int i =0; i < N*M; i++)
        if(A[i/M][i%M] == 'D') ansR =max(ansR,ans[i]/4);
    if(ansR == 0) writeln("Poor Dima!");
    else writeln(ansR);}

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

bool solve(ref int[] ans, ref int[][] G, ref int[] vis, int x) {
    if(vis[x]) return false;
    ans[x] =1;
    vis[x] =true;
    for(int i =0; i < G[x].length; i++) {
        if(x == 13) writeln(G[x][i]);
        if(!solve(ans,G,vis,G[x][i])) return false;}
    for(int i =0; i < G[x].length; i++) ans[x] =max(ans[x],ans[G[x][i]]+1);
    vis[x] =false;
    return true;}

void main() {
    int N,M;
    scanf(" %d %d\n",&N,&M);
    string A[]; A.length =N;
    for(int i =0; i < N; i++) A[i] =chomp(readln());

    int G[][]; G.length =N*M;
    int dx[] =[1,-1,0,0];
    int dy[] =[0,0,1,-1];
    for(int i =0; i < N; i++) for(int j =0; j < M; j++)
        for(int k =0; k < 4; k++) {
            int x =i+dx[k], y =j+dy[k];
            if(x < 0 || y < 0 || x >= N || y >= M) continue;
            if(A[i][j] == 'D' && A[x][y] == 'I') G[i*M+j] ~=(x*M+y);
            else if(A[i][j] == 'I' && A[x][y] == 'M') G[i*M+j] ~=(x*M+y);
            else if(A[i][j] == 'M' && A[x][y] == 'A') G[i*M+j] ~=(x*M+y);
            else if(A[i][j] == 'A' && A[x][y] == 'D') G[i*M+j] ~=(x*M+y);}

    int ans[]; ans.length =N*M;
    int vis[]; vis.length =N*M;
    for(int i =0; i < N*M; i++) ans[i] =-1, vis[i] =false;
    for(int i =0; i < N*M; i++) if(ans[i] == -1)
        if(!solve(ans,G,vis,i)) {
            writeln("Poor Inna! ",i);
            return;}
    int ansR =0;
    for(int i =0; i < N*M; i++)
        if(A[i/M][i%M] == 'D') ansR =max(ansR,ans[i]/4);
    if(ansR == 0) writeln("Poor Dima!");
    else writeln(ansR);}


Alice wants to send an important message to Bob. Message a = (a1, ..., an) is a sequence of positive integers (characters).To compress the message Alice wants to use binary Huffman coding. We recall that binary Huffman code, or binary prefix code is a function f, that maps each letter that appears in the string to some binary string (that is, string consisting of characters '0' and '1' only) such that for each pair of different characters ai and aj string f(ai) is not a prefix of f(aj) (and vice versa). The result of the encoding of the message a1, a2, ..., an is the concatenation of the encoding of each character, that is the string f(a1)f(a2)... f(an). Huffman codes are very useful, as the compressed message can be easily and uniquely decompressed, if the function f is given. Code is usually chosen in order to minimize the total length of the compressed message, i.e. the length of the string f(a1)f(a2)... f(an).Because of security issues Alice doesn't want to send the whole message. Instead, she picks some substrings of the message and wants to send them separately. For each of the given substrings ali... ari she wants to know the minimum possible length of the Huffman coding. Help her solve this problem.

The first line of the input contains the single integer n (1 ≤ n ≤ 100 000) — the length of the initial message. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000) — characters of the message. Next line contains the single integer q (1 ≤ q ≤ 100 000) — the number of queries. Then follow q lines with queries descriptions. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the position of the left and right ends of the i-th substring respectively. Positions are numbered from 1. Substrings may overlap in any way. The same substring may appear in the input more than once.

Print q lines. Each line should contain a single integer — the minimum possible length of the Huffman encoding of the substring ali... ari.

NoteIn the first query, one of the optimal ways to encode the substring is to map 1 to "0", 2 to "10" and 3 to "11".Note that it is correct to map the letter to the empty substring (as in the fifth query from the sample).

import std.stdio;
import std.algorithm;
import std.container.dlist;

const int N = 100_123;
const int kSqrt = 400;

struct BiList {
  int mult;
  int prv, nxt;
}

struct Query {
  int l, r, id;
}

bool cmp(Query a, Query b) {
  if (a.l / kSqrt != b.l / kSqrt) {
    return a.l < b.l;
  }
  if (a.r == b.r) { return false; }
  return cast(bool)((a.r < b.r) ^ ((a.l / kSqrt) % 2));
}

int[N] ans;
int[N] val;
Query[N] qs;
int[N] cnt_val;
BiList[N] cnts_list;

void EraseFromBi(int prv, int nxt) {
  cnts_list[prv].nxt = nxt;
  cnts_list[nxt].prv = prv;
}

void AddToBi(int ind, int prv, int nxt) {
//   writef("+%d, %d, %d\n", ind, prv, nxt);
  cnts_list[ind].prv = prv;
  cnts_list[ind].nxt = nxt;
  cnts_list[prv].nxt = ind;
  cnts_list[nxt].prv = ind;
}

void Modify(int ind, int diff) {
  int v = val[ind];
  int c = cnt_val[v];
  int p = cnts_list[c].prv;
  int r = cnts_list[c].nxt;
  cnts_list[c].mult--;
  if (cnts_list[c].mult == 0) {
    EraseFromBi(p, r);
  }
  c += diff;
  cnt_val[v] += diff;
  if (cnts_list[c].mult == 0) {
    if (diff == 1 && cnts_list[c - 1].mult) {
      p = c - 1;
    }
    if (diff == -1 && cnts_list[c + 1].mult) {
      r = c + 1;
    }
    AddToBi(c, p, r);
  }
  cnts_list[c].mult++;
//   foreach (j; 0 .. 5) {
//     writef("(m: %d, p: %d, n: %d), ", cnts_list[j].mult, cnts_list[j].prv, cnts_list[j].nxt);
//   }
//   writef("\n");
}

void Add(int ind) {
  Modify(ind, 1);
}

void Remove(int ind) {
  Modify(ind, -1);
}

struct Pair {
  int freq, cnt;
}

struct Que {
  Pair[N] q;
  int beg, past_en;
  void Reset() {
    beg = 0;
    past_en = 0;
  }
  bool empty() {
    return beg == past_en;
  }
  void insertBack(Pair p) {
    q[past_en] = p;
    past_en++;
  }
  void insertFront(Pair p) {
    beg--;
    q[beg] = p;
  }
  Pair front() {
    return q[beg];
  }
  Pair back() {
    return q[past_en - 1];
  }
  void removeFront(int a) {
    beg += a;
  }
}

Que too_big, que;

void main() {
  int n;
  readf("%d", &n);
  foreach (i; 1 .. n + 1) {
    readf(" %d", &val[i]);
  }
  int que_num;
  readf(" %d", &que_num);
  foreach (i; 1 .. que_num + 1) {
    readf(" %d %d", &qs[i].l, &qs[i].r);
    qs[i].id = i;
  }

  sort!(cmp)(qs[1 .. que_num + 1]);
//   if (val[1] == 52388) {
//     while (1) { val[1] = 3; }
//   }
  int curl = 1, curr = 0;
  cnts_list[0].mult = N;

  foreach (i; 1 .. que_num + 1) {
    Query z = qs[i];
    while (curl > z.l) {
      curl--;
      Add(curl);
    }
    while (curr < z.r) {
      curr++;
      Add(curr);
    }
    while (curl < z.l) {
      Remove(curl);
      curl++;
    }
    while (curr > z.r) {
      Remove(curr);
      curr--;
    }

    int res = 0;
    too_big.Reset;
    que.Reset;
    int cur = 0;
    do {
      cur = cnts_list[cur].nxt;
      if (cur != 0) {
        too_big.insertBack(Pair(cur, cnts_list[cur].mult));
      }
    } while (cur != 0);

    void Transfer(int up_to) {
      if (too_big.empty()) { return; }
      if ((que.empty() && up_to == -1) || too_big.front().freq <= up_to) {
        //writef("%d %d\n", too_big.front().freq, too_big.front().cnt);
        que.insertBack(too_big.front());
        too_big.removeFront(1);
        Transfer(up_to);
      }
    }
    Transfer(-1);
    while (!que.empty()) {
      Pair p = que.front();
      que.removeFront(1);
      if (p.cnt % 2 == 0) {
        res += p.cnt * p.freq;
        Transfer(2 * p.freq);
        que.insertBack(Pair(2 * p.freq, p.cnt / 2));
      } else if (p.cnt == 1) {
        if (que.empty()) { Transfer(-1); }
        if (que.empty()) { break; }
        Pair q = que.front();
        que.removeFront(1);
        res += p.freq + q.freq;
        Transfer(p.freq + q.freq);
        que.insertBack(Pair(p.freq + q.freq, 1));
        if (q.cnt > 1) {
          que.insertFront(Pair(q.freq, q.cnt - 1));
        }
      } else {
        res += (p.cnt - 1) * p.freq;
        Transfer(2 * p.freq);
        que.insertBack(Pair(2 * p.freq, p.cnt / 2));
        que.insertFront(Pair(p.freq, 1));
      }
    }
    ans[qs[i].id] = res;
  }

  foreach (i; 1 .. que_num + 1) {
    writef("%d\n", ans[i]);
  }

}

import std.stdio;
import std.algorithm;
import std.container.dlist;

const int N = 100_123;
const int kSqrt = 400;

struct BiList {
  int mult;
  int prv, nxt;
}

struct Query {
  int l, r, id;
}

bool cmp(Query a, Query b) {
  if (a.l / kSqrt != b.l / kSqrt) {
    return a.l < b.l;
  }
  return cast(bool)((a.r < b.r) ^ (a.l / kSqrt % 2));
}

int[N] ans;
int[N] val;
Query[N] qs;
int[N] cnt_val;
BiList[N] cnts_list;

void EraseFromBi(int ind, int prv, int nxt) {
//   writef("-%d\n", ind);
  cnts_list[prv].nxt = nxt;
  cnts_list[nxt].prv = prv;
}

void AddToBi(int ind, int prv, int nxt) {
//   writef("+%d, %d, %d\n", ind, prv, nxt);
  cnts_list[ind].prv = prv;
  cnts_list[ind].nxt = nxt;
  cnts_list[prv].nxt = ind;
  cnts_list[nxt].prv = ind;
}

void Modify(int ind, int diff) {
  int v = val[ind];
  int* c = &cnt_val[v];
  int p = cnts_list[*c].prv;
  int r = cnts_list[*c].nxt;
  cnts_list[*c].mult--;
  if (cnts_list[*c].mult == 0) {
    EraseFromBi(*c, p, r);
  }
  *c += diff;
  if (cnts_list[*c].mult == 0) {
    if (diff == 1 && cnts_list[*c - 1].mult) {
      p = *c - 1;
    }
    if (diff == -1 && cnts_list[*c + 1].mult) {
      r = *c + 1;
    }
    AddToBi(*c, p, r);
  }
  cnts_list[*c].mult++;
//   foreach (j; 0 .. 5) {
//     writef("(m: %d, p: %d, n: %d), ", cnts_list[j].mult, cnts_list[j].prv, cnts_list[j].nxt);
//   }
//   writef("\n");
}

void Add(int ind) {
  Modify(ind, 1);
}

void Remove(int ind) {
  Modify(ind, -1);
}

struct Pair {
  int freq, cnt;
}

Pair[N] huff;

void main() {
  int n;
  readf("%d", &n);
  foreach (i; 1 .. n + 1) {
    readf(" %d", &val[i]);
  }
  int que_num;
  readf(" %d", &que_num);
  foreach (i; 1 .. que_num + 1) {
    readf(" %d %d", &qs[i].l, &qs[i].r);
    qs[i].id = i;
  }

  sort!(cmp)(qs[1 .. que_num + 1]);
//   foreach (i; 1 .. que_num + 1) {
//     writef("%d %d\n", qs[i].l, qs[i].r);
//   }

  int curl = 1, curr = 0;
  cnts_list[0].mult = N;

  foreach (i; 1 .. que_num + 1) {
    Query z = qs[i];
    while (curl > z.l) {
      curl--;
      Add(curl);
    }
    while (curr < z.r) {
      curr++;
      Add(curr);
    }
    while (curl < z.l) {
      Remove(curl);
      curl++;
    }
    while (curr > z.r) {
      Remove(curr);
      curr--;
    }

    int res;

    DList!Pair too_big, que;
    int cur = 0;
    do {
      cur = cnts_list[cur].nxt;
      //writef("cur: %d\n", cur);
      if (cur != 0) {
        too_big.insertBack(Pair(cur, cnts_list[cur].mult));
      }
    } while (cur != 0);

//     writef("Zap %d\n", qs[i].id);
//     foreach (j; 1 .. 4) {
//       writef("%d ", cnt_val[j]);
//     }
//     writeln();
//     foreach (j; 0 .. 5) {
//       writef("(m: %d, p: %d, n: %d), ", cnts_list[j].mult, cnts_list[j].prv, cnts_list[j].nxt);
//     }
//     writef("\n");
//     foreach (p; too_big) {
//       writef("(%d, %d), ", p.freq, p.cnt);
//     }
//     writeln();
    void Transfer(int up_to) {
      if (too_big.empty()) { return; }
      if (que.empty() || too_big.front().freq <= up_to) {
        //writef("%d %d\n", too_big.front().freq, too_big.front().cnt);
        que.insertBack(too_big.front());
        too_big.removeFront(1);
        Transfer(up_to);
      }
    }
    Transfer(-1);
    while (!que.empty()) {
      Pair p = que.front();
      que.removeFront(1);
      if (p.cnt % 2 == 0) {
        res += p.cnt * p.freq;
        Transfer(2 * p.freq);
        que.insertBack(Pair(2 * p.freq, p.cnt / 2));
      } else if (p.cnt == 1) {
        if (que.empty()) { Transfer(-1); }
        if (que.empty()) { break; }
        Pair q = que.front();
        que.removeFront(1);
        res += p.freq + q.freq;
        Transfer(p.freq + q.freq);
        que.insertBack(Pair(p.freq + q.freq, 1));
        if (q.cnt > 1) {
          que.insertFront(Pair(q.freq, q.cnt - 1));
        }
      } else {
        res += (p.cnt - 1) * p.freq;
        Transfer(2 * p.freq);
        que.insertBack(Pair(2 * p.freq, p.cnt / 2));
        que.insertFront(Pair(p.freq, 1));
      }
    }
    ans[qs[i].id] = res;
    //writef("Odp: %d\n", res);
  }

  foreach (i; 1 .. que_num + 1) {
    writef("%d\n", ans[i]);
  }

}


You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.

The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i < b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.

Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).

NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.

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!long).array;
    auto B = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    long X = 0;
    B %= 2;

    foreach (i, a; A) {
        if (i != K - 1) {
            X += B * a % 2;
            X %= 2;
        } else {
            X += a % 2;
            X %= 2;
        }
    }

    writeln(X ? "odd" : "even");
}

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

void main ()
{
	int b, k;
	while (readf (" %s %s", &b, &k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		a[0..$ - 1] *= b;
		auto res = sum (a, 0L);
		writeln (res % 2 == 0 ? "even" : "odd");
	}
}


There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times:  Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$

For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.

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

int[] permutationMatch(T)(in T[] A, in T[] B) {
    // given array A and its permutation B, returns index array I.
    // I[i] == j means A[i] == B[j];
    assert(A.length == B.length);
    int N = cast(int)(A.length);
    int[] ans = new int[N];
    DList!(int)[T] index;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        if (a !in index) index[a] = DList!int();
        index[A[i]] ~= i;
    }
    for (int j = 0; j < N; j++) {
        int b = B[j];
        int i = index[b].front; index[b].removeFront;
        ans[i] = j;
    }
    return ans;
}

alias P = Tuple!(int,int);
void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!int).array;
    auto B = readln.chomp.split(" ").map!(to!int).array;
    bool C() {
        int i = N-1, j = N-1;
        auto s = new RedBlackTree!(int, "a<b", true)();
        while (true) {
            if (j >= 1 && B[j] == B[j-1]) {
                s.insert(B[j]);
                j--;
            } else if (i >= 0 && j >= 0 && A[i] == B[j]) {
                i--;
                j--;
            } else {
                if (i < 0 || A[i] !in s) return false;
                s.removeKey(A[i]);
                i--;
            }
            if (i == -1 && j == -1) break;
        }
        return true;
    }
    writeln(C() ? "YES" : "NO");
}

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

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

bool solve (int [] a, int [] b, int n)
{
	int [int] saved;
	int j = 0;
	foreach (i; 0..n)
	{
		if (a[i] == b[j])
		{
			j++;
			while (j < n && b[j] == b[j - 1] &&
			    saved.get (b[j], 0) > 0)
			{
				saved[b[j]] -= 1;
				j++;
			}
		}
		else
		{
			saved[a[i]] += 1;
		}
		debug {writeln (i, " ", j, " ", saved);}
	}
	return saved.byValue.sum == 0;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		writeln (solve (a, b, n) ? "YES" : "NO");
	}
}

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

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

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

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

int N;
int[] A, B;

bool solve() {
  auto nxt = new int[N];
  {
    auto app = new int[N + 1];
    app[] = N;
    foreach_reverse (i; 0 .. N) {
      nxt[i] = app[A[i]];
      app[A[i]] = i;
    }
  }

  {
    auto cnt = new int[N];
    cnt[] = 1;
    int i;
    foreach (j; 0 .. N) {
      for (; ; ) {
        if (i >= N) {
          return false;
        }
        if (A[i] == B[j]) {
          if (--cnt[i] == 0) {
            ++i;
          }
          break;
        }
        if (nxt[i] >= N) {
          return false;
        }
        cnt[nxt[i]] += cnt[i];
        cnt[i] = 0;
        ++i;
      }
    }
  }
  return true;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        N = readInt;
        A = new int[N]; foreach (i; 0 .. N) A[i] = readInt;
        B = new int[N]; foreach (i; 0 .. N) B[i] = readInt;

        const ans = solve;
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}

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

int[] permutationMatch(T)(in T[] A, in T[] B) {
    // given array A and its permutation B, returns index array I.
    // I[i] == j means A[i] == B[j];
    assert(A.length == B.length);
    int N = cast(int)(A.length);
    int[] ans = new int[N];
    DList!(int)[T] index;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        if (a !in index) index[a] = DList!int();
        index[A[i]] ~= i;
    }
    for (int j = 0; j < N; j++) {
        int b = B[j];
        int i = index[b].front; index[b].removeFront;
        ans[i] = j;
    }
    return ans;
}

alias P = Tuple!(int,int);
void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!int).array;
    auto B = readln.chomp.split(" ").map!(to!int).array;
    bool C() {
        int i = N-1;
        auto s = new RedBlackTree!(int, "a<b", true)();
        for (int j = N-1; j >= 0; j--) {
            if (j >= 1 && B[j] == B[j-1]) {
                s.insert(B[j]);
                continue;
            }
            if (A[i] == B[j]) {
                i--;
            } else {
                if (A[i] in s) {
                    s.removeKey(A[i]);
                    i--;
                } else {
                    return false;
                }
            }
        }
        return true;
    }
    writeln(C() ? "YES" : "NO");
}

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

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

int[] permutationMatch(T)(in T[] A, in T[] B) {
    // given array A and its permutation B, returns index array I.
    // I[i] == j means A[i] == B[j];
    assert(A.length == B.length);
    int N = cast(int)(A.length);
    int[] ans = new int[N];
    DList!(int)[T] index;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        if (a !in index) index[a] = DList!int();
        index[A[i]] ~= i;
    }
    for (int j = 0; j < N; j++) {
        int b = B[j];
        int i = index[b].front; index[b].removeFront;
        ans[i] = j;
    }
    return ans;
}

alias P = Tuple!(int,int);
void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!int).array;
    auto B = readln.chomp.split(" ").map!(to!int).array;
    bool C() {
        int i = N-1;
        auto s = new RedBlackTree!(int, "a<b", true)();
        for (int j = N-1; j >= 0; j--) {
            if (j >= 1 && B[j] == B[j-1]) {
                s.insert(B[j]);
                continue;
            }
            if (i >= 0 && A[i] == B[j]) {
                i--;
            } else {
                if (A[i] in s) {
                    s.removeKey(A[i]);
                } else {
                    return false;
                }
            }
        }
        return true;
    }
    writeln(C() ? "YES" : "NO");
}

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

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

bool solve (int [] a, int [] b, int n)
{
	int [int] asks;
	for (int i = n - 1, j = n - 1; i > 0 || j > 0; )
	{
		if (j >= 0 && a[j] in asks && asks[a[j]] > 0)
		{
			asks[a[j]] -= 1;
			j--;
			continue;
		}
		if (a[j] == b[i])
		{
			i--;
			j--;
			continue;
		}
		if (i + 1 < n && b[i] == b[i + 1])
		{
			asks[b[i]] += 1;
			i--;
			continue;
		}
		return false;
	}
	return true;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		writeln (solve (a, b, n) ? "YES" : "NO");
	}
}