Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $$$n$$$ hotels, where the $$$i$$$-th hotel is located in the city with coordinate $$$x_i$$$. Sonya is a smart girl, so she does not open two or more hotels in the same city.Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $$$d$$$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $$$n$$$ hotels to the new one is equal to $$$d$$$.

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1\leq n\leq 100$$$, $$$1\leq d\leq 10^9$$$) — the number of Sonya's hotels and the needed minimum distance from a new hotel to all others. The second line contains $$$n$$$ different integers in strictly increasing order $$$x_1, x_2, \ldots, x_n$$$ ($$$-10^9\leq x_i\leq 10^9$$$) — coordinates of Sonya's hotels.

Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to $$$d$$$.

NoteIn the first example, there are $$$6$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$-6$$$, $$$5$$$, $$$6$$$, $$$12$$$, $$$13$$$, and $$$19$$$.In the second example, there are $$$5$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$2$$$, $$$6$$$, $$$13$$$, $$$16$$$, and $$$21$$$.

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

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

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

    auto ans = 2;
    foreach (a, b; lockstep(arr, arr.dropOne)) {
        auto dist = b - a;
        ans += dist < 2*d ? 0 : dist > 2*d ? 2 : 1;
    }

    ans.writeln;
}


Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $$$1$$$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $$$3$$$ steps, and the second contains $$$4$$$ steps, she will pronounce the numbers $$$1, 2, 3, 1, 2, 3, 4$$$.You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

The first line contains $$$n$$$ ($$$1 \le n \le 1000$$$) — the total number of numbers pronounced by Tanya. The second line contains integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with $$$x$$$ steps, she will pronounce the numbers $$$1, 2, \dots, x$$$ in that order. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

In the first line, output $$$t$$$ — the number of stairways that Tanya climbed. In the second line, output $$$t$$$ numbers — the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways.

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

void main()
{
    readln;

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

    auto ans = zip(StoppingPolicy.longest, arr, arr.dropOne).filter!(t => t[1] == 1 || t[1] == 0).map!(t => t[0]).array;

    ans.length.writeln;
    ans.writefln!("%(%s %)");
}

import std.stdio;
int main()
{
	int a=0;
	readf(" %d", &a);
	int[] m = new int[a];
	for (int i=0; i<a; i++)
	{
		readf(" %d", &m[i]);
	}
	int count=0;
	for (int i=0; i<a; i++)
	{
		if (m[i]==1)
		{
			count=count+1;
		}
	}
	writeln(count);
	for (int i=1; i<a; i++)
	{
		if (m[i]==1)
		{
			writeln(m[i-1]);
		}
	}
	writeln(m[a-1]);
	return 0;
}


You are a mayor of Berlyatov. There are $$$n$$$ districts and $$$m$$$ two-way roads between them. The $$$i$$$-th road connects districts $$$x_i$$$ and $$$y_i$$$. The cost of travelling along this road is $$$w_i$$$. There is some path between each pair of districts, so the city is connected.There are $$$k$$$ delivery routes in Berlyatov. The $$$i$$$-th route is going from the district $$$a_i$$$ to the district $$$b_i$$$. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district $$$a_i$$$ to the district $$$b_i$$$ to deliver products.The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $$$0$$$).Let $$$d(x, y)$$$ be the cheapest cost of travel between districts $$$x$$$ and $$$y$$$.Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $$$0$$$. In other words, you have to find the minimum possible value of $$$\sum\limits_{i = 1}^{k} d(a_i, b_i)$$$ after applying the operation described above optimally.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$; $$$n - 1 \le m \le min(1000, \frac{n(n-1)}{2})$$$; $$$1 \le k \le 1000$$$) — the number of districts, the number of roads and the number of courier routes. The next $$$m$$$ lines describe roads. The $$$i$$$-th road is given as three integers $$$x_i$$$, $$$y_i$$$ and $$$w_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$; $$$1 \le w_i \le 1000$$$), where $$$x_i$$$ and $$$y_i$$$ are districts the $$$i$$$-th road connects and $$$w_i$$$ is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts. The next $$$k$$$ lines describe courier routes. The $$$i$$$-th route is given as two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the districts of the $$$i$$$-th route. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).

Print one integer — the minimum total courier routes cost you can achieve (i.e. the minimum value $$$\sum\limits_{i=1}^{k} d(a_i, b_i)$$$, where $$$d(x, y)$$$ is the cheapest cost of travel between districts $$$x$$$ and $$$y$$$) if you can make some (at most one) road cost zero.

NoteThe picture corresponding to the first example:There, you can choose either the road $$$(2, 4)$$$ or the road $$$(4, 6)$$$. Both options lead to the total cost $$$22$$$.The picture corresponding to the second example:There, you can choose the road $$$(3, 4)$$$. This leads to the total cost $$$13$$$.

// Cheese-Cracker: cheese-cracker.github.io
const int INF = 10^^9 + 300;
tup[][] adj;
int[][] dis;

void djkes(int v){
    int cur;
    auto cask = rbt!tup;
    cask.insert(tup(0, v));
    dis[v][v] = 0;

    while(cask.length){
        cur = cask.front[1];
        cask.removeFront;
        foreach(ed; adj[cur]){
            int u = ed[0].to!int, w = ed[1].to!int;
            /* writeln(u, " ", w); */
            if(dis[v][u] > dis[v][cur] + w){
                cask.removeKey(tup(dis[v][u], u));
                dis[v][u] = dis[v][cur] + w;
                cask.insert(tup(dis[v][u], u));
            }
        }
    }
}

void play(){
    int n = rd!int, m = rd!int, k = rd!int;
    dis = new int[][](n+1, n+1);
    adj = new tup[][](n+1);
    tup[] routes, roads;
    int x, y, w;
    foreach(i; 0..m){
        x = rd!int;
        y = rd!int;
        w = rd!int;
        roads ~= tup(x, y);
        adj[x] ~= tup(y, w);
        adj[y] ~= tup(x, w);
    }
    foreach(i; 1..n+1){
        dis[i].fill(INF);
        djkes(i);
    }
    /* writeln(dis); */
    foreach(i; 0..k){
        routes ~= tup(rd!int, rd!int);
    }
    ll mindist = INF;
    foreach(i; 0..m){
        int st = roads[i][0];
        int end = roads[i][1];
        ll totdist = 0;
        foreach(j; 0..k){
            int rst = routes[j][0];
            int rend = routes[j][1];
            ll dist = dis[rst][rend];
            dist = min(dist, dis[rst][st] + dis[rend][end]);
            dist = min(dist, dis[rst][end] + dis[rend][st]);
            /* writeln(j, " ", dist); */
            totdist += dist;
        }
        mindist = min(totdist, mindist);
    }
    writeln(mindist);
}

int main(){
    long t = 1;
    /* t = rd;        // Toggle! */
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ a.each!(w => write(w, "| ")); writeln; } }
alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(int, int);
alias trip = Tuple!(int, int, int);
T max(T = long)(T a, T b){ return (a > b) ? a : b; }
T min(T = long)(T a, T b){ return (a < b) ? a : b; }

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

immutable int infinity = int.max / 2;

void main ()
{
	int n, m, k;
	while (readf !(" %s %s %s") (n, m, k) > 0)
	{
		alias Edge = Tuple !(int, q{u}, int, q{v}, int, q{w});
		auto adj = new int [] [n];
		auto edges = new Edge [m];
		foreach (int j, ref e; edges)
		{
			readf !(" %s %s %s") (e.u, e.v, e.w);
			e.u -= 1;
			e.v -= 1;
			adj[e.u] ~= j;
			adj[e.v] ~= j;
		}
		auto x = new int [k];
		auto y = new int [k];
		foreach (i; 0..k)
		{
			readf !(" %s %s") (x[i], y[i]);
		}
		x[] -= 1;
		y[] -= 1;

		int [] [] dist;
		foreach (i; 0..n)
		{
			auto d = new int [n];
			d[] = infinity;
			d[i] = 0;
			alias Record = Tuple !(int, q{d}, int, q{v});
			auto t = redBlackTree !(Record);
			t.insert (Record (d[i], i));
			while (!t.empty)
			{
				auto v = t.front.v;
				t.removeFront ();
				foreach (j; adj[v])
				{
					auto e = edges[j];
					auto u = e.u ^ e.v ^ v;
					if (d[u] > d[v] + e.w)
					{
						t.removeKey (Record (d[u], u));
						d[u] = d[v] + e.w;
						t.insert (Record (d[u], u));
					}
				}
			}
			dist ~= d;
		}

		int res = infinity;
		foreach (e; edges)
		{
			int cur = 0;
			foreach (i; 0..k)
			{
				auto temp = dist[x[i]][y[i]];
				temp = min (temp,
				    dist[x[i]][e.u] + dist[y[i]][e.v]);
				temp = min (temp,
				    dist[x[i]][e.v] + dist[y[i]][e.u]);
				cur += temp;
			}
			res = min (res, cur);
		}

		writeln (res);
	}
}

// Cheese-Cracker: cheese-cracker.github.io
const int INF = 10^^8;
tup[][] adj;
int[][] dis;

void djkes(int v){
    int cur;
    auto cask = rbt!tup;
    cask.insert(tup(0, v));
    dis[v][v] = 0;

    while(cask.length){
        cur = cask.front[1];
        cask.removeFront;
        foreach(ed; adj[cur]){
            int u = ed[0].to!int, w = ed[1].to!int;
            /* writeln(u, " ", w); */
            if(dis[v][u] > dis[v][cur] + w){
                cask.removeKey(tup(dis[v][u], u));
                dis[v][u] = dis[v][cur] + w;
                cask.insert(tup(dis[v][u], u));
            }
        }
    }
}

void play(){
    int n = rd!int, m = rd!int, k = rd!int;
    dis = new int[][](n+1, n+1);
    adj = new tup[][](n+1);
    tup[] routes, roads;
    int x, y, w;
    foreach(i; 0..m){
        x = rd!int;
        y = rd!int;
        w = rd!int;
        roads ~= tup(x, y);
        adj[x] ~= tup(y, w);
        adj[y] ~= tup(x, w);
    }
    foreach(i; 1..n+1){
        dis[i].fill(INF);
        djkes(i);
    }
    /* writeln(dis); */
    foreach(i; 0..k){
        routes ~= tup(rd!int, rd!int);
    }
    ll mindist = INF;
    foreach(i; 0..m){
        int st = roads[i][0];
        int end = roads[i][1];
        ll totdist = 0;
        foreach(j; 0..k){
            int rst = routes[j][0];
            int rend = routes[j][1];
            ll dist = dis[rst][rend];
            dist = min(dist, dis[rst][st] + dis[rend][end]);
            dist = min(dist, dis[rst][end] + dis[rend][st]);
            /* writeln(j, " ", dist); */
            totdist += dist;
        }
        mindist = min(totdist, mindist);
    }
    writeln(mindist);
}

int main(){
    long t = 1;
    /* t = rd;        // Toggle! */
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ a.each!(w => write(w, "| ")); writeln; } }
alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(int, int);
alias trip = Tuple!(int, int, int);
T max(T = long)(T a, T b){ return (a > b) ? a : b; }
T min(T = long)(T a, T b){ return (a < b) ? a : b; }


Olya has an array of integers $$$a_1, a_2, \ldots, a_n$$$. She wants to split it into tandem repeats. Since it's rarely possible, before that she wants to perform the following operation several (possibly, zero) number of times: insert a pair of equal numbers into an arbitrary position. Help her!More formally:  A tandem repeat is a sequence $$$x$$$ of even length $$$2k$$$ such that for each $$$1 \le i \le k$$$ the condition $$$x_i = x_{i + k}$$$ is satisfied.  An array $$$a$$$ could be split into tandem repeats if you can split it into several parts, each being a subsegment of the array, such that each part is a tandem repeat.  In one operation you can choose an arbitrary letter $$$c$$$ and insert $$$[c, c]$$$ to any position in the array (at the beginning, between any two integers, or at the end).  You are to perform several operations and split the array into tandem repeats or determine that it is impossible. Please note that you do not have to minimize the number of operations.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 30\,000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 500$$$).  The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — the initial array.  It is guaranteed that the sum of $$$n^2$$$ over all test cases does not exceed $$$250\,000$$$.

For each test case print answer in the following format. If you cannot turn the array into a concatenation of tandem repeats, print a single integer $$$-1$$$. Otherwise print the number of operations $$$q$$$ ($$$0 \le q \le 2 \cdot n^2$$$) that you want to do. Then print the descriptions of operations. In each of the following $$$q$$$ lines print two integers $$$p$$$ and $$$c$$$ ($$$1 \le c \le 10^9$$$), which mean that you insert the integer $$$c$$$ twice after $$$p$$$ elements of the array. If the length of the array is $$$m$$$ before the operation, then the condition $$$0 \le p \le m$$$ should be satisfied. Then you should print any way to split the resulting array into tandem repeats. First, print a single integer $$$d$$$, and then print a sequence $$$t_1, t_2, \ldots, t_d$$$ of even integers of size $$$d$$$ ($$$d, t_i \ge 1$$$). These numbers are the lengths of the subsegments from left to right. Note that the size of the resulting array $$$a$$$ is $$$m = n + 2 \cdot q$$$. The following statements must hold:    $$$m = \sum\limits_{i = 1}^{d}{t_i}$$$.    For all integer $$$i$$$ such that $$$1 \le i \le d$$$, the sequence $$$a_l, a_{l+1}, \ldots, a_r$$$ is a tandem repeat, where $$$l = \sum\limits_{j = 1}^{i - 1}{t_j} + 1$$$, $$$r = l + t_i - 1$$$.  It can be shown that if the array can be turned into a concatenation of tandem repeats, then there exists a solution satisfying all constraints. If there are multiple answers, you can print any.

NoteIn the first test case, you cannot apply operations to the array to make it possible to split it into tandem repeats.In the second test case the array is already a tandem repeat $$$[5, 5] = \underbrace{([5] + [5])}_{t_1 = 2}$$$, thus we can do no operations at all.In the third test case, initially, we have the following array: $$$$$$[1, 3, 1, 2, 2, 3].$$$$$$ After the first insertion with $$$p = 1, c = 3$$$: $$$$$$[1, \textbf{3, 3}, 3, 1, 2, 2, 3].$$$$$$ After the second insertion with $$$p = 5, c = 3$$$: $$$$$$[1, 3, 3, 3, 1, \textbf{3, 3}, 2, 2, 3].$$$$$$ After the third insertion with $$$p = 5, c = 3$$$: $$$$$$[1, 3, 3, 3, 1, \textbf{3, 3}, 3, 3, 2, 2, 3].$$$$$$ After the fourth insertion with $$$p = 10, c = 3$$$: $$$$$$[1, 3, 3, 3, 1, 3, 3, 3, 3, 2, \textbf{3, 3}, 2, 3].$$$$$$ The resulting array can be represented as a concatenation of tandem repeats: $$$$$$\underbrace{([1, 3, 3, 3] + [1, 3, 3, 3])}_{t_1 = 8} + \underbrace{([3, 2, 3] + [3, 2, 3])}_{t_2 = 6}.$$$$$$In the fourth test case, initially, we have the following array: $$$$$$[3, 2, 1, 1, 2, 3].$$$$$$ After the first insertion with $$$p = 0, c = 3$$$: $$$$$$[\textbf{3, 3}, 3, 2, 1, 1, 2, 3].$$$$$$ After the second insertion with $$$p = 8, c = 3$$$: $$$$$$[3, 3, 3, 2, 1, 1, 2, 3, \textbf{3, 3}].$$$$$$ After the third insertion with $$$p = 5, c = 3$$$ $$$$$$[3, 3, 3, 2, 1, \textbf{3, 3}, 1, 2, 3, 3, 3].$$$$$$ After the fourth insertion with $$$p = 6, c = 2$$$: $$$$$$[3, 3, 3, 2, 1, 3, \textbf{2, 2}, 3, 1, 2, 3, 3, 3].$$$$$$ After the fifth insertion with $$$p = 7, c = 1$$$: $$$$$$[3, 3, 3, 2, 1, 3, 2, \textbf{1, 1}, 2, 3, 1, 2, 3, 3, 3].$$$$$$ The resulting array can be represented as a concatenation of tandem repeats: $$$$$$\underbrace{([3] + [3])}_{t_1 = 2} + \underbrace{([3, 2, 1] + [3, 2, 1])}_{t_2 = 6} + \underbrace{([1, 2, 3] + [1, 2, 3])}_{t_3 = 6} + \underbrace{([3] + [3])}_{t_4 = 2}.$$$$$$

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

void main ()
{
	auto tests = readln.strip.to !(int);
multitest_loop:
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		int [int] c;
		foreach (ref x; a)
		{
			c[x] += 1;
		}
		if (c.byValue.any !(k => k % 2 != 0))
		{
			writeln (-1);
			continue multitest_loop;
		}

		alias Record = Tuple !(int, q{pos}, int, q{val});
		Record [] inserts;
		int [] parts;
		int start = 0;
		while (!a.empty)
		{
			int j = 1;
			while (a[j] != a.front)
			{
				j += 1;
			}
			foreach (pos; 1..j)
			{
				inserts ~= Record (start + j + pos, a[pos]);
			}
			parts ~= j * 2;
			start += j * 2;
			a = a[1..j].retro.array ~ a[j + 1..$];
		}
		writeln (inserts.length);
		foreach (ref r; inserts)
		{
			writeln (r.pos, " ", r.val);
		}
		writeln (parts.length);
		writefln !(`%(%s %)`) (parts);
	}
}


There are $$$n$$$ block towers in a row, where tower $$$i$$$ has a height of $$$a_i$$$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation:  Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \leq i, j \leq n$$$; $$$i \neq j$$$), and move a block from tower $$$i$$$ to tower $$$j$$$. This essentially decreases $$$a_i$$$ by $$$1$$$ and increases $$$a_j$$$ by $$$1$$$. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $$$\max(a)-\min(a)$$$. What's the minimum possible ugliness you can achieve, after any number of days?

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of buildings. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the heights of the buildings.

For each test case, output a single integer — the minimum possible ugliness of the buildings.

NoteIn the first test case, the ugliness is already $$$0$$$.In the second test case, you should do one operation, with $$$i = 1$$$ and $$$j = 3$$$. The new heights will now be $$$[2, 2, 2, 2]$$$, with an ugliness of $$$0$$$.In the third test case, you may do three operations:   with $$$i = 3$$$ and $$$j = 1$$$. The new array will now be $$$[2, 2, 2, 1, 5]$$$,  with $$$i = 5$$$ and $$$j = 4$$$. The new array will now be $$$[2, 2, 2, 2, 4]$$$,  with $$$i = 5$$$ and $$$j = 3$$$. The new array will now be $$$[2, 2, 3, 2, 3]$$$.  The resulting ugliness is $$$1$$$. It can be proven that this is the minimum possible ugliness for this test.

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto a = ma(n, readInt!int);
  auto s = a.sum;
  if (s % n == 0) return writeln(0);
  return writeln(1);
}

// main {{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
// }}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
		popChar;
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!long).array;
    long totalsum = a.sum;
    writeln(totalsum % n == 0 ? 0 : 1);
  }
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		auto tot = a.sum;
		ans[ti] = tot % n ? 1 : 0;
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto s = a.sum;
		writefln !("%d") (!!(s % n));
	}
}

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

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

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

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

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

        const sumA = A.sum;
        writeln((sumA % N == 0) ? 0 : 1);
      }
    }
  } catch (EOFException e) {
  }
}


You are given $$$n$$$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $$$0$$$ in case the intersection is an empty set.For example, the intersection of segments $$$[1;5]$$$ and $$$[3;10]$$$ is $$$[3;5]$$$ (length $$$2$$$), the intersection of segments $$$[1;5]$$$ and $$$[5;7]$$$ is $$$[5;5]$$$ (length $$$0$$$) and the intersection of segments $$$[1;5]$$$ and $$$[6;6]$$$ is an empty set (length $$$0$$$).Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $$$(n - 1)$$$ segments has the maximal possible length.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of segments in the sequence. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 10^9$$$) — the description of the $$$i$$$-th segment.

Print a single integer — the maximal possible length of the intersection of $$$(n - 1)$$$ remaining segments after you remove exactly one segment from the sequence.

NoteIn the first example you should remove the segment $$$[3;3]$$$, the intersection will become $$$[2;3]$$$ (length $$$1$$$). Removing any other segment will result in the intersection $$$[3;3]$$$ (length $$$0$$$).In the second example you should remove the segment $$$[1;3]$$$ or segment $$$[2;6]$$$, the intersection will become $$$[2;4]$$$ (length $$$2$$$) or $$$[1;3]$$$ (length $$$2$$$), respectively. Removing any other segment will result in the intersection $$$[2;3]$$$ (length $$$1$$$).In the third example the intersection will become an empty set no matter the segment you remove.In the fourth example you will get the intersection $$$[3;10]$$$ (length $$$7$$$) if you remove the segment $$$[1;5]$$$ or the intersection $$$[1;5]$$$ (length $$$4$$$) if you remove the segment $$$[3;10]$$$.

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

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

    auto mxle = tuple(-1, -1);
    auto mnr = tuple(10 ^^ 9, 10 ^^ 9);
    Tuple!(int, int)[] segs;
    foreach (_; 0 .. n) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;
        segs ~= tuple(a, b);

        if (a > mxle[0]) mxle[1] = mxle[0], mxle[0] = a;
        else if (a > mxle[1]) mxle[1] = a;

        if (b < mnr[0]) mnr[1] = mnr[0], mnr[0] = b;
        else if (b < mnr[1]) mnr[1] = b;
    }

    debug { segs.writeln; writeln(mxle, ' ', mnr); }

    auto ans = 0;
    foreach (sg; segs) {
        auto x = sg[0], y = sg[1];
        auto cur = (y != mnr[0] ? mnr[0] : mnr[1]) - (x != mxle[0] ? mxle[0] : mxle[1]);
        if (cur < 0) cur = 0;
        ans = max(ans, cur);
    }

    ans.writeln;
}

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

  int n; rd(n);
  struct T{int l, r;}
  auto s=new T[](n);
  foreach(i; 0..n) rd(s[i].l, s[i].r);

  int mxlen=0;
  s.sort!"a.l==b.l ? a.r<b.r : a.l>b.l";
  // writeln(s[0]);
  mxlen=max(mxlen, s[1..$].minElement!("a.r").r-s[1..$].maxElement!("a.l").l);
  s.sort!"a.r==b.r ? a.l>b.l : a.r<b.r";
  // writeln(s[0]);
  mxlen=max(mxlen, s[1..$].minElement!("a.r").r-s[1..$].maxElement!("a.l").l);
  writeln(mxlen);
}

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


Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed.Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times.

The first line contains three integers: a, b, n (1 ≤ a, b, n ≤ 105).

In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number a n times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them.

import std.conv;
import std.stdio;

void main() {
    int a, b, n;

    readf("%s %s %s", &a, &b, &n);

    if( a%b != 0 ) {
        --n;
        auto tmp = a * 10;
        bool f;
        for( int i = 0; i < 10; ++i ) {
            if( ( tmp + i ) % b == 0 )
            {
                a = tmp + i;
                f = true;
                break;
            }
        }
        if(!f) {
            writeln("-1");
            return;
        }
    }

    string as = to!string(a);

    for( int i; i < n; ++i ) {
        bool f;
        /*foreach(x; 1..10) {
            if( x % b == 0 ) {
                as ~= to!string(x);
                f = true;
                break;
            }
        }
        if(!f) {
            i = n;
            as = "-1";
        }*/
        as ~= "0";
    }

    writeln(as);

}

module cf_260A;

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

void main() {
    int a, b, n;

    readf("%d %d %d", &a, &b, &n);

    int mod = a % b;
    int ops = 0;

    string resultNumber = to!string(a);
    for (int i = 0; i < n; ++i) {
        for (int j = min(9, b); j >= 0; --j) {
            if ((mod * 10 + j) % b == 0) {
                resultNumber ~= j + '0';
                mod = 0;
                ++ops;
                break;
            }
        }
    }

    writeln(ops == n? resultNumber: "-1");
}

import std.conv;
import std.stdio;

void main() {
    int a, b, n;

    readf("%s %s %s", &a, &b, &n);

    if( a%b != 0 ) {
        --n;
        auto tmp = a * 10;
        bool f;
        for( int i = 1; i < 10; ++i ) {
            if( ( tmp + i ) % b == 0 )
            {
                a = tmp + i;
                f = true;
                break;
            }
        }
        if(!f) {
            writeln("-1");
            return;
        }
    }

    string as = to!string(a);

    for( int i; i < n; ++i ) {
        bool f;
        /*foreach(x; 1..10) {
            if( x % b == 0 ) {
                as ~= to!string(x);
                f = true;
                break;
            }
        }
        if(!f) {
            i = n;
            as = "-1";
        }*/
        as ~= "0";
    }

    writeln(as);

}

import std.conv;
import std.stdio;

void main() {
    int a, b, n;

    readf("%s %s %s", &a, &b, &n);

    if( a%b != 0 ) {
        --n;
        auto tmp = a * 10;
        bool f;
        for( int i = 1; i < 10; ++i ) {
            if( ( tmp + i ) % b == 0 )
            {
                a = tmp + i;
                f = true;
                break;
            }
        }
        if(!f) {
            writeln("-1");
            return;
        }
    }

    string as = to!string(a);

    for( int i; i < n; ++i ) {
        bool f;
        foreach(x; 1..10) {
            if( x % b == 0 ) {
                as ~= to!string(x);
                f = true;
                break;
            }
        }
        if(!f) {
            i = n;
            as = "-1";
        }
    }

    writeln(as);

}


A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.

The first input line contains integer k (1 ≤ k ≤ 1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1 ≤ |s| ≤ 1000, where |s| is the length of string s.

Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them. If the solution doesn't exist, print "-1" (without quotes).

#!/usr/bin/rdmd
import std.stdio;
import std.string;

const int MAX_N = 10004, MAX_K = 256, MAX_C = 0x3F3F3F3F, NA = -1;

int a [MAX_K];
string s;
int k, n;

int main ()
{
	while (readf (" %d ", &k) > 0)
	{
		s = chomp (readln ());
		n = s.length;
		for (int j = 0; j < MAX_K; j++)
			a[j] = 0;
		for (int i = 0; i < n; i++)
			a[s[i]]++;

		bool ok = true;
		for (int j = 0; j < MAX_K; j++)
			if (a[j] % k != 0)
				ok = false;
		if (!ok)
		{
			writefln ("-1");
		}
		else
		{
			for (int i = 0; i < k; i++)
				for (int j = 0; j < MAX_K; j++)
					for (int p = 0; p < a[j] / k; p++)
					{
						writef ("%s", cast (char) j);
					}
			writeln ();
		}
	}
	return 0;
}


Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?

First line of input data contains single integer n (1 ≤ n ≤ 106) — length of the array. Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).

Output answer in single line. "First", if first player wins, and "Second" otherwise (without quotes).

NoteIn first sample first player remove whole array in one move and win.In second sample first player can't make a move and lose.

// Try Codeforces
// author: Leonardone @ NEETSDKASU
import std.stdio, std.array, std.conv, std.string, std.algorithm;

auto gets() { return readln().chomp(); }
auto getV(T)() { return to!T(readln().chomp()); }
auto getVals(T)() { return to!(T[])(readln().chomp().split(" ")); }

auto isOdd(int p) { return p % 2 != 0; }

void main() {
    int n = getV!int();
    auto xs = getVals!int();
    auto odds = 0;
    foreach (x ; xs) {
        if (isOdd(x)) {
            odds++;
        }
    }
    if (odds == 0) {
        writeln("Second");
        return;
    }
    writeln("First");
}

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

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

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

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

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

      bool ans;
      if (A.sum % 2 != 0) {
        ans = true;
      } else {
        if (A.any!"a % 2 != 0") {
          ans = true;
        } else {
          ans = false;
        }
      }
      writeln(ans ? "First" : "Second");
    }
  } catch (EOFException e) {
  }
}


Let's call an array $$$t$$$ dominated by value $$$v$$$ in the next situation.At first, array $$$t$$$ should have at least $$$2$$$ elements. Now, let's calculate number of occurrences of each number $$$num$$$ in $$$t$$$ and define it as $$$occ(num)$$$. Then $$$t$$$ is dominated (by $$$v$$$) if (and only if) $$$occ(v) > occ(v')$$$ for any other number $$$v'$$$. For example, arrays $$$[1, 2, 3, 4, 5, 2]$$$, $$$[11, 11]$$$ and $$$[3, 2, 3, 2, 3]$$$ are dominated (by $$$2$$$, $$$11$$$ and $$$3$$$ respectevitely) but arrays $$$[3]$$$, $$$[1, 2]$$$ and $$$[3, 3, 2, 2, 1]$$$ are not.Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.You are given array $$$a_1, a_2, \dots, a_n$$$. Calculate its shortest dominated subarray or say that there are no such subarrays.The subarray of $$$a$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_i, a_{i + 1}, \dots, a_j$$$ for some $$$1 \le i \le j \le n$$$.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the corresponding values of the array $$$a$$$. It's guaranteed that the total length of all arrays in one test doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or $$$-1$$$ if there are no such subarrays.

NoteIn the first test case, there are no subarrays of length at least $$$2$$$, so the answer is $$$-1$$$.In the second test case, the whole array is dominated (by $$$1$$$) and it's the only dominated subarray.In the third test case, the subarray $$$a_4, a_5, a_6$$$ is the shortest dominated subarray.In the fourth test case, all subarrays of length more than one are dominated.

import std.stdio;
import std.algorithm;
import core.stdcpp.allocator;

int n;
int [int] lst;

void main() {
  int t;
  readf(" %s", &t);
  while(t-- > 0) {
    readf(" %s", &n);
    for(int i = 0; i < n; ++i) {
      lst[i] = -1;
    }
    int bst = n + 1;
    for(int i = 0; i < n; ++i) {
      int x;
      readf(" %s", &x); x--;
      if(lst[x] != -1) bst = min(bst, i - lst[x] + 1);
      lst[x] = i;
    }
    if(bst == n + 1) bst = -1;
    writefln("%s", bst);
  }
}

import std.stdio;
import std.algorithm;

void main() {
  int t;
  readf(" %s", &t);
  while(t-- > 0) {
    int n;
    readf(" %s", &n);
    int [] lst = new int[n];
    for(int i = 0; i < n; ++i) {
      lst[i] = -1;
    }
    int bst = n + 1;
    for(int i = 0; i < n; ++i) {
      int x;
      readf(" %s", &x); x--;
      if(lst[x] != -1) bst = min(bst, i - lst[x] + 1);
      lst[x] = i;
    }
    if(bst == n + 1) bst = -1;
    writefln("%s", bst);
  }
}

import std.stdio;
import std.algorithm;
import core.stdcpp.allocator;

const int N = cast(int)2e5 + 10;

int n;
int [N] lst;

void main() {
  int t;
  readf(" %s", &t);
  while(t-- > 0) {
    readf(" %s", &n);
    for(int i = 0; i < n; ++i) {
      lst[i] = -1;
    }
    int bst = n + 1;
    for(int i = 0; i < n; ++i) {
      int x;
      readf(" %s", &x); x--;
      if(lst[x] != -1) bst = min(bst, i - lst[x] + 1);
      lst[x] = i;
    }
    if(bst == n + 1) bst = -1;
    writefln("%s", bst);
  }
}

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

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 = 998244353;
//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 t = RD!int;
	auto ans = new long[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto a = RDA(-1);
		auto pos = new size_t[](n);
		pos[] = -1;
		ans[i] = long.max;
		foreach (j, e; a)
		{
			if (pos[e] != -1)
			{
				ans[i] = min(ans[i], j - pos[e] + 1);
			}
			pos[e] = j;
		}
		if (ans[i] == long.max)
			ans[i] = -1;
	}

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


Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.

If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output. If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print "Friendship" (without quotes).

NoteIn the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton".In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".

import std.stdio;
import std.string;

int main()
{
	int z=0;
	readf(" %d", &z);
	string s;
	readf(" %s", &s);
	char[] m = s.dup;
	int a=0;
	int d=0;
	for (int i=0; i<z; i++)
	{
		if (m[i]=='A')
		{
			a=a+1;
		}
		else
		{
			d=d+1;
		}
	}
	if (a>d)
	{
		writeln("Anton");
	}
	else if (d>a)
	{
		writeln("Danik");
	}
	else
	{
		writeln("Friendship");
	}
	return 0;
}


This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.

NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
/*******************************It's a Me, Mario!*******************************************/

void play(){
    int n, q;
    n = rd!int;
    q = rd!int;
    ll[] arr = rdarr;
    if(n == 1){ writeln(arr[0]); return;}
    ll[] res;
    bool side = (arr[1] > arr[0]), nside;
    if(!side){ res ~= arr[0]; }
    foreach(i; 1..n){
        if(arr[i] > arr[i-1]){
            nside = 1;
        }else{
            nside = 0;
        }
        if(nside != side){
            res ~= arr[i-1];
            side = nside;
        }
    }
    if(side){ res ~= arr[n-1]; }
    /* writeln(res); */
    ll pow = 0;
    foreach(i; 0..res.length){
        if(i % 2 == 0){
            pow += res[i];
        }else if(i != res.length-1){
            pow -= res[i];
        }
    }
    writeln(pow);
}

int main(){
    long t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

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

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

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

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

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

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

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

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

void solve()
{
    int N, Q; get(N, Q);
    long[] AS; get(AS);
    int p;
    foreach (i, a; AS) if (a == N) {
        p = i.to!int;
        break;
    }
    long sum_a = N;
    long min_a, max_a;
    void update(long a) {
        if (min_a == -1) {
            if (a < max_a) {
                sum_a += max_a;
                max_a = -1;
                min_a = a;
            } else {
                max_a = a;
            }
        } else {
            if (a > min_a) {
                sum_a -= min_a;
                min_a = -1;
                max_a = a;
            } else {
                min_a = a;
            }
        }
    }
    if (p < N-1) {
        max_a = -1; min_a = AS[p+1];
        foreach (i; p+2..N) update(AS[i]);
        if (max_a != -1) sum_a += max_a;
    }
    if (p > 0) {
        max_a = -1; min_a = AS[p-1];
        foreach_reverse (i; 0..p-1) update(AS[i]);
        if (max_a != -1) sum_a += max_a;
    }
    writeln(sum_a);
}

void main()
{
    int T; get(T);
    foreach (_; 0..T) solve();
}

import std.algorithm;
import std.container;
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, q;
		readf !(" %s %s") (n, q);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		long total = 0;

		void mark (int i, int delta)
		{
			if (i < 0 || i >= n)
			{
				return;
			}
			if ((i == 0 || a[i] > a[i - 1]) &&
			    (i == n - 1 || a[i] > a[i + 1]))
			{
				total += a[i] * delta;
			}
			if ((i > 0 && a[i] < a[i - 1]) &&
			    (i < n - 1 && a[i] < a[i + 1]))
			{
				total -= a[i] * delta;
			}
		}

		foreach (i; 0..n)
		{
			mark (i, +1);
		}
		writeln (total);
		foreach (s; 0..q)
		{
			int l, r;
			readf !(" %s %s") (l, r);
			readln;
			l -= 1;
			r -= 1;
			auto p = chain (iota (l - 1, l + 2),
			    iota (max (l + 2, r - 1), r + 2)).array;
			foreach (i; p)
			{
				mark (i, -1);
			}
			swap (a[l], a[r]);
			foreach (i; p)
			{
				mark (i, +1);
			}
			writeln (total);
		}
	}
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;

void main(string[] args)
{
  auto t = next!int;
  foreach(tc; 0 .. t)
    {
      auto n = next!int;
      auto q = next!int;
      auto a = new int[](n); foreach(ref ai; a) ai = next!int;
      assert(q == 0);
      long maxval = a[0], minval = a[0];
      long globalmax = a[0];
      foreach(ai; a[1 ..$])
	{
	  long localmax = ai;
	  if (minval < 0) localmax -= minval;
	  long localmin = ai;
	  if (maxval > 0) localmin -= maxval;
	  maxval = max(localmax, maxval);
	  minval = min(localmin, minval);
	}
      maxval.writeln;
    }
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  string toString()
  {
    return to!string(rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto next(T)()
{
  static if (is(T == int) || is(T == long) || is(T == short))
    {
      import std.ascii: isDigit;
      T res;
      while(!frontChar.isDigit)
	popChar;
      while(frontChar.isDigit)
	{
	  res *= 10;
	  res += frontChar - '0';
	  popChar;
	}
      return res;
    }
  else static if (is(T == string))
    {
      import std.ascii: isWhite;
      string res;
      while(frontChar.isWhite)
	popChar;
      while(!frontChar.isWhite)
	{
	  res ~= frontChar;
	  popChar;
	}
      return res;
    }
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto t = next!int;
  foreach(tc; 0 .. t)
    {
      auto n = next!int;
      auto q = next!int;
      auto a = next!int(n);
      assert(q == 0);
      long maxval = a[0], minval = a[0];
      long globalmax = a[0];
      foreach(ai; a[1 ..$])
	{
	  long localmax = ai;
	  if (minval < 0) localmax -= minval;
	  long localmin = ai;
	  if (maxval > 0) localmin -= maxval;
	  maxval = max(localmax, maxval);
	  minval = min(localmin, minval);
	}
      maxval.writeln;
    }
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  string toString()
  {
    return to!string(rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto dp = new long[][](n+1, 2);
		foreach (i; 0..n)
		{
			dp[i+1][0].chmax(dp[i][0]);
			dp[i+1][1].chmax(dp[i][1]);
			dp[i+1][0].chmax(dp[i][1] - a[i]);
			dp[i+1][1].chmax(dp[i][0] + a[i]);
		}
		ans[ti] = max(dp[n][0], dp[n][1]);
	}

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

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
/*******************************It's a Me, Mario!*******************************************/

void play(){
    int n, q;
    n = rd!int;
    q = rd!int;
    ll[] arr = rdarr;
    if(n == 1){ writeln(arr[0]); return;}
    ll[] res;
    bool side = (arr[1] > arr[0]), nside;
    foreach(i; 1..n){
        if(arr[i] > arr[i-1]){
            nside = 1;
        }else{
            nside = 0;
        }
        if(nside != side){
            res ~= arr[i-1];
            side = nside;
        }
    }
    if(side){ res ~= arr[n-1]; }
    /* writeln(res); */
    ll pow = 0;
    foreach(i; 0..res.length){
        if(i % 2 == 0){
            pow += res[i];
        }else if(i != res.length-1){
            pow -= res[i];
        }
    }
    writeln(pow);
}

int main(){
    long t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long[] b = [a[0]];
		foreach (i; 1..n-1)
		{
			if (a[i] < a[i-1] && a[i] < a[i+1])
				b ~= a[i];
			else if (a[i] > a[i-1] && a[i] > a[i+1])
				b ~= a[i];
		}
		b ~= a[n-1];

		int j = -1;
		foreach (i; 1..b.length)
		{
			if (b[i] > b[i-1])
			{
				ans[ti] += b[i];
				j = cast(int)i;
				break;
			}
		}

		if (j == -1)
			ans[ti] = b[0];
		else
		{
			foreach (i; j+2..b.length)
			{
				if (b[i] > b[i-1])
				{
					ans[ti] += b[i] - b[i-1];
				}
			}
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		long[] b = [a[0]];
		foreach (i; 1..n-1)
		{
			if (a[i] <= a[i-1] && a[i] <= a[i+1])
				b ~= a[i];
			else if (a[i] >= a[i-1] && a[i] >= a[i+1])
				b ~= a[i];
		}
		b ~= a[n-1];

		if (b.length >= 2)
		{
			if (b[0] >= b[1])
				ans[ti] += b[0];
		}
		int j = -1;
		foreach (i; 1..b.length)
		{
			if (b[i] > b[i-1])
			{
				ans[ti] += b[i];
				j = cast(int)i;
				break;
			}
		}

		if (j == -1)
			ans[ti] = b[0];
		else
		{
			foreach (i; j+2..b.length)
			{
				if (b[i] > b[i-1])
				{
					ans[ti] += b[i] - b[i-1];
				}
			}
		}
	}

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


You are given a tree that consists of $$$n$$$ nodes. You should label each of its $$$n-1$$$ edges with an integer in such way that satisfies the following conditions:   each integer must be greater than $$$0$$$;  the product of all $$$n-1$$$ numbers should be equal to $$$k$$$;  the number of $$$1$$$-s among all $$$n-1$$$ integers must be minimum possible. Let's define $$$f(u,v)$$$ as the sum of the numbers on the simple path from node $$$u$$$ to node $$$v$$$. Also, let $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $$$10^9 + 7$$$.In this problem, since the number $$$k$$$ can be large, the result of the prime factorization of $$$k$$$ is given instead.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines describes an edge: the $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — indices of vertices connected by the $$$i$$$-th edge. Next line contains a single integer $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — the number of prime factors of $$$k$$$. Next line contains $$$m$$$ prime numbers $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i < 6 \cdot 10^4$$$) such that $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$, the sum of $$$m$$$ over all test cases doesn't exceed $$$6 \cdot 10^4$$$, and the given edges for each test cases form a tree.

Print the maximum distribution index you can get. Since answer can be too large, print it modulo $$$10^9+7$$$.

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

immutable int mod = 10 ^^ 9 + 7;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto adj = new int [] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}
		readln;
		auto m = readln.strip.to !(int);
		auto q = readln.splitter.map !(to !(int)).array;

		sort (q);
		while (q.length > n - 1)
		{
			q[$ - 2] = (q[$ - 2] * 1L * q[$ - 1]) % mod;
			q.length -= 1;
		}
		reverse (q);
		while (q.length < n - 1)
		{
			q ~= 1;
		}

		auto d = new int [n];
		long [] nums;

		void recur (int v, int p)
		{
			d[v] = 1;
			foreach (u; adj[v])
			{
				if (u != p)
				{
					recur (u, v);
					nums ~= d[u] * 1L * (n - d[u]);
					d[v] += d[u];
				}
			}
		}

		recur (0, -1);
		sort (nums);
		reverse (nums);
		nums[] %= mod;

		int res = 0;
		foreach (i; 0..n - 1)
		{
			res = (res + nums[i] * q[i]) % mod;
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto edges = new int[][](n);
		foreach (i; 0..n-1)
		{
			auto u = RD!int-1;
			auto v = RD!int-1;
			edges[u] ~= v;
			edges[v] ~= u;
		}
		auto m = RD!int;
		auto p = RDA;
		p.sort!"a > b"();
		while (p.length > n-1)
		{
			p[1].modm(p[0]);
			p.popFront;
		}

		long[] list;
		long dfs(int pos, int last)
		{
			long cnt;
			foreach (v; edges[pos])
			{
				if (v == last) continue;
				cnt += dfs(v, pos);
			}
			++cnt;
			auto x = cnt;
			x *= (n-cnt);
			list ~= x;
			return cnt;
		}
		dfs(0, -1);
		list.sort!"a > b"();
		debug writeln(list);

		foreach (i; 0..n-1)
		{
			long pp = 1;
			if (!p.empty)
			{
				pp = p.front; p.popFront;
			}
			pp.modm(list[i]);
			ans[ti].moda(pp);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto edges = new int[][](n);
		foreach (i; 0..n-1)
		{
			auto u = RD!int-1;
			auto v = RD!int-1;
			edges[u] ~= v;
			edges[v] ~= u;
		}
		auto m = RD!int;
		auto p = RDA;
		p.sort!"a > b"();

		long[] list;
		int dfs(int pos, int last)
		{
			int cnt;
			foreach (v; edges[pos])
			{
				if (v == last) continue;
				cnt += dfs(v, pos);
			}
			++cnt;
			list ~= cnt * (n-cnt);
			return cnt;
		}
		dfs(0, -1);
		list.sort!"a > b"();

		foreach (i; 0..n-1)
		{
			long pp = 1;
			if (!p.empty)
			{
				pp = p.front; p.popFront;
			}
			pp *= list[i];
			ans[ti].moda(pp);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto edges = new int[][](n);
		foreach (i; 0..n-1)
		{
			auto u = RD!int-1;
			auto v = RD!int-1;
			edges[u] ~= v;
			edges[v] ~= u;
		}
		auto m = RD!int;
		auto p = RDA;
		p.sort!"a > b"();

		long[] list;
		long dfs(int pos, int last)
		{
			long cnt;
			foreach (v; edges[pos])
			{
				if (v == last) continue;
				cnt += dfs(v, pos);
			}
			++cnt;
			list ~= cnt * (n-cnt);
			return cnt;
		}
		dfs(0, -1);
		list.sort!"a > b"();

		foreach (i; 0..n-1)
		{
			long pp = 1;
			if (!p.empty)
			{
				pp = p.front; p.popFront;
			}
			pp *= list[i];
			ans[ti].moda(pp);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto edges = new int[][](n);
		foreach (i; 0..n-1)
		{
			auto u = RD!int-1;
			auto v = RD!int-1;
			edges[u] ~= v;
			edges[v] ~= u;
		}
		auto m = RD!int;
		auto p = RDA;
		p.sort!"a > b"();
		while (p.length > n-1)
		{
			p[1].modm(p[0]);
			p.popFront;
		}

		long[] list;
		long dfs(int pos, int last)
		{
			long cnt;
			foreach (v; edges[pos])
			{
				if (v == last) continue;
				cnt += dfs(v, pos);
			}
			++cnt;
			auto x = cnt;
			x.modm(n-cnt);
			list ~= x;
			return cnt;
		}
		dfs(0, -1);
		list.sort!"a > b"();
		debug writeln(list);

		foreach (i; 0..n-1)
		{
			long pp = 1;
			if (!p.empty)
			{
				pp = p.front; p.popFront;
			}
			pp.modm(list[i]);
			ans[ti].moda(pp);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto edges = new int[][](n);
		foreach (i; 0..n-1)
		{
			auto u = RD!int-1;
			auto v = RD!int-1;
			edges[u] ~= v;
			edges[v] ~= u;
		}
		auto m = RD!int;
		auto p = RDA;
		p.sort!"a > b";

		long[] list;
		int dfs(int pos, int last)
		{
			int cnt;
			foreach (v; edges[pos])
			{
				if (v == last) continue;
				cnt += dfs(v, pos);
			}
			++cnt;
			list ~= cnt * (n-cnt);
			return cnt;
		}
		dfs(0, -1);
		list.sort!"a > b"();

		foreach (i; 0..n-1)
		{
			long pp = 1;
			if (!p.empty)
			{
				pp = p.front; p.popFront;
			}
			pp.modm(list[i]);
			ans[ti].moda(pp);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto edges = new int[][](n);
		foreach (i; 0..n-1)
		{
			auto u = RD!int-1;
			auto v = RD!int-1;
			edges[u] ~= v;
			edges[v] ~= u;
		}
		auto m = RD!int;
		auto p = RDA;
		p.sort!"a > b"();

		long[] list;
		long dfs(int pos, int last)
		{
			long cnt;
			foreach (v; edges[pos])
			{
				if (v == last) continue;
				cnt += dfs(v, pos);
			}
			++cnt;
			list ~= cnt * (n-cnt);
			return cnt;
		}
		dfs(0, -1);
		list.sort!"a > b"();

		foreach (i; 0..n-1)
		{
			long pp = 1;
			if (!p.empty)
			{
				pp = p.front; p.popFront;
			}
			pp.modm(list[i]);
			ans[ti].moda(pp);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto edges = new int[][](n);
		foreach (i; 0..n-1)
		{
			auto u = RD!int-1;
			auto v = RD!int-1;
			edges[u] ~= v;
			edges[v] ~= u;
		}
		auto m = RD!int;
		auto p = RDA;
		p.sort!"a > b"();

		long[] list;
		long dfs(int pos, int last)
		{
			long cnt;
			foreach (v; edges[pos])
			{
				if (v == last) continue;
				cnt += dfs(v, pos);
			}
			++cnt;
			auto x = cnt;
			x.modm(n-cnt);
			list ~= x;
			return cnt;
		}
		dfs(0, -1);
		list.sort!"a > b"();
		debug writeln(list);

		foreach (i; 0..n-1)
		{
			long pp = 1;
			if (!p.empty)
			{
				pp = p.front; p.popFront;
			}
			pp.modm(list[i]);
			ans[ti].moda(pp);
		}
	}

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


On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:   the sum of the costs of stuck pins;  the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.

The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.

Output the single number — the least fine you will have to pay.

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

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

    struct pt {
        int x, c;
        int opCmp(ref const pt p2) const {
            return x - p2.x;
        }
    }

    auto pts = new pt[] (n);
    foreach (i; 0 .. n) {
        readf("%s %s", &pts[i].x, &pts[i].c);
        readln;
    }

    pts.sort();

    debug { pts.writeln; }

    immutable long INF = 10L ^^ 18;
    auto dp = new long[][] (n, n+1);
    foreach (ref rw; dp) { rw[] = INF; }
    dp[n-1][0] = pts[n-1].c;
    dp[n-1][1] = 0;
    int done = 1;
    foreach_reverse (i; 0 .. n-1) {
        debug { i.writeln; }
        int dst = pts[i+1].x - pts[i].x;
        foreach (j; 0 .. done + 1) {
            dp[i][0] = min(dp[i][0], pts[i].c + dp[i+1][j] + dst.to!long * j);
        }

        foreach (k; 1 .. done + 2) {
            dp[i][k] = dp[i+1][k-1] + dst.to!long * (k-1);
        }

        ++done;
    }

    debug {
        foreach (rw; dp) {
            rw.writefln!"%(%s %)";
        }
    }

    dp[0][0].writeln;
}

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

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

    struct pt {
        int x, c;
        int opCmp(ref const pt p2) const {
            return x - p2.x;
        }
    }

    auto pts = new pt[] (n);
    foreach (i; 0 .. n) {
        readf("%s %s", &pts[i].x, &pts[i].c);
        readln;
    }

    pts.sort();

    debug { pts.writeln; }

    immutable long INF = 10L ^^ 18;
    auto dp = new long[][] (n, n);
    foreach (ref rw; dp) { rw[] = INF; }
    dp[n-1][0] = pts[n-1].c;
    dp[n-1][1] = 0;
    int done = 1;
    foreach_reverse (i; 0 .. n-1) {
        debug { i.writeln; }
        int dst = pts[i+1].x - pts[i].x;
        foreach (j; 0 .. done + 1) {
            dp[i][0] = min(dp[i][0], pts[i].c + dp[i+1][j] + dst.to!long * j);
        }

        foreach (k; 1 .. done + 1) {
            dp[i][k] = dp[i+1][k-1] + dst.to!long * (k-1);
        }

        ++done;
    }

    debug {
        foreach (rw; dp) {
            rw.writefln!"%(%s %)";
        }
    }

    dp[0][0].writeln;
}