You are walking through a parkway near your house. The parkway has $$$n+1$$$ benches in a row numbered from $$$1$$$ to $$$n+1$$$ from left to right. The distance between the bench $$$i$$$ and $$$i+1$$$ is $$$a_i$$$ meters.Initially, you have $$$m$$$ units of energy. To walk $$$1$$$ meter of distance, you spend $$$1$$$ unit of your energy. You can't walk if you have no energy. Also, you can restore your energy by sitting on benches (and this is the only way to restore the energy). When you are sitting, you can restore any integer amount of energy you want (if you sit longer, you restore more energy). Note that the amount of your energy can exceed $$$m$$$.Your task is to find the minimum amount of energy you have to restore (by sitting on benches) to reach the bench $$$n+1$$$ from the bench $$$1$$$ (and end your walk).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$; $$$1 \le m \le 10^4$$$). The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the distance between benches $$$i$$$ and $$$i+1$$$.

For each test case, print one integer — the minimum amount of energy you have to restore (by sitting on benches) to reach the bench $$$n+1$$$ from the bench $$$1$$$ (and end your walk) in the corresponding test case.

NoteIn the first test case of the example, you can walk to the bench $$$2$$$, spending $$$1$$$ unit of energy, then restore $$$2$$$ units of energy on the second bench, walk to the bench $$$3$$$, spending $$$2$$$ units of energy, restore $$$1$$$ unit of energy and go to the bench $$$4$$$.In the third test case of the example, you have enough energy to just go to the bench $$$6$$$ without sitting at all.

module CodeForces;

import std;

int main()
{
	int lineNum = stdin.readln.strip.to!int;

    for ( int i = 0; i < lineNum; i++ )
	{
		int[] oturakSayısıVeBaslangıcEnerjisiİkilisi = stdin.readln.strip.split.map!(a=> a.to!int()).array;
		int başlangıçEnerjisi = oturakSayısıVeBaslangıcEnerjisiİkilisi.back();

		int[] oturakAralıkMesafeleri = stdin.readln.strip.split.map!( a=> a.to!int() ).array;
		int toplamOturakMesafesi = oturakAralıkMesafeleri.sum();

		writeln( max(0, toplamOturakMesafesi - başlangıçEnerjisi) );
	}
    return 0;
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto M = scan!int;
      auto A = scan!int(N);

      return max(0, A.sum - M);
    }

    foreach(i; 0..QN) {
      outputForAtCoder(&subSolve);
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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


AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays $$$a$$$ and $$$b$$$, both consist of $$$n$$$ non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero):  She chooses two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$), then decreases the $$$i$$$-th element of array $$$a$$$ by $$$1$$$, and increases the $$$j$$$-th element of array $$$a$$$ by $$$1$$$. The resulting values at $$$i$$$-th and $$$j$$$-th index of array $$$a$$$ are $$$a_i - 1$$$ and $$$a_j + 1$$$, respectively. Each element of array $$$a$$$ must be non-negative after each operation. If $$$i = j$$$ this operation doesn't change the array $$$a$$$. AquaMoon wants to make some operations to make arrays $$$a$$$ and $$$b$$$ equal. Two arrays $$$a$$$ and $$$b$$$ are considered equal if and only if $$$a_i = b_i$$$ for all $$$1 \leq i \leq n$$$.Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays $$$a$$$ and $$$b$$$ equal.Please note, that you don't have to minimize the number of operations.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 100$$$). The sum of all $$$a_i$$$ does not exceed $$$100$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \leq b_i \leq 100$$$). The sum of all $$$b_i$$$ does not exceed $$$100$$$.

For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer $$$m$$$ ($$$0 \leq m \leq 100$$$) in the first line — the number of operations. Then print $$$m$$$ lines, each line consists of two integers $$$i$$$ and $$$j$$$ — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with $$$m \leq 100$$$. If there are multiple possible solutions, you can print any.

NoteIn the first example, we do the following operations:  $$$i = 2$$$, $$$j = 1$$$: $$$[1, 2, 3, 4] \rightarrow [2, 1, 3, 4]$$$;  $$$i = 3$$$, $$$j = 1$$$: $$$[2, 1, 3, 4] \rightarrow [3, 1, 2, 4]$$$; In the second example, it's impossible to make two arrays equal.

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);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array;
    auto b = readln.strip.split.map!(to!long).array;
    long suma = a.sum;
    long sumb = b.sum;
    if (suma != sumb) {
      writeln(-1);
      continue;
    }
    long m = 0;
    foreach (i ; 0 .. n) {
      if (b[i] > a[i])
        m += b[i] - a[i];
    }
    writeln(m);
    int i = 0, j = 0;
    while (m--) {
      while (a[i] <= b[i])
        i++;
      while (a[j] >= b[j])
        j++;
      a[i]--;
      a[j]++;
      writefln("%d %d", i + 1, j + 1);
    }
  }
}

// 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);
  while(tests--) {
    int n; readf!"%s\n"(n);
    auto a = readln.splitter.map!(to!int).array;
    auto b = readln.splitter.map!(to!int).array;
    if (a.sum != b.sum) {
      "-1".writeln;
    }
    else {
      alias Pair = Tuple!(int, "i", int, "j");
      Pair[] ans;
      void add_pair(int x, int y) {
        a[x]--; a[y]++;
        ans ~= Pair(x + 1, y + 1);
      }
      int[] s, g;
      foreach(i; 0 .. n) {
        if (a[i] < b[i]) s ~= i;
        else g ~= i;
      }
      int i, j;
      for (i = 0; i < s.length; ) {
        if (a[s[i]] != b[s[i]]) {
          while (a[g[j]] == b[g[j]]) ++j;
          add_pair(g[j], s[i]);
        }
        else {
          ++i;
        }
      }
      writefln!"%s"(ans.length);
      foreach(p; ans) {
        writefln!"%s %s"(p.i, p.j);
      }
    }
  }

} // main

// Vicfred
// https://codeforces.com/contest/1546/problem/A
// greedy
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

struct point {
    int x, y;
}
void main() {
    int t = readln.chomp.to!int;

while(t--) {
    int n = readln.chomp.to!int;
    int[] a = readln.split.map!(to!int).array;
    int[] b = readln.split.map!(to!int).array;

    int sum_a = a.sum;
    int sum_b = b.sum;

    if(sum_a != sum_b) {
        "-1".writeln;
        continue;
    }

    point[] idx;

    int i, j;
    while(i < n && j < n) {
        while(a[i] <= b[i]) {
            i += 1;
            if(i >= n || j >= n)
                break;
        }
        while(a[j] >= b[j]) {
            j += 1;
            if(i >= n || j >= n)
                break;
        }
        if(i >= n || j >= n)
            break;
        idx ~= point(i, j);
        a[i] -= 1;
        a[j] += 1;
    }

    if(a == b) {
        idx.length.writeln;
        idx.each!(it => "%s %s".writefln(it.x + 1, it.y + 1));
    } else {
        "-1".writeln;
    }
}
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
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);
	auto ok = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto b = RDA;

		if (a.sum != b.sum) continue;

		ok[ti] = true;
		long[] x, y;
		foreach (i; 0..n)
		{
			auto d = b[i] - a[i];
			if (d >= 0)
			{
				foreach (_; 0..d)
					x ~= i;
			}
			else
			{
				foreach (_; 0..-d)
					y ~= i;
			}
		}

		foreach (i; 0..x.length)
		{
			auto xx = x.front; x.popFront;
			auto yy = y.front; y.popFront;
			ans[ti] ~= [yy+1, xx+1];
		}
	}

	foreach (ti, e; ans)
	{
		if (e.empty)
			writeln(ok[ti] ? 0 : -1);
		else
		{
			writeln(e.length);
			foreach (ee; e)
				writeln(ee[0], " ", ee[1]);
		}
	}
	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);
  while(tests--) {
    int n; readf!"%s\n"(n);
    auto a = readln.splitter.map!(to!int).array;
    auto b = readln.splitter.map!(to!int).array;
    if (a.sum != b.sum) {
      "-1".writeln;
    }
    else {
      alias Pair = Tuple!(int, "i", int, "j");
      Pair[] ans;
      foreach(i; 0 .. n) {
        while (a[i] != b[i]) {
          if (a[i] > b[i]) {
            ans ~= Pair(i + 1, i + 2);
            a[i]--;
            a[i + 1]++;
          }
          else {
            a[i]++;
            a[i + 1]--;
            ans ~= Pair(i + 2, i + 1);
          }
        }
      }
      writefln!"%s"(ans.length);
      foreach(p; ans) {
        writefln!"%s %s"(p.i, p.j);
      }
    }
  }

} // main


You are standing on the $$$\mathit{OX}$$$-axis at point $$$0$$$ and you want to move to an integer point $$$x > 0$$$.You can make several jumps. Suppose you're currently at point $$$y$$$ ($$$y$$$ may be negative) and jump for the $$$k$$$-th time. You can:   either jump to the point $$$y + k$$$  or jump to the point $$$y - 1$$$. What is the minimum number of jumps you need to reach the point $$$x$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains the single integer $$$x$$$ ($$$1 \le x \le 10^6$$$) — the destination point.

For each test case, print the single integer — the minimum number of jumps to reach $$$x$$$. It can be proved that we can reach any integer point $$$x$$$.

NoteIn the first test case $$$x = 1$$$, so you need only one jump: the $$$1$$$-st jump from $$$0$$$ to $$$0 + 1 = 1$$$.In the second test case $$$x = 2$$$. You need at least three jumps:   the $$$1$$$-st jump from $$$0$$$ to $$$0 + 1 = 1$$$;  the $$$2$$$-nd jump from $$$1$$$ to $$$1 + 2 = 3$$$;  the $$$3$$$-rd jump from $$$3$$$ to $$$3 - 1 = 2$$$; Two jumps are not enough because these are the only possible variants:   the $$$1$$$-st jump as $$$-1$$$ and the $$$2$$$-nd one as $$$-1$$$ — you'll reach $$$0 -1 -1 =-2$$$;  the $$$1$$$-st jump as $$$-1$$$ and the $$$2$$$-nd one as $$$+2$$$ — you'll reach $$$0 -1 +2 = 1$$$;  the $$$1$$$-st jump as $$$+1$$$ and the $$$2$$$-nd one as $$$-1$$$ — you'll reach $$$0 +1 -1 = 0$$$;  the $$$1$$$-st jump as $$$+1$$$ and the $$$2$$$-nd one as $$$+2$$$ — you'll reach $$$0 +1 +2 = 3$$$; In the third test case, you need two jumps: the $$$1$$$-st one as $$$+1$$$ and the $$$2$$$-nd one as $$$+2$$$, so $$$0 + 1 + 2 = 3$$$.In the fourth test case, you need three jumps: the $$$1$$$-st one as $$$-1$$$, the $$$2$$$-nd one as $$$+2$$$ and the $$$3$$$-rd one as $$$+3$$$, so $$$0 - 1 + 2 + 3 = 4$$$.

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 x = readln.strip.to !(int);
		int step = 0;
		int pos = 0;
		while (pos < x)
		{
			step += 1;
			pos += step;
		}
		writeln (step + (pos - x == 1));
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

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

		bool f(long y)
		{
			return y * (y+1) / 2 < x;
		}
		auto r = binarySearch!(f)(0, x) + 1;
		if (r * (r+1) / 2 == x+1)
		{
			ans[ti] = r+1;
		}
		else
		{
			ans[ti] = r;
		}
	}

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


Mark is cleaning a row of $$$n$$$ rooms. The $$$i$$$-th room has a nonnegative dust level $$$a_i$$$. He has a magical cleaning machine that can do the following three-step operation.   Select two indices $$$i<j$$$ such that the dust levels $$$a_i$$$, $$$a_{i+1}$$$, $$$\dots$$$, $$$a_{j-1}$$$ are all strictly greater than $$$0$$$.  Set $$$a_i$$$ to $$$a_i-1$$$.  Set $$$a_j$$$ to $$$a_j+1$$$.  Mark's goal is to make $$$a_1 = a_2 = \ldots = a_{n-1} = 0$$$ so that he can nicely sweep the $$$n$$$-th room. Determine the minimum number of operations needed to reach his goal.

The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2\leq n\leq 2\cdot 10^5$$$) — the number of rooms. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0\leq a_i\leq 10^9$$$) — the dust level of each room. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print a line containing a single integer — the minimum number of operations. It can be proven that there is a sequence of operations that meets the goal.

NoteIn the first case, one possible sequence of operations is as follows.   Choose $$$i=1$$$ and $$$j=2$$$, yielding the array $$$[1,1,0]$$$.  Choose $$$i=1$$$ and $$$j=3$$$, yielding the array $$$[0,1,1]$$$.  Choose $$$i=2$$$ and $$$j=3$$$, yielding the array $$$[0,0,2]$$$.  At this point, $$$a_1=a_2=0$$$, completing the process.In the second case, one possible sequence of operations is as follows.   Choose $$$i=4$$$ and $$$j=5$$$, yielding the array $$$[0,2,0,1,1]$$$.  Choose $$$i=2$$$ and $$$j=3$$$, yielding the array $$$[0,1,1,1,1]$$$.  Choose $$$i=2$$$ and $$$j=5$$$, yielding the array $$$[0,0,1,1,2]$$$.  Choose $$$i=3$$$ and $$$j=5$$$, yielding the array $$$[0,0,0,1,3]$$$.  Choose $$$i=4$$$ and $$$j=5$$$, yielding the array $$$[0,0,0,0,4]$$$. In the last case, the array already satisfies the condition.

// cheese-cracker [2022-07-15]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    int st = 0;
    for(;st < n; ++st){
        if(arr[st] > 0){
            break;
        }
    }
    long summ = 0;
    long cnt = 0;
    for(int i = st; i < n - 1; ++i){
        summ += arr[i];
        cnt += (arr[i] == 0);
    }
    writeln(summ + cnt);
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }


A club plans to hold a party and will invite some of its $$$n$$$ members. The $$$n$$$ members are identified by the numbers $$$1, 2, \dots, n$$$. If member $$$i$$$ is not invited, the party will gain an unhappiness value of $$$a_i$$$.There are $$$m$$$ pairs of friends among the $$$n$$$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited.However, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number.What is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq \min(10^5,\frac{n(n-1)}{2})$$$) — the number of club members and pairs of friends. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \dots,a_n$$$ ($$$0 \leq a_i \leq 10^4$$$) — the unhappiness value array. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x,y \leq n$$$, $$$x \neq y$$$) indicating that $$$x$$$ and $$$y$$$ are friends. Each unordered pair $$$(x,y)$$$ appears at most once in each test case. It is guaranteed that both the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.

For each test case, print a line containing a single integer – the minimum possible unhappiness value of a valid party.

NoteIn the first test case, all members can be invited. So the unhappiness value is $$$0$$$.In the second test case, the following options are possible:   invite $$$1$$$ and $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$);  invite $$$2$$$ and $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$2$$$);  invite only $$$1$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$4$$$);  invite only $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$5$$$);  invite only $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$);  invite nobody ($$$0$$$ cakes eaten, unhappiness value equal to $$$6$$$).  The minimum unhappiness value is achieved by inviting $$$2$$$ and $$$3$$$.In the third test case, inviting members $$$3,4,5$$$ generates a valid party with the minimum possible unhappiness value.

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)); }
T euDist2(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return c.sum; }
double euDist(T)(T[] a, T[] b) { return sqrt(cast(double)euDist2(a,b)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto a = RDA;
		auto edges = new int[][](n);
		foreach (i; 0..m)
		{
			auto x = RD!int-1;
			auto y = RD!int-1;
			edges[x] ~= y;
			edges[y] ~= x;
		}

		if (m % 2 == 0) continue;

		ans[ti] = a.sum;
		foreach (i; 0..n)
		{
			if (edges[i].length % 2)
				ans[ti].chmin(a[i]);
		}

		foreach (i; 0..n)
		{
			if (edges[i].length % 2) continue;

			foreach (v; edges[i])
			{
				if (edges[v].length % 2) continue;
				ans[ti].chmin(a[i]+a[v]);
			}
		}
	}

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


Polycarp wants to cook a soup. To do it, he needs to buy exactly $$$n$$$ liters of water.There are only two types of water bottles in the nearby shop — $$$1$$$-liter bottles and $$$2$$$-liter bottles. There are infinitely many bottles of these two types in the shop.The bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles correspondingly.Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles. You also have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. The next $$$q$$$ lines contain queries. The $$$i$$$-th query is given as three space-separated integers $$$n_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \le n_i \le 10^{12}, 1 \le a_i, b_i \le 1000$$$) — how many liters Polycarp needs in the $$$i$$$-th query, the cost (in burles) of the bottle of the first type in the $$$i$$$-th query and the cost (in burles) of the bottle of the second type in the $$$i$$$-th query, respectively.

Print $$$q$$$ integers. The $$$i$$$-th integer should be equal to the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n_i$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a_i$$$ burles and the bottle of the second type costs $$$b_i$$$ burles.

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

  int q;
  rd(q);
  while (q--) {
    long n, a, b;
    rd(n, a, b);
    auto ans = n * a;
    if (n & 1) {
      ans = min(ans, n / 2 * b + a);
    } else {
      ans = min(ans, n / 2 * b);
    }
    writeln(ans);
  }
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

import std.stdio;
int main()
{
	long t=0;
	readf(" %d", &t);
	for (long i=0; i<t; i++)
	{
		long a=0;
		long b=0;
		long c=0;
		readf(" %d", &a);
		readf(" %d", &b);
		readf(" %d", &c);
		if (b*2<=c)
		{
			writeln(a*b);
		}
		else
		{
			if (a%2==0)
			{
				writeln(a*c/2);
			}
			else
			{
				writeln((a/2)*c+b);
			}
		}
	}
	return 0;
}


There is a house with $$$n$$$ flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i = 1$$$ if in the $$$i$$$-th flat the light is on and $$$a_i = 0$$$ otherwise.Vova thinks that people in the $$$i$$$-th flats are disturbed and cannot sleep if and only if $$$1 < i < n$$$ and $$$a_{i - 1} = a_{i + 1} = 1$$$ and $$$a_i = 0$$$.Vova is concerned by the following question: what is the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number $$$k$$$.

The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of flats in the house. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_i \in \{0, 1\}$$$), where $$$a_i$$$ is the state of light in the $$$i$$$-th flat.

Print only one integer — the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the light then nobody will be disturbed.

NoteIn the first example people from flats $$$2$$$ and $$$7$$$ or $$$4$$$ and $$$7$$$ can turn off the light and nobody will be disturbed. It can be shown that there is no better answer in this example.There are no disturbed people in second and third examples.

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

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

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

    auto ans = 0;
    foreach (i; 1 .. n-1) {
        if (arr[i-1] == 1 && arr[i] == 0 && arr[i+1] == 1) {
            ++ans;
            arr[i+1] = 0;
        }
    }

    ans.writeln;
}


Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.

The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.

Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".

import std.stdio, std.string;

void solve(int[] a, int[] b, int n, int m)
{
    auto ans = 0;
    auto i = 0, j = 0;
    long sa = 0, sb = 0;
    while (i < n && j < m)
    {
        if (sa > sb)
        {
            sb += b[j];
        }
        else if (sa < sb)
        {
            sa += a[i];
        }
        else
        {
            sa += a[i];
            sb += b[j];
        }
        if (sa == sb)
        {
            ++ ans;
            ++ i;
            ++ j;
            sa = sb = 0;
        }
        else if (sa > sb)
        {
            ++ j;
        }
        else
        {
            ++ i;
        }
    }
    if (i < n || j < m)
    {
        writeln(-1);
    }
    else
    {
        writeln(ans);
    }
}

int main(string[] args)
{
    int n, m;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            readf(" %d", &a[i]);
        }
        readf("\n%d\n", &m);
        auto b = new int[m];
        foreach (i; 0 .. m)
        {
            readf(" %d", &b[i]);
        }
        readln;
        solve(a, b, n, m);
    }
    return 0;
}


So the Beautiful Regional Contest (BeRC) has come to an end! $$$n$$$ students took part in the contest. The final standings are already known: the participant in the $$$i$$$-th place solved $$$p_i$$$ problems. Since the participants are primarily sorted by the number of solved problems, then $$$p_1 \ge p_2 \ge \dots \ge p_n$$$.Help the jury distribute the gold, silver and bronze medals. Let their numbers be $$$g$$$, $$$s$$$ and $$$b$$$, respectively. Here is a list of requirements from the rules, which all must be satisfied:  for each of the three types of medals, at least one medal must be awarded (that is, $$$g>0$$$, $$$s>0$$$ and $$$b>0$$$);  the number of gold medals must be strictly less than the number of silver and the number of bronze (that is, $$$g<s$$$ and $$$g<b$$$, but there are no requirements between $$$s$$$ and $$$b$$$);  each gold medalist must solve strictly more problems than any awarded with a silver medal;  each silver medalist must solve strictly more problems than any awarded a bronze medal;  each bronze medalist must solve strictly more problems than any participant not awarded a medal;  the total number of medalists $$$g+s+b$$$ should not exceed half of all participants (for example, if $$$n=21$$$, then you can award a maximum of $$$10$$$ participants, and if $$$n=26$$$, then you can award a maximum of $$$13$$$ participants). The jury wants to reward with medals the total maximal number participants (i.e. to maximize $$$g+s+b$$$) so that all of the items listed above are fulfilled. Help the jury find such a way to award medals.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains an integer $$$n$$$ ($$$1 \le n \le 4\cdot10^5$$$) — the number of BeRC participants. The second line of a test case contains integers $$$p_1, p_2, \dots, p_n$$$ ($$$0 \le p_i \le 10^6$$$), where $$$p_i$$$ is equal to the number of problems solved by the $$$i$$$-th participant from the final standings. The values $$$p_i$$$ are sorted in non-increasing order, i.e. $$$p_1 \ge p_2 \ge \dots \ge p_n$$$. The sum of $$$n$$$ over all test cases in the input does not exceed $$$4\cdot10^5$$$.

Print $$$t$$$ lines, the $$$j$$$-th line should contain the answer to the $$$j$$$-th test case. The answer consists of three non-negative integers $$$g, s, b$$$.   Print $$$g=s=b=0$$$ if there is no way to reward participants with medals so that all requirements from the statement are satisfied at the same time.  Otherwise, print three positive numbers $$$g, s, b$$$ — the possible number of gold, silver and bronze medals, respectively. The sum of $$$g+s+b$$$ should be the maximum possible. If there are several answers, print any of them.

NoteIn the first test case, it is possible to reward $$$1$$$ gold, $$$2$$$ silver and $$$3$$$ bronze medals. In this case, the participant solved $$$5$$$ tasks will be rewarded with the gold medal, participants solved $$$4$$$ tasks will be rewarded with silver medals, participants solved $$$2$$$ or $$$3$$$ tasks will be rewarded with bronze medals. Participants solved exactly $$$1$$$ task won't be rewarded. It's easy to see, that in this case, all conditions are satisfied and it is possible to reward participants in this way. It is impossible to give more than $$$6$$$ medals because the number of medals should not exceed half of the number of participants. The answer $$$1$$$, $$$3$$$, $$$2$$$ is also correct in this test case.In the second and third test cases, it is impossible to reward medals, because at least one medal of each type should be given, but the number of medals should not exceed half of the number of participants.

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; }
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 t = RD!int;
	auto ans = new int[][](t, 3);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto p = RDA!int;
		int[int] cnt;
		foreach (j; 0..n)
		{
			++cnt[p[j]];
		}
		auto keys = cnt.keys;
		keys.sort!"a > b"();
		size_t pos;
		int x;
		foreach (j, key; keys)
		{
			x += cnt[key];
			if (x > n/2)
				break;
			pos = j;
		}

		size_t l;
		ans[i][0] = cnt[keys[0]];
		foreach (j, key; keys[0..pos+1])
		{
			if (j == 0) continue;
			ans[i][1] += cnt[key];
			l = j;
			if (ans[i][1] > ans[i][0])
				break;
		}
		foreach (key; keys[l+1..pos+1])
		{
			ans[i][2] += cnt[key];
		}
		if (!(ans[i][1] > ans[i][0] && ans[i][2] > ans[i][0]))
		{
			ans[i] = [0, 0, 0];
		}
	}

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

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string 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;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	int t = rint;
	foreach(_; 0 .. t){
		int n = rint;
		long[] ps = rlong(n);

		X[] xs;
		long lastp = -1;
		int cnt = 0;
		foreach(p; ps){
			if(lastp >= 0 && lastp != p){
				xs ~= X(lastp, cnt);
				cnt = 0;
			}
			lastp = p;
			cnt += 1;
		}
		xs ~= X(lastp, cnt);

		int total;
		foreach(x; xs) total += x.cnt;

		int g, s, b;
		int sum = g = xs[0].cnt;
		int i = 1;
		for(; i < xs.length; i ++){
			sum += xs[i].cnt;
			if(sum > g * 2){
				s = sum - g;
				break;
			}
		}
		for(i += 1; i < xs.length; i ++){
			sum += xs[i].cnt;
			if(sum * 2 > total){
				b = sum - xs[i].cnt - g - s;
				break;
			}
		}
		if(b <= g) g = 0, s = 0, b = 0;

		writeln(g, " ", s, " ", b);
	}
}
struct X{
	long p;
	int cnt;
}

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

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

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

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

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

        const grp = P.group.array;
        const grpLen = cast(int)(grp.length);
        debug {
          writeln("grp = ", grp);
        }
        auto sum = new int[grpLen + 1];
        foreach (j; 0 .. grpLen) {
          sum[j + 1] = sum[j] + grp[j][1];
        }

        auto ans = new int[3];
        foreach (j; 2 .. grpLen) {
          if (sum[1] - sum[0] < sum[j] - sum[1]) {
            foreach (k; j + 1 .. grpLen + 1) {
              if (sum[1] - sum[0] < sum[k] - sum[j] && 2 * sum[k] <= N) {
                if (ans.sum < sum[k]) {
                  ans = [sum[1] - sum[0], sum[j] - sum[1], sum[k] - sum[j]];
                }
              }
            }
            break;
          }
        }
        writeln(ans[0], " ", ans[1], " ", ans[2]);
      }
    }
  } catch (EOFException e) {
  }
}


You are given an integer $$$n$$$. In $$$1$$$ move, you can do one of the following actions:  erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is "empty");  add one digit to the right. The actions may be performed in any order any number of times.Note that if, after deleting some digit from a number, it will contain leading zeroes, they will not be deleted. E.g. if you delete from the number $$$301$$$ the digit $$$3$$$, the result is the number $$$01$$$ (not $$$1$$$).You need to perform the minimum number of actions to make the number any power of $$$2$$$ (i.e. there's an integer $$$k$$$ ($$$k \ge 0$$$) such that the resulting number is equal to $$$2^k$$$). The resulting number must not have leading zeroes.E.g. consider $$$n=1052$$$. The answer is equal to $$$2$$$. First, let's add to the right one digit $$$4$$$ (the result will be $$$10524$$$). Then let's erase the digit $$$5$$$, so the result will be $$$1024$$$ which is a power of $$$2$$$.E.g. consider $$$n=8888$$$. The answer is equal to $$$3$$$. Let's erase any of the digits $$$8$$$ three times. The result will be $$$8$$$ which is a power of $$$2$$$.

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 consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, output in a separate line one integer $$$m$$$ — the minimum number of moves to transform the number into any power of $$$2$$$.

NoteThe answer for the first test case was considered above.The answer for the second test case was considered above.In the third test case, it's enough to add to the right the digit $$$4$$$ — the number $$$6$$$ will turn into $$$64$$$.In the fourth test case, let's add to the right the digit $$$8$$$ and then erase $$$7$$$ and $$$5$$$ — the taken number will turn into $$$8$$$.The numbers of the fifth and the sixth test cases are already powers of two so there's no need to make any move.In the seventh test case, you can delete first of all the digit $$$3$$$ (the result is $$$01$$$) and then the digit $$$0$$$ (the result is $$$1$$$).

// Cheese-Cracker: cheese-cracker.github.io

dchar[] stringify(ll num){
    dchar[] res;
    while(num > 0){
        res ~= to!dchar('0' + (num % 10));
        num /= 10;
    }
    res.reverse;
    return res;
}

dchar[][] pow2;
void preProcess(){
    ll num = 1;
    for(int i = 0; i <= 62; ++i){
        pow2 ~= stringify(num);
        num *= 2;
    }
}

ll common(dchar[] w, dchar[] p2){
    int ptr = 0;
    foreach(c; w){
        if(p2[ptr] == c){
            ++ptr;
        }
        if(ptr == p2.length.to!long){
            return ptr.to!long;
        }
    }
    return ptr.to!long;
}

void theCode(){
    auto w = scan!(dchar[]);
    ll mindist = 32;
    for(int i = 0; i < 62; ++i){
        ll com = common(w, pow2[i]);
        ll dist = w.length.to!long + pow2[i].length.to!long - 2 * com;
        mindist = min(dist, mindist);
    }
    writeln(mindist);
}

void main(){
    preProcess();
    long tests = scan;        // Toggle!
    while(tests--) theCode();
}

/*********  That's All Folks!  *********/
import std.stdio, std.random, std.functional, std.container, std.algorithm;
import std.numeric, std.range, std.typecons, std.string, std.math, std.conv;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");

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;

size_t solve(string a, string t)
{
  size_t i, j, matched;
  while (i < a.length && j < t.length) {
    if (a[i] == t[j]) {
      i++;
      j++;
      matched++;
    } else {
      i++;
    }
  }
  return a.length - matched + (t.length - j);
}

void main()
{
  string[] pow2list;
  long x = 0;
  while (x < 60) {
    pow2list ~= to!string(1L << x);
    x++;
  }
  long t;
  readf!" %d "(t);
  while (t--) {
    auto a = readln.strip;
    writeln(pow2list.map!(t => solve(a, t)).minElement);
  }
}

// Cheese-Cracker: cheese-cracker.github.io

dchar[] stringify(ll num){
    dchar[] res;
    while(num > 0){
        res ~= to!dchar('0' + (num % 10));
        num /= 10;
    }
    res.reverse;
    return res;
}

dchar[][] pow2;
void preProcess(){
    ll num = 1;
    for(int i = 0; i <= 50; ++i){
        pow2 ~= stringify(num);
        num *= 2;
    }
}

ll common(dchar[] w, dchar[] p2){
    int ptr = 0;
    foreach(c; w){
        if(p2[ptr] == c){
            ++ptr;
        }
        if(ptr == p2.length.to!long){
            return ptr.to!long;
        }
    }
    return ptr.to!long;
}

void theCode(){
    auto w = scan!(dchar[]);
    ll mindist = 32;
    for(int i = 0; i <= 50; ++i){
        ll com = common(w, pow2[i]);
        ll dist = w.length.to!long + pow2[i].length.to!long - 2 * com;
        mindist = min(dist, mindist);
    }
    writeln(mindist);
}

void main(){
    preProcess();
    long tests = scan;        // Toggle!
    while(tests--) theCode();
}

/*********  That's All Folks!  *********/
import std.stdio, std.random, std.functional, std.container, std.algorithm;
import std.numeric, std.range, std.typecons, std.string, std.math, std.conv;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");


You are given a rooted tree consisting of $$$n$$$ vertices. Vertices are numbered from $$$1$$$ to $$$n$$$. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of parents $$$p$$$ containing $$$n$$$ numbers: $$$p_i$$$ is a parent of the vertex with the index $$$i$$$. The parent of a vertex $$$u$$$ is a vertex that is the next vertex on the shortest path from $$$u$$$ to the root. For example, on the simple path from $$$5$$$ to $$$3$$$ (the root), the next vertex would be $$$1$$$, so the parent of $$$5$$$ is $$$1$$$.The root has no parent, so for it, the value of $$$p_i$$$ is $$$i$$$ (the root is the only vertex for which $$$p_i=i$$$).Find such a set of paths that:  each vertex belongs to exactly one path, each path can contain one or more vertices;  in each path each next vertex — is a son of the current vertex (that is, paths always lead down — from parent to son);  number of paths is minimal. For example, if $$$n=5$$$ and $$$p=[3, 1, 3, 3, 1]$$$, then the tree can be divided into three paths:   $$$3 \rightarrow 1 \rightarrow 5$$$ (path of $$$3$$$ vertices),  $$$4$$$ (path of $$$1$$$ vertices).  $$$2$$$ (path of $$$1$$$ vertices).     Example of splitting a root tree into three paths for $$$n=5$$$, the root of the tree — node $$$3$$$.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case consists of two lines. The first of them contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). It is the number of vertices in the tree. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the $$$p$$$ array encodes some rooted tree. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.

For each test case on the first line, output an integer $$$m$$$ — the minimum number of non-intersecting leading down paths that can cover all vertices of the tree. Then print $$$m$$$ pairs of lines containing path descriptions. In the first of them print the length of the path, in the second — the sequence of vertices specifying that path in the order from top to bottom. You can output the paths in any order. If there are several answers, output any of them.

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 p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;

		auto c = new int [n];
		foreach (i; 0..n)
		{
			if (p[i] != i)
			{
				c[p[i]] += 1;
			}
		}

		int [] [] answer;
		auto used = new bool [n];
		foreach (i; 0..n)
		{
			if (c[i] == 0)
			{
				auto t = [i];
				int j = i;
				used[j] = true;
				while (!used[p[j]])
				{
					j = p[j];
					used[j] = true;
					t ~= j;
				}
				answer ~= t;
			}
		}

		writeln (answer.length);
		foreach (ref t; answer)
		{
			writefln !("%s\n%(%s %)")
			    (t.length, t.retro.map !(q{a + 1}));
		}
		writeln;
	}
}


oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array:   Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$.  Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the arrays $$$a$$$ and $$$b$$$, where $$$b$$$ is a permutation of $$$a$$$, determine if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$.

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

For each test case, print "AC" (without quotes) if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$, and "WA" (without quotes) otherwise.

NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.In the third test case, the array $$$[2,1]$$$ has sadness $$$0$$$.In the fourth test case, the array $$$[3,2,3,1]$$$ has sadness $$$1$$$.

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

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

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

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

int N;
int[] A, B;

int[][] graph;
int[] vis;
bool dfs(int u) {
  vis[u] = 1;
  foreach (v; graph[u]) {
    if (vis[v] == 0) {
      if (!dfs(v)) {
        return false;
      }
    } else if (vis[v] == 1) {
      return false;
    }
  }
  vis[u] = 2;
  return true;
}

bool solve() {
  auto xss = new int[][N + 1];
  foreach (i; 0 .. N) {
    xss[A[i]] ~= i;
  }
  auto lens = new int[N + 1];
  foreach (a; 1 .. N + 1) {
    lens[a] = cast(int)(xss[a].length);
  }

  int am;
  foreach (a; 1 .. N + 1) {
    if (lens[am] < lens[a]) {
      am = a;
    }
  }
  debug {
    writeln("am = ", am);
  }

  auto ids = new int[N];
  ids[] = -1;
  foreach (i; 0 .. N) if (B[i] != am) {
    ids[i] = xss[B[i]][--lens[B[i]]];
  }
  debug {
    writeln("ids = ", ids);
  }

  auto used = new bool[N];
  graph = new int[][N + 1];
  foreach (i; 0 .. N) if (A[i] == am) {
    int[] js;
    for (int j = i; ; ) {
      j = ids[j];
      if (j == -1) {
        break;
      }
      js ~= j;
      used[j] = true;
    }
    debug {
      writeln("js = ", js);
      writeln("A js = ", js.map!(j => A[j]));
    }
    const jsLen = cast(int)(js.length);
    foreach (k; 0 .. jsLen - 1) {
      graph[A[js[k]]] ~= A[js[k + 1]];
    }
  }
  foreach (i; 0 .. N) if (A[i] != am) {
    if (!used[i]) {
      return false;
    }
  }

  vis = new int[N + 1];
  foreach (a; 1 .. N + 1) if (vis[a] == 0) {
    if (!dfs(a)) {
      return false;
    }
  }

  return true;
}

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

        const ans = solve;
        writeln(ans ? "AC" : "WA");
      }
    }
  } 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 N;
int[] A, B;

bool solve() {
  auto xss = new int[][N + 1];
  foreach (i; 0 .. N) {
    xss[A[i]] ~= i;
  }
  auto lens = new int[N + 1];
  foreach (a; 1 .. N + 1) {
    lens[a] = cast(int)(xss[a].length);
  }

  int am;
  foreach (a; 1 .. N + 1) {
    if (lens[am] < lens[a]) {
      am = a;
    }
  }
  debug {
    writeln("am = ", am);
  }

  auto ids = new int[N];
  ids[] = -1;
  foreach (i; 0 .. N) if (B[i] != am) {
    ids[i] = xss[B[i]][--lens[B[i]]];
  }
  debug {
    writeln("ids = ", ids);
  }

  auto vis = new bool[N + 1];
  int zeit;
  auto used = new int[N + 1];
  foreach (i; 0 .. N) if (A[i] == am) {
    debug {
      int[] js = [i];
    }
    ++zeit;
    for (int j = i; ; ) {
      j = ids[j];
      debug {
        js ~= j;
      }
      if (j == -1 || A[j] == am) {
        break;
      }
      vis[j] = true;
      if (used[A[j]] == zeit) {
        debug {
          writeln("used ", A[j]);
        }
        return false;
      }
      used[A[j]] = zeit;
    }
    debug {
      writeln("js = ", js);
    }
  }
  foreach (i; 0 .. N) if (A[i] != am) {
    if (!vis[i]) {
      return false;
    }
  }

  return true;
}

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

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


Tired of boring dates, Leha and Noora decided to play a game.Leha found a tree with n vertices numbered from 1 to n. We remind you that tree is an undirected graph without cycles. Each vertex v of a tree has a number av written on it. Quite by accident it turned out that all values written on vertices are distinct and are natural numbers between 1 and n.The game goes in the following way. Noora chooses some vertex u of a tree uniformly at random and passes a move to Leha. Leha, in his turn, chooses (also uniformly at random) some vertex v from remaining vertices of a tree (v ≠ u). As you could guess there are n(n - 1) variants of choosing vertices by players. After that players calculate the value of a function f(u, v) = φ(au·av) · d(u, v) of the chosen vertices where φ(x) is Euler's totient function and d(x, y) is the shortest distance between vertices x and y in a tree.Soon the game became boring for Noora, so Leha decided to defuse the situation and calculate expected value of function f over all variants of choosing vertices u and v, hoping of at least somehow surprise the girl.Leha asks for your help in calculating this expected value. Let this value be representable in the form of an irreducible fraction . To further surprise Noora, he wants to name her the value . Help Leha!

The first line of input contains one integer number n (2 ≤ n ≤ 2·105)  — number of vertices in a tree. The second line contains n different numbers a1, a2, ..., an (1 ≤ ai ≤ n) separated by spaces, denoting the values written on a tree vertices. Each of the next n - 1 lines contains two integer numbers x and y (1 ≤ x, y ≤ n), describing the next edge of a tree. It is guaranteed that this set of edges describes a tree.

In a single line print a number equal to P·Q - 1 modulo 109 + 7.

NoteEuler's totient function φ(n) is the number of such i that 1 ≤ i ≤ n,and gcd(i, n) = 1, where gcd(x, y) is the greatest common divisor of numbers x and y.There are 6 variants of choosing vertices by Leha and Noora in the first testcase:  u = 1, v = 2, f(1, 2) = φ(a1·a2)·d(1, 2) = φ(1·2)·1 = φ(2) = 1  u = 2, v = 1, f(2, 1) = f(1, 2) = 1  u = 1, v = 3, f(1, 3) = φ(a1·a3)·d(1, 3) = φ(1·3)·2 = 2φ(3) = 4  u = 3, v = 1, f(3, 1) = f(1, 3) = 4  u = 2, v = 3, f(2, 3) = φ(a2·a3)·d(2, 3) = φ(2·3)·1 = φ(6) = 2  u = 3, v = 2, f(3, 2) = f(2, 3) = 2 Expected value equals to . The value Leha wants to name Noora is 7·3 - 1 = 7·333333336 = 333333338 .In the second testcase expected value equals to , so Leha will have to surprise Hoora by number 8·1 - 1 = 8 .

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

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

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

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

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

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

int N;
int[] A, B;

int[] lpf, phi;
Mint[] inv, weights;

int[][] G;
int[] par, dep;
int[] seq, poss;
int zeit;
int[] dis, fin;

void dfs(int u, int p) {
  par[u] = p;
  dep[u] = (p == -1) ? 0 : (dep[p] + 1);
  poss[u] = cast(int)(seq.length);
  seq ~= u;
  dis[u] = zeit++;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
      seq ~= u;
    }
  }
  fin[u] = zeit++;
}

int shallower(int u, int v) {
  return (dep[u] <= dep[v]) ? u : v;
}

int[][] mn;

int lca(int u, int v) {
  int a = poss[u], b = poss[v];
  if (a > b) {
    swap(a, b);
  }
  const e = bsr(b - a + 1);
  const l = shallower(mn[e][a], mn[e][b - (1 << e) + 1]);
  debug {
    // writeln("lca ", u, " ", v, " = ", l);
  }
  return l;
}

void main() {

  try {
    for (; ; ) {
      N = readInt();
      auto perm = new int[N + 1];
      foreach (i; 1 .. N + 1) {
        perm[i] = readInt();
      }
      A = new int[N - 1];
      B = new int[N - 1];
      foreach (i; 0 .. N - 1) {
        A[i] = perm[readInt()];
        B[i] = perm[readInt()];
      }
      debug {
        writeln("A = ", A);
        writeln("B = ", B);
      }

      lpf = iota(N + 1).array;
      phi = iota(N + 1).array;
      foreach (p; 2 .. N + 1) {
        if (lpf[p] == p) {
          for (int n = p; n <= N; n += p) {
            chmin(lpf[n], p);
            phi[n] = phi[n] / p * (p - 1);
          }
        }
      }
      inv = new Mint[N + 1];
      inv[1] = 1;
      foreach (n; 2 .. N + 1) {
        inv[n] = -(MO / n) * inv[cast(int)(MO % n)];
      }
      weights = new Mint[N + 1];
      weights[1] = 1;
      foreach (n; 2 .. N + 1) {
        const p = lpf[n];
        weights[n] = (n / p % p == 0) ? Mint(0) : (inv[p - 1] * weights[n / p]);
      }

      G = new int[][N + 1];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      par = new int[N + 1];
      dep = new int[N + 1];
      seq = [];
      poss = new int[N + 1];
      zeit = 0;
      dis = new int[N + 1];
      fin = new int[N + 1];
      dfs(1, -1);
      debug {
        writeln("par = ", par);
        writeln("dep = ", dep);
        writeln("seq = ", seq);
        writeln("poss = ", poss);
        writeln("dis = ", dis);
        writeln("fin = ", fin);
      }

      const seqLen = cast(int)(seq.length);
      const E = bsr(seqLen) + 1;
      mn = new int[][](E, seqLen);
      mn[0][] = seq[];
      foreach (e; 0 .. E - 1) {
        mn[e + 1][] = mn[e][];
        foreach (x; 0 .. seqLen - (1 << e)) {
          mn[e + 1][x] = shallower(mn[e][x], mn[e][x + (1 << e)]);
        }
      }
      debug {
        writeln("mn = ", mn);
        foreach (u; 1 .. N + 1) foreach (v; 1 .. N + 1) {
          lca(u, v);
        }
      }

      Mint ans;

      foreach (k; 1 .. N / 2 + 1) {
        if (weights[k]) {
          debug {
            writefln("**** k = %s ****", k);
          }
          int n = N / k;
          auto us = new int[n];
          foreach (x; 0 .. n) {
            us[x] = k * (1 + x);
          }
          us.sort!((u, v) => (dis[u] < dis[v]));
          debug {
            writeln("us = ", us);
          }
          us.length += n - 1;
          foreach (x; 0 .. n - 1) {
            us[n + x] = lca(us[x], us[x + 1]);
          }
          us.sort!((u, v) => (dis[u] < dis[v]));
          us = us.uniq.array;
          n = cast(int)(us.length);
          debug {
            writeln("us = ", us);
          }
          auto pp = new int[n];
          pp[0] = -1;
          int stackLen;
          auto stack = new int[n];
          stack[stackLen++] = 0;
          foreach (x; 1 .. n) {
            for (; fin[us[stack[stackLen - 1]]] < dis[us[x]]; --stackLen) {}
            pp[x] = stack[stackLen - 1];
            stack[stackLen++] = x;
          }
          debug {
            writeln("pp = ", pp);
          }
          auto graph = new int[][n];
          foreach (x; 1 .. n) {
            graph[pp[x]] ~= x;
          }
          Mint tot;
          foreach (x; 0 .. n) {
            if (us[x] % k == 0) {
              tot += phi[us[x]];
            }
          }
          Mint score;
          Mint dfs(int x) {
            Mint sum;
            foreach (y; graph[x]) {
              const res = dfs(y);
              score += (tot - res) * res * abs(dep[us[x]] - dep[us[y]]);
              sum += res;
            }
            if (us[x] % k == 0) {
              sum += phi[us[x]];
            }
            return sum;
          }
          dfs(0);
          debug {
            writeln("score = ", score);
          }
          ans += weights[k] * score;
        }
      }

      ans /= 1L * N * (N - 1) / 2;
      writeln(ans);

      debug {
        long brtPhi(long n) {
          long ret = n;
          for (long p = 2; p^^2 <= n; ++p) {
            if (n % p == 0) {
              do {
                n /= p;
              } while (n % p == 0);
              ret = ret / p * (p - 1);
            }
          }
          if (n > 1) {
            ret = ret / n * (n - 1);
          }
          return ret;
        }
        auto d = new int[][](N + 1, N + 1);
        foreach (u; 1 .. N + 1) {
          d[u][] = N;
          d[u][u] = 0;
        }
        foreach (i; 0 .. N - 1) {
          d[A[i]][B[i]] = d[B[i]][A[i]] = 1;
        }
        foreach (w; 1 .. N + 1) foreach (u; 1 .. N + 1) foreach (v; 1 .. N + 1) {
          chmin(d[u][v], d[u][w] + d[w][v]);
        }
        Mint brt;
        foreach (u; 1 .. N + 1) foreach (v; u + 1 .. N + 1) {
          brt += brtPhi(1L * u * v) * d[u][v];
        }
        writefln("brt = %s / NC2 = %s", brt, brt / (1L * N * (N - 1) / 2));

        Mint slw;
        foreach (k; 1 .. N + 1) {
          Mint sum;
          for (int u = k; u <= N; u += k) for (int v = u + k; v <= N; v += k) {
            sum += phi[u] * phi[v] * d[u][v];
          }
          writeln(k, ": ", sum);
          slw += weights[k] * sum;
        }
        writefln("slw = %s / NC2 = %s", slw, slw / (1L * N * (N - 1) / 2));
      }
    }
  } catch (EOFException e) {
  }
}


A positive number $$$x$$$ of length $$$n$$$ in base $$$p$$$ ($$$2 \le p \le 10^9$$$) is written on the blackboard. The number $$$x$$$ is given as a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < p$$$) — the digits of $$$x$$$ in order from left to right (most significant to least significant).Dmitry is very fond of all the digits of this number system, so he wants to see each of them at least once.In one operation, he can:   take any number $$$x$$$ written on the board, increase it by $$$1$$$, and write the new value $$$x + 1$$$ on the board. For example, $$$p=5$$$ and $$$x=234_5$$$.  Initially, the board contains the digits $$$2$$$, $$$3$$$ and $$$4$$$;  Dmitry increases the number $$$234_5$$$ by $$$1$$$ and writes down the number $$$240_5$$$. On the board there are digits $$$0, 2, 3, 4$$$;  Dmitry increases the number $$$240_5$$$ by $$$1$$$ and writes down the number $$$241_5$$$. Now the board contains all the digits from $$$0$$$ to $$$4$$$. Your task is to determine the minimum number of operations required to make all the digits from $$$0$$$ to $$$p-1$$$ appear on the board at least once.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^3$$$) — the number of test cases. The descriptions of the input test cases follow. The first line of description of each test case contains two integers $$$n$$$ ($$$1 \le n \le 100$$$) and $$$p$$$ ($$$2 \le p \le 10^9$$$) — the length of the number and the base of the number system. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < p$$$) — digits of $$$x$$$ in number system with base $$$p$$$ It is guaranteed that the number $$$x$$$ does not contain leading zeros (that is, $$$a_1>0$$$).

For each test case print a single integer — the minimum number of operations required for Dmitry to get all the digits on the board from $$$0$$$ to $$$p-1$$$. It can be shown that this always requires a finite number of operations.

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

int solve (int n, int p, int [] a)
{
	bool [int] vis;
	foreach (ref c; a)
	{
		vis[c] = true;
	}

	if (vis.length == p)
	{
		return 0;
	}

	int me = a.back;
	int hi = p - 1;
	while (hi in vis)
	{
		hi -= 1;
	}
	int lo = me;
	while (lo in vis)
	{
		lo -= 1;
	}

	if (lo < 0) // no carry needed
	{
		return hi - me;
	}

	int res = p - me;
	int pos = n - 1;
	a[pos] = p - 1;
	while (pos >= 0)
	{
		a[pos] += 1;
		vis[a[pos]] = true;
		if (a[pos] < p)
		{
			break;
		}
		a[pos] = 0;
		pos -= 1;
	}
	if (pos < 0)
	{
		vis[1] = true;
	}
	lo = me;
	while (lo in vis)
	{
		lo -= 1;
	}
	if (lo != -1)
	{
		res += lo;
	}
	return res;
}

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


Recently Vasya learned that, given two points with different $$$x$$$ coordinates, you can draw through them exactly one parabola with equation of type $$$y = x^2 + bx + c$$$, where $$$b$$$ and $$$c$$$ are reals. Let's call such a parabola an $$$U$$$-shaped one.Vasya drew several distinct points with integer coordinates on a plane and then drew an $$$U$$$-shaped parabola through each pair of the points that have different $$$x$$$ coordinates. The picture became somewhat messy, but Vasya still wants to count how many of the parabolas drawn don't have any drawn point inside their internal area. Help Vasya.The internal area of an $$$U$$$-shaped parabola is the part of the plane that lies strictly above the parabola when the $$$y$$$ axis is directed upwards.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of points. The next $$$n$$$ lines describe the points, the $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ — the coordinates of the $$$i$$$-th point. It is guaranteed that all points are distinct and that the coordinates do not exceed $$$10^6$$$ by absolute value.

In the only line print a single integer — the number of $$$U$$$-shaped parabolas that pass through at least two of the given points and do not contain any of the given points inside their internal area (excluding the parabola itself).

NoteOn the pictures below all $$$U$$$-shaped parabolas that pass through at least two given points are drawn for each of the examples. The $$$U$$$-shaped parabolas that do not have any given point inside their internal area are drawn in red.   The first example.   The second example.

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

immutable real eps = 1E-17;

alias Point = Tuple !(long, q{x}, long, q{y});

bool higher (ref Point u, ref Point v, ref Point w)
{
	auto x1 = u.x;
	auto y1 = u.y;
	auto x2 = w.x;
	auto y2 = w.y;
/*
	auto bNum = y1 - y2 - x1 ^^ 2 + y2 ^^ 2;
	auto bDen = x1 - x2;
	auto cNum = x1 * y2 - y1 * x2 + x1 * x2 * (x1 - x2);
	auto cDen = x1 - x2;
*/
	real b = real (y1 - y2) / real (x1 - x2) - (x1 + x2);
	real c = y1 - x1 * real (x1 + b);

	real xm = v.x;
	real ym = v.y;
	real yp = xm * real (xm + b) + c;
	return ym - yp <= eps * (abs (ym) + abs (yp) + 1.0);
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new Point [n];
		foreach (ref c; p)
		{
			readf (" %s %s", &c.x, &c.y);
		}
		sort (p);

		Point [] temp;
		foreach (i; 0..n)
		{
			if (i == n - 1 || p[i + 1].x > p[i].x)
			{
				temp ~= p[i];
			}
		}
		p = temp;
		n = p.length.to !(int);

		if (n < 2)
		{
			writeln (0);
			continue;
		}

		Point [] s;
		s ~= p[0];
		s ~= p[1];
		foreach (i; 2..n)
		{
			debug {writeln (s);}
			while (s.length > 1 &&
			    higher (s[$ - 2], s[$ - 1], p[i]))
			{
				s.popBack ();
				s.assumeSafeAppend ();
			}
			if (s.length == 1 ||
			    higher (s[$ - 2], p[i], s[$ - 1]))
			{
				s ~= p[i];
			}
		}
		debug {writeln (s);}
		writeln (s.length - 1);
	}
}

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

immutable real eps = 1E-17;

alias Point = Tuple !(long, q{x}, long, q{y});

bool higher (ref Point u, ref Point v, ref Point w)
{
	auto x1 = u.x;
	auto y1 = u.y;
	auto x2 = w.x;
	auto y2 = w.y;
/*
	auto bNum = y1 - y2 - x1 ^^ 2 + y2 ^^ 2;
	auto bDen = x1 - x2;
	auto cNum = x1 * y2 - y1 * x2 + x1 * x2 * (x1 - x2);
	auto cDen = x1 - x2;
*/
	real b = real (y1 - y2) / real (x1 - x2) - (x1 + x2);
	real c = y1 - x1 * real (x1 + b);

	real xm = v.x;
	real ym = v.y;
	real yp = xm * real (xm + b) + c;
	return ym - yp <= eps * (abs (ym) + abs (yp) + 1.0);
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new Point [n];
		foreach (ref c; p)
		{
			readf (" %s %s", &c.x, &c.y);
		}
		sort (p);

		Point [] temp;
		foreach (i; 0..n)
		{
			if (i == n - 1 || p[i + 1].x > p[i].x)
			{
				temp ~= p[i];
			}
		}
		p = temp;
		n = p.length.to !(int);

		if (n < 2)
		{
			writeln (0);
			continue;
		}

		Point [] s;
		s ~= p[0];
		s ~= p[1];
		foreach (i; 2..n)
		{
			debug {writeln (s);}
			while (s.length > 1 &&
			    higher (s[$ - 2], s[$ - 1], p[i]))
			{
				s.popBack ();
				s.assumeSafeAppend ();
			}
			if (s.length == 1 ||
			    !higher (s[$ - 2], s[$ - 1], p[i]))
			{
				s ~= p[$ - 1];
			}
		}
		debug {writeln (s);}
		writeln (s.length - 1);
	}
}


Let's define radix sum of number $$$a$$$ consisting of digits $$$a_1, \ldots ,a_k$$$ and number $$$b$$$ consisting of digits $$$b_1, \ldots ,b_k$$$(we add leading zeroes to the shorter number to match longer length) as number $$$s(a,b)$$$ consisting of digits $$$(a_1+b_1)\mod 10, \ldots ,(a_k+b_k)\mod 10$$$. The radix sum of several integers is defined as follows: $$$s(t_1, \ldots ,t_n)=s(t_1,s(t_2, \ldots ,t_n))$$$You are given an array $$$x_1, \ldots ,x_n$$$. The task is to compute for each integer $$$i (0 \le i < n)$$$ number of ways to consequently choose one of the integers from the array $$$n$$$ times, so that the radix sum of these integers is equal to $$$i$$$. Calculate these values modulo $$$2^{58}$$$.

The first line contains integer $$$n$$$ — the length of the array($$$1 \leq n \leq 100000$$$). The second line contains $$$n$$$ integers $$$x_1, \ldots x_n$$$ — array elements($$$0 \leq x_i < 100000$$$).

Output $$$n$$$ integers $$$y_0, \ldots, y_{n-1}$$$ — $$$y_i$$$ should be equal to corresponding number of ways modulo $$$2^{58}$$$.

NoteIn the first example there exist sequences: sequence $$$(5,5)$$$ with radix sum $$$0$$$, sequence $$$(5,6)$$$ with radix sum $$$1$$$, sequence $$$(6,5)$$$ with radix sum $$$1$$$, sequence $$$(6,6)$$$ with radix sum $$$2$$$.

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

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

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

int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = cast(int)(as.length); for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a < val)); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a <= val)); }

// a^-1 (mod 2^64)
long modInv(long a)
in {
  assert(a & 1, "modInv: a must be odd");
}
do {
  long b = ((a << 1) + a) ^ 2;
  b *= 2 - a * b;
  b *= 2 - a * b;
  b *= 2 - a * b;
  b *= 2 - a * b;
  return b;
}

enum L = 10;
enum H = 5;
enum MO = 2L^^58;

alias Z = Tuple!(long, long, long, long);

Z add(in Z a, in Z b) {
  return Z(a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]);
}

// 1 - X + X^2 - X^3 + X^4
Z mul(in Z a, in Z b) {
  Z c = Z(
    a[0] * b[0],
    a[0] * b[1] + a[1] * b[0],
    a[0] * b[2] + a[1] * b[1] + a[2] * b[0],
    a[0] * b[3] + a[1] * b[2] + a[2] * b[1] + a[3] * b[0],
  );
  long c4 = a[1] * b[3] + a[2] * b[2] + a[3] * b[1];
  long c5 = a[2] * b[3] + a[3] * b[2];
  long c6 = a[3] * b[3];
  c[2] -= c6; c[3] += c6; c4 -= c6; c5 += c6;
  c[1] -= c5; c[2] += c5; c[3] -= c5; c4 += c5;
  c[0] -= c4; c[1] += c4; c[2] -= c4; c[3] += c4;
  return c;
}

void main() {
  Z[] G = new Z[L + 1];
  G[0] = Z(1, 0, 0, 0);
  G[1] = Z(0, 1, 0, 0);
  foreach (i; 1 .. L + 1) {
    G[i] = mul(G[i - 1], G[1]);
  }
  debug {
    foreach (i; 0 .. L + 1) {
      writefln("G[%s] = %s", i, G[i]);
    }
  }

  try {
    for (; ; ) {
      const N = readInt();
      auto X = new int[N];
      foreach (n; 0 .. N) {
        X[n] = readInt();
      }
      Z[] a = new Z[L^^H];
      foreach (n; 0 .. N) {
        ++a[X[n]][0];
      }
      foreach (h; 0 .. H) {
        foreach (i; 0 .. L^^H) {
          if (i / L^^h % L == 0) {
            Z[] x = new Z[L];
            foreach (j; 0 .. L) {
              x[j] = a[i + L^^h * j];
            }
            Z[] y = new Z[L];
            foreach (j; 0 .. L) foreach (k; 0 .. L) {
              y[k] = add(y[k], mul(G[(j * k) % L], x[j]));
            }
            foreach (j; 0 .. L) {
              a[i + L^^h * j] = y[j];
            }
          }
        }
      }
      foreach (i; 0 .. L^^H) {
        Z b = a[i];
        a[i] = Z(1, 0, 0, 0);
        for (int e = N; e; e >>= 1) {
          if (e & 1) {
            a[i] = mul(a[i], b);
          }
          b = mul(b, b);
        }
      }
      foreach_reverse (h; 0 .. H) {
        foreach (i; 0 .. L^^H) {
          if (i / L^^h % L == 0) {
            Z[] x = new Z[L];
            foreach (j; 0 .. L) {
              x[j] = a[i + L^^h * j];
            }
            Z[] y = new Z[L];
            foreach (j; 0 .. L) foreach (k; 0 .. L) {
              y[k] = add(y[k], mul(G[L - (j * k) % L], x[j]));
            }
            foreach (j; 0 .. L) {
              a[i + L^^h * j] = y[j];
            }
          }
        }
      }
      foreach (n; 0 .. N) {
        assert(a[n][1] == 0);
        assert(a[n][2] == 0);
        assert(a[n][3] == 0);
        long ans = a[n][0];
        // ans /= L^H
        ans *= modInv(5^^H);
        assert(ans % 2^^H == 0);
        ans /= 2^^H;
        ans = (ans % MO + MO) % MO;
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.Each mole i has a home placed at the position (ai, bi). Moving this mole one time means rotating his position point (xi, yi) 90 degrees counter-clockwise around it's home point (ai, bi).A regiment is compact only if the position points of the 4 moles form a square with non-zero area.Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.

The first line contains one integer n (1 ≤ n ≤ 100), the number of regiments. The next 4n lines contain 4 integers xi, yi, ai, bi ( - 104 ≤ xi, yi, ai, bi ≤ 104).

Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print "-1" (without quotes).

NoteIn the first regiment we can move once the second or the third mole.We can't make the second regiment compact.In the third regiment, from the last 3 moles we can move once one and twice another one.In the fourth regiment, we can move twice the first mole and once the third mole.

import std.stdio;
import std.exception;
import std.container;

const dx = [1, 0, -1, 0];
const dy = [0, 1, 0, -1];

struct state {
	int dir[4];
};

ref int at(int[] d, state s) {
	int idx = 0;
	foreach (i; 0..4)
		idx = idx * 4 + s.dir[i];
	return d[idx];
}

bool isRect(int[] xs, int[] ys) {
	foreach (i; 1..4)
		foreach (j; 1..i) {
			int dx1 = xs[i] - xs[0], dy1 = ys[i] - ys[0];
			int dx2 = xs[j] - xs[0], dy2 = ys[j] - ys[0];
			if ((dx1 != -dy2 || dy1 != dx2) &&
				(dx1 != dy2 || dy1 != -dx2))
					continue;
			if (dx1 == 0 && dy1 == 0) continue;
			int needX = xs[0] + dx1 + dx2;
			int needY = ys[0] + dy1 + dy2;
			foreach (t; 1..4) {
				if (i == t || j == t)
					continue;
				if (xs[t] == needX && ys[t] == needY)
					return true;
			}
		}
	return false;
}

void solve() {
	int[4] dxs, dys, xs, ys;
	foreach (i; 0..4) {
		int curx, cury;
		enforce(readf(" %s %s %s %s", &curx, &cury, &xs[i], &ys[i]));
		dxs[i] = curx - xs[i];
		dys[i] = cury - ys[i];
	}
	bool ok(state s) {
		int[4] curx, cury;
		//writeln("CHECK");
		foreach (i; 0..4) {
			curx[i] = xs[i] + dx[s.dir[i]] * dxs[i] - dy[s.dir[i]] * dys[i];
			cury[i] = ys[i] + dy[s.dir[i]] * dxs[i] + dx[s.dir[i]] * dys[i];
			//writeln(curx[i], ' ', cury[i]);
		}
		return isRect(curx, cury);
	}
	auto d = new int[4 ^^ 4];
	d[] = -1;
	d.at(state.init) = 0;
	auto q = DList!state();
	q.insertBack(state.init);
	while (!q.empty) {
		state v = q.front;
		q.removeFront;
		if (ok(v)) {
			writeln(d.at(v));
			return;
		}
		foreach (i; 0..4) {
			state nv = v;
			nv.dir[i]++;
			nv.dir[i] %= 4;
			if (d.at(nv) == -1) {
				d.at(nv) = d.at(v) + 1;
				q.insertBack(nv);
			}
		}
	}
	writeln(-1);
}

void main() {
	size_t n;
	enforce(readf(" %s", &n) == 1);
	foreach (_; 0..n)
		solve();
}


You are given an undirected graph, constisting of n vertices and m edges. Each edge of the graph has some non-negative integer written on it.Let's call a triple (u, v, s) interesting, if 1 ≤ u < v ≤ n and there is a path (possibly non-simple, i.e. it can visit the same vertices and edges multiple times) between vertices u and v such that xor of all numbers written on the edges of this path is equal to s. When we compute the value s for some path, each edge is counted in xor as many times, as it appear on this path. It's not hard to prove that there are finite number of such triples.Calculate the sum over modulo 109 + 7 of the values of s over all interesting triples.

The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 0 ≤ m ≤ 200 000) — numbers of vertices and edges in the given graph. The follow m lines contain three integers ui, vi and ti (1 ≤ ui, vi ≤ n, 0 ≤ ti ≤ 1018, ui ≠ vi) — vertices connected by the edge and integer written on it. It is guaranteed that graph doesn't contain self-loops and multiple edges.

Print the single integer, equal to the described sum over modulo 109 + 7.

NoteIn the first example the are 6 interesting triples:   (1, 2, 1)  (1, 3, 2)  (1, 4, 3)  (2, 3, 3)  (2, 4, 2)  (3, 4, 1)  The sum is equal to 1 + 2 + 3 + 3 + 2 + 1 = 12.In the second example the are 12 interesting triples:   (1, 2, 1)  (2, 3, 2)  (1, 3, 3)  (3, 4, 4)  (2, 4, 6)  (1, 4, 7)  (1, 4, 8)  (2, 4, 9)  (3, 4, 11)  (1, 3, 12)  (2, 3, 13)  (1, 2, 14)  The sum is equal to 1 + 2 + 3 + 4 + 6 + 7 + 8 + 9 + 11 + 12 + 13 + 14 = 90.

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

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

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

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

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

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

enum E = 60;
enum LIM = 300_010;

int N, M;
int[] U, V;
long[] T;

int[][] G;
int[] dep;
long[] pot;
int[] us;
long[] cycs;

void dfs(int u, int p) {
  dep[u] = (p == -1) ? 0 : (dep[p] + 1);
  us ~= u;
  foreach (i; G[u]) {
    const v = U[i] ^ V[i] ^ u;
    if (v != p) {
      if (dep[v] == -1) {
        pot[v] = pot[u] ^ T[i];
        dfs(v, u);
      } else if (dep[v] < dep[u]) {
        cycs ~= pot[u] ^ pot[v] ^ T[i];
      }
    }
  }
}

void main() {
  auto two = new Mint[LIM];
  two[0] = 1;
  foreach (i; 1 .. LIM) {
    two[i] = two[i - 1] * 2;
  }

  try {
    for (; ; ) {
      N = readInt();
      M = readInt();
      U = new int[M];
      V = new int[M];
      T = new long[M];
      foreach (i; 0 .. M) {
        U[i] = readInt() - 1;
        V[i] = readInt() - 1;
        T[i] = readLong();
      }

      G = new int[][N];
      foreach (i; 0 .. M) {
        G[U[i]] ~= i;
        G[V[i]] ~= i;
      }
      dep = new int[N];
      dep[] = -1;
      pot = new long[N];

      Mint ans;
      foreach (r; 0 .. N) {
        if (dep[r] == -1) {
          us = [];
          cycs = [];
          dfs(r, -1);
          long[] bases;
          foreach (cyc; cycs) {
            long x = cyc;
            foreach (base; bases) {
              chmin(x, x ^ base);
            }
            if (x) {
              bases ~= x;
            }
          }
          debug {
            writeln("us = ", us);
            writeln("pot = ", pot);
            writeln("cycs = ", cycs);
            writeln("bases = ", bases);
          }
          foreach (e; 0 .. E) {
            long[2] cntP, cntB;
            foreach (u; us) {
              ++cntP[(pot[u] >> e) & 1];
            }
            foreach (base; bases) {
              ++cntB[(base >> e) & 1];
            }
            Mint[2] numP, numB;
            numP[1] = cntP[0] * cntP[1];
            numP[0] = (cntP[0] + cntP[1]) * (cntP[0] + cntP[1] - 1) / 2 - numP[1];
            if (cntB[1] == 0) {
              numB[0] = two[cast(int)(cntB[0])];
              numB[1] = 0;
            } else {
              numB[0] = numB[1] = two[cast(int)(cntB[0] + cntB[1] - 1)];
            }
            debug {
              if (e <= 4) {
                writeln("e = ", e);
                writeln("  cntP = ", cntP, ", numP = ", numP);
                writeln("  cntB = ", cntB, ", numB = ", numB);
              }
            }
            ans += two[e] * (numP[0] * numB[1] + numP[1] * numB[0]);
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}