There is a graph of $$$n$$$ rows and $$$10^6 + 2$$$ columns, where rows are numbered from $$$1$$$ to $$$n$$$ and columns from $$$0$$$ to $$$10^6 + 1$$$:  Let's denote the node in the row $$$i$$$ and column $$$j$$$ by $$$(i, j)$$$.Initially for each $$$i$$$ the $$$i$$$-th row has exactly one obstacle — at node $$$(i, a_i)$$$. You want to move some obstacles so that you can reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph (you can't pass through obstacles). Moving one obstacle to an adjacent by edge free node costs $$$u$$$ or $$$v$$$ coins, as below:  If there is an obstacle in the node $$$(i, j)$$$, you can use $$$u$$$ coins to move it to $$$(i-1, j)$$$ or $$$(i+1, j)$$$, if such node exists and if there is no obstacle in that node currently.  If there is an obstacle in the node $$$(i, j)$$$, you can use $$$v$$$ coins to move it to $$$(i, j-1)$$$ or $$$(i, j+1)$$$, if such node exists and if there is no obstacle in that node currently.  Note that you can't move obstacles outside the grid. For example, you can't move an obstacle from $$$(1,1)$$$ to $$$(0,1)$$$. Refer to the picture above for a better understanding. Now you need to calculate the minimal number of coins you need to spend to be able to reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph without passing through obstacles.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$u$$$ and $$$v$$$ ($$$2 \le n \le 100$$$, $$$1 \le u, v \le 10^9$$$) — the number of rows in the graph and the numbers of coins needed to move vertically and horizontally respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — where $$$a_i$$$ represents that the obstacle in the $$$i$$$-th row is in node $$$(i, a_i)$$$. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^4$$$.

For each test case, output a single integer — the minimal number of coins you need to spend to be able to reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph without passing through obstacles. It can be shown that under the constraints of the problem there is always a way to make such a trip possible.

NoteIn the first sample, two obstacles are at $$$(1, 2)$$$ and $$$(2,2)$$$. You can move the obstacle on $$$(2, 2)$$$ to $$$(2, 3)$$$, then to $$$(1, 3)$$$. The total cost is $$$u+v = 7$$$ coins.  In the second sample, two obstacles are at $$$(1, 3)$$$ and $$$(2,2)$$$. You can move the obstacle on $$$(1, 3)$$$ to $$$(2, 3)$$$. The cost is $$$u = 3$$$ coins.

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

string FMT_F = "%.10f";

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

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

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

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

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

		bool ok;
		foreach (i; 1..n)
		{
			auto d = a[i] - a[i-1];
			if (d.abs > 1)
				ok = true;
		}
		if (ok) continue;

		bool[long] used;
		foreach (i; 0..n)
			used[a[i]] = true;
		if (used.length == 1)
			ans[ti] = min(v * 2, u + v);
		else
			ans[ti] = min(u, v);
	}

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

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

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

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

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

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

        bool bad = true;
        bool same = true;
        foreach (i; 0 .. N - 1) {
          bad = bad && (abs(A[i + 1] - A[i]) <= 1);
          same = same && (abs(A[i + 1] - A[i]) <= 0);
        }
        long ans;
        if (bad) {
          if (same) {
            ans = min(V + V, V + U);
          } else {
            ans = min(V, U);
          }
        } else {
          ans = 0;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, u, v;
		readf !(" %s %s %s") (n, u, v);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto d = 0;
		foreach (i; 1..n)
		{
			d = max (d, abs (a[i] - a[i - 1]));
		}
		int res = 0;
		if (d <= 0)
		{
			res += v;
		}
		if (d <= 1)
		{
			res += min (u, v);
		}
		writeln (res);
	}
}


You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).

Print $$$t$$$ integers — the required numbers $$$a+b$$$.

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

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

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

void main() {
    int t; scan(t);
    foreach (_; 0..t) {
        int a, b; scan(a, b);
        writeln(a + b);
    }
}

void scan(T...)(ref T a) {
    string[] ss = readln.split;
    foreach (i, t; T) a[i] = ss[i].to!t;
}
T read(T=string)() { return readln.chomp.to!T; }
T[] reads(T)() { return readln.split.to!(T[]); }
alias readints = reads!int;

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

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

void main() {

}


This is an interactive problem.The jury has a permutation $$$p$$$ of length $$$n$$$ and wants you to guess it. For this, the jury created another permutation $$$q$$$ of length $$$n$$$. Initially, $$$q$$$ is an identity permutation ($$$q_i = i$$$ for all $$$i$$$).You can ask queries to get $$$q_i$$$ for any $$$i$$$ you want. After each query, the jury will change $$$q$$$ in the following way:   At first, the jury will create a new permutation $$$q'$$$ of length $$$n$$$ such that $$$q'_i = q_{p_i}$$$ for all $$$i$$$.  Then the jury will replace permutation $$$q$$$ with pemutation $$$q'$$$. You can make no more than $$$2n$$$ queries in order to quess $$$p$$$.

The first line of input contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases.

NoteIn the first test case the hidden permutation $$$p = [4, 2, 1, 3]$$$.Before the first query $$$q = [1, 2, 3, 4]$$$ so answer for the query will be $$$q_3 = 3$$$.Before the second query $$$q = [4, 2, 1, 3]$$$ so answer for the query will be $$$q_2 = 2$$$.Before the third query $$$q = [3, 2, 4, 1]$$$ so answer for the query will be $$$q_4 = 1$$$.In the second test case the hidden permutation $$$p = [1, 3, 4, 2]$$$.Empty strings are given only for better readability. There will be no empty lines in the testing system.

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 b = new bool [n];
		auto p = new int [n];

		int ask (int pos)
		{
			writeln ("? ", pos + 1);
			stdout.flush ();
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				foreach (j; 0..q.length - 1)
				{
					auto u = q[j];
					auto v = q[j + 1];
					p[u] = v;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
		stdout.flush ();
	}
}

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

int ask(int i) {
    writefln("? %s", i);
    stdout.flush;
    int x = read!int;
    return x;
}

void solve() {
    int N = read!int;
    int count = 0;
    auto known = new bool[N+1];
    auto cycles = new int[][0];
    int c = 1;
    int[] ks;
    int[] cs;
    int nasked = 0;
    for (int k = 0; count < N; k++) {
        while (known[c]) c++;
        cycles ~= new int[0];
        ks ~= nasked;
        cs ~= c;
        while (true) {
            int x = ask(c);
            nasked++;
            cycles[k] ~= x;
            if (known[x]) {
                break;
            }
            known[x] = true;
            count++;
        }
    }

    int[] P = new int[N + 1]; P[] = -1;
    foreach (i, cycle; cycles) {
        //writeln("cycle: ", cycle);
        int n = cast(int)(cycle.length) - 1;
        int k = ks[i];
        //writeln("k: ", k);
        int s = (N*n + n - k) % n + 1;
        //writeln("s: ", s);
        c = cs[i];
        for (int j = 0; j < n; j++) {
            P[c] = cycle[s];
            //writeln("--> ", [c, cycle[s]]);
            c = cycle[s];
            s = (s == n ? 1 : s + 1);
        }
    }
    //writeln(cycles);
    //writeln(ks);
    writefln("! %(%s %)", P[1 .. $]);
    stdout.flush;
}

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

import std;

uint
query (size_t index) {
    writefln("? %s", index + 1);
    stdout.flush;

    uint response;
    readf(" %s", response);
    return response - 1;
}

void
print(in uint[] p) {
    writefln("! %(%s %)\n", p);
    stdout.flush;
}

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable n = () { uint n; readf!" %s"(n); return n; }();

        uint[] p = new uint[n];

        uint steps = 0;
        foreach (i, val; p)
            if (val == 0) {
                uint[] vec;
                uint start = query(i);
                ++ steps;
                do {
                    vec ~= query(i);
                    ++ steps;
                } while(vec.back != start);

                immutable needToShift = (steps - 1) % vec.length;
                //stderr.writeln("LOG:", vec, " -- ", needToShift);

                vec = vec[$ - needToShift .. $] ~ vec[0 .. $ - needToShift];
                //stderr.writeln("LOG:", vec, " -- ", needToShift);

                do {
                    p[i] = vec.front + 1;
                    i = vec.front;
                    vec.popFront;
                } while (!vec.empty);
            }
        print(p);
    }
}
// ""

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 b = new bool [n];
		auto p = new int [n];

		int ask (int pos)
		{
			writeln ("? ", pos + 1);
			stdout.flush ();
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				foreach (j; 0..q.length - 1)
				{
					auto u = q[j];
					auto v = q[j + 1];
					p[v] = u;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
		stdout.flush ();
	}
}

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 b = new bool [n];
		auto p = new int [n];

		int ask (int pos)
		{
			writeln (pos + 1);
			stdout.flush ();
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				q.popBack ();
				foreach (j; 0..q.length)
				{
					auto u = q[j];
					auto v = q[(j + 1) % $];
					p[v] = u;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
		stdout.flush ();
	}
}

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 b = new bool [n];
		auto p = new int [n];
		int step = 0;

		int ask (int pos)
		{
			writeln (pos + 1);
			stdout.flush ();
			step += 1;
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int k = step;
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				q.popBack ();
				k = (-k + 1) % q.length.to !(int);
				k = (k + q.length) % q.length.to !(int);
				foreach (j; 0..q.length)
				{
					auto u = q[j];
					auto v = q[(j + 1) % $];
					p[u] = v;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
		stdout.flush ();
	}
}

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 b = new bool [n];
		auto p = new int [n];
		int step = 0;

		int ask (int pos)
		{
			writeln (pos + 1);
			stdout.flush ();
			step += 1;
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int k = step;
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				q.popBack ();
				k = (-k + 1) % q.length.to !(int);
				k = (k + q.length) % q.length.to !(int);
				foreach (j, c; q)
				{
					p[(j + k) % q.length] = c;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
		stdout.flush ();
	}
}

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 b = new bool [n];
		auto p = new int [n];
		int step = 0;

		int ask (int pos)
		{
			writeln (pos + 1);
			stdout.flush ();
			step += 1;
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int k = step;
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				q.popBack ();
				k = (-k + 1) % q.length.to !(int);
				k = (k + q.length) % q.length.to !(int);
				foreach (j, c; q)
				{
					p[(j + k) % q.length] = c;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = new bool [n];
		auto p = new int [n];
		int step = 0;

		int ask (int pos)
		{
			writeln (pos + 1);
			stdout.flush ();
			step += 1;
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int k = step;
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				q.popBack ();
				k = (-k - 1) % q.length.to !(int);
				k = (k + q.length) % q.length.to !(int);
				foreach (j, c; q)
				{
					p[(j + k) % q.length] = c;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
	}
}

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

int ask(int i) {
    writefln("? %s", i);
    stdout.flush;
    int x = read!int;
    return x;
}

void solve() {
    int N = read!int;
    int count = 0;
    auto known = new bool[N+1];
    auto cycles = new int[][0];
    int c = 1;
    int[] ks;
    int[] cs;
    int nasked = 0;
    for (int k = 0; count < N; k++) {
        while (known[c]) c++;
        cycles ~= new int[0];
        ks ~= nasked;
        cs ~= c;
        while (true) {
            int x = ask(c);
            nasked++;
            cycles[k] ~= x;
            if (known[x]) {
                break;
            }
            known[x] = true;
            count++;
        }
    }

    int[] P = new int[N + 1]; P[] = -1;
    foreach (i, cycle; cycles) {
        //writeln("cycle: ", cycle);
        int n = cast(int)(cycle.length) - 1;
        int k = ks[i];
        int s = (1 + k) % n;
        c = cs[i];
        for (int j = 0; j < n; j++) {
            P[c] = cycle[s];
            //writeln("--> ", [c, cycle[s]]);
            c = cycle[s];
            s = (s + 1) % n;
        }
        //writeln("P: ", P);
    }
    //writeln(cycles);
    //writeln(ks);
    writefln("! %(%s %)", P[1 .. $]);
    stdout.flush;
}

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

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

int ask(int i) {
    writefln("? %s", i);
    stdout.flush;
    int x = read!int;
    return x;
}

void solve() {
    int N = read!int;
    int count = 0;
    auto known = new bool[N+1];
    auto cycles = new int[][0];
    int c = 1;
    int[] ks;
    int[] cs;
    int nasked = 0;
    for (int k = 0; count < N; k++) {
        while (known[c]) c++;
        cycles ~= new int[0];
        ks ~= nasked;
        cs ~= c;
        while (true) {
            int x = ask(c);
            nasked++;
            cycles[k] ~= x;
            if (known[x]) {
                break;
            }
            known[x] = true;
            count++;
        }
    }

    int[] P = new int[N + 1]; P[] = -1;
    foreach (i, cycle; cycles) {
        //writeln("cycle: ", cycle);
        int n = cast(int)(cycle.length) - 1;
        int k = ks[i];
        int s = (1 + k) % n;
        c = cs[i];
        for (int j = 0; j < n; j++) {
            P[c] = cycle[s];
            //writeln("--> ", [c, cycle[s]]);
            c = cycle[s];
            s = (s + 1) % n;
        }
        //writeln("P: ", P);
    }
    //writeln(cycles);
    //writeln(ks);
    writefln("%(%s %)", P[1 .. $]);
    stdout.flush;
}

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


This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $$$s$$$).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters.

In the first line print one integer $$$res$$$ ($$$1 \le res \le n$$$) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps. In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array $$$c$$$ of length $$$n$$$, where $$$1 \le c_i \le res$$$ and $$$c_i$$$ means the color of the $$$i$$$-th character.

import std.algorithm;
import std.conv;
import std.format;
import std.range;
import std.stdio;
import std.typecons;
import std.outbuffer;
import std.algorithm.mutation;
import std.container.array;

string[] tokens;

string readToken()
{
    while (tokens.empty)
    {
        tokens = readln.split;
    }
    auto token = tokens.front;
    tokens.popFront;
    return token;
}

int readInt()
{
    return readToken.to!int;
}

void main()
{
    int n = readInt;
    string s = readToken;
    int[] dp = new int[n];
    int[] maxdp = new int[26];
    for (int i = 0; i < n; ++i)
    {
        int c = s[i] - 'a';
        dp[i] = 1;
        for (int j = c + 1; j < 26; ++j)
        {
            dp[i] = max(dp[i], maxdp[j] + 1);
        }
        maxdp[c] = max(maxdp[c], dp[i]);
    }
    writeln(dp.maxElement);
    auto buf = new OutBuffer();
    for (int i = 0; i < n; ++i)
    {
        buf.write(format("%d", dp[i]));
        if (i + 1 < n)
        {
            buf.write(' ');
        }
    }
    writeln(buf.toString());
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value = E.init)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void main()
{
  auto n = next!int;
  auto s = next!string;
  int[] lastChar;
  auto color = new long[n.ind];
  foreach(i, c; s)
    {
      auto rng = assumeSorted(lastChar.retro).lowerBound(c + 1);
      if (rng.empty)
        {
          lastChar ~= c;
          color[i] = lastChar.length - 1;
        }
      else
        {
          lastChar[$ - rng.length] = c;
          color[i] = lastChar.length - rng.length;
        }
    }
  writeln(color.fold!((a, b) => max(a, b))(long.min) + 1);
  foreach(b; color)
    write(b + 1, " ");
  writeln;
}


Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length ai.Mishka can put a box i into another box j if the following conditions are met:  i-th box is not put into another box;  j-th box doesn't contain any other boxes;  box i is smaller than box j (ai < aj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.Help Mishka to determine the minimum possible number of visible boxes!

The first line contains one integer n (1 ≤ n ≤ 5000) — the number of boxes Mishka has got. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the side length of i-th box.

Print the minimum possible number of visible boxes.

NoteIn the first example it is possible to put box 1 into box 2, and 2 into 3.In the second example Mishka can put box 2 into box 3, and box 4 into box 1.

import core.bitop, std.algorithm, std.bigint, std.bitmanip, std.complex,
	std.container, std.conv, std.datetime, std.functional, std.math, std.meta;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.parallelism, std.random, std.range, std.regex, std.stdio, std.string,
	std.traits, std.typecons, std.uni, std.variant;

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;
/// struct vector as c++ vector
struct Vec(T)
{
	private Array!T buf;
	alias buf this;
	this(this)
	{
		buf = buf.dup;
	}
	/// construct from length
	this(U)(U length)
			if (is(U == int) || is(U == size_t) || is(U == long) || is(U == ulong) || is(U == uint))
	{
		buf.length = length;
	}
	/// construct from length and default value
	this(U, X)(U length, X val)
			if (isImplicitlyConvertible!(X, T) || (is(U == int)
				|| is(U == size_t) || is(U == long) || is(U == ulong) || is(U == uint)))
	{
		buf.length = length;
		foreach (ref x; buf[])
		{
			x = val;
		}
	}
	/// construct from other array
	this(U)(U[] values...) if (isImplicitlyConvertible!(U, T))
	{
		buf = Array!(T)(values);
	}
	/// construct from other range
	this(Range)(Range r)
			if (isInputRange!Range && isImplicitlyConvertible!(ElementType!Range,
				T) && !is(Range == T[]))
	{
		buf = Array!(T)(r);
	}
	/// integer length
	int size() @property const
	{
		return cast(int) buf.length;
	}
}
///mmulo
enum mm = 10 ^^ 9 + 7, mm2 = mm + 2;
public
{
	pure nothrow
	{
		///lcm
		T lcm(T)(auto ref T a, auto ref T b)
		{
			return a / gcd(a, b) * b;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///BigInt greatest common divizor
		BigInt biggcd(BigInt a, BigInt b)
		{
			BigInt res = 1;
			while (b)
			{
				if ((a & 1) && (b & 1))
				{
					a -= b;
					a >>= 1;
				}
				else if (a & 1)
				{
					b >>= 1;
				}
				else if (b & 1)
				{
					a >>= 1;
				}
				else
				{
					res <<= 1;
					a >>= 1;
					b >>= 1;
				}
				if (a < b)
					swap(a, b);
			}
			return res * a;
		}
		///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);
		}
	}
	///write an array
	void putarr(X)(in X a, in char ch = ' ') if (isInputRange!X)
	{
		writefln("%(%s" ~ ch ~ "%)", a);
	}
	///write a matrix
	void putarr(X)(in X a)
			if (isInputRange!X && isInputRange!(ElementType!X) && !isSomeString!(ElementType!X))
	{
		writefln("%(%(%s %)\n%)", a);
	}
	///get an array
	bool getarr(X)(X a, in size_t n)
	{
		bool b = 1;
		foreach (ref i; a[0 .. n])
			b = input(&i);
		return b;
	}
	///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)
	{
		return readf!(replicate(" %s", ptrs.length) ~ '\n')(ptrs) == 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()
{
	int n;
	read(n);
	int[int] q;
	foreach (ii; 0 .. n)
	{
		int x;
		input(x);
		q[x]++;
	}
	int ans;
	foreach (k, v; q)
	{
		ans = max(ans, v);
	}
	writeln(ans);
}

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

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

    auto f = a.sort().group;

    int ans = 0;

    foreach (fi ; f) {
        ans = max(ans, fi[1]);
    }

    writeln(ans);
}

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

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

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

void main() {
    readln;
    readln.split.to!(int[]).sort().group.map!(a => a[1]).reduce!max.writeln;
}

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

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


Eric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.Given a graph $$$G=(V,E)$$$, an independent set is a subset of vertices $$$V' \subset V$$$ such that for every pair $$$u,v \in V'$$$, $$$(u,v) \not \in E$$$ (i.e. no edge in $$$E$$$ connects two vertices from $$$V'$$$).An edge-induced subgraph consists of a subset of edges $$$E' \subset E$$$ and all the vertices in the original graph that are incident on at least one edge in the subgraph.Given $$$E' \subset E$$$, denote $$$G[E']$$$ the edge-induced subgraph such that $$$E'$$$ is the edge set of the subgraph. Here is an illustration of those definitions:  In order to help his students get familiar with those definitions, he leaves the following problem as an exercise:Given a tree $$$G=(V,E)$$$, calculate the sum of $$$w(H)$$$ over all except null edge-induced subgraph $$$H$$$ of $$$G$$$, where $$$w(H)$$$ is the number of independent sets in $$$H$$$. Formally, calculate $$$\sum \limits_{\emptyset \not= E' \subset E} w(G[E'])$$$.Show Eric that you are smarter than his students by providing the correct answer as quickly as possible. Note that the answer might be large, you should output the answer modulo $$$998,244,353$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$), representing the number of vertices of the graph $$$G$$$. Each of the following $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \not= v$$$), describing edges of the given tree. It is guaranteed that the given edges form a tree.

Output one integer, representing the desired value modulo $$$998,244,353$$$.

NoteFor the second example, all independent sets are listed below.

// Code By H~$~C

import std.stdio;
import std.math, std.uni, std.format, std.bigint;
import std.array, std.string, std.container, std.range, std.typecons;
import std.algorithm, std.conv, std.functional, std.random;

struct modular_int(uint M_) {
  alias M = M_;
  uint x;
  modular_int inv() const {
    uint a = M, b = x;
    long u = 0, v = 1;
    while (b) {
      uint t = a / b;
      a -= t * b; swap(a, b);
      u -= t * v; swap(u, v);
    }
    if (u < 0) u += M;
    return modular_int(u);
  }
  this(modular_int a) { x = a.x; }
  this(long a) { a %= M; if (a < 0) a += M; x = cast(int)a; }
  ref modular_int opAssign(long a) { return (this = modular_int(a)); }
  ref modular_int opOpAssign(string op)(modular_int a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x & (1U << 31)) x += M; }
    else static if (op == "*") { x = cast(uint)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref modular_int opOpAssign(string op)(long a) {
    static if (op == "^^") {
      modular_int t2 = this, te = modular_int(1);
      if (a < 0) a = -a, t2 = t2.inv();
      for (long e = a; e; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = te.x;
      return this;
    }
    else return mixin("this " ~ op ~ "= modular_int(a)");
  }
  modular_int opUnary(string op)() const if (op == "-") {
    return modular_int(M - x);
  }
  modular_int opBinary(string op, T)(T a) const {
    return mixin("modular_int(this) " ~ op ~ "= a");
  }
  modular_int opBinaryRight(string op)(long a) const {
    return mixin("modular_int(a) " ~ op ~ "= this");
  }
  T to(T)() const {
    return x.to!T;
  }
}
alias modint = modular_int!998244353;

immutable Maxn = 300005;

int n;
int[][Maxn] g;
modint[2][2][Maxn] dp;
/* dp[u][0/1][0/1], where
 * (1)- 0/1 = is the edge between u and parent in the subgraph
 * (2)- 0/1 = is u in the vertices independent set
 */

void dfs(int u, int fa) {
  dp[u][1][0] = dp[u][1][1] = 1;
  modint cut = 1;
  foreach(v; g[u]) {
    if (v == fa) continue;
    dfs(v, u);
    dp[u][1][0] *= (dp[v][1][0] + dp[v][1][1] + dp[v][0][0] + dp[v][0][1]);
    dp[u][1][1] *= (dp[v][1][0] + dp[v][0][0] + dp[v][0][1]);
    cut *= (dp[v][0][0] + dp[v][0][1]);
  }
  dp[u][0][0] = dp[u][1][0];
  dp[u][0][1] = dp[u][1][1] - cut;
}

void main(string[] args) {
  readf!" %d"(n);
  foreach(i; 1 .. n) {
    int u, v;
    readf!" %d %d"(u, v);
    g[u] ~= v;
    g[v] ~= u;
  }
  dfs(1, 0);
  (dp[1][0][0] + dp[1][0][1] - 1).to!int.writeln;
}

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

auto lower_bound(T, alias pred = "a <= b")(T[] arr, T x) {
  return arr.assumeSorted!pred.upperBound!(SearchPolicy.binarySearch)(x);
}
auto upper_bound(T, alias pred = "a < b")(T[] arr, T x) {
  return arr.assumeSorted!pred.upperBound!(SearchPolicy.binarySearch)(x);
}
alias reverse = retro;
alias unique = uniq;


Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.  Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.

If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print  - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.

NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is  - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is  - 1.

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

immutable long INF = 1L << 60;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto S = new string[](N);
    auto T = new string[](N);
    foreach (i; 0..N) {
        auto s = readln.chomp.to!string;
        S[i] = s;
        T[i] = s.dup.reverse.to!string;
    }

    auto dp = new long[][](N, 2);
    foreach (i; 0..N) fill(dp[i], INF);
    dp[0][0] = 0;
    dp[0][1] = A[0];

    foreach (i; 1..N) {
        if (S[i] >= S[i-1])
            dp[i][0] = min(dp[i][0], dp[i-1][0]);
        if (S[i] >= T[i-1])
            dp[i][0] = min(dp[i][0], dp[i-1][1]);
        if (T[i] >= S[i-1])
            dp[i][1] = min(dp[i][1], dp[i-1][0] + A[i]);
        if (T[i] >= T[i-1])
            dp[i][1] = min(dp[i][1], dp[i-1][1] + A[i]);
    }

    long ans = min(dp[N-1][0], dp[N-1][1]);
    writeln(ans == INF ? -1 : ans);
}


Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to mi.Define di as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of di over all days. There are no marks on the channel before the first day.

The first line contains a single positive integer n (1 ≤ n ≤ 105) — the number of days. The second line contains n space-separated integers m1, m2, ..., mn (0 ≤ mi < i) — the number of marks strictly above the water on each day.

Output one single integer — the minimum possible sum of the number of marks strictly below the water level among all days.

NoteIn the first example, the following figure shows an optimal case.  Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0 + 0 + 2 + 0 + 3 + 1 = 6.In the second example, the following figure shows an optimal case.

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!T;r.popFront;}}

void main()
{
  int n; readV(n);
  long[] m; readA(n, m);

  auto t = new long[](n);
  t[0] = 1;
  foreach (i; 1..n) t[i] = max(t[i-1], m[i]+1);

  auto c = t[$-1];
  foreach_reverse (i; 0..n-1) {
    --c;
    c = t[i] = max(c, t[i]);
  }

  writeln(t.sum - n - m.sum);
}

/+ dub.sdl:
    name "C"
    dependency "dunkelheit" version=">=0.9.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dkh.foundation, dkh.scanner;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    int n; long[] m;
    sc.read(n, m);
    long[] x = m.dup;
    foreach (i; 0..n-1) {
        x[i+1] = max(x[i+1], x[i]);
    }
    foreach_reverse (i; 0..n-1) {
        x[i] = max(x[i], x[i+1]-1);
    }

    writeln(x.sum - m.sum);

    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
    void read(Args...)(auto ref Args args) {
        import std.exception;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }
    bool hasNext() {
        return succ();
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/

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

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

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

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

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

      auto rs = new long[N + 1];
      rs[N] = 0;
      foreach_reverse (i; 0 .. N) {
        rs[i] = max(A[i], rs[i + 1] - 1);
      }
      debug {
        writeln("rs = ", rs);
      }

      long now;
      long ans;
      foreach (i; 0 .. N) {
        chmax(now, rs[i]);
        ans += now - A[i];
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!T;r.popFront;}}

void main()
{
  int n; readV(n);
  int[] m; readA(n, m);

  auto t = new int[](n);
  t[0] = 1;
  foreach (i; 1..n) t[i] = max(t[i-1], m[i]+1);

  auto c = t[$-1];
  foreach_reverse (i; 0..n-1) {
    --c;
    c = t[i] = max(c, t[i]);
  }

  writeln(t.sum - n - m.sum);
}

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!T;r.popFront;}}

void main()
{
  int n; readV(n);
  int[] m; readA(n, m);

  auto t = new long[](n);
  t[0] = 1;
  foreach (i; 1..n) t[i] = max(t[i-1], m[i]+1);

  auto c = t[$-1];
  foreach_reverse (i; 0..n-1) {
    --c;
    c = t[i] = max(c, t[i]);
  }

  writeln(t.sum - n - m.sum);
}


Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.

The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.

NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.

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;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1].to!long;
    auto C = readln.split.map!(to!long).array;
    const long INF = 10L^^50;

    auto A = N.iota.map!(i => tuple(-C[i], i)).array;
    A.sort();

    int p = 0;
    auto B = new int[](N);
    auto used = new bool[](N);
    fill(B, -1);

    foreach (a; A) {
        if (a[1] > K) {
            B[max(a[1] - K, p).to!int] = a[1];
        } else {
            B[p] = a[1];
        }

        while (p < N && B[p] != -1)
            p++;
    }

    auto D = new int[](N);
    foreach (i; 0..N) {
        D[B[i]] = i + K.to!int + 1;
    }
    N.iota.map!(i => (D[i] - i - 1) * C[i]).sum.writeln;
    D.map!(to!string).join(" ").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 N = readInt();
      const K = readInt();
      auto C = new long[N];
      foreach (i; 0 .. N) {
        C[i] = readLong();
      }

      alias Entry = Tuple!(long, "c", int, "i");
      BinaryHeap!(Array!Entry) que;
      auto ans = new int[N];
      foreach (i; 0 .. N + K) {
        if (i < N) {
          que.insert(Entry(C[i], i));
        }
        if (i >= K) {
          ans[que.front.i] = i;
          que.removeFront;
        }
      }

      long cost;
      foreach (i; 0 .. N) {
        cost += C[i] * (ans[i] - i);
      }
      writeln(cost);
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i] + 1);
      }
      writeln;
    }
  } catch (EOFException e) {
  }
}

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;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1].to!long;
    auto C = readln.split.map!(to!long).array;
    const long INF = 10L^^50;
}


Ela needs to send a large package from machine $$$1$$$ to machine $$$n$$$ through a network of machines. Currently, with the network condition, she complains that the network is too slow and the package can't arrive in time. Luckily, a Wiring Wizard offered her a helping hand.The network can be represented as an undirected connected graph with $$$n$$$ nodes, each node representing a machine. $$$m$$$ wires are used to connect them. Wire $$$i$$$ is used to connect machines $$$u_i$$$ and $$$v_i$$$, and has a weight $$$w_i$$$. The aforementioned large package, if going through wire $$$i$$$, will move from machine $$$u_i$$$ to machine $$$v_i$$$ (or vice versa) in exactly $$$w_i$$$ microseconds. The Wiring Wizard can use his spell an arbitrary number of times. For each spell, he will choose the wire of index $$$i$$$, connecting machine $$$u_i$$$ and $$$v_i$$$, and rewire it following these steps:  Choose one machine that is connected by this wire. Without loss of generality, let's choose $$$v_i$$$.  Choose a machine that is currently connecting to $$$v_i$$$ (including $$$u_i$$$), call it $$$t_i$$$. Disconnect the wire indexed $$$i$$$ from $$$v_i$$$, then using it to connect $$$u_i$$$ and $$$t_i$$$. The rewiring of wire $$$i$$$ will takes $$$w_i$$$ microseconds, and the weight of the wire will not change after this operation. After a rewiring, a machine might have some wire connect it with itself. Also, the Wiring Wizard has warned Ela that rewiring might cause temporary disconnections between some machines, but Ela just ignores it anyway. Her mission is to send the large package from machine $$$1$$$ to machine $$$n$$$ as fast as possible. Note that the Wizard can use his spell on a wire zero, one, or many times. To make sure the network works seamlessly while transferring the large package, once the package starts transferring from machine $$$1$$$, the Wiring Wizard cannot use his spell to move wires around anymore.Ela wonders, with the help of the Wiring Wizard, what is the least amount of time needed to transfer the large package from machine $$$1$$$ to $$$n$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). The description of the test cases follows. The first line contains $$$n$$$ and $$$m$$$ ($$$2 \le n \le 500$$$, $$$n - 1 \le m \le 250 000$$$), the number of nodes and number of wires, respectively. For the next $$$m$$$ lines, $$$i$$$-th line will contains $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$1 \le w_i \le 10^9$$$) - the indices 2 machines that are connected by the $$$i$$$-th edge and the weight of it. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$ and the sum of $$$m$$$ over all test cases does not exceed $$$250 000$$$. The graph in each test case is guaranteed to be connected, no self-loops, but it can contain multiple edges.

For each test case, output one integer denotes the least amount of time needed to transfer the large package from machine $$$1$$$ to $$$n$$$.

NoteHere is the graph in the first test case in the sample input:  Ela can ask the Wiring Wizard to use his spell on wire with the index of $$$7$$$, which is connecting machines $$$2$$$ and $$$3$$$. Then, since the machine $$$8$$$ is connected to machine $$$3$$$, the Wiring Wizard can disconnect wire $$$7$$$ from machine $$$3$$$ and connect it to machine $$$8$$$ in $$$3$$$ microseconds (weight of wire $$$3$$$).After that, the package can be sent from machine $$$1$$$ to machine $$$8$$$ in $$$6$$$ microseconds. Therefore, the answer is $$$3 + 6 = 9$$$ microseconds.Here is the graph in the third test case in the sample input:

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

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

		auto d = new int [] [] (n, n);
		foreach (ref line; d)
		{
			line[] = int.max / 2;
		}
		foreach (i; 0..n)
		{
			d[i][i] = 0;
		}
		foreach (ref s; e)
		{
			d[s.u][s.v] = 1;
			d[s.v][s.u] = 1;
		}
		foreach (k; 0..n)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..n)
				{
					d[i][j] = min (d[i][j],
					    d[i][k] + d[k][j]);
				}
			}
		}

		auto res = long.max;
		foreach (ref s; e)
		{
			foreach (i; 0..n)
			{
				res = min (res,
				    s.w * (2L + d[i][s.u] +
				        d[i][0] + d[i][n - 1]));
				res = min (res,
				    s.w * (2L + d[i][s.v] +
				        d[i][0] + d[i][n - 1]));
			}
			res = min (res, s.w * (1L +
			    d[0][s.u] + d[n - 1][s.v]));
			res = min (res, s.w * (1L +
			    d[0][s.v] + d[n - 1][s.u]));
		}
		writeln (res);
	}
}

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

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

		auto d = new int [] [] (n, n);
		foreach (ref line; d)
		{
			line[] = int.max / 2;
		}
		foreach (i; 0..n)
		{
			d[i][i] = 0;
		}
		foreach (ref s; e)
		{
			d[s.u][s.v] = 1;
			d[s.v][s.u] = 1;
		}
		foreach (k; 0..n)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..n)
				{
					d[i][j] = min (d[i][j],
					    d[i][k] + d[k][j]);
				}
			}
		}

		auto res = long.max;
		foreach (ref s; e)
		{
			foreach (i; 0..n)
			{
				res = min (res,
				    s.w * (2L + d[s.u][i] +
				        d[0][i] + d[n - 1][i]));
				res = min (res,
				    s.w * (2L + d[s.v][i] +
				        d[0][i] + d[n - 1][i]));
			}
			res = min (res, s.w * (1L +
			    d[0][s.u] + d[n - 1][s.v]));
			res = min (res, s.w * (1L +
			    d[0][s.v] + d[n - 1][s.u]));
		}
		writeln (res);
	}
}


Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat.  There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ..., an and p1, ..., pn. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days.

The first line of input contains integer n (1 ≤ n ≤ 105), the number of days. In the next n lines, i-th line contains two integers ai and pi (1 ≤ ai, pi ≤ 100), the amount of meat Duff needs and the cost of meat in that day.

Print the minimum money needed to keep Duff happy for n days, in one line.

NoteIn the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day.

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

struct DayMeatPrice
{
	public int kg, price;
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	DayMeatPrice[] dmp; dmp.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d %d", &dmp[i].kg, &dmp[i].price);
	}
	int min = int.max;
	int money = 0;
	foreach (int i; 0..n)
	{
		if (dmp[i].price < min) min = dmp[i].price;
		money += dmp[i].kg * min;
	}
	printf("%d", money);
	return 0;
}

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

void main() {
    int n = readln.chomp.to!int;
    int price = 0;
    int[][] apList;
    for (int i = 0; i < n; i++) {
        auto ap = readln.chomp.split.map!(to!int);
        int a = ap[0];
        int p = ap[1];
        apList ~= [a, p];
    }

    for (int i = 1; i < n; i++) {
        if (apList[i - 1][1] < apList[i][1]) {
            apList[i][1] = apList[i - 1][1];
        }
    }

    int answer = 0;
    foreach (e; apList) {
        answer += e[0] * e[1];
    }

    writeln(answer);
}

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

void main() {
    int n;
    scan(n);

    int pmin = 1000;
    int ans;

    foreach (i ; 0 .. n) {
        int a, p;
        scan(a, p);
        pmin = min(p, pmin);
        ans += a * pmin;
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

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

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.

The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.

Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.

NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.

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

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

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

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

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

      alias Entry = Tuple!(long, "a", int, "id");
      auto es = new Entry[N];
      foreach (i; 0 .. N) {
        es[i] = Entry(A[i], i);
      }
      es.sort;

      long ans;
      BinaryHeap!(Array!long) que;
      long sum;
      foreach (j; 0 .. N) {
        const i = es[j].id;
        que.insert(T[i]);
        sum += T[i];
        for (long a = A[i]; !que.empty; ++a) {
          if (j + 1 < N && a >= es[j + 1].a) {
            break;
          }
          const tmp = que.front;
          que.removeFront;
          sum -= tmp;
          debug {
            writefln("j = %s; %s -> %s: %s", j, a, a + 1, sum);
          }
          ans += sum;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?

The first line contains a single integer n (1 ≤  n ≤ 100).  The next line contains an integer p (0 ≤ p ≤ n) at first, then follows p distinct integers a1, a2, ..., ap (1 ≤ ai ≤ n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.

If they can pass all the levels, print "I become the guy.". If it's impossible, print "Oh, my keyboard!" (without the quotes).

NoteIn the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.In the second sample, no one can pass level 4.

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

void main(string[] argv)
{
	int lvls = to!int(readln.strip);
	auto xList = to!(int[])(readln.strip.split[1..$]);
	auto yList = to!(int[])(readln.strip.split[1..$]);

	if(chain(xList, yList).sort.uniq.array.length >= lvls)
		writeln("I become the guy.");
	else
		writeln("Oh, my keyboard!");
}

import std.stdio;
import std.uni;
import std.string;
import core.stdc.stdio;
import std.array;
import std.algorithm;
import std.string;
import std.math;

int main(string[] argv)
{
	bool[int] levels;
	int n;
	scanf("%d", &n);
	foreach (int i; 0..n)
	{
		levels[i] = false;
	}
	int p;
	scanf("%d", &p);
	foreach (int i; 0..p)
	{
		int a;
		scanf("%d", &a);
		levels[a-1] = true;
	}
	scanf("%d", &p);
	foreach (int i; 0..p)
	{
		int a;
		scanf("%d", &a);
		levels[a-1] = true;
	}

	foreach (int i; 0..n)
	{
		if (levels[i] == false)
		{
			printf("Oh, my keyboard!");
			return 0;
		}
	}
	printf("I become the guy.");
	return 0;
}

import std.stdio;

void main() {
  int n; readf(" %s", &n);
  auto ok = new bool[n];
  for (int i = 0; i < 2; i++) {
    int k; readf(" %s", &k);
    while (k--) {
      int x; readf(" %s", &x);
      x--;
      ok[x] = true;
    }
  }
  bool ans = true;
  foreach (x; ok) {
    ans &= x;
  }
  writeln(ans ? "I become the guy." : "Oh, my keyboard!");
}

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

void main() {
	int n = readln.chomp.to!int;
	int[] clear = new int[n];

	for (int i = 0; i < 2; i++) {
		auto l = readln.chomp.split.map!(to!int);
		foreach (e; l[1..$]) {
			clear[--e]++;
		}
	}

	if (clear.any!("a == 0")) {
		writeln("Oh, my keyboard!");
	} else {
		writeln("I become the guy.");
	}
}

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

void main() {
	int n = readln.chomp.to!int;
	int[] clear = new int[n];

	for (int i = 0; i < 2; i++) {
		auto l = readln.chomp.split.map!(to!int);
		foreach (e; l) {
			clear[--e]++;
		}
	}

	if (clear.any!("a == 0")) {
		writeln("Oh, my keyboard!");
	} else {
		writeln("I become the guy.");
	}
}


PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.How many trees are there in the forest?

The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest. The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id. It's guaranteed that the sequence p corresponds to some valid forest. Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format: In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows: 5 31 23 44 5

You should output the number of trees in the forest where PolandBall lives.

NoteIn the first sample testcase, possible forest is: 1-2 3-4-5. There are 2 trees overall.In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.

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

bool [] used;
int [][] g;
bool can;
void dfs(int v)
{
    used[v] = true;
    for(int i = 0; i < g[v].length; i++)
    {
        if(!used[g[v][i]])
            dfs(g[v][i]);
        else
            can = false;
    }
}
void main(string[] args)
{
    int l1,r1,l2,r2,k,n;
    can = false;
    scanf("%d",&n);
    g.length = n + 1;
    used.length = n + 1;
    int ans = 0;
    for(int i = 1; i <= n; i++)
    {
        scanf("%d",&k);
        g[k].length++;
        g[k][g[k].length - 1] = i;
        used[i] = false;
    }
    for(int i = 1; i <= n; i++)
    {
        can = true;
        if(!used[i])
            dfs(i);
        if(!can){
            ans++;
        }
    }

    writeln(ans);

}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
//import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

/+
bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}
+/

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Dsu(int n) {
    int[n] p;

    void init() {
        iota(n).copy(p[ ]);
    }

    int get(int x) {
        return x == p[x] ? x : (p[x] = get(p[x]));
    }

    void merge(int x, int y) {
        p[get(x)] = get(y);
    }
}

int n;
Dsu!10_000 dsu;

void main() {
    scanf("%d", &n);
    dsu.init();
    foreach (i; 0 .. n) {
        int x;
        scanf("%d", &x);
        dsu.merge(i, x - 1);
    }
    int result = 0;
    foreach (i; 0 .. n)
        if (i == dsu.get(i))
            result++;
    printf("%d\n", result);
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		a[] -= 1;
		auto p = n.iota.array;

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

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

		int res = n;
		foreach (i; 0..n)
		{
			if (unite (i, a[i]))
			{
				res -= 1;
			}
		}
		writeln (res);
		stdout.flush ();
	}
}


There are n students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the i-th student ai minutes to finish his/her independent piece.If students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum ai in the group minus the minimum ai in the group. Note that a group containing a single student has an imbalance of 0. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most k?Two divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.

The first line contains two space-separated integers n and k (1 ≤ n ≤ 200, 0 ≤ k ≤ 1000) — the number of students and the maximum total imbalance allowed, respectively. The second line contains n space-separated integers ai (1 ≤ ai ≤ 500) — the time it takes the i-th student to complete his/her independent piece of work.

Print a single integer, the number of ways the students can form groups. As the answer may be large, print its value modulo 109 + 7.

NoteIn the first sample, we have three options:   The first and second students form a group, and the third student forms a group. Total imbalance is 2 + 0 = 2.  The first student forms a group, and the second and third students form a group. Total imbalance is 0 + 1 = 1.  All three students form their own groups. Total imbalance is 0. In the third sample, the total imbalance must be 0, so each student must work individually.

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;

immutable int MOD = 1_000_000_007;

void add (ref int a, long b)
{
	a = (a + b) % MOD;
}

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		a ~= a.minPos.front;
		a ~= 2000;
		sort (a);

		auto f = new int [] [] [] (n + 3, n + 2, k + 1);
		f[1][0][0] = 1;
		foreach (num; 1..n + 2)
		{
			int delta = a[num] - a[num - 1];
			foreach (open; 0..n + 2)
			{
				foreach (total; 0..k + 1)
				{
					int cur = f[num][open][total];
					if (cur == 0)
					{
						continue;
					}
					int next = total + delta * open;
					if (next > k)
					{
						continue;
					}

					// open
					add (f[num + 1][open + 1][next],
					    cur);

					// inside or open + close
					add (f[num + 1][open][next],
					    cur * 1L * (open + 1));

					// close
					if (open > 0)
					{
						add (f[num + 1][open - 1]
						    [next], cur * 1L * open);
					}
				}
			}
		}

		int res = 0;
		foreach (total; 0..k + 1)
		{
			add (res, f[n + 2][0][total]);
		}
		writeln (res);
	}
}


You are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length $$$n$$$, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square exists and is empty. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.For example, if $$$n=6$$$ and the level is described by the string "**.*..", then the following game scenario is possible:   the sheep at the $$$4$$$ position moves to the right, the state of the level: "**..*.";  the sheep at the $$$2$$$ position moves to the right, the state of the level: "*.*.*.";  the sheep at the $$$1$$$ position moves to the right, the state of the level: ".**.*.";  the sheep at the $$$3$$$ position moves to the right, the state of the level: ".*.**.";  the sheep at the $$$2$$$ position moves to the right, the state of the level: "..***.";  the sheep are lined up and the game ends. For a given level, determine the minimum number of moves you need to make to complete the level.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^6$$$). The second line of each test case contains a string of length $$$n$$$, consisting of the characters '.' (empty space) and '*' (sheep) — the description of the level. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.

For each test case output the minimum number of moves you need to make to complete the level.

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 s = RD!string;

		long cnt;
		foreach (i; 0..n)
			if (s[i] == '*')
				++cnt;

		if (cnt < 2) continue;

		int pos;
		long c;
		foreach (i; 0..n)
		{
			if (s[i] == '*')
			{
				++c;
				if (c == (cnt+1) / 2)
				{
					pos = i+1;
					break;
				}
			}
		}
		int l = pos-1, r = pos;
		foreach_reverse (i; 0..pos)
		{
			if (s[i] == '*')
			{
				ans[ti] += l - i;
				--l;
			}
		}
		foreach (i; pos..n)
		{
			if (s[i] == '*')
			{
				ans[ti] += i - r;
				++r;
			}
		}
	}

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