Prefix function of string $$$t = t_1 t_2 \ldots t_n$$$ and position $$$i$$$ in it is defined as the length $$$k$$$ of the longest proper (not equal to the whole substring) prefix of substring $$$t_1 t_2 \ldots t_i$$$ which is also a suffix of the same substring.For example, for string $$$t = $$$ abacaba the values of the prefix function in positions $$$1, 2, \ldots, 7$$$ are equal to $$$[0, 0, 1, 0, 1, 2, 3]$$$.Let $$$f(t)$$$ be equal to the maximum value of the prefix function of string $$$t$$$ over all its positions. For example, $$$f($$$abacaba$$$) = 3$$$.You are given a string $$$s$$$. Reorder its characters arbitrarily to get a string $$$t$$$ (the number of occurrences of any character in strings $$$s$$$ and $$$t$$$ must be equal). The value of $$$f(t)$$$ must be minimized. Out of all options to minimize $$$f(t)$$$, choose the one where string $$$t$$$ is the lexicographically smallest.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The only line of each test case contains string $$$s$$$ ($$$1 \le |s| \le 10^5$$$) consisting of lowercase English letters. It is guaranteed that the sum of lengths of $$$s$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single string $$$t$$$. The multisets of letters in strings $$$s$$$ and $$$t$$$ must be equal. The value of $$$f(t)$$$, the maximum of prefix functions in string $$$t$$$, must be as small as possible. String $$$t$$$ must be the lexicographically smallest string out of all strings satisfying the previous conditions.

NoteA string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.In the first test case, $$$f(t) = 0$$$ and the values of prefix function are $$$[0, 0, 0, 0, 0]$$$ for any permutation of letters. String ckpuv is the lexicographically smallest permutation of letters of string vkcup.In the second test case, $$$f(t) = 1$$$ and the values of prefix function are $$$[0, 1, 0, 1, 0, 1, 0]$$$.In the third test case, $$$f(t) = 5$$$ and the values of prefix function are $$$[0, 1, 2, 3, 4, 5]$$$.

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

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

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

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

enum V = 26;

char chr(int u) {
  return cast(char)('a' + u);
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const S = readToken();
        const N = cast(int)(S.length);
        debug {
          writeln("S = ", S);
          stdout.flush;
        }

        auto freq = new int[V];
        foreach (i; 0 .. N) {
          ++freq[S[i] - 'a'];
        }

        int ansLen;
        auto ans = new char[N];
        ans[] = '?';
        foreach (u; 0 .. V) {
          if (freq[u] == N) {
            ans[] = chr(u);
            goto done;
          }
        }
        foreach (u; 0 .. V) {
          if (freq[u] == 1) {
            ans[ansLen++] = chr(u);
            foreach (v; 0 .. V) {
              if (u != v) {
                foreach (_; 0 .. freq[v]) {
                  ans[ansLen++] = chr(v);
                }
              }
            }
            goto done;
          }
        }
        {
          int u0 = -1;
          foreach (u; 0 .. V) {
            if (freq[u] > 0) {
              u0 = u;
              break;
            }
          }
          assert(~u0);
          if (freq[u0] <= N / 2 + 1) {
            ans[0] = chr(u0);
            int pos = 1;
            foreach (_; 1 .. freq[u0]) {
              ans[pos] = chr(u0);
              pos += 2;
            }
            pos = 0;
            foreach (v; u0 + 1 .. V) {
              foreach (_; 0 .. freq[v]) {
                for (; ans[pos] != '?'; ++pos) {}
                ans[pos] = chr(v);
              }
            }
          } else {
            int u1 = -1;
            foreach (u; u0 + 1 .. V) {
              if (freq[u] > 0) {
                u1 = u;
                break;
              }
            }
            assert(~u1);
            int u2 = -1;
            foreach (u; u1 + 1 .. V) {
              if (freq[u] > 0) {
                u2 = u;
                break;
              }
            }
            if (~u2) {
              ans[ansLen++] = chr(u0);
              ans[ansLen++] = chr(u1);
              foreach (_; 1 .. freq[u0]) ans[ansLen++] = chr(u0);
              ans[ansLen++] = chr(u2);
              foreach (_; 1 .. freq[u1]) ans[ansLen++] = chr(u1);
              foreach (_; 1 .. freq[u2]) ans[ansLen++] = chr(u2);
              foreach (u; u2 + 1 .. V) {
                foreach (_; 0 .. freq[u]) ans[ansLen++] = chr(u);
              }
            } else {
              ans[ansLen++] = chr(u0);
              foreach (_; 0 .. freq[u1]) ans[ansLen++] = chr(u1);
              foreach (_; 1 .. freq[u0]) ans[ansLen++] = chr(u0);
            }
          }
        }
       done:{}
        writeln(ans);

        debug {
          auto A = new int[N];
          foreach (i; 0 .. N) {
            A[i] = S[i] - 'a';
          }
          A.sort;
          int mn = N + 1;
          int[] ams;
          do {
            auto fail = new int[N + 1];
            int j = fail[0] = -1;
            foreach (i; 0 .. N) {
              for (; ~j && A[j] != A[i]; j = fail[j]) {}
              fail[i + 1] = ++j;
            }
            const cost = fail.maxElement;
            // writeln(A, ": ", fail, " ", cost);
            if (chmin(mn, cost)) {
              ams = A.dup;
            }
          } while (A.nextPermutation);
          writeln("mn = ", mn);
          string brt;
          foreach (i; 0 .. N) {
            brt ~= chr(ams[i]);
          }
          writeln("brt = ", brt);
          assert(brt == ans);
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

immutable int letters = 26;

string solve (string s)
{
	int [letters] d;
	foreach (ref c; s)
	{
		d[c - 'a'] += 1;
	}

	foreach (let; 0..letters)
	{
		if (d[let] == 1)
		{
			string res;
			res ~= cast (char) (let + 'a');
			d[let] -= 1;
			foreach (x; 0..letters)
			{
				foreach (y; 0..d[x])
				{
					res ~= cast (char) (x + 'a');
				}
			}
			return res;
		}
	}

	foreach (let; 0..letters)
	{
		if (d[let] > 0)
		{
			string res;
			res ~= cast (char) (let + 'a');
			d[let] -= 1;
			string [2] add;
			foreach (x; 0..letters)
			{
				foreach (y; 0..d[x])
				{
					add[x > let] ~= cast (char) (x + 'a');
				}
			}

			if (add[0].length <= add[1].length + 1)
			{
				while (!add[0].empty || !add[1].empty)
				{
					foreach (v; 0..2)
					{
						if (!add[v].empty)
						{
							res ~= add[v][0];
							add[v].popFront ();
						}
					}
				}
				return res;
			}

			if (add[1].empty || add[1].front == add[1].back)
			{
				res ~= add[1];
				res ~= add[0];
				return res;
			}

			auto second = add[1][0];
			res ~= second;
			add[1].popFront ();
			res ~= add[0];
			foreach (i, ref c; add[1])
			{
				if (c != second)
				{
					res ~= c;
					res ~= add[1][0..i];
					res ~= add[1][i + 1..$];
					return res;
				}
			}

			assert (false);
		}
	}

	assert (false);
}

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


Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:  She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her .  Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.

The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones.  The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.

Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.

NotePlease note that the answers to the questions may overflow 32-bit integer type.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto B = A.dup.sort().array;

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

    auto M = readln.chomp.to!int;
    foreach (_; 0..M) {
        auto s = readln.split.map!(to!int);
        auto t = s[0]-1;
        auto l = s[1];
        auto r = s[2];
        writeln(acm[t][r] - acm[t][l-1]);
    }
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;
    auto B = A.dup.sort().array;

    auto acm = new int[][](2, N+1);
    foreach (i; 1..N+1) {
        acm[0][i] = acm[0][i-1] + A[i-1];
        acm[1][i] = acm[1][i-1] + B[i-1];
    }

    auto M = readln.chomp.to!int;
    foreach (_; 0..M) {
        auto s = readln.split.map!(to!int);
        auto t = s[0]-1;
        auto l = s[1];
        auto r = s[2];
        writeln(acm[t][r] - acm[t][l-1]);
    }
}


Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$.

If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO".

NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product.

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 0..n)
		{
			bool ok = true;
			for (long j = 1; j*j <= a[i]; ++j)
			{
				if (j*j == a[i])
					ok = false;
			}
			if (ok)
			{
				ans[ti] = true;
				break;
			}
		}
	}

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


You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode: repeat ni times    yi := y    y := yi + 1end repeatHere y is a shared variable. Everything else is local for the process. All actions on a given row are atomic, i.e. when the process starts executing a row it is never interrupted. Beyond that all interleavings are possible, i.e. every process that has yet work to do can be granted the rights to execute its next row. In the beginning y = 0. You will be given an integer W and ni, for i = 1, ... , N. Determine if it is possible that after all processes terminate, y = W, and if it is possible output an arbitrary schedule that will produce this final value.

In the first line of the input you will be given two space separated integers N (1 ≤ N ≤ 100) and W ( - 109 ≤ W ≤ 109). In the second line there are N space separated integers ni (1 ≤ ni ≤ 1000).

On the first line of the output write Yes if it is possible that at the end y = W, or No otherwise. If the answer is No then there is no second line, but if the answer is Yes, then on the second line output a space separated list of integers representing some schedule that leads to the desired result. For more information see note.

NoteFor simplicity, assume that there is no repeat statement in the code of the processes, but the code from the loop is written the correct amount of times. The processes are numbered starting from 1. The list of integers represent which process works on its next instruction at a given step. For example, consider the schedule 1 2 2 1 3. First process 1 executes its first instruction, then process 2 executes its first two instructions, after that process 1 executes its second instruction, and finally process 3 executes its first instruction. The list must consists of exactly 2·Σ i = 1...N ni numbers.

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, W;
int[] A;

int[] solve() {
	int[] ret;
	const sumA = reduce!"a + b"(0, A);
	if (!(1 <= W && W <= sumA)) {
		return null;
	}
	if (N == 1) {
		if (W != A[0]) {
			return null;
		}
		ret.length = A[0] * 2;
		ret[] = 0;
		return ret;
	}
	int im = -1;
	foreach (i; 0 .. N) {
		if (A[i] == 1) {
			im = i;
		}
	}
	if (im != -1) {
		int[] kills = new int[N];
		int need = sumA - W;
		foreach (i; 0 .. N) {
			kills[i] = min(need, A[i] - ((i == im) ? 1 : 0));
			need -= kills[i];
		}
debug{
writeln("kills = ",kills);
}
		ret ~= im;
		foreach (i; 0 .. N) {
			foreach (_; 0 .. kills[i]) {
				ret ~= i;
				ret ~= i;
			}
		}
		ret ~= im;
		foreach (i; 0 .. N) {
			foreach (_; 0 .. A[i] - ((i == im) ? 1 : 0) - kills[i]) {
				ret ~= i;
				ret ~= i;
			}
		}
		return ret;
	} else {
		if (W == 1) {
			return null;
		}
		int[] kills = new int[N];
		int need = sumA - W;
		foreach (i; 0 .. N) {
			kills[i] = min(need, A[i] - ((i < 2) ? 1 : 0));
			need -= kills[i];
		}
debug{
writeln("kills = ",kills);
}
		ret ~= 0;
		foreach (i; 1 .. N) {
			foreach (_; 0 .. kills[i]) {
				ret ~= i;
				ret ~= i;
			}
		}
		ret ~= 0;
		ret ~= 1;
		foreach (j; 0 .. kills[0]) {
			ret ~= 0;
			ret ~= 0;
		}
		ret ~= 1;
		foreach (i; 0 .. N) {
			foreach (_; 0 .. A[i] - ((i < 2) ? 1 : 0) - kills[i]) {
				ret ~= i;
				ret ~= i;
			}
		}
		return ret;
	}
}

int judge(int[] xs) {
	int y;
	int[] ys = new int[N];
	bool[] toSet = new bool[N];
	foreach (i; xs) {
		if (toSet[i]) {
			y = ys[i] + 1;
		} else {
			ys[i] = y;
		}
		toSet[i] = !toSet[i];
	}
	return y;
}

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

		if (auto res = solve) {
			writeln("Yes");
			foreach (idx, i; res) {
				if (idx > 0) {
					write(" ");
				}
				write(i + 1);
			}
			writeln;
debug{
assert(W==res.judge);
}
		} else {
			writeln("No");
		}
	}
	} catch (EOFException) {}
}

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, W;
int[] A;

int[] solve() {
	int[] ret;
	const sumA = reduce!"a + b"(0, A);
	if (!(1 <= W && W <= sumA)) {
		return null;
	}
	if (N == 1) {
		if (W != A[0]) {
			return null;
		}
		ret.length = A[0] * 2;
		ret[] = 0;
		return ret;
	}
	int im = -1;
	foreach (i; 0 .. N) {
		if (A[i] == 1) {
			im = i;
		}
	}
	if (im != -1) {
		int[] kills = new int[N];
		int need = sumA - W;
		foreach (i; 0 .. N) {
			kills[i] = min(need, A[i] - ((i == im) ? 1 : 0));
			need -= kills[i];
		}
debug{
writeln("kills = ",kills);
}
		ret ~= im;
		foreach (i; 0 .. N) {
			foreach (_; 0 .. kills[i]) {
				ret ~= i;
				ret ~= i;
			}
		}
		ret ~= im;
		foreach (i; 0 .. N) {
			foreach (_; 0 .. A[i] - ((i < 2) ? 1 : 0) - kills[i]) {
				ret ~= i;
				ret ~= i;
			}
		}
		return ret;
	} else {
		if (W == 1) {
			return null;
		}
		int[] kills = new int[N];
		int need = sumA - W;
		foreach (i; 0 .. N) {
			kills[i] = min(need, A[i] - ((i < 2) ? 1 : 0));
			need -= kills[i];
		}
debug{
writeln("kills = ",kills);
}
		ret ~= 0;
		foreach (i; 1 .. N) {
			foreach (_; 0 .. kills[i]) {
				ret ~= i;
				ret ~= i;
			}
		}
		ret ~= 0;
		ret ~= 1;
		foreach (j; 0 .. kills[0]) {
			ret ~= 0;
			ret ~= 0;
		}
		ret ~= 1;
		foreach (i; 0 .. N) {
			foreach (_; 0 .. A[i] - ((i < 2) ? 1 : 0) - kills[i]) {
				ret ~= i;
				ret ~= i;
			}
		}
		return ret;
	}
}

int judge(int[] xs) {
	int y;
	int[] ys = new int[N];
	bool[] toSet = new bool[N];
	foreach (i; xs) {
		if (toSet[i]) {
			y = ys[i] + 1;
		} else {
			ys[i] = y;
		}
		toSet[i] = !toSet[i];
	}
	return y;
}

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

		if (auto res = solve) {
			writeln("Yes");
			foreach (idx, i; res) {
				if (idx > 0) {
					write(" ");
				}
				write(i + 1);
			}
			writeln;
debug{
assert(W==res.judge);
}
		} else {
			writeln("No");
		}
	}
	} catch (EOFException) {}
}


Let's call a positive integer composite if it has at least one divisor other than $$$1$$$ and itself. For example:  the following numbers are composite: $$$1024$$$, $$$4$$$, $$$6$$$, $$$9$$$;  the following numbers are not composite: $$$13$$$, $$$1$$$, $$$2$$$, $$$3$$$, $$$37$$$. You are given a positive integer $$$n$$$. Find two composite integers $$$a,b$$$ such that $$$a-b=n$$$.It can be proven that solution always exists.

The input contains one integer $$$n$$$ ($$$1 \leq n \leq 10^7$$$): the given integer.

Print two composite integers $$$a,b$$$ ($$$2 \leq a, b \leq 10^9, a-b=n$$$). It can be proven, that solution always exists. If there are several possible solutions, you can print any.

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

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

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

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.read_int;
        while (t--) {
                int a = cin.read_int;
                writeln(a * 9, " ", a * 8);
        }
}

import std.stdio;
bool isSimple(int a)
{
	if (a!=0)
	{
		int c=0;
		for (int i=1; i<a+1; i++)
		{
			if (a%i==0)
			{
				c=c+1;
			}
		}
		if (c>2)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	else
	{
		return false;
	}
}
int main()
{
	int a=0;
	readf(" %d", &a);
	int c=0;
	int b=a;
	while (true)
	{
		b=b+1;
		c=c+1;
		if (!(isSimple(b)) && !(isSimple(c)))
		{
			break;
		}
	}
	writeln(b);
	writeln(c);
	return 0;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;

	if (n == 1)
		writeln("9 8");
	else
	{
		writeln(n*3, " ", n*2);
	}

	stdout.flush;
	debug readln;
}

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

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

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

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.read_int;
        while (t--) {
                int a = cin.read_int;
                writeln(a * 8, " ", a * 8);
        }
}

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

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

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

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.read_int;
        while (t--) {
                int a = cin.read_int;
                writeln(a * 3, " ", a * 2);
        }
}

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

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

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

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.read_int;
        while (t--) {
                int a = cin.read_int;
                writeln(a * 3 - a * 2);
        }
}

import std.stdio;
bool isSimple(int a)
{
	int c=0;
	for (int i=1; i<a+1; i++)
	{
		if (a%i==0)
		{
			c=c+1;
		}
	}
	if (c>2)
	{
		return false;
	}
	else
	{
		return true;
	}
}
int main()
{
	int a=0;
	readf(" %d", &a);
	int c=4;
	int b=0;
	while (true)
	{
		b=a+c;
		c=c+2;
		if (!(isSimple(b)))
		{
			break;
		}
	}
	writeln(b);
	writeln(c);
	return 0;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;

	if (n == 1)
		writeln("9 8");
	else
	{
		writeln(n*2, " ", n*3);
	}

	stdout.flush;
	debug readln;
}


This is an interactive problem.In good old times dwarves tried to develop extrasensory abilities:  Exactly n dwarves entered completely dark cave.  Each dwarf received a hat — white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves.  Dwarves went out of the cave to the meadow and sat at an arbitrary place one after the other. When a dwarf leaves the cave, he sees the colors of all hats of all dwarves that are seating on the meadow (i.e. left the cave before him). However, he is not able to see the color of his own hat and none of the dwarves can give him this information.  The task for dwarves was to got diverged into two parts — one with dwarves with white hats and one with black hats. After many centuries, dwarves finally managed to select the right place on the meadow without error. Will you be able to repeat their success?You are asked to successively name n different integer points on the plane. After naming each new point you will be given its color — black or white. Your task is to ensure that the named points can be split by a line in such a way that all points of one color lie on the same side from the line and points of different colors lie on different sides. Moreover, no points can belong to the line. Also, you need to report any such line at the end of the process.In this problem, the interactor is adaptive — the colors of the points in the tests are not fixed beforehand and the jury program can select them arbitrarily, in particular, depending on your program output.

NoteIn the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.The following picture illustrates the first test.

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

bool put (int x, int y)
{
	writeln (x, " ", y);
	stdout.flush ();
	return readln.strip == "white";
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto origin = put (0, 0);
		n -= 1;

		int xLo = 0;
		int xHi = 10 ^^ 9;
		while (n > 15)
		{
			int xMe = (xLo + xHi) / 2;
			auto cur = put (xMe, 0);
			n -= 1;
			if (cur == origin)
			{
				xLo = xMe;
			}
			else
			{
				xHi = xMe;
			}
		}

		int yLo = 0;
		int yHi = 10 ^^ 9;
		while (n > 0)
		{
			int yMe = (yLo + yHi) / 2;
			auto cur = put (0, yMe);
			n -= 1;
			if (cur == origin)
			{
				yLo = yMe;
			}
			else
			{
				yHi = yMe;
			}
		}

		int xMe = (xLo + xHi) / 2;
		int yMe = (yLo + yHi) / 2;
		writeln (xMe, " ", 0, " ", 0, " ", yMe);
		stdout.flush ();
	}
}


You are given a tournament — complete directed graph.In one operation you can pick any vertex $$$v$$$ and change the direction of all edges with $$$v$$$ on one of the ends (i.e all edges $$$u \to v$$$ change their orientation to $$$v \to u$$$ and vice versa).You want to make the tournament strongly connected with the smallest possible number of such operations if it is possible. Also, if it is possible, you need to find the number of ways to make this number of operations to make graph strongly connected (two ways are different if for some $$$i$$$ vertex that we chose on $$$i$$$-th operation in one way is different from vertex that we chose on $$$i$$$-th operation in another way). You only need to find this value modulo $$$998\,244\,353$$$.

The first line of input contains one integer $$$n$$$ ($$$3 \leq n \leq 2000$$$): the number of vertices in the tournament. Following $$$n$$$ lines contain a description of the given tournament, each of them contains a binary string of length $$$n$$$. If $$$j$$$-th character of $$$i$$$-th string is equal to '1', then the graph has an edge $$$i \to j$$$. It is guaranteed that there are no edges $$$i \to i$$$ and the graph has exactly one edge among $$$i \to j$$$ and $$$j \to i$$$ for different $$$i$$$ and $$$j$$$.

If it is not possible to convert tournament to strongly connected with the given operations, output "-1". Otherwise, output two integers: the smallest number of operations that you need to make the given graph strongly connected and the number of ways to do this number of operations to make graph strongly connected, modulo $$$998\,244\,353$$$.

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

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

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

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

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

      auto a = new int[][](N, N);
      auto deg = new int[N];
      foreach (u; 0 .. N) foreach (v; 0 .. N) {
        a[u][v] = A[u][v] - '0';
        deg[u] += a[u][v];
      }

      void flip(int u) {
        foreach (v; 0 .. N) {
          if (u != v) {
            deg[u] -= a[u][v];
            deg[v] -= a[v][u];
            swap(a[u][v], a[v][u]);
            deg[u] += a[u][v];
            deg[v] += a[v][u];
          }
        }
      }
      bool check() {
        auto ds = deg.dup.sort;
        int sum;
        foreach (j; 1 .. N) {
          sum += ds[j - 1];
          if (sum == j * (j - 1) / 2) {
            return false;
          }
        }
        return true;
      }

      int ansNum = N + 1;
      long ansCnt;
      void doIt(int num) {
        if (chmin(ansNum, num)) {
          ansCnt = 0;
        }
        if (ansNum == num) {
          ++ansCnt;
        }
      }

      if (N <= 8) {
        foreach (p; 0 .. 1 << N) {
          foreach (u; 0 .. N) {
            if (p & 1 << u) {
              flip(u);
            }
          }
          if (check()) {
            doIt(popcnt(p));
          }
          foreach (u; 0 .. N) {
            if (p & 1 << u) {
              flip(u);
            }
          }
        }
      } else {
        if (check()) {
          doIt(0);
        }
        foreach (u; 0 .. N) {
          flip(u);
          if (check()) {
            doIt(1);
          }
          flip(u);
        }
      }
      if (ansNum > N) {
        writeln(-1);
      } else {
        foreach (k; 1 .. ansNum + 1) {
          ansCnt *= k;
        }
        writeln(ansNum, " ", ansCnt);
      }
    }
  } catch (EOFException e) {
  }
}


Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.

The only string contains the string s of length l (3 ≤ l ≤ 5000), consisting of small English letters only.

Print the only number — the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if

NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.

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

immutable int letters = 26;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto n = s.length.to !(int);
		s = s ~ s;
		real invN = 1.0 / n;
		real res = 0.0;
		foreach (c; 'a'..'z' + 1)
		{
			string [] t;
			foreach (i; 0..n)
			{
				if (s[i] == c)
				{
					t ~= s[i..i + n];
				}
			}
			int temp = 0;
			foreach (i; 0..n)
			{
				int [letters] d;
				foreach (r; t)
				{
					d[r[i] - 'a'] += 1;
				}
				int cur = 0;
				foreach (e; 0..letters)
				{
					if (d[e] == 1)
					{
						cur += 1;
					}
				}
				temp = max (temp, cur);
			}
			res += temp * invN;
		}
		writefln ("%.20f", res);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const S = readToken();
      const L = cast(int)(S.length);

      auto kss = new int[][26];
      foreach (k; 0 .. L) {
        kss[S[k] - 'a'] ~= k;
      }
      int ans;
      foreach (a; 0 .. 26) {
        int mx;
        foreach (x; 0 .. L) {
          auto cnt = new int[26];
          foreach (k; kss[a]) {
            ++cnt[S[(k + x) % L] - 'a'];
          }
          int num1;
          foreach (b; 0 .. 26) {
            if (cnt[b] == 1) {
              ++num1;
            }
          }
          chmax(mx, num1);
        }
        ans += mx;
      }
      writefln("%.10f", ans / cast(real)(L));
    }
  } catch (EOFException e) {
  }
}


Pavel has several sticks with lengths equal to powers of two.He has $$$a_0$$$ sticks of length $$$2^0 = 1$$$, $$$a_1$$$ sticks of length $$$2^1 = 2$$$, ..., $$$a_{n-1}$$$ sticks of length $$$2^{n-1}$$$. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.It is forbidden to break sticks, and each triangle should consist of exactly three sticks.Find the maximum possible number of triangles.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 300\,000$$$) — the number of different lengths of sticks. The second line contains $$$n$$$ integers $$$a_0$$$, $$$a_1$$$, ..., $$$a_{n-1}$$$ ($$$1 \leq a_i \leq 10^9$$$), where $$$a_i$$$ is the number of sticks with the length equal to $$$2^i$$$.

Print a single integer — the maximum possible number of non-degenerate triangles that Pavel can make.

NoteIn the first example, Pavel can, for example, make this set of triangles (the lengths of the sides of the triangles are listed): $$$(2^0, 2^4, 2^4)$$$, $$$(2^1, 2^3, 2^3)$$$, $$$(2^1, 2^2, 2^2)$$$.In the second example, Pavel cannot make a single triangle.In the third example, Pavel can, for example, create this set of triangles (the lengths of the sides of the triangles are listed): $$$(2^0, 2^0, 2^0)$$$, $$$(2^1, 2^1, 2^1)$$$, $$$(2^2, 2^2, 2^2)$$$.

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

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

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

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

int N;
long[] A;

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

      long ans;
      long sum;
      foreach (i; 0 .. N) {
        sum += A[i];
        const tmp = min(sum / 3, A[i] / 2);
        ans += tmp;
        sum -= tmp * 3;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

    int prev = 0;
    long ans = 0;
    foreach (e; arr) {
        auto withprev = min(prev, e / 2);
        e -= withprev * 2;
        prev -= withprev;
        ans += withprev;

        auto triple = e / 3;
        e -= triple * 3;
        ans += triple;

        prev += e;
    }

    ans.writeln;
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		long res = 0;
		long saved = 0;
		foreach_reverse (i; 0..n)
		{
			auto pairs = a[i] / 2;
			saved += pairs;
			if (a[i] % 2 == 1 && saved > 0)
			{
				res += 1;
				saved -= 1;
			}
		}
		res += saved * 2 / 3;
		writeln (res);
	}
}

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

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

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

    int prev = 0;
    long ans = 0;
    foreach (e; arr) {
        auto withprev = min(prev*2, e);
        e -= withprev;
        prev -= withprev / 2;
        ans += withprev / 2;

        auto triple = e / 3;
        e -= triple * 3;
        ans += triple;

        prev += e;
    }

    ans.writeln;
}

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

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

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

    int prev = 0;
    long ans = 0;
    foreach (e; arr) {
        ans += e / 3;
        e = e % 3;
        if (e == 2 && prev > 0) {
            ans += 1;
            e -= 2;
            prev -= 1;
        }

        prev += e;
    }

    ans.writeln;
}


Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $$$a=[1, 3, 3, 7]$$$ is good because there is the element $$$a_4=7$$$ which equals to the sum $$$1 + 3 + 3$$$.You are given an array $$$a$$$ consisting of $$$n$$$ integers. Your task is to print all indices $$$j$$$ of this array such that after removing the $$$j$$$-th element from the array it will be good (let's call such indices nice).For example, if $$$a=[8, 3, 5, 2]$$$, the nice indices are $$$1$$$ and $$$4$$$:   if you remove $$$a_1$$$, the array will look like $$$[3, 5, 2]$$$ and it is good;  if you remove $$$a_4$$$, the array will look like $$$[8, 3, 5]$$$ and it is good. You have to consider all removals independently, i. e. remove the element, check if the resulting array is good, and return the element into the array.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — elements of the array $$$a$$$.

In the first line print one integer $$$k$$$ — the number of indices $$$j$$$ of the array $$$a$$$ such that after removing the $$$j$$$-th element from the array it will be good (i.e. print the number of the nice indices). In the second line print $$$k$$$ distinct integers $$$j_1, j_2, \dots, j_k$$$ in any order — nice indices of the array $$$a$$$. If there are no such indices in the array $$$a$$$, just print $$$0$$$ in the first line and leave the second line empty or do not print it at all.

NoteIn the first example you can remove any element with the value $$$2$$$ so the array will look like $$$[5, 1, 2, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 1 + 2 + 2$$$).In the second example you can remove $$$8$$$ so the array will look like $$$[3, 5, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 3 + 2$$$). You can also remove $$$2$$$ so the array will look like $$$[8, 3, 5]$$$. The sum of this array is $$$16$$$ and there is an element equals to the sum of remaining elements ($$$8 = 3 + 5$$$).In the third example you cannot make the given array good by removing exactly one element.

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

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

    auto sm = arr.sum(0L);
    int [long] cnt;
    arr.each!(x => ++cnt[x]);

    int[] ans;
    foreach (i, e; arr) {
        sm -= e;
        --cnt[e];

        if (sm % 2 == 0 && cnt.get(sm/2, 0) > 0) ans ~= cast(int)i+1;

        sm += e;
        ++cnt[e];
    }

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

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

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

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

    auto sm = arr.sum;
    int [int] cnt;
    arr.each!(x => ++cnt[x]);

    int[] ans;
    foreach (i, e; arr) {
        sm -= e;
        --cnt[e];

        if (sm % 2 == 0 && cnt.get(sm/2, 0) > 0) ans ~= cast(int)i+1;

        sm += e;
        ++cnt[e];
    }

    ans.writefln!("%(%s %)");
}

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

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

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

    auto sm = arr.sum;
    int [int] cnt;
    arr.each!(x => ++cnt[x]);

    int[] ans;
    foreach (i, e; arr) {
        sm -= e;
        --cnt[e];

        if (sm % 2 == 0 && cnt.get(sm/2, 0) > 0) ans ~= cast(int)i+1;

        sm += e;
        ++cnt[e];
    }

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


Lunar New Year is approaching, and Bob is going to receive some red envelopes with countless money! But collecting money from red envelopes is a time-consuming process itself.Let's describe this problem in a mathematical way. Consider a timeline from time $$$1$$$ to $$$n$$$. The $$$i$$$-th red envelope will be available from time $$$s_i$$$ to $$$t_i$$$, inclusive, and contain $$$w_i$$$ coins. If Bob chooses to collect the coins in the $$$i$$$-th red envelope, he can do it only in an integer point of time between $$$s_i$$$ and $$$t_i$$$, inclusive, and he can't collect any more envelopes until time $$$d_i$$$ (inclusive) after that. Here $$$s_i \leq t_i \leq d_i$$$ holds.Bob is a greedy man, he collects coins greedily — whenever he can collect coins at some integer time $$$x$$$, he collects the available red envelope with the maximum number of coins. If there are multiple envelopes with the same maximum number of coins, Bob would choose the one whose parameter $$$d$$$ is the largest. If there are still multiple choices, Bob will choose one from them randomly.However, Alice — his daughter — doesn't want her father to get too many coins. She could disturb Bob at no more than $$$m$$$ integer time moments. If Alice decides to disturb Bob at time $$$x$$$, he could not do anything at time $$$x$$$ and resumes his usual strategy at the time $$$x + 1$$$ (inclusive), which may lead to missing some red envelopes.Calculate the minimum number of coins Bob would get if Alice disturbs him optimally.

The first line contains three non-negative integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq 200$$$, $$$1 \leq k \leq 10^5$$$), denoting the length of the timeline, the number of times Alice can disturb Bob and the total number of red envelopes, respectively. The following $$$k$$$ lines describe those $$$k$$$ red envelopes. The $$$i$$$-th line contains four positive integers $$$s_i$$$, $$$t_i$$$, $$$d_i$$$ and $$$w_i$$$ ($$$1 \leq s_i \leq t_i \leq d_i \leq n$$$, $$$1 \leq w_i \leq 10^9$$$) — the time segment when the $$$i$$$-th envelope is available, the time moment Bob can continue collecting after collecting the $$$i$$$-th envelope, and the number of coins in this envelope, respectively.

Output one integer — the minimum number of coins Bob would get if Alice disturbs him optimally.

NoteIn the first sample, Alice has no chance to disturb Bob. Therefore Bob will collect the coins in the red envelopes at time $$$1$$$ and $$$5$$$, collecting $$$13$$$ coins in total.In the second sample, Alice should disturb Bob at time $$$1$$$. Therefore Bob skips the first envelope, collects the second one and can not do anything after that. So the answer is $$$2$$$.

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

alias Block = Tuple!(int, "s", int, "t", int, "d", long, "w");
immutable long INF = 1L << 59;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto K = s[2];
    auto B = new Block[](K);
    foreach (i; 0..K) {
        s = readln.split.map!(to!int);
        B[i] = Block(s[0], s[1], s[2], s[3].to!long);
    }

    B.sort!"a[0] < b[0]";
    auto pq = new BinaryHeap!(Array!Block, "a[3] == b[3] ? a[2] < b[2] : a[3] < b[3]");
    int p = 0;

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

    foreach (i; 1..N+1) {
        while (!pq.empty && pq.front.t < i) pq.removeFront;
        while (p < K && B[p].s == i) pq.insert(B[p++]);
        auto next = pq.empty ? Block(-1, -1, -1, -INF) : pq.front;

        foreach (j; 0..M+1) {
            if (next.s == -1) {
                dp[i+1][j] = min(dp[i+1][j], dp[i][j]);
            } else {
                dp[next.d+1][j] = min(dp[next.d+1][j], dp[i][j] + next.w);
                if (j < M) dp[i+1][j+1] = min(dp[i+1][j+1], dp[i][j]);
            }
        }
    }

    dp[N+1].reduce!min.writeln;
}

import std.algorithm;
import std.container;
import std.stdio;
import std.typecons;

alias Envelope = Tuple !(int, q{w}, int, q{d}, int, q{s}, int, q{t}, int, q{i});

void main ()
{
	int n, m, k;
	while (readf (" %s %s %s", &n, &m, &k) > 0)
	{
		n += 1;
		auto a = new Envelope [k];
		auto add = new int [] [n + 1];
		auto rem = new int [] [n + 1];
		foreach (i, ref e; a)
		{
			readf (" %s %s %s %s", &e.s, &e.t, &e.d, &e.w);
			e.i = i;
			add[e.s] ~= i;
			rem[e.t] ~= i;
		}

		auto t = redBlackTree !(Envelope) ();
		auto f = new long [] [] (n + 1, m + 1);
		foreach (ref line; f)
		{
			line[] = long.max / 2;
		}
		f[0][0] = 0;
		foreach (x; 0..n)
		{
			foreach (z; add[x])
			{
				t.insert (a[z]);
			}
			foreach (y; 0..m + 1)
			{
				auto ny = y + !t.empty;
				if (ny <= m)
				{
					f[x + 1][ny] =
					    min (f[x + 1][ny],
					    f[x][y]);
				}
				if (!t.empty)
				{
					f[t.back.d + 1][y] =
					    min (f[t.back.d + 1][y],
					    f[x][y] + t.back.w);
				}
			}
			foreach (z; rem[x])
			{
				t.removeKey (a[z]);
			}
		}
		writeln (f[n].minElement);
	}
}

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

enum inf3 = 1_001_001_001;
enum inf6 = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;

alias Seg = Tuple!(int, "s", int, "t", int, "d", int, "v");
alias Env = Tuple!(int, "v", int, "d", int, "t");

void main() {
    int n, m, k;
    scan(n, m, k);

    auto s = new Seg[](k);

    foreach (i ; 0 .. k) {
        int si, ti, di, vi;

        scan(si, ti, di, vi);
        si--, ti--, di--;
        s[i] = Seg(si, ti, di, vi);
    }

    s.sort();

    auto bh = new BinaryHeap!(Array!Env, "a < b")();
    auto dp = new long[][](n + 1, m + 1);
    fillAll(dp, inf6);
    dp[0][0] = 0;

    foreach (i ; 0 .. n) {
        while (!s.empty && s.front.s <= i) {
            bh.insert(Env(s.front.v, s.front.d, s.front.t));
            s.popFront();
        }
        while (!bh.empty && bh.front.t < i) {
            bh.popFront();
        }

        if (bh.empty) {
            foreach (j ; 0 .. m + 1) {
                dp[i + 1][j] = min(dp[i + 1][j], dp[i][j]);
            }
            continue;
        }

        int v = bh.front.v;
        int d = bh.front.d;

        debug {
            writeln(v, " ", d);
        }

        foreach (j ; 0 .. m + 1) {
            if (dp[i][j] == inf6) continue;
            // いたずらした場合
            if (j < m) dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j]);
            // しなかった場合
            dp[d + 1][j] = min(dp[d + 1][j], dp[i][j] + v);
        }
    }

    debug {
        writefln("%(%s\n%)", dp);
    }

    long ans = inf6;

    foreach (j ; 0 .. m + 1) {
        ans = min(ans, dp[n][j]);
    }

    writeln(ans);
}

struct UnionFind {
    private {
        int _size;
        int[] _parent;
        long[] wa;
        int bcnt;
        bool[] bad;
        int[] hen;
    }

    this(int N, long[] x)
    in {
        assert(N > 0);
    }
    body {
        _size = N;
        _parent = new int[](_size);
        foreach (i ; 0 .. _size) {
            _parent[i] = i;
        }
        wa = new long[](N);
        wa[] = x.dup;
        bad = new bool[](N);
        hen = new int[](N);
    }

    int findRoot(int x)
    in {
        assert(0 <= x && x < _size);
    }
    body {
        if (_parent[x] != x) {
            _parent[x] = findRoot(_parent[x]);
        }

        return _parent[x];
    }

    bool same(int x, int y)
    in {
        assert(0 <= x && x < _size);
        assert(0 <= y && y < _size);
    }
    body {
        return findRoot(x) == findRoot(y);
    }

    void merge(int x, int y)
    in {
        assert(0 <= x && x < _size);
        assert(0 <= y && y < _size);
    }
    body {
        int u = findRoot(x);
        int v = findRoot(y);

        if (u == v) return;

        _parent[v] = u;
        wa[u] += wa[v];
        wa[v] = 0;

        hen[u] += hen[v] + 1;
        hen[v] = 0;
    }
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$).  Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.

Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.

NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).

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

void main() {
    int n, k;
    scan(n, k);

    auto h = readln.split.to!(int[]);

    auto hmin = h.reduce!min;
    auto hmax = h.reduce!max;

    if (hmin == hmax) {
        writeln(0);
        return;
    }

    auto cnt = new int[](hmax + 1);
    foreach (i ; 0 .. n) {
        cnt[h[i]]++;
    }

    foreach_reverse (i ; 0 .. hmax) {
        cnt[i] += cnt[i+1];
    }

    debug {
        stderr.writeln(cnt);
    }

    int ans;
    int store;

    foreach_reverse (i ; 0 .. hmax + 1) {
        if (i == hmin) {
            ans++;
            break;
        }
        if (store + cnt[i] > k) {
            ans++;
            store = cnt[i];
        }
        else {
            store += cnt[i];
        }
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

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

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

  auto all = reduce!((res, val) => (res && val == a[0]))(true, a);
  if (all) {
    writeln(0);
    return;
  }
  auto freq = new int[](3 * 10 ^^ 5);
  foreach (val; a)
    freq[val]++;
  auto mn = reduce!(min)(a), mx = reduce!(max)(a);
  int num = 0, s = 0;
  for (int h = mx; h > mn; h--) {
    freq[h] += freq[h + 1];
    if ((s += freq[h]) > k) {
      num++;
      s = freq[h];
    }
  }
  writeln(num + (s > 0));
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

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

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

  auto all = reduce!((res, val) => (res && val == a[0]))(true, a);
  if (all) {
    writeln(0);
    return;
  }
  auto freq = new int[](3 * 10 ^^ 5);
  foreach (val; a)
    freq[val]++;
  auto mn = reduce!(min)(a), mx = reduce!(max)(a);
  int num = 0;
  for (int h = mx, s = 0; h >= mn; h--) {
    freq[h] += freq[h + 1];
    if ((s += freq[h]) > k) {
      num++;
      s = freq[h];
    }
  }
  writeln(num);
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}


A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:  b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.  For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1. The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.

The first input line of the input contains a single integer n (3 ≤ n ≤ 500 000) — the length of the initial sequence. The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.

If the sequence will never become stable, print a single number  - 1. Otherwise, first print a single integer — the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space  — the resulting sequence itself.

NoteIn the second sample the stabilization occurs in two steps: , and the sequence 00000 is obviously stable.

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)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		a = a[0] ~ a ~ a[$ - 1];
		n += 2;

		int res = 0;
		int pos = 1;
		int val = a[pos];
		foreach (i; 1..n)
		{
			if (a[i] == a[i - 1])
			{
				int nextpos = i;
				int nextval = a[nextpos];
				int cur = 0;
				for (int lo = pos + 1, hi = nextpos - 2;
				    lo <= hi; lo++, hi--)
				{
					cur++;
					a[lo] = val;
					a[hi] = nextval;
				}
				res = max (res, cur);
				pos = nextpos;
				val = nextval;
			}
		}

		writeln (res);
		writefln ("%(%s %)", a[1..$ - 1]);
	}
}


Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.Assume that we have a cat with a number $$$x$$$. A perfect longcat is a cat with a number equal $$$2^m - 1$$$ for some non-negative integer $$$m$$$. For example, the numbers $$$0$$$, $$$1$$$, $$$3$$$, $$$7$$$, $$$15$$$ and so on are suitable for the perfect longcats.In the Cat Furrier Transform, the following operations can be performed on $$$x$$$:  (Operation A): you select any non-negative integer $$$n$$$ and replace $$$x$$$ with $$$x \oplus (2^n - 1)$$$, with $$$\oplus$$$ being a bitwise XOR operator. (Operation B): replace $$$x$$$ with $$$x + 1$$$. The first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B.Neko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most $$$40$$$ operations. Can you help Neko writing a transformation plan?Note that it is not required to minimize the number of operations. You just need to use no more than $$$40$$$ operations.

The only line contains a single integer $$$x$$$ ($$$1 \le x \le 10^6$$$).

The first line should contain a single integer $$$t$$$ ($$$0 \le t \le 40$$$) — the number of operations to apply. Then for each odd-numbered operation print the corresponding number $$$n_i$$$ in it. That is, print $$$\lceil \frac{t}{2} \rceil$$$ integers $$$n_i$$$ ($$$0 \le n_i \le 30$$$), denoting the replacement $$$x$$$ with $$$x \oplus (2^{n_i} - 1)$$$ in the corresponding step. If there are multiple possible answers, you can print any of them. It is possible to show, that there is at least one answer in the constraints of this problem.

NoteIn the first test, one of the transforms might be as follows: $$$39 \to 56 \to 57 \to 62 \to 63$$$. Or more precisely: Pick $$$n = 5$$$. $$$x$$$ is transformed into $$$39 \oplus 31$$$, or $$$56$$$.  Increase $$$x$$$ by $$$1$$$, changing its value to $$$57$$$.  Pick $$$n = 3$$$. $$$x$$$ is transformed into $$$57 \oplus 7$$$, or $$$62$$$.  Increase $$$x$$$ by $$$1$$$, changing its value to $$$63 = 2^6 - 1$$$. In the second and third test, the number already satisfies the goal requirement.

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

bool check (int i) {
  return 0 == ((i + 1) & i);
}

void main() {
  int x;
  readf (" %d", &x);
  int[] a;
  if (check (x)) {
    writeln (0);
    return;
  }
  foreach (ops; 0 .. 40) {
    debug stderr.writeln (x);
    if (ops & 1) {
      ++x;
    } else {
      int j = -1;
      foreach (i; 0 .. 30) {
        if (x & (1 << i)) {
          j = i;
        }
      }
      a ~= j + 1;
      x ^= (1 << (j + 1)) - 1;
    }
    if (check (x)) {
      writeln (ops + 1);
      writefln ("%(%s %)", a);
      return;
    }
  }
  enforce (false);
}

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

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

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

	ulong x = read.to!ulong;

	int t = 0;
	int[] ns = [];

	int i = 1;
	ulong m = 1;
	while(m <= x) m *= 2, i += 1;
	if(x == m - 1){
		t = 0, ns = [];
		writeln(t), writeln(ns.map!(to!string).join(" "));
		return;
	}
	else{
		while(m > 0){
			m /= 2, i -= 1;
			if(m & x) continue;
			if(m == 0) break;

			t += 1;
			ns ~= i;
			x ^= m * 2 - 1;
			if((x & (m * 2 - 1)) == m * 2 - 1) break;

			t += 1;
			x += 1;
		}
	}
	writeln(t);
	writeln(ns.map!(to!string).join(" "));
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto x = RD;

	long cnt;
	long[] ans;
	foreach (i; 0..20)
	{
		auto y = 1UL << (19 - i);
		if (x & y) continue;
		x = x ^ ((y << 1) - 1);
		ans ~= 20 - i;
		++cnt;
		if (x == (2^^20)-1) break;
		++x;
		++cnt;
	}

	debug writeln(x);

	writeln(cnt);
	if (cnt != 0)
	{
		write(ans[0]);
		foreach (e; ans[1..$])
			write(" ", e);
		writeln();
	}
	stdout.flush();
	debug readln();
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto x = RD;

	long cnt;
	long[] ans;
	foreach (i; 0..20)
	{
		auto y = 1UL << (19 - i);
		if (x & y) continue;
		x = x ^ ((y << 1) - 1);
		ans ~= 20 - i;
		++cnt;
		if (x == (2^^21)-1) break;
		++x;
		++cnt;
	}

	debug writeln(x);

	writeln(cnt);
	if (cnt != 0)
	{
		write(ans[0]);
		foreach (e; ans[1..$])
			write(" ", e);
		writeln();
	}
	stdout.flush();
	debug readln();
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto x = RD!int;

	long cnt;
	long[] ans;
	foreach (i; 0..20)
	{
		auto y = 1 << (19 - i);
		if (x & y) continue;
		x = x ^ y;
		ans ~= 21 - i;
		++cnt;
		if (x == (2^^20)-1) break;
		++x;
		++cnt;
	}

	debug writeln(x);

	writeln(cnt);
	if (cnt != 0)
	{
		write(ans[0]);
		foreach (e; ans[1..$])
			write(" ", e);
		writeln();
	}
	stdout.flush();
	debug readln();
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto x = RD;

	long cnt;
	long[] ans;
	foreach (i; 0..20)
	{
		auto y = 1UL << (19 - i);
		if (x & y) continue;
		x = x ^ ((y << 1) - 1);
		ans ~= 21 - i;
		++cnt;
		if (x == (2^^20)-1) break;
		++x;
		++cnt;
	}

	debug writeln(x);

	writeln(cnt);
	if (cnt != 0)
	{
		write(ans[0]);
		foreach (e; ans[1..$])
			write(" ", e);
		writeln();
	}
	stdout.flush();
	debug readln();
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto t = RD!int;

	long cnt;
	long[] ans;
	foreach (i; 0..6)
	{
		auto x = 1 << (5 - i);
		if (t & x) continue;
		t = t ^ x;
		ans ~= 7 - i;
		++cnt;
		if (t == 63) break;
		++t;
		++cnt;
	}

	debug writeln(t);

	writeln(cnt);
	if (cnt != 0)
	{
		write(ans[0]);
		foreach (e; ans[1..$])
			write(" ", e);
		writeln();
	}
	stdout.flush();
	debug readln();
}


Codeforces is a wonderful platform and one its feature shows how much someone contributes to the community. Every registered user has contribution — an integer number, not necessarily positive. There are n registered users and the i-th of them has contribution ti.Limak is a little polar bear and he's new into competitive programming. He doesn't even have an account in Codeforces but he is able to upvote existing blogs and comments. We assume that every registered user has infinitely many blogs and comments.  Limak can spend b minutes to read one blog and upvote it. Author's contribution will be increased by 5.  Limak can spend c minutes to read one comment and upvote it. Author's contribution will be increased by 1. Note that it's possible that Limak reads blogs faster than comments.Limak likes ties. He thinks it would be awesome to see a tie between at least k registered users. To make it happen he is going to spend some time on reading and upvoting. After that, there should exist an integer value x that at least k registered users have contribution exactly x.How much time does Limak need to achieve his goal?

The first line contains four integers n, k, b and c (2 ≤ k ≤ n ≤ 200 000, 1 ≤ b, c ≤ 1000) — the number of registered users, the required minimum number of users with the same contribution, time needed to read and upvote a blog, and time needed to read and upvote a comment, respectively. The second line contains n integers t1, t2, ..., tn (|ti| ≤ 109) where ti denotes contribution of the i-th registered user.

Print the minimum number of minutes Limak will spend to get a tie between at least k registered users.

NoteIn the first sample, there are 4 registered users and Limak wants a tie between at least 3 of them. Limak should behave as follows.  He spends 100 minutes to read one blog of the 4-th user and increase his contribution from 1 to 6.  Then he spends 4·30 = 120 minutes to read four comments of the 2-nd user and increase his contribution from 2 to 6 (four times it was increaded by 1). In the given scenario, Limak spends 100 + 4·30 = 220 minutes and after that each of users 2, 3, 4 has contribution 6.In the second sample, Limak needs 30 minutes to read a blog and 100 minutes to read a comment. This time he can get 3 users with contribution equal to 12 by spending 100 + 3·30 = 190 minutes:  Spend 2·30 = 60 minutes to read two blogs of the 1-st user to increase his contribution from 2 to 12.  Spend 30 + 100 minutes to read one blog and one comment of the 3-rd user. His contribution will change from 6 to 6 + 5 + 1 = 12.

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

immutable int MUCH = 10 ^^ 9;
immutable int BASE = 5;
static assert (MUCH % BASE == 0);

void main ()
{
	int n, k;
	long b, c;
	while (readf (" %s %s %s %s", &n, &k, &b, &c) > 0)
	{
		b = min (b, c * BASE);
		readln;
		auto t = readln.split.map !(to !(int)).array;
		sort (t);
		int [] [BASE] s;
		foreach (r; 0..BASE)
		{
			s[r] = t.filter !(x => (x + MUCH) % BASE == r).array;
		}

		long res = long.max;
		foreach (type; 0..BASE)
		{
			int [BASE] lo;
			int [BASE] hi;
			int total = 0;
			long cost = 0;

			void removeSome (int cur)
			{
				int p = -1;
				long z = -1;
				foreach (r; 0..BASE)
				{
					if (lo[r] < hi[r])
					{
						int delta = cur - s[r][lo[r]];
						int bd = delta / BASE;
						int cd = delta - bd * BASE;
						long add = bd * b + cd * c;
						if (z < add)
						{
							z = add;
							p = r;
						}
					}
				}
				assert (p != -1 && z != -1);
				cost -= z;
				lo[p]++;
				total--;
			}

			void process (int cur)
			{
				foreach (r; 0..BASE)
				{
					while (hi[r] < s[r].length &&
					    s[r][hi[r]] <= cur)
					{
						int delta = cur - s[r][hi[r]];
						int bd = delta / BASE;
						int cd = delta - bd * BASE;
						long add = bd * b + cd * c;
						cost += add;
						hi[r]++;
						total++;
						if (total > k)
						{
							removeSome (cur);
						}
						if (total >= k)
						{
							res = min (res, cost);
						}
					}
				}
			}

			int prev = type - MUCH - BASE;
			foreach (i; 0..n)
			{
				int cur = t[i];
				while ((cur + MUCH) % BASE != type)
				{
					cur++;
				}
				if (cur <= prev)
				{
					continue;
				}
				cost += total * b * (cur - prev) / BASE;
				prev = cur;
				process (cur);
			}
		}

		writeln (res);
	}
}

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

immutable int MUCH = 10 ^^ 9;
immutable int BASE = 5;
static assert (MUCH % BASE == 0);

void main ()
{
	int n, k;
	long b, c;
	while (readf (" %s %s %s %s", &n, &k, &b, &c) > 0)
	{
		b = min (b, c * BASE);
		readln;
		auto t = readln.split.map !(to !(int)).array;
		sort (t);
		int [] [BASE] s;
		foreach (r; 0..BASE)
		{
			s[r] = t.filter !(x => (x + MUCH) % BASE == r).array;
		}

		long res = long.max;
		foreach (type; 0..BASE)
		{
			int [BASE] lo;
			int [BASE] hi;
			int total = 0;
			long cost = 0;

			void removeSome (int cur)
			{
				int p = -1;
				long z = -1;
				foreach (r; 0..BASE)
				{
					if (lo[r] < hi[r])
					{
						int delta = cur - s[r][lo[r]];
						int bd = delta / BASE;
						int cd = delta - bd * BASE;
						long add = bd * b + cd * c;
						if (z < add)
						{
							z = add;
							p = r;
						}
					}
				}
				cost -= z;
				lo[p]++;
			}

			void process (int cur)
			{
				foreach (r; 0..BASE)
				{
					while (hi[r] < s[r].length &&
					    s[r][hi[r]] <= cur)
					{
						int delta = cur - s[r][hi[r]];
						int bd = delta / BASE;
						int cd = delta - bd * BASE;
						long add = bd * b + cd * c;
						cost += add;
						hi[r]++;
						total++;
						if (total > k)
						{
							removeSome (cur);
						}
						if (total >= k)
						{
							res = min (res, cost);
						}
					}
				}
			}

			int prev = type - MUCH - BASE;
			foreach (i; 0..n)
			{
				int cur = t[i];
				while ((cur + MUCH) % BASE != type)
				{
					cur++;
				}
				if (cur <= prev)
				{
					continue;
				}
				cost += total * b * (cur - prev) / BASE;
				prev = cur;
				process (cur);
			}
		}

		writeln (res);
	}
}


You are given an $$$n \times m$$$ table, consisting of characters «A», «G», «C», «T». Let's call a table nice, if every $$$2 \times 2$$$ square contains all four distinct characters. Your task is to find a nice table (also consisting of «A», «G», «C», «T»), that differs from the given table in the minimum number of characters.

First line contains two positive integers $$$n$$$ and $$$m$$$ — number of rows and columns in the table you are given ($$$2 \leq n, m, n \times m \leq 300\,000$$$). Then, $$$n$$$ lines describing the table follow. Each line contains exactly $$$m$$$ characters «A», «G», «C», «T».

Output $$$n$$$ lines, $$$m$$$ characters each. This table must be nice and differ from the input table in the minimum number of characters.

NoteIn the first sample, the table is already nice. In the second sample, you can change 9 elements to make the table nice.

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

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[0]; tokens.popFront; return token; }
int readInt() { return readToken().to!int; }
long readLong() { return readToken().to!long; }
real readReal() { return readToken().to!real; }

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

int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = cast(int)(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) => (a < val)); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a <= val)); }

immutable CS = "ACGT";

int M, N;
string[] A;

void main() {
  try {
    for (; ; ) {
      M = readInt();
      N = readInt();
      A = new string[M];
      foreach (x; 0 .. M) {
        A[x] = readToken();
      }
      auto rowCost = new int[][][](4, 4, M);
      auto colCost = new int[][][](4, 4, N);
      foreach (p; 0 .. 4) foreach (q; 0 .. 4) {
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          if (A[x][y] != CS[[p, q][y % 2]]) {
            ++rowCost[p][q][x];
          }
          if (A[x][y] != CS[[p, q][x % 2]]) {
            ++colCost[p][q][y];
          }
        }
      }
      int opt = M * N + 1;
      int[] permOpt;
      int dirOpt = -1;
      foreach (dir; 0 .. 2) {
        int[] perm = iota(4).array;
        do {
          int sum;
          if (dir == 0) {
            foreach (x; 0 .. M) {
              const p = perm[(x % 2) * 2 + 0];
              const q = perm[(x % 2) * 2 + 1];
              sum += min(rowCost[p][q][x], rowCost[q][p][x]);
            }
          } else {
            foreach (y; 0 .. N) {
              const p = perm[(y % 2) * 2 + 0];
              const q = perm[(y % 2) * 2 + 1];
              sum += min(colCost[p][q][y], colCost[q][p][y]);
            }
          }
          if (opt > sum) {
            opt = sum;
            permOpt = perm.dup;
            dirOpt = dir;
          }
        } while (perm.nextPermutation);
      }
      debug {
        writefln("opt = %s", opt);
        writefln("permOpt = %s", permOpt);
        writefln("dirOpt = %s", dirOpt);
      }
      auto ans = new char[][](M, N);
      if (dirOpt == 0) {
        foreach (x; 0 .. M) {
          int p = permOpt[(x % 2) * 2 + 0];
          int q = permOpt[(x % 2) * 2 + 1];
          if (rowCost[p][q][x] > rowCost[q][p][x]) {
            swap(p, q);
          }
          foreach (y; 0 .. N) {
            ans[x][y] = CS[[p, q][y % 2]];
          }
        }
      } else {
        foreach (y; 0 .. N) {
          int p = permOpt[(y % 2) * 2 + 0];
          int q = permOpt[(y % 2) * 2 + 1];
          if (colCost[p][q][y] > colCost[q][p][y]) {
            swap(p, q);
          }
          foreach (x; 0 .. M) {
            ans[x][y] = CS[[p, q][x % 2]];
          }
        }
      }
      int cnt;
      foreach (x; 0 .. M) foreach (y; 0 .. N) {
        if (A[x][y] != ans[x][y]) {
          ++cnt;
        }
      }
      assert(opt == cnt);
      foreach (x; 0 .. M) {
        foreach (y; 0 .. N) {
          write(ans[x][y]);
        }
        writeln();
      }
    }
  } catch (EOFException e) {
  }
}


Tonya was given an array of $$$a$$$ of length $$$n$$$ written on a postcard for his birthday. For some reason, the postcard turned out to be a cyclic array, so the index of the element located strictly to the right of the $$$n$$$-th is $$$1$$$. Tonya wanted to study it better, so he bought a robot "Burenka-179".A program for Burenka is a pair of numbers $$$(s, k)$$$, where $$$1 \leq s \leq n$$$, $$$1 \leq k \leq n-1$$$. Note that $$$k$$$ cannot be equal to $$$n$$$. Initially, Tonya puts the robot in the position of the array $$$s$$$. After that, Burenka makes exactly $$$n$$$ steps through the array. If at the beginning of a step Burenka stands in the position $$$i$$$, then the following happens:   The number $$$a_{i}$$$ is added to the usefulness of the program.  "Burenka" moves $$$k$$$ positions to the right ($$$i := i + k$$$ is executed, if $$$i$$$ becomes greater than $$$n$$$, then $$$i := i - n$$$). Help Tonya find the maximum possible usefulness of a program for "Burenka" if the initial usefulness of any program is $$$0$$$.Also, Tony's friend Ilyusha asks him to change the array $$$q$$$ times. Each time he wants to assign $$$a_p := x$$$ for a given index $$$p$$$ and a value $$$x$$$. You need to find the maximum possible usefulness of the program after each of these changes.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) is the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$0 \le q \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. The following $$$q$$$ lines contain changes, each of them contains two integers $$$p$$$ and $$$x$$$ ($$$1 \leq p \leq n$$$, $$$1 \leq x \leq 10^9$$$), meaning you should assign $$$a_p := x$$$. It is guaranteed that the sum of $$$n$$$ and the sum of $$$q$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$.

For each test case, output $$$q+1$$$ numbers — the maximum usefulness of a program initially and after each of the changes.

NoteIn the first test case, initially and after each request, the answer is achieved at $$$s = 1$$$, $$$k = 1$$$ or $$$s = 2$$$, $$$k = 1$$$.In the second test case, initially, the answer is achieved when $$$s = 1$$$, $$$k = 2$$$ or $$$s = 3$$$, $$$k = 2$$$. After the first request, the answer is achieved at $$$s = 2$$$, $$$k = 2$$$ or $$$s = 4$$$, $$$k = 2$$$.

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

    void main ()
    {
    	auto tests = readln.strip.to !(int);
    	foreach (test; 0..tests)
    	{
    		int n, q;
    		readf !(" %s %s") (n, q);

    		auto divs = [1];
    		int m = n;
    		for (int d = 2; d * d <= m; d++)
    		{
    			if (m % d == 0)
    			{
    				divs ~= n / d;
    				do
    				{
    					m /= d;
    				}
    				while (m % d == 0);
    			}
    		}
    		if (1 < m && m < n)
    		{
    			divs ~= n / m;
    		}
    		auto nDivs = divs.length.to !(int);

    		readln;
    		auto a = readln.splitter.map !(to !(int)).array;
    		auto c = new long [] [nDivs];
    		foreach (j, d; divs)
    		{
    			c[j] = new long [d * 2 + 2];
    			foreach (i; 0..n)
    			{
    				c[j][i % d + d] += a[i] * 1L * d;
    			}
    			foreach_reverse (k; 1..d)
    			{
    				c[j][k] = max (c[j][k * 2], c[j][k * 2 + 1]);
    			}
    		}

    		writeln (c.map !(line => line[1]).maxElement);
    		foreach (r; 0..q)
    		{
    			int i, x;
    			readf !(" %s %s") (i, x);
        		readln;
    			i -= 1;
    			auto delta = x - a[i];
    			foreach (j, d; divs)
    			{
    				int k = i % d + d;
    				c[j][k] += delta * 1L * d;
    				for (k >>= 1; k > 0; k >>= 1)
    				{
    					c[j][k] = max (c[j][k * 2],
    					    c[j][k * 2 + 1]);
    				}
    			}
    			a[i] = x;
    			writeln (c.map !(line => line[1]).maxElement);
    		}
    	}
    }

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, q;
		readf !(" %s %s") (n, q);

		auto divs = [1];
		int m = n;
		for (int d = 2; d * d <= m; d++)
		{
			if (m % d == 0)
			{
				divs ~= n / d;
				do
				{
					m /= d;
				}
				while (m % d == 0);
			}
		}
		if (1 < m && m < n)
		{
			divs ~= n / m;
		}
		auto nDivs = divs.length.to !(int);

/*
		auto a = new int [n];
		foreach (ref x; a)
		{
			readf !(" %s") (x);
		}
*/
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto c = new long [] [nDivs];
		foreach (j, d; divs)
		{
			c[j] = new long [d * 2 + 2];
			foreach (i; 0..n)
			{
				c[j][i % d + d] += a[i] * 1L * d;
			}
			foreach_reverse (k; 1..d)
			{
				c[j][k] = max (c[j][k * 2], c[j][k * 2 + 1]);
			}
		}

		writeln (c.map !(line => line[1]).maxElement);
		foreach (r; 0..q)
		{
			int i, x;
			readf !(" %s %s") (i, x);
			i -= 1;
			auto delta = x - a[i];
			foreach (j, d; divs)
			{
				int k = i % d + d;
				c[j][k] += delta * 1L * d;
				for (k >>= 1; k > 0; k >>= 1)
				{
					c[j][k] = max (c[j][k * 2],
					    c[j][k * 2 + 1]);
				}
			}
			a[i] = x;
			writeln (c.map !(line => line[1]).maxElement);
		}
	}
}