You are given $$$n$$$ arrays that can have different sizes. You also have a table with $$$w$$$ columns and $$$n$$$ rows. The $$$i$$$-th array is placed horizontally in the $$$i$$$-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table.You need to find the maximum sum of the integers in the $$$j$$$-th column for each $$$j$$$ from $$$1$$$ to $$$w$$$ independently.  Optimal placements for columns $$$1$$$, $$$2$$$ and $$$3$$$ are shown on the pictures from left to right. Note that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero.

The first line contains two integers $$$n$$$ ($$$1 \le n \le 10^{6}$$$) and $$$w$$$ ($$$1 \le w \le 10^{6}$$$) — the number of arrays and the width of the table. Each of the next $$$n$$$ lines consists of an integer $$$l_{i}$$$ ($$$1 \le l_{i} \le w$$$), the length of the $$$i$$$-th array, followed by $$$l_{i}$$$ integers $$$a_{i1}, a_{i2}, \ldots, a_{il_i}$$$ ($$$-10^{9} \le a_{ij} \le 10^{9}$$$) — the elements of the array. The total length of the arrays does no exceed $$$10^{6}$$$.

Print $$$w$$$ integers, the $$$i$$$-th of them should be the maximum sum for column $$$i$$$.

NoteIllustration for the first example is in the statement.

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

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

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

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

enum INF = 10L^^18;

int N, W;
int[] L;
long[][] A;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      W = readInt();
      L = new int[N];
      A = new long[][N];
      foreach (i; 0 .. N) {
        L[i] = readInt();
        A[i] = new long[L[i]];
        foreach (j; 0 .. L[i]) {
          A[i][j] = readLong();
        }
      }

      auto ans = new long[W + 1];

      alias Entry = Tuple!(long, "val", int, "key");
      auto que = new Entry[W];
      int qb, qe;

      foreach (i; 0 .. N) {
        if (W >= 2 * L[i]) {
          // always empty ok
          auto ls = A[i].dup, rs = A[i].dup;
          foreach (j; 0 .. L[i] - 1) {
            chmax(ls[j + 1], ls[j]);
          }
          foreach_reverse (j; 1 .. L[i]) {
            chmax(rs[j - 1], rs[j]);
          }
          foreach (x; 0 .. L[i]) {
            long mx = ls[x];
            chmax(mx, 0);
            debug {
              writefln("long ans %s %s: %s", i, x, mx);
            }
            ans[x] += mx;
            ans[x + 1] -= mx;
          }
          foreach (x; W - L[i] .. W) {
            long mx = rs[x - (W - L[i])];
            chmax(mx, 0);
            debug {
              writefln("long ans %s %s: %s", i, x, mx);
            }
            ans[x] += mx;
            ans[x + 1] -= mx;
          }
          // [L[i], W - L[i])
          {
            long mx = rs[0];
            chmax(mx, 0);
            debug {
              writefln("long ans %s [%s, %s): %s", i, L[i], W - L[i], mx);
            }
            ans[L[i]] += mx;
            ans[W - L[i]] -= mx;
          }
        } else {
          qb = qe = 0;
          /*
            index j at position x
            <=> j <= x && L[i] - j <= W - x
            <=> x - (W - L[i]) <= j <= x
          */
          foreach (x; 0 .. W) {
            if (x < L[i]) {
              // push x
              for (; qe - qb >= 1 && que[qe - 1].val <= A[i][x]; --qe) {}
              que[qe++] = Entry(A[i][x], x);
            }
            for (; qe - qb >= 1 && !(x - (W - L[i]) <= que[qb].key); ++qb) {}
            assert(qe - qb >= 1);
            long mx = que[qb].val;
            if (x >= L[i] || W - 1 - x >= L[i]) {
              chmax(mx, 0);
            }
            debug {
              writefln("short ans %s %s: %s", i, x, mx);
            }
            ans[x] += mx;
            ans[x + 1] -= mx;
          }
        }
      }

      foreach (x; 0 .. W) {
        ans[x + 1] += ans[x];
      }
      assert(ans[W] == 0);

      foreach (x; 0 .. W) {
        if (x > 0) {
          write(" ");
        }
        write(ans[x]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum INF = 10L^^18;

int N, W;
int[] L;
long[][] A;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      W = readInt();
      L = new int[N];
      A = new long[][N];
      foreach (i; 0 .. N) {
        L[i] = readInt();
        A[i] = new long[L[i]];
        foreach (j; 0 .. L[i]) {
          A[i][j] = readLong();
        }
      }

      auto ans = new long[W + 1];

      alias Entry = Tuple!(long, "val", int, "key");
      auto que = new Entry[W];
      int qb, qe;

      foreach (i; 0 .. N) {
        if (W >= 2 * L[i]) {
          auto ls = A[i].dup, rs = A[i].dup;
          foreach (j; 0 .. L[i] - 1) {
            chmax(ls[j + 1], ls[j]);
          }
          foreach_reverse (j; 1 .. L[i]) {
            chmax(rs[j - 1], rs[j]);
          }
          foreach (x; 0 .. L[i]) {
            long mx = ls[x];
            if (x >= L[i] || W - 1 - x >= L[i]) {
              chmax(mx, 0);
            }
            debug {
              writefln("long ans %s %s: %s", i, x, mx);
            }
            ans[x] += mx;
            ans[x + 1] -= mx;
          }
          foreach (x; W - L[i] .. W) {
            long mx = rs[W - 1 - x];
            if (x >= L[i] || W - 1 - x >= L[i]) {
              chmax(mx, 0);
            }
            debug {
              writefln("long ans %s %s: %s", i, x, mx);
            }
            ans[x] += mx;
            ans[x + 1] -= mx;
          }
          /*
            [L[i], W - L[i])
            empty ok
          */
          {
            long mx = rs[0];
            chmax(mx, 0);
            debug {
              writefln("long ans %s [%s, %s): %s", i, L[i], W - L[i], mx);
            }
            ans[L[i]] += mx;
            ans[W - L[i]] -= mx;
          }
        } else {
          qb = qe = 0;
          /*
            index j at position x
            <=> j <= x && L[i] - j <= W - x
            <=> x - (W - L[i]) <= j <= x
          */
          foreach (x; 0 .. W) {
            if (x < L[i]) {
              // push x
              for (; qe - qb >= 1 && que[qe - 1].val <= A[i][x]; --qe) {}
              que[qe++] = Entry(A[i][x], x);
            }
            for (; qe - qb >= 1 && !(x - (W - L[i]) <= que[qb].key); ++qb) {}
            assert(qe - qb >= 1);
            long mx = que[qb].val;
            if (x >= L[i] || W - 1 - x >= L[i]) {
              chmax(mx, 0);
            }
            debug {
              writefln("short ans %s %s: %s", i, x, mx);
            }
            ans[x] += mx;
            ans[x + 1] -= mx;
          }
        }
      }

      foreach (x; 0 .. W) {
        ans[x + 1] += ans[x];
      }
      assert(ans[W] == 0);

      foreach (x; 0 .. W) {
        if (x > 0) {
          write(" ");
        }
        write(ans[x]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum INF = 10L^^18;

int N, W;
int[] L;
long[][] A;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      W = readInt();
      L = new int[N];
      A = new long[][N];
      foreach (i; 0 .. N) {
        L[i] = readInt();
        A[i] = new long[L[i]];
        foreach (j; 0 .. L[i]) {
          A[i][j] = readLong();
        }
      }

      auto ans = new long[W + 1];

      alias Entry = Tuple!(long, "val", int, "key");
      auto que = new Entry[W];
      int qb, qe;

      foreach (i; 0 .. N) {
        if (W >= 2 * L[i]) {
          // always empty ok
          auto ls = A[i].dup, rs = A[i].dup;
          foreach (j; 0 .. L[i] - 1) {
            chmax(ls[j + 1], ls[j]);
          }
          foreach_reverse (j; 1 .. L[i]) {
            chmax(rs[j - 1], rs[j]);
          }
          foreach (x; 0 .. L[i]) {
            long mx = ls[x];
            chmax(mx, 0);
            debug {
              writefln("long ans %s %s: %s", i, x, mx);
            }
            ans[x] += mx;
            ans[x + 1] -= mx;
          }
          foreach (x; W - L[i] .. W) {
            long mx = rs[W - 1 - x];
            chmax(mx, 0);
            debug {
              writefln("long ans %s %s: %s", i, x, mx);
            }
            ans[x] += mx;
            ans[x + 1] -= mx;
          }
          // [L[i], W - L[i])
          {
            long mx = rs[0];
            chmax(mx, 0);
            debug {
              writefln("long ans %s [%s, %s): %s", i, L[i], W - L[i], mx);
            }
            ans[L[i]] += mx;
            ans[W - L[i]] -= mx;
          }
        } else {
          qb = qe = 0;
          /*
            index j at position x
            <=> j <= x && L[i] - j <= W - x
            <=> x - (W - L[i]) <= j <= x
          */
          foreach (x; 0 .. W) {
            if (x < L[i]) {
              // push x
              for (; qe - qb >= 1 && que[qe - 1].val <= A[i][x]; --qe) {}
              que[qe++] = Entry(A[i][x], x);
            }
            for (; qe - qb >= 1 && !(x - (W - L[i]) <= que[qb].key); ++qb) {}
            assert(qe - qb >= 1);
            long mx = que[qb].val;
            if (x >= L[i] || W - 1 - x >= L[i]) {
              chmax(mx, 0);
            }
            debug {
              writefln("short ans %s %s: %s", i, x, mx);
            }
            ans[x] += mx;
            ans[x + 1] -= mx;
          }
        }
      }

      foreach (x; 0 .. W) {
        ans[x + 1] += ans[x];
      }
      assert(ans[W] == 0);

      foreach (x; 0 .. W) {
        if (x > 0) {
          write(" ");
        }
        write(ans[x]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


Let $$$f(i)$$$ denote the minimum positive integer $$$x$$$ such that $$$x$$$ is not a divisor of $$$i$$$.Compute $$$\sum_{i=1}^n f(i)$$$ modulo $$$10^9+7$$$. In other words, compute $$$f(1)+f(2)+\dots+f(n)$$$ modulo $$$10^9+7$$$.

The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 10^4$$$), the number of test cases. Then $$$t$$$ cases follow. The only line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq 10^{16}$$$).

For each test case, output a single integer $$$ans$$$, where $$$ans=\sum_{i=1}^n f(i)$$$ modulo $$$10^9+7$$$.

NoteIn the fourth test case $$$n=4$$$, so $$$ans=f(1)+f(2)+f(3)+f(4)$$$.  $$$1$$$ is a divisor of $$$1$$$ but $$$2$$$ isn't, so $$$2$$$ is the minimum positive integer that isn't a divisor of $$$1$$$. Thus, $$$f(1)=2$$$.  $$$1$$$ and $$$2$$$ are divisors of $$$2$$$ but $$$3$$$ isn't, so $$$3$$$ is the minimum positive integer that isn't a divisor of $$$2$$$. Thus, $$$f(2)=3$$$.  $$$1$$$ is a divisor of $$$3$$$ but $$$2$$$ isn't, so $$$2$$$ is the minimum positive integer that isn't a divisor of $$$3$$$. Thus, $$$f(3)=2$$$.  $$$1$$$ and $$$2$$$ are divisors of $$$4$$$ but $$$3$$$ isn't, so $$$3$$$ is the minimum positive integer that isn't a divisor of $$$4$$$. Thus, $$$f(4)=3$$$. Therefore, $$$ans=f(1)+f(2)+f(3)+f(4)=2+3+2+3=10$$$.

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

string FMT_F = "%.10f";

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

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

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

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

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

		long x = 1;
		long last = n;
		foreach (i; 2..n+10)
		{
			x = lcm(x, i);
			auto tmp = last - n / x;
			tmp.modm(i);
			ans[ti].moda(tmp);
			last = n / x;
			if (last == 0) break;
		}
	}

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

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  immutable(long) mod = 10 ^^ 9 + 7;
  while(tests--) {
    long n; readf!"%s\n"(n);
    long ans, p = 2;
    foreach(d; [2, 3, 2, 5, 1, 7, 2, 3, 1, 11, 1, 13, 1, 1, 2, 17, 1, 19, 1, 1, 1, 23, 1, 5, 1, 3, 1, 29, 1, 31, 2, 1, 1, 1, 1, 37, 1, 1, 1, 41, 1, 43, 1, 1, 1, 47, 1, 7, 1, 1, 1, 53, 1, 1, 1, 1, 1, 59, 1, 61, 1, 1, 2, 1, 1, 67, 1, 1, 1, 71, 1, 73, 1, 1, 1, 77, 1, 79, 1]) {
      long q = n / d;
      ans = (ans + (n - q) * p) % mod;
      n = q;
      ++p;
    }
    ans.writeln;
  }

} // main


For a vector $$$\vec{v} = (x, y)$$$, define $$$|v| = \sqrt{x^2 + y^2}$$$.Allen had a bit too much to drink at the bar, which is at the origin. There are $$$n$$$ vectors $$$\vec{v_1}, \vec{v_2}, \cdots, \vec{v_n}$$$. Allen will make $$$n$$$ moves. As Allen's sense of direction is impaired, during the $$$i$$$-th move he will either move in the direction $$$\vec{v_i}$$$ or $$$-\vec{v_i}$$$. In other words, if his position is currently $$$p = (x, y)$$$, he will either move to $$$p + \vec{v_i}$$$ or $$$p - \vec{v_i}$$$.Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position $$$p$$$ satisfies $$$|p| \le 1.5 \cdot 10^6$$$ so that he can stay safe.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of moves. Each of the following lines contains two space-separated integers $$$x_i$$$ and $$$y_i$$$, meaning that $$$\vec{v_i} = (x_i, y_i)$$$. We have that $$$|v_i| \le 10^6$$$ for all $$$i$$$.

Output a single line containing $$$n$$$ integers $$$c_1, c_2, \cdots, c_n$$$, each of which is either $$$1$$$ or $$$-1$$$. Your solution is correct if the value of $$$p = \sum_{i = 1}^n c_i \vec{v_i}$$$, satisfies $$$|p| \le 1.5 \cdot 10^6$$$. It can be shown that a solution always exists under the given constraints.

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

immutable double maxR = 1_500_000.0 - 1.0;

alias Vector = Tuple !(double, q{x}, double, q{y});

bool less (int a, int b)
{
	auto at = atan2 (v[a].y, v[a].x);
	auto bt = atan2 (v[b].y, v[b].x);
	if (at != bt)
	{
		return at < bt;
	}
	return a < b;
}

__gshared Vector [] v;
__gshared Vector total;
__gshared int [] b;
__gshared RedBlackTree !(int, less) t;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		v = new Vector [n + 1];
		foreach (ref c; v[0..n])
		{
			int x, y;
			readf (" %s %s", &x, &y);
			c = Vector (x, y);
		}

		b = new int [n];
		b[] = 1;
		t = redBlackTree !(less, int) ();
		v[n] = Vector (0, 0);
		foreach (i; 0..n)
		{
			if (uniform (0, 2))
			{
				b[i] *= -1;
				v[i].x *= -1;
				v[i].y *= -1;
			}
			v[n].x += v[i].x;
			v[n].y += v[i].y;
			t.insert (i);
		}

		bool relax (int cur)
		{
			auto next = v[n];
			next.x -= 2 * v[cur].x;
			next.y -= 2 * v[cur].y;
			debug {writefln ("relax %s %.0f %.0f %.0f %.0f " ~
			    "%.10f %.10f", cur, v[cur].x, v[cur].y,
			    next.x, next.y, hypot (next.y, next.x),
			    hypot (v[n].y, v[n].x)); stdout.flush;}
			if (hypot (next.y, next.x) < hypot (v[n].y, v[n].x))
			{
				t.removeKey (cur);
				b[cur] *= -1;
				v[cur].x *= -1;
				v[cur].y *= -1;
				t.insert (cur);
				v[n] = next;
				return true;
			}
			return false;
		}

		while (hypot (v[n].y, v[n].x) > maxR)
		{
			debug {writefln ("%.0f %.0f %.10f", v[n].x, v[n].y,
			    hypot (v[n].y, v[n].x)); stdout.flush;}

			auto lo = t.lowerBound (n);
			debug {writeln (lo.empty);}
			if (relax (!lo.empty ? lo.back : t.back))
			{
				continue;
			}

			auto hi = t.upperBound (n);
			debug {writeln (hi.empty);}
			if (relax (!hi.empty ? hi.front : t.front))
			{
				continue;
			}

			auto me = t.equalRange (n);
			debug {writeln (me.empty);}
			if (relax (!me.empty ? me.front : t.back))
			{
				continue;
			}

			assert (false);
		}

		debug {writefln ("%.0f %.0f %.10f", v[n].x, v[n].y,
		    hypot (v[n].y, v[n].x)); stdout.flush;}
		writefln ("%(%s %)", b);
	}
}

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

alias Pt = Tuple!(long, "x", long, "y", int, "id");

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto V = new Pt[N];
      foreach (i; 0 .. N) {
        V[i].x = readLong();
        V[i].y = readLong();
        V[i].id = i;
      }
      V.sort!((a, b) => (a.x^^2 + a.y^^2 < b.x^^2 + b.y^^2));
      debug {
        writeln("V = ", V);
      }

      auto ans = new int[N];

      ans[V[0].id] = +1;
      long x = V[0].x, y = V[0].y;
      if (N % 2 == 0) {
        foreach (s; [+1, -1]) {
          const xx = x + s * V[1].x;
          const yy = y + s * V[1].y;
          if (xx^^2 + yy^^2 <= 2 * (V[1].x^^2 + V[1].y^^2)) {
            debug {
              writeln(s, " ", V[1]);
              writeln(xx, " ", yy);
            }
            ans[V[1].id] = s;
            x = xx;
            y = yy;
            goto found2;
          }
        }
        assert(false);
       found2:
      }
      for (int i = (N % 2 == 0) ? 2 : 1; i < N; i += 2) {
        foreach (s; [+1, -1]) foreach (t; [+1, -1]) {
          const xx = x + s * V[i].x + t * V[i + 1].x;
          const yy = y + s * V[i].y + t * V[i + 1].y;
          if (xx^^2 + yy^^2 <= 2 * (V[i + 1].x^^2 + V[i + 1].y^^2)) {
            debug {
              writeln(s, " ", V[i], ", ", t, " ", V[i + 1]);
              writeln(xx, " ", yy);
            }
            ans[V[i].id] = s;
            ans[V[i + 1].id] = t;
            x = xx;
            y = yy;
            goto found;
          }
        }
        assert(false);
       found:
      }

      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


You and your friend are participating in a TV show "Run For Your Prize".At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.What is the minimum number of seconds it will take to pick up all the prizes?

The first line contains one integer n (1 ≤ n ≤ 105) — the number of prizes. The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 106 - 1) — the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.

Print one integer — the minimum number of seconds it will take to collect all prizes.

NoteIn the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5.

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

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

  auto t1=new int[](n), t2=new int[](n);
  foreach(i, a; as)
    t1[i]=a-1, t2[i]=1_000_000-a;
  auto mn=1_000_000_000;
  for(int i=0; i<=n; i++){
    if(i==0) mn=min(mn, t2[i]);
    else if(i==n) mn=min(mn, t1[n-1]);
    else mn=min(mn, max(t1[i-1], t2[i]));
  }

  writeln(mn);
}

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


Tsumugi brought $$$n$$$ delicious sweets to the Light Music Club. They are numbered from $$$1$$$ to $$$n$$$, where the $$$i$$$-th sweet has a sugar concentration described by an integer $$$a_i$$$.Yui loves sweets, but she can eat at most $$$m$$$ sweets each day for health reasons.Days are $$$1$$$-indexed (numbered $$$1, 2, 3, \ldots$$$). Eating the sweet $$$i$$$ at the $$$d$$$-th day will cause a sugar penalty of $$$(d \cdot a_i)$$$, as sweets become more sugary with time. A sweet can be eaten at most once.The total sugar penalty will be the sum of the individual penalties of each sweet eaten.Suppose that Yui chooses exactly $$$k$$$ sweets, and eats them in any order she wants. What is the minimum total sugar penalty she can get?Since Yui is an undecided girl, she wants you to answer this question for every value of $$$k$$$ between $$$1$$$ and $$$n$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 200\ 000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 200\ 000$$$).

You have to output $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ on a single line, separed by spaces, where $$$x_k$$$ is the minimum total sugar penalty Yui can get if she eats exactly $$$k$$$ sweets.

NoteLet's analyze the answer for $$$k = 5$$$ in the first example. Here is one of the possible ways to eat $$$5$$$ sweets that minimize total sugar penalty:  Day $$$1$$$: sweets $$$1$$$ and $$$4$$$  Day $$$2$$$: sweets $$$5$$$ and $$$3$$$  Day $$$3$$$ : sweet $$$6$$$ Total penalty is $$$1 \cdot a_1 + 1 \cdot a_4 + 2 \cdot a_5 + 2 \cdot a_3 + 3 \cdot a_6 = 6 + 4 + 8 + 6 + 6 = 30$$$. We can prove that it's the minimum total sugar penalty Yui can achieve if she eats $$$5$$$ sweets, hence $$$x_5 = 30$$$.

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

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

    long ans = 0;

    foreach (i; 0..N) {
        ans += B[i % M] + A[i];
        B[i % M] += A[i];
        write(ans, " ");
    }

    writeln;
}

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

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

void solve(){
	int n = rint, m = rint;
	long[] as = rlong(n);
	as.sort();

	long[] sums = new long[](n);
	long an;
	long[] ans;
	foreach(k; 0 .. n){
		sums[k % m] += as[k];
		an += sums[k % m];
		ans ~= an;
	}

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

/*
(k - 1 => k)

some sweets move from day d to day d + 1.
they are that of ( ~= k % m)-th order.

us[k % m] = sum of ...

*/

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

string FMT_F = "%.10f";

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

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

//long mod = 10^^9 + 7;
long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

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

	auto b = new long[](n+m);
	foreach (i; 0..n)
	{
		b[m+i] = b[i] + a[i];
	}
	auto ans = new long[](n+1);
	foreach (i; 0..n)
	{
		ans[i+1] = ans[i] + a[i];
		ans[i+1] += b[i];
	}

	ans[1..$].map!(to!string).join(" ").writeln;
	stdout.flush();
	debug readln();
}


Polycarp has an integer $$$n$$$ that doesn't contain the digit 0. He can do the following operation with his number several (possibly zero) times: Reverse the prefix of length $$$l$$$ (in other words, $$$l$$$ leftmost digits) of $$$n$$$. So, the leftmost digit is swapped with the $$$l$$$-th digit from the left, the second digit from the left swapped with ($$$l-1$$$)-th left, etc. For example, if $$$n=123456789$$$ and $$$l=5$$$, then the new value of $$$n$$$ will be $$$543216789$$$.Note that for different operations, the values of $$$l$$$ can be different. The number $$$l$$$ can be equal to the length of the number $$$n$$$ — in this case, the whole number $$$n$$$ is reversed.Polycarp loves even numbers. Therefore, he wants to make his number even. At the same time, Polycarp is very impatient. He wants to do as few operations as possible.Help Polycarp. Determine the minimum number of operations he needs to perform with the number $$$n$$$ to make it even or determine that this is impossible.You need to answer $$$t$$$ independent test cases.

The first line contains the number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains one integer $$$n$$$ ($$$1 \le n < 10^9$$$). It is guaranteed that the given number doesn't contain the digit 0.

Print $$$t$$$ lines. On each line print one integer — the answer to the corresponding test case. If it is impossible to make an even number, print -1.

NoteIn the first test case, $$$n=3876$$$, which is already an even number. Polycarp doesn't need to do anything, so the answer is $$$0$$$.In the second test case, $$$n=387$$$. Polycarp needs to do $$$2$$$ operations: Select $$$l=2$$$ and reverse the prefix $$$\underline{38}7$$$. The number $$$n$$$ becomes $$$837$$$. This number is odd. Select $$$l=3$$$ and reverse the prefix $$$\underline{837}$$$. The number $$$n$$$ becomes $$$738$$$. This number is even.It can be shown that $$$2$$$ is the minimum possible number of operations that Polycarp needs to do with his number to make it even.In the third test case, $$$n=4489$$$. Polycarp can reverse the whole number (choose a prefix of length $$$l=4$$$). It will become $$$9844$$$ and this is an even number.In the fourth test case, $$$n=3$$$. No matter how hard Polycarp tried, he would not be able to make an even number.

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

void main()
{
  long t;
  readf!" %d "(t);
  foreach (casenum ; 1 .. t + 1) {
    auto s = readln.strip;
    if ((s[$ - 1] - '0') % 2 == 0)
      writeln(0);
    else if ((s[0] - '0') % 2 == 0)
      writeln(1);
    else {
      bool good = false;
      foreach (ch ; s) {
        if ((ch - '0') % 2 == 0) {
          good = true;
          break;
        }
      }
      writeln(good ? 2 : -1);
    }
  }
}

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 s = readln.strip;
		writeln (s.back % 2 == 0 ? 0 :
		    s.front % 2 == 0 ? 1 :
		    s.canFind !(x => x % 2 == 0) ? 2 :
		    -1);
	}
}


You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You should write a program which finds sum of the best subsequence.

The first line contains integer number n (1 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≤ ai ≤ 104). The sequence contains at least one subsequence with odd sum.

NoteIn the first example sum of the second and the fourth elements is 3.

import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,
	core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
//import core.stdc.stdio;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias long lint;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
immutable int mod=1000000007;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
int sz(T)(T a) if(hasLength!T)
{
	return cast(int)a.length;
}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter
//------------------------------------------program beginning--------------------------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n;
	//writeln("hello");
loop:while(read(n))
	{
		auto a=arread!int;
		sort(a);
		int pos=sz(a)-1;
		long s=0,m=0;
		while(pos>=0 && a[pos]>0)
		{
			s+=a[pos];
			if(a[pos]&1)m=a[pos];
			pos--;
		}
		while(pos>=0 && a[pos]%2==0)pos--;
		if(pos<0)
		{
			if(s&1)writeln(s);
			else writeln(s-m);
		}
		else
		{
			if(s&1)writeln(s);
			else writeln(max(s-(m==0?int.max:m),s+a[pos]));
		}
	}
	//debug system("pause");
}

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

immutable int inf = 10^^9 + 7;
immutable int c = 10^^4;

int n;
int[] a;

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

    int e_max = 0, o_max = -inf;

    foreach (i ; 0 .. n) {
        int t_emax = e_max, t_omax = o_max;

        if ((a[i] + c) % 2 == 0) {
            e_max = max(e_max, e_max + a[i]);
            o_max = max(o_max, o_max + a[i]);
        }
        else {
            e_max = max(e_max, t_omax + a[i]);
            o_max = max(o_max, t_emax + a[i]);
        }

        debug {
            writeln("e_max:", e_max);
            writeln("o_max:", o_max);
        }
    }

    writeln(o_max);
}

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

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

immutable int inf = 10^^9 + 7;
int n;
int[] a;

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

    auto dp = new int[][](n + 1, 2);
    dp[0][0] = 0, dp[0][1] = -inf;

    foreach (i ; 0 .. n) {
        if (a[i] & 1) {
            dp[i + 1][0] = max(dp[i][0], dp[i][1] + a[i]);
            dp[i + 1][1] = max(dp[i][1], dp[i][0] + a[i]);
        }
        else {
            dp[i + 1][0] = max(dp[i][0], dp[i][0] + a[i]);
            dp[i + 1][1] = max(dp[i][1], dp[i][1] + a[i]);
        }
    }

    writeln(dp[n][1]);
}

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

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

immutable int inf = 10^^9 + 7;
immutable int c = 10^^4;

int n;
int[] a;

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

    int e_max = 0, o_max = -inf;

    foreach (i ; 0 .. n) {
        if ((a[i] + c) % 2 == 0) {
            e_max = max(e_max, e_max + a[i]);
            o_max = max(o_max, o_max + a[i]);
        }
        else {
            e_max = max(e_max, o_max + a[i]);
            o_max = max(o_max, e_max + a[i]);
        }

        debug {
            writeln("e_max:", e_max);
            writeln("o_max:", o_max);
        }
    }

    writeln(o_max);
}

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


A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then:   first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group.  friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.

For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.

NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.

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

void solve() {
    int N; readf("%d\n", &N);
    auto X = readln.chomp.split(" ").map!(to!int).array;
    auto Y = readln.chomp.split(" ").map!(to!int).array;
    auto Z = iota(0, N).map!((i) => Y[i] - X[i]).array;
    Z = Z.sort.reverse.array;
    int r = N - 1;
    int ans = 0;
    for (int l = 0; l < N; l++) {
        while (l < r && Z[l] + Z[r] < 0) {
            r--;
        }
        if (l < r) {
            ans++;
            r--;
        }
    }
    ans.writeln;
}

void main() {
    int T; readf("%d\n", &T);
    foreach (t; 0 .. T) {
        solve();
    }
}


The title is a reference to the very first Educational Round from our writers team, Educational Round 18.There is a bag, containing colored balls. There are $$$n$$$ different colors of balls, numbered from $$$1$$$ to $$$n$$$. There are $$$\mathit{cnt}_i$$$ balls of color $$$i$$$ in the bag. The total amount of balls in the bag is odd (e. g. $$$\mathit{cnt}_1 + \mathit{cnt}_2 + \dots + \mathit{cnt}_n$$$ is odd).In one move, you can choose two balls with different colors and take them out of the bag.At some point, all the remaining balls in the bag will have the same color. That's when you can't make moves anymore.Find any possible color of the remaining balls.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 20$$$) — the number of colors. The second line contains $$$n$$$ integers $$$\mathit{cnt}_1, \mathit{cnt}_2, \dots, \mathit{cnt}_n$$$ ($$$1 \le \mathit{cnt}_i \le 100$$$) — the amount of balls of each color in the bag. The total amount of balls in the bag is odd (e. g. $$$\mathit{cnt}_1 + \mathit{cnt}_2 + \dots + \mathit{cnt}_n$$$ is odd).

For each testcase, print a single integer — any possible color of the remaining balls, after you made some moves and can't make moves anymore.

NoteIn the first testcase, your first and only move can be one of the following:   take balls with colors $$$1$$$ and $$$2$$$;  take balls with colors $$$1$$$ and $$$3$$$;  take balls with colors $$$2$$$ and $$$3$$$. After the move, exactly one ball will remain. Its color can be $$$3, 2$$$ or $$$1$$$ depending on the move.In the second testcase, you can't make moves at all — there is only color of balls already. This color is $$$1$$$.In the third testcase, you can keep removing one ball of color $$$1$$$ and one ball of color $$$2$$$ until there are no more balls of color $$$1$$$. At the end, three balls of color $$$2$$$ remain.

import std;

void main()
{
    int w;
    scanf("%d\n", &w);
    foreach(_; 0..w)
    {
        int n;
        scanf("%d\n", &n);
        auto a = readln.split.to!(int[]);
        writeln(maxIndex(a) + 1);
    }
}


Sloth is bad, mkay? So we decided to prepare a problem to punish lazy guys.You are given a tree, you should count the number of ways to remove an edge from it and then add an edge to it such that the final graph is a tree and has a perfect matching. Two ways of this operation are considered different if their removed edges or their added edges aren't the same. The removed edge and the added edge can be equal.A perfect matching is a subset of edges such that each vertex is an endpoint of exactly one of these edges.

The first line contains n (2 ≤ n ≤ 5·105) — the number of vertices. Each of the next n - 1 lines contains two integers a and b (1 ≤ a, b ≤ n) — the endpoints of one edge. It's guaranteed that the graph is a tree.

Output a single integer — the answer to the problem.

NoteIn first sample, there are 8 ways:  edge between 2 and 3 turns to edge between 1 and 3,  edge between 2 and 3 turns to edge between 1 and 4,  edge between 2 and 3 turns to edge between 2 and 3,  edge between 2 and 3 turns to edge between 2 and 4,  edge between 1 and 2 turns to edge between 1 and 2,  edge between 1 and 2 turns to edge between 1 and 4,  edge between 3 and 4 turns to edge between 1 and 4,  edge between 3 and 4 turns to edge between 3 and 4.

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 Info {
  int sz;
  int[2][2] a;
  Info opBinary(string op)(Info f) const if (op == "*") {
    Info g;
    g.sz = sz + f.sz;
    foreach (x; 0 .. 2) foreach (y; 0 .. 2) {
      foreach (xx; 0 .. 2 - x) foreach (yy; 0 .. 2 - y) {
        g.a[x + xx][y + yy] += a[x][y] * f.a[xx][yy];
      }
    }
    return g;
  }
  Info up() const {
    Info f;
    f.sz = 1 + sz;
    f.a[0][1] += a[0][0];
    f.a[1][0] += a[0][0];
    f.a[1][1] += a[0][1];
    f.a[0][0] += a[1][0];
    f.a[0][1] += a[1][1];
    return f;
  }
}
Info identity() {
  Info f;
  f.a[0][0] = 1;
  return f;
}

int N;
int[] A, B;

int[][] G;
int[] par;
Info[] dp, DP;

void dfs(int u, int p) {
  par[u] = p;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
    }
  }
  Info f = identity;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      f = f * dp[v];
    }
  }
  dp[u] = f.up;
}

Info[] ls, rs;
void DFS(int u, int p) {
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
    }
  }
  const len = cast(int)(vs.length);
  ls[0] = rs[len] = identity;
  if (p != -1) {
    rs[len] = DP[u];
  }
  foreach (j; 0 .. len) {
    ls[j + 1] = ls[j] * dp[vs[j]];
  }
  foreach_reverse (j; 0 .. len) {
    rs[j] = dp[vs[j]] * rs[j + 1];
  }
  foreach (j; 0 .. len) {
    DP[vs[j]] = (ls[j] * rs[j + 1]).up;
  }
  foreach (j; 0 .. len) {
    DFS(vs[j], u);
  }
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }

      par = new int[N];
      dp = new Info[N];
      DP = new Info[N];
      const rt = 0;
      ls = new Info[N + 1];
      rs = new Info[N + 1];
      dfs(rt, -1);
      DFS(rt, -1);
      debug {
        writeln("rt = ", rt);
        writeln("dp = ", dp);
        writeln("DP = ", DP);
      }
      long ans;
      foreach (u; 0 .. N) {
        if (u != rt) {
          if (dp[u].a[0][0] && DP[u].a[0][0]) {
            ans += 1L * dp[u].sz * DP[u].sz;
          } else {
            ans += 1L * dp[u].a[0][1] * DP[u].a[0][1];
          }
        }
      }
      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)); }

struct Info {
  int sz;
  // int[2][2] a;
  int a00, a01, a10, a11;
  Info opBinary(string op)(Info f) const if (op == "*") {
    Info g;
    g.sz = sz + f.sz;
    /*
    foreach (x; 0 .. 2) foreach (y; 0 .. 2) {
      foreach (xx; 0 .. 2 - x) foreach (yy; 0 .. 2 - y) {
        g.a[x + xx][y + yy] += a[x][y] * f.a[xx][yy];
      }
    }
    */
    g.a00 += a00 * f.a00;
    g.a01 += a00 * f.a01;
    g.a10 += a00 * f.a10;
    g.a11 += a00 * f.a11;
    g.a01 += a01 * f.a00;
    g.a11 += a01 * f.a10;
    g.a10 += a10 * f.a00;
    g.a11 += a10 * f.a01;
    g.a11 += a11 * f.a00;
    return g;
  }
  Info up() const {
    Info f;
    f.sz = 1 + sz;
    // f.a[0][1] += a[0][0];
    // f.a[1][0] += a[0][0];
    // f.a[1][1] += a[0][1];
    // f.a[0][0] += a[1][0];
    // f.a[0][1] += a[1][1];
    f.a01 += a00;
    f.a10 += a00;
    f.a11 += a01;
    f.a00 += a10;
    f.a01 += a11;
    return f;
  }
}
Info identity() {
  Info f;
  // f.a[0][0] = 1;
  f.a00 = 1;
  return f;
}

int N;
int[] A, B;

int[][] G;
int[] par;
Info[] dp, DP;

void dfs(int u, int p) {
  par[u] = p;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
    }
  }
  Info f = identity;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      f = f * dp[v];
    }
  }
  dp[u] = f.up;
}

void DFS(int u, int p) {
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
    }
  }
  const len = cast(int)(vs.length);
  auto ls = new Info[len + 1];
  auto rs = new Info[len + 1];
  ls[0] = rs[len] = identity;
  if (p != -1) {
    rs[len] = DP[u];
  }
  foreach (j; 0 .. len) {
    ls[j + 1] = ls[j] * dp[vs[j]];
  }
  foreach_reverse (j; 0 .. len) {
    rs[j] = dp[vs[j]] * rs[j + 1];
  }
  foreach (j; 0 .. len) {
    DP[vs[j]] = (ls[j] * rs[j + 1]).up;
  }
  foreach (j; 0 .. len) {
    DFS(vs[j], u);
  }
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }

      par = new int[N];
      dp = new Info[N];
      DP = new Info[N];
      const rt = 0;
      dfs(rt, -1);
      DFS(rt, -1);
      debug {
        writeln("rt = ", rt);
        writeln("dp = ", dp);
        writeln("DP = ", DP);
      }
      long ans;
      foreach (u; 0 .. N) {
        if (u != rt) {
          // if (dp[u].a[0][0] && DP[u].a[0][0]) {
          if (dp[u].a00 && DP[u].a00) {
            ans += 1L * dp[u].sz * DP[u].sz;
          } else {
            ans += 1L * dp[u].a01 * DP[u].a01;
          }
        }
      }
      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)); }

struct Info {
  int sz;
  int[2][2] a;
  Info opBinary(string op)(Info f) const if (op == "*") {
    Info g;
    g.sz = sz + f.sz;
    foreach (x; 0 .. 2) foreach (y; 0 .. 2) {
      foreach (xx; 0 .. 2 - x) foreach (yy; 0 .. 2 - y) {
        g.a[x + xx][y + yy] += a[x][y] * f.a[xx][yy];
      }
    }
    return g;
  }
  Info up() const {
    Info f;
    f.sz = 1 + sz;
    f.a[0][1] += a[0][0];
    f.a[1][0] += a[0][0];
    f.a[1][1] += a[0][1];
    f.a[0][0] += a[1][0];
    f.a[0][1] += a[1][1];
    return f;
  }
}
Info identity() {
  Info f;
  f.a[0][0] = 1;
  return f;
}

int N;
int[] A, B;

int[][] G;
int[] par;
Info[] dp, DP;

void dfs(int u, int p) {
  par[u] = p;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
    }
  }
  Info f = identity;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      f = f * dp[v];
    }
  }
  dp[u] = f.up;
}

void DFS(int u, int p) {
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
    }
  }
  const len = cast(int)(vs.length);
  auto ls = new Info[len + 1];
  auto rs = new Info[len + 1];
  ls[0] = rs[len] = identity;
  if (p != -1) {
    rs[len] = DP[u];
  }
  foreach (j; 0 .. len) {
    ls[j + 1] = ls[j] * dp[vs[j]];
  }
  foreach_reverse (j; 0 .. len) {
    rs[j] = dp[vs[j]] * rs[j + 1];
  }
  foreach (j; 0 .. len) {
    DP[vs[j]] = (ls[j] * rs[j + 1]).up;
  }
  foreach (j; 0 .. len) {
    DFS(vs[j], u);
  }
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }

      par = new int[N];
      dp = new Info[N];
      DP = new Info[N];
      const rt = 0;
      dfs(rt, -1);
      DFS(rt, -1);
      debug {
        writeln("rt = ", rt);
        writeln("dp = ", dp);
        writeln("DP = ", DP);
      }
      long ans;
      foreach (u; 0 .. N) {
        if (u != rt) {
          if (dp[u].a[0][0] && DP[u].a[0][0]) {
            ans += 1L * dp[u].sz * DP[u].sz;
          } else {
            ans += 1L * dp[u].a[0][1] * DP[u].a[0][1];
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


For a connected undirected weighted graph G, MST (minimum spanning tree) is a subgraph of G that contains all of G's vertices, is a tree, and sum of its edges is minimum possible.You are given a graph G. If you run a MST algorithm on graph it would give you only one MST and it causes other edges to become jealous. You are given some queries, each query contains a set of edges of graph G, and you should determine whether there is a MST containing all these edges or not.

The first line contains two integers n, m (2  ≤ n, m  ≤ 5·105, n - 1 ≤ m) — the number of vertices and edges in the graph and the number of queries. The i-th of the next m lines contains three integers ui, vi, wi (ui ≠ vi, 1 ≤ wi ≤ 5·105) — the endpoints and weight of the i-th edge. There can be more than one edges between two vertices. It's guaranteed that the given graph is connected. The next line contains a single integer q (1 ≤ q ≤ 5·105) — the number of queries. q lines follow, the i-th of them contains the i-th query. It starts with an integer ki (1 ≤ ki ≤ n - 1) — the size of edges subset and continues with ki distinct space-separated integers from 1 to m — the indices of the edges. It is guaranteed that the sum of ki for 1 ≤ i ≤ q does not exceed 5·105.

For each query you should print "YES" (without quotes) if there's a MST containing these edges and "NO" (of course without quotes again) otherwise.

NoteThis is the graph of sample:  Weight of minimum spanning tree on this graph is 6.MST with edges (1, 3, 4, 6), contains all of edges from the first query, so answer on the first query is "YES".Edges from the second query form a cycle of length 3, so there is no spanning tree including these three edges. Thus, answer is "NO".

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

immutable int maxW = 500_009;

alias Edge = Tuple !(int, q{u}, int, q{v}, int, q{w});
alias Record = Tuple !(int, q{v}, int, q{p}, int, q{r});

void solve (int n, int m, Edge [] e, int qn, int [] [] q)
{
	auto order = m.iota.array;
	makeIndex !((a, b) => a.w < b.w) (e, order);

	foreach (ref query; q)
	{
		schwartzSort !(a => e[a].w) (query);
	}

	auto hasW = new int [] [maxW];
	foreach (k, ref query; q)
	{
		int [] d;
		foreach (c; query)
		{
			d ~= e[c].w;
		}
//		sort (d);
		foreach (w; uniq (d))
		{
			hasW[w] ~= k;
		}
	}
	debug
	{
		foreach (w; 0..maxW)
		{
			if (!hasW[w].empty)
			{
				writeln (w, ": ", hasW[w]);
			}
		}
	}

	auto p = n.iota.array;
	auto r = new int [n];

	int root (int v)
	{
		while (v != p[v])
		{
			v = p[v];
		}
		return v;
	}

	Record [] backups;

	bool unite (int u, int v, bool doBackup)
	{
		u = root (u);
		v = root (v);
		if (u == v)
		{
			return false;
		}
		if (r[u] > r[v])
		{
			swap (u, v);
		}
		if (doBackup)
		{
			backups ~= Record (u, p[u], r[u]);
			backups ~= Record (v, p[v], r[v]);
		}
		p[u] = v;
		if (r[u] == r[v])
		{
			r[v] += 1;
		}
		return true;
	}

	void restoreBackups ()
	{
		foreach_reverse (backup; backups)
		{
			p[backup.v] = backup.p;
			r[backup.v] = backup.r;
		}
		backups.length = 0;
	}

	auto res = new bool [qn];
	res[] = true;

	int prevW = -1;
	foreach (j; 0..m)
	{
		int y = order[j];
		int curW = e[y].w;
		if (prevW != curW)
		{
			foreach (k; hasW[curW])
			{
				while (!q[k].empty && e[q[k].front].w == curW)
				{
					int x = q[k].front;
					q[k].popFront ();
					if (!unite (e[x].u, e[x].v, true))
					{
						res[k] = false;
					}
				}
				restoreBackups ();
			}
			prevW = curW;
		}
		unite (e[y].u, e[y].v, false);
	}

	foreach (c; res)
	{
		writeln (c ? "YES" : "NO");
	}
}

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto e = new Edge [m];
		foreach (ref edge; e)
		{
			readf (" %s %s %s", &edge.u, &edge.v, &edge.w);
			edge.u -= 1;
			edge.v -= 1;
		}

		int qn;
		readf (" %s", &qn);
		readln;
		auto q = new int [] [qn];
		foreach (ref query; q)
		{
			query = readln.splitter.drop (1)
			    .map !(to !(int)).array;
			query[] -= 1;
		}

		solve (n, m, e, qn, q);
	}
}

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

alias KV = Tuple!(int, "key", int, "val");
KV[] history;

int root(int[] uf, int u) {
  // return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
  if (uf[u] < 0) {
    return u;
  } else {
    const r = uf.root(uf[u]);
    if (uf[u] != r) {
      history ~= KV(u, uf[u]);
      uf[u] = r;
    }
    return r;
  }
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  history ~= KV(u, uf[u]);
  history ~= KV(v, uf[v]);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      auto U = new int[M];
      auto V = new int[M];
      auto W = new int[M];
      foreach (i; 0 .. M) {
        U[i] = readInt() - 1;
        V[i] = readInt() - 1;
        W[i] = readInt();
      }
      const Q = readInt();
      auto K = new int[Q];
      auto E = new int[][Q];
      foreach (q; 0 .. Q) {
        K[q] = readInt();
        E[q] = new int[K[q]];
        foreach (k; 0 .. K[q]) {
          E[q][k] = readInt() - 1;
        }
      }

      const limW = W.maxElement + 1;
      auto edgess = new int[][limW];
      foreach (i; 0 .. M) {
        edgess[W[i]] ~= i;
      }
      alias QK = Tuple!(int, "q", int, "k");
      auto qkss = new QK[][limW];
      foreach (q; 0 .. Q) {
        foreach (k; 0 .. K[q]) {
          qkss[W[E[q][k]]] ~= QK(q, k);
        }
      }

      auto ans = new bool[Q];
      ans[] = true;
      auto uf = new int[N];
      uf[] = -1;
      foreach (w; 0 .. limW) {
        auto qks = qkss[w];
        const len = cast(int)(qks.length);
        for (int j = 0, k; j < len; j = k) {
          for (k = j; k < len && qks[j].q == qks[k].q; ++k) {}
          history = [];
          foreach (l; j .. k) {
            const e = E[qks[l].q][qks[l].k];
            if (!uf.connect(U[e], V[e])) {
              ans[qks[l].q] = false;
            }
          }
          foreach_reverse (kv; history) {
            uf[kv.key] = kv.val;
          }
        }
        foreach (i; edgess[w]) {
          uf.connect(U[i], V[i]);
        }
      }

      foreach (q; 0 .. Q) {
        writeln(ans[q] ? "YES" : "NO");
      }
    }
  } 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)); }

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      auto U = new int[M];
      auto V = new int[M];
      auto W = new int[M];
      foreach (i; 0 .. M) {
        U[i] = readInt() - 1;
        V[i] = readInt() - 1;
        W[i] = readInt();
      }
      const Q = readInt();
      auto K = new int[Q];
      auto E = new int[][Q];
      foreach (q; 0 .. Q) {
        K[q] = readInt();
        E[q] = new int[K[q]];
        foreach (k; 0 .. K[q]) {
          E[q][k] = readInt() - 1;
        }
      }

      const limW = W.maxElement + 1;
      auto edgess = new int[][limW];
      foreach (i; 0 .. M) {
        edgess[W[i]] ~= i;
      }
      alias QK = Tuple!(int, "q", int, "k");
      auto qkss = new QK[][limW];
      foreach (q; 0 .. Q) {
        foreach (k; 0 .. K[q]) {
          qkss[W[E[q][k]]] ~= QK(q, k);
        }
      }

      auto ans = new bool[Q];
      ans[] = true;
      auto uf = new int[N];
      uf[] = -1;
      auto saves = new int[N];
      foreach (w; 0 .. limW) {
        auto qks = qkss[w];
        const len = cast(int)(qks.length);
        for (int j = 0, k; j < len; j = k) {
          for (k = j; k < len && qks[j].q == qks[k].q; ++k) {}
          foreach (l; j .. k) {
            const e = E[qks[l].q][qks[l].k];
            saves[U[e]] = uf[U[e]];
            saves[V[e]] = uf[V[e]];
          }
          foreach (l; j .. k) {
            const e = E[qks[l].q][qks[l].k];
            if (!uf.connect(U[e], V[e])) {
              ans[qks[l].q] = false;
            }
          }
          foreach (l; j .. k) {
            const e = E[qks[l].q][qks[l].k];
            uf[U[e]] = saves[U[e]];
            uf[V[e]] = saves[V[e]];
          }
        }
        foreach (i; edgess[w]) {
          uf.connect(U[i], V[i]);
        }
      }

      foreach (q; 0 .. Q) {
        writeln(ans[q] ? "YES" : "NO");
      }
    }
  } 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)); }

alias KV = Tuple!(int, "key", int, "val");
KV[] history;

int root(int[] uf, int u) {
  // return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
  if (uf[u] < 0) {
    return u;
  } else {
    const r = uf.root(uf[u]);
    if (uf[u] != r) {
      history ~= KV(u, r);
      uf[u] = r;
    }
    return r;
  }
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  history ~= KV(u, uf[u]);
  history ~= KV(v, uf[v]);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      auto U = new int[M];
      auto V = new int[M];
      auto W = new int[M];
      foreach (i; 0 .. M) {
        U[i] = readInt() - 1;
        V[i] = readInt() - 1;
        W[i] = readInt();
      }
      const Q = readInt();
      auto K = new int[Q];
      auto E = new int[][Q];
      foreach (q; 0 .. Q) {
        K[q] = readInt();
        E[q] = new int[K[q]];
        foreach (k; 0 .. K[q]) {
          E[q][k] = readInt() - 1;
        }
      }

      const limW = W.maxElement + 1;
      auto edgess = new int[][limW];
      foreach (i; 0 .. M) {
        edgess[W[i]] ~= i;
      }
      alias QK = Tuple!(int, "q", int, "k");
      auto qkss = new QK[][limW];
      foreach (q; 0 .. Q) {
        foreach (k; 0 .. K[q]) {
          qkss[W[E[q][k]]] ~= QK(q, k);
        }
      }

      auto ans = new bool[Q];
      ans[] = true;
      auto uf = new int[N];
      uf[] = -1;
      foreach (w; 0 .. limW) {
        auto qks = qkss[w];
        const len = cast(int)(qks.length);
        for (int j = 0, k; j < len; j = k) {
          for (k = j; k < len && qks[j].q == qks[k].q; ++k) {}
          history = [];
          foreach (l; j .. k) {
            const e = E[qks[l].q][qks[l].k];
            if (!uf.connect(U[e], V[e])) {
              ans[qks[l].q] = false;
            }
          }
          foreach_reverse (kv; history) {
            uf[kv.key] = kv.val;
          }
        }
        foreach (i; edgess[w]) {
          uf.connect(U[i], V[i]);
        }
      }

      foreach (q; 0 .. Q) {
        writeln(ans[q] ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}


Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart.Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.

The first line contains integer m (1 ≤ m ≤ 105) — the number of discount types. The second line contains m integers: q1, q2, ..., qm (1 ≤ qi ≤ 105).  The third line contains integer n (1 ≤ n ≤ 105) — the number of items Maxim needs. The fourth line contains n integers: a1, a2, ..., an (1 ≤ ai ≤ 104) — the items' prices. The numbers in the lines are separated by single spaces.

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

NoteIn the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200.In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.

import std.algorithm;
import std.stdio;

void main() {
    int M;
    readf(" %s", &M);
    int[] Q = new int[M];
    foreach (ref q; Q)
        readf(" %s", &q);
    int use = reduce!(min)(Q);

    int N;
    readf(" %s", &N);
    int[] A = new int[N];
    foreach (ref a; A)
        readf(" %s", &a);
    sort!("a > b")(A);

    long ans = 0;
    foreach (i, a; A) {
        auto m = i % (use + 2);
        if (m < use)
            ans += a;
    }
    writeln(ans);
}

import std.stdio : write, writeln, writefln, stdin;
import std.array;
import std.range;
import std.typecons;
import std.algorithm : max, min;

int m;
int[] q;
int n;
int[] a;

T sum(T)(T[] l ...){
	T s;
	foreach(v; l){
		s += v;
	}
	return s;
}

void main(){
	m.next;
	q = q.init;
	foreach(i; m.iota){
		q ~= next!int();
	}
	n.next;
	a = a.init;
	foreach(i; n.iota){
		a ~= next!int();
	}

	q = q.sort;
	a = a.sort.retro.array;

	int cnt;
	int sum;
	for(int i=0; i<n; ++i){
		if( cnt >= q[0] ){
			++i;
			cnt = 0;
		}else{
			sum += a[i];
			++cnt;
		}
	}

	sum.writeln;
}

import std.stdio : readln;
import std.conv : to;
import std.string : split, chomp;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}


Polycarp has prepared $$$n$$$ competitive programming problems. The topic of the $$$i$$$-th problem is $$$a_i$$$, and some problems' topics may coincide.Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:  number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;  the total number of problems in all the contests should be maximized. Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of problems Polycarp has prepared. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) where $$$a_i$$$ is the topic of the $$$i$$$-th problem.

Print one integer — the maximum number of problems in the set of thematic contests.

NoteIn the first example the optimal sequence of contests is: $$$2$$$ problems of the topic $$$1$$$, $$$4$$$ problems of the topic $$$2$$$, $$$8$$$ problems of the topic $$$10$$$.In the second example the optimal sequence of contests is: $$$3$$$ problems of the topic $$$3$$$, $$$6$$$ problems of the topic $$$6$$$.In the third example you can take all the problems with the topic $$$1337$$$ (the number of such problems is $$$3$$$ so the answer is $$$3$$$) and host a single contest.

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

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

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

    int [int] cnt;
    arr.each!(x => ++cnt[x]);

    debug { cnt.writeln; }

    auto vals = cnt.values.sort().retro().array;

    auto ans = 0, cur = int.max;
    foreach (i, v; vals.enumerate(1)) {
        if (cur == 1) break;

        auto nxt = min(v, cur / 2);
        auto now = i.iota.map!(x => nxt * 2^^x).sum;

        debug { writeln(nxt, ' ', now); }

        ans = max(ans, now);
        cur = nxt;
    }

    ans.writeln;
}

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

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

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

    int [int] cnt;
    arr.each!(x => ++cnt[x]);

    debug { cnt.writeln; }

    auto vals = cnt.values.sort().retro().array;

    auto ans = 0, cur = int.max;
    foreach (i, v; vals.enumerate(1)) {
        if (cur == 1) break;

        auto nxt = min(v, cur / 2);
        auto now = (2^^i - 1) * nxt;

        debug { writeln(nxt, ' ', now); }

        ans = max(ans, now);
        cur = nxt;
    }

    ans.writeln;
}

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

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

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

    int [int] cnt;
    arr.each!(x => ++cnt[x]);

    debug { cnt.writeln; }

    auto vals = cnt.values.sort().retro().array;

    auto ans = 0, cur = int.max;
    foreach (i, v; vals) {
        if (cur == 1) break;

        auto nxt = min(v, cur / 2);
        auto now = (2^^(i+1) - 1) * nxt;

        debug { writeln(nxt, ' ', now); }

        ans = max(ans, now.to!int);
        cur = nxt;
    }

    ans.writeln;
}


You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills:  the matrix has a row with prime numbers only;  the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.

The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.

Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.

NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.

import std.algorithm;
import std.math;
import std.stdio;

immutable int MAX_N =     500;
immutable int MAX_L = 120_000;

int [MAX_N] [MAX_N] a;

int main ()
{
	auto s = new bool [MAX_L];
	s[] = true;
	s[0] = s[1] = false;
	for (int i = 2; i * i < MAX_L; i++)
	{
		if (s[i])
		{
			for (int j = i * i; j < MAX_L; j += i)
			{
				s[j] = false;
			}
		}
	}

	auto c = new int [MAX_L];
	for (int i = MAX_L - 2; i >= 0; i--)
	{
		if (!s[i])
		{
			c[i] = c[i + 1] + 1;
		}
	}

	int n, m;
	while ((readf (" %s %s", &n, &m) >= 0) && !stdin.eof ())
	{
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				readf (" %s", &a[i][j]);
			}
		}

		auto u = new int [n];
		auto v = new int [m];
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				u[i] += c[a[i][j]];
				v[j] += c[a[i][j]];
			}
		}
		int res = int.max;
		foreach (a; u ~ v)
		{
			res = min (res, a);
		}
		writefln ("%s", res);
	}
	return 0;
}


A string $$$s$$$ of length $$$n$$$ ($$$1 \le n \le 26$$$) is called alphabetical if it can be obtained using the following algorithm:  first, write an empty string to $$$s$$$ (i.e. perform the assignment $$$s$$$ := "");  then perform the next step $$$n$$$ times;  at the $$$i$$$-th step take $$$i$$$-th lowercase letter of the Latin alphabet and write it either to the left of the string $$$s$$$ or to the right of the string $$$s$$$ (i.e. perform the assignment $$$s$$$ := $$$c+s$$$ or $$$s$$$ := $$$s+c$$$, where $$$c$$$ is the $$$i$$$-th letter of the Latin alphabet). In other words, iterate over the $$$n$$$ first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string $$$s$$$ or append a letter to the right of the string $$$s$$$. Strings that can be obtained in that way are alphabetical.For example, the following strings are alphabetical: "a", "ba", "ab", "bac" and "ihfcbadeg". The following strings are not alphabetical: "z", "aa", "ca", "acb", "xyz" and "ddcba".From the given string, determine if it is alphabetical.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is written on a separate line that contains one string $$$s$$$. String $$$s$$$ consists of lowercase letters of the Latin alphabet and has a length between $$$1$$$ and $$$26$$$, inclusive.

Output $$$t$$$ lines, each of them must contain the answer to the corresponding test case. Output YES if the given string $$$s$$$ is alphabetical and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive answer).

11
a
ba
ab
bac
ihfcbadeg
z
aa
ca
acb
xyz
ddcba

NoteThe example contains test cases from the main part of the condition.

// Vicfred
// https://codeforces.com/contest/1547/problem/B
// greedy
import std.algorithm;
import std.stdio;

int find(string s, char c) {
    for(int i = 0; i < s.length; ++i) {
        if(s[i] == c)
            return i;
    }
    return -1;
}

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

while(t--) {
    string s;
    readf("%s\n", &s);
    int index = find(s, 'a');
    if(index == -1) {
        "NO".writeln;
        continue;
    }
    int R, L;
    L = index;
    R = index;
    bool valid = true;
    for(int i = 1; i < s.length; ++i) {
        char c = cast(char)('a' + i);
        int idx = find(s, c);
        if(idx == -1) {
            valid = false;
            break;
        }
        if(idx != L - 1 && idx != R + 1) {
            valid = false;
            break;
        }
        L = min(L, idx);
        R = max(R, idx);
    }
    if(valid) {
        "YES".writeln;
    } else {
        "NO".writeln;
    }
}
}


You are given a permutation $$$a_1, a_2, \ldots, a_n$$$ of size $$$n$$$, where each integer from $$$1$$$ to $$$n$$$ appears exactly once.You can do the following operation any number of times (possibly, zero):  Choose any three indices $$$i, j, k$$$ ($$$1 \le i < j < k \le n$$$).  If $$$a_i > a_k$$$, replace $$$a_i$$$ with $$$a_i + a_j$$$. Otherwise, swap $$$a_j$$$ and $$$a_k$$$. Determine whether you can make the array $$$a$$$ sorted in non-descending order.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 10$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1 \le a_i \le n$$$, $$$a_i \neq a_j$$$ if $$$i \neq j$$$) — the elements of the array $$$a$$$.

For each test case, output "Yes" (without quotes) if the array can be sorted in non-descending order, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "YES", "yEs" and "yes" will be recognized as a positive response).

NoteIn the first test case, $$$[1,2,3]$$$ is already sorted in non-descending order.In the second test case, we can choose $$$i = 1,j = 2,k = 3$$$. Since $$$a_1 \le a_3$$$, swap $$$a_2$$$ and $$$a_3$$$, the array then becomes $$$[1,2,3]$$$, which is sorted in non-descending order.In the seventh test case, we can do the following operations successively:  Choose $$$i = 5,j = 6,k = 7$$$. Since $$$a_5 \le a_7$$$, swap $$$a_6$$$ and $$$a_7$$$, the array then becomes $$$[1,2,6,7,4,5,3]$$$.  Choose $$$i = 5,j = 6,k = 7$$$. Since $$$a_5 > a_7$$$, replace $$$a_5$$$ with $$$a_5+a_6=9$$$, the array then becomes $$$[1,2,6,7,9,5,3]$$$.  Choose $$$i = 2,j = 5,k = 7$$$. Since $$$a_2 \le a_7$$$, swap $$$a_5$$$ and $$$a_7$$$, the array then becomes $$$[1,2,6,7,3,5,9]$$$.  Choose $$$i = 2,j = 4,k = 6$$$. Since $$$a_2 \le a_6$$$, swap $$$a_4$$$ and $$$a_6$$$, the array then becomes $$$[1,2,6,5,3,7,9]$$$.  Choose $$$i = 1,j = 3,k = 5$$$. Since $$$a_1 \le a_5$$$, swap $$$a_3$$$ and $$$a_5$$$, the array then becomes $$$[1,2,3,5,6,7,9]$$$, which is sorted in non-descending order. In the third, the fourth, the fifth and the sixth test cases, it can be shown that the array cannot be sorted in non-descending order.

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!long;
    auto a = readln.splitter.map!(to!long).array;
    writeln (a[0] == 1 ? "Yes" : "No");
  }
}

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;
		writeln (a.front == a.minElement ? "Yes" : "No");
	}
}


You are given a connected, undirected and unweighted graph with $$$n$$$ vertices and $$$m$$$ edges. Notice the limit on the number of edges: $$$m \le n + 2$$$.Let's say we color some of the edges red and the remaining edges blue. Now consider only the red edges and count the number of connected components in the graph. Let this value be $$$c_1$$$. Similarly, consider only the blue edges and count the number of connected components in the graph. Let this value be $$$c_2$$$.Find an assignment of colors to the edges such that the quantity $$$c_1+c_2$$$ is minimised.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$n-1 \leq m \leq \min{\left(n+2,\frac{n \cdot (n-1)}{2}\right)}$$$) — the number of vertices and the number of edges respectively. $$$m$$$ lines follow. The $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i,v_i \le n$$$, $$$u_i \ne v_i$$$) denoting that the $$$i$$$-th edge goes between vertices $$$u_i$$$ and $$$v_i$$$. The input is guaranteed to have no multiple edges or self loops. The graph is also guaranteed to be connected. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^6$$$.

For each test case, output a binary string of length $$$m$$$. The $$$i$$$-th character of the string should be 1 if the $$$i$$$-th edge should be colored red, and 0 if it should be colored blue. If there are multiple ways to assign colors to edges that give the minimum answer, you may output any.

Note The corresponding graph of the first test case is:  $$$c_1 + c_2 = 1 + 2 = 3$$$ The corresponding graph of the second test case is:  $$$c_1 + c_2 = 2 + 2 = 4$$$

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto a = new int [] [n];
		alias Edge = Tuple !(int, q{u}, int, q{v});
		auto e = new Edge [m];
		foreach (ref c; e)
		{
			readf !(" %s %s") (c.u, c.v);
			c.u -= 1;
			c.v -= 1;
			a[c.u] ~= c.v;
			a[c.v] ~= c.u;
		}

		auto order = m.iota.array;
		auto vis = new bool [m];
		int [] p;

		int root (int v)
		{
			if (p[v] != v)
			{
				p[v] = root (p[v]);
			}
			return p[v];
		}

		bool unite (int u, int v)
		{
			u = root (u);
			v = root (v);
			if (u == v)
			{
				return false;
			}
			p[u] = v;
			return true;
		}

		while (true)
		{
			p = n.iota.array;
			randomShuffle (order);
			foreach (j; order)
			{
				vis[j] = unite (e[j].u, e[j].v);
			}

			bool [int] b;
			foreach (j; m.iota.filter !(j => !vis[j]))
			{
				b[e[j].u] = true;
				b[e[j].v] = true;
			}

			if (!(m == n + 2 && b.length == 3))
			{
				break;
			}
			debug {stderr.writeln ("bad");}
		}

		writefln !("%(%d%)") (vis);
	}
}