You are given a positive integer $$$m$$$ and two integer sequence: $$$a=[a_1, a_2, \ldots, a_n]$$$ and $$$b=[b_1, b_2, \ldots, b_n]$$$. Both of these sequence have a length $$$n$$$.Permutation is a sequence of $$$n$$$ different positive integers from $$$1$$$ to $$$n$$$. For example, these sequences are permutations: $$$[1]$$$, $$$[1,2]$$$, $$$[2,1]$$$, $$$[6,7,3,4,1,2,5]$$$. These are not: $$$[0]$$$, $$$[1,1]$$$, $$$[2,3]$$$.You need to find the non-negative integer $$$x$$$, and increase all elements of $$$a_i$$$ by $$$x$$$, modulo $$$m$$$ (i.e. you want to change $$$a_i$$$ to $$$(a_i + x) \bmod m$$$), so it would be possible to rearrange elements of $$$a$$$ to make it equal $$$b$$$, among them you need to find the smallest possible $$$x$$$.In other words, you need to find the smallest non-negative integer $$$x$$$, for which it is possible to find some permutation $$$p=[p_1, p_2, \ldots, p_n]$$$, such that for all $$$1 \leq i \leq n$$$, $$$(a_i + x) \bmod m = b_{p_i}$$$, where $$$y \bmod m$$$ — remainder of division of $$$y$$$ by $$$m$$$.For example, if $$$m=3$$$, $$$a = [0, 0, 2, 1], b = [2, 0, 1, 1]$$$, you can choose $$$x=1$$$, and $$$a$$$ will be equal to $$$[1, 1, 0, 2]$$$ and you can rearrange it to make it equal $$$[2, 0, 1, 1]$$$, which is equal to $$$b$$$.

The first line contains two integers $$$n,m$$$ ($$$1 \leq n \leq 2000, 1 \leq m \leq 10^9$$$): number of elemens in arrays and $$$m$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < m$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \leq b_i < m$$$). It is guaranteed that there exists some non-negative integer $$$x$$$, such that it would be possible to find some permutation $$$p_1, p_2, \ldots, p_n$$$ such that $$$(a_i + x) \bmod m = b_{p_i}$$$.

Print one integer, the smallest non-negative integer $$$x$$$, such that it would be possible to find some permutation $$$p_1, p_2, \ldots, p_n$$$ such that $$$(a_i + x) \bmod m = b_{p_i}$$$ for all $$$1 \leq i \leq n$$$.

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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto a = RDA!int;
	auto b = RDA!int;
	int[int] set_a, set_b;
	foreach (e; a)
		++set_a[e];
	foreach (e; b)
		++set_b[e];
	auto list_a = new int[][](n+1);
	foreach (key; set_a.keys)
	{
		auto c = set_a[key];
		list_a[c] ~= key;
	}
	auto list_b = new int[][](n+1);
	foreach (key; set_b.keys)
	{
		auto c = set_b[key];
		list_b[c] ~= key;
	}
	debug writeln(list_a);
	debug writeln(list_b);

	bool[int] list_x;
	foreach (i; 0..n+1)
	{
		if (list_a[i].empty) continue;
		auto keys1 = list_a[i];
		auto keys2 = list_b[i];
		keys1.sort();
		keys2.sort();
		if (list_x.empty)
		{
			foreach (key2; keys2)
			{
				auto key1 = keys1[0];
				auto d = key2 - key1;
				if (d >= 0)
					list_x[d] = true;
				else
					list_x[m+d] = true;
			}
			debug writeln("list_x:", list_x);
		}
		bool[int] tmp;
		foreach (pos; 0..keys1.length)
		{
			int x;
			{
				auto key1 = keys1[0];
				auto key2 = keys2[(pos) % keys1.length];
				x = key2 - key1;
				if (x < 0)
					x += m;
			}
			bool ok = true;
			foreach (j; 0..keys1.length)
			{
				auto key1 = keys1[j];
				auto key2 = keys2[(j+pos) % keys1.length];
				auto d = key2 - key1;
				if (d < 0)
					d += m;
				if (x != d)
				{
					ok = false;
					break;
				}
			}
			if (ok)
				tmp[x] = true;
		}
		debug writeln("tmp:", tmp);
		list_x = tmp;
	}
	int ans = int.max;
	foreach (key; list_x.keys)
		ans.chmin(key);
	writeln(ans);
	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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto a = RDA!int;
	auto b = RDA!int;
	int[int] set_a, set_b;
	foreach (e; a)
		++set_a[e];
	foreach (e; b)
		++set_b[e];
	auto list_a = new int[][](n+1);
	foreach (key; set_a.keys)
	{
		auto c = set_a[key];
		list_a[c] ~= key;
	}
	auto list_b = new int[][](n+1);
	foreach (key; set_b.keys)
	{
		auto c = set_b[key];
		list_b[c] ~= key;
	}
	debug writeln(list_a);
	debug writeln(list_b);

	bool[int] list_x;
	foreach (i; 0..n+1)
	{
		if (list_a[i].empty) continue;
		auto keys1 = list_a[i];
		auto keys2 = list_b[i];
		if (list_x.empty)
		{
			foreach (key2; keys2)
			{
				auto key1 = keys1[0];
				auto d = key2 - key1;
				if (d >= 0)
					list_x[d] = true;
				else
					list_x[m+d] = true;
			}
			debug writeln("list_x:", list_x);
		}
		bool[int] tmp;
		auto used = new bool[](keys2.length);
		foreach (key1; keys1)
		{
			foreach (j, key2; keys2)
			{
				auto d = key2 - key1;
				if (d < 0)
					d += m;
				if (list_x.get(d, false) && !used[j])
				{
					tmp[d] = true;
					used[j] = true;
				}
			}
		}
		debug writeln("tmp:", tmp);
		list_x = tmp;
	}
	int ans = int.max;
	foreach (key; list_x.keys)
		ans.chmin(key);
	writeln(ans);
	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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto a = RDA!int;
	auto b = RDA!int;
	int[int] set_a, set_b;
	foreach (e; a)
		++set_a[e];
	foreach (e; b)
		++set_b[e];
	auto list_a = new int[][](n+1);
	foreach (key; set_a.keys)
	{
		auto c = set_a[key];
		list_a[c] ~= key;
	}
	auto list_b = new int[][](n+1);
	foreach (key; set_b.keys)
	{
		auto c = set_b[key];
		list_b[c] ~= key;
	}
	debug writeln(list_a);
	debug writeln(list_b);

	bool[int] list_x;
	foreach (i; 0..n+1)
	{
		if (list_a[i].empty) continue;
		auto keys1 = list_a[i];
		auto keys2 = list_b[i];
		if (list_x.empty)
		{
			foreach (key2; keys2)
			{
				auto key1 = keys1[0];
				auto d = key2 - key1;
				if (d >= 0)
					list_x[d] = true;
				else
					list_x[m+d] = true;
			}
			debug writeln("list_x:", list_x);
		}
		bool[int] tmp;
		foreach (key1; keys1)
		{
			foreach (key2; keys2)
			{
				auto d = key2 - key1;
				if (d < 0)
					d += m;
				if (list_x.get(d, false))
				{
					tmp[d] = true;
				}
			}
		}
		debug writeln("tmp:", tmp);
		list_x = tmp;
	}
	int ans = int.max;
	foreach (key; list_x.keys)
		ans.chmin(key);
	writeln(ans);
	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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto a = RDA!int;
	auto b = RDA!int;
	int[int] set_a, set_b;
	foreach (e; a)
		++set_a[e];
	foreach (e; b)
		++set_b[e];
	auto list_a = new int[][](n+1);
	foreach (key; set_a.keys)
	{
		auto c = set_a[key];
		list_a[c] ~= key;
	}
	auto list_b = new int[][](n+1);
	foreach (key; set_b.keys)
	{
		auto c = set_b[key];
		list_b[c] ~= key;
	}
	debug writeln(list_a);
	debug writeln(list_b);

	bool[int] list_x;
	foreach (i; 0..n+1)
	{
		if (list_a[i].empty) continue;
		auto keys1 = list_a[i];
		auto keys2 = list_b[i];
		if (list_x.empty)
		{
			foreach (key2; keys2)
			{
				auto key1 = keys1[0];
				auto d = key2 - key1;
				if (d >= 0)
					list_x[d] = true;
				else
					list_x[m+d] = true;
			}
			debug writeln("list_x:", list_x);
		}
		bool[int] tmp;
		foreach (key1; keys1)
		{
			foreach (key2; keys2)
			{
				auto d = key2 - key1;
				if (d < 0)
					d += m;
				if (list_x.get(d, false))
				{
					tmp[d] = true;
				}
			}
		}
		debug writeln("tmp:", tmp);
		list_x = tmp;
	}
	auto keys = list_x.keys;
	auto ans = keys[keys.MIN_POS()];
	writeln(ans);
	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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto a = RDA!int;
	auto b = RDA!int;
	int[int] set_a, set_b;
	foreach (e; a)
		++set_a[e];
	foreach (e; b)
		++set_b[e];
	auto list_a = new int[][](n+1);
	foreach (key; set_a.keys)
	{
		auto c = set_a[key];
		list_a[c] ~= key;
	}
	auto list_b = new int[][](n+1);
	foreach (key; set_b.keys)
	{
		auto c = set_b[key];
		list_b[c] ~= key;
	}
	debug writeln(list_a);
	debug writeln(list_b);

	bool[int] list_x;
	foreach (i; 0..n+1)
	{
		if (list_a[i].empty) continue;
		auto keys1 = list_a[i];
		auto keys2 = list_b[i];
		if (list_x.empty)
		{
			foreach (key2; keys2)
			{
				auto key1 = keys1[0];
				auto d = key2 - key1;
				if (d >= 0)
					list_x[d] = true;
				else
					list_x[m+d] = true;
			}
			debug writeln("list_x:", list_x);
		}
		bool[int] tmp;
		foreach (x; list_x.keys)
		{
			auto used = new bool[](keys2.length);
			bool ok = true;
			foreach (key1; keys1)
			{
				foreach (j, key2; keys2)
				{
					if (used[j]) continue;
					used[j] = true;
					auto d = key2 - key1;
					if (d < 0)
						d += m;
					if (x != d)
					{
						ok = false;
						break;
					}
				}
			}
			if (ok)
				tmp[x] = true;
		}
		debug writeln("tmp:", tmp);
		list_x = tmp;
	}
	int ans = int.max;
	foreach (key; list_x.keys)
		ans.chmin(key);
	writeln(ans);
	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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto a = RDA!int;
	auto b = RDA!int;
	int[int] set_a, set_b;
	foreach (e; a)
		++set_a[e];
	foreach (e; b)
		++set_b[e];
	auto list_a = new int[][](n+1);
	foreach (key; set_a.keys)
	{
		auto c = set_a[key];
		list_a[c] ~= key;
	}
	auto list_b = new int[][](n+1);
	foreach (key; set_b.keys)
	{
		auto c = set_b[key];
		list_b[c] ~= key;
	}
	debug writeln(list_a);
	debug writeln(list_b);

	bool[int] list_x;
	foreach (i; 0..n+1)
	{
		if (list_a[i].empty) continue;
		auto keys1 = list_a[i];
		auto keys2 = list_b[i];
		if (list_x.empty)
		{
			foreach (key2; keys2)
			{
				auto key1 = keys1[0];
				auto d = key2 - key1;
				if (d >= 0)
					list_x[d] = true;
				else
					list_x[m+d] = true;
			}
			debug writeln("list_x:", list_x);
		}
		bool[int] tmp;
		foreach (key1; keys1)
		{
			foreach (key2; keys2)
			{
				auto d = key2 - key1;
				if (d < 0)
					d += m;
				if (list_x.get(d, false))
				{
					tmp[d] = true;
				}
			}
		}
		debug writeln("tmp:", tmp);
		list_x = tmp;
	}
	writeln(list_x.keys[0]);
	stdout.flush;
	debug readln;
}


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. You have to choose a positive integer $$$d$$$ and paint all elements into two colors. All elements which are divisible by $$$d$$$ will be painted red, and all other elements will be painted blue.The coloring is called beautiful if there are no pairs of adjacent elements with the same color in the array. Your task is to find any value of $$$d$$$ which yields a beautiful coloring, or report that it is impossible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of elements of the array. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{18}$$$).

For each testcase print a single integer. If there is no such value of $$$d$$$ that yields a beautiful coloring, print $$$0$$$. Otherwise, print any suitable value of $$$d$$$ ($$$1 \le d \le 10^{18}$$$).

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

bool check(long[] a, long div)
{
  bool prev = ((a[0] % div) != 0);
  foreach (x ; a[1 .. $]) {
    bool cur = ((x % div) != 0);
    if (cur == prev)
      return false;
    prev = cur;
  }
  return true;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!long).array;
    long[] e, o;
    foreach (i ; 0 .. n) {
      if (i % 2 == 0)
        e ~= a[i];
      else
        o ~= a[i];
    }

    long gcdo = o[0];
    foreach (x ; o[1 .. $])
      gcdo = gcd(gcdo, x);
    long gcde = e[0];
    foreach (x ; e[1 .. $])
      gcde = gcd(gcde, x);

    if (check(a, gcdo)) {
      writeln(gcdo);
    } else if (check(a, gcde)) {
      writeln(gcde);
    } else {
      writeln(0);
    }
  }
}

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto a = ma(n, readInt!long);

  long[] even, odd;
  foreach(i; 0 .. n)
    {
      if (i%2)
	{
	  odd ~= a[i];
	}
      else
	{
	  even ~= a[i];
	}
    }
  auto egcd = even.fold!gcd,
    ogcd = odd.fold!gcd;
  if (odd.all!(ai => ai % egcd != 0)) return writeln(egcd);
  if (even.all!(ai => ai % ogcd != 0)) return writeln(ogcd);
  return writeln(0);
}

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

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

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

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

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

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

void solve(){
    auto n = scan;
    auto arr = scanArray;
    long gcd1 = arr[0];
    for(int i = 2; i < n; i += 2){
        gcd1 = gcd(gcd1, arr[i]);
    }
    long gcd2 = arr[1];
    for(int i = 3; i < n; i += 2){
        gcd2 = gcd(gcd2, arr[i]);
    }
    show(gcd1, gcd2);

    bool f = 1;
    for(int i = 1; i < n; i += 2){
        if(arr[i] % gcd1 == 0){
            f = 0;
            break;
        }
    }
    if(f){
        writeln(gcd1);
        return;
    }

    f = 1;
    for(int i = 0; i < n; i += 2){
        if(arr[i] % gcd2 == 0){
            f = 0;
            break;
        }
    }
    if(f){
        writeln(gcd2);
        return;
    }

    writeln(0);
}

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

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

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

bool check(long[] a, long div)
{
  bool prev = ((a[0] % div) != 0);
  foreach (x ; a[1 .. $]) {
    bool cur = ((x % div) != 0);
    if (cur == prev)
      return false;
    prev = cur;
  }
  return true;
}

// From: https://rosettacode.org/wiki/Least_common_multiple#D
T lcm(T)(T m, T n) pure nothrow {
    if (m == 0) return m;
    if (n == 0) return n;
    return abs((m * n) / gcd(m, n));
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!long).array;
    long[] b;
    foreach (i ; 1 .. n) {
      long x = a[i], y = a[i - 1];
      if (x > y)
        swap(x, y);
      if (y % x == 0)
        b ~= y / x;
      b ~= x;
      b ~= y;
    }

    long ans = 0;
    foreach (div ; b) {
      if (check(a, div)) {
        ans = div;
        break;
      }
    }
    writeln(ans);
  }
}

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

bool check(long[] a, long div)
{
  bool prev = ((a[0] % div) != 0);
  foreach (x ; a[1 .. $]) {
    bool cur = ((x % div) != 0);
    if (cur == prev)
      return false;
    prev = cur;
  }
  return true;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!long).array;
    long ans = 0;
    foreach (div ; a) {
      if (check(a, div)) {
        ans = div;
        break;
      }
    }
    writeln(ans);
  }
}

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto a = ma(n, readInt!int);

  int[] even, odd;
  foreach(i; 0 .. n)
    {
      if (i%2)
	{
	  odd ~= a[i];
	}
      else
	{
	  even ~= a[i];
	}
    }
  auto egcd = even.fold!gcd,
    ogcd = odd.fold!gcd;
  if (odd.all!(ai => ai % egcd != 0)) return writeln(egcd);
  if (even.all!(ai => ai % ogcd != 0)) return writeln(ogcd);
  return writeln(0);
}

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

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

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

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

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


Polycarp is playing a new computer game. This game has $$$n$$$ stones in a row. The stone on the position $$$i$$$ has integer power $$$a_i$$$. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if $$$n = 5$$$ and $$$a = [1, 5, 4, 3, 2]$$$, then Polycarp could make the following moves:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the rightmost stone. After this move $$$a = [5, 4, 3]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3, 2]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stones. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the power of the stones.

For each test case, output the minimum number of moves required to destroy the stones with the greatest and the lowest power.

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

void main() {
    foreach(t; 0 .. to!int(readln.strip)) {
        int n = to!int(readln.strip);
        auto ar = readln.strip.split.map!(to!int);
        int mn = ar.countUntil(1), mx = ar.countUntil(n);
        if(mn > mx) swap(mn, mx);
        writeln(min(n-mn, mx+1, n-mx+mn+1));
    }
}

// Vicfred
// https://codeforces.com/contest/1538/problem/A
//
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

int abs(int x) {
    return x > 0 ? x : -x;
}

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

while(t--) {
    int n = readln.chomp.to!int;
    int[] a = readln.split.map!(to!int).array;

    int maxima = a.maxElement;
    int minima = a.minElement;

    int left = 0;
    int right;

    for(int i = 0; i < n; ++i) {
        left += 1;
        if(a[i] == maxima || a[i] == minima) {
            break;
        }
    }

    for(int i = n - 1; i >= 0; --i) {
        right += 1;
        if(a[i] == maxima || a[i] == minima) {
            break;
        }
    }

    //left.writeln;
    //right.writeln;

    int between = abs(left - n + right - 1);
    //between.writeln;
    int[] ans = [left, right, between];
    ans.sort;
    //ans.writeln;
    (ans[0] + ans[1]).writeln;
}
}

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

int[] removeminmax(int[] a, int min_x, int max_x)
{
  auto l = a.countUntil!(x => (x == min_x || x == max_x));
  a = a.dup.reverse;
  auto r = a.countUntil!(x => (x == min_x || x == max_x));
  if (l < r) {
    a.reverse;
    return a[l + 1 .. $];
  } else {
    return a[r + 1 .. $];
  }
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!int).array;
    int min_x = a.minElement;
    int max_x = a.maxElement;
    int[] step1 = removeminmax(a, min_x, max_x);
    int[] step2 = removeminmax(step1, min_x, max_x);
    writeln(a.length - step2.length);
  }
}


Screen resolution of Polycarp's monitor is $$$a \times b$$$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $$$(x, y)$$$ ($$$0 \le x < a, 0 \le y < b$$$). You can consider columns of pixels to be numbered from $$$0$$$ to $$$a-1$$$, and rows — from $$$0$$$ to $$$b-1$$$.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.

In the first line you are given an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. In the next lines you are given descriptions of $$$t$$$ test cases. Each test case contains a single line which consists of $$$4$$$ integers $$$a, b, x$$$ and $$$y$$$ ($$$1 \le a, b \le 10^4$$$; $$$0 \le x < a$$$; $$$0 \le y < b$$$) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that $$$a+b>2$$$ (e.g. $$$a=b=1$$$ is impossible).

Print $$$t$$$ integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.

NoteIn the first test case, the screen resolution is $$$8 \times 8$$$, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.

import std.stdio;
import std.algorithm;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		int b=0;
		int c=0;
		int d=0;
		readf(" %d", &a);
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		c=c+1;
		d=d+1;
		writeln(max(max((a-c)*b, (c-1)*b),max((b-d)*a, (d-1)*a)));
	}
	return 0;
}


Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1, b2, ..., bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.

The first line contains two numbers n and m (2 ≤ n, m ≤ 100) — the dimensions of the matrix. The second line contains n numbers a1, a2, ..., an (0 ≤ ai ≤ 109), where ai is the xor of all elements in row i. The third line contains m numbers b1, b2, ..., bm (0 ≤ bi ≤ 109), where bi is the xor of all elements in column i.

If there is no matrix satisfying the given constraints in the first line, output "NO". Otherwise, on the first line output "YES", and then n rows of m numbers in each ci1, ci2, ... , cim (0 ≤ cij ≤ 2·109) — the description of the matrix. If there are several suitable matrices, it is allowed to print any of them.

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

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

    long a = 0;
    long b = 0;

    foreach (i; 0..N) a ^= A[i];
    foreach (i; 0..M) b ^= B[i];

    if (a != b) {
        writeln("NO");
        return;
    }

    a = 0;
    b = 0;
    auto ans = new long[][](N, M);
    foreach (i; 0..N-1) ans[i][M-1] = A[i], a ^= A[i];
    foreach (j; 0..M-1) ans[N-1][j] = B[j], b ^= B[j];
    ans[N-1][M-1] = a ^ B[M-1];

    writeln("YES");
    ans.each!(a => a.map!(to!string).join(" ").writeln);
}

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

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

    Tuple!(int, int)[][] vals;
    foreach (_; 0 .. 2) vals ~= readln.chomp.split.map!(to!int).enumerate.map!(t => tuple(cast(int)t[0], t[1])).array;

    debug { vals.writeln; }

    auto ans = new int[][] (n, m);

    foreach_reverse (b; 0 .. 31) {
        auto cur = 1 << b;

        auto f = (Tuple!(int, int)[] arr) => arr.filter!(t => (t[1] & cur) > 0).map!(t => t[0]).array;
        auto nrs = vals.map!f.array;

        debug { if (b < 4) writeln(cur, ' ', nrs[0], ' ', nrs[1]); }

        if (nrs[0].length % 2 != nrs[1].length % 2) {
            writeln("NO");
            return;
        }

        if (nrs[0].length % 2 == 0) { // both even from above
            if (nrs[0].empty) foreach (j; nrs[1]) ans[0][j] ^= cur;
            else if (nrs[1].empty) foreach (i; nrs[0]) ans[i][0] ^= cur;
            else {
                while (nrs[0].length < nrs[1].length) nrs[0] ~= nrs[0].back;
                while (nrs[1].length < nrs[0].length) nrs[1] ~= nrs[1].back;
                foreach (i, j; lockstep(nrs[0], nrs[1])) ans[i][j] ^= cur;
            }
        } else { // both odd
            foreach (i; nrs[0]) {
                foreach (j; nrs[1]) {
                    ans[i][j] ^= cur;
                }
            }
        }
    }

    writeln("YES");
    ans.each!(arr => arr.writefln!("%(%s %)"));
}

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

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

  auto ax=a.reduce!((r, e)=>(r^e)),
       bx=b.reduce!((r, e)=>(r^e));
  if(ax!=bx){writeln("NO"); return;}
  writeln("YES");
  write(a[0]^b[0]^bx, " ");
  writefln("%(%s %)", b[1..$]);
  foreach(i; 1..n){
    write(a[i], " ");
    auto zero=new int[](m-1);
    writefln("%(%s %)", zero);
  }
}

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

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

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

    Tuple!(int, int)[][] vals;
    foreach (_; 0 .. 2) vals ~= readln.chomp.split.map!(to!int).enumerate.map!(t => tuple(cast(int)t[0], t[1])).array;

    debug { vals.writeln; }

    auto ans = new int[][] (n, m);

    foreach_reverse (b; 0 .. 31) {
        auto cur = 1 << b;

        auto f = (Tuple!(int, int)[] arr) => arr.filter!(t => (t[1] & cur) > 0).map!(t => t[0]).array;
        auto nrs = vals.map!f.array;

        debug { if (b < 4) writeln(cur, ' ', nrs[0], ' ', nrs[1]); }

        if (nrs[0].length % 2 != nrs[1].length % 2) {
            writeln("NO");
            return;
        }

        if (nrs[0].length == 0) {
            foreach (j; nrs[1]) ans[0][j] ^= cur;
        } else if (nrs[1].length == 0) {
            foreach (i; nrs[0]) ans[i][0] ^= cur;
        } else if (nrs[0].length % 2 == 1) { // && nrs[1].length % 2 == 1 from above
            foreach (i; nrs[0]) {
                foreach (j; nrs[1]) {
                    ans[i][j] ^= cur;
                }
            }
        } else {
            while (nrs[0].length < nrs[1].length) nrs[0] ~= nrs[1].back;
            while (nrs[1].length < nrs[0].length) nrs[1] ~= nrs[0].back;
            foreach (i, j; lockstep(nrs[0], nrs[1])) ans[i][j] ^= cur;
        }
    }

    writeln("YES");
    ans.each!(arr => arr.writefln!("%(%s %)"));
}

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

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

    Tuple!(int, int)[][] vals;
    foreach (_; 0 .. 2) vals ~= readln.chomp.split.map!(to!int).enumerate.map!(t => tuple(cast(int)t[0], t[1])).array;

    debug { vals.writeln; }

    auto ans = new int[][] (n, m);

    foreach_reverse (b; 0 .. 31) {
        auto cur = 1 << b;

        auto f = (Tuple!(int, int)[] arr) => arr.filter!(t => (t[1] & cur) > 0).map!(t => t[0]).array;
        auto nrs = vals.map!f.array;

        debug { if (b < 4) writeln(cur, ' ', nrs[0], ' ', nrs[1]); }

        if (nrs[0].length % 2 != nrs[1].length % 2) {
            writeln("NO");
            return;
        }

        if (nrs[0].length == 0) {
            foreach (j; nrs[1]) ans[0][j] ^= cur;
        } else if (nrs[1].length == 0) {
            foreach (i; nrs[0]) ans[i][0] ^= cur;
        } else if (nrs[0].length % 2 == 1) { // && nrs[1].length % 2 == 1 from above
            foreach (i; nrs[0]) {
                foreach (j; nrs[1]) {
                    ans[i][j] ^= cur;
                }
            }
        } else {
            while (nrs[0].length < nrs[1].length) nrs[0] ~= nrs[1].back;
            while (nrs[1].length < nrs[0].length) nrs[1] ~= nrs[0].back;
            foreach (i, j; lockstep(nrs[0], nrs[1])) ans[i][j] ^= cur;
        }
    }

    ans.each!(arr => arr.writefln!("%(%s %)"));
}


The Government of Mars is not only interested in optimizing space flights, but also wants to improve the road system of the planet.One of the most important highways of Mars connects Olymp City and Kstolop, the capital of Cydonia. In this problem, we only consider the way from Kstolop to Olymp City, but not the reverse path (i. e. the path from Olymp City to Kstolop).The road from Kstolop to Olymp City is $$$\ell$$$ kilometers long. Each point of the road has a coordinate $$$x$$$ ($$$0 \le x \le \ell$$$), which is equal to the distance from Kstolop in kilometers. So, Kstolop is located in the point with coordinate $$$0$$$, and Olymp City is located in the point with coordinate $$$\ell$$$.There are $$$n$$$ signs along the road, $$$i$$$-th of which sets a speed limit $$$a_i$$$. This limit means that the next kilometer must be passed in $$$a_i$$$ minutes and is active until you encounter the next along the road. There is a road sign at the start of the road (i. e. in the point with coordinate $$$0$$$), which sets the initial speed limit.If you know the location of all the signs, it's not hard to calculate how much time it takes to drive from Kstolop to Olymp City. Consider an example:  Here, you need to drive the first three kilometers in five minutes each, then one kilometer in eight minutes, then four kilometers in three minutes each, and finally the last two kilometers must be passed in six minutes each. Total time is $$$3\cdot 5 + 1\cdot 8 + 4\cdot 3 + 2\cdot 6 = 47$$$ minutes.To optimize the road traffic, the Government of Mars decided to remove no more than $$$k$$$ road signs. It cannot remove the sign at the start of the road, otherwise, there will be no limit at the start. By removing these signs, the Government also wants to make the time needed to drive from Kstolop to Olymp City as small as possible.The largest industrial enterprises are located in Cydonia, so it's the priority task to optimize the road traffic from Olymp City. So, the Government of Mars wants you to remove the signs in the way described above.

The first line contains three integers $$$n$$$, $$$\ell$$$, $$$k$$$ ($$$1 \le n \le 500$$$, $$$1 \le \ell \le 10^5$$$, $$$0 \le k \le n-1$$$), the amount of signs on the road, the distance between the cities and the maximal number of signs you may remove. The second line contains $$$n$$$ integers $$$d_i$$$ ($$$d_1 = 0$$$, $$$d_i < d_{i+1}$$$, $$$0 \le d_i \le \ell - 1$$$) — coordinates of all signs. The third line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — speed limits.

Print a single integer — minimal possible time to drive from Kstolop to Olymp City in minutes, if you remove no more than $$$k$$$ road signs.

NoteIn the first example, you cannot remove the signs. So the answer is $$$47$$$, as it's said in the statements above.In the second example, you may remove the second and the fourth sign. In this case, you need to drive four kilometers in $$$4\cdot5 = 20$$$ minutes, and then six kilometers in $$$6\cdot3 = 18$$$, so the total time is $$$4\cdot5 + 6\cdot3 = 38$$$ minutes.

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!long;
  auto K = scan!int;
  auto X = scan!long(N) ~ L;
  auto S = scan!long(N) ~ 0;

  auto solve() {
    auto dp = new long[][](N, K + 1);
    foreach(ref p; dp) p[] = int.max;
    dp[0][0] = X[1] * S[0];
    auto preDp = new long[][](N, K + 1);

    foreach(i; 1..N) {
      // dp.deb;
      swap(dp, preDp);
      dp = new long[][](N, K + 1);
      foreach(ref p; dp) p[] = int.max;
      const distance = X[i + 1] - X[i];

      foreach(from; 0..i) {
        foreach(skipped; 0..K) {
          dp[from][skipped + 1].chmin(preDp[from][skipped] + S[from]*distance);
        }
        foreach(skipped; 0..K + 1) {
          dp[i][skipped].chmin(preDp[from][skipped] + S[i]*distance);
        }
      }
    }
    // dp.deb;

    return dp.map!minElement.minElement;
  }

  outputForAtCoder(&solve);
}

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

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

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

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

void main()
{
    immutable int INF = int.max;

    int n, t, k;
    readf!"%s %s %s"(n, t, k);
    readln;

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

    d ~= t;

    auto dp = new int[][] (n+1, k+1);
    dp[n][] = 0;
    foreach (i; 0 .. n) { dp[i][] = INF; }

    foreach_reverse (i; 0 .. n) {
        foreach (maxk; 0 .. k+1) {
            for (int nxt = i+1, leftk = maxk; nxt <= n && leftk >= 0; ++nxt, --leftk) {
                auto cur = dp[nxt][leftk] + (d[nxt] - d[i]) * a[i];
                dp[i][maxk] = min(dp[i][maxk], cur);
            }
        }
    }

    debug { dp.writeln; }

    dp[0][k].writeln;
}

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

void main()
{
    immutable int INF = int.max;

    int n, t, k;
    readf!"%s %s %s"(n, t, k);
    readln;

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

    d ~= t;

    auto dp = new int[][] (n+1, k+1);
    dp[n][] = 0;
    foreach (i; 0 .. n) { dp[i][] = INF; }

    foreach_reverse (i; 0 .. n) {
        foreach (maxk; 0 .. k+1) {
            if (maxk > 0) { dp[i][maxk] = dp[i][maxk-1]; }
            for (int nxt = i+1, leftk = maxk; nxt <= n && leftk >= 0; ++nxt, --leftk) {
                auto cur = dp[nxt][leftk] + (d[nxt] - d[i]) * a[i];
                dp[i][maxk] = min(dp[i][maxk], cur);
            }
        }
    }

    debug { dp.writeln; }

    dp[0][k].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)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

void main()
{
	auto n = RD!int;
	auto l = RD;
	auto k = RD!int;
	auto d = RDA ~ l;
	auto a = RDA;

	auto dp = new long[][](n, k+1);
	foreach (i; 0..n)
		dp[i][] = -1;
	dp[0][k] = 0;
	foreach (i; 1..n)
	{
		auto ndp = new long[][](n, k+1);
		foreach (j; 0..n)
			ndp[j][] = -1;
		foreach (j; 0..i)
		{
			foreach (m; 0..k+1)
			{
				if (dp[j][m] == -1) continue;
				ndp[i][m].chmax(dp[j][m]);
				if (m != 0)
				{
					ndp[j][m-1].chmax(dp[j][m] + (a[i] - a[j]) * (d[i+1] - d[i]));
				}
			}
		}
		dp = ndp;
		debug writeln(dp);
	}

	long ans;
	foreach (i; 0..n)
	{
		ans += a[i] * (d[i+1] - d[i]);
	}
	long tmp;
	foreach (i; 0..n)
	{
		foreach (j; 0..k+1)
		{
			tmp.chmax(dp[i][j]);
		}
	}
	ans -= tmp;

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

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

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

enum int INF = 1<<30;

void main() {
    int N, L, K; readf("%d %d %d\n", &N, &L, &K);
    auto D = readarray!int ~ [L];
    auto A = readarray!int ~ [0];
    N++;

    auto f = new int[][](K + 1, N + 1);
    auto nf = new int[][](K + 1, N + 1);
    foreach (ref l; f) l[] = INF;
    f[0][0] = 0;
    for (int n = 1; n < N; n++) {
        foreach (ref l; nf) l[] = INF;
        int d = D[n] - D[n-1];
        for (int k = 0; k <= min(K, n); k++) {
            for (int s = 0; s < n; s++) {
                nf[k][n] = min(nf[k][n], f[k][s] + d * A[s]);
                if (k + 1 <= min(K, n)) {
                    nf[k + 1][s] = min(nf[k + 1][s], f[k][s] + d * A[s]);
                }
            }
        }
        swap(f, nf);
    }
    int ans = INF;
    for (int k = 0; k <= K; k++) {
        ans = min(ans, f[k].reduce!min);
    }
    writeln(ans);
}

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!long;
  auto K = scan!int;
  auto X = scan!long(N) ~ L;
  auto S = scan!long(N) ~ 0;

  struct Run {
    long time;
    long speed;

    int opCmp(Run other) {
      if (time > other.time) return 1;
      if (time < other.time) return -1;

      return speed > other.speed ? 1 : speed == other.speed ? 0 : -1;
    }
  }

  auto solve() {
    auto dp = new Run[][](N, K + 1);
    foreach(ref d; dp) foreach(ref x; d) x = Run(int.max, int.max);
    dp[0][0] = Run(S[0] * X[1], S[0]);

    foreach(i; 1..N) {
      auto pre = dp[i - 1];
      const d = X[i + 1] - X[i];
      const speed = S[i];

      foreach(k; 0..K) {
        if (pre[k].speed == int.max) continue;

        const preSpeed = pre[k].speed;
        const newTime = pre[k].time + preSpeed * d;
        auto run = Run(newTime, preSpeed);
        dp[i][k + 1].chmin(run);
      }
      foreach(k; 0..K + 1) {
        if (pre[k].speed == int.max) continue;

        const newTime = pre[k].time + speed * d;
        auto run = Run(newTime, speed);
        dp[i][k].chmin(run);
      }
    }

    dp.each!deb;
    // dp.deb;
    return dp[N - 1].map!"a.time".minElement;
  }

  outputForAtCoder(&solve);
}

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

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

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

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!long;
  auto K = scan!int;
  auto X = scan!long(N) ~ L;
  auto S = scan!long(N) ~ 0;

  auto solve() {
    alias Run = Tuple!(long, "time", long, "speed");
    auto dp = new Run[][](N, K + 1);
    foreach(ref d; dp) foreach(ref x; d) x = Run(int.max, int.max);
    dp[0][0] = Run(S[0] * X[1], S[0]);

    foreach(i; 1..N) {
      auto pre = dp[i - 1];
      const d = X[i + 1] - X[i];
      const speed = S[i];

      foreach(k; 0..K) {
        if (pre[k].speed == int.max) continue;

        const preSpeed = pre[k].speed;
        const newTime = pre[k].time + preSpeed * d;
        if (dp[i][k + 1].time > newTime) {
          dp[i][k + 1] = Run(newTime, preSpeed);
        }
      }
      foreach(k; 0..K + 1) {
        if (pre[k].speed == int.max) continue;

        const newTime = pre[k].time + speed * d;
        if (dp[i][k].time > newTime) {
          dp[i][k] = Run(newTime, speed);
        }
      }
    }

    dp.each!deb;
    // dp.deb;
    return dp[N - 1].map!"a.time".minElement;
  }

  outputForAtCoder(&solve);
}

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

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

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

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!long;
  auto K = scan!int;
  auto X = scan!long(N) ~ L;
  auto S = scan!long(N) ~ 0;

  auto solve() {
    alias Run = Tuple!(long, "time", long, "speed");
    auto dp = new Run[][](N, K + 1);
    foreach(ref d; dp) d[] = Run(int.max, int.max);
    dp[0][0] = Run(S[0] * X[1], S[0]);

    foreach(i; 1..N) {
      auto pre = dp[i - 1];
      const d = X[i + 1] - X[i];
      const speed = S[i];

      foreach(k; 0..K) {
        if (pre[k].speed == int.max) continue;

        const preSpeed = pre[k].speed;
        const newTime = pre[k].time + preSpeed * d;
        if (dp[i][k + 1].time > newTime) {
          dp[i][k + 1] = Run(newTime, preSpeed);
        }
      }
      foreach(k; 0..K + 1) {
        if (pre[k].speed == int.max) continue;

        const newTime = pre[k].time + speed * d;
        if (dp[i][k].time > newTime) {
          dp[i][k] = Run(newTime, speed);
        }
      }
    }

    // dp.each!deb;

    // dp.deb;
    return dp[N - 1].map!"a.time".minElement;
  }

  outputForAtCoder(&solve);
}

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

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

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

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!long;
  auto K = scan!int;
  auto X = scan!long(N) ~ L;
  auto S = scan!long(N) ~ 0;

  auto solve() {
    alias Run = Tuple!(long, "time", long, "speed");
    auto dp = new Run[][](N, K + 1);
    foreach(ref d; dp) d[] = Run(int.max, int.max);
    dp[0][0] = Run(S[0] * X[1], S[0]);

    foreach(i; 1..N) {
      auto pre = dp[i - 1];
      const d = X[i + 1] - X[i];
      const speed = S[i];

      foreach(k; 0..K) {
        const preSpeed = pre[k].speed;
        const newTime = pre[k].time + preSpeed * d;
        if (dp[i][k + 1].time > newTime) {
          dp[i][k + 1] = Run(newTime, preSpeed);
        }
      }
      foreach(k; 0..K + 1) {
        const newTime = pre[k].time + speed * d;
        if (dp[i][k].time > newTime) {
          dp[i][k] = Run(newTime, speed);
        }
      }
    }

    // dp.deb;
    return dp[N - 1].map!"a.time".minElement;
  }

  outputForAtCoder(&solve);
}

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

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

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

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!int;
  auto K = scan!int;
  auto X = scan!int(N) ~ L;
  auto S = scan!int(N) ~ 0;

  auto solve() {
    alias Run = Tuple!(long, "time", long, "speed");
    auto dp = new Run[][](N, K + 1);
    foreach(ref d; dp) d[] = Run(int.max, int.max);
    dp[0][0] = Run(S[0] * X[1], S[0]);

    foreach(i; 1..N) {
      auto pre = dp[i - 1];
      const d = X[i + 1] - X[i];
      const speed = S[i];

      foreach(k; 0..K) {
        const preSpeed = pre[k].speed;
        const newTime = pre[k].time + preSpeed * d;
        if (dp[i][k + 1].time > newTime) {
          dp[i][k + 1] = Run(newTime, preSpeed);
        }
      }
      foreach(k; 0..K + 1) {
        const newTime = pre[k].time + speed * d;
        if (dp[i][k].time > newTime) {
          dp[i][k] = Run(newTime, speed);
        }
      }
    }

    // dp.deb;
    return dp[N - 1].map!"a.time".minElement;
  }

  outputForAtCoder(&solve);
}

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

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

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto l = RD;
	auto k = RD!int;
	auto d = RDA ~ l;
	auto a = RDA;

	auto dp = new long[][](n, k+1);
	foreach (i; 1..n)
	{
		auto ndp = new long[][](n, k+1);
		foreach (j; 0..i)
		{
			foreach (m; 0..k+1)
			{
				ndp[i][m].chmax(dp[j][m]);
				if (m != 0)
				{
					ndp[j][m-1].chmax(dp[j][m] + (a[i] - a[j]) * (d[i+1] - d[i]));
				}
			}
		}
		dp = ndp;
		debug writeln(dp);
	}

	long ans;
	foreach (i; 0..n)
	{
		ans += a[i] * (d[i+1] - d[i]);
	}
	long tmp;
	foreach (i; 0..n)
	{
		foreach (j; 0..k+1)
		{
			tmp.chmax(dp[i][j]);
		}
	}
	ans -= tmp;

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


Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning.The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan.First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible.Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation.Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired).Can you help Walter complete his task and gain the gang's trust?

The first line of input contains two integers n, m (2 ≤ n ≤ 105, ), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≤ x, y ≤ n, ) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not.

In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≤ x, y ≤ n, ), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up.  You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any.

NoteIn the first test the only path is 1 - 2In the second test the only shortest path is 1 - 3 - 4In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8

import std.stdio, std.array, std.range, std.string, std.typecons;
import std.algorithm, std.container, std.math, std.numeric, std.random;
void scan(T...)(ref T args) { foreach (ref arg; args) readf(" %s", &arg); }
void minify(T)(ref T a, in T b) { if (a > b) a = b; }
void maxify(T)(ref T a, in T b) { if (a < b) a = b; }
void ewriteln(T...)(T args) { stderr.writeln("\033[35m", args, "\033[0m"); }
int ilen(T)(const ref T a) { return cast(int)(a.length); }

// ok i'm half asleep this was not a good idea (no pun intended)

struct Edge {
	int v1, v2;
	bool w, u;
}

enum int N = 100008;
enum long OO = 10L ^^ 18;
int n, m;
size_t[][N] graph;
long[N] dist;
size_t[N] parent;

int[N] heap;
size_t[N] invheap;
size_t heaplen;

void hpush(int v) {
	heaplen++;
	heap[heaplen] = v;
	invheap[v] = heaplen;
	percUpIx(heaplen);
}
void hswap(size_t i1, size_t i2) {
	swap(heap[i1], heap[i2]);
	swap(invheap[heap[i1]], invheap[heap[i2]]);
}
void percUpIx(size_t ix) {
	if (ix == 1) return;
	size_t parent = ix / 2;
	if (dist[heap[parent]] > dist[heap[ix]]) {
		hswap(parent, ix);
		percUpIx(parent);
	}
}
void percDownIx(size_t ix) {
	size_t tgt = ix;
	foreach (tix; tuple(2*ix, 2*ix + 1)) {
		if (tix <= heaplen && dist[heap[tix]] < dist[heap[tgt]]) {
			tgt = tix;
		}
	}
	if (tgt != ix) {
		hswap(tgt, ix);
		percDownIx(tgt);
	}
}
void percUp(int v) { percUpIx(invheap[v]); }
int hpop() {
	assert(heaplen > 0);
	int ret = heap[1];
	hswap(1, heaplen);
	heaplen--;
	percDownIx(1);
	return ret;
}

Edge[N] edges;

bool[N] vis;

void printDiff() {
	int v = n;
	while (v != 1) {
		auto ei = parent[v];
		edges[ei].u = true;
		Edge e = edges[ei];
		e.u = true;
		assert(v == e.v1 || v == e.v2);
		v = e.v1 ^ e.v2 ^ v;
	}
	int count = 0;
	foreach (ei; 0..m) {
		Edge e = edges[ei];
		if (e.w ^ e.u) {
			count++;
		}
	}
	writeln(count);
	foreach (ei; 0..m) {
		Edge e = edges[ei];
		if (e.w ^ e.u) {
			writeln(e.v1, " ", e.v2, " ", e.u ? 1 : 0);
		}
	}
}

void main() {
	scan(n, m);
	foreach (i; 0..m) {
		int a, b, w;
		scan(a, b, w);
		edges[i] = Edge(a, b, cast(bool)w, false);
		graph[a] ~= i;
		graph[b] ~= i;
	}
	foreach (v; 2..n+1) {
		dist[v] = OO;
	}
	hpush(1);
	while (true) {
		int nxt = hpop();
		vis[nxt] = true;
		if (nxt == n) {
			printDiff();
			return;
		}
		foreach (ei; graph[nxt]) {
			Edge e = edges[ei];
			assert(nxt == e.v1 || nxt == e.v2);
			int other = e.v1 ^ e.v2 ^ nxt;
			long newdist = dist[nxt] + N + (e.w ? -1 : 1);
			if (newdist < dist[other]) {
				parent[other] = ei;
				if (dist[other] == OO) {
					dist[other] = newdist;
					hpush(other);
				} else {
					dist[other] = newdist;
					percUp(other);
				}
			}
		}
	}
}

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

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

//	chmin/chmax
void chmin(T)(ref T t, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int N, M;
int[] A, B, C;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		M = readInt;
		A = new int[M];
		B = new int[M];
		C = new int[M];
		foreach (i; 0 .. M) {
			A[i] = readInt - 1;
			B[i] = readInt - 1;
			C[i] = readInt;
		}

		auto g = new int[][N];
		foreach (i; 0 .. M) {
			g[A[i]] ~= i;
			g[B[i]] ~= i;
		}

		int[] q;
		int[] d = new int[N];
		d[] = -1;
		int[] dp = new int[N];
		dp[] = int.min;
		int[] prv = new int[N];
		prv[] = -1;

		d[0] = 0;
		q ~= 0;
		dp[0] = 0;
		for (; !q.empty; ) {
			const u = q.front; q.popFront;
			foreach (i; g[u]) {
				const v = A[i] ^ B[i] ^ u;
				if (d[v] == -1) {
					d[v] = d[u] + 1;
					q ~= v;
				}
				if (d[v] == d[u] + 1) {
					if (dp[v] < dp[u] + C[i]) {
						dp[v] = dp[u] + C[i];
						prv[v] = i;
					}
				}
			}
		}
debug{
writeln("d = ",d);
writeln("dp = ",dp);
writeln("prv = ",prv);
}

		bool[] used = new bool[M];
		Pair!(int, Pair!(int, int))[] anss;
		for (int u = N - 1; u != 0; ) {
			const i = prv[u];
			used[i] = true;
			if (C[i] == 0) {
				anss ~= pair(1, pair(A[i], B[i]));
			}
			u = A[i] ^ B[i] ^ u;
		}
		foreach (i; 0 .. M) if (!used[i]) {
			if (C[i] == 1) {
				anss ~= pair(0, pair(A[i], B[i]));
			}
		}
		writeln(anss.length);
		foreach (ans; anss) {
			writeln(ans.y.x + 1, " ", ans.y.y + 1, " ", ans.x);
		}

	}
	} catch (EOFException) {}
}


You are given a string $$$s$$$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0for init = 0 to inf    cur = init    ok = true    for i = 1 to |s|        res = res + 1        if s[i] == '+'            cur = cur + 1        else            cur = cur - 1        if cur < 0            ok = false            break    if ok        breakNote that the $$$inf$$$ denotes infinity, and the characters of the string are numbered from $$$1$$$ to $$$|s|$$$.You have to calculate the value of the $$$res$$$ after the process ends.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only lines of each test case contains string $$$s$$$ ($$$1 \le |s| \le 10^6$$$) consisting only of characters + and -. It's guaranteed that sum of $$$|s|$$$ over all test cases doesn't exceed $$$10^6$$$.

For each test case print one integer — the value of the $$$res$$$ after the process ends.

import std.stdio;
import std.range;
import std.algorithm;

void main() {
	int t;
	scanf("%d\n", &t);

	while (t--) {
		auto s = stdin.byLine.front;
		int n = s.length;

		int[] first_neg_i = repeat(-1, n + 3).array;

		int cur = 0;
		foreach (i, c; s) {
			if (c == '-') cur--;
			else cur++;

			if (cur < 0 && first_neg_i[-cur] == -1)
				first_neg_i[-cur] = i + 1;
		}

		long res = 0;
		int next = 1;
		while (true) {
			if (first_neg_i[next] != -1) {
				res += first_neg_i[next++];
			} else {
				res += n;
				break;
			}
		}

		res.writeln;
	}
}

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)
	{
		auto s = readln.strip;
		int balance = 0;
		int lo = 0;
		long res = s.length;
		foreach (i, char c; s)
		{
			balance += (c == '+') ? +1 : -1;
			if (lo > balance)
			{
				lo = balance;
				res += i + 1;
			}
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long last;
		long cnt;
		foreach (i; 0..s.length)
		{
			if (s[i] == '-')
				--cnt;
			else
				++cnt;

			if (cnt < last)
			{
				--last;
				ans[ti] += i+1;
			}
		}
		ans[ti] += s.length;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		long last;
		long cnt;
		foreach (i; 0..s.length)
		{
			if (s[i] == '-')
				--cnt;
			else
				++cnt;

			if (cnt < last)
			{
				--last;
				ans[ti] += i+1;
			}
		}
		ans[ti] += s.length;
	}

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


The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum  is maximal possible. Help George to cope with the task.

The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109).

Print an integer in a single line — the maximum possible value of sum.

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

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

    auto B = new long[](N-M+1);
    B[0] = 0;
    foreach (i; 0..M)
        B[0] += A[i];
    foreach (i; M..N) {
        B[i-M+1] = B[i-M] - A[i-M] + A[i];
    }

    auto dp = new long[][](N-M+1, K);
    foreach (i; 0..N-M+1)
        fill(dp[i], 0);
    dp[0][0] = B[0];

    foreach (i; 1..N-M+1) {
        dp[i][0] = B[i];
        foreach (j; 0..K) {
            dp[i][j] = max(dp[i][j], dp[i-1][j]);
            if (i >= M && j > 0) {
                dp[i][j] = max(dp[i][j], dp[i-M][j-1]+B[i]);
                dp[i][j] = max(dp[i][j], dp[i-M][j]);
            }
        }
    }

    //B.writeln;
    //dp.each!(writeln);
    dp[N-M][K-1].writeln;
}

import std.stdio;
import std.algorithm : max;

void main()
{
    int n, m, k;
    readf("%d %d %d\n", &n, &m, &k);
    auto t = new int[n + 1];
    auto s = new long[n + 1];
    auto w = new long[n + 1];
    auto p = new long[n + 1];
    foreach(i; 1 .. n + 1)
    {
        readf(" %d", &t[i]);
        if (i)
            s[i] = s[i - 1] + t[i];
    }

    foreach(i; 0 .. k)
    {
        foreach(j; m .. n + 1)
            w[j] = max(w[j - 1], p[j - m] + s[j] - s[j - m]);
        p = w.dup;
    }
    writeln(w[n]);
}

import std.stdio;
import std.algorithm;

void main() {
  int n, m, k;
  readf(" %s %s %s", &n, &m, &k);
  auto a = new int [n];
  auto sum = new long [n];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
    sum[i] = a[i];
    if (i > 0) {
      sum[i] += sum[i-1];
    }
  }
  auto f = new long [][] (n, k);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < k; j++) {
      if (i - 1 >= 0) {
        f[i][j] = f[i - 1][j];
      }
      long q = sum[i] - (i - m >= 0 ? sum[i - m] : 0);
      f[i][j] = max(f[i][j], (i - m >= 0 && j - 1 >= 0 ? f[i - m][j - 1] : 0) + q);
      if (i - 1 >= 0) {
        f[i][j] = max(f[i - 1][j], f[i][j]);
      }
    }
  }
  writeln(f[n - 1][k - 1]);
}

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

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

    auto B = new long[](N-M+1);
    B[0] = 0;
    foreach (i; 0..M)
        B[0] += A[i];
    foreach (i; M..N) {
        B[i-M+1] = B[i-M] - A[i-M] + A[i];
    }

    auto dp = new long[][](N-M+1, K);
    foreach (i; 0..N-M+1)
        fill(dp[i], 0);
    dp[0][0] = B[0];

    foreach (i; 1..N-M+1) {
        dp[i][0] = max(dp[i-1][0], B[i]);
        foreach (j; 1..K) {
            if (i >= M)
                dp[i][j] = max(dp[i-1][j-1]+B[i], dp[i-1][j]);
        }
    }

    dp[N-M][K-1].writeln;
}

import std.stdio;
import std.algorithm : max;

void main()
{
    int n, m, k;
    readf("%d %d %d\n", &n, &m, &k);
    auto t = new int[n + 1];
    auto s = new long[n + 1];
    auto w = new long[n + 1];
    auto p = new long[n + 1];
    foreach(i; 1 .. n + 1)
    {
        readf(" %d", &t[i]);
        if (i)
            s[i] = s[i - 1] + t[i];
    }

    foreach(i; 0 .. k)
    {
        writeln(s);
        writeln(w);
        foreach(j; m .. n + 1)
            w[j] = max(w[j - 1], p[j - m] + s[j] - s[j - m]);
        p = w.dup;
    }
    writeln(w[n]);
}