There is a robot staying at $$$X=0$$$ on the $$$Ox$$$ axis. He has to walk to $$$X=n$$$. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.The $$$i$$$-th segment of the path (from $$$X=i-1$$$ to $$$X=i$$$) can be exposed to sunlight or not. The array $$$s$$$ denotes which segments are exposed to sunlight: if segment $$$i$$$ is exposed, then $$$s_i = 1$$$, otherwise $$$s_i = 0$$$.The robot has one battery of capacity $$$b$$$ and one accumulator of capacity $$$a$$$. For each segment, you should choose which type of energy storage robot will use to go to the next point (it can be either battery or accumulator). If the robot goes using the battery, the current charge of the battery is decreased by one (the robot can't use the battery if its charge is zero). And if the robot goes using the accumulator, the current charge of the accumulator is decreased by one (and the robot also can't use the accumulator if its charge is zero).If the current segment is exposed to sunlight and the robot goes through it using the battery, the charge of the accumulator increases by one (of course, its charge can't become higher than it's maximum capacity).If accumulator is used to pass some segment, its charge decreases by 1 no matter if the segment is exposed or not.You understand that it is not always possible to walk to $$$X=n$$$. You want your robot to go as far as possible. Find the maximum number of segments of distance the robot can pass if you control him optimally.

The first line of the input contains three integers $$$n, b, a$$$ ($$$1 \le n, b, a \le 2 \cdot 10^5$$$) — the robot's destination point, the battery capacity and the accumulator capacity, respectively. The second line of the input contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$0 \le s_i \le 1$$$), where $$$s_i$$$ is $$$1$$$ if the $$$i$$$-th segment of distance is exposed to sunlight, and $$$0$$$ otherwise.

Print one integer — the maximum number of segments the robot can pass if you control him optimally.

NoteIn the first example the robot can go through the first segment using the accumulator, and charge levels become $$$b=2$$$ and $$$a=0$$$. The second segment can be passed using the battery, and charge levels become $$$b=1$$$ and $$$a=1$$$. The third segment can be passed using the accumulator, and charge levels become $$$b=1$$$ and $$$a=0$$$. The fourth segment can be passed using the battery, and charge levels become $$$b=0$$$ and $$$a=1$$$. And the fifth segment can be passed using the accumulator.In the second example the robot can go through the maximum number of segments using battery two times and accumulator one time in any order.

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

const long mod = 1_000_000_007;

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	long n = read.to!long;
	long b = read.to!long;
	long a = read.to!long;

	bool[] areSunny;
	foreach(i; 0 .. n) areSunny ~= read.to!int.to!bool;

	long amax = a;
	long ans = n;
	foreach(i, s; areSunny){
		if(s){
			if(a == amax && a > 0) a -= 1;
			else if(b > 0) b -= 1, a = min(amax, a + 1);
			else if(a > 0) a -= 1;
			else{
				ans = i;
				break;
			}
		}
		else{
			if(a > 0) a -= 1;
			else if(b > 0) b -= 1;
			else{
				ans = i;
				break;
			}
		}
	}
	ans.writeln;

}
/*

Greedy.
Use battery when sunny and use accumlator when cloudy.
Perform simulation of it.

*/

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; }
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; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
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;
	auto B = RD;
	auto A = RD;
	auto s = RDR.ARR;

	long a = A, b = B;
	long ans;
	foreach (e; s)
	{
		if (e == 1 && b != 0 && a != A)
		{
			--b; ++a;
		}
		else if (a != 0)
		{
			--a;
		}
		else if (b != 0)
		{
			--b;
		}
		else
		{
			break;
		}
		++ans;
	}

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

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

const long mod = 1_000_000_007;

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	long n = read.to!long;
	long b = read.to!long;
	long a = read.to!long;

	bool[] areSunny;
	foreach(i; 0 .. n) areSunny ~= read.to!int.to!bool;

	long amax = a;
	long ans = n;
	foreach(i, s; areSunny){
		if(s){
			if(b > 0) b -= 1, a = min(amax, a + 1);
			else if(a > 0) a -= 1;
			else{
				ans = i;
				break;
			}
		}
		else{
			if(a > 0) a -= 1;
			else if(b > 0) b -= 1;
			else{
				ans = i;
				break;
			}
		}
	}
	ans.writeln;

}
/*

Greedy.
Use battery when sunny and use accumlator when cloudy.
Perform simulation of it.

*/

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

const long mod = 1_000_000_007;

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	long n = read.to!long;
	long b = read.to!long;
	long a = read.to!long;

	bool[] areSunny;
	foreach(i; 0 .. n) areSunny ~= read.to!int.to!bool;

	long amax = a;
	long ans = n;
	foreach(i, s; areSunny){
		if(s){
			if(b > 0){
				b -= 1;
				if(a < amax) a += 1;
			}
			else if(a > 0){
				a -= 1;
			}
			else{
				ans = i + 1;
				break;
			}
		}
		else{
			if(a > 0){
				a -= 1;
			}
			else{
				ans = i + 1;
				break;
			}
		}
	}
	ans.writeln;

}
/*

Greedy.
Use battery when sunny and use accumlator when cloudy.
Perform simulation of it.

*/

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; }
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; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
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;
	auto B = RD;
	auto A = RD;
	auto s = RDR.ARR;

	long a = A, b = B;
	long ans;
	foreach (e; s)
	{
		if (e == 1 && b != 0)
		{
			--b; a = min(a+1, A);
		}
		else if (a != 0)
		{
			--a;
		}
		else if (b != 0)
		{
			--b;
		}
		else
		{
			break;
		}
		++ans;
	}

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


You are given $$$n$$$ segments on the coordinate axis. The $$$i$$$-th segment is $$$[l_i, r_i]$$$. Let's denote the set of all integer points belonging to the $$$i$$$-th segment as $$$S_i$$$.Let $$$A \cup B$$$ be the union of two sets $$$A$$$ and $$$B$$$, $$$A \cap B$$$ be the intersection of two sets $$$A$$$ and $$$B$$$, and $$$A \oplus B$$$ be the symmetric difference of $$$A$$$ and $$$B$$$ (a set which contains all elements of $$$A$$$ and all elements of $$$B$$$, except for the ones that belong to both sets).Let $$$[\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}]$$$ be an array where each element is either $$$\cup$$$, $$$\oplus$$$, or $$$\cap$$$. Over all $$$3^{n-1}$$$ ways to choose this array, calculate the sum of the following values:$$$$$$|(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n|$$$$$$In this expression, $$$|S|$$$ denotes the size of the set $$$S$$$.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$). Then, $$$n$$$ lines follow. The $$$i$$$-th of them contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 3 \cdot 10^5$$$).

Print one integer — the sum of $$$|(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n|$$$ over all possible ways to choose $$$[\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}]$$$. Since the answer can be huge, print it modulo $$$998244353$$$.

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

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

enum long mod = 998244353L;

alias Mat = long[4];
alias Vec = long[2];
long at(Mat m, int y, int x) {
    return m[y*2 + x];
}
Mat binop(Mat a, Mat b) {
    Mat r;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                r[i*2+j] += a.at(i, k) * b.at(k, j);
            }
        }
    }
    foreach (ref e; r) e %= mod;
    return r;
}
Vec binop(Mat a, Vec b) {
    Vec r;
    for (int i = 0; i < 2; i++) {
        for (int k = 0; k < 2; k++) {
            r[i] += a.at(i, k) * b[k];
        }
    }
    foreach (ref e; r) e %= mod;
    return r;
}
Mat transpose(Mat m) {
    Mat r;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            r[i*2+j] = m.at(j, i);
        }
    }
    return r;
}
enum Mat INMAT = [2, 2, 1, 1].transpose;
enum Mat OUTMAT = [2, 0, 1, 3].transpose;
alias SegMat = SegmentTree!(Mat, [1, 0, 0, 1], binop);

void main() {
    int N = read!int;
    alias E = Tuple!(int, "i", int, "d");
    E[][int] M;
    foreach (i; 0 .. N) {
        int L, R; readf("%d %d\n", &L, &R);
        M[L] ~= E(i, +1);
        M[R+1] ~= E(i, -1);
    }
    auto init = new Mat[N]; init[] = OUTMAT;
    auto seg = SegMat(init);
    Vec dp0_in = [1, 0];
    Vec dp0_out = [0, 1];
    auto dp0 = dp0_out;
    long ans = 0;
    long pv = 0;
    for (int x = 0; x <= 300_000; x++) {
        if (x in M) {
            foreach (m; M[x]) {
                auto i = m.i;
                auto d = m.d;
                if (i == 0) {
                    if (d > 0) {
                        dp0 = dp0_in;
                    } else {
                        dp0 = dp0_out;
                    }
                } else {
                    if (d > 0) {
                        seg.update(i, INMAT);
                    } else {
                        seg.update(i, OUTMAT);
                    }
                }
            }
            auto v = seg.query(1, N).transpose().binop(dp0);
            pv = v[0];
        }
        /*
        if (x <= 15) {
            writeln("x: ", x);
            writeln("pv: ", pv);
            writeln("ans: ", ans);
        }
        */
        ans += pv;
        ans %= mod;
    }
    writeln(ans);
}

struct SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    this(T[] xs) {
        int n_ = cast(int)(xs.length);
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[n - 1 .. n - 1 + n_] = xs;
        dat[n - 1 + n_ .. $] = unit;
        for (int k = n-2; k >= 0; k--){
            dat[k] = binop(dat[k*2+1], dat[k*2+2]);
        }
    }
    void update(int k, T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return cast(T)dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}


A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $$$k$$$-balanced if every substring of size $$$k$$$ of this bitstring has an equal amount of 0 and 1 characters ($$$\frac{k}{2}$$$ of each).You are given an integer $$$k$$$ and a string $$$s$$$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $$$k$$$-balanced bitstring by replacing every ? characters in $$$s$$$ with either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

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 two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ is even)  — the length of the string and the parameter for a balanced bitstring. The next line contains the string $$$s$$$ ($$$|s| = n$$$). It is given that $$$s$$$ consists of only 0, 1, and ?. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print YES if we can replace every ? in $$$s$$$ with 0 or 1 such that the resulting bitstring is $$$k$$$-balanced, or NO if it is not possible.

NoteFor the first test case, the string is already a $$$4$$$-balanced bitstring.For the second test case, the string can be transformed into 101.For the fourth test case, the string can be transformed into 0110.For the fifth test case, the string can be transformed into 1100110.

// 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 inz(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 = char)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    int n;
    n = to!int(rd);
    int k = to!int(rd);
    dchar[] wordstr;
    readln(wordstr);
    wordstr.popBack;
    int[] word;
    foreach(cr; wordstr){
        word ~= (cr - '0');
    }
    // Set all initially
    foreach(i; 0..n-k){
        if(word[i] <= 1){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }else if(word[i+k] <= 1){
            word[i] = word[i+k];
        }
    }
    // Check 0s and 1s
    ll c0 = 0, c1 = 0, cq = 0;
    foreach(i; 0..k){
        if(word[i] == 1) ++c1;
        if(word[i] > 1) ++cq;
    }
    c0 = k - cq - c1;
    foreach(i; k..n-k+1){
        if(c1 > k/2 || c0 > k/2 || abs(c1 - c0) > cq){
            writeln("NO");
            return;
        }
        // Remove
        c1 -= (word[i-k] == 1); c0 -= (word[i-k] == 0); cq -= (word[i-k] > 1);
        // Add
        c1 += (word[i] == 1); c0 += (word[i] == 0); cq += (word[i] > 1);

    }
    /* writeln(word); */
    if(c0 <= k/2 && c1 <= k/2 && abs(c1 - c0) <= cq){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		bool ok = true;
		foreach (i; 0..n-k)
		{
			if (s[i] == s[i+k]) continue;
			if (s[i] == '?')
				s[i] = s[i+k];
			else if (s[i+k] == '?')
				s[i+k] = s[i];
			else
			{
				ok = false;
				break;
			}
		}
		if (!ok) continue;

		long cnt0, cnt1;
		foreach (i; 0..k)
		{
			if (s[i] == '0')
				++cnt0;
			else if (s[i] == '1')
				++cnt1;
		}
		debug writeln("cnt0:", cnt0, " cnt1:", cnt1);

		auto k2 = k/2;
		foreach (i; 0..n-k)
		{
			if (cnt0 > k2 || cnt1 > k2)
			{
				ok = false;
				break;
			}
			if (s[i] == '0')
				--cnt0;
			else if (s[i] == '1')
				--cnt1;

			if (s[i+k] == '0')
				++cnt0;
			else if (s[i+k] == '1')
				++cnt1;
			debug writeln("i:", i, " cnt0:", cnt0, " cnt1:", cnt1);
		}
		if (cnt0 > k2 || cnt1 > k2)
			ok = false;

		ans[ti] = ok;
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.strip;
		auto p = new int [k];
		p[] = -1;
		foreach (d; 0..k)
		{
			for (int i = d; i < n; i += k)
			{
				if (s[i] != '?')
				{
					auto cur = s[i] - '0';
					if (p[d] == -1)
					{
						p[d] = cur;
					}
					else if (p[d] != cur)
					{
						p[d] = -2;
					}
				}
			}
		}
		writeln ((p.count (-2) > 0 ||
		    p.count (0) > k / 2 ||
		    p.count (1) > k / 2) ? "NO" : "YES");
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const K = readInt();
        const S = readToken();

        auto app = new bool[][](K, 2);
        foreach (i; 0 .. N) {
          if (S[i] != '?') {
            app[i % K][S[i] - '0'] = true;
          }
        }

        bool ok = true;
        auto cnt = new int[2];
        foreach (r; 0 .. K) {
          if (app[r][0] && app[r][1]) {
            ok = false;
          }
          foreach (s; 0 .. 2) {
            if (app[r][s]) {
              ++cnt[s];
            }
          }
        }

        bool ans;
        if (ok) {
          if (2 * cnt[0] <= K && 2 * cnt[1] <= K) {
            ans = true;
          }
        }
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}

// 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 inz(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 = char)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    int n;
    n = to!int(rd);
    int k = to!int(rd);
    dchar[] wordstr;
    readln(wordstr);
    wordstr.popBack;
    int[] word;
    foreach(cr; wordstr){
        word ~= (cr - '0');
    }
    // Set all initially
    foreach(i; 0..n-k-1){
        if(word[i] <= 1){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }else if(word[i+k] <= 1){
            word[i] = word[i+k];
        }
    }
    // Check 0s and 1s
    ll c0 = 0, c1 = 0, cq = 0;
    foreach(i; 0..k){
        if(word[i] == 1) ++c1;
        if(word[i] > 1) ++cq;
    }
    c0 = k - cq - c1;
    foreach(i; k..n-k+1){
        if(c1 > k/2 || c0 > k/2 || abs(c1 - c0) > cq){
            writeln("NO");
            return;
        }
        // Remove
        c1 -= (word[i-k] == 1); c0 -= (word[i-k] == 0); cq -= (word[i-k] > 1);
        // Add
        c1 += (word[i] == 1); c0 += (word[i] == 0); cq += (word[i] > 1);

    }
    /* writeln(word); */
    if(c0 <= k/2 && c1 <= k/2 && abs(c1 - c0) <= cq){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

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

// 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 inz(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 = char)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    int n;
    n = to!int(rd);
    int k = to!int(rd);
    dchar[] wordstr;
    readln(wordstr);
    wordstr.popBack;
    int[] word;
    foreach(cr; wordstr){
        word ~= (cr - '0');
    }
    // Set all initially
    foreach(i; 0..n-k-1){
        if(word[i] <= 1){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }else if(word[i+k] <= 1){
            word[i] = word[i+k];
        }
    }
    // Check 0s and 1s
    ll roll = 0;
    foreach(i; 0..k){
        if(word[i] == 1) ++roll;
    }
    // Handle ?
    foreach(i; 0..k){
        if(word[i] > 1){
            word[i] = !(roll >= k/2);
            roll += word[i];
        }
        if(i + k < n){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }
    }
    foreach(i; k .. n-k-1){
        if(i != k){ roll += word[i]; }
        if(roll != k/2){
            writeln("NO");
            return;
        }else{
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }
        roll -= word[i-k];
    }
    /* writeln(word); */
    if(roll == k/2){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

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

// 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 inz(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 = char)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    int n;
    n = to!int(rd);
    int k = to!int(rd);
    dchar[] wordstr;
    readln(wordstr);
    wordstr.popBack;
    int[] word;
    foreach(cr; wordstr){
        word ~= (cr - '0');
    }
    // Set all initially
    foreach(i; 0..n-k-1){
        if(word[i] <= 1){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }else if(word[i+k] <= 1){
            word[i] = word[i+k];
        }
    }
    // Check 0s and 1s
    ll roll = 0;
    foreach(i; 0..k){
        if(word[i] == 1) ++roll;
    }
    // Handle ?
    foreach(i; 0..k){
        // Handle
        if(word[i] > 1){
            word[i] = !(roll >= k/2);
            roll += word[i];
        }
        // HandleNext
        if(i + k < n){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }
    }
    foreach(i; k..n-k-1){
        // Handle Prev Check
        if(roll != k/2){
            writeln("NO");
            return;
        }else{
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }

        // Remove
        roll -= word[i-k];
        // Handle ?
        if(word[i] > 1){ word[i] = !(roll >= k/2); }
        // Add
        if(i != k-1){ roll += word[i]; }
    }
    /* writeln(word); */
    if(roll == k/2){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		bool ok = true;
		foreach (i; 0..n-k)
		{
			if (s[i] == s[i+k]) continue;
			if (s[i] == '?')
				s[i] = s[i+k];
			else if (s[i+k] == '?')
				s[i+k] = s[i];
			else
			{
				ok = false;
				break;
			}
		}
		if (!ok) continue;

		long cnt0, cnt1;
		foreach (i; 0..k)
		{
			if (s[i] == '0')
				++cnt0;
			else if (s[i] == '1')
				++cnt1;
		}
		debug writeln("cnt0:", cnt0, " cnt1:", cnt1);

		auto k2 = k/2;
		foreach (i; 0..n-k)
		{
			if (cnt0 > k2 || cnt1 > k2)
			{
				ok = false;
				break;
			}
			if (s[i] == '0')
				--cnt0;
			else if (s[i] == '1')
				--cnt1;

			if (s[i+k] == '0')
				++cnt0;
			else if (s[i] == '1')
				++cnt1;
			debug writeln("i:", i, " cnt0:", cnt0, " cnt1:", cnt1);
		}
		if (cnt0 > k2 || cnt1 > k2)
			ok = false;

		ans[ti] = ok;
	}

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


Alice, the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of $$$p$$$ players playing in $$$p$$$ different positions. She also recognizes the importance of audience support, so she wants to select $$$k$$$ people as part of the audience.There are $$$n$$$ people in Byteland. Alice needs to select exactly $$$p$$$ players, one for each position, and exactly $$$k$$$ members of the audience from this pool of $$$n$$$ people. Her ultimate goal is to maximize the total strength of the club.The $$$i$$$-th of the $$$n$$$ persons has an integer $$$a_{i}$$$ associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person $$$i$$$ and for each position $$$j$$$, Alice knows $$$s_{i, j}$$$  — the strength added by the $$$i$$$-th person to the club if he is selected to play in the $$$j$$$-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.

The first line contains $$$3$$$ integers $$$n,p,k$$$ ($$$2 \leq n \leq 10^{5}, 1 \leq p \leq 7, 1 \le k, p+k \le n$$$). The second line contains $$$n$$$ integers $$$a_{1},a_{2},\ldots,a_{n}$$$. ($$$1 \leq a_{i} \leq 10^{9}$$$). The $$$i$$$-th of the next $$$n$$$ lines contains $$$p$$$ integers $$$s_{i, 1}, s_{i, 2}, \dots, s_{i, p}$$$. ($$$1 \leq s_{i,j} \leq 10^{9}$$$)

Print a single integer $$${res}$$$  — the maximum possible strength of the club.

NoteIn the first sample, we can select person $$$1$$$ to play in the $$$1$$$-st position and persons $$$2$$$ and $$$3$$$ as audience members. Then the total strength of the club will be equal to $$$a_{2}+a_{3}+s_{1,1}$$$.

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

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader ();
  const n = r.next!uint;
  const p = r.next!uint;
  const k = r.next!uint;
  auto a = r.nextA!uint(n);
  auto b = new uint[][n];
  foreach (i; 0 .. n) {
    b[i] = r.nextA!uint (p);
  }
  auto idx = iota (0, n).array;
  idx.sort! ((i, j) => a[i] > a[j]);
  const int m = 1 << p;
  auto c = new ulong[m];
  auto pc = new int[m];
  foreach (i; 1 .. m) pc[i] = pc[i & (i-1)] + 1;
  auto e = new int[][m];
  foreach (i; 0 .. m) {
    foreach (j; 0 .. p) {
      if (!(i & (1 << j))) {
        e[i] ~= j;
      }
    }
  }
  auto d = new ulong[m];
  foreach (pos, x; idx) {
    d[] = c[];
    foreach (j; 0 .. m) {
      foreach (u; e[j]) {
        int o = j + (1 << u);
        ulong w = b[x][u] + c[j];
        if (d[o] < w) d[o] = w;
      }
      if (pos - pc[j] < k) {
        ulong w = a[x] + c[j];
        if (d[j] < w) d[j] = w;
      }
    }
    swap (c, d);
  }
  writeln (c.back);
}


There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one.  At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints.

The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists.

Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them.

NoteThe first test sample is the one in the picture.

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.string;
import std.range;
import std.range.primitives;
import std.conv;

int main() {
    debug stdin = File("in.txt", "r");

    char c;
    int n;
    readf("%s\n", &n);
    int fL = -1, fR = -1, lL = -1, lR = -1;
    foreach ( i ; 1 .. n + 1) {
        readf("%s", &c);
        if (c == 'R') {
            if (fR == -1) fR = i;
            lR = i;
        }
        else if (c == 'L') {
            if (fL == -1) fL = i;
            lL = i;
        }
    }
    if (fR == -1) writeln(lL, " ", fL - 1);
    else if (fL == -1) writeln(fR, " ", lR + 1);
    else writeln(fR, " ", lR);

    return 0;
}

module sigod.codeforces.p298A;

import std.stdio;

void main()
{
	stdin.readln();
	string road = stdin.readln();

	int r_start = -1;
	int r_end = -1;
	int l_start = -1;
	int l_end = -1;

	foreach (index, c; road) {
		if (c == 'R') {
			r_end = index + 1;

			if (r_start == -1) r_start = index + 1;
		}
		else if (c == 'L') {
			l_end = index + 1;

			if (l_start == -1) l_start = index + 1;
		}
	}

	int start = -1;
	int target = -1;

	if (l_start == -1) {
		start = r_start;
		target = r_end + 1;
	}
	else if (r_start == -1) {
		start = l_end;
		target = l_start - 1;
	}
	else {
		start = r_start;
		target = l_start - 1;
	}

	stdout.writeln(start, " ", target);
}


You are given a pair of integers $$$(a, b)$$$ and an integer $$$x$$$.You can change the pair in two different ways:   set (assign) $$$a := |a - b|$$$;  set (assign) $$$b := |a - b|$$$,  where $$$|a - b|$$$ is the absolute difference between $$$a$$$ and $$$b$$$.The pair $$$(a, b)$$$ is called $$$x$$$-magic if $$$x$$$ is obtainable either as $$$a$$$ or as $$$b$$$ using only the given operations (i.e. the pair $$$(a, b)$$$ is $$$x$$$-magic if $$$a = x$$$ or $$$b = x$$$ after some number of operations applied). You can apply the operations any number of times (even zero).Your task is to find out if the pair $$$(a, b)$$$ is $$$x$$$-magic or not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains three integers $$$a$$$, $$$b$$$ and $$$x$$$ ($$$1 \le a, b, x \le 10^{18}$$$).

For the $$$i$$$-th test case, print YES if the corresponding pair $$$(a, b)$$$ is $$$x$$$-magic and NO otherwise.

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]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto x = RD;

		if (a == x || b == x)
		{
			ans[ti] = true;
			continue;
		}

		if (a < b)
			swap(a, b);

		while (true)
		{
			auto rem = a % b;
			if (x > a) break;
			if ((x - rem) % b == 0)
			{
				ans[ti] = true;
				break;
			}
			if (rem == 0) break;
			a = b;
			b = rem;
		}
	}

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


The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.Let's consider a rectangular image that is represented with a table of size n × m. The table elements are integers that specify the brightness of each pixel in the image.A feature also is a rectangular table of size n × m. Each cell of a feature is painted black or white.To calculate the value of the given feature at the given image, you must perform the following steps. First the table of the feature is put over the table of the image (without rotations or reflections), thus each pixel is entirely covered with either black or white cell. The value of a feature in the image is the value of W - B, where W is the total brightness of the pixels in the image, covered with white feature cells, and B is the total brightness of the pixels covered with black feature cells.Some examples of the most popular Haar features are given below.   Your task is to determine the number of operations that are required to calculate the feature by using the so-called prefix rectangles.A prefix rectangle is any rectangle on the image, the upper left corner of which coincides with the upper left corner of the image.You have a variable value, whose value is initially zero. In one operation you can count the sum of pixel values at any prefix rectangle, multiply it by any integer and add to variable value.You are given a feature. It is necessary to calculate the minimum number of operations required to calculate the values of this attribute at an arbitrary image. For a better understanding of the statement, read the explanation of the first sample.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — the number of rows and columns in the feature. Next n lines contain the description of the feature. Each line consists of m characters, the j-th character of the i-th line equals to "W", if this element of the feature is white and "B" if it is black.

Print a single number — the minimum number of operations that you need to make to calculate the value of the feature.

6 8
BBBBBBBB
BBBBBBBB
BBBBBBBB
WWWWWWWW
WWWWWWWW
WWWWWWWW

NoteThe first sample corresponds to feature B, the one shown in the picture. The value of this feature in an image of size 6 × 8 equals to the difference of the total brightness of the pixels in the lower and upper half of the image. To calculate its value, perform the following two operations:  add the sum of pixels in the prefix rectangle with the lower right corner in the 6-th row and 8-th column with coefficient 1 to the variable value (the rectangle is indicated by a red frame);  add the number of pixels in the prefix rectangle with the lower right corner in the 3-rd row and 8-th column with coefficient  - 2 and variable value.  Thus, all the pixels in the lower three rows of the image will be included with factor 1, and all pixels in the upper three rows of the image will be included with factor 1 - 2 =  - 1, as required.

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

void main ()
{
	int n, m;
	while (readf (" %s %s ", &n, &m) > 0)
	{
		real [] [] a;
		foreach (i; 0..n)
		{
			a ~= readln.strip
			    .map !(q{a == 'B' ? -1.0L : +1.0L}).array;
		}
		int res = 0;
		foreach_reverse (i; 0..n)
		{
			foreach_reverse (j; 0..m)
			{
				if (a[i][j] != 0)
				{
					auto delta = -a[i][j];
					foreach (i2; 0..i + 1)
					{
						foreach (j2; 0..j + 1)
						{
							a[i2][j2] += delta;
						}
					}
					res++;
				}
			}
		}
		writeln (res);
	}
}


All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.Treasure Island may be represented as a rectangular table $$$n \times m$$$ which is surrounded by the ocean. Let us number rows of the field with consecutive integers from $$$1$$$ to $$$n$$$ from top to bottom and columns with consecutive integers from $$$1$$$ to $$$m$$$ from left to right. Denote the cell in $$$r$$$-th row and $$$c$$$-th column as $$$(r, c)$$$. Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell $$$(n, m)$$$.Vasya got off the ship in cell $$$(1, 1)$$$. Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell $$$(x, y)$$$ he can move only to cells $$$(x+1, y)$$$ and $$$(x, y+1)$$$. Of course Vasya can't move through cells with impassable forests.Evil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells $$$(1, 1)$$$ where Vasya got off his ship and $$$(n, m)$$$ where the treasure is hidden.Help Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure.

First line of input contains two positive integers $$$n$$$, $$$m$$$ ($$$3 \le n \cdot m \le 1\,000\,000$$$), sizes of the island. Following $$$n$$$ lines contains strings $$$s_i$$$ of length $$$m$$$ describing the island, $$$j$$$-th character of string $$$s_i$$$ equals "#" if cell $$$(i, j)$$$ contains an impassable forest and "." if the cell is free and passable. Let us remind you that Vasya gets of his ship at the cell $$$(1, 1)$$$, i.e. the first cell of the first row, and he wants to reach cell $$$(n, m)$$$, i.e. the last cell of the last row. It's guaranteed, that cells $$$(1, 1)$$$ and $$$(n, m)$$$ are empty.

Print the only integer $$$k$$$, which is the minimum number of cells Evil Witch has to turn into impassable forest in order to prevent Vasya from reaching the treasure.

NoteThe following picture illustrates the island in the third example. Blue arrows show possible paths Vasya may use to go from $$$(1, 1)$$$ to $$$(n, m)$$$. Red illustrates one possible set of cells for the Witch to turn into impassable forest to make Vasya's trip from $$$(1, 1)$$$ to $$$(n, m)$$$ impossible.

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, 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 = 1;
enum MOS = [987654323, 998244353, 10^^9 + 7, 10^^9 + 9];

void add(int k, ref int t, in int f) {
  if ((t += f) >= MOS[k]) {
    t -= MOS[k];
  }
}

int M, N;
string[] A;

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

      auto dpS = new int[][][](K, M, N);
      auto dpT = new int[][][](K, M, N);
      foreach (k; 0 .. K) {
        dpS[k][0][0] = 1;
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          if (A[x][y] == '.') {
            if (x + 1 < M && A[x + 1][y] == '.') {
              add(k, dpS[k][x + 1][y], dpS[k][x][y]);
            }
            if (y + 1 < N && A[x][y + 1] == '.') {
              add(k, dpS[k][x][y + 1], dpS[k][x][y]);
            }
          }
        }
        dpT[k][M - 1][N - 1] = 1;
        foreach_reverse (x; 0 .. M) foreach_reverse (y; 0 .. N) {
          if (A[x][y] == '.') {
            if (x - 1 >= 0 && A[x - 1][y] == '.') {
              add(k, dpT[k][x - 1][y], dpT[k][x][y]);
            }
            if (y - 1 >= 0 && A[x][y - 1] == '.') {
              add(k, dpT[k][x][y - 1], dpT[k][x][y]);
            }
          }
        }
      }

      int ans;

      bool zero = true;
      foreach (k; 0 .. K) {
        zero = zero && (dpT[k][0][0] == 0);
      }
      if (zero) {
        ans = 0;
      } else {
        ans = 2;
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          if (A[x][y] == '.' && !(x == 0 && y == 0) && !(x == M - 1 && y == N - 1)) {
            bool all = true;
            foreach (k; 0 .. K) {
              all = all && (dpT[k][0][0] == (1L * dpS[k][x][y] * dpT[k][x][y]) % MOS[k]);
            }
            if (all) {
              debug {
                writeln("block ", x, " ", y);
              }
              ans = 1;
            }
          }
        }
      }

      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, 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)); }

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

int M, N;
string[] A;

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

      auto uf = new int[M * N + 2];
      uf[] = -1;
      const s = M * N;
      const t = M * N + 1;

      foreach (x; 0 .. M) foreach (y; 0 .. N) {
        if (A[x][y] == '#') {
          if (x + 1 < M && A[x + 1][y] == '#') {
            uf.connect(x * N + y, (x + 1) * N + y);
          }
          if (y + 1 < N && A[x][y + 1] == '#') {
            uf.connect(x * N + y, x * N + (y + 1));
          }
        }
      }
      foreach (x; 0 .. M) foreach (y; 0 .. N) {
        if (A[x][y] == '#') {
          if (x == 0 || y == N - 1) {
            uf.connect(s, x * N + y);
          }
          if (x == M - 1 || y == 0) {
            uf.connect(t, x * N + y);
          }
        }
      }

      int ans;
      if (uf.root(s) == uf.root(t)) {
        ans = 0;
      } else {
        ans = 2;
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          if (A[x][y] == '.' && !(x == 0 && y == 0) && !(x == M - 1 && y == N - 1)) {
            bool hasS = (x == 0 || y == N - 1);
            bool hasT = (x == M - 1 || y == 0);
            foreach (xx; x - 1 .. x + 1 + 1) foreach (yy; y - 1 .. y + 1 + 1) {
              if (0 <= xx && xx < M && 0 <= yy && yy < N) {
                if (A[xx][yy] == '#') {
                  hasS = hasS || (uf.root(s) == uf.root(xx * N + yy));
                  hasT = hasT || (uf.root(t) == uf.root(xx * N + yy));
                }
              }
            }
            if (hasS && hasT) {
              debug {
                writeln(x, " ", y);
              }
              ans = 1;
            }
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, 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)); }

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

int M, N;
string[] A;

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

      auto uf = new int[M * N + 2];
      uf[] = -1;
      const s = M * N;
      const t = M * N + 1;

      foreach (x; 0 .. M) foreach (y; 0 .. N) {
        if (A[x][y] == '#') {
          foreach (xx; x - 1 .. x + 1 + 1) foreach (yy; y - 1 .. y + 1 + 1) {
            if (0 <= xx && xx < M && 0 <= yy && yy < N) {
              if (A[xx][yy] == '#') {
                uf.connect(x * N + y, xx * N + yy);
              }
            }
          }
        }
      }
      foreach (x; 0 .. M) foreach (y; 0 .. N) {
        if (A[x][y] == '#') {
          if (x == 0 || y == N - 1) {
            uf.connect(s, x * N + y);
          }
          if (x == M - 1 || y == 0) {
            uf.connect(t, x * N + y);
          }
        }
      }

      int ans;
      if (uf.root(s) == uf.root(t)) {
        ans = 0;
      } else {
        ans = 2;
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          if (A[x][y] == '.' && !(x == 0 && y == 0) && !(x == M - 1 && y == N - 1)) {
            bool hasS = (x == 0 || y == N - 1);
            bool hasT = (x == M - 1 || y == 0);
            foreach (xx; x - 1 .. x + 1 + 1) foreach (yy; y - 1 .. y + 1 + 1) {
              if (0 <= xx && xx < M && 0 <= yy && yy < N) {
                if (A[xx][yy] == '#') {
                  hasS = hasS || (uf.root(s) == uf.root(xx * N + yy));
                  hasT = hasT || (uf.root(t) == uf.root(xx * N + yy));
                }
              }
            }
            if (hasS && hasT) {
              debug {
                writeln(x, " ", y);
              }
              ans = 1;
            }
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are playing a game on a $$$n \times m$$$ grid, in which the computer has selected some cell $$$(x, y)$$$ of the grid, and you have to determine which one. To do so, you will choose some $$$k$$$ and some $$$k$$$ cells $$$(x_1, y_1),\, (x_2, y_2), \ldots, (x_k, y_k)$$$, and give them to the computer. In response, you will get $$$k$$$ numbers $$$b_1,\, b_2, \ldots b_k$$$, where $$$b_i$$$ is the manhattan distance from $$$(x_i, y_i)$$$ to the hidden cell $$$(x, y)$$$ (so you know which distance corresponds to which of $$$k$$$ input cells). After receiving these $$$b_1,\, b_2, \ldots, b_k$$$, you have to be able to determine the hidden cell. What is the smallest $$$k$$$ for which is it possible to always guess the hidden cell correctly, no matter what cell computer chooses?As a reminder, the manhattan distance between cells $$$(a_1, b_1)$$$ and $$$(a_2, b_2)$$$ is equal to $$$|a_1-a_2|+|b_1-b_2|$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows.  The single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — the number of rows and the number of columns in the grid.

For each test case print a single integer — the minimum $$$k$$$ for that test case.

NoteIn the first test case, the smallest such $$$k$$$ is $$$2$$$, for which you can choose, for example, cells $$$(1, 1)$$$ and $$$(2, 1)$$$.Note that you can't choose cells $$$(1, 1)$$$ and $$$(2, 3)$$$ for $$$k = 2$$$, as both cells $$$(1, 2)$$$ and $$$(2, 1)$$$ would give $$$b_1 = 1, b_2 = 2$$$, so we wouldn't be able to determine which cell is hidden if computer selects one of those.In the second test case, you should choose $$$k = 1$$$, for it you can choose cell $$$(3, 1)$$$ or $$$(1, 1)$$$.

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const M = readLong();
        const N = readLong();

        int ans;
        if (M == 1 && N == 1) {
          ans = 0;
        } else if (M == 1 || N == 1) {
          ans = 1;
        } else {
          ans = 2;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto m = readInt!int;
	int mx = max(n, m);
	int mn = min(n, m);
	if (mn > 1) return writeln(2);
	if (mx == 1) return writeln(0);
	return writeln(1);
}

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

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

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

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

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

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

void main()
{
  long t;
  readf!" %d "(t);
  foreach (casenum ; 1 .. t + 1) {
    long n, m;
    readf!" %d %d "(n, m);
    if (n == 1 && m == 1)
      writeln(0);
    else if (n == 1 || m == 1)
      writeln(1);
    else
      writeln(2);
  }
}

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]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		if (n == 1 && m == 1)
			ans[ti] = 0;
		else if (n == 1 || m == 1)
			ans[ti] = 1;
		else
			ans[ti] = 2;
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int m, n;
		readf !(" %s %s") (m, n);
		writeln ((m > 1) + (n > 1));
	}
}

// 提出解
void solve(){
	foreach(_; 0 .. scan!int){
		long n = scan!long, m = scan!long;
		long ans;
		if(n == 1 && m == 1) ans = 0;
		else if(n == 1 || m == 1) ans = 1;
		else ans = 2;

		ans.print;
	}
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// 愚直解
void jury(){
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// テストケース
void gen(){
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// テンプレ
import std;
bool DEBUG = 0;
void main(string[] args){
	if(args.canFind("-debug")) DEBUG = 1;
	if(args.canFind("-gen")) gen; else if(args.canFind("-jury")) jury; else solve;
}
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); }
void print(T)(T t){ writeln(t); }
void print(T, A ...)(T t, A a){ stdout.write(t, " "), print(a); }
string unsplit(T)(T xs, string d = " "){ return xs.array.to!(string[]).join(d); }
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)(int n){ return n.iota.map!(i => scan!T()).array; }
T mini(T)(ref T x, T y){ if(x > y) x = y; return x; }
T maxi(T)(ref T x, T y){ if(x < y) x = y; return x; }
T mid(T)(T l, T r, bool delegate(T) f){
	T m = (l + r) / 2; (f(m)? l: r) = m; return f(l)? f(r - 1)? r: mid(l, r, f): l;
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// ライブラリ（基本）

class UnionFind{
	this(int n){ foreach(i; 0 .. n) R ~= i, K ~= [i]; } int[] R; int[][] K;
	void unite(int a, int b){
		int ra = R[a], rb = R[b]; if(ra == rb) return;
		if(K[ra].length < K[rb].length) unite(b, a);
		else foreach(k; K[rb]) R[k] = ra, K[ra] ~= k;
	}
	int find(int a){ return R[a]; }
	int getSize(int a){ return K[R[a]].length.to!int; }
}
class Queue(T){
	private T[] xs; private uint i, j;
	this(T[] xs = []){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){ while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1; xs[j ++] = x; }
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	void flush(){ i = j; }
	alias empty = isEmpty, front = peek, popFront = deq, pop = deq, push = enq, top = peek;
	Queue opOpAssign(string op)(T x) if(op == "~"){ enq(x); return this; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}
class Stack(T){
	private T[] xs; private uint j;
	this(T[] xs = []){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j; }
	bool isEmpty(){ return j == 0; }
	void push(T x){ while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1; xs[j ++] = x; }
	T pop(){ assert(j > 0); return xs[-- j]; }
	T peek(){ assert(j > 0); return xs[j - 1]; }
	void clear(){ j = 0; }
	alias empty = isEmpty, front = peek, popFront = pop, top = peek;
	Stack opOpAssign(string op)(T x) if(op == "~"){ push(x); return this; }
	T opIndex(uint li){ assert(j > 0 && j - 1 >= li); return xs[j - 1 - li]; }
	static Stack!T opCall(T[] xs = []){ return new Stack!T(xs); }
	T[] array(){ return xs[0 .. j]; }
	override string toString(){ return array.to!string; }
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// ライブラリ（追加）

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const M = readLong();
        const N = readLong();

        const ans = min(M, N, 2);
        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)); }

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const M = readLong();
        const N = readLong();

        const ans = min(M, N, 3);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


The Bitlandians are quite weird people. They have very peculiar customs.As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.

The first line contains integer n (1 ≤ n ≤ 106) — the number of eggs. Next n lines contain two integers ai and gi each (0 ≤ ai, gi ≤ 1000; ai + gi = 1000): ai is the price said by A. for the i-th egg and gi is the price said by G. for the i-th egg.

If it is impossible to assign the painting, print "-1" (without quotes). Otherwise print a string, consisting of n letters "G" and "A". The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter "A" represents A. and letter "G" represents G. If we denote the money Uncle J. must pay A. for the painting as Sa, and the money Uncle J. must pay G. for the painting as Sg, then this inequality must hold: |Sa  -  Sg|  ≤  500.  If there are several solutions, you are allowed to print any of them.

module cf_282B;

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

void main() {
    immutable MAX_PRICE = 1000;
    immutable HALF_PRICE = 500;

    int n;
    int[] eggs;

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

    string result;
    int a = 0, g = 0, cur = 0;

    while (cur < n) {
        while (cur < n && abs(a - g) <= HALF_PRICE) {
            if (abs(a + MAX_PRICE - eggs[cur] - g) > HALF_PRICE) {
                break;
            }

            a += MAX_PRICE - eggs[cur++];
            result ~= 'A';
        }

        while (cur < n && abs(a - g) <= HALF_PRICE) {
            if (abs(g + eggs[cur] - a) > HALF_PRICE) {
                break;
            }

            g += eggs[cur++];
            result ~= 'G';
        }
    }

    if (abs(a - g) > HALF_PRICE) {
        writeln(-1);
    } else {
        writeln(result);
    }
}

import std.stdio;
import std.conv:to;
import std.string:chomp, countchars;
import std.array;

void main() {
    int eggs = to!int(readln().chomp);
    int A, G, iA, iG;
    auto result = appender!string();
    foreach(i; 0..eggs) {
        stdin.readf("%d %d\n", &iA, &iG);

        if((A + iA - G) <= 500) {
            A += iA;
            result.put("A");
        } else {
            G += iG;
            result.put("G");
        }
    }
    writeln(result.data);
}

module cf_282B;

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

struct Egg {
    int price;
    int pos;
}

void main() {
    immutable MAX_PRICE = 1000;

    int n;
    Egg[] eggs;

    readf("%d", &n);
    eggs = new Egg[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d %d", &eggs[i].price, &eggs[i].price);
        eggs[i].pos = i;
    }

    sort!((egg1, egg2) { return egg1.price < egg2.price; })(eggs);

    char[] result = new char[n];
    int a = 0, g = 0, left = 0, right = n - 1;

    while (left <= right) {
        g += eggs[left].price;
        result[eggs[left].pos] = 'G';
        ++left;
        a += MAX_PRICE - eggs[right].price;
        result[eggs[right].pos] = 'A';
        --right;
    }

    if (abs(a - g) > MAX_PRICE / 2) {
        writeln(-1);
    } else {
        writeln(result);
    }
}

module cf_282B;

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

struct Egg {
    int price;
    int pos;
}

void main() {
    immutable MAX_PRICE = 1000;

    int n;
    Egg[] eggs;

    readf("%d", &n);
    eggs = new Egg[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d %d", &eggs[i].price, &eggs[i].price);
        eggs[i].pos = i;
    }

    sort!((egg1, egg2) { return egg1.price < egg2.price; })(eggs);

    char[] result = new char[n];
    int a = 0, g = 0, left = 0, right = n - 1;

    while (left <= right) {
        if (a > g) {
            g += eggs[left].price;
            result[eggs[left].pos] = 'G';
            ++left;
        } else {
            a += MAX_PRICE - eggs[right].price;
            result[eggs[right].pos] = 'A';
            --right;
        }
    }

    if (abs(a - g) > MAX_PRICE / 2) {
        writeln(-1);
    } else {
        writeln(result);
    }
}

module cf_282B;

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

struct Egg {
    int price;
    int pos;
}

void main() {
    immutable MAX_PRICE = 1000;

    int n;
    Egg[] eggs;

    readf("%d", &n);
    eggs = new Egg[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d %d", &eggs[i].price, &eggs[i].price);
        eggs[i].pos = i;
    }

    sort!((egg1, egg2) { return egg1.price < egg2.price; })(eggs);

    char[] result = new char[n];
    int a = 0, g = 0, left = 0, right = n - 1;

    while (left <= right) {
        if (a > g) {
            g += eggs[left].price;
            result[eggs[left].pos] = 'G';
            ++left;
        } else {
            a += MAX_PRICE - eggs[right].price;
            result[eggs[right].pos] = 'A';
            --right;
        }
    }

    if (abs(a - g) > MAX_PRICE / 2 || n == 1) {
        writeln(-1);
    } else {
        writeln(result);
    }
}

module cf_282B;

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

struct Egg {
    int price;
    int pos;
}

void main() {
    immutable MAX_PRICE = 1000;

    int n;
    Egg[] eggs;

    readf("%d", &n);
    eggs = new Egg[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d %d", &eggs[i].price, &eggs[i].price);
        eggs[i].pos = i;
    }

    sort!((egg1, egg2) { return egg1.price < egg2.price; })(eggs);

    char[] result = new char[n];
    int a = 0, g = 0, eggLeft = 0, eggRight = n - 1;

    while (eggLeft <= eggRight) {
        if (a > g) {
            while (eggLeft <= eggRight && a >= g) {
                g += eggs[eggLeft].price;
                result[eggs[eggLeft].pos] = 'G';
                ++eggLeft;
            }
        } else {
            while (eggLeft <= eggRight && g >= a) {
                a += MAX_PRICE - eggs[eggRight].price;
                result[eggs[eggRight].pos] = 'A';
                --eggRight;
            }
        }
    }

    if (abs(a - g) > MAX_PRICE / 2) {
        writeln(-1);
    } else {
        writeln(result);
    }
}


You are given a Young diagram. Given diagram is a histogram with $$$n$$$ columns of lengths $$$a_1, a_2, \ldots, a_n$$$ ($$$a_1 \geq a_2 \geq \ldots \geq a_n \geq 1$$$).    Young diagram for $$$a=[3,2,2,2,1]$$$. Your goal is to find the largest number of non-overlapping dominos that you can draw inside of this histogram, a domino is a $$$1 \times 2$$$ or $$$2 \times 1$$$ rectangle.

The first line of input contain one integer $$$n$$$ ($$$1 \leq n \leq 300\,000$$$): the number of columns in the given histogram. The next line of input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 300\,000, a_i \geq a_{i+1}$$$): the lengths of columns.

Output one integer: the largest number of non-overlapping dominos that you can draw inside of the given Young diagram.

NoteSome of the possible solutions for the example:

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

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

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

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

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

      auto s = new long[2];
      foreach (i; 0 .. N) {
        s[i % 2] += A[i] / 2;
        s[1 - i % 2] += A[i] - A[i] / 2;
      }
      const ans = min(s[0], s[1]);
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters.Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (ai) represents the number of meters the guest is going to take up if he sits at the restaurant table.Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than p. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table.Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible n! orders of guests in the queue. Help Maxim, calculate this number.

The first line contains integer n (1 ≤ n ≤ 50) — the number of guests in the restaurant. The next line contains integers a1, a2, ..., an (1 ≤ ai ≤ 50) — the guests' sizes in meters. The third line contains integer p (1 ≤ p ≤ 50) — the table's length in meters.  The numbers in the lines are separated by single spaces.

In a single line print a real number — the answer to the problem. The answer will be considered correct, if the absolute or relative error doesn't exceed 10 - 4.

NoteIn the first sample the people will come in the following orders:   (1, 2, 3) — there will be two people in the restaurant;  (1, 3, 2) — there will be one person in the restaurant;  (2, 1, 3) — there will be two people in the restaurant;  (2, 3, 1) — there will be one person in the restaurant;  (3, 1, 2) — there will be one person in the restaurant;  (3, 2, 1) — there will be one person in the restaurant. In total we get (2 + 1 + 2 + 1 + 1 + 1) / 6 = 8 / 6 = 1.(3).

import std.stdio : write, writeln, writefln, stdin;
import std.array;
import std.range;
import std.typecons;
import std.algorithm : max, min;
import std.bigint;

int n;
int[] a;
bool[] done;
int p;

BigInt[long] note;
BigInt den;
int idx;
BigInt[ int ] cnt_note;
BigInt dfs( int sum, int cnt, long bits ){
	if( bits in note ){
		return note[ bits ];
	}
	if( sum > p ){
		if( cnt in cnt_note ){
			return cnt_note[ cnt ];
		}else{
			note[ bits ] = BigInt((cnt - 1).to!string)*(n - cnt).frac;
			cnt_note[ cnt ] = note[ bits ];
		}
		return note[ bits ];
	}
	if( cnt == n ){
		note[ bits ] = cnt;
		return BigInt(cnt.to!string);
	}

	BigInt all;

	int buf_key = -1;
	BigInt buf_res = BigInt("-1");
	foreach(i; n.iota){
		if( !done[i] ){
			if( buf_key == a[i] ){
				all += buf_res;
			}else{
				done[i] = true;
				idx = i;
				auto res = dfs( sum + a[i], cnt + 1, bits | (1L<<i) );
				all += res;
				done[i] = false;

				buf_res = res;
				buf_key = a[i];
			}
		}
	}

	note[ bits ] = all;
	return all;
}

BigInt[ int ] frac_note;
BigInt frac( int n ){
	if( n in frac_note ){
		return frac_note[ n ];
	}
	if( n == 0 ){
		return BigInt("1");
	}else{
		frac_note[ n ] = BigInt(n.to!string) * frac( n - 1 );
		return frac_note[ n ];
	}
}

void main(){
	n.next;
	a = a.init;
	foreach(i; n.iota) a ~= next!int();
	done = repeat( false ).take( n ).array;
	p.next;

	a.sort;
	BigInt num = dfs( 0, 0, 0 );

	den = frac( n );
	long res1 = (num/den).toLong;
	BigInt res2 = num%den;
	res2 *= BigInt("1_00000_00000");
	res2 /= den;
	double res2_ = res2.toLong / 1_00000_00000.;
	writefln( "%.10f", res1 + res2_ );
}

import std.stdio : readln;
import std.conv : to;
import std.string : split, chomp;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : write, writeln, writefln, stdin;
import std.array;
import std.range;
import std.typecons;
import std.algorithm : max, min;
import std.bigint;

int n;
int[] a;
bool[] done;
int p;

BigInt[long] note;
BigInt den;
BigInt dfs( int sum, BigInt cnt, long bits ){
	if( bits in note ){
		return note[ bits ];
	}
	if( sum > p ){
//		den += (n - cnt).frac;
		note[ bits ] = (cnt - 1)*(n - cnt).frac;
		return (cnt - 1)*(n - cnt).frac;
	}
	if( cnt == n ){
//		++den;
		note[ bits ] = cnt;
		return cnt;
	}

	BigInt all;
	int buf_key = -1;
	BigInt buf_res = BigInt("-1");
	foreach(i; n.iota){
		if( !done[i] ){
			if( buf_key == a[i] ){
				all += buf_res;
			}else{
				done[i] = true;
				auto res = dfs( sum + a[i], cnt + BigInt("1"), bits | (1<<i) );
				all += res;
				done[i] = false;

				buf_res = res;
				buf_key = a[i];
			}
		}
	}

	note[ bits ] = all;
	return all;
}

BigInt frac( BigInt n ){
	if( n == 0 ){
		return BigInt("1");
	}else{
		return n * frac( n - BigInt("1") );
	}
}

void main(){
	n.next;
	a = a.init;
	foreach(i; n.iota) a ~= next!int();
	done = repeat( false ).take( n ).array;
	p.next;

	BigInt num = dfs( 0, BigInt("0"), 0 );

	den = frac( BigInt(n.to!string) );
	debug(1) dbg( num, den );
	long res1 = (num/den).toLong;
	BigInt res2 = num%den;
	res2 *= BigInt("1_00000_00000");
	res2 /= den;
	double res2_ = res2.toLong / 1_00000_00000.;
	writefln( "%.10f", res1 + res2_ );
}

import std.stdio : readln;
import std.conv : to;
import std.string : split, chomp;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : write, writeln, writefln, stdin;
import std.array;
import std.range;
import std.typecons;
import std.algorithm : max, min;

int n;
int[] a;
bool[] done;
int p;

int den;
int dfs( int sum, int cnt ){
	if( sum > p ){
		++den;
		return cnt - 1;
	}
	if( cnt == n ){
		++den;
		return cnt;
	}

	int all;
	foreach(i; n.iota){
		if( !done[i] ){
			done[i] = true;
			all += dfs( sum + a[i], cnt + 1 );
			done[i] = false;
		}
	}

	return all;
}

void main(){
	n.next;
	a = a.init;
	foreach(i; n.iota) a ~= next!int();
	done = repeat( false ).take( n ).array;
	p.next;

	int num = dfs( 0, 0 );

	writefln( "%.10f", num/cast(double)den );
}

import std.stdio : readln;
import std.conv : to;
import std.string : split, chomp;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : write, writeln, writefln, stdin;
import std.array;
import std.range;
import std.typecons;
import std.algorithm : max, min;

int n;
int[] a;
bool[] done;
int p;

long den;
long dfs( int sum, int cnt ){
	if( sum > p ){
		den += (n - cnt).frac;
		return (cnt - 1)*(n - cnt).frac;
	}
	if( cnt == n ){
		++den;
		return cnt;
	}

	int all;
	foreach(i; n.iota){
		if( !done[i] ){
			done[i] = true;
			all += dfs( sum + a[i], cnt + 1 );
			done[i] = false;
		}
	}

	return all;
}

long frac( long n ){
	if( n == 0 ){
		return 1;
	}else{
		return n * frac( n - 1 );
	}
}

void main(){
	n.next;
	a = a.init;
	foreach(i; n.iota) a ~= next!int();
	done = repeat( false ).take( n ).array;
	p.next;

	long num = dfs( 0, 0 );

	[num, den, n.frac].writeln;
	writefln( "%.10f", num/cast(double)den );
}

import std.stdio : readln;
import std.conv : to;
import std.string : split, chomp;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : write, writeln, writefln, stdin;
import std.array;
import std.range;
import std.typecons;
import std.algorithm : max, min;

int n;
int[] a;
bool[] done;
int p;

long den;
long dfs( int sum, int cnt ){
	if( sum > p ){
		den += (n - cnt).frac;
		return (cnt - 1)*(n - cnt).frac;
	}
	if( cnt == n ){
		++den;
		return cnt;
	}

	int all;
	foreach(i; n.iota){
		if( !done[i] ){
			done[i] = true;
			all += dfs( sum + a[i], cnt + 1 );
			done[i] = false;
		}
	}

	return all;
}

long frac( long n ){
	if( n == 0 ){
		return 1;
	}else{
		return n * frac( n - 1 );
	}
}

void main(){
	n.next;
	a = a.init;
	foreach(i; n.iota) a ~= next!int();
	done = repeat( false ).take( n ).array;
	p.next;

	long num = dfs( 0, 0 );

	writefln( "%.10f", num/cast(double)den );
}

import std.stdio : readln;
import std.conv : to;
import std.string : split, chomp;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}


Nastia has received an array of $$$n$$$ positive integers as a gift.She calls such an array $$$a$$$ good that for all $$$i$$$ ($$$2 \le i \le n$$$) takes place $$$gcd(a_{i - 1}, a_{i}) = 1$$$, where $$$gcd(u, v)$$$ denotes the greatest common divisor (GCD) of integers $$$u$$$ and $$$v$$$.You can perform the operation: select two different indices $$$i, j$$$ ($$$1 \le i, j \le n$$$, $$$i \neq j$$$) and two integers $$$x, y$$$ ($$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$. Then change $$$a_i$$$ to $$$x$$$ and $$$a_j$$$ to $$$y$$$.The girl asks you to make the array good using at most $$$n$$$ operations.It can be proven that this is always possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_{n}$$$ ($$$1 \le a_i \le 10^9$$$) — the array which Nastia has received as a gift. It's guaranteed that the sum of $$$n$$$ in one test doesn't exceed $$$2 \cdot 10^5$$$.

For each of $$$t$$$ test cases print a single integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of operations. You don't need to minimize this number. In each of the next $$$k$$$ lines print $$$4$$$ integers $$$i$$$, $$$j$$$, $$$x$$$, $$$y$$$ ($$$1 \le i \neq j \le n$$$, $$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$ — in this manner you replace $$$a_i$$$ with $$$x$$$ and $$$a_j$$$ with $$$y$$$. If there are multiple answers, print any.

NoteConsider the first test case.Initially $$$a = [9, 6, 3, 11, 15]$$$.In the first operation replace $$$a_1$$$ with $$$11$$$ and $$$a_5$$$ with $$$9$$$. It's valid, because $$$\min{(a_1, a_5)} = \min{(11, 9)} = 9$$$.After this $$$a = [11, 6, 3, 11, 9]$$$.In the second operation replace $$$a_2$$$ with $$$7$$$ and $$$a_5$$$ with $$$6$$$. It's valid, because $$$\min{(a_2, a_5)} = \min{(7, 6)} = 6$$$.After this $$$a = [11, 7, 3, 11, 6]$$$ — a good array.In the second test case, the initial array is already good.

import std.stdio, std.string, std.algorithm, std.conv, std.range, std.math;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n;
        readf!"%d\n"(n);
        int[] a = readln.split.map!(to!int).array;
        int mn = cast(int)1E9 + 7, pos = -1;
        foreach (i; 0 .. n)
            if (a[i] < mn)
            {
                mn = a[i];
                pos = i;
            }
        writeln(n - 1);
        foreach (i; 0 .. n)
        {
            if (i == pos)
                continue;
            writeln(pos + 1, ' ', i + 1, ' ', mn, ' ', mn + abs(i - pos));
        }
    }
}

import std.stdio, std.string, std.algorithm, std.conv, std.range, std.math;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n;
        readf!"%d\n"(n);
        int[] a = readln.split.map!(to!int).array;
        int mn = cast(int)1E9 + 7, pos = -1;
        foreach (i; 0 .. n)
            if (a[i] < mn)
            {
                mn = a[i];
                pos = i;
            }
        foreach (i; 0 .. n)
        {
            if (i == pos)
                continue;
            writeln(pos + 1, ' ', i + 1, ' ', mn, ' ', mn + abs(i - pos));
        }
    }
}