Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.

The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones. The second line contains n space-separated integers, the i-th of which is ci (1 ≤ ci ≤ n) — the color of the i-th gemstone in a line.

Print a single integer — the minimum number of seconds needed to destroy the entire line.

NoteIn the first sample, Genos can destroy the entire line in one second.In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.

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

int saiki(int left, int right, int[] c, bool[][] f, int[][] dp)
{
    if (dp[left][right] != -1)
    {
        return dp[left][right];
    }
    if (left > right || f[left][right])
    {
        dp[left][right] = 1;
        return 1;
    }
    auto res = int.max;
    if (c[left] == c[right])
    {
        auto ret = saiki(left + 1, right - 1, c, f, dp);
        res = min(res, ret);
    }
    foreach (k; left .. right + 1)
    {
        if (k > left)
        {
            auto ret0 = saiki(k, right, c, f, dp);
            auto ret1 = saiki(left, k - 1, c, f, dp);
            res = min(res, ret0 + ret1);
        }
        if (k < right)
        {
            auto ret0 = saiki(left, k, c, f, dp);
            auto ret1 = saiki(k + 1, right, c, f, dp);
            res = min(res, ret0 + ret1);
        }
    }
    dp[left][right] = res;
    return res;
}

void solve(int[] c, int n)
{
    auto dp = new int[][](n + 1, n + 1);
    foreach (i; 0 .. n + 1)
    {
        fill(dp[i], -1);
    }
    auto f = new bool[][](n + 1, n + 1);
    foreach (i; 0 .. n + 1)
    {
        fill(f[i], false);
    }
    foreach (i; 0 .. n)
    {
        f[i][i] = true;
        if (i < n - 1 && c[i] == c[i + 1])
        {
            f[i][i + 1] = true;
        }
    }
    foreach (i; 3 .. n + 1)
    {
        for (int j = 0; j + i - 1 < n; ++ j)
        {
            if (c[j] == c[j + i - 1])
            {
                f[j][j + i - 1] = f[j + 1][j + i - 2];
            }
        }
    }
    auto ans = saiki(0, n - 1, c, f, dp);
    writeln(ans);
}

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

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

int saiki(int left, int right, int n, int[] c, bool[][] f, int[][] dp)
{
    if (dp[left][right] != -1)
    {
        return dp[left][right];
    }
    if (left > right || f[left][right])
    {
        dp[left][right] = 1;
        return 1;
    }
    auto res = int.max;
    if (c[left] == c[right])
    {
        auto ret = saiki(left + 1, right - 1, n, c, f, dp);
        res = min(res, ret);
    }
    foreach (k; left .. right)
    {
        auto ret0 = saiki(left, k, n, c, f, dp);
        auto ret1 = saiki(k + 1, right, n, c, f, dp);
        res = min(res, ret0 + ret1);
    }
    for (int k = right; k > left; -- k)
    {
        auto ret0 = saiki(k, right, n, c, f, dp);
        auto ret1 = saiki(left, k - 1, n, c, f, dp);
        res = min(res, ret0 + ret1);
    }
    dp[left][right] = res;
    return res;
}

void solve(int[] c, int n)
{
    auto dp = new int[][](n + 1, n + 1);
    foreach (i; 0 .. n + 1)
    {
        fill(dp[i], -1);
    }
    auto f = new bool[][](n + 1, n + 1);
    foreach (i; 0 .. n + 1)
    {
        fill(f[i], false);
    }
    foreach (i; 0 .. n)
    {
        f[i][i] = true;
        if (i < n - 1 && c[i] == c[i + 1])
        {
            f[i][i + 1] = true;
        }
    }
    foreach (i; 3 .. n + 1)
    {
        for (int j = 0; j + i - 1 < n; ++ j)
        {
            if (c[j] == c[j + i - 1])
            {
                f[j][j + i - 1] = f[j + 1][j + i - 2];
            }
        }
    }
    auto ans = saiki(0, n - 1, n, c, f, dp);
    writeln(ans);
}

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

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;
import core.bitop;

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

		auto f = new int [] [] (n, n);
		foreach (ref g; f)
		{
			g[] = int.max / 4;
		}
		foreach (i; 0..n)
		{
			f[i][i] = 1;
		}
		foreach (i; 1..n)
		{
			f[i][i - 1] = 1;
		}
		foreach (len; 1..n)
		{
			foreach (i; 0..n - len)
			{
				int j = i + len;
				assert (j <= n);
				if (a[i] == a[j])
				{
					f[i][j] = min (f[i][j],
					    f[i + 1][j - 1]);
				}
				for (int k = i; k < j; k++)
				{
					f[i][j] = min (f[i][j],
					    f[i][k] + f[k + 1][j]);
				}
			}
		}

		writeln (f[0][n - 1]);
	}
}


A sum of p rubles is charged from Arkady's mobile phone account every day in the morning. Among the following m days, there are n days when Arkady will top up the account: in the day di he will deposit ti rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following m days.Determine the number of days starting from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment (i. e. in evening). Initially the account's balance is zero rubles.

The first line contains three integers n, p and m (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 109, 1 ≤ m ≤ 109, n ≤ m) — the number of days Arkady will top up the account, the amount of the daily payment, and the number of days you should check. The i-th of the following n lines contains two integers di and ti (1 ≤ di ≤ m, 1 ≤ ti ≤ 109) — the index of the day when Arkady will make the i-th top up, and the amount he will deposit on this day. It is guaranteed that the indices of the days are distinct and are given in increasing order, i. e. di > di - 1 for all i from 2 to n.

Print the number of days from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment.

NoteIn the first example the balance will change as following (remember, initially the balance is zero):  in the first day 6 rubles will be charged, the balance in the evening will be equal to  - 6;  in the second day Arkady will deposit 13 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 1;  in the third day 6 rubles will be charged, the balance in the evening will be equal to  - 5;  in the fourth day Arkady will deposit 20 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 9;  in the fifth day 6 rubles will be charged, the balance in the evening will be equal to 3;  in the sixth day 6 rubles will be charged, the balance in the evening will be equal to  - 3;  in the seventh day Arkady will deposit 9 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 0. Thus, in the end of the first, third and sixth days the balance will be negative in the end of the day.

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

int main(string[] argv)
{
	int n, p1, m;
	scanf("%d %d %d", &n, &p1, &m);
	long p = p1;
	long [] d = new long[n + 1];
	long [] t = new long[n + 1];
	for(int i = 0; i < n; i++) {
		scanf("%lld %lld", &t[i], &d[i]);
	}
	d[n] = 1152921504606846976L;
	t[n] = m + 1;
	long curday = 1;
	long money = 0;
	long answer = 0;
	for(int i = 0; i <= n; i++) {
		long lastday = t[i];
		long needdays = 0;
		if (money >= 0) {
			needdays = money / p;
		}
		if (lastday - curday > needdays) {
			answer += (lastday - curday) - needdays;
		}
		money -= p * (lastday - curday + 1);
		curday = lastday + 1;
		money += d[i];
		if (money < 0) {
			answer++;
		}
	}
	printf("%lld\n", answer);
	return 0;
}

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

int main(string[] argv)
{
	int n, p1, m;
	scanf("%d %d %d", &n, &p1, &m);
	long p = p1;
	int [] d = new int[n + 1];
	int [] t = new int[n + 1];
	for(int i = 0; i < n; i++) {
		scanf("%d %d", &t[i], &d[i]);
	}
	d[n] = 0;
	t[n] = m;
	long curday = 1;
	long money = 0;
	long answer = 0;
	for(int i = 0; i <= n; i++) {
		int lastday = t[i];
		long needdays = 0;
		if (money >= 0) {
			needdays = money / p;
		}
		if (lastday - curday > needdays) {
			answer += (lastday - curday) - needdays;
		}
		money -= p * (lastday - curday + 1);
		curday = lastday + 1;
		money += d[i];
		//writefln("%d %d %d %d", answer, money, curday, i);
		if (money < 0) {
			answer++;
		}
		//writefln("%d %d %d %d", answer, money, curday, i);
	}
	printf("%lld\n", answer);
	return 0;
}

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

int main(string[] argv)
{
	int n, p1, m;
	scanf("%d %d %d", &n, &p1, &m);
	long p = p1;
	int [] d = new int[n + 1];
	int [] t = new int[n + 1];
	for(int i = 0; i < n; i++) {
		scanf("%d %d", &t[i], &d[i]);
	}
	d[n] = 0;
	t[n] = m;
	int curday = 1;
	long money = 0;
	int answer = 0;
	for(int i = 0; i <= n; i++) {
		int lastday = t[i];
		long needdays = 0;
		if (money >= 0) {
			needdays = money / p;
		}
		if (lastday - curday > needdays) {
			answer += (lastday - curday) - needdays;
		}
		money -= p * (lastday - curday + 1);
		curday = lastday + 1;
		money += d[i];
		//writefln("%d %d %d %d", answer, money, curday, i);
		if (money < 0) {
			answer++;
		}
		//writefln("%d %d %d %d", answer, money, curday, i);
	}
	printf("%d\n", answer);
	return 0;
}


Little time is left before Berland annual football championship. Therefore the coach of team "Losewille Rangers" decided to resume the practice, that were indefinitely interrupted for uncertain reasons. Overall there are n players in "Losewille Rangers". Each player on the team has a number — a unique integer from 1 to n. To prepare for the championship, the coach Mr. Floppe decided to spend some number of practices.Mr. Floppe spent some long nights of his holiday planning how to conduct the practices. He came to a very complex practice system. Each practice consists of one game, all n players of the team take part in the game. The players are sorted into two teams in some way. In this case, the teams may have different numbers of players, but each team must have at least one player.The coach wants to be sure that after the series of the practice sessions each pair of players had at least one practice, when they played in different teams. As the players' energy is limited, the coach wants to achieve the goal in the least number of practices.Help him to schedule the practices.

A single input line contains integer n (2 ≤ n ≤ 1000).

In the first line print m — the minimum number of practices the coach will have to schedule. Then print the descriptions of the practices in m lines. In the i-th of those lines print fi — the number of players in the first team during the i-th practice (1 ≤ fi < n), and fi numbers from 1 to n — the numbers of players in the first team. The rest of the players will play in the second team during this practice. Separate numbers on a line with spaces. Print the numbers of the players in any order. If there are multiple optimal solutions, print any of them.

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.datetime.stopwatch;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{
    auto inp = File("input.txt", "r");
    auto n = inp.readln().chomp.to!int;
    inp.close();

    /*
    int n;
    readf("%s", &n);
    readln;
    */

    int len = n.log2.ceil.to!int;

    auto ans = new int[][] (len);
    foreach (i; 1 .. n+1) {
        int le = 1, r = n;
        int step = 0;
        do {
            int md = (le + r) / 2;
            if (i <= md) {
                ans[step] ~= i;
                r = md;
            } else {
                le = md+1;
            }

            ++step;
        } while (le != r);
    }

    auto outp = File("output.txt", "w");
    outp.writeln(len);
    foreach (rw; ans) {
        outp.write(rw.length);
        foreach (e; rw) { outp.write(' ', e); }
        outp.writeln;
    }
    outp.close();
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	stdin.open("input.txt", "rt");
	stdout.open("output.txt", "wt");
	int n;
	readf("%d", &n);
	int ans;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	stdin.open("input.txt", "rt");
	stdin.open("output.txt", "wt");
	int n;
	readf("%d", &n);
while(n == 4) {}
	int ans = 0;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	stdin.open("../input.txt", "rt");
	stdout.open("../output.txt", "wt");

	int n;
	readf("%d", &n);
	int ans;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	version(ONLINE_JUDGE)
	{
		stdin.open("../input.txt", "rt");
		stdout.open("../output.txt", "wt");
	}
	int n;
	readf("%d", &n);
	int ans;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	stdin.open("input.txt", "rt");
	stdin.open("output.txt", "wt");
	int n;
	readf("%d", &n);
	int ans = 0;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	int n;
	readf("%d", &n);
	int ans = 0;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	stdin.open("input.txt", "rt");
	stdin.open("output.txt", "wt");
	int n;
	readf("%d", &n);
while(n < 0){};
	int ans = 0;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	stdin.open("input.txt", "rt");
	stdin.open("output.txt", "wt");
	int n;
	readf("%d", &n);
while(n == 3) {}
	int ans = 0;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	stdin.open("input.txt", "rt");
	stdin.open("output.txt", "wt");
	int n;
	readf("%d", &n);
while(n == 2) {}
	int ans = 0;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	stdin.open("input.txt", "rt");
	stdin.open("output.txt", "wt");
	int n;
	readf("%d", &n);
while(n > 2){};
	int ans = 0;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}

import std.stdio, std.file, std.conv;
import std.algorithm;

void main(string[] args)
{
	stdin.open("input.txt", "r");
	stdin.open("output.txt", "w");
	int n;
	readf("%d", &n);
	int ans = 0;
	while((1 << ans) < n) ans++;
	writeln(ans);
	for(int i = 0; i < ans; i++)
	{
		int[] a = [];
		for(int j = 1; j <= n; j++)
		{
			if((j & (1 << i)) == 0) a ~= j;
		}
		write(a.count(), ' ');
		foreach(x; a)
		{
			write(x, ' ');
		}
		writeln();
	}
}


All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of $$$n\cdot m$$$ different seals, denoted by distinct numbers. All of them were written in an $$$n\times m$$$ table.The table is lost now. Naruto managed to remember elements of each row from left to right, and elements of each column from top to bottom, but he doesn't remember the order of rows and columns. Please restore the table consistent with this data so that Naruto will be able to learn the new technique.

The first line of the input contains the only integer $$$t$$$ ($$$1\leq t\leq 100\,000$$$) denoting the number of test cases. Their descriptions follow. The first line of each test case description consists of two space-separated integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 500$$$) standing for the number of rows and columns in the table, respectively. All hand seals are encoded by the positive integers from $$$1$$$ to $$$n\cdot m$$$. The following $$$n$$$ lines contain $$$m$$$ space separated integers each, denoting elements of an arbitrary row in the table left to right. The following $$$m$$$ lines contain $$$n$$$ space separated integers each, denoting elements of an arbitrary column in the table top to bottom. Sum of $$$nm$$$ over all test cases does not exceed $$$250\,000$$$. It is guaranteed that each row occurs in the input exactly once, as well as each column. It is also guaranteed that each number from $$$1$$$ to $$$nm$$$ occurs exactly once in all rows, as well as in all columns. Finally, it is guaranteed that a table consistent with the input exists.

For each test case, output $$$n$$$ lines with $$$m$$$ space-separated integers each, denoting the restored table. One can show that the answer is always unique.

NoteConsider the first test case. The matrix is $$$2 \times 3$$$. You are given the rows and columns in arbitrary order.One of the rows is $$$[6, 5, 4]$$$. One of the rows is $$$[1, 2, 3]$$$.One of the columns is $$$[1, 6]$$$. One of the columns is $$$[2, 5]$$$. One of the columns is $$$[3, 4]$$$.You are to reconstruct the matrix. The answer is given in the output.

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 int[][][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto a = new int[][](n);
		auto b = new int[][](m);
		int[long] pos_a, pos_b;
		foreach (i; 0..n)
		{
			a[i] = RDA!int;
			pos_a[a[i][0]] = cast(int)i;
		}
		foreach (i; 0..m)
		{
			b[i] = RDA!int;
			foreach (e; b[i])
				pos_b[e] = cast(int)i;
		}

		auto p = pos_b[a[0][0]];
		foreach (i, e; b[p])
		{
			auto pp = pos_a[e];
			ans[ti] ~= a[pp];
		}
	}

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


Two players A and B have a list of $$$n$$$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $$$\{1, 2, 2, 3\}$$$ in a list and you decided to choose $$$2$$$ for the next turn, only a single instance of $$$2$$$ will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.

The first line of input contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the sizes of the list. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^6$$$), describing the list of the player A, who starts the game. The third line contains $$$n$$$ integers $$$b_i$$$ ($$$1 \le b_i \le 10^6$$$), describing the list of the player B.

Output the difference between A's score and B's score ($$$A-B$$$) if both of them are playing optimally.

NoteIn the first example, the game could have gone as follows:   A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A takes his $$$1$$$.  B takes his $$$1$$$. Hence, A's score is $$$1$$$, B's score is $$$1$$$ and difference is $$$0$$$.There is also another optimal way of playing:  A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A removes $$$1$$$ from B's list.  B removes $$$1$$$ from A's list. The difference in the scores is still $$$0$$$.In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be $$$0$$$.

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;

immutable long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto B = readln.split.map!(to!long).array;
    auto pqA = heapify(A);
    auto pqB = heapify(B);

    long ans = 0;
    foreach (i; 0..2*N) {
        if (i % 2 == 0) {
            if (pqA.empty) {
                pqB.popFront;
            } else if (pqB.empty) {
                ans += pqA.front;
                pqA.popFront;
            } else {
                if (pqA.front >= pqB.front) {
                    ans += pqA.front;
                    pqA.popFront;
                } else {
                    pqB.popFront;
                }
            }
        } else {
            if (pqA.empty) {
                ans -= pqB.front;
                pqB.popFront;
            } else if (pqB.empty) {
                pqA.popFront;
            } else {
                if (pqB.front >= pqA.front) {
                    ans -= pqB.front;
                    pqB.popFront;
                } else {
                    pqA.popFront;
                }
            }
        }
    }

    ans.writeln;
}

import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.datetime;
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;

    int[][2] arr;
    foreach (i; 0 .. 2) arr[i] = readln.chomp.split.map!(to!int).array.sort.array;

    debug { arr.writeln; }

    long[2] sc = [0, 0];
    foreach (_; 0 .. n) {
        foreach (i; 0 .. 2) {
            auto mine = i;
            auto opp = 1 - i;
            if (arr[opp].empty || (!arr[mine].empty && arr[mine].back > arr[opp].back)) {
                sc[mine] += arr[mine].back;
                arr[mine].popBack();
            } else {
                arr[opp].popBack();
            }
        }
    }

    writeln(sc[0] - sc[1]);
}

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

  int n; rd(n);
  auto a=readln.split.to!(long[]).sort!"a>b";
  auto b=readln.split.to!(long[]).sort!"a>b";

  long A=0, B=0;
  foreach(i; 0..(n*2)){
    if(i%2==0){
      if(a.length==0){
        b=b[1..$];
      }else if(b.length==0){
        A+=a[0];
        a=a[1..$];
      }else{
        if(a[0]<b[0]) b=b[1..$];
        else A+=a[0], a=a[1..$];
      }
    }else{
      if(a.length==0){
        B+=b[0];
        b=b[1..$];
      }else if(b.length==0){
        a=a[1..$];
      }else{
        if(b[0]<a[0]) a=a[1..$];
        else B+=b[0], b=b[1..$];
      }
    }
  }
  writeln(A-B);
}

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


Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of gears. The second line contains n digits a1, a2, ..., an (0 ≤ ai ≤ n - 1) — the sequence of active teeth: the active tooth of the i-th gear contains number ai.

In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.

NoteIn the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.

import std.stdio;
import std.algorithm;
import std.string;
import std.conv;
import std.array;
import std.range;
import std.ascii;
import std.functional;
import std.utf;
import std.typecons;
import std.numeric;
import std.complex;
import std.math;

alias isEven = unaryFun!("(a & 1) == 0");
alias isOdd =  unaryFun!("(a & 1) != 0");

void start()
{
	auto gearCount = to!int(stdin.readln().chomp());
	auto activeTooths = stdin.readln().chomp().split().map!(a => to!int(a));

	auto periodTime = gearCount - activeTooths[0];
	bool result = true;
	for ( int index = 0; index < gearCount; index++)
	{
		auto elem = activeTooths[index];

		if (isOdd(index))
		{
			auto temp = gearCount - periodTime;
			if (((elem + temp) % gearCount) != index )
			{
				result = false;
				break;
			}
		}
		else
		{
			if (((elem + periodTime) % gearCount) != index )
			{
				result = false;
				break;
			}
		}
	}

	if (result)
		writeln("Yes");
	else
		writeln("No");

}

void main(  string[] args )
{
	start();
}


Zibi is a competitive programming coach. There are $$$n$$$ competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).We know that the $$$i$$$-th competitor will always have score $$$x_i$$$ when he codes the first task and $$$y_i$$$ when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.Zibi wants all competitors to write a contest with each other. However, there are $$$m$$$ pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 300\,000$$$, $$$0 \le m \le 300\,000$$$) — the number of participants and the number of pairs of people who will not write a contest together. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^9 \le x_i, y_i \le 10^9$$$) — the scores which will the $$$i$$$-th competitor get on the first problem and on the second problem. It is guaranteed that there are no two people having both $$$x_i$$$ and $$$y_i$$$ same. Each of the next $$$m$$$ lines contain two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) — indices of people who don't want to write a contest in one team. Each unordered pair of indices will appear at most once.

Output $$$n$$$ integers — the sum of scores for all participants in the same order as they appear in the input.

NoteIn the first example, there will be only one team consisting of persons $$$1$$$ and $$$3$$$. The optimal strategy for them is to assign the first task to the $$$3$$$-rd person and the second task to the $$$1$$$-st person, this will lead to score equal to $$$1 + 2 = 3$$$.In the second example, nobody likes anyone, so there won't be any trainings. It seems that Zibi won't be titled coach in that case...

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

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

    auto x = new int[] (n);
    auto y = new int[] (n);

    foreach (i; 0 .. n) {
        readf("%s %s", &x[i], &y[i]);
        readln;
    }

    auto g = new int[][] (n);

    foreach (_; 0 .. m) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        --u, --v;

        g[u] ~= v;
        g[v] ~= u;
    }

    auto balance = new Tuple!(int, int)[] (n);
    foreach (i; 0 .. n) {
        balance[i] = tuple(x[i] - y[i], i);
    }

    balance.sort();

    auto ySum = y.sum(0L);
    long xSum = 0;

    debug { writeln(balance); writeln(ySum); }

    auto ans = new long[] (n);
    foreach (lft, t; balance) {
        auto b = t[0], pos = t[1];

        ySum -= y[pos];

        auto withX = (n - lft - 1).to!long * x[pos] + ySum;
        auto withY = lft.to!long * y[pos] + xSum;
        ans[pos] = withX + withY;

        xSum += x[pos];

        debug { writeln(pos, ' ', ans[pos]); }

        foreach (u; g[pos]) {
            ans[pos] -= min(x[pos] + y[u], x[u] + y[pos]);
        }
    }

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

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

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

    auto x = new int[] (n);
    auto y = new int[] (n);

    foreach (i; 0 .. n) {
        readf("%s %s", &x[i], &y[i]);
        readln;
    }

    auto g = new int[][] (n);

    foreach (_; 0 .. m) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        --u, --v;

        g[u] ~= v;
        g[v] ~= u;
    }

    auto balance = new Tuple!(int, int)[] (n);
    foreach (i; 0 .. n) {
        balance[i] = tuple(x[i] - y[i], i);
    }

    balance.sort();

    auto ySum = y.sum(0L);
    long xSum = 0;

    debug { writeln(balance); writeln(ySum); }

    auto ans = new long[] (n);
    foreach (lft, t; balance) {
        auto b = t[0], pos = t[1];

        ySum -= y[pos];

        auto withX = (n - lft - 1).to!long * x[pos] + ySum;
        auto withY = lft * y[pos] + xSum;
        ans[pos] = withX + withY;

        xSum += x[pos];

        debug { writeln(pos, ' ', ans[pos]); }

        foreach (u; g[pos]) {
            ans[pos] -= min(x[pos] + y[u], x[u] + y[pos]);
        }
    }

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


Andre has very specific tastes. Recently he started falling in love with arrays.Andre calls an nonempty array $$$b$$$ good, if sum of its elements is divisible by the length of this array. For example, array $$$[2, 3, 1]$$$ is good, as sum of its elements — $$$6$$$ — is divisible by $$$3$$$, but array $$$[1, 1, 2, 3]$$$ isn't good, as $$$7$$$ isn't divisible by $$$4$$$. Andre calls an array $$$a$$$ of length $$$n$$$ perfect if the following conditions hold:   Every nonempty subarray of this array is good.  For every $$$i$$$ ($$$1 \le i \le n$$$), $$$1 \leq a_i \leq 100$$$. Given a positive integer $$$n$$$, output any perfect array of length $$$n$$$. We can show that for the given constraints such an array always exists.An array $$$c$$$ is a subarray of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of every test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).

For every test, output any perfect array of length $$$n$$$ on a separate line.

NoteArray $$$[19, 33]$$$ is perfect as all $$$3$$$ its subarrays: $$$[19]$$$, $$$[33]$$$, $$$[19, 33]$$$, have sums divisible by their lengths, and therefore are good.

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)
	{
		"1".repeat (readln.strip.to !(int)).join (" ").writeln;
	}
}

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

string FMT_F = "%.10f";

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

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

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

//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 int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;

		foreach (i; 0..n)
			ans[ti] ~= 1;
	}

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


Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this!Let us remind you that a number is called prime if it is integer larger than one, and is not divisible by any positive integer other than itself and one.Rikhail calls a number a palindromic if it is integer, positive, and its decimal representation without leading zeros is a palindrome, i.e. reads the same from left to right and right to left.One problem with prime numbers is that there are too many of them. Let's introduce the following notation: π(n) — the number of primes no larger than n, rub(n) — the number of palindromic numbers no larger than n. Rikhail wants to prove that there are a lot more primes than palindromic ones.He asked you to solve the following problem: for a given value of the coefficient A find the maximum n, such that π(n) ≤ A·rub(n).

The input consists of two positive integers p, q, the numerator and denominator of the fraction that is the value of A (, ).

If such maximum number exists, then print it. Otherwise, print "Palindromic tree is better than splay tree" (without the quotes).

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;
import core.bitop;

immutable int MAX_N = 2_000_006;

void main ()
{
	auto s = new int [MAX_N];
	s[2..$] = 1;
	for (int i = 2; i * i < MAX_N; i++)
	{
		if (s[i])
		{
			for (int j = i; j * i < MAX_N; j++)
			{
				s[j * i] = 0;
			}
		}
	}

	auto t = new int [MAX_N];
	foreach (i; 1..MAX_N)
	{
		auto x = i.text;
		t[i] = equal (x, x.retro);
	}

	foreach (i; 1..MAX_N)
	{
		s[i] += s[i - 1];
		t[i] += t[i - 1];
	}
	debug {writeln (s.back, ' ', t.back);}

	int p, q;
	while (readf (" %s %s", &p, &q) > 0)
	{
		int res = 0;
		foreach (i; 1..MAX_N)
		{
			if (s[i] * q <= t[i] * p)
			{
				res = i;
			}
		}
		writeln (res);
	}
}


A sequence $$$a_1, a_2, \dots, a_n$$$ is called good if, for each element $$$a_i$$$, there exists an element $$$a_j$$$ ($$$i \ne j$$$) such that $$$a_i+a_j$$$ is a power of two (that is, $$$2^d$$$ for some non-negative integer $$$d$$$).For example, the following sequences are good:  $$$[5, 3, 11]$$$ (for example, for $$$a_1=5$$$ we can choose $$$a_2=3$$$. Note that their sum is a power of two. Similarly, such an element can be found for $$$a_2$$$ and $$$a_3$$$),  $$$[1, 1, 1, 1023]$$$,  $$$[7, 39, 89, 25, 89]$$$,  $$$[]$$$. Note that, by definition, an empty sequence (with a length of $$$0$$$) is good.For example, the following sequences are not good:  $$$[16]$$$ (for $$$a_1=16$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two),  $$$[4, 16]$$$ (for $$$a_1=4$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two),  $$$[1, 3, 2, 8, 8, 8]$$$ (for $$$a_3=2$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two). You are given a sequence $$$a_1, a_2, \dots, a_n$$$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.

The first line contains the integer $$$n$$$ ($$$1 \le n \le 120000$$$) — the length of the given sequence. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all $$$n$$$ elements, make it empty, and thus get a good sequence.

NoteIn the first example, it is enough to delete one element $$$a_4=5$$$. The remaining elements form the sequence $$$[4, 7, 1, 4, 9]$$$, which is good.

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.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

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

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

    auto ans = n;

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

    auto powersOfTwo = cast(int[]) recurrence!((a, n) => a[n-1] * 2)(1L).until!(x => x > 2 * 10 ^^ 9).array;

    debug { powersOfTwo.writeln; }

    foreach (e; arr) {
        cnt[e] -= 1;
        if (cnt[e] == 0) cnt.remove(e);
        ans -= cast(int) powersOfTwo.any!(x => x - e in cnt);
        cnt[e] += 1;
    }

    ans.writeln;
}


You are given a circular array with n elements. The elements are numbered from some element with values from 1 to n in clockwise order. The i-th cell contains the value ai. The robot Simba is in cell s.Each moment of time the robot is in some of the n cells (at the begin he is in s). In one turn the robot can write out the number written in current cell or move to the adjacent cell in clockwise or counterclockwise direction. To write out the number from the cell Simba doesn't spend any time, but to move to adjacent cell Simba spends one unit of time.Simba wants to write the number from each cell one time, so the numbers will be written in a non decreasing order. Find the least number of time units to write out all numbers.

The first line contains two integers n and s (1 ≤ s ≤ n ≤ 2000) — the number of cells in the circular array and the starting position of Simba. The second line contains n integers ai ( - 109 ≤ ai ≤ 109) — the number written in the i-th cell. The numbers are given for cells in order from 1 to n. Some of numbers ai can be equal.

In the first line print the number t — the least number of time units. Each of the next n lines should contain the direction of robot movement and the number of cells to move in that direction. After that movement the robot writes out the number from the cell in which it turns out. The direction and the number of cells should be printed in the form of +x in case of clockwise movement and -x in case of counterclockwise movement to x cells (0 ≤ x ≤ n - 1). Note that the sum of absolute values of x should be equal to t.

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

immutable int INF = int.max / 4;

void main ()
{
	int n;
	int s;
	while (readf (" %s %s", &n, &s) > 0)
	{
		s--;
		readln;
		auto a = readln.split.map !(to !(int)).array;
		auto b = a.dup;
		sort (b);
		b = b.uniq.array;
		int k = b.length;
		alias HalfEntry = Tuple !(int, q{value}, int, q{start});
		alias Entry = Tuple !(int, q{value}, int, q{start},
		    int, q{delta});
		auto f = new Entry [] [] (k + 1, n);
		foreach (ref g; f)
		{
			g[] = Entry (INF, INF, INF);
		}
		f[0][s] = Entry (0, INF, INF);

		foreach (i; 0..k)
		{
			auto chi = HalfEntry (INF, INF);
			foreach (j; 0..n)
			{
				int cur = f[i][j].value + j;
				chi = min (chi, HalfEntry (cur, -j));
			}
			auto hi = new HalfEntry [n];
			foreach_reverse (j; 0..n)
			{
				chi.value += 1;
				chi.start -= 1;
				int cur = f[i][j].value;
				chi = min (chi, HalfEntry (cur, 0));
				hi[j] = chi;
			}
			debug {writeln ("hi ", i, ": ", hi);}

			auto clo = HalfEntry (INF, INF);
			foreach (j; 0..n)
			{
				int cur = f[i][j].value + n - j;
				clo = min (clo, HalfEntry (cur, n - j));
			}
			auto lo = new HalfEntry [n];
			foreach (j; 0..n)
			{
				int cur = f[i][j].value;
				clo = min (clo, HalfEntry (cur, 0));
				lo[j] = clo;
				clo.value += 1;
				clo.start += 1;
			}
			debug {writeln ("lo ", i, ": ", lo);}

			int [] pos;
			foreach (j; 0..n)
			{
				if (a[j] == b[i])
				{
					pos ~= j;
				}
			}
			int w = pos.length;
			debug {writeln ("pos ", i, ": ", pos);}

			foreach (u; 0..w)
			{
				int nextpos = (u + 1) % w;
				int dnext = (pos[nextpos] - pos[u] + n - 1) %
				    n + 1;
				dnext = n - dnext;
				auto next = min
				    (Entry (lo[pos[nextpos]].expand, +1),
				    Entry (hi[pos[nextpos]].expand, +1));
				next.value += dnext;
				f[i + 1][pos[u]] = min (f[i + 1][pos[u]],
				    next);

				int prevpos = (u + w - 1) % w;
				int dprev = (pos[u] - pos[prevpos] + n - 1) %
				    n + 1;
				dprev = n - dprev;
				auto prev = min
				    (Entry (lo[pos[prevpos]].expand, -1),
				    Entry (hi[pos[prevpos]].expand, -1));
				prev.value += dprev;
				f[i + 1][pos[u]] = min (f[i + 1][pos[u]],
				    prev);
			}
			debug {writeln ("f ", i + 1, ": ", f[i + 1]);}
		}

		alias SuperEntry = Tuple !(int, q{value}, int, q{start},
		    int, q{delta}, int, q{pos});
		auto res = SuperEntry (INF, INF, INF, INF);
		if (true)
		{
			foreach (j; 0..n)
			{
				if (a[j] == b.back)
				{
					res = min (res,
					    SuperEntry (f[k][j].expand, j));
				}
			}
		}

		writeln (res.value);
		int [] ans;
		foreach_reverse (i; 0..k)
		{
			debug {writeln (res);}
			int cur = res.pos;
			int prev = cur;
			int add = 0;
			foreach (j; 0..n - 1)
			{
				cur = (cur + n - res.delta) % n;
				add += res.delta;
				if (a[cur] == a[prev])
				{
					ans ~= add;
					add = 0;
					prev = cur;
				}
			}
			ans ~= res.start;
			prev = (prev + n - res.start) % n;
			res = SuperEntry (f[i][prev].expand, prev);
		}
		writefln ("%(%+s\n%)", ans.retro);
	}
}

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

immutable int INF = int.max / 4;

void main ()
{
	int n;
	int s;
	while (readf (" %s %s", &n, &s) > 0)
	{
		s--;
		readln;
		auto a = readln.split.map !(to !(int)).array;
		auto b = a.dup;
		sort (b);
		b = b.uniq.array;
		int k = b.length;
		alias HalfEntry = Tuple !(int, q{value}, int, q{start});
		alias Entry = Tuple !(int, q{value}, int, q{start},
		    int, q{delta});
		auto f = new Entry [] [] (k + 1, n);
		foreach (ref g; f)
		{
			g[] = Entry (INF, INF, INF);
		}
		f[0][s] = Entry (0, INF, INF);

		foreach (i; 0..k)
		{
			auto chi = HalfEntry (INF, INF);
			foreach (j; 0..n)
			{
				int cur = f[i][j].value + j;
				chi = min (chi, HalfEntry (cur, -j));
			}
			auto hi = new HalfEntry [n];
			foreach_reverse (j; 0..n)
			{
				chi.value += 1;
				chi.start -= 1;
				int cur = f[i][j].value;
				chi = min (chi, HalfEntry (cur, 0));
				hi[j] = chi;
			}
			debug {writeln ("hi ", i, ": ", hi);}

			auto clo = HalfEntry (INF, INF);
			foreach (j; 0..n)
			{
				int cur = f[i][n - j - 1].value + j;
				clo = min (clo, HalfEntry (cur, j));
			}
			auto lo = new HalfEntry [n];
			foreach (j; 0..n)
			{
				int cur = f[i][j].value;
				clo = min (clo, HalfEntry (cur, 0));
				lo[j] = clo;
				clo.value += 1;
				clo.start += 1;
			}
			debug {writeln ("lo ", i, ": ", lo);}

			int [] pos;
			foreach (j; 0..n)
			{
				if (a[j] == b[i])
				{
					pos ~= j;
				}
			}
			int w = pos.length;
			debug {writeln ("pos ", i, ": ", pos);}

			foreach (u; 0..w)
			{
				int nextpos = (u + 1) % w;
				int dnext = (pos[nextpos] - pos[u] + n - 1) %
				    n + 1;
				dnext = n - dnext;
				auto next = min
				    (Entry (lo[pos[nextpos]].expand, +1),
				    Entry (hi[pos[nextpos]].expand, +1));
				next.value += dnext;
				f[i + 1][pos[u]] = min (f[i + 1][pos[u]],
				    next);

				int prevpos = (u + w - 1) % w;
				int dprev = (pos[u] - pos[prevpos] + n - 1) %
				    n + 1;
				dprev = n - dprev;
				auto prev = min
				    (Entry (lo[pos[prevpos]].expand, -1),
				    Entry (hi[pos[prevpos]].expand, -1));
				prev.value += dprev;
				f[i + 1][pos[u]] = min (f[i + 1][pos[u]],
				    prev);
			}
			debug {writeln ("f ", i + 1, ": ", f[i + 1]);}
		}

		alias SuperEntry = Tuple !(int, q{value}, int, q{start},
		    int, q{delta}, int, q{pos});
		auto res = SuperEntry (INF, INF, INF, INF);
		if (true)
		{
			foreach (j; 0..n)
			{
				if (a[j] == b.back)
				{
					res = min (res,
					    SuperEntry (f[k][j].expand, j));
				}
			}
		}

		writeln (res.value);
		int [] ans;
		foreach_reverse (i; 0..k)
		{
			int cur = res.pos;
			int prev = cur;
			int add = 0;
			foreach (j; 0..n - 1)
			{
				cur = (cur + n - res.delta) % n;
				add += res.delta;
				if (a[cur] == a[prev])
				{
					ans ~= add;
					add = 0;
					prev = cur;
				}
			}
			ans ~= res.start;
			prev = (prev + n - res.start) % n;
			res = SuperEntry (f[i][prev].expand, prev);
		}
		writefln ("%(%+s\n%)", ans.retro);
	}
}

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

immutable int INF = int.max / 4;

void main ()
{
	int n;
	int s;
	while (readf (" %s %s", &n, &s) > 0)
	{
		s--;
		readln;
		auto a = readln.split.map !(to !(int)).array;
		auto b = a.dup;
		sort (b);
		b = b.uniq.array;
		int k = b.length;
		alias HalfEntry = Tuple !(int, q{value}, int, q{start});
		alias Entry = Tuple !(int, q{value}, int, q{start},
		    int, q{delta});
		auto f = new Entry [] [] (k + 1, n);
		foreach (ref g; f)
		{
			g[] = Entry (INF, INF, INF);
		}
		f[0][s] = Entry (0, INF, INF);

		foreach (i; 0..k)
		{
			auto chi = HalfEntry (INF, INF);
			foreach (j; 0..n)
			{
				int cur = f[i][j].value + j;
				chi = min (chi, HalfEntry (cur, -j));
			}
			auto hi = new HalfEntry [n];
			foreach_reverse (j; 0..n)
			{
				chi.value += 1;
				chi.start -= 1;
				int cur = f[i][j].value;
				chi = min (chi, HalfEntry (cur, 0));
				hi[j] = chi;
			}
			debug {writeln ("hi ", i, ": ", hi);}

			auto clo = HalfEntry (INF, INF);
			foreach (j; 0..n)
			{
				int cur = f[i][n - j - 1].value + j;
				clo = min (clo, HalfEntry (cur, j));
			}
			auto lo = new HalfEntry [n];
			foreach (j; 0..n)
			{
				int cur = f[i][j].value;
				clo = min (clo, HalfEntry (cur, 0));
				lo[j] = clo;
				clo.value += 1;
				clo.start += 1;
			}
			debug {writeln ("lo ", i, ": ", lo);}

			int [] pos;
			foreach (j; 0..n)
			{
				if (a[j] == b[i])
				{
					pos ~= j;
				}
			}
			int w = pos.length;
			debug {writeln ("pos ", i, ": ", pos);}

			foreach (u; 0..w)
			{
				int nextpos = (u + 1) % w;
				int dnext = (pos[nextpos] - pos[u] + n - 1) %
				    n + 1;
				dnext = n - dnext;
				auto next = min
				    (Entry (lo[pos[nextpos]].expand, +1),
				    Entry (hi[pos[nextpos]].expand, +1));
				next.value += dnext;
				f[i + 1][pos[u]] = min (f[i + 1][pos[u]],
				    next);

				int prevpos = (u + w - 1) % w;
				int dprev = (pos[u] - pos[prevpos] + n - 1) %
				    n + 1;
				dprev = n - dprev;
				auto prev = min
				    (Entry (lo[pos[prevpos]].expand, -1),
				    Entry (hi[pos[prevpos]].expand, -1));
				prev.value += dprev;
				f[i + 1][pos[u]] = min (f[i + 1][pos[u]],
				    prev);
			}
			debug {writeln ("f ", i + 1, ": ", f[i + 1]);}
		}

		alias SuperEntry = Tuple !(int, q{value}, int, q{start},
		    int, q{delta}, int, q{pos});
		auto res = SuperEntry (INF, INF, INF, INF);
		if (true)
		{
			foreach (j; 0..n)
			{
				if (a[j] == b.back)
				{
					res = min (res,
					    SuperEntry (f[k][j].expand, j));
				}
			}
		}

		writeln (res.value);
		int [] ans;
		foreach_reverse (i; 0..k)
		{
			writeln (res);
			int cur = res.pos;
			int prev = cur;
			int add = 0;
			foreach (j; 0..n - 1)
			{
				cur = (cur + n - res.delta) % n;
				add += res.delta;
				writeln (cur, ' ', prev);
				if (a[cur] == a[prev])
				{
					ans ~= add;
					add = 0;
					prev = cur;
				}
			}
			ans ~= res.start;
			prev = (prev + n - res.start) % n;
			writeln (i, ' ', prev, ' ', f[i][prev]);
			res = SuperEntry (f[i][prev].expand, prev);
			writeln (ans);
		}
		writefln ("%(%+s\n%)", ans.retro);
	}
}


Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.

Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.

NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.

import core.bitop;
import core.checkedint;
import core.simd;
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:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.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));
}

int[10^^5] _a;

void main() {
    int n, k;
    nextCase: while (read(n, k)) {
        auto a = _a[0 .. n];
        int minimal = int.max;
        foreach (ref x; a) {
            read(x);
            minimal = min(minimal, x);
        }
        long result = 0;
        foreach (x; a) {
            const d = x - minimal;
            if (d % k) {
                writeln("-1");
                continue nextCase;
            }
            result += d / k;
        }
        writeln(result);
    }
}

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

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n,k;
loop:while(read(n,k))
	{
		auto a=arread!int;
		auto m=minElement(a);
		foreach(ref x; a) {x-=m;}
		long ans=0;
		foreach(x;a)
		{
			if(x%k!=0)
			{
				writeln(-1);
				continue loop;
			}
			else ans+=x/k;
		}
		writeln(ans);
	}
}

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;

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		long res = 0;
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		int lo = a.reduce !(min);
		if (a.any !(x => (x - lo) % k))
		{
			writeln (-1);
		}
		else
		{
			writeln (a.map !(x => (x - lo) / k).sum (0L));
		}
	}
}


You invited $$$n$$$ guests to dinner! You plan to arrange one or more circles of chairs. Each chair is going to be either occupied by one guest, or be empty. You can make any number of circles. Your guests happen to be a little bit shy, so the $$$i$$$-th guest wants to have a least $$$l_i$$$ free chairs to the left of his chair, and at least $$$r_i$$$ free chairs to the right. The "left" and "right" directions are chosen assuming all guests are going to be seated towards the center of the circle. Note that when a guest is the only one in his circle, the $$$l_i$$$ chairs to his left and $$$r_i$$$ chairs to his right may overlap.What is smallest total number of chairs you have to use?

First line contains one integer $$$n$$$  — number of guests, ($$$1 \leqslant n \leqslant 10^5$$$).  Next $$$n$$$ lines contain $$$n$$$ pairs of space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \leqslant l_i, r_i \leqslant 10^9$$$).

Output a single integer — the smallest number of chairs you have to use.

NoteIn the second sample the only optimal answer is to use two circles: a circle with $$$5$$$ chairs accomodating guests $$$1$$$ and $$$2$$$, and another one with $$$10$$$ chairs accomodationg guests $$$3$$$ and $$$4$$$.In the third sample, you have only one circle with one person. The guest should have at least five free chairs to his left, and at least six free chairs to his right to the next person, which is in this case the guest herself. So, overall number of chairs should be at least 6+1=7.

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;

immutable long MOD = 10^^9 + 7;
alias Pair = Tuple!(long, "l", long, "r");

void main() {
    auto N = readln.chomp.to!int;
    auto A = new Pair[](N);

    long ans = N;
    auto L = new BinaryHeap!(Array!Pair, "a.l == b.l ? a.r > b.r : a.l < b.l")();
    auto R = new BinaryHeap!(Array!Pair, "a.r == b.r ? a.l > b.l : a.r < b.r")();

    foreach (i; 0..N) {
        auto s = readln.split.map!(to!long);
        A[i] = Pair(s[0], s[1]);
        if (s[0] > s[1]) L.insert(A[i]);
        else if (s[0] < s[1]) R.insert(A[i]);
        else ans += s[0];
    }

    while (!L.empty && !R.empty) {
        if (L.front.l >= R.front.r) {
            auto p = L.front;
            L.popFront;
            if (p.r >= R.front.r) {
                ans += p.l;
                continue;
            }
            auto q = R.front;
            R.popFront;
            ans += p.l;
            Pair new_p = Pair(q.l, p.r);
            if (q.l > p.r) L.insert(new_p);
            else if (q.l < p.r) R.insert(new_p);
            else ans += q.l;
        } else {
            auto p = R.front;
            R.popFront;
            if (p.l >= L.front.l) {
                ans += p.r;
                continue;
            }
            auto q = L.front;
            L.popFront;
            ans += p.r;
            Pair new_p = Pair(p.l, q.r);
            if (p.l > q.r) L.insert(new_p);
            else if (p.l < q.r) R.insert(new_p);
            else ans += p.l;
        }
    }

    while (!L.empty) {
        ans += L.front.l;
        L.popFront;
    }

    while (!R.empty) {
        ans += R.front.r;
        R.popFront;
    }

    ans.writeln;
}

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

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

    int[] le, r;
    foreach (_; 0 .. n) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        le ~= a;
        r ~= b;
    }

    le.sort();
    r.sort();

    long ans = n + zip(le, r).map!(t => max(t[0], t[1])).sum(0L);
    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;

immutable long MOD = 10^^9 + 7;
alias Pair = Tuple!(long, "l", long, "r");

void main() {
    auto N = readln.chomp.to!int;
    auto A = new Pair[](N);

    long ans = N;
    auto L = new BinaryHeap!(Array!Pair, "a.l == b.l ? a.r > b.r : a.l < b.l")();
    auto R = new BinaryHeap!(Array!Pair, "a.r == b.r ? a.l > b.l : a.r < b.r")();

    foreach (i; 0..N) {
        auto s = readln.split.map!(to!long);
        A[i] = Pair(s[0], s[1]);
        if (s[0] > s[1]) L.insert(A[i]);
        else if (s[0] < s[1]) R.insert(A[i]);
        else ans += s[0];
    }

    while (!L.empty && !R.empty) {
        if (L.front.l >= R.front.r) {
            auto p = L.front;
            L.popFront;
            if (p.r >= R.front.r) {
                continue;
            }
            auto q = R.front;
            R.popFront;
            ans += p.l;
            Pair new_p = Pair(q.l, p.r);
            if (q.l > p.r) L.insert(new_p);
            else if (q.l < p.r) R.insert(new_p);
            else ans += q.l;
        } else {
            auto p = R.front;
            R.popFront;
            if (p.l >= L.front.l) {
                continue;
            }
            auto q = L.front;
            L.popFront;
            ans += p.r;
            Pair new_p = Pair(p.l, q.r);
            if (p.l > q.r) L.insert(new_p);
            else if (p.l < q.r) R.insert(new_p);
            else ans += p.l;
        }
    }

    while (!L.empty) {
        ans += L.front.l;
        L.popFront;
    }

    while (!R.empty) {
        ans += R.front.r;
        R.popFront;
    }

    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;

immutable long MOD = 10^^9 + 7;
alias Pair = Tuple!(long, "l", long, "r");

void main() {
    auto N = readln.chomp.to!int;
    auto A = new Pair[](N);

    long ans = N;
    auto L = new BinaryHeap!(Array!Pair, "a.l < b.l")();
    auto R = new BinaryHeap!(Array!Pair, "a.r < b.r")();

    foreach (i; 0..N) {
        auto s = readln.split.map!(to!long);
        A[i] = Pair(s[0], s[1]);
        if (s[0] > s[1]) L.insert(A[i]);
        else if (s[0] < s[1]) R.insert(A[i]);
        else ans += s[0];
    }

    while (!L.empty && !R.empty) {
        if (L.front.l >= R.front.r) {
            auto p = L.front;
            L.popFront;
            if (p.r >= R.front.r) {
                continue;
            }
            auto q = R.front;
            R.popFront;
            ans += p.l;
            Pair new_p = Pair(q.l, p.r);
            if (q.l > p.r) L.insert(new_p);
            else if (q.l < p.r) R.insert(new_p);
            else ans += q.l;
        } else {
            auto p = R.front;
            R.popFront;
            if (p.l >= L.front.l) {
                continue;
            }
            auto q = L.front;
            L.popFront;
            ans += p.r;
            Pair new_p = Pair(p.l, q.r);
            if (p.l > q.r) L.insert(new_p);
            else if (p.l < q.r) R.insert(new_p);
            else ans += p.l;
        }
    }

    while (!L.empty) {
        ans += L.front.l;
        L.popFront;
    }

    while (!R.empty) {
        ans += R.front.r;
        R.popFront;
    }

    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;

immutable long MOD = 10^^9 + 7;
alias Pair = Tuple!(long, "l", long, "r");

void main() {
    auto N = readln.chomp.to!int;
    auto A = new Pair[](N);

    long ans = N;
    auto L = new BinaryHeap!(Array!Pair, "a.l == b.l ? a.l < b.l : a.r > b.r")();
    auto R = new BinaryHeap!(Array!Pair, "a.r == b.r ? a.r < b.r : a.l > b.l")();

    foreach (i; 0..N) {
        auto s = readln.split.map!(to!long);
        A[i] = Pair(s[0], s[1]);
        if (s[0] > s[1]) L.insert(A[i]);
        else if (s[0] < s[1]) R.insert(A[i]);
        else ans += s[0];
    }

    while (!L.empty && !R.empty) {
        if (L.front.l >= R.front.r) {
            auto p = L.front;
            L.popFront;
            if (p.r >= R.front.r) {
                continue;
            }
            auto q = R.front;
            R.popFront;
            ans += p.l;
            Pair new_p = Pair(q.l, p.r);
            if (q.l > p.r) L.insert(new_p);
            else if (q.l < p.r) R.insert(new_p);
            else ans += q.l;
        } else {
            auto p = R.front;
            R.popFront;
            if (p.l >= L.front.l) {
                continue;
            }
            auto q = L.front;
            L.popFront;
            ans += p.r;
            Pair new_p = Pair(p.l, q.r);
            if (p.l > q.r) L.insert(new_p);
            else if (p.l < q.r) R.insert(new_p);
            else ans += p.l;
        }
    }

    while (!L.empty) {
        ans += L.front.l;
        L.popFront;
    }

    while (!R.empty) {
        ans += R.front.r;
        R.popFront;
    }

    ans.writeln;
}

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

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

    int[] le, r;
    foreach (_; 0 .. n) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        le ~= a;
        r ~= b;
    }

    le.sort();
    r.sort();

    long ans = n + zip(le, r).map!(t => max(t[0], t[1])).sum;
    ans.writeln;
}


A tree is a connected undirected graph without cycles. Note that in this problem, we are talking about not rooted trees.You are given four positive integers $$$n, d_{12}, d_{23}$$$ and $$$d_{31}$$$. Construct a tree such that:  it contains $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$,  the distance (length of the shortest path) from vertex $$$1$$$ to vertex $$$2$$$ is $$$d_{12}$$$,  distance from vertex $$$2$$$ to vertex $$$3$$$ is $$$d_{23}$$$,  the distance from vertex $$$3$$$ to vertex $$$1$$$ is $$$d_{31}$$$. Output any tree that satisfies all the requirements above, or determine that no such tree exists.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. This is followed by $$$t$$$ test cases, each written on a separate line. Each test case consists of four positive integers $$$n, d_{12}, d_{23}$$$ and $$$d_{31}$$$ ($$$3 \le n \le 2\cdot10^5; 1 \le d_{12}, d_{23}, d_{31} \le n-1$$$). It is guaranteed that the sum of $$$n$$$ values for all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, print YES if the suitable tree exists, and NO otherwise.  If the answer is positive, print another $$$n-1$$$ line each containing a description of an edge of the tree — a pair of positive integers $$$x_i, y_i$$$, which means that the $$$i$$$th edge connects vertices $$$x_i$$$ and $$$y_i$$$.  The edges and vertices of the edges can be printed in any order. If there are several suitable trees, output any of them.

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 main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    auto xs = readarray!int;
    int N = xs[0];
    auto ds = xs[1 .. $];

    int x2 = ds[0] + ds[2] - ds[1];
    if (x2 < 0 || x2 % 2 == 1) {
        writeln("NO");
        return;
    }
    int x = x2 / 2;
    if (ds[0] + ds[2] - x + 1 > N || ds[0] - x < 0 || ds[2] - x < 0) {
        writeln("NO");
        return;
    }

    writeln("YES");
    int[2][] ans;

    int H;
    int k;
    if (x == 0) {
        H = 1;
        k = 4;
    } else if (ds[0] == x) {
        H = 2;
        k = 4;
    } else if (ds[2] == x) {
        H = 3;
        k = 4;
    } else {
        H = 4;
        k = 5;
    }
    void makepath(int s, int t, int d) {
        if (d == 0) return;
        int c = s;
        for (int i = 1; i < d; i++) {
            ans ~= [c, k];
            c = k;
            k++;
        }
        ans ~= [c, t];
    }
    makepath(1, H, x);
    makepath(2, H, ds[0] - x);
    makepath(3, H, ds[2] - x);

    while (k <= N) {
        makepath(1, k, 1);
        k++;
    }

    foreach (a; ans) {
        writefln("%(%s %)", a);
    }
    assert(ans.length == N - 1);
}


«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.

The first line contains one integer n (1 ≤ n ≤ 3000) — the amount of previously added tests. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 3000) — indexes of these tests.

Output the required default value for the next test index.

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

void main()
{
    readln;
    auto as = sort(readln.split.map!(to!int).array).array   ~ int.max;
    writeln(as.enumerate(1).find!"a[1]!=a[0]"[0][0]);
}

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;

    bool[3002] b;
    readln.chomp.split.map!(to!int).each!(x => b[x] = 1);

    b[1..3002].enumerate(1).filter!(t => ! t[1]).map!(t => t[0]).front.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;

    bool[3002] b;
    readln.chomp.split.map!(to!int).each!(x => b[x] = 1);

    foreach (i; 1 .. n+2) {
        if (!b[i]) {
            writeln(i);
            return;
        }
    }
}

import std.c.stdio;

void main(string[] args)
{
    int n, t;
    bool a[3001];
    scanf("%d", &n);
    for (int i = 0; i < n; ++i)
    {
        scanf("%d", &t);
        a[t-1] = true;
    }
    for (int i = 0; i < 3001; ++i)
        if (!a[i])
        {
            printf("%d\n", i+1);
            break;
        }
}

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

void main()
{
    readln;
    auto as = sort(readln.split.map!(to!int).array).array   ~ 3001;
    writeln(as.enumerate(1).find!"a[1]!=a[0]"[0][0]);
}


There is a square grid of size $$$n \times n$$$. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs $$$\max(h, w)$$$ to color a rectangle of size $$$h \times w$$$. You are to make all cells white for minimum total cost.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the size of the square grid. Each of the next $$$n$$$ lines contains a string of length $$$n$$$, consisting of characters '.' and '#'. The $$$j$$$-th character of the $$$i$$$-th line is '#' if the cell with coordinates $$$(i, j)$$$ is black, otherwise it is white.

Print a single integer — the minimum total cost to paint all cells in white.

NoteThe examples and some of optimal solutions are shown on the pictures below.

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

immutable int limit = 51;

byte [limit] [limit] [limit] [limit] f;

int solve (int n, string [] board)
{
	foreach (height; 1..n + 1)
	{
		foreach (width; 1..n + 1)
		{
			foreach (row; 0..n - height + 1)
			{
				foreach (col; 0..n - width + 1)
				{
					f[row][row + height]
					    [col][col + width] =
					    cast (byte) (n);
				}
			}
		}
	}

	foreach (height; 1..n + 1)
	{
		foreach (width; 1..n + 1)
		{
			foreach (row; 0..n - height + 1)
			{
				foreach (col; 0..n - width + 1)
				{
					auto span = cast (byte)
					    max (width, height);
					auto cur = cast (byte) (n);
					scope (exit)
					{
						f[row][row + height]
						    [col][col + width] = cur;
					}
					if (span == 1)
					{
						cur = (board[row][col] == '#');
						continue;
					}
					cur = span;
					foreach (h; 1..height)
					{
						cur = cast (byte) min (cur,
						    f[row][row + h]
						        [col][col + width] +
						    f[row + h][row + height]
						        [col][col + width]);
					}
					foreach (w; 1..width)
					{
						cur = cast (byte) min (cur,
						    f[row][row + height]
						        [col][col + w] +
						    f[row][row + height]
						        [col + w][col + width]);
					}
				}
			}
		}
	}

	return f[0][n][0][n];
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		string [] board;
		foreach (row; 0..n)
		{
			board ~= readln.strip;
		}
		writeln (solve (n, board));
	}
}

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

int N;
string[] A;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      A = new string[N];
      foreach (x; 0 .. N) {
        A[x] = readToken();
      }

      auto sum = new int[][](N + 1, N + 1);
      foreach (x; 0 .. N) foreach (y; 0 .. N) {
        sum[x + 1][y + 1] = sum[x + 1][y] + sum[x][y + 1] - sum[x][y] + ((A[x][y] == '#') ? 1 : 0);
      }

      auto dp = new int[][][][](N + 1, N + 1, N + 1, N + 1);
      foreach (k; 1 .. N + 1) foreach (l; 1 .. N + 1) {
        foreach (xa; 0 .. N - k + 1) foreach (ya; 0 .. N - l + 1) {
          const xb = xa + k, yb = ya + l;
          if (sum[xa][ya] - sum[xb][ya] - sum[xa][yb] + sum[xb][yb] == 0) {
            dp[xa][xb][ya][yb] = 0;
          } else {
            dp[xa][xb][ya][yb] = max(k, l);
            foreach (x; xa + 1 .. xb) {
              chmin(dp[xa][xb][ya][yb], dp[xa][x][ya][yb] + dp[x][xb][ya][yb]);
            }
            foreach (y; ya + 1 .. yb) {
              chmin(dp[xa][xb][ya][yb], dp[xa][xb][ya][y] + dp[xa][xb][y][yb]);
            }
          }
        }
      }
      writeln(dp[0][N][0][N]);
    }
  } catch (EOFException e) {
  }
}

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

int solve (int n, string [] board)
{
	auto f = new int [] [] [] [] (n + 1, n + 1, n + 1, n + 1);
	foreach (height; 1..n + 1)
	{
		foreach (row; 0..n - height + 1)
		{
			foreach (width; 1..n + 1)
			{
				foreach (col; 0..n - width + 1)
				{
					f[row][row + height]
					    [col][col + width] = n;
				}
			}
		}
	}

	foreach (height; 1..n + 1)
	{
		foreach (row; 0..n - height + 1)
		{
			foreach (width; 1..n + 1)
			{
				foreach (col; 0..n - width + 1)
				{
					int span = max (width, height);
					int cur = n;
					scope (exit)
					{
						f[row][row + height]
						    [col][col + width] = cur;
					}
					if (span == 1)
					{
						cur = (board[row][col] == '#');
						continue;
					}
					foreach (h; 1..height)
					{
						cur = min (cur,
						    f[row][row + h]
						        [col][col + width] +
						    f[row + h][row + height]
						        [col][col + width]);
					}
					foreach (w; 1..width)
					{
						cur = min (cur,
						    f[row][row + height]
						        [col][col + w] +
						    f[row][row + height]
						        [col + w][col + width]);
					}
				}
			}
		}
	}

	return f[0][n][0][n];
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		string [] board;
		foreach (row; 0..n)
		{
			board ~= readln.strip;
		}
		writeln (solve (n, board));
	}
}


You have a board represented as a grid with $$$2 \times n$$$ cells.The first $$$k_1$$$ cells on the first row and first $$$k_2$$$ cells on the second row are colored in white. All other cells are colored in black.You have $$$w$$$ white dominoes ($$$2 \times 1$$$ tiles, both cells are colored in white) and $$$b$$$ black dominoes ($$$2 \times 1$$$ tiles, both cells are colored in black).You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.Can you place all $$$w + b$$$ dominoes on the board if you can place dominoes both horizontally and vertically?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$ and $$$k_2$$$ ($$$1 \le n \le 1000$$$; $$$0 \le k_1, k_2 \le n$$$). The second line of each test case contains two integers $$$w$$$ and $$$b$$$ ($$$0 \le w, b \le n$$$).

For each test case, print YES if it's possible to place all $$$w + b$$$ dominoes on the board and NO, otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first test case, $$$n = 1$$$, $$$k_1 = 0$$$ and $$$k_2 = 1$$$. It means that $$$2 \times 1$$$ board has black cell $$$(1, 1)$$$ and white cell $$$(2, 1)$$$. So, you can't place any white domino, since there is only one white cell.In the second test case, the board of the same size $$$2 \times 1$$$, but both cell are white. Since $$$w = 0$$$ and $$$b = 0$$$, so you can place $$$0 + 0 = 0$$$ dominoes on the board.In the third test case, board $$$2 \times 3$$$, but fully colored in black (since $$$k_1 = k_2 = 0$$$), so you can't place any white domino.In the fourth test case, cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, and $$$(2, 1)$$$ are white and other cells are black. You can place $$$2$$$ white dominoes at positions $$$((1, 1), (2, 1))$$$ and $$$((1, 2), (1, 3))$$$ and $$$2$$$ black dominoes at positions $$$((1, 4), (2, 4))$$$ $$$((2, 2), (2, 3))$$$.

// Vicfred
// https://codeforces.com/contest/1499/problem/A
// greedy
import std.algorithm;
import std.stdio;

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

while(t--) {
    long n, k1, k2;
    readf("%s %s %s\n", &n, &k1, &k2);

    if(k2 < k1)
        swap(k1,k2); // k2 >= k1

    long w, b;
    readf("%s %s\n", &w, &b);

    long j1, j2;
    j1 = n - k1;
    j2 = n - k2;

    long whites = k1 + ((k2 - k1) >> 1);
    long blacks = j2 + ((j1 - j2) >> 1);

    if(whites >= w && blacks >= b) {
        "YES".writeln;
    }
    else {
        "NO".writeln;
    }
}
}

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

string FMT_F = "%.10f";

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

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

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

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 bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k1 = RD!int;
		auto k2 = RD!int;
		auto w = RD!int;
		auto b = RD!int;

		auto x = min(k1, k2);
		auto y = abs(k1 - k2);
		auto z = n - max(k1, k2);
		w -= x + y / 2;
		b -= z + y / 2;
		ans[ti] = w <= 0 && b <= 0;
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush;
	debug readln;
}