You are given three integers $$$a \le b \le c$$$.In one move, you can add $$$+1$$$ or $$$-1$$$ to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers $$$A \le B \le C$$$ such that $$$B$$$ is divisible by $$$A$$$ and $$$C$$$ is divisible by $$$B$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a separate line as three space-separated integers $$$a, b$$$ and $$$c$$$ ($$$1 \le a \le b \le c \le 10^4$$$).

For each test case, print the answer. In the first line print $$$res$$$ — the minimum number of operations you have to perform to obtain three integers $$$A \le B \le C$$$ such that $$$B$$$ is divisible by $$$A$$$ and $$$C$$$ is divisible by $$$B$$$. On the second line print any suitable triple $$$A, B$$$ and $$$C$$$.

module C;

import std.stdio : readln, write, writeln;

struct IO {
  import std.conv : to;
  import std.range : empty, front, popFront, split;

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

  int readInt() {
    return readToken.to!int;
  }

  string[] tokens;
}

import std.container : Array;
import std.typecons : Tuple, tuple;

const int N = 30000;

Tuple!(int, int)[N] best;
Array!int[N] divisors;

void main() {
  import std.algorithm : min;
  import std.math : abs;

  for (int d = 1; d < N; ++d) {
    for (int n = d; n < N; n += d) {
      divisors[n].insert(d);
    }
  }
  IO io;
  int T = io.readInt;
  while (T--) {
    int a = io.readInt;
    int b = io.readInt;
    int c = io.readInt;
    auto result = tuple(a + b + c, 0, 0, 0);
    for (int z = 1; z < N; ++z) {
      best[z] = tuple(result[0], 0);
      foreach (y; divisors[z]) {
        best[z] = min(best[z], tuple(abs(y - a), y));
      }
    }
    for (int z = 1; z < N; ++z) {
      if (abs(z - c) < result[0]) {
        foreach (y; divisors[z]) {
          result = min(result, tuple(abs(z - c) + abs(y - b) + best[y][0], best[y][1], y, z));
        }
      }
    }
    writeln(result[0]);
    writeln(result[1], " ", result[2], " ", result[3]);
  }
}

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 rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.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 = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. rint){
        long a = rlong, b = rlong, c = rlong;
        long best = c * 3, A = a, B = b, C = c;
        foreach(long y; 1 .. 40000){
            long x = f(a, y);
            long z = g(c, y);
            long tmp = abs(x - a) + abs(y - b) + abs(z - c);
            log("a:", a, "b:", b, "c:", c, "x:", x, "y:", y, "z:", z, "tmp:", tmp, "best:", best, "A:", A, "B:", B, "C:", C);
            if(tmp < best) best = tmp, A = x, B = y, C = z;
        }
        best.writeln;
        writeln(A, " ", B, " ", C);
    }
}
long f(long a, long y){
    static long[][] us;
    if(! us.length){
        us ~= new long[](0);
        foreach(long i; 1 .. 40000) us ~= divisors(i);
    }

    long best = 40000, ans = -1;
    foreach(d; us[y.to!int]){
        if(abs(a - d) < best) best = abs(a - d), ans = d;
    }
    return ans;
}
long[] divisors(long a){
	long[] res, res2;
	for(long d = 1; d * d <= a; d ++){
		if(a % d == 0) res ~= d, res2 ~=  a / d;
	}
	foreach_reverse(d; res2) if(res[$ - 1] < d) res ~= d;
	return res;
}
long g(long c, long y){
    if(c % y > y / 2 || c / y == 0) return y * (c / y + 1);
    else return y * (c / y);
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//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 a = RD;
		auto b = RD;
		auto c = RD;
		ans[ti] = [long.max];
		foreach (i; 1..10^^4+1)
		{
			auto cnt1 = abs(a - i);
			foreach (j; 1..10^^4+1)
			{
				if (i * j > (10^^4)*2) break;
				auto cnt2 = abs(b - i*j);
				long num = c / (i*j), cnt3;
				if (num == 0)
				{
					num = 1;
					cnt3 = (i*j) - c % (i*j);
				}
				else
				{
					if ((i*j) - c % (i*j) < c % (i*j))
						++num;
					cnt3 = min(c % (i*j), (i*j) - c % (i*j));
				}
				auto tmp = cnt1 + cnt2 + cnt3;
				if (tmp < ans[ti][0])
				{
					ans[ti] = [tmp, i, i*j, i*j*num];
				}
			}
		}
	}

	foreach (e; ans)
	{
		writeln(e[0]);
		e[1..$].map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}

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 rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.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 = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. rint){
        long a = rlong, b = rlong, c = rlong;
        long best = c * 3, A = a, B = b, C = c;
        foreach(long y; 1 .. 4000){
            long x = f(a, y);
            long z = g(c, y);
            long tmp = abs(x - a) + abs(y - b) + abs(z - c);
            log("a:", a, "b:", b, "c:", c, "x:", x, "y:", y, "z:", z, "tmp:", tmp, "best:", best, "A:", A, "B:", B, "C:", C);
            if(tmp < best) best = tmp, A = x, B = y, C = z;
        }
        best.writeln;
        writeln(A, " ", B, " ", C);
    }
}
long f(long a, long y){
    static long[][] us;
    if(! us.length){
        us ~= new long[](0);
        foreach(long i; 1 .. 4000) us ~= divisors(i);
    }

    long best = 4000, ans = -1;
    foreach(d; us[y.to!int]){
        if(abs(a - d) < best) best = abs(a - d), ans = d;
    }
    return ans;
}
long[] divisors(long a){
	long[] res, res2;
	for(long d = 1; d * d <= a; d ++){
		if(a % d == 0) res ~= d, res2 ~=  a / d;
	}
	foreach_reverse(d; res2) if(res[$ - 1] < d) res ~= d;
	return res;
}
long g(long c, long y){
    if(c % y > y / 2 || c / y == 0) return y * (c / y + 1);
    else return y * (c / y);
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//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 a = RD;
		auto b = RD;
		auto c = RD;
		ans[ti] = [long.max];
		foreach (i; 1..10^^4+1)
		{
			auto cnt1 = abs(a - i);
			foreach (j; 1..10^^4+1)
			{
				if (i * j > (10^^4)*2) break;
				auto cnt2 = abs(b - i*j);
				auto num  = max(c / (i*j), 1);
				if ((i*j) - c % (i*j) < c % (i*j))
					++num;
				auto cnt3 = min(c % (i*j), (i*j) - c % (i*j));
				auto tmp = cnt1 + cnt2 + cnt3;
				if (tmp < ans[ti][0])
				{
					ans[ti] = [tmp, i, i*j, i*j*num];
				}
			}
		}
	}

	foreach (e; ans)
	{
		writeln(e[0]);
		e[1..$].map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//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 a = RD;
		auto b = RD;
		auto c = RD;
		ans[ti] = [long.max];
		foreach (i; 1..10^^4+1)
		{
			auto cnt1 = abs(a - i);
			foreach (j; 1..10^^4+1)
			{
				if (i * j > 10^^4) break;
				auto cnt2 = abs(b - i*j);
				auto num  = max(c / (i*j), 1);
				if ((i*j) - c % (i*j) < c % (i*j))
					++num;
				auto cnt3 = min(c % (i*j), (i*j) - c % (i*j));
				auto tmp = cnt1 + cnt2 + cnt3;
				if (tmp < ans[ti][0])
				{
					ans[ti] = [tmp, i, i*j, i*j*num];
				}
			}
		}
	}

	foreach (e; ans)
	{
		writeln(e[0]);
		e[1..$].map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}


Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?

The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.

Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.

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

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

    foreach (i; 0..min(M+1, N)) {
        long rest = N - i;
        long cnt = min(K * rest, M.to!long - i);
        ans = max(ans, 1.0L * (S + cnt) / rest);
        S -= A[i];
    }

    writefln("%.15f", ans);
}

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

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

    foreach (i; 0..min(M, N)) {
        long rest = N - i;
        long cnt = min(K * rest, M.to!long - i);
        ans = max(ans, 1.0L * (S + cnt) / rest);
        S -= A[i];
    }

    writefln("%.15f", ans);
}

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

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

    foreach (i; 0..min(M, N)) {
        long rest = N - i;
        long cnt = min(K * rest, M.to!long - i);
        ans = 1.0L * (S + cnt) / rest;
        S -= A[i];
    }

    writefln("%.15f", ans);
}


Kuznecov likes art, poetry, and music. And strings consisting of lowercase English letters.Recently, Kuznecov has found two strings, $$$a$$$ and $$$b$$$, of lengths $$$n$$$ and $$$m$$$ respectively. They consist of lowercase English letters and no character is contained in both strings. Let another string $$$c$$$ be initially empty. Kuznecov can do the following two types of operations:  Choose any character from the string $$$a$$$, remove it from $$$a$$$, and add it to the end of $$$c$$$.  Choose any character from the string $$$b$$$, remove it from $$$b$$$, and add it to the end of $$$c$$$. But, he can not do more than $$$k$$$ operations of the same type in a row. He must perform operations until either $$$a$$$ or $$$b$$$ becomes empty. What is the lexicographically smallest possible value of $$$c$$$ after he finishes?A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \neq y$$$;  in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1\leq n,m,k \leq 100$$$) — parameters from the statement. The second line of each test case contains the string $$$a$$$ of length $$$n$$$. The third line of each test case contains the string $$$b$$$ of length $$$m$$$.  The strings contain only lowercase English letters. It is guaranteed that no symbol appears in $$$a$$$ and $$$b$$$ simultaneously.

In each test case, output a single string $$$c$$$ — the answer to the problem.

3

6 4 2

aaaaaa

bbbb

5 9 3

caaca

bedededeb

7 7 1

noskill

wxhtzdy

NoteIn the first test case, it is optimal to take two 'a's from the string $$$a$$$ and add them to the string $$$c$$$. Then it is forbidden to take more characters from $$$a$$$, hence one character 'b' from the string $$$b$$$ has to be taken. Following that logic, we end up with $$$c$$$ being 'aabaabaa' when string $$$a$$$ is emptied.In the second test case it is optimal to take as many 'a's from string $$$a$$$ as possible, then take as many 'b's as possible from string $$$b$$$. In the end, we take two 'c's from the string $$$a$$$ emptying it.

module CodeForces;

import std;

int main()
{
	int lineNum = stdin.readln.strip.to!int;

    for ( int i = 0; i < lineNum; i++ )
	{
		int[] stringABAndOpCount = stdin.readln.strip.split.map!(a=> a.to!int()).array;
		int operationCount = stringABAndOpCount.back();

		dchar[] stringA = stdin.readln.strip.to!dstring.dup.sort.array;
		dchar[] stringB = stdin.readln.strip.to!dstring.dup.sort.array;

		int curATaken = 0;
		int curBTaken = 0;
		dchar[] result;
		while( !stringA.empty() && !stringB.empty() )
		{
			if ( curBTaken == operationCount || (curATaken < operationCount && stringA.front < stringB.front) )
			{
				result ~= stringA.front();
				stringA.popFront();
				curATaken++;
				curBTaken = 0;
			}
			else if ( curATaken == operationCount ||  (curBTaken < operationCount && stringB.front < stringA.front) )
			{
				result ~= stringB.front();
				stringB.popFront();
				curBTaken++;
				curATaken = 0;
			}
		}

		writeln(result);
	}

    return 0;
}


In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.

The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.

NoteIn the first sample, the train can take the route  and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.

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, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new bool [] [] (n, n);
		foreach (k; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u][v] = true;
			a[v][u] = true;
		}
		if (a[0][n - 1])
		{
			foreach (u; 0..n)
			{
				foreach (v; 0..n)
				{
					a[u][v] ^= true;
				}
			}
		}

		auto b = new bool [n];
		b[0] = true;
		int res = -1;
		foreach (k; 0..n + 2)
		{
			auto b2 = new bool [n];
			foreach (i; 0..n)
			{
				if (b[i])
				{
					foreach (j; 0..n)
					{
						if (a[i][j])
						{
							b2[j] = true;
						}
					}
				}
			}
			b = b2;
			if (b[n - 1])
			{
				res = k + 1;
				break;
			}
		}

		writeln (res);
	}
}


In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor.On the current level, the hero is facing $$$n$$$ caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave $$$i$$$, he will have to fight $$$k_i$$$ monsters in a row: first a monster with armor $$$a_{i, 1}$$$, then a monster with armor $$$a_{i, 2}$$$ and so on, finally, a monster with armor $$$a_{i, k_i}$$$.The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order.Each time the hero beats a monster, the hero's power increases by $$$1$$$.Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of caves. The $$$i$$$-th of the next $$$n$$$ lines contains an integer $$$k_i$$$ ($$$1 \le k_i \le 10^5$$$) — the number of monsters in the $$$i$$$-th cave, followed by $$$k_i$$$ integers $$$a_{i, 1}, a_{i, 2}, \ldots, a_{i, k_i}$$$ ($$$1 \le a_{i, j} \le 10^9$$$) — armor levels of the monsters in cave $$$i$$$ in order the hero has to fight them. It is guaranteed that the sum of $$$k_i$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.

NoteIn the first test case, the hero has to beat a single monster with armor $$$42$$$, it's enough to have power $$$43$$$ to achieve that.In the second test case, the hero can pass the level with initial power $$$13$$$ as follows:   enter cave $$$2$$$:   beat a monster with armor $$$12$$$, power increases to $$$14$$$;  beat a monster with armor $$$11$$$, power increases to $$$15$$$;   enter cave $$$1$$$:   beat a monster with armor $$$10$$$, power increases to $$$16$$$;  beat a monster with armor $$$15$$$, power increases to $$$17$$$;  beat a monster with armor $$$8$$$, power increases to $$$18$$$.

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

bool solve(long power, ref long[][] caves)
{
  foreach (cave ; caves) {
    if (power <= cave[0])
      return false;
    power += cave.length - 1;
  }
  return true;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n_caves;
    readf!" %d "(n_caves);
    long[][] caves;
    foreach (i ; 0 .. n_caves) {
      auto a = readln.strip.split.map!(to!long).array;
      foreach (j ; 1 .. a.length) {
        a[j] -= j - 1;
      }
      a[0] = a[1 .. $].maxElement;
      caves ~= a;
    }
    caves.sort!((a, b) => a[0] < b[0]);
    writeln(iota(0L, 1000000000L + 1 + 1).map!(power => solve(power, caves)).assumeSorted.lowerBound(true).length);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto b = new long[](n);
		foreach (i; 0..n)
		{
			foreach (j; 0..cast(int)a[i][0])
			{
				b[i].chmax(a[i][j+1]-j+1);
			}
		}

		auto index = b.MAKE_IDX();
		long p;
		foreach (i; index)
		{
			if (p < b[i])
			{
				ans[ti] += b[i] - p;
				p = b[i];
			}
			p += a[i][0];
		}
	}

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

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

bool solve(long power, ref long[][] caves)
{
  foreach (cave ; caves) {
    if (power <= cave[0])
      return false;
    power += cave.length - 1;
  }
  return true;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n_caves;
    readf!" %d "(n_caves);
    long[][] caves;
    foreach (i ; 0 .. n_caves) {
      auto a = readln.strip.split.map!(to!long).array;
      foreach (j ; 1 .. a.length) {
        a[j] -= j - 1;
      }
      a[0] = a[1 .. $].maxElement;
      caves ~= a;
    }
    caves.sort!((a, b) => a[0] == b[0] ? a.length > b.length : a[0] < b[0]);
    writeln(iota(0L, 1000000000L).map!(power => solve(power, caves)).assumeSorted.lowerBound(true).length);
  }
}

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

bool solve(long power, ref long[][] caves)
{
  foreach (cave ; caves) {
    if (power <= cave[0])
      return false;
    power += cave.length - 1;
  }
  return true;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n_caves;
    readf!" %d "(n_caves);
    long[][] caves;
    foreach (i ; 0 .. n_caves) {
      auto a = readln.strip.split.map!(to!long).array;
      foreach (j ; 1 .. a.length) {
        a[j] -= j - 1;
      }
      a[0] = a[1 .. $].maxElement;
      caves ~= a;
    }
    caves.sort!((a, b) => a[0] < b[0]);
    writeln(iota(0L, 1000000000L).map!(power => solve(power, caves)).assumeSorted.lowerBound(true).length);
  }
}


You are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root is vertex $$$1$$$. There is also a string $$$s$$$ denoting the color of each vertex: if $$$s_i = \texttt{B}$$$, then vertex $$$i$$$ is black, and if $$$s_i = \texttt{W}$$$, then vertex $$$i$$$ is white.A subtree of the tree is called balanced if the number of white vertices equals the number of black vertices. Count the number of balanced subtrees.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. In this problem, all trees have root $$$1$$$.The tree is specified by an array of parents $$$a_2, \dots, a_n$$$ containing $$$n-1$$$ numbers: $$$a_i$$$ is the parent of the vertex with the number $$$i$$$ for all $$$i = 2, \dots, n$$$. The parent of a vertex $$$u$$$ is a vertex that is the next vertex on a simple path from $$$u$$$ to the root.The subtree of a vertex $$$u$$$ is the set of all vertices that pass through $$$u$$$ on a simple path to the root. For example, in the picture below, $$$7$$$ is in the subtree of $$$3$$$ because the simple path $$$7 \to 5 \to 3 \to 1$$$ passes through $$$3$$$. Note that a vertex is included in its subtree, and the subtree of the root is the entire tree.  The picture shows the tree for $$$n=7$$$, $$$a=[1,1,2,3,3,5]$$$, and $$$s=\texttt{WBBWWBW}$$$. The subtree at the vertex $$$3$$$ is balanced.

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 4000$$$) — the number of vertices in the tree. The second line of each test case contains $$$n-1$$$ integers $$$a_2, \dots, a_n$$$ ($$$1 \le a_i < i$$$) — the parents of the vertices $$$2, \dots, n$$$. The third line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of the characters $$$\texttt{B}$$$ and $$$\texttt{W}$$$ — the coloring of the tree. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of balanced subtrees.

NoteThe first test case is pictured in the statement. Only the subtrees at vertices $$$2$$$ and $$$3$$$ are balanced.In the second test case, only the subtree at vertex $$$1$$$ is balanced.In the third test case, only the subtrees at vertices $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ are balanced.

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N - 1);
      auto S = scan.map!(c => c == 'B' ? 1 : -1).array;

      int[][] graph = new int[][](N, 0);
      foreach(i, a; A) graph[a - 1] ~= cast(int)i + 1;

      int[] tour;
      int step;
      int ans;
      int dfs(int cur) {
        int summ = S[cur];
        foreach(child; graph[cur]) {
          summ += dfs(child);
        }

        if (summ == 0) ans++;
        return summ;
      }

      dfs(0);
      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

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

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = [0] ~ readln.splitter.map !(to !(int)).array;
		a[] -= 1;
		auto s = readln.strip;

		auto c = new int [2] [n];
		int res = 0;

		foreach_reverse (i; 0..n)
		{
			c[i][s[i] == 'W'] += 1;
			res += (c[i][0] == c[i][1]);
			if (a[i] >= 0)
			{
				c[a[i]][] += c[i][];
			}
		}
		writeln (res);
	}
}

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N - 1);
      auto S = scan;

      int[][] graph = new int[][](N, 0);
      foreach(i, a; A) graph[a - 1] ~= cast(int)i + 1;

      int ans;
      int[] colors = new int[](N);
      colors[0] = S[0] == 'B' ? 1 : -1;
      for(auto q = new DList!int(0); !q.empty;) {
        auto p = q.front; q.removeFront;
        foreach(near; graph[p]) {
          auto c = colors[p] + (S[near] == 'B' ? 1 : -1);
          colors[near] = c;
          q.insertBack(near);
          if (c == 0) ans++;
        }
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

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

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


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.You may choose at most one consecutive subarray of $$$a$$$ and multiply all values contained in this subarray by $$$x$$$. You want to maximize the beauty of array after applying at most one such operation.

The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 3 \cdot 10^5, -100 \le x \le 100$$$) — the length of array $$$a$$$ and the integer $$$x$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the array $$$a$$$.

Print one integer — the maximum possible beauty of array $$$a$$$ after multiplying all values belonging to some consecutive subarray $$$x$$$.

NoteIn the first test case we need to multiply the subarray [-2, 1, -6], and the array becomes [-3, 8, 4, -2, 12] with beauty 22 ([-3, 8, 4, -2, 12]).In the second test case we don't need to multiply any subarray at all.In the third test case no matter which subarray we multiply, the beauty of array will be equal to 0.

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 INF = 1L << 59;

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

    auto dp = new long[][](N+1, 3);
    foreach (i; 0..N+1) dp[i][] = -INF;
    dp[0][0] = 0;

    foreach (i; 0..N) {
        long tmp = dp[i][0];
        dp[i+1][0] = max(dp[i+1][0], tmp + A[i], A[i]);

        tmp = max(tmp, dp[i][1]);
        dp[i+1][1] = max(dp[i+1][1], tmp + X * A[i], X * A[i]);

        tmp = max(tmp, dp[i][2]);
        dp[i+1][2] = max(dp[i+1][2], tmp + A[i], A[i]);
    }

    dp.map!(d => d.reduce!max).reduce!max.writeln;
}

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

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

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

    debug { arr.writeln; }

    auto sr = new long[] (n+2);
    foreach_reverse (i, e; arr.enumerate(1)) { sr[i] = max(0, e + sr[i+1]); }

    auto sl = new long[] (n+2);
    foreach (i, e; arr.enumerate(1)) { sl[i] = max(0, e + sl[i-1]); }

    auto nl = new long[] (n+2);
    foreach (i, e; arr.enumerate(1)) { nl[i] = max(sl[i], nl[i-1] + e.to!long * x); }

    debug { writeln(sl, ' ', sr, ' ', nl); }

    long ans = 0;
    foreach (i; 0 .. n+1) { ans = max(ans, nl[i] + sr[i+1]); }

    ans.writeln;
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
}

long solve (long[] a) {
  long curs = 0, maxs = 0;
  foreach (x; a) {
    curs += x;
    if (curs < 0) {
      curs = 0;
    }
    maxs = max (maxs, curs);
  }
  return maxs;
}

void main() {
  auto r = new InputReader;
  immutable n = r.next!int;
  immutable x = r.next!int;
  auto a = new long[n];
  foreach (i; 0 .. n) {
    a[i] = r.next!long;
  }
  long[3] curs;
  long maxs = 0;
  foreach (i; 0 .. n) {
    foreach_reverse (state; 0 .. 3) {
      long y = a[i];
      if (state == 1) {
        y *= x;
      }
      long s = long.min;
      foreach (oldstate; max (0, state - 1) .. state + 1) {
        s = max (s, curs[oldstate]);
      }
      s += y;
      if (s < 0) {
        s = 0;
      }
      curs[state] = s;
      maxs = max (maxs, s);
    }
  }
  writeln (maxs);
}

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

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

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

    debug { arr.writeln; }

    auto sr = new long[] (n+2);
    foreach_reverse (i, e; arr.enumerate(1)) { sr[i] = max(0, e + sr[i+1]); }

    auto sl = new long[] (n+2);
    foreach (i, e; arr.enumerate(1)) { sl[i] = max(0, e + sl[i-1]); }

    auto nl = new long[] (n+2);
    foreach (i, e; arr.enumerate(1)) { nl[i] = max(sl[i], nl[i-1] + e * x); }

    debug { writeln(sl, ' ', sr, ' ', nl); }

    long ans = 0;
    foreach (i; 0 .. n+1) { ans = max(ans, nl[i] + sr[i+1]); }

    ans.writeln;
}


The rules of Sith Tournament are well known to everyone. n Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.Jedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory.

The first line contains a single integer n (1 ≤ n ≤ 18) — the number of participants of the Sith Tournament. Each of the next n lines contains n real numbers, which form a matrix pij (0 ≤ pij ≤ 1). Each its element pij is the probability that the i-th participant defeats the j-th in a duel. The elements on the main diagonal pii are equal to zero. For all different i, j the equality pij + pji = 1 holds. All probabilities are given with no more than six decimal places. Jedi Ivan is the number 1 in the list of the participants.

Output a real number — the probability that Jedi Ivan will stay alive after the Tournament. Absolute or relative error of the answer must not exceed 10 - 6.

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

double saiki(int mask, int who, int n, double[][] dp, double[][] p)
{
    if (dp[mask][who] != -1)
    {
        return dp[mask][who];
    }
    if ((mask | 1) == (1 << n) - 1)
    {
        dp[mask][who] = 1.0;
        return 1.0;
    }
    if (mask & 1)
    {
        dp[mask][who] = 0;
        return 0;
    }
    auto res = 0.0;
    foreach (i; 0 .. n)
    {
        if (i != who && (mask & (1 << i)) == 0)
        {
            auto ret0 = saiki(mask | (1 << who), i, n, dp, p);
            auto ret1 = saiki(mask | (1 << i), who, n, dp, p);
            auto prob = ret0 * p[i][who] + ret1 * p[who][i];
            res = max(res, prob);
        }
    }
    dp[mask][who] = res;
    return res;
}

void solve(double[][] p, int n)
{
    auto dp = new double[][](1 << n, n);
    foreach (i; 0 .. 1 << n)
    {
        fill(dp[i], -1);
    }
    auto ans = 0.0;
    foreach (i; 0 .. n)
    {
        auto ret = saiki(0, i, n, dp, p);
        ans = max(ans, ret);
    }
    writefln("%.6f", ans);
}

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


You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.

The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.

Print the minimum non-zero element before each operation in a new line.

NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.

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

void main() {
  int n,k,lst = 0;
  readf!"%d %d\n" (n, k);
  auto v = readln.splitter.map!(to!int).array.sort;
  foreach(x;v) {
    if(x>lst) {
      writeln(x-lst);
      if(--k == 0) break;
    }
    lst = x;
  }
  foreach(i;0..k) writeln(0);
}

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

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

    long a = 0;
    A.sort();

    for (int p = 0, x = 0; x < M; ++x) {
        while (p < N && A[p] - a == 0)
            ++p;
        if (p >= N) {
            writeln(0);
            continue;
        }
        writeln(A[p] - a);
        a = A[p];
    }
}


Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).The next paragraph is specific to the version 1 of the problem.Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.Vova is a perfectionist, so he considers the wall completed when:  all parts of the wall has the same height;  the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial heights of the parts of the wall.

Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero). Print "NO" otherwise.

NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put a brick vertically on part 3 to make the wall $$$[4, 5, 5]$$$, then horizontally on parts 2 and 3 to make it $$$[4, 6, 6]$$$ and then vertically on part 1 to make it $$$[6, 6, 6]$$$.In the third example the wall is already complete.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(x => x.to!long % 2).array;

    bool solve() {
        if (A.count(1) % 2 == 1) {
            return false;
        }

        auto even = iota(0, N, 2).filter!(i => A[i] == 1).array.length;
        auto odd = iota(1, N, 2).filter!(i => A[i] == 1).array.length;
        return even == odd;
    }

    if (solve) {
        writeln("YES");
        return;
    }

    foreach (i; 0..N) A[i] ^= 1;

    if (solve) {
        writeln("YES");
        return;
    }

    writeln("NO");
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(x => x.to!long % 2).array;

    auto cnt = A.count(1);

    if (cnt % 2 == 1 && (N - cnt) % 2 == 1) {
        writeln("NO");
        return;
    }

    if ((N-1).iota.map!(i => A[i] != A[i+1]).all) {
        writeln("NO");
        return;
    }

    writeln("YES");
}


Grisha come to a contest and faced the following problem.You are given an array of size $$$n$$$, initially consisting of zeros. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. You perform $$$q$$$ operations on the array. The $$$i$$$-th operation is described with three integers $$$l_i$$$, $$$r_i$$$ and $$$x_i$$$ ($$$1 \leq l_i \leq r_i \leq n$$$, $$$1 \leq x_i \leq n$$$) and means that you should add $$$x_i$$$ to each of the elements with indices $$$l_i, l_i + 1, \ldots, r_i$$$. After all operations you should find the maximum in the array.Grisha is clever, so he solved the problem quickly.However something went wrong inside his head and now he thinks of the following question: "consider we applied some subset of the operations to the array. What are the possible values of the maximum in the array?"Help Grisha, find all integers $$$y$$$ between $$$1$$$ and $$$n$$$ such that if you apply some subset (possibly empty) of the operations, then the maximum in the array becomes equal to $$$y$$$.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n, q \leq 10^{4}$$$) — the length of the array and the number of queries in the initial problem. The following $$$q$$$ lines contain queries, one per line. The $$$i$$$-th of these lines contains three integers $$$l_i$$$, $$$r_i$$$ and $$$x_i$$$ ($$$1 \leq l_i \leq r_i \leq n$$$, $$$1 \leq x_i \leq n$$$), denoting a query of adding $$$x_i$$$ to the segment from $$$l_i$$$-th to $$$r_i$$$-th elements of the array, inclusive.

In the first line print the only integer $$$k$$$, denoting the number of integers from $$$1$$$ to $$$n$$$, inclusive, that can be equal to the maximum in the array after applying some subset (possibly empty) of the given operations. In the next line print these $$$k$$$ integers from $$$1$$$ to $$$n$$$ — the possible values of the maximum. Print these integers in increasing order.

NoteConsider the first example. If you consider the subset only of the first query, the maximum is equal to $$$1$$$. If you take only the second query, the maximum equals to $$$2$$$. If you take the first two queries, the maximum becomes $$$3$$$. If you take only the fourth query, the maximum becomes $$$4$$$. If you take the fourth query and something more, the maximum becomes greater that $$$n$$$, so you shouldn't print it.In the second example you can take the first query to obtain $$$1$$$. You can take only the second query to obtain $$$2$$$. You can take all queries to obtain $$$3$$$.In the third example you can obtain the following maximums:  You can achieve the maximim of $$$2$$$ by using queries: $$$(1)$$$.  You can achieve the maximim of $$$3$$$ by using queries: $$$(2)$$$.  You can achieve the maximim of $$$5$$$ by using queries: $$$(1, 2)$$$.  You can achieve the maximim of $$$6$$$ by using queries: $$$(3)$$$.  You can achieve the maximim of $$$8$$$ by using queries: $$$(1, 3)$$$.  You can achieve the maximim of $$$9$$$ by using queries: $$$(2, 3)$$$.

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

immutable long mod = 1_000_000_000_000_000_003;

alias Segment = Tuple !(int, q{l}, int, q{r}, int, q{x});
alias Event = Tuple !(int, q{pos}, bool, q{state}, int, q{value});

void main ()
{
	int n, q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		auto s = new Segment [q];
		Event [] e;
		foreach (ref c; s)
		{
			readf (" %s %s %s", &c.l, &c.r, &c.x);
			c.l -= 1;
			e ~= Event (c.l, true,  c.x);
			e ~= Event (c.r, false, c.x);
		}
		e ~= Event (n, true, 0);
		sort (e);

		auto ans = new bool [n + 1];
		auto f = new long [n + 1];
		f[0] = 1;
		int pos = -1;
		foreach (event; e)
		{
			if (pos != event.pos)
			{
				foreach (i; 0..n + 1)
				{
					ans[i] |= (f[i] != 0);
				}
				pos = event.pos;
			}
			auto x = event.value;
			if (event.state)
			{
				foreach_reverse (u; x..n + 1)
				{
					f[u] += f[u - x];
					if (f[u] >= mod)
					{
						f[u] -= mod;
					}
				}
			}
			else
			{
				foreach (u; x..n + 1)
				{
					f[u] -= f[u - x];
					if (f[u] < 0)
					{
						f[u] += mod;
					}
				}
			}
		}

		ans[0] = false;
		writeln (ans.sum);
		writefln ("%(%s %)", (n + 1).iota.filter !(x => ans[x]));
	}
}

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

struct ev {
    int le, r, x;
    int opCmp(ev e) { return r - e.r; }
}

ev[] evs;

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

    foreach (_; 0..q) {
        ev e;
        readf("%s %s %s", &e.le, &e.r, &e.x);
        readln;

        evs ~= e;
    }

    evs.sort();

    auto reach = (0).repeat(n+1).array;

    debug { writeln(evs); }

    foreach (e; evs) {
        foreach_reverse (i; e.x+1..n+1) {
            if (reach[i - e.x] >= e.le) reach[i] = max(reach[i], reach[i - e.x]);
        }
        reach[e.x] = max(reach[e.x], e.r);
    }

    auto oks = reach.enumerate.filter!(t => t.value > 0).map!(t => t.index).array;

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

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

struct ev { int p; bool isStart; int x; }

ev[] evs;

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

    foreach (_; 0..q) {
        int le, r, x;
        readf("%s %s %s", &le, &r, &x);
        readln;

        evs ~= ev(le, true, x);
        evs ~= ev(r, false, x);
    }

    evs.multiSort!(q{ a.p < b.p }, q{ (a.isStart ? 0 : 1) < (b.isStart ? 0 : 1) });

    debug { writeln(evs); }

    auto ans = false.repeat(n+1).array.BitArray;
    auto cur = false.repeat(n+1).array.BitArray;
    foreach (evt; evs) {
        if (evt.isStart) cur <<= evt.x, cur[evt.x] = true;
        else cur >>= evt.x;
        ans |= cur;
    }

    debug { writefln("%b", ans); }

    auto toPrint = ans.array.dropOne.enumerate(1).filter!(t => t.value).map!(t => t.index).array;
    toPrint.length.writeln;
    toPrint.writefln!("%(%s %)");
}

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

struct ev {
    int le, r, x;
    int opCmp(ev e) { return le - e.le; }
}

ev[] evs;

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

    foreach (_; 0..q) {
        ev e;
        readf("%s %s %s", &e.le, &e.r, &e.x);
        readln;

        evs ~= e;
    }

    evs.sort();

    auto reach = (0).repeat(n+1).array;

    debug { writeln(evs); }

    foreach (e; evs) {
        foreach_reverse (i; e.x+1..n+1) {
            if (reach[i - e.x] >= e.le) reach[i] = max(reach[i], reach[i - e.x]);
        }
        reach[e.x] = max(reach[e.x], e.r);
    }

    auto oks = reach.enumerate.filter!(t => t.value > 0).map!(t => t.index).array;

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

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

struct ev {
    int le, r, x;
    int opCmp(ev e) { return le - e.le; }
}

ev[] evs;

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

    foreach (_; 0..q) {
        ev e;
        readf("%s %s %s", &e.le, &e.r, &e.x);
        readln;

        evs ~= e;
    }

    evs.sort();

    auto reach = (0).repeat(n+1).array;

    debug { writeln(evs); }

    foreach (e; evs) {
        foreach_reverse (i; e.x+1..n+1) {
            if (reach[i - e.x] >= e.le) reach[i] = max(reach[i], e.r);
        }
        reach[e.x] = max(reach[e.x], e.r);
    }

    auto oks = reach.enumerate.filter!(t => t.value > 0).map!(t => t.index).array;

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

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

struct ev { int p; bool isStart; int x; }

ev[] evs;

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

    foreach (_; 0..q) {
        int le, r, x;
        readf("%s %s %s", &le, &r, &x);
        readln;

        evs ~= ev(le, true, x);
        evs ~= ev(r, false, x);
    }

    evs.multiSort!(q{ a.p < b.p }, q{ (a.isStart ? 0 : 1) < (b.isStart ? 0 : 1) });

    debug { writeln(evs); }

    auto ans = false.repeat(n+1).array.BitArray;
    auto cur = false.repeat(n+1).array.BitArray;
    foreach (evt; evs) {
        if (evt.isStart) cur <<= evt.x, cur[evt.x] = true;
        else cur >>= evt.x;
        ans |= cur;
    }

    debug { writefln("%b", ans); }

    auto toPrint = ans.array.enumerate.filter!(t => t.value).map!(t => t.index).array;
    toPrint.length.writeln;
    toPrint.writefln!("%(%s %)");
}

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

struct ev {
    int le, r, x;
    int opCmp(ev e) { return r - e.r; }
}

ev[] evs;

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

    foreach (_; 0..q) {
        ev e;
        readf("%s %s %s", &e.le, &e.r, &e.x);
        readln;

        evs ~= e;
    }

    evs.sort();

    auto reach = (0).repeat(n+1).array;

    debug { writeln(evs); }

    foreach (e; evs) {
        foreach_reverse (i; e.x+1..n+1) {
            if (reach[i - e.x] >= e.le) reach[i] = max(reach[i], e.r);
        }
        reach[e.x] = max(reach[e.x], e.r);
    }

    auto oks = reach.enumerate.filter!(t => t.value > 0).map!(t => t.index).array;

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


Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i > 1 the respective term satisfies the condition bi = bi - 1·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≤ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.

The first line of input contains four integers b1, q, l, m (-109 ≤ b1, q ≤ 109, 1 ≤ l ≤ 109, 1 ≤ m ≤ 105) — the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≤ ai ≤ 109) — numbers that will never be written on the board.

Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.

NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.

import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,
	core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
//import core.stdc.stdio;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;alias pair(X,Y)=Tuple!(X,"fi",Y,"se");
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;alias long lint;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;immutable int mod=1000000007;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~"\n", ptrs)==ptrs.length;}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------

void main()
{
	lint b1,q,l,m;
loop:while(read(&b1,&q,&l,&m))
	{
		auto a=arread!int;
		sort(a);
		if(q==1)
		{
			if(bins(a,b1) || abs(b1)>l)writeln(0);
			else writeln("inf");
		}
		else if(q==-1)
		{
			if((bins(a,b1) && bins(a,-1*b1)) || abs(b1)>l)writeln(0);
			else writeln("inf");
		}
		else
		{
			int ans=0;
			while(abs(b1)<=l)
			{
				if(!bins(a,b1))ans++;
				b1*=q;
				if(b1==0)
				{
					if(!bins(a,0))
					{
						writeln("inf");
						goto loop;
					}
					else break;
				}
			}
			writeln(ans);
		}
	}
	//debug system("pause");
}

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

immutable long INF = 10L ^^ 18 + 23;

void main()
{
    long b;
    int q, le, m;
    readf("%s %s %s %s", &b, &q, &le, &m);
    readln;

    auto t = readln.chomp.split.map!(to!int).redBlackTree;

    if (abs(b) > le) {
        writeln(0);
        return;
    }

    if (b == 0 || q == 1) {
        if (t.equalRange(b.to!int).empty()) writeln("inf");
        else writeln(0);

        return;
    }

    if (q == 0) {
        if (t.equalRange(0).empty()) writeln("inf");
        else writeln(t.equalRange(b.to!int).empty() ? 1 : 0);

        return;
    }

    if (q == -1) {
        bool isInf = t.equalRange(b.to!int).empty() || t.equalRange((-b).to!int).empty();
        if (isInf) writeln("inf");
        else writeln(0);

        return;
    }

    int ans = 0;
    while (abs(b) <= le) {
        if (t.equalRange(b.to!int).empty()) ++ans;

        b = b * q;
    }

    ans.writeln;
}

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

immutable long INF = 10L ^^ 18 + 23;

void main()
{
    long b;
    int q, le, m;
    readf("%s %s %s %s", &b, &q, &le, &m);
    readln;

    auto t = readln.chomp.split.map!(to!int).redBlackTree;

    if (abs(b) > le) {
        writeln(0);
        return;
    }

    if (b == 0 || q == 1) {
        if (t.equalRange(b.to!int).empty()) writeln("inf");
        else writeln(0);

        return;
    }

    if (q == 0) {
        if (t.equalRange(0).empty()) writeln("inf");
        else writeln(t.equalRange(b.to!int).empty() ? 0 : 1);

        return;
    }

    if (q == -1) {
        bool isInf = t.equalRange(b.to!int).empty() || t.equalRange((-b).to!int).empty();
        if (isInf) writeln("inf");
        else writeln(0);

        return;
    }

    int ans = 0;
    while (abs(b) <= le) {
        if (t.equalRange(b.to!int).empty()) ++ans;

        b = b * q;
    }

    ans.writeln;
}

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

immutable long INF = 10L ^^ 18 + 23;

void main()
{
    long b;
    int q, le, m;
    readf("%s %s %s %s", &b, &q, &le, &m);
    readln;

    auto t = readln.chomp.split.map!(to!int).redBlackTree;

    if (b == 0 || q == 1) {
        if (t.equalRange(b.to!int).empty()) writeln("inf");
        else writeln(0);

        return;
    }

    if (q == 0) {
        if (t.equalRange(0).empty()) writeln("inf");
        else writeln(t.equalRange(b.to!int).empty() ? 0 : 1);

        return;
    }

    if (q == -1) {
        bool isInf = t.equalRange(b.to!int).empty() || t.equalRange((-b).to!int).empty();
        if (isInf) writeln("inf");
        else writeln(0);

        return;
    }

    int ans = 0;
    while (abs(b) <= le) {
        if (t.equalRange(b.to!int).empty()) ++ans;

        b = b * q;
    }

    ans.writeln;
}


Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $$$a$$$ sticks and $$$b$$$ diamonds?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^9$$$) — the number of sticks and the number of diamonds, respectively.

For each test case print one integer — the maximum number of emeralds Polycarp can earn.

NoteIn the first test case Polycarp can earn two emeralds as follows: craft one sword and one shovel.In the second test case Polycarp does not have any diamonds, so he cannot craft anything.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		if (a < b)
			swap(a, b);
		auto d = a-b;
		auto cnt = min(d, b);
		ans[ti] += cnt;
		a -= cnt * 2;
		b -= cnt;
		cnt = b / 3;
		ans[ti] += cnt * 2;
		a -= cnt * 3;
		b -= cnt * 3;
		if (max(a, b) >= 2 && min(a, b) >= 1)
			++ans[ti];
	}

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


For some binary string $$$s$$$ (i.e. each character $$$s_i$$$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $$$2$$$ were written. For each pair (substring of length $$$2$$$), the number of '1' (ones) in it was calculated.You are given three numbers:  $$$n_0$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$0$$$;  $$$n_1$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$1$$$;  $$$n_2$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$2$$$. For example, for the string $$$s=$$$"1110011110", the following substrings would be written: "11", "11", "10", "00", "01", "11", "11", "11", "10". Thus, $$$n_0=1$$$, $$$n_1=3$$$, $$$n_2=5$$$.Your task is to restore any suitable binary string $$$s$$$ from the given values $$$n_0, n_1, n_2$$$. It is guaranteed that at least one of the numbers $$$n_0, n_1, n_2$$$ is greater than $$$0$$$. Also, it is guaranteed that a solution exists.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then test cases follow. Each test case consists of one line which contains three integers $$$n_0, n_1, n_2$$$ ($$$0 \le n_0, n_1, n_2 \le 100$$$; $$$n_0 + n_1 + n_2 > 0$$$). It is guaranteed that the answer for given $$$n_0, n_1, n_2$$$ exists.

Print $$$t$$$ lines. Each of the lines should contain a binary string corresponding to a test case. If there are several possible solutions, print any of them.

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto nn = readln.split.to!(int[]);
        auto n0 = nn[0];
        auto n1 = nn[1];
        auto n2 = nn[2];

        char[] rs;
        if (n1 == 0) {
            if (n0 > 0) {
                foreach (_n; 0..n0+1) rs ~= '0';
            } else {
                foreach (_n; 0..n2+1) rs ~= '1';
            }
            writeln(rs);
            continue;
        }

        if (n1%2 == 0) {
            rs ~= '1';
            --n1;
        }
        foreach (_n; 0..n0+1) rs ~= '0';
        foreach (_n; 0..n1/2) rs ~= "10";
        foreach (_n; 0..n2+1) rs ~= '1';

        writeln(rs);
    }
}

// Author: Ivan Kazmenko (gassa@mail.ru)
import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

string solve (int [] n)
{
pick_start_loop:
	foreach (v0; [0, 1])
	{
		int [] res;
		auto v = v0;
		res ~= v;
		while (sum (n) > 0)
		{
			if (n[v * 2] > 0)
			{
				n[v * 2] -= 1;
				res ~= v;
			}
			else if (n[1] > 0)
			{
				n[1] -= 1;
				v ^= 1;
				res ~= v;
			}
			else
			{
				continue pick_start_loop;
			}
		}
		return res.map !(text).join;
	}
	assert (false);
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.splitter.map !(to !(int)).array;
		writeln (solve (n));
	}
}

import std.stdio;
import std.algorithm;
import std.range;
import std.conv;
import std.string;
import std.array;
import std.meta;
import std.random;

// void check(bool[] res, int n0, int n1, int n2) {
// 	int nn0, nn1, nn2;
// 	assert(res.length > 0);
// 	foreach (i; 0 .. res.length - 1) {
// 		int count;
// 		if (res[i]) count++;
// 		if (res[i + 1]) count++;
// 		if (count ==0) nn0++;
// 		else if (count ==1) nn1++;
// 		else if (count == 2) nn2++;
// 	}
// 	assert(nn0 == n0);
// 	assert(nn1 == n1);
// 	assert(nn2 == n2);
// }

void main() {
	int n = readln.chomp.to!int;
	foreach (t; 0 .. n) {
		int[] ns = readln.chomp.split(" ").map!(to!int).array;
		// int[] ns = new int[3];
		// foreach (i; 0.. 3) {
		// 	ns[i] = uniform!"[]"(2, 1000);
		// }
		int n0 = ns[0], n1 = ns[1], n2 = ns[2];
		bool[] res;
		bool at = true;
		bool dontForget = false;
		if (n1 == 0) {
			if (n2 == 0) {
				res.assumeSafeAppend ~= false;
			}
			else {
				res.assumeSafeAppend ~= true;
			}
		}
		else {
			foreach (i; 0 .. n1 + 1) {
				if (i == n1 && at == true) {
					dontForget = true;
					break;
				}
				res.assumeSafeAppend ~= at;
				at = !at;
			}
		}
		bool[] prepend;
		foreach (i; 0 .. n2) {
			prepend.assumeSafeAppend ~= true;
		}
		res = prepend.assumeSafeAppend ~ res;
		foreach (i; 0 .. n0) {
			res.assumeSafeAppend ~= false;
		}
		if (dontForget) {
			res.assumeSafeAppend ~= true;
		}
		// check(res, n0, n1, n2);
		writeln(res.map!(x => x ? '1' : '0'));
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (n0 != 0)
			ans[ti] ~= '0';
		foreach (i; 0..n0)
		{
			ans[ti] ~= '0';
		}

		int n1o = n1;
		if (n1 % 2 == 0)
			n1o -= 1;
		if (n0 == 0 && n1 != 0)
			ans[ti] ~= '0';
		foreach (i; 0..n1o)
		{
			if (i % 2 == 0)
				ans[ti] ~= '1';
			else
				ans[ti] ~= '0';
		}

		if (n0 == 0 && n1 == 0)
			ans[ti] ~= '1';
		foreach (i; 0..n2)
		{
			ans[ti] ~= '1';
		}

		if (n1 % 2 == 0 && n1 != 0)
		{
			if (ans[ti][$-1] == '0')
				ans[ti] ~= '1';
			else
				ans[ti] ~= '0';
		}
	}

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