Jzzhu has two integers, n and m. He calls an integer point (x, y) of a plane special if 0 ≤ x ≤ n and 0 ≤ y ≤ m. Jzzhu defines a unit square as a square with corners at points (x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1), where x and y are some integers.Let's look at all the squares (their sides not necessarily parallel to the coordinate axes) with corners at the special points. For each such square Jzzhu paints a dot in every unit square that is fully inside it. After that some unit squares can contain several dots. Now Jzzhu wonders, how many dots he has painted on the plane. Find this number modulo 1000000007 (109 + 7).

The first line contains a single integer t (1 ≤ t ≤ 105) — the number of tests. Each of the next t lines contains the description of the test: two integers n and m (1 ≤ n, m ≤ 106) — the value of variables for the current test.

For each test output the total number of dots modulo 1000000007 (109 + 7).

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

//	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, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	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)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, 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)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

immutable long MO = 1000000007;

struct Mint {
	long v;
	this(long v = 0) {
		if ((this.v = v % MO) < 0) this.v += MO;
	}
	Mint opUnary(string op)() {
		static if (op == "-" || op == "+") {
			return mixin(op ~ "v");
		} else static if (op == "++" || op == "--") {
			return this = mixin(op ~ "v");
		}
	}
	Mint opBinary(string op)(const Mint a) const {
		static if (op == "+" || op == "-" || op == "*") {
			return Mint(mixin("v" ~ op ~ "a.v"));
		} else static if (op == "/") {
			assert(a.v != 0);
			return this * a ^^ (MO - 2);
		}
	}
	Mint opBinary(string op)(long a) const {
		static if (op == "^^") {
			Mint ret = 1, x = this;
			for (; a; a >>= 1, x *= x) if (a & 1) ret *= x;
			return ret;
		} else {
			return mixin("this" ~ op ~ "Mint(a)");
		}
	}
	Mint opAssign(long v) {
		return this = Mint(v);
	}
	Mint opOpAssign(string op)(const Mint a) {
		static if (op == "+" || op == "-" || op == "*" || op == "/") {
			return this = mixin("this" ~ op ~ "a");
		}
	}
	Mint opOpAssign(string op)(long a) {
		return this = mixin("this" ~ op ~ "a");
	}
	string toString() const {
		return v.to!string;
	}
	unittest {
		Mint a = -1;
		assert(a.v == MO - 1);
		++a;
		assert(a.v == 0);
		--a;
		assert(a.v == MO - 1);
		Mint b = 1_000_000_000;
		b += 1_000_000_000;
		assert(b.v == 2_000_000_000 % MO);
		b = 2;
		b -= 4;
		assert(b.v == MO - 2);
		b = 1_000_000_000;
		b *= 1_000_000_000;
		assert(b.v == 1_000_000_000_000_000_000 % MO);
		Mint c = -10;
		c /= 14;
		c *= 7;
		assert(c.v == MO - 5);
	}
}

long gcd(long a, long b) {
	return (b != 0) ? gcd(b, a % b) : a;
}

immutable LIM = 1000005;

/*
long[] phi;
long gcdSum(long n) {
	long ret;
	for (long d = 1; d * d <= n; ++d) if (n % d == 0) {
		ret += d * phi[cast(size_t)(n / d)];
		if (d != n / d) {
			ret += (n / d) * phi[cast(size_t)(d)];
		}
	}
	return ret;
}
*/

void main(string[] args) {
	long[] phi = new long[LIM];
	foreach (i; 1 .. LIM) phi[i] = i;
	foreach (i; 1 .. LIM) for (int j = i * 2; j < LIM; j += i) phi[j] -= phi[i];
// writeln("phi = ",phi[0..30]);
	long[] gcdSums = new long[LIM];
	foreach (i; 1 .. LIM) for (int j = i; j < LIM; j += i) {
		gcdSums[j] += i * phi[j / i];
	}

	Mint[] k1 = new Mint[LIM + 1];
	Mint[] k2 = new Mint[LIM + 1];
	Mint[] k3 = new Mint[LIM + 1];
	Mint[] k4 = new Mint[LIM + 1];
	foreach (k; 0 .. LIM) {
		k1[k + 1] = k1[k] + Mint(k) ^^ 1;
		k2[k + 1] = k2[k] + Mint(k) ^^ 2;
		k3[k + 1] = k3[k] + Mint(k) ^^ 3;
		k4[k + 1] = k4[k] + Mint(k) ^^ 4;
	}
// writeln("k1 = ",k1[0..10]);
// writeln("k2 = ",k2[0..10]);
// writeln("k3 = ",k3[0..10]);
// writeln("k4 = ",k4[0..10]);
	Mint[] k0a = new Mint[LIM + 1];
	Mint[] k1a = new Mint[LIM + 1];
	Mint[] k2a = new Mint[LIM + 1];
	foreach (k; 0 .. LIM) {
		k0a[k + 1] = k0a[k] + Mint(k) ^^ 0 * k2[k];
		k1a[k + 1] = k1a[k] + Mint(k) ^^ 1 * k2[k];
		k2a[k + 1] = k2a[k] + Mint(k) ^^ 2 * k2[k];
	}
// writeln("k0a = ",k0a[0..10]);
// writeln("k1a = ",k1a[0..10]);
// writeln("k2a = ",k2a[0..10]);
	Mint[] k0g = new Mint[LIM + 1];
	Mint[] k1g = new Mint[LIM + 1];
	Mint[] k2g = new Mint[LIM + 1];
	foreach (k; 0 .. LIM) {
		// const g = gcdSum(k);
// if(k<10)writeln("gcdSum(",k,") = ",g);
		const g = gcdSums[k] - k;
		k0g[k + 1] = k0g[k] + Mint(k) ^^ 0 * g;
		k1g[k + 1] = k1g[k] + Mint(k) ^^ 1 * g;
		k2g[k + 1] = k2g[k] + Mint(k) ^^ 2 * g;
	}
// writeln("k0g = ",k0g[0..10]);
// writeln("k1g = ",k1g[0..10]);
// writeln("k2g = ",k2g[0..10]);

	// try {
	for (int TC = readInt; TC--; ) {
		const M = readLong;
		const N = readLong;

		const L = min(M, N);

		/*
		long brt;
		foreach (k; 1 .. L + 1) {
			brt += (M - k + 1) * (N - k + 1) * k ^^ 2;
		}
		foreach (a; 1 .. L) foreach (b; 1 .. L) if (a + b <= L) {
			brt += (M - (a + b) + 1) * (N - (a + b) + 1) * (a ^^ 2 + b ^^ 2 - 2 * (a + b - gcd(a, b)));
		}
		writeln("brt = ", brt);
		//*/

		const m = Mint(M);
		const n = Mint(N);
		const l = cast(size_t)(L);
		Mint ans;

		ans += (m + 1) * (n + 1) * k2[l + 1];
		ans -= (m + 1) * k3[l + 1];
		ans -= (n + 1) * k3[l + 1];
		ans += k4[l + 1];

		ans += (m + 1) * (n + 1) * 2 * k0a[l + 1];
		ans -= (m + 1) * 2 * k1a[l + 1];
		ans -= (n + 1) * 2 * k1a[l + 1];
		ans += Mint(1) * 2 * k2a[l + 1];

		ans -= (m + 1) * (n + 1) * 2 * (k2[l + 1] - k1[l + 1]);
		ans += (m + 1) * 2 * (k3[l + 1] - k2[l + 1]);
		ans += (n + 1) * 2 * (k3[l + 1] - k2[l + 1]);
		ans -= Mint(1) * 2 * (k4[l + 1] - k3[l + 1]);

		ans += (m + 1) * (n + 1) * 2 * k0g[l + 1];
		ans -= (m + 1) * 2 * k1g[l + 1];
		ans -= (n + 1) * 2 * k1g[l + 1];
		ans += Mint(1) * 2 * k2g[l + 1];

		writeln(ans);

	}
	// } catch (EOFException) {}
}

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

//	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, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	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)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, 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)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

immutable long MO = 1000000007;

struct Mint {
	long v;
	this(long v = 0) {
		if ((this.v = v % MO) < 0) this.v += MO;
	}
	Mint opUnary(string op)() {
		static if (op == "-" || op == "+") {
			return mixin(op ~ "v");
		} else static if (op == "++" || op == "--") {
			return this = mixin(op ~ "v");
		}
	}
	Mint opBinary(string op)(const Mint a) const {
		static if (op == "+" || op == "-" || op == "*") {
			return Mint(mixin("v" ~ op ~ "a.v"));
		} else static if (op == "/") {
			assert(a.v != 0);
			return this * a ^^ (MO - 2);
		}
	}
	Mint opBinary(string op)(long a) const {
		static if (op == "^^") {
			Mint ret = 1, x = this;
			for (; a; a >>= 1, x *= x) if (a & 1) ret *= x;
			return ret;
		} else {
			return mixin("this" ~ op ~ "Mint(a)");
		}
	}
	Mint opAssign(long v) {
		return this = Mint(v);
	}
	Mint opOpAssign(string op)(const Mint a) {
		static if (op == "+" || op == "-" || op == "*" || op == "/") {
			return this = mixin("this" ~ op ~ "a");
		}
	}
	Mint opOpAssign(string op)(long a) {
		return this = mixin("this" ~ op ~ "a");
	}
	string toString() const {
		return v.to!string;
	}
	unittest {
		Mint a = -1;
		assert(a.v == MO - 1);
		++a;
		assert(a.v == 0);
		--a;
		assert(a.v == MO - 1);
		Mint b = 1_000_000_000;
		b += 1_000_000_000;
		assert(b.v == 2_000_000_000 % MO);
		b = 2;
		b -= 4;
		assert(b.v == MO - 2);
		b = 1_000_000_000;
		b *= 1_000_000_000;
		assert(b.v == 1_000_000_000_000_000_000 % MO);
		Mint c = -10;
		c /= 14;
		c *= 7;
		assert(c.v == MO - 5);
	}
}

long gcd(long a, long b) {
	return (b != 0) ? gcd(b, a % b) : a;
}

immutable LIM = 1000005;

/*
long[] phi;
long gcdSum(long n) {
	long ret;
	for (long d = 1; d * d <= n; ++d) if (n % d == 0) {
		ret += d * phi[cast(size_t)(n / d)];
		if (d != n / d) {
			ret += (n / d) * phi[cast(size_t)(d)];
		}
	}
	return ret;
}
*/

void main(string[] args) {
	long[] phi = new long[LIM];
	foreach (i; 1 .. LIM) phi[i] = i;
	foreach (i; 1 .. LIM) for (int j = i * 2; j < LIM; j += i) phi[j] -= phi[i];
writeln("phi = ",phi[0..30]);
	long[] gcdSums = new long[LIM];
	foreach (i; 1 .. LIM) for (int j = i; j < LIM; j += i) {
		gcdSums[j] += i * phi[j / i];
	}

	Mint[] k1 = new Mint[LIM + 1];
	Mint[] k2 = new Mint[LIM + 1];
	Mint[] k3 = new Mint[LIM + 1];
	Mint[] k4 = new Mint[LIM + 1];
	foreach (k; 0 .. LIM) {
		k1[k + 1] = k1[k] + Mint(k) ^^ 1;
		k2[k + 1] = k2[k] + Mint(k) ^^ 2;
		k3[k + 1] = k3[k] + Mint(k) ^^ 3;
		k4[k + 1] = k4[k] + Mint(k) ^^ 4;
	}
// writeln("k1 = ",k1[0..10]);
// writeln("k2 = ",k2[0..10]);
// writeln("k3 = ",k3[0..10]);
// writeln("k4 = ",k4[0..10]);
	Mint[] k0a = new Mint[LIM + 1];
	Mint[] k1a = new Mint[LIM + 1];
	Mint[] k2a = new Mint[LIM + 1];
	foreach (k; 0 .. LIM) {
		k0a[k + 1] = k0a[k] + Mint(k) ^^ 0 * k2[k];
		k1a[k + 1] = k1a[k] + Mint(k) ^^ 1 * k2[k];
		k2a[k + 1] = k2a[k] + Mint(k) ^^ 2 * k2[k];
	}
// writeln("k0a = ",k0a[0..10]);
// writeln("k1a = ",k1a[0..10]);
// writeln("k2a = ",k2a[0..10]);
	Mint[] k0g = new Mint[LIM + 1];
	Mint[] k1g = new Mint[LIM + 1];
	Mint[] k2g = new Mint[LIM + 1];
	foreach (k; 0 .. LIM) {
		// const g = gcdSum(k);
// if(k<10)writeln("gcdSum(",k,") = ",g);
		const g = gcdSums[k] - k;
		k0g[k + 1] = k0g[k] + Mint(k) ^^ 0 * g;
		k1g[k + 1] = k1g[k] + Mint(k) ^^ 1 * g;
		k2g[k + 1] = k2g[k] + Mint(k) ^^ 2 * g;
	}
// writeln("k0g = ",k0g[0..10]);
// writeln("k1g = ",k1g[0..10]);
// writeln("k2g = ",k2g[0..10]);

	// try {
	for (int TC = readInt; TC--; ) {
		const M = readLong;
		const N = readLong;

		const L = min(M, N);

		//*
		long brt;
		foreach (k; 1 .. L + 1) {
			brt += (M - k + 1) * (N - k + 1) * k ^^ 2;
		}
		foreach (a; 1 .. L) foreach (b; 1 .. L) if (a + b <= L) {
			brt += (M - (a + b) + 1) * (N - (a + b) + 1) * (a ^^ 2 + b ^^ 2 - 2 * (a + b - gcd(a, b)));
		}
		writeln("brt = ", brt);
		//*/

		const m = Mint(M);
		const n = Mint(N);
		const l = cast(size_t)(L);
		Mint ans;

		ans += (m + 1) * (n + 1) * k2[l + 1];
		ans -= (m + 1) * k3[l + 1];
		ans -= (n + 1) * k3[l + 1];
		ans += k4[l + 1];

		ans += (m + 1) * (n + 1) * 2 * k0a[l + 1];
		ans -= (m + 1) * 2 * k1a[l + 1];
		ans -= (n + 1) * 2 * k1a[l + 1];
		ans += Mint(1) * 2 * k2a[l + 1];

		ans -= (m + 1) * (n + 1) * 2 * (k2[l + 1] - k1[l + 1]);
		ans += (m + 1) * 2 * (k3[l + 1] - k2[l + 1]);
		ans += (n + 1) * 2 * (k3[l + 1] - k2[l + 1]);
		ans -= Mint(1) * 2 * (k4[l + 1] - k3[l + 1]);

		ans += (m + 1) * (n + 1) * 2 * k0g[l + 1];
		ans -= (m + 1) * 2 * k1g[l + 1];
		ans -= (n + 1) * 2 * k1g[l + 1];
		ans += Mint(1) * 2 * k2g[l + 1];

		writeln(ans);

	}
	// } catch (EOFException) {}
}


Recently Petya walked in the forest and found a magic stick.Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:   If the chosen number $$$a$$$ is even, then the spell will turn it into $$$\frac{3a}{2}$$$;  If the chosen number $$$a$$$ is greater than one, then the spell will turn it into $$$a-1$$$. Note that if the number is even and greater than one, then Petya can choose which spell to apply.Petya now has only one number $$$x$$$. He wants to know if his favorite number $$$y$$$ can be obtained from $$$x$$$ using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave $$$x$$$ as it is.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^9$$$) — the current number and the number that Petya wants to get.

For the $$$i$$$-th test case print the answer on it — YES if Petya can get the number $$$y$$$ from the number $$$x$$$ using known spells, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

import std.stdio;
import std.algorithm;

bool go(int x, int y) {
  if(x == 1) {
    return y == 1;
  }
  if(x <= 3) {
    return y <= 3;
  }
  return true;
}

void main() {
  int t;
  readf(" %s", &t);
  while(t-- > 0) {
    int x, y;
    readf(" %s %s", &x, &y);
    writefln(go(x, y) ? "YES" : "NO");
  }
}

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto x = RD;
		auto y = RD;
		bool[long] set;
		set[x] = true;
		while (x < y)
		{
			if (x % 2 == 0)
				x = x * 3 / 2;
			else
				--x;
			if (set.get(x, false))
				break;
			set[x] = true;
		}
		ans[i] = x >= y;
	}

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

import std.stdio;
import std.algorithm;

bool go(int x, int y) {
  if(x == 1) {
    return y == 1;
  }
  if(x == 3) {
    return y <= 3;
  }
  return true;
}

void main() {
  int t;
  readf(" %s", &t);
  while(t-- > 0) {
    int x, y;
    readf(" %s %s", &x, &y);
    writefln(go(x, y) ? "YES" : "NO");
  }
}


You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.For example, if the string s is abacaba and the query is l1 = 3, r1 = 6, k1 = 1 then the answer is abbacaa. If after that we would process the query l2 = 1, r2 = 4, k2 = 2 then we would get the string baabcaa.

The first line of the input contains the string s (1 ≤ |s| ≤ 10 000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters. Second line contains a single integer m (1 ≤ m ≤ 300) — the number of queries. The i-th of the next m lines contains three integers li, ri and ki (1 ≤ li ≤ ri ≤ |s|, 1 ≤ ki ≤ 1 000 000) — the description of the i-th query.

Print the resulting string s after processing all m queries.

NoteThe sample is described in problem statement.

import std.stdio;
import std.string;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		int m;
		readf (" %s", &m);
		foreach (q; 0..m)
		{
			int l, r, k;
			readf (" %s %s %s ", &l, &r, &k);
			l--;
			k %= (r - l);
			k = (r - l) - k;
			s = s[0..l] ~ s[l..r][k..$] ~ s[l..r][0..k] ~ s[r..$];
		}
		writeln (s);
	}
}


You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) — the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$) — card features. It is guaranteed that all cards are distinct.

Output one integer — the number of meta-sets.

NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set.   In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$.   In there third test, there are $$$54$$$ meta-sets.

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

void main() {
    int N, K; readf("%d %d\n", &N, &K);
    long[] X = new long[N];

    long encode(in int[] xs) {
        long r = 0;
        foreach_reverse (x; xs) {
            r = r * 3 + x;
        }
        return r;
    }
    int[] decode(long x) {
        int[] r = new int[K];
        foreach (k; 0 .. K) {
            r[k] = x % 3;
            x /= 3;
        }
        return r;
    }

    foreach (n; 0 .. N) {
        auto L = readln.chomp.split(" ").map!(to!int).array;
        X[n] = encode(L);
    }

    long f(long a, long b) {
        int[] buf = new int[K];
        foreach (k; 0 .. K) {
            int ak = a % 3, bk = b % 3;
            int ck = (ak == bk ? ak : 3 - ak - bk);
            buf[k] = ck;
            a /= 3;
            b /= 3;
        }
        return encode(buf);
    }

    bool[long] s;
    foreach (x; X) {
        s[x] = true;
    }
    long ans = 0;
    for (int i = 0; i < N; i++) {
        bool[long] used;
        used[X[i]] = true;
        long c = 0;
        for (int j = 0; j < N; j++) {
            if (X[j] in used) continue;
            long r = f(X[i], X[j]);
            /*
            writefln("%s %s -> %s", i, j, decode(r));
            writeln(r in used);
            writeln(r in s);
            */
            used[r] = true;
            if (r in s) { c++; }
        }
        //writeln([i, c]);
        ans += c * (c-1) / 2;
    }
    writeln(ans);
}


In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.

The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.

In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.

NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.

import std.stdio;
import std.algorithm;

void main()
{
    int n, m;
    int[] a;

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

    int i = 1, j = 0;
    int k = 0;
    int[] result = new int[100000];

    sort(a);

    while (m >= i && i <= 1000000000) {
        if (j < n && a[j] == i) {
            j++;
        }
        else {
            result[k] = i;
            m -= i;
            k++;
        }
        i++;
    }

    writef("%d\n", k);
    for (int p = 0; p < k; p++) {
        writef("%d", result[p]);

        if (p == k - 1) {
            writef("\n");
        }
        else {
            writef(" ");
        }
    }
}

import std.stdio;

void main()
{
    int n, m;
    int[] a;

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

    int i = 1, j = 0;
    int k = 0;
    int[] result = new int[100000];

    while (m >= i && i <= 1000000000) {
        if (j < n && a[j] == i) {
            j++;
        }
        else {
            result[k] = i;
            m -= i;
            k++;
        }
        i++;
    }

    writef("%d\n", k);
    for (int p = 0; p < k; p++) {
        writef("%d", result[p]);

        if (p == k - 1) {
            writef("\n");
        }
        else {
            writef(" ");
        }
    }
}


Paprika loves permutations. She has an array $$$a_1, a_2, \dots, a_n$$$. She wants to make the array a permutation of integers $$$1$$$ to $$$n$$$.In order to achieve this goal, she can perform operations on the array. In each operation she can choose two integers $$$i$$$ ($$$1 \le i \le n$$$) and $$$x$$$ ($$$x > 0$$$), then perform $$$a_i := a_i \bmod x$$$ (that is, replace $$$a_i$$$ by the remainder of $$$a_i$$$ divided by $$$x$$$). In different operations, the chosen $$$i$$$ and $$$x$$$ can be different.Determine the minimum number of operations needed to make the array a permutation of integers $$$1$$$ to $$$n$$$. If it is impossible, output $$$-1$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

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

For each test case, output the minimum number of operations needed to make the array a permutation of integers $$$1$$$ to $$$n$$$, or $$$-1$$$ if it is impossible.

NoteFor the first test, the only possible sequence of operations which minimizes the number of operations is:   Choose $$$i=2$$$, $$$x=5$$$. Perform $$$a_2 := a_2 \bmod 5 = 2$$$. For the second test, it is impossible to obtain a permutation of integers from $$$1$$$ to $$$n$$$.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		auto ok = new bool[](n);
		long[] b;
		foreach (i; 0..n)
		{
			if (a[i] <= n)
			{
				if (ok[a[i]-1])
					b ~= a[i];
				else
					ok[a[i]-1] = true;
			}
			else
			{
				b ~= a[i];
			}
		}
		b.sort;

		foreach (i; 0..n)
		{
			if (ok[i]) continue;
			if (b.front <= (i+1)*2)
			{
				ans[ti] = -1;
				break;
			}
			b.popFront;
			++ans[ti];
		}
	}

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

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto a = ma(n, readInt!int);
  auto filled = new bool[](n + 1);
  int[] fa;
  foreach(i, ai; a)
    {
      if (ai <= n)
	{
	  if (!filled[ai])
	    {
	      filled[ai] = true;
	      continue;
	    }
	}
      fa ~= ai;
    }
  sort(fa);
  debug writeln(fa);
  int ops = 0;
  foreach_reverse(i; 1 .. n + 1)
    {
      if (!filled[i])
	{
	  debug writeln("trying to fill ", i, " with fa ", fa, " back ", fa.back, " ", i < fa.back/2);
	  if (fa.empty || !(i < (fa.back + (fa.back%2))/2)) return writeln(-1);
	  fa.popBack;
	  ops++;
	  filled[i] = true;
	}
    }
  ops.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;
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 n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		auto v = new bool [n + 1];
		foreach (ref c; a)
		{
			if (1 <= c && c <= n && !v[c])
			{
				v[c] = true;
				c = 0;
			}
		}
		a = a.filter !(q{a != 0}).array;
		int res = 0;
		foreach (d; 1..n + 1)
		{
			if (!v[d])
			{
				if (a.front > d * 2)
				{
					res += 1;
					a.popFront ();
				}
				else
				{
					res = -1;
					break;
				}
			}
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		bool ok = true;
		foreach (i; 0..n)
		{
			if (a[i] == i+1) continue;
			if (a[i] <= (i+1)*2)
			{
				ok = false;
				break;
			}
			++ans[ti];
		}
		if (!ok)
			ans[ti] = -1;
	}

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


During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of $$$n$$$ high school students numbered from $$$1$$$ to $$$n$$$. Initially, each student $$$i$$$ is on position $$$i$$$. Each student $$$i$$$ is characterized by two numbers — $$$a_i$$$ and $$$b_i$$$. Dissatisfaction of the person $$$i$$$ equals the product of $$$a_i$$$ by the number of people standing to the left of his position, add the product $$$b_i$$$ by the number of people standing to the right of his position. Formally, the dissatisfaction of the student $$$i$$$, which is on the position $$$j$$$, equals $$$a_i \cdot (j-1) + b_i \cdot (n-j)$$$.The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.Although Stas is able to solve such problems, this was not given to him. He turned for help to you.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of people in the queue. Each of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq 10^8$$$) — the characteristic of the student $$$i$$$, initially on the position $$$i$$$.

Output one integer — minimum total dissatisfaction which can be achieved by rearranging people in the queue.

NoteIn the first example it is optimal to put people in this order: ($$$3, 1, 2$$$). The first person is in the position of $$$2$$$, then his dissatisfaction will be equal to $$$4 \cdot 1+2 \cdot 1=6$$$. The second person is in the position of $$$3$$$, his dissatisfaction will be equal to $$$2 \cdot 2+3 \cdot 0=4$$$. The third person is in the position of $$$1$$$, his dissatisfaction will be equal to $$$6 \cdot 0+1 \cdot 2=2$$$. The total dissatisfaction will be $$$12$$$.In the second example, you need to put people in this order: ($$$3, 2, 4, 1$$$). The total dissatisfaction will be $$$25$$$.

import std.algorithm.comparison;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.sorting;
import std.range;
import std.stdio;

void main() {
    int n;
    readf("%s %s", n);
    auto d = new long[](n);
    long s, b;
    foreach (i; 0..n) {
        readf(" %s %s", d[i], b);
        d[i] -= b;
        s += (n-1)*b;
    }
    sort(d);
    foreach (i; 0..n) {
        s += i * d[n-1-i];
    }
    writeln(s);
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = N.iota.map!(_ => readln.split.map!(to!long).array).array;
    A.sort!"a[0] - a[1] > b[0] - b[1]";
    N.iota.map!(i => A[i][0] * i + A[i][1] * (N - i - 1)).sum.writeln;
}

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

/*
x[j] = a[i](j - 1) + b[i](n - j)
 = (n b[i] - a[i]) + j(a[i] - b[i]).

sum x[j] = sum j[i] c[i], where c[j] = a[i] - b[i].

arrenge so that j[i] is large where c[i] is small.
*/

class X{
	long a;
	long b;
	long c;
	int j;
	long value;
	this(long a, long b){
		this.a = a;
		this.b = b;
		this.c = a - b;
	}
}

void solve(){

	int n = read!int;

	X[] xs;
	foreach(i; 0 .. n){
		long a = read!long;
		long b = read!long;
		xs ~= new X(a, b);
	}
	xs.sort!"a.c>b.c"();
	foreach(i, x; xs) log("i:", i, "a:", x.a, "b:", x.b, "c:", x.c);

	long ans = 0;
	foreach(int i, x; xs){
		x.j = i + 1;
		x.value = x.a * (x.j - 1) + x.b * (n - x.j);
		ans += x.value;
	}
	foreach(i, x; xs) log("i:", i, "a:", x.a, "b:", x.b, "c:", x.c, "j:", x.j, "value:", x.value);

	ans.writeln;

}

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;

alias Tree = RBT!int;

int[][] child;
bool[] visited;

long MOD = 998244353;
long[] fac;

long dfs(uint root) {

    uint nc = 0;

    visited[root] = true;
    long mul = 1;

    foreach (v; child[root]) {
        if (!visited[v]) {
            long ll = dfs(v);
            mul = (mul * ll) % MOD;
            nc++;
        }
    }

    if (root != 0)
        nc++;

    return (fac[nc] * mul) % MOD;
}

void main() {
    GC.disable();

    uint n;

    readf(" %s", n);

    auto a = new long[n];
    auto b = new long[n];
    long tt = 0;
    auto hh = new long[n];
    foreach (i; 0 .. n) {
        long x, y;

        readf(" %s %s", x, y);
        a[i] = x;
        b[i] = y;
        tt -= x;
        tt += y * n;
        if (x < y) {
            hh[i] = 1_00_000_000 + (y - x);
        }
        else
            hh[i] = (y - x);
    }

    sort(hh);
    // writeln(hh);

    foreach (i, e; hh) {
        if (e >= 1_00_000_000)
            tt -= (i + 1) * (e - 1_00_000_000);
        else {
            tt += (i + 1) * (-e);
        }
    }

    writeln(tt);
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
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!uint;
	auto arr = new long[2][](N);

	foreach (i; 0..N)
	{
		auto a = RD!long;
		auto b = RD!long;
		arr[i] = [a, b];
	}
	auto index = MAKE_IDX!"a[0] - a[1] > b[0] - b[1]"(arr);
	long ans;
	debug writeln(arr);
	foreach (ii, i; index)
	{
		ans += arr[i][0] * ii;
		ans += arr[i][1] * (N - ii - 1);
	}

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

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
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!uint;
	auto arr = new int[2][](N);

	foreach (i; 0..N)
	{
		auto a = RD!int;
		auto b = RD!int;
		arr[i] = [a, b];
	}
	auto index = MAKE_IDX!"a[0] - a[1] > b[0] - b[1]"(arr);
	uint ans;
	debug writeln(arr);
	foreach (ii, i; index)
	{
		ans += arr[i][0] * ii;
		ans += arr[i][1] * (N - ii - 1);
	}

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


For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $$$n$$$ days of summer. On the $$$i$$$-th day, $$$a_i$$$ millimeters of rain will fall. All values $$$a_i$$$ are distinct.The mayor knows that citizens will watch the weather $$$x$$$ days before the celebration and $$$y$$$ days after. Because of that, he says that a day $$$d$$$ is not-so-rainy if $$$a_d$$$ is smaller than rain amounts at each of $$$x$$$ days before day $$$d$$$ and and each of $$$y$$$ days after day $$$d$$$. In other words, $$$a_d < a_j$$$ should hold for all $$$d - x \le j < d$$$ and $$$d < j \le d + y$$$. Citizens only watch the weather during summer, so we only consider such $$$j$$$ that $$$1 \le j \le n$$$.Help mayor find the earliest not-so-rainy day of summer.

The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le x, y \le 7$$$) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after. The second line contains $$$n$$$ distinct integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ denotes the rain amount on the $$$i$$$-th day.

Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.

NoteIn the first example days $$$3$$$ and $$$8$$$ are not-so-rainy. The $$$3$$$-rd day is earlier.In the second example day $$$3$$$ is not not-so-rainy, because $$$3 + y = 6$$$ and $$$a_3 > a_6$$$. Thus, day $$$8$$$ is the answer. Note that $$$8 + y = 11$$$, but we don't consider day $$$11$$$, because it is not summer.

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 = RD!int;
	auto y = RD!int;
	auto a = RDA;
	int ans;
	foreach (i; 0..n)
	{
		bool ok = true;
		foreach (j; max(0, i-x)..min(n, i+1+y))
		{
			if (a[j] < a[i])
			{
				ok = false;
				break;
			}
		}
		if (ok)
		{
			ans = i+1;
			break;
		}
	}

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

import std.stdio;
import std.algorithm;

const int MAX = 100005;
int[MAX] a;

void main() {
    int n, x, y;
    readf(" %s %s %s", n, x, y);
    foreach(i; 0..n) readf(" %s", a[i]);

    foreach(i; 0..n) {
        bool ok = true;
        foreach(j; max(0, i-x)..min(i+y+1, n)) {
            ok &= a[j] >= a[i];
        }
        if (ok) {
            writeln(i+1);
            break;
        }
    }
}

import std.stdio;
import std.algorithm : all, map, maxElement, splitter;
import std.array;
import std.string : strip;
import std.conv : to;
import std.range : chain, enumerate, slide, repeat;

void main()
{
  // read array of ints
  int n, x, y;
  readf!"%d %d %d\n"(n, x, y);
  auto a = map!(to!(int))(readln().strip().splitter(' '));
  auto m = a.maxElement;
  auto p = chain(m.repeat(x), a, m.repeat(y)).array;

  foreach (i, win; p.slide(x + y + 1).enumerate(1)) {
    auto mid = win[x];

    if (win.all!(a => a >= mid)) {
      writeln(i);
      break;
    }
  }
}

import std.stdio;
import std.algorithm;

struct obb {
    int index;
    int value;
    int opCmp(obb o) const {
        return value - o.value;
    }
}

const int MAX = 100005;
int[MAX] a;
obb[MAX] o;
bool[MAX] flag;

void main() {
    int n, x, y;
    readf(" %s %s %s", n, x, y);
    foreach(i; 0..n) readf(" %s", a[i]);

    foreach(i; 0..n) o[i] = obb(i, a[i]);
    sort(o[0..n]);

    auto result = o[0].index;
    foreach(i; 0..n) {
        auto index = o[i].index;
        if (flag[index]) continue;
        bool ok = true;
        foreach(j; max(0, index-x)..min(index+y+1, n)) {
            flag[j] = true;
            ok &= a[j] >= o[i].value;
        }
        if (ok) {
            result = min(result, index);
        }
    }
    writeln(result+1);
}


Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).

You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.

NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.

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

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

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

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

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

int M, N;
long[] A, B;

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = new long[M];
		foreach (i; 0 .. M) {
			A[i] = readLong;
		}
		B = new long[N];
		foreach (i; 0 .. N) {
			B[i] = readLong;
		}

		long[] xs = A.dup ~ B.dup;
		xs.sort();
		const target = xs[N - 1];
		long ans;
		foreach (a; A) {
			if (a < target) {
				ans += target - a;
			}
		}
		foreach (b; B) {
			if (b > target) {
				ans += b - target;
			}
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}


You are given two integers $$$l$$$ and $$$r$$$ in binary representation. Let $$$g(x, y)$$$ be equal to the bitwise XOR of all integers from $$$x$$$ to $$$y$$$ inclusive (that is $$$x \oplus (x+1) \oplus \dots \oplus (y-1) \oplus y$$$). Let's define $$$f(l, r)$$$ as the maximum of all values of $$$g(x, y)$$$ satisfying $$$l \le x \le y \le r$$$.Output $$$f(l, r)$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of the binary representation of $$$r$$$. The second line contains the binary representation of $$$l$$$ — a string of length $$$n$$$ consisting of digits $$$0$$$ and $$$1$$$ ($$$0 \le l < 2^n$$$). The third line contains the binary representation of $$$r$$$ — a string of length $$$n$$$ consisting of digits $$$0$$$ and $$$1$$$ ($$$0 \le r < 2^n$$$). It is guaranteed that $$$l \le r$$$. The binary representation of $$$r$$$ does not contain any extra leading zeros (if $$$r=0$$$, the binary representation of it consists of a single zero). The binary representation of $$$l$$$ is preceded with leading zeros so that its length is equal to $$$n$$$.

In a single line output the value of $$$f(l, r)$$$ for the given pair of $$$l$$$ and $$$r$$$ in binary representation without extra leading zeros.

NoteIn sample test case $$$l=19$$$, $$$r=122$$$. $$$f(x,y)$$$ is maximal and is equal to $$$127$$$, with $$$x=27$$$, $$$y=100$$$, for example.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto lo = readln.strip.map !(q{a - '0'}).array;
		auto hi = readln.strip.map !(q{a - '0'}).array;
		auto res = hi.dup;
		if (lo[0] != hi[0])
		{
			res[] = 1;
		}

		uint [] inc (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 1)
				{
					break;
				}
			}
			return res;
		}

		if (res == hi && res[$ - 1] == 0 && lo != hi && inc (lo) != hi)
		{
			res[$ - 1] = 1;
		}
		writefln !("%(%s%)") (res);
	}
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto lo = readln.strip.map !(q{a - '0'}).array;
		auto hi = readln.strip.map !(q{a - '0'}).array;
		auto res = hi.dup;
		if (n == 1)
		{
			writeln (hi[$ - 1]);
			continue;
		}

		uint [] dec (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 0)
				{
					break;
				}
			}
			return res;
		}

		uint [] inc (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 1)
				{
					break;
				}
			}
			return res;
		}

		uint [] calc (uint [] x, uint [] y)
		{
			x = x.dup;
			y = y.dup;
			debug {writeln ("x = ", x);}
			debug {writeln ("y = ", y);}
			auto res = new uint [n];
			while (x[$ - 2..$] != [0, 0])
			{
				res[] ^= x[];
				x = inc (x);
			}
			while (y[$ - 2..$] != [1, 1])
			{
				res[] ^= y[];
				y = dec (y);
			}
			debug {writeln ("z = ", res);}
			return res;
		}

		void getBetter (uint [] x, uint [] y)
		{
			if (x < lo || y > hi)
			{
				return;
			}
			res = max (res, calc (x, y));
		}

		auto pos = 0;
		while (pos < n && lo[pos] == hi[pos])
		{
			pos += 1;
		}
		if (pos < n)
		{
			auto x = lo.dup;
			x[pos + 1..$] = 1;
			auto y = hi.dup;
			y[pos + 1..$] = 0;
			getBetter (x, y);
			if (x.canFind (1))
			{
				getBetter (dec (x), y);
			}
			if (y.canFind (0))
			{
				getBetter (x, inc (y));
			}
		}
		if (res == hi && res[$ - 1] == 0 && lo != hi && inc (lo) != hi)
		{
			res[$ - 1] = 1;
		}
		writefln !("%(%s%)") (res);
	}
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto lo = readln.strip.map !(q{a - '0'}).array;
		auto hi = readln.strip.map !(q{a - '0'}).array;
		auto res = hi.dup;

		uint [] inc (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 1)
				{
					break;
				}
			}
			return res;
		}

		if (res == hi && res[$ - 1] == 0 && lo != hi && inc (lo) != hi)
		{
			res[$ - 1] = 1;
		}
		writefln !("%(%s%)") (res);
	}
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto lo = readln.strip.map !(q{a - '0'}).array;
		auto hi = readln.strip.map !(q{a - '0'}).array;
		auto res = hi.dup;
		if (n == 1)
		{
			writeln (1);
			continue;
		}

		uint [] dec (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 0)
				{
					break;
				}
			}
			return res;
		}

		uint [] inc (uint [] x)
		{
			auto res = x.dup;
			foreach_reverse (i; 0..n)
			{
				res[i] ^= 1;
				if (res[i] == 1)
				{
					break;
				}
			}
			return res;
		}

		uint [] calc (uint [] x, uint [] y)
		{
			x = x.dup;
			y = y.dup;
			debug {writeln ("x = ", x);}
			debug {writeln ("y = ", y);}
			auto res = new uint [n];
			while (x[$ - 2..$] != [0, 0])
			{
				res[] ^= x[];
				x = inc (x);
			}
			while (y[$ - 2..$] != [1, 1])
			{
				res[] ^= y[];
				y = dec (y);
			}
			debug {writeln ("z = ", res);}
			return res;
		}

		void getBetter (uint [] x, uint [] y)
		{
			if (x < lo || y > hi)
			{
				return;
			}
			res = max (res, calc (x, y));
		}

		auto pos = 0;
		while (pos < n && lo[pos] == hi[pos])
		{
			pos += 1;
		}
		if (pos < n)
		{
			auto x = lo.dup;
			x[pos + 1..$] = 1;
			auto y = hi.dup;
			y[pos + 1..$] = 0;
			getBetter (x, y);
			if (x.canFind (1))
			{
				getBetter (dec (x), y);
			}
			if (y.canFind (0))
			{
				getBetter (x, inc (y));
			}
		}
		if (res == hi && res[$ - 1] == 0 && lo != hi && inc (lo) != hi)
		{
			res[$ - 1] = 1;
		}
		writefln !("%(%s%)") (res);
	}
}


You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.

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

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

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

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

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

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

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

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

alias X = Tuple!(int, "i", int, "p");

void main()
{
    int T; get(T); while (T--) {
        int N; get(N);
        int[] PS; get(PS);
        X[] xx;
        foreach (i, p; PS) xx ~= X(i.to!int, p);
        sort!"a.p > b.p"(xx);
        int r = N;
        int[] res;
        foreach (x; xx) if (x.i < r) {
            foreach (i; x.i..r) res ~= PS[i];
            r = x.i;
        }
        writefln!"%(%d %)"(res);
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto pos = new int[](n);
		foreach (i; 0..n)
			pos[p[i]-1] = i;

		int l = n;
		foreach_reverse (i; 0..n)
		{
			if (pos[i] > l) continue;
			ans[ti] ~= p[pos[i]..l];
			l = pos[i];
		}
	}

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


You have given an array $$$a$$$ of length $$$n$$$ and an integer $$$x$$$ to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be $$$q$$$. If $$$q$$$ is divisible by $$$x$$$, the robot adds $$$x$$$ copies of the integer $$$\frac{q}{x}$$$ to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if $$$q$$$ is not divisible by $$$x$$$, the robot shuts down.Please determine the sum of all values of the array at the end of the process.

The first input line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$, $$$2 \leq x \leq 10^9$$$) — the length of the array and the value which is used by the robot. The next line contains integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the initial values in the array. It is guaranteed that the sum of values $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output one integer — the sum of all elements at the end of the process.

NoteIn the first test case the array initially consists of a single element $$$[12]$$$, and $$$x=2$$$. After the robot processes the first element, the array becomes $$$[12, 6, 6]$$$. Then the robot processes the second element, and the array becomes $$$[12, 6, 6, 3, 3]$$$. After the robot processes the next element, the array becomes $$$[12, 6, 6, 3, 3, 3, 3]$$$, and then the robot shuts down, since it encounters an element that is not divisible by $$$x = 2$$$. The sum of the elements in the resulting array is equal to $$$36$$$.In the second test case the array initially contains integers $$$[4, 6, 8, 2]$$$, and $$$x=2$$$. The resulting array in this case looks like $$$ [4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 1, 1, 1]$$$.

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        int N; long X; get(N, X);
        long[] AA; get(AA);
        alias A = Tuple!(long, "c", long, "v");
        auto aa = AA.map!(a => A(1, a)).array();
        int i;
        bool broken;
        long r;
        while (i < aa.length) {
            auto a = aa[i++];
            r += a.v * a.c;
            if (!broken && a.v % X == 0) {
                aa ~= A(a.c * X, a.v / X);
            } else {
                broken = true;
            }
        }
        writeln(r);
    }
}

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

void theCode(){
    int n;
    n = scan!int;
    ll x = scan;
    auto arr = scanArray;
    ll summ = arr.sum;
    ll[] pows;
    foreach(el; arr){
        ll tim = 0;
        ll num = el;
        while(num > 0 && num % x == 0){
            num /= x;
            ++tim;
        }
        pows ~= tim;
    }
    for(int i = 0; i < 64; ++i){
        for(int j = 0; j < n; ++j){
            if(!pows[j]){
                writeln(summ);
                return;
            }
            summ += arr[j];
            --pows[j];
        }
    }
}

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

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = a.sum;
		(){
		foreach (cnt; 1..10^^5)
		{
			foreach (i; 0..n)
			{
				if (a[i] % x) return;

				auto y = a[i] / x;
				ans[ti] += y * x^^cnt;
				a[i] = y;
			}
		}}();
	}

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


Allen and Bessie are playing a simple number game. They both know a function $$$f: \{0, 1\}^n \to \mathbb{R}$$$, i. e. the function takes $$$n$$$ binary arguments and returns a real value. At the start of the game, the variables $$$x_1, x_2, \dots, x_n$$$ are all set to $$$-1$$$. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an $$$i$$$ such that $$$x_i = -1$$$ and either setting $$$x_i \to 0$$$ or $$$x_i \to 1$$$.After $$$n$$$ rounds all variables are set, and the game value resolves to $$$f(x_1, x_2, \dots, x_n)$$$. Allen wants to maximize the game value, and Bessie wants to minimize it.Your goal is to help Allen and Bessie find the expected game value! They will play $$$r+1$$$ times though, so between each game, exactly one value of $$$f$$$ changes. In other words, between rounds $$$i$$$ and $$$i+1$$$ for $$$1 \le i \le r$$$, $$$f(z_1, \dots, z_n) \to g_i$$$ for some $$$(z_1, \dots, z_n) \in \{0, 1\}^n$$$. You are to find the expected game value in the beginning and after each change.

The first line contains two integers $$$n$$$ and $$$r$$$ ($$$1 \le n \le 18$$$, $$$0 \le r \le 2^{18}$$$). The next line contains $$$2^n$$$ integers $$$c_0, c_1, \dots, c_{2^n-1}$$$ ($$$0 \le c_i \le 10^9$$$), denoting the initial values of $$$f$$$. More specifically, $$$f(x_0, x_1, \dots, x_{n-1}) = c_x$$$, if $$$x = \overline{x_{n-1} \ldots x_0}$$$ in binary. Each of the next $$$r$$$ lines contains two integers $$$z$$$ and $$$g$$$ ($$$0 \le z \le 2^n - 1$$$, $$$0 \le g \le 10^9$$$). If $$$z = \overline{z_{n-1} \dots z_0}$$$ in binary, then this means to set $$$f(z_0, \dots, z_{n-1}) \to g$$$.

Print $$$r+1$$$ lines, the $$$i$$$-th of which denotes the value of the game $$$f$$$ during the $$$i$$$-th round. Your answer must have absolute or relative error within $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

NoteConsider the second test case. If Allen goes first, he will set $$$x_1 \to 1$$$, so the final value will be $$$3$$$. If Bessie goes first, then she will set $$$x_1 \to 0$$$ so the final value will be $$$2$$$. Thus the answer is $$$2.5$$$.In the third test case, the game value will always be $$$1$$$ regardless of Allen and Bessie's play.

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();
      const R = readInt();
      auto C = new long[1 << N];
      foreach (i; 0 .. 1 << N) {
        C[i] = readLong();
      }
      auto Z = new int[R];
      auto G = new long[R];
      foreach (r; 0 .. R) {
        Z[r] = readInt();
        G[r] = readLong();
      }

      auto cs = C.dup;
      long now = cs.sum;
      foreach (r; 0 .. R + 1) {
        writefln("%.10f", now / cast(real)(1 << N));
        if (r < R) {
          now -= cs[Z[r]];
          cs[Z[r]] = G[r];
          now += cs[Z[r]];
        }
      }
    }
  } catch (EOFException e) {
  }
}


In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.Farmer John wants to book a set of k + 1 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j - i|. Help Farmer John protect his cows by calculating this minimum possible distance.

The first line of the input contains two integers n and k (1 ≤ k < n ≤ 100 000) — the number of rooms in the hotel and the number of cows travelling with Farmer John. The second line contains a string of length n describing the rooms. The i-th character of the string will be '0' if the i-th room is free, and '1' if the i-th room is occupied. It is guaranteed that at least k + 1 characters of this string are '0', so there exists at least one possible choice of k + 1 rooms for Farmer John and his cows to stay in.

Print the minimum possible distance between Farmer John's room and his farthest cow.

NoteIn the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms.In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2.In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1.

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

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto s = readln.strip;
		auto v = n.iota.filter !(x => s[x] == '0').array;
		debug {writeln (v);}

		int res = n;
		int p = 0;
		int q = 0;
		int r = k;

		int dist (int t)
		{
			return max (v[t] - v[p], v[r] - v[t]);
		}

		while (r < v.length)
		{
			q = max (q, p);
			while (q < r && dist (q + 1) <= dist (q))
			{
				q++;
			}
			res = min (res, dist (q));
			p++;
			r++;
		}

		writeln (res);
	}
}

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

void main() {
  int n, k;
  readf(" %s %s", &n, &k);
  readln;
  string s = readln.strip;

  auto cnt = new int[n];
  foreach (i; 0..n) {
    cnt[i] = s[i] == '0';
    if (i > 0) cnt[i] += cnt[i - 1];
  }

  bool check(int x) {
    foreach (i; 0..n) {
      int l = max(0, i - x);
      int r = min(n - 1, i + x);
      int q = cnt[r] - (l > 0 ? cnt[l - 1] : 0);
      if (q >= k + 1 && s[i] != '1') {
        return true;
      }
    }
    return false;
  }

  int lo = -1, hi = n * 2;
  while (lo + 1 < hi) {
    int mid = (lo + hi) >> 1;
    if (check(mid)) hi = mid;
    else lo = mid;
  }

  writeln(hi);
}


You are given a table $$$a$$$ of size $$$2 \times n$$$ (i.e. two rows and $$$n$$$ columns) consisting of integers from $$$1$$$ to $$$n$$$.In one move, you can choose some column $$$j$$$ ($$$1 \le j \le n$$$) and swap values $$$a_{1, j}$$$ and $$$a_{2, j}$$$ in it. Each column can be chosen no more than once.Your task is to find the minimum number of moves required to obtain permutations of size $$$n$$$ in both first and second rows of the table or determine if it is impossible to do that.You have to answer $$$t$$$ independent test cases.Recall that the permutation of size $$$n$$$ is such an array of size $$$n$$$ that contains each integer from $$$1$$$ to $$$n$$$ exactly once (the order of elements doesn't matter).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of columns in the table. The second line of the test case contains $$$n$$$ integers $$$a_{1, 1}, a_{1, 2}, \dots, a_{1, n}$$$ ($$$1 \le a_{1, i} \le n$$$), where $$$a_{1, i}$$$ is the $$$i$$$-th element of the first row of the table. The third line of the test case contains $$$n$$$ integers $$$a_{2, 1}, a_{2, 2}, \dots, a_{2, n}$$$ ($$$1 \le a_{2, i} \le n$$$), where $$$a_{2, i}$$$ is the $$$i$$$-th element of the second row of the table. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case print the answer: -1 if it is impossible to obtain permutation of size $$$n$$$ in both first and the second rows of the table, or one integer $$$k$$$ in the first line, where $$$k$$$ is the minimum number of moves required to obtain permutations in both rows, and $$$k$$$ distinct integers $$$pos_1, pos_2, \dots, pos_k$$$ in the second line ($$$1 \le pos_i \le n$$$) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any.

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

void main ()
{
	auto tests = readln.strip.to !(int);
multitest_loop:
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		int [] [] a;
		foreach (row; 0..2)
		{
			a ~= readln.splitter.map !(to !(int)).array;
		}

		auto posXor = new int [n];
		auto num = new int [n];
		foreach (row; 0..2)
		{
			foreach (col; 0..n)
			{
				a[row][col] -= 1;
				num[a[row][col]] += 1;
				posXor[a[row][col]] ^= (row << 20) | col;
			}
		}
		if (!num.all !(x => x == 2))
		{
			writeln (-1);
			continue multitest_loop;
		}

		int [] answer;
		auto vis = new bool [n];
		foreach (i; 0..n)
		{
			if (!vis[i])
			{
				int [] [2] cur;
				int row = 0;
				int col = i;
				int add = 0;
				do
				{
					vis[col] = true;
					auto pos = (row << 20) | col;
					pos ^= posXor[a[row][col]];
					add += (row == 0);
					cur[row] ~= col + 1;
					row = (pos >> 20) ^ 1;
					col = (pos & 0xFFFFF);
				}
				while (col != i);
				debug {writeln (cur);}
				answer ~= cur[].minElement !(x => x.length);
			}
		}
		writeln (answer.length);
		writefln !("%(%s %)") (answer);
	}
}


Alice has a cake, and she is going to cut it. She will perform the following operation $$$n-1$$$ times: choose a piece of the cake (initially, the cake is all one piece) with weight $$$w\ge 2$$$ and cut it into two smaller pieces of weight $$$\lfloor\frac{w}{2}\rfloor$$$ and $$$\lceil\frac{w}{2}\rceil$$$ ($$$\lfloor x \rfloor$$$ and $$$\lceil x \rceil$$$ denote floor and ceiling functions, respectively).After cutting the cake in $$$n$$$ pieces, she will line up these $$$n$$$ pieces on a table in an arbitrary order. Let $$$a_i$$$ be the weight of the $$$i$$$-th piece in the line.You are given the array $$$a$$$. Determine whether there exists an initial weight and sequence of operations which results in $$$a$$$.

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

For each test case, print a single line: print YES if the array $$$a$$$ could have resulted from Alice's operations, otherwise print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).

YES
NO
YES
YES
NO
YES
NO
YES
YES
YES
YES
NO
NO
YES

NoteIn the first test case, it's possible to get the array $$$a$$$ by performing $$$0$$$ operations on a cake with weight $$$327$$$.In the second test case, it's not possible to get the array $$$a$$$.In the third test case, it's possible to get the array $$$a$$$ by performing $$$1$$$ operation on a cake with weight $$$1\,970\,429\,473$$$:   Cut it in half, so that the weights are $$$[985\,214\,736, 985\,214\,737]$$$.  Note that the starting weight can be greater than $$$10^9$$$.In the fourth test case, it's possible to get the array $$$a$$$ by performing $$$2$$$ operations on a cake with weight $$$6$$$:  Cut it in half, so that the weights are $$$[3,3]$$$.  Cut one of the two pieces with weight $$$3$$$, so that the new weights are $$$[1, 2, 3]$$$ which is equivalent to $$$[2, 3, 1]$$$ up to reordering.

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

bool solve (long [] a, int n)
{
	sort !(q{a > b}) (a);
	auto t = redBlackTree !(true) ([a.sum]);
	while (!t.empty)
	{
		if (t.length > a.length)
		{
			return false;
		}
		auto cur = t.back;
		t.removeBack ();
		if (a.front > cur)
		{
			return false;
		}
		else if (a.front == cur)
		{
			a.popFront ();
		}
		else
		{
			auto half = cur / 2;
			t.insert (cur - half);
			t.insert (half);
		}
	}
	return true;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(long)).array;
		writeln (solve (a, n) ? "YES" : "NO");
	}
}


Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types:   easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem;  hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then:  if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems;  if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems;  if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$);  if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them;  if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them;  if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam.

The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases.  The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$.

Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam.

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

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

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

alias Task = Tuple!(uint, uint);

void main() {
  auto r = new InputReader;
  immutable nt = r.next!uint;
  auto res = uninitializedArray!(int[]) (nt);
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint;
    immutable T = r.next!uint;
    immutable a = r.next!uint;
    immutable b = r.next!uint;
    auto d = r.nextA!uint (n);
    auto t = r.nextA!uint (n);
    Task[] easy;
    Task[] hard;
    foreach (i; 0 .. n) {
      if (d[i]) {
        hard ~= Task (t[i], 1);
      } else {
        easy ~= Task (t[i], 0);
      }
    }
    sort (easy);
    sort (hard);
    debug stderr.writeln (easy);
    debug stderr.writeln (hard);
    auto m = merge (easy, hard);
    long curt;
    long ce = easy.length, ch = hard.length;
    long best;
    int k;
    while (!m.empty) {
      auto q = m.front;
      debug stderr.writeln (q, ", curt = ", curt);
      auto dt = q[0] - curt;
      if (dt > 0) {
        --dt;
        debug stderr.writefln ("dt = %d", dt);
        long k1 = min (dt / a, ce);
        dt -= k1 * a;
        long k2 = min (dt / b, ch);
        best = max (best, k + k1 + k2);
        debug stderr.writefln ("k = %d, k1 = %d, k2 = %d", k, k1, k2);
      }
      if (q[1]) {
        curt += b;
        --ch;
      } else {
        curt += a;
        --ce;
      }
      m.popFront ();
      ++k;
    }
    if (curt <= T) {
      best = n;
    }
    res[tid] = best.to!int;
  }
  writefln ("%(%s\n%)", res);
}

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

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

void solve(){
	int m = rint;
	foreach(_; 0 .. m){
		int n = rint;
		long tAll = rlong, a = rlong, b = rlong;
		int[] hs = rint(n);
		long[] ts = rlong(n);

		P[] ps;
		foreach(i; 0 .. n) ps ~= P(!!hs[i], ts[i]);
		ps.sort!"a.time < b.time"();

		long xAll, yAll;
		foreach(p; ps) if(p.isHard) yAll += 1; else xAll += 1;

		ps ~= P(0, tAll + 1);
		log("---");
		log("n:", n, "tAll:", tAll, "a:", a, "b:", b);
		log("ps:", ps, "xAll:", xAll, "yAll:", yAll);

		long x = 0, y = 0;
		long best = 0;
		foreach(p; ps){
			log("p:", p, "x:", x, "y:", y);
			if(p.time - 1 >= a * x + b * y){
				long t = (p.time - 1) - (a * x + b * y);
				long s = x + y;
				long x1 = min(xAll - x, t / a);
				if(x1 > 0){
					t -= x1 * a;
					s += x1;
				}
				long y1 = min(yAll - y, t / b);
				if(y1 > 0){
					t -= y1 * b;
					s += y1;
				}
				best.chmax(s);
				log("t:", t, "s:", s, "x1:", x1, "y1:", y1, "best:", best);
			}
			if(p.isHard) y += 1;
			else x += 1;
		}

		best.writeln;
	}
}

struct P{
	bool isHard;
	long time;
}