Let $$$a$$$ and $$$b$$$ be two arrays of lengths $$$n$$$ and $$$m$$$, respectively, with no elements in common. We can define a new array $$$\mathrm{merge}(a,b)$$$ of length $$$n+m$$$ recursively as follows:  If one of the arrays is empty, the result is the other array. That is, $$$\mathrm{merge}(\emptyset,b)=b$$$ and $$$\mathrm{merge}(a,\emptyset)=a$$$. In particular, $$$\mathrm{merge}(\emptyset,\emptyset)=\emptyset$$$.  If both arrays are non-empty, and $$$a_1<b_1$$$, then $$$\mathrm{merge}(a,b)=[a_1]+\mathrm{merge}([a_2,\ldots,a_n],b)$$$. That is, we delete the first element $$$a_1$$$ of $$$a$$$, merge the remaining arrays, then add $$$a_1$$$ to the beginning of the result.  If both arrays are non-empty, and $$$a_1>b_1$$$, then $$$\mathrm{merge}(a,b)=[b_1]+\mathrm{merge}(a,[b_2,\ldots,b_m])$$$. That is, we delete the first element $$$b_1$$$ of $$$b$$$, merge the remaining arrays, then add $$$b_1$$$ to the beginning of the result. This algorithm has the nice property that if $$$a$$$ and $$$b$$$ are sorted, then $$$\mathrm{merge}(a,b)$$$ will also be sorted. For example, it is used as a subroutine in merge-sort. For this problem, however, we will consider the same procedure acting on non-sorted arrays as well. For example, if $$$a=[3,1]$$$ and $$$b=[2,4]$$$, then $$$\mathrm{merge}(a,b)=[2,3,1,4]$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).There is a permutation $$$p$$$ of length $$$2n$$$. Determine if there exist two arrays $$$a$$$ and $$$b$$$, each of length $$$n$$$ and with no elements in common, so that $$$p=\mathrm{merge}(a,b)$$$.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases.  The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 2000$$$). The second line of each test case contains $$$2n$$$ integers $$$p_1,\ldots,p_{2n}$$$ ($$$1\le p_i\le 2n$$$). It is guaranteed that $$$p$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2000$$$.

For each test case, output "YES" if there exist arrays $$$a$$$, $$$b$$$, each of length $$$n$$$ and with no common elements, so that $$$p=\mathrm{merge}(a,b)$$$. Otherwise, output "NO".

NoteIn the first test case, $$$[2,3,1,4]=\mathrm{merge}([3,1],[2,4])$$$.In the second test case, we can show that $$$[3,1,2,4]$$$ is not the merge of two arrays of length $$$2$$$.In the third test case, $$$[3,2,6,1,5,7,8,4]=\mathrm{merge}([3,2,8,4],[6,1,5,7])$$$.In the fourth test case, $$$[1,2,3,4,5,6]=\mathrm{merge}([1,3,6],[2,4,5])$$$, for example.

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

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

		int [] d;
		int i = 0;
		while (i < n * 2)
		{
			int j = i;
			do
			{
				i += 1;
			}
			while (i < n * 2 && a[i] < a[j]);
			d ~= i - j;
		}

		auto f = new int [n * 2 + 1];
		f[] = int.max;
		f[0] = -1;
		foreach (int k, ref c; d)
		{
			for (int p = c; p <= n * 2; p++)
			{
				if (f[p] == int.max && f[p - c] < k)
				{
					f[p] = k;
				}
			}
		}
		writeln (f[n] < int.max ? "YES" : "NO");
	}
}

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

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

		int [] d;
		int i = 0;
		while (i < n * 2)
		{
			int j = i;
			do
			{
				i += 1;
			}
			while (i < n * 2 && a[i] < a[j]);
			d ~= i - j;
		}

		auto f = new bool [n * 2 + 1];
		f[0] = true;
		foreach (ref c; d)
			for (int p = n * 2; p >= c; p--)
				f[p] |= f[p - c];

		writeln (f[n] ? "YES" : "NO");
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        auto P = new int[2 * N + 1];
        foreach (i; 0 .. 2 * N) {
          P[i] = readInt();
        }
        P[2 * N] = 2 * N + 1;

        auto dp = new int[][](N + 1, N + 1);
        dp[0][0] = P[2 * N];
        foreach (s; 0 .. 2 * N) {
          foreach (a; 0 .. N + 1) {
            const b = s - a;
            if (0 <= b && b <= N) {
              if (dp[a][b] > 0) {
                const p = P[2 * N - (a + b) - 1];
                if (a < N && P[2 * N - (a + b) - 1] < dp[a][b]) {
                  chmax(dp[a + 1][b], dp[a][b]);
                }
                if (b < N && P[2 * N - (a + b) - 1] < P[2 * N - (a + b)]) {
                  chmax(dp[b + 1][a], P[2 * N - (a + b)]);
                }
              }
            }
          }
        }
        debug {
          foreach (a; 0 .. N + 1) {
            writeln(a, ": ", dp[a]);
          }
        }
        writeln((dp[N][N] > 0) ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int[] arr;
		int num, cnt;
		foreach (i; 0..n*2)
		{
			if (p[i] > num)
			{
				if (cnt != 0)
				{
					arr ~= cnt;
				}
				num = p[i];
				cnt = 0;
			}
			++cnt;
		}
		arr ~= cnt;
		debug writeln(arr);

		auto dp = new bool[](n+1);
		dp[0] = true;
		foreach (e; arr)
		{
			foreach_reverse (i; 0..dp.length)
			{
				if (!dp[i]) continue;
				auto ni = i + e;
				if (ni < n+1)
				{
					dp[ni] = true;
				}
			}
		}
		ans[ti] = dp[n];
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = 0 ~ readln.splitter.map !(to !(int)).array;
		auto f = new bool [] [] (2, n * 2 + 1);
		int b = 0;
		f[b][0] = true;
		foreach (i; 1..n * 2 + 1)
		{
			b ^= 1;
			f[b][] = false;
			foreach (j; 0..i)
			{
/*
				if (i - j > n)
				{
					continue;
				}
*/
				if (f[!b][j])
				{
					if (a[i - 1] < a[i] && i - j <= n)
					{
						f[b][j] = true;
					}
					if (a[j] < a[i])
					{
						f[b][i - 1] = true;
					}
				}
			}
		}
		writeln (f[b].any ? "YES" : "NO");
	}
}


People like to be fit. That's why many of them are ready to wake up at dawn, go to the stadium and run. In this problem your task is to help a company design a new stadium. The city of N has a shabby old stadium. Many people like it and every morning thousands of people come out to this stadium to run. The stadium can be represented as a circle, its length is exactly l meters with a marked start line. However, there can't be simultaneous start in the morning, so exactly at 7, each runner goes to his favorite spot on the stadium and starts running from there. Note that not everybody runs in the same manner as everybody else. Some people run in the clockwise direction, some of them run in the counter-clockwise direction. It mostly depends on the runner's mood in the morning, so you can assume that each running direction is equiprobable for each runner in any fixed morning. The stadium is tiny and is in need of major repair, for right now there only is one running track! You can't get too playful on a single track, that's why all runners keep the same running speed — exactly 1 meter per a time unit. Nevertheless, the runners that choose different directions bump into each other as they meet. The company wants to design a new stadium, but they first need to know how bad the old one is. For that they need the expectation of the number of bumpings by t time units after the running has begun. Help the company count the required expectation. Note that each runner chooses a direction equiprobably, independently from the others and then all runners start running simultaneously at 7 a.m. Assume that each runner runs for t time units without stopping. Consider the runners to bump at a certain moment if at that moment they found themselves at the same point in the stadium. A pair of runners can bump more than once.

The first line of the input contains three integers n, l, t (1 ≤ n ≤ 106, 1 ≤ l ≤ 109, 1 ≤ t ≤ 109). The next line contains n distinct integers a1, a2, ..., an (0 ≤ a1 < a2 < ... < an < l), here ai is the clockwise distance from the start line to the i-th runner's starting position.

Print a single real number — the answer to the problem with absolute or relative error of at most 10 - 6.

NoteThere are two runners in the first example. If the first runner run clockwise direction, then in 1 time unit he will be 1m away from the start line. If the second runner run counter-clockwise direction then in 1 time unit he will be also 1m away from the start line. And it is the only possible way to meet. We assume that each running direction is equiprobable, so the answer for the example is equal to 0.5·0.5 = 0.25.

import std.stdio;

void main() {
    int n;
    long l, t;
    readf(" %d %d %d", &n, &l, &t);
    auto a = new long[n];
    foreach (i; 0..n) scanf(" %d", &a[i]);

    long ans = 0;
    long q = 2 * t / l, r = 2 * t % l;
    for (int i, j, k; i < n; ++i) {
        while (a[i] - a[j] > r) ++j;
        while (l - (a[i] - a[k]) <= r) ++k;
        ans += 2 * (q + 1) * i - j - (i - k);
    }

    writefln("%.10f", ans / 4.0);
}

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

void main() {
    int n;
    long l, t;
    readf(" %d %d %d", &n, &l, &t);
    auto a = new long[n];
    foreach (i; 0..n) scanf(" %d", &a[i]);

    long ans = 0;
    long q = 2 * t / l, r = 2 * t % l;
    for (int i, j, k; i < n; ++i) {
        while (a[i] - a[j] > r) ++j;
        while (l - (a[i] - a[k]) <= r) ++k;
        ans += 2 * (q + 1) * i - j - (i - k);
    }

    writeln(ans / 4.0);
}


Polycarp was gifted an array $$$a$$$ of length $$$n$$$. Polycarp considers an array beautiful if there exists a number $$$C$$$, such that each number in the array occurs either zero or $$$C$$$ times. Polycarp wants to remove some elements from the array $$$a$$$ to make it beautiful.For example, if $$$n=6$$$ and $$$a = [1, 3, 2, 1, 4, 2]$$$, then the following options are possible to make the array $$$a$$$ array beautiful:   Polycarp removes elements at positions $$$2$$$ and $$$5$$$, array $$$a$$$ becomes equal to $$$[1, 2, 1, 2]$$$;  Polycarp removes elements at positions $$$1$$$ and $$$6$$$, array $$$a$$$ becomes equal to $$$[3, 2, 1, 4]$$$;  Polycarp removes elements at positions $$$1, 2$$$ and $$$6$$$, array $$$a$$$ becomes equal to $$$[2, 1, 4]$$$; Help Polycarp determine the minimum number of elements to remove from the array $$$a$$$ to make it beautiful.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case consists of one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — 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^9$$$) — array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer — the minimum number of elements that Polycarp has to remove from the array $$$a$$$ to make it beautiful.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		auto c = a.group.map !(q{a[1].to !(int)}).array;
		sort (c);
		int res = n;
		int k = c.length.to !(int);
		foreach (i; 0..k)
		{
			res = min (res, n - (k - i) * c[i]);
		}
		writeln (res);
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		auto c = a.group.map !(q{a[1].to !(int)}).array;
		sort (c);
		int res = n;
		int i = 0;
		int k = c.length.to !(int);
		foreach (num; 1..n + 1)
		{
			while (i < k && c[i] < num)
			{
				i += 1;
			}
			res = min (res, n - (k - i) * num);
		}
		writeln (res);
	}
}

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T); while (T--) {
        int N; get(N);
        int[] AA; get(AA);
        int[int] memo;
        foreach (a; AA) ++memo[a];
        int[] ps;
        foreach (_, v; memo) ps ~= v;
        sort!"a > b"(ps);
        int res = int.max, pre, s;
        foreach (i, p; ps) {
            s += p;
            if (i) pre += i.to!int * (ps[i - 1] - p);
            res = min(res, pre + N - s);
        }
        writeln(res);
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int[int] cnt;
		foreach (i; 0..n)
			++cnt[a[i]];

		int[int] cnt2;
		foreach (value; cnt.values)
			++cnt2[value];

		auto keys = cnt2.keys.sort;
		auto b = new long[](keys.length+1);
		auto c = new long[](keys.length+1);
		foreach (i; 0..keys.length)
		{
			auto key = keys[i];
			b[i+1] = b[i] + cnt2[key] * key;
			c[i+1] = c[i] + cnt2[key];
		}

		ans[ti] = long.max;
		foreach (i; 0..keys.length)
		{
			auto key = keys[i];
			long del = b[i] + b[$-1] - b[i+1];
			del -= (c[$-1] - c[i+1]) * key;
			ans[ti].chmin(del);
		}
	}

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


Levko loves strings of length n, consisting of lowercase English letters, very much. He has one such string s. For each string t of length n, Levko defines its beauty relative to s as the number of pairs of indexes i, j (1 ≤ i ≤ j ≤ n), such that substring t[i..j] is lexicographically larger than substring s[i..j].The boy wondered how many strings t are there, such that their beauty relative to s equals exactly k. Help him, find the remainder after division this number by 1000000007 (109 + 7).A substring s[i..j] of string s = s1s2... sn is string sisi  +  1... sj.String x  =  x1x2... xp is lexicographically larger than string y  =  y1y2... yp, if there is such number r (r < p), that x1  =  y1,  x2  =  y2,  ... ,  xr  =  yr and xr  +  1 > yr  +  1. The string characters are compared by their ASCII codes.

The first line contains two integers n and k (1 ≤ n ≤ 2000, 0 ≤ k ≤ 2000). The second line contains a non-empty string s of length n. String s consists only of lowercase English letters.

Print a single number — the answer to the problem modulo 1000000007 (109 + 7).

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

immutable int MN = 2010;
immutable int MK = 2010;
immutable long MD = 10^^9+7;

int main() {
    int n, k;
    string s;
    long[][] dp = new long[][](MN, MK);
    long[] sum = new long[](MK);
    readf("%d %d\n", &n, &k);
    s = chomp(readln());
    s ~= 'a';
    for (int i = 0; i <= n; i++) {
        dp[i][0] = 1;
    }
    for (int i = n; i >= 0; i--) {
        for (int u = 0; u <= k; u++) {
            sum[u] += dp[i+1][u]*(s[i]-'a');
            sum[u] %= MD;
            dp[i][u] += sum[u];
            dp[i][u] %= MD;
            for (int j = i-1; j >= 0; j--) {
                int d = u+(i-j)*(n-i+1);
                if (d > k) break;
                dp[j][d] += dp[i][u] * ('z'-s[i-1]);
                dp[j][d] %= MD;
            }
        }
    }
    writeln(dp[0][k]%MD);
    return 0;
}

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

immutable int MN = 2010;
immutable int MK = 2010;
immutable long MD = 10^^9+7;

int main() {
    int n, k;
    string s;
    long[MK][] dp = new long[MK][](MN);
    long[] sum = new long[](MK);
    readf("%d %d\n", &n, &k);
    s = chomp(readln());
    s ~= 'a';
    for (int i = 0; i <= n; i++) {
        dp[i][0] = 1;
    }
    for (int i = n; i >= 0; i--) {
        for (int u = 0; u <= k; u++) {
            sum[u] += dp[i+1][u]*(s[i]-'a');
            sum[u] %= MD;
            dp[i][u] += sum[u];
            dp[i][u] %= MD;
            for (int j = i-1; j >= 0; j--) {
                int d = u+(i-j)*(n-i+1);
                if (d > k) break;
                dp[j][d] += dp[i][u] * ('z'-s[i-1]);
                dp[j][d] %= MD;
            }
        }
    }
    writeln(dp[0][k]%MD);
    return 0;
}

import std.stdio, std.string, std.conv, std.algorithm, std.functional;
immutable int MN = 2010;
immutable long MD = 1^^9+7;
int n, k;
string s;

long[][] dp;
bool[][] used;

long solve(int i, int u) {
    if (i > n) return 0;
    if (u < 0) return 0;
    if (i == n) {
        if (u) {
            return 0;
        } else {
            return 1;
        }
    }
    if (used[i][u]) return dp[i][u];
    long r = 0;
    for (int j = i; j < n; j++) {
        r += solve(j+1, u-(j-i+1)*(n-j))*('z'-s[j]);
        r += solve(j+1, u)*(s[j]-'a');
    }
    if (!u) r++;
    r %= MD;
    dp[i][u] = r;
    used[i][u] = true;
    return r;
}

int main() {
    dp = new long[][](MN, MN);
    used = new bool[][](MN, MN);
    readf("%d %d\n", &n, &k);
    s = readln();
    writeln(solve(0, k));
    return 0;
}

import std.stdio, std.string, std.conv, std.algorithm, std.functional;
immutable int MN = 2010;
immutable long MD = 1^^9+7;
int n, k;
string s;

long[][] dp;
bool[][] used;

long solve(int i, int u) {
    if (i > n) return 0;
    if (u < 0) return 0;
    if (i == n) {
        if (u) {
            return 0;
        } else {
            return 1;
        }
    }
    if (used[i][u]) return dp[i][u];
    long r = 0;
    for (int j = i; j < n; j++) {
        r += solve(j+1, u-(j-i+1)*(n-j))*('z'-s[j]);
        r += solve(j+1, u)*(s[j]-'a');
    }
    if (!u) r++;
    dp[i][u] = r;
    used[i][u] = true;
    return r;
}

int main() {
    dp = new long[][](MN, MN);
    used = new bool[][](MN, MN);
    readf("%d %d\n", &n, &k);
    s = readln();
    writeln(solve(0, k));
    return 0;
}


A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).Killjoy's account is already infected and has a rating equal to $$$x$$$. Its rating is constant. There are $$$n$$$ accounts except hers, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th account's initial rating is $$$a_i$$$. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.Contests are regularly held on Codeforces. In each contest, any of these $$$n$$$ accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.Find out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.It can be proven that all accounts can be infected in some finite number of contests.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. The next $$$2t$$$ lines contain the descriptions of all test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$2 \le n \le 10^3$$$, $$$-4000 \le x \le 4000$$$) — the number of accounts on Codeforces and the rating of Killjoy's account. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(-4000 \le a_i \le 4000)$$$ — the ratings of other accounts.

For each test case output the minimal number of contests needed to infect all accounts.

NoteIn the first test case it's possible to make all ratings equal to $$$69$$$. First account's rating will increase by $$$1$$$, and second account's rating will decrease by $$$1$$$, so the sum of all changes will be equal to zero.In the second test case all accounts will be instantly infected, because all ratings (including Killjoy's account's rating) are equal to $$$4$$$.

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    long n = rd;
    long x = rd;
    ll[] arr = rdarr;
    ll summ = 0;
    bool aleq = 1, oneq = 0;
    foreach(el; arr){
        summ += el;
        if(el != x) aleq = 0;
        else oneq = 1;
    }
    if(aleq){
        writeln(0);
    }else if(summ == n*x || oneq){
        writeln(1);
    }else{
        writeln(2);
    }
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}

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

void solve()
{
    auto nx = readln.split.to!(int[]);
    auto N = nx[0];
    auto X = nx[1];
    int sum_a, infected;
    bool all_same = true;
    foreach (a; readln.split.to!(int[])) {
        if (a != X) all_same = false;
        if (a == X) ++infected;
        sum_a += a;
    }
    if (all_same) {
        writeln(0);
    } else if (X*N == sum_a) {
        writeln(1);
    } else if (infected == 0) {
        writeln(2);
    } else {
        writeln(1);
    }
}

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        solve();
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		bool allX = true;
		bool hasX;
		foreach (i; 0..n)
		{
			if (a[i] != x)
				allX = false;
			else
				hasX = true;
		}
		if (allX) continue;

		if (hasX)
		{
			ans[ti] = 1;
		}
		else
		{
			long tot;
			foreach (i; 0..n)
				tot += a[i];
			if (tot / n == x && tot % n == 0)
				ans[ti] = 1;
			else
				ans[ti] = 2;
		}
	}

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

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    long n = rd;
    long x = rd;
    ll[] arr = rdarr;
    ll summ = 0;
    bool aleq = 1;
    foreach(el; arr){
        summ += el;
        if(el != x) aleq = 0;
    }
    if(aleq){
        writeln(0);
    }else if(summ == n*x){
        writeln(1);
    }else{
        writeln(2);
    }
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}


The All-Berland Team Programming Contest will take place very soon. This year, teams of four are allowed to participate.There are $$$a$$$ programmers and $$$b$$$ mathematicians at Berland State University. How many maximum teams can be made if:  each team must consist of exactly $$$4$$$ students,  teams of $$$4$$$ mathematicians or $$$4$$$ programmers are unlikely to perform well, so the decision was made not to compose such teams. Thus, each team must have at least one programmer and at least one mathematician.Print the required maximum number of teams. Each person can be a member of no more than one team.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases. This is followed by descriptions of $$$t$$$ sets, one per line. Each set is given by two integers $$$a$$$ and $$$b$$$ ($$$0 \le a,b \le 10^9$$$).

Print $$$t$$$ lines. Each line must contain the answer to the corresponding set of input data — the required maximum number of teams.

NoteIn the first test case of the example, two teams can be composed. One way to compose two teams is to compose two teams of $$$2$$$ programmers and $$$2$$$ mathematicians.In the second test case of the example, only one team can be composed: $$$3$$$ programmers and $$$1$$$ mathematician in the team.

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long a, b;
    readf!" %d %d "(a, b);
    if (a > b)
      swap(a, b);
    writeln(min((a + b) / 4, a));
  }
}

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 a, b;
		readf !(" %s %s") (a, b);
		writeln (min (a, b, (a + b) / 4));
	}
}


Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode). procedure bubbleSortGraph()    build a graph G with n vertices and 0 edges    repeat        swapped = false        for i = 1 to n - 1 inclusive do:            if a[i] > a[i + 1] then                add an undirected edge in G between a[i] and a[i + 1]                swap( a[i], a[i + 1] )                swapped = true            end if        end for    until not swapped     /* repeat the algorithm as long as swapped value is true. */ end procedureFor a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.

The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).

Output a single integer — the answer to the problem.

NoteConsider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].

import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.numeric;
import std.range;
import std.stdio;
import std.typecons;

immutable int MAX_N = 100_005;
immutable int MAX_C = 0x3F3F3F3F;
immutable int NA    = -1;

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

		auto h = new int [n + 2];
		h[0] = -1;
		h[1..$] = n + 1;
		int res = 0;
		foreach (i; 0..n)
		{
			int lo = 0;
			int hi = n;
			while (lo < hi)
			{
				int me = (lo + hi + 1) >> 1;
				if (h[me] > a[i])
				{
					hi = me - 1;
				}
				else
				{
					lo = me;
				}
			}
			lo++;
			enforce (h[lo] > a[i]);
			h[lo] = a[i];
			res = max (res, lo);
			debug {writefln ("%s %s", h, lo);}
		}

		writeln (res);
	}
}

import std.stdio;

int[100000] b;
int c = 0;

void main() {
  int n;
  for (readf("%d", &n); n >= 1; --n) {
    int a;
    readf(" %d", &a);
    int l = 0;
    int r = c;
    while (l < r) {
      int m = l + r >> 1;
      if (a < b[m])
        r = m;
      else
        l = m + 1;
    }
    if (r == c)
      ++c;
    b[r] = a;
  }
  writeln(c);
}


Carousel Boutique is busy again! Rarity has decided to visit the pony ball and she surely needs a new dress, because going out in the same dress several times is a sign of bad manners. First of all, she needs a dress pattern, which she is going to cut out from the rectangular piece of the multicolored fabric.The piece of the multicolored fabric consists of $$$n \times m$$$ separate square scraps. Since Rarity likes dresses in style, a dress pattern must only include scraps sharing the same color. A dress pattern must be the square, and since Rarity is fond of rhombuses, the sides of a pattern must form a $$$45^{\circ}$$$ angle with sides of a piece of fabric (that way it will be resembling the traditional picture of a rhombus).Examples of proper dress patterns:  Examples of improper dress patterns:  The first one consists of multi-colored scraps, the second one goes beyond the bounds of the piece of fabric, the third one is not a square with sides forming a $$$45^{\circ}$$$ angle with sides of the piece of fabric.Rarity wonders how many ways to cut out a dress pattern that satisfies all the conditions that do exist. Please help her and satisfy her curiosity so she can continue working on her new masterpiece!

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2000$$$). Each of the next $$$n$$$ lines contains $$$m$$$ characters: lowercase English letters, the $$$j$$$-th of which corresponds to scrap in the current line and in the $$$j$$$-th column. Scraps having the same letter share the same color, scraps having different letters have different colors.

Print a single integer: the number of ways to cut out a dress pattern to satisfy all of Rarity's conditions.

NoteIn the first example, all the dress patterns of size $$$1$$$ and one of size $$$2$$$ are satisfactory.In the second example, only the dress patterns of size $$$1$$$ are satisfactory.

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

immutable int maxSide = 2002;
immutable int infinity = int.max / 2;

alias Array2D = int [maxSide] [maxSide];

void main ()
{
	Array2D s, f, b;
	int rows, cols;
	while (readf !(" %s %s") (rows, cols) > 0)
	{
		readln;
		s[0][0..cols + 2] = infinity;
		foreach (row; 1..rows + 1)
		{
			s[row][0..cols + 2] = infinity ~
			    readln.strip.map !(to !(int)).array ~ infinity;
		}
		s[rows + 1][0..cols + 2] = infinity;
		foreach (row; 0..rows + 2)
		{
			f[row][0..cols + 2] = infinity;
		}

		void rotate90 (ref Array2D a)
		{
			foreach (row; 0..rows + 2)
			{
				foreach (col; 0..cols + 2)
				{
					b[row][col] = a[col][rows + 1 - row];
				}
			}
			foreach (row; 0..rows + 2)
			{
				foreach (col; 0..cols + 2)
				{
					a[row][col] = b[row][col];
				}
			}
		}

		foreach (side; 0..4)
		{
			foreach (row; 1..rows + 1)
			{
				foreach (col; 1..cols + 1)
				{
					if (s[row][col] != s[row - 1][col] ||
					    s[row][col] != s[row][col - 1])
					{
						f[row][col] = 1;
					}
					else
					{
						f[row][col] = min (f[row][col],
						    f[row - 1][col] + 1,
						    f[row][col - 1] + 1);
					}
				}
			}
			swap (rows, cols);
			rotate90 (f);
			rotate90 (s);

			debug {writefln !("%(%-(%s %)\n%)") (f[1..rows + 1].map
			    !(line => line[1..cols + 1].map !(x =>
			    (x == infinity) ? "*" : x.text)));}
		}

		long res = 0;
		foreach (row; 1..rows + 1)
		{
			foreach (col; 1..cols + 1)
			{
				res += f[row][col];
			}
		}
		writeln (res);
	}
}


The elections in which three candidates participated have recently ended. The first candidate received $$$a$$$ votes, the second one received $$$b$$$ votes, the third one received $$$c$$$ votes. For each candidate, solve the following problem: how many votes should be added to this candidate so that he wins the election (i.e. the number of votes for this candidate was strictly greater than the number of votes for any other candidate)?Please note that for each candidate it is necessary to solve this problem independently, i.e. the added votes for any candidate do not affect the calculations when getting the answer for the other two candidates.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three integers $$$a$$$, $$$b$$$, and $$$c$$$ ($$$0 \le a,b,c \le 10^9$$$).

For each test case, output in a separate line three integers $$$A$$$, $$$B$$$, and $$$C$$$ ($$$A, B, C \ge 0$$$) separated by spaces — the answers to the problem for the first, second, and third candidate, respectively.

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

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long a,b,c;
        scanf("%lld %lld %lld\n", &a, &b, &c);
        writeln(max(0, max(b,c) - a + 1), ' ', max(0, max(a,c) - b + 1), ' ', max(0, max(a,b) - c + 1));
    }
}


John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.

A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.

In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.

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.datetime.stopwatch;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int MX_SZ = 100;

int binCoef(int n, int k) {
    int ans = 1;
    foreach (i; 1 .. k+1) {
        ans *= n - i + 1;
        ans /= i;
    }

    return ans;
}

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

    auto ans = new int[MX_SZ][MX_SZ];

    int cqSz = 3;
    while (binCoef(cqSz+1, 3) <= k) { ++cqSz; }

    foreach (i; 0 .. cqSz) {
        foreach (j; 0 .. cqSz) {
            if (i == j) { continue; }
            ans[i][j] = 1;
        }
    }

    int lft = k - binCoef(cqSz, 3);

    int idx = cqSz;
    while (lft > 0) {
        ans[0][idx] = ans[idx][0] = 1;

        debug { writeln(lft, ' ', idx); }

        int pos = 1;
        while (pos <= lft && pos < cqSz) {
            ans[pos][idx] = ans[idx][pos] = 1;
            lft -= pos;
            ++pos;
        }

        ++idx;
    }

    writeln(MX_SZ);
    ans.each!(line => line.writefln!"%(%s%)");
}

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.datetime.stopwatch;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int MX_SZ = 100;

int binCoef(int n, int k) {
    int ans = 1;
    foreach (i; 1 .. k+1) {
        ans *= n - i + 1;
        ans /= i;
    }

    return ans;
}

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

    auto ans = new int[MX_SZ][MX_SZ];

    int cqSz = 3;
    while (binCoef(cqSz+1, 3) <= k) { ++cqSz; }

    foreach (i; 0 .. cqSz) {
        foreach (j; 0 .. cqSz) {
            if (i == j) { continue; }
            ans[i][j] = 1;
        }
    }

    int lft = k - binCoef(cqSz, 3);

    int idx = cqSz;
    while (lft > 0) {
        ans[0][idx] = ans[idx][0] = 1;

        debug { writeln(lft, ' ', idx); }

        int p = 1, cur = 1;
        while (cur <= lft && p < cqSz) {
            ans[p][idx] = ans[idx][p] = 1;
            lft -= cur;
            ++p;
            cur = p;

            debug { writeln("in ", cur, ' ', lft); }
        }

        ++idx;
    }

    writeln(MX_SZ);
    ans.each!(line => line.writefln!"%(%s%)");
}

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.datetime.stopwatch;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

int binCoef(int n, int k) {
    int ans = 1;
    foreach (i; 1 .. k+1) {
        ans *= n - i + 1;
        ans /= i;
    }

    return ans;
}

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

    auto ans = new int[100][100];

    int cqSz = 3;
    while (binCoef(cqSz+1, 3) <= k) { ++cqSz; }

    foreach (i; 0 .. cqSz) {
        foreach (j; 0 .. cqSz) {
            if (i == j) { continue; }
            ans[i][j] = 1;
        }
    }

    int lft = k - binCoef(cqSz, 3);

    int idx = cqSz;
    while (lft > 0) {
        ans[0][idx] = ans[idx][0] = 1;

        int p = 1, cur = 1;
        while (cur <= lft && p < cqSz) {
            ans[p][idx] = ans[idx][p] = 1;
            lft -= cur;
            ++p;
            cur = binCoef(p+1, 2);
        }

        ++idx;
    }

    writeln(100);
    ans.each!(line => line.writefln!"%(%s%)");
}


Some time ago Mister B detected a strange signal from the space, which he started to study.After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation.Let's define the deviation of a permutation p as .Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them.Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example:  k = 0: shift p1, p2, ... pn,  k = 1: shift pn, p1, ... pn - 1,  ...,  k = n - 1: shift p2, p3, ... pn, p1.

First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct.

Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them.

NoteIn the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well.In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift.In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts.

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 P = new int[N];
      foreach (i; 0 .. N) {
        P[i] = readInt() - 1;
      }

      long ans = long.max;
      int km = -1;

      long now;
      long posi, nega;
      int offset;
      auto cnt = new int[4 * N + 1];
      void add(int val) {
        now += abs(offset + val);
        (offset + val >= 0) ? ++posi : ++nega;
        ++cnt[2 * N + val];
      }
      void rem(int val) {
        now -= abs(offset + val);
        (offset + val >= 0) ? --posi : --nega;
        --cnt[2 * N + val];
      }

      foreach (i; 0 .. N) {
        add(P[i] - i);
      }
      foreach (k; 0 .. N) {
        debug {
          writeln(k, ": ", now);
        }
        if (chmin(ans, now)) {
          km = k;
        }
        rem(P[N - 1 - k] - (N - 1 - k));
        posi -= cnt[2 * N - offset];
        nega += cnt[2 * N - offset];
        now -= posi;
        now += nega;
        --offset;
        add(P[N - 1 - k] - (N - 1 - k) + N);
      }
      writeln(ans, " ", km);

      debug {
        long brt = long.max;
        int brtkm = -1;
        foreach (k; 0 .. N) {
          long cost;
          foreach (i; 0 .. N) {
            cost += abs(P[i] - (k + i) % N);
          }
          debug {
            writeln("brt ", k, ": ", cost);
          }
          if (chmin(brt, cost)) {
            brtkm = k;
          }
        }
        writeln("brt: ", brt, " ", brtkm);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  alias Ev = Tuple!(int, long, long);
  auto n = next!long;
  auto p = next!long(n);
  p[] -= 1;
  auto dpt = new long[](cast(size_t)n); // delta per time
  void calcdpt(long i, long pi)
  {
    auto ts = redBlackTree!long([0]);
    if (pi >= i) ts.insert(pi - i);
    else ts.insert(n - i + pi);
    ts.insert(n - 1 - i);
    ts.insert(n - i);
    auto pd = long(0);
    debug auto tdpt = new long[](cast(size_t) n);
    foreach(t; ts)
      if (t < n)
	{
	  auto val = abs((i + 1 + t) % n - pi) - abs((i + t) % n - pi);
	  auto toadd = val - pd;
	  dpt[cast(size_t)t] += toadd;
	  debug tdpt[cast(size_t)t] += toadd;
	  pd = val;
	}
    long delta = 0;
    debug writeln("after adding ", i, " ", pi);
    debug foreach(t; 0 .. n)
      {
	write(abs((i + 1 + t)%n - pi) - abs((i + t)%n - pi), " ");
      }
    debug writeln;
    debug foreach(t; 0 .. n)
      {
	delta += tdpt[cast(size_t)t];
	write(delta, " ");
      }
    debug writeln;
  }
  foreach(i, pi; p)
    calcdpt(cast(long) i, pi);
  long deviation = iota(0, n).map!(i => abs(i - p[cast(size_t)i])).sum;
  long bestdeviation = deviation;
  long besttime = 0;
  long delta = dpt[0];

  long dev = deviation;
  long accdelta = dpt[0];
  debug write(dev, " ");
  debug foreach(t; 1 .. n)
    {
      dev += accdelta;
      write(dev, "(", iota(0, n).map!(i => abs((i + t) % n - p[cast(size_t)i])).sum, ") ");
      accdelta += dpt[cast(size_t)t];
    }
  writeln;
  foreach(t; 1 .. n)
    {
      deviation += delta;
      if (deviation < bestdeviation)
	{
	  bestdeviation = deviation;
	  besttime = t;
	}
      delta += dpt[cast(size_t)t];
    }
  writeln(bestdeviation, " ", besttime);
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

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

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  alias Ev = Tuple!(int, int, int);
  auto n = next!int;
  auto p = next!int(n);
  p[] -= 1;
  auto dpt = new int[](n); // delta per time
  void calcdpt(int i, int pi)
  {
    auto ts = redBlackTree!int([0]);
    if (pi >= i) ts.insert(pi - i);
    else ts.insert(n - i + pi);
    ts.insert(n - 1 - i);
    ts.insert(n - i);
    auto pd = int(0);
    foreach(t; ts)
      if (t < n)
	{
	  dpt[t] += abs((i + 1 + t) % n - pi) - abs((i + t) % n - pi) - pd;
	  pd = dpt[t];
	}
  }
  foreach(i, pi; p)
    calcdpt(cast(int) i, pi);
  long deviation = iota(0, n).map!(i => abs(i - p[i])).sum;
  long bestdeviation = deviation;
  int besttime = 0;
  long delta = 0;
  foreach(t; 0 .. n)
    {
      deviation += delta;
      if (deviation < bestdeviation)
	{
	  bestdeviation = deviation;
	  besttime = t;
	}
      delta += dpt[t];
    }
  writeln(bestdeviation, " ", besttime);
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

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

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  alias Ev = Tuple!(int, int, int);
  auto n = next!int;
  auto p = next!int(n);
  p[] -= 1;
  auto dpt = new int[](n); // delta per time
  void calcdpt(int i, int pi)
  {
    auto ts = redBlackTree!int([0]);
    if (pi >= i) ts.insert(pi - i);
    else ts.insert(n - i + pi);
    ts.insert(n - 1 - i);
    ts.insert(n - i);
    auto pd = int(0);
    debug auto tdpt = new int[](n);
    foreach(t; ts)
      if (t < n)
	{
	  auto val = abs((i + 1 + t) % n - pi) - abs((i + t) % n - pi);
	  auto toadd = val - pd;
	  dpt[t] += toadd;
	  debug tdpt[t] += toadd;
	  pd = val;
	}
    long delta = 0;
    debug writeln("after adding ", i, " ", pi);
    debug foreach(t; 0 .. n)
      {
	write(abs((i + 1 + t)%n - pi) - abs((i + t)%n - pi), " ");
      }
    debug writeln;
    debug foreach(t; 0 .. n)
      {
	delta += tdpt[t];
	write(delta, " ");
      }
    debug writeln;
  }
  foreach(i, pi; p)
    calcdpt(cast(int) i, pi);
  long deviation = iota(0, n).map!(i => abs(i - p[i])).sum;
  long bestdeviation = deviation;
  int besttime = 0;
  long delta = dpt[0];

  long dev = deviation;
  long accdelta = dpt[0];
  debug write(dev, " ");
  debug foreach(t; 1 .. n)
    {
      dev += accdelta;
      write(dev, "(", iota(0, n).map!(i => abs((i + t) % n - p[i])).sum, ") ");
      accdelta += dpt[t];
    }
  writeln;
  foreach(t; 1 .. n)
    {
      deviation += delta;
      if (deviation < bestdeviation)
	{
	  bestdeviation = deviation;
	  besttime = t;
	}
      delta += dpt[t];
    }
  writeln(bestdeviation, " ", besttime);
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


You still have partial information about the score during the historic football match. You are given a set of pairs $$$(a_i, b_i)$$$, indicating that at some point during the match the score was "$$$a_i$$$: $$$b_i$$$". It is known that if the current score is «$$$x$$$:$$$y$$$», then after the goal it will change to "$$$x+1$$$:$$$y$$$" or "$$$x$$$:$$$y+1$$$". What is the largest number of times a draw could appear on the scoreboard?The pairs "$$$a_i$$$:$$$b_i$$$" are given in chronological order (time increases), but you are given score only for some moments of time. The last pair corresponds to the end of the match.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10000$$$) — the number of known moments in the match. Each of the next $$$n$$$ lines contains integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \le a_i, b_i \le 10^9$$$), denoting the score of the match at that moment (that is, the number of goals by the first team and the number of goals by the second team). All moments are given in chronological order, that is, sequences $$$x_i$$$ and $$$y_j$$$ are non-decreasing. The last score denotes the final result of the match.

Print the maximum number of moments of time, during which the score was a draw. The starting moment of the match (with a score 0:0) is also counted.

NoteIn the example one of the possible score sequences leading to the maximum number of draws is as follows: 0:0, 1:0, 2:0, 2:1, 3:1, 3:2, 3:3, 3:4.

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

void main() {
    auto N = readln.chomp.to!int;
    auto AB = N.iota.map!(_ => readln.split.map!(to!long).array).array;

    long x = 0;
    long y = 0;
    long ans = 1;

    foreach (i; 0..N) {
        long a = AB[i][0];
        long b = AB[i][1];
        if (x > y) {
            if (b < x) {

            } else {
                ans += min(a, b) - x + 1;
            }
        } else if (x < y) {
            if (a < y) {

            } else {
                ans += min(a, b) - y + 1;
            }
        } else {
            ans += min(a, b) - x;
        }

        x = AB[i][0];
        y = AB[i][1];
    }

    ans.writeln;
}


You are given a system of pipes. It consists of two rows, each row consists of $$$n$$$ pipes. The top left pipe has the coordinates $$$(1, 1)$$$ and the bottom right — $$$(2, n)$$$.There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types:  Types of pipes You can turn each of the given pipes $$$90$$$ degrees clockwise or counterclockwise arbitrary (possibly, zero) number of times (so the types $$$1$$$ and $$$2$$$ can become each other and types $$$3, 4, 5, 6$$$ can become each other).You want to turn some pipes in a way that the water flow can start at $$$(1, 0)$$$ (to the left of the top left pipe), move to the pipe at $$$(1, 1)$$$, flow somehow by connected pipes to the pipe at $$$(2, n)$$$ and flow right to $$$(2, n + 1)$$$.Pipes are connected if they are adjacent in the system and their ends are connected. Here are examples of connected pipes:  Examples of connected pipes Let's describe the problem using some example:  The first example input And its solution is below:   The first example answer As you can see, the water flow is the poorly drawn blue line. To obtain the answer, we need to turn the pipe at $$$(1, 2)$$$ $$$90$$$ degrees clockwise, the pipe at $$$(2, 3)$$$ $$$90$$$ degrees, the pipe at $$$(1, 6)$$$ $$$90$$$ degrees, the pipe at $$$(1, 7)$$$ $$$180$$$ degrees and the pipe at $$$(2, 7)$$$ $$$180$$$ degrees. Then the flow of water can reach $$$(2, n + 1)$$$ from $$$(1, 0)$$$.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Then $$$q$$$ queries follow. Each query consists of exactly three lines. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of pipes in each row. The next two lines contain a description of the first and the second rows correspondingly. Each row description consists of $$$n$$$ digits from $$$1$$$ to $$$6$$$ without any whitespaces between them, each digit corresponds to the type of pipe in the corresponding cell. See the problem statement to understand which digits correspond to which types of pipes. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For the $$$i$$$-th query print the answer for it — "YES" (without quotes) if it is possible to turn some pipes in a way that the water flow can reach $$$(2, n + 1)$$$ from $$$(1, 0)$$$, and "NO" otherwise.

NoteThe first query from the example is described in the problem statement.

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new bool[](q);
	foreach (i; 0..q)
	{
		auto n = RD!int;
		auto a = RD!string;
		auto b = RD!string;
		int pos;
		ans[i] = true;
		foreach (j; 0..n)
		{
			if (pos == 0)
			{
				if ([a[j]].to!int >= 3)
				{
					if ([b[j]].to!int <= 2)
					{
						ans[i] = false;
						break;
					}
					pos = 1;
				}
			}
			else
			{
				if ([b[j]].to!int >= 3)
				{
					if ([a[j]].to!int <= 2)
					{
						ans[i] = false;
						break;
					}
					pos = 0;
				}
			}
		}
		if (pos == 0)
			ans[i] = false;
	}

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


Lunar New Year is approaching, and you bought a matrix with lots of "crosses".This matrix $$$M$$$ of size $$$n \times n$$$ contains only 'X' and '.' (without quotes). The element in the $$$i$$$-th row and the $$$j$$$-th column $$$(i, j)$$$ is defined as $$$M(i, j)$$$, where $$$1 \leq i, j \leq n$$$. We define a cross appearing in the $$$i$$$-th row and the $$$j$$$-th column ($$$1 < i, j < n$$$) if and only if $$$M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = $$$ 'X'.The following figure illustrates a cross appearing at position $$$(2, 2)$$$ in a $$$3 \times 3$$$ matrix. X.X.X.X.X Your task is to find out the number of crosses in the given matrix $$$M$$$. Two crosses are different if and only if they appear in different rows or columns.

The first line contains only one positive integer $$$n$$$ ($$$1 \leq n \leq 500$$$), denoting the size of the matrix $$$M$$$. The following $$$n$$$ lines illustrate the matrix $$$M$$$. Each line contains exactly $$$n$$$ characters, each of them is 'X' or '.'. The $$$j$$$-th element in the $$$i$$$-th line represents $$$M(i, j)$$$, where $$$1 \leq i, j \leq n$$$.

Output a single line containing only one integer number $$$k$$$ — the number of crosses in the given matrix $$$M$$$.

NoteIn the first sample, a cross appears at $$$(3, 3)$$$, so the answer is $$$1$$$.In the second sample, no crosses appear since $$$n < 3$$$, so the answer is $$$0$$$.In the third sample, crosses appear at $$$(3, 2)$$$, $$$(3, 4)$$$, $$$(4, 3)$$$, $$$(4, 5)$$$, so the answer is $$$4$$$.

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

immutable long MOD = 998244353;

void main() {
    auto N = readln.chomp.to!int;
    auto S = N.iota.map!(_ => readln.chomp).array;
    int ans = 0;
    int[] dr = [0, -1, -1, 1, 1];
    int[] dc = [0, -1, 1, -1, 1];

    foreach (r; 1..N-1) {
        foreach (c; 1..N-1) {
            int ok = 1;
            foreach (k; 0..5) {
                int nr = r + dr[k];
                int nc = c + dc[k];
                if (S[nr][nc] == '.') {
                    ok = 0;
                    break;
                }
            }
            ans += ok;
        }
    }

    ans.writeln;
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n=readln.chomp.to!int;
    auto a=new string[n];
    foreach(i;0..n)
        a[i]=readln.strip;
    int ans=0;
    foreach(i;1..n-1)
        foreach(j;1..n-1)
            if(a[i][j]=='X'
                && a[i-1][j-1]=='X'
                && a[i-1][j+1]=='X'
                && a[i+1][j-1]=='X'
                && a[i+1][j+1]=='X')
                ans++;
    writeln(ans);
}

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;

int[] di = [1, 1, -1, -1];
int[] dj = [1, -1, 1, -1];

void main() {
    int n;
    scan(n);
    auto m = iota(n).map!(i => readln.chomp).array;
    int ans;

    foreach (i ; 1 .. n - 1) {
        foreach (j ; 1 .. n - 1) {
            if (m[i][j] != 'X') continue;
            bool ok = true;
            foreach (k ; 0 .. 4) {
                int ni = i + di[k];
                int nj = j + dj[k];
                if (m[ni][nj] != 'X') {
                    ok = false;
                    break;
                }
            }
            ans += ok;
        }
    }

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


For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing:   Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$.  Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$.  This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.

NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case,   $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.

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

immutable int mod = 998_244_353;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto f = new long [n];
		auto c = new long [n];
		long total = 0;
		foreach (k; 0..n)
		{
			int cur = a[k];
			int i;
			for (i = k - 1; i >= 0; i--)
			{
				int parts = (a[i] + cur - 1) / cur;
				cur = a[i] / parts;
				auto key = cast (long) cur << 32 | parts;
				if (key == c[i])
				{
					break;
				}
				f[i] = parts - 1;
				c[i] = key;
			}
			for (i++; i <= k; i++)
			{
				if (i > 0)
				{
					f[i] = (f[i] * (i + 1) +
					    f[i - 1]) % mod;
				}
			}
			total = (total + f[k]) % mod;
		}
		writeln (total);
	}
}

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

immutable int mod = 998_244_353;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto f = new long [n];
		auto c = new long [n];
		long total = 0;
		foreach (k; 0..n)
		{
			int cur = a[k];
			int i;
			for (i = k - 1; i >= 0; i--)
			{
				int parts = (a[i] + cur - 1) / cur;
				cur = a[i] / parts;
				auto key = cast (long) cur << 32 | parts;
				if (key == c[i])
				{
					break;
				}
				f[i] = parts - 1;
				c[i] = key;
			}
			for (i++; i <= k; i++)
			{
				if (i > 0)
				{
					f[i] = f[i] * (i + 1) + f[i - 1];
				}
			}
			total += f[k];
		}
		writeln (total);
	}
}


The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $$$n$$$ haybale piles on the farm. The $$$i$$$-th pile contains $$$a_i$$$ haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) such that $$$|i-j|=1$$$ and $$$a_i>0$$$ and apply $$$a_i = a_i - 1$$$, $$$a_j = a_j + 1$$$. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile $$$1$$$ (i.e. to maximize $$$a_1$$$), and she only has $$$d$$$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $$$1$$$ if she acts optimally!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)  — the number of test cases. Next $$$2t$$$ lines contain a description of test cases  — two lines per test case. The first line of each test case contains integers $$$n$$$ and $$$d$$$ ($$$1 \le n,d \le 100$$$) — the number of haybale piles and the number of days, respectively.  The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 100$$$)  — the number of haybales in each pile.

For each test case, output one integer: the maximum number of haybales that may be in pile $$$1$$$ after $$$d$$$ days if Bessie acts optimally.

NoteIn the first test case of the sample, this is one possible way Bessie can end up with $$$3$$$ haybales in pile $$$1$$$:   On day one, move a haybale from pile $$$3$$$ to pile $$$2$$$  On day two, move a haybale from pile $$$3$$$ to pile $$$2$$$  On day three, move a haybale from pile $$$2$$$ to pile $$$1$$$  On day four, move a haybale from pile $$$2$$$ to pile $$$1$$$  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile $$$2$$$ to pile $$$1$$$ on the second day.

import std.stdio;

void main() {
    int t, n, d, v, res; readf("%d", &t); while(t--) {
        scanf("%d %d", &n, &d); scanf("%d", &res);
        for (int i = 1; i < n; i++) { scanf("%d", &v); if (d > 0) { res+= (i*v<=d ? v : (d/i)); d-=i*v; } }
        writeln(res);
    }
}

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint ();
    auto d = r.next!uint ();
    auto a = r.nextA!uint (n);
    foreach (i; 1 .. n) {
      while (d >= i && a[i] > 0) {
        d -= i;
        a[0]++;
        a[i]--;
      }
    }
    writeln (a[0]);
  }
}

import std.stdio : writeln;

struct IO {
    string readToken() {
        import std.range : empty, front, popFront, split;
        import std.stdio : readln;

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

    int readInt() {
        import std.conv : to;

        return readToken.to!int;
    }

    string[] tokens;
}

long binom2(int n) {
    return n * (n + 1L) >> 1;
}

void main() {
    IO io;
    int T = io.readInt;
    while (T--) {
        int n = io.readInt;
        int m = io.readInt;
        int result = 0;
        for (int i = 0; i < n; ++i) {
            int a = io.readInt;
            while (m >= i && a) {
                result++, m -= i, a--;
            }
        }
        writeln(result);
    }
}

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

struct Interval
{
  long l, h;

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

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

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

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

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

  long n, d;
  @dn long[] a;

  void solve(long tc = -1)
  {
    logSym!(this);
    long total = 0;
    foreach(i, ai; a)
      {
        if (i == 0)
          {
            total += ai;
            continue;
          }
        auto taken = min(ai, d / i);
        d -= taken * i;
        total += taken;
      }
    writeln(total);
  }
}

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto d = RD!int;
		auto a = RDA;
		ans[ti] = a[0];
		foreach (i; 1..n)
		{
			auto x = min(d/i, a[i]);
			ans[ti] += x;
			d -= i*x;
		}
	}

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


Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.

The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square.

Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7).

NoteIn the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.


Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?

The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000).

Print the n-th even-length palindrome number.

NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001.

import std.stdio;
import std.range;
import std.string;

void main() {

	string nstr = readln.strip;

    writeln(nstr, nstr.retro);
}

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

void main()
{
    auto n = strip(readln());
    auto x = to!string(n.retro());
    auto res = n ~ x;
    writeln(res);

}