Frog Gorf is traveling through Swamp kingdom. Unfortunately, after a poor jump, he fell into a well of $$$n$$$ meters depth. Now Gorf is on the bottom of the well and has a long way up.The surface of the well's walls vary in quality: somewhere they are slippery, but somewhere have convenient ledges. In other words, if Gorf is on $$$x$$$ meters below ground level, then in one jump he can go up on any integer distance from $$$0$$$ to $$$a_x$$$ meters inclusive. (Note that Gorf can't jump down, only up).Unfortunately, Gorf has to take a break after each jump (including jump on $$$0$$$ meters). And after jumping up to position $$$x$$$ meters below ground level, he'll slip exactly $$$b_x$$$ meters down while resting.Calculate the minimum number of jumps Gorf needs to reach ground level.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the depth of the well. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le i$$$), where $$$a_i$$$ is the maximum height Gorf can jump from $$$i$$$ meters below ground level. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le n - i$$$), where $$$b_i$$$ is the distance Gorf will slip down if he takes a break on $$$i$$$ meters below ground level.

If Gorf can't reach ground level, print $$$-1$$$. Otherwise, firstly print integer $$$k$$$ — the minimum possible number of jumps. Then print the sequence $$$d_1,\,d_2,\,\ldots,\,d_k$$$ where $$$d_j$$$ is the depth Gorf'll reach after the $$$j$$$-th jump, but before he'll slip down during the break. Ground level is equal to $$$0$$$. If there are multiple answers, print any of them.

NoteIn the first example, Gorf is on the bottom of the well and jump to the height $$$1$$$ meter below ground level. After that he slip down by meter and stays on height $$$2$$$ meters below ground level. Now, from here, he can reach ground level in one jump.In the second example, Gorf can jump to one meter below ground level, but will slip down back to the bottom of the well. That's why he can't reach ground level.In the third example, Gorf can reach ground level only from the height $$$5$$$ meters below the ground level. And Gorf can reach this height using a series of jumps $$$10 \Rightarrow 9 \dashrightarrow 9 \Rightarrow 4 \dashrightarrow 5$$$ where $$$\Rightarrow$$$ is the jump and $$$\dashrightarrow$$$ is slipping during breaks.

import core.bitop;
import std.algorithm;
import std.conv;
import std.numeric;
import std.range;
import std.stdio;
import std.string;

immutable int infinity = int.max / 4;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = 0 ~ readln.splitter.map !(to !(int)).array;
		auto b = 0 ~ readln.splitter.map !(to !(int)).array;

		int [] q;
		auto d = new int [n + 1];
		d[] = infinity;
		d[n] = 0;
		auto p = new int [2] [n + 1];
		q ~= n;
		auto next = iota (-1, n).array;
		while (!q.empty)
		{
			auto v = q.front;
			q.popFront ();
			q.assumeSafeAppend ();
			for (int w = v - 0; w >= v - a[v]; w = next[w])
			{
				int z = w + b[w];
				if (d[z] == infinity)
				{
					d[z] = d[v] + 1;
					p[z] = [w, v];
					q ~= z;
				}
				if (next[w] >= 0 &&
				    d[next[w] + b[next[w]]] < infinity)
				{
					next[w] = next[next[w]];
				}
			}
		}

		if (d[0] >= infinity)
		{
			writeln (-1);
		}
		else
		{
			int [] answer;
			int pos = 0;
			while (pos != n)
			{
				auto u = p[pos][0];
				auto v = p[pos][1];
				answer ~= u;
				pos = v;
			}
			writeln (d[0]);
			writefln !("%(%s %)") (answer.retro);
		}
	}
}

import core.bitop;
import std.algorithm;
import std.conv;
import std.numeric;
import std.range;
import std.stdio;
import std.string;

immutable int infinity = int.max / 4;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = 0 ~ readln.splitter.map !(to !(int)).array;
		auto b = 0 ~ readln.splitter.map !(to !(int)).array;
		auto c = new int [n + 1];
		auto p = new int [n + 1];
		c[n] = n - a[n];
		p[n] = n;
		foreach_reverse (i; 0..n)
		{
			c[i] = c[i + 1];
			p[i] = p[i + 1];
			if (c[i] > i - a[i])
			{
				c[i] = i - a[i];
				p[i] = i;
			}
		}
		debug {writeln (c);}
		debug {writeln (p);}

		auto d = new int [n + 1];
		auto q = new int [n + 1];
		d[n] = n;
		q[n] = n;
		foreach_reverse (i; 0..n)
		{
			d[i] = d[i + 1];
			q[i] = q[i + 1];
			if (d[i] > i + b[i])
			{
				d[i] = i + b[i];
				q[i] = i;
			}
		}
		debug {writeln (d);}
		debug {writeln (q);}

		int [] answer;
		int pos = n;
		while (pos != 0)
		{
			int best = c[pos];
			if (best == 0)
			{
				answer ~= c[pos];
				pos = c[pos];
				break;
			}
			int dive = d[c[pos]];
			if (dive >= pos)
			{
				break;
			}
			int height = q[c[pos]];
			answer ~= height;
			pos = dive;
		}

		if (pos == 0)
		{
			writeln (answer.length);
			writefln !("%(%s %)") (answer);
		}
		else
		{
			writeln (-1);
		}
		auto f = new int [n + 1];
		auto r = new int [n + 1];
		f[] = infinity;
		foreach (i; 1..n + 1)
		{
		//	f
		}
		debug {writeln (f);}
	}
}


Black is gifted with a Divine array $$$a$$$ consisting of $$$n$$$ ($$$1 \le n \le 2000$$$) integers. Each position in $$$a$$$ has an initial value. After shouting a curse over the array, it becomes angry and starts an unstoppable transformation.The transformation consists of infinite steps. Array $$$a$$$ changes at the $$$i$$$-th step in the following way: for every position $$$j$$$, $$$a_j$$$ becomes equal to the number of occurrences of $$$a_j$$$ in $$$a$$$ before starting this step.Here is an example to help you understand the process better:  Initial array:$$$2$$$ $$$1$$$ $$$1$$$ $$$4$$$ $$$3$$$ $$$1$$$ $$$2$$$After the $$$1$$$-st step:$$$2$$$ $$$3$$$ $$$3$$$ $$$1$$$ $$$1$$$ $$$3$$$ $$$2$$$After the $$$2$$$-nd step:$$$2$$$ $$$3$$$ $$$3$$$ $$$2$$$ $$$2$$$ $$$3$$$ $$$2$$$After the $$$3$$$-rd step:$$$4$$$ $$$3$$$ $$$3$$$ $$$4$$$ $$$4$$$ $$$3$$$ $$$4$$$...... In the initial array, we had two $$$2$$$-s, three $$$1$$$-s, only one $$$4$$$ and only one $$$3$$$, so after the first step, each element became equal to the number of its occurrences in the initial array: all twos changed to $$$2$$$, all ones changed to $$$3$$$, four changed to $$$1$$$ and three changed to $$$1$$$.The transformation steps continue forever.You have to process $$$q$$$ queries: in each query, Black is curious to know the value of $$$a_x$$$ after the $$$k$$$-th step of transformation.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the initial values of array $$$a$$$. The third line of each test case contains a single integer $$$q$$$ ($$$1 \le q \le 100\,000$$$) — the number of queries. Next $$$q$$$ lines contain the information about queries — one query per line. The $$$i$$$-th line contains two integers $$$x_i$$$ and $$$k_i$$$ ($$$1 \le x_i \le n$$$; $$$0 \le k_i \le 10^9$$$), meaning that Black is asking for the value of $$$a_{x_i}$$$ after the $$$k_i$$$-th step of transformation. $$$k_i = 0$$$ means that Black is interested in values of the initial array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2000$$$ and the sum of $$$q$$$ over all test cases doesn't exceed $$$100\,000$$$.

For each test case, print $$$q$$$ answers. The $$$i$$$-th of them should be the value of $$$a_{x_i}$$$ after the $$$k_i$$$-th step of transformation. It can be shown that the answer to each query is unique.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;
		auto q = RD!int;
		auto x = new int[](q);
		auto k = new long[](q);
		foreach (i; 0..q)
		{
			x[i] = RD!int-1;
			k[i] = RD;
		}
		auto index = k.MAKE_IDX;

		ans[ti].length = q;
		foreach (i; 0..n)
		{
			while (!index.empty)
			{
				auto j = index.front;
				if (k[j] > i) break;
				ans[ti][j] = a[x[j]];
				index.popFront;
			}
			auto cnt = new int[](n);
			foreach (e; a)
				++cnt[e-1];
			foreach (j; 0..n)
				a[j] = cnt[a[j]-1];
		}
		while (!index.empty)
		{
			auto j = index.front;
			ans[ti][j] = a[x[j]];
			index.popFront;
		}
	}

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

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

bool transform(int[] a, int[] freq)
{
  freq[] = 0;
  bool changed = false;
  foreach (i ; 0 .. a.length) {
    freq[a[i]]++;
  }
  foreach (i ; 0 .. a.length) {
    int new_ai = freq[a[i]];
    if (new_ai != a[i])
      changed = true;
    a[i] = new_ai;
  }
  return changed;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.strip.split.map!(to!int).array;
    auto q = readln.strip.to!int;
    Tuple!(int, int, int, int)[] queries;
    foreach (i ; 0 .. q) {
      int xi, ki;
      readf!" %d %d "(xi, ki);
      queries ~= tuple(xi, ki, i, 0);
    }
    queries.sort!((x, y) => x[1] < y[1]);
    auto freq = new int[](n + 1);

    int curk = 0;
    bool done = false;
    foreach (ref tmp ; queries) {
      int nextk = tmp[1];
      while (curk < nextk && !done) {
        if (!transform(a, freq))
          done = true;
        curk++;
      }
      tmp[3] = a[tmp[0] - 1];
    }

    queries.sort!((x, y) => x[2] < y[2]);
    foreach (ref tmp ; queries) {
      writeln(tmp[3]);
    }
  }
}


You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays:   $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$;  $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$;  $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$;  $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$;  and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j < 0$$$. If there are no $$$j$$$ such that $$$p_j < 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.

Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j < 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.

NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j < 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k < 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    ll[] newarr = arr.dup;
    ll[] locked;
    int lockix;
    foreach(i; 0..n){
        lockix = rd!int;
        if(lockix){
            locked ~= i;
            newarr[i] = to!ll(-1e8);
        }
    }
    newarr.sort();
    newarr.reverse();
    ll[] fin; int ptr = 0;
    foreach(i; 0..n){
        if(locked.length && locked.front == i){
            fin ~= arr[i];
            locked.popFront;
        }else{
            fin ~= newarr[ptr];
            assert(newarr[ptr] > - 1e6);
            ++ptr;
        }
        write(fin.back, " ");
    }
    writeln;
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}


Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one.

The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide.

Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower).

NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center.

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

void main ()
{
	int n;
	int m;
multitest_loop:
	while (readf (" %s %s", &n, &m) > 0)
	{
		alias Chord = Tuple !(int, q{a}, int, q{b});
		auto s = new Chord [m];
		bool [Chord] v;
		foreach (ref c; s)
		{
			readf (" %s %s", &c.a, &c.b);
			c.a -= 1;
			c.b -= 1;
			v[c] = true;
			swap (c.a, c.b);
			v[c] = true;
		}

		foreach (d; 1..n)
		{
			if (n % d != 0)
			{
				continue;
			}
			bool ok = true;
			foreach (ref c; s)
			{
				auto e = Chord ((c.a + d) % n, (c.b + d) % n);
				if (e !in v)
				{
					ok = false;
					break;
				}
			}
			if (ok)
			{
				writeln ("Yes");
				continue multitest_loop;
			}
		}
		writeln ("No");
	}
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.random;
import std.typecons;
import std.datetime.systime : Clock;

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

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

alias T = Tuple!(uint, uint);

void main() {
  rndGen.seed ((Clock.currTime.toHash & 0xffffffffU).to!uint);
  auto r = new InputReader;
  immutable n = r.next!uint, m = r.next!uint;
  auto a = uninitializedArray!(T[]) (m);
  bool[ulong] h;
  foreach (i; 0 .. m) {
    uint u = r.next!uint - 1, v = r.next!uint - 1;
    if (u > v) swap (u, v);
    a[i] = tuple (u, v);
    h[(u.to!ulong << 32) + v] = true;
  }
  randomShuffle (a);
  bool check (int k) {
    foreach (const p; a) {
      uint u = (p[0] + k) % n, v = (p[1] + k) % n;
      if (u > v) swap (u, v);
      if (! (((u.to!ulong << 32) + v) in h)) return false;
    }
    return true;
  }
  foreach (k; 1 .. n) {
    if (check (k)) {
      writeln ("Yes");
      return;
    }
  }
  writeln ("No");
}


In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.The trajectory of a camel's spit is an arc, i.e. if the camel in position x spits d meters right, he can hit only the camel in position x + d, if such a camel exists.

The first line contains integer n (1 ≤ n ≤ 100) — the amount of camels in the zoo. Each of the following n lines contains two integers xi and di ( - 104 ≤ xi ≤ 104, 1 ≤ |di| ≤ 2·104) — records in Bob's notepad. xi is a position of the i-th camel, and di is a distance at which the i-th camel spitted. Positive values of di correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.

If there are two camels, which spitted at each other, output YES. Otherwise, output NO.

import std.stdio;
import std.typecons;

void main() {
  int n;
  int[int] m;
  readf(" %d", &n);
  int x, d;
  alias pair = Tuple!(int, "x", int, "d");
  pair[] input;
  while(readf(" %d %d", &x, &d)) {
    m[x] = x+d;
    input ~= pair(x, d);
  }
  bool ans = false;
  foreach (p; input) {
    if(p.x + p.d in m && m[p.x+p.d] == p.x) {
      ans = true;
    }
  }
  writeln(ans ? "YES" : "NO");
}


There are $$$n$$$ positive integers written on the blackboard. Also, a positive number $$$k \geq 2$$$ is chosen, and none of the numbers on the blackboard are divisible by $$$k$$$. In one operation, you can choose any two integers $$$x$$$ and $$$y$$$, erase them and write one extra number $$$f(x + y)$$$, where $$$f(x)$$$ is equal to $$$x$$$ if $$$x$$$ is not divisible by $$$k$$$, otherwise $$$f(x) = f(x / k)$$$.In the end, there will be a single number of the blackboard. Is it possible to make the final number equal to $$$1$$$? If so, restore any sequence of operations to do so.

The first line contains two integers $$$n$$$ and $$$k$$$ — the initial number of integers on the blackboard, and the chosen number ($$$2 \leq n \leq 16$$$, $$$2 \leq k \leq 2000$$$). The second line contains $$$n$$$ positive integers $$$a_1, \ldots, a_n$$$ initially written on the blackboard. It is guaranteed that none of the numbers $$$a_i$$$ is divisible by $$$k$$$, and the sum of all $$$a_i$$$ does not exceed $$$2000$$$.

If it is impossible to obtain $$$1$$$ as the final number, print "NO" in the only line. Otherwise, print "YES" on the first line, followed by $$$n - 1$$$ lines describing operations. The $$$i$$$-th of these lines has to contain two integers $$$x_i$$$ and $$$y_i$$$ to be erased and replaced with $$$f(x_i + y_i)$$$ on the $$$i$$$-th operation. If there are several suitable ways, output any of them.

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

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

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

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

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

      auto ASum = new int[1 << N];
      foreach (i; 0 .. N) {
        foreach (h; 0 .. 1 << i) {
          ASum[h | 1 << i] = ASum[h] + A[i];
        }
      }

      auto dp = new BitArray[1 << N];
      foreach (h; 0 .. 1 << N) {
        dp[h] = BitArray(new bool[ASum[$ - 1] + 1]);
      }
      dp[0][0] = true;
      foreach (h; 0 .. 1 << N) {
        foreach_reverse (x; 1 .. ASum[h] / K + 1) {
          if (dp[h][x * K]) {
            dp[h][x] = true;
          }
        }
        foreach (i; 0 .. N) {
          if (!(h & 1 << i)) {
            auto f = dp[h].dup;
            f <<= A[i];
            dp[h | 1 << i] |= f;
          }
        }
      }
      debug {
        /*
        foreach (h; 0 .. 1 << N) {
          write(h, ":");
          foreach (x; 0 .. ASum[h] + 1) {
            if (dp[h][x]) {
              write(" ", x);
            }
          }
          writeln();
        }
        //*/
      }

      if (dp[$ - 1][1]) {
        auto fs = new int[N];
        fs[] = int.min;
        for (int h = (1 << N) - 1, x = 1; h; ) {
          foreach (i; 0 .. N) {
            if ((h & 1 << i) && x >= A[i] && dp[h ^ 1 << i][x - A[i]]) {
              fs[i] = 0;
              h ^= 1 << i;
              x -= A[i];
              goto found;
            }
          }
          x *= K;
          fs[] += 1;
         found:
        }
        debug {
          writeln("fs = ", fs);
        }
        BinaryHeap!(Array!(Tuple!(int, int)), "a > b") q;
        foreach (i; 0 .. N) {
          q.insert(tuple(fs[i], A[i]));
        }
        writeln("YES");
        foreach (j; 0 .. N - 1) {
          const e0 = q.front; q.removeFront;
          const e1 = q.front; q.removeFront;
          assert(e0[0] == e1[0]);
          writeln(e0[1], " ", e1[1]);
          int f = e0[0];
          int a = e0[1] + e1[1];
          for (; a % K == 0; ) {
            ++f;
            a /= K;
          }
          q.insert(tuple(f, a));
        }
      } else {
        writeln("NO");
      }
    }
  } 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)); }

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

      const ASum = A.sum;
      int m;
      for (m = 0; K^^m < ASum; ++m) {}

      auto kk = new int[m + 1];
      kk[0] = 1;
      foreach (j; 1 .. m + 1) {
        kk[j] = kk[j - 1] * K;
      }

      auto dp = new int[int][N + 1];
      dp[0][0] = -1;
      foreach (i; 0 .. N) {
        foreach (x; dp[i].keys) {
          foreach (e; 0 .. m + 1) {
            const xx = x + A[i] * kk[e];
            if (xx > kk[m]) {
              break;
            }
            if (xx !in dp[i + 1]) {
              dp[i + 1][xx] = e;
            }
          }
        }
      }
      if (kk[m] in dp[N]) {
        auto es = new int[N];
        int x = kk[m];
        foreach_reverse (i; 0 .. N) {
          es[i] = dp[i + 1][x];
          x -= A[i] * kk[es[i]];
        }
        assert(x == 0);
        debug {
          writeln("es = ", es);
        }
        alias Entry = Tuple!(int, "e", int, "a");
        BinaryHeap!(Array!Entry, "a > b") q;
        foreach (i; 0 .. N) {
          q.insert(Entry(es[i], A[i]));
        }
        writeln("YES");
        foreach (j; 0 .. N - 1) {
          const e0 = q.front; q.removeFront;
          const e1 = q.front; q.removeFront;
          debug {
            writeln(e0, " ", e1);
          }
          assert(e0.e == e1.e);
          writeln(e0.a, " ", e1.a);
          int e = e0.e;
          int a = e0.a + e1.a;
          for (; a % K == 0; ) {
            ++e;
            a /= K;
          }
          q.insert(Entry(e, a));
        }
      } else {
        writeln("NO");
      }
    }
  } catch (EOFException e) {
  }
}


You have an array $$$a_1, a_2, \dots, a_n$$$. All $$$a_i$$$ are positive integers.In one step you can choose three distinct indices $$$i$$$, $$$j$$$, and $$$k$$$ ($$$i \neq j$$$; $$$i \neq k$$$; $$$j \neq k$$$) and assign the sum of $$$a_j$$$ and $$$a_k$$$ to $$$a_i$$$, i. e. make $$$a_i = a_j + a_k$$$.Can you make all $$$a_i$$$ lower or equal to $$$d$$$ using the operation above any number of times (possibly, zero)?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$d$$$ ($$$3 \le n \le 100$$$; $$$1 \le d \le 100$$$) — the number of elements in the array $$$a$$$ and the value $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$) — the array $$$a$$$.

For each test case, print YES, if it's possible to make all elements $$$a_i$$$ less or equal than $$$d$$$ using the operation above. Otherwise, print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).

NoteIn the first test case, we can prove that we can't make all $$$a_i \le 3$$$.In the second test case, all $$$a_i$$$ are already less or equal than $$$d = 4$$$.In the third test case, we can, for example, choose $$$i = 5$$$, $$$j = 1$$$, $$$k = 2$$$ and make $$$a_5 = a_1 + a_2 = 2 + 1 = 3$$$. Array $$$a$$$ will become $$$[2, 1, 5, 3, 3]$$$.After that we can make $$$a_3 = a_5 + a_2 = 3 + 1 = 4$$$. Array will become $$$[2, 1, 4, 3, 3]$$$ and all elements are less or equal than $$$d = 4$$$.

import std.stdio, std.string, std.algorithm, std.conv, std.range;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int d;
        readf!"%d %d\n"(_, d);
        int[] a = readln.split.map!(to!int).array;
        a.sort();
        writeln(a[$ - 1] <= d || a[0] + a[1] <= d ? "YES" : "NO");
    }
}

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int N, D; get(N, D);
        int[] AS; get(AS);
        sort(AS);
        writeln(AS[$-1] <= D || (AS[0] + AS[1] <= D) ? "YES" : "NO");
    }
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 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 bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto d = RD!int;
		auto a = RDA;

		a.sort();
		auto x = a[0] + a[1];
		ans[ti] = x <= d || a[$-1] <= d;
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, d;
		readf !(" %s %s") (n, d);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		writeln ((a[$ - 1] <= d || a[0] + a[1] <= d) ? "Yes" : "No");
	}
}


Vasya has got $$$n$$$ books, numbered from $$$1$$$ to $$$n$$$, arranged in a stack. The topmost book has number $$$a_1$$$, the next one — $$$a_2$$$, and so on. The book at the bottom of the stack has number $$$a_n$$$. All numbers are distinct.Vasya wants to move all the books to his backpack in $$$n$$$ steps. During $$$i$$$-th step he wants to move the book number $$$b_i$$$ into his backpack. If the book with number $$$b_i$$$ is in the stack, he takes this book and all the books above the book $$$b_i$$$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $$$[1, 2, 3]$$$ (book $$$1$$$ is the topmost), and Vasya moves the books in the order $$$[2, 1, 3]$$$, then during the first step he will move two books ($$$1$$$ and $$$2$$$), during the second step he will do nothing (since book $$$1$$$ is already in the backpack), and during the third step — one book (the book number $$$3$$$). Note that $$$b_1, b_2, \dots, b_n$$$ are distinct.Help Vasya! Tell him the number of books he will put into his backpack during each step.

The first line contains one integer $$$n~(1 \le n \le 2 \cdot 10^5)$$$ — the number of books in the stack. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n~(1 \le a_i \le n)$$$ denoting the stack of books. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n~(1 \le b_i \le n)$$$ denoting the steps Vasya is going to perform. All numbers $$$a_1 \dots a_n$$$ are distinct, the same goes for $$$b_1 \dots b_n$$$.

Print $$$n$$$ integers. The $$$i$$$-th of them should be equal to the number of books Vasya moves to his backpack during the $$$i$$$-th step.

NoteThe first example is described in the statement.In the second example, during the first step Vasya will move the books $$$[3, 1, 4]$$$. After that only books $$$2$$$ and $$$5$$$ remain in the stack ($$$2$$$ is above $$$5$$$). During the second step Vasya will take the books $$$2$$$ and $$$5$$$. After that the stack becomes empty, so during next steps Vasya won't move any books.

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

    for (int i = 0, j = 0; i < N; ++i) {
        if (used[B[i]]) continue;
        while (A[j] != B[i]) {
            ans[i] += 1;
            used[A[j]] = true;
            j += 1;
        }
        ans[i] += 1;
        used[A[j]] = true;
        j += 1;
    }

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

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

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

    auto a = readln.split.to!(int[]);
    auto b = readln.split.to!(int[]);

    int[int] r;

    foreach (i ; 0 .. n) {
        r[a[i]] = i;
    }

    int p = -1;
    int[] ans;

    foreach (i ; 0 .. n) {
        if (r[b[i]] < p) {
            ans ~= 0;
        }
        else {
            ans ~= r[b[i]] - p;
            p = r[b[i]];
        }
    }

    writefln("%(%s %)", ans);
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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


You are given a problemset consisting of $$$n$$$ problems. The difficulty of the $$$i$$$-th problem is $$$a_i$$$. It is guaranteed that all difficulties are distinct and are given in the increasing order.You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let $$$a_{i_1}, a_{i_2}, \dots, a_{i_p}$$$ be the difficulties of the selected problems in increasing order. Then for each $$$j$$$ from $$$1$$$ to $$$p-1$$$ $$$a_{i_{j + 1}} \le a_{i_j} \cdot 2$$$ should hold. It means that the contest consisting of only one problem is always valid.Among all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of problems in the problemset. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — difficulties of the problems. It is guaranteed that difficulties of the problems are distinct and are given in the increasing order.

Print a single integer — maximum number of problems in the contest satisfying the condition in the problem statement.

NoteDescription of the first example: there are $$$10$$$ valid contests consisting of $$$1$$$ problem, $$$10$$$ valid contests consisting of $$$2$$$ problems ($$$[1, 2], [5, 6], [5, 7], [5, 10], [6, 7], [6, 10], [7, 10], [21, 23], [21, 24], [23, 24]$$$), $$$5$$$ valid contests consisting of $$$3$$$ problems ($$$[5, 6, 7], [5, 6, 10], [5, 7, 10], [6, 7, 10], [21, 23, 24]$$$) and a single valid contest consisting of $$$4$$$ problems ($$$[5, 6, 7, 10]$$$).In the second example all the valid contests consist of $$$1$$$ problem.In the third example are two contests consisting of $$$3$$$ problems: $$$[4, 7, 12]$$$ and $$$[100, 150, 199]$$$.

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

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

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

    auto ans = 1, cur = 1;
    foreach (a, b; lockstep(arr, arr.dropOne)) {
        if (a*2 >= b) ++cur;
        else {
            ans = max(ans, cur);
            cur = 1;
        }
    }
    ans = max(ans, cur);

    ans.writeln;
}

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

  int n; rd(n);
  auto a=readln.split.to!(long[]);

  auto dp=new int[](n);
  dp[0]=1;
  foreach(i; 1..n){
    dp[i]=1;
    if(a[i]<=a[i-1]*2){
      dp[i]=max(dp[i], dp[i-1]+1);
    }
  }
  writeln(dp.reduce!(max));
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


A running competition is going to be held soon. The stadium where the competition will be held can be represented by several segments on the coordinate plane:  two horizontal segments: one connecting the points $$$(0, 0)$$$ and $$$(x, 0)$$$, the other connecting the points $$$(0, y)$$$ and $$$(x, y)$$$;  $$$n + 1$$$ vertical segments, numbered from $$$0$$$ to $$$n$$$. The $$$i$$$-th segment connects the points $$$(a_i, 0)$$$ and $$$(a_i, y)$$$; $$$0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x$$$. For example, here is a picture of the stadium with $$$x = 10$$$, $$$y = 5$$$, $$$n = 3$$$ and $$$a = [0, 3, 5, 10]$$$:  A lap is a route that goes along the segments, starts and finishes at the same point, and never intersects itself (the only two points of a lap that coincide are its starting point and ending point). The length of a lap is a total distance travelled around it. For example, the red route in the picture representing the stadium is a lap of length $$$24$$$.The competition will be held in $$$q$$$ stages. The $$$i$$$-th stage has length $$$l_i$$$, and the organizers want to choose a lap for each stage such that the length of the lap is a divisor of $$$l_i$$$. The organizers don't want to choose short laps for the stages, so for each stage, they want to find the maximum possible length of a suitable lap.Help the organizers to calculate the maximum possible lengths of the laps for the stages! In other words, for every $$$l_i$$$, find the maximum possible integer $$$L$$$ such that $$$l_i \bmod L = 0$$$, and there exists a lap of length exactly $$$L$$$.If it is impossible to choose such a lap then print $$$-1$$$.

The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n, x, y \le 2 \cdot 10^5$$$, $$$n \le x$$$). The second line contains $$$n + 1$$$ integers $$$a_0$$$, $$$a_1$$$, ..., $$$a_n$$$ ($$$0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of stages. The fourth line contains $$$q$$$ even integers $$$l_1$$$, $$$l_2$$$, ..., $$$l_q$$$ ($$$4 \le l_i \le 10^6$$$) — the lengths of the stages.

Print $$$q$$$ numbers. The $$$i$$$-th number should be equal to the maximum possible length of a suitable lap for the $$$i$$$-th stage, or $$$-1$$$ if it is impossible to choose a lap for that stage.

// warning: bydlokod

import std.algorithm, std.complex, std.conv, std.math, std.numeric, std.range, std.stdio;

immutable int N = (1 << 19);

void main () {
    int n, x, y;
    readf !"%s %s %s\n" (&n, &x, &y);

    auto a = readln
            .splitter
            .map !(to!int)
            .array;

    Complex!double[] u, v;
    u.length = N;
    v.length = N;
    fill(u, complex(0));
    fill(v, complex(0));

    foreach(t; a) {
        u[t] = complex(1);
        v[x - t] = complex(1);
    }

    auto f = new Fft(N);
    auto g = f.fft !double (u), h = f.fft !double (v);

    g[] *= h[];
    auto w = f
            .inverseFft(g)
            .map !(c => (cast(int) c.re.round) != 0)
            .array[x..2*x+1];

    int[] ans;
    ans.length = N;
    fill(ans, -1);

    foreach(i; 1..x+1) {
        if (w[i]) {
            for (int j = 1; (i + y) * j < N; j++) {
                ans[(i + y) * j] = (i + y) * 2;
            }
        }
    }

    int q;
    readf !"%s\n" (&q);
    auto l = readln
            .splitter
            .map !(to!int)
            .map !(x => x / 2)
            .array;

    foreach(t; l) {
        writef !"%s " (ans[t]);
    }
}


You are given an undirected graph consisting of $$$n$$$ vertices. A number is written on each vertex; the number on vertex $$$i$$$ is $$$a_i$$$. Initially there are no edges in the graph.You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices $$$x$$$ and $$$y$$$ is $$$a_x + a_y$$$ coins. There are also $$$m$$$ special offers, each of them is denoted by three numbers $$$x$$$, $$$y$$$ and $$$w$$$, and means that you can add an edge connecting vertices $$$x$$$ and $$$y$$$ and pay $$$w$$$ coins for it. You don't have to use special offers: if there is a pair of vertices $$$x$$$ and $$$y$$$ that has a special offer associated with it, you still may connect these two vertices paying $$$a_x + a_y$$$ coins for it.What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices in the graph and the number of special offers, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{12}$$$) — the numbers written on the vertices. Then $$$m$$$ lines follow, each containing three integers $$$x$$$, $$$y$$$ and $$$w$$$ ($$$1 \le x, y \le n$$$, $$$1 \le w \le 10^{12}$$$, $$$x \ne y$$$) denoting a special offer: you may add an edge connecting vertex $$$x$$$ and vertex $$$y$$$, and this edge will cost $$$w$$$ coins.

Print one integer — the minimum number of coins you have to pay to make the graph connected.

NoteIn the first example it is possible to connect $$$1$$$ to $$$2$$$ using special offer $$$2$$$, and then $$$1$$$ to $$$3$$$ without using any offers.In next two examples the optimal answer may be achieved without using special offers.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = readln.split.map!(to!long).array;
    auto X = new Tuple!(int, long)[][](N);
    foreach (i; 0..M) {
        auto t = readln.split;
        auto u = t[0].to!int - 1;
        auto v = t[1].to!int - 1;
        auto w = t[2].to!long;
        X[u] ~= tuple(v, w);
        X[v] ~= tuple(u, w);
    }

    long ans = 0;
    int S = A.minIndex.to!int;
    auto pq = new BinaryHeap!(Array!(Tuple!(int, long)), "a[1] > b[1]")();
    auto used = new bool[](N);
    used[S] = true;

    foreach (i; 0..N) {
        if (i == S) continue;
        pq.insert(tuple(i, A[S] + A[i]));
    }

    foreach (t; X[S]) {
        pq.insert(tuple(t[0], t[1]));
    }

    while (!pq.empty) {
        auto t = pq.front;
        pq.removeFront;
        auto u = t[0];
        auto w = t[1];
        if (used[u]) continue;
        ans += w;
        used[u] = true;
        foreach (v; X[u]) {
            if (used[v[0]]) continue;
            pq.insert(tuple(v[0], v[1]));
        }
    }

    ans.writeln;
}

import std.stdio;
import std.container;
import std.random;
import std.range;
import std.algorithm;
import std.typecons;
import std.conv;
import std.format;

int[] par;
long[] smallest;

int find_set(int v) {
	if (v == par[v]) return v;
	return par[v] = find_set(par[v]);
}

Mt19937 rng;

void unite(int a, int b) {
	a = find_set(a);
	b = find_set(b);
	if (rng.front % 2) swap(a, b);
	rng.popFront();
	par[b] = a;
	smallest[a] = min(smallest[a], smallest[b]);
}

void main()
{
	int n, m;
	stdin.byLine.front.formattedRead!"%d %d"(n, m);

	par = iota(n + 1).array;
	smallest = stdin.byLine.front.split(" ").map!`parse!long(a)`.array;

	auto S = redBlackTree!(Tuple!(long, int));
	auto offers = redBlackTree!(Tuple!(long, int, int));

	foreach (i, e; smallest) {
		S.insert(tuple(e, i.to!int));
	}

	for (int i = 0; i < m; i++) {
		int a, b;
		long w;
		stdin.byLine.front.formattedRead!"%d %d %d"(a, b, w);

		a--; b--;
		offers.insert(tuple(w, a, b));
	}

	long totalCost = 0;
	while (true) {
		if (S.length == 1) {
			writeln(totalCost);
			return;
		}

		while (offers.length > 0 && find_set(offers.front[1]) == find_set(offers.front[2]))
			offers.removeFront();

		auto c1 = S.front; S.removeFront();
		auto c2 = S.front; S.removeFront();
		auto cost = c1[0] + c2[0];

		if (offers.length > 0 && offers.front[0] < cost) {
			S.insert([c1, c2]);
			totalCost += offers.front[0];
			int x = offers.front[1];
			int y = offers.front[2];

			int setx = find_set(x);
			int sety = find_set(y);

			S.removeKey(tuple(smallest[setx], setx));
			S.removeKey(tuple(smallest[sety], sety));
			unite(x, y);
			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		} else {
			totalCost += cost;
			int x = c1[1];
			int y = c2[1];
			unite(x, y);

			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		}
	}
}

import std.stdio;
import std.container;
import std.random;
import std.range;
import std.algorithm;
import std.typecons;

int[] par;
long[] smallest;

int find_set(int v) {
	if (v == par[v]) return v;
	return par[v] = find_set(par[v]);
}

Mt19937 rng;

void unite(int a, int b) {
	a = find_set(a);
	b = find_set(b);
	if (rng.front % 2) swap(a, b);
	rng.popFront();
	par[b] = a;
	smallest[a] = min(smallest[a], smallest[b]);
}

void main()
{
	par = iota(200000).array;
	smallest = new long[200000];

	int n, m;
	scanf("%d%d", &n, &m);

	auto S = redBlackTree!(Tuple!(long, int));
	auto offers = redBlackTree!(Tuple!(long, int, int));

	for (int i = 0; i < n; i++) {
		long x;
		scanf("%lld", &x);
		smallest[i] = x;

		S.insert(tuple(x, i));
	}

	for (int i = 0; i < m; i++) {
		int a, b;
		long w;
		scanf("%d%d%lld", &a, &b, &w);
		a--; b--;
		offers.insert(tuple(w, a, b));
	}

	long totalCost = 0;
	while (true) {
		if (S.length == 1) {
			writeln(totalCost);
			return;
		}

		while (offers.length > 0 && find_set(offers.front[1]) == find_set(offers.front[2]))
			offers.removeFront();

		auto c1 = S.front; S.removeFront();
		auto c2 = S.front; S.removeFront();
		auto cost = c1[0] + c2[0];

		if (offers.length > 0 && offers.front[0] < cost) {
			S.insert([c1, c2]);
			totalCost += offers.front[0];
			int x = offers.front[1];
			int y = offers.front[2];

			int setx = find_set(x);
			int sety = find_set(y);

			S.removeKey(tuple(smallest[setx], setx));
			S.removeKey(tuple(smallest[sety], sety));
			unite(x, y);
			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		} else {
			totalCost += cost;
			int x = c1[1];
			int y = c2[1];
			unite(x, y);

			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		}
	}
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = readln.split.map!(to!long).array;
    auto X = new Tuple!(int, long)[][](N);
    foreach (i; 0..M) {
        auto t = readln.split;
        auto u = t[0].to!int - 1;
        auto v = t[1].to!int - 1;
        auto w = t[2].to!long;
        X[u] ~= tuple(v, w);
        X[v] ~= tuple(u, w);
    }

    long ans = 0;
    int S = A.minIndex.to!int;
    auto pq = new BinaryHeap!(Array!(Tuple!(int, long)), "a[1] > b[1]")();
    auto used = new bool[](N);
    used[S] = true;

    foreach (i; 0..N) {
        if (i == S) continue;
        pq.insert(tuple(i, A[S] + A[i]));
    }

    foreach (t; X[0]) {
        pq.insert(tuple(t[0], t[1]));
    }

    while (!pq.empty) {
        auto t = pq.front;
        pq.removeFront;
        auto u = t[0];
        auto w = t[1];
        if (used[u]) continue;
        ans += w;
        used[u] = true;
        foreach (v; X[u]) {
            if (used[v[0]]) continue;
            pq.insert(tuple(v[0], v[1]));
        }
    }

    ans.writeln;
}

import std.stdio;
import std.container;
import std.random;
import std.range;
import std.algorithm;
import std.typecons;
import std.conv;
import std.format;

int[] par;
long[] smallest;

int find_set(int v) {
	if (v == par[v]) return v;
	return par[v] = find_set(par[v]);
}

Mt19937 rng;

void unite(int a, int b) {
	a = find_set(a);
	b = find_set(b);
	if (rng.front % 2) swap(a, b);
	rng.popFront();
	par[b] = a;
	smallest[a] = min(smallest[a], smallest[b]);
}

void main()
{
	par = iota(200000).array;

	int n, m;
	stdin.byLine.front.formattedRead!"%d %d"(n, m);

	auto S = redBlackTree!(Tuple!(long, int));
	auto offers = redBlackTree!(Tuple!(long, int, int));

	smallest = stdin.byLine.front.split(" ").map!`parse!long(a)`.array;

	smallest.writeln;

	foreach (i, e; smallest) {
		S.insert(tuple(e, i.to!int));
	}

	for (int i = 0; i < m; i++) {
		int a, b;
		long w;
		stdin.byLine.front.formattedRead!"%d %d %d"(a, b, w);

		a--; b--;
		offers.insert(tuple(w, a, b));
	}

	long totalCost = 0;
	while (true) {
		if (S.length == 1) {
			writeln(totalCost);
			return;
		}

		while (offers.length > 0 && find_set(offers.front[1]) == find_set(offers.front[2]))
			offers.removeFront();

		auto c1 = S.front; S.removeFront();
		auto c2 = S.front; S.removeFront();
		auto cost = c1[0] + c2[0];

		if (offers.length > 0 && offers.front[0] < cost) {
			S.insert([c1, c2]);
			totalCost += offers.front[0];
			int x = offers.front[1];
			int y = offers.front[2];

			int setx = find_set(x);
			int sety = find_set(y);

			S.removeKey(tuple(smallest[setx], setx));
			S.removeKey(tuple(smallest[sety], sety));
			unite(x, y);
			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		} else {
			totalCost += cost;
			int x = c1[1];
			int y = c2[1];
			unite(x, y);

			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		}
	}
}


Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i).The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1.We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree.Roma gives you m queries, the i-th of which consists of two numbers vi, hi. Let's consider the vertices in the subtree vi located at depth hi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used.

The first line contains two integers n, m (1 ≤ n, m ≤ 500 000) — the number of nodes in the tree and queries, respectively. The following line contains n - 1 integers p2, p3, ..., pn — the parents of vertices from the second to the n-th (1 ≤ pi < i). The next line contains n lowercase English letters, the i-th of these letters is written on vertex i. Next m lines describe the queries, the i-th line contains two numbers vi, hi (1 ≤ vi, hi ≤ n) — the vertex and the depth that appear in the i-th query.

Print m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes).

NoteString s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome.Clarification for the sample test.In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z".In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them.In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome.In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome.In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac".

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, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		readln;
		auto a = new int [] [n];
		auto p = readln.split.map !(to !(int)).array;
		foreach (u, v; p)
		{
			a[v - 1] ~= u + 1;
		}
		auto c = readln.strip.map !(x => 1 << (x - 'a')).array;

		auto w = new int [] [n];
		auto first = new int [n];
		auto last = new int [n];
		int cur = 0;

		void recur (int v, int h)
		{
			cur++;
			first[v] = cur;
			w[h] ~= v;
			foreach (u; a[v])
			{
				recur (u, h + 1);
			}
			last[v] = cur;
		}

		recur (0, 0);

		auto s = new int [] [n];
		foreach (h; 0..n)
		{
			int [] temp;
			temp ~= 0;
			foreach (v; w[h])
			{
				temp ~= temp[$ - 1] ^ c[v];
			}
			temp ~= 0;
			s[h] = temp;
		}

		foreach (j; 0..m)
		{
			int v;
			int h;
			readf (" %s %s", &v, &h);
			v--;
			h--;
			int cur_first = first[v];
			int cur_last = last[v];
			int [] temp = w[h];

			int lo1 = 0;
			int hi1 = temp.length - 1;
			while (lo1 < hi1)
			{
				int me1 = (lo1 + hi1) >> 1;
				if (first[temp[me1]] >= cur_first)
				{
					hi1 = me1;
				}
				else
				{
					lo1 = me1 + 1;
				}
			}

			int lo2 = lo1;
			int hi2 = temp.length - 1;
			while (lo2 < hi2)
			{
				int me2 = (lo2 + hi2 + 1) >> 1;
				if (last[temp[me2]] <= cur_last)
				{
					lo2 = me2;
				}
				else
				{
					hi2 = me2 - 1;
				}
			}

			debug {writeln (w[h].map !(x => [first[x], last[x]]),
			    ' ', s[h], ' ', lo1, ' ', lo2);}
			int cur_value = s[h][lo2 + 1] ^ s[h][lo1];
			writeln ((popcnt (cur_value) <= 1) ? "Yes" : "No");
		}
	}
}

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, m;
	while (readf (" %s %s ", &n, &m) > 0)
	{
		auto a = new int [] [n];
		auto p = readln.split.map !(to !(int)).array;
		foreach (u, v; p)
		{
			a[v - 1] ~= u + 1;
		}
		auto c = readln.strip.map !(x => 1 << (x - 'a')).array;

		auto w = new int [] [n];
		auto first = new int [n];
		auto last = new int [n];
		int cur = 0;

		void recur (int v, int h)
		{
			cur++;
			first[v] = cur;
			w[h] ~= v;
			foreach (u; a[v])
			{
				recur (u, h + 1);
			}
			last[v] = cur;
		}

		recur (0, 0);

		auto s = new int [] [n];
		foreach (h; 0..n)
		{
			int [] temp;
			temp ~= 0;
			foreach (v; w[h])
			{
				temp ~= temp[$ - 1] ^ c[v];
			}
			s[h] = temp;
		}

		foreach (j; 0..m)
		{
			int v;
			int h;
			readf (" %s %s", &v, &h);
			v--;
			h--;
			int cur_first = first[v];
			int cur_last = last[v];
			int [] temp = w[h];

			int lo1 = 0;
			int hi1 = temp.length - 1;
			while (lo1 < hi1)
			{
				int me1 = (lo1 + hi1) >> 1;
				if (first[temp[me1]] >= cur_first)
				{
					hi1 = me1;
				}
				else
				{
					lo1 = me1 + 1;
				}
			}

			int lo2 = lo1;
			int hi2 = temp.length - 1;
			while (lo2 < hi2)
			{
				int me2 = (lo2 + hi2 + 1) >> 1;
				if (last[temp[me2]] <= cur_last)
				{
					lo2 = me2;
				}
				else
				{
					hi2 = me2 - 1;
				}
			}

			debug {writeln (w[h], ' ', s[h], ' ', lo1, ' ', lo2);}
			int cur_value = s[h][lo2 + 1] ^ s[h][lo1];
			writeln ((popcnt (cur_value) <= 1) ? "Yes" : "No");
		}
	}
}

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, m;
	while (readf (" %s %s ", &n, &m) > 0)
	{
		auto a = new int [] [n];
		auto p = readln.split.map !(to !(int)).array;
		foreach (u, v; p)
		{
			a[v - 1] ~= u + 1;
		}
		auto c = readln.strip.map !(x => 1 << (x - 'a')).array;

		auto w = new int [] [n];
		auto first = new int [n];
		auto last = new int [n];
		int cur = 0;

		void recur (int v, int h)
		{
			cur++;
			first[v] = cur;
			w[h] ~= v;
			foreach (u; a[v])
			{
				recur (u, h + 1);
			}
			last[v] = cur;
		}

		recur (0, 0);

		auto s = new int [] [n];
		foreach (h; 0..n)
		{
			s[h] ~= 0;
			foreach (v; w[h])
			{
				s[h] ~= s[h][$ - 1] ^ c[v];
			}
		}

		foreach (j; 0..m)
		{
			int v;
			int h;
			readf (" %s %s", &v, &h);
			v--;
			h--;
			int cur_first = first[v];
			int cur_last = last[v];
			int [] temp = w[v];

			int lo1 = 0;
			int hi1 = w[v].length - 1;
			while (lo1 < hi1)
			{
				int me1 = (lo1 + hi1) >> 1;
				if (first[temp[me1]] >= cur_first)
				{
					hi1 = me1;
				}
				else
				{
					lo1 = me1 + 1;
				}
			}

			int lo2 = hi1;
			int hi2 = w[v].length - 1;
			while (lo2 < hi2)
			{
				int me2 = (lo2 + hi2 + 1) >> 1;
				if (last[temp[me2]] <= cur_last)
				{
					lo2 = me2;
				}
				else
				{
					hi2 = me2 - 1;
				}
			}

			int cur_value = s[h][lo2 + 1] ^ s[h][lo1];
			writeln ((popcnt (cur_value) <= 1) ? "Yes" : "No");
		}
	}
}


Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an n by n square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In other words, for every x, y such that 1 ≤ x, y ≤ n and ax, y ≠ 1, there should exist two indices s and t so that ax, y = ax, s + at, y, where ai, j denotes the integer in i-th row and j-th column.Help Okabe determine whether a given lab is good!

The first line of input contains the integer n (1 ≤ n ≤ 50) — the size of the lab.  The next n lines contain n space-separated integers denoting a row of the grid. The j-th integer in the i-th row is ai, j (1 ≤ ai, j ≤ 105).

Print "Yes" if the given lab is good and "No" otherwise. You can output each letter in upper or lower case.

NoteIn the first sample test, the 6 in the bottom left corner is valid because it is the sum of the 2 above it and the 4 on the right. The same holds for every number not equal to 1 in this table, so the answer is "Yes".In the second sample test, the 5 cannot be formed as the sum of an integer in the same row and an integer in the same column. Thus the answer is "No".

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

int n;

void main() {
    scan(n);
    auto a = new int[][](n, n);
    iota(n).each!(i => a[i][] = readln.split.to!(int[]));

    foreach (i ; 0 .. n) {
        foreach (j ; 0 .. n) {
            if (a[i][j] != 1) {
                bool flag;

                foreach (k ; 0 .. n) {
                    if (k == i) continue;

                    int x = a[i][j] - a[k][j];

                    foreach (l ; 0 .. n) {
                        if (x == a[i][l]) {
                            flag = true;
                            break;
                        }
                    }

                    if (flag) break;
                }

                if (!flag) {
                    writeln("No");
                    return;
                }
            }
        }
    }

    writeln("Yes");
}

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

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


Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.

The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109).

Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them.

NoteSample 1. You can reverse the entire array to get [1, 2, 3], which is sorted.Sample 3. No segment can be reversed such that the array will be sorted.DefinitionsA segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r].If you have an array a of size n and you reverse its segment [l, r], the array will become:a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].

import std.stdio;
import std.string;
import std.array: array;
import std.conv: to;
import std.algorithm: reverse, map, max, isSorted;

void main() {
	int n = readln.chomp.to!int;
	long[] a = readln.split.map!(to!long).array;

	int from;
	int to;

	long last_max = a[0];
	long last = a[0];
	bool x = false;
	bool y = false;
	bool no = false;
	bool z = false;

	if (a.isSorted) {
		writeln("yes");
		writeln("1 1");
	} else if (a.reverse.isSorted) {
		writeln("yes");
		writefln("1 %s", a.count);
	} else {
	a.reverse;
	foreach (int i; 0..n) {
		if (a[i] < last && !y) {
			from = i-1;
			y = true;
		} else if (y && !z && a[i] > last) {
			if (a[i] < last_max) {
				writeln("no");
				no = true;
				break;
			} else {
				to = i-1;
			}
			z = true;
		} else if (z && a[i] < last) {
			writeln("no");
			no = true;
			break;
		}
		last = a[i];
		last_max = max(a[i], last_max);
	}
	if (!no) {
		if (to != 0) {
			writeln("yes");
			writefln("%s %s", from + 1, to + 1);
		} else if (a[$-1] >= a[from - 1]) {
			writeln("yes");
			writefln("%s %s", from + 1, a.count);
		} else {
			writeln("no");
		}
	}
	}
}

import std.stdio;
import std.array: array, split;
import std.string: chomp;
import std.conv: to;
import std.algorithm: copy, sort, reverse, map, maxElement, minElement;

void main() {
	int n = readln.chomp.to!int;
	int[] b = readln.split.map!(to!int).array;
	int[] a = new int[n];
	b.copy(a);
	b.sort;

	if (a == b) {
		writeln("yes\n1 1");
	} else {
		int[] c;
		foreach(int i; 0..n) {
			if (a[i] != b[i]) {
				c ~= [i];
			}
		}
		int x = minElement(c);
		int y = maxElement(c);
		if (a[0..x] ~ a[x..y+1].reverse ~ a[y+1..n] == b) {
			writefln("yes\n%s %s", x+1, y+1);
		} else {
			writeln("no");
		}
	}
}

// https://codeforces.com/problemset/problem/451/B
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.stdio;
import std.string;

void main() {
    int n = readln.chomp.to!int;
    int[] a = readln.split.map!(to!int).array;

    int inversions = 0;
    int[] idx;

    foreach(i; 1..n-1) {
        int last = a[i]-a[i-1];
        int now = a[i+1]-a[i];

        last = last/abs(last);
        now = now/abs(now);

        if(last != now) {
            inversions += 1;
            idx ~= i;
            //writefln("una inversion en %d", i);
        }
    }

    if(inversions > 2) {
        writeln("no");
        return;
    }

    if(inversions == 0) {
        if(a.isSorted) {
            writeln("yes");
            writeln("1 1");
        }
        else {
            writeln("yes");
            writefln("1 %d", n);
        }
    } else if (inversions == 1) {
        int[] firsttry;
        for(int i = 0; i <= idx[0]; i++) {
            firsttry ~= a[i];
        }
        firsttry.sort;
        for(int i = idx[0]+1; i < n; i++) {
            firsttry ~= a[i];
        }
        if(firsttry.isSorted) {
            writeln("yes");
            writefln("1 %d", idx[0]+1);
            return;
        }
        int[] secondtry;
        for(int i = 0; i < idx[0]; i++) {
            secondtry ~= a[i];
        }
        int[] lastpart;
        for(int i = idx[0]; i < n; i++) {
            lastpart ~= a[i];
        }
        lastpart.sort;
        foreach(item; lastpart) {
            secondtry ~= item;
        }
        if(secondtry.isSorted) {
            writeln("yes");
            writefln("%d %d", idx[0]+1, n);
            return;
        } else {
            writeln("no");
            return;
        }
    } else {
        int idx1 = idx[0];
        int idx2 = idx[1];
        int[] test;
        int[] fin;
        for(int i = 0; i < idx[0]; i++)
            fin ~= a[i];
        for(int i = idx[0]; i <= idx[1]; i++)
            test ~= a[i];
        test.sort;
        foreach(item; test)
            fin ~= item;
        for(int i = idx[1]+1; i < n; i++)
            fin ~= a[i];
        if(fin.isSorted) {
            writeln("yes");
            writefln("%d %d", idx[0]+1, idx[1]+1);
        }
        else
            writeln("no");
    }
}

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

void main(){
    int n=readln.chomp.to!int;
    auto a=readln.splitter
                 .map!(to!int)
                 .array;
    if(isStrictlyMonotonic(a)){
        writefln!"yes \n1 1";
    }else{
        int l=0,r=n-1;
        while(l<=n && a[l+1]>a[l])
            l++;
        while(r>=1 && a[r-1]<a[r])
            r--;
        if(a[l..r+1].isStrictlyMonotonic!"a>b"){
            if((l==0 || a[l-1]<a[r])
                    && (r==n-1 || a[r+1]>a[l]))
                writefln!"yes\n%d %d"(l+1,r+1);
            else writeln("no");
        }
        else writeln("no");
    }
}

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

void main(){
    int n=readln.chomp.to!int;
    auto a=readln.splitter
                 .map!(to!int)
                 .array;
    if(isStrictlyMonotonic(a)){
        writefln!"yes\n1 1";
    }else{
        int l=0,r=n-1;
        while(l<=n && a[l+1]>a[l])
            l++;
        while(r>=1 && a[r-1]<a[r])
            r--;
        if(a[l..r+1].isStrictlyMonotonic!"a>b"){
            if((l==0 || a[l-1]<a[r])
                    && (r==n-1 || a[r+1]>a[l]))
                writefln!"yes\n%d %d"(l+1,r+1);
            else writeln("no");
        }
        else writeln("no");
    }
}

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

//	Input
class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { tokens = readln.split; if (stdin.eof) throw new EOFException; } 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, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	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)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, 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)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int N;
int[] A;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		A = new int[N];
		foreach (i; 0 .. N) {
			A[i] = readInt;
		}
		int[] sorted = A.dup;
		sorted.sort();
		int minPos = N, maxPos = -1;
		foreach (i; 0 .. N) {
			if (A[i] != sorted[i]) {
				chmin(minPos, i);
				chmax(maxPos, i);
			}
		}
		if (minPos <= maxPos) {
			A[minPos .. maxPos + 1].reverse;
			bool ok = true;
			foreach (i; 0 .. N) {
				if (A[i] != sorted[i]) {
					ok = false;
				}
			}
			if (ok) {
				writeln("yes");
				writeln(minPos + 1, " ", maxPos + 1);
			} else {
				writeln("no");
			}
		} else {
			writeln("yes");
			writeln("1 1");
		}
	}
	} catch (EOFException) {}
}

import std.stdio;
import std.string;
import std.array: array;
import std.conv: to;
import std.algorithm: reverse, map, max, isSorted;

void main() {
	int n = readln.chomp.to!int;
	int[] a = readln.split.map!(to!int).array;

	int from;
	int to;

	int last_max = a[0];
	int last = a[0];
	byte x = 0;
	bool y = false;
	bool no = false;

	if (a.reverse.isSorted) {
		writeln("yes");
		writefln("1 %s", a.count);
	} else {

	foreach (int i; 0..n) {
		if ((x == 0 && a[0] > a[1] || x == 1 && a[0] < a[1]) && a[i] < last && !y) {
			from = i-1;
			y = true;
		}
		if ((x == 0 && a[0] > a[1] || x == 1 && a[0] < a[1]) && a[i] > last) {
			if (a[i] < last_max) {
				writeln("no");
				no = true;
				break;
			} else {
				to = i;
			}
			x++;
		} else if (x && a[i] < last) {
			writeln("no");
			no = true;
			break;
		}
		last = i;
		last_max = max(i, last_max);
	}
	if (!no) {
		writeln("yes");
		writefln("%s %s", from + 1, to + 1);
	}
	}
}

import std.stdio;
import std.string;
import std.array: array;
import std.conv: to;
import std.algorithm: reverse, map, max, isSorted;

void main() {
	int n = readln.chomp.to!int;
	int[] a = readln.split.map!(to!int).array;

	int from;
	int to;

	int last_max = a[0];
	int last = a[0];
	bool x = false;
	bool y = false;
	bool no = false;
	bool z = false;

	if (a.isSorted) {
		writeln("yes");
		writeln("1 1");
	} else if (a.reverse.isSorted) {
		writeln("yes");
		writefln("1 %s", a.count);
	} else {
	a.reverse;
	foreach (int i; 0..n) {
		if (a[i] < last && !y) {
			from = i-1;
			y = true;
		} else if (y && !z && a[i] > last) {
			if (a[i] < last_max) {
				writeln("no");
				no = true;
				break;
			} else {
				to = i-1;
			}
			z = true;
		} else if (z && a[i] < last) {
			writeln("no");
			no = true;
			break;
		}
		last = a[i];
		last_max = max(a[i], last_max);
	}
	if (!no) {
		writeln("yes");
		writefln("%s %s", from + 1, to + 1);
	}
	}
}

import std.stdio;
import std.string;
import std.array: array;
import std.conv: to;
import std.algorithm: reverse, map, max, isSorted;

void main() {
	int n = readln.chomp.to!int;
	long[] a = readln.split.map!(to!long).array;

	int from;
	int to;

	long last_max = a[0];
	long last = a[0];
	bool x = false;
	bool y = false;
	bool no = false;
	bool z = false;

	if (a.isSorted) {
		writeln("yes");
		writeln("1 1");
	} else if (a.reverse.isSorted) {
		writeln("yes");
		writefln("1 %s", a.count);
	} else {
	a.reverse;
	foreach (int i; 0..n) {
		if (a[i] < last && !y) {
			from = i-1;
			y = true;
		} else if (y && !z && a[i] > last) {
			if (a[i] < last_max) {
				writeln("no");
				no = true;
				break;
			} else {
				to = i-1;
			}
			z = true;
		} else if (z && a[i] < last) {
			writeln("no");
			no = true;
			break;
		}
		last = a[i];
		last_max = max(a[i], last_max);
	}
	if (!no) {
		writeln("yes");
		if (to != 0) {
			writefln("%s %s", from + 1, to + 1);
		} else {
			writefln("%s %s", from + 1, a.count);
		}
	}
	}
}


Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to ai inclusive. No tickets are sold at the last station.Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values ρi, j among all pairs 1 ≤ i < j ≤ n.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of stations. The second line contains n - 1 integer ai (i + 1 ≤ ai ≤ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to ai inclusive.

Print the sum of ρi, j among all pairs of 1 ≤ i < j ≤ n.

NoteIn the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.Consider the second sample:   ρ1, 2 = 1  ρ1, 3 = 2  ρ1, 4 = 3  ρ1, 5 = 3  ρ2, 3 = 1  ρ2, 4 = 2  ρ2, 5 = 2  ρ3, 4 = 1  ρ3, 5 = 1  ρ4, 5 = 1 Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.

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

immutable int MED_N = 1 << 17;
immutable int MAX_N = MED_N << 1;

__gshared int [] t;

int maxSeg (int lo, int hi)
{
	int res = 0;
	for (lo += MED_N, hi += MED_N; lo < hi; lo >>= 1, hi >>= 1)
	{
		if (lo & 1)
		{
			res = max (res, t[lo]);
			lo++;
		}
		if (hi & 1)
		{
			hi--;
			res = max (res, t[hi]);
		}
	}
	return res;
}

__gshared int n;
__gshared int [] a;

__gshared int [] limit;
__gshared long [] value;

long recur (int k, int pos)
{
	if (k == n - 1)
	{
		return 0L;
	}
	long res = 0L;
	res += n - 1 - k;
	int next = maxSeg (k + 1, pos + 1);
	if (limit[pos] != next)
	{
		value[pos] = recur (pos, next);
		limit[pos] = next;
	}
	res += value[pos];
	return res;
}

void main ()
{
	while (readf (" %s", &n) > 0)
	{
		readln;
		a = readln.split.map !(to !(int)).array;
		a ~= [n];
		a[] -= 1;
		t = new int [MAX_N];
		t[MED_N..MED_N + n] = a[];
		foreach_reverse (i; 1..MED_N)
		{
			t[i] = max (t[2 * i + 0], t[2 * i + 1]);
		}
		limit = new int [n];
		value = new long [n];

		long res = 0L;
		foreach_reverse (i; 0..n)
		{
			res += recur (i, a[i]);
		}
		writeln (res);
	}
}


At the foot of Liyushan Mountain, $$$n$$$ tents will be carefully arranged to provide accommodation for those who are willing to experience the joy of approaching nature, the tranquility of the night, and the bright starry sky.The $$$i$$$-th tent is located at the point of $$$(x_i, y_i)$$$ and has a weight of $$$w_i$$$. A tent is important if and only if both $$$x_i$$$ and $$$y_i$$$ are even. You need to remove some tents such that for each remaining important tent $$$(x, y)$$$, there do not exist $$$3$$$ other tents $$$(x'_1, y'_1)$$$, $$$(x'_2, y'_2)$$$ and $$$(x'_3, y'_3)$$$ such that both conditions are true:   $$$|x'_j-x|, |y'_j - y|\leq 1$$$ for all $$$j \in \{1, 2, 3\}$$$, and  these four tents form a parallelogram (or a rectangle) and one of its sides is parallel to the $$$x$$$-axis. Please maximize the sum of the weights of the tents that are not removed. Print the maximum value.

The first line contains a single integer $$$n$$$ ($$$1\leq n\leq 1\,000$$$), representing the number of tents. Each of the next $$$n$$$ lines contains three integers $$$x_i$$$, $$$y_i$$$ and $$$w_i$$$ ($$$-10^9\leq x_i,y_i \leq 10^9$$$, $$$1\leq w_i\leq 10^9$$$), representing the coordinate of the $$$i$$$-th tent and its weight. No two tents are located at the same point.

A single integer — the maximum sum of the weights of the remaining tents.

NoteHere is an illustration of the second example. Black triangles indicate the important tents. This example also indicates all $$$8$$$ forbidden patterns.

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

class MaxFlow(Capa) {
  enum Capa wEPS = 0;
  enum Capa wINF = 10L^^18;
  int n, m;
  int[][] g;
  int[] zu;
  Capa[] capa;
  Capa tof;
  int[] lev, see, que;
  this(int n) {
    this.n = n; m = 0; g = new int[][n]; zu = []; capa = [];
    lev = new int[n]; see = new int[n]; que = new int[n];
  }
  void addEdge(int u, int v, Capa w0, Capa w1 = 0) {
    g[u] ~= m; zu ~= v; capa ~= w0; ++m;
    g[v] ~= m; zu ~= u; capa ~= w1; ++m;
  }
  Capa augment(int src, int ink, Capa flo) {
    if (src == ink) return flo;
    foreach (i; g[src][see[src] .. $]) {
      if (capa[i] > wEPS && lev[src] < lev[zu[i]]) {
        Capa f = augment(zu[i], ink, min(flo, capa[i]));
        if (f > wEPS) { capa[i] -= f; capa[i ^ 1] += f; return f; }
      }
      ++see[src];
    }
    return 0;
  }
  bool dinic(int src, int ink, Capa flo = wINF) {
    for (tof = 0; tof + wEPS < flo; ) {
      int qb, qe;
      lev[] = -1;
     dinicBFS:
      for (lev[src] = 0, que[qe++] = src; qb != qe; ) {
        const u = que[qb++];
        foreach (i; g[u]) {
          const v = zu[i];
          if (capa[i] > wEPS && lev[v] == -1) {
            lev[v] = lev[u] + 1; que[qe++] = v;
            if (v == ink) break dinicBFS;
          }
        }
      }
      if (lev[ink] == -1) return false;
      see[] = 0;
      for (; ; ) {
        Capa f = augment(src, ink, flo - tof);
        if (f <= wEPS) break;
        tof += f;
      }
    }
    return true;
  }
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto X = new long[N];
      auto Y = new long[N];
      auto W = new long[N];
      foreach (u; 0 .. N) {
        X[u] = readLong();
        Y[u] = readLong();
        W[u] = readLong();
      }

      alias Pt = Tuple!(long, "x", long, "y", int, "id");
      auto ps = new Pt[N];
      foreach (u; 0 .. N) {
        ps[u] = Pt(X[u], Y[u], u);
      }
      ps.sort;
      int get(long x, long y) {
        const pos = ps.lowerBound(Pt(x, y, -1));
        return (pos < N && ps[pos].x == x && ps[pos].y == y) ? ps[pos].id : -1;
      }

      auto mf = new MaxFlow!long(N * 2 + 2);
      foreach (u; 0 .. N) {
        mf.addEdge(u * 2, u * 2 + 1, W[u]);
        void ae(long x, long y) {
          const v = get(x, y);
          if (v != -1) {
            mf.addEdge(u * 2 + 1, v * 2, mf.wINF);
          }
        }
        if (!(Y[u] & 1)) {
          if (!(X[u] & 1)) {
            foreach (dy; [-1, +1]) {
              ae(X[u], Y[u] + dy);
            }
          } else {
            mf.addEdge(N * 2 + 1, u * 2, mf.wINF);
            foreach (dx; [-1, +1]) {
              ae(X[u] + dx, Y[u]);
            }
          }
        } else {
          if (!(X[u] & 1)) {
            foreach (dx; [-1, +1]) {
              ae(X[u] + dx, Y[u]);
            }
          } else {
            mf.addEdge(u * 2 + 1, N * 2, mf.wINF);
          }
        }
      }
      mf.dinic(N * 2 + 1, N * 2);

      long ans = W.sum;
      ans -= mf.tof;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

class MaxFlow(Capa) {
  enum Capa wEPS = 0;
  enum Capa wINF = 10L^^18;
  int n, m;
  int[][] g;
  int[] zu;
  Capa[] capa;
  Capa tof;
  int[] lev, see, que;
  this(int n) {
    this.n = n; m = 0; g = new int[][n]; zu = []; capa = [];
    lev = new int[n]; see = new int[n]; que = new int[n];
  }
  void addEdge(int u, int v, Capa w0, Capa w1 = 0) {
    g[u] ~= m; zu ~= v; capa ~= w0; ++m;
    g[v] ~= m; zu ~= u; capa ~= w1; ++m;
  }
  Capa augment(int src, int ink, Capa flo) {
    if (src == ink) return flo;
    foreach (i; g[src][see[src] .. $]) {
      if (capa[i] > wEPS && lev[src] < lev[zu[i]]) {
        Capa f = augment(zu[i], ink, min(flo, capa[i]));
        if (f > wEPS) { capa[i] -= f; capa[i ^ 1] += f; return f; }
      }
      ++see[src];
    }
    return 0;
  }
  bool dinic(int src, int ink, Capa flo = wINF) {
    for (tof = 0; tof + wEPS < flo; ) {
      int qb, qe;
      lev[] = -1;
     dinicBFS:
      for (lev[src] = 0, que[qe++] = src; qb != qe; ) {
        const u = que[qb++];
        foreach (i; g[u]) {
          const v = zu[i];
          if (capa[i] > wEPS && lev[v] == -1) {
            lev[v] = lev[u] + 1; que[qe++] = v;
            if (v == ink) break dinicBFS;
          }
        }
      }
      if (lev[ink] == -1) return false;
      see[] = 0;
      for (; ; ) {
        Capa f = augment(src, ink, flo - tof);
        if (f <= wEPS) break;
        tof += f;
      }
    }
    return true;
  }
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto X = new long[N];
      auto Y = new long[N];
      auto W = new long[N];
      foreach (u; 0 .. N) {
        X[u] = readLong();
        Y[u] = readLong();
        W[u] = readLong();
      }

      alias Pt = Tuple!(long, "x", long, "y", int, "id");
      auto ps = new Pt[N];
      foreach (u; 0 .. N) {
        ps[u] = Pt(X[u], Y[u], u);
      }
      ps.sort;
      int get(long x, long y) {
        const pos = ps.lowerBound(Pt(x, y, -1));
        return (pos < N && ps[pos].x == x && ps[pos].y == y) ? ps[pos].id : -1;
      }

      auto mf = new MaxFlow!long(N * 2 + 2);
      foreach (u; 0 .. N) {
        mf.addEdge(u * 2, u * 2 + 1, W[u]);
        void ae(long x, long y) {
          const v = get(x, y);
          if (v != -1) {
            mf.addEdge(u * 2 + 1, v * 2, mf.wINF);
          }
        }
        if (!(Y[u] & 1)) {
          if (!(X[u] & 1)) {
            foreach (dy; [-1, +1]) {
              ae(X[u], Y[u] + dy);
            }
          } else {
            mf.addEdge(N * 2 + 1, u * 2, mf.wINF);
            foreach (dx; [-1, +1]) {
              ae(X[u] + dx, Y[u]);
            }
          }
        } else {
          if (!(X[u] & 1)) {
            mf.addEdge(u * 2 + 1, N * 2, mf.wINF);
          } else {
            foreach (dx; [-1, +1]) {
              ae(X[u] + dx, Y[u]);
            }
          }
        }
      }
      mf.dinic(N * 2 + 1, N * 2);

      long ans = W.sum;
      ans -= mf.tof;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

class MaxFlow(Capa) {
  enum Capa wEPS = 0;
  enum Capa wINF = 10L^^18;
  int n, m;
  int[][] g;
  int[] zu;
  Capa[] capa;
  Capa tof;
  int[] lev, see, que;
  this(int n) {
    this.n = n; m = 0; g = new int[][n]; zu = []; capa = [];
    lev = new int[n]; see = new int[n]; que = new int[n];
  }
  void addEdge(int u, int v, Capa w0, Capa w1 = 0) {
    g[u] ~= m; zu ~= v; capa ~= w0; ++m;
    g[v] ~= m; zu ~= u; capa ~= w1; ++m;
  }
  Capa augment(int src, int ink, Capa flo) {
    if (src == ink) return flo;
    foreach (i; g[src][see[src] .. $]) {
      if (capa[i] > wEPS && lev[src] < lev[zu[i]]) {
        Capa f = augment(zu[i], ink, min(flo, capa[i]));
        if (f > wEPS) { capa[i] -= f; capa[i ^ 1] += f; return f; }
      }
      ++see[src];
    }
    return 0;
  }
  bool dinic(int src, int ink, Capa flo = wINF) {
    for (tof = 0; tof + wEPS < flo; ) {
      int qb, qe;
      lev[] = -1;
     dinicBFS:
      for (lev[src] = 0, que[qe++] = src; qb != qe; ) {
        const u = que[qb++];
        foreach (i; g[u]) {
          const v = zu[i];
          if (capa[i] > wEPS && lev[v] == -1) {
            lev[v] = lev[u] + 1; que[qe++] = v;
            if (v == ink) break dinicBFS;
          }
        }
      }
      if (lev[ink] == -1) return false;
      see[] = 0;
      for (; ; ) {
        Capa f = augment(src, ink, flo - tof);
        if (f <= wEPS) break;
        tof += f;
      }
    }
    return true;
  }
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto X = new long[N];
      auto Y = new long[N];
      auto W = new long[N];
      foreach (u; 0 .. N) {
        X[u] = readLong();
        Y[u] = readLong();
        W[u] = readLong();
      }

      alias Pt = Tuple!(long, "x", long, "y", int, "id");
      auto ps = new Pt[N];
      foreach (u; 0 .. N) {
        ps[u] = Pt(X[u], Y[u], u);
      }
      ps.sort;
      int get(long x, long y) {
        const pos = ps.lowerBound(Pt(x, y, -1));
        return (pos < N && ps[pos].x == x && ps[pos].y == y) ? ps[pos].id : -1;
      }

      auto mf = new MaxFlow!long(N * 2 + 2);
      foreach (u; 0 .. N) {
        mf.addEdge(u * 2, u * 2 + 1, W[u]);
        void ae(long x, long y) {
          const v = get(x, y);
          if (v != -1) {
            mf.addEdge(u * 2 + 1, v * 2, mf.wINF);
          }
        }
        if (!(Y[u] & 1)) {
          if (!(X[u] & 1)) {
            mf.addEdge(N * 2 + 1, u * 2, mf.wINF);
            foreach (dx; [-1, +1]) {
              ae(X[u] + dx, Y[u]);
            }
          } else {
            foreach (dy; [-1, +1]) foreach (dx; [-2, 0, +2]) {
              ae(X[u] + dx, Y[u] + dy);
            }
          }
        } else {
          if (!(X[u] & 1)) {
            mf.addEdge(u * 2 + 1, N * 2, mf.wINF);
          } else {
            foreach (dx; [-1, +1]) {
              ae(X[u] + dx, Y[u]);
            }
          }
        }
      }
      mf.dinic(N * 2 + 1, N * 2);

      long ans = W.sum;
      ans -= mf.tof;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.

The first line contains integer n (1 ≤ n ≤ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card.

In a single line print the answer to the problem — the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1.

NoteIn the first test you can make only one number that is a multiple of 90 — 0.In the second test you can make number 5555555550, it is a multiple of 90.

import std.c.stdio;
import std.stdio;

void main() {
  int n; scanf("%d", &n);
  int a;
  int f = 0, z = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d", &a);
    if (a == 5) { f++; }
    else { z++; }
  }
  if (z == 0) {
    printf("-1\n");
    return;
  }
  if (f < 9) {
    printf("0\n");
    return;
  }
  int x = f / 9 * 9;
  for (int i = 0; i < x; i++) {
    printf("5");
  }
  for (int i = 0; i < z; i++) {
    printf("0");
  }
  printf("\n");
}

import std.stdio;

void main() {
    int n;
    scanf("%u", &n);

    int a5, a0;
    while(n--) {
		int t;
		scanf("%u", &t);

		if(t == 5) a5++;
		else a0++;
    }

	if(a0 == 0) {
		write(-1);
		return;
	}

	int m, c;

	foreach(i; 0..a5)
		if((m += 5) % 9 == 0) c = i + 1;

	if(!c)
		a0 = 1;

	while(c--) write(5);
	while(a0--) write(0);
}

import std.c.stdio;
import std.stdio;

void main() {
  int n; scanf("%d", &n);
  int a;
  int f = 0, z = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d", &a);
    if (a == 5) { f++; }
    else { z++; }
  }
  if (f < 9 || z == 0) {
    printf("0\n");
    return;
  }
  int x = f / 9 * 9;
  for (int i = 0; i < x; i++) {
    printf("5");
  }
  for (int i = 0; i < z; i++) {
    printf("0");
  }
  printf("\n");
}