Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer.Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that.

The first line contains integer n (1 ≤ n ≤ 2·105) — the number of throws of the first team. Then follow n integer numbers — the distances of throws ai (1 ≤ ai ≤ 2·109).  Then follows number m (1 ≤ m ≤ 2·105) — the number of the throws of the second team. Then follow m integer numbers — the distances of throws of bi (1 ≤ bi ≤ 2·109).

Print two numbers in the format a:b — the score that is possible considering the problem conditions where the result of subtraction a - b is maximum. If there are several such scores, find the one in which number a is maximum.

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

int find(int tar, int[] arr)
{
    int left = 0, right = to!int(arr.length) - 1, ret = -1;
    while (left <= right)
    {
	int mid = (left + right) >> 1;
	if (arr[mid] == tar)
	{
	    ret = mid;
	    left = mid + 1;
	}
	else if (arr[mid] < tar)
	{
	    left = mid + 1;
	}
	else
	{
	    right = mid - 1;
	}
    }
    if (ret == -1) ret = left;
    return ret;
}

void solve(int[] a, int[] b)
{
    sort(a);
    sort(b);
    long ansa = a.length << 1, ansb = b.length << 1;
    long dist = ansa - ansb;
    foreach (i; 0 .. a.length)
    {
	if (i > 0 && a[i] == a[i - 1]) continue;
	auto pos = find(a[i] - 1, b);
	long scorea = i * 2 + (a.length - i) * 3;
	long scoreb;
	if (pos < b.length && b[pos] == a[i] - 1)
	{
	    scoreb = (pos + 1) * 2 + (b.length - pos - 1) * 3;
	}
	else
	{
	    scoreb = pos * 2 + (b.length - pos) * 3;
	}
	if (scorea - scoreb > dist || scorea - scoreb == dist && scorea > ansa)
	{
	    dist = scorea - scoreb;
	    ansa = scorea;
	    ansb = scoreb;
	}
    }
    writefln("%d:%d", ansa, ansb);
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
	auto a = new int[n];
	foreach (i; 0 .. n) scanf("%d", &a[i]);
	scanf("%d", &m);
	auto b = new int[m];
	foreach (i; 0 .. m) scanf("%d", &b[i]);
	solve(a, b);
    }
}

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

int find(int tar, int[] arr)
{
    int left = 0, right = to!int(arr.length) - 1, ret = -1;
    while (left <= right)
    {
	int mid = (left + right) >> 1;
	if (arr[mid] == tar)
	{
	    ret = mid;
	    left = mid + 1;
	    //right = mid - 1;
	}
	else if (arr[mid] < tar)
	{
	    left = mid + 1;
	}
	else
	{
	    right = mid - 1;
	}
    }
    if (ret == -1) ret = left;
    return ret;
}

void solve(int[] a, int[] b)
{
    sort(a);
    sort(b);
    long ansa = a.length << 1, ansb = b.length << 1;
    //auto pos = find(a[0] - 1, b);
    //long ansa = a.length * 3;
    //long ansb = pos * 2 + (b.length - pos) * 3;
    long dist = ansa - ansb;
    foreach (i; 0 .. a.length)
    {
	//if (i < a.length - 1 && a[i] == a[i + 1]) continue;
	if (i > 0 && a[i] == a[i - 1]) continue;
	auto pos = find(a[i] - 1, b);
	//long scorea = (i + 1) * 3 + (a.length - i - 1) * 2;
	long scorea = i * 2 + (a.length - i) * 3;
	long scoreb;
	if (pos < b.length && b[pos] == a[i] - 1)
	{
	    scoreb = (pos + 1) * 2 + (b.length - pos - 1) * 3;
	}
	else
	{
	    scoreb = pos * 2 + (b.length - pos) * 3;
	}
	if (scorea - scoreb > dist || scorea - scoreb == dist && scorea > ansa)
	{
	    dist = scorea - scoreb;
	    ansa = scorea;
	    ansb = scoreb;
	}
    }
    writefln("%d:%d", ansa, ansb);
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
	auto a = new int[n];
	foreach (i; 0 .. n) scanf("%d", &a[i]);
	scanf("%d", &m);
	auto b = new int[m];
	foreach (i; 0 .. m) scanf("%d", &b[i]);
	solve(a, b);
    }
}

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

int[] find(int tar, int[] arr)
{
    int left = 0, right = to!int(arr.length) - 1;
    auto ret = new int[2];
    while (left <= right)
    {
	int mid = (left + right) >> 1;
	if (arr[mid] == tar)
	{
	    ret[0] = mid;
	    ret[1] = 1;
	    return ret;
	}
	else if (arr[mid] < tar)
	{
	    left = mid + 1;
	}
	else
	{
	    right = mid - 1;
	}
    }
    ret[0] = left;
    ret[1] = 0;
    return ret;
}

void solve(int[] a, int[] b)
{
    sort(a);
    sort(b);
    long ansa = a.length << 1, ansb = b.length << 1;
    long dist = ansa - ansb;
    foreach (i; 0 .. a.length)
    {
	auto res = find(a[i], b);
	long scorea = (i + 1) * 3 + (a.length - i - 1) * 2;
	long scoreb;
	if (res[1] == 1)
	{
	    scoreb = (res[0] + 1) * 2 + (b.length - res[0] - 1) * 3;
	}
	else
	{
	    if (res[0] == 0)
	    {
		scoreb = b.length * 3;
	    }
	    else
	    {
		scoreb = res[0] * 2 + (b.length - res[0]) * 3;
	    }
	}
	if (scorea - scoreb > dist || scorea - scoreb == dist && scorea > ansa)
	{
	    dist = scorea - scoreb;
	    ansa = scorea;
	    ansb = scoreb;
	}
    }
    writefln("%d:%d", ansa, ansb);
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
	auto a = new int[n];
	foreach (i; 0 .. n) scanf("%d", &a[i]);
	scanf("%d", &m);
	auto b = new int[m];
	foreach (i; 0 .. m) scanf("%d", &b[i]);
	solve(a, b);
    }
}

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

int find(int tar, int[] arr)
{
    int left = 0, right = to!int(arr.length) - 1, ret = -1;
    while (left <= right)
    {
	int mid = (left + right) >> 1;
	if (arr[mid] == tar)
	{
	    ret = mid;
	    //left = mid + 1;
	    right = mid - 1;
	}
	else if (arr[mid] < tar)
	{
	    left = mid + 1;
	}
	else
	{
	    right = mid - 1;
	}
    }
    if (ret == -1) ret = left;
    return ret;
}

void solve(int[] a, int[] b)
{
    sort(a);
    sort(b);
    long ansa = a.length << 1, ansb = b.length << 1;
    //auto pos = find(a[0] - 1, b);
    //long ansa = a.length * 3;
    //long ansb = pos * 2 + (b.length - pos) * 3;
    long dist = ansa - ansb;
    foreach (i; 0 .. a.length)
    {
	//if (i < a.length - 1 && a[i] == a[i + 1]) continue;
	if (i > 0 && a[i] == a[i - 1]) continue;
	auto pos = find(a[i] - 1, b);
	//long scorea = (i + 1) * 3 + (a.length - i - 1) * 2;
	long scorea = i * 2 + (a.length - i) * 3;
	long scoreb;
	if (pos < b.length && b[pos] == a[i] - 1)
	{
	    scoreb = (pos + 1) * 2 + (b.length - pos - 1) * 3;
	}
	else
	{
	    scoreb = pos * 2 + (b.length - pos) * 3;
	}
	if (scorea - scoreb > dist || scorea - scoreb == dist && scorea > ansa)
	{
	    dist = scorea - scoreb;
	    ansa = scorea;
	    ansb = scoreb;
	}
    }
    writefln("%d:%d", ansa, ansb);
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
	auto a = new int[n];
	foreach (i; 0 .. n) scanf("%d", &a[i]);
	scanf("%d", &m);
	auto b = new int[m];
	foreach (i; 0 .. m) scanf("%d", &b[i]);
	solve(a, b);
    }
}

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

int find(int tar, int[] arr)
{
    int left = 0, right = to!int(arr.length) - 1, ret = -1;
    while (left <= right)
    {
	int mid = (left + right) >> 1;
	if (arr[mid] == tar)
	{
	    ret = mid;
	    //left = mid + 1;
	    right = mid - 1;
	}
	else if (arr[mid] < tar)
	{
	    left = mid + 1;
	}
	else
	{
	    right = mid - 1;
	}
    }
    if (ret == -1) ret = left;
    return ret;
}

void solve(int[] a, int[] b)
{
    sort(a);
    sort(b);
    long ansa = a.length << 1, ansb = b.length << 1;
    //auto pos = find(a[0] - 1, b);
    //long ansa = a.length * 3;
    //long ansb = pos * 2 + (b.length - pos) * 3;
    long dist = ansa - ansb;
    foreach (i; 0 .. a.length)
    {
	if (i < a.length - 1 && a[i] == a[i + 1]) continue;
	//if (i > 0 && a[i] == a[i - 1]) continue;
	auto pos = find(a[i] - 1, b);
	long scorea = (i + 1) * 3 + (a.length - i - 1) * 2;
	long scoreb = pos * 2 + (b.length - pos) * 3;
	if (scorea - scoreb > dist || scorea - scoreb == dist && scorea > ansa)
	{
	    dist = scorea - scoreb;
	    ansa = scorea;
	    ansb = scoreb;
	}
    }
    writefln("%d:%d", ansa, ansb);
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
	auto a = new int[n];
	foreach (i; 0 .. n) scanf("%d", &a[i]);
	scanf("%d", &m);
	auto b = new int[m];
	foreach (i; 0 .. m) scanf("%d", &b[i]);
	solve(a, b);
    }
}

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

int find(int tar, int[] arr)
{
    int left = 0, right = to!int(arr.length) - 1, ret = -1;
    while (left <= right)
    {
	int mid = (left + right) >> 1;
	if (arr[mid] == tar)
	{
	    ret = mid;
	    left = mid + 1;
	}
	else if (arr[mid] < tar)
	{
	    left = mid + 1;
	}
	else
	{
	    right = mid - 1;
	}
    }
    if (ret == -1) ret = left;
    return ret;
}

void solve(int[] a, int[] b)
{
    sort(a);
    sort(b);
    long ansa = a.length << 1, ansb = b.length << 1;
    long dist = ansa - ansb;
    foreach (i; 0 .. a.length)
    {
	if (i < a.length - 1 && a[i] == a[i + 1]) continue;
	auto pos = find(a[i], b);
	long scorea = (i + 1) * 3 + (a.length - i - 1) * 2;
	long scoreb = pos * 2 + (b.length - pos) * 3;
	if (scorea - scoreb > dist || scorea - scoreb == dist && scorea > ansa)
	{
	    dist = scorea - scoreb;
	    ansa = scorea;
	    ansb = scoreb;
	}
    }
    writefln("%d:%d", ansa, ansb);
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
	auto a = new int[n];
	foreach (i; 0 .. n) scanf("%d", &a[i]);
	scanf("%d", &m);
	auto b = new int[m];
	foreach (i; 0 .. m) scanf("%d", &b[i]);
	solve(a, b);
    }
}

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

int find(int tar, int[] arr)
{
    int left = 0, right = to!int(arr.length) - 1, ret = -1;
    while (left <= right)
    {
	int mid = (left + right) >> 1;
	if (arr[mid] == tar)
	{
	    ret = mid;
	    //left = mid + 1;
	    right = mid - 1;
	}
	else if (arr[mid] < tar)
	{
	    left = mid + 1;
	}
	else
	{
	    right = mid - 1;
	}
    }
    if (ret == -1) ret = left;
    return ret;
}

void solve(int[] a, int[] b)
{
    sort(a);
    sort(b);
    int ansa = a.length << 1, ansb = b.length << 1;
    //auto pos = find(a[0] - 1, b);
    //int ansa = a.length * 3;
    //int ansb = pos * 2 + (b.length - pos) * 3;
    int dist = ansa - ansb;
    foreach (i; 0 .. a.length)
    {
	//if (i < a.length - 1 && a[i] == a[i + 1]) continue;
	if (i > 0 && a[i] == a[i - 1]) continue;
	auto pos = find(a[i] - 1, b);
	//int scorea = (i + 1) * 3 + (a.length - i - 1) * 2;
	int scorea = i * 2 + (a.length - i) * 3;
	int scoreb = pos * 2 + (b.length - pos) * 3;
	if (scorea - scoreb > dist || scorea - scoreb == dist && scorea > ansa)
	{
	    dist = scorea - scoreb;
	    ansa = scorea;
	    ansb = scoreb;
	}
    }
    writefln("%d:%d", ansa, ansb);
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
	auto a = new int[n];
	foreach (i; 0 .. n) scanf("%d", &a[i]);
	scanf("%d", &m);
	auto b = new int[m];
	foreach (i; 0 .. m) scanf("%d", &b[i]);
	solve(a, b);
    }
}

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

int[] find(int tar, int[] arr)
{
    int left = 0, right = to!int(arr.length) - 1;
    auto ret = new int[2];
    while (left <= right)
    {
	int mid = (left + right) >> 1;
	if (arr[mid] == tar)
	{
	    ret[0] = mid;
	    ret[1] = 1;
	    return ret;
	}
	else if (arr[mid] < tar)
	{
	    left = mid + 1;
	}
	else
	{
	    right = mid - 1;
	}
    }
    ret[0] = left;
    ret[1] = 0;
    return ret;
}

void solve(int[] a, int[] b)
{
    sort(a);
    sort(b);
    long ansa = a.length << 1, ansb = b.length << 1;
    long dist = ansa - ansb;
    foreach (i; 0 .. a.length)
    {
	auto res = find(a[i], b);
	long scorea = (i + 1) * 3 + (a.length - i - 1) * 2;
	long scoreb;
	if (res[1] == 1)
	{
	    scoreb = res[0] * 2 + (b.length - res[0]) * 3;
	}
	else
	{
	    if (res[0] == 0)
	    {
		scoreb = b.length * 3;
	    }
	    else
	    {
		scoreb = res[0] * 2 + (b.length - res[0]) * 3;
	    }
	}
	if (scorea - scoreb > dist || scorea - scoreb == dist && scorea > ansa)
	{
	    dist = scorea - scoreb;
	    ansa = scorea;
	    ansb = scoreb;
	}
    }
    writefln("%d:%d", ansa, ansb);
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
	auto a = new int[n];
	foreach (i; 0 .. n) scanf("%d", &a[i]);
	scanf("%d", &m);
	auto b = new int[m];
	foreach (i; 0 .. m) scanf("%d", &b[i]);
	solve(a, b);
    }
}

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

int find(int tar, int[] arr)
{
    int left = 0, right = to!int(arr.length) - 1;
    while (left <= right)
    {
	int mid = (left + right) >> 1;
	if (arr[mid] == tar)
	{
	    return mid;
	}
	else if (arr[mid] < tar)
	{
	    left = mid + 1;
	}
	else
	{
	    right = mid - 1;
	}
    }
    return left;
}

void solve(int[] a, int[] b)
{
    sort(a);
    sort(b);
    long ansa = a.length << 1, ansb = b.length << 1;
    long dist = ansa - ansb;
    foreach (i; 0 .. a.length)
    {
	auto pos = find(a[i], b);
	long scorea = (i + 1) * 3 + (a.length - i - 1) * 2;
	long scoreb = pos * 2 + (b.length - pos) * 3;
	if (scorea - scoreb > dist || scorea - scoreb == dist && scorea > ansa)
	{
	    dist = scorea - scoreb;
	    ansa = scorea;
	    ansb = scoreb;
	}
    }
    writefln("%d:%d", ansa, ansb);
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
	auto a = new int[n];
	foreach (i; 0 .. n) scanf("%d", &a[i]);
	scanf("%d", &m);
	auto b = new int[m];
	foreach (i; 0 .. m) scanf("%d", &b[i]);
	solve(a, b);
    }
}


Once upon a time DravDe, an outstanding person famous for his professional achievements (as you must remember, he works in a warehouse storing Ogudar-Olok, a magical but non-alcoholic drink) came home after a hard day. That day he had to drink 9875 boxes of the drink and, having come home, he went to bed at once.DravDe dreamt about managing a successful farm. He dreamt that every day one animal came to him and asked him to let it settle there. However, DravDe, being unimaginably kind, could send the animal away and it went, rejected. There were exactly n days in DravDe’s dream and the animal that came on the i-th day, ate exactly ci tons of food daily starting from day i. But if one day the animal could not get the food it needed, it got really sad. At the very beginning of the dream there were exactly X tons of food on the farm.DravDe woke up terrified...When he retold the dream to you, he couldn’t remember how many animals were on the farm by the end of the n-th day any more, but he did remember that nobody got sad (as it was a happy farm) and that there was the maximum possible amount of the animals. That’s the number he wants you to find out. It should be noticed that the animals arrived in the morning and DravDe only started to feed them in the afternoon, so that if an animal willing to join them is rejected, it can’t eat any farm food. But if the animal does join the farm, it eats daily from that day to the n-th.

The first input line contains integers n and X (1 ≤ n ≤ 100, 1 ≤ X ≤ 104) — amount of days in DravDe’s dream and the total amount of food (in tons) that was there initially. The second line contains integers ci (1 ≤ ci ≤ 300). Numbers in the second line are divided by a space.

Output the only number — the maximum possible amount of animals on the farm by the end of the n-th day given that the food was enough for everybody.

NoteNote to the first example: DravDe leaves the second and the third animal on the farm. The second animal will eat one ton of food on the second day and one ton on the third day. The third animal will eat one ton of food on the third day.

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, X;
int[] C;

void main(string[] args) {
	auto inp = File("input.txt", "r");
	auto outp = File("output.txt", "w");
	for (string line; (line = inp.readln) != null; ) {
		{
			auto tks = line.split;
			N = tks[0].to!int;
			X = tks[1].to!int;
		}
		C = new int[N];
		{
			auto tks = inp.readln.split;
			foreach (i; 0 .. N) {
				C[i] = tks[i].to!int;
			}
		}

		int[] costs;
		foreach (i; 0 .. N) {
			costs ~= C[i] * (N - i);
		}
		costs.sort();

		int ans;
		int x = X;
		foreach (c; costs) {
			if (x >= c) {
				x -= c;
				++ans;
			}
		}
		outp.writeln(ans);
	}
}


You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).

Output one integer $$$m$$$ — the maximum median you can get.

NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 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 N, K; get(N, K);
    int[] AS; get(AS);
    int l, r = N + 1;
    auto cs = new int[](N + 1);
    while (l + 1 < r) {
        auto m = (l + r) / 2;
        cs[] = 0;
        foreach (i; 0..N) {
            cs[i + 1] += cs[i];
            cs[i + 1] += AS[i] >= m ? 1 : -1;
        }
        int min_p;
        foreach (i; K..N + 1) {
            min_p = min(min_p, cs[i - K]);
            if (cs[i] - min_p > 0) goto ok;
        }
        r = m;
        continue;
        ok:
        l = m;
    }
    writeln(l);
}

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 N, K; get(N, K);
    int[] AS; get(AS);
    int l, r = N + 1;
    auto cs = new int[](N + 1);
    while (l + 1 < r) {
        auto m = (l + r) / 2;
        cs[] = 0;
        foreach (i; 0..N) {
            cs[i + 1] += cs[i];
            cs[i + 1] += AS[i] >= m ? 1 : -1;
        }
        int min_p;
        foreach (i; K..N + 1) {
            if (cs[i] - min_p > 0) goto ok;
            min_p = min(min_p, cs[i - K]);
        }
        r = m;
        continue;
        ok:
        l = m;
    }
    writeln(l);
}

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 N, K; get(N, K);
    int[] AS; get(AS);
    int l, r = N + 1;
    auto cs = new int[](N + 1);
    while (l + 1 < r) {
        auto m = (l + r) / 2;
        cs[] = 0;
        foreach (i; 0..N) {
            cs[i + 1] += cs[i];
            cs[i + 1] += AS[i] >= m ? 1 : -1;
        }
        int min_p;
        foreach (i; K..N) {
            min_p = min(min_p, cs[i - K]);
            if (cs[i + 1] - min_p > 0) goto ok;
        }
        r = m;
        continue;
        ok:
        l = m;
    }
    writeln(l);
}

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 N, K; get(N, K);
    int[] AS; get(AS);
    int l, r = N + 1;
    while (l + 1 < r) {
        auto m = (l + r) / 2;
        int c;
        foreach (i; 0..K) if (AS[i] >= m) ++c;
        foreach (i; K..N) {
            if (c > K / 2) goto ok;
            if (AS[i - K] >= m) --c;
            if (AS[i] >= m) ++c;
        }
        if (c > K / 2) goto ok;
        {
            c = 0;
            int i;
            while (i < N && AS[i] < m) ++i;
            int j = i;
            while (i < N) {
                while (j < N && j < i + K) {
                    if (AS[j] >= m) ++c;
                    ++j;
                }
                while (j < N && AS[j] < m) ++j;
                while (j < N && AS[j] >= m) {
                    ++c;
                    ++j;
                }
                if (j - i < K) break;
                if (c > (j - i) / 2) goto ok;
                while (i < N && AS[i] >= m) {
                    --c;
                    ++i;
                }
                while (i < N && AS[i] < m) ++i;
            }
        }
        r = m;
        continue;
        ok:
        l = m;
    }
    writeln(l);
}


Omkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array $$$a = [a_1, a_2, \ldots, a_n]$$$ of $$$n$$$ distinct integers. An array $$$b = [b_1, b_2, \ldots, b_k]$$$ is called nice if for any two distinct elements $$$b_i, b_j$$$ of $$$b$$$, $$$|b_i-b_j|$$$ appears in $$$b$$$ at least once. In addition, all elements in $$$b$$$ must be distinct. Can you add several (maybe, $$$0$$$) integers to $$$a$$$ to create a nice array $$$b$$$ of size at most $$$300$$$? If $$$a$$$ is already nice, you don't have to add any elements.For example, array $$$[3, 6, 9]$$$ is nice, as $$$|6-3|=|9-6| = 3$$$, which appears in the array, and $$$|9-3| = 6$$$, which appears in the array, while array $$$[4, 2, 0, 6, 9]$$$ is not nice, as $$$|9-4| = 5$$$ is not present in the array.For integers $$$x$$$ and $$$y$$$, $$$|x-y| = x-y$$$ if $$$x > y$$$ and $$$|x-y| = y-x$$$ otherwise.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \leq t \leq 50$$$), the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \cdots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$) — the elements of the array $$$a$$$.

For each test case, output one line containing YES if Omkar can create a nice array $$$b$$$ by adding elements to $$$a$$$ and NO otherwise. The case of each letter does not matter, so yEs and nO will also be accepted. If the first line is YES, output a second line containing a single integer $$$k$$$ ($$$n \leq k \leq 300$$$).  Then output one line containing $$$k$$$ distinct integers $$$b_1, b_2, \cdots, b_k$$$ ($$$-10^9 \leq b_i \leq 10^9$$$), the elements of the nice array $$$b$$$. $$$b_1, b_2, \cdots, b_k$$$ can be in any order. For each $$$a_i$$$ in $$$a$$$, $$$a_i$$$ must appear at least once in $$$b$$$. It can be proved that if Omkar can create such an array $$$b$$$, then he can also do so in a way that satisfies the above constraints. If multiple solutions exist, you can print any.

// Vicfred
// https://codeforces.com/contest/1536/problem/A
//
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int t = readln.chomp.to!int;

while(t--) {
    int n = readln.chomp.to!int;
    int[] a = readln.split.map!(to!int).array;

    if(a.count!(x => x < 0) > 0) {
        "NO".writeln;
    } else {
        "YES".writeln;
        "101".writeln;
        for(int i = 0; i < 101; ++i)
            writef("%s ", i);
        "".writeln;
    }
}
}

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

void main() {
    foreach(t; 0 .. to!int(readln.strip)) {
        int n = to!int(readln.strip);
        auto nums = readln.split.map!(to!int).array.sort;
        if(nums[0] < 0) {
            writeln("NO");
        } else {
            writeln("YES");
            writeln(nums[$-1]+1);
            writeln(iota(nums[$-1]+1).map!(to!string).join(" "));
        }
    }
}

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

int[] solve(ref int[] a, size_t bbase, ref int[int] freq)
{
  size_t n = a.length;
  foreach (i ; bbase .. n)
    freq[a[i]] = 1;

  int[int] b;
  foreach (i ; bbase .. n) {
    foreach (j ; 0 .. i) {
      int diff = abs(a[i] - a[j]);
      if (!freq.get(diff, 0)) {
        b[diff] = 1;
      }
    }
  }

  if (b.length == 0)
    return a;

  if (a.length + b.length > 300)
    return [];

  bbase = a.length;
  a ~= b.keys;
  return solve(a, bbase, freq);
}

void main()
{
  int t;
  readf!" %d "(t);
  foreach (casenum ; 0 .. t) {
    int n;
    readf!" %d "(n);
    auto a = readln.chomp.split.map!(to!int).array;
//    writeln(a);
    int[int] freq;

    auto result = solve(a, 0, freq);
    if (result.length == 0) {
      writeln("NO");
    } else {
      writeln("YES");
      writeln(result.length);
      writeln(result.map!text.joiner(" "));
    }
  }
}

// Cheese-Cracker: cheese-cracker.github.io

void theCode(){
    ll n = scan;
    auto arr = scanArray;
    ll maxx = 0;
    foreach(el; arr){
        if(el < 0){
            writeln("NO");
            return;
        }
        maxx = max(el, maxx);
    }
    writeln("YES");
    writeln(maxx+1);
    foreach(el; 0..maxx+1){
        write(el, " ");
    }
    writeln;
}

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

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

import std.stdio;
import std.algorithm;
import std.numeric;
void solve (){
  int n;
  readf!"%d\n"(n);
  int [] x;
  for (int i = 0; i < n-1; i ++){
    int u;
    readf!"%d "(u);
    x ~= u;
  }
  int u;
  readf!"%d\n"(u);
  x ~= u;
  x.sort!"a < b"();
  if (x[0] < 0){
    writeln("nO");
    return;
  }
  int max = x[n-1];
  writeln("yEs\n", max+1);
  for(int i = 0; i <= max; i ++){
    write(i, " ");
  }
  writeln();
}

void main (){
  int t;
  readf!"%d\n"(t);
  while(t--){
    solve();
  }
}

// Vicfred
// https://codeforces.com/contest/1536/problem/A
//
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.stdio;
import std.string;

long abs(long n) {
    return n < 0 ? -n : n;
}

bool contains(long[] a, long item) {
    foreach(x; a)
        if(x == item)
            return true;
    return false;
}

void main() {
    int t = readln.chomp.to!int;

while(t--) {
    long n = readln.chomp.to!long;
    long[] a = readln.split.map!(to!long).array;

    while(n < 301) {
        bool found = false;
        n = cast(long)a.length;
        for(int i = 0; i < n; ++i) {
            for(int j = i + 1; j < n; ++j) {
                long x = abs(a[i] - a[j]);
                if(!a.contains(x)) {
                    //writefln("%s no esta", x);
                    a ~= x;
                    found = true;
                }
            }
        }
        if(!found) {
            break;
        }
    }
    if(n >= 301) {
        "NO".writeln;
    } else {
        "YES".writeln;
        foreach(item; a) {
            writef("%s ", item);
        } "".writeln;
    }
}
}

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

void main() {
    foreach(t; 0 .. to!int(readln.strip)) {
        int n = to!int(readln.strip);
        auto nums = readln.split.map!(to!int).array.sort;
        if(nums[0] < 0) {
            writeln("NO");
        } else {
            writeln("YES");
            writeln(nums[$-1]-nums[0]+1);
            writeln(iota(nums[$-1]+1).map!(to!string).join(" "));
        }
    }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers.Let $$$min(l, r)$$$ be the minimum value among $$$a_l, a_{l + 1}, \ldots, a_r$$$ and $$$max(l, r)$$$ be the maximum value among $$$a_l, a_{l + 1}, \ldots, a_r$$$.Your task is to choose three positive (greater than $$$0$$$) integers $$$x$$$, $$$y$$$ and $$$z$$$ such that:  $$$x + y + z = n$$$;  $$$max(1, x) = min(x + 1, x + y) = max(x + y + 1, n)$$$. In other words, you have to split the array $$$a$$$ into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).Among all such triples (partitions), you can choose any.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: NO in the only line if there is no such partition of $$$a$$$ that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers $$$x$$$, $$$y$$$ and $$$z$$$ ($$$x + y + z = n$$$) in the second line. If there are several answers, you can print any.

YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4

// Author: Ivan Kazmenko (gassa@mail.ru)
module solution;
import std.algorithm, std.conv, std.range, std.stdio, 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, x = a.dup, y = a.dup;
		foreach (i; 1..n) x[i] = max (x[i], x[i - 1]);
		foreach_reverse (i; 0..n - 1) y[i] = max (y[i], y[i + 1]);
		auto v = a.maxElement;
		auto maxPlaces = n.iota.filter !(i => a[i] == v).array;
		int lo = maxPlaces[$ / 2], hi = lo + 1;
		while (true) {
			if (lo == 0 || hi == n) {
				writeln ("NO");
				break;
			}
			if (x[lo - 1] == v && y[hi] == v) {
				writeln ("YES");
				writeln (lo, " ", hi - lo, " ", n - hi);
				break;
			}
			int u = (lo - 1 == 0) ? int.min : min (x[lo - 2], a[lo - 1]);
			int w = (hi + 1 == n) ? int.min : min (y[hi + 1], a[hi]);
			if (u > w) v = min (v, a[--lo]);
			else v = min (v, a[hi++]);
		}
	}
}


You are given a binary array$$$^{\dagger}$$$ of length $$$n$$$. You are allowed to perform one operation on it at most once. In an operation, you can choose any element and flip it: turn a $$$0$$$ into a $$$1$$$ or vice-versa.What is the maximum number of inversions$$$^{\ddagger}$$$ the array can have after performing at most one operation?$$$^\dagger$$$ A binary array is an array that contains only zeroes and ones.$$$^\ddagger$$$ The number of inversions in an array is the number of pairs of indices $$$i,j$$$ such that $$$i<j$$$ and $$$a_i > a_j$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the array. The following line contains $$$n$$$ space-separated positive integers $$$a_1$$$, $$$a_2$$$,..., $$$a_n$$$ ($$$0 \leq a_i \leq 1$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, output a single integer  — the maximum number of inversions the array can have after performing at most one operation.

NoteFor the first test case, the inversions are initially formed by the pairs of indices ($$$1, 2$$$), ($$$1, 4$$$), ($$$3, 4$$$), being a total of $$$3$$$, which already is the maximum possible.For the second test case, the inversions are initially formed by the pairs of indices ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$), being a total of four. But, by flipping the first element, the array becomes $$${1, 1, 0, 0, 1, 0}$$$, which has the inversions formed by the pairs of indices ($$$1, 3$$$), ($$$1, 4$$$), ($$$1, 6$$$), ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$) which total to $$$7$$$ inversions which is the maximum possible.

import std;

long cntinv(int[] a)
{
  long ans = 0;
  int cnt1 = 0;
  foreach (i ; 0 .. a.length) {
    if (a[i] == 1)
      cnt1++;
    if (a[i] == 0)
      ans += cnt1;
  }
  return ans;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.splitter.map!(to!int).array;
    int[] pfa = [0];
    foreach (x ; a)
      pfa ~= pfa.back + x;
    long ans = cntinv(a);
    long bestans = ans;
    foreach (i ; 0 .. a.length.to!int) {
      int left1  = pfa[i] - pfa[0];
      int left0  = i - left1;
      int right1 = pfa[a.length] - pfa[i + 1];
      int right0 = (n - (i + 1)) - right1;
//      writefln("i=%d l1=%d l0=%d r1=%d r0=%d", i, left1, left0, right1, right0);
      if (a[i] == 0) {
        long tmp = ans - left1 + right0;
        bestans = max(tmp, bestans);
      } else {
        long tmp = ans - right0 + left1;
        bestans = max(tmp, bestans);
      }
    }
    writeln(bestans);
  }
}


You have a string of decimal digits s. Let's define bij = si·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j) such that x ≤ i ≤ y, z ≤ j ≤ t.

The first line contains integer a (0 ≤ a ≤ 109), the second line contains a string of decimal integers s (1 ≤ |s| ≤ 4000).

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

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 MAX_SUM = 36004;

void main ()
{
	int a;
	while (readf (" %s ", &a) > 0)
	{
		auto s = readln ().strip ();
		int n = s.length;
		int [] b;
		foreach (c; s)
		{
			b ~= c - '0';
		}
		debug {writeln (b);}
		int [MAX_SUM] t;
		foreach (i; 0..n)
		{
			int cur = 0;
			foreach (j; i..n)
			{
				cur += b[j];
				t[cur]++;
			}
		}

		long res = 0;
		foreach (i; 0..t.length)
		{
		        for (int j = i; j < t.length && i * j <= a; j++)
		        {
				if (i * j == a)
				{
					debug {writefln ("%s:%s, %s:%s",
					                 i, t[i], j, t[j]);}
					res += t[i] * cast (long) t[j] *
					       (1 + (i < j));
				}
			}
		}

		writeln (res);
	}
}

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 MAX_SUM = 36004;

void main ()
{
	int a;
	while (readf (" %s ", &a) > 0)
	{
		auto s = readln ().strip ();
		int n = s.length;
		int [] b;
		foreach (c; s)
		{
			b ~= c - '0';
		}
		debug {writeln (b);}
		int [MAX_SUM] t;
		foreach (i; 0..n)
		{
			int cur = 0;
			foreach (j; i..n)
			{
				cur += b[j];
				t[cur]++;
			}
		}

		long res = 0;
		if (a == 0)
		{
			long q = 0;
			foreach (i; 0..t.length)
			{
				q += t[i];
			}
			res = q * q;
		}
		else
		foreach (i; 0..t.length)
		{
		        for (int j = ((i == 0) ? 0 : a / i); j < t.length && i * j <= a; j++)
		        {
				if (i * j == a)
				{
					debug {writefln ("%s:%s, %s:%s",
					                 i, t[i], j, t[j]);}
					res += t[i] * cast (long) t[j];
				}
			}
		}

		writeln (res);
	}
}


You are given a sequence of positive integers a1, a2, ..., an. While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a single integer x + 1 on their place. This way the number of elements in the sequence is decreased by 1 on each step. You stop performing the operation when there is no pair of equal consecutive elements.For example, if the initial sequence is [5, 2, 1, 1, 2, 2], then after the first operation you get [5, 2, 2, 2, 2], after the second — [5, 3, 2, 2], after the third — [5, 3, 3], and finally after the fourth you get [5, 4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.Determine the final sequence after you stop performing the operation.

The first line contains a single integer n (2 ≤ n ≤ 2·105) — the number of elements in the sequence. The second line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109).

In the first line print a single integer k — the number of elements in the sequence after you stop performing the operation.  In the second line print k integers — the sequence after you stop performing the operation.

NoteThe first example is described in the statements.In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].In the third example there are no two equal consecutive elements initially, so the sequence does not change.

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	int [] bk = new int[n];
	int tk = -1;
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	for(int e = 0; e < n; e++){
        if(tk == -1){
            bk[++tk] = arr[e];
        } else {
            while(tk >= 0 && bk[tk] == arr[e]){
                tk--;
                arr[e]++;
            }
            bk[++tk] = arr[e];
        }
    }
    printf("%d\n", tk + 1);
    for(int e = 0; e <= tk; e++)
        printf("%d ", bk[e]);
    printf("\n");
	return 0;
}

import std.stdio;

/* Hello World Program in D Programming */
void main(string[ ] args)
{
    int n;
    scanf("%d", &n);
    int[211111] a;
    int a_len = 0;
    for (int i = 0; i < n; ++i) {
        scanf("%d", &a[i]);
    }
    for (int i = 0; i < n; ++i) {
        a[a_len] = a[i];
        ++a_len;
        while (a_len > 1 && a[a_len - 1] == a[a_len - 2]) {
            --a_len;
            ++a[a_len - 1];
        }
    }
    printf("%d\n", a_len);
    for (int i = 0; i < a_len; ++i) {
        printf("%d ", a[i]);
    }
    printf("\n");

    return;
}

import std.stdio;

void main() {
  int n; readf(" %s", &n);
  auto ok = new int[n];
  int top=0;
  for (int i = 0; i < n; i++) {
    int k; readf(" %s", &k);
      if(top==0){ok[top]=k; top++;}
    else
    {
        if(ok[top-1]!=k){ok[top]=k; top++;}
      else
      {while(ok[top-1]==k && top>0)
      {
        ok[top-1]=k+1;
        k++;
        top--;
      }
      top++;
      }
    }

  }
  writeln(top);
  writeln("\n");
   int i=0;
  while(i<top) {
    writeln(ok[i]);
      i++;
    writeln(" ");
  }

}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto p = [0] ~ readln.splitter.map !(to !(int)).array;
		auto a = new int [n + 1];
		auto cp = 0;
		foreach (i; 1..n + 1)
		{
		    auto x = p[i];
		    while (cp > 0 && a[cp] == x) {
		        x += 1;
		        cp -= 1;
		    }
		    cp += 1;
		    a[cp] = x;
		}
		writeln(cp);
		foreach (i; 1..cp + 1)
		{
		    write(a[i]);
		    write(" ");
		}
	}
}

module main;

import std.stdio;
import std.string;

int main(string[] argv)
{
	int n, j = 0;
	scanf("%d", &n);
    int [] a = new int[n];
    for(int i = 0; i < n; i++)
    {
    scanf("%d", &a[j]);
    while(j > 0 && a[j] == a[j - 1])
    {
        a[j - 1]++;
         a[j] = 0;
        j--;
     }
    j++;
    }
    writeln(j);
    for(int i = 0; i < j; i++)
       write(a[i]," ");

	return 0;
}

import core.stdc.stdio;
int n;
int [333333] a;
int [333333] nxt;
int [333333] prv;
void suka(int pos) {
    a[pos] += 1;
    nxt[pos] = nxt[nxt[pos]];
    if(nxt[pos] < n)
        prv[nxt[pos]] = pos;
}
void main()
{
	scanf("%d",&n);
	int len = n;
	for (int i=0;i<n;i++) {
	    scanf("%d",&a[i]);
	    nxt[i] = i + 1;
	    prv[i] = i - 1;
    }
	for (int i;i<n;) {
	    int nx = nxt[i];
	    if(i + 1 < n) {
	        if(a[i] == a[nx]) {
	            suka(i);
	            len--;
	            i = prv[i];
	            continue;
            }
	    }
	    i = nx;
	}
	printf("%d\n", len);
	for (int i;i<n;) {
	    int nx = nxt[i];
	    printf("%d ", a[i]);
	    i = nx;
	}
	printf("\n");
}

import std.stdio;

void main()
{
    int[900100] a;
    int n;
    int it = 0, t;
    readf("%d\n", &n);
    for(int i = 0; i < n; i++, it++)
    {
        readf("%d ", &t);
        a[it] = t;
        if(it == 0)
            continue;
        while(a[it] == a[it - 1])
        {
            it--;
            // writef("add to %d\n", it);
            // writef("%d\n", a[it]);
            a[it] = a[it] + 1;
            // writef("%d\n", a[it]);
        }
    }

    // writef("her: %d\n", a[0]);
    writef("%d\n", it);

    for(int k = 0; k < it; k++)
        writef("%d ", a[k]);
}

import std.stdio, std.bigint, std.string;

void main() {
    int n;
    scanf("%d", &n);
    int[] a = new int[n];
    for(int i = 0; i<n; i++) {
		scanf("%d", &a[i]);
	}
	int [] b= new int[n];
	for (int i =0; i < n; ++i) {
	    b[i] = -1;
	}
	b[0] = a[0];
	int c = 1;
	int i = 1;
	while (i < n) {
		c +=1;
		b[c-1] = a[i];

		while (c > 1 && b[c-1] == b[c-2]) {
		    b[c-2] = b[c-2] +1;
		    c-=1;
		}
		i += 1;
	}
    writeln(c);
    for (int j = 0; j < c; ++j) {
        write(b[j]);
        write(" ");
    }
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	int l=0;
	for(int i = 0; i<n; i++)
	{
		scanf("%d", &arr[l]);
		if(l>0)
		{
			while(1)
			{
				if(arr[l]==arr[l-1])
				{
					arr[l-1]++;
					l--;
				}
				else
				{
					break;
				}
			}
		}
		l++;
	}
	printf("%d\n", l);
	for(int i=0;i<l;i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

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

  int n; rd(n);
  auto x=readln.split.to!(int[]);
    int[200005] val,pre,nxt;
  for(int i=1;i<=n;i++) {
    val[i]=x[i-1];
    pre[i]=i-1;
    nxt[i]=i+1;
  }
  nxt[0]=1;
  pre[n+1]=n;
  int cnt=n;
  for(int i=nxt[1];i<=n;i=nxt[i]) {
    while(val[i]==val[pre[i]]) {
        val[i]++;
        cnt--;
        nxt[pre[pre[i]]]=nxt[pre[i]];
        pre[nxt[pre[i]]]=pre[pre[i]];
    }
  }
  writeln(cnt);
  for(int i=nxt[0];i<=n;i=nxt[i])
    write(val[i]),write(' ');
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x){
    e=l[i].to!(typeof(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.range;
import std.numeric;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = stdin;

  auto n = next!int;
  auto a = next!int(n);
  auto finalA = DList!int();
  foreach(ai; a)
    {
      auto toInsert = ai;
      while (!finalA.empty && finalA.front == toInsert)
	{
	  finalA.removeFront;
	  toInsert++;
	}
      finalA.insertFront(toInsert);
    }
  auto finalAArray = finalA[].array;
  finalAArray.length.writeln;
  foreach_reverse(fai; finalAArray)
    write(fai, " ");
  writeln;
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  string toString()
  {
    return to!string(rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
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.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto p = [0] ~ readln.splitter.map !(to !(int)).array;
		auto a = new int [n + 1];
		auto cp = 0;
		foreach (i; 1..n + 1)
		{
		    auto x = p[i];
		    while (cp > 0 && a[cp] == x) {
		        x += 1;
		        cp -= 1;
		    }
		    cp += 1;
		    a[cp] = x;
		}
		foreach (i; 1..cp + 1)
		{
		    write(a[i]);
		    write(" ");
		}
	}
}

import std.stdio;

void main()
{
    int[101000] a;
    int n;
    int it = 0, t;
    readf("%d\n", &n);
    for(int i = 0; i < n; i++, it++)
    {
        readf("%d ", &t);
        a[it] = t;
        if(it == 0)
            continue;
        if(a[it] == a[it - 1])
        {
            it--;
            // writef("add to %d\n", it);
            // writef("%d\n", a[it]);
            a[it] = a[it] + 1;
            // writef("%d\n", a[it]);
        }
    }

    // writef("her: %d\n", a[0]);

    for(int k = 0; k < it; k++)
        writef("%d ", a[k]);
}

import std.stdio;

void main()
{
    int[101000] a;
    int n;
    int it = 0, t;
    readf("%d\n", &n);
    for(int i = 0; i < n; i++, it++)
    {
        readf("%d ", &t);
        a[it] = t;
        if(it == 0)
            continue;
        if(a[it] == a[it - 1])
        {
            it--;
            // writef("add to %d\n", it);
            // writef("%d\n", a[it]);
            a[it] = a[it] + 1;
            // writef("%d\n", a[it]);
        }
    }

    // writef("her: %d\n", a[0]);
    writef("%d\n", it);

    for(int k = 0; k < it; k++)
        writef("%d ", a[k]);
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	int l=0;
	for(int i = 0; i<n; i++)
	{
		scanf("%d", &arr[l]);
		if(l>0)
		{
			while(1)
			{
				if(arr[l]==arr[l-1])
				{
					arr[l-1]++;
					l--;
				}
				else
				{
					break;
				}
			}
		}
		l++;
	}
	printf("%d", l);
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	int l=0;
	for(int i = 0; i<n; i++)
	{
		scanf("%d", &arr[l]);
		if(l>0)
		{
			while(1)
			{
				if(arr[l]==arr[l-1])
				{
					arr[l-1]++;
					l--;
				}
				else
				{
					break;
				}
			}
		}
		l++;
	}
	printf("%d", l);
	for(int i=0;i<l;i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}


You are given a digital clock with $$$n$$$ digits. Each digit shows an integer from $$$0$$$ to $$$9$$$, so the whole clock shows an integer from $$$0$$$ to $$$10^n-1$$$. The clock will show leading zeroes if the number is smaller than $$$10^{n-1}$$$.You want the clock to show $$$0$$$ with as few operations as possible. In an operation, you can do one of the following:   decrease the number on the clock by $$$1$$$, or  swap two digits (you can choose which digits to swap, and they don't have to be adjacent). Your task is to determine the minimum number of operations needed to make the clock show $$$0$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — number of digits on the clock. The second line of each test case contains a string of $$$n$$$ digits $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \le s_1, s_2, \ldots, s_n \le 9$$$) — the number on the clock. Note: If the number is smaller than $$$10^{n-1}$$$ the clock will show leading zeroes.

For each test case, print one integer: the minimum number of operations needed to make the clock show $$$0$$$.

NoteIn the first example, it's optimal to just decrease the number $$$7$$$ times.In the second example, we can first swap the first and last position and then decrease the number by $$$1$$$.In the third example, the clock already shows $$$0$$$, so we don't have to perform any operations.

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

void main()
{
    int t;
    scanf("%d", &t);
    foreach(_; 0..t)
    {
        int str_len;
        scanf("%d", &str_len);
        getchar();
        auto str = readln.strip();
        // writeln(str);
        uint[] arr = new uint[str_len];

        for(int i = 0; i < str_len; i++)
        {
            arr[i] = to!uint(str[i..i + 1]);
        }
        auto zeros = new uint[str_len];
        long res = 0;
        int last_non_null = str_len - 1;
        while (arr != zeros)
        {
            if (arr[last_non_null] == 0){
                last_non_null--;
            }
            else
            {
                if (last_non_null != str_len - 1)
                    res += 1;
                res += arr[last_non_null];
                arr[last_non_null] = 0;
                last_non_null--;
            }
        }
        writeln(res);
    }
}


Let's denote that some array $$$b$$$ is bad if it contains a subarray $$$b_l, b_{l+1}, \dots, b_{r}$$$ of odd length more than $$$1$$$ ($$$l < r$$$ and $$$r - l + 1$$$ is odd) such that $$$\forall i \in \{0, 1, \dots, r - l\}$$$ $$$b_{l + i} = b_{r - i}$$$.If an array is not bad, it is good.Now you are given an array $$$a_1, a_2, \dots, a_n$$$. Some elements are replaced by $$$-1$$$. Calculate the number of good arrays you can obtain by replacing each $$$-1$$$ with some integer from $$$1$$$ to $$$k$$$.Since the answer can be large, print it modulo $$$998244353$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n, k \le 2 \cdot 10^5$$$) — the length of array $$$a$$$ and the size of "alphabet", i. e., the upper bound on the numbers you may use to replace $$$-1$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_i = -1$$$ or $$$1 \le a_i \le k$$$) — the array $$$a$$$.

Print one integer — the number of good arrays you can get, modulo $$$998244353$$$.

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

int saiki(int idx, int flag, int k, int[][] dp)
{
    if (dp[idx][flag] != -1) return dp[idx][flag];
    if (idx == 0)
    {
        dp[idx][flag] = 1;
        return 1;
    }
    if (idx == 1)
    {
        if (flag == 0) dp[idx][flag] = k - 2;
        else dp[idx][flag] = k - 1;
        return dp[idx][flag];
    }
    static const int mod = 998244353;
    long ret0 = saiki(idx - 1, 1, k, dp);
    long ret1 = saiki(idx - 1, 0, k, dp);
    if (flag == 0) dp[idx][flag] = (ret0 + ret1 * (k - 2)) % mod;
    else dp[idx][flag] = (ret1 * (k - 1)) % mod;
    return dp[idx][flag];
}

void calc(int left, int k, int[] a, int[][] dp, ref long ans)
{
    static const int mod = 998244353;
    auto n = cast(int)a.length;
    int right;
    if ((n & 1) ^ left) right = n - 1;
    else right = n - 2;
    auto L = 0;
    while (left < n && a[left] == -1)
    {
        left += 2;
        ++ L;
    }
    if (left >= n)
    {
        foreach (i; 0 .. L - 1) ans = (ans * (k - 1)) % mod;
        ans = (ans * k) % mod;
        return;
    }
    foreach (i; 0 .. L) ans = (ans * (k - 1)) % mod;
    while (right >= 0 && a[right] == -1)
    {
        right -= 2;
        ans = (ans * (k - 1)) % mod;
    }
    for (int j, i = left; i < right; i = j)
    {
        for (j = i + 2; j < right && a[j] == -1; j += 2) {}
        L = (j - i) / 2 - 1;
        if (a[i] != a[j])
        {
            ans *= saiki(L, 0, k, dp);
        }
        else
        {
            if (L == 0)
            {
                ans = 0;
                return;
            }
            ans *= saiki(L, 1, k, dp);
        }
        ans %= mod;
    }
}

void solve(int[] a, int k)
{
    static const int mod = 998244353;
    auto n = cast(int)a.length;
    auto dp = new int[][]((n >> 1) + 2, 2);
    foreach (i; 0 .. (n >> 1) + 2) fill(dp[i], -1);
    long ans = 1;
    calc(0, k, a, dp, ans);
    if (ans != 0 && n > 1) calc(1, k, a, dp, ans);
    writeln(ans);
}

int main(string[] args)
{
    int n, k;
    while (readf("%d %d\n", &n, &k) == 2)
    {
        auto a = new int[n];
        foreach (i; 0 .. n) readf(" %d", &a[i]);
        readln;
        solve(a, k);
    }
    return 0;
}


Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.

The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children.

Print "Yes" if the tree is a spruce and "No" otherwise.

NoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example:

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, std.datetime;

void main() {
    auto N = readln.chomp.to!int;
    auto G = new int[][](N);
    foreach (i; 0..N-1) {
        auto v = readln.chomp.to!int;
        G[v-1] ~= i+1;
    }

    auto is_leaf = new bool[](N);
    foreach (i; 0..N) is_leaf[i] = G[i].length == 0;

    auto ok = new bool[](N);
    foreach (i; 0..N) {
        if (is_leaf[i]) {
            ok[i] = true;
            continue;
        }
        int cnt = 0;
        foreach (m; G[i]) {
            cnt += is_leaf[m];
        }
        ok[i] = cnt >= 3;
    }

    writeln(ok.all ? "Yes" : "No");
}

void main() {
	auto N = ri;
	int[][] tree = new int[][](N+3, 0);
	//foreach(i; 2..N+2) tree[i] = [];
	foreach(i; 2..N+1) {
		auto p = ri;
		tree[p] ~= i;
	}
	ulong k;
	int[][] que;
	que = [[],[]];
	que[0] ~= 1;
	bool flag = true;
	while(que[k%2] != []) {
		auto p = que[k%2].front;
		que[k%2].popFront;
		ulong cnt;
		bool ok = true;
		foreach(i; tree[p]) {
			que[(k+1)%2] ~= i;
			debug writefln("%s %s %s", tree[i], [], tree[i] == []);
			if(tree[i] == []) cnt++;
			else ok = false;
		}
		if((!ok && cnt == 0) || cnt != 0 && cnt < 3) flag = false;
		k++;
	}
	writeln(flag ? "Yes" : "No");
}

// ===================================

import std.stdio;
import std.string;
import std.functional;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;

T readAs(T)() if (isBasicType!T) {
	return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
	return readln.split.to!T;
}

T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		res[i] = readAs!(T[]);
	}
	return res;
}

T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		auto s = rs;
		foreach(j; 0..width) res[i][j] = s[j].to!T;
	}
	return res;
}

int ri() {
	return readAs!int;
}

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}

/+ dub.sdl:
    name "B"
    dependency "dunkelheit" version=">=0.9.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dkh.foundation, dkh.scanner;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) sc.read!true;

    int n;
    sc.read(n);
    int[][] g = new int[][](n);
    foreach (i; 1..n) {
        int p;
        sc.read(p); p--;
        g[p] ~= i;
    }

    bool ans = true;
    int dfs(int p) {
        if (g[p].length == 0) return 1;
        int u = 0;
        foreach (d; g[p]) {
            u += dfs(d);
        }
        if (u < 3) ans = false;
        return 0;
    }
    dfs(0);
    if (ans) writeln("Yes");
    else writeln("No");
    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
    void read(bool enforceEOF = false, T, Args...)(ref T x, auto ref Args args) {
        import std.exception;
        enforce(readSingle(x));
        static if (args.length == 0) {
            enforce(enforceEOF == false || !succ());
        } else {
            read!enforceEOF(args);
        }
    }
    void read(bool enforceEOF = false, Args...)(auto ref Args args) {
        import std.exception;
        static if (args.length == 0) {
            enforce(enforceEOF == false || !succ());
        } else {
            enforce(readSingle(args[0]));
            read!enforceEOF(args);
        }
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/

import core.bitop;
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;

bool solve (int [] p)
{
	auto n = p.length;
	auto d = new int [n];
	foreach (i; 1..n)
	{
		d[p[i]] += 1;
	}
	auto isLeaf = new bool [n];
	auto leafSons = new int [n];
	foreach (i; 1..n)
	{
		isLeaf[i] = (d[i] == 0);
		leafSons[p[i]] += isLeaf[i];
	}
	foreach (i; 0..n)
	{
		if (!isLeaf[i])
		{
			if (leafSons[i] < 3)
			{
				return false;
			}
		}
	}
	return true;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new int [n];
		foreach (i; 1..n)
		{
			readf (" %s", &p[i]);
		}
		p[] -= 1;
		writeln (solve (p) ? "Yes" : "No");
	}
}

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

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

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

    foreach (i ; 1 .. n) {
        int pi;
        scan(pi);
        adj[pi-1] ~= i;
    }

    bool ans = true;

    void dfs(int v, int p) {
        if (adj[v].empty) return;

        int lc;

        foreach (u ; adj[v]) {
            if (u == p) continue;
            if (adj[u].empty) {
                lc++;
            }
            else {
                dfs(u, v);
            }
        }

        if (lc < 3) ans = false;

        return;
    }

    dfs(0,0);

    writeln(ans ? "Yes" : "No");
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    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; rd(n);
  auto par=new int[](n);
  par[0]=-1;
  foreach(int i; 1..n){
    int p; rd(p);
    par[i]=(p-1);
  }

  auto leaf=new bool[](n);
  foreach(i; 0..n){
    auto c=count(par, i);
    if(c==0) leaf[i]=true;
  }
  foreach(i; 0..n)if(leaf[i]==false){
    int c=0;
    foreach(j; 0..n){
      if(par[j]==i && leaf[j]) c++;
    }
    if(c<3){writeln("No"); return;}
  }
  writeln("Yes");
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x){
    e=l[i].to!(typeof(e));
  }
}
void wr(T...)(T x){
  import std.stdio;
  foreach(e; x) write(e, " ");
  writeln();
}

void main() {
	auto N = ri;
	int[] arr;
	foreach(i; 0..N-1) arr ~= ri;
	bool[ulong] m;
	arr.enumerate.filter!(i => i.value == 1).map!(i => i.index).array.each!(i => m[i] = true);
	arr.enumerate.filter!(i => i.value != 1).each!(i => m[i.value-1] = false);
	if(m.values.count!(i => i) == 3) writeln("Yes");
	else writeln("No");
}

// ===================================

import std.stdio;
import std.string;
import std.functional;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;

T readAs(T)() if (isBasicType!T) {
	return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
	return readln.split.to!T;
}

T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		res[i] = readAs!(T[]);
	}
	return res;
}

T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		auto s = rs;
		foreach(j; 0..width) res[i][j] = s[j].to!T;
	}
	return res;
}

int ri() {
	return readAs!int;
}

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}

void main() {
	auto N = ri;
	int[][] tree = new int[][](N+3, 0);
	//foreach(i; 2..N+2) tree[i] = [];
	foreach(i; 2..N+1) {
		auto p = ri;
		tree[p] ~= i;
	}
	ulong k;
	int[][] que;
	que = [[],[]];
	que[0] ~= 1;
	bool flag = true;
	while(que[k%2] != []) {
		auto p = que[k%2].front;
		que[k%2].popFront;
		ulong cnt;
		foreach(i; tree[p]) {
			que[(k+1)%2] ~= i;
			debug writefln("%s %s %s", tree[i], [], tree[i] == []);
			if(tree[i] == []) cnt++;
		}
		if(cnt != 0 && cnt < 3) flag = false;
		k++;
	}
	writeln(flag ? "Yes" : "No");
}

// ===================================

import std.stdio;
import std.string;
import std.functional;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;

T readAs(T)() if (isBasicType!T) {
	return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
	return readln.split.to!T;
}

T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		res[i] = readAs!(T[]);
	}
	return res;
}

T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		auto s = rs;
		foreach(j; 0..width) res[i][j] = s[j].to!T;
	}
	return res;
}

int ri() {
	return readAs!int;
}

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}


Suppose you are given a string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters. You need to compress it using the smallest possible number of coins.To compress the string, you have to represent $$$s$$$ as a concatenation of several non-empty strings: $$$s = t_{1} t_{2} \ldots t_{k}$$$. The $$$i$$$-th of these strings should be encoded with one of the two ways:  if $$$|t_{i}| = 1$$$, meaning that the current string consists of a single character, you can encode it paying $$$a$$$ coins;  if $$$t_{i}$$$ is a substring of $$$t_{1} t_{2} \ldots t_{i - 1}$$$, then you can encode it paying $$$b$$$ coins. A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.So your task is to calculate the minimum possible number of coins you need to spend in order to compress the given string $$$s$$$.

The first line contains three positive integers, separated by spaces: $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \leq n, a, b \leq 5000$$$) — the length of the string, the cost to compress a one-character string and the cost to compress a string that appeared before. The second line contains a single string $$$s$$$, consisting of $$$n$$$ lowercase English letters.

Output a single integer — the smallest possible number of coins you need to spend to compress $$$s$$$.

NoteIn the first sample case, you can set $$$t_{1} =$$$ 'a', $$$t_{2} =$$$ 'b', $$$t_{3} =$$$ 'a' and pay $$$3 + 3 + 1 = 7$$$ coins, since $$$t_{3}$$$ is a substring of $$$t_{1}t_{2}$$$.In the second sample, you just need to compress every character by itself.In the third sample, you set $$$t_{1} = t_{2} =$$$ 'a', $$$t_{3} =$$$ 'aa' and pay $$$10 + 1 + 1 = 12$$$ coins, since $$$t_{2}$$$ is a substring of $$$t_{1}$$$ and $$$t_{3}$$$ is a substring of $$$t_{1} t_{2}$$$.

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

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

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

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

enum INF = 10^^9;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const A = readInt();
      const B = readInt();
      const S = readToken();

      auto lcp = new int[][](N + 1, N + 1);
      foreach_reverse (i; 0 .. N) foreach_reverse (j; 0 .. N) {
        lcp[i][j] = (S[i] == S[j]) ? (1 + lcp[i + 1][j + 1]) : 0;
      }
      foreach (i; 0 .. N + 1) {
        foreach (j; 0 .. N) {
          chmax(lcp[i][j + 1], lcp[i][j]);
        }
      }

      auto dp = new int[N + 1];
      dp[] = INF;
      dp[0] = 0;
      foreach (i; 0 .. N) {
        chmin(dp[i + 1], dp[i] + A);
        foreach (j; i + 1 .. N + 1) {
          // lcp[i][k] >= j - i, 0 <= k <= i - (j - i)
          if (0 <= i - (j - i) && lcp[i][i - (j - i)] >= j - i) {
            chmin(dp[j], dp[i] + B);
          }
        }
      }
      writeln(dp[N]);
    }
  } catch (EOFException e) {
  }
}

int[] make_z(in char[] s) {
  import std.algorithm : max;
  import std.conv : to;

  int n = s.length.to!(int);
  auto z = new int[](n);
  for (int i = 1, p = 0; i < n; i++) {
    if (i + z[i - p] < p + z[p]) {
      z[i] = z[i - p];
    } else {
      auto j = max(0, p + z[p] - i);
      while (i + j < n && s[j] == s[i + j]) {
        j++;
      }
      z[i] = j;
      p = i;
    }
  }
  z[0] = n;
  return z;
}

void chmin(ref int l, int r) {
  if (l > r) {
    l = r;
  }
}

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

  int n, a, b;
  rd(n, a, b);
  auto s = readln.chomp.to!(char[]);

  auto z = new int[][](n, n);
  foreach (i; 0 .. n) {
    z[i][i .. $] = make_z(s[i .. $]);
  }
  auto dp = new int[](n + 1);
  fill(dp, 5000 * 5000);
  dp[0] = 0;
  foreach (i; 0 .. n) {
    chmin(dp[i + 1], dp[i] + a);
    foreach (j; 0 .. i) {
      if (z[j][i] > 0) {
        chmin(dp[i + min(z[j][i], i - j)], dp[i] + b);
      }
    }
  }
  writeln(dp[n]);
}

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


This is the easy version of this problem. The only difference is the constraint on $$$k$$$ — the number of gifts in the offer. In this version: $$$k=2$$$.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "$$$k$$$ of goods for the price of one" is held in store. Remember, that in this problem $$$k=2$$$.Using this offer, Vasya can buy exactly $$$k$$$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by $$$a_i$$$ — the number of coins it costs. Initially, Vasya has $$$p$$$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:  Vasya can buy one good with the index $$$i$$$ if he currently has enough coins (i.e $$$p \ge a_i$$$). After buying this good, the number of Vasya's coins will decrease by $$$a_i$$$, (i.e it becomes $$$p := p - a_i$$$).  Vasya can buy a good with the index $$$i$$$, and also choose exactly $$$k-1$$$ goods, the price of which does not exceed $$$a_i$$$, if he currently has enough coins (i.e $$$p \ge a_i$$$). Thus, he buys all these $$$k$$$ goods, and his number of coins decreases by $$$a_i$$$ (i.e it becomes $$$p := p - a_i$$$). Please note that each good can be bought no more than once.For example, if the store now has $$$n=5$$$ goods worth $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$, respectively, $$$k=2$$$, and Vasya has $$$6$$$ coins, then he can buy $$$3$$$ goods. A good with the index $$$1$$$ will be bought by Vasya without using the offer and he will pay $$$2$$$ coins. Goods with the indices $$$2$$$ and $$$3$$$ Vasya will buy using the offer and he will pay $$$4$$$ coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$t$$$ test cases.  The first line of each test case contains three integers $$$n, p, k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le p \le 2\cdot10^9$$$, $$$k=2$$$) — the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — the prices of goods. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$. It is guaranteed that in this version of the problem $$$k=2$$$ for all test cases.

For each test case in a separate line print one integer $$$m$$$ — the maximum number of goods that Vasya can buy.

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional, std.meta;
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 t;
    readf("%s", &t);
    readln;

    while (t--) {
        int n, p, k;
        readf("%s %s %s", &n, &p, &k);
        readln;

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

        arr.sort();

        auto cost = new int[] (n+1);
        cost[0] = 0;
        foreach (i, e; arr.enumerate(1)) {
            if (i < k) { cost[i.to!int] = cost[i.to!int - 1] + e; }
            else { cost[i.to!int] = cost[i.to!int - k] + e; }
        }

        int ans = 0;
        foreach (i, e; cost) {
            if (e <= p) { ans = i.to!int; }
        }

        ans.writeln;
    }
}

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

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  immutable t = r.next!uint;
  auto res = uninitializedArray!(int[]) (t);
  foreach (tid; 0 .. t) {
    immutable n = r.next!uint;
    auto p = r.next!uint;
    immutable k = r.next!uint;
    auto a = r.nextA!uint (n);
    sort (a);
    /*
    auto s = new long[n+1];
    s[0] = 0;
    foreach (i; 1 .. n + 1) s[i] = s[i-1] + a[i-1];
    */
    auto b = new long[n+1];
    b[0] = 0;
    foreach (i; 1 .. n + 1) {
      immutable val = a[i-1];
      b[i] = b[i-1] + val;
      int j = (i - (k - 1));
      if (j >= 1) {
        b[i] = min (b[i], b[j-1] + val);
      }
    }
    int ans;
    foreach_reverse (i; 1 .. n + 1) {
      if (b[i] <= p) {
        ans = i;
        break;
      }
    }
    res[tid] = ans;
  }
  writefln ("%(%s\n%)", res);
}

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 p = rlong;
		int k = rint;
		long[] as = rlong(n);
		as.sort();
		log("---");
		log("n:", n, "p:", p, "k:", k, "as:", as);

		int ans = 0;
		int tmp1 = 0;
		foreach(r; 0 .. k){
			int tmp2 = tmp1;
			for(int m = 0; r + k * m <= n; m ++){
				log("r:", r, "m:", m, "x:", r + k * m, "tmp1:", tmp1, "tmp2:", tmp2, "f:", tmp2 <= p);
				if(tmp2 <= p) ans.chmax(r + k * m);
				else break;
				if(r + k * m + k - 1 < n) tmp2 += as[r + k * m + k - 1];
				else break;
			}
			tmp1 += as[r];
		}
		ans.writeln;
	}
}


Allen, having graduated from the MOO Institute of Techcowlogy (MIT), has started a startup! Allen is the president of his startup. He also hires $$$n-1$$$ other employees, each of which is assigned a direct superior. If $$$u$$$ is a superior of $$$v$$$ and $$$v$$$ is a superior of $$$w$$$ then also $$$u$$$ is a superior of $$$w$$$. Additionally, there are no $$$u$$$ and $$$v$$$ such that $$$u$$$ is the superior of $$$v$$$ and $$$v$$$ is the superior of $$$u$$$. Allen himself has no superior. Allen is employee number $$$1$$$, and the others are employee numbers $$$2$$$ through $$$n$$$.Finally, Allen must assign salaries to each employee in the company including himself. Due to budget constraints, each employee's salary is an integer between $$$1$$$ and $$$D$$$. Additionally, no employee can make strictly more than his superior.Help Allen find the number of ways to assign salaries. As this number may be large, output it modulo $$$10^9 + 7$$$.

The first line of the input contains two integers $$$n$$$ and $$$D$$$ ($$$1 \le n \le 3000$$$, $$$1 \le D \le 10^9$$$). The remaining $$$n-1$$$ lines each contain a single positive integer, where the $$$i$$$-th line contains the integer $$$p_i$$$ ($$$1 \le p_i \le i$$$). $$$p_i$$$ denotes the direct superior of employee $$$i+1$$$.

Output a single integer: the number of ways to assign salaries modulo $$$10^9 + 7$$$.

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

struct ModInt(int M_) {
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op)() const if (op == "-") { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

enum LIM = 10^^4;
Mint[] inv, fac, invFac;
void prepare() {
  inv = new Mint[LIM];
  fac = new Mint[LIM];
  invFac = new Mint[LIM];
  inv[1] = 1;
  foreach (i; 2 .. LIM) {
    inv[i] = -(Mint.M / i) * inv[cast(size_t)(Mint.M % i)];
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM) {
    fac[i] = fac[i - 1] * i;
    invFac[i] = invFac[i - 1] * inv[i];
  }
}
Mint binom(long n, long k) {
  if (0 <= k && k <= n) {
    assert(n < LIM);
    return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] * invFac[cast(size_t)(n - k)];
  } else {
    return Mint(0);
  }
}

void main() {
  prepare();
  try {
    for (; ; ) {
      const N = readInt();
      const D = readLong();
      auto P = new int[N];
      foreach (u; 1 .. N) {
        P[u] = readInt() - 1;
      }
      P[0] = -1;

      const lim = N + 10;
      auto dp = new Mint[][](N, lim);
      foreach (u; 0 .. N) {
        dp[u][1 .. lim] = Mint(1);
      }
      foreach_reverse (u; 0 .. N) {
        foreach (j; 1 .. lim) {
          dp[u][j] += dp[u][j - 1];
        }
        if (P[u] != -1) {
          foreach (j; 1 .. lim) {
            dp[P[u]][j] *= dp[u][j];
          }
        }
      }
      debug {
        foreach (u; 0 .. N) {
          writeln(u, ": ", dp[u]);
        }
      }

      Mint ans;
      foreach (j; 1 .. lim) {
        Mint prod = dp[0][j];
        foreach (k; 1 .. lim) {
          if (j != k) {
            prod *= (D - k);
            // prod /= (j - k);
            prod *= (j - k < 0) ? -inv[-(j - k)] : inv[j - k];
          }
        }
        ans += prod;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}