There is a $$$n \times m$$$ grid. You are standing at cell $$$(1, 1)$$$ and your goal is to finish at cell $$$(n, m)$$$.You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell $$$(x, y)$$$. You can:   move right to the cell $$$(x, y + 1)$$$ — it costs $$$x$$$ burles;  move down to the cell $$$(x + 1, y)$$$ — it costs $$$y$$$ burles. Can you reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first and only line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n, m \le 100$$$; $$$0 \le k \le 10^4$$$) — the sizes of grid and the exact amount of money you need to spend.

For each test case, if you can reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first test case, you are already in the final cell, so you spend $$$0$$$ burles.In the second, third and fourth test cases, there are two paths from $$$(1, 1)$$$ to $$$(2, 2)$$$: $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(1, 2)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ or $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$. Both costs $$$1 + 2 = 3$$$ burles, so it's the only amount of money you can spend.In the fifth test case, there is the only way from $$$(1, 1)$$$ to $$$(1, 4)$$$ and it costs $$$1 + 1 + 1 = 3$$$ burles.

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;

void main()
{
    auto l= to!long(readln().chomp);
    foreach(_; 0..l)
    {
        auto params = readln().chomp.splitter(" ").map!(to!long).array;
        long m = params[0];
        long n = params[1];
        long k = params[2];

        writeln(m*n-1 == k ? "YES" : "NO");
    }
}

// Vicfred
// https://codeforces.com/contest/1519/problem/B
// math
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

while(t--) {
    int n, m, k;
    readf("%s %s %s\n", &n, &m, &k);
    if(k == n * m - 1)
        "YES".writeln;
    else
        "NO".writeln;
}
}

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)); }
double[] rotate(double[] vec, double rad) { return [cos(rad) * vec[0] - sin(rad) * vec[1], sin(rad) * vec[0] + cos(rad) * vec[1]]; }

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 bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD;
		auto m = RD;
		auto k = RD;

		long cnt = n-1;
		cnt += n * (m-1);
		ans[ti] = cnt == k;
	}

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


There is a grid with $$$n$$$ rows and $$$m$$$ columns, and three types of cells:   An empty cell, denoted with '.'.  A stone, denoted with '*'.  An obstacle, denoted with the lowercase Latin letter 'o'. All stones fall down until they meet the floor (the bottom row), an obstacle, or other stone which is already immovable. (In other words, all the stones just fall down as long as they can fall.)Simulate the process. What does the resulting grid look like?

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 50$$$) — the number of rows and the number of columns in the grid, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either '.', '*', or 'o' — an empty cell, a stone, or an obstacle, respectively.

For each test case, output a grid with $$$n$$$ rows and $$$m$$$ columns, showing the result of the process. You don't need to output a new line after each test, it is in the samples just for clarity.

import std;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		char [] [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip.dup;
		}
		foreach_reverse (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (board[row][col] == '*')
				{
					for (int pos = row; pos + 1 < rows &&
					    board[pos + 1][col] == '.'; pos++)
					{
						swap (board[pos][col],
						    board[pos + 1][col]);
					}
				}
			}
		}
		writefln !("%-(%s\n%)\n") (board);
	}
}


This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.

In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.

NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    arr.sort();
    ll[] res = new ll[](n);
    foreach(i; 0..n/2){
        res[2*i + 1] = arr[i];
    }
    foreach(i;(n/2)..n){
        res[2*(i - n/2)] = arr[i];
    }
    ll num = 0;
    foreach(i; 1..n-1){
        if(res[i] < res[i-1] && res[i] < res[i+1]){
            ++num;
        }
    }
    writeln(num);
    foreach(el; res){
        write(el, " ");
    }
    writeln;
}

void main(){
    long t = 1;
    /* t = rd; */
    while(t--) solve();
    stdout.flush;
}

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

void main()
{
    auto N = readln.chomp.to!int;
    auto AS = readln.split.to!(int[]);
    sort!"a > b"(AS);

    auto BS = new int[](N);
    int i, j;
    while (j < N) {
        BS[j] = AS[i];
        ++i;
        j += 2;
    }
    foreach (k; 0..N) if (BS[k] == 0) BS[k] = AS[i++];
    if (N%2 == 0) {
        int k = 1;
        while (k < N-1) {
            if (BS[k-1] > BS[k] && BS[k+1] > BS[k]) {
                k += 2;
                continue;
            }
            BS[$-1] = BS[k];
            BS[k] = AS[i-1];
            goto end;
        }
    }
    end:

    int r;
    foreach (k; 1..N-1) if (BS[k-1] > BS[k] && BS[k+1] > BS[k]) ++r;
    writeln(r);
    writeln(BS.to!(string[]).join(" "));
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;
	a.sort();

	auto ans = new long[](n);
	foreach (i; 0..n/2)
	{
		ans[i*2+1] = a.front; a.popFront;
	}
	foreach (i; n/2..n)
	{
		ans[(i-n/2)*2] = a.front; a.popFront;
	}

	long cnt;
	foreach (i; 1..n-1)
	{
		if (ans[i] < ans[i-1] && ans[i] < ans[i+1])
			++cnt;
	}

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


Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.

The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).

Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1).In the second sample you need 6 moves to build permutation (1, 3, 2).

import std.algorithm;
import std.math;
import std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			scanf (" %d", &a[i]);
		}
		sort (a);
		long res = 0;
		foreach (i; 0..n)
		{
			res += abs (i + 1 - a[i]);
		}
		writeln (res);
	}
}

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

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			scanf (" %d", &a[i]);
		}
		sort (a);
		long res = 0;
		foreach (i; 0..n)
		{
			res += abs (i + 1 - a[i]);
		}
		writeln (res);
	}
}

import std.stdio;
import std.math;
import std.algorithm;
/*
int myabs(int a) {
  if (a < 0) return -a;
  return a;
}
*/
void main() {
  int n;
  scanf("%d",&n);
  int[] a = new int[n];
  for (int i = 0 ; i < n ; ++i)
    scanf("%d",&a[i]);
  sort(a);
  ulong ans = 0;
  foreach (int idx, ele ; a) {
    ans += abs(idx-ele+1);
  }
  writef("%d\n", ans);
}

import std.stdio, std.string, std.conv, std.range, std.array, std.algorithm;
import std.uni, std.math, std.container, std.typecons, std.typetuple;
import core.bitop, std.datetime;

immutable int mod = 10^^9 + 7;

void main()
{
    auto n = readln.chomp.to!int;
    auto a = readln.split.to!(long[]);

    long ans;

    sort(a);

    foreach (i ; 0 .. n) {
        ans += abs(i + 1 - a[i]);
    }

    writeln(ans);
}

void readVars(T...)(auto ref T args)
{
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

import std.stdio, std.string, std.conv, std.range, std.array, std.algorithm;
import std.uni, std.math, std.container, std.typecons, std.typetuple;
import core.bitop, std.datetime;

immutable int mod = 10^^9 + 7;

void main()
{
    auto n = readln.chomp.to!int;
    auto a = readln.split.to!(int[]);

    long ans;

    sort(a);

    foreach (i ; 0 .. n) {
        ans += abs(i + 1 - a[i]);
    }

    writeln(ans);
}

void readVars(T...)(auto ref T args)
{
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

import std.stdio, std.string, std.conv, std.range, std.array, std.algorithm;
import std.uni, std.math, std.container, std.typecons, std.typetuple;
import core.bitop, std.datetime;

immutable int mod = 10^^9 + 7;

void main()
{
    auto n = readln.chomp.to!int;
    auto a = readln.split.to!(int[]);

    long ans;

    sort(a);

    foreach (i ; 0 .. n) {
        if(i + 1 > a[i]) {
            ans += i + 1 - a[i];
        }
        else {
            ans += a[i] - i - 1;
        }
    }

    writeln(ans);
}

void readVars(T...)(auto ref T args)
{
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

module sigod.codeforces.p285C;

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

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

	stdin.readln();
	long[] a = read_array!(long)();

	sort(a);

	long result = 0;

	foreach (i, ai; a) {
		result += abs(ai - (i + 1));
	}

	stdout.writeln(result);
}

private
T[] read_array(T)()
{
	auto input = stdin.readln().strip().split();

	T[] result = new T[input.length];

	foreach (index, ref element; input) {
		result[index] = element.to!T();
	}

	return result;
}

import std.stdio;
import std.math;
import std.algorithm;
/*
int myabs(int a) {
  if (a < 0) return -a;
  return a;
}
*/
void main() {
  int n;
  scanf("%d",&n);
  int[] a = new int[n];
  for (int i = 0 ; i < n ; ++i)
    scanf("%d",&a[i]);
  sort(a);
  int ans = 0;
  foreach (int idx, ele ; a) {
    ans += abs(idx-ele+1);
  }
  writef("%d\n", ans);
}

import std.stdio;
import std.math;
import std.algorithm;
/*
int myabs(int a) {
  if (a < 0) return -a;
  return a;
}
*/
void main() {
  int n;
  scanf("%d",&n);
  int[] a = new int[n];
  for (int i = 0 ; i < n ; ++i)
    scanf("%d",&a[i]);
  sort(a);
  int ans = 0;
  foreach (int idx, ele ; a) {
    ans += abs(idx-ele+1);
  }
  printf("%d\n", ans);
}


You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types:   empty string;  '(' + RBS + ')';  '[' + RBS + ']';  RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.

NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.

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

// Main Logic Here
void play(){
    dchar[] word = rd!(dchar[]);
    ll bal0 = 0, bal1 = 0;
    ll pair0 = 0, pair1 = 0;
    foreach(cr; word){
        show(cr, pair0, pair1);
        if(cr == '('){
            ++bal0;
        }else if(cr == '['){
            ++bal1;
        }else if(cr == ')'){
            if(bal0 > 0) ++pair0;
            --bal0;
        }else if(cr==']'){
            if(bal1 > 0) ++pair1;
            --bal1;
        }
        bal0 = max(bal0, 0);
        bal1 = max(bal1, 0);
    }
    writeln(pair1 + pair0);
}

int main(){
    long t = 1;
    t = rd;        // Toggle for testcases!
    while(t--) play();  // Let's play!
    return 0;
}

/**********That's All Folks!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;    // Read input
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
alias ll = long;
alias tup = Tuple!(long, "x",  long, "y");
void show(A...)(A a) { debug{ foreach(t; a){ stderr.write(t, "| "); } stderr.writeln; } } // Debug
/* Add if TLE, T max(T = long)(T a, T b){ return (a > b) ? a : b; } */

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

auto go (string s, string c)
{
	char [] stack = "**".dup;
	foreach (ref e; s.filter !(e => c.canFind (e)))
	{
		stack.assumeSafeAppend ();
		stack ~= e;
		if (stack[$ - 2..$] == c)
		{
			stack.popBackN (2);
		}
	}
	return stack.length.to !(int) - 2;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		writeln ((s.length - s.go ("()") - s.go ("[]")) / 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(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto s = RD!string;

		long cnt1, cnt2;
		foreach (c; s)
		{
			if (c == ')')
			{
				if (cnt1 > 0)
				{
					--cnt1;
					++ans[ti];
				}
			}
			else if (c == '(')
			{
				++cnt1;
			}
			else if (c == ']')
			{
				if (cnt2 > 0)
				{
					--cnt2;
					++ans[ti];
				}
			}
			else
			{
				++cnt2;
			}
		}
	}

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

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

// Main Logic Here
void play(){
    dchar[] word = rd!(dchar[]);
    ll bal0 = 0, bal1 = 0;
    ll pair0 = 0, pair1 = 0;
    foreach(cr; word){
        show(cr, pair0, pair1);
        if(cr == '('){
            ++bal0;
        }else if(cr == '['){
            ++bal1;
        }else if(cr == ')'){
            if(bal0 > 0) ++pair0;
            --bal0;
        }else if(cr==']'){
            if(bal1 > 0) ++pair1;
            --bal1;
        }
    }
    writeln(pair1 + pair0);
}

int main(){
    long t = 1;
    t = rd;        // Toggle for testcases!
    while(t--) play();  // Let's play!
    return 0;
}

/**********That's All Folks!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;    // Read input
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
alias ll = long;
alias tup = Tuple!(long, "x",  long, "y");
void show(A...)(A a) { debug{ foreach(t; a){ stderr.write(t, "| "); } stderr.writeln; } } // Debug
/* Add if TLE, T max(T = long)(T a, T b){ return (a > b) ? a : b; } */


Once Bob decided to lay a parquet floor in his living room. The living room is of size n × m metres. Bob had planks of three types: a planks 1 × 2 meters, b planks 2 × 1 meters, and c planks 2 × 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks.

The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≤ n, m ≤ 100, 0 ≤ a, b, c ≤ 104), n and m — the living room dimensions, a, b and c — amount of planks 1 × 2, 2 × 1 и 2 × 2 respectively. It's not allowed to turn the planks.

If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room — output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any.

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

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

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

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

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

int M, N, A, B, C;

char getColor(int x, int y) {
	return 'a' + ((x % 5) * 5 + (y % 5));
}

char[][] solve() {
	char[][] ret = new char[][](M, N);
	if ((M * N) % 2 != 0) {
		return null;
	}
	if (M * N > A * 2 + B * 2 + C * 4) {
		return null;
	}
	if (M % 2 != 0) {
		if (N / 2 > A) {
			return null;
		}
		for (int y = 0; y < N; y += 2) {
			ret[M - 1][y] = ret[M - 1][y + 1] = getColor(M - 1, y);
		}
		--M;
		A -= N / 2;
	}
	if (N % 2 != 0) {
		if (M / 2 > B) {
			return null;
		}
		for (int x = 0; x < M; x += 2) {
			ret[x][N - 1] = ret[x + 1][N - 1] = getColor(x, N - 1);
		}
		--N;
		B -= M / 2;
	}
	for (int x = 0; x < M; x += 2) for (int y = 0; y < N; y += 2) {
		if (A >= 2) {
			ret[x][y] = ret[x][y + 1] = getColor(x, y);
			ret[x + 1][y] = ret[x + 1][y + 1] = getColor(x + 1, y);
			A -= 2;
		} else if (B >= 2) {
			ret[x][y] = ret[x + 1][y] = getColor(x, y);
			ret[x][y + 1] = ret[x + 1][y + 1] = getColor(x, y + 1);
			B -= 2;
		} else if (C >= 1) {
			ret[x][y] = ret[x][y + 1] = ret[x + 1][y] = ret[x + 1][y + 1] = getColor(x, y);
			C -= 1;
		} else {
			return null;
		}
	}
	return ret;
}

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = readInt;
		B = readInt;
		C = readInt;

		if (const res = solve) {
			foreach (line; res) {
				writeln(line.to!string);
			}
		} else {
			writeln("IMPOSSIBLE");
		}
	}
	} catch (EOFException) {}
}

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

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

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

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

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

int M, N, A, B, C;

char getColor(int x, int y) {
	return 'a' + ((x % 5) * 5 + (y % 5));
}

char[][] solve() {
	char[][] ret = new char[][](M, N);
	if ((M * N) % 2 != 0) {
		return null;
	}
	if (M * N > A * 2 + B * 2 + C * 4) {
		return null;
	}
	if (M % 2 != 0) {
		if (N / 2 > A) {
			return null;
		}
		for (int y = 0; y < N; y += 2) {
			ret[M - 1][y] = ret[M - 1][y + 1] = getColor(M - 1, y);
		}
		--M;
		A -= N / 2;
	}
	if (N % 2 != 0) {
		if (M / 2 > B) {
			return null;
		}
		for (int x = 0; x < M; x += 2) {
			ret[x][N - 1] = ret[x + 1][N - 1] = getColor(x, N - 1);
		}
		--N;
		B -= M / 2;
	}
	for (int x = 0; x < M; x += 2) for (int y = 0; y < N; y += 2) {
		if (A >= 2) {
			ret[x][y] = ret[x][y + 1] = getColor(x, y);
			ret[x + 1][y] = ret[x + 1][y + 1] = getColor(x + 1, y);
			A -= 2;
		} else if (B >= 2) {
			ret[x][y] = ret[x + 1][y] = getColor(x, y);
			ret[x][y + 1] = ret[x + 1][y + 1] = getColor(x, y + 1);
			B -= 2;
		} else if (C >= 1) {
			ret[x][y] = ret[x][y + 1] = ret[x + 1][y] = ret[x + 1][y + 1] = getColor(x, y);
			C -= 1;
		} else {
			return null;
		}
	}
	return ret;
}

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = readInt;
		B = readInt;
		C = readInt;

		if (const res = solve) {
			foreach (x; 0 .. M) {
				writeln(res[x].to!string);
			}
		} else {
			writeln("IMPOSSIBLE");
		}
	}
	} catch (EOFException) {}
}


Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:  In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero.  When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.

The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105) — the elements of the array.

Print a single integer — the minimum number of seconds needed to make all elements of the array equal to zero.

NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		int [int] v;
		foreach (c; a)
		{
			v[c] += 1;
		}
		int res = 0;
		foreach (key, value; v)
		{
			if (key != 0)
			{
				res += 1;
			}
		}
		writeln (res);
	}
}


You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.The elevator has two commands:   Go up or down one floor. The movement takes 1 second.  Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1.You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.

The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees. The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator.

Print a single integer — the minimal possible time in seconds.

Note Explaination for the first sample  t = 0 t = 2 t = 3 t = 5 t = 6 t = 7 t = 9 t = 10

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

void main() {
    immutable int INF = 1 << 29;

    int[] unfold(int n) {
        return [n / 1000 % 10, n / 100 % 10, n / 10 % 10, n % 10];
    }

    int fold(int[] a) {
        int[] b = a.dup;
        b.sort!"a > b";
        return b[0] + b[1] * 10 + b[2] * 100 + b[3] * 1000;
    }

    auto N = readln.chomp.to!int;
    auto src = new int[](N);
    auto dst = new int[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        src[i] = s[0];
        dst[i] = s[1];
    }

    auto dp = new int[][](N+1, 10000);
    foreach (i; 0..N+1) dp[i].fill(INF);
    dp[0][0] = 0;

    foreach (i; 0..N) {
        int cur = i == 0 ? 1 : src[i-1];
        int tar = src[i];
        foreach (a; 0..10) {
            foreach (b; a..10) {
                foreach (c; b..10) {
                    foreach (d; c..10) {
                        foreach (k; 1..10) {
                            if (dp[i][d + c*10 + b*100 + a*1000] >= INF) continue;
                            int hi = max(cur, tar, k);
                            int lo = min(cur, tar, k);
                            int[] v = [a, b, c, d];
                            int cost = 1;
                            foreach (j; 0..4) if (lo <= v[j] && v[j] <= hi) v[j] = 0, cost += 1;
                            int z = -1;
                            foreach (j; 0..4) if (v[j] == 0) z = j;
                            if (z == -1) continue;
                            v[z] = dst[i];
                            int dist = abs(cur - k) + abs(k - tar);
                            int fv = fold(v);
                            dp[i+1][fv] = min(dp[i+1][fv], dp[i][d + c*10 + b*100 + a*1000] + dist + cost);
                        }
                    }
                }
            }
        }
    }

    int ans = INF;

    foreach (a; 0..10) {
        foreach (b; a..10) {
            foreach (c; b..10) {
                foreach (d; c..10) {
                    int[] v = [a, b, c, d];
                    if (v.all!"a == 0") {
                        ans = min(ans, dp[N][0]);
                        continue;
                    }
                    int hi = (src.back, v.filter!"a != 0".reduce!max);
                    int lo = (src.back, v.filter!"a != 0".reduce!min);
                    int cost = (a != 0) + (b != 0) + (c != 0) + (d != 0);
                    int dist = min(abs(src.back - hi) + abs(hi - lo), abs(src.back - lo) + abs(lo - hi));
                    ans = min(ans, dp[N][fold([a, b, c, d])] + dist + cost);
                }
            }
        }
    }

    ans.writeln;
}

import std.algorithm;
import std.conv;
import std.math;
import std.stdio;

immutable int infinity = int.max / 4;
immutable int totalLevels = 9;
immutable int NA = -1;

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

		alias State = int [4];
		State [] states;
		int [State] stateNum;
		foreach (a; NA..totalLevels)
		{
			foreach (b; a..totalLevels)
			{
				foreach (c; b..totalLevels)
				{
					foreach (d; c..totalLevels)
					{
						State state = [a, b, c, d];
						do
						{
							stateNum[state] =
							    states.length
							    .to !(int);
						}
						while (nextPermutation
						    (state[]));
						states ~= state;
					}
				}
			}
		}
		immutable int totalStates = 715;
		assert (totalStates == states.length);

		auto f = new int [totalLevels] [] [] (n + 1, totalStates);
		foreach (i; 0..n + 1)
		{
			foreach (stateIndex; 0..totalStates)
			{
				f[i][stateIndex][] = infinity;
			}
		}
		f[0][0][0] = 0;

		int res = infinity;
		foreach (i; 0..n + 1)
		{
			foreach_reverse (stateIndex; 0..totalStates)
			{
				auto curState = states[stateIndex];
				foreach (level; 0..totalLevels)
				{
					auto cur = f[i][stateIndex][level];
					if (cur >= infinity)
					{
						continue;
					}
					foreach (j, v; curState)
					{
						if (v == NA)
						{
							continue;
						}
						auto nextValue = cur + abs
						    (level - v) + 1;
						auto nextState = curState;
						nextState[j] = NA;
						auto nextIndex =
						    stateNum[nextState];
						f[i][nextIndex][v] =
						    min (f[i][nextIndex][v],
						    nextValue);
					}

					if (i < n && curState[0] == NA)
					{
						auto u = src[i];
						auto nextValue = cur + abs
						    (level - u) + 1;
						auto nextState = curState;
						nextState[0] = dst[i];
						auto nextIndex =
						    stateNum[nextState];
						f[i + 1][nextIndex][u] =
						    min (f[i + 1][nextIndex]
						    [u], nextValue);
					}
				}
			}
		}

		writeln (minElement (f[n][0][]));
	}
}

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

void main() {
    immutable int INF = 1 << 29;

    int[] unfold(int n) {
        return [n / 1000 % 10, n / 100 % 10, n / 10 % 10, n % 10];
    }

    int fold(int[] a) {
        int[] b = a.dup;
        b.sort!"a > b";
        return b[0] + b[1] * 10 + b[2] * 100 + b[3] * 1000;
    }

    auto N = readln.chomp.to!int;
    auto src = new int[](N);
    auto dst = new int[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        src[i] = s[0];
        dst[i] = s[1];
    }

    auto dp = new int[][](N+1, 10000);
    foreach (i; 0..N+1) dp[i].fill(INF);
    dp[0][0] = 0;

    foreach (i; 0..N) {
        int cur = i == 0 ? 1 : src[i-1];
        int tar = src[i];
        foreach (a; 0..10) {
            foreach (b; a..10) {
                foreach (c; b..10) {
                    foreach (d; c..10) {
                        foreach (k; 1..10) {
                            int[] v = [a, b, c, d];
                            int fv = fold(v);
                            if (dp[i][fv] >= INF) continue;
                            int hi = max(cur, tar, k);
                            int lo = min(cur, tar, k);
                            int cost = 1;
                            foreach (j; 0..4) if (lo <= v[j] && v[j] <= hi) v[j] = 0, cost += 1;
                            int z = -1;
                            foreach (j; 0..4) if (v[j] == 0) z = j;
                            if (z == -1) continue;
                            v[z] = dst[i];
                            int dist = abs(cur - k) + abs(k - tar);
                            dp[i+1][fv] = min(dp[i+1][fv], dp[i][d + c*10 + b*100 + a*1000] + dist + cost);
                        }
                    }
                }
            }
        }
    }

    int ans = INF;

    foreach (a; 0..10) {
        foreach (b; a..10) {
            foreach (c; b..10) {
                foreach (d; c..10) {
                    int[] v = [a, b, c, d];
                    if (v.all!"a == 0") {
                        ans = min(ans, dp[N][0]);
                        continue;
                    }
                    int hi = (src.back, v.filter!"a != 0".reduce!max);
                    int lo = (src.back, v.filter!"a != 0".reduce!min);
                    int cost = (a != 0) + (b != 0) + (c != 0) + (d != 0);
                    int dist = min(abs(src.back - hi) + abs(hi - lo), abs(src.back - lo) + abs(lo - hi));
                    ans = min(ans, dp[N][fold([a, b, c, d])] + dist + cost);
                }
            }
        }
    }

    ans.writeln;
}


Phoenix has $$$n$$$ blocks of height $$$h_1, h_2, \dots, h_n$$$, and all $$$h_i$$$ don't exceed some value $$$x$$$. He plans to stack all $$$n$$$ blocks into $$$m$$$ separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than $$$x$$$. Please help Phoenix build $$$m$$$ towers that look beautiful. Each tower must have at least one block and all blocks must be used.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$x$$$ ($$$1 \le m \le n \le 10^5$$$; $$$1 \le x \le 10^4$$$) — the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.  The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le h_i \le x$$$) — the heights of the blocks.  It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$10^5$$$.

For each test case, if Phoenix cannot build $$$m$$$ towers that look beautiful, print NO. Otherwise, print YES, followed by $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$, where $$$y_i$$$ ($$$1 \le y_i \le m$$$) is the index of the tower that the $$$i$$$-th block is placed in. If there are multiple solutions, print any of them.

NoteIn the first test case, the first tower has height $$$1+2+3=6$$$ and the second tower has height $$$1+2=3$$$. Their difference is $$$6-3=3$$$ which doesn't exceed $$$x=3$$$, so the towers are beautiful.In the second test case, the first tower has height $$$1$$$, the second tower has height $$$1+2=3$$$, and the third tower has height $$$3$$$. The maximum height difference of any two towers is $$$3-1=2$$$ which doesn't exceed $$$x=3$$$, so the towers are beautiful.

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.container.binaryheap;
import std.typecons;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto params = readln().chomp.splitter(" ").map!(to!int).array;
        int n = params[0];
        int m = params[1];
        int x = params[2];

        auto arr = readln().chomp.splitter(" ").map!(to!long).array;

        int cur = 0;
        auto h = heapify!"a[0] > b[0]"([[0L, 1L]]);

        foreach(i; 2..m+1)
        {
            h.insert([0L, to!long(i)]);
        }

        foreach (int i; 0..n)
        {
            auto ar = h.front;
            h.removeFront();
            h.insert([arr[i]+ar[0], ar[1]]);
            arr[i] = ar[1];
        }

        writeln("YES");
        writeln(arr.map!(to!string).joiner(" "));
    }
}

import std.stdio, std.algorithm, std.typecons, std.container, std.range;

void main() {
  int t;
  readf!" %d"(t);

  while (t--) {
    writeln("YES");
    int n, m, x;
    readf!" %d %d %d\n"(n, m, x);

    auto heap = iota(m).map!"tuple(0L, a + 1)".array.heapify!"a > b";

    foreach (h; readln.split.map!"a.to!int") {
      auto tower = heap.front;
      tower[0] += h;
      write(tower[1], ' ');
      heap.replaceFront(tower);
    }
  }
}

import std.stdio;
import std.container;
import std.typecons;
import std.ascii;
import std.algorithm;
import std.range;
import core.stdc.stdio;

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
void solve()
{
	int n = readInt!int;
	int m = readInt!int;
	int x = readInt!int;
	auto h = new int[](n); foreach(ref hi; h) hi = readInt!int;
	auto queue = redBlackTree!(Tuple!(int, size_t))();
	auto cnt = new int[](m);
	auto bucket = new size_t[](n);
	bucket[] = -1;
	foreach(i, cnti; cnt) queue.insert(tuple(cnti, i));
	foreach(i, ref hi; h)
	{
		auto nextPlaceT = queue.front; queue.removeFront;
		auto nextBucket = nextPlaceT[1];
		bucket[i] = nextBucket + 1;
		cnt[nextPlaceT[1]] += hi;
		queue.insert(tuple(cnt[nextPlaceT[1]], nextPlaceT[1]));
	}
	"YES".writeln;
	foreach(bi; bucket) bi.write(" ");
	writeln;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

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

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

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m, x;
		readf !(" %s %s %s") (n, m, x);
		readln;
		auto h = readln.splitter.map !(to !(int)).array;
		auto y = new int [m];
		auto t = redBlackTree !((i, j) => y[i] < y[j], true)
		    (m.iota.array);
		auto answer = new int [n];
		foreach (i, ref c; h)
		{
			auto p = t.front;
			t.removeFront ();
			y[p] += c;
			answer[i] = p + 1;
			t.insert (p);
		}
		writeln ("YES");
		writefln !("%(%s %)") (answer);
	}
}


You have a grid with n rows and n columns. Each cell is either empty (denoted by '.') or blocked (denoted by 'X').Two empty cells are directly connected if they share a side. Two cells (r1, c1) (located in the row r1 and column c1) and (r2, c2) are connected if there exists a sequence of empty cells that starts with (r1, c1), finishes with (r2, c2), and any two consecutive cells in this sequence are directly connected. A connected component is a set of empty cells such that any two cells in the component are connected, and there is no cell in this set that is connected to some cell not in this set.Your friend Limak is a big grizzly bear. He is able to destroy any obstacles in some range. More precisely, you can choose a square of size k × k in the grid and Limak will transform all blocked cells there to empty ones. However, you can ask Limak to help only once.The chosen square must be completely inside the grid. It's possible that Limak won't change anything because all cells are empty anyway.You like big connected components. After Limak helps you, what is the maximum possible size of the biggest connected component in the grid?

The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 500) — the size of the grid and Limak's range, respectively. Each of the next n lines contains a string with n characters, denoting the i-th row of the grid. Each character is '.' or 'X', denoting an empty cell or a blocked one, respectively.

Print the maximum possible size (the number of cells) of the biggest connected component, after using Limak's help.

NoteIn the first sample, you can choose a square of size 2 × 2. It's optimal to choose a square in the red frame on the left drawing below. Then, you will get a connected component with 10 cells, marked blue in the right drawing.

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

immutable int NA = -1;
immutable int DIRS = 4;
immutable int [DIRS + 1] DROW = [-1,  0, +1,  0,  0];
immutable int [DIRS + 1] DCOL = [ 0, -1,  0, +1,  0];

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto b = new bool [] [] (n + 2, n + 2);
		foreach (row; 0..n)
		{
			auto s = readln.strip;
			foreach (col; 0..n)
			{
				if (s[col] == '.')
				{
					b[row + 1][col + 1] = true;
				}
			}
		}
		auto a = new int [] [] (n + 2, n + 2);
		foreach (ref t; a)
		{
			t[] = NA;
		}

		int num = 0;
		int [] size;
		size.reserve ((n * n + 1) / 2);

		void mark (int row, int col)
		{
			if (!b[row][col] || a[row][col] != NA)
			{
				return;
			}
			a[row][col] = num;
			size[num]++;
			foreach (dir; 0..DIRS)
			{
				mark (row + DROW[dir], col + DCOL[dir]);
			}
		}

		foreach (row; 1..n + 1)
		{
			foreach (col; 1..n + 1)
			{
				if (b[row][col] && a[row][col] == NA)
				{
					size ~= 0;
					mark (row, col);
					num++;
				}
			}
		}

		int res = 0;
		int cur = 0;
		auto conn = new int [num];

		void delCell (int row, int col)
		{
			if (!b[row][col])
			{
				cur--;
			}
			foreach (dir; 0..DIRS + 1)
			{
				int crow = row + DROW[dir];
				int ccol = col + DCOL[dir];
				int comp = a[crow][ccol];
				if (comp == NA)
				{
					continue;
				}
				conn[comp]--;
				if (conn[comp] == 0)
				{
					cur -= size[comp];
				}
			}
		}

		void addCell (int row, int col)
		{
			if (!b[row][col])
			{
				cur++;
			}
			foreach (dir; 0..DIRS + 1)
			{
				int crow = row + DROW[dir];
				int ccol = col + DCOL[dir];
				int comp = a[crow][ccol];
				if (comp == NA)
				{
					continue;
				}
				if (conn[comp] == 0)
				{
					cur += size[comp];
				}
				conn[comp]++;
			}
		}

		foreach (crow; 1..k + 1)
		{
			foreach (ccol; 1..k + 1)
			{
				addCell (crow, ccol);
			}
		}
		auto curSaved = cur;
		auto connSaved = conn.dup;

		foreach (row; 1..n - k + 2)
		{
			foreach (col; 1..n - k + 2)
			{
				debug {writeln (row, " ", col, " ", cur);}
				res = max (res, cur);
				if (col + 1 == n - k + 2)
				{
					break;
				}
				foreach (crow; row..row + k)
				{
					delCell (crow, col);
					addCell (crow, col + k);
				}
			}
			if (row + 1 == n - k + 2)
			{
				break;
			}
			cur = curSaved;
			conn[] = connSaved[];
			foreach (ccol; 1..k + 1)
			{
				delCell (row, ccol);
				addCell (row + k, ccol);
			}
			curSaved = cur;
			connSaved[] = conn[];
		}

		writeln (res);
	}
}


You have a playlist consisting of $$$n$$$ songs. The $$$i$$$-th song is characterized by two numbers $$$t_i$$$ and $$$b_i$$$ — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of $$$3$$$ songs having lengths $$$[5, 7, 4]$$$ and beauty values $$$[11, 14, 6]$$$ is equal to $$$(5 + 7 + 4) \cdot 6 = 96$$$.You need to choose at most $$$k$$$ songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$) – the number of songs in the playlist and the maximum number of songs you can choose, respectively. Each of the next $$$n$$$ lines contains two integers $$$t_i$$$ and $$$b_i$$$ ($$$1 \le t_i, b_i \le 10^6$$$) — the length and beauty of $$$i$$$-th song.

Print one integer — the maximum pleasure you can get.

NoteIn the first test case we can choose songs $$${1, 3, 4}$$$, so the total pleasure is $$$(4 + 3 + 6) \cdot 6 = 78$$$.In the second test case we can choose song $$$3$$$. The total pleasure will be equal to $$$100 \cdot 100 = 10000$$$.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto TB = N.iota.map!(_ => readln.split.map!(to!long).array).array;
    TB.sort!"a[1] > b[1]";

    auto pq = new BinaryHeap!(Array!long, "a > b");
    long tmp = 0;
    long ans = 0;

    for (int i = 0; i < N; ) {
        long b = TB[i][1];
        while (i < N && TB[i][1] == b) {
            pq.insert(TB[i][0]);
            tmp += TB[i][0];
            if (pq.length > K) {
                tmp -= pq.front;
                pq.removeFront;
            }
            ++i;
        }
        ans = max(ans, tmp * b);
    }

    ans.writeln;
}

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

alias S = Tuple!(long, "t", long, "b");

S[10^^5*3] SS;

long[10^^5*3] MIN_P;

void main()
{
    auto nk = readln.split.to!(int[]);
    auto N = nk[0];
    auto K = nk[1];

    foreach (i; 0..N) {
        auto tb = readln.split.to!(long[]);
        SS[i] = S(tb[0], tb[1]);
    }

    sort!"a.b > b.b"(SS[0..N]);

    long t, p, r;
    auto tree = redBlackTree!true(0L);
    foreach (i; 0..N) {
        if (!tree.front) tree.removeFront();
        t += SS[i].t;
        tree.insert(SS[i].t);
        if (tree.length > K) {
            t -= tree.front;
            tree.removeFront();
        }
        r = max(r, t * SS[i].b);
    }

    writeln(r);
}

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

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

void main() {
  auto r = new InputReader;
  immutable n = r.next!uint;
  immutable k = r.next!uint;
  auto a = uninitializedArray!(Tuple!(uint, uint)[]) (n);
  auto c = uninitializedArray!(uint[]) (n);
  foreach (i, ref p; a) {
    auto l = r.next!uint;
    auto b = r.next!uint;
    p = tuple (b, l);
    c[i] = l;
  }
  c.sort ();
  auto t1 = new RedBlackTree!(int, "a < b", true) ();
  auto t2 = new RedBlackTree!(int, "a < b", true) ();
  long s;
  foreach (i; 0 .. k) {
    t2.insert (c[n-1-i]);
    s += c[n-1-i];
  }
  foreach (i; k .. n) {
    t1.insert (c[n-1-i]);
  }
  a.sort ();
  debug stderr.writeln (a);
  debug stderr.writeln (c);

  long res = long.min;
  foreach (i; 0 .. n) {
    int x = a[i][0];
    res = max (res, x * s);
    //remove p[i][1]
    int w = a[i][1];
    auto e = t1.equalRange (w);
    if (e.empty) {
      s -= w;
      t2.removeKey (w);
      if (t1.empty) {
      } else {
        int v = t1.back;
        t1.removeBack ();
        t2.insert (v);
        s += v;
      }
    } else {
      t1.removeKey (w);
    }
  }
  writeln (res);
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto TB = N.iota.map!(_ => readln.split.map!(to!long).array).array;
    TB.sort!"a[1] > b[1]";

    auto pq = new BinaryHeap!(Array!long, "a < b");
    long tmp = 0;
    long ans = 0;

    for (int i = 0; i < N; ) {
        long b = TB[i][1];
        while (i < N && TB[i][1] == b) {
            pq.insert(TB[i][0]);
            tmp += TB[i][0];
            if (pq.length > K) {
                tmp -= pq.front;
                pq.removeFront;
            }
            ++i;
        }
        ans = max(ans, tmp * b);
    }

    ans.writeln;
}


You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears:  Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one;  Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows:  Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$;  then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$;  then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$;  then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$;  and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.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. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		alias Segment = Tuple !(int, q{len}, int, q{start});
		auto t = redBlackTree !(Segment);
		t.insert (Segment (-(n - 1), 0));
		auto a = new int [n];
		foreach (i; 0..n)
		{
			auto lo = t.front.start;
			auto hi = t.front.start - t.front.len;
			t.removeFront ();
			auto me = (lo + hi) / 2;
			a[me] = i + 1;
			t.insert (Segment (-(me - lo - 1), lo));
			t.insert (Segment (-(hi - me - 1), me + 1));
		}
		writefln !("%(%s %)") (a);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		BinaryHeap!(Array!(int[]), "a[1]-a[0] == b[1]-b[0] ? a[0] > b[0] : a[1]-a[0] < b[1]-b[0]") heap;
		heap.insert([0, n]);
		int i = 1;
		while (!heap.empty)
		{
			auto nd = heap.front; heap.popFront;
			auto l = nd[0];
			auto r = nd[1];
			auto m = (l+r-1)/2;
			ans[ti][m] = i;
			++i;
			if (r-l == 1) continue;
			else if (r-l == 2)
			{
				heap.insert([m+1, r]);
			}
			else
			{
				heap.insert([l, m]);
				heap.insert([m+1, r]);
			}
		}
	}

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


Alice and Bob are playing a game. They have an array of positive integers $$$a$$$ of size $$$n$$$.Before starting the game, Alice chooses an integer $$$k \ge 0$$$. The game lasts for $$$k$$$ stages, the stages are numbered from $$$1$$$ to $$$k$$$. During the $$$i$$$-th stage, Alice must remove an element from the array that is less than or equal to $$$k - i + 1$$$. After that, if the array is not empty, Bob must add $$$k - i + 1$$$ to an arbitrary element of the array. Note that both Alice's move and Bob's move are two parts of the same stage of the game. If Alice can't delete an element during some stage, she loses. If the $$$k$$$-th stage ends and Alice hasn't lost yet, she wins.Your task is to determine the maximum value of $$$k$$$ such that Alice can win if both players play optimally. Bob plays against Alice, so he tries to make her lose the game, if it's possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$).

For each test case, print one integer — the maximum value of $$$k$$$ such that Alice can win if both players play optimally.

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

// returns true if Alice wins
bool solve(int[] a, int k)
{
  foreach_reverse (i ; 1 .. k + 1) {
    // Alice turn
    while (a.length > 0 && a.back > i)
      a = a[0 .. $ - 1];
    if (a.empty)
      return false;
    a = a[0 .. $ - 1];
    if (a.length > 0)
      a = a[1 .. $];
  }
  return true;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.splitter.map!(to!int).array.sort.array;
    writeln(iota(0, n + 105).map!(k => !solve(a, k)).assumeSorted.lowerBound(true).length - 1);
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);

		bool ok (int k)
		{
			int cur = k;
			int pos = 0;
			for (int i = n - 1; i >= pos; i--)
			{
				if (i < pos)
				{
					break;
				}
				if (a[i] <= cur)
				{
					cur -= 1;
					pos += 1;
				}
			}
			return cur == 0;
		}

		int lo = 0;
		int hi = n + 1;
		while (hi - lo > 1)
		{
			int me = (lo + hi) / 2;
			if (ok (me))
			{
				lo = me;
			}
			else
			{
				hi = me;
			}
		}
		writeln (lo);
	}
}

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

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

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

    bool C(int k) {
        auto X = A.dup;
        sort!"a>b"(X);
        int i = 0, j = N;
        for (int t = k; t >= 1; t--) {
            while (i < j && X[i] > t) {
                i++;
            }
            if (i >= j) return false;
            i++;
            // turn of B
            j--;
        }
        return true;
    }

    for (int k = 1; ; k++) {
        if (! C(k)) {
            writeln(k - 1);
            return;
        }
    }

}

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

// returns tru if Alice wins
bool solve(int[] a, int k)
{
  foreach_reverse (i ; 1 .. k + 1) {
    // Alice turn
    while (a.length > 0 && a.back > k)
      a = a[0 .. $ - 1];
    if (a.empty)
      return false;
    a = a[0 .. $ - 1];
    // Bob turn
    if (a.length > 0)
      a = a[1 .. $];
  }
  return true;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.splitter.map!(to!int).array.sort.array;
    int k = 0;
    while (solve(a, k)) {
      k++;
    }
    writeln(k - 1);
  }
}

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

// returns tru if Alice wins
bool solve(int[] a, int k)
{
  foreach_reverse (i ; 1 .. k + 1) {
    // Alice turn
    while (a.length > 0 && a.back > k)
      a = a[0 .. $ - 1];
    if (a.empty)
      return false;
    a = a[0 .. $ - 1];
    if (a.length > 0)
      a = a[1 .. $];
  }
  return true;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.splitter.map!(to!int).array.sort.array;
    writeln(iota(0, n + 105).map!(k => !solve(a, k)).assumeSorted.lowerBound(true).length - 1);
  }
}

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

// returns tru if Alice wins
bool solve(int[] a, int k)
{
  foreach_reverse (i ; 1 .. k + 1) {
    while (a.length > 0 && a.back > k)
      a = a[0 .. $ - 1];
    if (a.empty)
      return false;
    a = a[0 .. $ - 1];
    if (a.length > 0)
      a = a[1 .. $];
  }
  return true;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.splitter.map!(to!int).array.sort.array;
    writeln(iota(1, n + 5).map!(k => !solve(a, k)).assumeSorted.lowerBound(true).length);
  }
}


Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second.The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.

The first line of the input contains a single integer l (1 ≤ l ≤ 1 000) — the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≤ p, q ≤ 500) — the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively.

Print a single real number — the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4.  Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .

NoteIn the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor.

import std.stdio;
import std.string;
void main()
{
	double a,b,c;
	readf("%f\n%f\n%f\n",&a,&b,&c);
	writeln(a*b/(b+c));
}

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                double l = cin.readDouble;
                double p = cin.readDouble;
                double q = cin.readDouble;
                writeln(p * (l / (p + q)));

        }
}

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

void main ()
{
    int l, p, q;
    while (readf (" %s %s %s", &l, &p, &q) > 0)
    {
        writeln (l * p * 1.0 / (p + q));
    }
}


You are given a string $$$s$$$ consisting of $$$n$$$ characters. Each character of $$$s$$$ is either 0 or 1.A substring of $$$s$$$ is a contiguous subsequence of its characters.You have to choose two substrings of $$$s$$$ (possibly intersecting, possibly the same, possibly non-intersecting — just any two substrings). After choosing them, you calculate the value of the chosen pair of substrings as follows:  let $$$s_1$$$ be the first substring, $$$s_2$$$ be the second chosen substring, and $$$f(s_i)$$$ be the integer such that $$$s_i$$$ is its binary representation (for example, if $$$s_i$$$ is 11010, $$$f(s_i) = 26$$$);  the value is the bitwise OR of $$$f(s_1)$$$ and $$$f(s_2)$$$. Calculate the maximum possible value you can get, and print it in binary representation without leading zeroes.

The first line contains one integer $$$n$$$ — the number of characters in $$$s$$$. The second line contains $$$s$$$ itself, consisting of exactly $$$n$$$ characters 0 and/or 1. All non-example tests in this problem are generated randomly: every character of $$$s$$$ is chosen independently of other characters; for each character, the probability of it being 1 is exactly $$$\frac{1}{2}$$$. This problem has exactly $$$40$$$ tests. Tests from $$$1$$$ to $$$3$$$ are the examples; tests from $$$4$$$ to $$$40$$$ are generated randomly. In tests from $$$4$$$ to $$$10$$$, $$$n = 5$$$; in tests from $$$11$$$ to $$$20$$$, $$$n = 1000$$$; in tests from $$$21$$$ to $$$40$$$, $$$n = 10^6$$$.  Hacks are forbidden in this problem.

Print the maximum possible value you can get in binary representation without leading zeroes.

NoteIn the first example, you can choose the substrings 11010 and 101. $$$f(s_1) = 26$$$, $$$f(s_2) = 5$$$, their bitwise OR is $$$31$$$, and the binary representation of $$$31$$$ is 11111.In the second example, you can choose the substrings 1110010 and 11100.

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

int[] solve(int[] a, int[] n2)
{
  int[] offs;
  foreach (i ; 0 .. cast(int)n2.length)
    if (n2[i])
      offs ~= i;
  int best_i = -1, best_score = -1;
  foreach (i ; 0 .. cast(int)(a.length - n2.length + 1)) {
    int score = 0;
    foreach (j ; offs) {
      if (a[i + j] == 1)
        score++;
      else
        break;
    }
    if (score > best_score) {
      best_i = i;
      best_score = score;
    } else if (score == best_score) {
      bool better = false;
      foreach (j ; offs[score .. $]) {
        if (a[i + j] == a[best_i + j])
          continue;
        if (a[i + j] == 1)
          better = true;
        break;
      }
      if (better) {
        best_i = i;
        best_score = score;
      }
    }
  }
  return a[best_i .. best_i + n2.length];
}

void main()
{
  long n;
  readf!" %d "(n);
  auto a = readln.strip.splitter("").map!(to!int).array;
  auto n1 = a.find(1).array;
  auto n2 = n1.map!(x => x ^ 1).find(1).array;

  if (n1.empty) {
    writeln(0);
    return;
  }

  while (true) {
    if (n2.empty)
      break;
    auto tmp = solve(a, n2);
    if (tmp[0] == 0) {
      n2 = n2[1 .. $];
      while (!n2.empty && n2[0] == 0)
        n2 = n2[1 .. $];
    } else {
      foreach (i ; 0 .. tmp.length) {
        n1[$ - i - 1] |= tmp[$ - i - 1];
      }
      break;
    }
  }

  writeln(n1.map!text.joiner(""));
}

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

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

void main() {
    int N = read!int;
    auto s = read!string;

    //auto rmlz() {
    {
        int k = 0;
        while (s[k] == '0' && k < N - 1) k++;
        s = s[k .. $];
    }
    N = cast(int)(s.length);

    int lo = 0;
    for (int i = 0; i < N; i++) {
        if (s[i] == '1') {
            lo++;
        } else {
            break;
        }
    }

    string f(string b) {
        char z(char x, char y) {
            if (x == '1' || y == '1') return '1';
            else return '0';
        }
        int m = cast(int)(b.length);
        auto r = new char[N];
        for (int i = 0; i < N; i++) {
            if (i < N - m) {
                r[i] = s[i] ;
            } else {
                r[i] = z(s[i], b[i - N + m]);
            }
        }
        return r.idup;
    }

    string ans = s;
    for (int k = 1; k <= lo; k++) {
        auto s2 = s[0 .. $ - k];
        auto cand = f(s2);
        ans = max(ans, cand);
    }

    writeln(ans);
}

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

int[] solve(int[] a, int[] n2)
{
  int[] offs;
  foreach (i ; 0 .. cast(int)n2.length)
    if (n2[i])
      offs ~= i;
  int best_i = -1, best_score = -1;
  foreach (i ; 0 .. cast(int)(a.length - n2.length + 1)) {
    int score = 0;
    foreach (j ; offs) {
      if (a[i + j] == 1)
        score++;
      else
        break;
    }
    if (score > best_score) {
      best_i = i;
      best_score = score;
    }
  }
  return a[best_i .. best_i + n2.length];
}

void main()
{
  long n;
  readf!" %d "(n);
  auto a = readln.strip.splitter("").map!(to!int).array;
  auto n1 = a.find(1).array;
  auto n2 = n1.map!(x => x ^ 1).find(1).array;

  if (n1.empty) {
    writeln(0);
    return;
  }

  while (true) {
    if (n2.empty)
      break;
    auto tmp = solve(a, n2);
    if (tmp[0] == 0) {
      n2 = n2[1 .. $];
      while (!n2.empty && n2[0] == 0)
        n2 = n2[1 .. $];
    } else {
      foreach (i ; 0 .. tmp.length) {
        n1[$ - i - 1] |= tmp[$ - i - 1];
      }
      break;
    }
  }

  writeln(n1.map!text.joiner(""));
}

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

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

void main() {
    int N = read!int;
    auto s = read!string;

    int lo = 0;
    for (int i = 0; i < N; i++) {
        if (s[i] == '1') {
            lo++;
        } else {
            break;
        }
    }

    string f(string b) {
        char z(char x, char y) {
            if (x == '1' || y == '1') return '1';
            else return '0';
        }
        int m = cast(int)(b.length);
        auto r = new char[N];
        for (int i = 0; i < N; i++) {
            if (i < N - m) {
                r[i] = s[i] ;
            } else {
                r[i] = z(s[i], b[i - N + m]);
            }
        }
        return r.idup;
    }

    string ans = s;
    for (int k = 1; k <= lo; k++) {
        auto s2 = s[0 .. $ - k];
        auto cand = f(s2);
        ans = max(ans, cand);
    }
    writeln(ans);
}


When Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions:   There is no vertex that has more than two incident edges painted the same color.  For any two vertexes that have incident edges painted the same color (say, c), the path between them consists of the edges of the color c. Not all tree paintings are equally good for Adam. Let's consider the path from some vertex to the root. Let's call the number of distinct colors on this path the cost of the vertex. The cost of the tree's coloring will be the maximum cost among all the vertexes. Help Adam determine the minimum possible cost of painting the tree. Initially, Adam's tree consists of a single vertex that has number one and is the root. In one move Adam adds a new vertex to the already existing one, the new vertex gets the number equal to the minimum positive available integer. After each operation you need to calculate the minimum cost of coloring the resulting tree.

The first line contains integer n (1 ≤ n ≤ 106) — the number of times a new vertex is added. The second line contains n numbers pi (1 ≤ pi ≤ i) — the numbers of the vertexes to which we add another vertex.

Print n integers — the minimum costs of the tree painting after each addition.

NoteThe figure below shows one of the possible variants to paint a tree from the sample at the last moment. The cost of the vertexes with numbers 11 and 12 equals 3.

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

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

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

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

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

int N;
int[] P;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt + 1;
		P = new int[N];
		P[0] = -1;
		foreach (u; 1 .. N) {
			P[u] = readInt - 1;
		}

		int[] ans = new int[N];
		int[] dp = new int[N];
		auto bests = new Pair!(int, int)[][](N, 2);

		foreach (u; 1 .. N) {
debug{
writeln("u = ",u);
writeln("dp = ",dp);
writeln("bests = ",bests);
}
			dp[u] = 1;
			bests[u][] = pair(0, -1);
			for (int v = u; v != 0; v = P[v]) {
				auto bp = bests[P[v]];
				foreach (j; 0 .. 2) {
					if (bp[j].y == v) {
						bp[j].x = -1;
					}
				}
				if (bp[0] < bp[1]) {
					swap(bp[0], bp[1]);
				}
				auto tmp = pair(dp[v], v);
				foreach (j; 0 .. 2) {
					if (bp[j] < tmp) {
						bp[j].swap(tmp);
					}
				}
				const nxt = max(bp[0].x, bp[1].x + 1);
				if (dp[P[v]] == nxt) {
					break;
				}
				dp[P[v]] = nxt;
			}
			ans[u] = bests[0][0].x;
		}

		writeln(ans[1 .. N].to!string.removechars("[],"));
	}
	} catch (EOFException) {}
}


Little Dormi received a histogram with $$$n$$$ bars of height $$$a_1, a_2, \ldots, a_n$$$ for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.To modify the histogram, Little Dormi is able to perform the following operation an arbitrary number of times: Select an index $$$i$$$ ($$$1 \le i \le n$$$) where $$$a_i>0$$$, and assign $$$a_i := a_i-1$$$.Little Dormi defines the ugliness score of his histogram (after performing some number of operations) as the sum of the vertical length of its outline and the number of operations he performed on it. And to make the histogram as perfect as possible, he would like to minimize the ugliness score after modifying it with some number of operations.However, as his histogram is very large, Little Dormi is having trouble minimizing the ugliness score, so as Little Dormi's older brother, help him find the minimal ugliness.Consider the following example where the histogram has $$$4$$$ columns of heights $$$4,8,9,6$$$:  The blue region represents the histogram, and the red lines represent the vertical portion of the outline. Currently, the vertical length of the outline is $$$4+4+1+3+6 = 18$$$, so if Little Dormi does not modify the histogram at all, the ugliness would be $$$18$$$.However, Little Dormi can apply the operation once on column $$$2$$$ and twice on column $$$3$$$, resulting in a histogram with heights $$$4,7,7,6$$$:  Now, as the total vertical length of the outline (red lines) is $$$4+3+1+6=14$$$, the ugliness is $$$14+3=17$$$ dollars. It can be proven that this is optimal.

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

For each test case output one integer, the minimal ugliness Little Dormi can achieve with the histogram in that test case.

NoteExample $$$1$$$ is the example described in the statement.The initial histogram for example $$$2$$$ is given below:  The ugliness is currently $$$2+1+6+3+4=16$$$.By applying the operation once on column $$$1$$$, six times on column $$$3$$$, and three times on column $$$4$$$, we can end up with a histogram with heights $$$1,1,1,1,0,0$$$:  The vertical length of the outline is now $$$1+1=2$$$ and Little Dormi made $$$1+6+3=10$$$ operations, so the final ugliness is $$$2+10=12$$$, which can be proven to be optimal.

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

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.chomp.split.map!(to!int).array;
    int[] b = [0] ~ a ~ [0];
    long result = 0;
    foreach (i ; 1 .. b.length - 1) {
      int diff_l = b[i] - b[i - 1];
      int diff_r = b[i] - b[i + 1];
      if (diff_l > 0 && diff_r > 0) {
        b[i] -= min(diff_l, diff_r);
        result += min(diff_l, diff_r);
      }
    }
    foreach (i ; 1 .. b.length) {
      result += abs(b[i] - b[i - 1]);
    }
    writeln(result);
  }
}

import std.stdio;
import std.math;
import std.ascii;
import std.algorithm;
import std.range;
import core.stdc.stdio;

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
void solve()
{
	int n = readInt!int;
	auto a = new int[](n);
	foreach(ref ai; a) ai = readInt!int;
	a = 0 ~ a ~ 0;
	long ops = 0;
	long border = 0;
	foreach(i; 1 .. n + 1)
	{
		if (a[i] > a[i - 1] && a[i] > a[i + 1])
		{
			debug writeln("reducing ", i, " ", a[i]);
			int s = max(a[i - 1], a[i + 1]);
			ops += a[i] - s;
			a[i] = cast(int)s;
		}
		border += abs(a[i - 1] - a[i]);
	}
	border += a[n];
	(border + ops).writeln;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

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

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

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
multitest_end:
  while(tests--) {
    int n; readf!"%s\n"(n);
    int[] a = readln.splitter.map!(to!int).array;
    long res = 0;
    foreach(i; 0 .. n) {
      int low = 0;
      if(i > 0) {
        low = max(low, a[i - 1]);
      }
      if(i + 1 < n) {
        low = max(low, a[i + 1]);
      }
      int delta = max(0, a[i] - low);
      a[i] -= delta;
      res += delta;
    }
    res += a[0];
    res += a[n - 1];
    foreach(i; 1 .. n) {
      res += abs(a[i] - a[i - 1]);
    }
    res.writeln;
  }

} // main

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		long res = 0;
		foreach (i; 0..n)
		{
			auto lo = 0;
			if (i > 0)
			{
				lo = max (lo, a[i - 1]);
			}
			if (i + 1 < n)
			{
				lo = max (lo, a[i + 1]);
			}
			int delta = max (0, a[i] - lo);
			a[i] -= delta;
			res += delta;
		}
		debug {writeln (a, " ", res);}
		res += a[0];
		res += a[n - 1];
		foreach (i; 1..n)
		{
			res += abs (a[i] - a[i - 1]);
		}
		writeln (res);
	}
}


Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second.Scrooge signed exactly k papers throughout his life and all those signatures look the same.Find the total time Scrooge wasted signing the papers.

The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 1000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai — integers xi and yi, separated by a space. All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.

Print one real number — the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10 - 6.

import std.stdio;
import std.math;

void main() {
    int n, k; scanf("%u %u", &n, &k);
    double t = 0;
    double x, y, px, py;
    scanf("%lf %lf", &px, &py);
    foreach (i; 1 .. n) {
        scanf("%lf %lf", &x, &y);
        double dx = abs(x - px);
        double dy = abs(y - py);
        t += sqrt(dx * dx + dy * dy);
        px = x; py = y;
    }
    printf("%.9f\n", t / 50 * k);
}

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

double dist(int x1, int y1, int x2, int y2) {
        double dist = sqrt((x1.to!double - x2.to!double) ^^ 2 + (y1.to!double - y2.to!double) ^^ 2).to!double;
        return dist;
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt();
                int k = cin.readInt();
                int[][] points = new int[][](n, 2);
                for (int i = 0; i < n; i++) {
                        int a = cin.readInt;
                        int b = cin.readInt;
                        points[i][0] = a;
                        points[i][1] = b;
                }
                double totalDistance = 0;
                for (int i = 1; i < n; i++) {
                        totalDistance += dist(points[i][0], points[i][1], points[i - 1][0], points[i - 1][1]);
                }
                double time = k * cast(double)(totalDistance / 50.0);
                writefln("%.9f", time);
        }
}