There are $$$n$$$ heaps of stone. The $$$i$$$-th heap has $$$h_i$$$ stones. You want to change the number of stones in the heap by performing the following process once:   You go through the heaps from the $$$3$$$-rd heap to the $$$n$$$-th heap, in this order.  Let $$$i$$$ be the number of the current heap.  You can choose a number $$$d$$$ ($$$0 \le 3 \cdot d \le h_i$$$), move $$$d$$$ stones from the $$$i$$$-th heap to the $$$(i - 1)$$$-th heap, and $$$2 \cdot d$$$ stones from the $$$i$$$-th heap to the $$$(i - 2)$$$-th heap.  So after that $$$h_i$$$ is decreased by $$$3 \cdot d$$$, $$$h_{i - 1}$$$ is increased by $$$d$$$, and $$$h_{i - 2}$$$ is increased by $$$2 \cdot d$$$.  You can choose different or same $$$d$$$ for different operations. Some heaps may become empty, but they still count as heaps. What is the maximum number of stones in the smallest heap after the process?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$). The second lines of each test case contains $$$n$$$ integers $$$h_1, h_2, h_3, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the maximum number of stones that the smallest heap can contain.

NoteIn the first test case, the initial heap sizes are $$$[1, 2, 10, 100]$$$. We can move the stones as follows.   move $$$3$$$ stones and $$$6$$$ from the $$$3$$$-rd heap to the $$$2$$$-nd and $$$1$$$ heap respectively. The heap sizes will be $$$[7, 5, 1, 100]$$$;  move $$$6$$$ stones and $$$12$$$ stones from the last heap to the $$$3$$$-rd and $$$2$$$-nd heap respectively. The heap sizes will be $$$[7, 17, 7, 82]$$$. In the second test case, the last heap is $$$1$$$, and we can not increase its size.In the third test case, it is better not to move any stones.In the last test case, the final achievable configuration of the heaps can be $$$[3, 5, 3, 4, 3, 3]$$$.

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 euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
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); }

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 n = RD!int;
		auto h = RDA;

		bool f(long x)
		{
			auto hh = h.dup;
			foreach_reverse (i; 2..n)
			{
				if (hh[i] < x) return false;
				auto rem = hh[i] - x;
				auto d = min(rem / 3, h[i] / 3);
				hh[i-1] += d;
				hh[i-2] += d*2;
			}
			return (hh[0] >= x) && (hh[1] >= x);
		}
		ans[ti] = binarySearch!(f)(0, 10L^^10);
	}

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

import std.algorithm, std.range, std.stdio, std.numeric, std.array, std.exception,
       std.container, std.typecons, std.conv, std.random, std.bigint;

void read(S...)(ref S args) {
  auto input = readln.split;
  enforce(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

bool possible(long[] arr, long answer) {
  auto original = arr.dup;

  foreach_reverse(i; 2 .. arr.length) {
    if (arr[i] < answer) return false;
    long d = min(arr[i] - answer, original[i]) / 3;
    arr[i - 1] += d;
    arr[i - 2] += 2 * d;
  }

  return arr[0] >= answer && arr[1] >= answer;
}

void main() {
  int T;
  read(T);

  while (T--) {
    int n;
    read(n);
    auto arr = list!long;
    long low = 0, high = int.max;

    while (high != low) {
      long mid = (high + low) / 2;
      if (mid == low) mid = high;

      if (possible(arr.dup, mid)) low = mid;
      else high = mid - 1;
    }

    writeln(low);
  }
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void solve() {
    int N = read!int;
    auto H = readarray!int;

    bool C(int x) {
        auto G = H.dup;
        for (int i = N - 1; i >= 2; i--) {
            if (G[i] < x) return false;
            int d = min(H[i] / 3, (G[i] - x) / 3);
            G[i - 1] += d;
            G[i - 2] += 2*d;
        }
        if (G[0] < x || G[1] < x) return false;
        return true;
    }
    int lb = 0, ub = 1_000_000_001;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (C(mid) ? lb : ub) = mid;
    }
    writeln(lb);
}

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

void main() { runSolver(); }

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

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

      bool isOK(long x) {
        auto a = A.dup;
        foreach_reverse(int i; 2..N) {
          const d = max(0, min(A[i], a[i] - x) / 3);
          a[i - 2] += d * 2;
          a[i - 1] += d;
          a[i] -= d * 3;
        }

        // deb(x, a);
        return a.all!(z => z >= x);
      }

      return binarySearch(&isOK, 1, 10L^^9 + 2);
    }

    foreach(_; 0..QN) subSolve().writeln;
  }

  outputForAtCoder(&solve);
}

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

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

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

// 提出解
void solve(){
	foreach(_; 0 .. scan!int){
		int n = scan!int;
		long[] hs = scan!long(n);

		bool isOK(long k){
			log("k:", k);
			long[] us = hs.dup;
			foreach_reverse(i; 2 .. n){
				if(us[i] <= k) continue;
				long d = min(hs[i], us[i] - k) / 3;
				us[i - 2] += d * 2, us[i - 1] += d, us[i] -= d * 3;
				log("i:", i, "d:", d, "us:", us);
			}
			log("us:", us);
			foreach(u; us) if(u < k) return 0;
			log("k:", k, "-> OK");
			return 1;
		}

		long high = hs.reduce!max + 1;
		long ans = mid(0, high, &isOK) - 1;

		ans.print;

	}
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// 愚直解
void jury(){
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// テストケース
void gen(){
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// テンプレ
import std;
bool DEBUG = 0;
void main(string[] args){
	if(args.canFind("-debug")) DEBUG = 1;
	if(args.canFind("-gen")) gen; else if(args.canFind("-jury")) jury; else solve;
}
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); }
void print(T)(T t){ writeln(t); }
void print(T, A ...)(T t, A a){ stdout.write(t, " "), print(a); }
string unsplit(T)(T xs, string d = " "){ return xs.array.to!(string[]).join(d); }
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)(int n){ return n.iota.map!(i => scan!T()).array; }
T mini(T)(ref T x, T y){ if(x > y) x = y; return x; }
T maxi(T)(ref T x, T y){ if(x < y) x = y; return x; }
T mid(T)(T l, T r, bool delegate(T) f){
	T m = (l + r) / 2; (f(m)? l: r) = m; return f(l)? f(r - 1)? r: mid(l, r, f): l;
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// ライブラリ（基本）

class UnionFind{
	this(int n){ foreach(i; 0 .. n) R ~= i, K ~= [i]; } int[] R; int[][] K;
	void unite(int a, int b){
		int ra = R[a], rb = R[b]; if(ra == rb) return;
		if(K[ra].length < K[rb].length) unite(b, a);
		else foreach(k; K[rb]) R[k] = ra, K[ra] ~= k;
	}
	int find(int a){ return R[a]; }
	int getSize(int a){ return K[R[a]].length.to!int; }
}
class Queue(T){
	private T[] xs; private uint i, j;
	this(T[] xs = []){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){ while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1; xs[j ++] = x; }
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	void flush(){ i = j; }
	alias empty = isEmpty, front = peek, popFront = deq, pop = deq, push = enq, top = peek;
	Queue opOpAssign(string op)(T x) if(op == "~"){ enq(x); return this; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}
class Stack(T){
	private T[] xs; private uint j;
	this(T[] xs = []){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j; }
	bool isEmpty(){ return j == 0; }
	void push(T x){ while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1; xs[j ++] = x; }
	T pop(){ assert(j > 0); return xs[-- j]; }
	T peek(){ assert(j > 0); return xs[j - 1]; }
	void clear(){ j = 0; }
	alias empty = isEmpty, front = peek, popFront = pop, top = peek;
	Stack opOpAssign(string op)(T x) if(op == "~"){ push(x); return this; }
	T opIndex(uint li){ assert(j > 0 && j - 1 >= li); return xs[j - 1 - li]; }
	static Stack!T opCall(T[] xs = []){ return new Stack!T(xs); }
	T[] array(){ return xs[0 .. j]; }
	override string toString(){ return array.to!string; }
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// ライブラリ（追加）

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 euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
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); }

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 n = RD!int;
		auto h = RDA;

		bool f(long x)
		{
			auto hh = h.dup;
			foreach_reverse (i; 2..n)
			{
				if (hh[i] < x) return false;
				auto rem = hh[i] - x;
				auto d = min(rem / 3, h[i] / 3);
				hh[i-1] += d;
				hh[i-2] += d*2;
			}
			return (hh[0] >= x) && (hh[1] >= x);
		}
		ans[ti] = binarySearch!(f)(-1L, 2L^^10);
	}

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
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); }

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 n = RD!int;
		auto h = RDA;

		bool f(long x)
		{
			auto hh = h.dup;
			foreach_reverse (i; 2..n)
			{
				if (hh[i] < x) return false;
				auto rem = hh[i] - x;
				auto d = min(rem / 3, h[i] / 3);
				hh[i-1] += d;
				hh[i-2] += d*2;
			}
			return (hh[0] >= x) && (hh[1] >= x);
		}
		ans[ti] = binarySearch!(f)(0, 2L^^10);
	}

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
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); }

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 n = RD!int;
		auto h = RDA;

		bool f(long x)
		{
			auto hh = h.dup;
			foreach_reverse (i; 2..n)
			{
				if (hh[i] < x) return false;
				auto rem = hh[i] - x;
				auto d = min(rem / 3, h[i] / 3);
				hh[i-1] += d;
				hh[i-2] += d*2;
			}
			return hh[0] >= x && hh[1] >= x;
		}
		ans[ti] = binarySearch!(f)(0, 2L^^10);
	}

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
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); }

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 n = RD!int;
		auto h = RDA;

		bool f(long x)
		{
			auto hh = h.dup;
			foreach_reverse (i; 2..n)
			{
				auto rem = hh[i] - x;
				if (rem < 0) return false;
				auto d = min(rem / 3, h[i] / 3);
				hh[i-1] += d;
				hh[i-2] += d*2;
			}
			return hh[0] >= x && hh[1] >= x;
		}
		ans[ti] = binarySearch!(f)(0, 2L^^9+1);
	}

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

import std.algorithm, std.range, std.stdio, std.numeric, std.array, std.exception,
       std.container, std.typecons, std.conv, std.random, std.bigint;

void read(S...)(ref S args) {
  auto input = readln.split;
  enforce(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

bool possible(long[] arr, long answer) {
  arr = [0L, 0L] ~ arr;
  auto original = arr.dup;

  foreach_reverse(i; 2 .. arr.length) {
    if (arr[i] < answer) return false;
    long d = min(arr[i] - answer, original[i]) / 3;
    arr[i - 1] += d;
    arr[i - 2] += 2 * d;
    arr[i] -= 3 * d;
  }

  return true;
}

void main() {
  int T;
  read(T);

  while (T--) {
    int n;
    read(n);
    auto arr = list!long;
    long low = 0, high = int.max;

    while (high != low) {
      long mid = (high + low) / 2;
      if (mid == low) mid = high;

      if (possible(arr, mid)) low = mid;
      else high = mid - 1;
    }

    writeln(low);
  }
}


Ashishgup and FastestFinger play a game. They start with a number $$$n$$$ and play in turns. In each turn, a player can make any one of the following moves:  Divide $$$n$$$ by any of its odd divisors greater than $$$1$$$.  Subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. Divisors of a number include the number itself.The player who is unable to make a move loses the game.Ashishgup moves first. Determine the winner of the game if both of them play optimally.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer  — $$$n$$$ ($$$1 \leq n \leq 10^9$$$).

For each test case, print "Ashishgup" if he wins, and "FastestFinger" otherwise (without quotes).

FastestFinger
Ashishgup
Ashishgup
FastestFinger
Ashishgup
FastestFinger
Ashishgup

NoteIn the first test case, $$$n = 1$$$, Ashishgup cannot make a move. He loses.In the second test case, $$$n = 2$$$, Ashishgup subtracts $$$1$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the third test case, $$$n = 3$$$, Ashishgup divides by $$$3$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the last test case, $$$n = 12$$$, Ashishgup divides it by $$$3$$$. Now $$$n = 4$$$, FastestFinger is forced to subtract $$$1$$$, and Ashishgup gets $$$3$$$, so he wins by dividing it by $$$3$$$.

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto N = readln.chomp.to!long;
        if (N == 1) {
            writeln("FastestFinger");
            continue;
        }
        if (N == 2 || N%2 == 1) {
            writeln("Ashishgup");
            continue;
        }
        auto n = N;
        int t;
        while (n%2 == 0) {
            ++t;
            n /= 2;
        }
        if (n == 1) {
            writeln("FastestFinger");
            continue;
        }
        if (t > 1) {
            writeln("Ashishgup");
            continue;
        }

        int c;
        for (long k = 3; k^^2 <= N; k += 2) {
            while (n%k == 0) {
                ++c;
                n /= k;
            }
        }
        if (n != 1) {
            ++c;
        }
        writeln(c == 1 ? "FastestFinger": "Ashishgup");
    }
}

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

bool isPrime (int n)
{
	if (n < 2)
	{
		return false;
	}
	for (int d = 2; d * d <= n; d++)
	{
		if (n % d == 0)
		{
			return false;
		}
	}
	return true;
}

bool solve (int n)
{
	int p2 = bsf (n);
	int rem = n >> p2;
	if (p2 == 0)
	{
		return rem > 1;
	}
	else if (p2 == 1)
	{
		return !isPrime (rem);
	}
	else
	{
		return rem > 1;
	}
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		writeln (solve (n) ? "Ashishgup" : "FastestFinger");
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		bool dfs(long x, bool turn)
		{
			if (x == 1) return !turn;
			if (x == 2 || x % 2) return turn;

			bool res = !turn;
			for (long i = 3; i*i <= x; ++i)
			{
				if (x % i) continue;
				if (i % 2)
					res |= dfs(x/i, !turn) == turn;
				if ((x / i) % 2)
					res |= dfs(i, !turn) == turn;
			}
			return res;
		}
		ans[ti] = dfs(n, true);
	}

	foreach (e; ans)
	{
		writeln(e ? "Ashishgup" : "FastestFinger");
	}
	stdout.flush;
	debug readln;
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto N = readln.chomp.to!long;
        if (N == 1) {
            writeln("FastestFinger");
            continue;
        }
        if (N == 2 || N%2 == 1) {
            writeln("Ashishgup");
            continue;
        }
        auto n = N;
        int t;
        while (n%2 == 0) {
            ++t;
            n /= 2;
        }
        if (n == 1) {
            writeln("FastestFinger");
            continue;
        }
        if (t > 1) {
            writeln("Ashishgup");
            continue;
        }

        int c;
        for (long k = 3; k^^2 <= N; k += 2) {
            while (n%k == 0) {
                ++c;
                n /= k;
            }
        }
        if (n%2 != 0 && n != 1) {
            ++c;
        }
        writeln(c%2 == 1 ? "FastestFinger": "Ashishgup");
    }
}


We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7.The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.

The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.

Print the minimum number of steps modulo 109 + 7.

NoteThe first example: "ab"  →  "bba".The second example: "aab"  →  "abba"  →  "bbaba"  →  "bbbbaa".

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

long powmod(long a, long x, long m) {
    long ret = 1;
    while (x) {
        if (x % 2) ret = ret * a % m;
        a = a * a % m;
        x /= 2;
    }
    return ret;
}

void main() {
    immutable long MOD = 10^^9 + 7;

    auto S = readln.chomp;
    auto N = S.length.to!int;

    long a = 0;
    long b = 0;
    long ans = 0;
    char prev = 'x';
    foreach (i; 0..N) {
        if (S[i] == 'a' && prev == 'b') {
            ans += b * (powmod(2, a, MOD) - 1) % MOD;
            ans = (ans + MOD) % MOD;
            a++;
            b = 0;
        }
        else if (S[i] == 'a') {
            a++;
        }
        else {
            b++;
        }

        prev = S[i];
    }

    ans += b * (powmod(2, a, MOD) - 1) % MOD;
    ans = (ans + MOD) % MOD;

    ans.writeln;
}

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

long powmod(long a, long x, long m) {
    long ret = 1;
    while (x) {
        if (x % 2) ret = ret * a % m;
        a = a * a % m;
        x /= 2;
    }
    return ret;
}

void main() {
    immutable long MOD = 10^^9 + 7;

    auto S = readln.chomp;
    auto N = S.length.to!int;

    long a = 0;
    long b = 0;
    long ans = 0;
    char prev = 'x';
    foreach (i; 0..N) {
        if (S[i] == 'a' && prev == 'b') {
            ans += b * powmod(2, a, MOD) % MOD - 1;
            ans = (ans + MOD) % MOD;
            a++;
            b = 0;
        }
        else if (S[i] == 'a') {
            a++;
        }
        else {
            b++;
        }

        prev = S[i];
    }

    ans += b * powmod(2, a, MOD) % MOD - 1;
    ans = (ans + MOD) % MOD;

    ans.writeln;
}


Once archaeologists found m mysterious papers, each of which had a pair of integers written on them. Ancient people were known to like writing down the indexes of the roads they walked along, as «a b» or «b a», where a, b are the indexes of two different cities joint by the road . It is also known that the mysterious papers are pages of two travel journals (those days a new journal was written for every new journey).During one journey the traveler could walk along one and the same road several times in one or several directions but in that case he wrote a new entry for each time in his journal. Besides, the archaeologists think that the direction the traveler took on a road had no effect upon the entry: the entry that looks like «a b» could refer to the road from a to b as well as to the road from b to a.The archaeologists want to put the pages in the right order and reconstruct the two travel paths but unfortunately, they are bad at programming. That’s where you come in. Go help them!

The first input line contains integer m (1 ≤ m ≤ 10000). Each of the following m lines describes one paper. Each description consists of two integers a, b (1 ≤ a, b ≤ 10000, a ≠ b).

In the first line output the number L1. That is the length of the first path, i.e. the amount of papers in its description. In the following line output L1 space-separated numbers — the indexes of the papers that describe the first path. In the third and fourth lines output similarly the length of the second path L2 and the path itself. Both paths must contain at least one road, i.e. condition L1 > 0 and L2 > 0 must be met. The papers are numbered from 1 to m according to the order of their appearance in the input file. The numbers should be output in the order in which the traveler passed the corresponding roads. If the answer is not unique, output any. If it’s impossible to find such two paths, output «-1». Don’t forget that each paper should be used exactly once, i.e L1 + L2 = m.

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

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

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

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

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

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

immutable N = 10005;
int M;
int[] A, B;

int[][] G;
int[] deg;

bool[] used;
int[] path;
void dfs(int u) {
	foreach (i; G[u]) {
		if (!used[i]) {
			used[i] = true;
			dfs(A[i] ^ B[i] ^ u);
			path ~= i;
		}
	}
}

int[] eulerianPath(int[] us) {
	int[] odds;
	foreach (u; us) {
		if (deg[u] % 2 != 0) {
			odds ~= u;
		}
	}
	switch (odds.length) {
		case 0: {
			path.clear;
			dfs(us[0]);
			return path;
		} break;
		case 2: {
			path.clear;
			dfs(odds[0]);
			return path;
		} break;
		default: {
			return null;
		}
	}
}

int[][] solve() {
	G = new int[][N];
	deg = new int[N];
	foreach (i; 0 .. M) {
		G[A[i]] ~= i;
		G[B[i]] ~= i;
		++deg[A[i]];
		++deg[B[i]];
	}
	used = new bool[M];

	if (M < 2) {
		return null;
	}

	int[] uf = new int[N];
	uf[] = -1;
	foreach (i; 0 .. M) {
		uf.conn(A[i], B[i]);
	}
	int[][] us = new int[][N];
	foreach (u; 0 .. N) {
		us[uf.root(u)] ~= u;
	}
	int[][] edges = new int[][N];
	foreach (i; 0 .. M) {
		edges[uf.root(A[i])] ~= i;
	}
	const numCompos = edges.count!"!a.empty";
	if (numCompos == 1) {
		int[] odds;
		foreach (u; 0 .. N) {
			if (deg[u] % 2 != 0) {
				odds ~= u;
			}
		}
		switch (odds.length) {
			case 0: {
				path.clear;
				dfs(A[0]);
				return [ path[0 .. 1], path[1 .. $] ];
			} break;
			case 2: {
				path.clear;
				dfs(odds[0]);
				return [ path[0 .. 1], path[1 .. $] ];
			} break;
			case 4: {
				A ~= odds[0];
				B ~= odds[1];
				G[A[M]] ~= M;
				G[B[M]] ~= M;
				used ~= false;
				path.clear;
				dfs(odds[2]);
				const int idx = path.length - path.find(M).length;
				return [ path[0 .. idx], path[idx + 1 .. $] ];
			} break;
			default: {
				return null;
			}
		}
	} else if (numCompos == 2) {
		int[][] ret;
		foreach (r; 0 .. N) if (!edges[r].empty) {
			if (auto res = us[r].eulerianPath) {
				ret ~= res;
			} else {
				return null;
			}
		}
		return ret;
	} else {
		return null;
	}
}

void main(string[] args) {
	auto inp = File("input.txt", "r");
	auto outp = File("output.txt", "w");
	for (string line; (line = inp.readln) != null; ) {
		M = line.chomp.to!int;
		A = new int[M];
		B = new int[M];
		foreach (i; 0 .. M) {
			auto tks = inp.readln.split;
			A[i] = tks[0].to!int;
			B[i] = tks[1].to!int;
		}
debug{
writeln("A = ",A);
writeln("B = ",B);
}

		if (auto res = solve) {
debug{
writeln("res = ",res);
}
			foreach (path; res) {
				outp.writeln(path.length);
				path[] += 1;
				outp.writeln(path.to!string.removechars("[],"));
			}
		} else {
			outp.writeln(-1);
		}
	}
}


Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.This day, Mocha got a sequence $$$a$$$ of length $$$n$$$. In each operation, she can select an arbitrary interval $$$[l, r]$$$ and for all values $$$i$$$ ($$$0\leq i \leq r-l$$$), replace $$$a_{l+i}$$$ with $$$a_{l+i} \,\&\, a_{r-i}$$$ at the same time, where $$$\&$$$ denotes the bitwise AND operation. This operation can be performed any number of times.For example, if $$$n=5$$$, the array is $$$[a_1,a_2,a_3,a_4,a_5]$$$, and Mocha selects the interval $$$[2,5]$$$, then the new array is $$$[a_1,a_2\,\&\, a_5, a_3\,\&\, a_4, a_4\,\&\, a_3, a_5\,\&\, a_2]$$$.Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?

Each test contains multiple test cases.  The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).

For each test case, print one integer — the minimal value of the maximum value in the sequence.

NoteIn the first test case, Mocha can choose the interval $$$[1,2]$$$, then the sequence becomes $$$[ 0, 0]$$$, where the first element is $$$1\,\&\,2$$$, and the second element is $$$2\,\&\,1$$$.In the second test case, Mocha can choose the interval $$$[1,3]$$$, then the sequence becomes $$$[ 1,1,1]$$$, where the first element is $$$1\,\&\,3$$$, the second element is $$$1\,\&\,1$$$, and the third element is $$$3\,\&\,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)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		ans[ti] = a[0];
		foreach (i; 0..n)
		{
			ans[ti] &= a[i];
		}
	}

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

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	a.fold!((ai, aj) => ai&aj).writeln;
}

// main {{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
// }}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
		popChar;
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

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

void theCode(){
    int n = scan!int;
    ll[] arr  = scanArray;
    ll minn = arr[0];
    for(int i = 0; i < n; ++i){
        minn = minn & arr[i];
    }
    writeln(minn);
}

void main(){
    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");


This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $$$a_1, a_2, \dots, a_n$$$.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$$$, where $$$a_1 \dots a_p$$$ and $$$b_1 \dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally,  if $$$p \ge q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$;  if $$$p < q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$, your task is to help students to calculate $$$\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\,244\,353$$$.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array.

Print the answer modulo $$$998\,244\,353$$$.

import std.stdio;
import std.typecons;
import std.math : log10, pow;
import std.algorithm;

const int MAX = 100005;
int MOD = 998244353;
int n;
long[MAX] a;
int[20] count;

void main() {
    readf(" %s", n);
    foreach(i; 0..n) readf(" %s", a[i]);

    foreach(i; 0..n) count[numOfDigits(a[i])]++;

    long result = 0;
    foreach(i; 0..n){
        foreach(j; 1..11) {
            if (count[j] == 0) continue;
            auto d = min(numOfDigits(a[i]), j);
            auto r = calc(a[i], d);
            auto x = r[0];
            auto y = r[1] % MOD;
            result += (y * 11 * count[j]) % MOD + ((((pow10(d * 2) % MOD) * x) % MOD) * 2 * count[j]) % MOD;
            result %= MOD;
        }
    }
    writeln(result);
}

auto pow10(long x) {
    return pow(10, x);
}

auto numOfDigits(long x) {
    if (x == 0) return 1;
    return 1 + cast(int) log10(x);
}

auto calc(long x, int digits) {
    long base = 1;
    long y = 0;
    int k = 0;
    while(x > 0) {
        auto d = x % 10;
        x = x / 10;
        y += d * base;
        base *= 100;
        k++;
        if (k >= digits) {
            break;
        }
    }
    return tuple(x, y);
}

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 read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

const long mod = 998_244_353;

void solve(){
	int n = read.to!int;

	long[] as;
	foreach(i; 0 .. n) as ~= read.to!long;

	long[][] ws;
	foreach(a; as){
		long [] w;
		for(long x = a; x > 0; x /= 10) w ~= x % 10;
		ws ~= w;
	}
	log("ws:", ws);

	int[] ks;
	foreach(a; as){
		int k = 0;
		long m = 1;
		while(a >= m) k += 1, m *= 10;
		ks ~= k;
	}
	log("ks:", ks);

	long[] ms = [1];
	foreach(i; 1 .. 24){
		ms ~= ms[$ - 1] * 10 % mod;
	}
	log("ms:", ms);

	long[] rs;
	foreach(i; 0 .. 11){
		long r;
		foreach(k; ks){
			if(i < k) r += 11 * ms[i * 2], r %= mod;
			else r += 2 * ms[k * 2] * ms[i - k], r %= mod;
		}
		rs ~= r;
	}
	log("rs:", rs);

	long ans;
	foreach(w; ws){
		foreach(i, t; w){
			ans += t * rs[i];
			ans %= mod;
		}
	}

	ans.writeln;
}

import std.stdio;
import std.typecons;
import std.math : log10, pow;
import std.algorithm;

const int MAX = 100005;
int MOD = 998244353;
int n;
long[MAX] a;
int[20] count;

void main() {
    readf(" %s", n);
    foreach(i; 0..n) readf(" %s", a[i]);

    foreach(i; 0..n) count[numOfDigits(a[i])]++;

    long result = 0;
    foreach(i; 0..n){
        foreach(j; 1..11) {
            if (count[j] == 0) continue;
            auto d = min(numOfDigits(a[i]), j);
            auto r = calc(a[i], d);
            auto x = r[0];
            auto y = r[1] % MOD;
            result += (y * 11 * count[j]) % MOD + ((((pow10(d * 2) % MOD) * x) % MOD) * 2 * count[j]) % MOD;
            result %= MOD;
        }
    }
    writeln(result);
}

auto pow10(int x) {
    return cast(long) pow(10, x);
}

auto numOfDigits(long x) {
    return 1 + cast(int) log10(x);
}

auto calc(long x, int digits) {
    long base = 1;
    long y = 0;
    int k = 0;
    while(x > 0) {
        auto d = x % 10;
        x = x / 10;
        y += d * base;
        base *= 100;
        k++;
        if (k >= digits) {
            break;
        }
    }
    return tuple(x, y);
}

import std.stdio;
import std.typecons;
import std.math : log10, pow;
import std.algorithm;

const int MAX = 100005;
int MOD = 998244353;
int n;
long[MAX] a;
int[10] count;

void main() {
    readf(" %s", n);
    foreach(i; 0..n) readf(" %s", a[i]);

    foreach(i; 0..n) count[numOfDigits(a[i])]++;

    long result = 0;
    foreach(i; 0..n){
        foreach(j; 1..10) {
            if (count[j] == 0) continue;
            auto d = min(numOfDigits(a[i]), j);
            auto r = calc(a[i], d);
            auto x = r[0];
            auto y = r[1] % MOD;
            result += (y * 11 * count[j]) % MOD + ((((pow10(d * 2) % MOD) * x) % MOD) * 2 * count[j]) % MOD;
            result %= MOD;
        }
    }
    writeln(result);
}

auto pow10(int x) {
    return cast(long) pow(10, x);
}

auto numOfDigits(long x) {
    return 1 + cast(int) log10(x);
}

auto calc(long x, int digits) {
    long base = 1;
    long y = 0;
    int k = 0;
    while(x > 0) {
        auto d = x % 10;
        x = x / 10;
        y += d * base;
        base *= 100;
        k++;
        if (k >= digits) {
            break;
        }
    }
    return tuple(x, y);
}

import std.stdio;
import std.typecons;
import std.math : log10, pow;
import std.algorithm;

const int MAX = 100005;
int MOD = 998244353;
int n;
long[MAX] a;
int[10] count;

void main() {
    readf(" %s", n);
    foreach(i; 0..n) readf(" %s", a[i]);

    foreach(i; 0..n) count[numOfDigits(a[i])]++;

    long result = 0;
    foreach(i; 0..n){
        foreach(j; 1..10) {
            if (count[j] == 0) continue;
            auto d = min(numOfDigits(a[i]), j);
            auto r = calc(a[i], d);
            auto x = r[0];
            auto y = r[1] % MOD;
            result += (y * 11 * count[j]) % MOD + ((((pow10(d * 2) % MOD) * x) % MOD) * 2 * count[j]) % MOD;
            result %= MOD;
        }
    }
    writeln(result);
}

auto pow10(int x) {
    return cast(int) pow(10, x);
}

auto numOfDigits(long x) {
    return 1 + cast(int) log10(x);
}

auto calc(long x, int digits) {
    long base = 1;
    long y = 0;
    int k = 0;
    while(x > 0) {
        auto d = x % 10;
        x = x / 10;
        y += d * base;
        base *= 100;
        k++;
        if (k >= digits) {
            break;
        }
    }
    return tuple(x, y);
}


Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.

The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font:

Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes).

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int n_Cases = 1;
        // n_Cases = cin.readInt;

	for (int case_i = 1; case_i <= n_Cases; case_i++) {
                char[] s = cin.readString.dup;
                char[] r = "AHIMOTUVWXY".dup;
                foreach (i; s) {
                        if (!r.canFind(i)) {
                                writeln("NO");
                                return;
                        }
                }
                writeln(s.dup.reverse == s.dup ? "YES" : "NO");
	}
}

module main;

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

auto table = "AHIMOTUVWXY";

void solve(char[] str)
{
    int i = 0, j = str.length - 1;
    while (i < j)
    {
        if (str[i] != str[j] || find(table, str[i]) == "")
        {
            writefln("NO");
            return;
        }
        ++ i;
        -- j;
    }
    if (i == j && find(table, str[i]) == "")
    {
        writefln("NO");
        return;
    }
    writefln("YES");
}

int main(string[] args)
{
    char[] str;
    while (stdin.readln(str))
    {
        solve(chomp(str));
    }
    return 0;
}

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

immutable int NA = -1;
immutable string A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
immutable string B = "AxxxxxxHIxxxMxOxxxxTUVWXYx";

void main ()
{
	char [dchar] d;
	foreach (i; 0..A.length)
	{
		d[A[i]] = B[i];
	}

	char [] s;
	while ((s = to !(char []) (readln ().strip ())) != "")
	{
		char [] b = s.dup;
		reverse (b);
		char [] c;
		foreach (x; b)
		{
			c ~= d[x];
		}
		writeln (s == c ? "YES" : "NO");
	}
}

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int n_Cases = 1;
        // n_Cases = cin.readInt;

	for (int case_i = 1; case_i <= n_Cases; case_i++) {
                char[] s = cin.readString.dup;
                if (s.length == 1) writeln("NO");
                else writeln(s.dup.reverse != s ? "NO" : "YES");
	}
}

module main;

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

auto table = "AHIMOTUVWXY";

void solve(char[] str)
{
    int i = 0, j = str.length - 1;
    while (i < j)
    {
        if (str[i] != str[j])
        {
            writefln("NO");
            return;
        }
        ++ i;
        -- j;
    }
    if (i == j && find(table, str[i]) == "")
    {
        writefln("NO");
        return;
    }
    writefln("YES");
}

int main(string[] args)
{
    char[] str;
    while (stdin.readln(str))
    {
        solve(chomp(str));
    }
    return 0;
}


The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.

The first line of input will contain an integer n (1 ≤ n ≤ 105), the number of events. The next line will contain n space-separated integers. If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.

Print a single integer, the number of crimes which will go untreated.

NoteLets consider the second example:  Firstly one person is hired.  Then crime appears, the last hired person will investigate this crime.  One more person is hired.  One more crime appears, the last hired person will investigate this crime.  Crime appears. There is no free policeman at the time, so this crime will go untreated.  One more person is hired.  One more person is hired.  One more person is hired. The answer is one, as one crime (on step 5) will go untreated.

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

void main() {
  auto n = readln.strip.to!int;
  auto a = readln.split.map!(to!int).array;
  int s = 0, r = 0;
  foreach (v; a) {
    s += v;
    if (s < 0) {
      r++;
      s = 0;
    }
  }
  writeln(r);
}

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

	readln;

	int sumCrimes, emplPols;
	foreach (el; readln.split.map!(to!int)) {
		if (el == -1) {
			if (emplPols > 0)
				--emplPols;
			else
				++sumCrimes;
		}
		else
			emplPols += el;
	}

	writeln(sumCrimes);
}

import std.stdio;
import core.stdc.stdio;
import std.string;
import std.regex;
import std.math;
import std.algorithm;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int crimes, police_officers;
	foreach (int i; 0..n)
	{
		int tbd; scanf("%d", &tbd);
		if (tbd < 0)
		{
			if (police_officers > 0)
			{
				police_officers += tbd;
			} else {
				crimes -= tbd;
			}
		} else {
			police_officers += tbd;
		}
	}
	printf("%d", crimes);
	return 0;
}


Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.

The single line contains three integers k, d and t (1 ≤ k, d, t ≤ 1018).

Print a single number, the total time of cooking in minutes. The relative or absolute error must not exceed 10 - 9. Namely, let's assume that your answer is x and the answer of the jury is y. The checker program will consider your answer correct if .

NoteIn the first example, the chicken will be cooked for 3 minutes on the turned on stove, after this it will be cooked for . Then the chicken will be cooked for one minute on a turned off stove, it will be cooked for . Thus, after four minutes the chicken will be cooked for . Before the fifth minute Julia will turn on the stove and after 2.5 minutes the chicken will be ready .In the second example, when the stove is turned off, Julia will immediately turn it on, so the stove will always be turned on and the chicken will be cooked in 20 minutes.

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	long k, d, t;
	read(k, d, t);
	t *= 2;
	k *= 2;
	d *= 2;
	auto r = d * ((k + d - 1) / d);
	auto e = k + (d - k % d) % d / 2;
	auto ans = t / e * r;
	t %= e;
	ans += min(k, t);
	t -= k;
	if (t > 0)
		ans += 2 * t;
	writefln("%.10f", 1.0L * ans / 2);
}

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

real solve (long k, long d, long t)
{
	if (k % d == 0)
	{
		return t;
	}
	real goodParts = k / d;
	real goodAdd = k % d;
	real goodTime = goodParts * d + goodAdd;
	real badTime = d - goodAdd;
	real periodTime = goodTime + badTime;
	real periodCook = goodTime + badTime * 0.5;
	debug {writefln ("%.20f %.20f", goodTime, badTime);}

	real res = 0.0;
	real toCook = t;
	for (real times = 1L << 60; times >= 1; times = times * 0.5)
	{
		if (toCook >= periodCook * times)
		{
			toCook -= periodCook * times;
			res += periodTime * times;
		}
	}

	real extra = min (toCook, goodTime);
	res += extra;
	toCook -= extra;
	if (toCook > 0)
	{
		res += toCook * 2;
	}
	return res;
}

void main ()
{
	long k, d, t;
	while (readf (" %s %s %s", &k, &d, &t) > 0)
	{
		real res = solve (k, d, t);
		writefln ("%.20f", res);
	}
}

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	long k, d, t;
	read(k, d, t);
	t *= 2;
	k *= 2;
	d *= 2;
	auto r = d * ((k + d - 1) / d);
	auto e = k + (d - k % d) % d / 2;
	auto ans = t / e * r;
	t %= e;
	ans += min(k, t);
	t -= k;
	if (t > 0)
		ans += 2 * t;
	writeln(1.0L * ans / 2);
}


You are given a sequence a consisting of n integers. Find the maximum possible value of  (integer remainder of ai divided by aj), where 1 ≤ i, j ≤ n and ai ≥ aj.

The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105).  The second line contains n space-separated integers ai (1 ≤ ai ≤ 106).

import std.stdio;
import std.algorithm;

int n;
int[200005] a;
int[1000005] f;

void main() {
    readf(" %s", n);
    foreach(i; 0..n) readf(" %s", a[i]);

    auto m = a[0..n].fold!max;
    foreach(x; a[0..n]) f[x] = x;
    foreach(i; 1..m+1)
        if (f[i] == 0) f[i] = f[i-1];

    auto result = 0;
    a[0..n].sort();
    foreach(i, x; a[0..n]) {
        // ensure that the algorithm run in harmonic sum time: 1/2 + 1/3 + 1/4 ....
        if (i >= 1 && a[i] == a[i-1]) continue;
        auto y = x + x;
        while (y <= m) {
           result = max(result, f[y-1] % x);
           y += x;
        }
        result = max(result, m % x);
    }
    writeln(result);
}

import std.stdio;
import std.algorithm;

int n;
int[200005] a;
int[1000005] f;

void main() {
    readf(" %s", n);
    foreach(i; 0..n) readf(" %s", a[i]);

    auto m = a[0..n].fold!max;
    foreach(x; a[0..n]) f[x] = x;
    foreach(i; 1..m+1)
        if (f[i] == 0) f[i] = f[i-1];

    auto result = 0;
    a[0..n].sort();
    foreach(i, x; a[0..n]) {
        if (x == 1) continue;
        if (i >= 1 && a[i] == a[i-1]) continue;
        auto y = x + x;
        while (y <= m) {
           result = max(result, f[y-1] % x);
           y += x;
        }
        result = max(result, m % x);
    }
    writeln(result);
}


Medicine faculty of Berland State University has just finished their admission campaign. As usual, about $$$80\%$$$ of applicants are girls and majority of them are going to live in the university dormitory for the next $$$4$$$ (hopefully) years.The dormitory consists of $$$n$$$ rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number $$$i$$$ costs $$$c_i$$$ burles. Rooms are numbered from $$$1$$$ to $$$n$$$.Mouse doesn't sit in place all the time, it constantly runs. If it is in room $$$i$$$ in second $$$t$$$ then it will run to room $$$a_i$$$ in second $$$t + 1$$$ without visiting any other rooms inbetween ($$$i = a_i$$$ means that mouse won't leave room $$$i$$$). It's second $$$0$$$ in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from $$$1$$$ to $$$n$$$ at second $$$0$$$.What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?

The first line contains as single integers $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of rooms in the dormitory. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^4$$$) — $$$c_i$$$ is the cost of setting the trap in room number $$$i$$$. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — $$$a_i$$$ is the room the mouse will run to the next second after being in room $$$i$$$.

Print a single integer — the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from.

NoteIn the first example it is enough to set mouse trap in rooms $$$1$$$ and $$$4$$$. If mouse starts in room $$$1$$$ then it gets caught immideately. If mouse starts in any other room then it eventually comes to room $$$4$$$.In the second example it is enough to set mouse trap in room $$$2$$$. If mouse starts in room $$$2$$$ then it gets caught immideately. If mouse starts in any other room then it runs to room $$$2$$$ in second $$$1$$$.Here are the paths of the mouse from different starts from the third example:  $$$1 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$;  $$$2 \rightarrow 2 \rightarrow \dots$$$;  $$$3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$;  $$$4 \rightarrow 3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$;  $$$5 \rightarrow 6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$$$;  $$$6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$$$;  $$$7 \rightarrow 6 \rightarrow 7 \rightarrow \dots$$$; So it's enough to set traps in rooms $$$2$$$ and $$$6$$$.

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

void main() {
    auto N = readln.chomp.to!int;
    auto C = readln.split.map!(to!long).array;
    auto A = readln.split.map!(x => x.to!int-1).array;
    auto used = new int[](N);
    int cnt = 0;
    long ans = 0;

    foreach (i; 0..N) {
        if (used[i]) continue;
        ++cnt;
        int[] nodes;
        int n = i;
        while (!used[n]) {
            nodes ~= n;
            used[n] = cnt;
            n = A[n];
        }
        if (used[n] != cnt) continue;
        bool flag = false;
        long tmp = 1L << 59;
        foreach (j; nodes) {
            if (j == n) flag = true;
            if (flag) tmp = min(tmp, C[j]);
        }

        ans += tmp;
    }

    ans.writeln;
}

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

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

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

    auto p = readln.chomp.split.map!(to!int).array;
    p[] -= 1;

    int getMinForCycle(int v) {
        auto ans = int.max;
        int u = v;
        do {
            ans = min(ans, cost[u]);
            u = p[u];
        } while (u != v);

        debug { writeln(v, ' ', ans); }

        return ans;
    }

    auto vis = new int[n];
    int dfs(int v) {
        if (vis[v] == 2) {
            return 0;
        }

        vis[v] = 1;
        debug { v.writeln; }

        auto u = p[v];
        auto ret = 0;
        if (vis[u] == 0) {
            ret = dfs(u);
        } else if (vis[u] == 1) {
            ret = getMinForCycle(v);
        } else if (vis[u] == 2) {
            ret = 0;
        }
        vis[v] = 2;
        return ret;
    }

    auto ans = n.iota.map!(x => dfs(x)).sum;

    ans.writeln;
}

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

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

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

    auto p = readln.chomp.split.map!(to!int).array;
    p[] -= 1;

    int getMinForCycle(int v) {
        auto ans = int.max;
        int u = v;
        do {
            ans = min(ans, cost[u]);
            u = p[u];
        } while (u != v);

        debug { writeln(v, ' ', ans); }

        return ans;
    }

    auto vis = new int[n];
    int dfs(int v) {
        if (vis[v] == 2) {
            return 0;
        }

        vis[v] = 1;
        debug { v.writeln; }

        auto u = p[v];
        auto ret = 0;
        if (vis[u] == 0) {
            ret = dfs(u);
        } else if (vis[u] == 1) {
            ret = getMinForCycle(v);
        } else if (vis[u] == 2) {
            ret = 0;
        }
        vis[v] = 2;
        return ret;
    }

    auto ans = 0;
    foreach (i; 0 .. n) {
        ans += dfs(i);
    }

    ans.writeln;
}

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

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

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

    auto p = readln.chomp.split.map!(to!int).array;
    p[] -= 1;

    int getMinForCycle(int v) {
        auto ans = int.max;
        int u = v;
        do {
            ans = min(ans, cost[u]);
            u = p[u];
        } while (u != v);

        debug { writeln(v, ' ', ans); }

        return ans;
    }

    auto ans = 0;
    auto vis = new int[n];
    void dfs(int v) {
        if (vis[v] == 2) {
            return;
        }

        vis[v] = 1;
        debug { v.writeln; }

        auto u = p[v];
        if (vis[u] == 0) {
            dfs(u);
        } else if (vis[u] == 1) {
            ans += getMinForCycle(v);
        }
        vis[v] = 2;
    }

    foreach (i; 0 .. n) {
        dfs(i);
    }

    ans.writeln;
}


Guy-Manuel and Thomas are planning $$$144$$$ trips around the world.You are given a simple weighted undirected connected graph with $$$n$$$ vertexes and $$$m$$$ edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than $$$3$$$ which passes through the vertex $$$1$$$. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost $$$0$$$ aren't exciting. You may choose any subset of edges incident to the vertex $$$1$$$ and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to $$$0$$$ which passes through the vertex $$$1$$$ in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo $$$10^9+7$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^5$$$) — the number of vertexes and edges in the graph. The $$$i$$$-th of the next $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$ and $$$w_i$$$ ($$$1 \le a_i, b_i \le n, a_i \neq b_i, 0 \le w_i < 32$$$) — the endpoints of the $$$i$$$-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than $$$3$$$ which passes through the vertex $$$1$$$.

NoteThe pictures below represent the graphs from examples.  In the first example, there aren't any nontrivial cycles with cost $$$0$$$, so we can either remove or keep the only edge incident to the vertex $$$1$$$.  In the second example, if we don't remove the edge $$$1-2$$$, then there is a cycle $$$1-2-4-5-2-1$$$ with cost $$$0$$$; also if we don't remove the edge $$$1-3$$$, then there is a cycle $$$1-3-2-4-5-2-3-1$$$ of cost $$$0$$$. The only valid subset consists of both edges.  In the third example, all subsets are valid except for those two in which both edges $$$1-3$$$ and $$$1-4$$$ are kept.

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

uint addVector(uint p, int x) {
  uint pp = p;
  foreach (y; 0 .. L) {
    if (p & 1U << y) {
      pp |= 1U << (y ^ x);
    }
  }
  return pp;
}

int N, M;
int[] A, B, W;
int[][] G;

int[] dep, sums;
int[] cycs, cycs0;

void dfs(int u, int p, int d, int s) {
  debug {
    writeln("dfs ", u, " ", p, " ", d, " ", s);
  }
  dep[u] = d;
  sums[u] = s;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      if (dep[v] == -1) {
        dfs(v, u, d + 1, s ^ W[i]);
      } else {
        if (dep[u] > dep[v]) {
          debug {
            writeln("back edge ", u, " ", v, " ", (sums[u] ^ sums[v] ^ W[i]));
          }
          ((v == 0) ? cycs0 : cycs) ~= (sums[u] ^ sums[v] ^ W[i]);
        }
      }
    }
  }

}

void main() {
  int V;
  int[uint] ids;
  int[] ps;
  DList!int que;
  que ~= 1U << 0;
  for (; !que.empty; ) {
    const p = que.front;
    que.removeFront;
    foreach (x; 0 .. L) {
      const pp = addVector(p, x);
      if (pp !in ids) {
        ids[pp] = V++;
        ps ~= pp;
        que ~= pp;
      }
    }
  }
  auto add = new int[][](V + 1, V + 1);
  foreach (u; 0 .. V + 1) foreach (v; 0 .. V + 1) {
    add[u][v] = V;
  }
  foreach (u; 0 .. V) foreach (v; 0 .. V) {
    bool orth = true;
    int pp;
    foreach (x; 0 .. L) foreach (y; 0 .. L) {
      if ((ps[u] & 1U << x) && (ps[v] & 1U << y)) {
        pp |= 1U << (x ^ y);
        if (x != 0 && y != 0) {
          orth = orth && ((x ^ y) != 0);
        }
      }
    }
    if (orth) {
      assert(pp in ids);
      add[u][v] = ids[pp];
    }
  }
  debug {
    writeln("V = ", V);
    /*
    foreach (u; 0 .. V) {
      foreach (x; 0 .. L) {
        write((ps[u] >> x) & 1U);
      }
      writeln();
    }
    */
  }

  try {
    for (; ; ) {
      N = readInt();
      M = readInt();
      A = new int[M];
      B = new int[M];
      W = new int[M];
      foreach (i; 0 .. M) {
        A[i] = readInt() - 1;
        B[i] = readInt() - 1;
        W[i] = readInt();
      }
      G = new int[][N];
      foreach (i; 0 .. M) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      dep = new int[N];
      dep[] = -1;
      dep[0] = 0;
      sums = new int[N];
      int[] us, us1;
      foreach (i; G[0]) {
        const int v = A[i] ^ B[i] ^ 0;
        if (dep[v] == -1) {
          cycs = [];
          cycs0 = [];
          dfs(v, 0, 1, W[i]);
          debug {
            writeln("0 -> ", v, ": ", cycs, " ", cycs0);
          }

          uint q = 1U << 0;
          bool orth = true;
          foreach (cyc; cycs) {
            orth = orth && !(q & 1U << cyc);
            q = addVector(q, cyc);
          }
          foreach (cyc; cycs0) {
            orth = orth && !(q & 1U << cyc);
            q = addVector(q, cyc);
          }
          us ~= orth ? ids[q] : V;
          debug {
            write("q = ");
            foreach (x; 0 .. L) {
              write((q >> x) & 1U);
            }
            writeln();
          }

          if (cycs0) {
            uint q1 = 1U << 0;
            bool orth1 = true;
            foreach (cyc; cycs) {
              orth1 = orth1 && !(q1 & 1U << cyc);
              q1 = addVector(q1, cyc);
            }
            us1 ~= orth1 ? ids[q1] : V;
            debug {
              write("q1 = ");
              foreach (x; 0 .. L) {
                write((q1 >> x) & 1U);
              }
              writeln();
            }
          } else {
            us1 ~= -1;
          }
        }
      }
      debug {
        writeln("us = ", us);
        writeln("us1 = ", us1);
      }

      const len = cast(int)(us.length);
      auto dp = new Mint[][](len + 1, V + 1);
      dp[0][0] = 1;
      foreach (j; 0 .. len) {
        if (us1[j] != -1) {
          foreach (u; 0 .. V + 1) {
            dp[j + 1][u] += dp[j][u];
            dp[j + 1][add[u][us1[j]]] += dp[j][u] * 2;
            dp[j + 1][add[u][us[j]]] += dp[j][u];
          }
        } else {
          foreach (u; 0 .. V + 1) {
            dp[j + 1][u] += dp[j][u];
            dp[j + 1][add[u][us[j]]] += dp[j][u];
          }
        }
      }
      debug {
        foreach (j; 0 .. len + 1) {
          write(j);
          foreach (u; 0 .. V + 1) {
            if (dp[j][u].x != 0) {
              write(" ", u, ":", dp[j][u]);
            }
          }
          writeln();
        }
      }
      const ans = dp[len][0 .. V].sum;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Consider a sequence of integers $$$a_1, a_2, \ldots, a_n$$$. In one move, you can select any element of the sequence and delete it. After an element is deleted, all elements to the right are shifted to the left by $$$1$$$ position, so there are no empty spaces in the sequence. So after you make a move, the sequence's length decreases by $$$1$$$. The indices of the elements after the move are recalculated.E. g. let the sequence be $$$a=[3, 2, 2, 1, 5]$$$. Let's select the element $$$a_3=2$$$ in a move. Then after the move the sequence will be equal to $$$a=[3, 2, 1, 5]$$$, so the $$$3$$$-rd element of the new sequence will be $$$a_3=1$$$ and the $$$4$$$-th element will be $$$a_4=5$$$.You are given a sequence $$$a_1, a_2, \ldots, a_n$$$ and a number $$$k$$$. You need to find the minimum number of moves you have to make so that in the resulting sequence there will be at least $$$k$$$ elements that are equal to their indices, i. e. the resulting sequence $$$b_1, b_2, \ldots, b_m$$$ will contain at least $$$k$$$ indices $$$i$$$ such that $$$b_i = i$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two consecutive lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$). The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$). The numbers in the sequence are not necessarily different. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2000$$$.

For each test case output in a single line:   $$$-1$$$ if there's no desired move sequence;  otherwise, the integer $$$x$$$ ($$$0 \le x \le n$$$) — the minimum number of the moves to be made so that the resulting sequence will contain at least $$$k$$$ elements that are equal to their indices.

NoteIn the first test case the sequence doesn't satisfy the desired condition, but it can be provided by deleting the first element, hence the sequence will be $$$[1, 2, 3, 4, 5, 6]$$$ and $$$6$$$ elements will be equal to their indices.In the second test case there are two ways to get the desired result in $$$2$$$ moves: the first one is to delete the $$$1$$$-st and the $$$3$$$-rd elements so that the sequence will be $$$[1, 2, 3]$$$ and have $$$3$$$ elements equal to their indices; the second way is to delete the $$$2$$$-nd and the $$$3$$$-rd elements to get the sequence $$$[5, 2, 3]$$$ with $$$2$$$ desired elements.

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

void main()
{
	int t = readInt!int;
	while (t--)
	{
		solve();
	}
}

void solve()
{
	int n = readInt!int;
	int k = readInt!int;
	auto a = new int[](n); foreach(ref ai; a) ai = readInt!int - 1;
	auto reqrem = new int[](n);
	foreach(i, ref remi; reqrem)
	{
		if (a[i] <= i)
		{
			remi = cast(int)(i - a[i]);
		}
		else
		{
			remi = -1;
		}
	}
	auto mxlen = new int[](n);
	auto visited = new bool[](n);
	int maxLength(int i)
	{
		if (reqrem[i] == -1) return 0;
		if (visited[i]) return mxlen[i];
		visited[i] = true;
		mxlen[i] = 0;
		foreach(j; 0 .. i)
		{
			if (reqrem[j] == -1) continue;
			if (reqrem[j] <= reqrem[i])
			{
				int delta = reqrem[i] - reqrem[j];
				debug writeln(i, " -> ", j);
				if (delta <= i - j - 1)
				{
					mxlen[i] = max(mxlen[i], maxLength(j));
				}
			}
		}
		mxlen[i]++;
		return mxlen[i];
	}
	debug writeln(reqrem);
	debug
	{
		iota(0, n).map!(i=>maxLength(i)).writeln;
	}
	int minmoves = int.max;
	foreach(i; 0 .. n)
	{
		if (reqrem[i] != -1)
		{
			if (maxLength(i) >= k)
			{
				minmoves = min(minmoves, reqrem[i]);
			}
		}
	}
	if (minmoves == int.max) writeln(-1);
	else writeln(minmoves);
}
/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
		popChar;
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else
			static assert(text("Operator ", operator, " not supported"));
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}