Polycarp has invited $$$n$$$ friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side.Each friend is characterized by two values $$$h_i$$$ (their height) and $$$w_i$$$ (their width). On the photo the $$$i$$$-th friend will occupy a rectangle $$$h_i \times w_i$$$ (if they are standing) or $$$w_i \times h_i$$$ (if they are lying on the side).The $$$j$$$-th friend can be placed in front of the $$$i$$$-th friend on the photo if his rectangle is lower and narrower than the rectangle of the $$$i$$$-th friend. Formally, at least one of the following conditions must be fulfilled:  $$$h_j < h_i$$$ and $$$w_j < w_i$$$ (both friends are standing or both are lying);  $$$w_j < h_i$$$ and $$$h_j < w_i$$$ (one of the friends is standing and the other is lying). For example, if $$$n = 3$$$, $$$h=[3,5,3]$$$ and $$$w=[4,4,3]$$$, then:  the first friend can be placed in front of the second: $$$w_1 < h_2$$$ and $$$h_1 < w_2$$$ (one of the them is standing and the other one is lying);  the third friend can be placed in front of the second: $$$h_3 < h_2$$$ and $$$w_3 < w_2$$$ (both friends are standing or both are lying). In other cases, the person in the foreground will overlap the person in the background.Help Polycarp for each $$$i$$$ find any $$$j$$$, such that the $$$j$$$-th friend can be located in front of the $$$i$$$-th friend (i.e. at least one of the conditions above is fulfilled).Please note that you do not need to find the arrangement of all people for a group photo. You just need to find for each friend $$$i$$$ any other friend $$$j$$$ who can be located in front of him. Think about it as you need to solve $$$n$$$ separate independent subproblems.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of friends. This is followed by $$$n$$$ lines, each of which contains a description of the corresponding friend. Each friend is described by two integers $$$h_i$$$ and $$$w_i$$$ ($$$1 \leq h_i, w_i \leq 10^9$$$) — height and width of the $$$i$$$-th friend, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output $$$n$$$ integers on a separate line, where the $$$i$$$-th number is the index of a friend that can be placed in front of the $$$i$$$-th. If there is no such friend, then output -1. If there are several answers, output any.

NoteThe first test case is described in the statement.In the third test case, the following answers are also correct:   $$$[-1, -1, 1, 2]$$$;  $$$[-1, -1, 1, 1]$$$;  $$$[-1, -1, 2, 1]$$$.

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

struct r {
    int h, w, idx;
};

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

    while (t--) {
        int n;
        readf("%s", &n);
        readln;

        auto a = new r[] (n);
        foreach (i; 0 .. n) {
            readf("%s %s", &a[i].h, &a[i].w);
            readln;

            a[i].idx = i;
        }

        foreach (i; 0 .. n) {
            if (a[i].h > a[i].w) { swap(a[i].h, a[i].w); }
        }

        a.schwartzSort!(x => x.h);
        int mn = -1, nxtmn = 0;

        auto ans = new int[] (n);
        ans[a[0].idx] = -1;

        foreach (i; 1 .. n) {
            if (a[i].h > a[i-1].h) { mn = nxtmn; }

            ans[a[i].idx] = mn != -1 && a[mn].w < a[i].w ? a[mn].idx : -1;

            if (a[i].w < a[nxtmn].w) { nxtmn = i; }
        }

        ans.map!(x => x != -1 ? x+1 : -1).map!(to!string).join(" ").writeln;
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto h = new long[](n);
		auto w = new long[](n);
		foreach (i; 0..n)
		{
			h[i] = RD;
			w[i] = RD;
		}

		auto tmp = new int[](n);
		tmp[] = -1;

		auto list = new long[][](n*2);
		foreach (i; 0..n)
		{
			list[i*2] = [h[i], w[i], i];
			list[i*2+1] = [w[i], h[i], i];
		}
		auto index = list.MAKE_IDX!"a[0] == b[0] ? a[1] > b[1] : a[0] < b[0]";
		long minW = long.max;
		int posW;
		foreach (i; index)
		{
			auto hh = list[i][0];
			auto ww = list[i][1];
			auto jj = cast(int)list[i][2];
			if (minW < ww)
			{
				tmp[jj] = posW+1;
			}
			if (ww < minW)
			{
				minW = ww;
				posW = jj;
			}
		}

		ans[ti] = tmp;
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		alias Friend = Tuple !(int, q{w}, int, q{h}, int, q{id});
		auto f = new Friend [n * 2];
		foreach (i; 0..n)
		{
			int w, h;
			readf !(" %s %s") (w, h);
			f[i * 2 + 0] = Friend (w, h, i);
			f[i * 2 + 1] = Friend (h, w, i);
		}
		sort (f);
		auto lo = f.front;
		auto answer = (-1).repeat (n).array;
		int j = 0;
		foreach (ref c; f)
		{
			while (f[j].w < c.w)
			{
				if (lo.h > f[j].h)
				{
					lo = f[j];
				}
				j += 1;
			}
			if (lo.w < c.w && lo.h < c.h)
			{
				answer[c.id] = lo.id + 1;
			}
		}
		writefln !("%(%s %)") (answer);
	}
}

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

struct r {
    int h, w, idx;
};

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

    while (t--) {
        int n;
        readf("%s", &n);
        readln;

        auto a = new r[] (n);
        foreach (i; 0 .. n) {
            readf("%s %s", &a[i].h, &a[i].w);
            readln;
            a[i].idx = i;
        }

        a.schwartzSort!(x => x.h);
        int mn = -1, nxtmn = 0;

        auto ans = new int[] (n);
        ans[a[0].idx] = -1;

        foreach (i; 1 .. n) {
            if (a[i].h > a[i-1].h) { mn = nxtmn; }

            ans[a[i].idx] = mn != -1 && a[mn].w < a[i].w ? a[mn].idx : -1;

            if (a[i].w < a[nxtmn].w) { nxtmn = i; }
        }

        ans.map!(x => x != -1 ? x+1 : -1).map!(to!string).join(" ").writeln;
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto h = new long[](n);
		auto w = new long[](n);
		foreach (i; 0..n)
		{
			h[i] = RD;
			w[i] = RD;
		}

		auto tmp = new int[](n);
		tmp[] = -1;

		auto list = new long[][](n*2);
		foreach (i; 0..n)
		{
			list[i*2] = [h[i], w[i], i];
			list[i*2+1] = [w[i], h[i], i];
		}
		auto index = list.MAKE_IDX!"a[0] < b[0]";
		long minW = long.max;
		int posW;
		foreach (i; index)
		{
			auto hh = list[i][0];
			auto ww = list[i][1];
			auto jj = cast(int)list[i][2];
			if (minW < ww)
			{
				tmp[jj] = posW+1;
			}
			if (ww < minW)
			{
				minW = ww;
				posW = jj;
			}
		}

		ans[ti] = tmp;
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		alias Friend = Tuple !(int, q{w}, int, q{h}, int, q{id});
		auto f = new Friend [n * 2];
		foreach (i; 0..n)
		{
			int w, h;
			readf !(" %s %s") (w, h);
			f[i * 2 + 0] = Friend (w, h, i);
			f[i * 2 + 1] = Friend (h, w, i);
		}
		sort (f);
		auto lo = f.front;
		auto answer = (-1).repeat (n).array;
		foreach (ref c; f)
		{
			if (lo.h > c.h)
			{
				lo = c;
			}
			if (lo.w < c.w && lo.h < c.h)
			{
				answer[c.id] = lo.id + 1;
			}
		}
		writefln !("%(%s %)") (answer);
	}
}


The only difference between the two versions is that this version asks the maximal possible answer.Homer likes arrays a lot. Today he is painting an array $$$a_1, a_2, \dots, a_n$$$ with two kinds of colors, white and black. A painting assignment for $$$a_1, a_2, \dots, a_n$$$ is described by an array $$$b_1, b_2, \dots, b_n$$$ that $$$b_i$$$ indicates the color of $$$a_i$$$ ($$$0$$$ for white and $$$1$$$ for black).According to a painting assignment $$$b_1, b_2, \dots, b_n$$$, the array $$$a$$$ is split into two new arrays $$$a^{(0)}$$$ and $$$a^{(1)}$$$, where $$$a^{(0)}$$$ is the sub-sequence of all white elements in $$$a$$$ and $$$a^{(1)}$$$ is the sub-sequence of all black elements in $$$a$$$. For example, if $$$a = [1,2,3,4,5,6]$$$ and $$$b = [0,1,0,1,0,0]$$$, then $$$a^{(0)} = [1,3,5,6]$$$ and $$$a^{(1)} = [2,4]$$$.The number of segments in an array $$$c_1, c_2, \dots, c_k$$$, denoted $$$\mathit{seg}(c)$$$, is the number of elements if we merge all adjacent elements with the same value in $$$c$$$. For example, the number of segments in $$$[1,1,2,2,3,3,3,2]$$$ is $$$4$$$, because the array will become $$$[1,2,3,2]$$$ after merging adjacent elements with the same value. Especially, the number of segments in an empty array is $$$0$$$.Homer wants to find a painting assignment $$$b$$$, according to which the number of segments in both $$$a^{(0)}$$$ and $$$a^{(1)}$$$, i.e. $$$\mathit{seg}(a^{(0)})+\mathit{seg}(a^{(1)})$$$, is as large as possible. Find this number.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$).

Output a single integer, indicating the maximal possible total number of segments.

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

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

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

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

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

      const gs = A.group.array;
      const gsLen = cast(int)(gs.length);
      debug {
        writeln("A = ", A);
        writeln("gs = ", gs);
      }

      int ans;
      for (int j = 0, k; j < gsLen; j = k) {
        for (k = j; k < gsLen && (gs[j][1] == 1) == (gs[k][1] == 1); ++k) {}
        if (gs[j][1] == 1) {
          ans += (k - j);
          if (0 < j && k < gsLen && gs[j - 1][0] == gs[k][0]) {
            if ((k - j) % 2 != 0) {
              bool bad = true;
              for (int l = j + 1; l < k; l += 2) {
                bad = bad && (gs[j - 1][0] == gs[l][0]);
              }
              if (bad) {
                debug {
                  writeln("bad ", gs[j .. k]);
                }
                ans -= 1;
              }
            }
          }
        } else {
          ans += 2 * (k - j);
        }
      }
      writeln(ans);

      debug {
        int brt = 0;
        foreach (p; 0 .. 1 << N) {
          int cost;
          int[2] bs = [-1, -1];
          foreach (i; 0 .. N) {
            const s = (p >> i) & 1;
            if (bs[s] != A[i]) {
              ++cost;
              bs[s] = A[i];
            }
          }
          chmax(brt, cost);
        }
        writeln("brt = ", brt);
        assert(brt == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		int res = 0;
		int [2] [] p = [[-1, -1]];
		foreach (ref c; a)
		{
			int [2] [] [2] q;
			int next = res;
			foreach (ref prev; p)
			{
				foreach (j; 0..2)
				{
					auto good = (prev[j] != c);
					q[good] ~= [c, prev[!j]];
	                	}
			}
			foreach (j; 0..2)
			{
				if (!q[j].empty)
				{
					res = next + j;
					p = q[j];
				}
			}
			foreach (ref prev; p)
			{
				sort (prev[]);
			}
			p = p.sort.uniq.take (4).array;
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

	auto pos = new int[][](n+1);
	foreach (i; 0..n)
	{
		pos[a[i]] ~= i;
	}

	int[] a0 = [n], a1 = [n];
	foreach (i; 0..n)
	{
		pos[a[i]].popFront;
		if (a0.back == a[i])
			a1 ~= a[i];
		else if (a1.back == a[i])
			a0 ~= a[i];
		else
		{
			int x = n, y = n;
			if (!pos[a0.back].empty)
				x = pos[a0.back].front;
			if (!pos[a1.back].empty)
				y = pos[a1.back].front;
			if (x < y)
				a0 ~= a[i];
			else
				a1 ~= a[i];
		}
	}

	debug writeln("a0:", a0);
	debug writeln("a1:", a1);
	a0.popFront;
	a1.popFront;
	long ans;
	if (!a0.empty)
	{
		++ans;

		foreach (i; 1..a0.length)
		{
			if (a0[i-1] != a0[i])
				++ans;
		}
	}
	if (!a1.empty)
	{
		++ans;
		foreach (i; 1..a1.length)
		{
			if (a1[i-1] != a1[i])
				++ans;
		}
	}

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

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 N; get(N);
    int a, b, c;
    int[] aa; get(aa);
    foreach (i, x; aa) {
        if (a == x && b == x) {
            continue;
        } else if (a != x && b != x) {
            if (i+1 < aa.length) {
                auto y = aa[i+1];
                if (a == y) {
                    a = x;
                } else {
                    b = x;
                }
            }
        } else if (a != x) {
            a = x;
        } else if (b != x) {
            b = x;
        }
        ++c;
    }
    writeln(c);
}

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

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

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

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

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

      const gs = A.group.array;
      const gsLen = cast(int)(gs.length);
      debug {
        writeln("gs = ", gs);
      }

      int ans;
      for (int j = 0, k; j < gsLen; j = k) {
        for (k = j; k < gsLen && (gs[j][1] == 1) == (gs[k][1] == 1); ++k) {}
        if (gs[j][1] == 1) {
          ans += (k - j);
          if (0 < j && k < gsLen) {
            if ((k - j) % 2 != 0) {
              bool bad = true;
              for (int l = j + 1; l < k; l += 2) {
                bad = bad && (gs[j - 1][0] == gs[l][0] && gs[l][0] == gs[k][0]);
              }
              if (bad) {
                debug {
                  writeln("bad ", gs[j .. k]);
                }
                ans -= 1;
              }
            }
          }
        } else {
          ans += 2 * (k - j);
        }
      }
      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)); }

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

      auto nxt = new int[N + 1];
      nxt[N] = -1;
      foreach_reverse (i; 0 .. N) {
        nxt[i] = (i + 1 < N && A[i] != A[i + 1]) ? A[i + 1] : nxt[i + 1];
      }
      debug {
        writeln("nxt = ", nxt);
      }

      int ans;
      int[2] bs = [-1, -1];
      foreach (i; 0 .. N) {
        void add(int s) {
          if (bs[s] != A[i]) {
            ++ans;
          }
          bs[s] = A[i];
        }
        add(i % 2);
      }
      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)); }

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

      auto nxt = new int[N + 1];
      nxt[N] = -1;
      foreach_reverse (i; 0 .. N) {
        nxt[i] = (i + 1 < N && A[i] != A[i + 1]) ? A[i + 1] : nxt[i + 1];
      }
      debug {
        writeln("nxt = ", nxt);
      }

      int ans;
      int[2] bs = [-1, -1];
      foreach (i; 0 .. N) {
        void add(int s) {
          if (bs[s] != A[i]) {
            ++ans;
          }
          bs[s] = A[i];
        }
        if (bs[0] == A[i]) {
          add(1);
        } else if (bs[1] == A[i]) {
          add(0);
        } else if (bs[0] == nxt[i]) {
          add(1);
        } else if (bs[1] == nxt[i]) {
          add(0);
        } else {
          add(0);
        }
      }
      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)); }

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

      int ans;
      foreach (g; A.group) {
        ans += (g[1] >= 2) ? 2 : 1;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;

	long[] a0 = [a[0]], a1;
	foreach (i; 1..n)
	{
		if (a0.back == a[i])
			a1 ~= a[i];
		else
			a0 ~= a[i];
	}

	long ans = 1;
	foreach (i; 1..a0.length)
	{
		if (a0[i-1] != a0[i])
			++ans;
	}
	if (!a1.empty)
	{
		++ans;
		foreach (i; 1..a1.length)
		{
			if (a1[i-1] != a1[i])
				++ans;
		}
	}

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

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 N; get(N);
    int a, b, c;
    foreach (x; readln.split.to!(int[])) {
        if (a != x) {
            a = x;
            ++c;
        } else if (b != x) {
            b = x;
            ++c;
        }
    }
    writeln(c);
}


A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$).

For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new string[](t*2);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!string;
		bool f;
		foreach (i; 0..n)
		{
			if (s[i] == '0')
			{
				ans[ti*2] ~= '0';
				ans[ti*2+1] ~= '0';
			}
			else if (s[i] == '2')
			{
				if (f)
				{
					ans[ti*2] ~= '0';
					ans[ti*2+1] ~= '2';
				}
				else
				{
					ans[ti*2] ~= '1';
					ans[ti*2+1] ~= '1';
				}
			}
			else if (s[i] == '1')
			{
				if (f)
				{
					ans[ti*2] ~= '0';
					ans[ti*2+1] ~= '1';
				}
				else
				{
					ans[ti*2] ~= '1';
					ans[ti*2+1] ~= '0';
					f = true;
				}
			}
			else if (s[i] == '3')
			{
				if (f)
				{
					ans[ti*2] ~= '1';
					ans[ti*2+1] ~= '2';
				}
				else
				{
					ans[ti*2] ~= '2';
					ans[ti*2+1] ~= '1';
					f = true;
				}
			}
		}
	}

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


Slime and his $$$n$$$ friends are at a party. Slime has designed a game for his friends to play.At the beginning of the game, the $$$i$$$-th player has $$$a_i$$$ biscuits. At each second, Slime will choose a biscuit randomly uniformly among all $$$a_1 + a_2 + \ldots + a_n$$$ biscuits, and the owner of this biscuit will give it to a random uniform player among $$$n-1$$$ players except himself. The game stops when one person will have all the biscuits.As the host of the party, Slime wants to know the expected value of the time that the game will last, to hold the next activity on time.For convenience, as the answer can be represented as a rational number $$$\frac{p}{q}$$$ for coprime $$$p$$$ and $$$q$$$, you need to find the value of $$$(p \cdot q^{-1})\mod 998\,244\,353$$$. You can prove that $$$q\mod 998\,244\,353 \neq 0$$$.

The first line contains one integer $$$n\ (2\le n\le 100\,000)$$$: the number of people playing the game. The second line contains $$$n$$$ non-negative integers $$$a_1,a_2,\dots,a_n\ (1\le a_1+a_2+\dots+a_n\le 300\,000)$$$, where $$$a_i$$$ represents the number of biscuits the $$$i$$$-th person own at the beginning.

Print one integer: the expected value of the time that the game will last, modulo $$$998\,244\,353$$$.

NoteFor the first example, in the first second, the probability that player $$$1$$$ will give the player $$$2$$$ a biscuit is $$$\frac{1}{2}$$$, and the probability that player $$$2$$$ will give the player $$$1$$$ a biscuit is $$$\frac{1}{2}$$$. But anyway, the game will stop after exactly $$$1$$$ second because only one player will occupy all biscuits after $$$1$$$ second, so the answer is $$$1$$$.

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

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

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

      const M = A.sum;
      const invM = Mint(M).inv;
      const invN1 = Mint(N - 1).inv;

      // e[i] = 1 + (i/M) e[i-1] + (1-i/M) (1-1/(N-1)) e[i] + (1-i/M) (1/(N_1)) e[i+1]
      auto fs = new Mint[M + 1];
      auto gs = new Mint[M + 1];
      gs[M - 1] = 1;
      foreach_reverse (i; 1 .. M) {
        const probN = i * invM;
        const prob0 = (1 - i * invM) * (1 - invN1);
        const probP = (1 - i * invM) * invN1;
        fs[i - 1] = ((1 - prob0) * fs[i] - probP * fs[i + 1] - 1) / probN;
        gs[i - 1] = ((1 - prob0) * gs[i] - probP * gs[i + 1] - 0) / probN;
      }
      // e[0] = 1 + (1-1/(N-1)) e[0] + (1/(N_1)) e[1]
      const fM1 = (1 - (1 - invN1)) * fs[0] - invN1 * fs[1] - 1;
      const gM1 = (1 - (1 - invN1)) * gs[0] - invN1 * gs[1] - 0;
      const eM1 = -fM1 / gM1;
      auto es = new Mint[M + 1];
      foreach (i; 0 .. M + 1) {
        es[i] = fs[i] + gs[i] * eM1;
      }

      Mint ans;
      foreach (i; 0 .. N) {
        ans += es[A[i]];
      }
      ans -= es[0] * (N - 1);
      ans /= N;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.Find the size of the maximum clique in such graph.

The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points. Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.

Print a single number — the number of vertexes in the maximum clique of the given graph.

NoteIf you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!The picture for the sample test.

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

alias XW = Tuple!(long, "x", long, "w");

void main()
{
    auto N = readln.chomp.to!int;
    XW[] xws;
    foreach (_; 0..N) {
        auto xw = readln.split.to!(long[]);
        xws ~= XW(xw[0], xw[1]);
    }
    sort!"a.x + a.w < b.x + b.w"(xws);
    int r;
    long last = long.min;
    foreach (xw; xws) {
        if (last <= xw.x - xw.w) {
            ++r;
            last = xw.x + xw.w;
        }
    }
    writeln(r);
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto x = new int [n];
		auto r = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s %s", &x[i], &r[i]);
		}

		alias Pair = Tuple !(int, q{lo}, int, q{hi});
		Pair [] a;
		foreach (i; 0..n)
		{
			a ~= Pair (x[i] - r[i], x[i] + r[i]);
		}
		a.sort !(q{a.hi < b.hi}, SwapStrategy.stable);
		long res = 0;
		int cur = int.min;
		foreach (c; a)
		{
			if (cur <= c.lo)
			{
				res++;
				cur = c.hi;
			}
		}
		writeln (res);
	}
}

import std.algorithm, std.conv, std.range, std.stdio, std.typecons, std.string;
void main () {
	int n, x, r, res, cur = int.min;
	string s;
	readf (" %s%s", &n, &s);
	auto a = s.split.map!(to!int).chunks (2)
		.map!"tuple(a[0]+a[1],a[0]-a[1])".array.sort;
	foreach (c; a) if (cur <= c[1]) res++, cur = c[0];
	res.writeln;
}

import std.algorithm, std.stdio, std.typecons;
void main () {
	int n, x, r, res, cur = int.min;
	readf (" %s", &n);
	Tuple !(int, int) [] a;
	foreach (i; 0..n) readf (" %s %s", &x, &r), a ~= tuple (x + r, x - r);
	a.sort;
	foreach (c; a) if (cur <= c[1]) res++, cur = c[0];
	res.writeln;
}

import std.algorithm, std.stdio, std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Pair = Tuple !(int, q{hi}, int, q{lo});
		Pair [] a;
		foreach (i; 0..n)
		{
			int x, r;
			readf (" %s %s", &x, &r);
			a ~= Pair (x + r, x - r);
		}
		sort (a);
		long res = 0;
		int cur = int.min;
		foreach (c; a)
		{
			if (cur <= c.lo)
			{
				res++;
				cur = c.hi;
			}
		}
		writeln (res);
	}
}


Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions in the operands are different.For example, if X = 10910 = 11011012, Y = 4110 = 1010012, then:  X xor Y  =  6810  =  10001002. Write a program, which takes two non-negative integers A and B as an input and finds two non-negative integers X and Y, which satisfy the following conditions:   A = X + Y  B  =  X xor Y, where xor is bitwise exclusive or.  X is the smallest number among all numbers for which the first two conditions are true.

The first line contains integer number A and the second line contains integer number B (0 ≤ A, B ≤ 264 - 1).

The only output line should contain two integer non-negative numbers X and Y. Print the only number -1 if there is no answer.

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

void main()
{
    ulong a, b;
    readf("%s %s", &a, &b);
    readln;

    ulong x = 0, y = 0;
    bool need = false;
    foreach_reverse (i; 0 .. 64) {
        ulong val = 1L << i;
        bool sm = (val & a) > 0;
        bool xr = (val & b) > 0;

        if (sm) {
            if (xr) {
                if (need) {
                    writeln(-1);
                    return;
                } else {
                    y += val;
                }
            } else {
                if (need) {
                    x += val;
                    y += val;
                } else {
                    need = true;
                }
            }
        } else {
            if (xr) {
                if (need) {
                    y += val;
                } else {
                    writeln(-1);
                    return;
                }
            } else {
                if (need) {
                    x += val;
                    y += val;
                    need = false;
                } else {
                }
            }
        }
    }

    if (need) {
        writeln(-1);
        return;
    }

    writeln(x, ' ', y);
}


There is a weighted tree with $$$n$$$ nodes and $$$n-1$$$ edges. The nodes are conveniently labeled from $$$1$$$ to $$$n$$$. The weights are positive integers at most $$$100$$$. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes.Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes $$$p$$$ and $$$q$$$, and the judge will return the maximum distance between a node in $$$p$$$ and a node in $$$q$$$. In the words, maximum distance between $$$x$$$ and $$$y$$$, where $$$x \in p$$$ and $$$y \in q$$$. After asking not more than $$$9$$$ questions, you must report the maximum distance between any pair of nodes.

NoteIn the first example, the first tree looks as follows: In the first question, we have $$$p = {1}$$$, and $$$q = {2, 3, 4, 5}$$$. The maximum distance between a node in $$$p$$$ and a node in $$$q$$$ is $$$9$$$ (the distance between nodes $$$1$$$ and $$$5$$$).The second tree is a tree with two nodes with an edge with weight $$$99$$$ between them.

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

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

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

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

enum K = 9;

void main() {
  const numCases = readInt();
  foreach (caseId; 0 .. numCases) {
    const N = readInt();
    int ans;
    foreach (k; 0 .. K) {
      int[][2] a;
      foreach (u; 0 .. N) {
        a[(u >> k) & 1] ~= u;
      }
      if (!a[0].empty && !a[1].empty) {
        writefln("%s %s %s %s", a[0].length, a[1].length,
                 a[0].map!(u => u + 1).to!string.replaceAll(regex(`[\[\],]`), ""),
                 a[1].map!(u => u + 1).to!string.replaceAll(regex(`[\[\],]`), ""));
        stdout.flush;
        const res = readInt();
        if (res == -1) {
          import core.stdc.stdlib;
          exit(0);
        }
        chmax(ans, res);
      }
    }
    writefln("-1 %s", ans);
    stdout.flush;
  }
}


After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you).  You are given an array $$$h_1, h_2, \dots, h_n$$$, where $$$h_i$$$ is the height of the $$$i$$$-th mountain, and $$$k$$$ — the number of boulders you have.You will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is $$$h_i$$$):   if $$$h_i \ge h_{i + 1}$$$, the boulder will roll to the next mountain;  if $$$h_i < h_{i + 1}$$$, the boulder will stop rolling and increase the mountain height by $$$1$$$ ($$$h_i = h_i + 1$$$);  if the boulder reaches the last mountain it will fall to the waste collection system and disappear. You want to find the position of the $$$k$$$-th boulder or determine that it will fall into the waste collection system.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line in each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$; $$$1 \le k \le 10^9$$$) — the number of mountains and the number of boulders. The second line contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 100$$$) — the height of the mountains. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case, print $$$-1$$$ if the $$$k$$$-th boulder will fall into the collection system. Otherwise, print the position of the $$$k$$$-th boulder.

NoteLet's simulate the first case:  The first boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ it rolls to $$$i = 2$$$ and stops there because $$$h_2 < h_3$$$.  The new heights are $$$[4,2,2,3]$$$.  The second boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ the boulder rolls to $$$i = 2$$$; since $$$h_2 \ge h_3$$$ the boulder rolls to $$$i = 3$$$ and stops there because $$$h_3 < h_4$$$.  The new heights are $$$[4,2,3,3]$$$.  The third boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ it rolls to $$$i = 2$$$ and stops there because $$$h_2 < h_3$$$.  The new heights are $$$[4,3,3,3]$$$. The positions where each boulder stopped are the following: $$$[2,3,2]$$$.In the second case, all $$$7$$$ boulders will stop right at the first mountain rising its height from $$$1$$$ to $$$8$$$.The third case is similar to the first one but now you'll throw $$$5$$$ boulders. The first three will roll in the same way as in the first test case. After that, mountain heights will be equal to $$$[4, 3, 3, 3]$$$, that's why the other two boulders will fall into the collection system.In the fourth case, the first and only boulders will fall straight into the collection system.

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

		while (k > 0)
		{
			bool ok;
			foreach (i; 0..n-1)
			{
				if (h[i] < h[i+1])
				{
					--k;
					++h[i];
					ans[ti] = i+1;
					ok = true;
					break;
				}
			}
			if (!ok)
			{
				ans[ti] = -1;
				break;
			}
		}
	}

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

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

long solve (int n, int k, int [] h)
{
	while (true)
	{
		int i = 0;
		while (i < n - 1 && h[i + 1] <= h[i])
		{
			i += 1;
		}
		if (i == n - 1)
		{
			return -1;
		}
		h[i] += 1;
		k -= 1;
		if (k <= 0)
		{
			return i + 1;
		}
	}
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto h = readln.splitter.map !(to !(int)).array;
		writeln (solve (n, k, h));
	}
}

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, k; get(n, k);
        int[] hs; get(hs);

        int p;
        while (k--) {
            foreach (i, ref h; hs) {
                if (i == hs.length - 1) goto ng;
                if (h >= hs[i+1]) continue;
                p = i.to!int;
                ++h;
                break;
            }
        }
        writeln(p + 1);
        continue;

        ng:
        writeln(-1);
    }
}

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

		ans[ti] = -1;
		long[][] s;
		(){
		foreach (i; 0..n)
		{
			if (s.empty)
				s ~= [h[i], i];
			else if (h[i] <= s[$-1][0])
				s ~= [h[i], i];
			else
			{
				auto x = h[i];
				while (!s.empty)
				{
					if (s[$-1][0] > x)
					{
						s ~= [x, s[$-1][1]+1];
						break;
					}
					auto nd = s.back; s.popBack;
					auto y = nd[0];
					auto p = nd[1];
					k -= (x - y) * (i - p);
					debug writeln("i:", i, " p:", p, " x:", x, " y:", y, " k:", k);
					if (k <= 0)
					{
						debug writeln("i:", i, " p:", p, " k:", k);
						ans[ti] = p + 1 - k;
						return;
					}
				}
			}
		}}();
	}

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

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

long solve (int n, long k, int [] h)
{
	while (true)
	{
		if (isSorted !(q{a > b}) (h))
		{
			return -1;
		}
		int i = 1;
		while (h[i] <= h[i - 1])
                {
                	i += 1;
                }
                int j = i - 1;
                while (j > 0 && h[j - 1] == h[j])
                {
                	j -= 1;
                }
                int len = i - j;
		int cur = h[i] - h[j];
		k -= cur * 1L * (i - j);
		if (k <= 0)
		{
			return i - (k + cur * 1L * (i - j) - 1) % len;
		}
		h[j..i] += cur;
	}
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto h = readln.splitter.map !(to !(int)).array;
		writeln (solve (n, k, h));
	}
}


This is the easy version of this problem. The difference between easy and hard versions is only the constraints on $$$a_i$$$ and on $$$n$$$. You can make hacks only if both versions of the problem are solved.Burenka is the crown princess of Buryatia, and soon she will become the $$$n$$$-th queen of the country. There is an ancient tradition in Buryatia — before the coronation, the ruler must show their strength to the inhabitants. To determine the strength of the $$$n$$$-th ruler, the inhabitants of the country give them an array of $$$a$$$ of exactly $$$n$$$ numbers, after which the ruler must turn all the elements of the array into zeros in the shortest time. The ruler can do the following two-step operation any number of times:   select two indices $$$l$$$ and $$$r$$$, so that $$$1 \le l \le r \le n$$$ and a non-negative integer $$$x$$$, then  for all $$$l \leq i \leq r$$$ assign $$$a_i := a_i \oplus x$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. It takes $$$\left\lceil \frac{r-l+1}{2} \right\rceil$$$ seconds to do this operation, where $$$\lceil y \rceil$$$ denotes $$$y$$$ rounded up to the nearest integer. Help Burenka calculate how much time she will need.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 5000$$$) — elements of the array.  It is guaranteed that the sum of $$$n$$$ in all tests does not exceed $$$5000$$$.

For each test case, output a single number  — the minimum time that Burenka will need.

NoteIn the first test case, Burenka can choose segment $$$l = 1$$$, $$$r = 4$$$, and $$$x=5$$$. so it will fill the array with zeros in $$$2$$$ seconds.In the second test case, Burenka first selects segment $$$l = 1$$$, $$$r = 2$$$, and $$$x = 1$$$, after which $$$a = [0, 2, 2]$$$, and then the segment $$$l = 2$$$, $$$r = 3$$$, and $$$x=2$$$, which fills the array with zeros. In total, Burenka will spend $$$2$$$ seconds.

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

alias Tuple!(int,int) K;
enum int INF = 1<<29;

void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!int).array;

    /*
    int[K] cache;
    int f(int k, int s) {
        // turn [k, N) into 0
        if (k == N) return 0;
        auto key = K(k, s);
        if (key in cache) return cache[key];
        int ans = int.max;
        // don't use s
        ans = min(ans, f(k + 1, A[k]) + (A[k] > 0));
        // use s
        ans = min(ans, f(k + 1, A[k] ^ s) + ((A[k] ^ s) > 0));
        return cache[key] = ans;
    }
    */

    int L = 8191;
    auto f = new int[][](N + 1, L + 1);
    foreach (ref l; f) l[] = INF;
    f[0][0] = 0;
    for (int k = 0; k < N; k++) {
        for (int s = 0; s <= L; s++) {
            // use x = A[k]
            f[k + 1][A[k]] = min(f[k + 1][A[k]], f[k][s] + (A[k] > 0));
            // use x = A[k] ^ s
            int x = A[k] ^ s;
            f[k + 1][x] = min(f[k + 1][x], f[k][s] + (x > 0));
        }
    }
    writeln(f[N].reduce!min);
}

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

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

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

		bool [int] v;
		int cur = 0;
		v[cur] = true;
		int res = 0;
		foreach (ref x; a)
		{
			if ((x ^ cur) in v)
			{
				v = null;
				cur = 0;
				v[cur] = true;
				continue;
			}
			res += 1;
			cur ^= x;
			v[cur] = true;
		}
		writeln (res);
	}
}

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

alias Tuple!(int,int) K;
enum int INF = 1<<29;

void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!int).array;

    /*
    int[K] cache;
    int f(int k, int s) {
        // turn [k, N) into 0
        if (k == N) return 0;
        auto key = K(k, s);
        if (key in cache) return cache[key];
        int ans = int.max;
        // don't use s
        ans = min(ans, f(k + 1, A[k]) + (A[k] > 0));
        // use s
        ans = min(ans, f(k + 1, A[k] ^ s) + ((A[k] ^ s) > 0));
        return cache[key] = ans;
    }
    */

    int L = 8191;
    auto f = new int[][](N + 1, L + 1);
    foreach (ref l; f) l[] = INF;
    f[0][] = 0;
    for (int k = 0; k < N; k++) {
        for (int s = 0; s <= L; s++) {
            // use x = A[k]
            f[k + 1][A[k]] = min(f[k + 1][A[k]], f[k][s] + (A[k] > 0));
            // use x = A[k] ^ s
            int x = A[k] ^ s;
            f[k + 1][x] = min(f[k + 1][x], f[k][s] + (x > 0));
        }
    }
    writeln(f[N].reduce!min);
}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		int cur = 0;
		int res = 0;
		foreach (ref c; a)
		{
			if (c == 0)
			{
				cur = 0;
				continue;
			}
			res += 1;
			cur ^= c;
			if (cur == 0)
			{
				res -= 1;
			}
		}
		writeln (res);
	}
}


Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:  The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:   given a row index i, flip all the values in the i-th row in A;  given a column index i, flip all the values in the i-th column in A;  find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?

The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:    1 i — flip the values of the i-th row;  2 i — flip the values of the i-th column;  3 — output the unusual square of A.  Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.

/// https://codeforces.com/contest/405/problem/C
/// PS> dmd cf.d; if($?) {cat in.txt | .\cf.exe}
import std.stdio : stdin, write, writeln;

void main()
{
  int n, q, sum = 0;
  stdin.readf!"%d\n"(n);

  for (int i=0; i<n; i++)
    sum += stdin.readln()[i << 1];

  stdin.readf!"%d\n"(q);
  for (int i=0; i<q; i++) {
    int cmd = stdin.readln()[0];
    if (cmd == '3')
      write(sum & 1);
    else
      sum++;
  }
  writeln();
}

/// https://codeforces.com/contest/405/problem/C
/// PS> dmd cf.d; if($?) {cat in.txt | .\cf.exe}
import std.stdio : stdin, writeln;

void main()
{
  int n, q, sum = 0;
  stdin.readf!"%d\n"(n);

  for (int i=0; i<n<<1; i+=2)
    sum += stdin.readln()[i];
  stdin.readf!"%d\n"(q);

  char[] res; res.reserve(q);
  for (int i=0; i<q; i++)
    if (stdin.readln()[0] == '3')
      res ~= '0' + (sum & 1);
    else
      sum++;
  writeln(res);
}

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

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		bool s = false;
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				int t;
				scanf (" %d", &t);
				if (i == j)
				{
					if (t)
					{
						s ^= true;
					}
				}
			}
		}

		int q;
		scanf (" %d", &q);
		string res;
		foreach (k; 0..q)
		{
			int t, i;
			scanf (" %d", &t);
			switch (t)
			{
				case 1:
				case 2:
					scanf (" %d", &i);
					s ^= true;
					break;
				case 3:
					res ~= s ? '1' : '0';
					break;
				default:
					assert (false);
			}
		}
		writeln (res);
	}
}


In the country of Never, there are n cities and a well-developed road system. There is exactly one bidirectional road between every pair of cities, thus, there are as many as  roads! No two roads intersect, and no road passes through intermediate cities. The art of building tunnels and bridges has been mastered by Neverians.An independent committee has evaluated each road of Never with a positive integer called the perishability of the road. The lower the road's perishability is, the more pleasant it is to drive through this road.It's the year of transport in Never. It has been decided to build a museum of transport in one of the cities, and to set a single signpost directing to some city (not necessarily the one with the museum) in each of the other cities. The signposts must satisfy the following important condition: if any Neverian living in a city without the museum starts travelling from that city following the directions of the signposts, then this person will eventually arrive in the city with the museum.Neverians are incredibly positive-minded. If a Neverian travels by a route consisting of several roads, he considers the perishability of the route to be equal to the smallest perishability of all the roads in this route.The government of Never has not yet decided where to build the museum, so they consider all n possible options. The most important is the sum of perishabilities of the routes to the museum city from all the other cities of Never, if the travelers strictly follow the directions of the signposts. The government of Never cares about their citizens, so they want to set the signposts in a way which minimizes this sum. Help them determine the minimum possible sum for all n possible options of the city where the museum can be built.

The first line contains a single integer n (2 ≤ n ≤ 2000) — the number of cities in Never. The following n - 1 lines contain the description of the road network. The i-th of these lines contains n - i integers. The j-th integer in the i-th line denotes the perishability of the road between cities i and i + j. All road perishabilities are between 1 and 109, inclusive.

For each city in order from 1 to n, output the minimum possible sum of perishabilities of the routes to this city from all the other cities of Never if the signposts are set in a way which minimizes this sum.

NoteThe first example is explained by the picture below. From left to right, there is the initial road network and the optimal directions of the signposts in case the museum is built in city 1, 2 and 3, respectively. The museum city is represented by a blue circle, the directions of the signposts are represented by green arrows.For instance, if the museum is built in city 3, then the signpost in city 1 must be directed to city 3, while the signpost in city 2 must be directed to city 1. Then the route from city 1 to city 3 will have perishability 2, while the route from city 2 to city 3 will have perishability 1. The sum of perishabilities of these routes is 3.

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

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

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

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

enum INF = 10L^^18;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new long[][](N, N);
      foreach (u; 0 .. N) foreach (v; u + 1 .. N) {
        A[u][v] = A[v][u] = readLong();
      }

      long mn = INF;
      int sm = -1, tm = -1;
      foreach (u; 0 .. N) foreach (v; u + 1 .. N) {
        if (chmin(mn, A[u][v])) {
          sm = u;
          tm = v;
        }
      }

      auto dist = new long[][](N, 2);
      auto vis = new bool[][](N, 2);
      foreach (u; 0 .. N) foreach (k; 0 .. 2) {
        dist[u][k] = INF;
      }
      dist[sm][0] = dist[tm][0] = 0;
      for (; ; ) {
        int um = -1, km = 0;
        foreach (u; 0 .. N) foreach (k; 0 .. 2) {
          if (!vis[u][k]) {
            if (um == -1 || dist[um][km] > dist[u][k]) {
              um = u;
              km = k;
            }
          }
        }
        if (um == -1) {
          break;
        }
        vis[um][km] = true;
        foreach (v; 0 .. N) {
          if (um != v) {
            chmin(dist[v][0], dist[um][km] + (A[um][v] - mn) * (km + 1));
            chmin(dist[v][1], dist[um][km]);
          }
        }
      }
      debug {
        writeln("dist = ", dist);
      }

      foreach (u; 0 .. N) {
        writeln(dist[u][0] + (N - 1) * mn);
      }
    }
  } catch (EOFException e) {
  }
}


Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:  If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.  Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.

The first line of the input contains integers n, h and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ h ≤ 109) — the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1 ≤ ai ≤ h) — the heights of the pieces.

Print a single integer — the number of seconds required to smash all the potatoes following the process described in the problem statement.

NoteConsider the first sample.   First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.  Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.  Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.  Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.  During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2·5 = 10 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.

import std.stdio;

void main()
{
	int n, h, k;
	long result = 0;
	int[] heights;

	scanf("%d%d%d", &n, &h, &k);
	heights = new int[n];
	for (int i = 0; i < n; i++) {
		scanf("%d", &heights[i]);
	}

	int processed = 0;
	int loaded = 0;
	long loadedHeight = 0;
	while (processed < n) {

		while (loaded < n && loadedHeight + heights[loaded] <= h) {
			loadedHeight += heights[loaded];
			loaded++;
		}

		if (heights[processed] > k) {
			long iterations = (heights[processed] - 1) / k;
			loadedHeight -= iterations * k;
			result += iterations;
			heights[processed] -= iterations * k;
		}
		else {
			result++;

			int powerLeft = k;
			while (processed < loaded && powerLeft - heights[processed] >= 0) {
				powerLeft -= heights[processed];
				loadedHeight -= heights[processed];
				processed++;
			}

			if (processed < loaded && powerLeft > 0) {
				heights[processed] -= powerLeft;
				loadedHeight -= powerLeft;
			}
		}
	}

	writef("%d\n", result);
}


This is the easy version of the problem. The only difference is that in this version $$$n \leq 2000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2000$$$) — the number of potions.  The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ... ,$$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) which represent the change in health after drinking that potion.

Output a single integer, the maximum number of potions you can drink without your health becoming negative.

NoteFor the sample, you can drink $$$5$$$ potions by taking potions $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$ and $$$6$$$. It is not possible to drink all $$$6$$$ potions because your health will go negative at some point

import std.stdio;
import std.ascii;
import core.stdc.stdio;
import std.algorithm;

int main()
{
    int n = readInt!int;
    auto a = new long[](n);
    foreach(ref ai; a) ai = readInt!long;
    int pos = cast(int) a.count!(ai => ai >= 0);
    long[][] maxSum = new long[][](n + 1, n + 1);
    maxSum[0][0] = (a[0] < 0)? 0 : a[0];
    foreach(i; 1 .. n)
    {
        maxSum[i][0] = (a[i] < 0)? maxSum[i-1][0] : (maxSum[i-1][0] + a[i]);
    }
    foreach(p; 1 .. n)
    {
        foreach(i; 0 .. n)
        {
            if (a[i] < 0)
            {
                if (i == 0)
                {
                    maxSum[i][p] = -1;
                }
                else
                {
                    maxSum[i][p] = max(maxSum[i-1][p], maxSum[i-1][p-1] + a[i]);
                }
            }
            else
            {
                if (i == 0)
                {
                    maxSum[i][p] = -1;
                }
                else
                {
                    maxSum[i][p] = (maxSum[i-1][p] >= 0)? (maxSum[i-1][p] + a[i]) : maxSum[i-1][p];
                }
            }
        }
    }
    int p = 0;
    while (p + 1 < n && maxSum[n-1][p + 1] >= 0)
    {
        p++;
    }
    writeln(pos + p);
    return 0;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
    currChar = getchar();
}
char topChar()
{
    return cast(char) currChar;
}
void popChar()
{
    currChar = getchar();
}
auto readInt(T)()
{
    T num = 0;
    int sgn = 0;
    while (topChar.isWhite) popChar;
    while (topChar == '-' || topChar == '+') { sgn ^= (topChar == '-'); popChar; }
    while (topChar.isDigit) { num *= 10; num += (topChar - '0'); popChar; }
    if (sgn) return -num; return num;
}
string readString()
{
    string res = "";
    while (topChar.isWhite) popChar;
    while (!topChar.isWhite) { res ~= topChar; popChar; }
    return res;
}

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

int solve(int[] a)
{
    auto n = to!int(a.length);
    auto pdp = new long[n + 1];
    auto ndp = new long[n + 1];
    fill(pdp, -1);
    pdp[0] = 0;
    foreach (i; 0 .. n)
    {
        ndp[0] = pdp[0];
        foreach (j; 1 .. i + 2)
        {
            ndp[j] = pdp[j];
            if (pdp[j - 1] >= 0 && pdp[j - 1] + a[i] >= 0)
            {
                ndp[j] = max(ndp[j], pdp[j - 1] + a[i]);
            }
        }
        ndp[0 .. i + 2].copy(pdp);
    }
    auto res = 0;
    foreach_reverse (i; 0 .. n + 1) if (pdp[i] >= 0)
    {
        res = i;
        break;
    }
    return res;
}

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

import std.stdio;
import std.ascii;
import core.stdc.stdio;
import std.algorithm;

int main()
{
    int n = readInt!int;
    auto a = new int[](n);
    foreach(ref ai; a) ai = readInt!int;
    int pos = cast(int) a.count!(ai => ai >= 0);
    int[][] maxSum = new int[][](n + 1, n + 1);
    maxSum[0][0] = (a[0] < 0)? 0 : a[0];
    foreach(i; 1 .. n)
    {
        maxSum[i][0] = (a[i] < 0)? maxSum[i-1][0] : (maxSum[i-1][0] + a[i]);
    }
    foreach(p; 1 .. n)
    {
        foreach(i; 0 .. n)
        {
            if (a[i] < 0)
            {
                if (i == 0)
                {
                    maxSum[i][p] = a[i];
                }
                else
                {
                    maxSum[i][p] = max(maxSum[i-1][p], maxSum[i-1][p-1] + a[i]);
                }
            }
            else
            {
                if (i == 0)
                {
                    maxSum[i][p] = -1;
                }
                else
                {
                    maxSum[i][p] = (maxSum[i-1][p] >= 0)? (maxSum[i-1][p] + a[i]) : maxSum[i-1][p];
                }
            }
        }
    }
    int p = 0;
    while (p + 1 < n && maxSum[n-1][p + 1] >= 0)
    {
        p++;
    }
    writeln(pos + p);
    return 0;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
    currChar = getchar();
}
char topChar()
{
    return cast(char) currChar;
}
void popChar()
{
    currChar = getchar();
}
auto readInt(T)()
{
    T num = 0;
    int sgn = 0;
    while (topChar.isWhite) popChar;
    while (topChar == '-' || topChar == '+') { sgn ^= (topChar == '-'); popChar; }
    while (topChar.isDigit) { num *= 10; num += (topChar - '0'); popChar; }
    if (sgn) return -num; return num;
}
string readString()
{
    string res = "";
    while (topChar.isWhite) popChar;
    while (!topChar.isWhite) { res ~= topChar; popChar; }
    return res;
}


Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.

The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts.  Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.

Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.

NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.

import std.stdio;
import std.bigint;
import std.container;
import std.array;
import std.algorithm;
import std.conv;
import std.bitmanip;
import std.functional;
import std.math;
import std.numeric;
import std.string;
import std.range;
import std.uni;
import std.complex;
import std.typecons;
import core.stdc.stdio:freopen;
import core.bitop;
import std.regex;
import std.complex;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
immutable int mod=1000000007;
pure nothrow @safe X binpow(X,Y)(X base,Y exp)
if(!is(Y==float) && !is(Y==real) && !is(Y==double))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow @safe auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
if(!is(Y==float) && !is(Y==real) && !is(Y==double))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@safe @property void putarr(X)(X a,in char ch=' ')
{
	foreach(const ref i;a)write(i,ch);
}
@safe @property void putarr(X)(X[][] a)
{
	foreach(i;0..a.length)
	{
		foreach(j;0..a[i].length)write(a[i][j],' ');
		writeln;
	}
}
void getarr(X)(X a,in int n)
{
	foreach(ref i;a[0..n])input(&i);
}
auto arread(T)()
{
	return readln.split.map!(to!(T)).array;
}
bool input(T...)(T ptrs) if (ptrs.length > 0) {
	return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;
}
struct pair(X,Y)
{
	X fi;
	Y se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
		}
	this(this){fi=fi;se=se;}
	int opCmp(ref const pair!(X,Y) s_) const pure nothrow
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(X x_,Y y_) pure nothrow
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(X a_) pure nothrow @safe @property @nogc
{
	return a_*a_;
}
X cub(X)(X a_) pure nothrow @safe @property @nogc
{
	return a_*a_*a_;
}
alias pair!(int,int) pii;
alias pair!(long,long) pll;
void inf(in char* name) nothrow @nogc @system
{
	freopen(name,"r",core.stdc.stdio.stdin);
}
void ouf(in char* name) nothrow @nogc @system
{
	freopen(name,"w",core.stdc.stdio.stdout);
}
//split strip readln equalRange upperBound lowerBound string wstring
//dstring ulong wchar dchar array uint foreach_reverse find count false
//nextPermutation isSorted fill reverse swap size_t clear empty insert
//front back remove hypot sqrt round continue swapRanges minPos maxPos
//break goto switch boyerMooreFinder minElement maxElement heapify true
//static multiSort schwartzSort partialSort merge uniq joiner filter
//cumulativeFold fold each sort isAlpha isNumber isWhite isLower isUpper
//toLower toUpper mixin debug
pll[] a;
void main()
{
	int n,k,s,t;
	input(&n,&k,&s,&t);
	a.length=n;
	foreach(i;0..n)input(&a[i].se,&a[i].fi);
	sort(a);
	readln;
	auto g=sort(arread!long).array;
	g~=s;
	bool check(long v)
	{
		long pos=0,q=0;
		foreach(i;0..k+1)
		{
			if(g[i]-pos>v)return false;
			long r=g[i]-pos;
			q+=min(v-r,r)+2*(r-min(v-r,r));
			//debug writeln(q);
			pos=g[i];
		}
		return q<=t;
	}
	long l=1,r=int.max,m;
	while(l<r)
	{
		m=(l+r)/2;
		if(check(m))r=m;
		else l=m+1;
	}
	debug writeln(l);
	int p=0;
	while(p<n && a[p].fi<l)p++;
	if(p==n){writeln(-1);return;}
	long ans=int.max;
	foreach(i;p..n)ans=min(ans,a[i].se);
	writeln(ans);
}

import std.stdio;
import std.bigint;
import std.container;
import std.array;
import std.algorithm;
import std.conv;
import std.bitmanip;
import std.functional;
import std.math;
import std.numeric;
import std.string;
import std.range;
import std.uni;
import std.complex;
import std.typecons;
import core.stdc.stdio:freopen;
import core.bitop;
import std.regex;
import std.complex;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
immutable int mod=1000000007;
pure nothrow @safe X binpow(X,Y)(X base,Y exp)
if(!is(Y==float) && !is(Y==real) && !is(Y==double))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow @safe auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
if(!is(Y==float) && !is(Y==real) && !is(Y==double))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@safe @property void putarr(X)(X a,in char ch=' ')
{
	foreach(const ref i;a)write(i,ch);
}
@safe @property void putarr(X)(X[][] a)
{
	foreach(i;0..a.length)
	{
		foreach(j;0..a[i].length)write(a[i][j],' ');
		writeln;
	}
}
void getarr(X)(X a,in int n)
{
	foreach(ref i;a[0..n])input(&i);
}
auto arread(T)()
{
	return readln.split.map!(to!(T)).array;
}
bool input(T...)(T ptrs) if (ptrs.length > 0) {
	return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;
}
struct pair(X,Y)
{
	X fi;
	Y se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
		}
	this(this){fi=fi;se=se;}
	int opCmp(ref const pair!(X,Y) s_) const pure nothrow
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(X x_,Y y_) pure nothrow
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(X a_) pure nothrow @safe @property @nogc
{
	return a_*a_;
}
X cub(X)(X a_) pure nothrow @safe @property @nogc
{
	return a_*a_*a_;
}
alias pair!(int,int) pii;
alias pair!(long,long) pll;
void inf(in char* name) nothrow @nogc @system
{
	freopen(name,"r",core.stdc.stdio.stdin);
}
void ouf(in char* name) nothrow @nogc @system
{
	freopen(name,"w",core.stdc.stdio.stdout);
}
//split strip readln equalRange upperBound lowerBound string wstring
//dstring ulong wchar dchar array uint foreach_reverse find count false
//nextPermutation isSorted fill reverse swap size_t clear empty insert
//front back remove hypot sqrt round continue swapRanges minPos maxPos
//break goto switch boyerMooreFinder minElement maxElement heapify true
//static multiSort schwartzSort partialSort merge uniq joiner filter
//cumulativeFold fold each sort isAlpha isNumber isWhite isLower isUpper
//toLower toUpper mixin debug
pll[] a;
void main()
{
	int n,k,s,t;
	input(&n,&k,&s,&t);
	a.length=n;
	foreach(i;0..n)input(&a[i].se,&a[i].fi);
	sort(a);
	readln;
	auto g=sort(arread!long).array;
	g~=s;
	bool check(long v)
	{
		long pos=0,q=0;
		foreach(i;0..k+1)
		{
			if(g[i]-pos>v)return false;
			long r=g[i]-pos;
			q+=min(v-r,r)+2*(r-min(v-r,r));
			pos=g[i];
		}
		return q<=t;
	}
	long l=1,r=2*s,m;
	while(l<r)
	{
		m=(l+r)/2;
		if(check(m))r=m;
		else l=m+1;
	}
	debug writeln(l);
	int p=0;
	while(p<n && a[p].fi<l)p++;
	if(p==n){writeln(-1);return;}
	long ans=int.max;
	foreach(i;p..n)ans=min(ans,a[i].se);
	writeln(ans);
}