A ticket is a string consisting of six digits. A ticket is considered lucky if the sum of the first three digits is equal to the sum of the last three digits. Given a ticket, output if it is lucky or not. Note that a ticket can have leading zeroes.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of testcases. The description of each test consists of one line containing one string consisting of six digits.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. Output "YES" if the given ticket is lucky, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case, the sum of the first three digits is $$$2 + 1 + 3 = 6$$$ and the sum of the last three digits is $$$1 + 3 + 2 = 6$$$, they are equal so the answer is "YES".In the second test case, the sum of the first three digits is $$$9 + 7 + 3 = 19$$$ and the sum of the last three digits is $$$8 + 9 + 4 = 21$$$, they are not equal so the answer is "NO".In the third test case, the sum of the first three digits is $$$0 + 4 + 5 = 9$$$ and the sum of the last three digits is $$$2 + 0 + 7 = 9$$$, they are equal so the answer is "YES".

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

int[] rtln(T)() { return to!(T[])(strip(readln).split("")); }

void main() {
    int t, n, m;
    readf("%d\n", t);
    while(t--) {
        auto arr = rtln!int;
		if ((arr[0] + arr[1] + arr[2]) == (arr[3]+arr[4]+arr[5]))
			writeln("YES");
		else
			writeln("NO");
    }
}

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan.map!(c => c - '0').array;

      auto a = N[0..3].sum;
      auto b = N[3..6].sum;

      return a == b ? "YES" : "NO";
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

// ----------------------------------------------

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

// -----------------------------------------------

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		writeln (s[0..$ / 2].sum == s[$ / 2..$].sum ? "YES" : "NO");
	}
}


Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain.

The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$) — the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip.

Print a single integer — the smallest number Dima can obtain.

NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.strip;
		int i = n / 2;
		int j = n - i;
		while (s[i] == '0')
		{
			i -= 1;
		}
		while (j < n && s[j] == '0')
		{
			j += 1;
		}
		auto res = BigInt (s);
		if (i > 0)
		{
			res = min (res, BigInt (s[0..i]) + BigInt (s[i..$]));
		}
		if (j < n)
		{
			res = min (res, BigInt (s[0..j]) + BigInt (s[j..$]));
		}
		writeln (res);
	}
}

import std.algorithm, std.bigint, std.conv, std.stdio, std.string;
void main () {
	auto n = readln.strip.to!int, s = readln.strip, i = n / 2, j = n - i;
	while (s[i] == '0') i -= 1;
	while (j < n && s[j] == '0') j += 1;
	auto res = BigInt (s);
	if (i > 0) res = min (res, BigInt (s[0..i]) + BigInt (s[i..$]));
	if (j < n) res = min (res, BigInt (s[0..j]) + BigInt (s[j..$]));
	writeln (res);
}

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

T readNum(T)(){
  return readStr.to!T;
}

T[] readNums(T)(){
  return readStr.split.to!(T[]);
}

string readStr(){
  return readln.chomp;
}

void main(){
  auto n = readNum!int;
  string s = readStr;

  BigInt ret = s;

  auto c = s.length / 2;
  auto found = false;
  auto d = s.length % 2 == 1 ? 1 : 0;
  auto p = s.length % 2 == 1 ? 1 : 0;

  while(1){
    if(s[c-d+p] != '0'){
      BigInt l = s[0 .. c-d+p];
      BigInt r = s[c-d+p .. $];

      ret = min(ret, l+r);
      found = true;
    }

    if(s[c+d] != '0'){
      BigInt l = s[0 .. c+d];
      BigInt r = s[c+d .. $];

      ret = min(ret, l+r);
      found = true;
    }

    if(found) break;
    else d++;
  }

  writeln(ret);
}

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

alias Tree = RBT!int;
alias ll = long;

void main() {
  GC.disable();

  int l;
  readf(" %s\n", l);
  string s =  readln.strip;

  int idx = s.length/2;
  while(idx >= 0 && idx < s.length) {
    if (s[idx] != '0') break;
    idx--;
  }

  BigInt ans = s;
  if (idx > 0 && idx < s.length) {
    BigInt a = s[0 ..  idx];
    BigInt b = s[idx .. $];
    BigInt ss = a + b;
    ans = min(ans, ss);
  }

  idx = s.length/2+1;

  while(idx >= 0 && idx < s.length) {
    if (s[idx] != '0') break;
    idx++;
  }

  if (idx > 0 && idx < s.length) {
    BigInt a = s[0 ..  idx];
    BigInt b = s[idx .. $];
    BigInt ss = a + b;
    ans = min(ans, ss);
  }

  writeln(ans);

}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.strip;
		int i = n / 2;
		int j = n - i;
		while (s[i] == '0')
		{
			i -= 1;
		}
		while (j < n && s[j] == '0')
		{
			j += 1;
		}
		writeln (i, " ", j);
		auto res = BigInt (s);
		if (i > 0)
		{
			res = min (res, BigInt (s[0..i]) + BigInt (s[i..$]));
		}
		if (j < n)
		{
			res = min (res, BigInt (s[0..j]) + BigInt (s[j..$]));
		}
		writeln (res);
	}
}


Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous).If it is possible to partition the array, also give any possible way of valid partitioning.

The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109).

In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition.

module main;

import std.stdio, std.string;

void solve(int[] a, int n, int k, int p)
{
    int[] odd, even;
    foreach (val; a)
    {
        if (val & 1)
        {
            odd ~= val;
        }
        else
        {
            even ~= val;
        }
    }
    auto evenAns = new int[][p + 1];
    auto oddAns = new int[][k - p + 1];
    int i, j, t, oddIdx, evenIdx;
    for (i = 0, j = 0; i < p && j < even.length; ++ i, ++ j)
    {
        evenAns[i] ~= even[j];
    }
    evenIdx = j;
    for (t = 0, j = 0; t < k - p && j < odd.length; ++ t, ++ j)
    {
        oddAns[t] ~= odd[j];
    }
    oddIdx = j;
    if (t < k - p)
    {
        writeln("NO");
        return;
    }
    else if (i < p)
    {
        auto evenNeed = p - i;
        auto oddLeft = odd.length - oddIdx;
        if (oddLeft % 2 != 0 || (oddLeft >> 1) < evenNeed)
        {
            writeln("NO");
            return;
        }
        j = oddIdx;
        while (i < p)
        {
            evenAns[i] ~= odd[j];
            evenAns[i] ~= odd[j + 1];
            ++ i;
            j += 2;
        }
        while (j < odd.length)
        {
            evenAns[p - 1] ~= odd[j];
            ++ j;
        }
    }
    else
    {
        auto oddLeft = odd.length - oddIdx;
        if (oddLeft & 1)
        {
            writeln("NO");
            return;
        }
        for (j = oddIdx; j < odd.length; j += 2)
        {
            if (p > 0)
            {
                evenAns[p - 1] ~= odd[j];
                evenAns[p - 1] ~= odd[j + 1];
            }
            else
            {
                oddAns[k - p - 1] ~= odd[j];
                oddAns[k - p - 1] ~= odd[j + 1];
            }
        }
        for (j = evenIdx; j < even.length; ++ j)
        {
            if (p > 0)
            {
                evenAns[p - 1] ~= even[j];
            }
            else
            {
                oddAns[k - p - 1] ~= even[j];
            }
        }
    }
    writeln("YES");
    foreach (idx; 0 .. p)
    {
        writef("%d ", evenAns[idx].length);
        foreach (val; evenAns[idx])
        {
            writef("%d ", val);
        }
        writeln();
    }
    foreach (idx; 0 .. k - p)
    {
        writef("%d ", oddAns[idx].length);
        foreach (val; oddAns[idx])
        {
            writef("%d ", val);
        }
        writeln();
    }
}

int main(string[] args)
{
    int n, k, p;
    while (scanf("%d%d%d", &n, &k, &p) == 3)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            scanf("%d", &a[i]);
        }
        solve(a, n, k, p);
    }
    return 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; }

int N, K, P;
int[] A;

int[][] solve() {
	int[][] as = new int[][2];
	foreach (a; A) {
		as[a % 2] ~= a;
	}
	if (as[1].length < K - P) {
		return null;
	}
	int[][][] rets = new int[][][2];

	int[] rs;
	foreach (idx, a; as[1]) {
		if (idx < K - P) {
			rets[1] ~= [ a ];
		} else {
			rs ~= a;
		}
	}
	if (rs.length % 2 != 0) {
		return null;
	}

	int[][] groups;
	foreach (a; as[0]) {
		groups ~= [ a ];
	}
	for (int j = 0; j < rs.length; j += 2) {
		groups ~= rs[j .. j + 2];
	}
	if (groups.length < P) {
		return null;
	}
	foreach (idx, group; groups) {
		if (idx < P) {
			rets[0] ~= group;
		} else {
			rets[(0 < P) ? 0 : 1][0] ~= group;
		}
	}
	return rets[0] ~ rets[1];
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		K = readInt;
		P = readInt;
		A = new int[N];
		foreach (i; 0 .. N) {
			A[i] = readInt;
		}

		if (auto res = solve) {
			writeln("YES");
			foreach (line; res) {
				writeln(line.length, " ", line.to!string.removechars("[],"));
			}
		} else {
			writeln("NO");
		}
	}
	} catch (EOFException) {}
}

module main;

import std.stdio, std.string;

void solve(int[] a, int n, int k, int p)
{
    int[] odd, even;
    foreach (i, val; a)
    {
        if (val & 1)
        {
            odd ~= val;
        }
        else
        {
            even ~= val;
        }
    }
    auto evenAns = new int[][p];
    auto oddAns = new int[][k - p];
    int i, j, t, oddIdx, evenIdx;
    for (i = 0, j = 0; i < p && j < even.length; ++ i, ++ j)
    {
        evenAns[i] ~= even[j];
    }
    evenIdx = j;
    for (t = 0, j = 0; t < k - p && j < odd.length; ++ t, ++ j)
    {
        oddAns[t] ~= odd[j];
    }
    oddIdx = j;
    if (t < k - p)
    {
        writeln("NO");
        return;
    }
    else if (i < p)
    {
        auto evenNeed = p - i;
        auto oddLeft = odd.length - oddIdx;
        if (oddLeft % 2 != 0 || (oddLeft >> 1) < evenNeed)
        {
            writeln("NO");
            return;
        }
        j = oddIdx;
        while (i < p)
        {
            evenAns[i] ~= odd[j];
            evenAns[i] ~= odd[j + 1];
            ++ i;
            ++ j;
        }
        while (j < odd.length)
        {
            evenAns[$ - 1] ~= odd[j];
            ++ j;
        }
    }
    else
    {
        auto oddLeft = odd.length - oddIdx;
        if (oddLeft & 1)
        {
            writeln("NO");
            return;
        }
        for (j = oddIdx; j < odd.length; j += 2)
        {
            evenAns[$ - 1] ~= odd[j];
            evenAns[$ - 1] ~= odd[j + 1];
        }
        for (j = evenIdx; j < even.length; ++ j)
        {
            evenAns[$ - 1] ~= even[j];
        }
    }
    writeln("YES");
    foreach (idx; 0 .. p)
    {
        writef("%d ", evenAns[idx].length);
        foreach (val; evenAns[idx])
        {
            writef("%d ", val);
        }
        writeln();
    }
    foreach (idx; 0 .. k - p)
    {
        writef("%d ", oddAns[idx].length);
        foreach (val; oddAns[idx])
        {
            writef("%d ", val);
        }
        writeln();
    }
}

int main(string[] args)
{
    int n, k, p;
    while (scanf("%d%d%d", &n, &k, &p) == 3)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            scanf("%d", &a[i]);
        }
        solve(a, n, k, p);
    }
    return 0;
}

module main;

import std.stdio, std.string;

void solve(int[] a, int n, int k, int p)
{
    int[] odd, even;
    foreach (i, val; a)
    {
        if (val & 1)
        {
            odd ~= val;
        }
        else
        {
            even ~= val;
        }
    }
    auto evenAns = new int[][p];
    auto oddAns = new int[][k - p];
    int i, j, t, oddIdx, evenIdx;
    for (i = 0, j = 0; i < p && j < even.length; ++ i, ++ j)
    {
        evenAns[i] ~= even[j];
    }
    evenIdx = j;
    for (t = 0, j = 0; t < k - p && j < odd.length; ++ t, ++ j)
    {
        oddAns[t] ~= odd[j];
    }
    oddIdx = j;
    if (t < k - p)
    {
        writeln("NO");
        return;
    }
    else if (i < p)
    {
        auto evenNeed = p - i;
        auto oddLeft = odd.length - oddIdx;
        if (oddLeft % 2 != 0 || (oddLeft << 1) < evenNeed)
        {
            writeln("NO");
            return;
        }
        j = oddIdx;
        while (i < p)
        {
            evenAns[i] ~= odd[j];
            evenAns[i] ~= odd[j + 1];
            ++ i;
            ++ j;
        }
        while (j < odd.length)
        {
            evenAns[$ - 1] ~= odd[j];
            ++ j;
        }
    }
    else
    {
        auto oddLeft = odd.length - oddIdx;
        if (oddLeft & 1)
        {
            writeln("NO");
            return;
        }
        for (j = oddIdx; j < odd.length; j += 2)
        {
            evenAns[$ - 1] ~= odd[j];
            evenAns[$ - 1] ~= odd[j + 1];
        }
        for (j = evenIdx; j < even.length; ++ j)
        {
            evenAns[$ - 1] ~= even[j];
        }
    }
    writeln("YES");
    foreach (idx; 0 .. p)
    {
        writef("%d ", evenAns[idx].length);
        foreach (val; evenAns[idx])
        {
            writef("%d ", val);
        }
        writeln();
    }
    foreach (idx; 0 .. k - p)
    {
        writef("%d ", oddAns[idx].length);
        foreach (val; oddAns[idx])
        {
            writef("%d ", val);
        }
        writeln();
    }
}

int main(string[] args)
{
    int n, k, p;
    while (scanf("%d%d%d", &n, &k, &p) == 3)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            scanf("%d", &a[i]);
        }
        solve(a, n, k, p);
    }
    return 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; }

int N, K, P;
int[] A;

int[][] solve() {
	int[][] as = new int[][2];
	foreach (a; A) {
		as[a % 2] ~= a;
	}
	if (as[1].length < K - P) {
		return null;
	}
	if ((as[1].length - (K - P)) % 2 != 0) {
		return null;
	}
	int[][][] rets = new int[][][2];
	int[] rs = as[0];
	foreach (idx, a; as[1]) {
		if (idx < K - P) {
			rets[1] ~= [ a ];
		} else {
			rs ~= a;
		}
	}
	foreach (idx, a; rs) {
		if (idx < P) {
			rets[0] ~= [ a ];
		} else {
			rets[0][0] ~= a;
		}
	}
	return rets[0] ~ rets[1];
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		K = readInt;
		P = readInt;
		A = new int[N];
		foreach (i; 0 .. N) {
			A[i] = readInt;
		}

		if (auto res = solve) {
			writeln("YES");
			foreach (line; res) {
				writeln(line.length, " ", line.to!string.removechars("[],"));
			}
		} else {
			writeln("NO");
		}
	}
	} catch (EOFException) {}
}


You are given a sequence $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ pairwise distinct positive integers.Find $$$\left\lfloor \frac n 2 \right\rfloor$$$ different pairs of integers $$$x$$$ and $$$y$$$ such that:   $$$x \neq y$$$;  $$$x$$$ and $$$y$$$ appear in $$$a$$$;  $$$x~mod~y$$$ doesn't appear in $$$a$$$. Note that some $$$x$$$ or $$$y$$$ can belong to multiple pairs.$$$\lfloor x \rfloor$$$ denotes the floor function — the largest integer less than or equal to $$$x$$$. $$$x~mod~y$$$ denotes the remainder from dividing $$$x$$$ by $$$y$$$.If there are multiple solutions, print any of them. It can be shown that at least one solution always exists.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of the sequence. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$). All numbers in the sequence are pairwise distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

The answer for each testcase should contain $$$\left\lfloor \frac n 2 \right\rfloor$$$ different pairs of integers $$$x$$$ and $$$y$$$ such that $$$x \neq y$$$, $$$x$$$ and $$$y$$$ appear in $$$a$$$ and $$$x~mod~y$$$ doesn't appear in $$$a$$$. Print the pairs one after another. You can print the pairs in any order. However, the order of numbers in the pair should be exactly such that the first number is $$$x$$$ and the second number is $$$y$$$. All pairs should be pairwise distinct. If there are multiple solutions, print any of them.

NoteIn the first testcase there are only two pairs: $$$(1, 4)$$$ and $$$(4, 1)$$$. $$$\left\lfloor \frac 2 2 \right\rfloor=1$$$, so we have to find one pair. $$$1~mod~4=1$$$, and $$$1$$$ appears in $$$a$$$, so that pair is invalid. Thus, the only possible answer is a pair $$$(4, 1)$$$.In the second testcase, we chose pairs $$$8~mod~2=0$$$ and $$$8~mod~4=0$$$. $$$0$$$ doesn't appear in $$$a$$$, so that answer is valid. There are multiple possible answers for that testcase.In the third testcase, the chosen pairs are $$$9~mod~5=4$$$ and $$$7~mod~5=2$$$. Neither $$$4$$$, nor $$$2$$$, appears in $$$a$$$, so that answer is valid.

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

struct S { int x, y; };

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array.sort.array;
    bool[int] nums;
    foreach (x ; a)
      nums[x] = true;
    bool[S] used;
    S[] ans;

    while (ans.length < n / 2) {
      int x = a[uniform(0, a.length)];
      int y = a[uniform(0, a.length)];
again:
      if (x < y)
        swap(x, y);
      if (x == y || (S(x, y) in used))
        continue;
      int z = x % y;
      if (!(z in nums)) {
        ans ~= S(x, y);
        used[S(x, y)] = true;
      } else {
        y = z;
        goto again;
      }
    }
    foreach (tmp ; ans) {
      writefln("%d %d", tmp.x, tmp.y);
    }
  }
}

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

void solve(){
    auto n = scan!int;
    auto arr = scanArray;
    arr.sort;
    auto k = arr[0];
    for(int i = n/2 + (n % 2 != 0); i < n; ++i){
        writeln(arr[i], " ", k);
    }
}

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

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

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto a = ma(n, readInt!int);
  sort(a);
  foreach(i; 1 .. 1 + n/2)
    {
      writeln(a[i], " ", a[0]);
    }
  writeln;
}

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

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

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

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

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

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

struct S { int x, y; };

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array.sort.array;
    bool[int] nums;
    foreach (x ; a)
      nums[x] = true;
    bool[S] used;
    S[] ans;
    foreach_reverse (j ; 0 .. a.length) {
      foreach (i ; 0 .. j) {
        int x = a[j];
        int y = a[i];
        if ((S(x, y) in used) || ((x % y) in nums))
          continue;
        ans ~= S(x, y);
        used[S(x, y)] = true;
      }
    }
/*
    while (ans.length < n / 2) {
      int x = a[uniform(0, a.length)];
      int y = a[uniform(0, a.length)];
      if (x < y)
        swap(x, y);
      if (x == y || (S(x, y) in used) || ((x % y) in nums))
        continue;
      ans ~= S(x, y);
      used[S(x, y)] = true;
    }
*/
    foreach (tmp ; ans) {
      writefln("%d %d", tmp.x, tmp.y);
    }
  }
}


Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied: The picture is connected, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side). Each gray cell has an even number of gray neighbours. There are exactly $$$n$$$ gray cells with all gray neighbours. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed).Leo Jr. is now struggling to draw a beautiful picture with a particular choice of $$$n$$$. Help him, and provide any example of a beautiful picture.To output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin $$$(0, 0)$$$, axes $$$0x$$$ and $$$0y$$$ are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.

The only line contains a single integer $$$n$$$ ($$$1 \leq n \leq 500$$$) — the number of gray cells with all gray neighbours in a beautiful picture.

In the first line, print a single integer $$$k$$$ — the number of gray cells in your picture. For technical reasons, $$$k$$$ should not exceed $$$5 \cdot 10^5$$$. Each of the following $$$k$$$ lines should contain two integers — coordinates of a gray cell in your picture. All listed cells should be distinct, and the picture should satisdfy all the properties listed above. All coordinates should not exceed $$$10^9$$$ by absolute value. One can show that there exists an answer satisfying all requirements with a small enough $$$k$$$.

NoteThe answer for the sample is pictured below:

import std.algorithm;
import std.conv;
import std.numeric;
import std.stdio;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		writeln (n * 3 + 4);
		writeln (0, " ", 0);
		foreach (i; 0..n + 1)
		{
			foreach (j; 0..2)
			{
				foreach (k; 0..2)
				{
					if (j + k > 0)
					{
						writeln (i + j, " ", i + k);
					}
				}
			}
		}
	}
}

// Code By H~$~C

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

void _Main() {
  int n;
  readf!" %s"(n);
  writeln(3 * n + 4);
  writeln("0 0\n0 1");
  foreach(i; 0 .. n) {
    writefln!"%s %s\n%s %s\n%s %s"(i + 1, i, i + 1, i + 1, i + 1, i + 2);
  }
  writefln!"%s %s\n%s %s"(n + 1, n, n + 1, n + 1);
}

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

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      debug {
        writeln("N = ", N);
      }

      writeln(3 * (N + 1) + 1);
      foreach (i; 0 .. N + 1) {
        writeln(i, " ", i);
        writeln(i, " ", i + 1);
        writeln(i + 1, " ", i);
      }
      writeln(N + 1, " ", N + 1);
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	writeln(4 + n * 3);
	writeln("0 0");
	writeln("0 1");
	writeln("1 0");
	writeln("1 1");

	foreach (i; 0..n)
	{
		writeln(i+2, " ", i+2);
		writeln(i+1, " ", i+2);
		writeln(i+2, " ", i+1);
	}

	stdout.flush;
	debug readln;
}

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();
      debug {
        writeln("N = ", N);
      }

      foreach (i; 0 .. N + 1) {
        writeln(i, " ", i);
        writeln(i, " ", i + 1);
        writeln(i + 1, " ", i);
      }
      writeln(N + 1, " ", N + 1);
    }
  } catch (EOFException e) {
  }
}


A permutation $$$p$$$ of length $$$n$$$ is called almost perfect if for all integer $$$1 \leq i \leq n$$$, it holds that $$$\lvert p_i - p^{-1}_i \rvert \le 1$$$, where $$$p^{-1}$$$ is the inverse permutation of $$$p$$$ (i.e. $$$p^{-1}_{k_1} = k_2$$$ if and only if $$$p_{k_2} = k_1$$$).Count the number of almost perfect permutations of length $$$n$$$ modulo $$$998244353$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of each test case follows. The first and only line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 3 \cdot 10^5$$$) — the length of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, output a single integer — the number of almost perfect permutations of length $$$n$$$ modulo $$$998244353$$$.

NoteFor $$$n = 2$$$, both permutations $$$[1, 2]$$$, and $$$[2, 1]$$$ are almost perfect.For $$$n = 3$$$, there are only $$$6$$$ permutations. Having a look at all of them gives us:  $$$[1, 2, 3]$$$ is an almost perfect permutation.  $$$[1, 3, 2]$$$ is an almost perfect permutation.  $$$[2, 1, 3]$$$ is an almost perfect permutation.  $$$[2, 3, 1]$$$ is NOT an almost perfect permutation ($$$\lvert p_2 - p^{-1}_2 \rvert = \lvert 3 - 1 \rvert = 2$$$).  $$$[3, 1, 2]$$$ is NOT an almost perfect permutation ($$$\lvert p_2 - p^{-1}_2 \rvert = \lvert 1 - 3 \rvert = 2$$$).  $$$[3, 2, 1]$$$ is an almost perfect permutation. So we get $$$4$$$ almost perfect permutations.

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

immutable int mod = 998_244_353;
immutable int limit = 300_005;

int [] f;
int [] fi;
int [] f2;
int [] p2;

int powMod (int a, int p)
{
	int res = 1;
	for ( ; p > 0; p >>= 1)
	{
		if (p & 1)
		{
			res = (res * 1L * a) % mod;
		}
		a = (a * 1L * a) % mod;
	}
	return res;
}

int invMod (int a)
{
	return powMod (a, mod - 2);
}

int choose (int n, int k)
{
	auto res = f[n];
	res = (res * 1L * fi[n - k]) % mod;
	res = (res * 1L * fi[k]) % mod;
	return res;
}

void prepare ()
{
	f = new int [limit + 1];
	f[0] = 1;
	foreach (i; 1..limit + 1)
	{
		f[i] = (f[i - 1] * 1L * i) % mod;
	}

	fi = new int [limit + 1];
	fi[0] = 1;
	foreach (i; 1..limit + 1)
	{
		fi[i] = invMod (f[i]);
	}

	f2 = new int [limit + 1];
	f2[0] = 1;
	f2[1] = 1;
	foreach (i; 2..limit + 1)
	{
		f2[i] = (f2[i - 2] * 1L * i) % mod;
	}

	p2 = new int [limit + 1];
	p2[0] = 1;
	foreach (i; 1..limit + 1)
	{
		p2[i] = (p2[i - 1] * 2) % mod;
	}
}

void main ()
{
	prepare ();
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);

		auto g = new int [n + 1];
		g[0] = 1;
		g[1] = 1;
		foreach (i; 2..n + 1)
		{
			g[i] = (g[i - 1] + g[i - 2] * (i - 1L)) % mod;
		}

		int res = 0;
		for (int k = 0; 4 * k <= n; k++)
		{
			int temp = choose (n - 2 * k, 2 * k);
			temp = (temp * 1L * p2[k]) % mod;
			if (k > 0)
			{
				temp = (temp * 1L * f2[k * 2 - 1]) % mod;
			}
			temp = (temp * 1L * g[n - 4 * k]) % mod;
			res = (res + temp) % mod;
		}

		writeln (res);
	}
}


A rectangle with sides $$$A$$$ and $$$B$$$ is cut into rectangles with cuts parallel to its sides. For example, if $$$p$$$ horizontal and $$$q$$$ vertical cuts were made, $$$(p + 1) \cdot (q + 1)$$$ rectangles were left after the cutting. After the cutting, rectangles were of $$$n$$$ different types. Two rectangles are different if at least one side of one rectangle isn't equal to the corresponding side of the other. Note that the rectangle can't be rotated, this means that rectangles $$$a \times b$$$ and $$$b \times a$$$ are considered different if $$$a \neq b$$$.For each type of rectangles, lengths of the sides of rectangles are given along with the amount of the rectangles of this type that were left after cutting the initial rectangle.Calculate the amount of pairs $$$(A; B)$$$ such as the given rectangles could be created by cutting the rectangle with sides of lengths $$$A$$$ and $$$B$$$. Note that pairs $$$(A; B)$$$ and $$$(B; A)$$$ are considered different when $$$A \neq B$$$.

The first line consists of a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^{5}$$$) — amount of different types of rectangles left after cutting the initial rectangle. The next $$$n$$$ lines each consist of three integers $$$w_{i}, h_{i}, c_{i}$$$ $$$(1 \leq w_{i}, h_{i}, c_{i} \leq 10^{12})$$$ — the lengths of the sides of the rectangles of this type and the amount of the rectangles of this type. It is guaranteed that the rectangles of the different types are different.

Output one integer — the answer to the problem.

NoteIn the first sample there are three suitable pairs: $$$(1; 9)$$$, $$$(3; 3)$$$ and $$$(9; 1)$$$.In the second sample case there are 6 suitable pairs: $$$(2; 220)$$$, $$$(4; 110)$$$, $$$(8; 55)$$$, $$$(10; 44)$$$, $$$(20; 22)$$$ and $$$(40; 11)$$$.Here the sample of cut for $$$(20; 22)$$$.  The third sample has no suitable pairs.

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

alias Input = Tuple!(long, "w", long, "h", long, "c");

int N;
Input[] inputs;

long solve() {
  inputs.sort;
  debug {
    writeln("inputs = ", inputs);
  }

  int K = 0, L = -1;
  for (int i = 0, j; i < N; i = j) {
    for (j = i; j < N && inputs[i].w == inputs[j].w; ++j) {}
    ++K;
    if (L == -1) {
      L = j - i;
    }
    if (L != j - i) {
      debug {
        writeln("not rect");
      }
      return 0;
    }
  }
  debug {
    writeln("K = ", K, ", L = ", L);
  }

  auto ws = new long[K];
  auto hs = new long[L];
  foreach (e; 0 .. K) ws[e] = inputs[e * L + 0].w;
  foreach (f; 0 .. L) hs[f] = inputs[0 * L + f].h;
  foreach (e; 0 .. K) foreach (f; 0 .. L) {
    if (ws[e] != inputs[e * L + f].w) {
      debug {
        writeln("not rect (w)");
      }
      return 0;
    }
    if (hs[f] != inputs[e * L + f].h) {
      debug {
        writeln("not rect (h)");
      }
      return 0;
    }
  }

  auto xs = new long[K];
  auto ys = new long[L];
  foreach (e; 0 .. K) xs[e] = inputs[e * L + 0].c;
  foreach (f; 0 .. L) ys[f] = inputs[0 * L + f].c;
  const gx = xs.reduce!gcd;
  const gy = ys.reduce!gcd;
  xs[] /= gx;
  ys[] /= gy;
  debug {
    writeln("xs = ", xs);
    writeln("ys = ", ys);
  }

  long r = inputs[0 * L + 0].c / xs[0] / ys[0];
  foreach (e; 0 .. K) foreach (f; 0 .. L) {
    if (0 != inputs[e * L + f].c % xs[e]) {
      debug {
        writeln("not divisible by x");
      }
      return 0;
    }
    if (0 != inputs[e * L + f].c / xs[e] % ys[f]) {
      debug {
        writeln("not divisible by y");
      }
      return 0;
    }
    if (r != inputs[e * L + f].c / xs[e] / ys[f]) {
      debug {
        writeln("incorrect rate");
      }
    }
  }
  debug {
    writeln("r = ", r);
  }
  long ans;
  for (long d = 1; d^^2 <= r; ++d) {
    if (r % d == 0) {
      ++ans;
      if (d != r / d) {
        ++ans;
      }
    }
  }
  return ans;
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      inputs = new Input[N];
      foreach (i; 0 .. N) {
        inputs[i].w = readLong();
        inputs[i].h = readLong();
        inputs[i].c = readLong();
      }

      const res = solve();
      writeln(res);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

alias Input = Tuple!(long, "w", long, "h", long, "c");

int N;
Input[] inputs;

long solve() {
  inputs.sort;
  debug {
    writeln("inputs = ", inputs);
  }

  int K = 0, L = -1;
  for (int i = 0, j; i < N; i = j) {
    for (j = i; j < N && inputs[i].w == inputs[j].w; ++j) {}
    ++K;
    if (L == -1) {
      L = j - i;
    }
    if (L != j - i) {
      debug {
        writeln("not rect");
      }
      return 0;
    }
  }
  debug {
    writeln("K = ", K, ", L = ", L);
  }

  auto ws = new long[K];
  auto hs = new long[L];
  foreach (e; 0 .. K) ws[e] = inputs[e * L + 0].w;
  foreach (f; 0 .. L) hs[f] = inputs[0 * L + f].h;
  foreach (e; 0 .. K) foreach (f; 0 .. L) {
    if (ws[e] != inputs[e * L + f].w) {
      writeln("not rect (w)");
      return 0;
    }
    if (hs[f] != inputs[e * L + f].h) {
      writeln("not rect (h)");
      return 0;
    }
  }

  auto xs = new long[K];
  auto ys = new long[L];
  foreach (e; 0 .. K) xs[e] = inputs[e * L + 0].c;
  foreach (f; 0 .. L) ys[f] = inputs[0 * L + f].c;
  const gx = xs.reduce!gcd;
  const gy = ys.reduce!gcd;
  xs[] /= gx;
  ys[] /= gy;
  debug {
    writeln("xs = ", xs);
    writeln("ys = ", ys);
  }

  long r = inputs[0 * L + 0].c / xs[0] / ys[0];
  foreach (e; 0 .. K) foreach (f; 0 .. L) {
    if (0 != inputs[e * L + f].c % xs[e]) {
      writeln("not divisible by x");
      return 0;
    }
    if (0 != inputs[e * L + f].c / xs[e] % ys[f]) {
      writeln("not divisible by y");
      return 0;
    }
    if (r != inputs[e * L + f].c / xs[e] / ys[f]) {
      writeln("incorrect rate");
    }
  }
  debug {
    writeln("r = ", r);
  }
  long ans;
  for (long d = 1; d^^2 <= r; ++d) {
    if (r % d == 0) {
      ++ans;
      if (d != r / d) {
        ++ans;
      }
    }
  }
  return ans;
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      inputs = new Input[N];
      foreach (i; 0 .. N) {
        inputs[i].w = readLong();
        inputs[i].h = readLong();
        inputs[i].c = readLong();
      }

      const res = solve();
      writeln(res);
    }
  } catch (EOFException e) {
  }
}


You are given $$$n$$$ chips on a number line. The $$$i$$$-th chip is placed at the integer coordinate $$$x_i$$$. Some chips can have equal coordinates.You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:  Move the chip $$$i$$$ by $$$2$$$ to the left or $$$2$$$ to the right for free (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 2$$$ or with $$$x_i + 2$$$);  move the chip $$$i$$$ by $$$1$$$ to the left or $$$1$$$ to the right and pay one coin for this move (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 1$$$ or with $$$x_i + 1$$$). Note that it's allowed to move chips to any integer coordinate, including negative and zero.Your task is to find the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate (i.e. all $$$x_i$$$ should be equal after some sequence of moves).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of chips. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), where $$$x_i$$$ is the coordinate of the $$$i$$$-th chip.

Print one integer — the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate.

NoteIn the first example you need to move the first chip by $$$2$$$ to the right and the second chip by $$$1$$$ to the right or move the third chip by $$$2$$$ to the left and the second chip by $$$1$$$ to the left so the answer is $$$1$$$.In the second example you need to move two chips with coordinate $$$3$$$ by $$$1$$$ to the left so the answer is $$$2$$$.

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n = RD!int;
	auto x = RDA;
	long cnt;
	foreach (i; 0..n)
	{
		if (x[i] % 2 == 0)
			++cnt;
	}

	writeln(n - max(cnt, n - cnt));
	stdout.flush();
	debug readln();
}


This problem is an extension of the problem "Wonderful Coloring - 1". It has quite many differences, so you should read this statement completely.Recently, Paul and Mary have found a new favorite sequence of integers $$$a_1, a_2, \dots, a_n$$$. They want to paint it using pieces of chalk of $$$k$$$ colors. The coloring of a sequence is called wonderful if the following conditions are met:  each element of the sequence is either painted in one of $$$k$$$ colors or isn't painted;  each two elements which are painted in the same color are different (i. e. there's no two equal values painted in the same color);  let's calculate for each of $$$k$$$ colors the number of elements painted in the color — all calculated numbers must be equal;  the total number of painted elements of the sequence is the maximum among all colorings of the sequence which meet the first three conditions. E. g. consider a sequence $$$a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$$$ and $$$k=3$$$. One of the wonderful colorings of the sequence is shown in the figure.    The example of a wonderful coloring of the sequence $$$a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$$$ and $$$k=3$$$. Note that one of the elements isn't painted. Help Paul and Mary to find a wonderful coloring of a given sequence $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first one contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le k \le n$$$) — the length of a given sequence and the number of colors, respectively. The second one contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Output $$$t$$$ lines, each of them must contain a description of a wonderful coloring for the corresponding test case. Each wonderful coloring must be printed as a sequence of $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$0 \le c_i \le k$$$) separated by spaces where   $$$c_i=0$$$, if $$$i$$$-th element isn't painted;  $$$c_i>0$$$, if $$$i$$$-th element is painted in the $$$c_i$$$-th color.  Remember that you need to maximize the total count of painted elements for the wonderful coloring. If there are multiple solutions, print any one.

NoteIn the first test case, the answer is shown in the figure in the statement. The red color has number $$$1$$$, the blue color — $$$2$$$, the green — $$$3$$$.

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

void main()
{
	int t = readInt!int;
	while (t--)
	{
		solve();
	}
}

void solve()
{
	int n = readInt!int;
	int k = readInt!int;
	auto a = new Tuple!(int, int)[](n);
	foreach(i, ref ai; a)
	{
		ai = tuple(readInt!int, cast(int)i);
	}
	sort(a);
	auto cai = a.chunkBy!(v => v[0]).array;
	auto trash = new Tuple!(int, int)[](0);
	auto color = new int[](n);
	foreach(chunk; cai)
	{
		auto indices = chunk[1].array;
		debug writeln(chunk);
		if (indices.length >= k)
		{
			foreach(i; 0 .. k)
			{
				color[indices[i][1]] = i + 1;
			}
		}
		else
		{
			trash ~= chunk[1].array;
		}
	}
	while (trash.length >= k)
	{
		auto toFill = trash[0 .. k];
		foreach(i, t; toFill)
		{
			color[t[1]] = cast(int)i + 1;
		}
		trash = trash[k .. $];
	}
	foreach(c; color) c.write(" ");
	writeln;
}

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

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

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

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

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

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

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

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


Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's".The restaurant "Alice's" serves $$$n$$$ kinds of food. The cost for the $$$i$$$-th kind is always $$$c_i$$$. Initially, the restaurant has enough ingredients for serving exactly $$$a_i$$$ dishes of the $$$i$$$-th kind. In the New Year's Eve, $$$m$$$ customers will visit Alice's one after another and the $$$j$$$-th customer will order $$$d_j$$$ dishes of the $$$t_j$$$-th kind of food. The $$$(i + 1)$$$-st customer will only come after the $$$i$$$-th customer is completely served.Suppose there are $$$r_i$$$ dishes of the $$$i$$$-th kind remaining (initially $$$r_i = a_i$$$). When a customer orders $$$1$$$ dish of the $$$i$$$-th kind, the following principles will be processed. If $$$r_i > 0$$$, the customer will be served exactly $$$1$$$ dish of the $$$i$$$-th kind. The cost for the dish is $$$c_i$$$. Meanwhile, $$$r_i$$$ will be reduced by $$$1$$$. Otherwise, the customer will be served $$$1$$$ dish of the cheapest available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by $$$1$$$. If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is $$$0$$$.If the customer doesn't leave after the $$$d_j$$$ dishes are served, the cost for the customer will be the sum of the cost for these $$$d_j$$$ dishes.Please determine the total cost for each of the $$$m$$$ customers.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), representing the number of different kinds of food and the number of customers, respectively. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$), where $$$a_i$$$ denotes the initial remain of the $$$i$$$-th kind of dishes. The third line contains $$$n$$$ positive integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 10^6$$$), where $$$c_i$$$ denotes the cost of one dish of the $$$i$$$-th kind. The following $$$m$$$ lines describe the orders of the $$$m$$$ customers respectively. The $$$j$$$-th line contains two positive integers $$$t_j$$$ and $$$d_j$$$ ($$$1 \leq t_j \leq n$$$, $$$1 \leq d_j \leq 10^7$$$), representing the kind of food and the number of dishes the $$$j$$$-th customer orders, respectively.

Print $$$m$$$ lines. In the $$$j$$$-th line print the cost for the $$$j$$$-th customer.

NoteIn the first sample, $$$5$$$ customers will be served as follows. Customer $$$1$$$ will be served $$$6$$$ dishes of the $$$2$$$-nd kind, $$$1$$$ dish of the $$$4$$$-th kind, and $$$1$$$ dish of the $$$6$$$-th kind. The cost is $$$6 \cdot 3 + 1 \cdot 2 + 1 \cdot 2 = 22$$$. The remain of the $$$8$$$ kinds of food will be $$$\{8, 0, 2, 0, 4, 4, 7, 5\}$$$. Customer $$$2$$$ will be served $$$4$$$ dishes of the $$$1$$$-st kind. The cost is $$$4 \cdot 6 = 24$$$. The remain will be $$$\{4, 0, 2, 0, 4, 4, 7, 5\}$$$. Customer $$$3$$$ will be served $$$4$$$ dishes of the $$$6$$$-th kind, $$$3$$$ dishes of the $$$8$$$-th kind. The cost is $$$4 \cdot 2 + 3 \cdot 2 = 14$$$. The remain will be $$$\{4, 0, 2, 0, 4, 0, 7, 2\}$$$. Customer $$$4$$$ will be served $$$2$$$ dishes of the $$$3$$$-rd kind, $$$2$$$ dishes of the $$$8$$$-th kind. The cost is $$$2 \cdot 3 + 2 \cdot 2 = 10$$$. The remain will be $$$\{4, 0, 0, 0, 4, 0, 7, 0\}$$$. Customer $$$5$$$ will be served $$$7$$$ dishes of the $$$7$$$-th kind, $$$3$$$ dishes of the $$$1$$$-st kind. The cost is $$$7 \cdot 3 + 3 \cdot 6 = 39$$$. The remain will be $$$\{1, 0, 0, 0, 4, 0, 0, 0\}$$$.In the second sample, each customer is served what they order except the last one, who leaves angrily without paying. For example, the second customer is served $$$6$$$ dishes of the second kind, so the cost is $$$66 \cdot 6 = 396$$$.In the third sample, some customers may not be served what they order. For example, the second customer is served $$$6$$$ dishes of the second kind, $$$6$$$ of the third and $$$1$$$ of the fourth, so the cost is $$$66 \cdot 6 + 666 \cdot 6 + 6666 \cdot 1 = 11058$$$.

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

immutable long MOD = 998244353;

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

    auto B = N.iota.map!(i => tuple(C[i], i)).array;
    B.sort();
    int p = 0;

    foreach (_; 0..M) {

        s = readln.split.map!(to!int);
        auto t = s[0] - 1;
        auto d = s[1].to!long;
        long ans = 0;

        if (A[t] >= d) {
            writeln(C[t] * d);
            A[t] -= d;
        } else {
            ans += A[t] * C[t];
            d -= A[t];
            A[t] = 0;
            while (d > 0 && p < N) {
                while (p < N && A[B[p][1]] == 0) ++p;
                if (p >= N) break;
                long v = min(d, A[B[p][1]]);
                ans += v * C[B[p][1]];
                A[B[p][1]] -= v;
                d -= v;
            }
            if (d == 0) {
                writeln(ans);
            } else {
                writeln(0);
            }
        }
    }
}

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

enum inf3 = 1_001_001_001;
enum inf6 = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;

alias Dish = Tuple!(int, "cost", int, "index");

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

    auto ds = new Dish[](n);
    foreach (i ; 0 .. n) {
        ds[i] = Dish(c[i], i);
    }

    ds.sort!();

    foreach (j ; 0 .. m) {
        int tj, dj;
        scan(tj, dj);
        tj--;

        long ans;

        if (a[tj] > 0) {
            int x = min(dj, a[tj]);
            ans += 1L * x * c[tj];
            a[tj] -= x;
            dj -= x;
        }

        while (dj > 0 && !ds.empty) {
            int cost = ds.front.cost;
            int ind = ds.front.index;

            int x = min(dj, a[ind]);
            ans += 1L * x * c[ind];
            a[ind] -= x;
            dj -= x;

            if (a[ind] == 0) {
                ds.popFront();
            }
        }

        if (dj > 0) {
            ans = 0;
        }

        writeln(ans);
    }
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    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);
        }
    }
}


In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.You are given an integer array $$$a[1 \ldots n] = [a_1, a_2, \ldots, a_n]$$$.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[3, 4, 4]$$$ currently in the deque, adding an element $$$1$$$ to the beginning will produce the sequence $$$[\color{red}{1}, 3, 4, 4]$$$, and adding the same element to the end will produce $$$[3, 4, 4, \color{red}{1}]$$$.The elements of the array are sequentially added to the initially empty deque, starting with $$$a_1$$$ and finishing with $$$a_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or to the end.For example, if we consider an array $$$a = [3, 7, 5, 5]$$$, one of the possible sequences of actions looks like this: $$$\quad$$$ 1.add $$$3$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{3}]$$$ in it;$$$\quad$$$ 2.add $$$7$$$ to the end of the deque:deque has a sequence $$$[3, \color{red}{7}]$$$ in it;$$$\quad$$$ 3.add $$$5$$$ to the end of the deque:deque has a sequence $$$[3, 7, \color{red}{5}]$$$ in it;$$$\quad$$$ 4.add $$$5$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{5}, 3, 7, 5]$$$ in it;Find the minimal possible number of inversions in the deque after the whole array is processed. An inversion in sequence $$$d$$$ is a pair of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$d_i > d_j$$$. For example, the array $$$d = [5, 3, 7, 5]$$$ has exactly two inversions — $$$(1, 2)$$$ and $$$(3, 4)$$$, since $$$d_1 = 5 > 3 = d_2$$$ and $$$d_3 = 7 > 5 = d_4$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases.  The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — array size. The second line of the description contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the minimal possible number of inversions in the deque after executing the described algorithm.

NoteOne of the ways to get the sequence $$$[5, 3, 7, 5]$$$ in the deque, containing only two inversions, from the initial array $$$[3, 7, 5, 5]$$$ (the first sample test case) is described in the problem statement. Also, in this example, you could get the answer of two inversions by simply putting each element of the original array at the end of the deque. In this case, the original sequence $$$[3, 7, 5, 5]$$$, also containing exactly two inversions, will be in the deque as-is.

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

struct fw {
    int[] arr;
    int sz;

    this(int sz) {
        this.sz = sz;
        arr = new int[sz+1];
        arr[] = 0;
    }

    void add(int p) {
        while (p <= sz) {
            arr[p] += 1;
            p += (1 << p.bsf);
        }
    }

    int sum(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (1 << p.bsf);
        }

        return ret;
    }
}

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

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

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

        auto uni = arr.dup.sort.uniq.array;
        int[int] mapping;
        foreach (i, e; uni.enumerate(1)) { mapping[e] = i; }
        arr = arr.map!(x => mapping[x]).array;

        debug { writeln(uni, ' ' , mapping, ' ', arr); }

        auto f = fw(uni.length.to!int);
        long ans = 0;
        foreach (i, e; arr) {
            auto smaller = f.sum(e-1);
            auto bigger = i - f.sum(e);

            ans += min(smaller, bigger);

            f.add(e);
        }

        ans.writeln;
    }
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	int[2][] vis;
	auto ft = FenwickTree(n);
	foreach(i, ai; a) vis ~= [ai, cast(int)i];
	sort(vis);
	auto less = new int[](n);
	auto equal = new int[](n);
	{
		int i = 0;
		while (i < n)
		{
			auto v = vis[i][0];
			int[] _is;
			while (i < n && vis[i][0] == v)
			{
				_is ~= vis[i][1];
				i++;
			}
			int cnt = 0;
			foreach(j; _is)
			{
				less[j] = ft.sum(j-1);
				equal[j] = cnt++;
			}
			foreach(j; _is)
			{
				ft.add(j, 1);
			}
		}
	}
	auto deque = DList!int();
	long mininvs = 0;
	debug writeln(less);
	foreach(i; 0 .. n)
	{
		auto l = less[i];
		auto e = equal[i];
		auto g = i - l - e;
		mininvs += min(l, g);
	}
	writeln(mininvs);
}
struct FenwickTree {
	int[] bit;
	int n;

	this(int n) {
		this.n = n;
		bit = new int[](n);

	}

	int sum(int r) {
		int ret = 0;
		for (; r >= 0; r = (r & (r + 1)) - 1)
			ret += bit[r];
		return ret;
	}

	int sum(int l, int r) {
		return sum(r) - sum(l - 1);
	}

	void add(int idx, int delta) {
		for (; idx < n; idx = idx | (idx + 1))
			bit[idx] += delta;
	}
}

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

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

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

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

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

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

struct fw {
    int[] arr;
    int sz;

    this(int sz) {
        this.sz = sz;
        arr = new int[sz+1];
        arr[] = 0;
    }

    void add(int p) {
        while (p <= sz) {
            arr[p] += 1;
            p += (1 << p.bsf);
        }
    }

    int sum(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (1 << p.bsf);
        }

        return ret;
    }
}

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

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

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

        auto uni = arr.dup.sort.uniq.array;
        int[int] mapping;
        foreach (i, e; uni.enumerate(1)) { mapping[e] = i; }
        arr = arr.map!(x => mapping[x]).array;

        debug { writeln(uni, ' ' , mapping, ' ', arr); }

        auto f = fw(uni.length.to!int);
        int ans = 0;
        foreach (i, e; arr) {
            auto smaller = f.sum(e-1);
            auto bigger = i - f.sum(e);

            ans += min(smaller, bigger);

            f.add(e);
        }

        ans.writeln;
    }
}


You are given two arrays $$$a$$$ and $$$b$$$ of positive integers, with length $$$n$$$ and $$$m$$$ respectively. Let $$$c$$$ be an $$$n \times m$$$ matrix, where $$$c_{i,j} = a_i \cdot b_j$$$. You need to find a subrectangle of the matrix $$$c$$$ such that the sum of its elements is at most $$$x$$$, and its area (the total number of elements) is the largest possible.Formally, you need to find the largest number $$$s$$$ such that it is possible to choose integers $$$x_1, x_2, y_1, y_2$$$ subject to $$$1 \leq x_1 \leq x_2 \leq n$$$, $$$1 \leq y_1 \leq y_2 \leq m$$$, $$$(x_2 - x_1 + 1) \times (y_2 - y_1 + 1) = s$$$, and $$$$$$\sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} \leq x.$$$$$$

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 2000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2000$$$). The third line contains $$$m$$$ integers $$$b_1, b_2, \ldots, b_m$$$ ($$$1 \leq b_i \leq 2000$$$). The fourth line contains a single integer $$$x$$$ ($$$1 \leq x \leq 2 \cdot 10^{9}$$$).

If it is possible to choose four integers $$$x_1, x_2, y_1, y_2$$$ such that $$$1 \leq x_1 \leq x_2 \leq n$$$, $$$1 \leq y_1 \leq y_2 \leq m$$$, and $$$\sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} \leq x$$$, output the largest value of $$$(x_2 - x_1 + 1) \times (y_2 - y_1 + 1)$$$ among all such quadruplets, otherwise output $$$0$$$.

NoteMatrix from the first sample and the chosen subrectangle (of blue color):  Matrix from the second sample and the chosen subrectangle (of blue color):

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto t = readln.split.map!(to!int);
    auto H = t[0];
    auto W = t[1];
    auto A = readln.split.map!(to!long).array;
    auto B = readln.split.map!(to!long).array;
    auto X = readln.chomp.to!long;

    auto minA = new long[](H+1);
    auto minB = new long[](W+1);

    foreach (len; 1..H+1) {
        long s = 0;
        foreach (i; 0..len) s += A[i];
        minA[len] = s;
        foreach (i; len..H) {
            s = s - A[i-len] + A[i];
            minA[len] = min(minA[len], s);
        }
    }

    foreach (len; 1..W+1) {
        long s = 0;
        foreach (i; 0..len) s += B[i];
        minB[len] = s;
        foreach (i; len..W) {
            s = s - B[i-len] + B[i];
            minB[len] = min(minB[len], s);
        }
    }

    long ans = 0;
    foreach (i; 0..H+1) foreach (j; 0..W+1) if (minA[i] * minB[j] <= X) ans = max(ans, i * j);

    ans.writeln;
}

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto t = readln.split.map!(to!int);
    auto H = t[0];
    auto W = t[1];
    auto A = readln.split.map!(to!long).array;
    auto B = readln.split.map!(to!long).array;
    auto X = readln.chomp.to!long;

    auto minA = new long[](H+1);
    auto minB = new long[](W+1);

    foreach (len; 1..H+1) {
        long s = 0;
        foreach (i; 0..len) s += A[i];
        minA[len] = s;
        foreach (i; len..H-len+1) {
            s = s - A[i-len] + A[i];
            minA[len] = min(minA[len], s);
        }
    }

    foreach (len; 1..W+1) {
        long s = 0;
        foreach (i; 0..len) s += B[i];
        minB[len] = s;
        foreach (i; len..W-len+1) {
            s = s - B[i-len] + B[i];
            minB[len] = min(minB[len], s);
        }
    }

    long ans = 0;
    foreach (i; 0..H+1) foreach (j; 0..W+1) if (minA[i] * minB[j] <= X) ans = max(ans, i * j);

    ans.writeln;
}


Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!

The single line contains integers p, x (1 ≤ p ≤ 106, 1 ≤ x ≤ 9).

If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.

NoteSample 1: 142857·5 = 714285.Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".

import std.stdio;

int[1000010] ans, tmp;

void update(int[] tar, int[] data, int len)
{
    for (int idx = 0; idx < len; ++ idx)
    {
        tar[idx] = data[idx];
    }
}

void solve(int p, int x)
{
    bool succ = false;
    foreach (int last; 0 .. 10)
    {
        tmp[p - 1] = last;
        int carry = 0, val;
        for (int idx = p - 2; idx >= 0; -- idx)
        {
            val = x * tmp[idx + 1] + carry;
            tmp[idx] = val % 10;
            carry = val / 10;
        }
        if (tmp[0] == 0)
        {
            continue;
        }
        val = x * tmp[0] + carry;
        if (val % 10 == tmp[p - 1] && val / 10 == 0)
        {
            if (succ)
            {
                bool flag = false;
                for (int idx = 0; idx < p; ++ idx)
                {
                    if (tmp[idx] < ans[idx])
                    {
                        flag = true;
                    }
                    if (tmp[idx] != ans[idx])
                    {
                        break;
                    }
                }
                if (flag == true)
                {
                    update(ans, tmp, p);
                }
            }
            else
            {
                succ = true;
                update(ans, tmp, p);
            }
        }
    }
    if (succ)
    {
        for (int idx = 0; idx < p; ++ idx)
        {
            write(ans[idx]);
        }
        writeln();
    }
    else
    {
        writeln("Impossible");
    }
}

void main()
{
    int p, x;
    while (scanf("%d%d", &p, &x) == 2)
    {
        solve(p, x);
    }
}


Rick and Morty want to find MR. PBH and they can't do it alone. So they need of Mr. Meeseeks. They Have generated n Mr. Meeseeks, standing in a line numbered from 1 to n. Each of them has his own color. i-th Mr. Meeseeks' color is ai. Rick and Morty are gathering their army and they want to divide Mr. Meeseeks into some squads. They don't want their squads to be too colorful, so each squad should have Mr. Meeseeks of at most k different colors. Also each squad should be a continuous subarray of Mr. Meeseeks in the line. Meaning that for each 1 ≤ i ≤ e ≤ j ≤ n, if Mr. Meeseeks number i and Mr. Meeseeks number j are in the same squad then Mr. Meeseeks number e should be in that same squad.  Also, each squad needs its own presidio, and building a presidio needs money, so they want the total number of squads to be minimized.Rick and Morty haven't finalized the exact value of k, so in order to choose it, for each k between 1 and n (inclusive) need to know the minimum number of presidios needed.

The first line of input contains a single integer n (1 ≤ n ≤ 105) — number of Mr. Meeseeks. The second line contains n integers a1, a2, ..., an separated by spaces (1 ≤ ai ≤ n) — colors of Mr. Meeseeks in order they standing in a line.

In the first and only line of input print n integers separated by spaces. i-th integer should be the minimum number of presidios needed if the value of k is i.

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 bAdd(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    bit[x] += val;
  }
}

// sum of [0, pos)
T bSum(T)(T[] bit, int pos)
in {
  assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold");
}
do {
  T ret = 0;
  for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
    ret += bit[x];
  }
  return ret;
}

// min pos s.t. pred(sum of [0, pos))
//   assume pred(sum of [0, pos)) is non-decreasing
int bBinarySearch(alias pred, T)(T[] bit) {
  import core.bitop : bsr;
  import std.functional : unaryFun;
  alias predFun = unaryFun!pred;
  if (predFun(0)) return 0;
  int pos = 0;
  T sum = 0;
  foreach_reverse (e; 0 .. bsr(bit.length) + 1) {
    const x = (pos | 1 << e) - 1;
    if (x < bit.length && !predFun(sum + bit[x])) {
      pos |= 1 << e;
      sum += bit[x];
    }
  }
  return pos + 1;
}

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

      auto app = new int[N];
      app[] = -1;
      auto nxt = new int[N];
      foreach_reverse (i; 0 .. N) {
        nxt[i] = app[A[i]];
        app[A[i]] = i;
      }

      auto ans = new int[N + 1];
      auto kss = new int[][N];
      foreach (k; 1 .. N + 1) {
        kss[0] ~= k;
      }

      auto bit = new int[N];
      foreach (a; 0 .. N) {
        if (app[a] != -1) {
          bit.bAdd(app[a], +1);
        }
      }
      foreach (i; 0 .. N) {
        foreach (k; kss[i]) {
          ++ans[k];
          const pos = bit.bBinarySearch!(s => (s > k)) - 1;
          if (pos < N) {
            kss[pos] ~= k;
          }
        }
        bit.bAdd(i, -1);
        if (nxt[i] != -1) {
          bit.bAdd(nxt[i], +1);
        }
      }

      foreach (k; 1 .. N + 1) {
        if (k > 1) write(" ");
        write(ans[k]);
      }
      writeln;
    }
  } catch (EOFException e) {
  }
}


Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string $$$a$$$ consisting of lowercase English letters. The string $$$a$$$ has a length of $$$2$$$ or more characters. Then, from string $$$a$$$ he builds a new string $$$b$$$ and offers Alice the string $$$b$$$ so that she can guess the string $$$a$$$.Bob builds $$$b$$$ from $$$a$$$ as follows: he writes all the substrings of length $$$2$$$ of the string $$$a$$$ in the order from left to right, and then joins them in the same order into the string $$$b$$$.For example, if Bob came up with the string $$$a$$$="abac", then all the substrings of length $$$2$$$ of the string $$$a$$$ are: "ab", "ba", "ac". Therefore, the string $$$b$$$="abbaac".You are given the string $$$b$$$. Help Alice to guess the string $$$a$$$ that Bob came up with. It is guaranteed that $$$b$$$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.

The first line contains a single positive integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case consists of one line in which the string $$$b$$$ is written, consisting of lowercase English letters ($$$2 \le |b| \le 100$$$) — the string Bob came up with, where $$$|b|$$$ is the length of the string $$$b$$$. It is guaranteed that $$$b$$$ was built according to the algorithm given above.

Output $$$t$$$ answers to test cases. Each answer is the secret string $$$a$$$, consisting of lowercase English letters, that Bob came up with.

NoteThe first test case is explained in the statement.In the second test case, Bob came up with the string $$$a$$$="ac", the string $$$a$$$ has a length $$$2$$$, so the string $$$b$$$ is equal to the string $$$a$$$.In the third test case, Bob came up with the string $$$a$$$="bcdaf", substrings of length $$$2$$$ of string $$$a$$$ are: "bc", "cd", "da", "af", so the string $$$b$$$="bccddaaf".

import std.stdio;
import std.range;
import std.string : strip;

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

  foreach (i; 0..t) {
    auto s = readln.strip;
    writeln(s.takeOne.chain(s.dropOne.stride(2)));
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new string[](t);
	foreach (ti; 0..t)
	{
		auto b = RD!string;
		auto begin = b[0];
		auto end = b[$-1];
		foreach (i; 1..b.length-1)
		{
			if (i % 2 == 0) continue;
			ans[ti] ~= b[i];
		}
		ans[ti] = begin ~ ans[ti] ~ end;
	}

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


You are given a chessboard of size $$$n \times n$$$. It is filled with numbers from $$$1$$$ to $$$n^2$$$ in the following way: the first $$$\lceil \frac{n^2}{2} \rceil$$$ numbers from $$$1$$$ to $$$\lceil \frac{n^2}{2} \rceil$$$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $$$n^2 - \lceil \frac{n^2}{2} \rceil$$$ numbers from $$$\lceil \frac{n^2}{2} \rceil + 1$$$ to $$$n^2$$$ are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation $$$\lceil\frac{x}{y}\rceil$$$ means division $$$x$$$ by $$$y$$$ rounded up.For example, the left board on the following picture is the chessboard which is given for $$$n=4$$$ and the right board is the chessboard which is given for $$$n=5$$$.  You are given $$$q$$$ queries. The $$$i$$$-th query is described as a pair $$$x_i, y_i$$$. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le q \le 10^5$$$) — the size of the board and the number of queries. The next $$$q$$$ lines contain two integers each. The $$$i$$$-th line contains two integers $$$x_i, y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — description of the $$$i$$$-th query.

For each query from $$$1$$$ to $$$q$$$ print the answer to this query. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$. Queries are numbered from $$$1$$$ to $$$q$$$ in order of the input.

NoteAnswers to the queries from examples are on the board in the picture from the problem statement.

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

void main() {
    auto s = readln.split.map!(to!long);
    auto N = s[0];
    auto Q = s[1];

    while (Q--) {
        s = readln.split.map!(to!long);
        auto r = s[0];
        auto c = s[1];
        if ((r + c) % 2 == 0) {
            long odd = r / 2;
            long even = r - 1 - odd;
            long n = odd * (N / 2 + N % 2) + even * (N / 2);
            writeln(n + (c - 1) / 2 + 1);
        } else {
            long odd = r / 2;
            long even = r - 1 - odd;
            long n = odd * (N / 2) + even * (N / 2 + N % 2);
            n += N * N / 2 + N % 2;
            writeln(n + (c - 1) / 2 + 1);
        }
    }
}

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

long f(int n, int x, int y) {
    auto sumOdd = (x+y) % 2 == 1;
    auto rowOdd = x % 2 == 1;
    auto prevRows = n % 2 == 0 ?
        cast(long)(x-1) * n/2 :
        cast(long)(x-1)/2 * (n/2 + n/2 + 1) + (!rowOdd ? (sumOdd ? n/2 : n/2+1) : 0);
    auto prevCols = (y-1) / 2;
    return 1 + prevRows + prevCols + (sumOdd ? f(n, n, n) : 0);
}

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

    while (q--) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        f(n, x, y).writeln;
    }
}

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

void main() {
    auto s = readln.split.map!(to!long);
    auto N = s[0];
    auto Q = s[1];

    while (Q--) {
        s = readln.split.map!(to!long);
        auto r = s[0];
        auto c = s[1];
        if ((r + c) % 2 == 0) {
            long odd = r / 2;
            long even = r - 1 - odd;
            long n = odd * (N / 2 + N % 2) + even * N / 2;
            writeln(n + (c - 1) / 2 + 1);
        } else {
            long odd = r / 2;
            long even = r - 1 - odd;
            long n = odd * N / 2 + even * (N / 2 + N % 2);
            n += N * N / 2 + N % 2;
            writeln(n + (c - 1) / 2 + 1);
        }
    }
}