A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $$$v$$$ (different from root) is the previous to $$$v$$$ vertex on the shortest path from the root to the vertex $$$v$$$. Children of the vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent.A vertex is a leaf if it has no children. We call a vertex a bud, if the following three conditions are satisfied:   it is not a root,  it has at least one child, and  all its children are leaves. You are given a rooted tree with $$$n$$$ vertices. The vertex $$$1$$$ is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud.What is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of the vertices in the given tree. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) meaning that there is an edge between vertices $$$u$$$ and $$$v$$$ in the tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer — the minimal number of leaves that is possible to get after some operations.

NoteIn the first test case the tree looks as follows:  Firstly you can choose a bud vertex $$$4$$$ and re-hang it to vertex $$$3$$$. After that you can choose a bud vertex $$$2$$$ and re-hang it to vertex $$$7$$$. As a result, you will have the following tree with $$$2$$$ leaves:  It can be proved that it is the minimal number of leaves possible to get.In the second test case the tree looks as follows:  You can choose a bud vertex $$$3$$$ and re-hang it to vertex $$$5$$$. As a result, you will have the following tree with $$$2$$$ leaves:  It can be proved that it is the minimal number of leaves possible to get.

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

immutable int NA = -1;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto adj = new int [] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}
		readln;

		int leaves = 0;
		int cuts = 0;
		int start = 1;

		int recur (int v, int p)
		out (res)
		{
			debug {writeln (v + 1, "<=", p + 1, ": ", res);}
		}
		body
		{
			int depth = 0;
			foreach (u; adj[v])
			{
				if (u == p)
				{
					continue;
				}
				int cur = recur (u, v) + 1;
				depth = max (depth, cur);
			}
			if (depth == 0 && p != NA)
			{
				leaves += 1;
				debug {writeln ("leaf ", v + 1);}
				if (p == 0)
				{
					start = 0;
					debug {writeln ("start ", v + 1);}
				}
			}
			if (depth == 1 && p != NA)
			{
				cuts += 1;
				debug {writeln ("cut ", v + 1);}
				return NA;
			}
			return depth;
		}

		recur (0, NA);

		writeln (leaves - cuts + start);
	}
}


You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that:  each digit is painted either in the color $$$1$$$ or in the color $$$2$$$;  if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$.

Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign).

NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits.

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return read.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtype!real;
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void solve(){
	int t = rint;

	A:
	foreach(_; 0 .. t){

		int n = rint;
		char[] cs = read.to!(char[]);

		int[] as;
		foreach(c; cs) as ~= ("" ~ c).to!int;

		string ans = "-";
		foreach(k; 0 .. 9){
			int u = 0, v = k;
			int isOK = 1;
			string tempans = "";
			foreach(a; as){
				if(a >= v){
					tempans ~= "2";
					if(a > v) v = a;
				}
				else if(a <= k && a >= u){
					tempans ~= "1";
					if(a > u) u = a;
				}
				else{
					isOK = 0;
					break;
				}
				log("cs:", cs, "k:", k, "a:", a, "u:", u, "v:", v, "tempans:", tempans);
			}
			if(isOK){
				ans = tempans;
				break;
			}
		}
		ans.writeln;
	}
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new char[][](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto d = RD!string;
		auto e = new long[](n);
		foreach (j, c; d)
		{
			e[j] = [c].to!long;
		}
		auto index = new size_t[](e.length);
		makeIndex!("a < b", SwapStrategy.stable)(e, index);
		size_t[] a1 = [index[0]], a2;
		bool ok = true;
		foreach (j; index[1..$])
		{
			if (a2.empty)
			{
				if (j >= a1.back)
					a1 ~= j;
				else
					a2 ~= j;
			}
			else
			{
				if (j >= a1.back && e[j] == e[a2.front])
					a1 ~= j;
				else if (j >= a2.back)
					a2 ~= j;
				else
				{
					ok = false;
					break;
				}
			}
		}
		debug writeln(a1, a2);
		if (ok)
		{
			ans[i] = new char[](n);
			if (a2.empty)
			{
				foreach (j; 0..n) ans[i][j] = '1';
			}
			else
			{
				foreach (j; a1)
				{
					ans[i][j] = '1';
				}
				foreach (j; a2)
				{
					ans[i][j] = '2';
				}
			}
		}
		else
			ans[i] = "-".dup;
	}

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

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return read.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtype!real;
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void solve(){
	int t = rint;

	A:
	foreach(_; 0 .. t){

		int n = rint;
		char[] cs = read.to!(char[]);

		int a = 0, b = 0;
		string ans = "";
		foreach(c; cs){
			int x = ("" ~ c).to!int;
			if(b <= c) b = c, ans ~= "2";
			else if(a <= c) a = c, ans ~= "1";
			else{
				"-".writeln;
				continue A;
			}
		}
		ans.writeln;
	}
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new char[][](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto d = RD!string;
		auto e = new long[](n);
		foreach (j, c; d)
		{
			e[j] = [c].to!long;
		}
		auto index = new size_t[](e.length);
		makeIndex!("a < b", SwapStrategy.stable)(e, index);
		size_t[] a1 = [index[0]], a2;
		bool ok = true;
		foreach (j; index[1..$])
		{
			if (j >= a1.back)
				a1 ~= j;
			else if (a2.empty)
				a2 ~= j;
			else if (j >= a2.back)
				a2 ~= j;
			else
			{
				ok = false;
				break;
			}
		}
		debug writeln(a1, a2);
		if (ok)
		{
			ans[i] = new char[](n);
			if (a2.empty)
			{
				foreach (j; 0..n) ans[i][j] = '1';
			}
			else
			{
				foreach (j; a1)
				{
					ans[i][j] = '1';
				}
				foreach (j; a2)
				{
					ans[i][j] = '2';
				}
			}
		}
		else
			ans[i] = "-".dup;
	}

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


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by $$$2$$$) or determine that there is no such subset.Both the given array and required subset may contain equal values.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$), number of test cases to solve. Descriptions of $$$t$$$ test cases follow. A description of each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$), length of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$), elements of $$$a$$$. The given array $$$a$$$ can contain equal values (duplicates).

For each test case output $$$-1$$$ if there is no such subset of elements. Otherwise output positive integer $$$k$$$, number of elements in the required subset. Then output $$$k$$$ distinct integers ($$$1 \leq p_i \leq n$$$), indexes of the chosen elements. If there are multiple solutions output any of them.

NoteThere are three test cases in the example.In the first test case, you can choose the subset consisting of only the second element. Its sum is $$$4$$$ and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		readf(" %d", &a);
		int[] m = new int[a];
		for (int j=0; j<a; j++)
		{
			readf(" %d", &m[j]);
		}
		if (a==1 && m[0]%2==1)
		{
			writeln(-1);
		}
		else
		{
			int count=0;
			for (int j=0; j<a; j++)
			{
				if (m[j]%2==0)
				{
					count=count+1;
					writeln(1);
					writeln(j+1);
					break;
				}
			}
			if (count==0)
			{
				writeln(2);
				writeln(1);
				writeln(2);
			}
		}
	}
	return 0;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		foreach (i; 0..n)
		{
			if (a[i] % 2 == 0)
			{
				ans[ti] = [i+1];
				break;
			}
		}
		if (!ans[ti].empty) continue;
		foreach (i; 0..n)
		{
			if (a[i] % 2)
			{
				ans[ti] ~= i+1;
			}
		}
		if (ans[ti].length == 1)
			ans[ti].length = 0;
		else
			ans[ti] = ans[ti][0..2];
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln(-1);
		else
		{
			writeln(e.length);
			e.map!(to!string).join(" ").writeln;
		}
	}
	stdout.flush;
	debug readln;
}


Alice is playing with some stones.Now there are three numbered heaps of stones. The first of them contains $$$a$$$ stones, the second of them contains $$$b$$$ stones and the third of them contains $$$c$$$ stones.Each time she can do one of two operations:  take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones);  take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones). She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $$$0$$$ stones. Can you help her?

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. Next $$$t$$$ lines describe test cases in the following format: Line contains three non-negative integers $$$a$$$, $$$b$$$ and $$$c$$$, separated by spaces ($$$0 \leq a,b,c \leq 100$$$) — the number of stones in the first, the second and the third heap, respectively. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.

Print $$$t$$$ lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer  — the maximum possible number of stones that Alice can take after making some operations.

NoteFor the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is $$$9$$$. It is impossible to make some operations to take more than $$$9$$$ stones, so the answer is $$$9$$$.

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;

struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}

Input input;

void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto brange(alias low, alias high, alias pred, bool value)()
{
  return iota(low, high + 1).map!((a) => cast(int) pred(a)).assumeSorted.equalRange(value);
}
auto ftrue(alias low, alias high, alias pred)()
{
  return brange!(low, high, pred, false).length + low;
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t;
      get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
struct ModNum(T)
{
  T representative, modulus;
  this(T representative, T modulus)
  {
    this.representative = representative;
    this.modulus = modulus;
  }
  T minimalPositiveRepresentative()
  {
    return ((representative % modulus) + modulus) % modulus;
  }
  T minimalNegativeRepresentative()
  {
    return ((representative % modulus) - modulus) % modulus;
  }
  T maxRepresentative(T upperBound)
  {
    return upperBound - pmod(upperBound - representative, modulus);
  }
  T minRepresentative(T lowerBound)
  {
    return lowerBound + pmod(representative - lowerBound, modulus);
  }
}
// minimum possible representative of x modulo m.
T pmod(T)(T x, T m)
{
  return (x % m + m) % m;
}
// solves ax + by = gcd(a, b) and returns gcd(a, b)
T extendedEuclideanAlgorithm(T)(T a, T b, out T x, out T y)
{
  if (a == 0)
    {
      x = 0, y = 1;
      return b;
    }
  T x1, y1;
  auto d = egcd(b % a, a, x1, y1);
  x = y1 - (b / a) * x1, y = x1;
  return d;
}
alias egcd = extendedEuclideanAlgorithm;
// solves ax = b (mod m) giving a solution as a modulus class.
bool solveLinearCongruence(T)(T a, T b, T m, out ModNum!T res)
{
  T x, p;
  b = pmod(b, m);
  T y;
  T g = egcd(a, m, x, y);
  if (b % g != 0)
    return false;
  p = m / g;
  x = pmod(x * b / g, p);
  res.representative = x;
  res.modulus = p;
  return true;
}

void main()
{
  // a - x >= 0
  // b - y - 2x >= 0
  // b - 2y >= 0

  alias ln = int;
  ln t; get(t);
  while(t--)
    {
      ln a, b, c; get(a, b, c);
      ln mx = 0;
      for(ln x = 0; x <= a; x++)
	{
	  for(ln y = 0; c - 2 * y >= 0; y++)
	    {
	      if ( b - y - 2 * x >= 0)
		{
		  mx = max(mx, x + y + 2 * x + 2 * y);
		}
	    }
	}
      wr(mx);    }
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (i; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto c = RD;
		auto cnt1 = min(c/2, b);
		auto cnt2 = min((b-cnt1)/2, a);
		ans[i] = (cnt1+cnt2) * 3;
	}

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

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;

struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}

Input input;

void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto brange(alias low, alias high, alias pred, bool value)()
{
  return iota(low, high + 1).map!((a) => cast(int) pred(a)).assumeSorted.equalRange(value);
}
auto ftrue(alias low, alias high, alias pred)()
{
  return brange!(low, high, pred, false).length + low;
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t;
      get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
struct ModNum(T)
{
  T representative, modulus;
  this(T representative, T modulus)
  {
    this.representative = representative;
    this.modulus = modulus;
  }
  T minimalPositiveRepresentative()
  {
    return ((representative % modulus) + modulus) % modulus;
  }
  T minimalNegativeRepresentative()
  {
    return ((representative % modulus) - modulus) % modulus;
  }
  T maxRepresentative(T upperBound)
  {
    return upperBound - pmod(upperBound - representative, modulus);
  }
  T minRepresentative(T lowerBound)
  {
    return lowerBound + pmod(representative - lowerBound, modulus);
  }
}
// minimum possible representative of x modulo m.
T pmod(T)(T x, T m)
{
  return (x % m + m) % m;
}
// solves ax + by = gcd(a, b) and returns gcd(a, b)
T extendedEuclideanAlgorithm(T)(T a, T b, out T x, out T y)
{
  if (a == 0)
    {
      x = 0, y = 1;
      return b;
    }
  T x1, y1;
  auto d = egcd(b % a, a, x1, y1);
  x = y1 - (b / a) * x1, y = x1;
  return d;
}
alias egcd = extendedEuclideanAlgorithm;
// solves ax = b (mod m) giving a solution as a modulus class.
bool solveLinearCongruence(T)(T a, T b, T m, out ModNum!T res)
{
  T x, p;
  b = pmod(b, m);
  T y;
  T g = egcd(a, m, x, y);
  if (b % g != 0)
    return false;
  p = m / g;
  x = pmod(x * b / g, p);
  res.representative = x;
  res.modulus = p;
  return true;
}

void main()
{
  // a - x >= 0
  // b - y - 2x >= 0
  // b - 2y >= 0

  alias ln = int;
  ln t; get(t);
  while(t--)
    {
      ln a, b, c; get(a, b, c);
      ln mx = 0;
      for(ln x = 0; x <= a; x++)
	{
	  for(ln y = 0; 2 * y <= b; y++)
	    {
	      if ( b - y - 2 * x >= 0 && c - 2 * y >= 0)
		{
		  mx = max(mx, x + y + 2 * x + 2 * y);
		}
	    }
	}
      wr(mx);    }
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;

struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}

Input input;

void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto brange(alias low, alias high, alias pred, bool value)()
{
  return iota(low, high + 1).map!((a) => cast(int) pred(a)).assumeSorted.equalRange(value);
}
auto ftrue(alias low, alias high, alias pred)()
{
  return brange!(low, high, pred, false).length + low;
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t;
      get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
struct ModNum(T)
{
  T representative, modulus;
  this(T representative, T modulus)
  {
    this.representative = representative;
    this.modulus = modulus;
  }
  T minimalPositiveRepresentative()
  {
    return ((representative % modulus) + modulus) % modulus;
  }
  T minimalNegativeRepresentative()
  {
    return ((representative % modulus) - modulus) % modulus;
  }
  T maxRepresentative(T upperBound)
  {
    return upperBound - pmod(upperBound - representative, modulus);
  }
  T minRepresentative(T lowerBound)
  {
    return lowerBound + pmod(representative - lowerBound, modulus);
  }
}
// minimum possible representative of x modulo m.
T pmod(T)(T x, T m)
{
  return (x % m + m) % m;
}
// solves ax + by = gcd(a, b) and returns gcd(a, b)
T extendedEuclideanAlgorithm(T)(T a, T b, out T x, out T y)
{
  if (a == 0)
    {
      x = 0, y = 1;
      return b;
    }
  T x1, y1;
  auto d = egcd(b % a, a, x1, y1);
  x = y1 - (b / a) * x1, y = x1;
  return d;
}
alias egcd = extendedEuclideanAlgorithm;
// solves ax = b (mod m) giving a solution as a modulus class.
bool solveLinearCongruence(T)(T a, T b, T m, out ModNum!T res)
{
  T x, p;
  b = pmod(b, m);
  T y;
  T g = egcd(a, m, x, y);
  if (b % g != 0)
    return false;
  p = m / g;
  x = pmod(x * b / g, p);
  res.representative = x;
  res.modulus = p;
  return true;
}

void main()
{
  // a - x >= 0
  // b - y - 2x >= 0
  // b - 2y >= 0

  alias ln = int;
  ln t; get(t);
  while(t--)
    {
      ln a, b, c; get(a, b, c);
      ln mx = 0;
      for(ln x = 0; x <= a; x++)
	{
	  for(ln y = 0; 2 * y <= b; y++)
	    {
	      if ( b - y - 2 * x >= 0 && b - 2 * y >= 0)
		{
		  mx = max(mx, x + y + 2 * x + 2 * y);
		}
	    }
	}
      wr(mx);
    }
}


A number is called 2050-number if it is $$$2050$$$, $$$20500$$$, ..., ($$$2050 \cdot 10^k$$$ for integer $$$k \ge 0$$$).Given a number $$$n$$$, you are asked to represent $$$n$$$ as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.

The first line contains a single integer $$$T$$$ ($$$1\le T\leq 1\,000$$$) denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^{18}$$$) denoting the number to be represented.

For each test case, output the minimum number of 2050-numbers in one line.  If $$$n$$$ cannot be represented as the sum of 2050-numbers, output $$$-1$$$ instead.

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 n= to!long(readln().chomp);
    foreach(_; 0..n)
    {
        auto param = readln().chomp;
        long d = to!long(param);

        if(d % 2050 != 0)
        {
            writeln(-1);
        }
        else
        {
            long m = d / 2050;
            long sum = 0;
            while(m  > 0)
            {
                sum += (m%10);
                m /= 10;
            }

            writeln(sum);
        }
    }
}

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

immutable int base = 2050;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(long);
		if (n % base != 0)
		{
			writeln (-1);
		}
		else
		{
			n /= base;
			writeln (n.text.map !(q{a - '0'}).sum);
		}
	}
}

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

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

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

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

enum A = 2050L;

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

        long ans;
        if (N % A == 0) {
          for (long m = N / A; m > 0; m /= 10) {
            ans += m % 10;
          }
        } else {
          ans = -1;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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 n= to!long(readln().chomp);
    foreach(_; 0..n)
    {
        auto param = readln().chomp;
        real d = to!real(param);
        if(d < 2050)
        {
         writeln(-1);
         continue;
        }
        real m = 2050 * pow(10, ceil(log10(d))-4);
        //writeln(m);
        int c = 0;

        while(d > m)
        {
            d -= m;
            c++;

            if(m > d)
                m /= 10;
        }

        if(d < m)
            writeln(-1);
        else
            writeln(c+1);
    }
}

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 n= to!long(readln().chomp);
    outer : foreach(_; 0..n)
    {
        auto param = readln().chomp;
        long d = to!long(param);
        long m = 2050;

        while(m*10 <= d)
        {
            m = m*10;
        }

        int c = 0;
        while(d >= m)
        {
            d -= m;
            c++;

             if(m > d && m >= 10)
                m /= 10;
        }

        if(d != 0)
        writeln(-1);
        else writeln(c);
    }
}

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 n= to!long(readln().chomp);
    outer : foreach(_; 0..n)
    {
        auto param = readln().chomp;
        long d = to!long(param);
        long m = 2050;

        while(m*10 <= d)
        {
            m = m*10;
        }

        int c = 0;
        while(d >= m)
        {
            d -= m;
            c++;

             if(m > d && m > 10)
                m /= 10;
        }

        if(d != 0)
        writeln(-1);
        else writeln(c);
    }
}

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 n= to!long(readln().chomp);
    foreach(_; 0..n)
    {
        auto param = readln().chomp;
        long d = to!long(param);
        long m = 2050;

        if(d < m || d % m != 0)
        {
            writeln(-1);
            continue;
        }

        long q = d / m;

        while(m*10 <= d)
        {
            m = m*10;
        }

        int c = 0;
        while(d > 0)
        {
            d -= m;
            c++;
             if(m > d)
                m /= 10;

        }

        writeln(c);
    }
}

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 n= to!long(readln().chomp);
    foreach(_; 0..n)
    {
        auto param = readln().chomp;
        long d = to!long(param);
        long m = 2050;

        if(d < m || d % m != 0)
        {
            writeln(-1);
            continue;
        }

        long q = d / m;

        while(m*10 < d)
        {
            m = m*10;
        }

        int c = 0;
        while(d > 0)
        {
            d -= m;
            c++;
             if(m > d)
                m /= 10;

        }

        writeln(c);
    }
}


Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario.  Each one of them has a set of numbers between 1 and n - 1 (inclusive). Rick's set is s1 with k1 elements and Morty's is s2 with k2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins.Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.

The first line of input contains a single integer n (2 ≤ n ≤ 7000) — number of objects in game. The second line contains integer k1 followed by k1 distinct integers s1, 1, s1, 2, ..., s1, k1 — Rick's set. The third line contains integer k2 followed by k2 distinct integers s2, 1, s2, 2, ..., s2, k2 — Morty's set 1 ≤ ki ≤ n - 1 and 1 ≤ si, 1, si, 2, ..., si, ki ≤ n - 1 for 1 ≤ i ≤ 2.

In the first line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end. Similarly, in the second line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Morty plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end.

Win Win Win Win Win Win Win
Lose Win Lose Lose Win Lose Lose

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int [] [] moves;
		foreach (i; 0..2)
		{
			int [] line;
			int k;
			readf (" %s", &k);
			foreach (j; 0..k)
			{
				int v;
				readf (" %s", &v);
				line ~= n - v;
			}
			moves ~= line;
		}

		auto g = new int [] [] (2, n);
		auto c = new int [] [] (2, n);

		alias Pair = Tuple !(int, q{who}, int, q{pos});
		Pair [] q;

		void add (Pair p, int v)
		{
			g[p.who][p.pos] = v;
			c[p.who][p.pos] = n;
			q ~= p;
		}

		add (Pair (0, 0), -1);
		add (Pair (1, 0), -1);

		while (!q.empty)
		{
			auto who = q.front.who;
			auto pos = q.front.pos;
			auto res = g[who][pos];
			q.popFront ();
			q.assumeSafeAppend ();

			foreach (d; moves[!who])
			{
				int next = (pos + d) % n;
				if (g[!who][next] != 0)
				{
					continue;
				}
				if (res == -1)
				{
					add (Pair (!who, next), +1);
				}
				else
				{
					c[!who][next] += 1;
					if (c[!who][next] >=
					    moves[!who].length)
					{
						add (Pair (!who, next), -1);
					}
				}
			}
		}

		foreach (line; g)
		{
			line.drop (1).map !(x =>
			    ["Lose", "Loop", "Win"][x + 1]).join (" ").writeln;
		}
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto K = new int[2];
      auto S = new int[][2];
      foreach (i; 0 .. 2) {
        K[i] = readInt();
        S[i] = new int[K[i]];
        foreach (j; 0 .. K[i]) {
          S[i][j] = readInt();
        }
      }

      auto dp = new int[][](2, N);
      auto cnt = new int[][](2, N);
      foreach (t; 0 .. 2) foreach (u; 0 .. N) {
        dp[t][u] = -1;
        cnt[t][u] = K[t];
      }

      auto que = new int[2 * N * 2];
      int qb, qe;
      foreach (t; 0 .. 2) {
        dp[t][0] = 0;
        que[qe++] = t;
        que[qe++] = 0;
      }

      for (; qb != qe; ) {
        const t = que[qb++];
        const x = que[qb++];
        foreach (s; S[t ^ 1]) {
          const tt = t ^ 1;
          const xx = (x - s < 0) ? (x - s + N) : (x - s);
          if (dp[tt][xx] == -1) {
            if (dp[t][x] & 1) {
              if (--cnt[tt][xx] > 0) {
                continue;
              }
            }
            dp[tt][xx] = dp[t][x] + 1;
            que[qe++] = tt;
            que[qe++] = xx;
          }
        }
      }

      foreach (t; 0 .. 2) {
        foreach (x; 1 .. N) {
          if (x > 1) write(" ");
          write((dp[t][x] == -1) ? "Loop" : (dp[t][x] & 1) ? "Win" : "Lose");
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}


This task is very simple. Given a string S of length n and q queries each query is on the format i j k which means sort the substring consisting of the characters from i to j in non-decreasing order if k = 1 or in non-increasing order if k = 0.Output the final string after applying the queries.

The first line will contain two integers n, q (1 ≤ n ≤ 105, 0 ≤ q ≤ 50 000), the length of the string and the number of queries respectively.  Next line contains a string S itself. It contains only lowercase English letters. Next q lines will contain three integers each i, j, k (1 ≤ i ≤ j ≤ n, ).

Output one line, the string S after applying the queries.

import std.stdio;
import std.c.stdio;
import std.math;
import std.algorithm;
import std.conv;
import std.string;
import std.array;
import std.typecons;

immutable(int) C = 26;

void bsortFill(char[] s, int[C] ct, int order) {
  if (order == 0) {
    assert(false);
  }
  int k = order == 1 ? 0 : C - 1;
  int p = 0;
  while (p < s.length) {
    while (ct[k] == 0) {
      k += order;
      assert(0 <= k && k < C);
    }
    s[p++] = cast(char)(k + 'a');
    ct[k]--;
  }
}

void bsort(char[] s, int order) {
  int[C] ct;
  foreach (c; s) {
    ct[c - 'a']++;
  }
  bsortFill(s, ct, order);
}

struct SqrtDecomposition {

  struct Bucket {
    int size;
    char[] s;
    int[C] ct;
    int order;

    void eval() {
      if (order == 0) return;
      bsortFill(s, ct, order);
      order = 0;
    }
  }

  int n, m, bsize;
  Bucket[] bs;
  this(string s) {
    n = cast(int)s.length;
    bsize = cast(int)sqrt(real(n)) + 1;
    m = (n - 1) / bsize + 1;
    bs = new Bucket[m];
    foreach(int i; 0..m) {
      int l = i * bsize, r = min(n, bsize * (i + 1));
      bs[i].order = 0;
      bs[i].size = r - l;
      foreach (j; l..r) {
        bs[i].s ~= s[j];
        bs[i].ct[s[j] - 'a']++;
      }
    }
  }

  void sort(int l, int r, int order) {
    r--;
    int lb = l / bsize;
    int rb = r / bsize;
    if (lb == rb) {
      bs[lb].eval();
      bsort(bs[lb].s[l-lb*bsize..r-lb*bsize+1], order);
    } else {
      int[C] ct;
      bs[lb].eval();
      bs[rb].eval();
      char[] ls = bs[lb].s[(l-lb*bsize)..$];
      char[] rs = bs[rb].s[0..r-rb*bsize+1];
      bsort(ls, order);
      bsort(rs, order);
      foreach (c; ls) {
        ct[c - 'a']++;
        bs[lb].ct[c - 'a']--;
      }
      foreach (i; lb+1..rb) {
        foreach(j; 0..C) {
          ct[j] += bs[i].ct[j];
          bs[i].ct[j] = 0;
        }
      }
      foreach (c; rs) {
        ct[c - 'a']++;
        bs[rb].ct[c - 'a']--;
      }
      {
        int k = order == 1 ? 0 : C - 1;
        int p = 0;
        while (p < ls.length) {
          while (ct[k] == 0) {
            k += order;
            assert(0 <= k && k < C);
          }
          ls[p++] = cast(char)(k + 'a');
          bs[lb].ct[k]++;
          ct[k]--;
        }
      }
      {
        int k = order == 1 ? 0 : C - 1;
        foreach (i; lb+1..rb) {
          int t = bs[i].size;
          while (t > 0) {
            if (ct[k] > t) {
              ct[k] -= t;
              bs[i].ct[k] += t;
              t = 0;
            } else {
              t -= ct[k];
              bs[i].ct[k] += ct[k];
              ct[k] = 0;
              k += order;
            }
          }
          bs[i].order = order;
        }
      }
      {
        int k = order == 1 ? 0 : C - 1;
        int p = 0;
        while (p < rs.length) {
          while (ct[k] == 0) {
            k += order;
            assert(0 <= k && k < C);
          }
          rs[p++] = cast(char)(k + 'a');
          bs[rb].ct[k]++;
          ct[k]--;
        }
      }
    }
  }

  void print() {
    foreach (i; 0..m) {
      bs[i].eval();
      write(bs[i].s);
    }
    writeln();
  }
}

void main() {
  auto input = readln().split().map!(to!int);
  int n = input[0], q = input[1];
  string s = readln().strip();
  auto sq = SqrtDecomposition(s);
  while (q--) {
    auto query = readln().split().map!(to!int);
    int l = query[0] - 1, r = query[1], order = query[2];
    order = (order == 1 ? 1 : -1);
    sq.sort(l, r, order);

  }
  sq.print();
}


George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers b. During the game, George modifies the array by using special changes. Let's mark George's current array as b1, b2, ..., b|b| (record |b| denotes the current length of the array). Then one change is a sequence of actions:   Choose two distinct indexes i and j (1 ≤ i, j ≤ |b|; i ≠ j), such that bi ≥ bj.  Get number v = concat(bi, bj), where concat(x, y) is a number obtained by adding number y to the end of the decimal record of number x. For example, concat(500, 10) = 50010, concat(2, 2) = 22.  Add number v to the end of the array. The length of the array will increase by one.  Remove from the array numbers with indexes i and j. The length of the array will decrease by two, and elements of the array will become re-numbered from 1 to current length of the array. George played for a long time with his array b and received from array b an array consisting of exactly one number p. Now George wants to know: what is the maximum number of elements array b could contain originally? Help him find this number. Note that originally the array could contain only positive integers.

The first line of the input contains a single integer p (1 ≤ p < 10100000). It is guaranteed that number p doesn't contain any leading zeroes.

Print an integer — the maximum number of elements array b could contain originally.

NoteLet's consider the test examples:   Originally array b can be equal to {5, 9, 5, 5}. The sequence of George's changes could have been: {5, 9, 5, 5} → {5, 5, 95} → {95, 55} → {9555}.  Originally array b could be equal to {1000000000, 5}. Please note that the array b cannot contain zeros.  Originally array b could be equal to {800, 10, 1}.  Originally array b could be equal to {45}. It cannot be equal to {4, 5}, because George can get only array {54} from this array in one operation. Note that the numbers can be very large.

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

bool isSmaller(string a, string b) {
    return a.length == b.length ? a < b : a.length < b.length;
}

ulong x(string s) {
    for (uint i = s.length - 1; i >= 0; i--) {
        if (s[i] == '0') continue;
        if (s[0 .. i].isSmaller(s[i .. $])) break;
        return x(s[0 .. i]) + 1;
    }
    return 1;
}

void main() {
    string s = stdin.readln.chomp;
    writeln(s.x);
}


No Great Victory anniversary in Berland has ever passed without the war parade. This year is not an exception. That’s why the preparations are on in full strength. Tanks are building a line, artillery mounts are ready to fire, soldiers are marching on the main square... And the air forces general Mr. Generalov is in trouble again. This year a lot of sky-scrapers have been built which makes it difficult for the airplanes to fly above the city. It was decided that the planes should fly strictly from south to north. Moreover, there must be no sky scraper on a plane’s route, otherwise the anniversary will become a tragedy. The Ministry of Building gave the data on n sky scrapers (the rest of the buildings are rather small and will not be a problem to the planes). When looking at the city from south to north as a geometrical plane, the i-th building is a rectangle of height hi. Its westernmost point has the x-coordinate of li and the easternmost — of ri. The terrain of the area is plain so that all the buildings stand on one level. Your task as the Ministry of Defence’s head programmer is to find an enveloping polyline using the data on the sky-scrapers. The polyline’s properties are as follows:  If you look at the city from south to north as a plane, then any part of any building will be inside or on the boarder of the area that the polyline encloses together with the land surface.  The polyline starts and ends on the land level, i.e. at the height equal to 0.  The segments of the polyline are parallel to the coordinate axes, i.e. they can only be vertical or horizontal.  The polyline’s vertices should have integer coordinates.  If you look at the city from south to north the polyline (together with the land surface) must enclose the minimum possible area.  The polyline must have the smallest length among all the polylines, enclosing the minimum possible area with the land.  The consecutive segments of the polyline must be perpendicular.    Picture to the second sample test (the enveloping polyline is marked on the right).

The first input line contains integer n (1 ≤ n ≤ 100000). Then follow n lines, each containing three integers hi, li, ri (1 ≤ hi ≤ 109,  - 109 ≤ li < ri ≤ 109).

In the first line output integer m — amount of vertices of the enveloping polyline. The next m lines should contain 2 integers each — the position and the height of the polyline’s vertex. Output the coordinates of each vertex in the order of traversing the polyline from west to east. Remember that the first and the last vertices of the polyline should have the height of 0.

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

immutable INF = 1_001_001_001;

int N;
int[] H, A, B;

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

		int[] xs;
		xs ~= -INF;
		xs ~= +INF;
		foreach (i; 0 .. N) {
			xs ~= A[i];
			xs ~= B[i];
		}
		xs.sort();
		xs = xs.unique;
debug{
writeln("xs = ",xs);
}
		const int n = xs.length - 1;

		int[][] adds = new int[][n + 1];
		foreach (i; 0 .. N) {
			const j = xs.lowerBound(A[i]);
			adds[j] ~= i;
		}

		int[] ys = new int[n];
		auto q = BinaryHeap!(Array!(Pair!(int, int)))();
		q.insert(pair(0, INF));
		foreach (j; 0 .. n) {
			foreach (i; adds[j]) {
				q.insert(pair(H[i], B[i]));
			}
			for (; q.front.y <= xs[j]; ) {
				q.removeFront;
			}
			ys[j] = q.front.x;
		}
debug{
writeln("ys = ",ys);
}

		Pair!(int, int)[] ans;
		ans ~= pair(xs[1], 0);
		for (int j = 1, k; j < n - 1; j = k) {
			for (k = j; k < n - 1 && ys[j] == ys[k]; ++k) {}
			ans ~= pair(xs[j], ys[j]);
			ans ~= pair(xs[k], ys[j]);
		}
		ans ~= pair(xs[n - 1], 0);
		outp.writeln(ans.length);
		foreach (p; ans) {
			outp.writeln(p.x, " ", p.y);
		}
	}
}


Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj = xi.Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.

The first input line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of markers and the number of caps, correspondingly.  Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1 ≤ xi, yi ≤ 1000) — the i-th marker's color and diameter, correspondingly. Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1 ≤ aj, bj ≤ 1000) — the color and diameter of the j-th cap, correspondingly.

Print two space-separated integers u, v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.

NoteIn the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed — the first and the third markers.

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

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    auto ns = readln.chomp.split.map!(to!int).array;

    auto vals = new int[][][] (2, 1001, 1001);
    foreach (i; 0 .. 2) {
        foreach (_; 0 .. ns[i]) {
            int x, y;
            readf("%s %s", &x, &y);
            readln;
            vals[i][y][x] += 1;
        }
    }

    int u = 0, v = 0;
    foreach (d; 1 .. 1001) {
        int mleft = 0, cleft = 0;
        int ok = 0;
        foreach (c; 1 .. 1001) {
            ok += min(vals[0][d][c], vals[1][d][c]);
            if (vals[0][d][c] > vals[1][d][c]) mleft += vals[0][d][c] - vals[1][d][c];
            else cleft += vals[1][d][c] - vals[0][d][c];
        }

        u += ok;
        v += ok;

        u += min(mleft, cleft);
    }

    writeln(u, ' ', v);
}

module cf_159b;

import std.stdio;
import std.algorithm;

void main() {
  immutable MAX_VALUE = 1000;

  int n, m, a, b;
  int[MAX_VALUE + 1][MAX_VALUE + 1] pairCount;
  int[MAX_VALUE + 1] diamCount;
  int closed = 0, nicelyClosed = 0;

  readf("%d %d", &n, &m);
  for (int i = 0; i < n; ++i) {
    readf(" %d %d", &a, &b);
    ++pairCount[a][b];
    ++diamCount[b];
  }
  for (int i = 0; i < m; ++i) {
    readf(" %d %d", &a, &b);

    if (pairCount[a][b] > 0) {
      ++nicelyClosed;
      --pairCount[a][b];
    }
    if (diamCount[b] > 0) {
      ++closed;
      --diamCount[b];
    }
  }

  writeln(closed, " ", nicelyClosed);
}

module cf_159b;

import std.stdio;
import std.algorithm;

void main() {
  immutable MAX_VALUE = 1000;

  int n, m, a, b;
  int[MAX_VALUE + 1][MAX_VALUE + 1] pairCount;
  int[MAX_VALUE + 1] diamCount;
  int closed = 0, nicelyClosed = 0;

  readf("%d %d", &n, &m);
  for (int i = 0; i < n; ++i) {
    readf(" %d %d", &a, &b);
    ++pairCount[a][b];
    ++diamCount[b];
  }
  for (int i = 0; i < m; ++i) {
    readf(" %d %d", &a, &b);

    if (pairCount[a][b] > 0) {
      ++nicelyClosed;
    }
    if (diamCount[b] > 0) {
      ++closed;
    }
  }

  writeln(closed, " ", nicelyClosed);
}

module cf_159b;

import std.stdio;
import std.algorithm;

void main() {
  int n, m;
  int[2][] markers, caps;

  readf("%d %d", &n, &m);
  markers = new int[2][n];
  caps = new int[2][m];
  for (int i = 0; i < n; ++i) {
    readf(" %d %d", &markers[i][0], &markers[i][1]);
  }
  for (int i = 0; i < m; ++i) {
    readf(" %d %d", &caps[i][0], &caps[i][1]);
  }

  sort!((a, b) { return a[0] < b[0] || a[0] == b[0] && a[1] < b[1]; })(markers);
  sort!((a, b) { return a[0] < b[0] || a[0] == b[0] && a[1] < b[1]; })(caps);

  int nicelyClosed = 0;
  for (int i = 0; i < n; ++i) {
    int l = 0, r = caps.length - 1;
    while (l < r) {
      int mid = (l + r) / 2;
      bool leftCondition = markers[i][0] > caps[mid][0] ||
    markers[i][0] == caps[mid][0] && markers[i][1] > caps[mid][1];
      if (leftCondition) {
    l = mid + 1;
      } else {
    r = mid;
      }
    }

    bool cond = markers[i][0] == caps[r][0] && markers[i][1] == caps[r][1];
    if (cond) {
      ++nicelyClosed;
    }
  }

  sort!((a, b) { return a[1] < b[1]; })(markers);
  sort!((a, b) { return a[1] < b[1]; })(caps);

  int closed = 0;
  for (int i = 0; i < n; ++i) {
    int l = 0, r = caps.length - 1;
    while (l < r) {
      int mid = (l + r) / 2;
      if (markers[i][1] > caps[mid][1]) {
    l = mid + 1;
      } else {
    r = mid;
      }
    }

    bool cond = markers[i][1] == caps[r][1];
    if (cond) {
      ++closed;
    }
  }

  writeln(closed, " ", nicelyClosed);
}


The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.Satisfy Arkady's curiosity and tell him the final version of the name.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the length of the initial name and the number of designers hired, respectively. The second line consists of n lowercase English letters and represents the original name of the corporation. Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters xi and yi.

11 6
abacabadaba
a b
b c
a d
e g
f a
b b

NoteIn the second sample the name of the corporation consecutively changes as follows:

import std.stdio;
import std.array;
import std.conv;
import std.algorithm;
int[] dat;
void main()
{
	int num,query;
	string[]zs=split(readln());
	num=to!int(zs[0]);
	query=to!int(zs[1]);
	string s=readln();
	for(int i=0;i<26;i++)dat~=i;
	for(int i=0;i<query;i++)
	{
		char za,zb;
		zs=split(readln());
		za=to!char(zs[0]);
		zb=to!char(zs[1]);
		int a,b;
		for(int j=0;j<26;j++)
		{
			if(za-'a'==dat[j])a=j;
			if(zb-'a'==dat[j])b=j;
		}
		swap(dat[a],dat[b]);
	}
	for(int i=0;i<num;i++)write(to!char('a'+dat[s[i]-'a']));
	writeln();
	readln();
}

import std.stdio;
import std.array;
import std.conv;
import std.algorithm;
int[] dat;
void main()
{
	int num,query;
	string[]zs=split(readln());
	num=to!int(zs[0]);
	query=to!int(zs[1]);
	string s=readln();
	for(int i=0;i<26;i++)dat~=i;
	for(int i=0;i<query;i++)
	{
		char za,zb;
		zs=split(readln());
		za=to!char(zs[0]);
		zb=to!char(zs[1]);
		swap(dat[za-'a'],dat[zb-'a']);
	}
	for(int i=0;i<num;i++)write(to!char('a'+dat[s[i]-'a']));
	writeln();
	readln();
}


In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.For example, for n = 4 the sum is equal to  - 1 - 2 + 3 - 4 =  - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.Calculate the answer for t values of n.

The first line of the input contains a single integer t (1 ≤ t ≤ 100) — the number of values of n to be processed. Each of next t lines contains a single integer n (1 ≤ n ≤ 109).

Print the requested sum for each of t integers n given in the input.

NoteThe answer for the first sample is explained in the statement.

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--) {
                long n = cin.readString.to!long;
                long sum = (n * (n + 1)) / 2;
                int num = 0;
                for (int i = 1; num <= n; i++) {
                        num = 1 << i;
                        sum -= num;
                }
                writeln(sum);
        }
}

import std.stdio;

void main ()
{
	int tests;
	readf (" %s", &tests);
	foreach (test; 0..tests)
	{
		int n;
		readf (" %s", &n);
		long res = n * 1L * (n + 1) / 2;
		for (int p = 1; p <= n; p <<= 1)
		{
			res -= p * 2;
		}
		writeln (res);
	}
}

module main;

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

immutable int MAX_LOG = 31;
int[MAX_LOG] powers;
long[MAX_LOG] prefixes;

long specialSum( int n ) {

//    debug {writeln((1L + n) * n / 2);
//            writeln(cast (int)(trunc(log2(cast (double)(n)))));
//            writeln(prefixes[cast (int)(trunc(log2(cast (double)(n))))]);};
    return (1L + n) * n / 2 - 2 *
            prefixes[cast (int)(trunc(log2(cast (double)(n))))];
}

int main() {

    auto t = readln().strip().to! (int);
    long answers[];

    powers[0] = 1;
    foreach (int i; 1..powers.length)
        powers[i] = powers[i - 1] * 2;
    prefixes[0] = 1;
    foreach (int i; 1..prefixes.length)
        prefixes[i] = prefixes[i - 1] + powers[i];

    // debug {writeln(powers, '\n', prefixes);};

    foreach (int i; 0..t) {
        auto n = readln().strip().to! (int);

        answers ~= specialSum(n);
    }

    foreach (i; answers)
        writeln(i);

	return 0;
}


There are n cities located along the one-way road. Cities are numbered from 1 to n in the direction of the road.The i-th city had produced pi units of goods. No more than si units of goods can be sold in the i-th city.For each pair of cities i and j such that 1 ≤ i < j ≤ n you can no more than once transport no more than c units of goods from the city i to the city j. Note that goods can only be transported from a city with a lesser index to the city with a larger index. You can transport goods between cities in any order.Determine the maximum number of produced goods that can be sold in total in all the cities after a sequence of transportations.

The first line of the input contains two integers n and c (1 ≤ n ≤ 10 000, 0 ≤ c ≤ 109) — the number of cities and the maximum amount of goods for a single transportation. The second line contains n integers pi (0 ≤ pi ≤ 109) — the number of units of goods that were produced in each city. The third line of input contains n integers si (0 ≤ si ≤ 109) — the number of units of goods that can be sold in each city.

Print the maximum total number of produced goods that can be sold in all cities after a sequence of transportations.

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

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

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

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

enum INF = 10L^^18;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const C = readLong();
      auto P = new long[N];
      foreach (i; 0 .. N) {
        P[i] = readLong();
      }
      auto S = new long[N];
      foreach (i; 0 .. N) {
        S[i] = readLong();
      }

      // num src-side
      auto dp = new long[N + 1];
      dp[] = INF;
      dp[0] = 0;
      foreach (i; 0 .. N) {
        foreach_reverse (j; 1 .. i + 1 + 1) {
          dp[j] = min(dp[j - 1] + S[i], dp[j] + P[i] + C * j);
        }
        dp[0] = dp[0] + P[i] + C * 0;
      }
      const ans = dp.minElement;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


It's well known that the best way to distract from something is to do one's favourite thing. Job is such a thing for Leha.So the hacker began to work hard in order to get rid of boredom. It means that Leha began to hack computers all over the world. For such zeal boss gave the hacker a vacation of exactly x days. You know the majority of people prefer to go somewhere for a vacation, so Leha immediately went to the travel agency. There he found out that n vouchers left. i-th voucher is characterized by three integers li, ri, costi — day of departure from Vičkopolis, day of arriving back in Vičkopolis and cost of the voucher correspondingly. The duration of the i-th voucher is a value ri - li + 1.At the same time Leha wants to split his own vocation into two parts. Besides he wants to spend as little money as possible. Formally Leha wants to choose exactly two vouchers i and j (i ≠ j) so that they don't intersect, sum of their durations is exactly x and their total cost is as minimal as possible. Two vouchers i and j don't intersect if only at least one of the following conditions is fulfilled: ri < lj or rj < li.Help Leha to choose the necessary vouchers!

The first line contains two integers n and x (2 ≤ n, x ≤ 2·105) — the number of vouchers in the travel agency and the duration of Leha's vacation correspondingly. Each of the next n lines contains three integers li, ri and costi (1 ≤ li ≤ ri ≤ 2·105, 1 ≤ costi ≤ 109) — description of the voucher.

Print a single integer — a minimal amount of money that Leha will spend, or print  - 1 if it's impossible to choose two disjoint vouchers with the total duration exactly x.

NoteIn the first sample Leha should choose first and third vouchers. Hereupon the total duration will be equal to (3 - 1 + 1) + (6 - 5 + 1) = 5 and the total cost will be 4 + 1 = 5.In the second sample the duration of each voucher is 3 therefore it's impossible to choose two vouchers with the total duration equal to 2.

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

immutable lim = 2 * 10^^5 + 7;
immutable inf = 2 * 10^^9 + 7;
alias Query = Tuple!(int, "l", int, "type", int, "r", int, "c");
int n, x;

void main() {
    scan(n, x);

    auto t = new Query[](2*n);

    int li, ri, ci;

    foreach (i ; 0 .. n) {
        scan(li, ri, ci);
        t[2*i] = Query(li, 0, ri, ci);
        t[2*i + 1] = Query(ri, 1, li, ci);
    }

    t.sort();

    auto minc = new int[](lim);
    minc[] = inf;

    int ans = inf;

    foreach (i ; 0 .. 2*n) {
        if (t[i].type == 0) {
            int d = t[i].r - t[i].l + 1;
            if (x - d >= 0 && minc[x - d] < inf) {
                ans = min(ans, minc[x - d] + t[i].c);
            }
        }
        else {
            int d = t[i].l - t[i].r + 1;
            minc[d] = min(minc[d], t[i].c);
        }
    }

    if (ans == inf) {
        writeln(-1);
    }
    else {
        writeln(ans);
    }
}

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

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

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

immutable lim = 2 * 10^^5 + 7;
immutable inf = 2 * 10^^9 + 7;
alias Trip = Tuple!(int, "r", int, "l", int, "c");
int n, x;

void main() {
    scan(n, x);

    auto t = new Trip[](n);

    int li, ri, ci;

    foreach (i ; 0 .. n) {
        scan(li, ri, ci);
        t[i] = Trip(ri, li, ci);
    }

    auto tl = t.dup;

    t.sort();
    tl.sort!"a[1] < b[1]"();

    debug {
        writeln("t:", t);
        writeln("tl:", tl);
    }

    auto minc = new long[](lim);
    minc[] = inf;

    long ans = inf;

    foreach (i ; 1 .. lim) {
        while (!tl.empty && i == tl.front.l) {
            int d = tl.front.r - tl.front.l + 1;
            if (x - d >= 0) {
                ans = min(ans, minc[x - d] + tl.front.c);
            }
            tl.popFront();
        }

        while (!tl.empty && i == t.front.r) {
            int d = t.front.r - t.front.l + 1;
            minc[d] = min(minc[d], t.front.c);
            t.popFront();
        }
    }

    if (ans == inf) {
        writeln(-1);
    }
    else {
        writeln(ans);
    }
}

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

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

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

immutable lim = 2 * 10^^5 + 7;
immutable inf = 2 * 10^^9 + 7;
alias Trip = Tuple!(int, "r", int, "l", int, "c");
int n, x;

void main() {
    scan(n, x);

    auto t = new Trip[](n);

    int li, ri, ci;

    foreach (i ; 0 .. n) {
        scan(li, ri, ci);
        t[i] = Trip(ri, li, ci);
    }

    t.sort();

    auto dp = new int[][](lim, 3);

    foreach (i ; 0 .. lim) {
        dp[i][1] = dp[i][2] = inf;
    }

    foreach (i ; 1 .. lim) {
        dp[i][1] = min(dp[i][1], dp[i - 1][1]);
        dp[i][2] = min(dp[i][2], dp[i - 1][2]);

        while (!t.empty && i == t.front.r) {
            dp[i][1] = min(dp[i][1], t.front.c);

            dp[i][2] = min(dp[i][2], dp[t.front.l - 1][1] + t.front.c);

            t.popFront();
        }
    }

    debug {
        writefln("%(%(%s %)\n%)", dp[0 .. 10]);
    }

    int ans = dp[lim - 1][2];

    if (ans == inf) {
        writeln(-1);
    }
    else {
        writeln(ans);
    }
}

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

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

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

immutable lim = 2 * 10^^5 + 7;
immutable inf = 2 * 10^^9 + 7;
alias Trip = Tuple!(int, "r", int, "l", int, "c");
int n, x;

void main() {
    scan(n, x);

    auto t = new Trip[](n);

    int li, ri, ci;

    foreach (i ; 0 .. n) {
        scan(li, ri, ci);
        t[i] = Trip(ri, li, ci);
    }

    t.sort();

    auto dp = new long[][](lim, 3);

    foreach (i ; 0 .. lim) {
        dp[i][1] = dp[i][2] = inf;
    }

    foreach (i ; 1 .. lim) {
        dp[i][1] = min(dp[i][1], dp[i - 1][1]);
        dp[i][2] = min(dp[i][2], dp[i - 1][2]);

        while (!t.empty && i == t.front.r) {
            dp[i][1] = min(dp[i][1], t.front.c);
            dp[i][2] = min(dp[i][2], dp[t.front.l - 1][1] + t.front.c);
            t.popFront();
        }
    }

    debug {
        writefln("%(%(%s %)\n%)", dp[0 .. 10]);
    }

    long ans = dp[lim - 1][2];

    if (ans == inf) {
        writeln(-1);
    }
    else {
        writeln(ans);
    }
}

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

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


As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.

The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.

NoteHere is the graph of the example, satisfying $$$l_i=i$$$.

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

int ask (bool [] used)
{
	writefln !("? %(%s%)") (used.map !(to !(int)));
	stdout.flush ();
	return readln.strip.to !(int);
}

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;

		auto len = new int [m];
		auto used = new bool [m];
		foreach (i; 0..m)
		{
			used[i] = true;
			len[i] = ask (used);
			used[i] = false;
		}

		int res = 0;
		auto p = m.iota.array;
		p.schwartzSort !(i => len[i]);
		foreach (i; p)
		{
			used[i] = true;
			int cur = ask (used);
			if (res + len[i] == cur)
			{
				res = cur;
			}
			else
			{
				used[i] = false;
			}
		}

		writefln !("! %s") (res);
		stdout.flush ();
	}
}

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

long ask(in char[] s) {
    writefln("? %s", s);
    stdout.flush;
    long r = readln.chomp.to!long;
    return r;
}

void main() {
    int N, M; readf("%d %d\n", &N, &M);

    long[] L = new long[M]; L[$-1] = -1;

    char[] q = new char[M]; q[] = '0';
    for (int i = 0; i < M; i++) {
        q[i] = '1';
        L[i] = ask(q);
        q[i] = '0';
    }
    auto idx = M.iota.array.sort!((a, b) => L[a] < L[b]).array;

    long C = 0;
    foreach (k; idx) {
        q[k] = '1';
        long nC = ask(q);
        if (nC == C + L[k]) {
            // need k
            C = nC;
        } else {
            // don't need k
            q[k] = '0';
        }
    }
    writefln("! %s", C);
    stdout.flush;
}

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

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

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

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

void main() {
  const N = readInt;
  const M = readInt;

  alias Edge = Tuple!(long, "c", int, "i");
  auto es = new Edge[M];
  foreach (i; 0 .. M) {
    auto cs = new char[M];
    cs[] = '0';
    cs[i] = '1';
    writefln("? %s", cs);
    stdout.flush;
    es[i].c = readLong;
    es[i].i = i;
  }
  es.sort;

  long ans;
  {
    auto cs = new char[M];
    cs[] = '0';
    long bef;
    foreach (e; es) {
      const i = e.i;
      cs[i] = '1';
      writefln("? %s", cs);
      stdout.flush;
      const res = readLong;
      if (bef + e.c == res) {
        ans += e.c;
        bef = res;
      } else {
        cs[i] = '0';
      }
    }
  }

  writefln("! %s", ans);
  stdout.flush;
}

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

int ask (bool [] used)
{
	writefln !("? %(%s%)") (used.map !(to !(int)));
	stdout.flush ();
	return readln.strip.to !(int);
}

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;

		auto len = new int [m];
		auto used = new bool [m];
		foreach (i; 0..m)
		{
			used[i] = true;
			len[i] = ask (used);
			used[i] = false;
		}

		int res = 0;
		foreach (i; 0..m)
		{
			used[i] = true;
			int cur = ask (used);
			if (res + len[i] == cur)
			{
				res = cur;
			}
			else
			{
				used[i] = false;
			}
		}

		writefln !("! %s") (res);
		stdout.flush ();
	}
}


Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions (i, j), where i < j, exactly once. MoJaK doesn't like to upset Sajjad.Given the permutation, determine whether it is possible to swap all pairs of positions so that the permutation stays the same. If it is possible find how to do that.

The first line contains single integer n (1 ≤ n ≤ 1000) — the size of the permutation. As the permutation is not important, you can consider ai = i, where the permutation is a1, a2, ..., an.

If it is not possible to swap all pairs of positions so that the permutation stays the same, print "NO", Otherwise print "YES", then print  lines: the i-th of these lines should contain two integers a and b (a < b) — the positions where the i-th swap is performed.

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

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n;
loop:while(read(n))
	{
		if(n%4>1){writeln("NO");continue loop;}
		else writeln("YES");
		void go(int x)
		{
			if(x<=1)return;
			int y=x-4;
			foreach(i;1..y+1)write(i,' ',y+1,'\n');
			foreach(i;1..y+1)write(i,' ',y+3,'\n');
			write(y+1,' ',x,'\n');
			write(y+2,' ',y+3,'\n');
			write(y+1,' ',y+3,'\n');
			write(y+2,' ',x,'\n');
			foreach_reverse(i;1..y+1)write(i,' ',y+4,'\n');
			foreach_reverse(i;1..y+1)write(i,' ',y+2,'\n');

			write(y+1,' ',y+2,'\n');
			write(y+3,' ',y+4,'\n');
			go(y);
		}
		go(n);
	}
}

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

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n;
loop:while(read(n))
	{
		if(n%4>1){writeln("NO");}
		else writeln("YES");
		void go(int x)
		{
			if(x<=1)return;
			int y=x-4;
			foreach(i;1..y+1)write(i,' ',y+1,'\n');
			write(y+1,' ',x,'\n');
			write(y+2,' ',y+3,'\n');
			write(y+1,' ',y+3,'\n');
			write(y+2,' ',x,'\n');
			foreach(i;1..y+1)write(i,' ',y+2,'\n');
			write(y+1,' ',y+2,'\n');
			write(y+3,' ',y+4,'\n');
			go(y);
		}
		go(n);
	}
}

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

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n;
loop:while(read(n))
	{
		if(n%4>1){writeln("NO");continue loop;}
		else writeln("YES");
		void go(int x)
		{
			if(x<=1)return;
			int y=x-4;
			foreach(i;1..y+1)write(i,' ',y+1,'\n');
			write(y+1,' ',x,'\n');
			write(y+2,' ',y+3,'\n');
			write(y+1,' ',y+3,'\n');
			write(y+2,' ',x,'\n');
			foreach(i;1..y+1)write(i,' ',y+2,'\n');
			write(y+1,' ',y+2,'\n');
			write(y+3,' ',y+4,'\n');
			go(y);
		}
		go(n);
	}
}

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

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n;
loop:while(read(n))
	{
		if(n%4>1){writeln("NO");continue loop;}
		else writeln("YES");
		void go(int x)
		{
			if(x<=1)return;
			int y=x-4;
			foreach(i;1..y+1)write(i,' ',y+1,'\n');
			foreach(i;1..y+1)write(i,' ',y+3,'\n');
			write(y+1,' ',x,'\n');
			write(y+2,' ',y+3,'\n');
			write(y+1,' ',y+3,'\n');
			write(y+2,' ',x,'\n');
			foreach(i;1..y+1)write(i,' ',y+4,'\n');
			foreach(i;1..y+1)write(i,' ',y+2,'\n');
			write(y+1,' ',y+2,'\n');
			write(y+3,' ',y+4,'\n');
			go(y);
		}
		go(n);
	}
}