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!string;

		foreach (c; n)
		{
			ans[ti].chmax(c-'0');
		}
	}

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

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()
{
	auto n = readInt!long;
	int md = int.min;
	while (n)
	{
		md = cast(int)max(md, n % 10);
		n /= 10;
	}
	md.writeln;
}

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

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

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

  while (t--) {
    string s;
    read(s);

    char c = s[0];
    foreach (e; s) {
      c = max(c, e);
    }

    writeln(c);
  }
}

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    auto s = readln.strip;
    writeln(s.maxElement);
  }

} // main

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    writeln(n.text.split("").map!(to!int).maxElement);
  }
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readToken();
        int ans;
        foreach (c; N) {
          chmax(ans, c - '0');
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		writeln (s.maxElement);
	}
}


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

void solve(int[] a, int k)
{
    auto n = cast(int)a.length;
    int[int] cnt;
    auto longest = 0;
    auto left = -1, right = -1;
    auto i = 0, j = 0;
    auto count = 0;
    while (j < n)
    {
        if (!(a[j] in cnt) || cnt[a[j]] == 0)
        {
            ++ count;
        }
        if (!(a[j] in cnt))
        {
            cnt[a[j]] = 0;
        }
        ++ cnt[a[j]];
        if (count <= k)
        {
            if (j - i + 1 > longest)
            {
                left = i + 1;
                right = j + 1;
                longest = j - i + 1;
            }
        }
        else
        {
            while (i <= j && count > k)
            {
                -- cnt[a[i]];
                if (cnt[a[i]] == 0)
                {
                    -- count;
                }
                ++ i;
            }
        }
        ++ j;
    }
    writeln(left, " ", right);
}

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

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

void solve(int[] a, int k)
{
    auto n = cast(int)a.length;
    auto m = reduce!(max)(a);
    auto cnt = new int[m + 1];
    auto longest = 0;
    auto left = -1, right = -1;
    auto i = 0, j = 0;
    auto count = 0;
    while (j < n)
    {
        if (cnt[a[j]] == 0)
        {
            ++ count;
        }
        ++ cnt[a[j]];
        if (count <= k)
        {
            if (j - i + 1 > longest)
            {
                left = i + 1;
                right = j + 1;
                longest = j - i + 1;
            }
        }
        else
        {
            while (i <= j && count > k)
            {
                -- cnt[a[i]];
                if (cnt[a[i]] == 0)
                {
                    -- count;
                }
                ++ i;
            }
        }
        ++ j;
    }
    writeln(left, " ", right);
}

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

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

void solve(int[] a, int k)
{
    auto n = cast(int)a.length;
    int[int] cnt;
    auto longest = 0;
    auto left = -1, right = -1;
    auto i = 0, j = 0;
    auto count = 0;
    while (j < n)
    {
        if (!(a[j] in cnt) || cnt[a[j]] == 0)
        {
            ++ count;
        }
        if (!a[j] in cnt)
        {
            cnt[a[j]] = 0;
        }
        ++ cnt[a[j]];
        if (count <= k)
        {
            if (j - i + 1 > longest)
            {
                left = i + 1;
                right = j + 1;
                longest = j - i + 1;
            }
        }
        else
        {
            while (i <= j && count > k)
            {
                -- cnt[a[i]];
                if (cnt[a[i]] == 0)
                {
                    -- count;
                }
                ++ i;
            }
        }
        ++ j;
    }
    writeln(left, " ", right);
}

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


import std;

alias MinMax = Tuple!(long, "min", long, "max");

long
readLong () {
    long a;
    readf!" %s"(a);
    return a;
}

MinMax
minMax () {
    immutable nb_to_read = readLong();
    long min = long.max, max = long.min;
    foreach (i; 0 .. nb_to_read) {
        immutable x = readLong();

        if (x < min)
            min = x;
        if (x > max)
            max = x;
    }
    return MinMax(min, max);
}

long
base_length (in MinMax seg) {
    return seg.max - seg.min;
}

void main () {
    immutable t = readLong();

    foreach (test_index; 0 .. t) {
        immutable w = readLong(), h = readLong();

        long area = -1;
        area = max(area, base_length(minMax()) * h);
        area = max(area, base_length(minMax()) * h);
        area = max(area, base_length(minMax()) * w);
        area = max(area, base_length(minMax()) * w);

        writeln(area);
    }
}

// ""

immutable multi = true;

void solve(int tc)
{
  auto w = readInt!long;
  auto h = readInt!long;
  auto x1n = readInt!int;
  auto x1 = ma(x1n, readInt!long);
  auto x2n = readInt!int;
  auto x2 = ma(x2n, readInt!long);
  auto y1n = readInt!int;
  auto y1 = ma(y1n, readInt!long);
  auto y2n = readInt!int;
  auto y2 = ma(y2n, readInt!long);
  max((x1.back - x1.front) * h,
      (x2.back - x2.front) * h,
      (y1.back - y1.front) * w,
      (y2.back - y2.front) * w).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;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
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;
// }}}

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long w, h;
    readf!" %d %d "(w, h);
    auto h1 = readln.splitter.map!(to!long).array[1 .. $];
    auto h2 = readln.splitter.map!(to!long).array[1 .. $];
    auto v1 = readln.splitter.map!(to!long).array[1 .. $];
    auto v2 = readln.splitter.map!(to!long).array[1 .. $];
    writeln(max((h1.maxElement - h1.minElement) * h,
                (h2.maxElement - h2.minElement) * h,
                (v1.maxElement - v1.minElement) * w,
                (v2.maxElement - v2.minElement) * w));
  }
}

import std;

alias MinMax = Tuple!(int, "min", int, "max");

int
readInt () {
    int a;
    readf!" %s"(a);
    return a;
}

MinMax
minMax () {
    immutable nb_to_read = readInt();
    int min = int.max, max = int.min;
    foreach (i; 0 .. nb_to_read) {
        immutable x = readInt();

        if (x < min)
            min = x;
        if (x > max)
            max = x;
    }
    return MinMax(min, max);
}

int
base_length (in MinMax seg) {
    return seg.max - seg.min;
}

void main () {
    immutable t = readInt();

    foreach (test_index; 0 .. t) {
        immutable w = readInt(), h = readInt();

        int area = -1;
        area = max(area, base_length(minMax()) * h);
        area = max(area, base_length(minMax()) * h);
        area = max(area, base_length(minMax()) * w);
        area = max(area, base_length(minMax()) * w);

        writeln(area);
    }
}

// ""

immutable multi = true;

void solve(int tc)
{
  auto w = readInt!long;
  auto h = readInt!long;
  auto x1n = readInt!int;
  auto x1 = ma(x1n, readInt!long);
  auto x2n = readInt!int;
  auto x2 = ma(x2n, readInt!long);
  auto y1n = readInt!int;
  auto y1 = ma(y1n, readInt!long);
  auto y2n = readInt!int;
  auto y2 = ma(y2n, readInt!long);
  max((x1.back - x1.front) * h,
      (x2.back - x2.front) * h,
      (y1.back - x1.front) * w,
      (y2.back - y2.front) * w).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;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
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;
// }}}


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

immutable int mod = 10^^9 + 7;

void main(){
    long n, m;
    readVars(n, m);
    auto a = readln.split.to!(int[]).map!(a => a - 1);

    //stderr.writeln(a);

    long ans;
    int pos;

    foreach(ai ; a){
        ans += (ai - pos + n) % n;
        pos = ai;
    }

    writeln(ans);
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

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

string[] tokens;
int tokenId = 0;
string readToken() { for (; tokenId == tokens.length; ) tokens = readln.split, tokenId = 0; return tokens[tokenId++]; }
int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

const long MOD = 100007;

void main () {
	long n = readInt(), m = readInt();
	long[100007] arr = 0;
	for(uint i = 0; i < m; i++) {
		arr[i] = readLong();
	}
	long cost = 0;
	for(int i = 0; i < m - 1; i++) {
		if(arr[i] <= arr[i + 1]) cost += arr[i + 1] - arr[i];
		else cost += n - arr[i] + arr[i + 1];
	}
	writeln(cost + arr[0] - 1);
}

import std.stdio;
import core.stdc.stdio;

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
		tasks[i]--;
	}

	int cp = 0;
	long steps = 0;
	foreach (int i; 0..m)
	{
		int ts = tasks[i] - cp;
		ts = ts < 0 ? n + ts : ts;
		steps += ts;
		cp = tasks[i];
	}
	printf("%lld", steps);
	return 0;
}

import std.stdio: writeln, stdin;
import std.regex: split, regex;
import std.string: strip;
import std.conv: to;
import std.algorithm.iteration: map;

void main()
{
  auto nm = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto as = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto n = nm[0], m = nm[1];
  int b;
  long time = 0;
  foreach(a; as )
  {
    if (a<b) time+=n;
    b=a;
  }
  writeln(time+as[$-1]-1);
}

import std.stdio: writeln, stdin;
import std.regex: split, regex;
import std.string: strip;
import std.conv: to;
import std.algorithm.iteration: map;

void main()
{
  auto nm = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto as = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto n = nm[0], m = nm[1];
  int b, time = 0;
  foreach(a; as )
  {
    if (a<b) time+=n;
    b=a;

  }
  writeln(time+as[$-1]-1);
}

import std.stdio;
import core.stdc.stdio;

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
	}
	int s = 0;
	int ts = 0;
	int t = 0;
	while (t < m)
	{
		while (t < m && tasks[t] == s+1)
		{
			tasks[t] = 0;
			t++;
		}
		if (t >= m)
			continue;

		if (tasks[t] - 1 >= s)
		{
			ts += (tasks[t] - 1 - s);
			s = tasks[t] - 1;
		} else {
			ts += n - (s - tasks[t] + 1);
			s = tasks[t] - 1;
		}
	}
	printf("%d", ts);
	return 0;
}

import std.stdio;
import core.stdc.stdio;

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
	}
	int s = 0;
	long ts = 0;
	int t = 0;
	while (t < m)
	{
		while (t < m && tasks[t] == s+1)
		{
			tasks[t] = 0;
			t++;
		}
		if (t >= m)
			continue;

		if (tasks[t] - 1 >= s)
		{
			ts += (tasks[t] - 1 - s);
			s = tasks[t] - 1;
		} else {
			ts += n - (s - tasks[t] + 1);
			s = tasks[t] - 1;
		}
	}
	printf("%d", ts);
	return 0;
}

import std.stdio;
import core.stdc.stdio;

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
	}
	int s = 0;
	int ts = 0;
	int t = 0;
	while (t < m)
	{
		while (t < m && tasks[t] == s+1)
		{
			tasks[t] = 0;
			t++;
		}
		if (t >= m)
			continue;

		if (tasks[t] - 1 >= s)
		{
			ts += (tasks[t] - 1 - s);
			s = tasks[t] - 1;
		} else {
			ts += (n - s) + (s - tasks[t] + 1);
			s = tasks[t] - 1;
		}
	}
	printf("%d", ts);
	return 0;
}

import std.stdio;
import core.stdc.stdio;

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
	}
	int s = 0;
	long ts = 0;
	int t = 0;
	while (t < m)
	{
		while (t < m && tasks[t] == s+1)
		{
			tasks[t] = 0;
			t++;
		}
		if (t >= m)
			continue;

		if (tasks[t] - 1 >= s)
		{
			ts += (tasks[t] - 1 - s);
			s = tasks[t] - 1;
		} else {
			ts += n - s + tasks[t] - 1;
			s = tasks[t] - 1;
		}
	}
	printf("%d", ts);
	return 0;
}

import std.stdio;
import core.stdc.stdio;

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
		tasks[i]--;
	}

	int cp = 0;
	long steps = 0;
	foreach (int i; 0..m)
	{
		int ts = tasks[i] - cp;
		ts = ts < 0 ? n + ts : ts;
		steps += ts;
		cp = tasks[i];
	}
	printf("%d", steps);
	return 0;
}


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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		while (!a.empty && !a.back)
		{
			a.popBack ();
		}
		long cur = 0;
		int good = 0;
		int bad = 0;
		foreach (ref x; a)
		{
			cur += x;
			good += (cur >= 0);
			bad += (cur == 0);
		}
		auto res = (good == a.length && bad <= 1 && cur == 0);
		writeln (res ? "YES" : "NO");
	}
}

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

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

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

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

int N;
long[] A;

bool solve() {
  long b;
  foreach (i; 0 .. N) {
    const c = A[i] + b;
    if (c < 0) {
      return false;
    } else if (c == 0) {
      foreach (j; i + 1 .. N) {
        if (A[j] != 0) {
          return false;
        }
      }
      return true;
    } else {
      b = c;
    }
  }
  return (b == 0);
}

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

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


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

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

// 提出解
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; }
}

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

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

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


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 != 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.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");
    }
}


// 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");

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

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


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


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

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

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


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

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


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


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


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


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

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

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

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

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

      alias Entry = Tuple!(int, "s", int, "i", int, "j");
      Entry[] es;
      foreach (i; 0 .. M) foreach (j; 0 .. N) {
        es ~= Entry(A[i] + B[j], i, j);
      }
      es.sort;
      const esLen = cast(int)(es.length);
      Tuple!(long, long)[] fs;
      for (int k = 0, l; k < esLen; k = l) {
        for (l = k; l < esLen && es[k].s == es[l].s; ++l) {}
        long f0, f1;
        foreach (ref e; es[k .. l]) {
          f0 |= 1L << e.i;
          f1 |= 1L << e.j;
          fs ~= tuple(f0, f1);
        }
      }
      const fsLen = cast(int)(fs.length);
      int ans;
      foreach (k; 0 .. fsLen) foreach (l; k .. fsLen) {
        int score;
        score += popcnt(fs[k][0] | fs[l][0]);
        score += popcnt(fs[k][1] | fs[l][1]);
        chmax(ans, score);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

immutable int half = 20005;
immutable int limit = (half << 1) + 1;

void main ()
{
	int m, n;
	while (readf (" %s %s", &m, &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		a[] += half;
		b[] += half;
		auto u = new int [limit];
		auto v = new int [limit];
		foreach (ref c; a)
		{
			u[c] += 1;
		}
		foreach (ref c; b)
		{
			v[c] += 1;
		}
		auto f = new bool [limit];
		auto g = new bool [limit];
		auto mask = new long [2] [] [] (m, n);
		foreach (p; 0..m)
		{
			foreach (q; 0..n)
			{
				foreach (r; 0..m)
				{
					foreach (s; 0..n)
					{
						if (a[r] - a[p] == b[q] - b[s])
						{
							mask[p][q][0] |=
							    1L << r;
							mask[p][q][1] |=
							    1L << s;
						}
					}
				}
			}
		}

		int res = 0;
		foreach (p; 0..m)
		{
			foreach (q; 0..n)
			{
				foreach (r; 0..m)
				{
					foreach (s; 0..n)
					{
						auto cur = 0;
						cur += popcnt (mask[p][q][0] |
						    mask[r][s][0]);
						cur += popcnt (mask[p][q][1] |
						    mask[r][s][1]);
						res = max (res, cur);
					}
				}
			}
		}
		writeln (res);
	}
}

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

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

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

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

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

      alias Entry = Tuple!(int, "s", int, "i", int, "j");
      Entry[] es;
      foreach (i; 0 .. M) foreach (j; 0 .. N) {
        es ~= Entry(A[i] + B[j], i, j);
      }
      es.sort;
      const esLen = cast(int)(es.length);
      Tuple!(long, long)[] fs;
      for (int k = 0, l; k < esLen; k = l) {
        for (l = k; l < esLen && es[k].s == es[l].s; ++l) {}
        long f0, f1;
        foreach (ref e; es[k .. l]) {
          f0 |= 1L << e.i;
          f1 |= 1L << e.j;
          fs ~= tuple(f0, f1);
        }
      }
      const fsLen = cast(int)(fs.length);
      int ans;
      foreach (k; 0 .. fsLen) foreach (l; k + 1 .. fsLen) {
        int score;
        score += popcnt(fs[k][0] | fs[l][0]);
        score += popcnt(fs[k][1] | fs[l][1]);
        chmax(ans, score);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


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

immutable int mod = 998_244_353;
immutable int NA = -1;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
		}

		int recur (int v, int p)
		{
			int subtrees = a[v].length.to !(int) + (p == NA);
			int res = 1;
			for (int i = 1; i < subtrees; i++)
			{
				res = (res * 1L * i) % mod;
			}
			if (p == NA)
			{
				res = (res * 1L * n) % mod;
			}
			else
			{
				res = (res * 1L * (subtrees)) % mod;
			}
			foreach (u; a[v])
			{
				if (u != p)
				{
					res = (res * 1L * recur (u, v)) % mod;
				}
			}
			return res;
		}

		writeln (recur (0, NA));
	}
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

int[][] child;
bool[] visited;

long MOD = 998244353;
long[] fac;

long dfs(uint root) {

    uint nc = 0;

    visited[root] = true;
    long mul = 1;

    foreach (v; child[root]) {
        if (!visited[v]) {
            long ll = dfs(v);
            mul = (mul * ll) % MOD;
            nc++;
        }
    }

    if (root != 0)
        nc++;

    return (fac[nc] * mul) % MOD;
}

void main() {
    GC.disable();

    uint n;

    readf(" %s", n);

    child = new int[][n];
    visited = new bool[n];
    visited[] = false;
    fac = new long[n + 10];
    fac[0] = 1;
    foreach (i; 1 .. n + 1)
        fac[i] = (fac[i - 1] * i) % MOD;

    foreach (i; 0 .. n - 1) {
        uint u, v;
        readf(" %s %s", u, v);
        u--;
        v--;
        child[u] ~= v;
        child[v] ~= u;
    }

    long ans = dfs(0);
    writeln((n * ans) % MOD);

}

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

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

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

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

enum long MO = 998244353;

int N;
int[] U, V;

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

void dfs(int u, int p) {
  foreach (v; G[u]) {
    if (v != p) {
      ++deg[u];
      dfs(v, u);
    }
  }
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[U[i]] ~= V[i];
        G[V[i]] ~= U[i];
      }
      deg = new int[N];
      const rt = 0;
      dfs(rt, -1);

      long ans = N;
      foreach (u; 0 .. N) {
        foreach (k; 1 .. deg[u] + 1) {
          ans *= k;
          ans %= MO;
        }
        if (u != rt) {
          ans *= (deg[u] + 1);
          ans %= MO;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

int[][] child;
bool[] visited;

long MOD = 998244353;
long[] fac;

long dfs(uint root) {

    uint nc = 0;

    visited[root] = true;
    long mul = 1;

    foreach (v; child[root]) {
        if (!visited[v]) {
            long ll = dfs(v);
            mul = (mul * ll) % MOD;
            nc++;
        }
    }

    if (root != 0)
        nc++;

    return (fac[nc] * mul) % MOD;
}

void main() {
    GC.disable();

    uint n;

    readf(" %s", n);

    child = new int[][n];
    visited = new bool[n];
    visited[] = false;
    fac = new long[n + 10];
    fac[0] = 1;
    foreach (i; 1 .. n + 1)
        fac[i] = (fac[i - 1] * i) % MOD;

    foreach (i; 0 .. n - 1) {
        uint u, v;
        readf(" %s %s", u, v);
        u--;
        v--;
        child[u] ~= v;
        child[v] ~= u;
    }

    long ans = dfs(0);
    writeln(n * ans);

}