In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor.To begin with friends learned the rules: in the race there are n sections of equal length and m participants. The participants numbered from 1 to m. About each participant the following is known: li — the number of the starting section,  ri — the number of the finishing section (li ≤ ri), ti — the time a biathlete needs to complete an section of the path, ci — the profit in roubles. If the i-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman. The i-th biathlete passes the sections from li to ri inclusive. The competitor runs the whole way in (ri - li + 1)·ti time units. It takes him exactly ti time units to pass each section. In case of the athlete's victory on k sections the man who has betted on him receives k·ci roubles.In each section the winner is determined independently as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed.We should also add that Nikita can bet on each section and on any contestant running in this section.Help the friends find the maximum possible profit.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). Then follow m lines, each containing 4 integers li, ri, ti, ci (1 ≤ li ≤ ri ≤ n, 1 ≤ ti, ci ≤ 1000).

Print a single integer, the maximal profit in roubles that the friends can get. In each of n sections it is not allowed to place bets on more than one sportsman.

NoteIn the first test the optimal bet is: in the 1-2 sections on biathlete 1, in section 3 on biathlete 3, in section 4 on biathlete 4. Total: profit of 5 rubles for 1 section, the profit of 5 rubles for 2 section, profit of 30 rubles for a 3 section, profit of 20 rubles for 4 section. Total profit 60 rubles.In the second test the optimal bet is: on 1 and 5 sections on biathlete 1, in the 2-4 sections on biathlete 2, in the 6-7 sections on athlete 4. There is no winner in the 8 section. Total: profit of 10 rubles for 1 section, the profit of 15 rubles for 2,3,4 section, profit of 10 rubles for a 5 section, profit of 20 rubles for 6, 7 section. Total profit 105 rubles.

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

struct Player {
        int l;
        int r;
        int t;
        int c;
        bool[101] track = false;
}

void main() {
        IO cin;
        int n_Cases = 1;
        // n_Cases = cin.readInt;

	for (int case_i = 1; case_i <= n_Cases; case_i++) {
                int n = cin.readInt;
                int m = cin.readInt;
                Player[] p = new Player[m];
                for (int i = 0; i < m; i++) {
                        p[i].l = cin.readInt;
                        p[i].r = cin.readInt;
                        p[i].t = cin.readInt;
                        p[i].c = cin.readInt;
                        for (int t = p[i].l; t <= p[i].r; t++) {
                                p[i].track[t] = true;
                        }
                }
                int profit = 0;
                for (int i = 1; i <= n; i++) {
                        int minTime = 99999;
                        int bestPlayer = 0;
                        bool found = false;
                        for (int j = 0; j < m; j++) {
                                if (p[j].track[i] && minTime > p[j].t) {
                                        minTime = p[j].t;
                                        bestPlayer = j;
                                        found = true;
                                }
                        }
                        if (found) profit += p[bestPlayer].c;
                }
                writeln(profit);
        }
}


Hr0d1y has $$$q$$$ queries on a binary string $$$s$$$ of length $$$n$$$. A binary string is a string containing only characters '0' and '1'.A query is described by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \leq l_i \lt r_i \leq n)$$$. For each query, he has to determine whether there exists a good subsequence in $$$s$$$ that is equal to the substring $$$s[l_i\ldots r_i]$$$.   A substring $$$s[i\ldots j]$$$ of a string $$$s$$$ is the string formed by characters $$$s_i s_{i+1} \ldots s_j$$$. String $$$a$$$ is said to be a subsequence of string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some characters without changing the order of the remaining characters. A subsequence is said to be good if it is not contiguous and has length $$$\ge 2$$$. For example, if $$$s$$$ is "1100110", then the subsequences $$$s_1s_2s_4$$$ ("1100110") and $$$s_1s_5s_7$$$ ("1100110") are good, while $$$s_1s_2s_3$$$ ("1100110") is not good. Can you help Hr0d1y answer each query?

The first line of the input contains a single integer $$$t$$$ ($$$1\leq t \leq 100$$$) — the number of test cases. The description of each test case is as follows. The first line contains two integers $$$n$$$ ($$$2 \leq n \leq 100$$$) and $$$q$$$ ($$$1\leq q \leq 100$$$) — the length of the string and the number of queries.  The second line contains the string $$$s$$$. The $$$i$$$-th of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \leq l_i \lt r_i \leq n$$$).

For each test case, output $$$q$$$ lines. The $$$i$$$-th line of the output of each test case should contain "YES" if there exists a good subsequence equal to the substring $$$s[l_i...r_i]$$$, and "NO" otherwise. You may print each letter in any case (upper or lower).

NoteIn the first test case,   $$$s[2\ldots 4] = $$$ "010". In this case $$$s_1s_3s_5$$$ ("001000") and $$$s_2s_3s_6$$$ ("001000") are good suitable subsequences, while $$$s_2s_3s_4$$$ ("001000") is not good.  $$$s[1\ldots 3] = $$$ "001". No suitable good subsequence exists.  $$$s[3\ldots 5] = $$$ "100". Here $$$s_3s_5s_6$$$ ("001000") is a suitable good subsequence.

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

// Main Logic Here
void play(){
    int n, q;
    n = rd!int; q = rd!int;
    dchar[] arr = rd!(dchar[]);
    auto before = new ll[2][n+1];
    auto after = new ll[2][n+1];
    bool is1 = 0, is0 = 0;

    foreach(i; 0..n){
        before[i][0] = is0;
        before[i][1] = is1;
        is0 = (arr[i] == '0' || is0);
        is1 = (arr[i] == '1' || is1);
    }
    is1 = 0; is0 = 0;
    foreach_reverse(i; 0..n){
        after[i][0] = is0;
        after[i][1] = is1;
        is0 = (arr[i] == '0' || is0);
        is1 = (arr[i] == '1' || is1);
    }
    show(before);
    show(after);
    while(q--){
        int l = rd!int;
        int r = rd!int;
        show(l, r);
        if(before[l-1][to!int(arr[l-1] - '0')] || after[r-1][to!int(arr[r-1] - '0')]){
            writeln("YES");
        }else{
            writeln("NO");
        }
    }
}

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

/**********That's All Folks!**********/
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;    // Read input
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; }
alias ll = long;
alias tup = Tuple!(long, "x",  long, "y");
void show(A...)(A a) { debug{ foreach(t; a){ stderr.write(t, "| "); } stderr.writeln; } } // Debug
/* Add if TLE, T max(T = long)(T a, T b){ return (a > b) ? a : b; } */

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto q = RD!int;
		auto s = RD!string;
		ans[ti].length = q;
		foreach (i; 0..q)
		{
			auto l = RD!int-1;
			auto r = RD!int-1;
			bool ok;
			foreach (j; 0..l)
			{
				if (s[j] == s[l])
				{
					ok = true;
					break;
				}
			}
			foreach (j; r+1..n)
			{
				if (s[j] == s[r])
				{
					ok = true;
					break;
				}
			}
			ans[ti][i] = ok;
		}
	}

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

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

// Main Logic Here
void play(){
    int n, q;
    n = rd!int; q = rd!int;
    dchar[] arr = rd!(dchar[]);
    auto before = new ll[2][n+1];
    auto after = new ll[2][n+1];
    bool is1 = 0, is0 = 0;

    foreach(i; 0..n){
        before[i][0] = is0;
        before[i][1] = is1;
        is0 = (arr[i] == '0' || is0);
        is1 = (arr[i] == '1' || is1);
    }
    is1 = 0; is0 = 1;
    foreach_reverse(i; 0..n){
        after[i][0] = is0;
        after[i][1] = is1;
        is0 = (arr[i] == '0' || is0);
        is1 = (arr[i] == '1' || is1);
    }
    show(before);
    show(after);
    while(q--){
        int l = rd!int;
        int r = rd!int;
        show(l, r);
        if(before[l-1][to!int(arr[l-1] - '0')] || after[r-1][to!int(arr[r-1] - '0')]){
            writeln("YES");
        }else{
            writeln("NO");
        }
    }
}

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

/**********That's All Folks!**********/
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;    // Read input
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; }
alias ll = long;
alias tup = Tuple!(long, "x",  long, "y");
void show(A...)(A a) { debug{ foreach(t; a){ stderr.write(t, "| "); } stderr.writeln; } } // Debug
/* Add if TLE, T max(T = long)(T a, T b){ return (a > b) ? a : b; } */


A tree is an undirected graph with exactly one simple path between each pair of vertices. We call a set of simple paths $$$k$$$-valid if each vertex of the tree belongs to no more than one of these paths (including endpoints) and each path consists of exactly $$$k$$$ vertices.You are given a tree with $$$n$$$ vertices. For each $$$k$$$ from $$$1$$$ to $$$n$$$ inclusive find what is the maximum possible size of a $$$k$$$-valid set of simple paths.

The first line of the input contains a single integer $$$n$$$ ($$$2 \le n \le 100\,000$$$) — the number of vertices in the tree. Then following $$$n - 1$$$ lines describe the tree, each of them contains two integers $$$v$$$, $$$u$$$ ($$$1 \le v, u \le n$$$) — endpoints of the corresponding edge. It is guaranteed, that the given graph is a tree.

Output $$$n$$$ numbers, the $$$i$$$-th of which is the maximum possible number of paths in an $$$i$$$-valid set of paths.

NoteOne way to achieve the optimal number of paths for the second sample is illustrated in the following picture:

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

immutable int NA = -1;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
		}

		auto c = new int [] [n];
		int [] order;

		void recurBuild (int v, int p)
		{
			foreach (u; a[v])
			{
				if (u != p)
				{
					recurBuild (u, v);
					c[v] ~= u;
				}
			}
			order ~= v;
		}

		recurBuild (0, NA);

		auto ans = new int [n + 1];
		ans[] = NA;

		alias Record = Tuple !(int, q{paths}, int, q{depth});
		auto r = new Record [n];
		int k;

		void doCalc ()
		{
			foreach (v; order)
			{
				if (c[v].length == 1)
				{
					r[v] = r[c[v][0]];
					r[v].depth += 1;
					if (r[v].depth >= k)
					{
						r[v].paths += 1;
						r[v].depth = 0;
					}
					continue;
				}
				int max1 = 0;
				int max2 = 0;
				int totalPaths = 0;
				foreach (u; c[v])
				{
					with (r[u])
					{
						totalPaths += paths;
						if (max1 < depth)
						{
							max2 = max1;
							max1 = depth;
						}
						else if (max2 < depth)
						{
							max2 = depth;
						}
					}
				}
				int max3 = max1 + max2 + 1;
				if (max3 >= k)
				{
					totalPaths += 1;
					max1 = -1;
				}
				r[v] = Record (totalPaths, max1 + 1);
			}
		}

		void calcAns (int k)
		{
			debug {writeln ("calc ", k); stdout.flush ();}
			if (ans[k] == NA)
			{
				doCalc ();
				ans[k] = r[0].paths;
			}
		}

		int prev = 0;
		int step = 1;
		int maxStep = 1;
		k = 1;
		while (k <= n)
		{
			calcAns (k);
			if (ans[k] == ans[prev])
			{
				step *= 2;
				maxStep = max (maxStep, step);
				prev = k;
				k = prev + step;
				k = min (k, n + (prev == n));
			}
			else if (step > 1)
			{
				step /= 2;
				k = prev + step;
				k = min (k, n + (prev == n));
			}
			else
			{
				step = max (1, maxStep / 2);
				prev = k;
				k = prev + step;
			}
		}

		ans[n] = max (ans[n], 0);
		foreach (i; 2..n + 1)
		{
			if (ans[i] == NA)
			{
				ans[i] = ans[i - 1];
			}
		}

		foreach (i; 1..n + 1)
		{
			writeln (ans[i]);
		}
	}
}


You have a rooted tree consisting of n vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to n. Then we represent the color of vertex v as cv. The tree root is a vertex with number 1.In this problem you need to answer to m queries. Each query is described by two integers vj, kj. The answer to query vj, kj is the number of such colors of vertices x, that the subtree of vertex vj contains at least kj vertices of color x.You can find the definition of a rooted tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory).

The first line contains two integers n and m (2 ≤ n ≤ 105; 1 ≤ m ≤ 105). The next line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105). The next n - 1 lines contain the edges of the tree. The i-th line contains the numbers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the vertices connected by an edge of the tree. Next m lines contain the queries. The j-th line contains two integers vj, kj (1 ≤ vj ≤ n; 1 ≤ kj ≤ 105).

Print m integers — the answers to the queries in the order the queries appear in the input.

NoteA subtree of vertex v in a rooted tree with root r is a set of vertices {u : dist(r, v) + dist(v, u) = dist(r, u)}. Where dist(x, y) is the length (in edges) of the shortest path between vertices x and y.

import std.stdio;

int n, m;

int[] col;
int[][] edge, child;
int[2][][] query;

int size[];
void root(int u) {
    size[u] = 1;
    foreach(v; edge[u]) {
        if (size[v] == 0) {
            child[u] ~= v;
            root(v);
            size[u] += size[v];
        }
    }
}

int[][] least, num, cols;
void add(int lv, int c, bool rt) {
    ++least[lv][++num[lv][c]];
    cols[lv].assumeSafeAppend;
    cols[lv] ~= c;
    if (!rt) --least[lv+1][num[lv+1][c]--];
}

int[] ans;
void dfs(int u, int lv) {
    int maxv = -1;
    foreach(v; child[u]) {
        if (maxv == -1 || size[v] > size[maxv]) {
            maxv = v;
        }
    }

    if (maxv != -1) {
        dfs(maxv, lv);
        foreach(v; child[u]) {
            if (v == maxv) continue;
            dfs(v, lv+1);
            foreach(c; cols[lv+1]) {
                add(lv, c, false);
            }
            cols[lv+1].length = 0;
        }
    }
    add(lv, col[u], true);

    foreach(q; query[u]) {
        ans[q[0]] = q[1] > n ? 0 : least[lv][q[1]];
    }
}

void main() {
    readf(" %d %d", &n, &m);

    col = new int[](n);
    foreach(i; 0..n) {
        readf(" %d", &col[i]);
        --col[i];
    }

    edge = new int[][](n, 0);
    foreach(i; 0..n-1) {
        int a, b;
        readf(" %d %d", &a, &b);
        --a, --b;

        edge[a] ~= b;
        edge[b] ~= a;
    }

    query = new int[2][][](n, 0);
    foreach(i; 0..m) {
        int v, k;
        readf(" %d %d", &v, &k);
        --v;

        query[v] ~= [i, k];
    }

    child = new int[][](n, 0);
    size = new int[](n);
    root(0);

    int log = 1;
    while (1 << log < n) { ++log; }

    least = new int[][](log, n+1);
    num = new int[][](log, 10^^5);
    cols = new int[][](log, 0);

    ans = new int[](m);
    dfs(0, 0);

    foreach(a; ans) {
        writeln(a);
    }
}

import std.stdio;

int n, m;

int[] col;
int[][] edge, child;
int[2][][] query;

int size[];
void root(int u) {
    size[u] = 1;
    foreach(v; edge[u]) {
        if (size[v] == 0) {
            child[u] ~= v;
            root(v);
            size[u] += size[v];
        }
    }
}

int[][] least, num, cols;
void add(int lv, int c, bool rt) {
    ++least[lv][++num[lv][c]];
    cols[lv] ~= c;
    if (!rt) --least[lv+1][num[lv+1][c]--];
}

int[] ans;
void dfs(int u, int lv) {
    int maxv = -1;
    foreach(v; child[u]) {
        if (maxv == -1 || size[v] > size[maxv]) {
            maxv = v;
        }
    }

    if (maxv != -1) {
        dfs(maxv, lv);
        foreach(v; child[u]) {
            if (v == maxv) continue;
            dfs(v, lv+1);
            foreach(c; cols[lv+1]) {
                add(lv, c, false);
            }
            cols[lv+1].length = 0;
        }
    }
    add(lv, col[u], true);

    foreach(q; query[u]) {
        ans[q[0]] = q[1] > n ? 0 : least[lv][q[1]];
    }
}

void main() {
    readf(" %d %d", &n, &m);

    col = new int[](n);
    foreach(i; 0..n) {
        readf(" %d", &col[i]);
        --col[i];
    }

    edge = new int[][](n, 0);
    foreach(i; 0..n-1) {
        int a, b;
        readf(" %d %d", &a, &b);
        --a, --b;

        edge[a] ~= b;
        edge[b] ~= a;
    }

    query = new int[2][][](n, 0);
    foreach(i; 0..m) {
        int v, k;
        readf(" %d %d", &v, &k);
        --v;

        query[v] ~= [i, k];
    }

    child = new int[][](n, 0);
    size = new int[](n);
    root(0);

    int lg = 0;
    while (1 << lg <= n) ++lg;

    least = new int[][](lg, n+1);
    num = new int[][](lg, 10^^5);
    cols = new int[][](lg, 0);

    ans = new int[](m);
    dfs(0, 0);

    foreach(a; ans) {
        writeln(a);
    }
}

import std.stdio;

int n, m;

int[] col;
int[][] edge, child;
int[2][][] query;

int size[];
void root(int u) {
    size[u] = 1;
    foreach(v; edge[u]) {
        if (size[v] == 0) {
            child[u] ~= v;
            root(v);
            size[u] += size[v];
        }
    }
}

int[][] least, num, cols;
void add(int lv, int c, bool rt) {
    ++least[lv][++num[lv][c]];
    cols[lv] ~= c;
    if (!rt) --least[lv+1][num[lv+1][c]--];
}

int[] ans;
void dfs(int u, int lv) {
    int maxv = -1;
    foreach(v; child[u]) {
        if (maxv == -1 || size[v] > size[maxv]) {
            maxv = v;
        }
    }

    if (maxv != -1) {
        dfs(maxv, lv);
        foreach(v; child[u]) {
            if (v == maxv) continue;
            dfs(v, lv+1);
            foreach(c; cols[lv+1]) {
                add(lv, c, false);
            }
            cols[lv+1].length = 0;
        }
    }
    add(lv, col[u], true);

    foreach(q; query[u]) {
        ans[q[0]] = q[1] > n ? 0 : least[lv][q[1]];
    }
}

void main() {
    readf(" %d %d", &n, &m);

    col = new int[](n);
    foreach(i; 0..n) {
        readf(" %d", &col[i]);
        --col[i];
    }

    edge = new int[][](n, 0);
    foreach(i; 0..n-1) {
        int a, b;
        readf(" %d %d", &a, &b);
        --a, --b;

        edge[a] ~= b;
        edge[b] ~= a;
    }

    query = new int[2][][](n, 0);
    foreach(i; 0..m) {
        int v, k;
        readf(" %d %d", &v, &k);
        --v;

        query[v] ~= [i, k];
    }

    child = new int[][](n, 0);
    size = new int[](n);
    root(0);

    int log = 1;
    while (1 << log < n) { ++log; }

    least = new int[][](log, n+1);
    num = new int[][](log, 10^^5);
    cols = new int[][](log, 0);

    ans = new int[](m);
    dfs(0, 0);

    foreach(a; ans) {
        writeln(a);
    }
}

import std.stdio;

int n, m;

int[] col;
int[][] edge, child;
int[2][][] query;

int size[];
void root(int u) {
    size[u] = 1;
    foreach(v; edge[u]) {
        if (size[v] == 0) {
            child[u] ~= v;
            root(v);
            size[u] += size[v];
        }
    }
}

int[][] least, num, cols;
void add(int lv, int c, bool rt) {
    ++least[lv][++num[lv][c]];
    cols[lv].assumeSafeAppend;
    cols[lv] ~= c;
    if (!rt) --least[lv+1][num[lv+1][c]--];
}

int[] ans;
void dfs(int u, int lv) {
    if (child[u] !is null) {
        int maxv = -1;
        foreach(v; child[u]) {
            if (maxv == -1 || size[v] > size[maxv]) {
                maxv = v;
            }
        }

        dfs(maxv, lv);
        foreach(v; child[u]) {
            if (v == maxv) continue;
            dfs(v, lv+1);
            foreach(c; cols[lv+1]) {
                add(lv, c, false);
            }
            cols[lv+1].length = 0;
        }
    }
    add(lv, col[u], true);

    foreach(q; query[u]) {
        ans[q[0]] = least[lv][q[1]];
    }
}

void main() {
    readf(" %d %d", &n, &m);

    col = new int[](n);
    foreach(i; 0..n) {
        readf(" %d", &col[i]);
        --col[i];
    }

    edge = new int[][](n, 0);
    foreach(i; 0..n-1) {
        int a, b;
        readf(" %d %d", &a, &b);
        --a, --b;

        edge[a] ~= b;
        edge[b] ~= a;
    }

    query = new int[2][][](n, 0);
    foreach(i; 0..m) {
        int v, k;
        readf(" %d %d", &v, &k);
        --v;

        query[v] ~= [i, k];
    }

    child = new int[][](n, 0);
    size = new int[](n);
    root(0);

    int log = 1;
    while (1 << log < n) { ++log; }

    least = new int[][](log, n+1);
    num = new int[][](log, 10^^5);
    cols = new int[][](log, 0);

    ans = new int[](m);
    dfs(0, 0);

    foreach(a; ans) {
        writeln(a);
    }
}


Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $$$(x_1,y_1)$$$ to the point $$$(x_2,y_2)$$$.He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly $$$1$$$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $$$1$$$ unit.   For example, if the box is at the point $$$(1,2)$$$ and Wabbit is standing at the point $$$(2,2)$$$, he can pull the box right by $$$1$$$ unit, with the box ending up at the point $$$(2,2)$$$ and Wabbit ending at the point $$$(3,2)$$$.Also, Wabbit can move $$$1$$$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $$$1$$$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes $$$1$$$ second to travel $$$1$$$ unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$. Note that the point where Wabbit ends up at does not matter.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$: the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains four space-separated integers $$$x_1, y_1, x_2, y_2$$$ $$$(1 \leq x_1, y_1, x_2, y_2 \leq 10^9)$$$, describing the next test case.

For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$.

NoteIn the first test case, the starting and the ending points of the box are $$$(1,2)$$$ and $$$(2,2)$$$ respectively. This is the same as the picture in the statement. Wabbit needs only $$$1$$$ second to move as shown in the picture in the statement.In the second test case, Wabbit can start at the point $$$(2,1)$$$. He pulls the box to $$$(2,1)$$$ while moving to $$$(3,1)$$$. He then moves to $$$(3,2)$$$ and then to $$$(2,2)$$$ without pulling the box. Then, he pulls the box to $$$(2,2)$$$ while moving to $$$(2,3)$$$. It takes $$$4$$$ seconds.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int x1, y1, x2, y2;
		readf !(" %s %s %s %s") (x1, y1, x2, y2);
		writeln (abs (x1 - x2) + abs (y1 - y2) +
		    2 * (x1 != x2 && y1 != y2));
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto x1 = RD!int;
		auto y1 = RD!int;
		auto x2 = RD!int;
		auto y2 = RD!int;

		ans[ti] = abs(x1-x2) + abs(y1-y2);
		if (x1 != x2 && y1 != y2)
			ans[ti] += 2;
	}

	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}


You are given a simple weighted connected undirected graph, consisting of $$$n$$$ vertices and $$$m$$$ edges.A path in the graph of length $$$k$$$ is a sequence of $$$k+1$$$ vertices $$$v_1, v_2, \dots, v_{k+1}$$$ such that for each $$$i$$$ $$$(1 \le i \le k)$$$ the edge $$$(v_i, v_{i+1})$$$ is present in the graph. A path from some vertex $$$v$$$ also has vertex $$$v_1=v$$$. Note that edges and vertices are allowed to be included in the path multiple times.The weight of the path is the total weight of edges in it.For each $$$i$$$ from $$$1$$$ to $$$q$$$ consider a path from vertex $$$1$$$ of length $$$i$$$ of the maximum weight. What is the sum of weights of these $$$q$$$ paths?Answer can be quite large, so print it modulo $$$10^9+7$$$.

The first line contains a three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$2 \le n \le 2000$$$; $$$n - 1 \le m \le 2000$$$; $$$m \le q \le 10^9$$$) — the number of vertices in the graph, the number of edges in the graph and the number of lengths that should be included in the answer. Each of the next $$$m$$$ lines contains a description of an edge: three integers $$$v$$$, $$$u$$$, $$$w$$$ ($$$1 \le v, u \le n$$$; $$$1 \le w \le 10^6$$$) — two vertices $$$v$$$ and $$$u$$$ are connected by an undirected edge with weight $$$w$$$. The graph contains no loops and no multiple edges. It is guaranteed that the given edges form a connected graph.

Print a single integer — the sum of the weights of the paths from vertex $$$1$$$ of maximum weights of lengths $$$1, 2, \dots, q$$$ modulo $$$10^9+7$$$.

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

immutable int mod = 10 ^^ 9 + 7;

void main ()
{
	int n, m, q;
	while (readf !(" %s %s %s") (n, m, q) > 0)
	{
		auto d = new long [n];
		alias Edge = Tuple !(int, q{u}, int, q{v}, int, q{w});
		auto e = new Edge [m];
		foreach (j; 0..m)
		{
			int u, v, w;
			readf !(" %s %s %s") (u, v, w);
			u -= 1;
			v -= 1;
			e ~= Edge (u, v, w);
			d[u] = max (d[u], w);
			d[v] = max (d[v], w);
		}

		long res = 0;
		auto cur = new long [] [] (2, n);
		int b = 0;
		cur[b][] = long.min;
		cur[b][0] = 0;
		int oldQ = q;
		while (q > 0 && oldQ - q <= 2000)
		{
			b ^= 1;
			cur[b][] = long.min;
			foreach (ref edge; e)
			{
				cur[b][edge.v] = max (cur[b][edge.v],
				    cur[!b][edge.u] + edge.w);
				cur[b][edge.u] = max (cur[b][edge.u],
				    cur[!b][edge.v] + edge.w);
			}
			res = (res + cur[b].maxElement) % mod;
			q -= 1;
		}

		auto p = n.iota.array;
		while (q > 0)
		{
			makeIndex (cur[b], p);
			b ^= 1;
			int lo = 1;
			int hi = q;
			while (lo < hi)
			{
				int me = (lo + hi) / 2;
				cur[b][] = cur[!b][] + d[] * me;
				if (cur[b].countUntil (cur[b].maxElement) ==
				    cur[!b].countUntil (cur[!b].maxElement))
				{
					lo = me + 1;
				}
				else
				{
					hi = me;
				}
			}
			debug {writeln ("q = ", q, ", lo = ", lo);}
			long top = cur[!b].maxElement;
			long add = top % mod;
			int pos = cur[!b].countUntil (top).to !(int);
			long arithm = ((lo - 0L) * (lo - 1L) / 2) % mod;
			res = (res + add * (lo - 1L)) % mod;
			res = (res + d[pos] * arithm) % mod;
			cur[b][] = cur[!b][] + d[] * lo;
			res = (res + cur[b].maxElement) % mod;
			q -= lo;
		}
		writeln (res);
	}
}


You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!   Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$, $$$1 \le x \le 10^9$$$) — the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $$$n$$$ lines of each query contain the descriptions of types of blows you can deal. The $$$i$$$-th line contains two integers $$$d_i$$$ and $$$h_i$$$ ($$$1 \le d_i, h_i \le 10^9$$$) — the description of the $$$i$$$-th blow.

For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich.  If Zmei Gorynuch cannot be defeated print $$$-1$$$.

NoteIn the first query you can deal the first blow (after that the number of heads changes to $$$10 - 6 + 3 = 7$$$), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?

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

void main() {
    auto T = readln.chomp.to!int;

    while (T--) {
        auto s = readln.split.map!(to!int);
        auto N = s[0];
        auto X = s[1].to!long;
        auto A = N.iota.map!(_ => readln.split.map!(to!long).array).array;
        A.sort!"a[0] - a[1] > b[0] - b[1]";

        if (A.map!(a => a[0] >= X).any) {
            writeln(1);
            continue;
        }

        if (A.front[0] <= A.front[1]) {
            writeln(-1);
            continue;
        }

        auto d = A.front[0] - A.front[1];
        auto m = A.map!(a => a[0]).reduce!max;

        if ((X - m) % d == 0) {
            writeln((X - m) / d + 1);
        } else {
            writeln((X - m) / d + 2);
        }
    }
}


You are given a permutation of numbers from 1 to n. Determine whether there's a pair of integers a, b (1 ≤ a, b ≤ n; a ≠ b) such that the element  (note, that it is usual division, not integer one) is between a and b in this permutation.

First line consists of a single integer n (1 ≤ n ≤ 300000) — the size of permutation. Second line contains n integers — the permutation itself.

Print "YES", if such a pair exists, "NO" otherwise (in both cases without quotes, the answer is case insensitive).

NoteIn the second example 2 is between 1 and 3. Additionally 4 is between 3 and 5.

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

bool solve (int [] p)
{
	static immutable int MAX_LIMIT = 60;

	int n = to !(int) (p.length);

	auto q = new int [n];
	foreach (i; 0..n)
	{
		q[p[i]] = i;
	}

	foreach (i; 0..n)
	{
		int k = 0;
		int lim = min (i + 1, n - i);
		if (lim <= 2 * MAX_LIMIT)
		{
			foreach (j; 1..lim)
			{
				if ((q[i - j] < q[i]) != (q[i + j] < q[i]))
				{
					return true;
				}
			}
		}
		else
		{
			foreach (j; 1..MAX_LIMIT)
			{
				if ((q[i - j] < q[i]) != (q[i + j] < q[i]))
				{
					return true;
				}
			}
			foreach (j; lim - MAX_LIMIT..lim)
			{
				if ((q[i - j] < q[i]) != (q[i + j] < q[i]))
				{
					return true;
				}
			}
		}
	}

	foreach (i; 0..n)
	{
		int lo = max (0, i - MAX_LIMIT);
		foreach_reverse (j; lo..i)
		{
			int k = p[i] * 2 - p[j];
			if (k < 0 || n <= k)
			{
				continue;
			}
			if (q[k] > i)
			{
				return true;
			}
		}

		int hi = min (n - 1, i + MAX_LIMIT);
		foreach (j; i + 1..hi + 1)
		{
			int k = p[i] * 2 - p[j];
			if (k < 0 || n <= k)
			{
				continue;
			}
			if (q[k] < i)
			{
				return true;
			}
		}
	}

	return false;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new int [n];
		foreach (ref x; p)
		{
			readf (" %s", &x);
		}
		p[] -= 1;
		writeln (solve (p) ? "YES" : "NO");
	}
}

import std.algorithm;
import std.stdio;

bool solve (int [] p)
{
	static immutable int MAX_LIMIT = 60;

	int n = p.length;

	auto q = new int [n];
	foreach (i; 0..n)
	{
		q[p[i]] = i;
	}

	foreach (i; 0..n)
	{
		int lo = max (0, i - MAX_LIMIT);
		foreach_reverse (j; lo..i)
		{
			int k = p[i] * 2 - p[j];
			if (k < 0 || n <= k)
			{
				continue;
			}
			if (q[k] > i)
			{
				return true;
			}
		}

		int hi = min (n - 1, i + MAX_LIMIT);
		foreach (j; i + 1..hi + 1)
		{
			int k = p[i] * 2 - p[j];
			if (k < 0 || n <= k)
			{
				continue;
			}
			if (q[k] < i)
			{
				return true;
			}
		}
	}

	return false;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new int [n];
		foreach (ref x; p)
		{
			readf (" %s", &x);
		}
		p[] -= 1;
		writeln (solve (p) ? "YES" : "NO");
	}
}

import std.algorithm;
import std.stdio;

bool solve (int [] p)
{
	static immutable int MAX_LIMIT = 60;

	int n = p.length;

	auto q = new int [n];
	foreach (i; 0..n)
	{
		q[p[i]] = i;
	}

	foreach (i; 0..n)
	{
		int k = 0;
		int lim = min (i + 1, n - i);
		if (lim <= 2 * MAX_LIMIT)
		{
			foreach (j; 1..lim)
			{
				if ((q[i - j] < q[i]) != (q[i + j] < q[i]))
				{
					return true;
				}
			}
		}
		else
		{
			foreach (j; 1..MAX_LIMIT)
			{
				if ((q[i - j] < q[i]) != (q[i + j] < q[i]))
				{
					return true;
				}
			}
			foreach (j; lim - MAX_LIMIT..lim)
			{
				if ((q[i - j] < q[i]) != (q[i + j] < q[i]))
				{
					return true;
				}
			}
		}
	}

	return false;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new int [n];
		foreach (ref x; p)
		{
			readf (" %s", &x);
		}
		p[] -= 1;
		writeln (solve (p) ? "YES" : "NO");
	}
}


Berland crossword is a puzzle that is solved on a square grid with $$$n$$$ rows and $$$n$$$ columns. Initially all the cells are white.To solve the puzzle one has to color some cells on the border of the grid black in such a way that:   exactly $$$U$$$ cells in the top row are black;  exactly $$$R$$$ cells in the rightmost column are black;  exactly $$$D$$$ cells in the bottom row are black;  exactly $$$L$$$ cells in the leftmost column are black. Note that you can color zero cells black and leave every cell white.Your task is to check if there exists a solution to the given puzzle.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains $$$5$$$ integers $$$n, U, R, D, L$$$ ($$$2 \le n \le 100$$$; $$$0 \le U, R, D, L \le n$$$).

For each testcase print "YES" if the solution exists and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteHere are possible solutions to testcases $$$1$$$, $$$2$$$ and $$$4$$$:

// Vicfred
// https://codeforces.com/contest/1494/problem/B
// brute force
import std.stdio;

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

while(t--) {
    long n, U, R, D, L;
    readf("%s %s %s %s %s\n", &n, &U, &R, &D, &L);
    bool found = false;
    for(int mask = 0; mask < (1 << 4); mask++) {
        long up     = U;
        long right  = R;
        long down   = D;
        long left   = L;
        if(mask & (1 << 0)) {
            up -= 1;
            left -= 1;
        }
        if(mask & (1 << 1)) {
            left -= 1;
            down -= 1;
        }
        if(mask & (1 << 2)) {
            down -= 1;
            right -= 1;
        }
        if(mask & (1 << 3)) {
            right -= 1;
            up -= 1;
        }
        if((up >= 0 && right >= 0 && down >= 0 && left >= 0) &&
          (up <= n - 2 && right <= n - 2 && down <= n - 2 && left <= n - 2)) {
            found = true;
            break;
        }
    }
    if(found)
        "YES".writeln;
    else
        "NO".writeln;
}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD;
		auto U = RD;
		auto R = RD;
		auto D = RD;
		auto L = RD;

		foreach (i; 0..2^^4)
		{
			auto arr = new int[](4);
			arr[0] = i & 1;
			arr[1] = (i>>1) & 1;
			arr[2] = (i>>2) & 1;
			arr[3] = (i>>3) & 1;
			debug writeln(arr);

			auto u = n - arr[0] - arr[1];
			auto r = n - arr[1] - arr[2];
			auto d = n - arr[2] - arr[3];
			auto l = n - arr[3] - arr[0];
			if (inside(U, 2 - arr[0] - arr[1], u+1) && inside(R, 2 - arr[1] - arr[2], r+1) &&
				inside(D, 2 - arr[2] - arr[3], d+1) && inside(L, 2 - arr[3] - arr[0], l+1))
			{
				ans[ti] = true;
				break;
			}
		}
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	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 a = readln.splitter.map !(to !(int)).array;
		auto n = a[0] - 2;
		a = a[1..$];
		bool ok = false;
		foreach (i; 0..16)
		{
			auto corners = 4.iota.map !(k => (i >> k) & 1).array;
			auto b = a.dup;
			foreach (k; 0..4)
			{
				b[k] -= corners[k];
				b[(k + 1) & 3] -= corners[k];
			}
			ok |= b.all !(v => 0 <= v && v <= n);
		}
		writeln (ok ? "YES" : "NO");
	}
}


The determinant of a matrix 2 × 2 is defined as follows:A matrix is called degenerate if its determinant is equal to zero. The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements.You are given a matrix . Consider any degenerate matrix B such that norm ||A - B|| is minimum possible. Determine ||A - B||.

The first line contains two integers a and b (|a|, |b| ≤ 109), the elements of the first row of matrix A.  The second line contains two integers c and d (|c|, |d| ≤ 109) the elements of the second row of matrix A.

Output a single real number, the minimum possible value of ||A - B||. Your answer is considered to be correct if its absolute or relative error does not exceed 10 - 9.

NoteIn the first sample matrix B is In the second sample matrix B is

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

void main ()
{
	int a, b, c, d;
	while (readf (" %s %s %s %s", &a, &b, &c, &d) > 0)
	{
		real res = min (max (abs (a), abs (b)),
		    max (abs (b), abs (d)),
		    max (abs (d), abs (c)),
		    max (abs (c), abs (a)));
		real lo = 0.0;
		real hi = res;
		foreach (step; 0..200)
		{
			real me = (lo + hi) * 0.5;
			bool pos = false;
			bool neg = false;
			foreach (k; 0..16)
			{
				real e = (k & 1) ? a + me : a - me;
				real f = (k & 2) ? b + me : b - me;
				real g = (k & 4) ? c + me : c - me;
				real h = (k & 8) ? d + me : d - me;
				real cur = e * h - f * g;
				if (cur > +1E-15)
				{
					pos = true;
				}
				if (cur < -1E-15)
				{
					neg = true;
				}
			}
			debug {writefln ("%.15f %s %s", me, pos, neg);}
			if (pos && neg)
			{
				hi = me;
			}
			else
			{
				lo = me;
			}
		}
		writefln ("%.15f", lo);
	}
}

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

void main ()
{
	int a, b, c, d;
	while (readf (" %s %s %s %s", &a, &b, &c, &d) > 0)
	{
		real res = min (max (a, b), max (b, d),
		    max (d, c), max (c, a));
		real lo = 0.0;
		real hi = res;
		foreach (step; 0..100)
		{
			real me = (lo + hi) * 0.5;
			bool pos = false;
			bool neg = false;
			foreach (k; 0..16)
			{
				real e = (k & 1) ? a + me : a - me;
				real f = (k & 2) ? b + me : b - me;
				real g = (k & 4) ? c + me : c - me;
				real h = (k & 8) ? d + me : d - me;
				real cur = e * h - f * g;
				if (cur >= 0)
				{
					pos = true;
				}
				if (cur <= 0)
				{
					neg = true;
				}
			}
			debug {writefln ("%.15f %s %s", me, pos, neg);}
			if (pos && neg)
			{
				hi = me;
			}
			else
			{
				lo = me;
			}
		}
		writefln ("%.15f", lo);
	}
}


A subway scheme, classic for all Berland cities is represented by a set of n stations connected by n passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage.Berland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once.This invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say "I live in three passages from the ringroad" and another one could reply "you loser, I live in one passage from the ringroad". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...).The Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme.

The first line contains an integer n (3 ≤ n ≤ 3000), n is the number of stations (and trains at the same time) in the subway scheme. Then n lines contain descriptions of the trains, one per line. Each line contains a pair of integers xi, yi (1 ≤ xi, yi ≤ n) and represents the presence of a passage from station xi to station yi. The stations are numbered from 1 to n in an arbitrary order. It is guaranteed that xi ≠ yi and that no pair of stations contain more than one passage. The passages can be used to travel both ways. It is guaranteed that the given description represents a classic subway scheme.

Print n numbers. Separate the numbers by spaces, the i-th one should be equal to the distance of the i-th station from the ringroad. For the ringroad stations print number 0.

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

struct Queue(T) {
  private T[] items = [T.init];
  private size_t first, last;

  @property bool empty() {
    return first == last;
  }

  void push(T top) {
    if (last == items.length) {
      items.length = max(1, items.length*2);
    }
    items[last] = top;
    last++;
  }

  T pop() {
    if (this.empty)
      throw new Exception("Empty Queue.");
    auto top = items[first];
    first++;
    return top;
  }
}

void main() {
  int n;
  readf(" %d", &n);
  auto g = new int[][](n+1, 0);
  auto parent = new int[](n+1);
  auto visited = new int[](n+1);
  auto cycle = new int[](n+1);
  auto distances = new int[](n+1);
  int a,b;
  while (readf(" %d %d", &a, &b)) {
    g[a] ~= b;
    g[b] ~= a;
  }
  bool cycle_found = false;
  void dfs(int u, int p) {
    visited[u] = 1;
    parent[u] = p;
    if(cycle_found) return;
    foreach (v; g[u]) {
      if (v == p || visited[v] == 2 || cycle_found) continue;
      if (visited[v] == 1) {
        cycle[v] = 1;
        int x = u;
        while (x != v) {
          cycle[x] = 1;
          x = parent[x];
        }
        cycle_found = true;
        return;
      }
      dfs(v, u);
    }
    visited[u] = 2;
  }

  void bfs(int u0) {
    Queue!int q;
    q.push(u0);
    while (!q.empty) {
      auto u = q.pop();
      visited[u] = 1;
      foreach (v; g[u]) {
        debug {
          writeln("Start: ", v);
        }
        if (visited[v]) continue;
        debug {
          writeln("not visited");
        }
        if (!cycle[v]) {
          distances[v] = distances[u] + 1;
          debug {
            writeln(distances[v], ' ', distances[u]);
          }
        }
        q.push(v);
      }
    }
  }
  dfs(1, 0);
  visited[] = 0;
  bfs(to!int(cycle.countUntil(1)));
  debug {
    writeln(cycle);
  }
  writefln("%(%s %)", distances[1..$]);
}

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

struct Queue(T) {
  private T[] items = [T.init];
  private size_t first, last;

  @property bool empty() {
    return first == last;
  }

  void push(T top) {
    if (last == items.length) {
      items.length = max(1, items.length*2);
    }
    items[last] = top;
    last++;
  }

  T pop() {
    if (this.empty)
      throw new Exception("Empty Queue.");
    auto top = items[first];
    first++;
    return top;
  }
}

void main() {
  int n;
  readf(" %d", &n);
  auto g = new int[][](n+1, 0);
  auto parent = new int[](n+1);
  auto visited = new int[](n+1);
  auto cycle = new int[](n+1);
  auto distances = new int[](n+1);
  int a,b;
  while (readf(" %d %d", &a, &b)) {
    g[a] ~= b;
    g[b] ~= a;
  }
  bool cycle_found = false;
  void dfs(int u, int p) {
    visited[u] = 1;
    parent[u] = p;
    if(cycle_found) return;
    foreach (v; g[u]) {
      if (v == p || visited[v] == 2 || cycle_found) continue;
      if (visited[v] == 1) {
        cycle[v] = 1;
        int x = u;
        while (x != v) {
          cycle[x] = 1;
          x = parent[x];
        }
        cycle_found = true;
        return;
      }
      dfs(v, u);
    }
    visited[u] = 2;
  }

  void bfs(int u0) {
    Queue!int q;
    q.push(u0);
    while (!q.empty) {
      auto u = q.pop();
      visited[u] = 1;
      foreach (v; g[u]) {
        if (visited[v]) continue;
        if (!cycle[v]) {
          distances[v] = distances[u] + 1;
        }
        q.push(v);
      }
    }
  }
  dfs(1, 0);
  visited[] = 0;
  bfs(to!int(cycle.countUntil(1) + 1));
  debug {
    writeln(cycle);
  }
  writefln("%(%s %)", distances[1..$]);
}


Phoenix has a string $$$s$$$ consisting of lowercase Latin letters. He wants to distribute all the letters of his string into $$$k$$$ non-empty strings $$$a_1, a_2, \dots, a_k$$$ such that every letter of $$$s$$$ goes to exactly one of the strings $$$a_i$$$. The strings $$$a_i$$$ do not need to be substrings of $$$s$$$. Phoenix can distribute letters of $$$s$$$ and rearrange the letters within each string $$$a_i$$$ however he wants.For example, if $$$s = $$$ baba and $$$k=2$$$, Phoenix may distribute the letters of his string in many ways, such as:   ba and ba  a and abb  ab and ab  aa and bb But these ways are invalid:   baa and ba  b and ba  baba and empty string ($$$a_i$$$ should be non-empty) Phoenix wants to distribute the letters of his string $$$s$$$ into $$$k$$$ strings $$$a_1, a_2, \dots, a_k$$$ to minimize the lexicographically maximum string among them, i. e. minimize $$$max(a_1, a_2, \dots, a_k)$$$. Help him find the optimal distribution and print the minimal possible value of $$$max(a_1, a_2, \dots, a_k)$$$.String $$$x$$$ is lexicographically less than string $$$y$$$ if either $$$x$$$ is a prefix of $$$y$$$ and $$$x \ne y$$$, or there exists an index $$$i$$$ ($$$1 \le i \le min(|x|, |y|))$$$ such that $$$x_i$$$ < $$$y_i$$$ and for every $$$j$$$ $$$(1 \le j < i)$$$ $$$x_j = y_j$$$. Here $$$|x|$$$ denotes the length of the string $$$x$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case consists of two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$) — the length of string $$$s$$$ and the number of non-empty strings, into which Phoenix wants to distribute letters of $$$s$$$, respectively. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases is $$$\le 10^5$$$.

Print $$$t$$$ answers — one per test case. The $$$i$$$-th answer should be the minimal possible value of $$$max(a_1, a_2, \dots, a_k)$$$ in the $$$i$$$-th test case.

6
4 2
baba
5 2
baacb
5 3
baacb
5 3
aaaaa
6 4
aaxxzz
7 1
phoenix

NoteIn the first test case, one optimal solution is to distribute baba into ab and ab. In the second test case, one optimal solution is to distribute baacb into abbc and a.In the third test case, one optimal solution is to distribute baacb into ac, ab, and b.In the fourth test case, one optimal solution is to distribute aaaaa into aa, aa, and a.In the fifth test case, one optimal solution is to distribute aaxxzz into az, az, x, and x.In the sixth test case, one optimal solution is to distribute phoenix into ehinopx.

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto nk = readln.split.to!(int[]);
        auto N = nk[0];
        auto K = nk[1];

        auto SS = readln.chomp.to!(dchar[]);
        sort(SS);
        auto S = SS.to!(char[]);

        char[] a;
        if (N == 1) {
            a = S;
        } else if (S[0] != S[K-1]) {
            a = [S[K-1]];
        } else if (S[0] == S[$-1]) {
            foreach (_c; 0..(S.length.to!int+K-1)/K) a ~= S[0];
        } else if (S[K] == S[$-1]) {
            auto n = S.length.to!int-K;
            a ~= S[0];
            foreach (_c; 0..(n+K-1)/K) a ~= S[K];
        } else {
            a = [S[0]] ~ S[K..$];
        }
        writeln(a);
    }
}

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

immutable int letters = 26;

void main ()
{
	readln;
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto s = readln.strip;
		auto d = new int [letters];
		foreach (char c; s)
		{
			d[c - 'a'] += 1;
		}
                int lo = 0;
                int let = 0;
                foreach (i; 0..k)
                {
			while (d[let] == 0)
			{
				let += 1;
				lo = i;
			}
			d[let] -= 1;
			n -= 1;
                }

		string res = "" ~ cast (char) (let + 'a');
		if (lo == 0)
		{
			while (d[let] == 0)
			{
				let += 1;
			}
			if (d[let] == n)
			{
				foreach (z; 0..(d[let] + k - 1) / k)
				{
					res ~= cast (char) (let + 'a');
				}
			}
			else
			{
				foreach (cur; 0..letters)
				{
					foreach (z; 0..d[cur])
					{
						res ~= cast (char) (cur + 'a');
					}
				}
	        	}
		}
		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) { x.modm(y.modpow(mod - 2)); }

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

		auto a = new int[](n);
		foreach (i; 0..n)
			a[i] = s[i] - 'a';
		a.sort();

		{
			auto cnt = new int[](26);
			foreach (i; 0..n)
			{
				++cnt[a[i]];
			}

			int c, cc;
			foreach (i; 0..26)
			{
				if (cnt[i] != 0)
				{
					++c;
					if (cc == 0)
						cc = cnt[i];
				}
			}
			debug writeln("c:", c);
			if (c == 1)
			{
				foreach (i; 0..(n+k-1)/k)
				{
					ans[ti] ~= cast(char)('a'+a[i*k]);
				}
				continue;
			}
			else if (c == 2 && cc == k)
			{
				foreach (i; 0..(n+k-1)/k)
				{
					ans[ti] ~= cast(char)('a'+a[i*k]);
				}
				continue;
			}
		}
		{
			auto cnt = new int[](26);
			foreach (i; 0..k)
			{
				++cnt[a[i]];
			}
			int p;
			foreach_reverse (i; 0..26)
			{
				if (cnt[i] == 0) continue;
				p = i;
				break;
			}
			ans[ti] ~= cast(char)('a'+p);
			if (cnt[p] != k) continue;
		}
		debug writeln("ans:", ans[ti]);
		foreach (i; k..n)
			ans[ti] ~= cast(char)('a'+a[i]);
	}

	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) { x.modm(y.modpow(mod - 2)); }

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

		auto a = new int[](n);
		foreach (i; 0..n)
			a[i] = s[i] - 'a';
		a.sort();

		int l;
		while (l < n)
		{
			auto cnt = new int[](26);
			foreach (i; l..min(l+k, n))
			{
				++cnt[a[i]];
			}
			int p, p2;
			foreach_reverse (i; 0..26)
			{
				if (cnt[i] == 0) continue;
				p = i;
				break;
			}
			foreach (i; 0..26)
			{
				if (cnt[i] == 0) continue;
				p2 = i;
				break;
			}
			debug writeln(cnt);

			auto c = cast(char)('a'+p);
			if (k != cnt[p] || l+k >= n)
			{
				ans[ti] ~= c;
				break;
			}
			else
			{
				if (l == 0)
					ans[ti] ~= c;
				else
				{
					foreach (i; 0..cnt[p2])
						ans[ti] ~= c;
				}
			}
			l += k;
		}
	}

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

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto nk = readln.split.to!(int[]);
        auto N = nk[0];
        auto K = nk[1];

        auto SS = readln.chomp.to!(dchar[]);
        sort(SS);
        auto S = SS.to!(char[]);

        char[] a;
        if (N == 1) {
            a = S;
        } else if (S[0] != S[K-1]) {
            a = [S[K-1]];
            continue;
        } else if (S[0] == S[$-1]) {
            foreach (_c; 0..(S.length.to!int+K-1)/K) a ~= S[0];
        } else if (S[K] == S[$-1]) {
            auto n = S.length.to!int-K;
            a ~= S[0];
            foreach (_c; 0..(n+K-1)/K) a ~= S[K];
        } else {
            a = [S[0]] ~ S[K..$];
        }
        writeln(a);
    }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto nk = readln.split.to!(int[]);
        auto N = nk[0];
        auto K = nk[1];

        auto SS = readln.chomp.to!(dchar[]);
        sort(SS);
        auto S = SS.to!(char[]);

        char[] a;
        if (N == 1) {
            writeln(S);
            continue;
        } else if (S[0] != S[K-1]) {
            writeln(S[K-1]);
            continue;
        } else if (S[0] == S[$-1]) {
            foreach (_c; 0..(S.length.to!int+K-1)/K) a ~= S[0];
            writeln(a);
            continue;
        }

        int[26] cs;
        foreach (c; S) ++cs[c-'a'];
        bool b;
        foreach (c; cs) if (c%K != 0) b = true;
        if (b) {
            if (S[K] == S[$-1]) {
                auto n = S.length.to!int-K;
                a ~= S[0];
                foreach (_c; 0..(n+K-1)/K) a ~= S[K];
            } else {
                a = [S[0]] ~ S[K..$];
            }
        } else {
            foreach (i, c; cs) foreach (_c; 0..c/K) a ~= i.to!char+'a';
        }
        writeln(a);
    }
}

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) { x.modm(y.modpow(mod - 2)); }

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

		auto a = new int[](n);
		foreach (i; 0..n)
			a[i] = s[i] - 'a';
		a.sort();

		int l;
		while (l < n)
		{
			auto cnt = new int[](26);
			foreach (i; l..min(l+k, n))
			{
				++cnt[a[i]];
			}
			int p;
			foreach_reverse (i; 0..26)
			{
				if (cnt[i] == 0) continue;
				p = i;
				break;
			}
			debug writeln(cnt);

			auto c = cast(char)('a'+p);
			if (k != cnt[p] || l+k >= n)
			{
				ans[ti] ~= c;
				break;
			}
			else
			{
				if (l == 0)
					ans[ti] ~= c;
				else
				{
					foreach (i; 0..cnt[p])
						ans[ti] ~= c;
				}
			}
			l += k;
		}
	}

	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) { x.modm(y.modpow(mod - 2)); }

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

		auto a = new int[](n);
		foreach (i; 0..n)
			a[i] = s[i] - 'a';
		a.sort();

		{
			auto cnt = new int[](26);
			foreach (i; 0..n)
			{
				++cnt[a[i]];
			}

			int c;
			foreach (i; 0..26)
			{
				if (cnt[i] != 0)
					++c;
			}
			bool ok = true;
			if (c != 1)
			{
				foreach (i; 0..26)
				{
					if (cnt[i] % k)
						ok = false;
				}
			}
			if (ok)
			{
				foreach (i; 0..(n+k-1)/k)
				{
					ans[ti] ~= cast(char)('a'+a[i*k]);
				}
				continue;
			}
		}

		{
			auto cnt = new int[](26);
			foreach (i; 0..k)
			{
				++cnt[a[i]];
			}
			int p;
			foreach_reverse (i; 0..26)
			{
				if (cnt[i] == 0) continue;
				p = i;
				break;
			}
			ans[ti] ~= cast(char)('a'+p);
			if (cnt[p] != k) continue;
		}
		foreach (i; k..n)
			ans[ti] ~= cast(char)('a'+a[i]);
	}

	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) { x.modm(y.modpow(mod - 2)); }

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

		auto a = new int[](n);
		foreach (i; 0..n)
			a[i] = s[i] - 'a';
		a.sort();

		if (k == 1)
		{
			foreach (i; 0..n)
			{
				ans[ti] ~= cast(char)('a'+a[i]);
			}
			continue;
		}

		{
			auto cnt = new int[](26);
			foreach (i; 0..k)
			{
				++cnt[a[i]];
			}
			int p;
			foreach_reverse (i; 0..26)
			{
				if (cnt[i] == 0) continue;
				p = i;
				break;
			}
			ans[ti] ~= cast(char)('a'+p);
			if (cnt[p] != k) continue;
		}
		int l = k;
		while (l < n)
		{
			if (l+k < n)
			{
				foreach (i; l..min(l+k, n))
				{
					ans[ti] ~= cast(char)('a'+a[i]);
				}
				l += k;
				continue;
			}

			auto cnt = new int[](26);
			foreach (i; l..min(l+k, n))
			{
				++cnt[a[i]];
			}
			int p;
			foreach (i; 0..26)
			{
				if (cnt[i] == 0) continue;
				p = i;
				break;
			}
			debug writeln(cnt);

			if (cnt[p] == min(k, n-l) && l+k >= n)
			{
				ans[ti] ~= cast(char)('a'+p);
				break;
			}
			l += k;
		}
	}

	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) { x.modm(y.modpow(mod - 2)); }

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

		auto a = new int[](n);
		foreach (i; 0..n)
			a[i] = s[i] - 'a';
		a.sort();

		{
			auto cnt = new int[](26);
			foreach (i; 0..n)
			{
				++cnt[a[i]];
			}

			int c;
			foreach (i; 0..26)
			{
				if (cnt[i] != 0)
					++c;
			}
			debug writeln("c:", c);
			if (c <= 2)
			{
				foreach (i; 0..(n+k-1)/k)
				{
					ans[ti] ~= cast(char)('a'+a[i*k]);
				}
				continue;
			}
		}
		{
			auto cnt = new int[](26);
			foreach (i; 0..k)
			{
				++cnt[a[i]];
			}
			int p;
			foreach_reverse (i; 0..26)
			{
				if (cnt[i] == 0) continue;
				p = i;
				break;
			}
			ans[ti] ~= cast(char)('a'+p);
			if (cnt[p] != k) continue;
		}
		debug writeln("ans:", ans[ti]);
		foreach (i; k..n)
			ans[ti] ~= cast(char)('a'+a[i]);
	}

	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) { x.modm(y.modpow(mod - 2)); }

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

		auto a = new int[](n);
		foreach (i; 0..n)
			a[i] = s[i] - 'a';
		a.sort();

		{
			auto cnt = new int[](26);
			foreach (i; 0..n)
			{
				++cnt[a[i]];
			}
			bool ok = true;
			foreach (i; 0..26)
			{
				if (cnt[i] % k)
					ok = false;
			}
			if (ok)
			{
				foreach (i; 0..n/k)
				{
					ans[ti] ~= cast(char)('a'+a[i*k]);
				}
				continue;
			}
		}

		{
			auto cnt = new int[](26);
			foreach (i; 0..k)
			{
				++cnt[a[i]];
			}
			int p;
			foreach_reverse (i; 0..26)
			{
				if (cnt[i] == 0) continue;
				p = i;
				break;
			}
			ans[ti] ~= cast(char)('a'+p);
			if (cnt[p] != k) continue;
		}
		int l = k;
		while (l < n)
		{
			if (l+k < n)
			{
				foreach (i; l..min(l+k, n))
				{
					ans[ti] ~= cast(char)('a'+a[i]);
				}
				l += k;
				continue;
			}

			auto cnt = new int[](26);
			foreach (i; l..min(l+k, n))
			{
				++cnt[a[i]];
			}
			int p;
			foreach (i; 0..26)
			{
				if (cnt[i] == 0) continue;
				p = i;
				break;
			}
			debug writeln(cnt);

			if (cnt[p] == min(k, n-l) && l+k >= n)
			{
				ans[ti] ~= cast(char)('a'+p);
				break;
			}
			l += k;
		}
	}

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


Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.

In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week).

Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.

NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25.

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

alias Tuple!(int, "diff", int, "i") Prod;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!int).array;
    auto B = readln.split.map!(to!int).array;

    auto P = new Prod[](N);
    foreach (i; 0..N) {
        P[i] = Prod(A[i]-B[i], i);
    }
    P.sort!"a.diff < b.diff"();

    long ans = 0;
    foreach (i, p; enumerate(P)) {
        if (i < K) ans += A[p.i];
        else if (p.diff <= 0) ans += A[p.i];
        else ans += B[p.i];
    }

    ans.writeln;
}

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

struct XD
{
    int a;
    int b;
    int opCmp(ref const XD xd) const
    {
        if (a - b > xd.a - xd.b) return 1;
        if (a - b < xd.a - xd.b) return -1;
        return 0;
    }
}

void solve(XD[] xds, int n, int k)
{
    sort(xds);
    auto ans = 0;
    foreach (i; 0 .. k)
    {
        ans += xds[i].a;
    }
    int i;
    for (i = k; i < n && xds[i].a < xds[i].b; ++ i)
    {
        ans += xds[i].a;
    }
    for (; i < n; ++ i)
    {
        ans += xds[i].b;
    }
    writeln(ans);
}

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

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

struct XD
{
    int a;
    int b;
    int opCmp(ref const XD xd) const
    {
        if (a - b > xd.a - xd.b) return 1;
        if (a - b < xd.a - xd.b) return -1;
        return 0;
    }
}

void solve(XD[] xds, int n, int k)
{
    sort(xds);
    auto bs = new int[n];
    bs[n - 1] = xds[n - 1].b;
    for (int i = n - 2; i >= 0; -- i)
    {
        bs[i] = bs[i + 1] + xds[i].b;
    }
    auto ans = int.max;
    auto sum = 0;
    foreach (i; 0 .. k)
    {
        sum += xds[i].a;
    }
    for (int i = k; i < n; ++ i)
    {
        ans = min(ans, sum + bs[i]);
        sum += xds[i].a;
    }
    ans = min(ans, sum);
    writeln(ans);
}

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


You are given two integer arrays $$$a$$$ and $$$b$$$ of length $$$n$$$.You can reverse at most one subarray (continuous subsegment) of the array $$$a$$$. Your task is to reverse such a subarray that the sum $$$\sum\limits_{i=1}^n a_i \cdot b_i$$$ is maximized.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^7$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^7$$$).

Print single integer — maximum possible sum after reversing at most one subarray (continuous subsegment) of $$$a$$$.

NoteIn the first example, you can reverse the subarray $$$[4, 5]$$$. Then $$$a = [2, 3, 2, 3, 1]$$$ and $$$2 \cdot 1 + 3 \cdot 3 + 2 \cdot 2 + 3 \cdot 4 + 1 \cdot 2 = 29$$$.In the second example, you don't need to use the reverse operation. $$$13 \cdot 2 + 37 \cdot 4 = 174$$$.In the third example, you can reverse the subarray $$$[3, 5]$$$. Then $$$a = [1, 8, 3, 6, 7, 6]$$$ and $$$1 \cdot 5 + 8 \cdot 9 + 3 \cdot 6 + 6 \cdot 8 + 7 \cdot 8 + 6 \cdot 6 = 235$$$.

import std;

long[5000] a;
long[5000] b;
long[][] dp;
long nonrev;

long solve(int first, int last)
{
  if (last - first >= 2) {
    long result = ((dp[first + 1][last - 1] != 0) ? (dp[first + 1][last - 1]) : solve(first + 1, last - 1)) -
                    a[first] * b[first] - a[last] * b[last] +
                    a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else if (last - first == 1) {
    long result = nonrev -
                  a[first] * b[first] - a[last] * b[last] +
                  a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else {
    dp[first][last] = nonrev;
    return nonrev;
  }
}

void main()
{
  int n, i, j, first, last;

  dp = new long[][](5000, 5000);

  readf!(" %d")(n);
  for (i = 0; i < n; i++)
    readf!(" %d")(a[i]);
  for (i = 0; i < n; i++)
    readf!(" %d")(b[i]);

  nonrev = 0;
  for (i = 0; i < n; i++)
    nonrev += a[i] * b[i];

  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
      dp[i][j] = 0;

  long best = 0;
  for (first = 0; first < n; first++) {
    for (last = first; last < n; last++) {
      long result = solve(first, last);
      if (result > best) {
        best = result;
      }
    }
  }
  writeln(best);
}

import std.stdio;

long[5000] a;
long[5000] b;
long[][] dp;
long nonrev;

long solve(int first, int last)
{
  if (dp[first][last] != 0)
    return dp[first][last];
  if (last - first >= 2) {
    long result = ((dp[first + 1][last - 1] != 0) ? (dp[first + 1][last - 1]) : solve(first + 1, last - 1)) -
                    a[first] * b[first] - a[last] * b[last] +
                    a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else if (last - first == 1) {
    long result = nonrev -
                  a[first] * b[first] - a[last] * b[last] +
                  a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else {
    dp[first][last] = nonrev;
    return nonrev;
  }
}

void main()
{
  int n, i, j, first, last;

  dp = new long[][](5000, 5000);

  readf!(" %d")(n);
  for (i = 0; i < n; i++)
    readf!(" %d")(a[i]);
  for (i = 0; i < n; i++)
    readf!(" %d")(b[i]);

  nonrev = 0;
  for (i = 0; i < n; i++)
    nonrev += a[i] * b[i];

  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
      dp[i][j] = 0;

  long best = 0;
  for (first = n - 1; first >= 0; first--) {
    for (last = first; last < n; last++) {
      long result = solve(first, last);
      if (result > best) {
        best = result;
      }
    }
  }
  writeln(best);
}

import std.stdio;

long[5000] a;
long[5000] b;
long[][] dp;
long nonrev;

long solve(int first, int last)
{
  if (dp[first][last] != 0)
    return dp[first][last];
  if (last - first >= 2) {
    long result = ((dp[first + 1][last - 1] != 0) ? (dp[first + 1][last - 1]) : solve(first + 1, last - 1)) -
                    a[first] * b[first] - a[last] * b[last] +
                    a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else if (last - first == 1) {
    long result = nonrev -
                  a[first] * b[first] - a[last] * b[last] +
                  a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else {
    dp[first][last] = nonrev;
    return nonrev;
  }
}

void main()
{
  int n, i, j, first, last;

  dp = new long[][](5000, 5000);

  readf!(" %d")(n);
  for (i = 0; i < n; i++)
    readf!(" %d")(a[i]);
  for (i = 0; i < n; i++)
    readf!(" %d")(b[i]);

  nonrev = 0;
  for (i = 0; i < n; i++)
    nonrev += a[i] * b[i];

  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
      dp[i][j] = 0;

  long best = 0;
  for (first = 0; first < n; first++) {
    for (last = first; last < n; last++) {
      long result = solve(first, last);
      if (result > best) {
        best = result;
      }
    }
  }
  writeln(best);
}

import std.stdio;

long[5000] a;
long[5000] b;
long[][] dp;
long nonrev;

long solve(int first, int last)
{
  if (last - first >= 2) {
    long result = ((dp[first + 1][last - 1] != 0) ? (dp[first + 1][last - 1]) : solve(first + 1, last - 1)) -
                    a[first] * b[first] - a[last] * b[last] +
                    a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else if (last - first == 1) {
    long result = nonrev -
                  a[first] * b[first] - a[last] * b[last] +
                  a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else {
    dp[first][last] = nonrev;
    return nonrev;
  }
}

void main()
{
  int n, i, j, first, last;

  dp = new long[][](5000, 5000);

  readf!(" %d")(n);
  for (i = 0; i < n; i++)
    readf!(" %d")(a[i]);
  for (i = 0; i < n; i++)
    readf!(" %d")(b[i]);

  nonrev = 0;
  for (i = 0; i < n; i++)
    nonrev += a[i] * b[i];

  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
      dp[i][j] = 0;

  long best = 0;
  for (first = 0; first < n; first++) {
    for (last = first; last < n; last++) {
      long result = solve(first, last);
      if (result > best) {
        best = result;
      }
    }
  }
  writeln(best);
}

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;

long[5000] a;
long[5000] b;
long[][] dp;
long nonrev;

long solve(int first, int last)
{
  if (last - first >= 2) {
    long result = ((dp[first + 1][last - 1] != 0) ? (dp[first + 1][last - 1]) : solve(first + 1, last - 1)) -
                    a[first] * b[first] - a[last] * b[last] +
                    a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else if (last - first == 1) {
    long result = nonrev -
                  a[first] * b[first] - a[last] * b[last] +
                  a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else {
    dp[first][last] = nonrev;
    return nonrev;
  }
}

void main()
{
  int n, i, j, first, last;

  dp = new long[][](5000, 5000);

  readf!(" %d")(n);
  for (i = 0; i < n; i++)
    readf!(" %d")(a[i]);
  for (i = 0; i < n; i++)
    readf!(" %d")(b[i]);

  nonrev = 0;
  for (i = 0; i < n; i++)
    nonrev += a[i] * b[i];

  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
      dp[i][j] = 0;

  long best = 0;
  for (first = 0; first < n; first++) {
    for (last = first; last < n; last++) {
      long result = solve(first, last);
      if (result > best) {
        best = result;
      }
    }
  }
  writeln(best);
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;
	auto b = RDA;

	auto c = new long[](n+1);
	foreach (i; 0..n)
	{
		c[i+1] = c[i] + a[i] * b[i];
	}

	long ans = c[n];
	foreach (m; 0..n-1)
	{
		auto l = m;
		auto r = m+1;
		long x;
		while (l >= 0 && r < n)
		{
			x += a[r] * b[l] + a[l] * b[r];
			long tmp = c[l] + c[n] - c[r+1] + x;
			ans.chmax(tmp);
			--l; ++ r;
		}
	}
	foreach (m; 1..n-1)
	{
		auto l = m-1;
		auto r = m+1;
		long x = a[m] * b[m];
		while (l >= 0 && r < n)
		{
			x += a[r] * b[l] + a[l] * b[r];
			long tmp = c[l] + c[n] - c[r+1] + x;
			ans.chmax(tmp);
			--l; ++r;
		}
	}

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

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

long solve(long[] a, long[] b)
{
    auto n = to!int(a.length);
    auto s = new long[n];
    s[0] = a[0] * b[0];
    foreach (i; 1 .. n) s[i] = s[i - 1] + a[i] * b[i];
    auto dp = new long[][](n, 3);
    foreach (i; 0 .. n) dp[i][1] = a[i] * b[i];
    long res = s[n - 1];
    foreach (i; 1 .. n)
    {
        foreach (j; 0 .. n - i)
        {
            dp[j][2] = dp[j + 1][0] + a[j] * b[j + i] + a[j + i] * b[j];
            long v = dp[j][2] + (s[n - 1] - s[j + i]);
            if (j > 0) v += s[j - 1];
            res = max(res, v);
        }
        foreach (j; 0 .. n)
        {
            dp[j][0] = dp[j][1];
            dp[j][1] = dp[j][2];
        }
    }
    return res;
}

int main(string[] args)
{
    readln;
    auto a = map!(to!long)(readln.strip.split(" ")).array;
    auto b = map!(to!long)(readln.strip.split(" ")).array;
    auto ret = solve(a, b);
    writeln(ret);
    return 0;
}

//import std;
import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;

long[] a;
long[] b;
long[][] dp;
long nonrev;

long solve(int first, int last)
{
  if (last - first >= 2) {
    long result = ((dp[first + 1][last - 1] != 0) ? (dp[first + 1][last - 1]) : solve(first + 1, last - 1)) -
                    a[first] * b[first] - a[last] * b[last] +
                    a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else if (last - first == 1) {
    long result = nonrev -
                  a[first] * b[first] - a[last] * b[last] +
                  a[first] * b[last] + a[last] * b[first];
    dp[first][last] = result;
    return result;
  } else {
    dp[first][last] = nonrev;
    return nonrev;
  }
}

void main()
{
  int n, x, i, j, first, last;

  writeln(0);
  stdout.flush;
  return;

  readf!" %s "(n);
  dp = new long[][](n, n);
  a = new long[](n);
  b = new long[](n);

  for (i = 0; i < n; i++)
    readf!" %s "(a[i]);
  for (i = 0; i < n; i++)
    readf!" %s "(b[i]);

  nonrev = 0;
  for (i = 0; i < n; i++)
    nonrev += a[i] * b[i];

  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
      dp[i][j] = 0;

  long best = 0;
  for (first = 0; first < n; first++) {
    for (last = first; last < n; last++) {
      long result = solve(first, last);
      if (result > best) {
        best = result;
      }
    }
  }
  writeln(best);
  stdout.flush;
}