An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.

A single line contains integer n (1 ≤ n ≤ 5000) — the number of students at an exam.

In the first line print integer k — the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other. In the second line print k distinct integers a1, a2, ..., ak (1 ≤ ai ≤ n), where ai is the number of the student on the i-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |ai - ai + 1| ≠ 1 for all i from 1 to k - 1. If there are several possible answers, output any of them.

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

void main() {
    uint n;
    readf(`%u`, &n);

    auto res =	iota(0, (n + 1) / 2).map!(a => a * 2 + 1).array ~
				iota(1, (n + 2) / 2).map!(a => a * 2).array;

	if(n > 1 && n < 4) n--;
	if(n == 4) res = [ 3, 1, 4, 2 ];

    writef("%u\n%(%s %)", n, res[0..n]);
}

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

void main() {
    uint n;
    readf(`%u`, &n);

    auto res =	iota(0, (n + 1) / 2).map!(a => a * 2 + 1).retro.array ~
				iota(1, (n + 2) / 2).map!(a => a * 2).array;

	if(n > 1 && n < 4) n--;

    writef("%u\n%(%s %)", n, res[0..n]);
}

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

void main() {
    uint n;
    readf(`%u`, &n);

    auto res =	iota(0, (n + 1) / 2).map!(a => a * 2 + 1).array ~
				iota(1, (n + 2) / 2).map!(a => a * 2).array;

	if(n > 1 && n < 5) n--;
	if(n == 3) res = res.remove(1);

    writef("%u\n%(%s %)", n, res[0..n]);
}

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

void main() {
    uint n;
    readf(`%u`, &n);

    auto res =	iota(0, (n + 1) / 2).map!(a => a * 2 + 1).array ~
				iota(1, (n + 2) / 2).map!(a => a * 2).array;

	if(n > 1 && n < 5) n--;
	if(n == 3) res = [ 1, 4, 2 ];

    writef("%u\n%(%s %)", n, res[0..n]);
}


Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i < b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.

If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.

NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.

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

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

    if (E.map!(e => e[1] != N).any) {
        writeln("NO");
        return;
    }

    auto A = E.map!(e => e[0]).array;
    A.sort();

    foreach (i; 0..N-1) {
        if (A[i] < i + 1) {
            writeln("NO");
            return;
        }
    }

    auto used = new int[](N+1);
    foreach (a; A) used[a] = true;
    auto ans = new int[](N-1);
    int start = 0;
    int x = 1;

    foreach (i; 0..N-1) {
        if (i == N - 2 || A[i] != A[i+1]) {
            ans[start] = A[i];
            foreach (j; start+1..i+1) {
                while (used[x]) ++x;
                used[x] = true;
                ans[j] = x;
            }
            start = i + 1;
        }
    }

    writeln("YES");
    foreach (i; 0..ans.length.to!int - 1) {
        writeln(ans[i], " ", ans[i+1]);
    }
    writeln(ans.back, " ", N);
}

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

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

    Tuple!(int, int)[] arr;
    foreach (_; 0 .. n-1) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        arr ~= tuple(a, b);
    }

    if (arr.map!(t => t[1]).any!(x => x != n)) {
        writeln("NO");
        return;
    }

    auto mn = arr.map!(t => t[0]).array;

    mn.sort();

    debug { mn.writeln; }

    if (mn.enumerate(1).any!(t => t[0] > t[1])) {
        writeln("NO");
        return;
    }

    auto isFree = new bool[] (n+1);
    isFree[] = true;
    int nxt = 1;

    auto grouped = mn.group.array;

    Tuple!(int, int)[] ans;
    foreach (t; grouped) {
        int e = t[0], cnt = t[1];

        int[] cur;
        foreach (_; 1 .. cnt) {
            while (!isFree[nxt]) { ++nxt; }
            cur ~= nxt;
            isFree[nxt] = false;
        }

        cur ~= e;
        isFree[e] = false;

        foreach (a, b; lockstep(cur, cur.dropOne)) { ans ~= tuple(a, b); }

        ans ~= tuple(n, cur.front);
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

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

    if (E.map!(e => e[1] != N).any) {
        writeln("NO");
        return;
    }

    auto A = E.map!(e => e[0]).array;
    A.sort();

    foreach (i; 0..N-1) {
        if (A[i] < i + 1) {
            writeln("No");
            return;
        }
    }

    auto used = new int[](N+1);
    foreach (a; A) used[a] = true;
    auto ans = new int[](N-1);
    int start = 0;
    int x = 1;

    foreach (i; 0..N-1) {
        if (i == N - 2 || A[i] != A[i+1]) {
            ans[start] = A[i];
            foreach (j; start+1..i+1) {
                while (used[x]) ++x;
                used[x] = true;
                ans[j] = x;
            }
            start = i + 1;
        }
    }

    writeln("YES");
    foreach (i; 0..ans.length.to!int - 1) {
        writeln(ans[i], " ", ans[i+1]);
    }
    writeln(ans.back, " ", N);
}

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

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

    Tuple!(int, int)[] arr;
    foreach (_; 0 .. n-1) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        arr ~= tuple(a, b);
    }

    if (arr.map!(t => t[1]).any!(x => x != n)) {
        writeln("NO");
        return;
    }

    auto mn = arr.map!(t => t[0]).array;

    mn.sort();

    debug { mn.writeln; }

    if (mn.enumerate(1).any!(t => t[0] > t[1])) {
        writeln("NO");
        return;
    }

    auto isFree = new bool[] (n+1);
    isFree[] = true;
    int nxt = 1;

    auto grouped = mn.group.array;

    Tuple!(int, int)[] ans;
    foreach (t; grouped) {
        int e = t[0], cnt = t[1];

        int[] cur;
        foreach (_; 1 .. cnt) {
            while (!isFree[nxt]) { ++nxt; }
            cur ~= nxt;
        }

        isFree[e] = false;
        cur ~= e;

        foreach (a, b; lockstep(cur, cur.dropOne)) { ans ~= tuple(a, b); }

        ans ~= tuple(n, cur.front);
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

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

    int[] arr;
    foreach (_; 0 .. n-1) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        arr ~= a;
    }

    debug { arr.writeln; }

    arr.sort();

    Tuple!(int, int)[] ans;
    auto lst = 1;
    foreach (i, e; arr) {
        if (e < i+1) {
            writeln("NO");
            return;
        }

        if (i+1 < e) { continue; }

        foreach (v; lst .. e) {
            ans ~= tuple(v, v+1);
        }

        ans ~= tuple(lst, n);

        lst = e+1;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

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

    Tuple!(int, int)[] arr;
    foreach (_; 0 .. n-1) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        arr ~= tuple(a, b);
    }

    if (arr.map!(t => t[1]).any!(x => x != n)) {
        writeln("NO");
        return;
    }

    auto mn = arr.map!(t => t[0]).array;

    mn.sort();

    debug { mn.writeln; }

    arr.sort();

    Tuple!(int, int)[] ans;
    auto lst = 1;
    foreach (i, e; mn) {
        if (e < i+1) {
            writeln("NO");
            return;
        }

        if (i+1 < e) { continue; }

        foreach (v; lst .. e) {
            ans ~= tuple(v, v+1);
        }

        ans ~= tuple(lst, n);

        lst = e+1;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

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

    Tuple!(int, int)[] arr;
    foreach (_; 0 .. n-1) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        arr ~= tuple(a, b);
    }

    if (arr.map!(t => t[1]).any!(x => x != n)) {
        writeln("NO");
        return;
    }

    auto mn = arr.map!(t => t[1]).array;

    mn.sort();

    debug { mn.writeln; }

    arr.sort();

    Tuple!(int, int)[] ans;
    auto lst = 1;
    foreach (i, e; mn) {
        if (e < i+1) {
            writeln("NO");
            return;
        }

        if (i+1 < e) { continue; }

        foreach (v; lst .. e) {
            ans ~= tuple(v, v+1);
        }

        ans ~= tuple(lst, n);

        lst = e+1;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}


Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of Andrey's friends. The second line contains n real numbers pi (0.0 ≤ pi ≤ 1.0) — the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point.

Print a single real number — the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10 - 9.

NoteIn the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one.In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1·0.8 + 0.9·0.2 = 0.26.

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

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new real [n];
		foreach (ref x; p)
		{
			readf (" %s", &x);
		}
		sort (p);
		real res = 0.0;
		real good = 0.0;
		real bad = 1.0;
		foreach_reverse (c; p)
		{
			real nbad = bad * (1.0 - c);
			real ngood = good * (1.0 - c) + bad * c;
			if (res < ngood)
			{
				res = ngood;
				good = ngood;
				bad = nbad;
			}
		}
		writefln ("%.20g", res);
	}
}

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

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new real [n];
		foreach (ref x; p)
		{
			readf (" %s", &x);
		}
		sort (p);
		real res = 0.0;
		real good = 0.0;
		real bad = 1.0;
		foreach_reverse (c; p)
		{
			real nbad = bad * (1.0 - c);
			real ngood = good * (1.0 - c) + bad * c;
			res = max (res, ngood);
			good = ngood;
			bad = nbad;
		}
		writeln (res);
	}
}


Polycarp was presented with some sequence of integers $$$a$$$ of length $$$n$$$ ($$$1 \le a_i \le n$$$). A sequence can make Polycarp happy only if it consists of different numbers (i.e. distinct numbers).In order to make his sequence like this, Polycarp is going to make some (possibly zero) number of moves.In one move, he can:   remove the first (leftmost) element of the sequence. For example, in one move, the sequence $$$[3, 1, 4, 3]$$$ will produce the sequence $$$[1, 4, 3]$$$, which consists of different numbers.Determine the minimum number of moves he needs to make so that in the remaining sequence all elements are different. In other words, find the length of the smallest prefix of the given sequence $$$a$$$, after removing which all values in the sequence will be unique.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the given sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the given sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print your answer on a separate line — the minimum number of elements that must be removed from the beginning of the sequence so that all remaining elements are different.

NoteThe following are the sequences that will remain after the removal of prefixes:  $$$[1, 4, 3]$$$;  $$$[1]$$$;  $$$[1]$$$;  $$$[6, 5, 4, 3, 2, 1]$$$;  $$$[2, 1]$$$. It is easy to see that all the remaining sequences contain only distinct elements. In each test case, the shortest matching prefix was removed.

import std;
import std.outbuffer: OutBuffer;

void main()
{
    int t;
    OutBuffer buf = new OutBuffer();
    scanf("%d", &t);
    getchar();
    outer: foreach(_; 0..t)
    {
        int n;
        scanf("%d", &n);
        getchar();
        auto s = readln.split.to!(int[]);
        bool[int] uni;
        uni[s[n-1]] = true;
        foreach(i; iota(n-2,-1,-1)) {
            if (uni.get(s[i], false)) {
                writeln(i + 1);
                continue outer;
            }
            uni[s[i]] = true;
        }
        writeln(0);
    }
}


The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.

The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 100). Then follow n lines describing instructions. The i-th line contains m integers: xi1, xi2, ..., xim (0 ≤ xij ≤ k), where xij is the instruction that must be executed by the i-th core at the j-th cycle. If xij equals 0, then the corresponding instruction is «do nothing». But if xij is a number from 1 to k, then the corresponding instruction is «write information to the memory cell number xij». We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from 1 to k.

Print n lines. In the i-th line print integer ti. This number should be equal to 0 if the i-th core won't be locked, or it should be equal to the number of the cycle when this core will be locked.

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

void main ()
{
	int n, m, k;
	while (readf (" %s %s %s", &n, &m, &k) > 0)
	{
		auto b = new int [n];
		b[] = int.max;
		auto c = new bool [k];
		c[] = false;
		auto a = new int [] [] (m, n);
		foreach (i; 0..n)
		{
			foreach (t; 0..m)
			{
				readf (" %s", &a[t][i]);
				a[t][i]--;
			}
		}
		foreach (t; 0..m)
		{
			foreach (i; 0..n) if (b[i] == int.max && a[t][i] >= 0)
			{
				if (c[a[t][i]])
				{
					b[i] = min (b[i], t + 1);
				}
				foreach (j; i + 1..n) if (b[j] == int.max &&
				                          a[t][j] >= 0)
				{
					if (a[t][i] == a[t][j])
					{
						b[i] = min (b[i], t + 1);
						b[j] = min (b[j], t + 1);
						c[a[t][i]] = true;
					}
				}
			}
		}
		foreach (ref x; b)
		{
			if (x == int.max)
			{
				x = 0;
			}
		}
		writefln ("%(%s\n%)", b);
	}
}


At first, there was a legend related to the name of the problem, but now it's just a formal statement.You are given $$$n$$$ points $$$a_1, a_2, \dots, a_n$$$ on the $$$OX$$$ axis. Now you are asked to find such an integer point $$$x$$$ on $$$OX$$$ axis that $$$f_k(x)$$$ is minimal possible.The function $$$f_k(x)$$$ can be described in the following way:   form a list of distances $$$d_1, d_2, \dots, d_n$$$ where $$$d_i = |a_i - x|$$$ (distance between $$$a_i$$$ and $$$x$$$);  sort list $$$d$$$ in non-descending order;  take $$$d_{k + 1}$$$ as a result. If there are multiple optimal answers you can print any of them.

The first line contains single integer $$$T$$$ ($$$ 1 \le T \le 2 \cdot 10^5$$$) — number of queries. Next $$$2 \cdot T$$$ lines contain descriptions of queries. All queries are independent.  The first line of each query contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k < n$$$) — the number of points and constant $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_1 < a_2 < \dots < a_n \le 10^9$$$) — points in ascending order. It's guaranteed that $$$\sum{n}$$$ doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$T$$$ integers — corresponding points $$$x$$$ which have minimal possible value of $$$f_k(x)$$$. If there are multiple answers you can print any of them.

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		int d = int.max;
		int x;
		foreach (i; 0..n - k)
		{
			int cur = a[i + k] - a[i];
			if (d > cur)
			{
				d = cur;
				x = (a[i + k] + a[i]) / 2;
			}
		}
		writeln (x);
	}
}

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

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

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

void main() {
  auto r = new InputReader;
  immutable nt = r.next!uint;
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint;
    immutable k = r.next!uint;
    auto a = r.nextA!int (n);
    long res = int.max;
    int x = int.max;
    foreach (i; k .. n) {
      int d = a[i] - a[i - k];
      if (res > d) {
        res = d;
        x = (a[i] + a[i - k]) / 2;
      }
    }
    writeln (x);
  }
}

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 t = read.to!int;
	foreach(_; 0 .. t){
		int n = read.to!int;
		int k = read.to!int;

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

		long best = as[k] - as[0];
		int bestleft = 0;
		foreach(i; 0 .. n - k){
			long tmp = as[i + k] - as[i];
			if(tmp < best) best = tmp, bestleft = i;
		}

		long ans = as[bestleft] + best / 2;
		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; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

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

void main()
{
	auto T = RD!int;
	auto ans = new long[](T);
	foreach (i; 0..T)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto a = RDR.ARR;
		auto diff = new long[](n-k);
		foreach (j; k..n)
		{
			diff[j-k] = a[j] - a[j-k];
		}
		auto pos = MIN_POS(diff);
		ans[i]   = (a[pos+k] + a[pos]) / 2;
	}

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

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 t = read.to!int;
	foreach(_; 0 .. t){
		int n = read.to!int;
		int k = read.to!int;

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

		long best = as[k] - as[0];
		int bestleft = 0;
		{
			long tmp = as[n - 1] - as[n - 1 - k];
			if(tmp < best) best = tmp, bestleft = n - 1 - k;
		}
		foreach(i; 0 .. n - k - 1){
			long tmp = as[i + (k + 1)] - as[i];
			if(tmp < best) best = tmp, bestleft = i;
		}

		long ans = as[bestleft] + best / 2;
		ans.writeln;

	}
}


You play a computer game. In this game, you lead a party of $$$m$$$ heroes, and you have to clear a dungeon with $$$n$$$ monsters. Each monster is characterized by its power $$$a_i$$$. Each hero is characterized by his power $$$p_i$$$ and endurance $$$s_i$$$.The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero (exactly one) who is going to enter the dungeon this day.When the hero enters the dungeon, he is challenged by the first monster which was not defeated during the previous days (so, if the heroes have already defeated $$$k$$$ monsters, the hero fights with the monster $$$k + 1$$$). When the hero fights the monster, there are two possible outcomes:  if the monster's power is strictly greater than the hero's power, the hero retreats from the dungeon. The current day ends;  otherwise, the monster is defeated. After defeating a monster, the hero either continues fighting with the next monster or leaves the dungeon. He leaves the dungeon either if he has already defeated the number of monsters equal to his endurance during this day (so, the $$$i$$$-th hero cannot defeat more than $$$s_i$$$ monsters during each day), or if all monsters are defeated — otherwise, he fights with the next monster. When the hero leaves the dungeon, the current day ends.Your goal is to defeat the last monster. What is the minimum number of days that you need to achieve your goal? Each day you have to use exactly one hero; it is possible that some heroes don't fight the monsters at all. Each hero can be used arbitrary number of times.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then the test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of monsters in the dungeon. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the power of the $$$i$$$-th monster. The third line contains one integer $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the number of heroes in your party. Then $$$m$$$ lines follow, each describing a hero. Each line contains two integers $$$p_i$$$ and $$$s_i$$$ ($$$1 \le p_i \le 10^9$$$, $$$1 \le s_i \le n$$$) — the power and the endurance of the $$$i$$$-th hero. It is guaranteed that the sum of $$$n + m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print one integer — the minimum number of days you have to spend to defeat all of the monsters (or $$$-1$$$ if it is impossible).

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

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

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

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

        int m;
        readf("%s", &m);
        readln;

        Tuple!(int, int)[] htmp;
        foreach (i; 0 .. m) {
            int p, s;
            readf("%s %s", &p, &s);
            readln;

            htmp ~= tuple(p, s);
        }

        htmp = htmp.sort().array.retro().array;

        Tuple!(int, int)[] h;
        h ~= htmp[0];
        foreach (e; htmp[1 .. $]) {
            if (e[1] > h.back[1]) {
                h ~= e;
            }
        }

        debug { h.writeln; }

        if (a.maxElement > h.front[0]) {
            writeln(-1);
            continue;
        }

        int fnd(int ht) {
            int le = 0, r = h.length.to!int - 1;
            while (le < r) {
                int md = (le + r) / 2 + 1;
                if (ht <= h[md][0]) { le = md; }
                else { r = md - 1; }
            }

            return le;
        }

        int ans = 0;
        int lst = 0;
        int cur = -1;
        foreach (i, e; a) {
            if (cur == -1 || i - lst + 1 > h[cur][1]) {
                int idx = fnd(e);
                ++ans;
                lst = i.to!int;
                cur = idx;
            } else if (e > h[cur][0]) {
                int idx = fnd(e);
                if (i - lst + 1 > h[idx][1]) {
                    ++ans;
                    lst = i.to!int;
                }
                cur = idx;
            }

            debug { writeln(i, ' ', ans, ' ', cur); }
        }

        ans.writeln;
    }

}

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

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

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

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

        int m;
        readf("%s", &m);
        readln;

        int[int] hd;
        foreach (i; 0 .. m) {
            int p, s;
            readf("%s %s", &p, &s);
            readln;

            hd[s] = max(hd.get(s, 0), p);
        }

        auto h = hd.byPair.array;

        if (a.maxElement > h.back[1]) {
            writeln(-1);
            continue;
        }

        debug { h.writeln; }

        int ans = 0;
        int lst = 0;
        int cur = -1;
        foreach (i, e; a) {
            if (cur == -1
                || i - lst + 1 > h[cur][0]
                || e > h[cur][1]) {

                int le = 0, r = h.length.to!int - 1;
                while (le < r) {
                    int md = (le + r) / 2;
                    if (e <= h[md][1]) { r = md; }
                    else { le = md + 1; }
                }

                if (cur == -1 || (i - lst + 1 >= h[le][0])) {
                    ++ans;
                    lst = i.to!int;
                }

                cur = le;

                debug { writeln(i, ' ', ans, ' ', cur); }
            }
        }

        ans.writeln;
    }

}

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

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

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

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

        int m;
        readf("%s", &m);
        readln;

        int[int] hd;
        foreach (i; 0 .. m) {
            int p, s;
            readf("%s %s", &p, &s);
            readln;

            hd[s] = max(hd.get(s, 0), p);
        }

        auto h = hd.byPair.array;

        debug { h.writeln; }

        if (a.maxElement > h.front[1]) {
            writeln(-1);
            continue;
        }

        int ans = 0;
        int lst = 0;
        int cur = -1;
        foreach (i, e; a) {
            if (cur == -1
                || i - lst + 1 > h[cur][0]
                || e > h[cur][1]) {

                int le = 0, r = h.length.to!int - 1;
                while (le < r) {
                    int md = (le + r) / 2;
                    if (e <= h[md][1]) { r = md; }
                    else { le = md + 1; }
                }

                if (cur == -1 || (i - lst + 1 >= h[le][0])) {
                    ++ans;
                    lst = i.to!int;
                }

                cur = le;

                debug { writeln(i, ' ', ans, ' ', cur); }
            }
        }

        ans.writeln;
    }

}

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

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

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

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

        int m;
        readf("%s", &m);
        readln;

        Tuple!(int, int)[] htmp;
        foreach (i; 0 .. m) {
            int p, s;
            readf("%s %s", &p, &s);
            readln;

            htmp ~= tuple(p, s);
        }

        htmp = htmp.sort().array.retro().array;

        Tuple!(int, int)[] h;
        h ~= htmp[0];
        foreach (e; htmp[1 .. $]) {
            if (e[1] > h.back[1]) {
                h ~= e;
            }
        }

        debug { h.writeln; }

        if (a.maxElement > h.front[0]) {
            writeln(-1);
            continue;
        }

        int ans = 0;
        int lst = 0;
        int cmx = 0;
        int cur = -1;

        int fnd(int ht) {
            int le = 0, r = h.length.to!int - 1;
            while (le < r) {
                int md = (le + r) / 2 + 1;
                if (ht <= h[md][0]) { le = md; }
                else { r = md - 1; }
            }

            return le;
        }

        foreach (i, e; a) {
            cmx = max(cmx, e);

            if (cur == -1 || i - lst + 1 > h[cur][1]) {
                int idx = fnd(e);
                ++ans;
                cmx = e;
                cur = idx;
            } else if (e > h[cur][0]) {
                int idx = fnd(e);
                if (i - lst + 1 > h[idx][1]) {
                    cmx = e;
                    ++ans;
                }
                cur = idx;
            }

            debug { writeln(i, ' ', ans, ' ', cur); }
        }

        ans.writeln;
    }

}

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

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

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

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

        int m;
        readf("%s", &m);
        readln;

        Tuple!(int, int)[] htmp;
        foreach (i; 0 .. m) {
            int p, s;
            readf("%s %s", &p, &s);
            readln;

            htmp ~= tuple(p, s);
        }

        htmp = htmp.sort().array.retro().array;

        Tuple!(int, int)[] h;
        h ~= htmp[0];
        foreach (e; htmp[1 .. $]) {
            if (e[1] > h.back[1]) {
                h ~= e;
            }
        }

        debug { h.writeln; }

        if (a.maxElement > h.front[0]) {
            writeln(-1);
            continue;
        }

        int ans = 0;
        int lst = 0;
        int cur = -1;
        foreach (i, e; a) {
            if (cur == -1
                || i - lst + 1 > h[cur][1]
                || e > h[cur][0]) {

                int le = 0, r = h.length.to!int - 1;
                while (le < r) {
                    int md = (le + r) / 2 + 1;
                    if (e <= h[md][0]) { le = md; }
                    else { r = md - 1; }
                }

                if (cur == -1 || (i - lst + 1 >= h[le][1])) {
                    ++ans;
                    lst = i.to!int;
                }

                cur = le;

                debug { writeln(i, ' ', ans, ' ', cur); }
            }
        }

        ans.writeln;
    }

}


Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.The park is a rectangular table with $$$n$$$ rows and $$$m$$$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $$$1$$$. For example, park with $$$n=m=2$$$ has $$$12$$$ streets.You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park).    The park sizes are: $$$n=4$$$, $$$m=5$$$. The lighted squares are marked yellow. Please note that all streets have length $$$1$$$. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit. Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$n$$$, $$$m$$$ ($$$1 \le n, m \le 10^4$$$) — park sizes.

Print $$$t$$$ answers to the test cases. Each answer must be a single integer — the minimum number of lanterns that are required to light all the squares.

NotePossible optimal arrangement of the lanterns for the $$$2$$$-nd test case of input data example: Possible optimal arrangement of the lanterns for the $$$3$$$-rd test case of input data example:

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int a, b;
		readf !(" %s %s") (a, b);
		writeln ((a * b + 1) / 2);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		if (n % 2 == 0)
			ans[ti] = (n/2) * m;
		else if (m % 2 == 0)
			ans[ti] = (m/2) * n;
		else
		{
			ans[ti] = (n/2) * m;
			ans[ti] += (m+1)/2;
		}
	}

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


We'll call a set of positive integers a beautiful if the following condition fulfills: for any prime p, if , then . In other words, if one number from the set is divisible by prime p, then at least half of numbers from the set is divisible by p.Your task is to find any beautiful set, where the number of elements is equal to k and each element doesn't exceed 2k2.

The first line contains integer k (10 ≤ k ≤ 5000) that shows how many numbers the required beautiful set should have.

In the first line print k space-separated integers that are a beautiful set. If there are multiple such sets, you are allowed to print any of them.

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

immutable int [] p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		long [] a;
		int m = n * n * 2;

		for (int d = 1; d <= p.length; d++)
		{
			void recur (long v, int c)
			{
				if (v > m)
				{
					return;
				}
				if (a.length == n)
				{
					return;
				}
				foreach (i; c..d)
				{
					recur (v * p[i], i);
					if (a.length >= 3 * n)
					{
						return;
					}
				}
				a ~= v;
			}

			bool solve ()
			{
				a = [];
				recur (1, 0);
				if (a.length < n)
				{
					return false;
				}

				auto s = new int [d];
				foreach (j; 0..a.length)
				{
					foreach (i; 0..d)
					{
						s[i] += (a[j] % p[i] == 0);
					}
					if (j >= n - 1)
					{
						bool ok = true;
						foreach (i; 0..d)
						{
							if (s[i] * 2 < n)
							{
								ok = false;
								break;
							}
						}
						if (ok)
						{
							a = a[j - n + 1..
							      j + 1];
							return true;
						}

						foreach (i; 0..d)
						{
							s[i] -= (a[j - n + 1] %
							         p[i] == 0);
						}
					}
				}

				return true;
			}

			if (solve ())
			{
				break;
			}
		}

		assert (a.length == n);
		sort (a);
		foreach (i; 0..p.length)
		{
			int num = 0;
			foreach (e; a)
			{
				num += (e % p[i] == 0);
			}
			debug {writeln (p[i], ": ", num);}
			if (num != 0 && num * 2 < n)
			{
				assert (false);
			}
		}
		writefln ("%(%s %)", a);
	}
}

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

immutable int [] p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		long [] a;
		int m = n * n * 2;

		for (int d = 1; d <= p.length; d++)
		{
			void recur (long v, int c)
			{
				if (v > m)
				{
					return;
				}
				if (a.length == n)
				{
					return;
				}
				foreach (i; c..d)
				{
					recur (v * p[i], i);
					if (a.length == n)
					{
						return;
					}
				}
				a ~= v;
			}

			a = [];
			recur (1, 0);
			bool ok = true;
			foreach (i; 0..d)
			{
				int num = 0;
				foreach (e; a)
				{
					num += (e % p[i] == 0);
				}
				debug {writeln (p[i], ": ", num);}
				if (num * 2 < n)
				{
					ok = false;
					break;
				}
			}
			if (ok)
			{
				break;
			}
		}

		sort (a);
		writefln ("%(%s %)", a);
	}
}

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

immutable int [] p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		long [] a;
		int m = n * n * 2;

		for (int d = 1; d <= p.length; d++)
		{
			void recur (long v, int c)
			{
				if (v > m)
				{
					return;
				}
				if (a.length == n)
				{
					return;
				}
				foreach (i; c..d)
				{
					recur (v * p[i], i);
					if (a.length == n)
					{
						return;
					}
				}
				a ~= v;
			}

			a = [];
			recur (1, 0);
			bool ok = true;
			foreach (i; 0..d)
			{
				int num = 0;
				foreach (e; a)
				{
					num += (e % p[i] == 0);
				}
				debug {writeln (p[i], ": ", num);}
				if (num * 2 < n)
				{
					ok = false;
					break;
				}
			}
			if (ok)
			{
				break;
			}
		}

		writefln ("%(%s %)", a);
	}
}


Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence pi. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.While Gennady treats the teeth of the i-th child, the child is crying with the volume of vi. At that the confidence of the first child in the line is reduced by the amount of vi, the second one — by value vi - 1, and so on. The children in the queue after the vi-th child almost do not hear the crying, so their confidence remains unchanged.If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of dj and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of dj.All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.

The first line of the input contains a positive integer n (1 ≤ n ≤ 4000) — the number of kids in the line.  Next n lines contain three integers each vi, di, pi (1 ≤ vi, di, pi ≤ 106) — the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child.

In the first line print number k — the number of children whose teeth Gennady will cure. In the second line print k integers — the numbers of the children who will make it to the end of the line in the increasing order.

NoteIn the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to  - 2, 1, 3, 1, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0, 2, 0. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit.In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5,  - 1, 6, 8. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5, 5, 7. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0, 3. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last.

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

void main() {
    long n = readln.chomp.to!long;
    long[][] children;
    bool[] remain = new bool[cast(uint)n];

    for (int i = 0; i < n; i++) {
        children ~= readln.chomp.split.map!(to!long).array;
        remain[i] = true;
    }

    long[] ans;
    foreach (int i, e; children) {
        long v = e[0];
        long d = e[1];
        long p = e[2];

        if (p >= 0) {
            ans ~= i + 1;
            long vv = v;
            for (int j = i + 1; j < children.length; j++) {
                if (vv <= 0) {
                    break;
                }
                if (remain[j]) {
                    children[j][2] -= vv;
                    vv--;
                }
            }
        }

        long decr = 0;
        for (int j = i + 1; j < children.length; j++) {
            if (remain[j]) {
                children[j][2] -= decr;
                if (children[j][2] < 0) {
                    remain[j] = false;
                    decr += children[j][1];
                }
            }
        }
    }

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

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

void main() {
    int n = readln.chomp.to!int;
    int[][] children;
    bool[] remain = new bool[n];

    for (int i = 0; i < n; i++) {
        children ~= readln.chomp.split.map!(to!int).array;
        remain[i] = true;
    }

    int[] ans;
    foreach (int i, e; children) {
        int v = e[0];
        int d = e[1];
        int p = e[2];

        if (p >= 0) {
            ans ~= i + 1;
            int vv = v;
            for (int j = i + 1; j < children.length; j++) {
                if (vv <= 0) {
                    break;
                }
                if (remain[j]) {
                    children[j][2] -= vv;
                    vv--;
                }
            }
        }

        int decr = 0;
        for (int j = i + 1; j < children.length; j++) {
            if (remain[j]) {
                children[j][2] -= decr;
                if (children[j][2] < 0) {
                    remain[j] = false;
                    decr += children[j][1];
                }
            }
        }
    }

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


There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≤ i, j ≤ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.

The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.

Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.

module main;
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.variant,
	std.stdio,std.bitmanip;
import core.stdc.stdio : freopen;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias boyerMooreFinder strfind;
alias make_pair mp;
alias binary_search bins;
alias pair(X,Y)=Tuple!(X,q{fi},Y,q{se});
pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_)
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
immutable int mod=10^^9+7;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b)
	{
		return a/gcd(a,b)*b;
	}
	@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))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(g<a[m])r=m;
			else l=m;
		}
		return (g<a[l])?l:r;
	}
	size_t binf(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 (g==a[l])?l: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,in size_t m) if(isRandomAccessRange!X)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n) if(hasSlicing!X)
{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 void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow void ouf(in char* name) {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 countUntil
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	/*int n;
	loop:while(read(&n))
	{

	}*/
	auto s=readln.strip;
	int[char] w;
	foreach(c;s)w[c]++;
	long ans;
	foreach(k;w.byValue)
	{
		ans+=1L*k*(k-1);
	}
	writeln(ans+s.length);
}


Vlad went into his appartment house entrance, now he is on the $$$1$$$-th floor. He was going to call the elevator to go up to his apartment.There are only two elevators in his house. Vlad knows for sure that:  the first elevator is currently on the floor $$$a$$$ (it is currently motionless),  the second elevator is located on floor $$$b$$$ and goes to floor $$$c$$$ ($$$b \ne c$$$). Please note, if $$$b=1$$$, then the elevator is already leaving the floor $$$1$$$ and Vlad does not have time to enter it. If you call the first elevator, it will immediately start to go to the floor $$$1$$$. If you call the second one, then first it will reach the floor $$$c$$$ and only then it will go to the floor $$$1$$$. It takes $$$|x - y|$$$ seconds for each elevator to move from floor $$$x$$$ to floor $$$y$$$.Vlad wants to call an elevator that will come to him faster. Help him choose such an elevator.

The first line of the input contains the only $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. This is followed by $$$t$$$ lines, three integers each $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^8$$$, $$$b \ne c$$$) — floor numbers described in the statement.

Output $$$t$$$ numbers, each of which is the answer to the corresponding test case. As an answer, output:   $$$1$$$, if it is better to call the first elevator;  $$$2$$$, if it is better to call the second one;  $$$3$$$, if it doesn't matter which elevator to call (both elevators will arrive in the same time).

NoteIn the first test case of the example, the first elevator is already on the floor of $$$1$$$.In the second test case of the example, when called, the elevators would move as follows:  At the time of the call, the first elevator is on the floor of $$$3$$$, and the second one is on the floor of $$$1$$$, but is already going to another floor;  in $$$1$$$ second after the call, the first elevator would be on the floor $$$2$$$, the second one would also reach the floor $$$2$$$ and now can go to the floor $$$1$$$;  in $$$2$$$ seconds, any elevator would reach the floor $$$1$$$. In the third test case of the example, the first elevator will arrive in $$$2$$$ seconds, and the second in $$$1$$$.

import std.stdio;
import std.math;
import core.stdc.stdio;

void main() {
    int T;
    scanf("%d\n", &T);
    while (T--) {
        int a, b, c; scanf("%d %d %d\n", &a, &b, &c);
        int x = a - 1,
            y = abs(b - c) + abs(c - 1);
        if (x < y) {
            writeln(1);
        } else if (x > y) {
            writeln(2);
        } else {
            writeln(3);
        }
    }
}


Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.

The first line contains integer n (1 ≤ n ≤ 105) — the number of nodes in the tree. The next n - 1 lines contain the tree edges. The i-th line contains integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the nodes that are connected by the i-th edge. It is guaranteed that the given graph is a tree.

Print a single real number — the expectation of the number of steps in the described game. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.

NoteIn the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are: 1 × (1 / 2) + 2 × (1 / 2) = 1.5In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are: 1 × (1 / 3) + (1 + 1.5) × (2 / 3) = (1 / 3) + (5 / 3) = 2

import std.stdio;

int [] [] a;
double res;
int n;

void recur (int v, int p, int d)
{
	res += 1.0 / d;
	foreach (u; a[v])
		if (u != p)
			recur (u, v, d + 1);
}

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

		res = 0;
		recur (1, 0, 1);
		writefln ("%.7f", res);
	}
}

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

int [] [] a;
double res;

void recur (int v, int p, int d)
{
	res += 1.0 / d;
	foreach (u; a[v])
	{
		if (u != p)
		{
			recur (u, v, d + 1);
		}
	}
}

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

		res = 0;
		recur (0, -1, 1);
		writefln ("%.10f", res);
	}
}


You are given a string $$$s$$$, consisting of $$$n$$$ letters, each letter is either 'a' or 'b'. The letters in the string are numbered from $$$1$$$ to $$$n$$$.$$$s[l; r]$$$ is a continuous substring of letters from index $$$l$$$ to $$$r$$$ of the string inclusive. A string is called balanced if the number of letters 'a' in it is equal to the number of letters 'b'. For example, strings "baba" and "aabbab" are balanced and strings "aaab" and "b" are not.Find any non-empty balanced substring $$$s[l; r]$$$ of string $$$s$$$. Print its $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$). If there is no such substring, then print $$$-1$$$ $$$-1$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of the string. The second line of the testcase contains a string $$$s$$$, consisting of $$$n$$$ letters, each letter is either 'a' or 'b'.

For each testcase print two integers. If there exists a non-empty balanced substring $$$s[l; r]$$$, then print $$$l$$$ $$$r$$$ ($$$1 \le l \le r \le n$$$). Otherwise, print $$$-1$$$ $$$-1$$$.

NoteIn the first testcase there are no non-empty balanced subtrings.In the second and third testcases there are multiple balanced substrings, including the entire string "abbaba" and substring "baba".

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto s = [0] ~ (cast(char[])readString).map!(c => c == 'a'? 1 : -1).array;
	auto ss = s.cumulativeFold!((a, b) => a + b).array;
	foreach(i; 1 .. n+1)
		foreach(j; i+1 .. n+1)
		{
			if (ss[i-1] == ss[j])
			{
				return writeln(i, " ", j);
			}
		}
	return writeln("-1 -1");
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// 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;
// }}}

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

void main()
{
    int t;
    scanf("%d", &t);
    foreach(_; 0..t)
    {
        int str_len;
        scanf("%d", &str_len);
        getchar();
        auto str = readln.strip();
        // writeln(str);
        int[] check = new int[str_len];
        bool flag = true;
        for(int i = 0; i < str_len; i++)
        {
            if (flag == false)
                break;
            if (str[i] == 'a')
            {
                for (int j = i; j >= 0; j--)
                {
                    check[j] += 1;
                    if (check[j] == 0)
                    {
                        writeln(j + 1,' ', i + 1);
                        flag = false;
                    }
                }
            }
            else
            {
                for (int j = i; j >= 0; j--)
                {
                    check[j] -= 1;
                    if (check[j] == 0)
                    {
                        writeln(j + 1,' ', i + 1);
                        flag = false;
                    }
                }
            }
        }
        if (flag)
            writeln("-1 -1");
    }
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto s = [0] ~ (cast(char[])readString).map!(c => c == 'a'? 1 : -1).array;
	auto ss = s.cumulativeFold!((a, b) => a + b).array;
	foreach(i; 1 .. n)
		foreach(j; i+1 .. n)
		{
			if (ss[i-1] == ss[j])
			{
				return writeln(i, " ", j);
			}
		}
	return writeln("-1 -1");
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// 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;
// }}}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto s = [0] ~ (cast(char[])readString).map!(c => c == 'a'? 1 : -1).array;
	auto ss = s.cumulativeFold!((a, b) => a + b).array;
	foreach(i; 1 .. n)
		foreach(j; 1 .. n)
		{
			if (ss[i] == ss[j-1])
			{
				return writeln(i, " ", j);
			}
		}
	return writeln("-1 -1");
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// 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;
// }}}


For the first place at the competition, Alex won many arrays of integers and was assured that these arrays are very expensive. After the award ceremony Alex decided to sell them. There is a rule in arrays pawnshop: you can sell array only if it can be compressed to a generator.This generator takes four non-negative numbers $$$n$$$, $$$m$$$, $$$c$$$, $$$s$$$. $$$n$$$ and $$$m$$$ must be positive, $$$s$$$ non-negative and for $$$c$$$ it must be true that $$$0 \leq c < m$$$. The array $$$a$$$ of length $$$n$$$ is created according to the following rules:   $$$a_1 = s \bmod m$$$, here $$$x \bmod y$$$ denotes remainder of the division of $$$x$$$ by $$$y$$$;  $$$a_i = (a_{i-1} + c) \bmod m$$$ for all $$$i$$$ such that $$$1 < i \le n$$$. For example, if $$$n = 5$$$, $$$m = 7$$$, $$$c = 4$$$, and $$$s = 10$$$, then $$$a = [3, 0, 4, 1, 5]$$$.Price of such an array is the value of $$$m$$$ in this generator.Alex has a question: how much money he can get for each of the arrays. Please, help him to understand for every array whether there exist four numbers $$$n$$$, $$$m$$$, $$$c$$$, $$$s$$$ that generate this array. If yes, then maximize $$$m$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of arrays. The first line of array description contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the size of this array. The second line of array description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$ ) — elements of the array.  It is guaranteed that the sum of array sizes does not exceed $$$10^5$$$.

For every array print:    $$$-1$$$, if there are no such four numbers that generate this array;  $$$0$$$, if $$$m$$$ can be arbitrary large;  the maximum value $$$m$$$ and any appropriate $$$c$$$ ($$$0 \leq c < m$$$) in other cases.

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

/*
a[i]-a[i-1] = c (mod m)
a[1] = s mod m
m > a[i] for i=1,...,n

arbitrary s
m | a[1]-s
m | a[i]-(a[i-1]+c) = a[i]-a[i-1]-c

1 positive, 1 negative at MAX
a = -b => mod is a-(-b).

if only positive or only negative, m can be arbitrary large
if >1 pos or >1 neg, impossible.
*/

void main() {
    int t; readf(" %d",&t);
    while (t--) {
        int n; readf(" %d",&n);
        int[] a;
        foreach (i; 0..n) {
            int x; readf(" %d",&x);
            a~=x;
        }
        RedBlackTree!int neg = new RedBlackTree!int;
        RedBlackTree!int nonneg = new RedBlackTree!int;
        int mxElem = a[0];
        foreach (i; 1..n) {
            mxElem=max(mxElem, a[i]);
            immutable int c = a[i]-a[i-1];
            if (c>=0) nonneg.insert(c);
            else neg.insert(c);
        }
        if (neg.length()>1 || nonneg.length()>1)
            writeln(-1);
        else if (neg.length()==0 || nonneg.length()==0)
            writeln(0);
        else {
            const int m=nonneg.front()-neg.back();
            if (m>mxElem)
                writefln("%d %d",m,nonneg.front());
            else writeln(-1);
        }
    }
}


Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.

The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers:    0 ≤ plusi, minusi ≤ 50;  150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved;  300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved;  450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved;  600 ≤ di ≤ 2000 or di = 0, if problem D is not solved;  750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved.  All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).

Print on the single line the handle of the room leader.

NoteThe number of points that each participant from the example earns, are as follows:   Petr — 3860  tourist — 4140  Egor — 4030  c00lH4x0R —  - 350  some_participant — 2220 Thus, the leader of the room is tourist.

module cf_74a;

import std.stdio;

void main() {
  int n;
  string nick, leaderNick;
  int plus, minus, a, b, c, d, e;
  int leaderScore = int.min;

  readf("%d", &n);
  for (int i = 0; i < n; ++i) {
    readf(" %s ", &nick);
    readf(" %d %d", &plus, &minus);
    readf(" %d %d %d %d %d", &a, &b, &c, &d, &e);

    int curScore = plus * 100 - minus * 50 + a + b + c + d + e;
    if (curScore > leaderScore) {
      leaderScore = curScore;
      leaderNick = nick;
    }
  }

  writeln(leaderNick);
}


The only difference between easy and hard versions is constraints.There are $$$n$$$ kids, each of them is reading a unique book. At the end of any day, the $$$i$$$-th kid will give his book to the $$$p_i$$$-th kid (in case of $$$i = p_i$$$ the kid will give his book to himself). It is guaranteed that all values of $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i.e. $$$p$$$ is a permutation). The sequence $$$p$$$ doesn't change from day to day, it is fixed.For example, if $$$n=6$$$ and $$$p=[4, 6, 1, 3, 5, 2]$$$ then at the end of the first day the book of the $$$1$$$-st kid will belong to the $$$4$$$-th kid, the $$$2$$$-nd kid will belong to the $$$6$$$-th kid and so on. At the end of the second day the book of the $$$1$$$-st kid will belong to the $$$3$$$-th kid, the $$$2$$$-nd kid will belong to the $$$2$$$-th kid and so on.Your task is to determine the number of the day the book of the $$$i$$$-th child is returned back to him for the first time for every $$$i$$$ from $$$1$$$ to $$$n$$$.Consider the following example: $$$p = [5, 1, 2, 4, 3]$$$. The book of the $$$1$$$-st kid will be passed to the following kids:  after the $$$1$$$-st day it will belong to the $$$5$$$-th kid,  after the $$$2$$$-nd day it will belong to the $$$3$$$-rd kid,  after the $$$3$$$-rd day it will belong to the $$$2$$$-nd kid,  after the $$$4$$$-th day it will belong to the $$$1$$$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 200$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 200$$$) — the number of kids in the query. The second line of the query contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct, i.e. $$$p$$$ is a permutation), where $$$p_i$$$ is the kid which will get the book of the $$$i$$$-th kid.

For each query, print the answer on it: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the number of the day the book of the $$$i$$$-th child is returned back to him for the first time in this query.

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[][](q);
	foreach (i; 0..q)
	{
		auto n = RD!int;
		auto p = RDA!int(-1);
		auto root = new int[](n);
		root[] = -1;
		ans[i].length = n;
		foreach (j; 0..n)
		{
			if (root[j] != -1)
			{
				ans[i][j] = ans[i][root[j]];
				continue;
			}
			int pos = p[j];
			root[j] = j;
			int cnt = 1;
			while (pos != j)
			{
				++cnt;
				root[pos] = j;
				pos = p[pos];
			}
			ans[i][j] = cnt;
		}
	}

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

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


Alice and Bob got very bored during a long car trip so they decided to play a game. From the window they can see cars of different colors running past them. Cars are going one after another.The game rules are like this. Firstly Alice chooses some color A, then Bob chooses some color B (A ≠ B). After each car they update the number of cars of their chosen color that have run past them. Let's define this numbers after i-th car cntA(i) and cntB(i).  If cntA(i) > cntB(i) for every i then the winner is Alice.  If cntB(i) ≥ cntA(i) for every i then the winner is Bob.  Otherwise it's a draw. Bob knows all the colors of cars that they will encounter and order of their appearance. Alice have already chosen her color A and Bob now wants to choose such color B that he will win the game (draw is not a win). Help him find this color.If there are multiple solutions, print any of them. If there is no such color then print -1.

The first line contains two integer numbers n and A (1 ≤ n ≤ 105, 1 ≤ A ≤ 106) – number of cars and the color chosen by Alice. The second line contains n integer numbers c1, c2, ..., cn (1 ≤ ci ≤ 106) — colors of the cars that Alice and Bob will encounter in the order of their appearance.

Output such color B (1 ≤ B ≤ 106) that if Bob chooses it then he will win the game. If there are multiple solutions, print any of them. If there is no such color then print -1. It is guaranteed that if there exists any solution then there exists solution with (1 ≤ B ≤ 106).

NoteLet's consider availability of colors in the first example:   cnt2(i) ≥ cnt1(i) for every i, and color 2 can be the answer.  cnt4(2) < cnt1(2), so color 4 isn't the winning one for Bob.  All the other colors also have cntj(2) < cnt1(2), thus they are not available. In the third example every color is acceptable except for 10.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto A = s[1];
    auto C = readln.split.map!(to!int).array;

    immutable int MAX = 10^^6 + 1;
    auto cnt = new bool[int][](MAX);
    foreach (i; 1..MAX) if (i != A) cnt[0][i] = true;
    auto cnt2 = new int[](MAX);

    bool[int] ans;
    foreach (i; 1..MAX) if (i != A) ans[i] = true;

    foreach (c; C) {
        if (c == A) {
            cnt2[c] += 1;
            int old = cnt2[c] - 1;
            foreach (i; cnt[old].keys) {
                if (i in ans) ans.remove(i);
                cnt2[i] = -1;
            }
            cnt[old].clear;
        } else if (cnt2[c] != -1) {
            cnt[cnt2[c]].remove(c);
            cnt2[c] += 1;
            cnt[cnt2[c]][c] = true;
        }
    }

    if (ans.keys.length == 0) writeln(-1);
    else writeln(ans.keys[0]);
}

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;

immutable lim = 10^^6 + 1;

int n, a;
int[] c;

void main() {
    scan(n, a);
    c = readln.split.to!(int[]);

    auto cnt = new int[](lim);
    auto ok = new bool[](lim);
    ok[] = true;

    foreach (ci ; c){
        cnt[ci]++;

        if (ci != a && cnt[ci] <= cnt[a]) {
            ok[ci] = false;
        }
    }

    foreach (i ; 1 .. lim) {
        if (i == a) continue;
        if (cnt[i] >= cnt[a] && ok[i]) {
            writeln(i);
            return;
        }
    }

    writeln(-1);

}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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

class SegTree(T){
private:
    T[] data;
    int N;

public:
    int depth;

    this(int size){
        N = size;

        while(2^^depth < N){
            depth++;
        }

        data = new int[](2^^(depth + 1) - 1);
    }

    void update(int i, T x){
        i += 2^^depth - 1;
        data[i] = x;

        while(i > 0){
            i = (i - 1) / 2;
            data[i] = max(data[2*i + 1], data[2*i + 2]);
        }
    }

    T find(int s, int t, int k, int l, int r){
        if (r <= s || t <= l) {
            return 0;
        }

        if (s <= l && r <= t) {
            return data[k];
        }

        auto vl = find(s, t, 2*k + 1, l, (l + r) / 2);
        auto vr = find(s, t, 2*k + 2, (l + r) / 2, r);

        return max(vl, vr);
    }

    void print(){
        stderr.writefln("%(%s %)", data);
    }
}

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;

immutable lim = 10^^6 + 1;

int n, a;
int[] c;

void main() {
    scan(n, a);
    c = readln.split.to!(int[]);

    auto cnt = new int[](lim);
    auto sg = new SegTree!(int)(lim);

    foreach (ci ; c) {
        if (ci == a) {
            cnt[a]++;

            if (cnt[a] > sg.find(0, lim, 0, 0, 2^^sg.depth)) {
                writeln(-1);
                return;
            }
        }
        else {
            cnt[ci]++;
            sg.update(ci, cnt[ci]);
        }

        debug {
            //sg.print();
            writeln("cnt:", cnt[0 .. 20]);
        }
    }

    foreach (i ; 1 .. lim) {
        if (i == a) continue;

        if (cnt[i] >= cnt[a]) {
            writeln(i);
            return;
        }
    }
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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

class SegTree(T){
private:
    T[] data;
    int N;

public:
    int depth;

    this(int size){
        N = size;

        while(2^^depth < N){
            depth++;
        }

        data = new int[](2^^(depth + 1) - 1);
    }

    void update(int i, T x){
        i += 2^^depth - 1;
        data[i] = x;

        while(i > 0){
            i = (i - 1) / 2;
            data[i] = max(data[2*i + 1], data[2*i + 2]);
        }
    }

    T find(int s, int t, int k, int l, int r){
        if (r <= s || t <= l) {
            return 0;
        }

        if (s <= l && r <= t) {
            return data[k];
        }

        auto vl = find(s, t, 2*k + 1, l, (l + r) / 2);
        auto vr = find(s, t, 2*k + 2, (l + r) / 2, r);

        return max(vl, vr);
    }

    void print(){
        stderr.writefln("%(%s %)", data);
    }
}

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;

immutable lim = 10^^6 + 1;

int n, a;
int[] c;

void main() {
    scan(n, a);
    c = readln.split.to!(int[]);

    auto cnt = new int[](lim);
    auto sg = new SegTree!(int)(lim);

    foreach (ci ; c) {
        if (ci == a) {
            cnt[a]++;

            if (cnt[a] > sg.find(0, lim, 0, 0, 2^^sg.depth)) {
                writeln(-1);
                return;
            }
        }
        else {
            cnt[ci]++;
            sg.update(ci, cnt[ci]);
        }

        debug {
            //sg.print();
            writeln("cnt:", cnt[0 .. 20]);
        }
    }

    foreach (i ; 1 .. lim) {
        if (i == a) continue;

        if (cnt[i] > 0 && cnt[i] >= cnt[a]) {
            writeln(i);
            return;
        }
    }
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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

class SegTree(T){
private:
    T[] data;
    int N;

public:
    int depth;

    this(int size){
        N = size;

        while(2^^depth < N){
            depth++;
        }

        data = new int[](2^^(depth + 1) - 1);
    }

    void update(int i, T x){
        i += 2^^depth - 1;
        data[i] = x;

        while(i > 0){
            i = (i - 1) / 2;
            data[i] = max(data[2*i + 1], data[2*i + 2]);
        }
    }

    T find(int s, int t, int k, int l, int r){
        if (r <= s || t <= l) {
            return 0;
        }

        if (s <= l && r <= t) {
            return data[k];
        }

        auto vl = find(s, t, 2*k + 1, l, (l + r) / 2);
        auto vr = find(s, t, 2*k + 2, (l + r) / 2, r);

        return max(vl, vr);
    }

    void print(){
        stderr.writefln("%(%s %)", data);
    }
}


A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$).

For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer  — the minimum possible value of $$$k$$$.

NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$.

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int T; scanf("%d\n", &T);
    foreach (t; 0 .. T) {
        long N; scanf("%lld\n", &N);
        int dfs(long n, long d, long f) {
            // have to make n, with 2^x and d'! (d' >= d). f = d!
            int ans = popcnt(n);
            long nf = f * (d + 1);
            if (n >= f) {
                ans = min(ans, 1 + dfs(n - f, d+1, nf));
            }
            if (n >= nf) {
                ans = min(ans, dfs(n, d+1, nf));
            }
            return ans;
        }
        writeln(dfs(N, 3, 6));
    }
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int T; scanf("%d\n", &T);
    foreach (t; 0 .. T) {
        long N; scanf("%Ld\n", &N);
        int dfs(long n, long d, long f) {
            // have to make n, with 2^x and d'! (d' >= d). f = d!
            int ans = popcnt(n);
            long nf = f * (d + 1);
            if (n >= f) {
                ans = min(ans, 1 + dfs(n - f, d+1, nf));
            }
            if (n >= nf) {
                ans = min(ans, dfs(n, d+1, nf));
            }
            return ans;
        }
        writeln(dfs(N, 3, 6));
    }
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int T; scanf("%d\n", &T);
    foreach (t; 0 .. T) {
        long N; scanf("%Ld\n", &N);
        int dfs(long n, long d, long f) {
            // have to make n, with 2^x and d'! (d' >= d). f = d!
            int ans = popcnt(n);
            if (n >= f) {
                long nf = f * (d + 1);
                ans = min(ans, 1 + dfs(n - f, d+1, nf));
            }
            return ans;
        }
        writeln(dfs(N, 3, 6));
    }
}


Polycarp was recently given a set of $$$n$$$ (number $$$n$$$ — even) dominoes. Each domino contains two integers from $$$1$$$ to $$$n$$$.Can he divide all the dominoes into two sets so that all the numbers on the dominoes of each set are different? Each domino must go into exactly one of the two sets.For example, if he has $$$4$$$ dominoes: $$$\{1, 4\}$$$, $$$\{1, 3\}$$$, $$$\{3, 2\}$$$ and $$$\{4, 2\}$$$, then Polycarp will be able to divide them into two sets in the required way. The first set can include the first and third dominoes ($$$\{1, 4\}$$$ and $$$\{3, 2\}$$$), and the second set — the second and fourth ones ($$$\{1, 3\}$$$ and $$$\{4, 2\}$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains a single even integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of dominoes. The next $$$n$$$ lines contain pairs of numbers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) describing the numbers on the $$$i$$$-th domino. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print:   YES, if it is possible to divide $$$n$$$ dominoes into two sets so that the numbers on the dominoes of each set are different;  NO if this is not possible.  You can print YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer).

NoteIn the first test case, the dominoes can be divided as follows:   First set of dominoes: $$$[\{1, 2\}, \{4, 3\}]$$$  Second set of dominoes: $$$[\{2, 1\}, \{3, 4\}]$$$  In other words, in the first set we take dominoes with numbers $$$1$$$ and $$$2$$$, and in the second set we take dominoes with numbers $$$3$$$ and $$$4$$$.In the second test case, there's no way to divide dominoes into $$$2$$$ sets, at least one of them will contain repeated number.

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() {
    int N = readln.chomp.to!int;
    int[] A = new int[N],
          B = new int[N];

    bool C() {
        int[][] V = new int[][N];
        foreach (i; 0 .. N) {
            int a, b; readf("%d %d\n", &a, &b);
            a--; b--;
            A[i] = a;
            B[i] = b;
            V[a] ~= i;
            V[b] ~= i;
        }
        for (int i = 0; i < N; i++) {
            if (V[i].length != 2) return false;
            if (A[i] == B[i]) return false;
        }
        bool[int] X, Y;
        bool[int] used;

        bool fill(int i) {
            int a = A[i], b = B[i];
            if (a !in X && b !in X) {
                used[i] = true;
                X[a] = true;
                X[b] = true;
                foreach (v; V[a] ~ V[b]) {
                    if (v in used) continue;
                    if (! fill(v)) return false;
                }
                return true;
            } else if (a !in Y && b !in Y) {
                used[i] = true;
                Y[a] = true;
                Y[b] = true;
                foreach (v; V[a] ~ V[b]) {
                    if (v in used) continue;
                    if (! fill(v)) return false;
                }
                return true;
            } else {
                return false;
            }
        }

        for (int i = 0; i < N; i++) {
            if (i in used) continue;
            if (! fill(i)) return false;
        }
        return true;
    }
    writeln(C() ? "YES" : "NO");
}

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

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() {
    int N = readln.chomp.to!int;
    int[] A = new int[N],
          B = new int[N];

    bool C() {
        int[][] V = new int[][N];
        foreach (i; 0 .. N) {
            int a, b; readf("%d %d\n", &a, &b);
            a--; b--;
            A[i] = a;
            B[i] = b;
            V[a] ~= i;
            V[b] ~= i;
        }
        for (int i = 0; i < N; i++) {
            if (V[i].length != 2) return false;
            if (A[i] == B[i]) return false;
        }
        bool[int] X, Y;
        for (int i = 0; i < N; i++) {
            int a = A[i], b = B[i];
            if (a !in X && b !in X) {
                X[a] = true;
                X[b] = true;
            } else if (a !in Y && b !in Y) {
                Y[a] = true;
                Y[b] = true;
            } else {
                return false;
            }
        }
        return true;
    }
    writeln(C() ? "YES" : "NO");
}

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