ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of rows of seats in the bus. Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.  Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.

If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output). If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line. If there are multiple solutions, you may print any of them.

NoteNote that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.O+|+XXO|XXOX|OOXX|OXOO|OOOO|XX

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

struct IO {
        string read_string() {
                while (tokens.empty) {
                tokens = readln.split;
        }
        auto token = tokens.front;
                tokens.popFront;
                return token;
        }

        int read_int() {
                return read_string.to!int;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // int t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                char[][] v = new char[][n];
                bool seat_found = false;
                for (int i = 0; i < n; i++) {
                        v[i] = new char[5];
                        v[i] = cin.read_string.dup;
                }

                for (int i = 0; i < n; i++) {
                        bool flag1 = (v[i][0] == 'O' && v[i][1] == 'O');
                        bool flag2 = (v[i][3] == 'O' && v[i][4] == 'O');
                        if (!seat_found && flag1) {
                                seat_found = true;
                                v[i][0] = '+';
                                v[i][1] = '+';
                        } else if (!seat_found && flag2) {
                                seat_found = true;
                                v[i][3] = '+';
                                v[i][4] = '+';
                        }
                }

                if (!seat_found) writeln("NO");
                else {
                        writeln("YES");
                        foreach (i; v) {
                                foreach(j; i)
                                        write(j);
                                writeln();
                        }
                }
        }
}

import std.stdio;

void position(int n, int row, int col, char[6][1000] rows)
{
	rows[row][col] = rows[row][col + 1] = '+';

	printf("YES\n");
	for (int i = 0; i < n; i++) {
		printf("%s\n", rows[i].ptr);
	}
}

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

	char[6][1000] rows;
	for (int i = 0; i < n; i++) {
		scanf("%s", rows[i].ptr);
	}

	for (int i = 0; i < n; i++) {
		if (rows[i][0] == 'O' && rows[i][1] == 'O') {
			position(n, i, 0, rows);
			return;
		}
		if (rows[i][3] == 'O' && rows[i][4] == 'O') {
			position(n, i, 3, rows);
			return;
		}
	}

	printf("NO\n");
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.math;
import std.array;

int main(string[] argv)
{
	int n;
	scanf("%d\n", &n);
	string[] seats; seats.length = n;
	foreach (int i; 0..n)
	{
		seats[i] = readln();
	}
	bool there_is_seat = false;
	foreach (int i; 0..n)
	{
		if (canFind(seats[i], "OO") == true)
		{
			there_is_seat = true;
			seats[i] = replaceFirst(seats[i], "OO", "++");
			break;
		}
	}
	printf(there_is_seat ? "YES\n" : "NO");
	if (there_is_seat)
	{
		foreach (int i; 0..n)
		{
			write(seats[i]);
		}
	}
	return 0;
}

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

struct IO {
        string read_string() {
                while (tokens.empty) {
                tokens = readln.split;
        }
        auto token = tokens.front;
                tokens.popFront;
                return token;
        }

        int read_int() {
                return read_string.to!int;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // int t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                char[][] v = new char[][n];
                bool seat_found = false;
                for (int i = 0; i < n; i++) {
                        v[i] = new char[5];
                        v[i] = cin.read_string.dup;
                }

                for (int i = 0; i < n; i++) {
                        bool flag1 = (v[i][0] == 'O' && v[i][1] == 'O');
                        bool flag2 = (v[i][3] == 'O' && v[i][4] == 'O');
                        if (!seat_found && flag1) {
                                seat_found = true;
                                v[i][0] = '+';
                                v[i][1] = '+';
                        } else if (!seat_found && flag2) {
                                seat_found = true;
                                v[i][3] = '+';
                                v[i][4] = '+';
                        }
                }

                if (!seat_found) writeln("NO");
                else {
                        foreach (i; v) {
                                foreach(j; i)
                                        write(j);
                                writeln();
                        }
                }
        }
}

import std.stdio;

void position(int n, int row, int col, char[1000][6] rows)
{
	rows[row][col] = rows[row][col + 1] = '+';

	for (int i = 0; i < n; i++) {
		printf("%s\n", rows[i].ptr);
	}
}

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

	char[1000][6] rows;
	for (int i = 0; i < n; i++) {
		scanf("%s", rows[i].ptr);
	}

	for (int i = 0; i < n; i++) {
		if (rows[i][0] == 'O' && rows[i][1] == 'O') {
			position(n, i, 0, rows);
			return;
		}
		if (rows[i][3] == 'O' && rows[i][4] == 'O') {
			position(n, i, 3, rows);
			return;
		}
	}

	printf("NO\n");
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.math;
import std.array;

int main(string[] argv)
{
	int n;
	scanf("%d\n", &n);
	string[] seats; seats.length = n;
	foreach (int i; 0..n)
	{
		seats[i] = readln();
	}
	bool there_is_seat = false;
	foreach (int i; 0..n)
	{
		if (canFind(seats[i], "OO") == true)
		{
			there_is_seat = true;
			seats[i] = replace(seats[i], "OO", "++");
			break;
		}
	}
	printf(there_is_seat ? "YES\n" : "NO");
	if (there_is_seat)
	{
		foreach (int i; 0..n)
		{
			write(seats[i]);
		}
	}
	return 0;
}


Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this:  Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result:  He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.

NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.

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()
{
    int t;
    readf("%s", &t);
    readln;

    while (t--) {
        int n;
        readf("%s", &n);
        readln;

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

        auto le = a[0 .. n];
        auto r = a[n .. $];

        debug { writeln(le); writeln(r); }

        int go(int[] a, int[] b) {
            int[int] sc;
            sc[0] = n;
            int cur = 0;
            foreach (i, e; a.enumerate(1)) {
                if (e == 1) { cur += 1; }
                else { cur -= 1; }

                sc[cur] = n - i;
            }

            debug { sc.writeln; }

            int eat = sc[0] + n;
            int now = 0;
            foreach_reverse (i, e; b) {
                if (e == 1) { now -= 1; }
                else { now += 1; }

                if (now !in sc) { continue; }

                eat = min(eat, i + sc[now]);
            }

            return eat;
        }

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

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

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

		int cnt;
		foreach (i; 0..n*2)
			cnt += (a[i] == 0 ? -1 : 1);
		auto b = new int[](n+1);
		foreach (i; 0..n)
		{
			b[i+1] = b[i] + (a[n-i-1] == 0 ? -1 : 1);
		}
		auto c = new int[](n+1);
		foreach (i; 0..n)
		{
			c[i+1] = c[i] + (a[n+i] == 0 ? -1 : 1);
		}
		int[int] set;
		foreach (i; 0..n+1)
		{
			auto v = set.get(b[i], int.max);
			set[b[i]] = min(v, i);
		}
		int tmp = int.max;
		foreach (i; 0..n+1)
		{
			auto remain = cnt - c[i];
			auto v = set.get(remain, -1);
			if (v != -1)
				tmp.chmin(i + v);
			debug writeln("cnt:", cnt, " c[i]:", c[i]);
			debug writeln(i, ":", tmp);
		}
		ans[ti] = tmp;
	}

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

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

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

		int[int[]] memo;
		int dfs(int l, int r, int[] cnt)
		{
			auto diff = cnt[0] - cnt[1];
			if (diff == 0) return r-l;
			auto m = memo.get([l, r], -1);
			if (m != -1) return m;

			auto high = diff > 0 ? 0 : 1;
			int r1 = int.max, r2 = int.max;
			if (l != 0)
			{
				if (a[l-1] == high || abs(diff)+1 < l-1)
				{
					auto tmp = cnt.dup;
					--tmp[a[l-1]];
					r1 = dfs(l-1, r, tmp);
				}
			}
			if (r != n*2)
			{
				if (a[r] == high || abs(diff)+1 < n*2 - r - 1)
				{
					auto tmp = cnt.dup;
					--tmp[a[r]];
					r2 = dfs(l, r+1, tmp);
				}
			}
			memo[[l, r].idup] = min(r1, r2);
			return min(r1, r2);
		}

		int[] cnt = [0, 0];
		foreach (e; a)
			++cnt[e];
		ans[ti] = dfs(n, n, cnt);
	}

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

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

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

		int[int[]] memo;
		int dfs(int l, int r, int[] cnt)
		{
			auto diff = cnt[0] - cnt[1];
			if (diff == 0) return r-l;
			auto m = memo.get([l, r], -1);
			if (m != -1) return m;

			auto high = diff > 0 ? 0 : 1;
			int r1 = int.max, r2 = int.max;
			if (l != 0)
			{
				if (a[l-1] == high || diff+1 < l-1)
				{
					auto tmp = cnt.dup;
					--tmp[a[l-1]];
					r1 = dfs(l-1, r, tmp);
				}
			}
			if (r != n*2)
			{
				if (a[r] == high || diff+1 < n*2 - r - 1)
				{
					auto tmp = cnt.dup;
					--tmp[a[r]];
					r2 = dfs(l, r+1, tmp);
				}
			}
			memo[[l, r].idup] = min(r1, r2);
			return min(r1, r2);
		}

		int[] cnt = [0, 0];
		foreach (e; a)
			++cnt[e];
		ans[ti] = dfs(n, n, cnt);
	}

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

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

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

		int[int[]] memo;
		int dfs(int l, int r, int[] cnt)
		{
			auto diff = cnt[0] - cnt[1];
			if (diff == 0) return r-l;
			auto m = memo.get([l, r], -1);
			if (m != -1) return m;

			auto high = diff > 0 ? 0 : 1;
			int r1 = int.max, r2 = int.max;
			if (l != 0)
			{
				if (a[l-1] == high || abs(diff)+1 <= l-1)
				{
					auto tmp = cnt.dup;
					--tmp[a[l-1]];
					r1 = dfs(l-1, r, tmp);
				}
			}
			if (r != n*2)
			{
				if (a[r] == high || abs(diff)+1 <= n*2 - r - 1)
				{
					auto tmp = cnt.dup;
					--tmp[a[r]];
					r2 = dfs(l, r+1, tmp);
				}
			}
			memo[[l, r].idup] = min(r1, r2);
			return min(r1, r2);
		}

		int[] cnt = [0, 0];
		foreach (e; a)
			++cnt[e];
		ans[ti] = dfs(n, n, cnt);
	}

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


You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of points on the line. The second line contains n integers xi ( - 109 ≤ xi ≤ 109) — the coordinates of the given n points.

Print the only integer x — the position of the optimal point on the line. If there are several optimal points print the position of the leftmost one. It is guaranteed that the answer is always the integer.

import std.stdio;
import std.algorithm;

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

	int[] p = new int[n];
	for (int i = 0; i < n; i++) {
		scanf("%d", &p[i]);
	}

	p.sort();

	printf("%d\n", p[(n - 1) / 2]);
}

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

void main ()
{
	auto n = readln.strip.to !(int);
	auto a = readln.split.map !(to !(int)).array;
	sort (a);
	writeln (a[(n - 1) / 2]);
}

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

void main ()
{
	auto n = readln.strip.to !(int);
	auto a = readln.split.map !(to !(int)).array;
	writeln (a[(n - 1) / 2]);
}


For the multiset of positive integers $$$s=\{s_1,s_2,\dots,s_k\}$$$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $$$s$$$ as follow: $$$\gcd(s)$$$ is the maximum positive integer $$$x$$$, such that all integers in $$$s$$$ are divisible on $$$x$$$. $$$\textrm{lcm}(s)$$$ is the minimum positive integer $$$x$$$, that divisible on all integers from $$$s$$$.For example, $$$\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$$$ and $$$\textrm{lcm}(\{4,6\})=12$$$. Note that for any positive integer $$$x$$$, $$$\gcd(\{x\})=\textrm{lcm}(\{x\})=x$$$.Orac has a sequence $$$a$$$ with length $$$n$$$. He come up with the multiset $$$t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}$$$, and asked you to find the value of $$$\gcd(t)$$$ for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.

The first line contains one integer $$$n\ (2\le n\le 100\,000)$$$. The second line contains $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 200\,000$$$).

Print one integer: $$$\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\})$$$.

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

long lcm(long a, long b)
{
    return a * b / gcd(a, b);
}

void main()
{
    auto N = readln.chomp.to!int;
    auto as = readln.split.to!(long[]);
    auto ls = new long[](N);
    ls[0] = as[0];
    foreach (i; 1..N) ls[i] = gcd(as[i], ls[i-1]);
    auto rs = new long[](N);
    rs[$-1] = as[$-1];
    foreach_reverse (i; 0..N-1) rs[i] = gcd(as[i], rs[i+1]);

    auto x = rs[1];
    foreach (i; 1..N-1) x = lcm(x, gcd(ls[i-1], rs[i+1]));
    writeln(lcm(x, ls[$-2]));
}

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

void main ()
{
	immutable int limit = 200_001;

	auto s = new int [limit];
	for (int d = 2; d < limit; d++)
	{
		if (s[d] == 0)
		{
			s[d] = d;
			for (int e = d; e * 1L * d < limit; e++)
			{
				if (s[e * d] == 0)
				{
					s[e * d] = d;
				}
			}
		}
	}

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto num = new int [] [limit];
		foreach (c; readln.splitter.map !(to !(int)))
		{
			int [int] fact;
			while (s[c] > 0)
			{
				fact[s[c]] += 1;
				c /= s[c];
			}
			foreach (prime, power; fact)
			{
				num[prime] ~= power;
			}
		}
		long res = 1;
		foreach (prime, ref list; num)
		{
			if (list.length >= n - 1)
			{
				sort !(q{a > b}) (list);
				res *= prime ^^ list[n - 2];
			}
		}
		writeln (res);
	}
}

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

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

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

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

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

      const lim = A.maxElement + 1;
      auto ess = new int[][lim];

      foreach (i; 0 .. N) {
        int a = A[i];
        for (int p = 2; p^^2 <= a; ++p) {
          if (a % p == 0) {
            int e;
            do {
              ++e;
              a /= p;
            } while (a % p == 0);
            ess[p] ~= e;
          }
        }
        if (a > 1) {
          ess[a] ~= 1;
        }
      }

      long ans = 1;
      foreach (p; 2 .. lim) {
        if (ess[p].length >= N - 1) {
          ess[p].sort;
          ess[p].reverse;
          ans *= p^^ess[p][N - 2];
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	immutable int limit = 200_001;

	auto s = new int [limit];
	for (int d = 2; d * d < limit; d++)
	{
		if (s[d] == 0)
		{
			s[d] = d;
			for (int e = d * d; e < limit; e += d)
			{
				if (s[e] == 0)
				{
					s[e] = d;
				}
			}
		}
	}

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto num = new int [] [limit];
		foreach (c; readln.splitter.map !(to !(int)))
		{
			int [int] fact;
			while (s[c] > 0)
			{
				fact[s[c]] += 1;
				c /= s[c];
			}
			foreach (prime, power; fact)
			{
				num[prime] ~= power;
			}
		}
		long res = 1;
		foreach (prime, ref list; num)
		{
			if (list.length >= n - 1)
			{
				sort !(q{a > b}) (list);
				res *= prime ^^ list[n - 2];
			}
		}
		writeln (res);
	}
}


You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.

The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≤ |si| ≤ 100), one per line. The total length of strings is not greater than 100. The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≤ ai, bi ≤ n + i - 1) — the number of strings that are concatenated to form sn + i.

Print m lines, each should contain one integer — the answer to the question after the corresponding operation.

NoteOn the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.On the second operation the string "01100" is created. Now all strings of length k = 2 are present.On the third operation the string "1111111111" is created. There is no zero, so the answer is 0.

import std.algorithm, std.conv, std.stdio, std.string;
struct S {
	string s;
	bool [] [9] m;

	this (string r) {
		s = r;
		foreach (w; 1..9)
			m[w] = new bool [1 << w];
		foreach (w; 1..9)
			foreach (p; w..s.length + 1)
				m[w][s[p - w..p].to !(int) (2)] = 1;
	}

	this (S a, S b) {
		s = a.s ~ b.s;
		if (s.length > 2 * 9)
			s = s[0..9] ~ "*" ~ s[$ - 9..$];
		foreach (w; 1..9)
			m[w] = a.m[w].dup,
			m[w][] |= b.m[w][];
		foreach (x; 1..a.s.length + 1)
			foreach (y; 1..b.s.length + 1)
				if (x + y < 9)
					m[x + y][(a.s[$ - x..$] ~ b.s[0..y]).to !(int) (2)] = 1;
	}
}

void main () {
	S [] s;
	foreach (i; 0..readln.strip.to!int)
		s ~= S (readln.strip);
	foreach (j; 0..readln.strip.to!int) {
		int u, v;
		readf (" %s %s", &u, &v);
		s ~= S (s[u - 1], s[v - 1]);
		s[$ - 1].m[1..$].countUntil !(x => !x.all).writeln;
	}
}

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

immutable int limit = 15;

struct LongString
{
	string s;
	bool [] [limit] mark;

	this (string r)
	{
		s = r;
		foreach (len; 1..limit)
		{
			mark[len] = new bool [1 << len];
		}
		foreach (pos; 0..s.length)
		{
			foreach (len; 1..limit)
			{
				if (pos + len <= s.length)
				{
					auto t = s[pos..pos + len]
					    .to !(int) (2);
					mark[len][t] = true;
				}
			}
		}
		if (s.length > 2 * limit)
		{
			s = s[0..limit] ~ "*" ~ s[$ - limit..$];
		}
		debug {writeln (s, ": ", mark[].map !(sum));}
	}

	this (LongString a, LongString b)
	{
		s = a.s ~ b.s;
		foreach (len; 1..limit)
		{
			mark[len] = new bool [1 << len];
			mark[len][] |= a.mark[len][];
			mark[len][] |= b.mark[len][];
		}
		foreach (x; 1..a.s.length + 1)
		{
			foreach (y; 1..b.s.length + 1)
			{
				if (x + y < limit)
				{
					auto t = (a.s[$ - x..$] ~ b.s[0..y])
					    .to !(int) (2);
					mark[x + y][t] = true;
				}
			}
		}
		if (s.length > 2 * limit)
		{
			s = s[0..limit] ~ "*" ~ s[$ - limit..$];
		}
		debug {writeln (s, ": ", mark[].map !(sum));}
	}

	int fullness ()
	{
		foreach (len; 1..limit)
		{
			if (!all (mark[len]))
			{
				return len - 1;
			}
		}
		return limit - 1;
	}
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		LongString [] s;
		foreach (i; 0..n)
		{
			auto t = readln.strip;
			s ~= LongString (t);
		}

		int m;
		readf (" %s", &m);
		foreach (j; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			s ~= LongString (s[u], s[v]);
			writeln (s.back.fullness);
		}
	}
}

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

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

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

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

enum K = 10;

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

      auto heads = new string[N + M];
      auto tails = new string[N + M];
      auto has = new bool[][][](N + M, K);
      foreach (i; 0 .. N + M) {
        foreach (k; 0 .. K) {
          has[i][k] = new bool[1 << k];
        }
      }
      foreach (i; 0 .. N) {
        const len = cast(int)(S[i].length);
        if (len > K) {
          heads[i] = S[i][0 .. K];
          tails[i] = S[i][$ - K .. $];
        } else {
          heads[i] = tails[i] = S[i];
        }
        foreach (k; 1 .. K) {
          foreach (x; 0 .. len - k + 1) {
            int p;
            foreach (l; 0 .. k) {
              p |= (S[i][x + l] - '0') << l;
            }
            has[i][k][p] = true;
          }
        }
      }

      foreach (j; 0 .. M) {
        const i = N + j;
        heads[i] = heads[A[j]] ~ heads[B[j]];
        if (heads[i].length > K) {
          heads[i] = heads[i][0 .. K];
        }
        tails[i] = tails[A[j]] ~ tails[B[j]];
        if (tails[i].length > K) {
          tails[i] = tails[i][$ - K .. $];
        }
        foreach (k; 1 .. K) {
          foreach (p; 0 .. 1 << k) {
            has[i][k][p] = has[A[j]][k][p] || has[B[j]][k][p];
          }
        }
        const lenA = cast(int)(tails[A[j]].length);
        const lenB = cast(int)(heads[B[j]].length);
        foreach (kA; 1 .. lenA + 1) foreach (kB; 1 .. lenB + 1) {
          if (kA + kB < K) {
            int p;
            foreach (l; 0 .. kA) {
              p |= (tails[A[j]][lenA - kA + l] - '0') << l;
            }
            foreach (l; 0 .. kB) {
              p |= (heads[B[j]][l] - '0') << (kA + l);
            }
            has[i][kA + kB][p] = true;
          }
        }
        int ans;
        foreach (k; 1 .. K) {
          if (has[i][k].all) {
            ans = k;
          }
        }
        writeln(ans);
      }

    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum K = 10;

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

      auto heads = new string[N + M];
      auto tails = new string[N + M];
      auto has = new bool[][][](N + M, K);
      foreach (i; 0 .. N + M) {
        foreach (k; 0 .. K) {
          has[i][k] = new bool[1 << k];
        }
      }
      foreach (i; 0 .. N) {
        const len = cast(int)(S[i].length);
        heads[i] = S[i][0 .. min(K - 1, len)];
        tails[i] = S[i][len - min(K - 1, len) .. len];
        foreach (k; 1 .. K) {
          foreach (x; 0 .. len - k + 1) {
            int p;
            foreach (l; 0 .. k) {
              p |= (S[i][x + l] - '0') << l;
            }
            debug {
              writeln(i, " ", k, " ", p);
            }
            has[i][k][p] = true;
          }
        }
      }

      foreach (j; 0 .. M) {
        const i = N + j;
        heads[i] = heads[A[j]] ~ heads[B[j]];
        if (heads[i].length > K - 1) {
          heads[i] = heads[i][0 .. K - 1];
        }
        tails[i] = tails[A[j]] ~ tails[B[j]];
        if (tails[i].length > K - 1) {
          tails[j] = tails[i][$ - (K - 1) .. $];
        }
        foreach (k; 1 .. K) {
          foreach (p; 0 .. 1 << k) {
            has[i][k][p] = has[A[j]][k][p] || has[B[j]][k][p];
          }
        }
        debug {
          writeln(tails[A[j]], " ", heads[B[j]]);
        }
        const lenA = cast(int)(tails[A[j]].length);
        const lenB = cast(int)(heads[B[j]].length);
        foreach (kA; 1 .. lenA + 1) foreach (kB; 1 .. lenB + 1) {
          if (kA + kB < K) {
            int p;
            foreach (l; 0 .. kA) {
              p |= (tails[A[j]][$ - 1 - l] - '0') << l;
            }
            foreach (l; 0 .. kB) {
              p |= (heads[B[j]][l] - '0') << (kA + l);
            }
            debug {
              writeln(i, " ", kA, " ", kB, " ", p);
            }
            has[i][kA + kB][p] = true;
          }
        }
        int ans;
        foreach (k; 1 .. K) {
          if (has[i][k].all) {
            ans = k;
          }
        }
        writeln(ans);
      }

    }
  } catch (EOFException e) {
  }
}


Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.

The first line contains the single integer n (1 ≤ n ≤ 1000) — the number of contests where the coder participated. The next line contains n space-separated non-negative integer numbers — they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.

Print the single number — the number of amazing performances the coder has had during his whole history of participating in the contests.

NoteIn the first sample the performances number 2 and 3 are amazing.In the second sample the performances number 2, 4, 9 and 10 are amazing.

import std.stdio;

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

	int max, min;
	readf(" %s", &min);
	max = min;
	int counter, temp;
	for (int i = 1; i < n; i++) {
		readf(" %s", &temp);
		if (temp > max) {
			counter++;
			max = temp;
		}

		if (temp < min) {
			counter++;
			min = temp;
		}
	}

	writeln(counter);
}

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

void main() {
	readln;
	auto nums = to!(int[])(readln.split);
	int max_point = nums[0], min_point = nums[0];
	int count_amazing;
	foreach(m; nums[1..$]){
		if(m > max_point){
			max_point = m;
			count_amazing++;
		}
		else if (m < min_point){
			min_point = m;
			count_amazing++;
		}
	}
	writeln(count_amazing);
}

import std.stdio
    , std.typecons
    , std.traits
    , std.algorithm
    , std.range
    , std.container;

void main() {
    alias insertion_sort = bad_insertion_sort;
    int n;
    int[] data;
    readf("%s\n", &n);

    {
        int t; readf("%s ", &t);
        data ~= t;
    }

    insertion_sort(data);

    uint much_wow;

    for(int i; i < n - 1; ++i) {
        int t;
        readf("%s ", &t);
        if(t > data[$ - 1] || t < data[0]) {
            ++much_wow;
        }
        data ~= t;
        insertion_sort(data);

        //data.writeln();
    }

    much_wow.writeln();
}

void bad_insertion_sort(T, alias pred = (c, d) => c < d)(T[] data) @nogc {
    foreach (i, immutable value; data[1 .. $]) {
        auto j = i + 1;
        for ( ; j > 0 && pred(value, data[j - 1]); --j) {
            data[j] = data[j - 1];
        }
        data[j] = value;
    }
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;

int main(string[] argv)
{
	int n, e;
	scanf("%d %d", &n, &e);
	int max = e;
	int min = e;
	int count = 0;
	foreach (int i; 1..n)
	{
		scanf("%d", &e);
		if (e > max)
		{
			count++;
			max = e;
		}
		else if (e < min)
		{
			count++;
			min = e;
		}
	}
	write(count);
	return 0;
}

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

void main() {
    int n = readln.chomp.to!int;
    auto p = readln.chomp.split.map!(to!int);

    int max = p[0];
    int min = p[0];
    int cnt = 0;
    for (int i = 1; i < n; i++) {
        if (max < p[i]) {
            cnt++;
            max = p[i];
        } else if (min > p[i]) {
            cnt++;
            min = p[i];
        }
    }

    cnt.writeln;
}


It is a holiday season, and Koala is decorating his house with cool lights! He owns $$$n$$$ lights, all of which flash periodically.After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters $$$a_i$$$ and $$$b_i$$$. Light with parameters $$$a_i$$$ and $$$b_i$$$ will toggle (on to off, or off to on) every $$$a_i$$$ seconds starting from the $$$b_i$$$-th second. In other words, it will toggle at the moments $$$b_i$$$, $$$b_i + a_i$$$, $$$b_i + 2 \cdot a_i$$$ and so on.You know for each light whether it's initially on or off and its corresponding parameters $$$a_i$$$ and $$$b_i$$$. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out.    Here is a graphic for the first example.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$), the number of lights. The next line contains a string $$$s$$$ of $$$n$$$ characters. The $$$i$$$-th character is "1", if the $$$i$$$-th lamp is initially on. Otherwise, $$$i$$$-th character is "0". The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 5$$$)  — the parameters of the $$$i$$$-th light.

Print a single integer — the maximum number of lights that will ever be on at the same time.

NoteFor first example, the lamps' states are shown in the picture above. The largest number of simultaneously on lamps is $$$2$$$ (e.g. at the moment $$$2$$$).In the second example, all lights are initially on. So the answer is $$$4$$$.

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return read.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtype!real;
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void solve(){
	int n = rint;
	string s = read;
	X[] xs;
	foreach(i; 0 .. n) xs ~= X(s[i] == '1', rint, rint);

	int ans = 0;
	foreach(t; 0 .. 200){
		int tmp = 0;
		foreach(i, x; xs){
			bool isNot;
			if(t < x.b) isNot = 0;
			else if((t - x.b) / x.a % 2 == 0) isNot = 1;
			else isNot = 0;

			if(isNot ^x.isOn) tmp += 1;
			if(t < 20) log("t:", t, "i:", i, "x:", x, "isNot:" , isNot, "tmp:", tmp);
		}
		ans = max(ans, tmp);
	}

	ans.writeln;
}
struct X{
	bool isOn;
	int a, b;
}

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

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

void main()
{
	auto n = RD!int;
	auto s = RD!string;
	auto a = new long[](n);
	auto b = new long[](n);
	foreach (i; 0..n)
	{
		a[i] = RD;
		b[i] = RD;
	}

	auto c = new int[](n);
	foreach (i; 0..n)
		c[i] = s[i] == '1' ? 1 : 0;

	long ans = c.sum;
	foreach (_; 0..10^^4)
	{
		b[] -= 1;
		foreach (i; 0..n)
		{
			if (b[i] == 0)
			{
				c[i] ^= 1;
				b[i]  = a[i];
			}
		}
		ans = max(ans, c.sum);
	}

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


This is an interactive problem. In the output section below you will see the information about flushing the output.Bear Limak thinks of some hidden number — an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.Integer x > 1 is called prime if it has exactly two distinct divisors, 1 and x. If integer x > 1 is not prime, it's called composite.You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2, 100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.When you are done asking queries, print "prime" or "composite" and terminate your program.You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2, 100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).

After each query you should read one string from the input. It will be "yes" if the printed integer is a divisor of the hidden number, and "no" otherwise.

Up to 20 times you can ask a query — print an integer from interval [2, 100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input. In any moment you can print the answer "prime" or "composite" (without the quotes). After that, flush the output and terminate your program. To flush you can use (just after printing an integer and end-of-line):    fflush(stdout) in C++;  System.out.flush() in Java;  stdout.flush() in Python;  flush(output) in Pascal;  See the documentation for other languages.  Hacking. To hack someone, as the input you should print the hidden number — one integer from the interval [2, 100]. Of course, his/her solution won't be able to read the hidden number from the input.

NoteThe hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.59 is a divisor of the hidden number. In the interval [2, 100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries).

import core.bitop;
import core.checkedint;
import core.simd;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

bool ask(int x) {
    writeln(x);
    stdout.flush();
    static char[4] storage;
    auto s = storage[ ];
    readln(s);
    return s[0] == 'y';
}

void main() {
    bool found;
    foreach (x; [2, 3, 5, 7])
        if (ask(x)) {
            if (found) {
                write("composite\n");
                return;
            }
            found = true;
            foreach (y; [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]) {
                if (x * y > 100)
                    break;
                if (ask(x * y)) {
                    write("composite\n");
                    return;
                }
            }
        }
    write("prime\n");
}

import std.stdio;
import std.string;

void main ()
{
	int divs = 0;
	foreach (p; 2..51)
	{
		bool ok = true;
		for (int d = 2; d * d <= p; d++)
		{
			if (p % d == 0)
			{
				ok = false;
			}
		}
		if (!ok)
		{
			continue;
		}
		writeln (p);
		stdout.flush ();
		bool cur = (readln.strip == "yes");
		divs += cur;
		if (cur && p * p <= 100)
		{
			writeln (p * p);
			stdout.flush ();
			bool next = (readln.strip == "yes");
			divs += next;
		}
	}
	writeln (divs > 1 ? "composite" : "prime");
}

import core.bitop;
import core.checkedint;
import core.simd;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

enum primes = [2, 3, 5, 7];

void main() {
    char[3] storage;
    foreach (x; primes) {
        writeln(x);
        stdout.flush();
        auto s = storage[ ];
        readln(s);
        if (s[0] == 'y') {
            write("composite\n");
            return;
        }
    }
    write("prime\n");
}

import core.bitop;
import core.checkedint;
import core.simd;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

enum primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71];

void main() {
    char[4] storage;
    foreach (x; primes) {
        writeln(x);
        stdout.flush();
        auto s = storage[ ];
        readln(s);
        if (s[0] == 'y') {
            write("composite\n");
            return;
        }
    }
    write("prime\n");
}

import core.bitop;
import core.checkedint;
import core.simd;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

char[4] storage;

bool ask(int x) {
    writeln(x);
    stdout.flush();
    auto s = storage[ ];
    readln(s);
    return s[0] == 'y';
}

void main() {
    bool found;
    foreach (x; [2, 3, 5, 7])
        if (ask(x)) {
            if (found) {
                write("composite\n");
                return;
            }
            found = true;
            foreach (y; [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47])
                if (ask(x * y)) {
                    write("composite\n");
                    return;
                }
        }
    write("prime\n");
}

import core.bitop;
import core.checkedint;
import core.simd;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

char[4] storage;

bool ask(int x) {
    writeln(x);
    stdout.flush();
    auto s = storage[ ];
    readln(s);
    return s[0] == 'y';
}

void main() {
    bool found;
    foreach (x; [2, 3, 5, 7])
        if (ask(x)) {
            if (found) {
                write("composite\n");
                return;
            }
            found = true;
            foreach (y; [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]) {
                if (x * y > 100)
                    break;
                if (ask(x * y)) {
                    write("composite\n");
                    return;
                }
            }
        }
    write("prime\n");
}

import core.bitop;
import core.checkedint;
import core.simd;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

enum primes = [2, 3, 5, 7];

void main() {
    char[4] storage;
    foreach (x; primes) {
        writeln(x);
        stdout.flush();
        auto s = storage[ ];
        readln(s);
        if (s[0] == 'y') {
            write("composite\n");
            return;
        }
    }
    write("prime\n");
}

import std.stdio;
import std.string;

void main ()
{
	bool ok = false;
	foreach (p; [2, 3, 5, 7])
	{
		writeln (p);
		stdout.flush ();
		ok |= readln.strip == "yes";
	}
	writeln (ok ? "composite" : "prime");
}


Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.

The first line contains an integer n (1 ≤ n ≤ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.

Print "YES" or "NO" (without the quotes) depending on the answer to the problem.

import std.stdio;
import std.math;
import std.array;
import std.algorithm;

bool solve(char[][] c){
  size_t n = c.length;
  for(int i = 0; i < n; i++){
    for(int j = 0; j < n; j++){
      int imp = 0;
      int cnt = 0;
      for(int a = i-1; a <= i+1; a++){
        for(int b = j-1;b <= j+1; b++){
          imp++;
          if(a >= 0 && a < n){
            if(b >= 0 && b < n){
              // write(c[a][b]);
              if(c[a][b] == 'o' && imp % 2 == 0){
                cnt++;
              }
            }
          }
        }
      }
      // writeln();
      // writeln(cnt);
      if(cnt % 2 == 1){
        return false;
      }
    }
  }
  return true;
}

void main(){
  int n;
  char c;

  readf("%s\n",&n);

  char[][] l = new char[][](n,n);
  for(int i = 0; i < n; i++){
    for(int j = 0; j < n; j++){
      char t = '\n';
      while(t == '\n'){
        readf("%c",&t);
      }
      l[i][j] = t;
    }
  }
  if(solve(l)){
    writeln("YES");
  } else {
    writeln("NO");
  }
}

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

immutable DX = [ +1, 0, -1, 0, ];
immutable DY = [ 0, +1, 0, -1, ];

int N;
string[] A;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		A = new string[N];
		foreach (x; 0 .. N) {
			A[x] = readToken;
		}

		bool ans = true;
		foreach (x; 0 .. N) foreach (y; 0 .. N) {
			int cnt;
			foreach (dir; 0 .. 4) {
				const xx = x + DX[dir];
				const yy = y + DY[dir];
				if (0 <= xx && xx < N && 0 <= yy && yy < N) {
					if (A[xx][yy] == 'o') {
						++cnt;
					}
				}
			}
			ans = ans && (cnt % 2 == 0);
		}
		writeln(ans ? "YES" : "NO");
	}
	} catch (EOFException) {}
}


You are given an array of positive integers $$$a_1, a_2, \ldots, a_n$$$.Make the product of all the numbers in the array (that is, $$$a_1 \cdot a_2 \cdot \ldots \cdot a_n$$$) divisible by $$$2^n$$$.You can perform the following operation as many times as you like:  select an arbitrary index $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the value $$$a_i$$$ with $$$a_i=a_i \cdot i$$$. You cannot apply the operation repeatedly to a single index. In other words, all selected values of $$$i$$$ must be different.Find the smallest number of operations you need to perform to make the product of all the elements in the array divisible by $$$2^n$$$. Note that such a set of operations does not always exist.

The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number test cases. Then the descriptions of the input data sets follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ values over all test cases in a test does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the least number of operations to make the product of all numbers in the array divisible by $$$2^n$$$. If the answer does not exist, print -1.

NoteIn the first test case, the product of all elements is initially $$$2$$$, so no operations needed.In the second test case, the product of elements initially equals $$$6$$$. We can apply the operation for $$$i = 2$$$, and then $$$a_2$$$ becomes $$$2\cdot2=4$$$, and the product of numbers becomes $$$3\cdot4=12$$$, and this product of numbers is divided by $$$2^n=2^2=4$$$. In the fourth test case, even if we apply all possible operations, we still cannot make the product of numbers divisible by $$$2^n$$$  — it will be $$$(13\cdot1)\cdot(17\cdot2)\cdot(1\cdot3)\cdot(1\cdot4)=5304$$$, which does not divide by $$$2^n=2^4=16$$$.In the fifth test case, we can apply operations for $$$i = 2$$$ and $$$i = 4$$$.

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

void solve() {
    int n = read!int;
    auto a = readarray!long;
    long twos;
    foreach(el; a)
        if (!(el & 1)) {
            while(el % 2 == 0) {
                el >>= 1;
                twos++;
            }
        }
    if (twos >= n)
        writeln(0);
    else {
        long[] oper;
        foreach(el;iota(n,0,-1).array) {
            if (!(el & 1)) {
                long tmp;
                while(el % 2 == 0) {
                    el >>= 1;
                    tmp++;
                }
                oper ~= tmp;
            }
        }
        sort!"a > b"(oper);
        n -= twos;
        foreach(i, el; oper)
            if (el >= n) {
                writeln(i+1);
                return;
            }
            else
                n -= el;

        writeln(-1);
    }
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!long).array;
    auto am = a.length.iota.map!(i => a[i] * (i + 1)).array;
    long lowzeroes = a.map!(x => cast(long)bsf(x)).sum;
    auto clzamd = a.length.iota.map!(i => bsf(am[i]) - bsf(a[i])).array.sort.reverse.array;
    long ans = 0;
    foreach (x ; clzamd) {
      if (lowzeroes >= n)
        break;
      if (x <= 0)
        break;
      lowzeroes += x;
      ans++;
    }
    writeln(lowzeroes >= n ? ans : -1);
  }
}


You are given an array of n integer numbers. Let sum(l, r) be the sum of all numbers on positions from l to r non-inclusive (l-th element is counted, r-th element is not counted). For indices l and r holds 0 ≤ l ≤ r ≤ n. Indices in array are numbered from 0. For example, if a = [ - 5, 3, 9, 4], then sum(0, 1) =  - 5, sum(0, 2) =  - 2, sum(1, 4) = 16 and sum(i, i) = 0 for each i from 0 to 4.Choose the indices of three delimiters delim0, delim1, delim2 (0 ≤ delim0 ≤ delim1 ≤ delim2 ≤ n) and divide the array in such a way that the value of res = sum(0, delim0) - sum(delim0, delim1) + sum(delim1, delim2) - sum(delim2, n) is maximal. Note that some of the expressions sum(l, r) can correspond to empty segments (if l = r for some segment).

The first line contains one integer number n (1 ≤ n ≤ 5000). The second line contains n numbers a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109).

Choose three indices so that the value of res is maximal. If there are multiple answers, print any of them.

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

long sum(int left, int right, long[] s)
{
    long res = 0;
    if (right > 0) res += s[right - 1];
    if (left > 0) res -= s[left - 1];
    return res;
}

void solve(int[] a, int n)
{
    auto fdp = new long[n + 1];
    auto bdp = new long[n + 1];
    auto fs = new long[n + 1];
    auto fidx = new int[n + 1];
    auto bidx = new int[n + 1];
    foreach (i; 0 .. n + 1)
    {
        fs[i] = 0;
        if (i < n) fs[i] = a[i];
        if (i > 0) fs[i] += fs[i - 1];
        fdp[i] = long.min;
        foreach (j; 0 .. i + 1)
        {
            auto val = sum(0, j, fs) - sum(j, i, fs);
            if (val > fdp[i])
            {
                fdp[i] = val;
                fidx[i] = j;
            }
        }
    }
    for (int i = n; i >= 0; -- i)
    {
        bdp[i] = long.min;
        foreach (j; i .. n + 1)
        {
            auto val = sum(i, j, fs) - sum(j, n, fs);
            if (val > bdp[i])
            {
                bdp[i] = val;
                bidx[i] = j;
            }
        }
    }
    long ans = long.min;
    int li = -1, mi = -1, ri = -1;
    foreach (i; 0 .. n + 1)
    {
        if (fdp[i] + bdp[i] > ans)
        {
            ans = fdp[i] + bdp[i];
            li = fidx[i];
            ri = bidx[i];
            mi = i;
        }
    }
    writeln(li, " ", mi, " ", ri);
}

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

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

long sum(int left, int right, long[] s)
{
    long res = 0;
    if (right > 0) res += s[right - 1];
    if (left > 0) res -= s[left - 1];
    return res;
}

void solve(int[] a, int n)
{
    auto fdp = new long[n + 1];
    auto bdp = new long[n + 1];
    auto fs = new long[n + 1];
    auto fidx = new int[n + 1];
    auto bidx = new int[n + 1];
    foreach (i; 0 .. n + 1)
    {
        fs[i] = 0;
        if (i < n) fs[i] = a[i];
        if (i > 0) fs[i] += fs[i - 1];
        fdp[i] = sum(0, i, fs) - sum(i, i, fs);
        fidx[i] = i;
        if (i > 0)
        {
            auto val = fdp[i - 1] - a[i - 1];
            if (val > fdp[i])
            {
                fdp[i] = val;
                fidx[i] = fidx[i - 1];
            }
        }
    }
    for (int i = n; i >= 0; -- i)
    {
        bdp[i] = sum(i, i, fs) - sum(i, n, fs);
        bidx[i] = i;
        if (i < n)
        {
            auto val = bdp[i + 1] + a[i];
            if (val > bdp[i])
            {
                bdp[i] = val;
                bidx[i] = bidx[i + 1];
            }
        }
    }
    long ans = long.min;
    int li = -1, mi = -1, ri = -1;
    foreach (i; 0 .. n + 1)
    {
        if (fdp[i] + bdp[i] > ans)
        {
            ans = fdp[i] + bdp[i];
            li = fidx[i];
            ri = bidx[i];
            mi = i;
        }
    }
    writeln(li, " ", mi, " ", ri);
}

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

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

long sum(int left, int right, long[] s)
{
    long res = 0;
    if (right > 0) res += s[right - 1];
    if (left > 0) res -= s[left - 1];
    return res;
}

void solve(int[] a, int n)
{
    auto fdp = new long[n + 1];
    auto bdp = new long[n + 1];
    auto fs = new long[n + 1];
    auto fidx = new int[n + 1];
    auto bidx = new int[n + 1];
    foreach (i; 0 .. n + 1)
    {
        fs[i] = 0;
        if (i < n) fs[i] = a[i];
        if (i > 0) fs[i] += fs[i - 1];
        fdp[i] = sum(0, i, fs) - sum(i, i, fs);
        fidx[i] = i;
        if (i > 0)
        {
            auto val = fdp[i - 1];
            if (i < n) val -= a[i];
            if (val > fdp[i])
            {
                fdp[i] = val;
                fidx[i] = fidx[i - 1];
            }
        }
    }
    for (int i = n; i >= 0; -- i)
    {
        bdp[i] = sum(i, i, fs) - sum(i, n, fs);
        bidx[i] = i;
        if (i < n)
        {
            auto val = bdp[i + 1] + a[i];
            if (val > bdp[i])
            {
                bdp[i] = val;
                bidx[i] = bidx[i + 1];
            }
        }
    }
    long ans = long.min;
    int li = -1, mi = -1, ri = -1;
    foreach (i; 0 .. n + 1)
    {
        if (fdp[i] + bdp[i] > ans)
        {
            ans = fdp[i] + bdp[i];
            li = fidx[i];
            ri = bidx[i];
            mi = i;
        }
    }
    writeln(li, " ", mi, " ", ri);
}

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

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

long sum(int left, int right, long[] s)
{
    long res = 0;
    if (right > 0) res += s[right - 1];
    if (left > 0) res -= s[left - 1];
    return res;
}

void solve(int[] a, int n)
{
    auto fdp = new long[n + 1];
    auto bdp = new long[n + 1];
    auto fs = new long[n + 1];
    auto fidx = new int[n + 1];
    auto bidx = new int[n + 1];
    foreach (i; 0 .. n + 1)
    {
        fs[i] = 0;
        if (i < n) fs[i] = a[i];
        if (i > 0) fs[i] += fs[i - 1];
        fdp[i] = sum(0, i, fs) - sum(i, i, fs);
        fidx[i] = i;
        if (i > 0 && i < n)
        {
            auto val = fdp[i - 1] - a[i];
            if (val > fdp[i])
            {
                fdp[i] = val;
                fidx[i] = fidx[i - 1];
            }
        }
    }
    for (int i = n; i >= 0; -- i)
    {
        bdp[i] = sum(i, i, fs) - sum(i, n, fs);
        bidx[i] = i;
        if (i < n)
        {
            auto val = bdp[i + 1] + a[i];
            if (val > bdp[i])
            {
                bdp[i] = val;
                bidx[i] = bidx[i + 1];
            }
        }
    }
    long ans = long.min;
    int li = -1, mi = -1, ri = -1;
    foreach (i; 0 .. n + 1)
    {
        if (fdp[i] + bdp[i] > ans)
        {
            ans = fdp[i] + bdp[i];
            li = fidx[i];
            ri = bidx[i];
            mi = i;
        }
    }
    writeln(li, " ", mi, " ", ri);
}

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


According to a new ISO standard, a flag of every country should have, strangely enough, a chequered field n × m, each square should be wholly painted one of 26 colours. The following restrictions are set:   In each row at most two different colours can be used.  No two adjacent squares can be painted the same colour. Pay attention, please, that in one column more than two different colours can be used.Berland's government took a decision to introduce changes into their country's flag in accordance with the new standard, at the same time they want these changes to be minimal. By the given description of Berland's flag you should find out the minimum amount of squares that need to be painted different colour to make the flag meet the new ISO standard. You are as well to build one of the possible variants of the new Berland's flag.

The first input line contains 2 integers n and m (1 ≤ n, m ≤ 500) — amount of rows and columns in Berland's flag respectively. Then there follows the flag's description: each of the following n lines contains m characters. Each character is a letter from a to z, and it stands for the colour of the corresponding square.

In the first line output the minimum amount of squares that need to be repainted to make the flag meet the new ISO standard. The following n lines should contain one of the possible variants of the new flag. Don't forget that the variant of the flag, proposed by you, should be derived from the old flag with the minimum amount of repainted squares. If the answer isn't unique, output any.

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, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	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)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, 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)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

immutable L = 26;
immutable INF = 1_000_000_000;

int M, N;
string[] A;

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = new string[M];
		foreach (x; 0 .. M) {
			A[x] = readToken;
		}

		auto costss = new int[][][](M, 2, L);
		foreach (x; 0 .. M) foreach (a; 0 .. L) {
			foreach (y; 0 .. N) {
				if (A[x][y] - 'a' != a) {
					++costss[x][y % 2][a];
				}
			}
		}
		auto costs = new int[][][](M, L, L);
		foreach (x; 0 .. M) foreach (a; 0 .. L) foreach (b; 0 .. L) {
			costs[x][a][b] = costss[x][0][a] + costss[x][1][b];
		}

		auto dp = new int[][][](M + 1, L, L);
		// auto prv = new Pair!(int, int)[][][](M + 1, L, L);
		foreach (x; 1 .. M + 1) foreach (a; 0 .. L) foreach (b; 0 .. L) {
			dp[x][a][b] = INF;
		}
		foreach (x; 0 .. M) foreach (a; 0 .. L) foreach (b; 0 .. L) if (dp[x][a][b] < INF) {
			foreach (aa; 0 .. L) if (a != aa) foreach (bb; 0 .. L) if (b != bb) if (aa != bb) {
				// if (dp[x + 1][aa][bb] > dp[x][a][b] + costs[x][aa][bb]) {
					// dp[x + 1][aa][bb] = dp[x][a][b] + costs[x][aa][bb];
					// prv[x + 1][aa][bb] = pair(a, b);
				// }
				chmin(dp[x + 1][aa][bb], dp[x][a][b] + costs[x][aa][bb]);
			}
		}

		int opt = INF;
		int am = -1, bm = -1;
		foreach (a; 0 .. L) foreach (b; 0 .. L) {
			if (opt > dp[M][a][b]) {
				opt = dp[M][a][b];
				am = a;
				bm = b;
			}
		}

		auto ans = new int[][M];
		for (int x = M, a = am, b = bm; x--; ) {
			ans[x] = [ a, b ];
			// const p = prv[x + 1][a][b];
			// a = p.x;
			// b = p.y;
			const aa = a, bb = b;
			for (a = 0; a < L; ++a) if (a != aa) for (b = 0; b < L; ++b) if (b != bb) {
				if (dp[x + 1][aa][bb] == dp[x][a][b] + costs[x][aa][bb]) {
					goto found;
				}
			}
			assert(false);
		// found:
		found:{}
		}

		writeln(opt);
		foreach (x; 0 .. M) {
			foreach (y; 0 .. N) {
				write(cast(char)('a' + ans[x][y % 2]));
			}
			writeln;
		}

	}
	} catch (EOFException) {}
}


You have a knapsack with the capacity of $$$W$$$. There are also $$$n$$$ items, the $$$i$$$-th one has weight $$$w_i$$$. You want to put some of these items into the knapsack in such a way that their total weight $$$C$$$ is at least half of its size, but (obviously) does not exceed it. Formally, $$$C$$$ should satisfy: $$$\lceil \frac{W}{2}\rceil \le C \le W$$$. Output the list of items you will put into the knapsack or determine that fulfilling the conditions is impossible. If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights of items in the knapsack.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains integers $$$n$$$ and $$$W$$$ ($$$1 \le n \le 200\,000$$$, $$$1\le W \le 10^{18}$$$).  The second line of each test case contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^9$$$) — weights of the items. The sum of $$$n$$$ over all test cases does not exceed $$$200\,000$$$.

For each test case, if there is no solution, print a single integer $$$-1$$$.  If there exists a solution consisting of $$$m$$$ items, print $$$m$$$ in the first line of the output and $$$m$$$ integers $$$j_1$$$, $$$j_2$$$, ..., $$$j_m$$$ ($$$1 \le j_i \le n$$$, all $$$j_i$$$ are distinct) in the second line of the output  — indices of the items you would like to pack into the knapsack. If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights items in the knapsack.

NoteIn the first test case, you can take the item of weight $$$3$$$ and fill the knapsack just right.In the second test case, all the items are larger than the knapsack's capacity. Therefore, the answer is $$$-1$$$.In the third test case, you fill the knapsack exactly in half.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n;
		long w;
		readf !(" %s %s") (n, w);
		readln;
		auto s = readln.splitter.map !(to !(long)).array;
		auto p = n.iota.array;
		p.sort !((i, j) => s[i] > s[j]);
		int [] answer;
		long total = 0;
		foreach (ref i; p)
		{
			if (total + s[i] <= w)
			{
				answer ~= i + 1;
				total += s[i];
			}
		}
		if (total * 2 < w)
		{
			writeln (-1);
		}
		else
		{
			writeln (answer.length);
			writefln !("%(%s %)") (answer);
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto index = w.MAKE_IDX!"a > b";
		long tot;
		foreach (i; index)
		{
			if (w[i] > W) continue;
			if (w[i] >= (W+1) / 2)
			{
				tot += w[i];
				ans[ti] ~= i+1;
				break;
			}
			tot += w[i];
			ans[ti] ~= i+1;
			if (tot >= (W+1) / 2) break;
		}
		if (tot < (W+1) / 2)
			ans[ti].length = 0;
	}

	foreach (e; ans)
	{
		if (e.length == 0)
			writeln(-1);
		else
		{
			writeln(e.length);
			e.map!(to!string).join(" ").writeln;
		}
	}
	stdout.flush;
	debug readln;
}


One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have n people standing on the first floor, the i-th person wants to go to the fi-th floor. Unfortunately, there is only one elevator and its capacity equal to k (that is at most k people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs |a - b| seconds to move from the a-th floor to the b-th floor (we don't count the time the people need to get on and off the elevator).What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor?

The first line contains two integers n and k (1 ≤ n, k ≤ 2000) — the number of people and the maximal capacity of the elevator. The next line contains n integers: f1, f2, ..., fn (2 ≤ fi ≤ 2000), where fi denotes the target floor of the i-th person.

Output a single integer — the minimal time needed to achieve the goal.

NoteIn first sample, an optimal solution is:   The elevator takes up person #1 and person #2.  It goes to the 2nd floor.  Both people go out of the elevator.  The elevator goes back to the 1st floor.  Then the elevator takes up person #3.  And it goes to the 2nd floor.  It picks up person #2.  Then it goes to the 3rd floor.  Person #2 goes out.  Then it goes to the 4th floor, where person #3 goes out.  The elevator goes back to the 1st floor.

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

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto a = new int [2000 + 1];
		foreach (i; 0..n)
		{
			int x;
			readf (" %s", &x);
			a[x]++;
		}
		long res = 0;
		int v = k;
		foreach_reverse (i, c; a)
		{
			foreach (j; 0..c)
			{
				if (v == k)
				{
					res += (i - 1) * 2;
				}
				v--;
				if (v == 0)
				{
					v = k;
				}
			}
		}
		writeln (res);
	}
}

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, K;
int[] F;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		K = readInt;
		F = new int[N];
		foreach (i; 0 .. N) {
			F[i] = readInt;
		}

		F.sort();
		int ans;
		for (int i = N - 1; i >= 0; i -= K) {
			ans += (F[i] - 1) * 2;
		}
		writeln(ans);
	}
	} catch (EOFException) {}
}


Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.Consider two infinite sets of numbers. The first set consists of odd positive numbers ($$$1, 3, 5, 7, \ldots$$$), and the second set consists of even positive numbers ($$$2, 4, 6, 8, \ldots$$$). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage — the first two numbers from the second set, on the third stage — the next four numbers from the first set, on the fourth — the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out two times more numbers than at the previous one, and also changes the set from which these numbers are written out to another. The ten first written numbers: $$$1, 2, 4, 3, 5, 7, 9, 6, 8, 10$$$. Let's number the numbers written, starting with one.The task is to find the sum of numbers with numbers from $$$l$$$ to $$$r$$$ for given integers $$$l$$$ and $$$r$$$. The answer may be big, so you need to find the remainder of the division by $$$1000000007$$$ ($$$10^9+7$$$).Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem.

The first line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq 10^{18}$$$) — the range in which you need to find the sum.

Print a single integer — the answer modulo $$$1000000007$$$ ($$$10^9+7$$$).

NoteIn the first example, the answer is the sum of the first three numbers written out ($$$1 + 2 + 4 = 7$$$).In the second example, the numbers with numbers from $$$5$$$ to $$$14$$$: $$$5, 7, 9, 6, 8, 10, 12, 14, 16, 18$$$. Their sum is $$$105$$$.

module c;import std.algorithm.comparison;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.range;
import std.stdio;

const MOD = 1000000007;

private long sum(long n) {
    long[] count = [0, 0];
    long n1 = 0, d = 1, s = 0;
    int odd = 1;
    while (n1 < n) {
        if (n1 + d >= n) {
            count[odd] += n - n1;
            break;
        } else {
            n1 += d;
            count[odd] += d;
            d *= 2;
            odd = 1 - odd;
        }
    }
    count[0] %= MOD;
    count[1] %= MOD;
    return (count[0]*(count[0]+1) + count[1]*count[1]) % MOD;
}

void main() {
    long l, r;
    readf("%s %s", l, r);
    writeln((MOD + sum(r) - sum(l-1)) % MOD);
}

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto s = readln.split.map!(to!long);
    auto l = s[0];
    auto r = s[1];

    long sm(long a, long n) {
        a %= MOD;
        n %= MOD;
        return n * (a + (n - 1)) % MOD;
    }

    long calc(long x, long n, long a, long cnt) {
        long res = 0;
        while (cnt + n + 2 * n <= x) {
            (res += sm(a, n)) %= MOD;
            (a += 2 * n % MOD) %= MOD;
            cnt += n + 2 * n;
            n = n * 4;
        }
        (res += sm(a, min(x - cnt, n))) %= MOD;
        return res;
    }

    long ansl = calc(l-1, 1, 1, 0) + calc(l-1, 2, 2, 1);
    long ansr = calc(r, 1, 1, 0) + calc(r, 2, 2, 1);
    writeln(((ansr - ansl) % MOD + MOD) % MOD);
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

long MOD = 1_000_000_007;

long find(long idx) {

    long eve = 1;
    long[] nn = [0, 0]; // 0 even, 1 odd
    uint turn = 1;
    long mul = 1;
    long tt = 0;
    if (idx <= 0)
        return 0;
    while (true) {
        if (tt + mul > idx) {
            nn[turn] += (idx - tt);
            tt += (idx - tt);
            break;
        }

        nn[turn] += mul;
        tt += mul;

        turn = 1 - turn;
        mul = 2 * mul;
    }
    long nod = nn[1];
    long nev = nn[0];

    long tt1 = ((nod % MOD) * (nod % MOD)) % MOD;
    long tt2 = 0;
    if (nev > 0)
        tt2 = (((nev + 1) % MOD) * (nev % MOD) % MOD);

    return (tt1 + tt2) % MOD;
}

void main() {
    GC.disable();

    long l, r;
    readf(" %s %s", l, r);

    writeln((find(r) - find(l - 1) + MOD) % MOD);

}


The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples:  $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points;  $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points;  $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point;  $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).

For each test case, print one integer — the maximum number of points a player can get for winning the game.

NoteTest cases of the example are described in the statement.

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

alias ll = long;
int isz(long t){ return to!int(t); }
static string[] tempstr;
T rd(T = long)() { while(!tempstr.length) tempstr = readln.chomp.split; string res = tempstr[0]; tempstr.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    int n, m, k;
    n = rd!int;
    m = rd!int;
    k = rd!int;
    int win = min(m, n/k);
    int leftj = (m - win);
    int max2 = leftj/(k-1) + (leftj % (k - 1) != 0);
    writeln(win - max2);
}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m, k;
		readf !(" %s %s %s") (n, m, k);
		auto win = min (m, n / k);
		auto left = m - win;
		auto others = k - 1;
		auto lose = (left + others - 1) / others;
		writeln (win - lose);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto cnt = n / k;
		auto x = min(cnt, m);
		m -= x;
		ans[ti] = x - (m+k-2) / (k-1);
	}

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

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

alias ll = long;
int isz(long t){ return to!int(t); }
static string[] tempstr;
T rd(T = long)() { while(!tempstr.length) tempstr = readln.chomp.split; string res = tempstr[0]; tempstr.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    int n, m, k;
    n = rd!int;
    m = rd!int;
    k = rd!int;
    int win = min(m, n/k);
    int leftj = (m - win);
    int max2 = leftj/(k-1) + (leftj % (k - 1));
    writeln(win - max2);
}

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