Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by $$$1$$$. If he manages to finish the level successfully then the number of clears increases by $$$1$$$ as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.So he peeked at the stats $$$n$$$ times and wrote down $$$n$$$ pairs of integers — $$$(p_1, c_1), (p_2, c_2), \dots, (p_n, c_n)$$$, where $$$p_i$$$ is the number of plays at the $$$i$$$-th moment of time and $$$c_i$$$ is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.Help him to check the correctness of his records.For your convenience you have to answer multiple independent test cases.

The first line contains a single integer $$$T$$$ $$$(1 \le T \le 500)$$$ — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of moments of time Polycarp peeked at the stats. Each of the next $$$n$$$ lines contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \le p_i, c_i \le 1000$$$) — the number of plays and the number of clears of the level at the $$$i$$$-th moment of time. Note that the stats are given in chronological order.

For each test case print a single line. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print "YES". Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened.The second test case is a nice example of a Super Expert level.In the third test case the number of plays decreased, which is impossible.The fourth test case is probably an auto level with a single jump over the spike.In the fifth test case the number of clears decreased, which is also impossible.Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it.

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.stdlib;

bool solve() {
    auto N = readln.chomp.to!int;
    int pa = 0, pb = 0;

    bool ok = true;

    while (N--) {
        auto s = readln.split.map!(to!int);
        auto a = s[0];
        auto b = s[1];
        if (a < b) ok = false;
        if (a < pa) ok = false;
        if (b < pb) ok = false;
        int da = a - pa;
        int db = b - pb;
        if (db > da) ok = false;
        pa = a;
        pb = b;
    }

    return ok;
}

void main() {
    auto T = readln.chomp.to!int;
    while (T--) writeln(solve ? "YES" : "NO");
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		int p0 = 0, c0 = 0;
		bool ok = true;
		foreach (i; 0..n)
		{
			int p, c;
			readf !(" %s %s") (p, c);
			if (p < p0 || c < c0 || p - p0 < c - c0)
			{
				ok = false;
			}
			p0 = p;
			c0 = c;
		}
		writeln (ok ? "YES" : "NO");
	}
}

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint;
    int lp, lc, lf;
    bool ok = true;
    foreach (i; 0 .. n) {
      const p = r.next!int;
      const c = r.next!int;
      const f = p - c;
      if (p < lp || c < lc || f < lf) {
        ok = false;
      }
      lp = p;
      lc = c;
      lf = f;
    }
    writeln (ok ? "YES" : "NO");
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		long lp, lc;
		ans[ti] = true;
		foreach (i; 0..n)
		{
			auto p = RD;
			auto c = RD;
			if (p < c || p < lp || c < lc)
			{
				ans[ti] = false;
			}
			auto d1 = p - lp;
			auto d2 = c - lc;
			if (d1 < d2)
				ans[ti] = false;
			lp = p;
			lc = c;
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		long lp, lc;
		ans[ti] = true;
		foreach (i; 0..n)
		{
			auto p = RD;
			auto c = RD;
			if (p < c || p < lp || c < lc)
			{
				ans[ti] = false;
			}
			lp = p;
			lc = c;
		}
	}

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


The only difference between the two versions is that in this version $$$n \leq 2 \cdot 10^5$$$ and the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.A terminal is a row of $$$n$$$ equal segments numbered $$$1$$$ to $$$n$$$ in order. There are two terminals, one above the other. You are given an array $$$a$$$ of length $$$n$$$. For all $$$i = 1, 2, \dots, n$$$, there should be a straight wire from some point on segment $$$i$$$ of the top terminal to some point on segment $$$a_i$$$ of the bottom terminal. You can't select the endpoints of a segment. For example, the following pictures show two possible wirings if $$$n=7$$$ and $$$a=[4,1,4,6,7,7,5]$$$.  A crossing occurs when two wires share a point in common. In the picture above, crossings are circled in red.What is the maximum number of crossings there can be if you place the wires optimally?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the elements of the array. The sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the maximum number of crossings there can be if you place the wires optimally.

NoteThe first test case is shown in the second picture in the statement.In the second test case, the only wiring possible has the two wires cross, so the answer is $$$1$$$.In the third test case, the only wiring possible has one wire, so the answer is $$$0$$$.

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N);

      auto st = SegTree!("a + b", int)(new int[](N + 1));
      long ans;
      foreach(i, a; A) {
        ans += st.sum(a, N + 1);

        auto x = st.get(a);
        st.update(a, x + 1);
      }

      return ans;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

struct SegTree(alias pred = "a + b", T = long) {
  alias predFun = binaryFun!pred;
  int size;
  T[] data;
  T monoid;

  this(T[] src, T monoid = T.init) {
    this.monoid = monoid;

    for(int i = 2; i < 2L^^32; i *= 2) {
      if (src.length <= i) {
        size = i;
        break;
      }
    }

    data = new T[](size * 2);
    foreach(i, s; src) data[i + size] = s;
    foreach_reverse(b; 1..size) {
      data[b] = predFun(data[b * 2], data[b * 2 + 1]);
    }
  }

  void update(int index, T value) {
    int i = index + size;
    data[i] = value;
    while(i > 0) {
      i /= 2;
      data[i] = predFun(data[i * 2], data[i * 2 + 1]);
    }
  }

  T get(int index) {
    return data[index + size];
  }

  T sum(int a, int b, int k = 1, int l = 0, int r = -1) {
    if (r < 0) r = size;

    if (r <= a || b <= l) return monoid;
    if (a <= l && r <= b) return data[k];

    T leftValue = sum(a, b, 2*k, l, (l + r) / 2);
    T rightValue = sum(a, b, 2*k + 1, (l + r) / 2, r);
    return predFun(leftValue, rightValue);
  }
}

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;
		a[] -= 1;
		auto b = new int [] [n];
		foreach_reverse (i; 0..n)
		{
			b[a[i]] ~= i;
		}

		auto t = new int [n + 1];

		void add (int i)
		{
			for ( ; i <= n; i += i & -i)
			{
				t[i] += 1;
			}
		}

		int ask (int i)
		{
			int res = 0;
			for ( ; i > 0; i -= i & -i)
			{
				res += t[i];
			}
			return res;
		}

		long res = 0;
		foreach (i; 0..n)
		{
			foreach (v; b[i])
			{
				res += ask (n - v);
				add (n - v);
			}
		}
		writeln (res);
	}
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N);

      auto st = SegTree!("a + b", int)(new int[](N + 1));
      int ans;
      foreach(i, a; A) {
        ans += st.sum(a, N + 1);

        auto x = st.get(a);
        st.update(a, x + 1);
      }

      return ans;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

struct SegTree(alias pred = "a + b", T = long) {
  alias predFun = binaryFun!pred;
  int size;
  T[] data;
  T monoid;

  this(T[] src, T monoid = T.init) {
    this.monoid = monoid;

    for(int i = 2; i < 2L^^32; i *= 2) {
      if (src.length <= i) {
        size = i;
        break;
      }
    }

    data = new T[](size * 2);
    foreach(i, s; src) data[i + size] = s;
    foreach_reverse(b; 1..size) {
      data[b] = predFun(data[b * 2], data[b * 2 + 1]);
    }
  }

  void update(int index, T value) {
    int i = index + size;
    data[i] = value;
    while(i > 0) {
      i /= 2;
      data[i] = predFun(data[i * 2], data[i * 2 + 1]);
    }
  }

  T get(int index) {
    return data[index + size];
  }

  T sum(int a, int b, int k = 1, int l = 0, int r = -1) {
    if (r < 0) r = size;

    if (r <= a || b <= l) return monoid;
    if (a <= l && r <= b) return data[k];

    T leftValue = sum(a, b, 2*k, l, (l + r) / 2);
    T rightValue = sum(a, b, 2*k + 1, (l + r) / 2, r);
    return predFun(leftValue, rightValue);
  }
}


You have a fence consisting of $$$n$$$ vertical boards. The width of each board is $$$1$$$. The height of the $$$i$$$-th board is $$$a_i$$$. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \neq a_i$$$ holds.Unfortunately, it is possible that now your fence is not great. But you can change it! You can increase the length of the $$$i$$$-th board by $$$1$$$, but you have to pay $$$b_i$$$ rubles for it. The length of each board can be increased any number of times (possibly, zero).Calculate the minimum number of rubles you have to spend to make the fence great again!You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of queries. The first line of each query contains one integers $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of boards in the fence. The following $$$n$$$ lines of each query contain the descriptions of the boards. The $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$) — the length of the $$$i$$$-th board and the price for increasing it by $$$1$$$, respectively. It is guaranteed that sum of all $$$n$$$ over all queries not exceed $$$3 \cdot 10^5$$$. It is guaranteed that answer to each query will not exceed $$$10^{18}$$$.

For each query print one integer — the minimum number of rubles you have to spend to make the fence great.

NoteIn the first query you have to increase the length of second board by $$$2$$$. So your total costs if $$$2 \cdot b_2 = 2$$$.In the second query you have to increase the length of first board by $$$1$$$ and the length of third board by $$$1$$$. So your total costs if $$$1 \cdot b_1 + 1 \cdot b_3 = 9$$$.In the third query the fence is great initially, so you don't need to spend rubles.

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

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

const long infty = 1_000_000_000_000_000_999;

void solve(){
	int q = rint;
	foreach(_; 0 .. q){
		int n = rint;
		S[] as;
		foreach(i; 0 .. n) as ~= S(rlong, rlong);

		long[][] xs = new long[][](n, 3);
			// xs[i][k]: min possible cost when #i is raised by k
		foreach(i, a; as){
			if(i == 0){
				xs[i][0] = 0;
				xs[i][1] = a.b;
				xs[i][2] = a.b + a.b;
			}
			else{
				S last = as[i - 1];
				foreach(k; 0 .. 3){
					long temp = infty;
					foreach(klast; 0 .. 3){
						if(last.a + klast == a.a + k) continue;
						temp = min(temp, xs[i - 1][klast] + a.b * k);
					}
					xs[i][k] = temp;
				}
			}
		}
		long ans = min(xs[n - 1][0], xs[n - 1][1], xs[n - 1][2]);
		ans.writeln;
	}
}
struct S{
	long a, b;
}


You are given two integers $$$x$$$ and $$$y$$$. You can perform two types of operations:   Pay $$$a$$$ dollars and increase or decrease any of these integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are four possible outcomes after this operation:   $$$x = 0$$$, $$$y = 6$$$;  $$$x = 0$$$, $$$y = 8$$$;  $$$x = -1$$$, $$$y = 7$$$;  $$$x = 1$$$, $$$y = 7$$$.   Pay $$$b$$$ dollars and increase or decrease both integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are two possible outcomes after this operation:   $$$x = -1$$$, $$$y = 6$$$;  $$$x = 1$$$, $$$y = 8$$$.  Your goal is to make both given integers equal zero simultaneously, i.e. $$$x = y = 0$$$. There are no other requirements. In particular, it is possible to move from $$$x=1$$$, $$$y=0$$$ to $$$x=y=0$$$.Calculate the minimum amount of dollars you have to spend on it.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 10^9$$$). The second line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case print one integer — the minimum amount of dollars you have to spend.

NoteIn the first test case you can perform the following sequence of operations: first, second, first. This way you spend $$$391 + 555 + 391 = 1337$$$ dollars.In the second test case both integers are equal to zero initially, so you dont' have to spend money.

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm, std.array, std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
int inz(long t){ return to!int(t); }
static string[] tempstr;
T rd(T = long)() { while(!tempstr.length) tempstr = readln.chomp.split; string res = tempstr[0]; tempstr.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    ll x, y, a, b;
    x = rd; y = rd;
    a = rd; b = rd;
    ll cost = a * (max(x, y) - min(x, y));
    cost += min(2*a*min(x, y), b*min(x, y));
    writeln(cost);
}

int main(){
    ll t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto xy = readln.split.to!(long[]);
        auto x = xy[0];
        auto y = xy[1];
        auto ab = readln.split.to!(long[]);
        auto a = ab[0];
        auto b = ab[1];

        writeln(min(
            x * a + y * a,
            min(x, y) * b + abs(x - y) * a
        ));
    }
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int x, y;
		readf !(" %s %s") (x, y);
		int a, b;
		readf !(" %s %s") (a, b);
		b = min (b, a * 2);
		if (x > y)
		{
			swap (x, y);
		}
		writeln (x * 1L * b + (y - x) * 1L * a);
	}
}

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    int x = r.next!int;
    int y = r.next!int;
    const long a = r.next!int;
    const long b = r.next!int;
    long res = (x + y) * a;
    if (x > y) swap (x, y);
    res = min (res, b * x + (y - x) * a);
    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)); }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto x = RD;
		auto y = RD;
		auto a = RD;
		auto b = RD;
		ans[ti] = abs(x-y) * a + min(abs(x), abs(y)) * b;
		ans[ti].chmin(x*a + y*a);
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto x = RD;
		auto y = RD;
		auto a = RD;
		auto b = RD;
		ans[ti] = abs(x-y) * a + min(x, y) * b;
	}

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


Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai  ≤  bi).Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!

The first line of the input contains one integer n (2 ≤ n ≤ 100 000) — number of cola cans. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — volume of remaining cola in cans. The third line contains n space-separated integers that b1, b2, ..., bn (ai ≤ bi ≤ 109) — capacities of the cans.

Print "YES" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteIn the first sample, there are already 2 cans, so the answer is "YES".

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

/* Start of Template */
// Input
class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() {
    while (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); }

// Min/Max
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; }

/* End of Template */

int n;
long total;
long maxone, maxtwo;

void main(string[] args) {
    try {
        for(; ; ) {
            n = readInt;
            maxone = long.min;
            maxtwo = long.min;
            total = 0;
            foreach (i; 0 .. n) total += readLong;
            foreach (i; 0 .. n) {
                long cur = readLong;
                if (cur > maxone) {
                    maxtwo = maxone;
                    maxone = cur;
                } else if (cur > maxtwo) {
                    maxtwo = cur;
                }
            }
            if (maxone + maxtwo - total < 0) writeln("NO");
            else writeln("YES");
        }
    } catch (EOFException) {}
}

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

/* template start */
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); }
/* template end */

void main(string[] args) {
    try {
        for(; ; ) {
            long n = readLong;
            long sum = 0;
            foreach (i; 0 .. n) sum += readLong;
            long maxone = long.min, maxtwo = long.min;
            foreach (i; 0 .. n) {
                long cur = readLong;
                if (cur > maxone) {
                    maxtwo = maxone;
                    maxone = cur;
                } else if (cur > maxtwo) {
                    maxtwo = cur;
                }
            }
            if (maxone + maxtwo - sum < 0) writeln("NO");
            else writeln("YES");
        }
    } catch (EOFException) {}
}

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

long n;

void main() {
  n = readln.chomp.to!long;
  auto a = readln.chomp.split.map!(to!long).array;
  auto b = readln.chomp.split.map!(to!long).array;

  sort!("a < b")(b);

  if (b[$-1] + b[$-2] >= reduce!("a + b")(0L, a)) "YES".writeln;
  else "NO".writeln;
}

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;

/* template start */
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); }
/* template end */

void main(string[] args) {
    try {
        for(; ; ) {
            int n = readInt;
            int sum = 0;
            foreach (i; 0 .. n) sum += readInt;
            int maxone = int.min, maxtwo = int.min;
            foreach (i; 0 .. n) {
                int cur = readInt;
                if (cur > maxone) {
                    maxtwo = maxone;
                    maxone = cur;
                } else if (cur > maxtwo) {
                    maxtwo = cur;
                }
            }
            if (maxone + maxtwo - sum < 0) writeln("NO");
            else writeln("YES");
        }
    } catch (EOFException) {}
}

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

int n;

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

  sort!("a < b")(b);

  if (b[$-1] + b[$-2] >= reduce!("a + b")(0, a)) "YES".writeln;
  else "NO".writeln;
}


You are given an array $$$a_1, a_2, \dots , a_n$$$. Array is good if for each pair of indexes $$$i < j$$$ the condition $$$j - a_j \ne i - a_i$$$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if $$$a = [1, 1, 3, 5]$$$, then shuffled arrays $$$[1, 3, 5, 1]$$$, $$$[3, 5, 1, 1]$$$ and $$$[5, 3, 1, 1]$$$ are good, but shuffled arrays $$$[3, 1, 5, 1]$$$, $$$[1, 1, 3, 5]$$$ and $$$[1, 1, 5, 3]$$$ aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.

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

For each test case print the shuffled version of the array $$$a$$$ which is good.

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint ();
    auto a = r.nextA!int (n);
    //j - a[j] != i - a[i]
    //j - i != a[j] - a[i]
    sort (a);
    reverse (a);
    writefln ("%(%s %)", a);
  }
}

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(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. scan!int){
        int n = scan!int;
        long[] as = scan!long(n);
        as.sort!"a>b"();
        as.unsplit.print;
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

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


Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration.  Twilight Sparkle wanted to track the path of Nightmare Moon. Unfortunately, she didn't know the exact path. What she knew is the parity of the number of times that each place Nightmare Moon visited. Can you help Twilight Sparkle to restore any path that is consistent with this information?Ponyville can be represented as an undirected graph (vertices are places, edges are roads between places) without self-loops and multi-edges. The path can start and end at any place (also it can be empty). Each place can be visited multiple times. The path must not visit more than 4n places.

The first line contains two integers n and m (2 ≤ n ≤ 105; 0 ≤ m ≤ 105) — the number of places and the number of roads in Ponyville. Each of the following m lines contains two integers ui, vi (1 ≤ ui, vi ≤ n; ui ≠ vi), these integers describe a road between places ui and vi. The next line contains n integers: x1, x2, ..., xn (0 ≤ xi ≤ 1) — the parity of the number of times that each place must be visited. If xi = 0, then the i-th place must be visited even number of times, else it must be visited odd number of times.

Output the number of visited places k in the first line (0 ≤ k ≤ 4n). Then output k integers — the numbers of places in the order of path. If xi = 0, then the i-th place must appear in the path even number of times, else i-th place must appear in the path odd number of times. Note, that given road system has no self-loops, therefore any two neighbouring places in the path must be distinct. If there is no required path, output -1. If there multiple possible paths, you can output any of them.

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

void main ()
{
	int n, m;
	test_loop:
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new int [] [n];
		foreach (i; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u] ~= v;
			a[v] ~= u;
		}

		auto x = new int [n];
		foreach (ref y; x)
		{
			readf (" %s", &y);
		}

		auto b = new bool [n];
		int [] ans;

		void recur (int v)
		{
			if (b[v])
			{
				return;
			}
			b[v] = true;

			foreach (u; a[v])
			{
				if (!b[u])
				{
					ans ~= u;
					x[u] ^= 1;
					recur (u);
					ans ~= v;
					x[v] ^= 1;

					if (x[u])
					{
						ans ~= u;
						x[u] ^= 1;
						ans ~= v;
						x[v] ^= 1;
					}
				}
			}
		}

		foreach (i; 0..n)
		{
			if (x[i])
			{
				ans ~= i;
				x[i] ^= 1;
				recur (i);

				if (x[i])
				{
					assert (!a[i].empty);
					ans ~= a[i][0];
					x[a[i][0]] ^= 1;
					ans ~= i;
					x[i] ^= 1;
					ans ~= a[i][0];
					x[a[i][0]] ^= 1;
				}

				foreach (y; x)
				{
					if (y)
					{
						writeln (-1);
						continue test_loop;
					}
				}

				ans[] += 1;
				writeln (ans.length);
				writefln ("%(%s %)", ans);
				continue test_loop;
			}
		}
		writeln (0);
	}
}

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

int N, M;
int[][] G;
int[] X;

int[] par;
void dfs(int u, int p) {
	par[u] = p;
	foreach (v; G[u]) if (v != p) {
		if (par[v] == -2) {
			dfs(v, u);
		}
	}
}

int[] ans;
int[] cnt;
void solve(int u, int p) {
	ans ~= u;
	cnt[u] ^= 1;
	foreach (v; G[u]) if (u == par[v]) {
		solve(v, u);
		ans ~= u;
		cnt[u] ^= 1;
	}
	if (cnt[u] != X[u]) {
		if (p != -1) {
			ans ~= p;
			cnt[p] ^= 1;
			ans ~= u;
			cnt[u] ^= 1;
		} else {
			assert(ans[$ - 1] == u);
			ans.popBack;
			cnt[u] ^= 1;
		}
	}
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		M = readInt;
		G = new int[][N];
		foreach (i; 0 .. M) {
			const u = readInt - 1;
			const v = readInt - 1;
			G[u] ~= v;
			G[v] ~= u;
		}
		X = new int[N];
		foreach (u; 0 .. N) {
			X[u] = readInt;
		}

		int src = -1;
		foreach (u; 0 .. N) {
			if (X[u]) {
				src = u;
				break;
			}
		}
		if (src == -1) {
			writeln("0");
			continue;
		}

		par = new int[N];
		par[] = -2;
		dfs(src, -1);

		bool ok = true;
		foreach (u; 0 .. N) {
			if (X[u]) {
				if (par[u] == -2) {
					ok = false;
					break;
				}
			}
		}
		if (!ok) {
			writeln("-1");
			continue;
		}

		ans = new int[0];
		cnt = new int[N];
		solve(src, -1);
		writeln(ans.length);
		foreach (j, u; ans) {
			if (j > 0) write(" ");
			write(u + 1);
		}
		writeln;

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

int N, M;
int[][] G;
int[] X;

int[] par;
void dfs(int u, int p) {
	par[u] = p;
	foreach (v; G[u]) if (v != p) {
		if (par[v] == -2) {
			dfs(v, u);
		}
	}
}

int[] ans;
int[] cnt;
void solve(int u, int p) {
	ans ~= u;
	cnt[u] ^= 1;
	foreach (v; G[u]) if (u == par[v]) {
		solve(v, u);
		ans ~= u;
		cnt[u] ^= 1;
	}
	if (cnt[u] != X[u]) {
		if (p != -1) {
			ans ~= p;
			cnt[p] ^= 1;
			ans ~= u;
			cnt[u] ^= 1;
		} else {
			assert(ans[$ - 1] == u);
			ans.popBack;
			cnt[u] ^= 1;
		}
	}
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		M = readInt;
		G = new int[][N];
		foreach (i; 0 .. M) {
			const u = readInt - 1;
			const v = readInt - 1;
			G[u] ~= v;
			G[v] ~= u;
		}
		X = new int[N];
		foreach (u; 0 .. N) {
			X[u] = readInt;
		}

		int src = -1;
		foreach (u; 0 .. N) {
			if (X[u]) {
				src = u;
				break;
			}
		}
		if (src == -1) {
			writeln("0");
			continue;
		}

		par = new int[N];
		par[] = -2;
		dfs(src, -1);
		foreach (u; 0 .. N) {
			if (X[u]) {
				if (par[u] == -2) {
					writeln("-1");
					break;
				}
			}
		}

		ans = new int[0];
		cnt = new int[N];
		solve(src, -1);
		writeln(ans.length);
		foreach (j, u; ans) {
			if (j > 0) write(" ");
			write(u + 1);
		}
		writeln;

	}
	} catch (EOFException) {}
}


Alice and Bob are playing yet another card game. This time the rules are the following. There are $$$n$$$ cards lying in a row in front of them. The $$$i$$$-th card has value $$$a_i$$$. First, Alice chooses a non-empty consecutive segment of cards $$$[l; r]$$$ ($$$l \le r$$$). After that Bob removes a single card $$$j$$$ from that segment $$$(l \le j \le r)$$$. The score of the game is the total value of the remaining cards on the segment $$$(a_l + a_{l + 1} + \dots + a_{j - 1} + a_{j + 1} + \dots + a_{r - 1} + a_r)$$$. In particular, if Alice chooses a segment with just one element, then the score after Bob removes the only card is $$$0$$$.Alice wants to make the score as big as possible. Bob takes such a card that the score is as small as possible.What segment should Alice choose so that the score is maximum possible? Output the maximum score.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of cards. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-30 \le a_i \le 30$$$) — the values on the cards.

Print a single integer — the final score of the game.

NoteIn the first example Alice chooses a segment $$$[1;5]$$$ — the entire row of cards. Bob removes card $$$3$$$ with the value $$$10$$$ from the segment. Thus, the final score is $$$5 + (-2) + (-1) + 4 = 6$$$.In the second example Alice chooses a segment $$$[1;4]$$$, so that Bob removes either card $$$1$$$ or $$$3$$$ with the value $$$5$$$, making the answer $$$5 + 2 + 3 = 10$$$.In the third example Alice can choose any of the segments of length $$$1$$$: $$$[1;1]$$$, $$$[2;2]$$$ or $$$[3;3]$$$. Bob removes the only card, so the score is $$$0$$$. If Alice chooses some other segment then the answer will be less than $$$0$$$.

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

immutable int maxValue = 30;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		int res = 0;
		for (int value = 0; value <= +maxValue; value++)
		{
			int cur = 0;
			int lo = cur;
			foreach (const ref c; a)
			{
				if (c > value)
				{
					cur = 0;
					lo = cur;
				}
				else
				{
					cur += c;
					lo = min (lo, cur);
					res = max (res, cur - lo - value);
				}
			}
		}

		writeln (res);
	}
}


This is an interactive problem.Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.Let's define $$$x$$$ as the distance to Mars. Unfortunately, Natasha does not know $$$x$$$. But it is known that $$$1 \le x \le m$$$, where Natasha knows the number $$$m$$$. Besides, $$$x$$$ and $$$m$$$ are positive integers.Natasha can ask the rocket questions. Every question is an integer $$$y$$$ ($$$1 \le y \le m$$$). The correct answer to the question is $$$-1$$$, if $$$x<y$$$, $$$0$$$, if $$$x=y$$$, and $$$1$$$, if $$$x>y$$$. But the rocket is broken — it does not always answer correctly. Precisely: let the correct answer to the current question be equal to $$$t$$$, then, if the rocket answers this question correctly, then it will answer $$$t$$$, otherwise it will answer $$$-t$$$.In addition, the rocket has a sequence $$$p$$$ of length $$$n$$$. Each element of the sequence is either $$$0$$$ or $$$1$$$. The rocket processes this sequence in the cyclic order, that is $$$1$$$-st element, $$$2$$$-nd, $$$3$$$-rd, $$$\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$\ldots$$$. If the current element is $$$1$$$, the rocket answers correctly, if $$$0$$$ — lies. Natasha doesn't know the sequence $$$p$$$, but she knows its length — $$$n$$$.You can ask the rocket no more than $$$60$$$ questions.Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.Your solution will not be accepted, if it does not receive an answer $$$0$$$ from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).

The first line contains two integers $$$m$$$ and $$$n$$$ ($$$1 \le m \le 10^9$$$, $$$1 \le n \le 30$$$) — the maximum distance to Mars and the number of elements in the sequence $$$p$$$.

NoteIn the example, hacking would look like this:5 2 31 0This means that the current distance to Mars is equal to $$$3$$$, Natasha knows that it does not exceed $$$5$$$, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...Really:on the first query ($$$1$$$) the correct answer is $$$1$$$, the rocket answered correctly: $$$1$$$;on the second query ($$$2$$$) the correct answer is $$$1$$$, the rocket answered incorrectly: $$$-1$$$;on the third query ($$$4$$$) the correct answer is $$$-1$$$, the rocket answered correctly: $$$-1$$$;on the fourth query ($$$5$$$) the correct answer is $$$-1$$$, the rocket answered incorrectly: $$$1$$$;on the fifth query ($$$3$$$) the correct and incorrect answer is $$$0$$$.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto M = s[0].to!long;
    auto N = s[1];
    auto P = new int[](N);
    long x;
    int[] Q;
    int debug_cnt = 0;

    debug {
        x = readln.chomp.to!long;
        Q = N.iota.map!(_ => readln.chomp.to!int).array;
    }

    int ask(long y) {
        writeln(y);
        stdout.flush;
        debug {
            if (x < y) return -1 * Q[debug_cnt];
            else if (x > y) return 1 * Q[debug_cnt];
            else return 0;
            ++debug_cnt;
        }
        return readln.chomp.to!int;
    }

    foreach (i; 0..N) {
        P[i] = ask(1);
        if (P[i] == 0)
            return;
    }

    long hi = M+1;
    long lo = 0;
    int cnt = 0;

    while (hi - lo > 1) {
        long mid = (hi + lo) / 2;
        int ret = ask(mid) * P[cnt%N];
        if (ret == 1) {
            lo = mid;
        } else if (ret == -1) {
            hi = mid;
        } else {
            return;
        }
        ++cnt;
    }
}

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

int ask (int x)
{
	writeln (x);
	stdout.flush ();
	int res;
	readf (" %s", &res);
	return res;
}

void solve (int m, int n)
{
	auto p = new int [n];
	foreach (ref c; p)
	{
		auto cur = ask (1);
		if (cur == 0)
		{
			return;
		}
		c = (cur == +1);
	}

	int lo = 1;
	int hi = m;
	for (int step = 0; ; step++)
	{
		int me = (lo + hi) / 2;
		auto cur = ask (me);
		if (cur == 0)
		{
			return;
		}
		cur *= (p[step % n] ? +1 : -1);
		if (cur < 0)
		{
			hi = me - 1;
		}
		else
		{
			lo = me + 1;
		}
	}
}

void main ()
{
	int m, n;
	while (readf (" %s %s", &m, &n) > 0)
	{
		solve (m, n);
	}
}

import std.range, std.stdio;
int f (int x) {
	x.writeln;
	stdout.flush;
	int r;
	readf (" %s", &r);
	return r;
}
void main () {
	int m, n;
	readf (" %s %s", &m, &n);
	auto p = new int [n];
	int k = 1;
	foreach (i; 0..99) {
		int v, x = (k + m) / 2;
		if (i < n) {
			v = f (1);
			p[i] = v;
		} else {
			v = f (x) * p[i % n];
			if (v < 0) m = x - 1;
			else k = x + 1;
		}
		if (!v) return;
	}
}

import std.stdio;
int f (int x) {
	x.writeln;
	stdout.flush;
	int r;
	readf (" %s", r);
	return r;
}
void main () {
	int m, n, k, i, v = 1, x;
	readf (" %s %s", m, n);
	auto p = new int [n];
	for (; v; i++)
		if (i < n) p[i] = v = f (1);
		else {
			x = (k + m + 1) / 2;
			v = f (x) * p[i % n];
			if (v < 0) m = x;
			else k = x;
		}
}

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

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

    auto seq = new int[] (n);

    foreach (ref e; seq) {
        writeln(1);
        stdout.flush();

        readf("%s", &e);
        readln;

        if (e == 0) {
            return;
        }
    }

    int ans = 0, le = 1, r = m, i = 0;
    do {
        int mid = (le + r) / 2;
        writeln(mid);
        stdout.flush();

        readf("%s", &ans);
        readln;

        if (ans == 0) {
            return;
        }

        if (ans * seq[i] == 1) le = mid + 1;
        else r = mid - 1;

        i = (i+1) % n;

    } while (ans != 0);
}


You are given two integers $$$n$$$ and $$$k$$$.You should create an array of $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ such that the sum $$$(a_1 + a_2 + \dots + a_n)$$$ is divisible by $$$k$$$ and maximum element in $$$a$$$ is minimum possible.What is the minimum possible maximum element in $$$a$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$).

For each test case, print one integer — the minimum possible maximum element in array $$$a$$$ such that the sum $$$(a_1 + \dots + a_n)$$$ is divisible by $$$k$$$.

NoteIn the first test case $$$n = 1$$$, so the array consists of one element $$$a_1$$$ and if we make $$$a_1 = 5$$$ it will be divisible by $$$k = 5$$$ and the minimum possible.In the second test case, we can create array $$$a = [1, 2, 1, 2]$$$. The sum is divisible by $$$k = 3$$$ and the maximum is equal to $$$2$$$.In the third test case, we can create array $$$a = [1, 1, 1, 1, 1, 1, 1, 1]$$$. The sum is divisible by $$$k = 8$$$ and the maximum is equal to $$$1$$$.

module main;
import std.stdio;

auto read(T)()
{
    T value;
    readf!" %s"(value);
    return value;
}

void main()
{
    int t = read!int();
    foreach (_; 0 .. t)
    {
        int n = read!int(), k = read!int();
        writeln(n < k ? (k + n - 1) / n : n % k ? 2 : 1);
    }
}

module main;
import std.stdio;

auto readInt()
{
    int value;
    readf!" %d"(value);
    return value;
}

void main()
{
    int t = readInt();
    foreach (_; 0 .. t)
    {
        int n = readInt(), k = readInt();
        writeln(n < k ? (k + n - 1) / n : n % k ? 2 : 1);
    }
}

import std.stdio;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        long n, k;
        readf!"%d %d\n"(n, k);
        k *= (n + k - 1) / k;
        writeln((k + n - 1) / n);
    }
}

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, K; get(N, K);
        writeln(N % K == 0 ? 1 : N > K ? 2 : (K + N - 1) / N);
    }
}

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)
	{
		long n, k;
		readf !(" %s %s") (n, k);
		k = max (k, (n + k - 1) / k * k);
		writeln ((k + n - 1) / n);
	}
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(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;
		auto k = RD;

		if (n >= k)
		{
			auto rem = k - (n % k);
			if (rem == k)
				ans[ti] = 1;
			else
				ans[ti] = 2;
		}
		else
		{
			ans[ti] = (k+n-1) / n;
		}
	}

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

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, 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, K; get(N, K);
        writeln((K == 1 || N == K) ? 1 : N > K ? 2 : (K + N - 1) / N);
    }
}

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, K; get(N, K);
        writeln(N == K ? 1 : N > K ? 2 : (K + N - 1) / N);
    }
}

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)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		k = max (k, (n + k - 1) / k * k);
		writeln ((k + n - 1) / n);
	}
}


This problem is actually a subproblem of problem G from the same contest.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \le a_i \le n$$$).You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad). It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Each query is represented by two lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the type of the $$$i$$$-th candy in the box. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For each query print one integer — the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.

NoteIn the first query, you can prepare a gift with two candies of type $$$8$$$ and one candy of type $$$5$$$, totalling to $$$3$$$ candies.Note that this is not the only possible solution — taking two candies of type $$$4$$$ and one candy of type $$$6$$$ is also valid.

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

immutable long INF = 1L << 59;

long f(long n) {
    return n * (n + 1) / 2;
}

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        auto N = readln.chomp.to!int;
        auto A = readln.split.map!(to!int).array;
        int[int] cnt1, cnt2;
        foreach (a; A) cnt1[a] += 1;
        foreach (a; cnt1.values) cnt2[a] += 1;
        auto B = cnt2.keys.array;
        B.sort!"a > b";
        long ans = 0;
        long lo = INF;
        foreach (b; B) {
            long v = min(b.to!long, lo);
            long n = min(cnt2[b].to!long, v);
            ans += f(v) - f(v - n);
            lo = v - n;
        }
        ans.writeln;
    }
}

void main() {
  import std.stdio, std.string, std.conv, std.algorithm;

  int q;
  rd(q);

  while (q--) {
    int n;
    rd(n);
    auto a = readln.split.to!(int[]);
    auto freq = new int[](n);
    foreach (el; a) {
      freq[el - 1] += 1;
    }
    int[] b;
    foreach (f; freq) {
      if (f > 0) {
        b ~= f;
      }
    }
    b.sort!"a>b";
    int last = b[0] + 1;
    long ans = 0;
    foreach (el; b) {
      ans += min(last - 1, el);
      last = min(last - 1, el);
      if (last == 0) {
        break;
      }
    }
    writeln(ans);
  }

}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}


You are given a following process. There is a platform with $$$n$$$ columns. $$$1 \times 1$$$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the $$$n$$$ columns have at least one square in them, the bottom row is being removed. You will receive $$$1$$$ point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.

The first line of input contain 2 integer numbers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the length of the platform and the number of the squares. The next line contain $$$m$$$ integer numbers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le n$$$) — column in which $$$i$$$-th square will appear.

Print one integer — the amount of points you will receive.

NoteIn the sample case the answer will be equal to $$$2$$$ because after the appearing of $$$6$$$-th square will be removed one row (counts of the squares on the platform will look like $$$[2~ 3~ 1]$$$, and after removing one row will be $$$[1~ 2~ 0]$$$).After the appearing of $$$9$$$-th square counts will be $$$[2~ 3~ 1]$$$, and after removing one row it will look like $$$[1~ 2~ 0]$$$.So the answer will be equal to $$$2$$$.

import std.stdio;
import std.algorithm;

void main() {
    int[int] aux;
    int n, m;
    readf(" %d %d", n, m);

    foreach (_; 0..m) {
        int num;
        readf(" %d", num);
        aux[num]++;
    }

    if (aux.length != n)
        writeln(0);
    else
        writeln(aux.values.minElement);
}

import std.stdio;
import std.algorithm;

void main() {
    int[int] aux;
    int n, m;
    readf(" %d %d", n, m);

    foreach (_; 0..m) {
        int num;
        readf(" %d", num);
        aux[num]++;
    }

    writeln(aux.values.minElement);
}

import std.stdio;
import std.algorithm;

void main() {
    int[int] aux;
    int n, m;
    readf(" %d %d", n, m);

    foreach (_; 0..m) {
        int num;
        readf(" %d", num);
        aux[num]++;
    }

    writeln(max(1, aux.values.minElement));
}

import std.stdio;
import std.algorithm;

void main() {
    int[int] aux;
    int n, m;
    readf(" %d %d", n, m);

    foreach (_; 0..m) {
        int num;
        readf(" %d", num);
        aux[num]++;
    }

    if (aux.length == 0)
        writeln(0);
    else
        writeln(aux.values.minElement);
}


In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing".For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again. Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative. As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.

The first line contains three integers n, m, k (1 ≤ m ≤ n ≤ 1000, 0 ≤ k ≤ 106) — total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow n lines, each containing two integers: r (1 ≤ r ≤ m) — index of the row, where belongs the corresponding tooth, and c (0 ≤ c ≤ 106) — its residual viability. It's guaranteed that each tooth row has positive amount of teeth.

In the first line output the maximum amount of crucians that Valerie can consume for dinner.

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

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

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                int m = cin.readInt;
                int k = cin.readInt;

                int[][] t_arr = new int[][](m);
                for (int i = 0; i < n; i++) {
                        int a = cin.readInt;
                        int b = cin.readInt;
                        t_arr[a - 1] ~= b;
                }
                int count = 0;

                for (int i = 0; i < m; i++) {
                        count += t_arr[i].minElement;
                }

                if (count >= k) writeln(k);
                else writeln(count);
        }
}


Fishingprince is playing with an array $$$[a_1,a_2,\dots,a_n]$$$. He also has a magic number $$$m$$$.He can do the following two operations on it:  Select $$$1\le i\le n$$$ such that $$$a_i$$$ is divisible by $$$m$$$ (that is, there exists an integer $$$t$$$ such that $$$m \cdot t = a_i$$$). Replace $$$a_i$$$ with $$$m$$$ copies of $$$\frac{a_i}{m}$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[2,3]$$$ and $$$i=1$$$, $$$a$$$ changes into $$$[1,1,3]$$$.  Select $$$1\le i\le n-m+1$$$ such that $$$a_i=a_{i+1}=\dots=a_{i+m-1}$$$. Replace these $$$m$$$ elements with a single $$$m \cdot a_i$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[3,2,2,3]$$$ and $$$i=2$$$, $$$a$$$ changes into $$$[3,4,3]$$$. Note that the array length might change during the process. The value of $$$n$$$ above is defined as the current length of the array (might differ from the $$$n$$$ in the input).Fishingprince has another array $$$[b_1,b_2,\dots,b_k]$$$. Please determine if he can turn $$$a$$$ into $$$b$$$ using any number (possibly zero) of operations.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n\le 5\cdot 10^4$$$, $$$2\le m\le 10^9$$$). The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$). The third line of each test case contains one integer $$$k$$$ ($$$1\le k\le 5\cdot 10^4$$$). The fourth line of each test case contains $$$k$$$ integers $$$b_1,b_2,\ldots,b_k$$$ ($$$1\le b_i\le 10^9$$$). It is guaranteed that the sum of $$$n+k$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each testcase, print Yes if it is possible to turn $$$a$$$ into $$$b$$$, and No otherwise. You can print each letter in any case (upper or lower).

NoteIn the first test case of the sample, we can do the second operation with $$$i=2$$$: $$$[1,\color{red}{2,2},4,2]\to [1,\color{red}{4},4,2]$$$.In the second testcase of the sample, we can:  do the second operation with $$$i=2$$$: $$$[1,\color{red}{2,2},8,2,2]\to [1,\color{red}{4},8,2,2]$$$.  do the second operation with $$$i=4$$$: $$$[1,4,8,\color{red}{2,2}]\to [1,4,8,\color{red}{4}]$$$.  do the first operation with $$$i=3$$$: $$$[1,4,\color{red}{8},4]\to [1,4,\color{red}{4,4},4]$$$.  do the second operation with $$$i=2$$$: $$$[1,\color{red}{4,4},4,4]\to [1,\color{red}{8},4,4]$$$.  do the second operation with $$$i=3$$$: $$$[1,8,\color{red}{4,4}]\to [1,8,\color{red}{8}]$$$.  do the second operation with $$$i=2$$$: $$$[1,\color{red}{8,8}]\to [1,\color{red}{16}]$$$.

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

void solve()
{
    ulong n, m;
    auto cmp = (ulong x) {
        auto count = 0;
        while (x % m == 0)
        {
            x /= m;
            count++;
        }
        return tuple(x, m^^count);
    };
    readf!(" %s %s")(n, m);
    readln;
    auto A = readln.splitter
        .map!(to!ulong)
        .map!(cmp)
        .chunkBy!(x => x[0])
        .map!(x => tuple(x[0], x[1].map!(y => y[1]).sum()));
    readln;
    auto B = readln.splitter
        .map!(to!ulong)
        .map!(cmp)
        .chunkBy!(x => x[0])
        .map!(x => tuple(x[0], x[1].map!(y => y[1]).sum()));
    writeln(A.equal(B) ? "Yes" : "No");
}

void main()
{
    size_t TC = 1;
    TC = readln.strip.to!int;
    foreach (_; 0 .. TC)
        solve();
}

import std;

void main(){
	int t=readln.strip.to!int;
	foreach(_;0..t){
		auto m=readln.strip.split.to!(int[])[1];
		auto a=readln.strip.split.to!(int[]);
		readln();
		auto b=readln.strip.split.to!(int[]);
		auto rle(int[] x){
			auto canonicalize(int value){
				long repetitions=1;
				while(value%m==0){
					value/=m;
					repetitions*=m;
				}
				return tuple(value,repetitions);
			}
			return x.map!canonicalize.chunkBy!(a=>a[0]).map!(x=>tuple(x[0],x[1].map!(y=>y[1]).sum));
		}
		writeln(equal(rle(a),rle(b))?"Yes":"No");
	}
}

import std;

void main(){
	int t=readln.strip.to!int;
	foreach(_;0..t){
		auto m=readln.strip.split.to!(int[])[1];
		auto a=readln.strip.split.to!(int[]);
		readln();
		auto b=readln.strip.split.to!(int[]);
		auto rle(int[] x){
			auto canonicalize(int value){
				long repetitions=1;
				while(value%m==0){
					value/=m;
					repetitions*=m;
				}
				return q(value,repetitions);
			}
			return x.map!canonicalize.chunkBy!(a=>a[0]).map!(x=>q(x[0],x[1].map!(y=>y[1]).sum));
		}
		writeln(equal(rle(a),rle(b))?"Yes":"No");
	}
}

auto q(T...)(T args){
	struct Q{
		T expand;
		alias expand this;
		string toString(){
			auto r="(";
			foreach(i,alias x;expand)
				r~=(i!=0?",":"")~text(x);
			r~=")";
			return r;
		}
	}
	return Q(args);
}

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

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

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

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

alias Entry = Tuple!(long, "val", long, "num");

Entry[] solve(long[] A, long M) {
  const N = cast(int)(A.length);
  auto es = new Entry[N];
  foreach (i; 0 .. N) {
    auto e = Entry(A[i], 1);
    for (; e.val % M == 0; ) {
      e.val /= M;
      e.num *= M;
    }
    es[i] = e;
  }
  Entry[] ans;
  for (int i = 0, j; i < N; i = j) {
    long sum;
    for (j = i; j < N && es[i].val == es[j].val; ++j) {
      sum += es[j].num;
    }
    ans ~= Entry(es[i].val, sum);
  }
  debug {
    writeln(ans);
  }
  return ans;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const ALen = readInt;
        const M = readLong;
        auto A = new long[ALen];
        foreach (i; 0 .. ALen) {
          A[i] = readLong;
        }
        const BLen = readInt;
        auto B = new long[BLen];
        foreach (i; 0 .. BLen) {
          B[i] = readLong;
        }

        const resA = solve(A, M);
        const resB = solve(B, M);
        writeln((resA == resB) ? "Yes" : "No");
      }
    }
  } catch (EOFException e) {
  }
}

import std;

void main(){
	int t=readln.strip.to!int;
	foreach(_;0..t){
		auto m=readln.strip.split.to!(int[])[1];
		auto a=readln.strip.split.to!(int[]);
		readln();
		auto b=readln.strip.split.to!(int[]);
		auto rle(int[] x){
			auto canonicalize(int value){
				int repetitions=1;
				while(value%m==0){
					value/=m;
					repetitions*=m;
				}
				return tuple(value,repetitions);
			}
			return x.map!canonicalize.chunkBy!(a=>a[0]).map!(x=>tuple(x[0],x[1].map!(y=>y[1]).sum));
		}
		writeln(equal(rle(a),rle(b))?"Yes":"No");
	}
}