Let's say string $$$s$$$ has period $$$k$$$ if $$$s_i = s_{i + k}$$$ for all $$$i$$$ from $$$1$$$ to $$$|s| - k$$$ ($$$|s|$$$ means length of string $$$s$$$) and $$$k$$$ is the minimum positive integer with this property.Some examples of a period: for $$$s$$$="0101" the period is $$$k=2$$$, for $$$s$$$="0000" the period is $$$k=1$$$, for $$$s$$$="010" the period is $$$k=2$$$, for $$$s$$$="0011" the period is $$$k=4$$$.You are given string $$$t$$$ consisting only of 0's and 1's and you need to find such string $$$s$$$ that:  String $$$s$$$ consists only of 0's and 1's;  The length of $$$s$$$ doesn't exceed $$$2 \cdot |t|$$$;  String $$$t$$$ is a subsequence of string $$$s$$$;  String $$$s$$$ has smallest possible period among all strings that meet conditions 1—3. Let us recall that $$$t$$$ is a subsequence of $$$s$$$ if $$$t$$$ can be derived from $$$s$$$ by deleting zero or more elements (any) without changing the order of the remaining elements. For example, $$$t$$$="011" is a subsequence of $$$s$$$="10101".

The first line contains single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains string $$$t$$$ ($$$1 \le |t| \le 100$$$) consisting only of 0's and 1's.

Print one string for each test case — string $$$s$$$ you needed to find. If there are multiple solutions print any one of them.

NoteIn the first and second test cases, $$$s = t$$$ since it's already one of the optimal solutions. Answers have periods equal to $$$1$$$ and $$$2$$$, respectively.In the third test case, there are shorter optimal solutions, but it's okay since we don't need to minimize the string $$$s$$$. String $$$s$$$ has period equal to $$$1$$$.

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm, std.array, std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
int inz(long t){ return to!int(t); }
static string[] tempstr;
T rd(T = long)() { while(!tempstr.length) tempstr = readln.chomp.split; string res = tempstr[0]; tempstr.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    char[] s;
    s = rd!(char[]);
    int[] nums;
    int[int] seen;
    seen[0] = 0; seen[1] = 0;
    foreach(cr; s){
        nums ~= cr - '0';
        ++seen[cr - '0'];
    }
    if(!(seen[0] && seen[1])){
        writeln(s);
    }else{
        int[] res;
        res ~= nums[0];
        foreach(i; 1..nums.length){
            if(nums[i] == nums[i-1]){
                res ~= !nums[i];
            }
            res ~= nums[i];
        }
        foreach(cr; res){
            write(cr);
        }
        writeln;
    }
}

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

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto t = readln.chomp;
        int o, z;
        foreach (c; t) {
            if (c == '0') ++z;
            if (c == '1') ++o;
        }
        if (o == 0 || z == 0) {
            writeln(t);
            continue;
        }

        char[] s;
        foreach (i; 0..t.length-1) {
            s ~= t[i];
            if (t[i] == t[i+1]) {
                if (t[i] == '0') {
                    s ~= '1';
                } else {
                    s ~= '0';
                }
            }
        }
        s ~= t[$-1];
        writeln(s);
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		auto n = s.length;
		string res;
		foreach (char part; "01")
		{
			if (s.canFind (part))
			{
				res ~= part;
			}
		}
		writeln (res.repeat (n).joiner);
	}
}

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

void test (string s) {
  if (s.all!"a=='0'" || s.all!"a == '1'") {
    writeln (s);
    return;
  }
  foreach (i; 0 .. s.length) {
    write ("01");
  }
  writeln;
}

void main() {
  auto s = readln;
  int nt;
  formattedRead (s, " %d", nt);
  foreach (tid; 0 .. nt) {
    s = readln.stripRight;
    test (s);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto T = RD!int;
	auto ans = new string[](T);
	foreach (ti; 0..T)
	{
		auto t = RD!string;
		bool[char] set;
		foreach (c; t)
		{
			set[c] = true;
		}
		if (set.keys.length == 1)
		{
			ans[ti] = t;
		}
		else
		{
			char last;
			foreach (i; 0..t.length)
			{
				if (t[i] == last)
				{
					if (t[i] == '0')
						ans[ti] ~= "10";
					else
						ans[ti] ~= "01";
				}
				else
				{
					ans[ti] ~= t[i];
				}
				last = t[i];
			}
		}
	}

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


A sequence of $$$n$$$ numbers is called permutation if it contains all numbers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences [$$$3, 1, 4, 2$$$], [$$$1$$$] and [$$$2,1$$$] are permutations, but [$$$1,2,1$$$], [$$$0,1$$$] and [$$$1,3,4$$$] — are not.For a permutation $$$p$$$ of even length $$$n$$$ you can make an array $$$b$$$ of length $$$\frac{n}{2}$$$ such that:   $$$b_i = \max(p_{2i - 1}, p_{2i})$$$ for $$$1 \le i \le \frac{n}{2}$$$ For example, if $$$p$$$ = [$$$2, 4, 3, 1, 5, 6$$$], then:   $$$b_1 = \max(p_1, p_2) = \max(2, 4) = 4$$$  $$$b_2 = \max(p_3, p_4) = \max(3,1)=3$$$  $$$b_3 = \max(p_5, p_6) = \max(5,6) = 6$$$  As a result, we made $$$b$$$ = $$$[4, 3, 6]$$$.For a given array $$$b$$$, find the lexicographically minimal permutation $$$p$$$ such that you can make the given array $$$b$$$ from it.If $$$b$$$ = [$$$4,3,6$$$], then the lexicographically minimal permutation from which it can be made is $$$p$$$ = [$$$1,4,2,3,5,6$$$], since:   $$$b_1 = \max(p_1, p_2) = \max(1, 4) = 4$$$  $$$b_2 = \max(p_3, p_4) = \max(2, 3) = 3$$$  $$$b_3 = \max(p_5, p_6) = \max(5, 6) = 6$$$ A permutation $$$x_1, x_2, \dots, x_n$$$ is lexicographically smaller than a permutation $$$y_1, y_2 \dots, y_n$$$ if and only if there exists such $$$i$$$ ($$$1 \le i \le n$$$) that $$$x_1=y_1, x_2=y_2, \dots, x_{i-1}=y_{i-1}$$$ and $$$x_i<y_i$$$.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one even integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains exactly $$$\frac{n}{2}$$$ integers $$$b_i$$$ ($$$1 \le b_i \le n$$$) — elements of array $$$b$$$. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print on a separate line:    lexicographically minimal permutation $$$p$$$ such that you can make an array $$$b$$$ from it;  or a number -1 if the permutation you are looking for does not exist.

NoteThe first test case is parsed in the problem statement.

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

immutable int infinity = int.max / 2;

int [] solve (int n, int [] b)
{
	auto a = new int [n];
	auto vis = new bool [n + 1];
	foreach (i, ref c; b)
	{
		a[i * 2 + 1] = c;
		if (vis[c])
		{
			return [-1];
		}
		vis[c] = true;
	}

	auto half = 1;
	while (half < b.length)
	{
		half *= 2;
	}
	auto limit = half * 2;
	auto t = new int [limit];
	t[] = -infinity;
	t[half..half + b.length] = b[];
	foreach_reverse (i; 1..half)
	{
		t[i] = max (t[i * 2 + 0], t[i * 2 + 1]);
	}

	foreach_reverse (v; 1..n + 1)
	{
		if (vis[v])
		{
			continue;
		}
		int i = 1;
		if (v >= t[i])
		{
			return [-1];
		}
		while (i < half)
		{
			i = i * 2 + 1;
			i -= (v >= t[i]);
		}

		a[(i - half) * 2] = v;
		t[i] = -infinity;
		for (i /= 2; i >= 1; i /= 2)
		{
			t[i] = max (t[i * 2 + 0], t[i * 2 + 1]);
		}
	}

	return a;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = readln.splitter.map !(to !(int)).array;
		writefln !("%(%s %)") (solve (n, b));
	}
}


Hanh lives in a shared apartment. There are $$$n$$$ people (including Hanh) living there, each has a private fridge. $$$n$$$ fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of $$$n$$$ people can open it.    For exampe, in the picture there are $$$n=4$$$ people and $$$5$$$ chains. The first person knows passcodes of two chains: $$$1-4$$$ and $$$1-2$$$. The fridge $$$1$$$ can be open by its owner (the person $$$1$$$), also two people $$$2$$$ and $$$4$$$ (acting together) can open it. The weights of these fridges are $$$a_1, a_2, \ldots, a_n$$$. To make a steel chain connecting fridges $$$u$$$ and $$$v$$$, you have to pay $$$a_u + a_v$$$ dollars. Note that the landlord allows you to create multiple chains connecting the same pair of fridges. Hanh's apartment landlord asks you to create exactly $$$m$$$ steel chains so that all fridges are private. A fridge is private if and only if, among $$$n$$$ people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge $$$i$$$ is not private if there exists the person $$$j$$$ ($$$i \ne j$$$) that the person $$$j$$$ can open the fridge $$$i$$$.For example, in the picture all the fridges are private. On the other hand, if there are $$$n=2$$$ fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person).Of course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly $$$m$$$ chains, and if yes, output any solution that minimizes the total cost.

Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 10$$$). Then the descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \le n \le 1000$$$, $$$1 \le m \le n$$$) — the number of people living in Hanh's apartment and the number of steel chains that the landlord requires, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$) — weights of all fridges.

For each test case:   If there is no solution, print a single integer $$$-1$$$.  Otherwise, print a single integer $$$c$$$ — the minimum total cost. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), meaning that the $$$i$$$-th steel chain connects fridges $$$u_i$$$ and $$$v_i$$$. An arbitrary number of chains can be between a pair of fridges.  If there are multiple answers, print any.

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

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

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

void main()
{
	auto T = RD!int;
	auto ans = new size_t[2][][](T);
	auto cost = new long[](T);
	foreach (i; 0..T)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto a = RDA;
		auto index = a.MAKE_IDX!"a < b";
		if (m < n || n == 2)
		{
			ans[i] = [];
			continue;
		}

		foreach (jj, j; index[0..$])
		{
			ans[i] ~= [j, index[(jj+1)%n]];
		}
		cost[i] = a.sum * 2;
		foreach (j; n..m)
		{
			ans[i] ~= [index[0], index[1]];
		}
		cost[i] += (m-n) * (a[index[0]] + a[index[1]]);
	}

	foreach (i, e; ans)
	{
		if (e.empty)
			writeln(-1);
		else
		{
			writeln(cost[i]);
			foreach (ee; e)
			{
				writeln(ee[0]+1, " ", ee[1]+1);
			}
		}
	}
	stdout.flush();
	debug readln();
}


High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.

Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.

NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto S = readln.chomp.to!string;

    auto ac = new int[](N+1);
    auto bc = new int[](N+1);
    foreach (i; 1..N+1) {
        ac[i] = ac[i-1] + (S[i-1] == 'a');
        bc[i] = bc[i-1] + (S[i-1] == 'b');
    }

    int ans = 0;
    int r = 0;
    foreach (l; 0..N) {
        while (r < N-1 && bc[r+2] - bc[l] <= K)
            r++;
        ans = max(ans, r-l+1);
    }
    r = 0;
    foreach (l; 0..N) {
        while (r < N-1 && ac[r+2] - ac[l] <= K)
            r++;
        ans = max(ans, r-l+1);
    }

    writeln(ans);
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

int n, k;
char[ ] s;

int solve(char c) {
    int a = 0, b = 0;
    int left = k;
    for (; b < n; b++)
        if (s[b] != c && !left--)
            break;
    int result = b - a;
    while (b < n) {
        while (a != b && s[a] == c)
            a++;
        a++;
        while (++b < n)
            if (s[b] != c)
                break;
        result = max(result, b - a);
    }
    return result;
}

void main() {
    static char[100_001] storage;
    while (read(&n, &k)) {
        s = storage[ ];
        readln(s);
        writeln(max(solve('a'), solve('b')));
    }
}


You have two positive integers $$$a$$$ and $$$b$$$.You can perform two kinds of operations:  $$$a = \lfloor \frac{a}{b} \rfloor$$$ (replace $$$a$$$ with the integer part of the division between $$$a$$$ and $$$b$$$)  $$$b=b+1$$$ (increase $$$b$$$ by $$$1$$$) Find the minimum number of operations required to make $$$a=0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of the description of each test case contains two integers $$$a$$$, $$$b$$$ ($$$1 \le a,b \le 10^9$$$).

For each test case, print a single integer: the minimum number of operations required to make $$$a=0$$$.

NoteIn the first test case, one of the optimal solutions is:  Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 4$$$ and $$$b = 2$$$.  Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 2$$$.  Increase $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 3$$$.  Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 0$$$ and $$$b = 3$$$.

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 a, b; get(a, b);
        int base;
        if (b == 1) {
            b = 2;
            base = 1;
        }

        auto r = int.max;
        for (;;) {
            int res = base;
            auto aa = a;
            while (aa) {
                aa /= b;
                res += 1;
            }
            if (res <= r) {
                r = res;
                b += 1;
                base += 1;
            } else {
                break;
            }
        }
        writeln(r);
    }
}

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 a = RD;
		auto b = RD;

		long bb;
		if (b == 1)
		{
			++bb;
		}

		ans[ti] = long.max;
		while (true)
		{
			long tmp;
			auto x = a;
			auto y = b + bb;
			while (x)
			{
				x /= y;
				++tmp;
			}
			tmp += bb;
			if (tmp <= ans[ti])
				ans[ti] = tmp;
			else
				break;
			++bb;
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int a, b;
		readf !(" %s %s") (a, b);
		int res = int.max;
		for (int step = 0; step <= 100; step++)
		{
			int num = step;
			int c = a;
			int d = b + step;
			if (d == 1)
			{
				continue;
			}
			while (c > 0)
			{
				c /= d;
				num += 1;
			}
			res = min (res, num);
		}
		writeln (res);
	}
}


You are a coach at your local university. There are $$$n$$$ students under your supervision, the programming skill of the $$$i$$$-th student is $$$a_i$$$.You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maximum number of students. But you also know that a team should be balanced. It means that the programming skill of each pair of students in a created team should differ by no more than $$$5$$$.Your task is to report the maximum possible number of students in a balanced team.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is a programming skill of the $$$i$$$-th student.

Print one integer — the maximum possible number of students in a balanced team.

NoteIn the first example you can create a team with skills $$$[12, 17, 15]$$$.In the second example you can take all students in a team because their programming skills are equal.In the third example you can create a team consisting of a single student (and you cannot create a team consisting of at least two students).

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

void main() {
    int n;
    readf!" %s"(n);

    int[] a = new int[](n);
    foreach (i; 0 .. n) {
        readf!" %s"(a[i]);
    }

    a.sort;

    debug {
        writeln(a);
    }

    int ans = 0;
    int l = 0, r = 0;
    for (; l < n; l++) {
        while (r < n && a[r] - a[l] <= 5) {
            r++;
        }
        ans = max(ans, r - l);
    }

    writeln(ans);
}

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

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

    for (int i = 0, j = 0; i < N; ++i) {
        if (j < i) j = i;
        while (j < N && A[j] - A[i] <= 5) ++j;
        ans = max(ans, j - i);
    }

    ans.writeln;
}

import std.functional,
       std.algorithm,
       std.container,
       std.typetuple,
       std.typecons,
       std.bigint,
       std.string,
       std.traits,
       std.array,
       std.range,
       std.stdio,
       std.conv;

bool chmax(t)(ref t a, t b) {
  if (a < b) {
    a = b;
    return true;
  } else {
    return false;
  }
}

void main() {
  int n = readln.chomp.to!int;
  int[] ns = readln.chomp.split.to!(int[]);
  sort!"a>b"(ns);
  int[int] hs;

  foreach (e; ns) {
    if (e in hs) {
      hs[e]++;
    } else {
      hs[e] = 1;
    }
  }

  int ans = 0;
  int len;

  foreach (e; ns) {
    foreach (i; 0..6) {
      if ((e - i) in hs) {
        len += hs[e - i];
      }
    }

    chmax(ans, len);
    len = 0;
  }

  writeln(ans);
}


Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".

NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

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

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

//Kadane's algorithm
long maximumSubArraySum(R) (R range) if (isInputRange!R && isIntegral!(ElementType!R)) {
  alias T = ElementType!R;
  alias S = Tuple! (long, "best", long, "cur");
  S next (in S s, in T x) {
    S t;
    t.cur = s.cur + x;
    t.best = max (s.best, t.cur);
    if (t.cur < 0) t.cur = 0;
    return t;
  }
  return reduce!next (tuple!("best", "cur") (long.min, 0L), range).best;
}

bool test (in long[] a) {
  long y = sum (a);
  long best = y;
  long cur = 0;
  int l = 0;
  foreach (x; a) {
    cur += x;
    ++l;
    if (best <= cur && l < a.length) {
      return false;
    }
    if (cur < 0) {
      cur = 0;
      l = 0;
    }
  }
  return true;
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint ();
    auto a = r.nextA!(long)(n);
    debug stderr.writeln (a);
    auto b = a.dup;
    b.reverse ();
    writeln ((test (a) && test (b)) ? "YES" : "NO");
  }
}

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

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

//Kadane's algorithm
long maximumSubArraySum(R) (R range) if (isInputRange!R && isIntegral!(ElementType!R)) {
  alias T = ElementType!R;
  alias S = Tuple! (long, "best", long, "cur");
  S next (in S s, in T x) {
    S t;
    t.cur = s.cur + x;
    t.best = max (s.best, t.cur);
    if (t.cur < 0) t.cur = 0;
    return t;
  }
  return reduce!next (tuple!("best", "cur") (long.min, 0L), range).best;
}

bool test (in long[] a) {
  long y = sum (a);
  long b = max (maximumSubArraySum (a[1 .. $]), maximumSubArraySum (a[0 .. $ - 1]));
  return y > b;
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint ();
    auto a = r.nextA!(long)(n);
    debug stderr.writeln (a);
    auto b = a.dup;
    b.reverse ();
    writeln ((test (a) && test (b)) ? "YES" : "NO");
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	foreach(_; 0 .. rint){
		int n = rint;
		long[] as = rlong(n);

		long inf = 1_00000_000_000_000 + 999;

		long x = as.sum;
		long y = -inf;
		long tmp;
		foreach(a; as[0 .. $ - 1]){
			if(tmp + a > 0) tmp += a, y.chmax(tmp);
			else tmp = 0;
		}
		tmp = 0;
		foreach(a; as[1 .. $]){
			if(tmp + a > 0) tmp += a, y.chmax(tmp);
			else tmp = 0;
		}
		foreach(a; as) y.chmax(a);
		log("x:", x, "y:", y);

		if(x > y) "YES".writeln;
		else "NO".writeln;

	}

}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(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);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(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 = E.init)
{
  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;
}

void main()
{
  int t;
  read(t);
  foreach(tc; 0 .. t)
    {
      long n;
      read(n);
      auto a = makeArray!long(n, next!long);
      long bestsum = 0;
      long totalbest = long.min;
      foreach(i; 0 .. n - 1)
        {
          bestsum = max(a[i.ind] + bestsum, a[i.ind]);
          totalbest = max(bestsum, totalbest);
        }
      long suffixsum = 0;
      long maxsuffixsum = long.min;
      foreach_reverse(i; 1 .. n)
        {
          suffixsum += a[i.ind];
          totalbest = max(suffixsum, totalbest);
        }
      writeln(a[].sum > totalbest? "YES" : "NO");
    }
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void 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 main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto x = a.sum;
		auto b = new long[](n+1);
		foreach (i; 0..n)
		{
			b[i+1] = b[i] + a[i];
		}
		long y = long.min;
		int l;
		foreach (r; 1..n+1)
		{
			if (l == 0 && r == n)
			{
				foreach (i; 2..n+1)
					y.chmax(b[i] - b[1]);
				break;
			}
			auto tmp = b[r] - b[l];
			if (tmp <= 0)
			{
				l = r;
			}
			y.chmax(tmp);
		}
		ans[ti] = x > y;
	}

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

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

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

//Kadane's algorithm
long maximumSubArraySum(R) (R range) if (isInputRange!R && isIntegral!(ElementType!R)) {
  alias T = ElementType!R;
  alias S = Tuple! (long, "best", long, "cur");
  S next (in S s, in T x) {
    S t;
    t.cur = s.cur + x;
    t.best = max (s.best, t.cur);
    if (t.cur < 0) t.cur = 0;
    return t;
  }
  return reduce!next (tuple!("best", "cur") (long.min, 0L), range).best;
}

bool test (in long[] a) {
  long y = sum (a);
  long best = y;
  long cur = 0;
  int l = 0;
  foreach (x; a) {
    cur += x;
    ++l;
    if (best <= cur && l < a.length) {
      return false;
    }
    if (cur < 0) {
      cur = 0;
      l = 0;
    }
  }
  return true;
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint ();
    auto a = r.nextA!(long)(n);
    debug stderr.writeln (a);
    writeln (test (a) ? "YES" : "NO");
  }
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(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);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(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 = E.init)
{
  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;
}

void main()
{
  int t;
  read(t);
  foreach(tc; 0 .. t)
    {
      int n;
      read(n);
      auto a = makeArray!int(n, next!int);
      int bestsum = 0;
      int totalbest = int.min;
      int totalbesti = -1;
      foreach(i; 0 .. n - 1)
        {
          bestsum = max(a[i] + bestsum, a[i]);
          if (bestsum > totalbest)
            {
              totalbest = bestsum;
            }
        }
      int suffixsum = 0;
      int maxsuffixsum = int.min;
      foreach_reverse(i; 1 .. n)
        {
          suffixsum += a[i];
          maxsuffixsum = max(suffixsum, maxsuffixsum);
        }
      totalbest = max(totalbest, maxsuffixsum);
      writeln(a[].sum > totalbest? "YES" : "NO");
    }
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(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);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(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 = E.init)
{
  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;
}

void main()
{
  int t;
  read(t);
  foreach(tc; 0 .. t)
    {
      int n;
      read(n);
      auto a = makeArray!int(n, next!int);
      int bestsum = 0;
      int totalbest = int.min;
      foreach(i; 0 .. n - 1)
        {
          bestsum = max(a[i] + bestsum, a[i]);
          totalbest = max(bestsum, totalbest);
        }
      int suffixsum = 0;
      int maxsuffixsum = int.min;
      foreach_reverse(i; 1 .. n)
        {
          suffixsum += a[i];
          totalbest = max(suffixsum, totalbest);
        }
      writeln(a[].sum > totalbest? "YES" : "NO");
    }
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void 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 main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto x = a.sum;
		auto b = new long[](n+1);
		foreach (i; 0..n)
		{
			b[i+1] = b[i] + a[i];
		}
		long y;
		int l;
		foreach (r; 1..n+1)
		{
			if (l == 0 && r == n) break;
			auto tmp = b[r] - b[l];
			if (tmp < 0)
			{
				l = r+1;
			}
			y.chmax(tmp);
		}
		ans[ti] = x > y;
	}

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

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void 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 main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto x = a.sum;
		auto b = new long[](n+1);
		foreach (i; 0..n)
		{
			b[i+1] = b[i] + a[i];
		}
		long y = long.min;
		int l;
		foreach (r; 1..n+1)
		{
			if (l == 0 && r == n) break;
			auto tmp = b[r] - b[l];
			if (tmp < 0)
			{
				l = r+1;
			}
			y.chmax(tmp);
		}
		ans[ti] = x > y;
	}

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


Inflation has occurred in Berlandia, so the store needs to change the price of goods.The current price of good $$$n$$$ is given. It is allowed to increase the price of the good by $$$k$$$ times, with $$$1 \le k \le m$$$, k is an integer. Output the roundest possible new price of the good. That is, the one that has the maximum number of zeros at the end.For example, the number 481000 is more round than the number 1000010 (three zeros at the end of 481000 and only one at the end of 1000010).If there are several possible variants, output the one in which the new price is maximal.If it is impossible to get a rounder price, output $$$n \cdot m$$$ (that is, the maximum possible price).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. Each test case consists of one line. This line contains two integers: $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$). Where $$$n$$$ is the old price of the good, and the number $$$m$$$ means that you can increase the price $$$n$$$ no more than $$$m$$$ times.

For each test case, output on a separate line the roundest integer of the form $$$n \cdot k$$$ ($$$1 \le k \le m$$$, $$$k$$$ — an integer). If there are several possible variants, output the one in which the new price (value $$$n \cdot k$$$) is maximal. If it is impossible to get a more rounded price, output $$$n \cdot m$$$ (that is, the maximum possible price).

NoteIn the first case $$$n = 6$$$, $$$m = 11$$$. We cannot get a number with two zeros or more at the end, because we need to increase the price $$$50$$$ times, but $$$50 > m = 11$$$. The maximum price multiple of $$$10$$$ would be $$$6 \cdot 10 = 60$$$.In the second case $$$n = 5$$$, $$$m = 43$$$. The maximum price multiple of $$$100$$$ would be $$$5 \cdot 40 = 200$$$.In the third case, $$$n = 13$$$, $$$m = 5$$$. All possible new prices will not end in $$$0$$$, then you should output $$$n \cdot m = 65$$$.In the fourth case, you should increase the price $$$15$$$ times.In the fifth case, increase the price $$$12000$$$ times.

import std;

// From: https://rosettacode.org/wiki/Prime_decomposition#D
Unqual!T[] decompose(T)(in T number)
{
    typeof(return) result;
    Unqual!T n = number;

    for (Unqual!T i = 2; n % i == 0; n /= i)
        result ~= i;
    for (Unqual!T i = 3; n >= i * i; i += 2)
        for (; n % i == 0; n /= i)
            result ~= i;

    if (n != 1)
        result ~= n;
    return result;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n, m;
    readf!" %d %d "(n, m);
    auto tmp = decompose(n);
    auto cnt2 = tmp.count(2);
    auto cnt5 = tmp.count(5);
    long xm = 1;
    if (cnt2 < cnt5) {
      while (cnt2 < cnt5 && xm * 2 <= m) {
        cnt2++;
        xm *= 2;
      }
      while (xm * 10 <= m) {
        xm *= 10;
      }
      if (m / xm > 0)
        xm *= m / xm;
    } else {
      while (cnt5 < cnt2 && xm * 5 <= m) {
        cnt5++;
        xm *= 5;
      }
      while (xm * 10 <= m) {
        xm *= 10;
      }
      if (m / xm > 0)
        xm *= m / xm;
    }
    writeln(xm == 1 ? n * m : n * xm);
  }
}

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

int zeroes (long n)
{
	int res = 0;
	while (n % 10 == 0)
	{
		res += 1;
		n /= 10;
	}
	return res;
}

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

		foreach (c; [2, 5, 10])
		{
			while (c <= m && zeroes (n) < zeroes (n * c))
			{
				n *= c;
				m /= c;
			}
		}
		writeln (n * m);
	}
}


Authors guessed an array $$$a$$$ consisting of $$$n$$$ integers; each integer is not less than $$$2$$$ and not greater than $$$2 \cdot 10^5$$$. You don't know the array $$$a$$$, but you know the array $$$b$$$ which is formed from it with the following sequence of operations:  Firstly, let the array $$$b$$$ be equal to the array $$$a$$$;  Secondly, for each $$$i$$$ from $$$1$$$ to $$$n$$$:   if $$$a_i$$$ is a prime number, then one integer $$$p_{a_i}$$$ is appended to array $$$b$$$, where $$$p$$$ is an infinite sequence of prime numbers ($$$2, 3, 5, \dots$$$);  otherwise (if $$$a_i$$$ is not a prime number), the greatest divisor of $$$a_i$$$ which is not equal to $$$a_i$$$ is appended to $$$b$$$;   Then the obtained array of length $$$2n$$$ is shuffled and given to you in the input. Here $$$p_{a_i}$$$ means the $$$a_i$$$-th prime number. The first prime $$$p_1 = 2$$$, the second one is $$$p_2 = 3$$$, and so on.Your task is to recover any suitable array $$$a$$$ that forms the given array $$$b$$$. It is guaranteed that the answer exists (so the array $$$b$$$ is obtained from some suitable array $$$a$$$). If there are multiple answers, you can print any.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$2n$$$ integers $$$b_1, b_2, \dots, b_{2n}$$$ ($$$2 \le b_i \le 2750131$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$. $$$2750131$$$ is the $$$199999$$$-th prime number.

In the only line of the output print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 2 \cdot 10^5$$$) in any order — the array $$$a$$$ from which the array $$$b$$$ can be obtained using the sequence of moves given in the problem statement. If there are multiple answers, you can print any.

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

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

    immutable int MX = 2750131;
    auto div = new int[] (MX + 1);
    div[] = 1;
    int[] prs;
    int[int] prsIdx;

    foreach (i; 2 .. MX + 1) {
        if (div[i] != 1) { continue; }

        foreach (j; (MX+1).iota.drop(i+i).stride(i)) {
            if (div[j] == 1) { div[j] = i; }
        }

        prs ~= i;
        prsIdx[i] = prs.length.to!int;
    }

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

    auto rbt = make!(RedBlackTree!(int, "a > b", true))(arr);

    int[] ans;
    while (!rbt.empty()) {
        auto x = rbt.front();
        rbt.removeFront();

        if (x in prsIdx) {
            auto v = prsIdx[x];
            rbt.removeKey(v);
            ans ~= v;
        } else {
            auto v = x / div[x];
            rbt.removeKey(v);
            ans ~= x;
        }
    }

    ans.map!(to!string).join(" ").writeln;
}

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

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

    immutable int MX = 2750131;
    auto div = new int[] (MX + 1);
    div[] = 1;
    int nxtIdx = 1;
    int[int] prsIdx;

    foreach (i; 2 .. MX + 1) {
        if (div[i] != 1) { continue; }

        foreach (j; (MX+1).iota.drop(i+i).stride(i)) {
            if (div[j] == 1) { div[j] = i; }
        }

        prsIdx[i] = nxtIdx;
        nxtIdx += 1;
    }

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

    auto rbt = make!(RedBlackTree!(int, "a > b", true))(arr);

    int[] ans;
    while (!rbt.empty()) {
        auto x = rbt.front();
        rbt.removeFront();

        if (x in prsIdx) {
            auto v = prsIdx[x];
            rbt.removeKey(v);
            ans ~= v;
        } else {
            auto v = x / div[x];
            rbt.removeKey(v);
            ans ~= x;
        }
    }

    ans.map!(to!string).join(" ").writeln;
}


There is an easy way to obtain a new task from an old one called "Inverse the problem": we give an output of the original task, and ask to generate an input, such that solution to the original problem will produce the output we provided. The hard task of Topcoder Open 2014 Round 2C, InverseRMQ, is a good example.Now let's create a task this way. We will use the task: you are given a tree, please calculate the distance between any pair of its nodes. Yes, it is very easy, but the inverse version is a bit harder: you are given an n × n distance matrix. Determine if it is the distance matrix of a weighted tree (all weights must be positive integers).

The first line contains an integer n (1 ≤ n ≤ 2000) — the number of nodes in that graph. Then next n lines each contains n integers di, j (0 ≤ di, j ≤ 109) — the distance between node i and node j.

If there exists such a tree, output "YES", otherwise output "NO".

NoteIn the first example, the required tree exists. It has one edge between nodes 1 and 2 with weight 2, another edge between nodes 1 and 3 with weight 7.In the second example, it is impossible because d1, 1 should be 0, but it is 1.In the third example, it is impossible because d1, 2 should equal d2, 1.

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

immutable int INF = int.max / 2;
immutable int NA = -1;

bool solve (int [] [] a)
{
	int n = a.length;
	foreach (i, c; a)
	{
		foreach (j, x; c)
		{
			if ((x == 0) != (i == j) || x != a[j][i])
			{
				return false;
			}
		}
	}

	auto d = new int [n];
	d[] = INF;
	auto p = new int [n];
	p[] = NA;
	auto b = new bool [n];
	alias edge = Tuple !(int, "v", int, "w");
	auto g = new edge [] [n];
	int cur = 0;
	foreach (k; 1..n)
	{
		b[cur] = true;
		foreach (i; 0..n)
		{
			if (d[i] > a[cur][i])
			{
				d[i] = a[cur][i];
				p[i] = cur;
			}
		}
		int next = cur;
		int w = INF;
		foreach (i; 0..n)
		{
			if (!b[i])
			{
				if (w > d[i])
				{
					w = d[i];
					next = i;
				}
			}
		}
		g[next] ~= edge (p[next], w);
		g[p[next]] ~= edge (next, w);
		cur = next;
	}
	debug {writeln (g);}

	foreach (i; 0..n)
	{
		auto e = new long [n];

		void recur (int v, int q, long z)
		{
			e[v] = z;
			foreach (h; g[v])
			{
				if (h.v != q)
				{
					recur (h.v, v, z + h.w);
				}
			}
		}

		recur (i, NA, 0);
		debug {writeln (e[], ' ', a[i][]);}
		if (e[] != a[i][])
		{
			return false;
		}
	}
	return true;
}

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto a = new int [] [] (n, n);
		foreach (ref c; a)
		{
			auto r = readln.split ();
			foreach (ref x; c)
			{
				x = to !(int) (r.front);
				r.popFront ();
//				readf (" %s", &x);
			}
		}
		writeln (solve (a) ? "YES" : "NO");
	}
}

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

immutable int INF = int.max / 2;
immutable int NA = -1;

bool solve (int [] [] a)
{
    int n = a.length;
    foreach (i, c; a)
    {
        foreach (j, x; c)
        {
            if ((x == 0) != (i == j) || x != a[j][i])
            {
                return false;
            }
        }
    }

    auto d = new int [n];
    d[] = INF;
    auto p = new int [n];
    p[] = NA;
    auto b = new bool [n];
    alias edge = Tuple !(int, "v", int, "w");
    auto g = new edge [] [n];
    int cur = 0;
    foreach (k; 1..n)
    {
        b[cur] = true;
        foreach (i; 0..n)
        {
            if (d[i] > a[cur][i])
            {
                d[i] = a[cur][i];
                p[i] = cur;
            }
        }
        int next = cur;
        int w = INF;
        foreach (i; 0..n)
        {
            if (!b[i])
            {
                if (w > d[i])
                {
                    w = d[i];
                    next = i;
                }
            }
        }
        g[next] ~= edge (p[next], w);
        g[p[next]] ~= edge (next, w);
        cur = next;
    }
    debug {writeln (g);}

    foreach (i; 0..n)
    {
        auto e = new long [n];

        void recur (int v, int q, long z)
        {
            e[v] = z;
            foreach (h; g[v])
            {
                if (h.v != q)
                {
                    recur (h.v, v, z + h.w);
                }
            }
        }

        recur (i, NA, 0);
        debug {writeln (e[], ' ', a[i][]);}
        if (e[] != a[i][])
        {
            return false;
        }
    }
    return true;
}

void main ()
{
    int n;
    while (readf (" %s", &n) > 0)
    {
        auto a = new int [] [] (n, n);
        foreach (ref c; a)
        {
            foreach (ref x; c)
            {
                readf (" %s", &x);
            }
        }
        writeln (solve (a) ? "YES" : "NO");
    }
}

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

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

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

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

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

int N;
long[][] D;

Pair!(long, Pair!(int, int))[] edges;

void doIt(int[] us) {
debug{
writeln("doIt ",us);
}
	if (us.length <= 1) {
		return;
	}
	int a = us[0];
	int b = -1;
	foreach (u; us[1 .. $]) {
		if (b == -1 || D[a][b] > D[a][u]) {
			b = u;
		}
	}
	edges ~= pair(D[a][b], pair(a, b));
	int[] usA, usB;
	foreach (u; us) {
		if (D[a][u] < D[b][u]) {
			usA ~= u;
		} else {
			usB ~= u;
		}
	}
	if (usA.empty || usB.empty) {
		return;
	}
	usA.doIt;
	usB.doIt;
}

bool solve() {
	foreach (u; 0 .. N) {
		if (D[u][u] != 0) {
			return false;
		}
	}
	foreach (u; 0 .. N) foreach (v; 0 .. N) {
		if (D[u][v] != D[v][u]) {
			return false;
		}
	}

	edges = new Pair!(long, Pair!(int, int))[0];
	int[] us = new int[N];
	foreach (u; 0 .. N) {
		us[u] = u;
	}
	us.doIt;
debug{
writeln(edges);
}
	if (edges.length != N - 1) {
		return false;
	}
	foreach (edge; edges) {
		if (edge.x <= 0) {
			return false;
		}
	}
	auto G = new Pair!(long, int)[][N];
	foreach (edge; edges) {
		G[edge.y.x] ~= pair(edge.x, edge.y.y);
		G[edge.y.y] ~= pair(edge.x, edge.y.x);
	}
	foreach (s; 0 .. N) {
		long[] ds = new long[N];
		void dfs(int u, int p, long d) {
			ds[u] = d;
			foreach (inci; G[u]) {
				const v = inci.y;
				if (v != p) {
					dfs(v, u, d + inci.x);
				}
			}
		}
		dfs(s, -1, 0);
debug{
writeln(s," : ",ds);
}
		foreach (u; 0 .. N) {
			if (D[s][u] != ds[u]) {
				return false;
			}
		}
	}
	return true;
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		D = new long[][](N, N);
		foreach (u; 0 .. N) foreach (v; 0 .. N) {
			D[u][v] = readLong;
		}

		writeln(solve ? "YES" : "NO");
	}
	} catch (EOFException) {}
}


You are given a string $$$s$$$, consisting only of Latin letters 'a', and a string $$$t$$$, consisting of lowercase Latin letters.In one move, you can replace any letter 'a' in the string $$$s$$$ with a string $$$t$$$. Note that after the replacement string $$$s$$$ might contain letters other than 'a'.You can perform an arbitrary number of moves (including zero). How many different strings can you obtain? Print the number, or report that it is infinitely large.Two strings are considered different if they have different length, or they differ at some index.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of testcases. The first line of each testcase contains a non-empty string $$$s$$$, consisting only of Latin letters 'a'. The length of $$$s$$$ doesn't exceed $$$50$$$. The second line contains a non-empty string $$$t$$$, consisting of lowercase Latin letters. The length of $$$t$$$ doesn't exceed $$$50$$$.

For each testcase, print the number of different strings $$$s$$$ that can be obtained after an arbitrary amount of moves (including zero). If the number is infinitely large, print -1. Otherwise, print the number.

NoteIn the first example, you can replace any letter 'a' with the string "a", but that won't change the string. So no matter how many moves you make, you can't obtain a string other than the initial one.In the second example, you can replace the second letter 'a' with "abc". String $$$s$$$ becomes equal to "aabc". Then the second letter 'a' again. String $$$s$$$ becomes equal to "aabcbc". And so on, generating infinitely many different strings.In the third example, you can either leave string $$$s$$$ as is, performing zero moves, or replace the only 'a' with "b". String $$$s$$$ becomes equal to "b", so you can't perform more moves on it.

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;
      auto T = scan;

      if (T != "a" && T.canFind('a')) return -1L;
      if (T == "a") return 1;

      return 2L ^^ S.length;
    }

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

  outputForAtCoder(&solve);
}

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

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

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


Vova's house is an array consisting of $$$n$$$ elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The $$$i$$$-th element of the array is $$$1$$$ if there is a heater in the position $$$i$$$, otherwise the $$$i$$$-th element of the array is $$$0$$$.Each heater has a value $$$r$$$ ($$$r$$$ is the same for all heaters). This value means that the heater at the position $$$pos$$$ can warm up all the elements in range $$$[pos - r + 1; pos + r - 1]$$$.Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater. Vova's target is to warm up the whole house (all the elements of the array), i.e. if $$$n = 6$$$, $$$r = 2$$$ and heaters are at positions $$$2$$$ and $$$5$$$, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first $$$3$$$ elements will be warmed up by the first heater and the last $$$3$$$ elements will be warmed up by the second heater).Initially, all the heaters are off.But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater.Your task is to find this number of heaters or say that it is impossible to warm up the whole house.

The first line of the input contains two integers $$$n$$$ and $$$r$$$ ($$$1 \le n, r \le 1000$$$) — the number of elements in the array and the value of heaters. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$) — the Vova's house description.

Print one integer — the minimum number of heaters needed to warm up the whole house or -1 if it is impossible to do it.

NoteIn the first example the heater at the position $$$2$$$ warms up elements $$$[1; 3]$$$, the heater at the position $$$3$$$ warms up elements $$$[2, 4]$$$ and the heater at the position $$$6$$$ warms up elements $$$[5; 6]$$$ so the answer is $$$3$$$.In the second example the heater at the position $$$1$$$ warms up elements $$$[1; 3]$$$ and the heater at the position $$$5$$$ warms up elements $$$[3; 5]$$$ so the answer is $$$2$$$.In the third example there are no heaters so the answer is -1.In the fourth example the heater at the position $$$3$$$ warms up elements $$$[1; 5]$$$, the heater at the position $$$6$$$ warms up elements $$$[4; 8]$$$ and the heater at the position $$$10$$$ warms up elements $$$[8; 10]$$$ so the answer is $$$3$$$.

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 inf = 10^^6;

void main() {
    int n, r;
    scan(n, r);
    auto a = readln.split.to!(int[]);
    a = a ~ repeat(0, r).array;

    int lt = -1;
    auto b = new int[](n + r);
    foreach (i ; 0 .. r) {
        if (a[i]) {
            lt = i;
        }
    }
    foreach (i ; r .. n + r) {
        b[i - r] = lt;
        if (lt == i - r) {
            lt = -1;
        }
        if (a[i]) {
            lt = i;
        }
    }

    auto c = new int[](n);
    c[0] = a[0] ? 0 : inf + 1;
    foreach (i ; 1 .. n) {
        if (a[i] == 1) {
            c[i] = 0;
        }
        else {
            c[i] = c[i-1] + 1;
        }
    }

    debug {
        writeln(b);
        writeln(c);
    }

    int ans;

    for (int pos; pos < n;) {
        ans++;
        if (b[pos] != -1) {
            pos = b[pos] + r;
        }
        else if (c[pos] < r) {
            pos = pos - c[pos] + r;
        }
        else {
            writeln(-1);
            return;
        }
    }

    writeln(ans);
}

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

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

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

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

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

  auto bs = new int[](n);
  foreach (int i, a; as) {
    if (a) {
      foreach (int j; max(0, i - r + 1) .. min(n, i + r)) {
        bs[j]++;
      }
    }
  }
  if (bs.find(0).length > 0) {
    writeln(-1);
    return;
  }
  int num = reduce!"a+b"(as);
  foreach (int i, b; bs) {
    if (as[i]) {
      if (b >= 2) {
        bool ok = true;
        foreach (int j; max(0, i - r + 1) .. min(n, i + r)) {
          ok &= bs[j] >= 2;
        }
        if (ok) {
          num--;
          foreach (int j; max(0, i - r + 1) .. min(n, i + r)) {
            bs[j]--;
          }
        }
      }
    }
  }
  writeln(num);
}

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

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

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

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

  auto bs = new int[](n);
  int num = 0;
  foreach (int i, b; bs) {
    if (b == 0) {
      num++;
      bool found = false;
      foreach (int j; i .. n) {
        if (as[j]) {
          found = true;
          for (int k = max(0, j - r + 1); k < min(n, j + r - 1); k++) {
            bs[k] = 1;
          }
          break;
        }
      }
      if (!found) {
        writeln(-1);
        return;
      }
    }
  }

  writeln(num);
}

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

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

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

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

  auto bs = new int[](n);
  int num = 0;
  foreach (int i, b; bs) {
    if (b == 0) {
      num++;
      bool found = false;
      int idx;
      foreach (int j; i .. n) {
        if (as[j]) {
          if (i < j - r + 1) {
            break;
          }
          found = true;
          idx = j;
        }
      }
      if (!found) {
        writeln(-1);
        return;
      }
      for (int k = max(0, idx - r + 1); k < min(n, idx + r); k++) {
        bs[k] = 1;
      }
    }
  }

  writeln(num);
}

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

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


A tree is a connected graph that doesn't contain any cycles.The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.

The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices. Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.

Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).

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

immutable int INF = 10L ^^ 9 + 23;

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

    auto g = new int[][] (n+1);
    foreach (_ ; 0 .. n-1) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        g[u] ~= v;
        g[v] ~= u;
    }

    auto mxh = new int[] (n+1);
    int dfsmxh(int v, int fr) {
        int h = 0;
        foreach (u; g[v]) {
            if (u == fr) continue;
            h = max(h, dfsmxh(u, v) + 1);
        }

        return mxh[v] = h;
    }

    dfsmxh(1, -1);
    foreach (ref r; g) {
        r = r.sort!((a, b) => mxh[a] < mxh[b]).array;
    }

    long dfs(int v, int fr, int h, ref int[int] cnt) {
        long ret = 0;

        while (! g[v].empty() && g[v].back == fr) { g[v].popBack(); }

        int[int] ncnt;
        if (! g[v].empty()) {
            ret += dfs(g[v].back, v, h+1, cnt);

            foreach (u; g[v][0 .. $-1]) {
                if (u == fr) continue;

                ncnt.clear();
                ret += dfs(u, v, h+1, ncnt);
                foreach (le; 1 .. k) {
                    debug { writeln("mid ", v, ' ' , u,  ' ', cnt, ' ', ncnt, ' ', h); }
                    ret += cnt.get(h + le, 0).to!long * ncnt.get(h + k - le, 0);
                }

                foreach (d; 1 .. k+1) {
                    if (! ncnt.get(h + d, 0) == 0) {
                        cnt[h + d] += ncnt.get(h + d, 0);
                    }
                }
            }

            debug { writeln("start ", v, ' ', h+k,  ' ', cnt.get(h + k, 0)); }
            ret += cnt.get(h + k, 0);
        }

        cnt[h] += 1;

        debug { writeln("ret ", v, ' ', ret); }

        return ret;
    }

    int[int] cnt;
    auto ans = dfs(1, -1, 0, cnt);

    ans.writeln;
}

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

immutable int INF = 10L ^^ 9 + 23;

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

    auto g = new int[][] (n+1);
    foreach (_ ; 0 .. n-1) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        g[u] ~= v;
        g[v] ~= u;
    }

    auto d = new int[][] (n+1, k+1);

    long dfs(int v, int fr) {
        long ret = 0;
        foreach (u; g[v]) {
            if (u == fr) continue;

            ret += dfs(u, v);
            foreach (le; 1 .. k) {
                ret += d[v][le].to!long * d[u][k - le - 1];
            }
            foreach (le; 1 .. k+1) {
                d[v][le] += d[u][le-1];
            }
        }

        ret += d[v][k];
        d[v][0] += 1;

        debug { writeln(v, ' ', d[v], ' ', ret); }

        return ret;
    }

    auto ans = dfs(1, -1);

    ans.writeln;
}