Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.There are $$$n_1$$$ different types of first courses Ivan can buy (the $$$i$$$-th of them costs $$$a_i$$$ coins), $$$n_2$$$ different types of second courses (the $$$i$$$-th of them costs $$$b_i$$$ coins), $$$n_3$$$ different types of drinks (the $$$i$$$-th of them costs $$$c_i$$$ coins) and $$$n_4$$$ different types of desserts (the $$$i$$$-th of them costs $$$d_i$$$ coins).Some dishes don't go well with each other. There are $$$m_1$$$ pairs of first courses and second courses that don't go well with each other, $$$m_2$$$ pairs of second courses and drinks, and $$$m_3$$$ pairs of drinks and desserts that don't go well with each other.Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!

The first line contains four integers $$$n_1$$$, $$$n_2$$$, $$$n_3$$$ and $$$n_4$$$ ($$$1 \le n_i \le 150000$$$) — the number of types of first courses, second courses, drinks and desserts, respectively. Then four lines follow. The first line contains $$$n_1$$$ integers $$$a_1, a_2, \dots, a_{n_1}$$$ ($$$1 \le a_i \le 10^8$$$), where $$$a_i$$$ is the cost of the $$$i$$$-th type of first course. Three next lines denote the costs of second courses, drinks, and desserts in the same way ($$$1 \le b_i, c_i, d_i \le 10^8$$$). The next line contains one integer $$$m_1$$$ ($$$0 \le m_1 \le 200000$$$) — the number of pairs of first and second courses that don't go well with each other. Each of the next $$$m_1$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n_1$$$; $$$1 \le y_i \le n_2$$$) denoting that the first course number $$$x_i$$$ doesn't go well with the second course number $$$y_i$$$. All these pairs are different. The block of pairs of second dishes and drinks that don't go well with each other is given in the same format. The same for pairs of drinks and desserts that don't go well with each other ($$$0 \le m_2, m_3 \le 200000$$$).

If it's impossible to choose a first course, a second course, a drink, and a dessert so that they go well with each other, print $$$-1$$$. Otherwise, print one integer — the minimum total cost of the dinner.

NoteThe best option in the first example is to take the first course $$$2$$$, the second course $$$1$$$, the drink $$$2$$$ and the dessert $$$1$$$.In the second example, the only pair of the first course and the second course is bad, so it's impossible to have dinner.

// cheese-cracker [2022-01-25]

const long INF = 1000_000_000_000;

void main(){
    auto n = scanArray!int;

    auto arr = new tup[][4];
    arr[0] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[1] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[2] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[3] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;

    alias pr = Tuple!(int, int);
    for(int i = 0; i < 3; ++i){
        bool[pr] hmap;

        // Scan into hmap
        int m = scan!int;
        for(int j = 0; j < m; ++j){
            hmap[pr(scan!int, scan!int)] = 1;
        }

        // Sort and Update Prev Round
        int fst = i;
        int snd = fst+1;
        arr[fst].sort;
        foreach(ref el; arr[snd]){
            int x = el[1];
            bool f = 0;
            for(int k = 0; k < n[fst] && arr[fst][k][0] < INF; ++k){
                int y = arr[fst][k][1];
                if(! (pr(y, x) in hmap) ){
                    el[0] += arr[fst][k][0];
                    f = 1;
                    break;
                }
            }
            if(!f){ el[0] = INF; }
        }
        hmap.clear;
    }
    arr[3].sort;
    writeln((arr[3][0][0] < INF) ? arr[3][0][0] : -1);
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, int);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

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

immutable int infinity = int.max / 2;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto n = s.splitter.map !(to !(int)).array;
		int [] [] a;
		foreach (i; 0..4)
		{
			a ~= readln.splitter.map !(to !(int)).array;
		}
		foreach (i; 0..3)
		{
			auto t = redBlackTree !(true) (a[i]);
			t.insert (infinity);
			auto g = new int [] [n[i + 1]];
			auto m = readln.strip.to !(int);
			foreach (j; 0..m)
			{
				auto v = readln.split;
				g[v[1].to !(int) - 1] ~= v[0].to !(int) - 1;
			}
			foreach (k; 0..n[i + 1])
			{
				foreach (c; g[k])
				{
					t.removeKey (a[i][c]);
				}
				auto value = t.front;
				foreach (c; g[k])
				{
					t.insert (a[i][c]);
				}
				a[i + 1][k] = (value < infinity) ?
				    a[i + 1][k] + value : infinity;
			}
		}
		auto res = a.back.minElement;
		writeln (res < infinity ? res : -1);
	}
}

// cheese-cracker [2022-01-25]

const long INF = 1000_000_000_000_000;

void main(){
    auto n = scanArray!int;

    auto arr = new tup[][4];
    arr[0] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[1] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[2] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[3] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;

    alias pr = Tuple!(int, int);
    for(int i = 0; i < 3; ++i){
        bool[pr] hmap;

        // Scan into hmap
        int m = scan!int;
        for(int j = 0; j < m; ++j){
            hmap[pr(scan!int, scan!int)] = 1;
        }

        // Sort and Update Prev Round
        int fst = i;
        int snd = fst+1;
        arr[fst].sort;
        foreach(ref el; arr[snd]){
            int x = el[1];
            bool f = 0;
            for(int k = 0; k < n[fst] && arr[fst][k][0] < INF; ++k){
                int y = arr[fst][k][1];
                if(! (pr(x, y) in hmap) ){
                    el[0] += arr[fst][k][0];
                    f = 1;
                    break;
                }
            }
            if(!f){ el[0] = INF; }
        }
    }
    arr[3].sort;
    writeln((arr[3][0][0] < INF) ? arr[3][0][0] : -1);
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, int);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

// cheese-cracker [2022-01-25]

const long INF = 1_000_000_000;

void main(){
    auto n = scanArray!int;

    auto arr = new tup[][4];
    arr[0] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[1] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[2] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[3] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;

    alias pr = Tuple!(int, int);
    for(int i = 0; i < 3; ++i){
        auto hmap = redBlackTree!(pr);

        // Scan into hmap
        int m = scan!int;
        for(int j = 0; j < m; ++j){
            hmap.insert(pr(scan!int, scan!int));
        }

        // Sort and Update Prev Round
        int fst = i;
        int snd = fst+1;
        arr[fst].sort;
        foreach(ref el; arr[snd]){
            int x = el[1];
            bool f = 0;
            for(int k = 0; k < n[fst] && arr[fst][k][0] < INF; ++k){
                int y = arr[fst][k][1];
                if(! (pr(x, y) in hmap) ){
                    el[0] += arr[fst][k][0];
                    f = 1;
                    break;
                }
            }
            if(!f){ el[0] = INF; }
        }
    }
    arr[3].sort;
    writeln((arr[3][0][0] < INF) ? arr[3][0][0] : -1);
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, int);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

// cheese-cracker [2022-01-25]

const long INF = 1_000_000_000;

void main(){
    auto n = scanArray!int;

    auto arr = new tup[][4];
    arr[0] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[1] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[2] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[3] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;

    alias pr = Tuple!(int, int);
    for(int i = 0; i < 3; ++i){
        bool[pr] hmap;

        // Scan into hmap
        int m = scan!int;
        for(int j = 0; j < m; ++j){
            hmap[pr(scan!int, scan!int)] = 1;
        }

        // Sort and Update Prev Round
        int fst = i;
        int snd = fst+1;
        arr[fst].sort;
        foreach(ref el; arr[snd]){
            int x = el[1];
            bool f = 0;
            for(int k = 0; k < n[fst] && arr[fst][k][0] < INF; ++k){
                int y = arr[fst][k][1];
                if(! (pr(x, y) in hmap) ){
                    el[0] += arr[fst][k][0];
                    f = 1;
                    break;
                }
            }
            if(!f){ el[0] = INF; }
        }
    }
    arr[3].sort;
    writeln((arr[3][0][0] < INF) ? arr[3][0][0] : -1);
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, int);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

// cheese-cracker [2022-01-25]

const long INF = 1_000_000_000;

void main(){
    auto n = scanArray!int;

    auto arr = new tup[][4];
    arr[0] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[1] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[2] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;
    arr[3] = scanArray.enumerate.map!(a => tup(a[1], a[0].to!int + 1)).array;

    alias pr = Tuple!(int, int);
    for(int i = 0; i < 3; ++i){
        bool[pr] hmap;

        // Scan into hmap
        int m = scan!int;
        for(int j = 0; j < m; ++j){
            hmap[pr(scan!int, scan!int)] = 1;
        }

        // Sort and Update Prev Round
        int fst = i;
        int snd = fst+1;
        arr[fst].sort;
        foreach(ref el; arr[snd]){
            int x = el[1];
            bool f = 0;
            for(int k = 0; k < n[0] && arr[fst][k][0] < INF; ++k){
                int y = arr[fst][k][1];
                if(! (pr(x, y) in hmap) ){
                    el[0] += arr[fst][k][0];
                    f = 1;
                    break;
                }
            }
            if(!f){ el[0] = INF; }
        }
    }
    arr[3].sort;
    writeln((arr[3][0][0] < INF) ? arr[3][0][0] : -1);
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, int);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

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

immutable int infinity = int.max / 2;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto n = s.splitter.map !(to !(int)).array;
		int [] [] a;
		foreach (i; 0..4)
		{
			a ~= readln.splitter.map !(to !(int)).array;
		}
		foreach (i; 0..3)
		{
			auto t = redBlackTree !(true) (a[i]);
			t.insert (infinity);
			auto g = new int [] [n[i + 1]];
			auto m = readln.strip.to !(int);
			foreach (j; 0..m)
			{
				auto v = readln.splitter.map !(to !(int)).array;
				v[] -= 1;
				g[v[1]] ~= v[0];
			}
			foreach (k; 0..n[i + 1])
			{
				foreach (c; g[k])
				{
					t.removeKey (a[i][c]);
				}
				auto value = t.front;
				foreach (c; g[k])
				{
					t.insert (a[i][c]);
				}
				a[i + 1][k] = (value < infinity) ?
				    a[i + 1][k] + value : infinity;
			}
		}
		auto res = a.back.maxElement;
		writeln (res < infinity ? res : -1);
	}
}


An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.  The second line contains n integers pi (1 ≤ pi ≤ n, pi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.

Print a single integer — the minimum number of actions needed to sort the railway cars.

NoteIn the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto p = readln.split.map !(to !(int)).array;
		p[] -= 1;
		auto q = new int [n];
		foreach (i, c; p)
		{
			q[c] = i;
		}
		int cur = 1;
		int res = cur;
		foreach (i; 1..n)
		{
			if (q[i] > q[i - 1])
			{
				cur++;
				res = max (res, cur);
			}
			else
			{
				cur = 1;
			}
		}
		writeln (n - res);
	}
}


Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows.  The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 10^9$$$) which location must be found.

For each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \ge 1$$$) separated by spaces — the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long k;
    readf!" %d "(k);
    long x, y;
    while ((x + 1) * (x + 1) < k)
      x++;
    y = k - x * x - 1;
    if (y <= x) {
      writefln("%d %d", y + 1, x + 1);
    } else {
      long delta = y - x;
      y = x;
      x -= delta;
      writefln("%d %d", y + 1, x + 1);
    }
  }
}

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

void theCode(){
    ll k = scan;
    k -= 1;
    ll rt = to!ll(floor(sqrt(to!double(k))));
    if((rt + 1) *(rt + 1) <= k){
        rt += 1;
    }
    ll lef = k - rt*rt;
    ll d = min(rt, lef);
    ll b = max(0, lef - rt);
    ll x = (rt+1) - b;
    ll y = d + 1;
    writeln(y, " ", x);
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) theCode();
}

/*********  That's All Folks!  *********/
import std.stdio, std.random, std.functional, std.container, std.algorithm;
import std.numeric, std.range, std.typecons, std.string, std.math, std.conv;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");


AquaMoon has two binary sequences $$$a$$$ and $$$b$$$, which contain only $$$0$$$ and $$$1$$$. AquaMoon can perform the following two operations any number of times ($$$a_1$$$ is the first element of $$$a$$$, $$$a_2$$$ is the second element of $$$a$$$, and so on): Operation 1: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\operatorname{min}(a_1,a_2)$$$, and remove the first element of $$$a$$$. Operation 2: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\operatorname{max}(a_1,a_2)$$$, and remove the first element of $$$a$$$.Note that after a removal of the first element of $$$a$$$, the former $$$a_2$$$ becomes the first element of $$$a$$$, the former $$$a_3$$$ becomes the second element of $$$a$$$ and so on, and the length of $$$a$$$ reduces by one.Determine if AquaMoon can make $$$a$$$ equal to $$$b$$$ by using these operations.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2\,000$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 50$$$, $$$m \leq n$$$) — the lengths of $$$a$$$ and $$$b$$$ respectively. The second line of each test case contains a string $$$a$$$ of length $$$n$$$, consisting only $$$0$$$ and $$$1$$$. The third line of each test case contains a string $$$b$$$ of length $$$m$$$, consisting only $$$0$$$ and $$$1$$$.

For each test case, output "YES" if AquaMoon can change $$$a$$$ to $$$b$$$ by using these options; otherwise, output "NO". You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).

NoteIn the first test case, you can use Operation 2 four times to make $$$a$$$ equals to $$$b$$$.In the second test case, you can use Operation 1 four times to make $$$a$$$ equals to $$$b$$$.In the third test case, it can be proved that no matter how we use the operations, it is impossible to make $$$a$$$ equal to $$$b$$$.In the fourth test case, it can be proved that no matter how we use the operations, it is impossible to make $$$a$$$ equal to $$$b$$$.In the fifth test case, you can use Operation 2 three times to make $$$a$$$ become $$$10101$$$, so the first element of $$$a$$$ equals to the first element of $$$b$$$, but it can be proved that no matter how to operate, the second to the fifth elements of $$$a$$$ can't be the same as $$$b$$$.

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 n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto s = readln.strip;
		auto t = readln.strip;
		auto b = n - m + 1;
		auto r = s[0..b];
		auto can = (t[0] == '0') ?
		    r.minElement == '0' :
		    r.maxElement == '1';
		writeln ((can && s[b..$] == t[1..$]) ? "YES" : "NO");
	}
}

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

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

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

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

enum INF = 10L^^18;

int N, M;
string A, B;

bool solve() {
  if (A[N - M + 1 .. N] != B[1 .. M]) {
    return false;
  }
  bool[2] has;
  foreach (i; 0 .. N - M + 1) {
    has[A[i] - '0'] = true;
  }
  if (has[0] && B[0] == '0') return true;
  if (has[1] && B[0] == '1') return true;
  return false;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        N = readInt;
        M = readInt;
        A = readToken;
        B = readToken;

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


You are a programmer and you have a New Year Tree (not the traditional fur tree, though) — a tree of four vertices: one vertex of degree three (has number 1), connected with three leaves (their numbers are from 2 to 4).On the New Year, programmers usually have fun. You decided to have fun as well by adding vertices to the tree. One adding operation looks as follows:  First we choose some leaf of the tree with number v.  Let's mark the number of vertices on the tree at this moment by variable n, then two vertexes are added to the tree, their numbers are n + 1 and n + 2, also you get new edges, one between vertices v and n + 1 and one between vertices v and n + 2. Your task is not just to model the process of adding vertices to the tree, but after each adding operation print the diameter of the current tree. Come on, let's solve the New Year problem!

The first line contains integer q (1 ≤ q ≤ 5·105) — the number of operations. Each of the next q lines contains integer vi (1 ≤ vi ≤ n) — the operation of adding leaves to vertex vi. Variable n represents the number of vertices in the current tree. It is guaranteed that all given operations are correct.

Print q integers — the diameter of the current tree after each operation.

import std.stdio, std.algorithm, core.bitop;

immutable N = 10^^6 + 22, LOGN = 22;

class Tree {
    int n;
    int[] dep;
    int[][] tab;

    this() {
        dep = new int[](N);
        tab = new int[][](LOGN, N);

        n = 1;

        dep[] = -1;
        dep[0] = 0;

        foreach(i; 0..LOGN) {
            tab[i][] = -1;
        }
    }

    int add(int p) {
        dep[n] = dep[p]+1;
        tab[0][n] = p;
        for (int i = 0; (tab[i+1][n] = tab[i][tab[i][n]]) != -1; ++i) {}
        return n++;
    }

    int level(int u, int k) {
        for(int i = 0; 1<<i <= k; ++i) {
            if (1<<i & k) u = tab[i][u];
        }
        return u;
    }

    int lca(int u, int v) {
        if (dep[u] > dep[v]) swap(u, v);
        v = level(v, dep[v] - dep[u]);
        if (u == v) return u;
        for (int i = bsr(dep[u]); i >= 0; --i) {
            if (tab[i][u] != tab[i][v]) {
                u = tab[i][u], v = tab[i][v];
            }
        }
        return tab[0][u];
    }

    int dist(int u, int v) {
        return dep[u] + dep[v] - 2*dep[lca(u, v)];
    }
}

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

    Tree t = new Tree();
    foreach(i; 0..3) {
        t.add(0);
    }

    int d = 2, du = 1, dv = 2;
    foreach(i; 0..q) {
        int v;
        readf(" %d", &v);
        --v;

        t.add(v);
        int w = t.add(v);

        if (t.dist(w, du) > d) {
            dv = w;
            d = t.dist(w, du);
        }
        if (t.dist(w, dv) > d) {
            du = w;
            d = t.dist(w, dv);
        }

        writeln(d);
    }
}


Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked $$$p^{k_i}$$$ problems from $$$i$$$-th category ($$$p$$$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.Formally, given $$$n$$$ numbers $$$p^{k_i}$$$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $$$10^{9}+7$$$.

Input consists of multiple test cases. The first line contains one integer $$$t$$$ $$$(1 \leq t \leq 10^5)$$$ — the number of test cases. Each test case is described as follows: The first line contains two integers $$$n$$$ and $$$p$$$ $$$(1 \leq n, p \leq 10^6)$$$. The second line contains $$$n$$$ integers $$$k_i$$$ $$$(0 \leq k_i \leq 10^6)$$$. The sum of $$$n$$$ over all test cases doesn't exceed $$$10^6$$$.

Output one integer — the reminder of division the answer by $$$1\,000\,000\,007$$$.

NoteYou have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $$$2$$$, but there is also a distribution where the difference is $$$10^9 + 8$$$, then the answer is $$$2$$$, not $$$1$$$.In the first test case of the example, there're the following numbers: $$$4$$$, $$$8$$$, $$$16$$$, $$$16$$$, and $$$8$$$. We can divide them into such two sets: $$${4, 8, 16}$$$ and $$${8, 16}$$$. Then the difference between the sums of numbers in sets would be $$$4$$$.

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

immutable int mod = 1_000_000_007;

int powMod (int a, int p)
{
	int res = 1;
	for ( ; p; p >>= 1)
	{
		if (p & 1)
		{
			res = (res * 1L * a) % mod;
		}
		a = (a * 1L * a) % mod;
	}
	return res;
}

void main ()
{
	auto tests = readln.strip.to !(int);
multitest_loop:
	foreach (test; 0..tests)
	{
		int n, p;
		readf !(" %s %s") (n, p);
		readln;
		auto k = readln.splitter.map !(to !(int)).array;
		if (p == 1)
		{
			writeln (n & 1);
			continue;
		}
		sort (k);

		int prev = k.back;
		long balance = 0;
		int res = 0;
		foreach_reverse (c; k)
		{
			while (prev > c && balance != 0 && balance < mod)
			{
				prev -= 1;
				balance = min (balance * p, mod);
			}
			prev = c;
			if (balance == 0)
			{
				balance += 1;
				res = (res + powMod (p, prev)) % mod;
			}
			else
			{
				balance -= 1;
				res = (res + mod - powMod (p, prev)) % mod;
			}
		}
		writeln (res);
	}
}


Pak Chanek, a renowned scholar, invented a card puzzle using his knowledge. In the puzzle, you are given a board with $$$n$$$ rows and $$$m$$$ columns. Let $$$(r, c)$$$ represent the cell in the $$$r$$$-th row and the $$$c$$$-th column.Initially, there are $$$k$$$ cards stacked in cell $$$(1, 1)$$$. Each card has an integer from $$$1$$$ to $$$k$$$ written on it. More specifically, the $$$i$$$-th card from the top of the stack in cell $$$(1, 1)$$$ has the number $$$a_i$$$ written on it. It is known that no two cards have the same number written on them. In other words, the numbers written on the cards are a permutation of integers from $$$1$$$ to $$$k$$$. All other cells are empty.You need to move the $$$k$$$ cards to cell $$$(n, m)$$$ to create another stack of cards. Let $$$b_i$$$ be the number written on the $$$i$$$-th card from the top of the stack in cell $$$(n, m)$$$. You should create the stack in cell $$$(n, m)$$$ in such a way so that $$$b_i = i$$$ for all $$$1 \leq i \leq k$$$.In one move, you can remove the top card from a cell and place it onto an adjacent cell (a cell that shares a common side). If the target cell already contains one or more cards, you place your card on the top of the stack. You must do each operation while satisfying the following restrictions:   Each cell other than $$$(1,1)$$$ and $$$(n,m)$$$ must not have more than one card on it.  You cannot move a card onto cell $$$(1,1)$$$.  You cannot move a card from cell $$$(n,m)$$$. Given the values of $$$n$$$, $$$m$$$, $$$k$$$ and the array $$$a$$$, determine if the puzzle is solvable.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$3 \leq n, m \leq 10^6$$$, $$$nm \leq 10^6$$$, $$$1 \leq k \leq 10^5$$$) — the size of the board and the number of cards. The second line of the test case contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ — the array $$$a$$$, representing the numbers written on the cards. The values of $$$a$$$ are a permutation of integers from $$$1$$$ to $$$k$$$. It is guaranteed that the sum of $$$nm$$$ and $$$k$$$ over all test cases do not exceed $$$10^6$$$ and $$$10^5$$$ respectively.

For each test case, output "YA" (without quotes) if it is possible and "TIDAK" (without quotes) otherwise, which mean yes and no in Indonesian respectively. You can output "YA" and "TIDAK" in any case (for example, strings "tiDAk", "tidak", and "Tidak" will be recognised as a negative response).

NoteIn the first test case, the following is one way the puzzle can be done:   Move the card with $$$3$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(1, 2)$$$, then cell $$$(1, 3)$$$.  Move the card with $$$6$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(2, 1)$$$, then cell $$$(3, 1)$$$, then cell $$$(3, 2)$$$, then cell $$$(3, 3)$$$.  Move the card with $$$4$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(1, 2)$$$.  Move the card with $$$1$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(2, 1)$$$, then cell $$$(2, 2)$$$, then cell $$$(2, 3)$$$.  Move the card with $$$2$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(2, 1)$$$, then cell $$$(2, 2)$$$.  Move the card with $$$5$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(2, 1)$$$, then cell $$$(3, 1)$$$, then cell $$$(3, 2)$$$, then cell $$$(3, 3)$$$.  Move the card with $$$2$$$ written on it from cell $$$(2, 2)$$$ to cell $$$(2, 1)$$$.  Move the card with $$$4$$$ written on it from cell $$$(1, 2)$$$ to cell $$$(2, 2)$$$, then cell $$$(3, 2)$$$, then cell $$$(3, 3)$$$.  Move the card with $$$3$$$ written on it from cell $$$(1, 3)$$$ to cell $$$(1, 2)$$$, then cell $$$(2, 2)$$$, then cell $$$(3, 2)$$$, then cell $$$(3, 3)$$$.  Move the card with $$$2$$$ written on it from cell $$$(2, 1)$$$ to cell $$$(3, 1)$$$, then cell $$$(3, 2)$$$, then cell $$$(3, 3)$$$.  Move the card with $$$1$$$ written on it from cell $$$(2, 3)$$$ to cell $$$(3, 3)$$$. An animated illustration regarding the process mentioned above is as follows:

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

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

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 solve() {
    int n,m,k;
    readf!" %d %d %d "(n,m,k);
    auto a = readarray!int;
    bool flag = true;
    int capacity;
    int maxR = k;
    bool[int] memory;
    foreach(e; a) {
        if (e == maxR)
            maxR--;
        else {
            memory[e] = true;
            capacity++;
        }
        while (maxR in memory) {
            memory.remove(maxR);
            capacity--;
            maxR--;
        }
        if (capacity > n*m - 4) {
            flag = false;
            break;
        }
    }
    if (flag)
        writeln("YA");
    else
        writeln("TIDAK");
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n, m, k;
    readf!" %d %d %d "(n, m, k);
    auto a = readln.splitter.map!(to!long).map!(x => k + 1 - x).array;
//    writeln(a);
    long maxsize = n * m - 3;
    auto h = redBlackTree!("a<b", true, long)();
    long stored = 0;
    bool good = true;
    foreach (x ; a) {
      while (!h.empty && h.front == stored + 1) {
        stored = h.front;
        h.removeFront;
      }
      if (h.length >= maxsize) {
        good = false;
        break;
      }
      h.insert(x);
    }
//    writeln(h);
    while (!h.empty && h.front == stored + 1) {
      stored = h.front;
      h.removeFront;
    }
    if (!h.empty)
      good = false;
    writeln(good ? "YA" : "TIDAK");
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m, k;
		readf !(" %s %s %s") (n, m, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		a[] -= 1;
		int limit = n * m - 4;
		bool ok = true;
		int num = 0;
		int last = k - 1;
		auto vis = new bool [k];
		foreach (i, ref cur; a)
		{
			vis[cur] = true;
			num += 1;
			while (last >= 0 && vis[last])
			{
				last -= 1;
				num -= 1;
			}
			ok &= (num <= limit);
		}
		writeln (ok ? "YA" : "TIDAK");
	}
}

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

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

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 solve() {
    int n,m,k;
    readf!" %d %d %d "(n,m,k);
    auto a = readarray!int;
    bool flag = true;
    int capacity;
    int maxR = k;
    bool[int] memory;
    foreach(e; a) {
        if (e == maxR)
            maxR--;
        else {
            memory[e] = true;
            capacity++;
        }
        while (maxR in memory) {
            memory.remove(maxR);
            capacity--;
            maxR--;
        }
        if (capacity > (n-1)*(m-1)) {
            flag = false;
            break;
        }
    }
    if (flag)
        writeln("YA");
    else
        writeln("TIDAK");
}

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

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

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

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 solve() {
    int n,m,k;
    readf!" %d %d %d "(n,m,k);
    auto a = readarray!int;
    bool flag = true;
    int capacity;
    int maxR = k;
    bool[int] memory;
    foreach(e; a) {
        if (e == maxR)
            maxR--;
        else {
            memory[e] = true;
            capacity++;
        }
        while (maxR in memory) {
            memory.remove(e);
            capacity--;
            maxR--;
        }
        if (capacity > (n-1)*(m-1)) {
            flag = false;
            break;
        }
    }
    if (flag)
        writeln("YA");
    else
        writeln("TIDAK");
}

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


Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.Vova has already wrote k tests and got marks a1, ..., ak. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.

The first line contains 5 space-separated integers: n, k, p, x and y (1 ≤ n ≤ 999, n is odd, 0 ≤ k < n, 1 ≤ p ≤ 1000, n ≤ x ≤ n·p, 1 ≤ y ≤ p). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games. The second line contains k space-separated integers: a1, ..., ak (1 ≤ ai ≤ p) — the marks that Vova got for the tests he has already written.

If Vova cannot achieve the desired result, print "-1". Otherwise, print n - k space-separated integers — the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.

NoteThe median of sequence a1, ..., an where n is odd (in this problem n is always odd) is the element staying on (n + 1) / 2 position in the sorted list of ai.In the first sample the sum of marks equals 3 + 5 + 4 + 4 + 1 = 17, what doesn't exceed 18, that means that Vova won't be disturbed by his classmates. And the median point of the sequence {1, 3, 4, 4, 5} equals to 4, that isn't less than 4, so his mom lets him play computer games.Please note that you do not have to maximize the sum of marks or the median mark. Any of the answers: "4 2", "2 4", "5 1", "1 5", "4 1", "1 4" for the first test is correct.In the second sample Vova got three '5' marks, so even if he gets two '1' marks, the sum of marks will be 17, that is more than the required value of 16. So, the answer to this test is "-1".

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

void main() {

	int n, k, p, x, y;

	readf(" %s %s %s %s %s\n", &n, &k, &p, &x, &y);

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

	foreach (i; 0 .. n - k) {
		arr ~= y;
	}

	int i;
	while ((k + i < arr.length)) {
		if ((arr[k + i] > 1)) {
			--arr[k + i];
			if (arr.filter!(a => a >= y).array.length <= n / 2) {
				++arr[k + i];
				goto x;
			}
		}
		else {
			x:
			++i;
		}
	}

	auto brr = arr.dup;

	brr.sort!"a < b";

	if (arr.reduce!"a + b" <= x && brr[(n + 1) / 2 - 1] >= y) {
		writefln("%(%s %)", arr[k .. $]);
	}
	else {
		writeln(-1);
	}
}

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

void main() {

	int n, k, p, x, y;

	readf(" %s %s %s %s %s\n", &n, &k, &p, &x, &y);

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

	foreach (i; 0 .. n - k) {
		arr ~= y;
	}

	int i;
	while ((k + i < arr.length) && (arr.filter!(a => a >= y).array.length > n / 2)) {
		if ((arr[k + i] > 1)) {
			if (arr.filter!(a => a >= y).array.length <= n / 2) {
				goto x;
			}
			--arr[k + i];
		}
		else {
			x:
			++i;
		}
	}

	auto brr = arr.dup;

	brr.sort!"a < b";

	if (arr.reduce!"a + b" <= x && brr[(n + 1) / 2 - 1] >= y) {
		writefln("%(%s %)", arr[k .. $]);
	}
	else {
		writeln(-1);
	}
}

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

void main() {

	int n, k, p, x, y;

	readf(" %s %s %s %s %s\n", &n, &k, &p, &x, &y);

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

	foreach (i; 0 .. n - k) {
		arr ~= y;
	}

	int i;
	while ((k + i < arr.length) && (arr.filter!(a => a >= y).array.length > n / 2)) {
		if ((arr[k + i] > 1)) {
			--arr[k + i];
			if (arr.filter!(a => a >= y).array.length <= n / 2) {
				++arr[k + i];
				goto x;
			}
		}
		else {
			x:
			++i;
		}
	}

	auto brr = arr.dup;

	brr.sort!"a < b";

	if (arr.reduce!"a + b" <= x && brr[(n + 1) / 2 - 1] >= y) {
		writefln("%(%s %)", arr[k .. $]);
	}
	else {
		writeln(-1);
		writeln(arr);
	}
}

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

void main() {

	int n, k, p, x, y;

	readf(" %s %s %s %s %s\n", &n, &k, &p, &x, &y);

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

	foreach (i; 0 .. n - k) {
		arr ~= y;
	}

	int i;
	while ((k + i < arr.length) && (arr.filter!(a => a >= y).array.length > n / 2)) {
		if (arr[k + i] > 1) {
			--arr[k + i];
		}
		else {
			++i;
		}
	}

	++arr[$ - 1];

	auto brr = arr.dup;

	brr.sort!"a < b";

	if (arr.reduce!"a + b" <= x && brr[(n + 1) / 2 - 1] >= y) {
		writefln("%(%s %)", arr[k .. $]);
	}
	else {
		writeln(-1);
	}
}


A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe xi. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg.The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.

The first line of input contains three space-separated integers, a, b and c (1 ≤ b < a < c ≤ 109), denoting the positions of Oleg, the first security guard and the second security guard, respectively. The next line of input contains a single integer n (1 ≤ n ≤ 105), denoting the number of banknotes. The next line of input contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 109), denoting that the i-th banknote is located in the xi-th safe. Note that xi are not guaranteed to be distinct.

Output a single integer: the maximum number of banknotes Oleg can take.

NoteIn the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.For the second sample, Oleg can't take any banknotes without bumping into any of the security guards.

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

}
void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int a,b,c;
loop:while(read(a,b,c))
	{
		int n;
		read(n);
		int ans;
		foreach(i;0..n)
		{
			int x;
			input(x);
			if(x>b && x<c)ans++;
		}
		writeln(ans);
	}
}

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

}
void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int a,b,c;
loop:while(read(a,b,c))
	{
		int n;
		read(n);
		auto ar=arread!int;
		sort(ar);
		debug writeln(ar);
		debug writeln(lowb(ar,c),' ',upb(ar,b));
		writeln(max(lowb(ar,c)*1L-upb(ar,b)*1L,0));
	}
}

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 A = readInt();
      const B = readInt();
      const C = readInt();
      const N = readInt();
      auto X = new int[N];
      foreach (i; 0 .. N) {
        X[i] = readInt();
      }

      int ans;
      foreach (i; 0 .. N) {
        if (B < X[i] && X[i] < C) {
          ++ans;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

}
void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int a,b,c;
loop:while(read(a,b,c))
	{
		int n;
		read(n);
		auto ar=arread!int;
		sort(ar);
		debug writeln(lowb(ar,c),' ',upb(ar,b));
		writeln(max(lowb(ar,c)*1L-upb(ar,b)*1L,0));
	}
}


You are playing a game called Slime Escape. The game takes place on a number line. Initially, there are $$$n$$$ slimes. For all positive integers $$$i$$$ where $$$1 \le i \le n$$$, the $$$i$$$-th slime is located at position $$$i$$$ and has health $$$a_i$$$. You are controlling the slime at position $$$k$$$. There are two escapes located at positions $$$0$$$ and $$$n+1$$$. Your goal is to reach any one of the two escapes by performing any number of game moves.In one game move, you move your slime to the left or right by one position. However, if there is another slime in the new position, you must absorb it. When absorbing a slime, the health of your slime would be increased by the health of the absorbed slime, then the absorbed slime would be removed from the game.Note that some slimes might have negative health, so your health would decrease when absorbing such slimes. You lose the game immediately if your slime has negative health at any moment during the game.Can you reach one of two escapes by performing any number of game moves, without ever losing the game?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 20\,000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two positive integers $$$n$$$, $$$k$$$ ($$$3 \leq n \leq 200\,000$$$, $$$1 \leq k \leq n$$$) — the number of slimes and the position of your slime. The second line of each test case contains $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the health of the slimes. It is guaranteed that health of your slime is non-negative ($$$a_k \geq 0$$$), and all other slimes have non-zero health ($$$a_i \ne 0$$$ for $$$i \ne k$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$200\,000$$$.

For each test case, print "YES" (without quotes) if you can escape without losing, and "NO" (without quotes) otherwise.

NoteIn the first test case, you control the slime at position $$$4$$$ with health $$$6$$$. One way to escape is to absorb the slimes at positions $$$5$$$, $$$6$$$, and $$$7$$$. Your slime escapes with $$$0$$$ health at position $$$8$$$.In the second test case, you control the slime with $$$232$$$ health at position $$$1$$$. Since your slime is already located next to the escape at position $$$0$$$, you can move to it without absorbing any slime.In the third test case, it can be shown that your slime would always have a negative health before reaching any one of two escapes.In the fourth test case, you control the slime at position $$$4$$$ with health $$$6$$$. The following describes a possible sequence of moves to win:  Absorb the slimes at positions $$$5$$$, $$$6$$$, and $$$7$$$: your health becomes $$$4$$$ after absorbing the slime with health $$$-2$$$; becomes $$$1$$$ after absorbing the slime with health $$$-3$$$; and becomes $$$7$$$ after absorbing the slime with health $$$6$$$.  Absorb the slimes at positions $$$3$$$, and $$$2$$$: your health becomes $$$7-7+10=10$$$.  Absorb the slime at position $$$8$$$: your health becomes $$$10-10=0$$$.  Use the escape at position $$$9$$$. Since your slime has maintained non-negative health at all times, you have won.

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void solve() {
    int N, K; scanf("%d %d\n", &N, &K);
    long[] A = readln.chomp.split(" ").map!(to!long).array;
    K--;

    bool f(int l, int r, long h, int d) {
        if (l == 0 || r == N-1) return true;
        if (d == 1) {
            // move to the right
            long ch = h;
            long mh = h;
            int mhi = r;
            for (int i = r+1; ; i++) {
                ch += A[i];
                if (mh <= ch) {
                    mh = ch;
                    mhi = i;
                }
                if (ch < 0) break;
                if (i == N-1) return true;
            }
            long nh = mh;
            int nr = mhi;
            if (r == nr) return false;
            return f(l, nr, nh, d * (-1));
        } else {
            // move to the left
            long ch = h;
            long mh = h;
            int mhi = l;
            for (int i = l-1; ; i--) {
                ch += A[i];
                if (mh <= ch) {
                    mh = ch;
                    mhi = i;
                }
                if (ch < 0) break;
                if (i == 0) return true;
            }
            long nh = mh;
            int nl = mhi;
            if (l == nl) return false;
            return f(nl, r, nh, d * (-1));
        }
    }
    writeln( f(K, K, A[K], 1) || f(K, K, A[K], -1) ? "YES" : "NO" );
}

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


Welcome to Rockport City!It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet $$$a$$$ dollars and Ronnie has bet $$$b$$$ dollars. But the fans seem to be disappointed. The excitement of the fans is given by $$$gcd(a,b)$$$, where $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. To make the race more exciting, you can perform two types of operations:  Increase both $$$a$$$ and $$$b$$$ by $$$1$$$.  Decrease both $$$a$$$ and $$$b$$$ by $$$1$$$. This operation can only be performed if both $$$a$$$ and $$$b$$$ are greater than $$$0$$$. In one move, you can perform any one of these operations. You can perform arbitrary (possibly zero) number of moves. Determine the maximum excitement the fans can get and the minimum number of moves required to achieve it.Note that $$$gcd(x,0)=x$$$ for any $$$x \ge 0$$$.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 5\cdot 10^3$$$) — the number of test cases. The first and the only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0\leq a, b\leq 10^{18}$$$).

For each test case, print a single line containing two integers.  If the fans can get infinite excitement, print 0 0. Otherwise, the first integer must be the maximum excitement the fans can get, and the second integer must be the minimum number of moves required to achieve that excitement.

NoteFor the first test case, you can apply the first operation $$$1$$$ time to get $$$a=9$$$ and $$$b=6$$$. It can be shown that $$$3$$$ is the maximum excitement possible.For the second test case, no matter how many operations you apply, the fans will always have an excitement equal to $$$1$$$. Since the initial excitement is also $$$1$$$, you don't need to apply any operation.For the third case, the fans can get infinite excitement by applying the first operation an infinite amount of times.For the fourth test case, you can apply the second operation $$$3$$$ times to get $$$a=0$$$ and $$$b=6$$$. Since, $$$gcd(0,6)=6$$$, the fans will get an excitement of $$$6$$$.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		if (a == b)
		{
			ans[ti] = [0, 0];
			continue;
		}
		if (a > b)
			swap(a, b);
		auto d = b - a;
		auto rem = b % d;
		ans[ti] = [d, min((d-rem) % d, rem)];
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1]);
	stdout.flush;
	debug readln;
}

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    long a, b;
    readf!"%s %s\n"(a, b);
    if (a == b) {
      "0 0".writeln;
    }
    else {
      long d = abs(a - b);
      long g = min(a % d, d - (a % d));
      writefln!"%s %s"(d, g);
    }
  }

} // main

// Vicfred
// https://codeforces.com/contest/1543/problem/A
// math
import std.algorithm;
import std.stdio;

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

while(t--) {
    long a, b;
    readf("%s %s\n", &a, &b);
    if(a == b) {
        "0 0".writeln;
        continue;
    }
    if(a > b) {
        swap(a, b);
    }
    writefln("%s %s", b - a, min(a % (b - a), b - a - a % (b - a)));
}
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long a, b;
    readf!" %d %d "(a, b);
    long g = gcd(a, b);
//    writeln(g);
    if (b < a) {
      long tmp = b;
      b = a;
      a = tmp;
    }
//    writefln("a=%d b=%d", a, b);
    long d = b - a;
//    writefln("d=%d", d);
    if (a == b) {
      writeln("0 0");
      continue;
    }
    long ans1 = abs(a - a / d * d);
    long ans2 = abs(a - (a + d - 1) / d * d);
    long ans3 = a;
    writefln("%d %d", d, min(ans1, ans2, ans3));
  }
}

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

void theCode(){
    ll a = scan;
    ll b = scan;
    ll diff = abs(a - b);
    ll rem = 0;
    if(diff > 0){
        rem = min(b % diff, diff - (b % diff));
    }
    writeln(diff, " ", rem);
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) theCode();
}

/*********  That's All Folks!  *********/
import std.stdio, std.random, std.functional, std.container, std.algorithm;
import std.numeric, std.range, std.typecons, std.string, std.math, std.conv;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		if (a == b)
		{
			ans[ti] = [0, 0];
			continue;
		}
		else if (a == 0)
		{
			ans[ti] = [b, 0];
			continue;
		}
		if (a > b)
			swap(a, b);
		auto d = b - a;
		auto rem = b % d;
		ans[ti] = [d, (d-rem) % d];
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1]);
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		if (a == b)
		{
			ans[ti] = [0, 0];
			continue;
		}
		if (a > b)
			swap(a, b);
		auto d = b - a;
		auto rem = b % d;
		ans[ti] = [d, (d-rem) % d];
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1]);
	stdout.flush;
	debug readln;
}


There are $$$n$$$ computers in the company network. They are numbered from $$$1$$$ to $$$n$$$.For each pair of two computers $$$1 \leq i < j \leq n$$$ you know the value $$$a_{i,j}$$$: the difficulty of sending data between computers $$$i$$$ and $$$j$$$. All values $$$a_{i,j}$$$ for $$$i<j$$$ are different.You want to separate all computers into $$$k$$$ sets $$$A_1, A_2, \ldots, A_k$$$, such that the following conditions are satisfied:   for each computer $$$1 \leq i \leq n$$$ there is exactly one set $$$A_j$$$, such that $$$i \in A_j$$$;  for each two pairs of computers $$$(s, f)$$$ and $$$(x, y)$$$ ($$$s \neq f$$$, $$$x \neq y$$$), such that $$$s$$$, $$$f$$$, $$$x$$$ are from the same set but $$$x$$$ and $$$y$$$ are from different sets, $$$a_{s,f} < a_{x,y}$$$. For each $$$1 \leq k \leq n$$$ find the number of ways to divide computers into $$$k$$$ groups, such that all required conditions are satisfied. These values can be large, so you need to find them by modulo $$$998\,244\,353$$$.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 1500$$$): the number of computers. The $$$i$$$-th of the next $$$n$$$ lines contains $$$n$$$ integers $$$a_{i,1}, a_{i,2}, \ldots, a_{i,n}$$$($$$0 \leq a_{i,j} \leq \frac{n (n-1)}{2}$$$). It is guaranteed that:    for all $$$1 \leq i \leq n$$$ $$$a_{i,i} = 0$$$;  for all $$$1 \leq i < j \leq n$$$ $$$a_{i,j} > 0$$$;  for all $$$1 \leq i < j \leq n$$$ $$$a_{i,j} = a_{j,i}$$$;  all $$$a_{i,j}$$$ for $$$i <j$$$ are different.

Print $$$n$$$ integers: the $$$k$$$-th of them should be equal to the number of possible ways to divide computers into $$$k$$$ groups, such that all required conditions are satisfied, modulo $$$998\,244\,353$$$.

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

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

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

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

enum MO = 998244353;
alias Mint = ModInt!MO;

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new int[][](N, N);
      foreach (u; 0 .. N) foreach (v; 0 .. N) {
        A[u][v] = readInt();
      }

      const lim = N * (N - 1) / 2 + 1;
      auto uvs = new int[2][lim];
      foreach (x; 0 .. lim) {
        uvs[x][] = -1;
      }
      foreach (u; 0 .. N) foreach (v; u + 1 .. N) {
        uvs[A[u][v]] = [u, v];
      }

      auto uf = new int[N];
      uf[] = -1;
      auto es = new int[N];
      auto dp = new Mint[][](N, N + 1);
      foreach (u; 0 .. N) {
        dp[u][1] = 1;
      }
      foreach (x; 0 .. lim) {
        const u = uvs[x][0];
        const v = uvs[x][1];
        if (u != -1 && v != -1) {
          const ru = uf.root(u);
          const rv = uf.root(v);
          if (ru != rv) {
            debug {
              writeln("merge ", ru, " ", rv);
            }
            auto work = new Mint[(-uf[ru]) + (-uf[rv]) + 1];
            foreach (k; 0 .. -uf[ru] + 1) foreach (l; 0 .. -uf[rv] + 1) {
              work[k + l] += dp[ru][k] * dp[rv][l];
            }
            uf.connect(ru, rv);
            const r = uf.root(ru);
            es[r] = es[ru] + es[rv];
            dp[r][0 .. work.length] = work[];
          }
          {
            const r = uf.root(ru);
            ++es[r];
            debug {
              writefln("es[%s] = %s", r, es[r]);
            }
            if (es[r] == (-uf[r]) * (-uf[r] - 1) / 2) {
              dp[r][1] += 1;
            }
          }
        }
      }

      const r = uf.root(0);
      foreach (k; 1 .. N + 1) {
        if (k > 1) write(" ");
        write(dp[r][k]);
      }
      writeln;
    }
  } catch (EOFException e) {
  }
}


At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks.Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array a[1], a[2], ..., a[n]. Then he should perform a sequence of m operations. An operation can be one of the following:  Print operation l, r. Picks should write down the value of .  Modulo operation l, r, x. Picks should perform assignment a[i] = a[i] mod x for each i (l ≤ i ≤ r).  Set operation k, x. Picks should set the value of a[k] to x (in other words perform an assignment a[k] = x). Can you help Picks to perform the whole sequence of operations?

The first line of input contains two integer: n, m (1 ≤ n, m ≤ 105). The second line contains n integers, separated by space: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109) — initial value of array elements. Each of the next m lines begins with a number type .    If type = 1, there will be two integers more in the line: l, r (1 ≤ l ≤ r ≤ n), which correspond the operation 1.  If type = 2, there will be three integers more in the line: l, r, x (1 ≤ l ≤ r ≤ n; 1 ≤ x ≤ 109), which correspond the operation 2.  If type = 3, there will be two integers more in the line: k, x (1 ≤ k ≤ n; 1 ≤ x ≤ 109), which correspond the operation 3.

For each operation 1, please print a line containing the answer. Notice that the answer may exceed the 32-bit integer.

NoteConsider the first testcase:  At first, a = {1, 2, 3, 4, 5}.  After operation 1, a = {1, 2, 3, 0, 1}.  After operation 2, a = {1, 2, 5, 0, 1}.  At operation 3, 2 + 5 + 0 + 1 = 8.  After operation 4, a = {1, 2, 2, 0, 1}.  At operation 5, 1 + 2 + 2 = 5.

import std.stdio;

immutable int MED_N = 1 << 17, MAX_N = MED_N << 1;

struct Node {int v, p; long s;}

class D {
static:
Node [MAX_N] t;

long get_sum (int l, int r) {
	long res = 0;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1) {
		if (l & 1)    res += t[l].s, l++;
		if (!(r & 1)) res += t[r].s, r--;
	}
	return res;
}

void assign (int k, int x) {
	t[k].v = x;
	t[k].p = k;
	t[k].s = x;
	for (int i = k >> 1; i > 0; k = i, i >>= 1) {
		if (t[k].v < t[k ^ 1].v) k ^= 1;
		t[i].v = t[k].v;
		t[i].p = t[k].p;
		t[i].s = t[k].s + t[k ^ 1].s;
	}
}

void modulo (int k, int x) {
	while (t[k].v >= x) assign (t[k].p, t[k].v % x);
}

void modulo (int l, int r, int x) {
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1) {
		if (l & 1)    modulo (l, x), l++;
		if (!(r & 1)) modulo (r, x), r--;
	}
}

void solve () {
	int n, m, t, l, r, x, k;
	while (readf (" %s %s", &n, &m) > 0) {
		foreach (i; 1..n + 1) {
			readf (" %s", &x);
			assign (i + MED_N, x);
		}
		foreach (q; 0..m) {
			readf (" %s", &t);
			if (t == 1) {
				readf (" %s %s", &l, &r);
				writeln (get_sum (l, r));
			} else if (t == 2) {
				readf (" %s %s %s", &l, &r, &x);
				modulo (l, r, x);
			} else if (t == 3) {
				readf (" %s %s", &k, &x);
				assign (k + MED_N, x);
			}
		}
	}
}
}

void main () {
	D.solve ();
}

import std.stdio;

immutable int MED_N = 1 << 17, MAX_N = MED_N << 1;

struct Node {int v, p; long s;}

__gshared Node [MAX_N] t;

long get_sum (int l, int r) {
	long res = 0;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1) {
		if (l & 1)    res += t[l].s, l++;
		if (!(r & 1)) res += t[r].s, r--;
	}
	return res;
}

void assign (int k, int x) {
	t[k].v = x;
	t[k].p = k;
	t[k].s = x;
	for (int i = k >> 1; i > 0; k = i, i >>= 1) {
		if (t[k].v < t[k ^ 1].v) k ^= 1;
		t[i].v = t[k].v;
		t[i].p = t[k].p;
		t[i].s = t[k].s + t[k ^ 1].s;
	}
}

void modulo (int k, int x) {
	while (t[k].v >= x) assign (t[k].p, t[k].v % x);
}

void modulo (int l, int r, int x) {
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1) {
		if (l & 1)    modulo (l, x), l++;
		if (!(r & 1)) modulo (r, x), r--;
	}
}

void main () {
	int n, m, t, l, r, x, k;
	while (readf (" %s %s", &n, &m) > 0) {
		foreach (i; 1..n + 1) {
			readf (" %s", &x);
			assign (i + MED_N, x);
		}
		foreach (q; 0..m) {
			readf (" %s", &t);
			if (t == 1) {
				readf (" %s %s", &l, &r);
				writeln (get_sum (l, r));
			} else if (t == 2) {
				readf (" %s %s %s", &l, &r, &x);
				modulo (l, r, x);
			} else if (t == 3) {
				readf (" %s %s", &k, &x);
				assign (k + MED_N, x);
			}
		}
	}
}

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

immutable int MED_N = 1 << 17;
immutable int MAX_N = MED_N << 1;

struct Node
{
	int max_value;
	int max_position;
	long sum_values;
}

__gshared Node [MAX_N] t;

long get_sum (int l, int r)
{
	long res = 0;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1)
	{
		if (l & 1)
		{
			res += t[l].sum_values;
			l++;
		}
		if (!(r & 1))
		{
			res += t[r].sum_values;
			r--;
		}
	}
	return res;
}

void assign (int k, int x)
{
	assert (MED_N <= k && k < MAX_N);
	t[k].max_value = x;
	t[k].max_position = k;
	t[k].sum_values = x;
	for (int i = k >> 1; i > 0; i >>= 1, k >>= 1)
	{
		if (t[k].max_value < t[k ^ 1].max_value)
		{
			k ^= 1;
		}
		t[i].max_value = t[k].max_value;
		t[i].max_position = t[k].max_position;
		t[i].sum_values = t[k].sum_values + t[k ^ 1].sum_values;
	}
}

void modulo (int k, int x)
{
	while (t[k].max_value >= x)
	{
		assign (t[k].max_position, t[k].max_value % x);
	}
}

void modulo (int l, int r, int x)
{
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1)
	{
		if (l & 1)
		{
			modulo (l, x);
			l++;
		}
		if (!(r & 1))
		{
			modulo (r, x);
			r--;
		}
	}
}

void main ()
{
	int n;
	int m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new int [n];
		foreach (i, ref x; a)
		{
			readf (" %s", &x);
			assign (i + MED_N, x);
		}
		foreach (q; 0..m)
		{
			int t;
			int l;
			int r;
			int x;
			int k;
			readf (" %s", &t);
			switch (t)
			{
				case 1:
					readf (" %s %s", &l, &r);
					writeln (get_sum (l - 1, r - 1));
					break;
				case 2:
					readf (" %s %s %s", &l, &r, &x);
					modulo (l - 1, r - 1, x);
					break;
				case 3:
					readf (" %s %s", &k, &x);
					assign (k - 1 + MED_N, x);
					break;
				default:
					assert (false);
			}
		}
	}
}

import std.stdio;

immutable int MED_N = 1 << 17, MAX_N = MED_N << 1;

struct Node {int v, p; long s;}

Node [MAX_N] t;

long get_sum (int l, int r) {
	long res = 0;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1) {
		if (l & 1)    res += t[l].s, l++;
		if (!(r & 1)) res += t[r].s, r--;
	}
	return res;
}

void assign (int k, int x) {
	t[k].v = x;
	t[k].p = k;
	t[k].s = x;
	for (int i = k >> 1; i > 0; k = i, i >>= 1) {
		if (t[k].v < t[k ^ 1].v) k ^= 1;
		t[i].v = t[k].v;
		t[i].p = t[k].p;
		t[i].s = t[k].s + t[k ^ 1].s;
	}
}

void modulo (int k, int x) {
	while (t[k].v >= x) assign (t[k].p, t[k].v % x);
}

void modulo (int l, int r, int x) {
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1) {
		if (l & 1)    modulo (l, x), l++;
		if (!(r & 1)) modulo (r, x), r--;
	}
}

void main () {
	int n, m, t, l, r, x, k;
	while (readf (" %s %s", &n, &m) > 0) {
		foreach (i; 1..n + 1) {
			readf (" %s", &x);
			assign (i + MED_N, x);
		}
		foreach (q; 0..m) {
			readf (" %s", &t);
			if (t == 1) {
				readf (" %s %s", &l, &r);
				writeln (get_sum (l, r));
			} else if (t == 2) {
				readf (" %s %s %s", &l, &r, &x);
				modulo (l, r, x);
			} else if (t == 3) {
				readf (" %s %s", &k, &x);
				assign (k + MED_N, x);
			}
		}
	}
}

import std.stdio;

immutable int MED_N = 1 << 17;
immutable int MAX_N = MED_N << 1;

struct Node
{
	int v, p;
	long s;
}

Node [MAX_N] t;

long get_sum (int l, int r)
{
	long res = 0;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1)
	{
		if (l & 1)
		{
			res += t[l].s;
			l++;
		}
		if (!(r & 1))
		{
			res += t[r].s;
			r--;
		}
	}
	return res;
}

void assign (int k, int x)
{
	t[k].v = x;
	t[k].p = k;
	t[k].s = x;
	for (int i = k >> 1; i > 0; k = i, i >>= 1)
	{
		if (t[k].v < t[k ^ 1].v)
		{
			k ^= 1;
		}
		t[i].v = t[k].v;
		t[i].p = t[k].p;
		t[i].s = t[k].s + t[k ^ 1].s;
	}
}

void modulo (int k, int x)
{
	while (t[k].v >= x)
	{
		assign (t[k].p, t[k].v % x);
	}
}

void modulo (int l, int r, int x)
{
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1)
	{
		if (l & 1)
		{
			modulo (l, x);
			l++;
		}
		if (!(r & 1))
		{
			modulo (r, x);
			r--;
		}
	}
}

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new int [n];
		foreach (i, ref x; a)
		{
			readf (" %s", &x);
			assign (i + MED_N, x);
		}
		foreach (q; 0..m)
		{
			int t, l, r, x, k;
			readf (" %s", &t);
			switch (t)
			{
				case 1:
					readf (" %s %s", &l, &r);
					writeln (get_sum (l - 1, r - 1));
					break;
				case 2:
					readf (" %s %s %s", &l, &r, &x);
					modulo (l - 1, r - 1, x);
					break;
				case 3:
					readf (" %s %s", &k, &x);
					assign (k - 1 + MED_N, x);
					break;
				default:
					assert (false);
			}
		}
	}
}

import std.stdio;

immutable int MED_N = 1 << 17, MAX_N = MED_N << 1;

struct Node {int v, p; long s;}

void main () {
Node [MAX_N] a;

long get_sum (int l, int r) {
	long res = 0;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1) {
		if (l & 1)    res += a[l].s, l++;
		if (!(r & 1)) res += a[r].s, r--;
	}
	return res;
}

void assign (int k, int x) {
	a[k].v = x;
	a[k].p = k;
	a[k].s = x;
	for (int i = k >> 1; i > 0; k = i, i >>= 1) {
		if (a[k].v < a[k ^ 1].v) k ^= 1;
		a[i].v = a[k].v;
		a[i].p = a[k].p;
		a[i].s = a[k].s + a[k ^ 1].s;
	}
}

void modulo (int k, int x) {
	while (a[k].v >= x) assign (a[k].p, a[k].v % x);
}

void modulo2 (int l, int r, int x) {
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1) {
		if (l & 1)    modulo (l, x), l++;
		if (!(r & 1)) modulo (r, x), r--;
	}
}

	int n, m, t, l, r, x, k;
	while (readf (" %s %s", &n, &m) > 0) {
		foreach (i; 1..n + 1) {
			readf (" %s", &x);
			assign (i + MED_N, x);
		}
		foreach (q; 0..m) {
			readf (" %s", &t);
			if (t == 1) {
				readf (" %s %s", &l, &r);
				writeln (get_sum (l, r));
			} else if (t == 2) {
				readf (" %s %s %s", &l, &r, &x);
				modulo2 (l, r, x);
			} else if (t == 3) {
				readf (" %s %s", &k, &x);
				assign (k + MED_N, x);
			}
		}
	}
}


You are given a sorted array $$$a_1, a_2, \dots, a_n$$$ (for each index $$$i > 1$$$ condition $$$a_i \ge a_{i-1}$$$ holds) and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$max(i)$$$ be equal to the maximum in the $$$i$$$-th subarray, and $$$min(i)$$$ be equal to the minimum in the $$$i$$$-th subarray. The cost of division is equal to $$$\sum\limits_{i=1}^{k} (max(i) - min(i))$$$. For example, if $$$a = [2, 4, 5, 5, 8, 11, 19]$$$ and we divide it into $$$3$$$ subarrays in the following way: $$$[2, 4], [5, 5], [8, 11, 19]$$$, then the cost of division is equal to $$$(4 - 2) + (5 - 5) + (19 - 8) = 13$$$.Calculate the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 1 \le a_i \le 10^9$$$, $$$a_i \ge a_{i-1}$$$).

Print the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays.

NoteIn the first test we can divide array $$$a$$$ in the following way: $$$[4, 8, 15, 16], [23], [42]$$$.

import std.algorithm.sorting : sort;
import std.stdio;

void main()
{
  char c;
  int n, k;
  readf!"%d %d\n"(n, k);
  auto a = new int[n];
  auto b = new int[n-1];
  foreach (i; 0..n) readf!"%d%c"(a[i], c);
  foreach (i; 0..n-1) b[i] = a[i] - a[i+1];

  b.sort;

  int s = a[$-1] - a[0];
  foreach (i; 0..k-1) s += b[i];

  writeln(s);
}

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;
	int k = read.to!int;
	long[] as;
	foreach(i; 0 .. n) as ~= read.to!int;

	long sum = as[n - 1] - as[0];
	log("sum:", sum);

	long[] ds;
	foreach(i; 0 .. n - 1) ds ~= as[i + 1] - as[i];
	log("ds:", ds);

	ds.sort!"a>b"();
	log("ds:", ds);

	foreach(i; 0 .. k - 1){
		sum -= ds[i];
	}

	sum.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!int;
	auto k = RD!int;
	auto a = RDA;
	auto d = new long[](n-1);
	foreach (i; 0..n-1)
	{
		d[i] = a[i+1] - a[i];
	}
	d.sort();
	auto ans = d[0..$-(k-1)].sum;

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


There is a pyramid which consists of $$$n$$$ floors. The floors are numbered from top to bottom in increasing order. In the pyramid, the $$$i$$$-th floor consists of $$$i$$$ rooms.Denote the $$$j$$$-th room on the $$$i$$$-th floor as $$$(i,j)$$$. For all positive integers $$$i$$$ and $$$j$$$ such that $$$1 \le j \le i < n$$$, there are $$$2$$$ one-way staircases which lead from $$$(i,j)$$$ to $$$(i+1,j)$$$ and from $$$(i,j)$$$ to $$$(i+1,j+1)$$$ respectively.In each room you can either put a torch or leave it empty. Define the brightness of a room $$$(i, j)$$$ to be the number of rooms with a torch from which you can reach the room $$$(i, j)$$$ through a non-negative number of staircases.For example, when $$$n=5$$$ and torches are placed in the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,2)$$$, $$$(4,1)$$$, $$$(4,3)$$$, and $$$(5,3)$$$, the pyramid can be illustrated as follows:  In the above picture, rooms with torches are colored in yellow, and empty rooms are white. The blue numbers in the bottom-right corner indicate the brightness of the rooms.The room $$$(4,2)$$$ (the room with a star) has brightness $$$3$$$. In the picture below, the rooms from where you can reach $$$(4,2)$$$ have red border. The brightness is $$$3$$$ since there are three torches among these rooms.  The pyramid is called nice if and only if for all floors, all rooms in the floor have the same brightness.Define the brilliance of a nice pyramid to be the sum of brightness over the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,1)$$$, ..., $$$(n,1)$$$.Find an arrangement of torches in the pyramid, such that the resulting pyramid is nice and its brilliance is maximized.We can show that an answer always exists. If there are multiple answers, output any one of them.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains a single positive integer $$$n$$$ ($$$1 \le n \le 500$$$) — the number of floors in the pyramid. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$.

For each test case, output $$$n$$$ lines, the arrangement of torches in the pyramid. The $$$i$$$-th line should contain $$$i$$$ integers, each separated with a space. The $$$j$$$-th integer on the $$$i$$$-th line should be $$$1$$$ if room $$$(i,j)$$$ has a torch, and $$$0$$$ otherwise. We can show that an answer always exists. If there are multiple answers, output any one of them.

NoteIn the third test case, torches are placed in $$$(1,1)$$$, $$$(2,1)$$$, $$$(2,2)$$$, $$$(3,1)$$$, and $$$(3,3)$$$.  The pyramid is nice as rooms on each floor have the same brightness. For example, all rooms on the third floor have brightness $$$3$$$.The brilliance of the pyramid is $$$1+2+3 = 6$$$. It can be shown that no arrangements with $$$n=3$$$ will have a greater brilliance.

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void solve() {
    int N = readln.chomp.to!int;
    for (int i = 0; i < N; i++) {
        auto L = new int[i + 1];
        L[] = 0;
        L[0] = 1;
        L[$-1] = 1;
        writefln("%(%s %)", L);
    }
}

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