This is the easy version of the problem. The only difference from the hard version is that in this version all coordinates are even.There are $$$n$$$ fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line.There are an infinite number of cows on the plane, one at every point with integer coordinates.Gregor is a member of the Illuminati, and wants to build a triangular fence, connecting $$$3$$$ distinct existing fence posts. A cow strictly inside the fence is said to be enclosed. If there are an odd number of enclosed cows and the area of the fence is an integer, the fence is said to be interesting.Find the number of interesting fences.

The first line contains the integer $$$n$$$ ($$$3 \le n \le 6000$$$), the number of fence posts which Gregor can choose to form the vertices of a fence. Each of the next $$$n$$$ line contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x,y \le 10^7$$$, $$$x$$$ and $$$y$$$ are even), where $$$(x,y)$$$ is the coordinate of a fence post. All fence posts lie at distinct coordinates. No three fence posts are on the same line.

Print a single integer, the number of interesting fences. Two fences are considered different if they are constructed with a different set of three fence posts.

NoteIn the first example, there is only $$$1$$$ fence. That fence is interesting since its area is $$$4$$$ and there is $$$1$$$ enclosed cow, marked in red.  In the second example, there are $$$3$$$ interesting fences.   $$$(0,0)$$$ — $$$(30,14)$$$ — $$$(2,10)$$$  $$$(2,16)$$$ — $$$(30,14)$$$ — $$$(2,10)$$$  $$$(30,14)$$$ — $$$(4,6)$$$ — $$$(2,10)$$$

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		alias Point = Tuple !(int, q{x}, int, q{y});
		auto p = new Point [n];
		foreach (ref c; p)
		{
			readf !(" %s %s") (c.x, c.y);
		}

		long [2] [2] k;
		foreach (ref c; p)
		{
			k[(c.x / 2) & 1][(c.y / 2) & 1] += 1;
		}

		long add (int u, int v, int a, int b, int f, int g)
		{
			if (tuple (u, v) != tuple (a, b) &&
			    tuple (u, v) != tuple (f, g) &&
			    tuple (a, b) != tuple (f, g))
			{
				return 0;
			}

			int [2] [2] used;
			long res = 1;

			res *= k[u][v] - used[u][v];
			used[u][v] += 1;
			res /= used[u][v];

			res *= k[a][b] - used[a][b];
			used[a][b] += 1;
			res /= used[a][b];

			res *= k[f][g] - used[f][g];
			used[f][g] += 1;
			res /= used[f][g];

			return res;
		}

		long total = 0;
		foreach (u; 0..2)
		{
			foreach (v; 0..2)
			{
				foreach (a; 0..2)
				{
					foreach (b; 0..2)
					{
						if (tuple (u, v) >
						    tuple (a, b))
						{
							continue;
						}
						foreach (f; 0..2)
						{
							foreach (g; 0..2)
							{
								if (tuple (a, b) >
								    tuple (f, g))
								{
									continue;
								}
								total += add
								    (u, v,
								    a, b,
								    f, g);
							}
						}
					}
				}
			}
		}

		writeln (total);
	}
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		alias Point = Tuple !(int, q{x}, int, q{y});
		auto p = new Point [n];
		foreach (ref c; p)
		{
			readf !(" %s %s") (c.x, c.y);
		}

		long [2] [2] k;
		foreach (ref c; p)
		{
			k[(c.x / 2) & 1][(c.y / 2) & 1] += 1;
		}

		long add (int u, int v, int a, int b, int f, int g)
		{
			if (tuple (u, v) != tuple (a, b) &&
			    tuple (u, v) != tuple (f, g) &&
			    tuple (a, b) != tuple (f, g))
			{
				return 0;
			}

			int [2] [2] used;
			long res = 1;

			res *= k[u][v] - used[u][v];
			used[u][v] += 1;
			res /= used[u][v];

			res *= k[a][b] - used[a][b];
			used[a][b] += 1;
			res /= used[a][b];

			res *= k[f][g] - used[f][g];
			used[f][g] += 1;
			res /= used[f][g];

			return res;
		}

		long total = 0;
		long total3 = 0;
		foreach (u; 0..2)
		{
			foreach (v; 0..2)
			{
				total3 += add (u, v, u, v, u, v);
				foreach (a; 0..2)
				{
					foreach (b; 0..2)
					{
						if (tuple (u, v) >
						    tuple (a, b))
						{
							continue;
						}
						foreach (f; 0..2)
						{
							foreach (g; 0..2)
							{
								if (tuple (a, b) >
								    tuple (f, g))
								{
									continue;
								}
								total += add
								    (u, v,
								    a, b,
								    f, g);
							}
						}
					}
				}
			}
		}

		writeln (total - total3 * 2);
	}
}


Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change.

The first line contains two space-separated integers n, s (1 ≤ n, s ≤ 100). The i-th of the next n lines contains two integers xi, yi (1 ≤ xi ≤ 100; 0 ≤ yi < 100), where xi represents the number of dollars and yi the number of cents needed in order to buy the i-th type of sugar.

Print a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.

NoteIn the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change.

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.functional;
import std.traits;
import std.string;
import std.container;

unittest{
  assert(solve(1) == [1], "Teste 1");
}

long[] solve(long a){
  debug(1) writefln("%s",a);
  return [1];
}

void main(){
  size_t n;
  long s;
  readf("%s %s\n",&n,&s);

  long max = -1;
  for(size_t i = 0; i < n; i++){
    long a,b;
    readf("%s %s\n ",&a,&b);
    if(s > a || (s == a && b == 0) ){
      if(b == 0 && max == -1){
        max = 0;
      }
      if(b != 0 && max < (100 - b)){
        max = 100 - b;
      }
    }
  }
  writeln(max);
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.functional;
import std.traits;
import std.string;
import std.container;

unittest{
  assert(solve(1) == [1], "Teste 1");
}

long[] solve(long a){
  debug(1) writefln("%s",a);
  return [1];
}

void main(){
  size_t n;
  long s;
  readf("%s %s\n",&n,&s);

  long max = -1;
  for(size_t i = 0; i < n; i++){
    long a,b;
    readf("%s %s\n ",&a,&b);
    if(s >= a){
      if(b == 0 && max == -1){
        max = 0;
      }
      if(b != 0 && max < (100 - b)){
        max = 100 - b;
      }
    }
  }
  writeln(max);
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.functional;
import std.traits;
import std.string;
import std.container;

unittest{
  assert(solve(1) == [1], "Teste 1");
}

long[] solve(long a){
  debug(1) writefln("%s",a);
  return [1];
}

void main(){
  size_t n;
  long s;
  readf("%s %s\n",&n,&s);

  long max = -1;
  for(size_t i = 0; i < n; i++){
    long a,b;
    readf("%s %s\n ",&a,&b);
    if(s >= a){
      if(b != 0 && max < (100 - b)){
        max = 100 - b;
      }
    }
  }
  writeln(max);
}


You are given a text consisting of $$$n$$$ space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. $$$w_i$$$ is the $$$i$$$-th word of text. All words consist only of lowercase Latin letters.Let's denote a segment of words $$$w[i..j]$$$ as a sequence of words $$$w_i, w_{i + 1}, \dots, w_j$$$. Two segments of words $$$w[i_1 .. j_1]$$$ and $$$w[i_2 .. j_2]$$$ are considered equal if $$$j_1 - i_1 = j_2 - i_2$$$, $$$j_1 \ge i_1$$$, $$$j_2 \ge i_2$$$, and for every $$$t \in [0, j_1 - i_1]$$$ $$$w_{i_1 + t} = w_{i_2 + t}$$$. For example, for the text "to be or not to be" the segments $$$w[1..2]$$$ and $$$w[5..6]$$$ are equal, they correspond to the words "to be".An abbreviation is a replacement of some segments of words with their first uppercase letters. In order to perform an abbreviation, you have to choose at least two non-intersecting equal segments of words, and replace each chosen segment with the string consisting of first letters of the words in the segment (written in uppercase). For example, for the text "a ab a a b ab a a b c" you can replace segments of words $$$w[2..4]$$$ and $$$w[6..8]$$$ with an abbreviation "AAA" and obtain the text "a AAA b AAA b c", or you can replace segments of words $$$w[2..5]$$$ and $$$w[6..9]$$$ with an abbreviation "AAAB" and obtain the text "a AAAB AAAB c".What is the minimum length of the text after at most one abbreviation?

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 300$$$) — the number of words in the text. The next line contains $$$n$$$ space-separated words of the text $$$w_1, w_2, \dots, w_n$$$. Each word consists only of lowercase Latin letters. It is guaranteed that the length of text does not exceed $$$10^5$$$.

Print one integer — the minimum length of the text after at most one abbreviation.

NoteIn the first example you can obtain the text "TB or not TB".In the second example you can obtain the text "a AAAB AAAB c".In the third example you can obtain the text "AB aa AB bb".

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

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

    auto s = readln.chomp.split.array;

    auto total = s.length - 1 + s.map!(x => x.length).sum;

    debug { total.writeln; }

    int mx = 1;
    int [string] vals;

    int[] nrs;
    foreach (e; s) {
        if (e !in vals) vals[e] = mx++;

        nrs ~= vals[e];
    }

    debug { nrs.writeln; }

    auto ans = total;
    foreach (st; 0 .. n) {
        auto gain = 0;
        foreach (end; st+1 .. n) {
            debug { nrs[st..end].writeln; }
            auto regs = 1;

            gain += s[end-1].length - 1 + cast(int)(end-1 != st);

            for (int p = end; p + end - st <= n; ++p) {
                if (nrs[st..end] == nrs[p..p+end-st]) {
                    debug { p.writeln; }
                    ++regs;
                    p += end-st - 1;
                }
            }

            if (regs > 1) ans = min(ans, total - gain * regs);
        }
    }

    ans.writeln;
}

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

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

    auto s = readln.chomp.split.array;

    auto total = s.map!(x => x.length).sum + s.length - 1;

    debug { total.writeln; }

    int mx = 1;
    int [string] vals;

    int[] nrs;
    foreach (e; s) {
        if (e !in vals) vals[e] = mx++;

        nrs ~= vals[e];
    }

    debug { nrs.writeln; }

    auto ans = total;
    foreach (st; 0 .. n) {
        auto gain = 0;
        auto len = 0;
        foreach (end; st+1 .. n) {
            debug { nrs[st..end].writeln; }
            auto regs = 1;

            len += 1;
            gain += s[end-1].length - 1 + cast(int)(end-1 != st);

            for (int p = end; p + len <= n; ++p) {
                if (nrs[st..end] == nrs[p..p+len]) {
                    debug { p.writeln; }
                    ++regs;
                    p += len - 1;
                }
            }

            if (regs > 1) ans = min(ans, total - gain * regs);
        }
    }

    ans.writeln;
}


Mihai plans to watch a movie. He only likes palindromic movies, so he wants to skip some (possibly zero) scenes to make the remaining parts of the movie palindromic.You are given a list $$$s$$$ of $$$n$$$ non-empty strings of length at most $$$3$$$, representing the scenes of Mihai's movie.A subsequence of $$$s$$$ is called awesome if it is non-empty and the concatenation of the strings in the subsequence, in order, is a palindrome.Can you help Mihai check if there is at least one awesome subsequence of $$$s$$$?A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.A sequence $$$a$$$ is a non-empty subsequence of a non-empty sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero, but not all) elements.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of scenes in the movie. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single non-empty string $$$s_i$$$ of length at most $$$3$$$, consisting of lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" if there is an awesome subsequence of $$$s$$$, or "NO" otherwise (case insensitive).

6

5

zx

ab

cc

zx

ba

2

ab

bad

4

co

def

orc

es

3

a

b

c

3

ab

cd

cba

2

ab

ab

NoteIn the first test case, an awesome subsequence of $$$s$$$ is $$$[ab, cc, ba]$$$

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

void solve(){
    auto n = scan!int;
    dchar[][] words;
    for(int i = 0; i < n; ++i){ words ~= scan!(dchar[]); }
    auto rbt = redBlackTree!(dchar[])(words);

    auto after = redBlackTree!(dchar[]);

    auto cback = new dchar[][n];

    bool f = 0;
    for(int i = 0; i < n; ++i){
        if(words[i].front == words[i].back){
            f = 1;
            break;
        }else if(words[i].length >= 2){
            dchar[] rev;
            rev ~= words[i];
            rev.reverse;
            if(rev in rbt || words[i] in after){
                f = 1;
                break;
            }

            if(rev.length == 3){
                after.insert(rev[1..$]);
                cback[i] ~= rev[0..2];
                show("af: ", rev[1..$], "bef: ", rev[0..2]);
            }
        }
    }
    auto before = redBlackTree!(dchar[]);
    for(int i = n-1; i >= 0; --i){
        if(cback[i].length){
            before.insert(cback[i]);
        }else if(words[i] in before){
            f = 1;
            break;
        }
    }
    writeln( (f) ? "YES" : "NO");
}

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

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

import std;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void solve() {
    int N = read!int;
    auto X = new string[N];
    foreach (i; 0 .. N) X[i] = readln.chomp;

    bool f() {
        bool[string] s;
        foreach (i; 0 .. N) {
            auto x = X[i];
            auto r = reverse(x.dup);
            if (x == r) return true;
            if (r in s) return true;
            if (x.length == 2) {
                for (char c = 'a'; c <= 'z'; c++) {
                    auto x1 = [c] ~ x;
                    auto r1 = reverse(x1.dup);
                    if (r1 in s) return true;
                }
            } else if (x.length == 3) {
                auto x1 = x[1 .. $];
                auto r1 = reverse(x1.dup);
                if (r1 in s) return true;
            }
            s[x] = true;
        }
        return false;
    }
    writeln(f() ? "YES" : "NO");
}

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

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

bool solve (string [] s, int n)
{
	if (s.any !(c => c.front == c.back))
	{
		return true;
	}
	auto t = s.map !(c => c.retro.text).array;
	int [string] first2;
	int [string] last2;
	int [string] first3;
	int [string] last3;
	foreach_reverse (i; 0..n)
	{
		first2[s[i][0..2]] = i;
		first3[s[i]] = i;
	}
	foreach (i; 0..n)
	{
		last2[t[i][0..2]] = i;
		last3[t[i]] = i;
	}
	foreach (c, posC; first3)
	{
		if (c in last3 && posC < last3[c])
		{
			return true;
		}
		if (c.length == 2 && c in last2 && posC < last2[c])
		{
			return true;
		}
	}
	foreach (d, posD; last3)
	{
		if (d in first3 && first3[d] < posD)
		{
			return true;
		}
		if (d.length == 2 && d in first2 && first2[d] < posD)
		{
			return true;
		}
	}
	return false;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = new string [n];
		foreach (ref c; s)
		{
			c = readln.strip;
		}
		writeln (solve (s, n) ? "YES" : "NO");
	}
}

import std;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void solve() {
    int N = read!int;
    auto X = new string[N];
    foreach (i; 0 .. N) X[i] = readln.chomp;

    bool f() {
        bool[string] s;
        foreach (i; 0 .. N) {
            auto x = X[i];
            if (x.length == 1) return true;
            auto r = reverse(x.dup);
            if (x == r) return true;
            if (r in s) return true;
            if (x.length == 2) {
                for (char c = 'a'; c <= 'z'; c++) {
                    auto r1 = [c] ~ r;
                    if (r1 in s) return true;
                }
            } else if (x.length == 3) {
                auto x1 = x[1 .. $];
                auto r1 = reverse(x1.dup);
                if (r1 in s) return true;
            }
            s[x] = true;
        }
        return false;
    }
    writeln(f() ? "YES" : "NO");
}

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

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

bool solve (string [] s, int n)
{
	if (s.any !(c => c.front == c.back))
	{
		return true;
	}
	auto t = s.map !(c => c.retro.text).array;
	int [string] first;
	int [string] last;
	foreach_reverse (i; 0..n)
	{
		first[s[i][0..2]] = i;
	}
	foreach (i; 0..n)
	{
		last[t[i][0..2]] = i;
	}
	foreach (c, posC; first)
	{
		if (c in last && posC < last[c])
		{
			return true;
		}
	}
	return false;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = new string [n];
		foreach (ref c; s)
		{
			c = readln.strip;
		}
		writeln (solve (s, n) ? "YES" : "NO");
	}
}


First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word — some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction —  it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: , where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.

The only line contains a string s (5 ≤ |s| ≤ 104) consisting of lowercase English letters.

On the first line print integer k — a number of distinct possible suffixes. On the next k lines print suffixes.  Print suffixes in lexicographical (alphabetical) order.

NoteThe first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.

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

void main() {
    auto S = readln.chomp;
    auto N = S.length.to!int;

    auto used = new bool[][](N+1, 4);
    bool[string] ans;

    void dfs(int r, int plen) { // [0..r)
        if (used[r][plen]) return;
        used[r][plen] = true;

        foreach (i; 2..4) {
            if (r - i > 4 && (i != plen || S[r-i..r] != S[r..r+plen])) {
                ans[S[r-i..r]] = true;
                dfs(r-i, i);
            }
        }
    }

    dfs(N, 0);
    auto anss = ans.keys.dup;
    anss.sort();

    ans.keys.length.writeln;
    foreach (a; anss) a.writeln;
}

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

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		string [] ans;
		auto n = s.length;
		auto f = new bool [2] [n + 1];
		f[n][0] = true;
		f[n][1] = true;
		for (int p = n; p >= 5; p--)
		{
			if (p + 2 <= n && (f[p + 2][1] ||
			    f[p + 2][0] && (p + 2 + 2 > n ||
			    s[p + 2..p + 2 + 2] != s[p..p + 2])))
			{
				f[p][0] = true;
				ans ~= s[p..p + 2];
			}
			if (p + 3 <= n && (f[p + 3][0] ||
			    f[p + 3][1] && (p + 3 + 3 > n ||
			    s[p + 3..p + 3 + 3] != s[p..p + 3])))
			{
				f[p][1] = true;
				ans ~= s[p..p + 3];
			}
		}

		sort (ans);
		ans = ans.uniq.array;
		writeln (ans.length);
		foreach (t; ans)
		{
			writeln (t);
		}
	}
}

import std.algorithm, std.array, std.stdio, std.string;
void main () {
	auto s = readln.strip;
	bool [string] ans;
	auto n = s.length;
	auto f = new bool [2] [n + 1];
	f[n] = [true, true];
	foreach_reverse (p; 0..n + 1)
		foreach (k; 0..2) {
			int m = k + 2;
			if (p - m >= 5 && (f[p][!k] || f[p][k] && (p + m > n || s[p..p + m] != s[p - m..p]))) {
				f[p - m][k] = true;
				ans[s[p - m..p]] = true;
			}
		}
	writefln ("%s%-(\n%s%)", ans.length, ans.byKey.array.sort);
}


Polycarp wrote on the board a string $$$s$$$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.After that, he erased some letters from the string $$$s$$$, and he rewrote the remaining letters in any order. As a result, he got some new string $$$t$$$. You have to find it with some additional information.Suppose that the string $$$t$$$ has length $$$m$$$ and the characters are numbered from left to right from $$$1$$$ to $$$m$$$. You are given a sequence of $$$m$$$ integers: $$$b_1, b_2, \ldots, b_m$$$, where $$$b_i$$$ is the sum of the distances $$$|i-j|$$$ from the index $$$i$$$ to all such indices $$$j$$$ that $$$t_j > t_i$$$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $$$b_i$$$, Polycarp finds all such indices $$$j$$$ that the index $$$j$$$ contains a letter that is later in the alphabet than $$$t_i$$$ and sums all the values $$$|i-j|$$$.For example, if $$$t$$$ = "abzb", then:  since $$$t_1$$$='a', all other indices contain letters which are later in the alphabet, that is: $$$b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$$$;  since $$$t_2$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_2=|2-3|=1$$$;  since $$$t_3$$$='z', then there are no indexes $$$j$$$ such that $$$t_j>t_i$$$, thus $$$b_3=0$$$;  since $$$t_4$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_4=|4-3|=1$$$. Thus, if $$$t$$$ = "abzb", then $$$b=[6,1,0,1]$$$.Given the string $$$s$$$ and the array $$$b$$$, find any possible string $$$t$$$ for which the following two requirements are fulfilled simultaneously:  $$$t$$$ is obtained from $$$s$$$ by erasing some letters (possibly zero) and then writing the rest in any order;  the array, constructed from the string $$$t$$$ according to the rules above, equals to the array $$$b$$$ specified in the input data.

The first line contains an integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. Each test case consists of three lines:   the first line contains string $$$s$$$, which has a length from $$$1$$$ to $$$50$$$ and consists of lowercase English letters;  the second line contains positive integer $$$m$$$ ($$$1 \le m \le |s|$$$), where $$$|s|$$$ is the length of the string $$$s$$$, and $$$m$$$ is the length of the array $$$b$$$;  the third line contains the integers $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_i \le 1225$$$).  It is guaranteed that in each test case an answer exists.

Output $$$q$$$ lines: the $$$k$$$-th of them should contain the answer (string $$$t$$$) to the $$$k$$$-th test case. It is guaranteed that an answer to each test case exists. If there are several answers, output any.

NoteIn the first test case, such strings $$$t$$$ are suitable: "aac', "aab".In the second test case, such trings $$$t$$$ are suitable: "a", "b", "c".In the third test case, only the string $$$t$$$ equals to "aba" is suitable, but the character 'b' can be from the second or third position.

import std.stdio;
import std.string : split, strip;
import std.algorithm : map, group, sort, filter;
import std.conv : to;
import std.utf : toUTF32;
import std.array : array;
import std.range : enumerate, walkLength;
import std.math : abs;

void main()
{
  int q;
  readf!"%d\n"(q);

  foreach (i; 0..q) {
    int m;
    dchar[] s = readln.strip.toUTF32.dup;
    readf!"%d\n"(m);
    auto t = readln.strip.split.map!(to!int).array;
    auto r = new dchar[m]; // result
    auto f = 0; // filled chars

    // letters available in s
    s.sort!"a > b";
    auto g = s.group;

    // fill zeros in t with largest available letter
    while (f < m) {
      // indices of zeros
      auto c = t.enumerate.filter!"a.value == 0".array;
      while (g.front[1] < c.length) {
        g.popFront;
      }

      foreach (e; c) {
        // fill zeros from largest valid letter
        r[e.index] = g.front[0];

        // update distance for all other letters
        foreach (j; 0..m) {
          if (t[j] > 0) {
            t[j] -= abs(cast(int) j - cast(int) e.index);
          }
        }

        t[e.index] = -1;
      }

      f += c.length;
      g.popFront; // letter is now invalid
    }

    writeln(r);
  }
}

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

immutable int letters = 26;

void main ()
{
	foreach (test; 0..readln.strip.to !(int))
	{
		auto s = readln.strip;
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		int [letters] num;
		foreach (ref c; s)
		{
			num[c - 'a'] += 1;
		}

		auto answer = new char [n];
		char now = 'z';
		int res = 0;
		while (res < n)
		{
			auto zeroes = a.count (0);
			while (num[now - 'a'] < zeroes)
			{
				now = cast (char) (now - 1);
			}

			foreach (i; 0..n)
			{
				if (a[i] == 0)
				{
					answer[i] = now;
				}
			}
			res += zeroes;

			foreach (i; 0..n)
			{
				if (answer[i] == now)
				{
					foreach (j; 0..n)
					{
						a[j] -= abs (i - j);
					}
				}
			}

			foreach (i; 0..n)
			{
				if (answer[i] == now)
				{
					a[i] = -1;
				}
			}

			now = cast (char) (now - 1);
		}
		writeln (answer);
	}
}


A correct expression of the form a+b=c was written; a, b and c are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so that:   character'+' is placed on the left of character '=',  characters '+' and '=' split the sequence into three non-empty subsequences consisting of digits (let's call the left part a, the middle part — b and the right part — c),  all the three parts a, b and c do not contain leading zeros,  it is true that a+b=c. It is guaranteed that in given tests answer always exists.

The first line contains a non-empty string consisting of digits. The length of the string does not exceed 106.

Output the restored expression. If there are several solutions, you can print any of them. Note that the answer at first should contain two terms (divided with symbol '+'), and then the result of their addition, before which symbol'=' should be.  Do not separate numbers and operation signs with spaces. Strictly follow the output format given in the examples. If you remove symbol '+' and symbol '=' from answer string you should get a string, same as string from the input data.

import core.bitop, std.algorithm, std.bigint, std.bitmanip, std.complex,
	std.container, std.conv, std.datetime, std.functional, std.math, std.meta;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.parallelism, std.random, std.range, std.regex, std.stdio, std.string,
	std.traits, std.typecons, std.uni, std.variant;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
/// struct vector as c++ vector
struct Vec(T)
{
	private Array!T buf;
	alias buf this;
	this(this)
	{
		buf = buf.dup;
	}
	/// construct from length
	this(U)(U length)
			if (is(U == int) || is(U == size_t) || is(U == long) || is(U == ulong) || is(U == uint))
	{
		buf.length = length;
	}
	/// construct from length and default value
	this(U, X)(U length, X val)
			if (isImplicitlyConvertible!(X, T) || (is(U == int)
				|| is(U == size_t) || is(U == long) || is(U == ulong) || is(U == uint)))
	{
		buf.length = length;
		foreach (ref x; buf[])
		{
			x = val;
		}
	}
	/// construct from other array
	this(U)(U[] values...) if (isImplicitlyConvertible!(U, T))
	{
		buf = Array!(T)(values);
	}
	/// construct from other range
	this(Range)(Range r)
			if (isInputRange!Range && isImplicitlyConvertible!(ElementType!Range,
				T) && !is(Range == T[]))
	{
		buf = Array!(T)(r);
	}
	/// integer length
	int size() @property const
	{
		return cast(int) buf.length;
	}
}
///mmulo
enum mm = 10 ^^ 9 + 7, mm2 = mm + 2;
public
{
	pure nothrow
	{
		///lcm
		T lcm(T)(auto ref T a, auto ref T b)
		{
			return a / gcd(a, b) * b;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///BigInt greatest common divizor
		BigInt biggcd(BigInt a, BigInt b)
		{
			BigInt res = 1;
			while (b)
			{
				if ((a & 1) && (b & 1))
				{
					a -= b;
					a >>= 1;
				}
				else if (a & 1)
				{
					b >>= 1;
				}
				else if (b & 1)
				{
					a >>= 1;
				}
				else
				{
					res <<= 1;
					a >>= 1;
					b >>= 1;
				}
				if (a < b)
					swap(a, b);
			}
			return res * a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	///write an array
	void putarr(X)(in X a, in char ch = ' ') if (isInputRange!X)
	{
		writefln("%(%s" ~ ch ~ "%)", a);
	}
	///write a matrix
	void putarr(X)(in X a)
			if (isInputRange!X && isInputRange!(ElementType!X) && !isSomeString!(ElementType!X))
	{
		writefln("%(%(%s %)\n%)", a);
	}
	///get an array
	bool getarr(X)(X a, in size_t n)
	{
		bool b = 1;
		foreach (ref i; a[0 .. n])
			b = input(&i);
		return b;
	}
	///read without format
	bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
	{
		return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
	}
	///readln without format
	bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
	{
		return readf!(replicate(" %s", ptrs.length) ~ '\n')(ptrs) == ptrs.length;
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	auto s = readln.strip;

	// long p1 = 997;
	// long p2 = 123_456;
	auto h1 = new long[s.length + 2], h2 = new long[s.length + 2];
	//  h2 = long[s.length];
	auto pw1 = new long[s.length + 2], pw2 = new long[s.length + 2];
	h2[0] = h1[0] = s[0] - '0';
	pw2[0] = pw1[0] = 1;
	foreach (i; 1 .. s.length)
	{
		h1[i] = (h1[i - 1] * 10 + s[i] - '0') % mm;
		h2[i] = (h2[i - 1] * 10 + s[i] - '0') % mm2;
		pw1[i] = (pw1[i - 1] * 10) % mm;
		pw2[i] = (pw2[i - 1] * 10) % mm2;
	}

	long get1(int l, int r)
	{
		long ans = h1[r];
		if (l > 0)
			ans = (ans + mm - (h1[l - 1] * pw1[r - l + 1]) % mm) % mm;
		return ans;
	}

	long get2(int l, int r)
	{
		long ans = h2[r];
		if (l > 0)
			ans = (ans + mm2 - (h2[l - 1] * pw2[r - l + 1]) % mm2) % mm2;
		return ans;
	}

	int n = cast(int) s.length;
	/*foreach_reverse (int i; 1 .. n / 2 + 1)
	{
		int len = (n - i);
		foreach (j; len - 3 .. len + 4)
		{
			// debug enter(j);
			if (j <= 0 || j > n - 1 || j > n - j - 1)
				continue;
			if ((j > 1 && s[0] == '0') || (j < n - j && s[j] == '0') || (j > 1
					&& s[n - j] == '0') || j == 0)
			{
				continue;
			}
			if ((get(0, j - 1) + get(j, n - j - 1)) % mm == get(n - j, n - 1))
			{
				auto a = s[0 .. j].BigInt;
				auto b = s[j .. n - j].BigInt;
				auto c = s[n - j .. n].BigInt;
				if (a + b == c)
				{
					writeln(s[0 .. j], '+', s[j .. n - j], '=', s[n - j .. n]);
					return;
				}
			}

		}

	}
	foreach_reverse (int i; 1 .. n / 2 + 1)
	{
		int len = (n - 2 * i);
		foreach (j; len - 3 .. len + 4)
		{
			// debug enter(j);
			if (j <= 0 || j > n - 1 || j > n - j - 1)
				continue;
			if ((j > 1 && s[0] == '0') || (j < n - j && s[j] == '0') || (j > 1
					&& s[n - j] == '0') || j == 0)
			{
				continue;
			}
			if ((get(0, j - 1) + get(j, n - j - 1)) % mm == get(n - j, n - 1))
			{
				auto a = s[0 .. j].BigInt;
				auto b = s[j .. n - j].BigInt;
				auto c = s[n - j .. n].BigInt;
				if (a + b == c)
				{
					writeln(s[0 .. j], '+', s[j .. n - j], '=', s[n - j .. n]);
					return;
				}
			}

		}

	}*/
	foreach (j; 1 .. n)
	{
		int d = n - j;
		if (d > j)
			continue;
		foreach (i; d - 2 .. d + 2)
		{
			debug enter(i, ' ', j);
			if (i <= 0 || i > j)
				continue;
			if (i > 1 && s[0] == '0')
				continue;
			if (i + 1 < j && s[i] == '0')
				continue;
			if (j < n - 1 && s[j] == '0')
				continue;
			if ((get1(0, i - 1) + get1(i, j - 1)) % mm == get1(j, n - 1)
					&& (get2(0, i - 1) + get2(i, j - 1)) % mm2 == get2(j, n - 1))
			{
				if (max(s[0 .. i].length, s[i .. j].length) > s[j .. n].length
						|| s[j .. n].length > 1 + max(s[0 .. i].length, s[i .. j].length))
					continue;
				// auto a = s[0 .. i].BigInt;
				// auto b = s[i .. j].BigInt;
				// auto c = s[j .. n].BigInt;
				// if (a + b == c)
				// {
				// 	writeln(s[0 .. i], '+', s[i .. j], '=', s[j .. n]);
				// 	return;
				// }
				auto a = s[0 .. i].map!(x => to!int(x - '0')).array;
				auto b = s[i .. j].map!(x => to!int(x - '0')).array;
				auto c = s[j .. n].map!(x => to!int(x - '0')).array;
				reverse(a);
				reverse(b);
				reverse(c);
				if (a.length < b.length)
					swap(a, b);
				a.length = c.length;
				int cur;
				foreach (f; 0 .. a.length)
				{
					if (f < b.length)
					{
						auto val = a[f] + b[f] + cur;
						a[f] = val % 10;
						cur = val / 10;
					}
					else
					{
						auto val = a[f] + cur;
						a[f] = val % 10;
						cur = val / 10;
					}
				}
				if (a[] == c[])
				{
					writeln(s[0 .. i], '+', s[i .. j], '=', s[j .. n]);
					return;
				}
			}
		}
		foreach (i; j - d - 2 .. j - d + 2)
		{
			debug enter(i, ' ', j);
			if (i <= 0 || i > j)
				continue;
			if (i > 1 && s[0] == '0')
				continue;
			if (i + 1 < j && s[i] == '0')
				continue;
			if (j < n - 1 && s[j] == '0')
				continue;

			if ((get1(0, i - 1) + get1(i, j - 1)) % mm == get1(j, n - 1)
					&& (get2(0, i - 1) + get2(i, j - 1)) % mm2 == get2(j, n - 1))
			{
				if (max(s[0 .. i].length, s[i .. j].length) > s[j .. n].length
						|| s[j .. n].length > 1 + max(s[0 .. i].length, s[i .. j].length))
					continue;
				// auto a = s[0 .. i].BigInt;
				// auto b = s[i .. j].BigInt;
				// auto c = s[j .. n].BigInt;
				// if (a + b == c)
				// {
				// 	writeln(s[0 .. i], '+', s[i .. j], '=', s[j .. n]);
				// 	return;
				// }
				auto a = s[0 .. i].map!(x => to!int(x - '0')).array;
				auto b = s[i .. j].map!(x => to!int(x - '0')).array;
				auto c = s[j .. n].map!(x => to!int(x - '0')).array;
				reverse(a);
				reverse(b);
				reverse(c);
				if (a.length < b.length)
					swap(a, b);
				a.length = c.length;
				int cur;
				foreach (f; 0 .. a.length)
				{
					if (f < b.length)
					{
						auto val = a[f] + b[f] + cur;
						a[f] = val % 10;
						cur = val / 10;
					}
					else
					{
						auto val = a[f] + cur;
						a[f] = val % 10;
						cur = val / 10;
					}
				}
				if (a[] == c[])
				{
					writeln(s[0 .. i], '+', s[i .. j], '=', s[j .. n]);
					return;
				}
			}
		}
	}
}


Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now she is solving the following problem. You are given four positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, such that $$$a \leq b \leq c \leq d$$$. Your task is to find three integers $$$x$$$, $$$y$$$, $$$z$$$, satisfying the following conditions: $$$a \leq x \leq b$$$. $$$b \leq y \leq c$$$. $$$c \leq z \leq d$$$. There exists a triangle with a positive non-zero area and the lengths of its three sides are $$$x$$$, $$$y$$$, and $$$z$$$.Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given as four space-separated integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$1 \leq a \leq b \leq c \leq d \leq 10^9$$$).

For each test case, print three integers $$$x$$$, $$$y$$$, $$$z$$$  — the integers you found satisfying the conditions given in the statement. It is guaranteed that the answer always exists. If there are multiple answers, print any.

NoteOne of the possible solutions to the first test case:One of the possible solutions to the second test case:

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto n = readln.split.to!(int[]);
        writeln(n[1], " ", n[2], " ", n[2]);
    }
}

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    auto a = r.nextA!uint (4);
    writeln (a[1], ' ', a[2], ' ', a[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 long[][](t);
	foreach (ti; 0..t)
	{
		auto abcd = RDA;
		ans[ti] = [abcd[1], abcd[2], abcd[2]];
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1], " ", e[2]);
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 long[][](t);
	foreach (ti; 0..t)
	{
		auto abcd = RDA;
		ans[ti] = [abcd[2], abcd[2], abcd[1]];
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1], " ", e[2]);
	stdout.flush;
	debug readln;
}


A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.

The first line of the input data contains numbers n and m (1 ≤ n, m ≤ 50), n — amount of lines, and m — amount of columns on Bob's sheet. The following n lines contain m characters each. Character «.» stands for a non-shaded square on the sheet, and «*» — for a shaded square. It is guaranteed that Bob has shaded at least one square.

Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better.

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

void main()
{
    auto nm = readln.split.map!(to!int);
    auto n = nm[0], m = nm[1];
    auto lines  = n.iota.map!(_ => readln.chomp).array;
    lines = lines.strip!(a => a == repeat(".").take(lines[0].length).array.join(""));
    auto lines1 = lines[0].length.iota.array.map!(i => lines.transversal(i).array);
    auto lines2 = lines1.strip!(a => a == repeat(".").take(lines1[0].length).array.join(""));
    lines2[0].length.iota.array.map!(i => lines2.transversal(i).array).each!writeln;
}

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

class Line
{
    public const ptrdiff_t firstStar;
    public const ptrdiff_t lastStar;
    public const string line;

    this(in string line)
    {
        this.firstStar = std.string.indexOf(line, '*');
        this.lastStar = std.string.lastIndexOf(line, '*');
        this.line = line;
    }

    invariant()
    {
        assert(firstStar <= lastStar, format("Last star cannot be before the first one: %s, %s", firstStar, lastStar));
        assert(firstStar >= 0 || (firstStar == -1 && lastStar == -1), "Both indexes must be -1 or >= 0");
    }
}

void testDotsCount(in string line, in ptrdiff_t firstStar, in ptrdiff_t lastStar)
{
    Line l;
    l = new Line(line);
    assert(l.firstStar == firstStar, format("Bad first star index: expected %s, got %s", firstStar, l.firstStar));
    assert(l.lastStar == lastStar, format("Bad last star index: expected %s, got %s", lastStar, l.lastStar));
}

unittest
{
    testDotsCount("..*...", 2, 2);
}

unittest
{
    testDotsCount("*...", 0, 0);
}

unittest
{
    testDotsCount("*", 0, 0);
}

unittest
{
    testDotsCount("***", 0, 2);
}

unittest
{
    testDotsCount("..***...*.*..", 2, 10);
}

void main()
{
    string firstLine = stdin.readln();
    int rows;
    int cols;
    formattedRead(firstLine, "%s %s", &rows, &cols);

    ptrdiff_t minFirstStar = -1;
    ptrdiff_t maxLastStar = -1;

    Line[50] lines;

    int firstLineWithStar = rows;
    int lastLineWithStar = 0;

    for (int i = 0; i < rows; i++) {
        Line l = new Line(stdin.readln());
        lines[i] = l;
        maxLastStar = max(maxLastStar, l.lastStar);
        if (l.firstStar != -1) {
            lastLineWithStar = i;
            firstLineWithStar = min(firstLineWithStar, i);
            if (minFirstStar == -1) {
                minFirstStar = l.firstStar;
            } else {
                minFirstStar = min(minFirstStar, l.firstStar);
            }
        }
    }
    for (int i = firstLineWithStar; i <= lastLineWithStar; i++)
    {
        stdout.writeln(lines[i].line[minFirstStar .. maxLastStar + 1]);
    }
}


Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $$$a$$$ coins, Barbara has $$$b$$$ coins and Cerene has $$$c$$$ coins. Recently Polycarp has returned from the trip around the world and brought $$$n$$$ coins.He wants to distribute all these $$$n$$$ coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives $$$A$$$ coins to Alice, $$$B$$$ coins to Barbara and $$$C$$$ coins to Cerene ($$$A+B+C=n$$$), then $$$a + A = b + B = c + C$$$.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all $$$n$$$ coins between sisters in a way described above.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a new line and consists of four space-separated integers $$$a, b, c$$$ and $$$n$$$ ($$$1 \le a, b, c, n \le 10^8$$$) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.

For each test case, print "YES" if Polycarp can distribute all $$$n$$$ coins between his sisters and "NO" otherwise.

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int a, b, c, n;
		readf !(" %s %s %s %s") (a, b, c, n);
		auto s = a + b + c + n;
		bool ok = (s % 3 == 0);
		s /= 3;
		ok &= (s >= a) && (s >= b) && (s >= c);
		writeln (ok ? "YES" : "NO");
	}
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
import std.algorithm.mutation;
import std.container.array;

string[] tokens;

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

int readInt()
{
    return readToken.to!int;
}

bool solve()
{
    int a = readInt;
    int b = readInt;
    int c = readInt;
    int n = readInt;
    int sum = a + b + c + n;
    if (sum % 3)
    {
        return false;
    }
    sum /= 3;
    return a <= sum && b <= sum && c <= sum;
}

void main()
{
    int T = readInt;
    while (T--)
    {
        writeln(solve ? "YES" : "NO");
    }
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

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

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

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

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

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

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

    }
}

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

void main()
{
  int t;
  read(t);
 testCase:foreach(tc; 0 .. t)
    {
      long[3] a;
      read(a);
      long n = next!long;
      sort(a[]);
      if (a[2] - a[1] + a[2] - a[0] <= n)
        {
          n -= 2 * a[2] - a[1] - a[0];
          if (n % 3 == 0)
            {
              writeln("YES");
              continue testCase;
            }
        }
      writeln("NO");
    }
}

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		int b=0;
		int c=0;
		int d=0;
		readf(" %d", &a);
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		if ((a+b+c+d)%3==0)
		{
			int r=(a+b+c+d)/3;
			if (r-a>=0 && r-b>=0 && r-c>=0)
			{
				writeln("YES");
			}
			else
			{
				writeln("NO");
			}
		}
		else
		{
			writeln("NO");
		}
	}
	return 0;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto c = RD;
		auto n = RD;
		if ((a+b+c+n) % 3 != 0)
			continue;

		auto m = max(a, b, c);
		auto d = m * 3 - a - b - c;
		ans[ti] = d <= n;
	}

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


You have integer $$$n$$$. Calculate how many ways are there to fully cover belt-like area of $$$4n-2$$$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $$$2$$$ coverings are different if some $$$2$$$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.Please look at pictures below for better understanding.  On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. These are the figures of the area you want to fill for $$$n = 1, 2, 3, 4$$$. You have to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).

For each test case, print the number of ways to fully cover belt-like area of $$$4n-2$$$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $$$10^{18}$$$.

NoteIn the first test case, there are the following $$$2$$$ ways to fill the area:  In the second test case, there is a unique way to fill the area:

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

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

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    auto n = r.next!uint;
    writeln (n);
  }
}

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 long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		ans[ti] = n;
	}

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

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!long;
        if (N == 1) {
            writeln(1);
        } else {
            writeln(2);
        }
    }
}

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    auto n = r.next!uint;
    writeln (n > 1 ? 2 : 1);
  }
}


You are given an array $$$a$$$ of length $$$n$$$, and an integer $$$x$$$. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was $$$[3, 6, 9]$$$, in a single operation one can replace the last two elements by their sum, yielding an array $$$[3, 15]$$$, or replace the first two elements to get an array $$$[9, 9]$$$. Note that the size of the array decreases after each operation.The beauty of an array $$$b=[b_1, \ldots, b_k]$$$ is defined as $$$\sum_{i=1}^k \left\lceil \frac{b_i}{x} \right\rceil$$$, which means that we divide each element by $$$x$$$, round it up to the nearest integer, and sum up the resulting values. For example, if $$$x = 3$$$, and the array is $$$[4, 11, 6]$$$, the beauty of the array is equal to $$$\left\lceil \frac{4}{3} \right\rceil + \left\lceil \frac{11}{3} \right\rceil + \left\lceil \frac{6}{3} \right\rceil = 2 + 4 + 2 = 8$$$.Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.

The first input line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 1000$$$). The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq x \leq 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$), the elements of the array $$$a$$$.  It is guaranteed that the sum of values of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output two integers — the minimal and the maximal possible beauty.

NoteIn the first test case the beauty of the array does not change if we perform any operations.In the second example we can leave the array unchanged to attain the maximum beauty, and to get the minimum beauty one can replace two elements $$$4$$$ and $$$11$$$ with their sum, yielding an array $$$[6, 15]$$$, which has its beauty equal to $$$7$$$.

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        int N; long X; get(N, X);
        long[] AA; get(AA);
        long s, b;
        foreach (a; AA) {
            s += a;
            b += (a + X - 1) / X;
        }
        writeln((s + X - 1) / X, " ", b);
    }
}

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

void theCode(){
    int n;
    n = scan!int;
    ll x = scan;
    auto arr = scanArray;
    ll maxx = 0, rem = 0;
    foreach(a; arr){
        maxx += (a/x) + (a % x != 0);
        ll r = a % x;
        if(r == 0) r = x;
        rem += x - r;
    }
    writeln(maxx - rem/x, " ", maxx);
}

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

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto tot = a.sum;
		ans[ti][0] = (tot+x-1) / x;
		foreach (i; 0..n)
		{
			ans[ti][1] += (a[i]+x-1) / x;
		}
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1]);
	stdout.flush;
	debug readln;
}


Little W and Little P decided to send letters to each other regarding the most important events during a day. There are $$$n$$$ events during a day: at time moment $$$t_i$$$ something happens to the person $$$p_i$$$ ($$$p_i$$$ is either W or P, denoting Little W and Little P, respectively), so he needs to immediately send a letter to the other person. They can send a letter using one of the two ways:  Ask Friendly O to deliver the letter directly. Friendly O takes $$$d$$$ acorns for each letter. Leave the letter at Wise R's den. Wise R values free space, so he takes $$$c \cdot T$$$ acorns for storing a letter for a time segment of length $$$T$$$. The recipient can take a letter from Wise R either when he leaves his own letter at Wise R's den, or at time moment $$$t_{n + 1}$$$, when everybody comes to Wise R for a tea. It is not possible to take a letter from Wise R's den at other time moments. The friends can store as many letters at Wise R's den as they want, paying for each one separately. Help the friends determine the minimum possible total cost of sending all letters.

The first line contains three integers $$$n, c, d$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq c \leq 10^2$$$, $$$1 \leq d \leq 10^8$$$) — the number of letters, the cost of storing a letter for one time unit at Wise R's den and the cost of delivering a letter via Friendly O. The next $$$n$$$ describe the events. The $$$i$$$-th of them contains an integer $$$t_i$$$ and a character $$$p_i$$$ ($$$0 \leq t_i \leq 10^6$$$, $$$p_i$$$ is either W or P) — the time the $$$i$$$-th event happens and the person the event happens to. The last line contains a single integer $$$t_{n + 1}$$$ ($$$0 \leq t_{n+1} \leq 10^6$$$) — the time when everybody comes to Wise R for a tea and takes all remaining letters.  It is guaranteed that $$$t_i < t_{i + 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n$$$.

Print a single integer — the minimum possible cost of delivery of all letters.

NoteOne of optimal solutions in the first example: At time moment 0 Little P leaves the letter at Wise R's den. At time moment 1 Little W leaves his letter at Wise R's den and takes Little P's letter. This letter is at the den from time moment 0 to time moment 1, it costs $$$1$$$ acorn. At time moment 3 Little P sends his letter via Friendly O, it costs $$$4$$$ acorns. At time moment 5 Little P leaves his letter at the den, receiving Little W's letter which storage costs 4 acorns. At time moment 8 Little P leaves one more letter at the den. At time moment 10 Little W comes to the den for a tea and receives the two letters, paying 5 and 2 acorns.The total cost of delivery is thus $$$1 + 4 + 4 + 5 + 2 = 16$$$ acorns.

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

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

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

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

enum INF = 10L^^18;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const C = readLong();
      const D = readLong();
      auto T = new long[N + 1];
      auto P = new string[N];
      foreach (i; 0 .. N) {
        T[i] = readLong();
        P[i] = readToken();
      }
      T[N] = readLong();

      auto TSum = new long[N + 2];
      foreach (i; 0 .. N + 1) {
        TSum[i + 1] = TSum[i] + T[i];
      }

      long[] crt = [0];
      for (int i = 0, j; i < N; i = j) {
        for (j = i; j < N && P[i] == P[j]; ++j) {}
        long mn = INF;
        foreach (x; 0 .. cast(int)(crt.length)) {
          chmin(mn, crt[x] + C * T[i] * x);
        }
        auto nxt = new long[j - i + 1];
        foreach (y; 1 .. j - i + 1) {
          nxt[y] = mn - C * (T[i] + (TSum[j] - TSum[j - y + 1])) - D * y;
        }
        // from 0
        foreach (y; 1 .. j - i + 1) {
          chmin(nxt[y], 0 - C * (TSum[j] - TSum[j - y]) - D * y);
        }
        debug {
          writeln(i, " ", j, ": ", nxt);
        }
        crt = nxt;
      }
      long ans = INF;
      foreach (x; 0 .. cast(int)(crt.length)) {
        chmin(ans, crt[x] + C * T[N] * x);
      }
      ans += D * N;
      writeln(ans);

      debug {
        long brt = INF;
        foreach (p; 0 .. 1 << N) {
          long cost;
          string denP;
          long denCnt;
          foreach (i; 0 .. N) {
            if (p & 1 << i) {
              if (denP != P[i]) {
                cost += C * T[i] * denCnt;
                denP = P[i];
                denCnt = 0;
              }
              cost -= C * T[i];
              ++denCnt;
            } else {
              cost += D;
            }
          }
          cost += C * T[N] * denCnt;
          chmin(brt, cost);
          debug {
            if (cost == 916) {
              foreach (i; 0 .. N) {
                write(cast(char)(P[i][0] + ((p & 1 << i) ? 0 : 32)));
              }
              writeln();
            }
          }
        }
        writeln("brt = ", brt);
        assert(brt == ans);
      }
    }
  } catch (EOFException e) {
  }
}


Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction  as a sum of three distinct positive fractions in form .Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that . Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.If there is no such answer, print -1.

The single line contains single integer n (1 ≤ n ≤ 104).

If the answer exists, print 3 distinct numbers x, y and z (1 ≤ x, y, z ≤ 109, x ≠ y, x ≠ z, y ≠ z). Otherwise print -1. If there are multiple answers, print any of them.

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

__gshared:

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

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

void main() {
    int n;
    while (read(&n)) {
        if (n == 1)
            writeln("-1");//Thanks to Alexit.
        else
            foreach (y; n + 1L .. 1_000_000_001L) {
                //I just believe it works.
                long num = n * y;
                long denom = y - n;
                if (!(num % denom) && num / denom <= 1_000_000_000) {
                    writeln(n, ' ', num / denom, ' ', y);
                    break;
                }
            }
    }
}

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;
import core.stdc.stdio:freopen;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree set;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
immutable int mod=1000000007;
T lcm (T)(T a,T b)
{
	return a/gcd(a,b)*b;
}
pure nothrow X binpow(X,Y)(X base,Y exp)
	if(!isFloatingPoint!Y && !is(typeof(exp.im)))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
	if(!isFloatingPoint!Y && !is(typeof(exp.im)))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@property void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(X a,in int n,in int m)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
@property bool getarr(X)(X a,in int n){bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0) {return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
struct pair(X,Y)
{
	X first;
	Y second;
	alias first fi;
	alias second se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
		}
	this(this){fi=fi;se=se;}
	int opCmp(ref const pair!(X,Y) s_) const pure nothrow
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(in X x_,in Y y_) pure nothrow
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(in X a_) pure nothrow @property @nogc {return a_*a_;}
X cub(X)(in X a_) pure nothrow @property @nogc {return a_*a_*a_;}
nothrow @nogc @system void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow @nogc @system void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
auto arread(T)(){return readln.split.map!(to!(T)).array;}
nothrow @property pure size_t lowb(T,X)(in T a,in 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;
}
pure @property nothrow size_t upb(T,X)(in T a,in 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;
}
pure @property nothrow size_t binf(T,X)(in T a,in 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;
}
pure @property nothrow bool binary_search(T,X)(in T a,in X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	return binf(a,g)!=a.length;
}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n;

	while(input(&n))
	{
		if(n==1) writeln(-1);
		else writeln(n,' ',n+1,' ',n*(n+1));
	}
}

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

__gshared:

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

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

void main() {
    int n;
    while (read(&n))
        foreach (y; n + 1L .. 1_000_000_001L) {
            //I just believe it works.
            long num = n * y;
            long denom = y - n;
            if (!(num % denom) && num / denom <= 1_000_000_000) {
                writeln(n, ' ', num / denom, ' ', y);
                break;
            }
        }
}

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

__gshared:

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

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

void main() {
    int n;
    while (read(&n))
        foreach (y; n + 1L .. 1_000_000_001L) {
            //I just believe it works.
            long num = n * y;
            long denom = y - n;
            if (!(num % denom)) {
                writeln(n, ' ', num / denom, ' ', y);
                break;
            }
        }
}


Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed $$$n$$$ cans in a row on a table. Cans are numbered from left to right from $$$1$$$ to $$$n$$$. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down.Vasya knows that the durability of the $$$i$$$-th can is $$$a_i$$$. It means that if Vasya has already knocked $$$x$$$ cans down and is now about to start shooting the $$$i$$$-th one, he will need $$$(a_i \cdot x + 1)$$$ shots to knock it down. You can assume that if Vasya starts shooting the $$$i$$$-th can, he will be shooting it until he knocks it down.Your task is to choose such an order of shooting so that the number of shots required to knock each of the $$$n$$$ given cans down exactly once is minimum possible.

The first line of the input contains one integer $$$n$$$ $$$(2 \le n \le 1\,000)$$$ — the number of cans. The second line of the input contains the sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1\,000)$$$, where $$$a_i$$$ is the durability of the $$$i$$$-th can.

In the first line print the minimum number of shots required to knock each of the $$$n$$$ given cans down exactly once. In the second line print the sequence consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them.

NoteIn the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots $$$20 \cdot 1 + 1 = 21$$$ times. After that only second can remains. To knock it down Vasya shoots $$$10 \cdot 2 + 1 = 21$$$ times. So the total number of shots is $$$1 + 21 + 21 = 43$$$.In the second example the order of shooting does not matter because all cans have the same durability.

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 n = RD!int;
	auto a = RDA;
	auto index = a.MAKE_IDX!"a > b"();
	long cnt;
	long[] ans;
	foreach (ii, i; index)
	{
		cnt += a[i]*(ii)+1;
		ans ~= i+1;
	}

	writeln(cnt);
	ans.map!(to!string).join(" ").writeln;
	stdout.flush();
	debug readln();
}


This is the hard version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.You are given an array $$$[a_1, a_2, \dots, a_n]$$$. Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs $$$f$$$ times in this subarray, then at least $$$2$$$ different values should occur exactly $$$f$$$ times.An array $$$c$$$ is a subarray of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array.

You should output exactly one integer  — the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output $$$0$$$.

NoteIn the first sample, the subarray $$$[1, 1, 2, 2, 3, 3]$$$ is good, but $$$[1, 1, 2, 2, 3, 3, 3]$$$ isn't: in the latter there are $$$3$$$ occurrences of number $$$3$$$, and no other element appears $$$3$$$ times.

// stay simple, stay naive

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

void main() {

  int n; readf!"%d"(n);
  int[] a = new int[n + 2];
  int[] cnt = new int[n + 2];
  foreach(i; 1 .. n + 1) {
    readf!" %d"(a[i]);
    cnt[a[i]]++;
  }
  int mx = 1;
  foreach(i; 2 .. n + 1) {
    if (cnt[i] > cnt[mx]) mx = i;
  }

  immutable int B = cast(int)(std.math.sqrt(cast(real)(n)));
  debug { writefln!"B = %s"(B); }
  int ans = 0;

  int[] c = new int[n + 1];
  foreach(i; 1 .. B) {
    int l = 1, tot = 0, num = i;
    void upd(int x, int d) {
      tot -= (c[x] == num);
      c[x] += d;
      tot += (c[x] == num);
    }
    foreach(r; 1 .. n + 1) {
      upd(a[r], 1);
      while (l <= r && c[a[r]] > num) {
        upd(a[l++], -1);
      }
      if (tot > 1) {
        ans = max(ans, r - l + 1);
      }
    }
    while (l <= n) {
      upd(a[l++], -1);
    }
  }
  debug { "Fuck!".writeln; }

  int[] lastPos = new int[n + 2];
  foreach(i; 1 .. n + 1) {
    if (i != mx && cnt[i] >= B) {
      foreach(j; 0 .. n + 1) {
        lastPos[j] = -1;
      }
      int t = cnt[mx];
      lastPos[t] = 0;
      foreach(j; 1 .. n + 1) {
        t += (a[j] == i) - (a[j] == mx);
        if (lastPos[t] == -1) lastPos[t] = j;
        else ans = max(ans, j - lastPos[t]);
      }
    }
  }

  ans.writeln;

}

// stay simple, stay naive

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

void main() {

  int n; readf!"%d"(n);
  int[] a = new int[n + 2];
  int[] cnt = new int[n + 2];
  foreach(i; 1 .. n + 1) {
    readf!" %d"(a[i]);
    cnt[a[i]]++;
  }
  int mx = 1;
  foreach(i; 2 .. n + 1) {
    if (cnt[i] > cnt[mx]) mx = i;
  }

  immutable int B = 314;
  int ans = 0;

  int[] c = new int[n + 1];
  foreach(i; 1 .. B) {
    int l = 1, tot = 0;
    void upd(int x, int d) {
      tot -= (c[x] == i);
      c[x] += d;
      tot += (c[x] == i);
    }
    foreach(r; 1 .. n + 1) {
      upd(a[r], 1);
      while (l <= r && c[a[r]] > i) {
        upd(a[l++], -1);
      }
      if (tot > 1) {
        ans = max(ans, r - l + 1);
      }
    }
    while (l <= n) {
      upd(a[l++], -1);
    }
  }
  debug { "Fuck!".writeln; }

  int[] lastPos = new int[n + 2];
  foreach(i; 1 .. n + 1) {
    if (i != mx && cnt[i] >= B) {
      foreach(j; 0 .. n + 1) {
        lastPos[j] = -1;
      }
      int t = cnt[mx];
      lastPos[t] = 0;
      foreach(j; 1 .. n + 1) {
        t += (a[j] == i) - (a[j] == mx);
        if (lastPos[t] == -1) lastPos[t] = j;
        else ans = max(ans, j - lastPos[t]);
      }
    }
  }

  ans.writeln;

}