Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every  you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.

The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.

Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).

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;

void main() {
    auto s = readln.split.map!(to!long);
    auto N = s[0].to!int;
    auto M = s[1].to!int;
    auto G = new Tuple!(int, long)[][](N);
    foreach (i; 0..M) {
        s = readln.split.map!(to!long);
        auto u = s[0].to!int - 1;
        auto v = s[1].to!int - 1;
        auto c = s[2];
        G[u] ~= tuple(v, c);
        G[v] ~= tuple(u, c);
    }
    auto A = readln.split.map!(to!long).array;

    auto pq = new BinaryHeap!(Array!(Tuple!(int, long)), "a[1] > b[1]");
    foreach (i; 0..N) pq.insert(tuple(i, A[i]));

    auto ans = new long[](N);
    ans[] = 10L ^^ 18;

    while (!pq.empty) {
        auto i = pq.front[0];
        auto cost = pq.front[1];
        pq.removeFront;
        if (cost > ans[i]) continue;
        ans[i] = cost;
        foreach (e; G[i]) {
            auto j = e[0];
            auto nc = cost + 2 * e[1];
            if (nc >= ans[j]) continue;
            pq.insert(tuple(j, nc));
        }
    }

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


Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.You are given a string s consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.A substring of a string is a nonempty sequence of consecutive characters.For example if string s is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The only line contains string s (1 ≤ |s| ≤ 3·105). The string s contains only digits from 0 to 9.

Print integer a — the number of substrings of the string s that are divisible by 4. Note that the answer can be huge, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

import std.stdio;
import std.string;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		long res = 0;
		foreach (pos; 1..s.length + 1)
		{
			res += !(s[pos - 1] & 3);
			if (pos > 1 && !((s[pos - 2] * 2 + s[pos - 1]) & 3))
			{
				res += pos - 1;
			}
		}
		writeln (res);
	}
}


Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!

The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$.

Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any.

NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable.

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

void main() {
    auto N = readln.chomp.to!int;
    auto S = ((N-1)*2).iota.map!(i => tuple(readln.chomp, i)).array;
    S.sort!((a, b) => a[0].length < b[0].length);
    auto ans = new char[]((N-1)*2);

    string merge(string x, string y) {
        string ret = "";
        foreach (i; 0..x.length.to!int) {
            if (i == 0) ret ~= x[i];
            else if (x[i] == y[i-1]) ret ~= x[i];
            else return "";
        }
        return ret ~ y[$-1];
    }

    bool check(string T) {
        for (int i = 0; i < (N-1)*2; i += 2) {
            bool p1 = T.startsWith(S[i][0]);
            bool s1 = T.endsWith(S[i][0]);
            bool p2 = T.startsWith(S[i+1][0]);
            bool s2 = T.endsWith(S[i+1][0]);
            if (p1 && s2) {
                ans[S[i][1]] = 'P';
                ans[S[i+1][1]] = 'S';
            } else if (s1 && p2) {
                ans[S[i][1]] = 'S';
                ans[S[i+1][1]] = 'P';
            } else {
                return false;
            }
        }
        return true;
    }

    string S1 = S[$-2][0];
    string S2 = S[$-1][0];
    string T1 = merge(S1, S2);
    string T2 = merge(S2, S1);
    if (T1 != "" && check(T1)) {
        ans.writeln;
        return;
    }
    if (T2 != "" && check(T2)) {
        ans.writeln;
        return;
    }
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto S = ((N-1)*2).iota.map!(i => tuple(readln.chomp, i)).array;
    S.sort!((a, b) => a[0].length < b[0].length);
    auto ans = new char[]((N-1)*2);

    string merge(string x, string y) {
        string ret = "";
        foreach (i; 0..x.length.to!int) {
            if (i == 0) ret ~= x[i];
            else if (x[i] == y[i-1]) ret ~= x[i];
            else return "";
        }
        return ret ~ y[$-1];
    }

    bool check(string T) {
        for (int i = 0; i < (N-1)*2; i += 2) {
            bool p1 = T.startsWith(S[i][0]);
            bool s1 = T.endsWith(S[i][0]);
            bool p2 = T.startsWith(S[i+1][0]);
            bool s2 = T.endsWith(S[i+1][0]);
            if (s1 && p2) {
                ans[S[i][1]] = 'P';
                ans[S[i+1][1]] = 'S';
            } else if (s2 && p1) {
                ans[S[i][1]] = 'S';
                ans[S[i+1][1]] = 'P';
            } else {
                return false;
            }
        }
        return true;
    }

    string S1 = S[$-2][0];
    string S2 = S[$-1][0];
    string T1 = merge(S1, S2);
    string T2 = merge(S2, S1);
    if (T1 != "" && check(T1)) {
        ans.writeln;
        return;
    }
    if (T2 != "" && check(T2)) {
        ans.writeln;
        return;
    }
}


It turns out that you are a great fan of rock band AC/PE. Peter learned that and started the following game: he plays the first song of the list of n songs of the group, and you have to find out the name of the song. After you tell the song name, Peter immediately plays the following song in order, and so on.The i-th song of AC/PE has its recognizability pi. This means that if the song has not yet been recognized by you, you listen to it for exactly one more second and with probability of pi percent you recognize it and tell it's name. Otherwise you continue listening it. Note that you can only try to guess it only when it is integer number of seconds after the moment the song starts playing.In all AC/PE songs the first words of chorus are the same as the title, so when you've heard the first ti seconds of i-th song and its chorus starts, you immediately guess its name for sure.For example, in the song Highway To Red the chorus sounds pretty late, but the song has high recognizability. In the song Back In Blue, on the other hand, the words from the title sound close to the beginning of the song, but it's hard to name it before hearing those words. You can name both of these songs during a few more first seconds.Determine the expected number songs of you will recognize if the game lasts for exactly T seconds (i. e. you can make the last guess on the second T, after that the game stops).If all songs are recognized faster than in T seconds, the game stops after the last song is recognized.

The first line of the input contains numbers n and T (1 ≤ n ≤ 5000, 1 ≤ T ≤ 5000), separated by a space. Next n lines contain pairs of numbers pi and ti (0 ≤ pi ≤ 100, 1 ≤ ti ≤ T). The songs are given in the same order as in Petya's list.

Output a single number — the expected number of the number of songs you will recognize in T seconds. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.

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 t;
	while (readf (" %s %s", &n, &t) > 0)
	{
		auto f = new real [] [] (2, t + 1);
		real res = 0.0;
		int b = 0;
		f[b][] = 0.0;
		f[b][0] = 1.0;
		foreach (i; 0..n)
		{
			b ^= 1;
			f[b][] = 0.0;

			real p;
			int r;
			readf (" %s %s", &p, &r);
			p *= 0.01;
			real q = 1.0 - p;
			real qr1 = q ^^ (r - 1);

//			f2; = f1 * p;
//			f3; = f1 * q * p + f2 * p;
//			f4; = f1 * q * q * p + f2 * q * p + f3 * p;
//			fr; = f0 * q^(r-1) * p + f0 * q^r;

//			r = 3
//			f1; = f0 * p
//			f2; = f0 * q * p + f1 * p
//			f3; = f0 * q^2 + f1 * q * p + f2 * p
//			f3; = f0 * q^2 * p + f1 * q * p + f2 * p + f0 * q^3
//			f4; = f1 * q^2 * p + f2 * q * p + f3 * p + f1 * q^3
			real cur = 0.0;
			foreach (j; 0..t)
			{
				cur *= q;
				cur += f[!b][j];
				debug {writeln (i, ' ', j, ' ', cur);}
				f[b][j + 1] += cur * p;
				if (j >= r - 1)
				{
					f[b][j + 1] +=
					    f[!b][j - r + 1] * qr1 * q;
					cur -= f[!b][j - r + 1] * qr1;
				}
				if (f[b][j + 1] < 1E-100)
				{
					f[b][j + 1] = 0.0;
				}
			}
			res += cur * q * i;
			res += f[b][t] * (i + 1);
		}
		foreach (j; 0..t)
		{
			res += f[b][j] * n;
		}

		writefln ("%.10f", res);
	}
}


Amugae has a hotel consisting of $$$10$$$ rooms. The rooms are numbered from $$$0$$$ to $$$9$$$ from left to right.The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance.One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory.

The first line consists of an integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the number of events in Amugae's memory. The second line consists of a string of length $$$n$$$ describing the events in chronological order. Each character represents:    'L': A customer arrives from the left entrance.  'R': A customer arrives from the right entrance.  '0', '1', ..., '9': The customer in room $$$x$$$ ($$$0$$$, $$$1$$$, ..., $$$9$$$ respectively) leaves.  It is guaranteed that there is at least one empty room when a customer arrives, and there is a customer in the room $$$x$$$ when $$$x$$$ ($$$0$$$, $$$1$$$, ..., $$$9$$$) is given. Also, all the rooms are initially empty.

In the only line, output the hotel room's assignment status, from room $$$0$$$ to room $$$9$$$. Represent an empty room as '0', and an occupied room as '1', without spaces.

NoteIn the first example, hotel room's assignment status after each action is as follows.   First of all, all rooms are empty. Assignment status is 0000000000.  L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000.  L: one more customer from the left entrance. Assignment status is 1100000000.  R: one more customer from the right entrance. Assignment status is 1100000001.  L: one more customer from the left entrance. Assignment status is 1110000001.  1: the customer in room $$$1$$$ leaves. Assignment status is 1010000001.  R: one more customer from the right entrance. Assignment status is 1010000011.  L: one more customer from the left entrance. Assignment status is 1110000011.  1: the customer in room $$$1$$$ leaves. Assignment status is 1010000011. So after all, hotel room's final assignment status is 1010000011.In the second example, hotel room's assignment status after each action is as follows.   L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000.  0: the customer in room $$$0$$$ leaves. Assignment status is 0000000000.  L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000 again.  0: the customer in room $$$0$$$ leaves. Assignment status is 0000000000.  L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000.  L: one more customer from the left entrance. Assignment status is 1100000000.  R: one more customer from the right entrance. Assignment status is 1100000001.  R: one more customer from the right entrance. Assignment status is 1100000011.  9: the customer in room $$$9$$$ leaves. Assignment status is 1100000010. So after all, hotel room's final assignment status is 1100000010.

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;

    auto s = readln.chomp;

    auto rooms = new bool[10];

    foreach (e; s) {
        if (e == 'L') {
            int i = 0;
            while (rooms[i]) { ++i; }
            rooms[i] = true;
        } else if (e == 'R') {
            int i = 9;
            while (rooms[i]) { --i; }
            rooms[i] = true;
        } else {
            rooms[e - '0'] = false;
        }
    }

    foreach (e; rooms) {
        write(e ? '1' : '0');
    }
    writeln;
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int n = read.to!int;
	char[] cs = readln.chomp.to!(char[]);

	char[] ans = "0000000000".to!(char[]);
	foreach(c; cs){
		if(c == 'L'){
			foreach(i; 0 .. 10) if(ans[i] == '0'){
				ans[i] = '1';
				break;
			}
		}
		else if(c == 'R'){
			foreach_reverse(i; 0 .. 10) if(ans[i] == '0'){
				ans[i] = '1';
				break;
			}
		}
		else{
			int i = (c - '0').to!int;
			ans[i] = '0';
		}
	}

	ans.writeln;
}

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

string FMT_F = "%.10f";

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; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
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; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * y / gcd(x, y); }

//long mod = 10^^9 + 7;
long mod = 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 main()
{
	auto n = RD;
	auto s = RD!string;
	auto ans = new long[](10);
	foreach (c; s)
	{
		if (c == 'L')
		{
			foreach (i; 0..10)
			{
				if (ans[i] == 0)
				{
					ans[i] = 1;
					break;
				}
			}
		}
		else if (c == 'R')
		{
			foreach_reverse (i; 0..10)
			{
				if (ans[i] == 0)
				{
					ans[i] = 1;
					break;
				}
			}
		}
		else
		{
			auto pos = [c].to!int;
			ans[pos] = 0;
		}

	}

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


The numbers $$$1, \, 2, \, \dots, \, n \cdot k$$$ are colored with $$$n$$$ colors. These colors are indexed by $$$1, \, 2, \, \dots, \, n$$$. For each $$$1 \le i \le n$$$, there are exactly $$$k$$$ numbers colored with color $$$i$$$.Let $$$[a, \, b]$$$ denote the interval of integers between $$$a$$$ and $$$b$$$ inclusive, that is, the set $$$\{a, \, a + 1, \, \dots, \, b\}$$$. You must choose $$$n$$$ intervals $$$[a_1, \, b_1], \, [a_2, \, b_2], \, \dots, [a_n, \, b_n]$$$ such that:   for each $$$1 \le i \le n$$$, it holds $$$1 \le a_i < b_i \le n \cdot k$$$;  for each $$$1 \le i \le n$$$, the numbers $$$a_i$$$ and $$$b_i$$$ are colored with color $$$i$$$;  each number $$$1 \le x \le n \cdot k$$$ belongs to at most $$$\left\lceil \frac{n}{k - 1} \right\rceil$$$ intervals. One can show that such a family of intervals always exists under the given constraints.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$2 \le k \le 100$$$) — the number of colors and the number of occurrences of each color. The second line contains $$$n \cdot k$$$ integers $$$c_1, \, c_2, \, \dots, \, c_{nk}$$$ ($$$1 \le c_j \le n$$$), where $$$c_j$$$ is the color of number $$$j$$$. It is guaranteed that, for each $$$1 \le i \le n$$$, it holds $$$c_j = i$$$ for exactly $$$k$$$ distinct indices $$$j$$$.

Output $$$n$$$ lines. The $$$i$$$-th line should contain the two integers $$$a_i$$$ and $$$b_i$$$. If there are multiple valid choices of the intervals, output any.

NoteIn the first sample, each number can be contained in at most $$$\left\lceil \frac{4}{3 - 1} \right\rceil = 2$$$ intervals. The output is described by the following picture:  In the second sample, the only interval to be chosen is forced to be $$$[1, \, 2]$$$, and each number is indeed contained in at most $$$\left\lceil \frac{1}{2 - 1} \right\rceil = 1$$$ interval.In the third sample, each number can be contained in at most $$$\left\lceil \frac{3}{3 - 1} \right\rceil = 2$$$ intervals. The output is described by the following picture:

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

immutable int NA = -1;

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

		auto x = (n + k - 2) / (k - 1);
		auto pos = new int [n];
		pos[] = NA;
		auto used = new bool [n];

		int [] [] answer;
		foreach (int i, ref cur; a)
		{
			if (pos[cur] != NA)
			{
				answer ~= [pos[cur], i];
				pos[cur] = NA;
				used[cur] = true;
				if (answer.length % x == 0)
				{
					pos[] = NA;
				}
				if (answer.length >= n)
				{
					break;
				}
			}
			else if (!used[cur])
			{
				pos[cur] = i;
			}
		}

		answer.schwartzSort !(c => a[c.front]);

		writefln !("%(%(%s %)\n%)") (answer.map !(map !(q{a + 1})));
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      auto C = new int[N * K];
      foreach (i; 0 .. N * K) {
        C[i] = readInt() - 1;
      }

      auto xss = new int[][N];
      foreach (i; 0 .. N * K) {
        xss[C[i]] ~= i;
      }

      auto as = new int[N];
      auto bs = new int[N];
      as[] = -1;
      bs[] = -1;
      auto nums = new int[K - 1];
      foreach (c; 0 .. N) {
        ++nums[c % (K - 1)];
      }
      foreach (k; 0 .. K - 1) {
        alias Entry = Tuple!(int, "x", int, "c");
        Entry[] es;
        foreach (c; 0 .. N) {
          if (as[c] == -1) {
            es ~= Entry(xss[c][k + 1], c);
          }
        }
        es.sort;
        foreach (j; 0 .. nums[k]) {
          const c = es[j].c;
          as[c] = xss[c][k];
          bs[c] = xss[c][k + 1];
        }
      }

      foreach (c; 0 .. N) {
        writeln(as[c] + 1, " ", bs[c] + 1);
      }
    }
  } catch (EOFException e) {
  }
}

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

immutable int NA = -1;

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

		auto x = (n + k - 2) / (k - 1);
		auto pos = new int [n];
		pos[] = NA;

		int [] [] answer;
		foreach (int i, ref cur; a)
		{
			if (pos[cur] == NA)
			{
				pos[cur] = i;
			}
			else
			{
				answer ~= [pos[cur] + 1, i + 1];
				pos[cur] = NA;
				if (answer.length % x == 0)
				{
					pos[] = NA;
				}
				if (answer.length >= n)
				{
					break;
				}
			}
		}

		writefln !("%(%(%s %)\n%)") (answer);
	}
}

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

// Dijkstra
class MinCostFlow(Capa, Cost, Capa CAPA_EPS = 0) {
  int n, m;
  int[][] g;
  int[] as, bs;
  Capa[] capa;
  Cost[] cost, pot;
  Capa tof;
  Cost toc;
  this(int n) {
    this.n = n; m = 0; g = new int[][n]; as = []; bs = []; capa = []; cost = [];
  }
  int addEdge(int u, int v, Capa w, Cost c) {
    debug {
      writeln("addEdge ", u, " ", v, " ", w, " ", c);
    }
    const i = m;
    g[u] ~= m; as ~= u; bs ~= v; capa ~= w; cost ~= c; ++m;
    g[v] ~= m; as ~= v; bs ~= u; capa ~= 0; cost ~= -c; ++m;
    return i;
  }
  bool solve(int source, int sink, Capa flow) {
    pot = new Cost[n];
    pot[] = 0;
    for (; ; ) {
      bool cont;
      foreach (u; 0 .. n) foreach (i; g[u]) if (capa[i] > CAPA_EPS) {
        const v = bs[i];
        if (pot[v] > pot[u] + cost[i]) {
          pot[v] = pot[u] + cost[i];
          cont = true;
        }
      }
      if (!cont) break;
    }
    auto dist = new Cost[n];
    auto prei = new int[n];
    auto vis = new bool[n];
    for (tof = 0, toc = 0; tof + CAPA_EPS < flow; ) {
      alias Entry = Tuple!(Cost, "c", int, "u");
      BinaryHeap!(Array!Entry, "a > b") que;
      dist[] = -1;
      prei[] = -1;
      vis[] = false;
      dist[source] = 0;
      prei[source] = -2;
      que.insert(Entry(0, source));
      for (; !que.empty(); ) {
        const c = que.front.c;
        const u = que.front.u;
        que.removeFront;
        if (vis[u]) continue;
        vis[u] = true;
        foreach (i; g[u]) if (capa[i] > CAPA_EPS) {
          const v = bs[i];
          if (vis[v]) continue;
          const cc = c + cost[i] + pot[u] - pot[v];
          if (prei[v] == -1 || dist[v] > cc) {
            dist[v] = cc;
            prei[v] = i;
            que.insert(Entry(cc, v));
          }
        }
      }
      if (!vis[sink]) return false;
      Capa f = flow - tof;
      for (int v = sink; v != source; ) {
        const i = prei[v];
        if (f > capa[i]) f = capa[i];
        v = as[i];
      }
      for (int v = sink; v != source; ) {
        const i = prei[v];
        capa[i] -= f; capa[i ^ 1] += f;
        v = as[i];
      }
      tof += f;
      toc += f * (dist[sink] - pot[source] + pot[sink]);
      pot[] += dist[];
    }
    return true;
  }
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      auto C = new int[N * K];
      foreach (i; 0 .. N * K) {
        C[i] = readInt() - 1;
      }

      auto app = new int[N];
      app[] = -1;
      auto nxt = new int[N * K];
      foreach_reverse (i; 0 .. N * K) {
        nxt[i] = app[C[i]];
        app[C[i]] = i;
      }

      const lim = (N + (K - 1) - 1) / (K - 1);
      auto mcf = new MinCostFlow!(int, int)(N * K + 1);
      foreach (i; 0 .. N * K) {
        mcf.addEdge(i, i + 1, lim, 0);
      }
      auto ids = new int[N * K];
      ids[] = -1;
      foreach (i; 0 .. N * K) {
        if (nxt[i] != -1) {
          ids[i] = mcf.addEdge(i, nxt[i] + 1, 1, -1);
        }
      }
      mcf.solve(0, N * K, lim);
      assert(mcf.toc <= -N);

      int cnt;
      foreach (i; 0 .. N * K) {
        if (ids[i] != -1 && mcf.capa[ids[i]] == 0) {
          writeln(i + 1, " ", nxt[i] + 1);
          if (++cnt >= N) {
            break;
          }
        }
      }
    }
  } catch (EOFException e) {
  }
}


At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.Each class must present two couples to the ball. In Vasya's class, $$$a$$$ boys and $$$b$$$ girls wish to participate. But not all boys and not all girls are ready to dance in pairs.Formally, you know $$$k$$$ possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair.For example, if $$$a=3$$$, $$$b=4$$$, $$$k=4$$$ and the couples $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(3, 4)$$$ are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below):   $$$(1, 3)$$$ and $$$(2, 2)$$$;  $$$(3, 4)$$$ and $$$(1, 3)$$$; But the following combinations are not possible:   $$$(1, 3)$$$ and $$$(1, 2)$$$ — the first boy enters two pairs;  $$$(1, 2)$$$ and $$$(2, 2)$$$ — the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$a$$$, $$$b$$$ and $$$k$$$ ($$$1 \le a, b, k \le 2 \cdot 10^5$$$) — the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains $$$k$$$ integers $$$a_1, a_2, \ldots a_k$$$. ($$$1 \le a_i \le a$$$), where $$$a_i$$$ is the number of the boy in the pair with the number $$$i$$$. The third line of each test case contains $$$k$$$ integers $$$b_1, b_2, \ldots b_k$$$. ($$$1 \le b_i \le b$$$), where $$$b_i$$$ is the number of the girl in the pair with the number $$$i$$$. It is guaranteed that the sums of $$$a$$$, $$$b$$$, and $$$k$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$. It is guaranteed that each pair is specified at most once in one test case.

For each test case, on a separate line print one integer — the number of ways to choose two pairs that match the condition above.

NoteIn the first test case, the following combinations of pairs fit:   $$$(1, 2)$$$ and $$$(3, 4)$$$;  $$$(1, 3)$$$ and $$$(2, 2)$$$;  $$$(1, 3)$$$ and $$$(3, 4)$$$;  $$$(2, 2)$$$ and $$$(3, 4)$$$. There is only one pair in the second test case.In the third test case, the following combinations of pairs fit:   $$$(1, 1)$$$ and $$$(2, 2)$$$;  $$$(1, 2)$$$ and $$$(2, 1)$$$.

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int A, B, K; get(A, B, K);
        int[] AA; get(AA);
        int[] BB; get(BB);
        long res;
        auto ac = new int[](A + 1);
        auto bc = new int[](B + 1);
        int[Tuple!(int, int)] ps;
        foreach_reverse (i; 0..K) {
            int a = AA[i], b = BB[i], p;
            auto t = tuple(a, b);
            if (t in ps) p = ps[t];
            res += (K - i - 1) - ac[a] - bc[b] + p;
            ac[a] += 1;
            bc[b] += 1;
            ps[t] += 1;
        }
        writeln(res);
    }
}

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)
	{
		int p, q, k;
		readf !(" %s %s %s") (p, q, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		a[] -= 1;
		b[] -= 1;
		auto da = new int [p];
		auto db = new int [q];
		foreach (ref c; a)
		{
			da[c] += 1;
		}
		foreach (ref c; b)
		{
			db[c] += 1;
		}
		long res = 0;
		foreach (i; 0..p)
		{
			res += da[i] * (da[i] - 1L);
		}
		foreach (j; 0..q)
		{
			res += db[j] * (db[j] - 1L);
		}
		writeln ((k * (k - 1L) - res) / 2);
	}
}

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 m = RD!int;
		auto k = RD!int;
		auto a = RDA(-1);
		auto b = RDA(-1);

		auto cnt_a = new long[](n);
		auto cnt_b = new long[](m);
		foreach (i; 0..k)
		{
			ans[ti] += i - cnt_a[a[i]] - cnt_b[b[i]];
			++cnt_a[a[i]];
			++cnt_b[b[i]];
		}
	}

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


Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya"  "nastya"  "nastya"  "nastya"  "nastya"  "nastya"  "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.

The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| < |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).

Print a single integer number, the maximum number of letters that Nastya can remove.

NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba"  "ababcba"  "ababcba"  "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.

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;

void main() {
    auto S = readln.chomp;
    auto T = readln.chomp;
    auto N = S.length.to!int;
    auto M = T.length.to!int;
    auto A = readln.split.map!(to!int).array;
    auto B = new int[](N);
    foreach (i; 0..N) {
        B[A[i]-1] = i;
    }

    int hi = N;
    int lo = M - 1;
    while (hi - lo > 1) {
        int mid = (hi + lo) / 2;
        int cnt = 0;
        int del = N - mid;
        foreach (i; 0..N) {
            if (B[i] < del)
                continue;
            if (S[i] == T[cnt])
                cnt += 1;
            if (cnt >= M)
                break;
        }
        if (cnt >= M)
            hi = mid;
        else
            lo = mid;
    }

    (N-hi).writeln;
}

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 ()
{
	while (true)
	{
		auto s = readln.strip;
		if (s is null)
		{
			break;
		}
		auto t = readln.strip;
		auto p = readln.splitter.map !(to !(int)).array;
		int n = cast (int) s.length;
		p[] -= 1;

		bool ok (int k)
		{
			auto cur = s.dup;
			foreach (i; 0..k)
			{
				cur[p[i]] = '-';
			}
			cur = cur.filter !(c => c != '-').text.dup;
			int pos = 0;
			foreach (c; cur)
			{
				if (c == t[pos])
				{
					pos += 1;
					if (pos >= t.length)
					{
						return true;
					}
				}
			}
			return false;
		}

		int lo = 0;
		int hi = n;
		while (lo < hi)
		{
			int me = (lo + hi + 1) >> 1;
			if (ok (me))
			{
				lo = me;
			}
			else
			{
				hi = me - 1;
			}
		}
		writeln (lo);
	}
}


Maksim has $$$n$$$ objects and $$$m$$$ boxes, each box has size exactly $$$k$$$. Objects are numbered from $$$1$$$ to $$$n$$$ in order from left to right, the size of the $$$i$$$-th object is $$$a_i$$$.Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the $$$i$$$-th object fits in the current box (the remaining size of the box is greater than or equal to $$$a_i$$$), he puts it in the box, and the remaining size of the box decreases by $$$a_i$$$. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.Maksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has. Your task is to say the maximum number of objects Maksim can pack in boxes he has.Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change).

The first line of the input contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^9$$$) — the number of objects, the number of boxes and the size of each box. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the size of the $$$i$$$-th object.

Print the maximum number of objects Maksim can pack using the algorithm described in the problem statement.

NoteIn the first example Maksim can pack only $$$4$$$ objects. Firstly, he tries to pack all the $$$5$$$ objects. Distribution of objects will be $$$[5], [2, 1]$$$. Maxim cannot pack the next object in the second box and he has no more empty boxes at all. Next he will throw out the first object and the objects distribution will be $$$[2, 1], [4, 2]$$$. So the answer is $$$4$$$.In the second example it is obvious that Maksim cannot pack all the objects starting from first, second, third and fourth (in all these cases the distribution of objects is $$$[4]$$$), but he can pack the last object ($$$[1]$$$).In the third example Maksim can pack all the objects he has. The distribution will be $$$[1, 2], [3], [1, 1]$$$.

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

bool ok(int[] a, int m, int k)
{
    auto n = cast(int)a.length;
    auto i = 0, j = 0;
    auto c = k;
    while (i < n && j < m)
    {
        if (a[i] > c)
        {
            ++ j;
            c = k;
        }
        else
        {
            c -= a[i];
            ++ i;
        }
    }
    return i == n ? true : false;
}

void solve(int[] a, int n, int m, int k)
{
    auto ans = 0;
    auto left = 0, right = n - 1;
    while (left <= right)
    {
        auto mid = (left + right) >> 1;
        if (!ok(a[mid .. n], m, k))
        {
            left = mid + 1;
        }
        else
        {
            ans = n - mid;
            right = mid - 1;
        }
    }
    writeln(ans);
}

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

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

  int n, m;
  long k;
  rd(n, m, k);
  auto a = readln.split.to!(long[]);

  for (auto i = n - 1, r = k; i >= 0; i--) {
    if ((r -= a[i]) < 0) {
      if ((--m) == 0) {
        writeln(n - i - 1);
        return;
      }
      r = k - a[i];
    }
  }

  writeln(n);
}

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

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


Yelisey has an array $$$a$$$ of $$$n$$$ integers.If $$$a$$$ has length strictly greater than $$$1$$$, then Yelisei can apply an operation called minimum extraction to it:   First, Yelisei finds the minimal number $$$m$$$ in the array. If there are several identical minima, Yelisey can choose any of them.  Then the selected minimal element is removed from the array. After that, $$$m$$$ is subtracted from each remaining element. Thus, after each operation, the length of the array is reduced by $$$1$$$.For example, if $$$a = [1, 6, -4, -2, -4]$$$, then the minimum element in it is $$$a_3 = -4$$$, which means that after this operation the array will be equal to $$$a=[1 {- (-4)}, 6 {- (-4)}, -2 {- (-4)}, -4 {- (-4)}] = [5, 10, 2, 0]$$$.Since Yelisey likes big numbers, he wants the numbers in the array $$$a$$$ to be as big as possible.Formally speaking, he wants to make the minimum of the numbers in array $$$a$$$ to be maximal possible (i.e. he want to maximize a minimum). To do this, Yelisey can apply the minimum extraction operation to the array as many times as he wants (possibly, zero). Note that the operation cannot be applied to an array of length $$$1$$$.Help him find what maximal value can the minimal element of the array have after applying several (possibly, zero) minimum extraction operations to the array.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the original length of the array $$$a$$$. The second line of the description lists $$$n$$$ space-separated integers $$$a_i$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each of them containing the answer to the corresponding test case. The answer to the test case is a single integer — the maximal possible minimum in $$$a$$$, which can be obtained by several applications of the described operation to it.

NoteIn the first example test case, the original length of the array $$$n = 1$$$. Therefore minimum extraction cannot be applied to it. Thus, the array remains unchanged and the answer is $$$a_1 = 10$$$.In the second set of input data, the array will always consist only of zeros.In the third set, the array will be changing as follows: $$$[\color{blue}{-1}, 2, 0] \to [3, \color{blue}{1}] \to [\color{blue}{2}]$$$. The minimum elements are highlighted with $$$\color{blue}{\text{blue}}$$$. The maximal one is $$$2$$$.In the fourth set, the array will be modified as $$$[2, 10, \color{blue}{1}, 7] \to [\color{blue}{1}, 9, 6] \to [8, \color{blue}{5}] \to [\color{blue}{3}]$$$. Similarly, the maximum of the minimum elements is $$$5$$$.

// Author: Ivan Kazmenko (gassa@mail.ru)
module solution;
import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		zip (a, chain (only (0), a)).map !(q{a[0] - a[1]})
		    .maxElement.writeln;
	}
}


Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction.Pavel has a plan: a permutation p and a sequence b1, b2, ..., bn, consisting of zeros and ones. Each second Pavel move skewer on position i to position pi, and if bi equals 1 then he reverses it. So he hope that every skewer will visit every position in both directions.Unfortunately, not every pair of permutation p and sequence b suits Pavel. What is the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements? Note that after changing the permutation should remain a permutation as well.There is no problem for Pavel, if some skewer visits some of the placements several times before he ends to cook. In other words, a permutation p and a sequence b suit him if there is an integer k (k ≥ 2n), so that after k seconds each skewer visits each of the 2n placements.It can be shown that some suitable pair of permutation p and sequence b exists for any n.

The first line contain the integer n (1 ≤ n ≤ 2·105) — the number of skewers. The second line contains a sequence of integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation, according to which Pavel wants to move the skewers. The third line contains a sequence b1, b2, ..., bn consisting of zeros and ones, according to which Pavel wants to reverse the skewers.

Print single integer — the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements.

NoteIn the first example Pavel can change the permutation to 4, 3, 1, 2.In the second example Pavel can change any element of b to 1.

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 p = readln.split.map !(to !(int)).array;
		auto b = readln.split.map !(to !(int)).array;
		p[] -= 1;
		int res = 0;
		auto d = new bool [n];
		foreach (i; 0..n)
		{
			if (!d[i])
			{
				int k = i;
				while (!d[k])
				{
					d[k] = true;
					k = p[k];
				}
				res += 1;
			}
		}
		if (res == 1)
		{
			res -= 1;
		}
		res += (1 + sum (b)) & 1;
		writeln (res);
	}
}


In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i.Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.

First line of input contains single integer number n (2 ≤ n ≤ 100 000)  — number of inflorescences. Second line of input contains sequence of n - 1 integer numbers p2, p3, ..., pn (1 ≤ pi < i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down.

Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest.

NoteIn first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them.In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect it.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto p = [0] ~ readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto a = new int [] [n];
		foreach (i; 1..n)
		{
			a[p[i]] ~= i;
		}

		auto d = new int [n];

		void recur (int v, int h)
		{
			d[h] ^= 1;
			foreach (u; a[v])
			{
				recur (u, h + 1);
			}
		}

		recur (0, 0);
		writeln (sum (d));
	}
}

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 P = new int[N];
      foreach (u; 1 .. N) {
        P[u] = readInt() - 1;
      }
      P[0] = -1;

      auto dep = new int[N];
      dep[0] = 0;
      foreach (u; 1 .. N) {
        dep[u] = 1 + dep[P[u]];
      }

      auto cnt = new int[N];
      foreach (u; 0 .. N) {
        ++cnt[dep[u]];
      }
      int ans;
      foreach (d; 0 .. N) {
        ans += cnt[d] % 2;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are a usual chat user on the most famous streaming platform. Of course, there are some moments when you just want to chill and spam something.More precisely, you want to spam the emote triangle of size $$$k$$$. It consists of $$$2k-1$$$ messages. The first message consists of one emote, the second one — of two emotes, ..., the $$$k$$$-th one — of $$$k$$$ emotes, the $$$k+1$$$-th one — of $$$k-1$$$ emotes, ..., and the last one — of one emote.For example, the emote triangle for $$$k=3$$$ consists of $$$5$$$ messages:  Of course, most of the channels have auto moderation. Auto moderator of the current chat will ban you right after you spam at least $$$x$$$ emotes in succession (you can assume you are the only user in the chat). Now you are interested — how many messages will you write before getting banned? Or maybe you will not get banned at all (i.e. will write all $$$2k-1$$$ messages and complete your emote triangle successfully)? Note that if you get banned as a result of writing a message, this message is also counted.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains integers $$$k$$$ and $$$x$$$ ($$$1 \le k \le 10^9; 1 \le x \le 10^{18}$$$).

For each test case, print the number of messages you will write before getting banned for the corresponding values $$$k$$$ and $$$x$$$.

NoteLet's analyze the test cases of the example.  In the first test case, you write three messages containing $$$1$$$, $$$2$$$ and $$$3$$$ emotes respectively, and since $$$1 + 2 + 3 \ge 6$$$, you get banned after that.  In the second test case, you write four messages containing $$$1$$$, $$$2$$$, $$$3$$$ and $$$4$$$ emotes respectively, and since $$$1 + 2 + 3 + 4 \ge 7$$$, you get banned after that.  In the third test case, you write one message containing exactly $$$1$$$ emote. It doesn't get you banned, since $$$1 < 2$$$, but you have already finished posting your emote triangle. So you wrote one message successfully.  In the fourth test case, you write four messages containing $$$1$$$, $$$2$$$, $$$3$$$ and $$$2$$$ emotes respectively, and since $$$1 + 2 + 3 + 2 \ge 7$$$, you get banned after that.  In the fifth test case, you write three messages containing $$$1$$$, $$$2$$$ and $$$1$$$ emote respectively. It doesn't get you banned, since $$$1 + 2 + 1 < 5$$$, but you have already finished posting your emote triangle. So you wrote three messages successfully.  In the sixth test case, since $$$x = 1$$$, you get banned as soon as you send your first message.  The seventh test case is too large to analyze, so we'll skip it.

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]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

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

		if (k == 1)
		{
			ans[ti] = 1;
			continue;
		}

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

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


You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n.You need to permute the array elements so that value  became minimal possible. In particular, it is allowed not to change order of elements at all.

The first line contains two integers n, k (2 ≤ n ≤ 3·105, 1 ≤ k ≤ min(5000, n - 1)).  The second line contains n integers A[1], A[2], ..., A[n] ( - 109 ≤ A[i] ≤ 109), separate by spaces — elements of the array A.

Print the minimum possible value of the sum described in the statement.

NoteIn the first test one of the optimal permutations is 1 4 2. In the second test the initial order is optimal. In the third test one of the optimal permutations is 2 3 4 4 3 5.

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

immutable long INF = long.max / 2;

void main ()
{
	int n, k;
	while (readf (" %s %s ", &n, &k) > 0)
	{
		auto a = readln.split.map !(to !(int)).array;
		sort !(q{a < b}, SwapStrategy.stable) (a);
		int total = a.back - a.front;
		int [] d;
		d ~= 0;
		foreach (i; 0..n - 1)
		{
			d ~= a[i + 1] - a[i];
		}
		d ~= 0;
		debug {writeln (d);}

		int q = n / k;
		int r = n - q * k;
		auto f = new long [] [] (2, r + 1);
		int b = 0;
		f[b][] = -INF;
		f[b][0] = 0;
		foreach (i; 0..k)
		{
			b ^= 1;
			f[b][] = -INF;
			foreach (j; 0..r + 1)
			{
				debug {writefln ("(%s, %s) <- " ~
				    "(%s, %s) + d[%s]", i + 1, j,
				    i, j, (i + 1) * q + j);}
				f[b][j] = max (f[b][j],
				    f[!b][j] + d[(i + 1) * q + j]);
				if (j > 0)
				{
					debug {writefln ("(%s, %s) <- " ~
					    "(%s, %s) + d[%s]", i + 1, j,
					    i, j - 1, (i + 1) * q + j);}
					f[b][j] = max (f[b][j],
					    f[!b][j - 1] + d[(i + 1) * q + j]);
				}
			}
		}

		writeln (total - f[b][r]);
	}
}

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

immutable long INF = long.max / 2;

void main ()
{
	int n, k;
	while (readf (" %s %s ", &n, &k) > 0)
	{
		auto a = readln.split.map !(to !(int)).array;
		sort !(q{a < b}, SwapStrategy.stable) (a);
		int total = a.back - a.front;
		int [] d;
		d ~= 0;
		foreach (i; 0..n - 1)
		{
			d ~= a[i + 1] - a[i];
		}
		d ~= 0;
		debug {writeln (d);}

		int q = n / k;
		int r = n - q * k;
		auto f = new int [] [] (2, r + 1);
		int b = 0;
		f[b][] = 0;
		foreach (i; 0..k)
		{
			b ^= 1;
			f[b][] = 0;
			foreach (j; 0..r + 1)
			{
				debug {writefln ("(%s, %s) <- " ~
				    "(%s, %s) + d[%s]", i + 1, j,
				    i, j, (i + 1) * q + j);}
				f[b][j] = f[!b][j] + d[(i + 1) * q + j];
				if (j > 0)
				{
					debug {writefln ("(%s, %s) <- " ~
					    "(%s, %s) + d[%s]", i + 1, j,
					    i, j - 1, (i + 1) * q + j);}
					f[b][j] = max (f[b][j],
					    f[!b][j - 1] + d[(i + 1) * q + j]);
				}
			}
		}

		writeln (total - f[b][r]);
	}
}


Slavic has an array of length $$$n$$$ consisting only of zeroes and ones. In one operation, he removes either the first or the last element of the array. What is the minimum number of operations Slavic has to perform such that the total sum of the array is equal to $$$s$$$ after performing all the operations? In case the sum $$$s$$$ can't be obtained after any amount of operations, you should output -1.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$s$$$ ($$$1 \leq n, s \leq 2 \cdot 10^5$$$) — the length of the array and the needed sum of elements. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$0 \leq a_i \leq 1$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the minimum amount of operations required to have the total sum of the array equal to $$$s$$$, or -1 if obtaining an array with sum $$$s$$$ isn't possible.

NoteIn the first test case, the sum of the whole array is $$$1$$$ from the beginning, so we don't have to make any operations.In the second test case, the sum of the array is $$$2$$$ and we want it to be equal to $$$1$$$, so we should remove the first element. The array turns into $$$[1, 0]$$$, which has a sum equal to $$$1$$$.In the third test case, the sum of the array is $$$5$$$ and we need it to be $$$3$$$. We can obtain such a sum by removing the first two elements and the last element, doing a total of three operations. The array turns into $$$[0, 1, 1, 1, 0, 0]$$$, which has a sum equal to $$$3$$$.

void main() { runSolver(); }

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

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

      int l, r;
      int sum;
      int ans;
      while(l <= r) {
        if (r < N && A[r] == 0) {
          r++;
        } else if (r < N && A[r] == 1 && sum < S) {
          r++;
          sum++;
        } else {
          sum -= A[l++];
        }

        if (sum == S) ans = max(ans, r - l);
        if (l >= N) break;
      }

      return ans == 0 ? -1 : N - ans;
    }

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

  outputForAtCoder(&solve);
}

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

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

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


In order to fly to the Moon Mister B just needs to solve the following problem.There is a complete indirected graph with n vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles.We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you?

The only line contains single integer n (3 ≤ n ≤ 300).

If there is no answer, print -1. Otherwise, in the first line print k (1 ≤ k ≤ n2) — the number of cycles in your solution. In each of the next k lines print description of one cycle in the following format: first print integer m (3 ≤ m ≤ 4) — the length of the cycle, then print m integers v1, v2, ..., vm (1 ≤ vi ≤ n) — the vertices in the cycle in the traverse order. Each edge should be in exactly two cycles.

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

      int[][] ans;
      if (N % 2 != 0) {
        ans ~= [0, 1, 2];
        ans ~= [0, 1, 2];
        for (int n = 3; n < N; n += 2) {
          ans ~= [n, n + 1, 0];
          ans ~= [n, n + 1, 0];
          for (int u = 1; u < n; u += 2) {
            ans ~= [n, u, n + 1, u + 1];
            ans ~= [n, u, n + 1, u + 1];
          }
        }
      } else {
        ans ~= [0, 1, 2];
        ans ~= [1, 2, 3];
        ans ~= [2, 3, 0];
        ans ~= [3, 0, 1];
        for (int n = 4; n < N; n += 2) {
          ans ~= [n, 0, n + 1, 1];
          ans ~= [n, n + 1, 0];
          ans ~= [n, n + 1, 1];
          for (int u = 2; u < n; u += 2) {
            ans ~= [n, u, n + 1, u + 1];
            ans ~= [n, u, n + 1, u + 1];
          }
        }
      }

      writeln(ans.length);
      foreach (cyc; ans) {
        write(cyc.length);
        foreach (u; cyc) {
          write(" ", u + 1);
        }
        writeln;
      }

      auto adj = new int[][](N, N);
      foreach (cyc; ans) {
        foreach (i; 0 .. cyc.length) {
          const u = cyc[i], v = cyc[(i + 1) % $];
          ++adj[u][v];
          ++adj[v][u];
        }
      }
      foreach (u; 0 .. N) foreach (v; 0 .. N) {
        assert(adj[u][v] == (u == v) ? 0 : 2);
      }
    }
  } catch (EOFException e) {
  }
}


There are $$$n$$$ monsters standing in a row numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th monster has $$$h_i$$$ health points (hp). You have your attack power equal to $$$a$$$ hp and your opponent has his attack power equal to $$$b$$$ hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to $$$0$$$.The fight with a monster happens in turns.   You hit the monster by $$$a$$$ hp. If it is dead after your hit, you gain one point and you both proceed to the next monster.  Your opponent hits the monster by $$$b$$$ hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most $$$k$$$ times in total (for example, if there are two monsters and $$$k=4$$$, then you can use the technique $$$2$$$ times on the first monster and $$$1$$$ time on the second monster, but not $$$2$$$ times on the first monster and $$$3$$$ times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.

The first line of the input contains four integers $$$n, a, b$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le a, b, k \le 10^9$$$) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique. The second line of the input contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 10^9$$$), where $$$h_i$$$ is the health points of the $$$i$$$-th monster.

Print one integer — the maximum number of points you can gain if you use the secret technique optimally.

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
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;
    int a = readInt;
    int b = readInt;
    int k = readInt;
    int[] need = new int[n];
    for (int i = 0; i < n; ++i)
    {
        int hp = readInt;
        int s = a + b;
        int rounds = (hp + s - 1) / s;
        hp -= (rounds - 1) * s;
        need[i] = (hp + a - 1) / a - 1;
    }
    sort(need);
    int result = 0;
    for (int i = 0; i < n; ++i)
    {
        if (need[i] <= k)
        {
            k -= need[i], result++;
        }
    }
    writeln(result);
}

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()
{
  mixin(input(q{n, a, b, k}));
  auto h = new long[n.ind];
  read(h);
  auto rk = h
    .map!((hi)
      {
       auto r = (hi % (a + b) == 0)? (a + b) : (hi % (a + b));
       // a * x >= r
       // x >= r / a
       return (r + pmod(-r, a)) / a - 1;
      })
    .array;
  sort(rk);
  auto points = long(0);
  foreach(rki; rk)
    {
      if (k < rki)
        break;
      k -= rki;
      points++;
    }
  writeln(points);
}

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 = 998244353;
//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 main()
{
	auto n = RD!int;
	auto a = RD!int;
	auto b = RD!int;
	auto k = RD!int;
	auto h = RDA(-1);

	auto cnt = new int[](n);
	foreach (i; 0..n)
	{
		auto r = h[i] % (a+b);
		cnt[i] = r / a;
	}
	cnt.sort();

	int ans;
	foreach (i; 0..n)
	{
		if (cnt[i] <= k)
		{
			++ans;
			k -= cnt[i];
		}
	}

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


Recently, Petya learned about a new game "Slay the Dragon". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of $$$n$$$ heroes, the strength of the $$$i$$$-th hero is equal to $$$a_i$$$.According to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon's defense is equal to $$$x$$$, then you have to send a hero with a strength of at least $$$x$$$ to kill it. If the dragon's attack power is $$$y$$$, then the total strength of the heroes defending the castle should be at least $$$y$$$.The player can increase the strength of any hero by $$$1$$$ for one gold coin. This operation can be done any number of times.There are $$$m$$$ dragons in the game, the $$$i$$$-th of them has defense equal to $$$x_i$$$ and attack power equal to $$$y_i$$$. Petya was wondering what is the minimum number of coins he needs to spend to defeat the $$$i$$$-th dragon.Note that the task is solved independently for each dragon (improvements are not saved).

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — number of heroes. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{12}$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th hero. The third line contains a single integer $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the number of dragons. The next $$$m$$$ lines contain two integers each, $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le 10^{12}; 1 \le y_i \le 10^{18}$$$) — defense and attack power of the $$$i$$$-th dragon.

Print $$$m$$$ lines, $$$i$$$-th of which contains a single integer — the minimum number of coins that should be spent to defeat the $$$i$$$-th dragon.

NoteTo defeat the first dragon, you can increase the strength of the third hero by $$$1$$$, then the strength of the heroes will be equal to $$$[3, 6, 3, 3]$$$. To kill the dragon, you can choose the first hero.To defeat the second dragon, you can increase the forces of the second and third heroes by $$$1$$$, then the strength of the heroes will be equal to $$$[3, 7, 3, 3]$$$. To kill the dragon, you can choose a second hero.To defeat the third dragon, you can increase the strength of all the heroes by $$$1$$$, then the strength of the heroes will be equal to $$$[4, 7, 3, 4]$$$. To kill the dragon, you can choose a fourth hero.To defeat the fourth dragon, you don't need to improve the heroes and choose a third hero to kill the dragon.To defeat the fifth dragon, you can increase the strength of the second hero by $$$2$$$, then the strength of the heroes will be equal to $$$[3, 8, 2, 3]$$$. To kill the dragon, you can choose a second hero.

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

void main()
{
	int n;
	scanf("%d", &n);
	getchar();
	auto heroes = readln.split().to!(long[]);
	int m;
	scanf("%d", &m);
	getchar();
	heroes.sort();
	long[] res = new long[m];
	long total = to!long(heroes.sum());
	foreach(i;0..m)
	{
		auto dragon = readln.split().to!(long[]);
		size_t send = 0;
		if (heroes[n - 1] < dragon[0])
			send = n - 1;
		else
		{
			size_t ok = n - 1;
			size_t ng = -1;
			while (ok - ng > 1)
			{
				size_t center = (ng + ok) / 2;
				if (heroes[center] >= dragon[0])
					ok = center;
				else
					ng = center;
			}
			send = ok;
		}
		res[i] = max(long(0), dragon[0] - heroes[send]) + max(long(0), dragon[1] - total + heroes[send]);
		if (send > 0)
			res[i] = min(res[i], max(long(0), dragon[0] - heroes[send - 1] + max(long(0), dragon[1] - total + heroes[send - 1])));
	}
	res.each!(a => writeln(a));
}

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

void main()
{
	int n;
	scanf("%d", &n);
	getchar();
	auto heroes = readln.split().to!(BigInt[]);
	int m;
	scanf("%d", &m);
	getchar();
	heroes.sort();
	BigInt[] res = new BigInt[m];
	BigInt total = to!BigInt(heroes.sum());
	foreach(i;0..m)
	{
		auto dragon = readln.split().to!(BigInt[]);
		size_t send = 0;
		if (heroes[n - 1] < dragon[0])
			send = n - 1;
		else
		{
			size_t ok = n - 1;
			size_t ng = -1;
			while (ok - ng > 1)
			{
				size_t center = (ng + ok) / 2;
				if (heroes[center] >= dragon[0])
					ok = center;
				else
					ng = center;
			}
			send = ok;
		}
		res[i] = max(BigInt(0), dragon[0] - heroes[send]) + max(BigInt(0), dragon[1] - total + heroes[send]);
		if (send > 0)
			res[i] = min(res[i], max(BigInt(0), dragon[0] - heroes[send - 1] + max(BigInt(0), dragon[1] - total + heroes[send - 1])));
	}
	res.each!(a => writeln(a));
}

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

void main()
{
	int n;
	scanf("%d", &n);
	getchar();
	auto heroes = readln.split().to!(ulong[]);
	int m;
	scanf("%d", &m);
	getchar();
	heroes.sort();
	foreach(_;0..m)
	{
		auto dragon = readln.split().to!(ulong[]);
		auto atack = heroes.find!((a,b) => a >= b)(dragon[0]);
		if (atack.empty)
		{
			if (dragon[1] > heroes.sum() - heroes.maxElement)
				writeln(dragon[0] - heroes.maxElement + max(0, dragon[1] - heroes.sum() + heroes.maxElement));
			else
				writeln(dragon[0] - heroes.maxElement);
		}
		else
		{
			ulong[] weak = heroes.find!((a,b) => a < b)(dragon[0]);
			ulong atacker = atack.minElement();
			if (!weak.empty)
			{
				ulong weaker = weak.maxElement();
				if (dragon[1] > heroes.sum() - weaker)
					if (dragon[1] > heroes.sum() - atacker)
						writeln(min(dragon[0] - weaker + dragon[1] - heroes.sum() + weaker, dragon[1] - heroes.sum() + atacker));
					else
						writeln(min(dragon[0] - weaker + dragon[1] - heroes.sum() + weaker, 0));
				else
					if (dragon[1] > heroes.sum() - atacker)
						writeln(min(dragon[0] - weaker, dragon[1] - heroes.sum() + atacker));
					else
						writeln(min(dragon[0] - weaker, 0));
			}
			else
			{
				if (dragon[1] > heroes.sum() - atacker)
					writeln(max(0, dragon[1] - heroes.sum() + atacker));
				else
					writeln(0);
			}
		}
	}
}

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

void main()
{
	int n;
	scanf("%d", &n);
	getchar();
	auto heroes = readln.split().to!(ulong[]);
	int m;
	scanf("%d", &m);
	getchar();
	heroes.sort();
	foreach(_;0..m)
	{
		auto dragon = readln.split().to!(ulong[]);
		auto atack = heroes.find!((a,b) => a >= b)(dragon[0]);
		if (atack.empty)
		{
			writeln(dragon[0] - heroes.maxElement() + max(0, dragon[1] - heroes.sum() + heroes.maxElement));
		}
		else
		{
			ulong[] weak = heroes.find!((a,b) => a < b)(dragon[0]);
			ulong atacker = atack.minElement();
			if (!weak.empty)
			{
				ulong weaker = weak.maxElement();
				if (dragon[1] > heroes.sum() - weaker)
					if (dragon[1] > heroes.sum() - atacker)
						writeln(min(dragon[0] - weaker + dragon[1] - heroes.sum() + weaker, dragon[1] - heroes.sum() + atacker));
					else
						writeln(min(dragon[0] - weaker + dragon[1] - heroes.sum() + weaker, 0));
				else
					if (dragon[1] > heroes.sum() - atacker)
						writeln(min(dragon[0] - weaker, dragon[1] - heroes.sum() + atacker));
					else
						writeln(min(dragon[0] - weaker, 0));
//				writeln(min(dragon[0] - weaker + max(0, dragon[1] - heroes.sum() + weaker), max(0, dragon[1] - heroes.sum() + atacker)));
			}
			else
			{
				if (dragon[1] > heroes.sum() - atacker)
					writeln(max(0, dragon[1] - heroes.sum() + atacker));
				else
					writeln(0);
			}
		}
	}
}

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

void main()
{
	int n;
	scanf("%d", &n);
	getchar();
	auto heroes = readln.split().to!(long[]);
	int m;
	scanf("%d", &m);
	getchar();
	heroes.sort();
	foreach(_;0..m)
	{
		auto dragon = readln.split().to!(long[]);
		auto atack = heroes.find!((a,b) => a >= b)(dragon[0]);
		if (atack.empty)
		{
			writeln(dragon[0] - heroes.maxElement() + max(0, dragon[1] - heroes.sum() + heroes.maxElement));
		}
		else
		{
			long[] weak = heroes.find!((a,b) => a < b)(dragon[0]);
			long atacker = atack.minElement();
			if (!weak.empty)
			{
				long weaker = weak.maxElement();
				writeln(min(dragon[0] - weaker + max(0, dragon[1] - heroes.sum() + weaker), max(0, dragon[1] - heroes.sum() + atacker)));
			}
			else
			{
					writeln(max(0, dragon[1] - heroes.sum() + atacker));
			}
		}
	}
}

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

void main()
{
	int n;
	scanf("%d", &n);
	getchar();
	auto heroes = readln.split().to!(long[]);
	int m;
	scanf("%d", &m);
	getchar();
	heroes.sort();
	foreach(_;0..m)
	{
		auto dragon = readln.split().to!(long[]);
		auto atack = heroes.find!((a,b) => a >= b)(dragon[0]);
		if (atack.empty)
		{
			writeln(dragon[0] - heroes.maxElement() + max(0, dragon[1] - heroes.sum() + heroes.maxElement));
		}
		else
		{
			long[] weak = heroes.find!((a,b) => a < b)(dragon[0]);
			long atacker = atack.minElement();
			if (!weak.empty)
			{
				long weaker = weak.maxElement();
				if (dragon[0] - weaker > atacker - dragon[0])
					writeln(max(0, dragon[1] - heroes.sum() + atacker));
				else
					writeln(dragon[0] - weaker + max(0, dragon[1] - heroes.sum() + weaker));
			}
			else
			{
					writeln(max(0, dragon[1] - heroes.sum()));
			}
		}
	}
}

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

void main()
{
	int n;
	scanf("%d", &n);
	getchar();
	auto heroes = readln.split().to!(long[]);
	int m;
	scanf("%d", &m);
	getchar();
	heroes.sort();
	foreach(_;0..m)
	{
		auto dragon = readln.split().to!(long[]);
		auto atack = heroes.find!((a,b) => a >= b)(dragon[0]);
		if (atack.empty)
		{
			writeln(dragon[0] - heroes.maxElement() + max(0, dragon[1] - heroes.sum() + heroes.maxElement));
		}
		else
		{
			long[] weak = heroes.find!((a,b) => a < b)(dragon[0]);
			long atacker = atack.minElement();
			if (!weak.empty)
			{
				long weaker = weak.maxElement();
				if (dragon[0] - weaker > atacker - dragon[0])
					writeln(max(0, dragon[1] - heroes.sum() + atacker));
				else
					writeln(dragon[0] - weaker + max(0, dragon[1] - heroes.sum() + weaker));
			}
			else
			{
					writeln(max(0, dragon[1] - heroes.sum() + atacker));
			}
		}
	}
}

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

void main()
{
	int n;
	scanf("%d", &n);
	getchar();
	auto heroes = readln.split().to!(long[]);
	int m;
	scanf("%d", &m);
	getchar();
	heroes.sort();
	foreach(_;0..m)
	{
		auto dragon = readln.split().to!(long[]);
		auto atack = heroes.find!((a,b) => a >= b)(dragon[0]);
		if (atack.empty)
		{
			writeln(dragon[0] - heroes.maxElement() + max(0, dragon[1] - heroes.sum() + heroes.maxElement));
		}
		else
		{
			long[] weak = heroes.find!((a,b) => a < b)(dragon[0]);
			long atacker = atack.minElement();
			if (!weak.empty)
			{
				long weaker = weak.maxElement();
				if (dragon[0] - weaker > atacker - dragon[0])
					writeln(atacker - dragon[0] + max(0, dragon[1] - heroes.sum() + atacker));
				else
					writeln(dragon[0] - weaker + max(0, dragon[1] - heroes.sum() + weaker));
			}
			else
			{
					writeln(atacker - dragon[0] + max(0, dragon[1] - heroes.sum() + atacker));
					debug{
						writeln(max(0, dragon[1] - heroes.sum() + atacker));
					}
			}
		}
	}
}