There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) — the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) — the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.

Print a single integer – the largest number of enemy spaceships that can be destroyed.

NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.

import core.bitop;
import std.algorithm;
import std.array;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int half = 20005;
immutable int limit = (half << 1) + 1;

void main ()
{
	int m, n;
	while (readf (" %s %s", &m, &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		a[] += half;
		b[] += half;
		auto u = new int [limit];
		auto v = new int [limit];
		foreach (ref c; a)
		{
			u[c] += 1;
		}
		foreach (ref c; b)
		{
			v[c] += 1;
		}
		auto f = new bool [limit];
		auto g = new bool [limit];
		auto mask = new long [2] [] [] (m, n);
		foreach (p; 0..m)
		{
			foreach (q; 0..n)
			{
				foreach (r; 0..m)
				{
					foreach (s; 0..n)
					{
						if (a[r] - a[p] == b[q] - b[s])
						{
							mask[p][q][0] |=
							    1L << r;
							mask[p][q][1] |=
							    1L << s;
						}
					}
				}
			}
		}

		int res = 0;
		foreach (p; 0..m)
		{
			foreach (q; 0..n)
			{
				foreach (r; 0..m)
				{
					foreach (s; 0..n)
					{
						auto cur = 0;
						cur += popcnt (mask[p][q][0] |
						    mask[r][s][0]);
						cur += popcnt (mask[p][q][1] |
						    mask[r][s][1]);
						res = max (res, cur);
					}
				}
			}
		}
		writeln (res);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const M = readInt();
      const N = readInt();
      auto A = new int[M];
      foreach (i; 0 .. M) {
        A[i] = readInt();
      }
      auto B = new int[N];
      foreach (j; 0 .. N) {
        B[j] = readInt();
      }
      A.sort;
      B.sort;

      alias Entry = Tuple!(int, "s", int, "i", int, "j");
      Entry[] es;
      foreach (i; 0 .. M) foreach (j; 0 .. N) {
        es ~= Entry(A[i] + B[j], i, j);
      }
      es.sort;
      const esLen = cast(int)(es.length);
      Tuple!(long, long)[] fs;
      for (int k = 0, l; k < esLen; k = l) {
        for (l = k; l < esLen && es[k].s == es[l].s; ++l) {}
        long f0, f1;
        foreach (ref e; es[k .. l]) {
          f0 |= 1L << e.i;
          f1 |= 1L << e.j;
          fs ~= tuple(f0, f1);
        }
      }
      const fsLen = cast(int)(fs.length);
      int ans;
      foreach (k; 0 .. fsLen) foreach (l; k .. fsLen) {
        int score;
        score += popcnt(fs[k][0] | fs[l][0]);
        score += popcnt(fs[k][1] | fs[l][1]);
        chmax(ans, score);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const M = readInt();
      const N = readInt();
      auto A = new int[M];
      foreach (i; 0 .. M) {
        A[i] = readInt();
      }
      auto B = new int[N];
      foreach (j; 0 .. N) {
        B[j] = readInt();
      }
      A.sort;
      B.sort;

      alias Entry = Tuple!(int, "s", int, "i", int, "j");
      Entry[] es;
      foreach (i; 0 .. M) foreach (j; 0 .. N) {
        es ~= Entry(A[i] + B[j], i, j);
      }
      es.sort;
      const esLen = cast(int)(es.length);
      Tuple!(long, long)[] fs;
      for (int k = 0, l; k < esLen; k = l) {
        for (l = k; l < esLen && es[k].s == es[l].s; ++l) {}
        long f0, f1;
        foreach (ref e; es[k .. l]) {
          f0 |= 1L << e.i;
          f1 |= 1L << e.j;
          fs ~= tuple(f0, f1);
        }
      }
      const fsLen = cast(int)(fs.length);
      int ans;
      foreach (k; 0 .. fsLen) foreach (l; k + 1 .. fsLen) {
        int score;
        score += popcnt(fs[k][0] | fs[l][0]);
        score += popcnt(fs[k][1] | fs[l][1]);
        chmax(ans, score);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with $$$n$$$ vertices, then he will ask you $$$q$$$ queries. Each query contains $$$5$$$ integers: $$$x$$$, $$$y$$$, $$$a$$$, $$$b$$$, and $$$k$$$. This means you're asked to determine if there exists a path from vertex $$$a$$$ to $$$b$$$ that contains exactly $$$k$$$ edges after adding a bidirectional edge between vertices $$$x$$$ and $$$y$$$. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.

The first line contains an integer $$$n$$$ ($$$3 \le n \le 10^5$$$), the number of vertices of the tree. Next $$$n-1$$$ lines contain two integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) each, which means there is an edge between vertex $$$u$$$ and $$$v$$$. All edges are bidirectional and distinct. Next line contains an integer $$$q$$$ ($$$1 \le q \le 10^5$$$), the number of queries Gildong wants to ask. Next $$$q$$$ lines contain five integers $$$x$$$, $$$y$$$, $$$a$$$, $$$b$$$, and $$$k$$$ each ($$$1 \le x,y,a,b \le n$$$, $$$x \ne y$$$, $$$1 \le k \le 10^9$$$) – the integers explained in the description. It is guaranteed that the edge between $$$x$$$ and $$$y$$$ does not exist in the original tree.

For each query, print "YES" if there exists a path that contains exactly $$$k$$$ edges from vertex $$$a$$$ to $$$b$$$ after adding an edge between vertices $$$x$$$ and $$$y$$$. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).  Possible paths for the queries with "YES" answers are:   $$$1$$$-st query: $$$1$$$ – $$$3$$$ – $$$2$$$  $$$2$$$-nd query: $$$1$$$ – $$$2$$$ – $$$3$$$  $$$4$$$-th query: $$$3$$$ – $$$4$$$ – $$$2$$$ – $$$3$$$ – $$$4$$$ – $$$2$$$ – $$$3$$$ – $$$4$$$ – $$$2$$$ – $$$3$$$

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(){
	int n = rint;
	Node[] nodes;
	foreach(i; 0 .. n) nodes ~= new Node(i);
	foreach(_; 0 .. n - 1){
		Node p = nodes[rint - 1], q = nodes[rint - 1];
		p.connectTo(q);
	}

	nodes[0].treefy(null);
	foreach(d; 0 .. 30) foreach(nd; nodes) nd.makeparents(d);

	foreach(_;0 .. rint){
		Node x = nodes[rint - 1], y = nodes[rint - 1], a = nodes[rint - 1], b = nodes[rint - 1];
		int k = rint;

		bool isOK(int d){
			return d <= k && d % 2 == k % 2;
		}

		string ans = "NO";
		if(isOK(a.distTo(b))) ans = "YES";
		if(isOK(a.distTo(x) + b.distTo(y) + 1)) ans = "YES";
		if(isOK(a.distTo(y) + b.distTo(x) + 1)) ans = "YES";

		ans.writeln;
	}
}

class Node{
	int id;
	Node[] nodes;
	int depth;
	Node parent;
	Node[] parents;
	bool isDone;
	this(int id){
		this.id = id;
	}
	void connectTo(Node nd){
		this.nodes ~= nd;
		nd.nodes ~= this;
	}
	void treefy(Node par){
		this.isDone = 1;
		if(!par) this.depth = 0;
		else this.parent = par, this.depth = par.depth + 1;
		foreach(nd; nodes) if(! nd.isDone) nd.treefy(this);
	}
	void makeparents(int depth){
		if(depth == 0){
			if(parent) parents ~= parent;
			return;
		}
		if(depth > parents.length) return;
		log("id:", id + 1, "depth:", depth, "parents:", parents.map!(p => p.id + 1).array);
		Node par = parents[depth - 1];
		if(depth <= par.parents.length) parents ~= par.parents[depth - 1];
	}
	int distTo(Node nd){
		//log("this:", this.id + 1, "nd:", nd.id + 1);
		Node p = this.lca(nd);
		int res = (this.depth - p.depth) + (nd.depth - p.depth);
		log("this:", this.id + 1, "nd:", nd.id + 1, "lca:", p.id + 1, "dist:", res);
		return res;
	}
	Node lca(Node nd){
		if(this.id == nd.id) return this;
		if(! this.parent) return this;
		if(! nd.parent) return nd;
		if(this.depth > nd.depth) return nd.lca(this);
		if(this.depth < nd.depth && nd.depth - this.depth > 10){
			foreach_reverse(p; nd.parents){
				if(p.depth > this.depth) return lca(p);
			}
		}
		if(this.depth < nd.depth){
			while(this.depth < nd.depth) if(nd.parent) nd = nd.parent; else return nd;
			return this.lca(nd);
		}

		int i = 0;
		while(i < this.parents.length && i < nd.parents.length &&
				this.parents[i].id != nd.parents[i].id) i += 1;
		if(i == 0) return this.parent;
		else return this.parents[i - 1].lca(nd.parents[i - 1]);
	}
}


$$$n$$$ people gathered to hold a jury meeting of the upcoming competition, the $$$i$$$-th member of the jury came up with $$$a_i$$$ tasks, which they want to share with each other.First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$ (an array of size $$$n$$$ where each integer from $$$1$$$ to $$$n$$$ occurs exactly once).Then the discussion goes as follows:  If a jury member $$$p_1$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped.  If a jury member $$$p_2$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped.  ...  If a jury member $$$p_n$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped.  If there are still members with tasks left, then the process repeats from the start. Otherwise, the discussion ends. A permutation $$$p$$$ is nice if none of the jury members tell two or more of their own tasks in a row. Count the number of nice permutations. The answer may be really large, so print it modulo $$$998\,244\,353$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — number of jury members. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the number of problems that the $$$i$$$-th member of the jury came up with. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the number of nice permutations, taken modulo $$$998\,244\,353$$$.

NoteExplanation of the first test case from the example:There are two possible permutations, $$$p = [1, 2]$$$ and $$$p = [2, 1]$$$. For $$$p = [1, 2]$$$, the process is the following:  the first jury member tells a task;  the second jury member tells a task;  the first jury member doesn't have any tasks left to tell, so they are skipped;  the second jury member tells a task. So, the second jury member has told two tasks in a row (in succession), so the permutation is not nice.For $$$p = [2, 1]$$$, the process is the following:  the second jury member tells a task;  the first jury member tells a task;  the second jury member tells a task. So, this permutation is nice.

immutable multi = true;

immutable long p = 998244353;
alias Zp = Z!p;

static this()
{
	Zp.makeFactorials(200_000+1);
}

void solve(int)
{
	int n = readInt!int;
	auto a = ma(n, readInt!int);
	auto mx = a.fold!max;
	int cntmx = 0, cntmxp = 0;
	foreach(i, ai; a) { if (ai == mx) cntmx++; else if (ai == mx-1) cntmxp++; }
	assert(cntmx > 0);
	if (cntmx > 1)
	{
		return writeln(Zp.fact[n].rep);
	}
	assert(cntmx == 1);
	debug writeln(cntmx);
	debug writeln(cntmxp);
	Zp ans = Zp.fact[n];
	debug writeln(ans);
	auto rem = n - cntmx - cntmxp;
	debug writeln(rem);
	foreach(i; 0 .. n)
	{
		debug writeln("C(", cntmxp, ", ", i, ") = ", Zp.C(cntmxp, i));
		ans = ans - (Zp.C(i, cntmxp) * Zp.fact[cntmxp] * Zp.fact[rem]);
		debug writeln(ans);
	}
	return writeln(ans.rep);
}

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

// modular {{{
struct Z(immutable long m)
{
	long rep;
	static immutable bool primeModulus = isPrime(m);
	static Z!m[] fact;
	static if (primeModulus) { static Z!m[] invFact; }
	static makeFactorials(int n)
	{
		fact = new Z!m[](n + 1);
		fact[0] = Z!m(1);
		foreach(i; 1 .. n + 1) fact[i] = Z!m(i) * fact[i - 1];
		static if (primeModulus)
		{
			invFact = new Z!m[](n + 1);
			invFact[n] = fact[n].inv;
			foreach_reverse(i; 0 .. n) invFact[i] = Z!m(i + 1) * invFact[i + 1];
		}
	}

	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else static if (operator == "/" && primeModulus)
		{
			assert(rhs != Z!m(0));
			return this * rhs.inv;
		}
		else
		{
			static assert(text("Operator ", operator, " not supported"));
		}
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	static if (primeModulus)
	{
		Z!m inv()
		{
			return this^^(m - 2);
		}
		static Z!m C(int n, int k)
		{
			if (k < 0 || k > n) return Z!m(0);
			return fact[n] * invFact[k] * invFact[n - k];
		}
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}
bool isPrime(long n)
{
	for(long d = 2; d * d <= n; d++)
		if (n % d == 0) return false;
	return true;
}
unittest
{
	alias Zp = Z!23;
	static assert(Zp.primeModulus);
	foreach(i; 1 .. 23) assert(Zp(i) * Zp(i).inv == Zp(1));
	Zp.makeFactorials(22);
	foreach(i; 0 .. 23) assert(Zp.fact[i] * Zp.invFact[i] == Zp(1));
	assert(Zp.C(3, 2) == Zp(3));
	assert(Zp.C(4, 2) == Zp(6));
}
// }}}

// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

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

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

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

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


Nauuo is a girl who loves drawing circles.One day she has drawn a circle and wanted to draw a tree on it.The tree is a connected undirected graph consisting of $$$n$$$ nodes and $$$n-1$$$ edges. The nodes are numbered from $$$1$$$ to $$$n$$$.Nauuo wants to draw a tree on the circle, the nodes of the tree should be in $$$n$$$ distinct points on the circle, and the edges should be straight without crossing each other."Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.Nauuo wants to draw the tree using a permutation of $$$n$$$ elements. A permutation of $$$n$$$ elements is a sequence of integers $$$p_1,p_2,\ldots,p_n$$$ in which every integer from $$$1$$$ to $$$n$$$ appears exactly once.After a permutation is chosen Nauuo draws the $$$i$$$-th node in the $$$p_i$$$-th point on the circle, then draws the edges connecting the nodes.The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo $$$998244353$$$, can you help her?It is obvious that whether a permutation is valid or not does not depend on which $$$n$$$ points on the circle are chosen.

The first line contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is an edge between $$$u$$$ and $$$v$$$. It is guaranteed that the given edges form a tree.

The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo $$$998244353$$$.

NoteExample 1All valid permutations and their spanning trees are as follows.Here is an example of invalid permutation: the edges $$$(1,3)$$$ and $$$(2,4)$$$ are crossed.Example 2Every permutation leads to a valid tree, so the answer is $$$4! = 24$$$.

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

int[][] child;
bool[] visited;

long MOD = 998244353;
long[] fac;

long dfs(uint root) {

    uint nc = 0;

    visited[root] = true;
    long mul = 1;

    foreach (v; child[root]) {
        if (!visited[v]) {
            long ll = dfs(v);
            mul = (mul * ll) % MOD;
            nc++;
        }
    }

    if (root != 0)
        nc++;

    return (fac[nc] * mul) % MOD;
}

void main() {
    GC.disable();

    uint n;

    readf(" %s", n);

    child = new int[][n];
    visited = new bool[n];
    visited[] = false;
    fac = new long[n + 10];
    fac[0] = 1;
    foreach (i; 1 .. n + 1)
        fac[i] = (fac[i - 1] * i) % MOD;

    foreach (i; 0 .. n - 1) {
        uint u, v;
        readf(" %s %s", u, v);
        u--;
        v--;
        child[u] ~= v;
        child[v] ~= u;
    }

    long ans = dfs(0);
    writeln((n * ans) % MOD);

}

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

immutable int mod = 998_244_353;
immutable int NA = -1;

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

		int recur (int v, int p)
		{
			int subtrees = a[v].length.to !(int) + (p == NA);
			int res = 1;
			for (int i = 1; i < subtrees; i++)
			{
				res = (res * 1L * i) % mod;
			}
			if (p == NA)
			{
				res = (res * 1L * n) % mod;
			}
			else
			{
				res = (res * 1L * (subtrees)) % mod;
			}
			foreach (u; a[v])
			{
				if (u != p)
				{
					res = (res * 1L * recur (u, v)) % mod;
				}
			}
			return res;
		}

		writeln (recur (0, NA));
	}
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, 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 long MO = 998244353;

int N;
int[] U, V;

int[][] G;
int[] deg;

void dfs(int u, int p) {
  foreach (v; G[u]) {
    if (v != p) {
      ++deg[u];
      dfs(v, u);
    }
  }
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      U = new int[N - 1];
      V = new int[N - 1];
      foreach (i; 0 .. N - 1) {
        U[i] = readInt() - 1;
        V[i] = readInt() - 1;
      }

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[U[i]] ~= V[i];
        G[V[i]] ~= U[i];
      }
      deg = new int[N];
      const rt = 0;
      dfs(rt, -1);

      long ans = N;
      foreach (u; 0 .. N) {
        foreach (k; 1 .. deg[u] + 1) {
          ans *= k;
          ans %= MO;
        }
        if (u != rt) {
          ans *= (deg[u] + 1);
          ans %= MO;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

int[][] child;
bool[] visited;

long MOD = 998244353;
long[] fac;

long dfs(uint root) {

    uint nc = 0;

    visited[root] = true;
    long mul = 1;

    foreach (v; child[root]) {
        if (!visited[v]) {
            long ll = dfs(v);
            mul = (mul * ll) % MOD;
            nc++;
        }
    }

    if (root != 0)
        nc++;

    return (fac[nc] * mul) % MOD;
}

void main() {
    GC.disable();

    uint n;

    readf(" %s", n);

    child = new int[][n];
    visited = new bool[n];
    visited[] = false;
    fac = new long[n + 10];
    fac[0] = 1;
    foreach (i; 1 .. n + 1)
        fac[i] = (fac[i - 1] * i) % MOD;

    foreach (i; 0 .. n - 1) {
        uint u, v;
        readf(" %s %s", u, v);
        u--;
        v--;
        child[u] ~= v;
        child[v] ~= u;
    }

    long ans = dfs(0);
    writeln(n * ans);

}


Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract k ≥ 1 non-overlapping substrings from it such that each of them contains string t as a substring? More formally, you need to calculate the number of ways to choose two sequences a1, a2, ..., ak and b1, b2, ..., bk satisfying the following requirements:  k ≥ 1          t is a substring of string saisai + 1... sbi (string s is considered as 1-indexed). As the number of ways can be rather large print it modulo 109 + 7.

Input consists of two lines containing strings s and t (1 ≤ |s|, |t| ≤ 105). Each string consists of lowercase Latin letters.

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

/* KMP法による文字列探索
 * 計算量 O(M + N). M: パターンの長さ, N: パターンを探す文字列の長さ */
class KMP {
    string s;
    int[] PMA;
    this(in string s) {
        this.s = s;
        buildPMA(s);
    }
    /* tに含まれるsの数を数える.
     * この実装では
     *   s = "ABA",
     *   t = "ABABA"
     * のとき2 ( [0, 3), [2, 5)でマッチ ) を返す.
     * [2, 5)でマッチさせたくなければbuildPMAでPMA[M]を0にしておく. */
    int[] match(in string t) {
        auto N = t.length, M = s.length;
        int[] ret;
        int si = 0, ti = 0;
        while (ti < N) {
            if (s[si] == t[ti]) {
                si++; ti++;
            } else {
                if (si == 0) ti++;
                si = PMA[si];
            }
            if (si == M) {
                ret ~= cast(int)ti;
                si = PMA[si];
            }
        }
        return ret;
    }
    /* Pattern Matching Automaton を作る */
    void buildPMA(in string s) {
        auto M = s.length;
        PMA = new int[M + 1];
        PMA[0] = 0; PMA[1] = 0;
        for (int i = 2; i <= M; i++) {
            int j = PMA[i - 1];
            while (true) {
                if (s[j] == s[i - 1]) { PMA[i] = j + 1; break; }
                if (j == 0) { PMA[i] = 0; break; }
                j = PMA[j];
            }
        }
    }
};

const MOD = 1_000_000_007;

void main() {
    string s = readln.chomp,
           t = readln.chomp;
    auto matcher = new KMP(t);
    auto M = matcher.match(s);

    auto end = new bool[s.length + 1];
    foreach (m; M) {
        end[m] = true;
    }

    auto dp = new int[s.length + 1];
    auto sum = new int[s.length + 1];
    auto ssum = new int[s.length + 1];
    int T = cast(int)(t.length);
    foreach (int i; 1 .. cast(int)s.length + 1) {
        if (end[i]) {
            dp[i] = ssum[i - T] + i - T + 1;
        } else {
            dp[i] = dp[i - 1];
        }
        dp[i] = dp[i] % MOD;
        sum[i] = (sum[i - 1] + dp[i]) % MOD;
        ssum[i] = (ssum[i - 1] + sum[i]) % MOD;
    }
    writeln(sum.back);
}


Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = $$$2$$$, b = $$$3$$$ changes the value of a to $$$5$$$ (the value of b does not change).In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations "a += b" or "b += a". Leo wants to test handling large integers, so he wants to make the value of either a or b strictly greater than a given value $$$n$$$. What is the smallest number of operations he has to perform?

The first line contains a single integer $$$T$$$ ($$$1 \leq T \leq 100$$$) — the number of test cases. Each of the following $$$T$$$ lines describes a single test case, and contains three integers $$$a, b, n$$$ ($$$1 \leq a, b \leq n \leq 10^9$$$) — initial values of a and b, and the value one of the variables has to exceed, respectively.

For each test case print a single integer — the smallest number of operations needed. Separate answers with line breaks.

NoteIn the first case we cannot make a variable exceed $$$3$$$ in one operation. One way of achieving this in two operations is to perform "b += a" twice.

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint;
import std.bitmanip, std.complex, std.container;
import std.math, std.mathspecial,std.numeric;
import std.regex, std.typecons;
import core.bitop;
class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }
bool chmin(T)(ref T t, in T f)
{ if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f)
{ if (t < f) { t = f; return true; } else { return false; } }
int binarySearch(alias pred, T)(in T[] as)
{int lo = -1, hi = cast(int)(as.length);
for(;lo + 1 < hi;){const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid;}
return hi;}
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }
void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const A = readLong();
        const B = readLong();
        const N = readLong();

        long ans;
        long a = A, b = B;
        for (; a <= N && b <= N; ) {
          if (a > b) {
            swap(a, b);
          }
          a += b;
          ++ans;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	foreach (t; 0..readln.strip.to !(int))
	{
		int a, b, n;
		readf !(" %s %s %s") (a, b, n);
		int res = 0;
		while (!(a > n || b > n))
		{
			if (a > b)
			{
				swap (a, b);
			}
			res += 1;
			a += b;
		}
		writeln (res);
	}
}

// Code By H~$~C

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

void _Main() {
  int a, b, n;
  readf!" %d %d %d"(a, b, n);
  if (a > b) swap(a, b);
  int cnt = 0;
  while (b <= n) {
    a += b;
    swap(a, b);
    cnt++;
  }
  writefln!"%s"(cnt);
}

void main(string[] args) {
  int tests = 1;
  readf!" %d"(tests);
  foreach (test; 0 .. tests) _Main();
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const A = readLong();
        const B = readLong();
        const N = readLong();

        long ans;
        long a = A, b = B;
        for (; a <= N && b <= N; ) {
          if (a > b) {
            swap(a, b);
          }
          a += b;
          ++ans;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		while (max(a, b) <= n)
		{
			if (a < b)
				a += b;
			else
				b += a;
			++ans[ti];
		}
	}

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


You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones. You can do the following operation:  choose two indices $$$1 \le i , j \le n$$$, $$$i \ne j$$$,  add $$$a_{i}$$$ to $$$a_{j}$$$,  remove $$$a_{i}$$$ from $$$a$$$. Note that elements of $$$a$$$ can become bigger than $$$1$$$ after performing some operations. Also note that $$$n$$$ becomes $$$1$$$ less after the operation.What is the minimum number of operations needed to make $$$a$$$ non-decreasing, i. e. that each element is not less than the previous element?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the size of array $$$a$$$. Next line contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$. It's guaranteed that sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer, minimum number of operations needed to make $$$a$$$ non-decreasing.

NoteIn the first test case, $$$a$$$ is already non-decreasing, so you don't need to do any operations and the answer is $$$0$$$.In the second test case, you can perform an operation for $$$i = 1$$$ and $$$j = 5$$$, so $$$a$$$ will be equal to $$$[0, 0, 1, 2]$$$ and it becomes non-decreasing.In the third test case, you can perform an operation for $$$i = 2$$$ and $$$j = 1$$$, so $$$a$$$ will be equal to $$$[1]$$$ and it becomes non-decreasing.

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

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

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

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

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

        auto ASum = new int[N + 1];
        foreach (i; 0 .. N) {
          ASum[i + 1] = ASum[i] + A[i];
        }

        int ans = N;
        foreach (k; 0 .. N + 1) {
          const l = ASum[k];
          const r = (N - k) - (ASum[N] - ASum[k]);
          const cost = max(l, r);
          chmin(ans, cost);
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		int i = 0;
		int j = n - 1;
		int res = 0;
		while (true)
		{
			while (i < n && a[i] == 0)
			{
				i += 1;
			}
			while (j >= 0 && a[j] == 1)
			{
				j -= 1;
			}
			if (i >= j)
			{
				break;
			}
			res += 1;
			i += 1;
			j -= 1;
		}
		writeln (res);
	}
}


There are $$$n$$$ chests. The $$$i$$$-th chest contains $$$a_i$$$ coins. You need to open all $$$n$$$ chests in order from chest $$$1$$$ to chest $$$n$$$.There are two types of keys you can use to open a chest:   a good key, which costs $$$k$$$ coins to use;  a bad key, which does not cost any coins, but will halve all the coins in each unopened chest, including the chest it is about to open. The halving operation will round down to the nearest integer for each chest halved. In other words using a bad key to open chest $$$i$$$ will do $$$a_i = \lfloor{\frac{a_i}{2}\rfloor}$$$, $$$a_{i+1} = \lfloor\frac{a_{i+1}}{2}\rfloor, \dots, a_n = \lfloor \frac{a_n}{2}\rfloor$$$;  any key (both good and bad) breaks after a usage, that is, it is a one-time use. You need to use in total $$$n$$$ keys, one for each chest. Initially, you have no coins and no keys. If you want to use a good key, then you need to buy it.During the process, you are allowed to go into debt; for example, if you have $$$1$$$ coin, you are allowed to buy a good key worth $$$k=3$$$ coins, and your balance will become $$$-2$$$ coins.Find the maximum number of coins you can have after opening all $$$n$$$ chests in order from chest $$$1$$$ to chest $$$n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$; $$$0 \leq k \leq 10^9$$$) — the number of chests and the cost of a good key respectively. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$0 \leq a_i \leq 10^9$$$)  — the amount of coins in each chest. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output a single integer  — the maximum number of coins you can obtain after opening the chests in order from chest $$$1$$$ to chest $$$n$$$. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

NoteIn the first test case, one possible strategy is as follows:   Buy a good key for $$$5$$$ coins, and open chest $$$1$$$, receiving $$$10$$$ coins. Your current balance is $$$0 + 10 - 5 = 5$$$ coins.  Buy a good key for $$$5$$$ coins, and open chest $$$2$$$, receiving $$$10$$$ coins. Your current balance is $$$5 + 10 - 5 = 10$$$ coins.  Use a bad key and open chest $$$3$$$. As a result of using a bad key, the number of coins in chest $$$3$$$ becomes $$$\left\lfloor \frac{3}{2} \right\rfloor = 1$$$, and the number of coins in chest $$$4$$$ becomes $$$\left\lfloor \frac{1}{2} \right\rfloor = 0$$$. Your current balance is $$$10 + 1 = 11$$$.  Use a bad key and open chest $$$4$$$. As a result of using a bad key, the number of coins in chest $$$4$$$ becomes $$$\left\lfloor \frac{0}{2} \right\rfloor = 0$$$. Your current balance is $$$11 + 0 = 11$$$.  At the end of the process, you have $$$11$$$ coins, which can be proven to be maximal.

import std.stdio;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

void solve() {
    long N, K; readf("%d %d\n", &N, &K);
    auto A = readln.chomp.split(" ").map!(to!long).array;
    long C = A.reduce!"a+b" - K * N;
    long ans = C;
    long[] rs;
    for (int i = cast(int)(N-1); i >= 0; i--) {
        long[] nrs;
        long rd = 0;
        rs ~= A[i];
        foreach (ref r; rs) {
            rd += (r - r / 2);
            r /= 2;
            if (r > 0) {
                nrs ~= r;
            }
        }
        C = C - rd + K;
        ans = max(ans, C);
        rs = nrs;
    }
    writeln(ans);
}

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

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

immutable int limit = 32;

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

		auto f = new long [n + 1];
		f[] = long.min / 2;
		f[0] = 0;
		long res = 0;
		foreach (d; 0..limit)
		{
			foreach (i; 0..n)
			{
				f[i + 1] = max (f[i + 1], f[i] + a[i] - k);
			}
			res = max (res, f[n]);
			a[] /= 2;
			foreach_reverse (i; 0..n)
			{
				f[i + 1] = max (f[i + 1], f[i] + a[i]);
			}
		}
		res = max (res, f.maxElement);
		writeln (res);
	}
}


Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of $$$2$$$ rows and $$$n$$$ columns. Monocarp controls a character, which starts in cell $$$(1, 1)$$$ — at the intersection of the $$$1$$$-st row and the $$$1$$$-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ in one step if $$$|x_1 - x_2| \le 1$$$ and $$$|y_1 - y_2| \le 1$$$. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell $$$(2, n)$$$ — at the intersection of row $$$2$$$ and column $$$n$$$.Help Monocarp determine if it is possible to complete the level.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of columns. The next two lines describe the level. The $$$i$$$-th of these lines describes the $$$i$$$-th line of the level — the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell. Additional constraint on the input: cells $$$(1, 1)$$$ and $$$(2, n)$$$ are safe.

For each test case, output YES if it is possible to complete the level, and NO otherwise.

NoteConsider the example from the statement.In the first test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (2, 3)$$$.In the second test case, one of the possible paths is $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 3) \rightarrow (2, 4)$$$.In the fourth test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (1, 3) \rightarrow (2, 4) \rightarrow (1, 5) \rightarrow (2, 6)$$$.

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

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        int n;
        scanf("%d", &n);
        getchar();
        auto str1 = readln.strip();
        auto str2 = readln.strip();
        bool flag = true;
        for (int i = 0; i < n; i++)
        {
            if ((str1[i] == str2[i]) && (str1[i] == '1'))
            {
                writeln("NO");
                flag = false;
                break;
            }
        }
        if (flag)
            writeln("YES");
    }
}


Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type.

The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.

NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.Optimal sequence of actions in the second sample case:   In the first day Anastasia collects 8 pebbles of the third type.  In the second day she collects 8 pebbles of the fourth type.  In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.  In the fourth day she collects 7 pebbles of the fifth type.  In the fifth day she collects 1 pebble of the second type.

import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,
	core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
//import core.stdc.stdio;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;alias pair(X,Y)=Tuple!(X,"fi",Y,"se");
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;alias long lint;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;immutable int mod=1000000007;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------

void main()
{
	int n,k;
loop:while(read(n,k))
	{
		auto w=arread!int;
		sort(w);
		int ans=0;
		foreach(x;w)
		{
			ans+=(x+k-1)/k;
		}
		writeln((ans+1)/2);
	}
	//debug system("pause");
}

import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,
	core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
//import core.stdc.stdio;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;alias pair(X,Y)=Tuple!(X,"fi",Y,"se");
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;alias long lint;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;immutable int mod=1000000007;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~"\n", ptrs)==ptrs.length;}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------

void main()
{
	int n,k;
loop:while(read(&n,&k))
	{
		auto w=arread!int;
		sort(w);
		int ans=0;
		foreach(x;w)
		{
			ans+=(x+k-1)/k;
		}
		writeln((ans+1)/2);
	}
	//debug system("pause");
}

import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,
	core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
//import core.stdc.stdio;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;alias pair(X,Y)=Tuple!(X,"fi",Y,"se");
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;alias long lint;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;immutable int mod=1000000007;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------
T orient_square(T)(pair!(T,T)[] figure...)if(is(typeof(figure.front*figure.front)==T))
{
	auto n=figure.front,t=figure.front;
	figure.popFront();
	T ans=0;
	for(;!figure.empty;figure.popFront())
	{
		ans+=(figure.front.fi-t.fi)*(figure.front.se+t.se);
		t=figure.front;
	}
	return ans+(n.fi-t.fi)*(n.se+t.se);
}

X binpow(X,Y)(X base,Y exp)if(is(typeof(exp>>1)))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
auto binpow(X,Y,Z)(X base,Y exp,in Z mm)if(is(typeof(exp>>1)) && is(typeof(base%mm)))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
real square(T)(pair!(T,T)[] figure...)if(is(typeof(figure.front*figure.front)==T))
{
	return abs(orient_square(figure))/2.000000000000000;
}
alias orient_square orsq;
class vertex(X,alias f="a+b",X n=0,size_t lg=0,size_t rg=size_t.max/2)
{
	protected
	{
		class node
		{
			X val;
			node l,r;
			this(){}
		};
		node root;
	}
	public
	{
		size_t lb=lg,rb=rg;
		X neutral=0;
		size_t length;
		alias fun=binaryFun!f;
		this()
		{
			root=new node();
			length=0;
		}

	}
	protected
	{
		bool insert(node t,size_t tl,size_t tr,size_t pos,X x)
		{
			bool mark=false;
			if(!t)
			{
				t=new node();
				mark=true;
			}
			if(tl==tr)
			{
				t.val=x;
			}
			else
			{
				size_t tm=(tl+tr)>>1;
				if(pos<=tm)
				{
					mark=insert(t.l,tl,tm,pos,x);
				}
				else
				{
					mark=insert(t.r,tm+1,tr,pos,x);
				}
				if(!t.l)t.val=t.r.val;
				else if(!t.r)t.val=t.l.val;
				else t.val=fun(t.l.val,t.r.val);
			}
			return mark;
		}
		bool erase(node t,size_t tl,size_t tr,size_t pos)
		{
			if(!t)return false;
			if(tl==tr)
			{
				t=null;
				return true;
			}
			else
			{
				size_t tm=(tl+tr)>>1;
				if(pos<=tm)
				{
					return erase(t.l,tl,tm,pos);
				}
				else
				{
					return erase(t.r,tm+1,tr,pos);
				}
				if(!t.l)t.val=t.r.val;
				else if(!t.r)t.val=t.l.val;
				else t.val=fun(t.l.val,t.r.val);
			}
		}
		X cel(node t,size_t tl,size_t tr,size_t l,size_t r)
		{
			if(!t)return neutral;
			if(tl==l && tr==r)return t.val;
			else
			{
				size_t tm=(tl+tr)>>1;
				if(r<=tm)return cel(t.l,tl,tm,l,r);
				else if(l>tm)return cel(t.r,tm+1,tr,l,r);
				else return fun(cel(t.l,tl,tm,l,tm),cel(t.r,tm+1,tr,tm+1,r));
			}
		}
	}
	public
	{
		void insert(size_t pos,X x)
			in
		{
			assert(pos>=lb && pos<=rb);
		}
		body
		{
			length+=insert(root,lb,rb,pos,x);
		}
		void erase(size_t pos)
			in
		{
			assert(pos>=lb && pos<=rb);
		}
		body
		{
			length-=erase(root,lb,rb,pos);
		}
		X cel(size_t l,size_t r)
			in
		{
			assert(l<=r && l>=lb && r<=rb);
		}
		body
		{
			return cel(root,lb,rb,l,r);
		}
	}
};
class item
{
	size_t cnt,prior;
	int key;
	item l,r;
	this(){}
	this(int val,int rnd)
	{
		key=val;
		cnt=1;
		prior=rnd;
	}
};
int cnt(item t)
{
	return t?t.cnt:0;
}
void upd_cnt(item t)
{
	t.cnt=cnt(t.l)+cnt(t.r)+1;
}
void merge(ref item t,item l,item r)
{
	if(!l || !r)
	{
		t=(l?l:r);
	}
	else
	{
		if(l.prior>r.prior)
		{
			merge(l.r,l.r,r);
			t=l;
		}
		else
		{
			merge(r.l,l,r.l);
			t=r;
		}
	}
	upd_cnt(t);
}
void split(item t,int key,ref item l,ref item r)
{
	if(!t)l=r=null;
	else if(key<t.key)
	{
		split(t.l,key,l,t.l);
		r=t;
	}
	else
	{
		split(t.r,key,t.r,r);
		l=t;
	}
	upd_cnt(t);
}
void insert(ref item t,item it)
{
	if(!t) t=it;
	else
	{
		if(it.prior>t.prior)
		{
			split(t,it.key,it.l,it.r);
			t=it;
		}
		else insert(it.key<t.key?t.l:t.r,it);
	}
	upd_cnt(t);
}
void erase(ref item t,int key)
{
	if(t.key==key)merge(t,t.l,t.r);
	else erase(key<t.key?t.l:t.r,key);
}
size_t order(item t,int key,size_t add=0)
{
	if(!t)return add+1;
	else if(key<=t.key)return order(t.l,key,add);
	else return order(t.r,key,cnt(t.l)+add+1);
}
class nitem
{
	size_t cnt,prior;
	int key;
	nitem l,r;
	this(){}
	this(int val,int rnd)
	{
		key=val;
		cnt=1;
		prior=rnd;
	}
};
int cnt(nitem t)
{
	return t?t.cnt:0;
}
void upd_cnt(nitem t)
{
	t.cnt=cnt(t.l)+cnt(t.r)+1;
}
void merge(ref nitem t,nitem l,nitem r)
{
	if(!l || !r)t=(l?l:r);
	else
	{
		if(l.prior>r.prior)
		{
			merge(l.r,l.r,r);
			t=l;
		}
		else
		{
			merge(r.l,l,r.l);
			t=r;
		}
	}
	upd_cnt(t);
}
void split(nitem t,int key,ref nitem l,ref nitem r,int add=0)
{
	if(!t){l=r=null;return;}
	int cur=add=cnt(t.l);
	if(key<=cur)
	{
		split(t.l,key,l,t.l,add);
		r=t;
	}
	else
	{
		split(t.r,key,t.r,r,add+1+cnt(t.l));
		l=t;
	}
	upd_cnt(t);
}
void insert(ref nitem t,nitem it)
{
	nitem l,r;
	split(t,it.key,l,r);
	merge(l,l,it);
	merge(t,l,r);
	upd_cnt(t);
}

void erase(ref nitem t,int key)
{
	if(t.key==key)merge(t,t.l,t.r);
	else erase(key<t.key?t.l:t.r,key);
}

void main()
{
	int n,k;
loop:while(read(n,k))
	{
		auto w=arread!int;
		sort(w);
		int ans=0;
		foreach(x;w)
		{
			ans+=(x+k-1)/k;
		}
		writeln((ans+1)/2);
	}
	//debug system("pause");
}

import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,
	core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
//import core.stdc.stdio;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;alias pair(X,Y)=Tuple!(X,"fi",Y,"se");
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;alias long lint;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;immutable int mod=1000000007;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~"\n", ptrs)==ptrs.length;}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------

void main()
{
	int n,k;
loop:while(read(&n,&k))
	{
		auto w=arread!int;
		sort(w);
		int ans=0;
		foreach(p;0..n-1)
		{
			ans+=w[p]/(2*k);
			w[p]%=2*k;
			if(w[p]==0)continue;
			ans++;
			if(w[p]<=k)w[p+1]-=k;
			w[p]=0;
		}
		if(w[n-1]>0)
		{
			ans+=w[n-1]/(2*k);
			w[n-1]%=2*k;
			if(w[n-1])ans++;
		}
		writeln(ans);
	}
	//debug system("pause");
}

import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,
	core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
//import core.stdc.stdio;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;alias pair(X,Y)=Tuple!(X,"fi",Y,"se");
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;alias long lint;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;immutable int mod=1000000007;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~"\n", ptrs)==ptrs.length;}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------

void main()
{
	int n,k;
loop:while(read(&n,&k))
	{
		auto w=arread!int;
		sort(w);
		int ans=0;
		foreach(x;w)
		{
			ans+=(x+k-1)/k;
		}
		writeln(ans);
	}
	//debug system("pause");
}


You've got an array consisting of n integers: a[1], a[2], ..., a[n]. Moreover, there are m queries, each query can be described by three integers li, ri, ki. Query li, ri, ki means that we should add  to each element a[j], where li ≤ j ≤ ri.Record  means the binomial coefficient, or the number of combinations from y elements into groups of x elements.You need to fulfil consecutively all queries and then print the final array.

The first line contains integers n, m (1 ≤ n, m ≤ 105). The second line contains n integers a[1], a[2], ..., a[n] (0 ≤ ai ≤ 109) — the initial array. Next m lines contain queries in the format li, ri, ki — to all elements of the segment li... ri add number  (1 ≤ li ≤ ri ≤ n; 0 ≤ k ≤ 100).

Print n integers: the i-th number is the value of element a[i] after all the queries. As the values can be rather large, print them modulo 1000000007 (109 + 7).

import std.stdio, std.string, std.conv, std.algorithm;
immutable int MN = 100010;
immutable int MK = 105;
immutable int MD = cast(int)(1e9+7.1);

int main() {
    long[MK][] b = new long[MK][](MN);
    long[MK][] c = new long[MK][](MN+MK);
    c[0][0] = 1;
    for (int i = 1; i < MN+MK; i++) {
        c[i][0] = 1;
        c[i][1..MK] = (c[i-1][0..MK-1] + c[i-1][1..MK]) % MD;
    }
    int n, m;
    readf("%d %d\n", &n, &m);
    string[] input = split(readln());
    long[] a = new long[](n);
    foreach (i, s; input) {
        a[i] = to!int(s);
    }
    for (int i = 0; i < m; i++) {
        int l, r, k;
        readf("%d %d %d\n", &l, &r, &k); l--;
        int f = 1;
        for (int j = 0; j <= k; j++) {
            b[l][k-j] += c[l][j]*f; b[l][k-j] %= MD;
            b[r][k-j] -= c[l][j]*f; b[r][k-j] %= MD;
            f = -f;
        }
    }
    long b1[MK];
    for (int i = 0; i < n; i++) {
        long r = a[i];
        b1[] += b[i][];
        b1[] %= MD;
        for (int k = 0; k < MK; k++) {
            r += b1[k]*c[i+k][k]%MD; r %= MD;
        }
        r = (r+MD)%MD;
        write(cast(int)r);
        if (i == n-1) {
            write("\n");
        } else {
            write(" ");
        }
    }
    return 0;
}

import std.stdio, std.string, std.conv, std.algorithm;
immutable int MN = 100010;
immutable int MK = 105;
immutable int MD = cast(int)(1e9+7.1);

int main() {
    long[][] b = new long[][](MN, MK);
    long[][] c = new long[][](MN+MK, MK);
    c[0][0] = 1;
    for (int i = 1; i < MN+MK; i++) {
        c[i][0] = 1;
        c[i][1..MK] = (c[i-1][0..MK-1] + c[i-1][1..MK]) % MD;
    }
    int n, m;
    readf("%d %d\n", &n, &m);
    string[] input = split(readln());
    auto a = map!(to!int)(input[]);
    for (int i = 0; i < m; i++) {
        int l, r, k;
        readf("%d %d %d\n", &l, &r, &k); l--;
        int f = 1;
        for (int j = 0; j <= k; j++) {
            b[l][k-j] += c[l][j]*f; b[l][k-j] %= MD;
            b[r][k-j] -= c[l][j]*f; b[r][k-j] %= MD;
            f = -f;
        }
    }
    long b1[MK];
    for (int i = 0; i < n; i++) {
        long r = a[i];
        b1[] += b[i][];
        b1[] %= MD;
        for (int k = 0; k < MK; k++) {
            r += b1[k]*c[i+k][k]%MD; r %= MD;
        }
        r = (r+MD)%MD;
        write(cast(int)r);
        if (i == n-1) {
            write("\n");
        } else {
            write(" ");
        }
    }
    return 0;
}

import std.stdio, std.string, std.conv, std.algorithm;
immutable int MN = 100010;
immutable int MK = 105;
immutable int MD = cast(int)(1e9+7.1);

int main() {
    long[MK][] b = new long[MK][MN];
    long[MK][] c = new long[MK][MN+MK];
    c[0][0] = 1;
    for (int i = 1; i < MN+MK; i++) {
        c[i][0] = 1;
        c[i][1..MK] = (c[i-1][0..MK-1] + c[i-1][1..MK]) % MD;
    }
    int n, m;
    readf("%d %d\n", &n, &m);
    string[] input = split(readln());
    auto a = map!(to!int)(input[]);
    for (int i = 0; i < m; i++) {
        int l, r, k;
        readf("%d %d %d\n", &l, &r, &k); l--;
        int f = 1;
        for (int j = 0; j <= k; j++) {
            b[l][k-j] += c[l][j]*f; b[l][k-j] %= MD;
            b[r][k-j] -= c[l][j]*f; b[r][k-j] %= MD;
            f = -f;
        }
    }
    long b1[MK];
    for (int i = 0; i < n; i++) {
        long r = a[i];
        b1[] += b[i][];
        b1[] %= MD;
        for (int k = 0; k < MK; k++) {
            r += b1[k]*c[i+k][k]%MD; r %= MD;
        }
        r = (r+MD)%MD;
        write(cast(int)r);
        if (i == n-1) {
            write("\n");
        } else {
            write(" ");
        }
    }
    return 0;
}

import std.stdio, std.string, std.conv, std.algorithm;
immutable int MN = 100010;
immutable int MK = 105;
immutable int MD = cast(int)(1e9+7.1);

int main() {
    long[MK][] b = new long[MK][](MN);
    long[MK][] c = new long[MK][](MN+MK);

    c[0][0] = 1;
    foreach (i; 1..MN+MK) {
        c[i][0] = 1;
        c[i][1..MK] = (c[i-1][0..MK-1] + c[i-1][1..MK]) % MD;
    }

    int n, m;
    readf("%d %d\n", &n, &m);
    string[] input = split(readln());
    long[] a = new long[](n);
    foreach (i; 0..n) {
        a[i] = to!int(input[i]);
    }
    foreach (i; 0..m) {
        int l, r, k;
        readf("%d %d %d\n", &l, &r, &k); l--;
        int f = 1;
        foreach_reverse (j; 0..k+1) {
            b[l][j] += c[l][k-j]*f; b[l][j] %= MD;
            b[r][j] -= c[l][k-j]*f; b[r][j] %= MD;
            f = -f;
        }
    }
    long[] b1 = new long[](MK);
    foreach (i; 0..n) {
        b1[] += b[i][];
        b1[] %= MD;
        for (int k = 0; k < MK; k++) {
            a[i] += b1[k]*c[i+k][k]%MD; a[i] %= MD;
        }
        a[i] = (a[i]+MD)%MD;
    }
    writeln(join(map!(to!string)(a[0..n]), " "));
    return 0;
}

import std.stdio, std.string, std.conv, std.algorithm;
immutable int MN = 100010;
immutable int MK = 105;
immutable int MD = cast(int)(1e9+7.1);

int main() {
    long[MK][] b = new long[MK][](MN);
    long[MK][] c = new long[MK][](MN+MK);

    c[0][0] = 1;
    foreach (i; 1..MN+MK) {
        c[i][0] = 1;
        c[i][1..MK] = (c[i-1][0..MK-1] + c[i-1][1..MK]) % MD;
    }

    int n, m;
    readf("%d %d\n", &n, &m);
    string[] input = split(readln());
    long[] a = new long[](n);
    for (int i = 0; i < n; i++) {
        a[i] = to!int(input[i]);
    }
    for (int i = 0; i < m; i++) {
        int l, r, k;
        readf("%d %d %d\n", &l, &r, &k); l--;
        int f = 1;
        foreach_reverse (j; 0..k+1) {
            b[l][j] += c[l][k-j]*f; b[l][j] %= MD;
            b[r][j] -= c[l][k-j]*f; b[r][j] %= MD;
            f = -f;
        }
    }
    long[] b1 = new long[](MK);
    foreach (i; 0..n) {
        b1[] += b[i][];
        b1[] %= MD;
        for (int k = 0; k < MK; k++) {
            a[i] += b1[k]*c[i+k][k]%MD; a[i] %= MD;
        }
        a[i] = (a[i]+MD)%MD;
    }
    writeln(join(map!(to!string)(a[0..n]), " "));
    return 0;
}

import std.stdio, std.string, std.conv, std.algorithm;
immutable int MN = 100010;
immutable int MK = 105;
immutable int MD = cast(int)(1e9+7.1);

int main() {
    long[MK][] b = new long[MK][](MN);
    long[MK][] c = new long[MK][](MN+MK);

    c[0][0] = 1;
    foreach (i; 1..MN+MK) {
        c[i][0] = 1;
        c[i][1..MK] = (c[i-1][0..MK-1] + c[i-1][1..MK]) % MD;
    }

    int n, m;
    readf("%d %d\n", &n, &m);
    string[] input = split(readln());
    long[] a = new long[](n);
    for (int i = 0; i < n; i++) {
        a[i] = to!int(input[i]);
    }
    for (int i = 0; i < m; i++) {
        int l, r, k;
        readf("%d %d %d\n", &l, &r, &k); l--;
        int f = 1;
        foreach_reverse (j; 0..k+1) {
            b[l][j] += c[l][k-j]*f; b[l][j] %= MD;
            b[r][j] -= c[l][k-j]*f; b[r][j] %= MD;
            f = -f;
        }
    }
    long[] b1 = new long[](MK);
    long[] r = new long[](n);
    foreach (i; 0..n) {
        b1[] += b[i][];
        b1[] %= MD;
        for (int k = 0; k < MK; k++) {
            r[i] += b1[k]*c[i+k][k]%MD; r[i] %= MD;
        }
        r[i] = (r[i]+MD)%MD;
    }
    writeln(join(map!(to!string)(r), " "));
    return 0;
}


Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are $$$n$$$ students living in a building, and for each of them the favorite drink $$$a_i$$$ is known. So you know $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le k$$$) is the type of the favorite drink of the $$$i$$$-th student. The drink types are numbered from $$$1$$$ to $$$k$$$.There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $$$k$$$ types of drink sets, the $$$j$$$-th type contains two portions of the drink $$$j$$$. The available number of sets of each of the $$$k$$$ types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $$$\lceil \frac{n}{2} \rceil$$$, where $$$\lceil x \rceil$$$ is $$$x$$$ rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $$$n$$$ is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if $$$\lceil \frac{n}{2} \rceil$$$ sets will be chosen optimally and students will distribute portions between themselves optimally?

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 1\,000$$$) — the number of students in the building and the number of different drinks. The next $$$n$$$ lines contain student's favorite drinks. The $$$i$$$-th line contains a single integer from $$$1$$$ to $$$k$$$ — the type of the favorite drink of the $$$i$$$-th student.

Print exactly one integer — the maximum number of students that can get a favorite drink.

NoteIn the first example, students could choose three sets with drinks $$$1$$$, $$$1$$$ and $$$2$$$ (so they will have two sets with two drinks of the type $$$1$$$ each and one set with two drinks of the type $$$2$$$, so portions will be $$$1, 1, 1, 1, 2, 2$$$). This way all students except the second one will get their favorite drinks.Another possible answer is sets with drinks $$$1$$$, $$$2$$$ and $$$3$$$. In this case the portions will be $$$1, 1, 2, 2, 3, 3$$$. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with $$$a_i = 1$$$ (i.e. the first, the third or the fourth).

import std.stdio;

void main() {
    int n, k;
    int[1005] count;

    readf(" %s %s", n, k);
    foreach(i; 0..n) {
        int a;
        readf(" %s", a);
        count[a]++;
    }

    int odds = 0;
    foreach(c; count) {
        if (c % 2 == 1) {
            odds++;
        }
    }

    int result = n - odds / 2;
    writeln(result);
}

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 read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int n = read.to!int;
	int k = read.to!int;

	int[] as;
	foreach(i; 0 .. n) as ~= read.to!int;

	int[int] ac;
	foreach(a; as){
		if(a !in ac) ac[a] = 0;
		ac[a] += 1;
	}

	int ans;
	int ocnt = n % 2;
	int[] ks = ac.keys;
	foreach(a; ks){
		int c = ac[a];
		if(c % 2 == 0) ans += c;
		else{
			if(ocnt >= 1) ans += c, ocnt = 0;
			else ans += c - 1, ocnt = 1;
		}
		log("a:", a, "cnt:", c, "ocnt:", ocnt, "ans:", ans);
	}

	ans.writeln;
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n = RD!int;
	auto k = RD!int;
	auto cnt = new long[](k);
	foreach (i; 0..n)
	{
		auto a = RD!int-1;
		++cnt[a];
	}
	long ans;
	long used;
	foreach (i; 0..k)
	{
		auto c = cnt[i] / 2;
		ans += c * 2;
		used += c;
		cnt[i] -= c * 2;
	}
	auto remain = n - used * 2 + n % 2;
	ans += remain / 2;

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


A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).You are given a permutation of $$$1,2,\dots,n$$$, $$$[a_1,a_2,\dots,a_n]$$$. For integers $$$i$$$, $$$j$$$ such that $$$1\le i<j\le n$$$, define $$$\operatorname{mn}(i,j)$$$ as $$$\min\limits_{k=i}^j a_k$$$, and define $$$\operatorname{mx}(i,j)$$$ as $$$\max\limits_{k=i}^j a_k$$$.Let us build an undirected graph of $$$n$$$ vertices, numbered $$$1$$$ to $$$n$$$. For every pair of integers $$$1\le i<j\le n$$$, if $$$\operatorname{mn}(i,j)=a_i$$$ and $$$\operatorname{mx}(i,j)=a_j$$$ both holds, or $$$\operatorname{mn}(i,j)=a_j$$$ and $$$\operatorname{mx}(i,j)=a_i$$$ both holds, add an undirected edge of length $$$1$$$ between vertices $$$i$$$ and $$$j$$$.In this graph, find the length of the shortest path from vertex $$$1$$$ to vertex $$$n$$$. We can prove that $$$1$$$ and $$$n$$$ will always be connected via some path, so a shortest path always exists.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 5\cdot 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1\le n\le 2.5\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1\le a_i\le n$$$). It's guaranteed that $$$a$$$ is a permutation of $$$1$$$, $$$2$$$, $$$\dots$$$, $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.

For each test case, print a single line containing one integer — the length of the shortest path from $$$1$$$ to $$$n$$$.

NoteThe following are illustrations of constructed graphs in example test cases.    the constructed graph in test case 1     the constructed graph in test case 2     the constructed graph in test case 3     the constructed graph in test case 4     the constructed graph in test case 5

import std;
void main(){
	auto t=readln.strip.to!int;
	foreach(_;0..t){
		auto n=readln.strip.to!int;
		auto a=readln.strip.split.to!(int[]);
		if(a.length==1){ writeln(0); continue; }
		int u=iota(n).maxElement!(i=>a[i]);
		int v=iota(n).minElement!(i=>a[i]);
		if(v<u) swap(u,v);
		int solve(R)(R x){
			if(x.length<=1) return 0;
			int mini=0,maxi=1,r=1;
			if(x[mini]>x[maxi]) swap(mini,maxi);
			for(int i=2;i<x.length;i++){
				if(x[i]<x[mini]){
					r+=mini<maxi;
					mini=i;
				}
				if(x[i]>x[maxi]){
					r+=maxi<mini;
					maxi=i;
				}
			}
			return r;
		}
		writeln(solve(a[0..u+1])+1+solve(a[v..$].retro));
	}
}

import std;
void main(){
	auto t=readln.strip.to!int;
	foreach(_;0..t){
		auto n=readln.strip.to!int;
		auto a=readln.strip.split.to!(int[]);
		if(a.length==1){ writeln(0); continue; }
		int u=iota(n).maxElement!(i=>a[i]);
		int v=iota(n).minElement!(i=>a[i]);
		if(v<u) swap(u,v);
		int solve(R)(R x){
			if(x.length<=1) return 0;
			int mini=0,maxi=1,r=1;
			if(x[mini]>x[maxi]) swap(mini,maxi);
			for(int i=2;i<x.length;i++){
				if(x[i]<x[mini]){
					if(maxi<mini){
						mini=i;
					}else{
						mini=i;
						r++;
					}
				}
				if(x[i]>x[maxi]){
					if(mini<maxi){
						maxi=i;
					}else{
						maxi=i;
						r++;
					}
				}
			}
			return r;
		}
		writeln(solve(a[0..u+1])+1+solve(a[v..$].retro));
	}
}

import std;

struct S(alias op,alias ε){
	alias T=typeof(ε);
	int n;
	T[] b;
	this(R)(R a){
		n=to!int(a.length);
		b=ε.repeat(4*n).array;
		T build(int l,int r,int i){
			if(l+1==r) return b[i]=a[l];
			int m=(l+r)/2;
			return b[i]=op(build(l,m,2*i),build(m,r,2*i+1));
		}
		build(0,n,1);
	}
	auto query(int ql,int qr){
		auto query_rec(int l,int r,int i){
			if(qr<=l||r<=ql) return ε;
			if(ql<=l&&r<=qr) return b[i];
			int m=(l+r)/2;
			return op(query_rec(l,m,2*i),query_rec(m,r,2*i+1));
		}
		return query_rec(0,n,1);
	}
	void opIndexAssign(T value,int k){
		T update_rec(int l,int r,int i){
			if(k<l||r<=k) return ε;
			if(l+1==r) return b[i]=value;
			int m=(l+r)/2;
			return b[i]=op(update_rec(l,m,2*i),update_rec(m,r,2*i+1));
		}
		update_rec(0,n,1);
	}
}

enum inf=to!int(3e5);

void main(){
	auto t=readln.strip.to!int;
	foreach(_;0..t){
		auto n=readln.strip.to!int;
		auto a=readln.strip.split.to!(int[]).map!(x=>x-1).array;
		auto maxtree=S!(max,tuple(0,-1))(a.zip(iota(n)));
		auto mintree=S!(min,tuple(inf,-1))(a.zip(iota(n)));
		auto ip=0.repeat(n).array;
		foreach(i,x;a) ip[x]=to!int(i);
		auto indextree=S!(min,n)(n.repeat(n));
		auto next_smaller=n.repeat(n).array;
		auto next_larger=n.repeat(n).array;
		foreach_reverse(i;0..n){
			next_smaller[i]=indextree.query(0,a[i]);
			next_larger[i]=indextree.query(a[i],n);
			indextree[a[i]]=i;
		}
		auto dist=chain(only(0),inf.repeat(n)).array;
		foreach(i;0..n-1){
			int[2] u=[
				maxtree.query(i+1,min(n,next_smaller[i]+1))[1],
				mintree.query(i+1,min(n,next_larger[i]+1))[1],
			];
			foreach(j;u) dist[j]=min(dist[j],dist[i]+1);
		}
		writeln(dist[n-1]);
	}
}

import std;
void main(){
	auto t=readln.strip.to!int;
	foreach(_;0..t){
		auto n=readln.strip.to!int;
		auto a=readln.strip.split.to!(int[]);
		int mini=0,maxi=0,r=0;
		for(int i=1;i<n;i++){
			r+=a[i]<a[mini]&&mini<=maxi;
			r+=a[i]>a[maxi]&&maxi<=mini;
			if(a[i]<a[mini]){
				if(mini<maxi) maxi=i;
				mini=i;
			}
			if(a[i]>a[maxi]){
				if(maxi<mini) mini=i;
				maxi=i;
			}
		}
		r+=(mini!=n-1&&maxi!=n-1);
		writeln(r);
	}
}

import std;
void main(){
	auto t=readln.strip.to!int;
	foreach(_;0..t){
		auto n=readln.strip.to!int;
		auto a=readln.strip.split.to!(int[]);
		int mini=0,maxi=0,r=0;
		for(int i=1;i<n;i++){
			r+=a[i]<a[mini]&&mini<=maxi;
			r+=a[i]>a[maxi]&&maxi<=mini;
			if(a[i]<a[mini]) mini=i;
			if(a[i]>a[maxi]) maxi=i;
		}
		r+=(mini!=n-1&&mini!=0)+(maxi!=n-1&&maxi!=0);
		writeln(r);
	}
}


You are given two arrays $$$a$$$ and $$$b$$$, consisting of $$$n$$$ integers each.Let's define a function $$$f(a, b)$$$ as follows:   let's define an array $$$c$$$ of size $$$n$$$, where $$$c_i = a_i \oplus b_i$$$ ($$$\oplus$$$ denotes bitwise XOR);  the value of the function is $$$c_1 \mathbin{\&} c_2 \mathbin{\&} \cdots \mathbin{\&} c_n$$$ (i.e. bitwise AND of the entire array $$$c$$$). Find the maximum value of the function $$$f(a, b)$$$ if you can reorder the array $$$b$$$ in an arbitrary way (leaving the initial order is also an option).

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of arrays $$$a$$$ and $$$b$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < 2^{30}$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i < 2^{30}$$$). The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the maximum value of the function $$$f(a, b)$$$ if you can reorder the array $$$b$$$ in an arbitrary way.

import std.stdio;
import core.memory;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!uint).array;
    auto B = readln.chomp.split(" ").map!(to!uint).array;

    bool f(int s) {
        int[uint] d;
        for (int i = 0; i < N; i++) {
            uint ap = A[i] & s;
            d[ap] = d.get(ap, 0) + 1;
            uint nbp = ~B[i] & s;
            d[nbp] = d.get(nbp, 0) - 1;
        }
        foreach (k, v; d) {
            if (v != 0) return false;
        }
        return true;
    }

    uint ans = 0;
    for (int k = 31; k >= 0; k--) {
        if (f(ans | (1<<k))) ans |= 1<<k;
    }
    writefln("%d", ans);
}

void main() {
    int T = readln.chomp.to!int;
    foreach (t; 0 .. T) {
        GC.disable();
        solve();
        GC.enable();
    }
}