Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101. The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it.An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.

The first line contains a sequence of characters each of which can either be a "0", a "1" or a "?". This sequence determines the initial arrangement of cards on the table from the left to the right. The characters "?" mean that the given card was spoiled before the game. The sequence's length ranges from 2 to 105, inclusive.

Print the set of outcomes for all possible initial digits arrangements. Print each possible outcome on a single line. Each outcome should be represented by two characters: the digits written on the cards that were left by the end of the game. The outcomes should be sorted lexicographically in ascending order (see the first sample).

NoteIn the first sample all 16 variants of numbers arrangement are possible. For the variant 0000 the outcome is 00. For the variant 1111 the outcome is 11. For the variant 0011 the outcome is 01. For the variant 1100 the outcome is 10. Regardless of outcomes for all other variants the set which we are looking for will contain all 4 possible outcomes.In the third sample only 2 variants of numbers arrangement are possible: 111 and 101. For the variant 111 the outcome is 11. For the variant 101 the outcome is 01, because on the first turn Masha can remove the first card from the left after which the game will end.

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    auto s = readln.chomp;

    int[] xs;
    int c0, c1;
    foreach (int i, c; s) {
        switch (c) {
            case '?': xs ~= i; break;
            case '0': c0++; break;
            case '1': c1++; break;
            default: assert(0);
        }
    }

    int N = cast(int)(s.length);

    int d0 = (N - 2) / 2,
        d1 = (N - 1) / 2;
    assert(d0 + d1 == N - 2);

    string[] ans;

    if (d1 >= c1) ans ~= "00";
    if (d0 >= c0) ans ~= "11";

    auto init = s[0 .. $ - 1];
    auto last = s.back;

    // 10が作れるか
    if (last == '0' && N / 2 >= c0 && (N + 1) / 2 >= c1) ans ~= "10";
    if (last == '?' && N / 2 >= c0 + 1 && (N + 1) / 2 >= c1) ans ~= "10";
    // 01が作れるか
    if (last == '1' && N / 2 >= c0 && (N + 1) / 2 >= c1) ans ~= "01";
    if (last == '?' && N / 2 >= c0 && (N + 1) / 2 >= c1 + 1) ans ~= "01";

    ans.sort;
    writeln(ans.join("\n"));

}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    auto s = readln.chomp;

    int[] xs;
    int c0, c1;
    foreach (int i, c; s) {
        switch (c) {
            case '?': xs ~= i; break;
            case '0': c0++; break;
            case '1': c1++; break;
            default: assert(0);
        }
    }

    int N = cast(int)(s.length);

    int d0 = (N - 2) / 2,
        d1 = (N - 1) / 2;
    assert(d0 + d1 == N - 2);

    string[] ans;

    if (d1 >= c1) ans ~= "00";
    if (d0 >= c0) ans ~= "11";

    auto init = s[0 .. $ - 1];
    auto last = s.back;

    // 10が作れるか
    if (last == '0' || last == '?') {
        if ((N - 1) / 2 >= init.count!"a == '0'" &&
            N / 2 >= init.count!"a == '1'") ans ~= "10";
    }
    // 01が作れるか
    if (last == '1' || last == '?') {
        if ((N - 1) / 2 >= init.count!"a == '0'" &&
            N / 2 >= init.count!"a == '1'") ans ~= "01";
    }

    ans.sort;
    writeln(ans.join("\n"));

}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    auto s = readln.chomp;

    int[] xs;
    int c0, c1;
    foreach (int i, c; s) {
        switch (c) {
            case '?': xs ~= i; break;
            case '0': c0++; break;
            case '1': c1++; break;
            default: assert(0);
        }
    }

    int N = cast(int)(s.length);

    int d0 = (N - 2) / 2,
        d1 = (N - 1) / 2;
    assert(d0 + d1 == N - 2);

    string[] ans;

    if (d1 >= c1) ans ~= "00";
    if (d0 >= c0) ans ~= "11";

    auto init = s[0 .. $ - 2];
    auto last = s[$ - 2 .. $];

    // 10が作れるか
    if (last[0] != '0' && last[1] != '1') {
        if ((N - 2) / 2 >= init.count!"a == '0'") ans ~= "10";
    }
    // 01が作れるか
    if (last[0] != '1' && last[1] != '0') {
        if ((N - 2) / 2 >= init.count!"a == '0'") ans ~= "01";
    }

    ans.sort;
    writeln(ans.join("\n"));

}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    auto s = readln.chomp;

    int[] xs;
    int c0, c1;
    foreach (int i, c; s) {
        switch (c) {
            case '?': xs ~= i; break;
            case '0': c0++; break;
            case '1': c1++; break;
            default: assert(0);
        }
    }

    int N = cast(int)(s.length);

    int d0 = (N - 2) / 2,
        d1 = (N - 1) / 2;
    assert(d0 + d1 == N - 2);

    string[] ans;

    if (d1 >= c1) ans ~= "00";
    if (d0 >= c0) ans ~= "11";

    auto init = s[0 .. $ - 1];
    auto last = s.back;

    // 10が作れるか
    if (last == '0' || last == '?') {
        if ((N - 1) / 2 >= init.count!"a == '0'") ans ~= "10";
    }
    // 01が作れるか
    if (last == '1' || last == '?') {
        if ((N - 1) / 2 >= init.count!"a == '0'") ans ~= "01";
    }

    ans.sort;
    writeln(ans.join("\n"));

}


You are given a sequence of numbers a1, a2, ..., an, and a number m.Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.

The first line contains two numbers, n and m (1 ≤ n ≤ 106, 2 ≤ m ≤ 103) — the size of the original sequence and the number such that sum should be divisible by it. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).

In the single line print either "YES" (without the quotes) if there exists the sought subsequence, or "NO" (without the quotes), if such subsequence doesn't exist.

NoteIn the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5.In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist.In the third sample test you need to choose two numbers 3 on the ends.In the fourth sample test you can take the whole subsequence.

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

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

    if (n >= m) {
        writeln("YES");
        return;
    }

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

    auto dp = new bool[] (m+1);
    dp[0] = true;
    auto dp2 = new bool[] (m+1);
    foreach (e; arr) {
        foreach (i; 0 .. m+1) dp2[i] |= dp[((i - e) % m + m) % m];
        dp[] |= dp2[];
    }

    writeln(dp[m] ? "YES" : "NO");
}


Alice has recently received an array $$$a_1, a_2, \dots, a_n$$$ for her birthday! She is very proud of her array, and when she showed her friend Bob the array, he was very happy with her present too!However, soon Bob became curious, and as any sane friend would do, asked Alice to perform $$$q$$$ operations of two types on her array:  $$$1$$$ $$$x$$$ $$$y$$$: update the element $$$a_x$$$ to $$$y$$$ (set $$$a_x = y$$$).  $$$2$$$ $$$l$$$ $$$r$$$: calculate how many non-decreasing subarrays exist within the subarray $$$[a_l, a_{l+1}, \dots, a_r]$$$. More formally, count the number of pairs of integers $$$(p,q)$$$ such that $$$l \le p \le q \le r$$$ and $$$a_p \le a_{p+1} \le \dots \le a_{q-1} \le a_q$$$. Help Alice answer Bob's queries!

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the size of the array, and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of Alice's array. The next $$$q$$$ lines consist of three integers each. The first integer of the $$$i$$$-th line is $$$t_i$$$, the operation being performed on the $$$i$$$-th step ($$$t_i = 1$$$ or $$$t_i = 2$$$). If $$$t_i = 1$$$, the next two integers are $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le 10^9$$$), updating the element at position $$$x_i$$$ to $$$y_i$$$ (setting $$$a_{x_i} = y_i$$$). If $$$t_i = 2$$$, the next two integers are $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$), the two indices Bob asks Alice about for the $$$i$$$-th query. It's guaranteed that there is at least one operation of the second type.

For each query of type $$$2$$$, print a single integer, the answer to the query.

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

struct S { int afront, aback, alength; int prefix, suffix; long ans; }

S op(S x, S y)
{
  if (x.alength == 0)
    return y;
  if (y.alength == 0)
    return x;
  if (x.aback <= y.afront) {
    long ans = x.ans + y.ans;
    ans -= cast(long)x.suffix * (x.suffix + 1) / 2;
    ans -= cast(long)y.prefix * (y.prefix + 1) / 2;
    ans += cast(long)(y.prefix + x.suffix) * (y.prefix + x.suffix + 1) / 2;
    return S(x.afront, y.aback, x.alength + y.alength,
                        x.alength == x.prefix ? x.suffix + y.prefix : x.prefix,
                        y.alength == y.suffix ? x.suffix + y.prefix : y.suffix,
                        ans);
  } else {
    return S(x.afront, y.aback, x.alength + y.alength, x.prefix, y.suffix, x.ans + y.ans);
  }
}

S e()
{
  return S(0, 0, 0, 0, 0, 0);
}

S s_val(int val)
{
  return S(val, val, 1, 1, 1, 1);
}

void main()
{
  int n, q;
  readf!" %d %d "(n, q);
  auto a = readln.strip.split.map!(x => s_val(x.to!int)).array;
  auto seg = a.Segtree!(S, op, e);

  while (q--) {
    auto req = readln.strip.split.map!(to!int).array;
    if (req[0] == 1) {
      seg.set(req[1] - 1, s_val(req[2]));
    } else {
      int l = req[1], r = req[2];
      l--;
      writeln(seg.prod(l, r).ans);
    }
  }
}

// Code from: https://github.com/kotet/atcoder-library-d

int celiPow2(int n) @safe pure nothrow @nogc
{
    int x = 0;
    while ((1u << x) < cast(uint)(n))
        x++;
    return x;
}

// --- segtree ---

struct Segtree(S, alias op, alias e)
{
    import std.functional : binaryFun, unaryFun;
    import std.traits : isCallable, Parameters;

    static if (is(typeof(e) : string))
    {
        auto unit()
        {
            return mixin(e);
        }
    }
    else
    {
        alias unit = e;
    }

    this(int n)
    {
        auto buf = new S[](n);
        buf[] = unit();
        this(buf);
    }

    this(S[] v)
    {
        _n = cast(int) v.length;
        log = celiPow2(_n);
        size = 1 << log;
        d = new S[](2 * size);
        d[] = unit();
        foreach (i; 0 .. _n)
            d[size + i] = v[i];
        foreach_reverse (i; 1 .. size)
            update(i);
    }

    void set(int p, S x)
    {
        assert(0 <= p && p < _n);
        p += size;
        d[p] = x;
        foreach (i; 1 .. log + 1)
            update(p >> i);
    }

    S get(int p)
    {
        assert(0 <= p && p < _n);
        return d[p + size];
    }

    S prod(int l, int r)
    {
        assert(0 <= l && l <= r && r <= _n);
        S sml = unit(), smr = unit();
        l += size;
        r += size;
        while (l < r)
        {
            if (l & 1)
                sml = binaryFun!(op)(sml, d[l++]);
            if (r & 1)
                smr = binaryFun!(op)(d[--r], smr);
            l >>= 1;
            r >>= 1;
        }
        return binaryFun!(op)(sml, smr);
    }

    S allProd()
    {
        return d[1];
    }

    int maxRight(alias f)(int l)
    {
        return maxRight(l, &unaryFun!(f));
    }

    int maxRight(F)(int l, F f) if (isCallable!F && Parameters!(F).length == 1)
    {
        assert(0 <= l && l <= _n);
        assert(f(unit()));
        if (l == _n)
            return _n;
        l += size;
        S sm = unit();
        do
        {
            while (l % 2 == 0)
                l >>= 1;
            if (!f(binaryFun!(op)(sm, d[l])))
            {
                while (l < size)
                {
                    l = 2 * l;
                    if (f(binaryFun!(op)(sm, d[l])))
                    {
                        sm = binaryFun!(op)(sm, d[l]);
                        l++;
                    }
                }
                return l - size;
            }
            sm = binaryFun!(op)(sm, d[l]);
            l++;
        }
        while ((l & -l) != l);
        return _n;
    }

    int minLeft(alias f)(int r)
    {
        return minLeft(r, &unaryFun!(f));
    }

    int minLeft(F)(int r, F f) if (isCallable!F && Parameters!(F).length == 1)
    {
        assert(0 <= r && r <= _n);
        assert(f(unit()));
        if (r == 0)
            return 0;
        r += size;
        S sm = unit();
        do
        {
            r--;
            while (r > 1 && (r % 2))
                r >>= 1;
            if (!f(binaryFun!(op)(d[r], sm)))
            {
                while (r < size)
                {
                    r = 2 * r + 1;
                    if (f(binaryFun!(op)(d[r], sm)))
                    {
                        sm = binaryFun!(op)(d[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = binaryFun!(op)(d[r], sm);
        }
        while ((r & -r) != r);
        return 0;
    }

private:
    int _n = 0, size = 1, log = 0;
    S[] d = [unit(), unit()];
    void update(int k)
    {
        d[k] = binaryFun!(op)(d[2 * k], d[2 * k + 1]);
    }
}


A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?

The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time.  The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one.  The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.

Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.

NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.

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

int a, b, c;

void main() {

	int n;

	readf(" %s", &n);

	int k;
	foreach (i; 0 .. n) {
		readf(" %s", &k);
		a ^= k;
	}

	foreach (i; 0 .. n - 1) {
		readf(" %s", &k);
		b ^= k;
	}

	foreach (i; 0 .. n - 2) {
		readf(" %s", &k);
		c ^= k;
	}

	writeln(a ^ b, '\n', b ^ c);
}

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

long a, b, c;

void main() {

	int n;

	readf(" %s", &n);

	int k;
	foreach (i; 0 .. n) {
		scanf("%d", &k);
		a += k;
	}

	foreach (i; 0 .. n - 1) {
		scanf("%d", &k);
		b += k;
	}

	foreach (i; 0 .. n - 2) {
		scanf("%d", &k);
		c += k;
	}

	writeln(a - b, '\n', b - c);
}

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

int[] a, b, c;

void main() {

	int n;

	readf(" %s", &n);

	int k;
	foreach (i; 0 .. n) {
		scanf("%d", &k);
		a ~= k;
	}

	foreach (i; 0 .. n - 1) {
		scanf("%d", &k);
		b ~= k;
	}

	foreach (i; 0 .. n - 2) {
		scanf("%d", &k);
		c ~= k;
	}

	sort(a);
	sort(b);
	sort(c);

	bool flag = 1;
	foreach (i; 0 .. n - 1)
		if (a[i] != b[i]) {
			writeln(a[i]);
			flag = 0;
			break;
		}

	if (flag)
		writeln(a[n - 1]);

	flag = 1;
	foreach (i; 0 .. n - 2)
		if (b[i] != c[i]) {
			writeln(b[i]);
			flag = 0;
			break;
		}

	if (flag)
		writeln(b[n - 2]);
}

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

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int[int] ce1;
	foreach (int i; 0..n)
	{
		int error;
		scanf("%d", &error);
		ce1[error]++;
	}
	int[int] ce2;
	foreach (int i; 0..(n-1))
	{
		int error;
		scanf("%d", &error);
		ce2[error]++;
	}
	foreach (int key; ce1.byKey)
	{
		if (!(key in ce2) || ce1[key] != ce2[key])
		{
			printf("%d\n", key);
			break;
		}
	}
	int[int] ce3;
	foreach (int i; 0..(n-2))
	{
		int error;
		scanf("%d", &error);
		ce3[error]++;
	}

	foreach (int key; ce2.byKey)
	{
		if (!(key in ce3) || ce2[key] != ce3[key])
		{
			printf("%d", key);
			break;
		}
	}
	return 0;
}

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

void main()
{
	readln;
	auto f=()=>readln.split.map!(to!int).reduce!"a^b";
	auto x=f(),y=f(),z=f();
	writeln(x^y,'\n',y^z);
}

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

int a, b, c;

void main() {

	int n;

	readf(" %s", &n);

	int k;
	foreach (i; 0 .. n) {
		readf(" %s", &k);
		a ^= k;
	}

	foreach (i; 0 .. n) {
		readf(" %s", &k);
		b ^= k;
	}

	foreach (i; 0 .. n) {
		readf(" %s", &k);
		c ^= k;
	}

	writeln(a ^ b, '\n', b ^ c);
}

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

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int[int] ce;
	foreach (int i; 0..(3*n - 3))
	{
		int error;
		scanf("%d", &error);
		ce[error]++;
	}
	int ak;
	int bk;
	foreach (int key; ce.byKey)
	{
		if (ce[key] < 3)
		{
			ak = (ak == 0 && ce[key] == 1) ? key : ak;
			bk = (bk == 0 && ce[key] == 2) ? key : bk;
		}
	}
	printf("%d\n%d", ak, bk);
	return 0;
}

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

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int[int] ce;
	foreach (int i; 0..(3*n - 3))
	{
		int error;
		scanf("%d", &error);
		ce[error]++;
	}
	int ak;
	int bk;
	foreach (int key; ce.byKey)
	{
		if (ce[key] % 3 != 0)
		{
			ak = (ak == 0 && ce[key] % 3 == 1) ? key : ak;
			bk = (bk == 0 && ce[key] % 3 == 2) ? key : bk;
		}
	}
	printf("%d\n%d", ak, bk);
	return 0;
}


Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.

The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.

Print a single integer, the minimum amount of lost milk. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}
		long res = long.max;

		long cur1 = 0;
		long t1 = 0;
		foreach (i; 0..n)
		{
			if (a[i] == 1)
			{
				t1++;
			}
			else
			{
				cur1 += t1;
			}
		}

		long cur2 = 0;
		long t2 = 0;
		foreach_reverse (i; 0..n)
		{
			if (a[i] == 0)
			{
				t2++;
			}
			else
			{
				cur2 += t2;
			}
		}

		debug {writeln (cur1, ' ', cur2);}
		res = min (cur1, cur2);
		writeln (res);
	}
}


Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.

The first line contains three integers n, m, k (1 ≤ n, m ≤ 500, 0 ≤ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze. Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.

Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#"). It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.

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

immutable int INF = int.max / 4;
immutable int DIRS = 4;
immutable int [DIRS] DR = [-1,  0, +1,  0];
immutable int [DIRS] DC = [ 0, -1,  0, +1];

void main ()
{
	int n, m, k;
	while (readf (" %s %s %s ", &n, &m, &k) > 0)
	{
		char [] [] a;
		char [] t1;
		foreach (j; 0..m + 2)
		{
			t1 ~= '#';
		}
		a ~= t1;
		foreach (i; 0..n)
		{
			char [] t2 = cast (char []) readln.strip;
			a ~= ('#' ~ t2 ~ '#');
		}
		a ~= t1;

		alias Tuple !(int, "r", int, "c") coord;
		auto s = coord (-1, -1);
iloop:		foreach (i; 0..n + 2)
		{
			foreach (j; 0..m + 2)
			{
				if (a[i][j] == '.')
				{
					s = coord (i, j);
					break iloop;
				}
			}
		}
		enforce (s != coord (-1, -1));

		auto d = new int [] [] (n + 2, m + 2);
		foreach (ref e; d)
		{
			e[] = INF;
		}
		d[s.r][s.c] = 0;
		coord [] q;
		q.reserve ((n + 2) * (m + 2));
		coord [] r = q;
		q.assumeSafeAppend;
		q ~= s;
		int p = 0;
		while (p < q.length)
		{
			auto cur = q[p];
			p++;
			foreach (dir; 0..DIRS)
			{
				auto next = coord (cur.r + DR[dir],
				                   cur.c + DC[dir]);
				if (a[next.r][next.c] != '.')
				{
					continue;
				}
				if (d[next.r][next.c] == INF)
				{
					d[next.r][next.c] =
					    d[cur.r][cur.c] + 1;
					q.assumeSafeAppend;
					q ~= next;
				}
			}
		}

		q = q[$ - k..$];
		foreach (cur; q)
		{
			a[cur.r][cur.c] = 'X';
		}

		foreach (b; a[1..n + 1])
		{
			writeln (b[1..m + 1]);
		}
	}
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  long n, m, k;
  @Dim("n") string[] maze;

  void solve(long tc = -1)
  {
    char[][] mmaze = maze.map!(row => row.dup).array;
    enum long[2][] deltas = [[+1, 0],
                             [-1, 0],
                             [0, +1],
                             [0, -1]];
    const initialPosition = delegate long[2]() {
      foreach(i; 0 .. n)
        foreach(j; 0 .. m)
          if (maze.at(i).at(j) == '.')
            return [i, j];
      assert(0);
    } ();
    auto dist = makeSlice!long(n, m);
    auto visited = makeSlice!bool(n, m);
    long[2][][long] withdist;
    auto maxdist = long(0);
    DList!(long[2]) queue;
    queue.insertFront(initialPosition);
    dist.at(initialPosition[0]).at(initialPosition[1]) = 0;
    visited.at(initialPosition[0]).at(initialPosition[1]) = true;
    withdist.require(0, null);
    withdist.at(0) = [initialPosition];
    while(!queue.empty)
      {
        auto node = queue.front;
        queue.removeFront;
        foreach(delta; deltas)
          {
            long[2] neighbour;
            neighbour[] = node[] + delta[];
            if (neighbour[0] >= 0 && neighbour[0] < n
                && neighbour[1] >= 0 && neighbour[1] < m
                && maze.at(neighbour[0]).at(neighbour[1]) == '.'
                && !visited.at(neighbour[0]).at(neighbour[1]))
              {
                dist.at(neighbour[0]).at(neighbour[1]) = dist.at(node[0]).at(node[1]) + 1;
                require(withdist, dist.at(neighbour[0]).at(neighbour[1]), null);
                withdist.at(dist.at(neighbour[0]).at(neighbour[1])) ~= neighbour;
                visited.at(neighbour[0]).at(neighbour[1]) = true;
                maxdist = max(maxdist, dist.at(neighbour[0]).at(neighbour[1]));
                queue.insertBack(neighbour);
              }
          }
      }
    auto inserted = long(0);
    auto disttoinsert = maxdist;
    while(inserted < k)
      {
        if (withdist.at(disttoinsert).empty)
          {
            disttoinsert--;
          }
        auto toinsert = withdist.at(disttoinsert)[$ - 1];
        mmaze.at(toinsert[0]).at(toinsert[1]) = 'X';
        withdist.at(disttoinsert).length--;
        inserted++;
      }
    foreach(row; mmaze)
      {
        writeln(row);
      }
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}


William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet.

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$.

Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions.

NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people.

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

void main()
{
  int n, d, saved = 0;
  readf(" %d %d ", &n, &d);

  auto uf = Dsu(n);

  while (d--) {
    int u, v;
    readf(" %d %d ", &u, &v);
    u--;
    v--;
    if (!uf.same(u, v)) {
      uf.merge(u, v);
    } else {
      saved++;
    }
    writeln(uf.groups.map!(x => x.length).array.sort!"a>b".take(saved + 1).sum - 1);
  }
}

// Code from: https://github.com/kotet/atcoder-library-d

struct Dsu
{
public:
    this(long n) @safe nothrow
    {
        _n = cast(int) n, parent_or_size = new int[](cast(int)n);
        parent_or_size[] = -1;
    }

    int merge(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        int x = leader(a), y = leader(b);
        if (x == y)
            return x;
        if (-parent_or_size[x] < -parent_or_size[y])
        {
            auto tmp = x;
            x = y;
            y = tmp;
        }
        parent_or_size[x] += parent_or_size[y];
        parent_or_size[y] = x;
        return x;
    }

    bool same(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        return leader(a) == leader(b);
    }

    int leader(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        if (parent_or_size[cast(int)a] < 0)
            return cast(int) a;
        return parent_or_size[cast(int)a] = leader(parent_or_size[cast(int)a]);
    }

    int size(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        return -parent_or_size[leader(a)];
    }

    int[][] groups() @safe nothrow
    {
        auto leader_buf = new int[](_n), group_size = new int[](_n);
        foreach (i; 0 .. _n)
        {
            leader_buf[i] = leader(i);
            group_size[leader_buf[i]]++;
        }
        auto result = new int[][](_n);
        foreach (i; 0 .. _n)
            result[i].reserve(group_size[i]);
        foreach (i; 0 .. _n)
            result[leader_buf[i]] ~= i;
        int[][] filtered;
        foreach (r; result)
            if (r.length != 0)
                filtered ~= r;
        return filtered;
    }

private:
    int _n;
    int[] parent_or_size;
}

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

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

    auto largest = redBlackTree!("a > b", true, int)();
    auto remaining = redBlackTree!("a > b", true, int)();

    Dsu uf;
    uf = Dsu(n);

    long ans;
    long saved;
    while (d--) {
      int u, v;
      readf(" %d %d ", &u, &v);
      u--;
      v--;
      if (!uf.same(u, v)) {
        if (largest.removeKey(uf.size(u)) == 0)
          remaining.removeKey(uf.size(u));
        else
          ans -= uf.size(u);
        if (largest.removeKey(uf.size(v)) == 0)
          remaining.removeKey(uf.size(v));
        else
          ans -= uf.size(v);
        uf.merge(u, v);
        remaining.insert(uf.size(v));
      } else {
        saved++;
      }
      while (largest.length > 0 && remaining.length > 0 && largest.back < remaining.front) {
        auto tmp = largest.back;
        largest.removeBack;
        ans -= tmp;
        remaining.insert(tmp);
      }
      while (largest.length < saved + 1 && remaining.length > 0) {
        auto tmp = remaining.front;
        remaining.removeFront;
        largest.insert(tmp);
        ans += tmp;
      }
      writeln(ans - 1 + saved - (largest.length - 1));
    }
}

// Code from: https://github.com/kotet/atcoder-library-d

struct Dsu
{
public:
    this(long n) @safe nothrow
    {
        _n = cast(int) n, parent_or_size = new int[](cast(int)n);
        parent_or_size[] = -1;
    }

    int merge(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        int x = leader(a), y = leader(b);
        if (x == y)
            return x;
        if (-parent_or_size[x] < -parent_or_size[y])
        {
            auto tmp = x;
            x = y;
            y = tmp;
        }
        parent_or_size[x] += parent_or_size[y];
        parent_or_size[y] = x;
        return x;
    }

    bool same(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        return leader(a) == leader(b);
    }

    int leader(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        if (parent_or_size[cast(int)a] < 0)
            return cast(int) a;
        return parent_or_size[cast(int)a] = leader(parent_or_size[cast(int)a]);
    }

    int size(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        return -parent_or_size[leader(a)];
    }

    int[][] groups() @safe nothrow
    {
        auto leader_buf = new int[](_n), group_size = new int[](_n);
        foreach (i; 0 .. _n)
        {
            leader_buf[i] = leader(i);
            group_size[leader_buf[i]]++;
        }
        auto result = new int[][](_n);
        foreach (i; 0 .. _n)
            result[i].reserve(group_size[i]);
        foreach (i; 0 .. _n)
            result[leader_buf[i]] ~= i;
        int[][] filtered;
        foreach (r; result)
            if (r.length != 0)
                filtered ~= r;
        return filtered;
    }

private:
    int _n;
    int[] parent_or_size;
}

immutable multi = false;

void solve(int tc)
{
  auto n = readInt!int;
  auto d = readInt!int;
  auto parent = iota(n).array;
  auto size = ma(n, 1);
  int getParent(int i)
  {
    if (parent[i] == i) return i;
    return parent[i] = getParent(parent[i]);
  }
  bool unite(int i, int j)
  {
    i = getParent(i);
    j = getParent(j);
    if (i == j) return false;
    if (size[i] > size[j]) swap(i, j);
    parent[i] = j;
    size[j] += size[i];
    return true;
  }
  int redundant = 0;
  foreach(i; 0 .. d)
    {
      redundant += int(!unite(readInt!int - 1, readInt!int - 1));
      (iota(n).filter!(j => parent[j] == j)
       .map!(j => size[j])
       .array
       .sort!((a, b) => a > b)
       .take(redundant + 1)
       .sum - 1).writeln;
    }
}

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

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

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

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

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

immutable multi = false;

void solve(int tc)
{
  auto n = readInt!int;
  auto d = readInt!int;
  auto parent = iota(n).array;
  auto size = ma(n, 1);
  foreach(i; 0 .. n) { parent[i] = i; size[i] = 1; }
  int getParent(int i)
  {
    if (parent[i] == i) return i;
    return parent[i] = getParent(parent[i]);
  }
  bool unite(int i, int j)
  {
    i = getParent(i);
    j = getParent(j);
    if (i == j) return false;
    if (size[i] > size[j]) swap(i, j);
    parent[i] = j;
    size[j] += size[i];
    return true;
  }
  int redundant = 0;
  foreach(i; 0 .. d)
    {
      redundant += int(!unite(readInt!int - 1, readInt!int - 1));
      (iota(n).filter!(j => parent[j] == j)
       .map!(j => size[j])
       .array
       .sort!((a, b) => a > b)
       .take(redundant + 1)
       .sum - 1).writeln;
    }
}

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

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

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

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

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

immutable multi = false;

void solve(int tc)
{
  auto n = readInt!int;
  auto d = readInt!int;
  auto parent = new int[](n);
  auto size = new int[](n);
  foreach(i; 0 .. n) { parent[i] = i; size[i] = 1; }
  int getParent(int i)
  {
    if (parent[i] == i) return i;
    return parent[i] = getParent(parent[i]);
  }
  bool unite(int i, int j)
  {
    i = getParent(i);
    j = getParent(j);
    if (i == j) return false;
    if (size[i] > size[j]) swap(i, j);
    parent[i] = j;
    size[j] += size[i];
    return true;
  }
  int redundant = 0;
  foreach(i; 0 .. d)
    {
      redundant += int(!unite(readInt!int - 1, readInt!int - 1));
      (iota(n).filter!(j => parent[j] == j)
       .map!(j => size[j])
       .array
       .sort!((a, b) => a > b)
       .take(redundant + 1)
       .sum - 1).writeln;
    }
}

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

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

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

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

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

immutable multi = false;

void solve(int tc)
{
  auto n = readInt!int;
  auto d = readInt!int;
  auto parent = new int[](n);
  auto size = new int[](n);
  foreach(i; 0 .. n) { parent[i] = i; size[i] = 1; }
  int getParent(int i)
  {
    if (parent[i] == i) return i;
    return parent[i] = getParent(parent[i]);
  }
  bool unite(int i, int j)
  {
    i = getParent(i);
    j = getParent(j);
    if (i == j) return false;
    if (size[i] > size[j]) swap(i, j);
    parent[i] = j;
    size[j] += size[i];
    return true;
  }
  int redundant = 0;
  foreach(i; 0 .. d)
    {
      auto x = readInt!int - 1;
      auto y = readInt!int - 1;
      auto newE = unite(x, y);
      redundant += int(!newE);
      int[] sizes;
      foreach(j; 0 .. n)
	{
	  if (parent[j] == j)
	    sizes ~= size[j];
	}
      sort(sizes);
      int ans = 0;
      foreach(k; 0 .. redundant + 1)
	{
	  ans += sizes[$ - 1 - k];
	}
      (ans-1).writeln;
    }
}

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

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

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

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

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

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

void main ()
{
	int n, d;
	while (readf !(" %s %s") (n, d) > 0)
	{
		auto p = n.iota.array;
		auto s = 1.repeat (n).array;

		int root (int v)
		{
			if (p[v] != v)
			{
				p[v] = root (p[v]);
			}
			return p[v];
		}

		bool unite (int u, int v)
		{
			u = root (u);
			v = root (v);
			if (u == v)
			{
				return false;
			}
			if (s[u] > s[v])
			{
				swap (u, v);
			}
			p[u] = v;
			s[v] += s[u];
			return true;
		}

		int add = 0;
		foreach (j; 0..d)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			auto cur = unite (u, v);
			add += !cur;

			auto t = n.iota.filter !(v => p[v] == v)
			    .map !(v => s[v]).array;
			sort (t);
			foreach (k; 0..add)
			{
				t[$ - 2] += t.back;
				t.popBack ();
			}
			writeln (t.back - 1);
		}
	}
}

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

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

    auto largest = redBlackTree!("a > b", true, int)();
    auto remaining = redBlackTree!("a > b", true, int)();

    Dsu uf;
    uf = Dsu(n);

    long ans;
    long saved;
    long req = 0;
    while (d--) {
      req++;
      int u, v;
      readf(" %d %d ", &u, &v);
      u--;
      v--;
      if (!uf.same(u, v)) {
        if (largest.removeKey(uf.size(u)) == 0)
          remaining.removeKey(uf.size(u));
        else
          ans -= uf.size(u);
        if (largest.removeKey(uf.size(v)) == 0)
          remaining.removeKey(uf.size(v));
        else
          ans -= uf.size(v);
        uf.merge(u, v);
        remaining.insert(uf.size(v));
      } else {
        saved++;
      }
      while (largest.length < saved + 1 && remaining.length > 0) {
        auto tmp = remaining.front;
        remaining.removeFront;
        largest.insert(tmp);
        ans += tmp;
      }
      writeln(min(req, ans + (saved + 1 - largest.length) - 1));
    }
}

// Code from: https://github.com/kotet/atcoder-library-d

struct Dsu
{
public:
    this(long n) @safe nothrow
    {
        _n = cast(int) n, parent_or_size = new int[](cast(int)n);
        parent_or_size[] = -1;
    }

    int merge(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        int x = leader(a), y = leader(b);
        if (x == y)
            return x;
        if (-parent_or_size[x] < -parent_or_size[y])
        {
            auto tmp = x;
            x = y;
            y = tmp;
        }
        parent_or_size[x] += parent_or_size[y];
        parent_or_size[y] = x;
        return x;
    }

    bool same(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        return leader(a) == leader(b);
    }

    int leader(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        if (parent_or_size[cast(int)a] < 0)
            return cast(int) a;
        return parent_or_size[cast(int)a] = leader(parent_or_size[cast(int)a]);
    }

    int size(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        return -parent_or_size[leader(a)];
    }

    int[][] groups() @safe nothrow
    {
        auto leader_buf = new int[](_n), group_size = new int[](_n);
        foreach (i; 0 .. _n)
        {
            leader_buf[i] = leader(i);
            group_size[leader_buf[i]]++;
        }
        auto result = new int[][](_n);
        foreach (i; 0 .. _n)
            result[i].reserve(group_size[i]);
        foreach (i; 0 .. _n)
            result[leader_buf[i]] ~= i;
        int[][] filtered;
        foreach (r; result)
            if (r.length != 0)
                filtered ~= r;
        return filtered;
    }

private:
    int _n;
    int[] parent_or_size;
}

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

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

    auto largest = redBlackTree!("a > b", true, int)();
    auto remaining = redBlackTree!("a > b", true, int)();

    Dsu uf;
    uf = Dsu(n);

    long ans;
    long saved;
    while (d--) {
      int u, v;
      readf(" %d %d ", &u, &v);
      u--;
      v--;
      if (!uf.same(u, v)) {
        if (largest.removeKey(uf.size(u)) == 0)
          remaining.removeKey(uf.size(u));
        else
          ans -= uf.size(u);
        if (largest.removeKey(uf.size(v)) == 0)
          remaining.removeKey(uf.size(v));
        else
          ans -= uf.size(v);
        uf.merge(u, v);
        remaining.insert(uf.size(v));
      } else {
        saved++;
      }
      while (largest.length < saved + 1 && remaining.length > 0) {
        auto tmp = remaining.front;
        remaining.removeFront;
        largest.insert(tmp);
        ans += tmp;
      }
      writeln(min(n - 1, ans + (saved + 1 - largest.length) - 1));
    }
}

// Code from: https://github.com/kotet/atcoder-library-d

struct Dsu
{
public:
    this(long n) @safe nothrow
    {
        _n = cast(int) n, parent_or_size = new int[](cast(int)n);
        parent_or_size[] = -1;
    }

    int merge(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        int x = leader(a), y = leader(b);
        if (x == y)
            return x;
        if (-parent_or_size[x] < -parent_or_size[y])
        {
            auto tmp = x;
            x = y;
            y = tmp;
        }
        parent_or_size[x] += parent_or_size[y];
        parent_or_size[y] = x;
        return x;
    }

    bool same(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        return leader(a) == leader(b);
    }

    int leader(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        if (parent_or_size[cast(int)a] < 0)
            return cast(int) a;
        return parent_or_size[cast(int)a] = leader(parent_or_size[cast(int)a]);
    }

    int size(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        return -parent_or_size[leader(a)];
    }

    int[][] groups() @safe nothrow
    {
        auto leader_buf = new int[](_n), group_size = new int[](_n);
        foreach (i; 0 .. _n)
        {
            leader_buf[i] = leader(i);
            group_size[leader_buf[i]]++;
        }
        auto result = new int[][](_n);
        foreach (i; 0 .. _n)
            result[i].reserve(group_size[i]);
        foreach (i; 0 .. _n)
            result[leader_buf[i]] ~= i;
        int[][] filtered;
        foreach (r; result)
            if (r.length != 0)
                filtered ~= r;
        return filtered;
    }

private:
    int _n;
    int[] parent_or_size;
}

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

struct edge { int u, v; };

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

    auto largest = redBlackTree!("a > b", true, int)();
    auto remaining = redBlackTree!("a > b", true, int)();

    int[][] adj = new int[][](n, 0);
    Dsu uf;
    uf = Dsu(n);

    long ans;
    long saved;
    while (d--) {
      int u, v;
      readf(" %d %d ", &u, &v);
      u--;
      v--;
      if (!uf.same(u, v)) {
        if (largest.removeKey(uf.size(u)) == 0)
          remaining.removeKey(uf.size(u));
        else
          ans -= uf.size(u);
        if (largest.removeKey(uf.size(v)) == 0)
          remaining.removeKey(uf.size(v));
        else
          ans -= uf.size(v);
        uf.merge(u, v);
        adj[u] ~= v;
        adj[v] ~= u;
        remaining.insert(uf.size(v));
      } else {
        saved++;
      }
      while (largest.length < saved + 1 && remaining.length > 0) {
        auto tmp = remaining.front;
        remaining.removeFront;
        largest.insert(tmp);
        ans += tmp;
      }
      writeln(ans - 1 + saved - (largest.length - 1));
    }
}

// Code from: https://github.com/kotet/atcoder-library-d

struct Dsu
{
public:
    this(long n) @safe nothrow
    {
        _n = cast(int) n, parent_or_size = new int[](cast(int)n);
        parent_or_size[] = -1;
    }

    int merge(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        int x = leader(a), y = leader(b);
        if (x == y)
            return x;
        if (-parent_or_size[x] < -parent_or_size[y])
        {
            auto tmp = x;
            x = y;
            y = tmp;
        }
        parent_or_size[x] += parent_or_size[y];
        parent_or_size[y] = x;
        return x;
    }

    bool same(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        return leader(a) == leader(b);
    }

    int leader(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        if (parent_or_size[cast(int)a] < 0)
            return cast(int) a;
        return parent_or_size[cast(int)a] = leader(parent_or_size[cast(int)a]);
    }

    int size(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        return -parent_or_size[leader(a)];
    }

    int[][] groups() @safe nothrow
    {
        auto leader_buf = new int[](_n), group_size = new int[](_n);
        foreach (i; 0 .. _n)
        {
            leader_buf[i] = leader(i);
            group_size[leader_buf[i]]++;
        }
        auto result = new int[][](_n);
        foreach (i; 0 .. _n)
            result[i].reserve(group_size[i]);
        foreach (i; 0 .. _n)
            result[leader_buf[i]] ~= i;
        int[][] filtered;
        foreach (r; result)
            if (r.length != 0)
                filtered ~= r;
        return filtered;
    }

private:
    int _n;
    int[] parent_or_size;
}


Andrew has $$$n$$$ piles with stones. The $$$i$$$-th pile contains $$$a_i$$$ stones. He wants to make his table clean so he decided to put every stone either to the $$$1$$$-st or the $$$n$$$-th pile.Andrew can perform the following operation any number of times: choose $$$3$$$ indices $$$1 \le i < j < k \le n$$$, such that the $$$j$$$-th pile contains at least $$$2$$$ stones, then he takes $$$2$$$ stones from the pile $$$j$$$ and puts one stone into pile $$$i$$$ and one stone into pile $$$k$$$. Tell Andrew what is the minimum number of operations needed to move all the stones to piles $$$1$$$ and $$$n$$$, or determine if it's impossible.

The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 10^5$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the minimum number of operations needed to move stones to piles $$$1$$$ and $$$n$$$, or print $$$-1$$$ if it's impossible.

NoteIn the first test case, it is optimal to do the following:   Select $$$(i, j, k) = (1, 2, 5)$$$. The array becomes equal to $$$[2, 0, 2, 3, 7]$$$.  Select $$$(i, j, k) = (1, 3, 4)$$$. The array becomes equal to $$$[3, 0, 0, 4, 7]$$$.  Twice select $$$(i, j, k) = (1, 4, 5)$$$. The array becomes equal to $$$[5, 0, 0, 0, 9]$$$. This array satisfy the statement, because every stone is moved to piles $$$1$$$ and $$$5$$$.  There are $$$4$$$ operations in total.In the second test case, it's impossible to put all stones into piles with numbers $$$1$$$ and $$$3$$$:   At the beginning there's only one possible operation with $$$(i, j, k) = (1, 2, 3)$$$. The array becomes equal to $$$[2, 1, 2]$$$.  Now there is no possible operation and the array doesn't satisfy the statement, so the answer is $$$-1$$$. In the third test case, it's optimal to do the following:   Select $$$(i, j, k) = (1, 2, 3)$$$. The array becomes equal to $$$[2, 0, 2]$$$. This array satisfies the statement, because every stone is moved to piles $$$1$$$ and $$$3$$$.  The is $$$1$$$ operation in total.In the fourth test case, it's impossible to do any operation, and the array doesn't satisfy the statement, so the answer is $$$-1$$$.

// cheese-cracker [2022-02-12]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    long summ = 0;
    bool f = 0;
    for(int i = 1; i < n-1; ++i){
        if(arr[i] >= 2){
            f = 1;
        }
        summ += arr[i]/2 + (arr[i] % 2 != 0);
    }
    if(f && !(n == 3 && arr[1] % 2 != 0) ){
        writeln(summ);
    }else{
        writeln(-1);
    }
}

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

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		bool ok;
		foreach (i; 1..n-1)
		{
			if (a[i] >= 2)
				ok = true;
		}
		if (n == 3 && a[1] % 2)
			ok = false;
		if (!ok)
			ans[ti] = -1;
		else
		{
			foreach (i; 1..n-1)
				ans[ti] += (a[i]+1) / 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;

long solve (int [] a, int n)
{
	if (a[1..$ - 1].all !(q{a == 0}))
	{
		return 0;
	}
	if (a[1..$ - 1].all !(q{a <= 1}))
	{
		return -1;
	}
	if (n == 3 && a[1] % 2 == 1)
	{
		return -1;
	}
	long res = 0;
	foreach (i; 1..n - 1)
	{
		res += a[i] / 2 + (a[i] & 1);
	}
	return res;
}

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

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;
        auto A = new long[N];
        foreach (i; 0 .. N) {
          A[i] = readLong;
        }

        bool good;
        if (N == 3) {
          good = (A[1] % 2 == 0);
        } else {
          foreach (i; 1 .. N - 1) {
            good = good || (A[i] >= 2);
          }
        }

        long ans;
        if (good) {
          foreach (i; 1 .. N - 1) {
            ans += (A[i] + 1) / 2;
          }
        } else {
          ans = -1;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

// cheese-cracker [2022-02-12]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    long summ = 0;
    bool f = 0;
    for(int i = 1; i < n-1; ++i){
        if(arr[i] >= 2){
            f = 1;
        }
        summ += arr[i];
    }
    if(f && !(n == 3 && arr[1] % 2 != 0) ){
        writeln(summ/2 + (summ % 2 != 0));
    }else{
        writeln(-1);
    }
}

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

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

// cheese-cracker [2022-02-12]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    long summ = 0;
    bool f = 0;
    for(int i = 1; i < n-1; ++i){
        if(arr[i] % 2 == 0){
            f = 1;
        }
        summ += arr[i];
    }
    if(f){
        writeln(summ/2 + (summ % 2 != 0));
    }else{
        writeln(-1);
    }
}

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

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

// cheese-cracker [2022-02-12]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    long[] opp, ops;
    long oper = 0;
    opp ~= 0;
    for(int i = 1; i < n-1; ++i){
        opp ~= oper;
        oper += arr[i] / 2;
    }
    ops ~= 0;
    oper = 0;
    for(int i = n-2; i > 0; --i){
        ops ~= oper;
        oper += arr[i] / 2;
    }
    ops ~= 0;
    ops.reverse;
    show(ops, opp);
    long ocnt = 0;
    for(int i = 1; i < n-1; ++i){
        ocnt = (arr[i] % 2 != 0);
        if(opp[i] + ops[i] >= ocnt){
            oper += ocnt;
        }else{
            writeln(-1);
            return;
        }
    }
    writeln(oper);
}

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

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

// cheese-cracker [2022-02-12]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    long[] opp, ops;
    long oper = 0;
    opp ~= 0;
    for(int i = 1; i < n-1; ++i){
        opp ~= oper;
        oper += arr[i] / 2;
    }
    ops ~= 0;
    oper = 0;
    for(int i = n-2; i > 0; --i){
        ops ~= oper;
        oper += arr[i] / 2;
    }
    long ocnt = 0;
    for(int i = 1; i < n-1; ++i){
        ocnt = (arr[i] % 2 != 0);
        if(opp[i] + ops[i] >= ocnt){
            oper += ocnt;
        }else{
            writeln(-1);
            return;
        }
    }
    writeln(oper);
}

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

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		bool ok;
		foreach (i; 1..n-1)
		{
			if (a[i] % 2 == 0)
				ok = true;
		}
		if (!ok)
			ans[ti] = -1;
		else
		{
			foreach (i; 1..n-1)
				ans[ti] += (a[i]+1) / 2;
		}
	}

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


Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper n points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess.

The first input line contains two integer numbers: n — amount of the drawn points and m — amount of the drawn segments (1 ≤ n ≤ 104, 0 ≤ m ≤ 104). The following m lines contain the descriptions of the segments. Each description contains two different space-separated integer numbers v, u (1 ≤ v ≤ n, 1 ≤ u ≤ n) — indexes of the points, joined by this segment. No segment is met in the description twice.

In the first line output number k — amount of the segments in the answer. In the second line output k space-separated numbers — indexes of these segments in ascending order. Each index should be output only once. Segments are numbered from 1 in the input order.

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

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

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

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

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

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

int[][] G;

int zeit;
int[] dis, low, parE, dep;
int[][] backEdges;
int[] cntTotal;
int[][] cnt;

void dfs(int u, int ip, int d) {
debug{
writeln("dfs ",u," ",ip," ",d);
}
	dis[u] = low[u] = zeit++;
	parE[u] = ip;
	dep[u] = d;
	foreach (i; G[u]) if (i != ip) {
		const v = A[i] ^ B[i] ^ u;
		if (dis[v] == -1) {
			dfs(v, i, d + 1);
			chmin(low[u], low[v]);
		} else if (dep[u] > dep[v]) {
debug{
writeln("  back edge ",u," ",v);
}
			//	back edge uv
			//	0: bad 1: good
			const s = (dep[u] - dep[v]) % 2;
			backEdges[s] ~= i;
			++cntTotal[s];
			++cnt[u][s];
			--cnt[v][s];
			chmin(low[u], dis[v]);
		}
	}
}

int[] ans;

void solve(int u) {
	foreach (i; G[u]) if (i != parE[u]) {
		const v = A[i] ^ B[i] ^ u;
		if (i == parE[v]) {
			solve(v);
			cnt[u][] += cnt[v][];
		}
	}
	if (parE[u] != -1) {
		//	try removing parE[u]
		if (cntTotal[0] - cnt[u][0] == 0 && (cnt[u][0] == 0 || cnt[u][1] == 0)) {
			ans ~= parE[u];
		}
	}
}

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

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

		zeit = 0;
		dis = new int[N];
		low = new int[N];
		parE = new int[N];
		dep = new int[N];
		backEdges = new int[][2];
		cntTotal = new int[2];
		cnt = new int[][](N, 2);
		dis[] = -1;
		foreach (u; 0 .. N) {
			if (dis[u] == -1) {
				dfs(u, -1, 0);
			}
		}
debug{
writeln("dis = ",dis);
writeln("low = ",low);
writeln("parE = ",parE);
writeln("dep = ",dep);
writeln("backEdges = ",backEdges);
writeln("cntTotal = ",cntTotal);
writeln("cnt = ",cnt);
}

		ans.clear;

		//	removing a tree edge
		foreach (u; 0 .. N) {
			if (parE[u] == -1) {
				solve(u);
			}
		}
debug{
writeln("cnt (summed) = ",cnt);
}

		//	removing a back edge
		if (cntTotal[0] == 0) {
			ans ~= backEdges[0];
			ans ~= backEdges[1];
		} if (cntTotal[0] == 1) {
			ans ~= backEdges[0];
		}

		ans.sort();
		writeln(ans.length);
		foreach (idx, i; ans) {
			if (idx > 0) {
				write(" ");
			}
			write(i + 1);
		}
		writeln;
	}
	} catch (EOFException) {}
}


During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters.The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: $$$1$$$, $$$2$$$, $$$3$$$, so that each character is painted in at most one color, and the description of the $$$i$$$-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color $$$i$$$.The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace.

The first line of the input contains two integers $$$n, q$$$ ($$$1 \leq n \leq 100\,000$$$, $$$1 \leq q \leq 1000$$$) — the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe — a string of length $$$n$$$ consisting of lowercase English characters. Each of the following line describes a single evolution and is in one of the following formats:    + $$$i$$$ $$$c$$$ ($$$i \in \{1, 2, 3\}$$$, $$$c \in \{\mathtt{a}, \mathtt{b}, \dots, \mathtt{z}\}$$$: append the character $$$c$$$ to the end of $$$i$$$-th religion description.  - $$$i$$$ ($$$i \in \{1, 2, 3\}$$$) – remove the last character from the $$$i$$$-th religion description. You can assume that the pattern is non-empty.  You can assume that no religion will have description longer than $$$250$$$ characters.

Write $$$q$$$ lines. The $$$i$$$-th of them should be YES if the religions could coexist in peace after the $$$i$$$-th evolution, or NO otherwise. You can print each character in any case (either upper or lower).

NoteIn the first example, after the 6th evolution the religion descriptions are: ad, bc, and ab. The following figure shows how these descriptions form three disjoint subsequences of the Word of Universe:

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

immutable int limit   = 251;
immutable int letters =  26;

void main ()
{
	int n;
	int q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		readln;
		auto s = readln.strip;

		auto next = new int [letters] [n + 2];
		auto cur = new int [letters];
		cur[] = n + 1;
		next[n][] = cur[];
		next[n + 1][] = cur[];
		foreach_reverse (i, c; s)
		{
			cur[c - 'a'] = to !(int) (i + 1);
			next[i][] = cur[];
		}
		debug {writefln ("%(%(%2s %)\n%)", next);}

		auto f = new int [limit] [] [] (limit, limit);
		f[0][0][0] = 0;
		auto a = new int [limit];
		auto b = new int [limit];
		auto c = new int [limit];

		pragma (inline, true)
		void calculate (int i, int j, int k)
		{
			auto v = n + 1;
			if (i > 0)
			{
				v = min (v, next[f[i - 1][j][k]][a[i - 1]]);
			}
			if (j > 0)
			{
				v = min (v, next[f[i][j - 1][k]][b[j - 1]]);
			}
			if (k > 0)
			{
				v = min (v, next[f[i][j][k - 1]][c[k - 1]]);
			}
			debug {writefln ("%s %s %s: %s", i, j, k, v);}
			f[i][j][k] = v;
		}

		int [3] pos = [0, 0, 0];
		foreach (r; 0..q)
		{
			auto command = readln.split;
			auto num = command[1].to !(int) - 1;
			if (command[0] == "+")
			{
				pos[num] += 1;
				auto let = command[2][0] - 'a';
				if (num == 0)
				{
					a[pos[0] - 1] = let;
					int i = pos[0];
					foreach (j; 0..pos[1] + 1)
					{
						foreach (k; 0..pos[2] + 1)
						{
							calculate (i, j, k);
						}
					}
				}
				else if (num == 1)
				{
					b[pos[1] - 1] = let;
					int j = pos[1];
					foreach (i; 0..pos[0] + 1)
					{
						foreach (k; 0..pos[2] + 1)
						{
							calculate (i, j, k);
						}
					}
				}
				else if (num == 2)
				{
					c[pos[2] - 1] = let;
					int k = pos[2];
					foreach (i; 0..pos[0] + 1)
					{
						foreach (j; 0..pos[1] + 1)
						{
							calculate (i, j, k);
						}
					}
				}
				else
				{
					assert (false);
				}
			}
			else if (command[0] == "-")
			{
				pos[num] -= 1;
			}
			else
			{
				assert (false);
			}
			writeln (f[pos[0]][pos[1]][pos[2]] <= n ? "YES" : "NO");
		}
	}
}


Tomorrow is a difficult day for Polycarp: he has to attend $$$a$$$ lectures and $$$b$$$ practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and draw everything he has to during all of the practical classes. Polycarp writes lectures using a pen (he can't use a pencil to write lectures!); he can write down $$$c$$$ lectures using one pen, and after that it runs out of ink. During practical classes Polycarp draws blueprints with a pencil (he can't use a pen to draw blueprints!); one pencil is enough to draw all blueprints during $$$d$$$ practical classes, after which it is unusable.Polycarp's pencilcase can hold no more than $$$k$$$ writing implements, so if Polycarp wants to take $$$x$$$ pens and $$$y$$$ pencils, they will fit in the pencilcase if and only if $$$x + y \le k$$$.Now Polycarp wants to know how many pens and pencils should he take. Help him to determine it, or tell that his pencilcase doesn't have enough room for all the implements he needs tomorrow!Note that you don't have to minimize the number of writing implements (though their total number must not exceed $$$k$$$).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then the test cases follow. Each test case is described by one line containing five integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ and $$$k$$$, separated by spaces ($$$1 \le a, b, c, d, k \le 100$$$) — the number of lectures Polycarp has to attend, the number of practical classes Polycarp has to attend, the number of lectures which can be written down using one pen, the number of practical classes for which one pencil is enough, and the number of writing implements that can fit into Polycarp's pencilcase, respectively. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.

For each test case, print the answer as follows: If the pencilcase can't hold enough writing implements to use them during all lectures and practical classes, print one integer $$$-1$$$. Otherwise, print two non-negative integers $$$x$$$ and $$$y$$$ — the number of pens and pencils Polycarp should put in his pencilcase. If there are multiple answers, print any of them. Note that you don't have to minimize the number of writing implements (though their total number must not exceed $$$k$$$).

NoteThere are many different answers for the first test case; $$$x = 7$$$, $$$y = 1$$$ is only one of them. For example, $$$x = 3$$$, $$$y = 1$$$ is also correct.$$$x = 1$$$, $$$y = 3$$$ is the only correct answer for the third test case.

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      {
	static foreach(n; 0 .. T[i].Types.length)
	  {
	    read(args[i][n]);
	  }
      }
    else
      readf!" %s "(args[i]);
}
auto brange(alias low, alias high, alias pred, bool value)()
{
  return iota(low, high + 1).map!((a) => cast(int) pred(a)).assumeSorted.equalRange(value);
}
auto ftrue(alias low, alias high, alias pred)()
{
  return brange!(low, high, pred, false).length + low;
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t;
      get(t);
      F(t);
    }
}
alias get = read;
alias w = writeln;
alias ln = long;
ln pmod(ln a, ln m)
{
  return ((a%m+m)%m);
}

int main()
{
  ln t; get(t);
  while(t--)
    {
      ln a, b, c, d, k; get(a, b, c, d, k);
      ln rp = (a + pmod(-a, c)) / c;
      ln rpc = (b + pmod(-b, d)) / d;
      if (rp + rpc <= k)
	{
	  w(rp, " ", rpc);
	}
      else
	{
	  w(-1);
	}
    }
  return 0;
}

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		int b=0;
		int c=0;
		int d=0;
		int e=0;
		readf(" %d", &a);
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		readf(" %d", &e);
		bool flag = false;
		for (int j=0; j<e+1; j++)
		{
			if (j*c>=a && (e-j)*d>=b)
			{
				writeln(j," ", (e-j));
				flag=true;
				break;
			}
		}
		if (flag==false)
		{
			writeln(-1);
		}
	}
	return 0;
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[2][](t);
	foreach (i; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto c = RD;
		auto d = RD;
		auto k = RD;
		auto x = (a+c-1)/c;
		auto y = (b+d-1)/d;
		if (x+y <= k)
			ans[i] = [x, y];
		else
			ans[i] = [-1, -1];
	}

	foreach (e; ans)
	{
		if (e[0] == -1)
			writeln(-1);
		else
			writeln(e[0], " ", e[1]);
	}
	stdout.flush();
	debug readln();
}