You are given a decimal representation of an integer $$$x$$$ without leading zeros.You have to perform the following reduction on it exactly once: take two neighboring digits in $$$x$$$ and replace them with their sum without leading zeros (if the sum is $$$0$$$, it's represented as a single $$$0$$$).For example, if $$$x = 10057$$$, the possible reductions are:   choose the first and the second digits $$$1$$$ and $$$0$$$, replace them with $$$1+0=1$$$; the result is $$$1057$$$;  choose the second and the third digits $$$0$$$ and $$$0$$$, replace them with $$$0+0=0$$$; the result is also $$$1057$$$;  choose the third and the fourth digits $$$0$$$ and $$$5$$$, replace them with $$$0+5=5$$$; the result is still $$$1057$$$;  choose the fourth and the fifth digits $$$5$$$ and $$$7$$$, replace them with $$$5+7=12$$$; the result is $$$10012$$$. What's the largest number that can be obtained?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Each testcase consists of a single integer $$$x$$$ ($$$10 \le x < 10^{200000}$$$). $$$x$$$ doesn't contain leading zeros. The total length of the decimal representations of $$$x$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the largest number that can be obtained after the reduction is applied exactly once. The number should not contain leading zeros.

NoteThe first testcase of the example is already explained in the statement.In the second testcase, there is only one possible reduction: the first and the second digits.

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto s = readln.strip;
    int best1 = -1;
    int eq1 = -1;

    foreach (i ; 0 .. cast(int)s.length - 1) {
      int digit1 = s[i] - '0';
      int digit2 = s[i + 1] - '0';
      if (digit1 + digit2 < 10 && digit1 + digit2 > digit1) {
        best1 = i;
        break;
      }
      if (digit1 + digit2 < 10 && digit1 + digit2 == digit1) {
        if (i + 2 >= s.length) {
          best1 = i;
          break;
        }
        int digit3 = s[i + 2] - '0';
        if (digit3 > digit2) {
          best1 = i;
          break;
        } else if (digit3 == digit2) {
          eq1 = i;
        }
      }
    }
    if (best1 == -1) {
      if (eq1 != -1)
        best1 = eq1;
      else
        best1 = cast(int)s.length - 2;
    }

    bool have_best2 = false;
    int default_best2;
    foreach_reverse (i ; 0 .. cast(int)s.length - 1) {
      if ((s[i] - '0') + (s[i + 1] - '0') >= 10) {
        have_best2 = true;
        default_best2 = i;
        break;
      }
    }
    int ans = best1;
    int best2 = -1;
    int eq2 = -1;
    if (have_best2) {
      foreach (i ; 0 .. cast(int)s.length - 1) {
        int digit1 = s[i] - '0';
        int digit2 = s[i + 1] - '0';
        if (digit1 + digit2 < 10)
          continue;
        if ((digit1 + digit2) / 10 > digit1) {
          best2 = i;
          break;
        }
        if ((digit1 + digit2) / 10 == digit1) {
          if ((digit1 + digit2) % 10 > digit2) {
            best2 = i;
            break;
          } else if ((digit1 + digit2) % 10 == digit2) {
            eq2 = i;
          }
        }
      }
      if (best2 == -1) {
        if (eq2 != -1)
          best2 = eq2;
        else
          best2 = default_best2;
      }
      ans = best2;
    }
    auto s1 = s[0 .. ans];
    auto s2 = ((s[ans] - '0') + (s[ans + 1] - '0')).to!string;
    auto s3 = s[ans + 2 .. $];
    writefln("%s%s%s", s1, s2, s3);
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		auto n = s.length.to !(int);
		int p = 1;
		foreach (i; 1..n)
		{
			if (s[i - 1] + s[i] > '0' + '9')
			{
				p = i;
			}
		}
		writeln (s[0..p - 1], s[p - 1] + s[p] - '0' - '0',
		    s[p + 1..$]);
	}
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;

      auto candidates = new int[][](0, 2);
      foreach(i; 0..cast(int)S.length - 1) {
        int sum = (S[i] - '0') + (S[i + 1] - '0');
        candidates ~= [i, sum];
      }

      auto twos = candidates.filter!"a[1] > 9";
      if (twos.empty) {
        return candidates[0][1].to!string ~ S[2..$];
      } else {
        auto c = candidates.filter!"a[1] > 9".array[$ - 1];
        return S[0..c[0]] ~ c[1].to!string ~ S[c[0] + 2..$];
      }
    }

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

  outputForAtCoder(&solve);
}

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

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

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

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

bool better1(int a, int b, int c)
{
  int x1 = (a + b) * 10 + c;
  int x2 = (b + c) < 10 ? a * 10 + (b + c) : a * 100 + (b + c);
  return x2 >= x1;
}

bool better2(int a, int b, int c)
{
  int x1 = (a + b) * 10 + c;
  int x2 = (b + c) < 10 ? a * 10 + (b + c) : a * 100 + (b + c);
  return (b + c) >= 10 && x2 >= x1;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto s = readln.strip;
    int best1 = 0;
    foreach (i ; 0 .. cast(int)s.length - 2) {
      if (!better1(s[i] - '0', s[i + 1] - '0', s[i + 2] - '0'))
        break;
      best1 = i + 1;
    }
    bool have_best2 = false;
    int best2;
    foreach (i ; 0 .. cast(int)s.length - 1) {
      if ((s[i] - '0') + (s[i + 1] - '0') >= 10) {
        have_best2 = true;
        best2 = i;
        break;
      }
    }
    int ans = best1;
    if (have_best2) {
      foreach (i ; best2 .. cast(int)s.length - 2) {
        if (!better2(s[i] - '0', s[i + 1] - '0', s[i + 2] - '0'))
          break;
        best2 = i + 1;
      }
      ans = best2;
    }
    auto s1 = s[0 .. ans];
    auto s2 = ((s[ans] - '0') + (s[ans + 1] - '0')).to!string;
    auto s3 = s[ans + 2 .. $];
    writefln("%s%s%s", s1, s2, s3);
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		auto n = s.length.to !(int);
		int p = n - 1;
		foreach (i; 1..n)
		{
			if (s[i - 1] + s[i] > '0' + '9')
			{
				p = i;
			}
		}
		writeln (s[0..p - 1], s[p - 1] + s[p] - '0' - '0',
		    s[p + 1..$]);
	}
}


You are given two strings $$$s$$$ and $$$t$$$, both consisting of lowercase English letters. You are going to type the string $$$s$$$ character by character, from the first character to the last one.When typing a character, instead of pressing the button corresponding to it, you can press the "Backspace" button. It deletes the last character you have typed among those that aren't deleted yet (or does nothing if there are no characters in the current string). For example, if $$$s$$$ is "abcbd" and you press Backspace instead of typing the first and the fourth characters, you will get the string "bd" (the first press of Backspace deletes no character, and the second press deletes the character 'c'). Another example, if $$$s$$$ is "abcaa" and you press Backspace instead of the last two letters, then the resulting text is "a".Your task is to determine whether you can obtain the string $$$t$$$, if you type the string $$$s$$$ and press "Backspace" instead of typing several (maybe zero) characters of $$$s$$$.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of test cases. The first line of each test case contains the string $$$s$$$ ($$$1 \le |s| \le 10^5$$$). Each character of $$$s$$$ is a lowercase English letter. The second line of each test case contains the string $$$t$$$ ($$$1 \le |t| \le 10^5$$$). Each character of $$$t$$$ is a lowercase English letter. It is guaranteed that the total number of characters in the strings over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" if you can obtain the string $$$t$$$ by typing the string $$$s$$$ and replacing some characters with presses of "Backspace" button, or "NO" if you cannot. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

4
ababa
ba
ababa
bb
aaa
aaaa
aababa
ababa

NoteConsider the example test from the statement.In order to obtain "ba" from "ababa", you may press Backspace instead of typing the first and the fourth characters.There's no way to obtain "bb" while typing "ababa".There's no way to obtain "aaaa" while typing "aaa".In order to obtain "ababa" while typing "aababa", you have to press Backspace instead of typing the first character, then type all the remaining characters.

import std.stdio;
import std.algorithm;
import std.array;
import std.ascii;
import core.stdc.stdio;

void main()
{
	int q = readInt!int;
	while (q--)
	{
		char[] s = cast(char[])readString;
		s.reverse;
		int ns = cast(int)s.length;
		char[] t = cast(char[])readString;
		t.reverse;
		int ei = -1;
		foreach(i, si; s)
		{
			if (si == t[0] && (i&1) == 0)
			{
				if (ei == -1) ei = cast(int)i;
			}
		}
		bool can(int i, char[] t)
		{
			while (i < ns && t.length > 0)
			{
				if (s[i] == t[0])
				{
					i++;
					t = t[1 .. $];
					continue;
				}
				else
				{
					i += 2;
				}
			}
			return t.length == 0;
		}
		bool cane = ei != -1 && can(ei, t.dup);
		if (cane) writeln("yes"); else writeln("no");
	}
}

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

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

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

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

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

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

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

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

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

string s, t;
int sn, tn;

bool solve(int si, int ti)
{
  if (ti == tn)
    return true;

  if (si == sn)
    return false;

  if (s[si] != t[ti] && si + 2 > sn)
    return false;

  if (s[si] == t[ti]) {
    bool ans1, ans2;
//    if (si + 2 <= sn)
//      ans1 = solve(si + 2, ti);
    if (si + 1 <= sn && ti + 1 <= tn)
      ans2 = solve(si + 1, ti + 1);
    return ans1 || ans2;
  } else {
    bool ans1, ans2;
    if (si + 2 <= sn)
      ans1 = solve(si + 2, ti);
    return ans1 || ans2;
  }
}

void main()
{
  long q;
  readf!" %d "(q);
  while (q--) {
    s = readln.strip.retro.text;
    t = readln.strip.retro.text;
    sn = cast(int)s.length;
    tn = cast(int)t.length;
//    writeln(s);
//    writeln(t);
    writeln(solve(0, 0) ? "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)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		if (s.length < ss.length) continue;
		if ((ss.length - s.length) % 2)
			s.popFront;

		int i, j;
		while (i < s.length && j < ss.length)
		{
			if (s[i] == ss[j])
			{
				++i;
				++j;
			}
			else
			{
				i += 2;
			}
		}
		debug writeln("i:", i, " j:", j);
		if (j == ss.length)
			ans[ti] = true;
	}

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

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

bool solve (string s, string t)
{
	if ((s.length % 2) != (t.length % 2))
	{
		s = s[1..$];
	}
	int pos = 0;
	bool skip = false;
	foreach (ref c; s)
	{
		if (skip)
		{
			skip = false;
			continue;
		}
		if (t[pos] == c)
		{
			pos += 1;
		}
		else
		{
			skip = true;
		}
		if (pos == t.length)
		{
			return true;
		}
	}
	return false;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		auto t = readln.strip;
		writeln (solve (s, t) ? "YES" : "NO");
	}
}

import std.stdio;
import std.ascii;
import core.stdc.stdio;

void main()
{
	int q = readInt!int;
	while (q--)
	{
		char[] s = cast(char[])readString;
		int ns = cast(int)s.length;
		char[] t = cast(char[])readString;
		int ei = -1;
		int oi = -1;
		foreach(i, si; s)
		{
			if (si == t[0])
			{
				if (i & 1)
				{
					if (oi == -1) oi = cast(int)i;
				}
				else if (ei == -1) ei = cast(int)i;
			}
		}
		bool can(int i, char[] t)
		{
			while (i < ns && t.length > 0)
			{
				if (s[i] == t[0])
				{
					i++;
					t = t[1 .. $];
					continue;
				}
				else
				{
					i += 2;
				}
			}
			return t.length == 0;
		}
		bool cane = ei != -1 && can(ei, t.dup);
		bool cano = oi != -1 && can(oi, t.dup);
		if (cane || cano) writeln("yes"); else writeln("no");
	}
}

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

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

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

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

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

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

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

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


The King of Berland Polycarp LXXXIV has $$$n$$$ daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are $$$n$$$ other kingdoms as well.So Polycarp LXXXIV has enumerated his daughters from $$$1$$$ to $$$n$$$ and the kingdoms from $$$1$$$ to $$$n$$$. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.Polycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.For the first daughter he takes the kingdom with the lowest number from her list and marries the daughter to their prince. For the second daughter he takes the kingdom with the lowest number from her list, prince of which hasn't been taken already. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the $$$n$$$-th daughter.For example, let there be $$$4$$$ daughters and kingdoms, the lists daughters have are $$$[2, 3]$$$, $$$[1, 2]$$$, $$$[3, 4]$$$, $$$[3]$$$, respectively.  In that case daughter $$$1$$$ marries the prince of kingdom $$$2$$$, daughter $$$2$$$ marries the prince of kingdom $$$1$$$, daughter $$$3$$$ marries the prince of kingdom $$$3$$$, leaving daughter $$$4$$$ nobody to marry to.Actually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. Note that this kingdom should not be present in the daughter's list.Polycarp LXXXIV wants to increase the number of married couples.Unfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.For your and our convenience you are asked to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of daughters and the number of kingdoms. Each of the next $$$n$$$ lines contains the description of each daughter's list. The first integer $$$k$$$ ($$$0 \le k \le n$$$) is the number of entries in the $$$i$$$-th daughter's list. After that $$$k$$$ distinct integers follow $$$g_i[1], g_i[2], \dots, g_i[k]$$$ ($$$1 \le g_i[j] \le n$$$) — the indices of the kingdoms in the list in the increasing order ($$$g_i[1] < g_i[2] < \dots < g_i[k]$$$). It's guaranteed that the total number of daughters over all test cases does not exceed $$$10^5$$$. It's also guaranteed that the total number of kingdoms in lists over all test cases does not exceed $$$10^5$$$.

For each test case print the answer to it. Print "IMPROVE" in the first line if Polycarp LXXXIV can add some kingdom to some of his daughter's list so that the total number of married couples increases. The second line then should contain two integers — the index of the daughter and the index of the kingdom Polycarp LXXXIV should add to that daughter's list. If there are multiple ways to add an entry so that the total number of married couples increases then print any of them. Otherwise the only line should contain one word "OPTIMAL".

IMPROVE
4 4
IMPROVE
1 1
OPTIMAL
OPTIMAL
OPTIMAL

NoteThe first test case is depicted in the statement. Adding the fourth kingdom to the list of the fourth daughter makes her marry the prince of the fourth kingdom.In the second test case any new entry will increase the number of marriages from $$$0$$$ to $$$1$$$.In the third and the fourth test cases there is no way to add an entry.In the fifth test case there is no way to change the marriages by adding any entry.

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(){
    A: foreach(_; 0 .. scan!int){
        int n = scan!int;
        bool[] isMarried = new bool[](n);
        bool[] isSold = new bool[](n);
        foreach(i; 0 .. n){
            int k = scan!int;
            int[] gs = scan!int(k).map!(x => x - 1).array;
            foreach(g; gs){
                if(! isSold[g]){
                    isSold[g] = 1;
                    isMarried[i] = 1;
                    break;
                }
            }
        }
        auto gq = new Queue!int;
        foreach(g; 0 .. n) if(! isSold[g]) gq.enq(g);

        if(gq.isEmpty){
            "OPTIMAL".print;
            continue A;
        }
        else{
            "IMPROVE".print;
            foreach(i; 0 .. n) if(! isMarried[i]){
                print(i + 1, gq.deq + 1);
                break;
            }
        }

    }
}

// ----- キュー -----
class Queue(T){
	private T[] xs;
	private uint i, j; // i : 次に読み出す位置　j: 次に書き込む位置
	this(){	}
	this(T[] xs){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){
		while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1;
		xs[j ++] = x;
	}
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(){ return new Queue!T; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}

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 n = RD!int;
		auto used = new bool[](n);
		foreach (i; 0..n)
		{
			auto k = RD;
			bool ok;
			foreach (j; 0..k)
			{
				auto e = RD!int-1;
				if (ok) continue;
				if (!used[e])
				{
					used[e] = true;
					ok = true;
				}
			}
			if (!ok)
			{
				ans[ti] = [i+1];
			}
		}
		if (!ans[ti].empty)
		{
			foreach (i; 0..n)
			{
				if (!used[i])
				{
					ans[ti] ~= i+1;
					break;
				}
			}
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
		{
			writeln("OPTIMAL");
		}
		else
		{
			writeln("IMPROVE");
			writeln(e[0], " ", e[1]);
		}
	}
	stdout.flush;
	debug readln;
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } 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(){
    A: foreach(_; 0 .. scan!int){
        int n = scan!int;
        bool[] isMarried = new bool[](n);
        bool[] isSold = new bool[](n);
        foreach(i; 0 .. n){
            int k = scan!int;
            int[] gs = scan!int(k).map!(x => x - 1).array;
            foreach(g; gs){
                if(! isSold[g]){
                    isSold[i] = 1;
                    isMarried[i] = 1;
                    break;
                }
            }
        }
        auto gq = new Queue!int;
        foreach(g; 0 .. n) if(! isSold[g]) gq.enq(g);

        if(gq.isEmpty){
            "OPTIMAL".print;
            continue A;
        }
        else{
            "IMPROVE".print;
            foreach(i; 0 .. n) if(! isMarried[i]){
                print(i + 1, gq.deq + 1);
                break;
            }
        }

    }
}

// ----- キュー -----
class Queue(T){
	private T[] xs;
	private uint i, j; // i : 次に読み出す位置　j: 次に書き込む位置
	this(){	}
	this(T[] xs){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){
		while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1;
		xs[j ++] = x;
	}
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(){ return new Queue!T; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}


You and your friend Ilya are participating in an individual programming contest consisting of multiple stages. A contestant can get between $$$0$$$ and $$$100$$$ points, inclusive, for each stage, independently of other contestants.Points received by contestants in different stages are used for forming overall contest results. Suppose that $$$k$$$ stages of the contest are completed. For each contestant, $$$k - \lfloor \frac{k}{4} \rfloor$$$ stages with the highest scores are selected, and these scores are added up. This sum is the overall result of the contestant. (Here $$$\lfloor t \rfloor$$$ denotes rounding $$$t$$$ down.)For example, suppose $$$9$$$ stages are completed, and your scores are $$$50, 30, 50, 50, 100, 10, 30, 100, 50$$$. First, $$$7$$$ stages with the highest scores are chosen — for example, all stages except for the $$$2$$$-nd and the $$$6$$$-th can be chosen. Then your overall result is equal to $$$50 + 50 + 50 + 100 + 30 + 100 + 50 = 430$$$.As of now, $$$n$$$ stages are completed, and you know the points you and Ilya got for these stages. However, it is unknown how many more stages will be held. You wonder what the smallest number of additional stages is, after which your result might become greater than or equal to Ilya's result, at least in theory. Find this number!

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of completed stages. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 100$$$) — your points for the completed stages. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le 100$$$) — Ilya's points for the completed stages. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the smallest number of additional stages required for your result to be able to become greater than or equal to Ilya's result. If your result is already not less than Ilya's result, print $$$0$$$.

NoteIn the first test case, you have scored $$$100$$$ points for the first stage, while Ilya has scored $$$0$$$. Thus, your overall result ($$$100$$$) is already not less than Ilya's result ($$$0$$$).In the second test case, you have scored $$$0$$$ points for the first stage, while Ilya has scored $$$100$$$. A single stage with an opposite result is enough for both your and Ilya's overall scores to become equal to $$$100$$$.In the third test case, your overall result is $$$30 + 40 + 50 = 120$$$, while Ilya's result is $$$100 + 100 + 100 = 300$$$. After three additional stages your result might become equal to $$$420$$$, while Ilya's result might become equal to $$$400$$$.In the fourth test case, your overall result after four additional stages might become equal to $$$470$$$, while Ilya's result might become equal to $$$400$$$. Three stages are not enough.

import std.algorithm, std.range, std.stdio, std.numeric, std.array, std.exception,
       std.container, std.typecons, std.conv, std.random, std.bigint;

void read(S...)(ref S args) {
  auto input = readln.split;
  assert(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

int[] a, b, A, B;

int solve(int m) {
  int n = a.length.to!int;

  int q = n + m;
  q -= q / 4;

  int pointB = B[min(q, B.length) - 1];

  int pointA = m * 100;
  if (q > m) {
    pointA += A[q - m - 1];
  }

  return pointA >= pointB;
}

void main() {
  int t;
  read(t);

  while (t--) {
    int n;
    read(n);
    a = list!int;
    b = list!int;

    sort(a);
    reverse(a);
    sort(b);
    reverse(b);

    A = a.dup;
    B = b.dup;
    foreach (i; 1 .. n) A[i] = A[i - 1] + A[i];
    foreach (i; 1 .. n) B[i] = B[i - 1] + B[i];

    if (solve(0)) {
      writeln(0);
      continue;
    } else {
      auto low = 0;
      auto high = 300000;

      while (high > low + 1) {
        int mid = high + low;
        mid /= 2;

        if (solve(mid)) {
          high = mid;
        } else {
          low = mid;
        }
      }

      writeln(high);
    }
  }
}

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

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
auto sp(R)(R r, size_t i, size_t j)
{
	if (j < i) return 0;
	if (i == 0) return r[j];
	return r[j] - r[i - 1];
}
void solve()
{
	int n = readInt!int;
	auto a = new int[](n);
	auto b = new int[](n);
	foreach(ref ai; a) ai = readInt!int;
	foreach(ref bi; b) bi = readInt!int;
	sort(a); sort(b);
	a.reverse, b.reverse;
	auto pa = a.cumulativeFold!((a, b)=> cast(long)a + b).array;
	auto pb = b.cumulativeFold!((a, b)=> cast(long)a + b).array;
	int used = n - (n/4);
	int hi = 5 * 1_000_00;
	int lo = 0;
	int ans = -1;
	while (lo <= hi)
	{
		int mi = (lo + hi) / 2;
		int nn = mi + n;
		int usedmi = nn - nn / 4;
		int usedorig = max(0, usedmi - mi);
		int usednew = usedmi - usedorig;
		long sa = usednew * 100;
		if (usedorig) sa += pa[usedorig - 1];
		long sb = pb[min(n, usedmi) - 1];
		if (sa >= sb)
		{
			ans = mi;
			hi = mi - 1;
		}
		else
		{
			lo = mi + 1;
		}
	}
	ans.writeln;
}

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

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

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

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

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

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

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

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

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    int n; readf!"%s\n"(n);
    auto a = readln.splitter.map!(to!int).array.sort.reverse;
    auto b = readln.splitter.map!(to!int).array.sort.reverse;
    int low = -1, high = 3 * n + 1;
    while (low + 1 < high) {
      int mid = (low + high) / 2;
      int k = n + mid;
      int r = k - k / 4;
      long A, B;
      foreach(i; 0 .. r) {
        A += (i < mid) ? 100 : a[i - mid];
        B += (i < n) ? b[i] : 0;
      }
      ((A >= B) ? high : low) = mid;
    }
    high.writeln;
  }

} // main

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

long solve_max(long[] pfa, long n)
{
  long total = cast(long)pfa.length + n;
  long accounted = total - total / 4;
  long score = min(accounted, n) * 100;
  long remaining = accounted - min(accounted, n);
  return score + (remaining > 0 ? pfa[cast(int)remaining - 1] : 0L);
}

long solve_min(long[] pfb, long n)
{
  long total = cast(long)pfb.length + n;
  long remaining = min(cast(long)pfb.length, total - total / 4);
  return (remaining > 0 ? pfb[cast(int)remaining - 1] : 0L);
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array.sort!((x, y) => x > y);
    auto b = readln.strip.split.map!(to!long).array.sort!((x, y) => x > y);

    long[] pfa;
    long[] pfb;

    long sum = 0;
    foreach (x ; a) {
      sum += x;
      pfa ~= sum;
    }
    sum = 0;
    foreach (x ; b) {
      sum += x;
      pfb ~= sum;
    }
    writeln(iota(0L, 1000000L).map!(x => solve_max(pfa, x) >= solve_min(pfb, x)).assumeSorted.lowerBound(true).length);
  }
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		a.sort();
		b.sort();

		auto aa = new long[](n+1);
		auto bb = new long[](n+1);
		foreach (i; 0..n)
		{
			aa[i+1] = aa[i] + a[i];
			bb[i+1] = bb[i] + b[i];
		}
		auto tot = a.sum - b.sum;

		auto i = n;
		while (true)
		{
			if (tot + (i-n) * 100 - aa[i/4] + bb[max(i/4-(i-n), 0)] >= 0)
				break;
			++i;
		}
		ans[ti] = i - n;
	}

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

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

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

		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		reverse (a);

		auto b = readln.splitter.map !(to !(int)).array;
		sort (b);
		reverse (b);

		auto sa = [0];
		foreach (ref c; a)
		{
			sa ~= sa.back + c;
		}

		auto sb = [0];
		foreach (ref c; b)
		{
			sb ~= sb.back + c;
		}

		bool ok (int add)
		{
			auto num = n + add;
			auto part = num - num / 4;

			int resA = 0;
			int numA = part;
			int fullA = min (add, numA);
			numA -= fullA;
			resA += fullA * 100;
			resA += sa[numA];

			int resB = 0;
			int numB = part;
			int someB = min (n, numB);
			numB -= someB;
			resB += sb[someB];

			debug {writeln (n, " ", add, ": ", resA, " ", resB);}
			return resA >= resB;
		}

		auto lo = 0;
		auto hi = 2 * 10 ^^ 7;
		while (lo < hi)
		{
			auto me = (lo + hi) >> 1;
			if (ok (me))
			{
				hi = me;
			}
			else
			{
				lo = me + 1;
			}
		}
		writeln (lo);
	}
}

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

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

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

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

enum L = 100;

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        auto A = new int[N];
        auto B = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt();
        }
        foreach (i; 0 .. N) {
          B[i] = readInt();
        }
        A.sort.reverse;
        B.sort.reverse;

        int lo = -1, hi = 3 * N + 1;
        for (; lo + 1 < hi; ) {
          const mid = (lo + hi) / 2;
          const k = N + mid;
          const num = k - k / 4;
          long scoreA, scoreB;
          foreach (i; 0 .. num) {
            scoreA += (i < mid) ? L : A[i - mid];
            scoreB += (i < N) ? B[i] : 0;
          }
          ((scoreA >= scoreB) ? hi : lo) = mid;
        }
        writeln(hi);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
auto sp(R)(R r, size_t i, size_t j)
{
	if (j < i) return 0;
	if (i == 0) return r[j];
	return r[j] - r[i - 1];
}
void solve()
{
	int n = readInt!int;
	auto a = new int[](n);
	auto b = new int[](n);
	foreach(ref ai; a) ai = readInt!int;
	foreach(ref bi; b) bi = readInt!int;
	sort(a); sort(b);
	a.reverse, b.reverse;
	auto pa = a.cumulativeFold!((a, b)=> cast(long)a + b).array;
	auto pb = b.cumulativeFold!((a, b)=> cast(long)a + b).array;
	int used = n - (n/4);
	int hi = 5 * 1_000_00;
	int lo = 0;
	int ans = -1;
	while (lo <= hi)
	{
		int mi = (lo + hi) / 2;
		int nn = mi + n;
		int usedmi = nn - nn / 4;
		int usedorig = max(0, usedmi - mi);
		int usednew = usedmi - usedorig;
		long sa = usednew * 100;
		if (usedorig) sa += pa[usedorig - 1];
		long sb = pb[$ - 1];
		if (sa >= sb)
		{
			ans = mi;
			hi = mi - 1;
		}
		else
		{
			lo = mi + 1;
		}
	}
	ans.writeln;
}

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

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

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

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

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

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

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

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


Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser.Last evening Roma started to play poker. He decided to spend no more than k virtual bourles — he will stop immediately if the number of his loses exceeds the number of his wins by k. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by k.Next morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won k bourles or he lost.The sequence written by Roma is a string s consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met:   In the end the absolute difference between the number of wins and loses is equal to k;  There is no hand such that the absolute difference before this hand was equal to k. Help Roma to restore any such sequence.

The first line contains two numbers n (the length of Roma's sequence) and k (1 ≤ n, k ≤ 1000). The second line contains the sequence s consisting of characters W, L, D and ?. There are exactly n characters in this sequence.

If there is no valid sequence that can be obtained from s by replacing all ? characters by W, L or D, print NO. Otherwise print this sequence. If there are multiple answers, print any of them.

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

int n, k;
char[1001] _s;
char[ ] s;
bool[2001][1000] dp;
char[1000] result;

bool dyn(int pos, int diff) {
    if (pos == n)
        return cast(bool)diff.among(k, -k);
    if (dp[pos][diff + 1000])
        return false;
    if (s[pos].among('D', '?'))
        if (dyn(pos + 1, diff)) {
            result[pos] = 'D';
            return true;
        }
    if (s[pos].among('W', '?') && (pos + 1 == n || diff + 1 < k))
        if (dyn(pos + 1, diff + 1)) {
            result[pos] = 'W';
            return true;
        }
    if (s[pos].among('L', '?') && (pos + 1 == n || diff - 1 > -k))
        if (dyn(pos + 1, diff - 1)) {
            result[pos] = 'L';
            return true;
        }
    dp[pos][diff + 1000] = true;
    return false;
}

void main() {
    while (read(n, k)) {
        s = _s[ ];
        readln(s);
        s = s[0 .. $ - 1];
        memset(dp.ptr, 0x00, dp.sizeof);
        if (dyn(0, 0))
            writeln(result[0 .. n]);
        else
            writeln("NO");
    }
}


Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...There are two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$. Initially, an $$$ans$$$ is equal to $$$0$$$ and the following operation is defined:   Choose position $$$i$$$ ($$$1 \le i \le n$$$);  Add $$$a_i$$$ to $$$ans$$$;  If $$$b_i \neq -1$$$ then add $$$a_i$$$ to $$$a_{b_i}$$$. What is the maximum $$$ans$$$ you can get by performing the operation on each $$$i$$$ ($$$1 \le i \le n$$$) exactly once?Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.

The first line contains the integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of arrays $$$a$$$ and $$$b$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$−10^6 \le a_i \le 10^6$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$ or $$$b_i = -1$$$). Additional constraint: it's guaranteed that for any $$$i$$$ ($$$1 \le i \le n$$$) the sequence $$$b_i, b_{b_i}, b_{b_{b_i}}, \ldots$$$ is not cyclic, in other words it will always end with $$$-1$$$.

In the first line, print the maximum $$$ans$$$ you can get. In the second line, print the order of operations: $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$). The $$$p_i$$$ is the position which should be chosen at the $$$i$$$-th step. If there are multiple orders, print any of them.

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

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

		auto g = new int [] [n];
		foreach (i; 0..n)
		{
			if (b[i] >= 0)
			{
				g[b[i]] ~= i;
			}
		}

		auto used = new bool [n];
		auto h = new int [] [n];

		void recur (int v, int w)
		{
			if (used[v])
			{
				return;
			}
			used[v] = true;
			foreach (u; g[v])
			{
				if (u != w)
				{
					recur (u, v);
					if (a[u] > 0)
					{
						h[v] ~= u;
						a[v] += a[u];
					}
					else
					{
						h[u] ~= v;
					}
				}
			}
		}

		foreach (v; 0..n)
		{
			recur (v, -1);
		}

		writeln (a.sum);

		int cur = 0;
		used[] = false;
		auto p = new int [n];

		void topologicalSort (int v)
		{
			if (used[v])
			{
				return;
			}
			used[v] = true;
			foreach (u; h[v])
			{
				topologicalSort (u);
			}
			p[cur] = v + 1;
			cur += 1;
		}

		foreach (v; 0..n)
		{
			topologicalSort (v);
		}
		writefln !("%(%s %)") (p);
	}
}

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

void main () {
	auto n = readln.strip.to !(int);
	auto a = readln.splitter.map !(to !(long)).array;
	auto b = readln.splitter.map !(to !(int)).array;

	auto g = new int [] [n];
	foreach (i; 0..n) if (b[i] > 0) g[b[i] - 1] ~= i;

	auto used = new bool [n];
	auto h = new int [] [n];

	void recur (int v) {
		if (used[v]) return;
		used[v] = true;
		foreach (u; g[v]) {
			recur (u);
			if (a[u] > 0) {h[v] ~= u; a[v] += a[u];}
			else h[u] ~= v;
		}
	}

	foreach (v; 0..n) recur (v);
	writeln (a.sum);

	int cur = 0;
	used[] = false;
	int [] p;

	void topSort (int v) {
		if (used[v]) return;
		used[v] = true;
		foreach (u; h[v]) topSort (u);
		p ~= v + 1;
	}

	foreach (v; 0..n) topSort (v);
	writefln !("%(%s %)") (p);
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;

DList!string _words;
void read(T)(out T t)
{
  import std.stdio: readln;
  while(_words.empty)
    {
      import std.array: split;
      foreach(word; readln.split)
        {
          _words.insertBack(word);
        }
    }
  import std.conv: to;
  string word = _words.front;
  _words.removeFront;
  t = to!T(word);
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum log =
  q{
    debug
    {
     _loglevel++;
     mixin(`_log!(__FUNCTION__, `, [ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back))].joiner(", ").array, `);`);
     scope(exit) _loglevel--;
    }
};

void main()
{
  long n;
  read(n);

  auto a = Array!long(); a.length = n.ind;
  auto b = Array!long(); b.length = n.ind;
  auto children = Array!(Appender!(long[]))(); children.length = n.ind;

  foreach(i; 0 .. n)
    read(a.at(i));
  foreach(ref childrenArray; children)
    childrenArray = appender!(long[])();
  foreach(i; 0 .. n)
    {
      read(b.at(i));
      if (b.at(i) == -1)
        continue;
      b.at(i)--;
      children.at(b.at(i)).put(i);
    }
  auto roots = iota(0, n).filter!(i => b.at(i) == -1).array;

  auto operations = appender!(long[])();
  auto done = new bool[n.ind];
  auto ans = long(0);

  void doOperation(long node)
  {
    assert(!done.at(node));
    if (b.at(node) != -1)
      a.at(b.at(node)) += a.at(node);
    operations.put(node);
    ans += a.at(node);
    done.at(node) = true;
  }

  void solveTree(long node)
  {
    mixin(log);
    foreach(child; children.at(node))
      {
        solveTree(child);
        if (a.at(child) >= 0)
          doOperation(child);
      }
  }
  foreach(root; roots)
    {
      solveTree(root);
    }

  void solveRemaining(long node)
  {
    if (!done.at(node))
      doOperation(node);
    foreach(child; children.at(node))
        solveRemaining(child);
  }

  foreach(root; roots)
    solveRemaining(root);

  writeln(ans);
  foreach(operation; operations)
    write(operation + 1, " ");
  writeln;
}


Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of $$$n$$$ different bloggers. Blogger numbered $$$i$$$ has $$$a_i$$$ followers.Since Masha has a limited budget, she can only sign a contract with $$$k$$$ different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers.Help her, find the number of ways to select $$$k$$$ bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers).For example, if $$$n=4$$$, $$$k=3$$$, $$$a=[1, 3, 1, 2]$$$, then Masha has two ways to select $$$3$$$ bloggers with the maximum total number of followers:   conclude contracts with bloggers with numbers $$$1$$$, $$$2$$$ and $$$4$$$. In this case, the number of followers will be equal to $$$a_1 + a_2 + a_4 = 6$$$.  conclude contracts with bloggers with numbers $$$2$$$, $$$3$$$ and $$$4$$$. In this case, the number of followers will be equal to $$$a_2 + a_3 + a_4 = 6$$$. Since the answer can be quite large, output it modulo $$$10^9+7$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 1000$$$) — the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$ ($$$1 \le a_i \le n$$$) — the number of followers of each blogger. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case, on a separate line output one integer — the number of ways to select $$$k$$$ bloggers so that the total number of their followers is maximum possible.

NoteThe test case is explained in the statements.In the second test case, the following ways are valid:   conclude contracts with bloggers with numbers $$$1$$$ and $$$2$$$. In this case, the number of followers will be equal to $$$a_1 + a_2 = 2$$$;  conclude contracts with bloggers with numbers $$$1$$$ and $$$3$$$. In this case, the number of followers will be equal to $$$a_1 + a_3 = 2$$$;  conclude contracts with bloggers with numbers $$$1$$$ and $$$4$$$. In this case, the number of followers will be equal to $$$a_1 + a_4 = 2$$$;  conclude contracts with bloggers with numbers $$$2$$$ and $$$3$$$. In this case, the number of followers will be equal to $$$a_2 + a_3 = 2$$$;  conclude contracts with bloggers with numbers $$$2$$$ and $$$4$$$. In this case, the number of followers will be equal to $$$a_2 + a_4 = 2$$$;  conclude contracts with bloggers with numbers $$$3$$$ and $$$4$$$. In this case, the number of followers will be equal to $$$a_3 + a_4 = 2$$$. In the third test case, the following ways are valid:   concludes a contract with a blogger with the number $$$2$$$. In this case, the number of followers will be equal to $$$a_2 = 2$$$.

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

string FMT_F = "%.10f";

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

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

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

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

struct Cmb
{
	void init(size_t n)
	{
		long powmod(long a, long p)
		{
			long ans = 1;
			long mul = a;
			while (p > 0)
			{
				if ((p & 1) == 1)
					ans.modm(mul);
				p >>= 1;
				mul.modm(mul);
			}
			return ans;
		}

		++n;
		fact = new long[2][](n);
		fact[0][0] = 1;
		foreach (i; 1..n)
		{
			fact[i][0] = fact[i-1][0];
			fact[i][0].modm(i);
		}
		fact[n-1][1] = powmod(fact[n-1][0], mod - 2);
		foreach_reverse (i; 0..n-1)
		{
			fact[i][1] = fact[i+1][1];
			fact[i][1].modm(i+1);
		}
	}

	long get(size_t n, size_t r)
	{
		long res = fact[n][0];
		res.modm(fact[r][1]);
		res.modm(fact[n-r][1]);
		return res;
	}

	long[2][] fact;
}

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

		auto cnt = new int[](n+1);
		foreach (i; 0..n)
		{
			++cnt[a[i]];
		}

		foreach_reverse (i; 0..n+1)
		{
			if (cnt[i] < k)
				k -= cnt[i];
			else
			{
				ans[ti] = cmb.get(cnt[i], k);
				break;
			}
		}
	}

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

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

immutable int mod = 10 ^^ 9 + 7;

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

alias inv = a => powMod (a, mod - 2);

int fact (int n)
{
	int res = 1;
	for (int i = 1; i <= n; i++)
	{
		res = (res * 1L * i) % mod;
	}
	return res;
}

int c (int n, int k)
{
	return fact (n) * 1L * inv (fact (n - k)) % mod * 1L *
	    inv (fact (k)) % mod;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort !(q{a > b}) (a);

		int lo = k - 1;
		int hi = k;
		if (a[lo] != a[hi])
		{
			writeln (1);
			continue;
		}

		while (lo > 0 && a[lo - 1] == a[lo])
		{
			lo -= 1;
		}
		while (hi + 1 < n && a[hi + 1] == a[hi])
		{
			hi += 1;
		}

		writeln (c (hi + 1 - lo, k - lo));
	}
}

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

enum P = 10L^^9 + 7;

void main()
{
    int T; get(T);
    while (T--) {
        int N, K; get(N, K);
        int[] aa; get(aa);
        auto MAX = new int[](K + 1);
        auto DP = new long[](K + 1);
        DP[0] = 1;
        foreach (a; aa) {
            foreach_reverse (i; 0..K) {
                if (MAX[i] + a > MAX[i+1]) {
                    MAX[i+1] = MAX[i] + a;
                    DP[i+1] = DP[i];
                } else if (MAX[i] + a == MAX[i+1]) {
                    (DP[i+1] += DP[i]) %= P;
                }
            }
        }
        writeln(DP[K]);
    }
}

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

immutable int mod = 10 ^^ 9 + 7;

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

alias inv = a => powMod (a, mod - 2);

int fact (int n)
{
	int res = 1;
	for (int i = 1; i <= n; i++)
	{
		res = (res * 1L * i) % mod;
	}
	return res;
}

int c (int n, int k)
{
	return fact (n) * 1L * inv (fact (n - k)) % mod * 1L *
	    inv (fact (k)) % mod;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort !(q{a > b}) (a);

		int lo = k - 1;
		int hi = k;
		if (a[lo] != a[hi])
		{
			writeln (1);
			continue;
		}

		while (lo > 0 && a[lo - 1] == a[lo])
		{
			lo -= 1;
		}
		while (hi + 1 < n && a[hi + 1] == a[hi])
		{
			hi += 1;
		}

		writeln (c (hi - lo, k - lo));
	}
}


Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa:  selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$).  selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$).  sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her!

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal.

5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda

Note  In the $$$1$$$-st test case Koa:   selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$).  selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$).   In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$.  In the $$$3$$$-rd test case Koa:   selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$).  selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$).  selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$).

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

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

    test: while (t--) {
        int n;
        readf("%s", &n);
        readln;

        auto a = readln.chomp;
        auto b = readln.chomp;

        auto vals = new RedBlackTree!int[] (25);
        foreach (i; (25).iota) { vals[i] = redBlackTree!int(); }

        foreach (ca, cb; lockstep(a, b)) {
            if (ca > cb) {
                writeln(-1);
                continue test;
            }

            if (ca == cb) { continue; }

            vals[ca - 'a'].insert(cb - 'a');
        }

        auto trans = new bool[][] (25, 25);
        foreach (i; (25).iota) { trans[i][] = false; }

        int ans = 0;

        foreach (let; (25).iota) {
            if (vals[let].empty()) { continue; }

            ans += 1;
            int nxt = vals[let].front;
            vals[let].removeFront();

            foreach (el; vals[let]) { vals[nxt].insert(el); }
        }

        ans.writeln;
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
multitest_loop:
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip;
		auto t = readln.strip;
		if (n.iota.any !(i => s[i] > t[i]))
		{
			writeln (-1);
			continue multitest_loop;
		}
		auto r = s.dup;
		int res = 0;
		auto b = new bool [n];
		foreach (c; 'a'..'u')
		{
			foreach (i; 0..n)
			{
				b[i] = (r[i] == c && r[i] < t[i]);
			}
			if (any (b))
			{
				auto d = n.iota.filter !(i => b[i])
				    .map !(i => t[i]).minElement;
				foreach (i; 0..n)
				{
					if (r[i] == c)
					{
						r[i] = d;
					}
				}
				res += 1;
			}
		}
		writeln (res);
	}
}

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

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

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

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

enum V = 20;

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

        bool ok = true;
        foreach (i; 0 .. N) {
          ok = ok && (A[i] <= B[i]);
        }
        if (ok) {
          auto needs = new int[V];
          foreach (i; 0 .. N) {
            needs[A[i] - 'a'] |= 1 << (B[i] - 'a');
          }
          int ans;
          foreach (u; 0 .. V) {
            needs[u] &= ~(1 << u);
            if (needs[u]) {
              const v = bsf(needs[u]);
              needs[v] |= needs[u];
              ++ans;
            }
          }
          writeln(ans);
        } else {
          writeln(-1);
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

struct UnionFind(T)
{
	void init(T n) { par = new T[](n); foreach (i; 0..n) par[i] = i; cnt = new T[](n); fill(cnt, 1); }
	T root(T i) { return par[i] == i ? i : (par[i] = root(par[i])); }
	bool same(T i, T j) { return root(i) == root(j); }
	void unite(T i, T j) { i = root(i); j = root(j); if (i == j) return; par[i] = j; cnt[j] += cnt[i]; }
	T size(T i) { return cnt[root(i)]; }
	T[] par, cnt;
}

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

		UnionFind!int uf;
		uf.init(20);
		bool ok = true;
		foreach (i; 0..n)
		{
			auto a = A[i] - 'a';
			auto b = B[i] - 'a';
			if (a > b)
			{
				ok = false;
				break;
			}
			else if (a == b) continue;
			uf.unite(a, b);
		}
		if (!ok)
		{
			ans[ti] = -1;
			continue;
		}
		debug writeln(uf.par);
		debug writeln(uf.cnt);

		auto root = new bool[](20);
		foreach (i; 0..20)
		{
			auto r = uf.root(i);
			root[r] = true;
		}
		foreach (i; 0..20)
		{
			if (root[i])
			{
				ans[ti] += uf.size(i) - 1;
			}
		}
	}

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

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

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

    test: while (t--) {
        int n;
        readf("%s", &n);
        readln;

        auto a = readln.chomp;
        auto b = readln.chomp;

        auto vals = new RedBlackTree!int[] (25);
        foreach (i; (25).iota) { vals[i] = redBlackTree!int(); }

        foreach (ca, cb; lockstep(a, b)) {
            if (ca > cb) {
                writeln(-1);
                continue test;
            }

            if (ca == cb) { continue; }

            vals[ca - 'a'].insert(cb - 'a');
        }

        auto trans = new bool[][] (25, 25);
        foreach (i; (25).iota) { trans[i][] = false; }

        foreach (let; (25).iota) {
            if (vals[let].empty()) { continue; }

            auto arr = [let].chain(vals[let][]);

            foreach (prev, nxt; lockstep(arr, arr.dropOne())) { trans[prev][nxt] = true; }
        }

        int ans = 0;

        foreach (i; (25).iota) { ans += trans[i].count!(x => x); }

        ans.writeln;
    }
}

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

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

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

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

enum V = 20;

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

        bool ok = true;
        foreach (i; 0 .. N) {
          ok = ok && (A[i] <= B[i]);
        }
        if (ok) {
          auto needs = new int[V];
          foreach (i; 0 .. N) {
            needs[A[i] - 'a'] |= 1 << (B[i] - 'a');
          }
          int ans;
          foreach (u; 0 .. V) {
            needs[u] &= ~(1 << u);
            if (needs[u]) {
              const v = bsf(u);
              needs[v] |= needs[u];
              ++ans;
            }
          }
          writeln(ans);
        } else {
          writeln(-1);
        }
      }
    }
  } catch (EOFException e) {
  }
}


It is the easy version of the problem. The only difference is that in this version $$$n = 1$$$.In the cinema seats can be represented as the table with $$$n$$$ rows and $$$m$$$ columns. The rows are numbered with integers from $$$1$$$ to $$$n$$$. The seats in each row are numbered with consecutive integers from left to right: in the $$$k$$$-th row from $$$m (k - 1) + 1$$$ to $$$m k$$$ for all rows $$$1 \le k \le n$$$. $$$1$$$$$$2$$$$$$\cdots$$$$$$m - 1$$$$$$m$$$$$$m + 1$$$$$$m + 2$$$$$$\cdots$$$$$$2 m - 1$$$$$$2 m$$$$$$2m + 1$$$$$$2m + 2$$$$$$\cdots$$$$$$3 m - 1$$$$$$3 m$$$$$$\vdots$$$$$$\vdots$$$$$$\ddots$$$$$$\vdots$$$$$$\vdots$$$$$$m (n - 1) + 1$$$$$$m (n - 1) + 2$$$$$$\cdots$$$$$$n m - 1$$$$$$n m$$$ The table with seats indices There are $$$nm$$$ people who want to go to the cinema to watch a new film. They are numbered with integers from $$$1$$$ to $$$nm$$$. You should give exactly one seat to each person.It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. $$$i$$$-th person has the level of sight $$$a_i$$$. Let's define $$$s_i$$$ as the seat index, that will be given to $$$i$$$-th person. You want to give better places for people with lower sight levels, so for any two people $$$i$$$, $$$j$$$ such that $$$a_i < a_j$$$ it should be satisfied that $$$s_i < s_j$$$.After you will give seats to all people they will start coming to their seats. In the order from $$$1$$$ to $$$nm$$$, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.Let's consider an example: $$$m = 5$$$, the person has the seat $$$4$$$ in the first row, the seats $$$1$$$, $$$3$$$, $$$5$$$ in the first row are already occupied, the seats $$$2$$$ and $$$4$$$ are free. The inconvenience of this person will be $$$2$$$, because he will go through occupied seats $$$1$$$ and $$$3$$$.Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$n = 1$$$, $$$1 \le m \le 300$$$) — the number of rows and places in each row respectively. The second line of each test case contains $$$n \cdot m$$$ integers $$$a_1, a_2, \ldots, a_{n \cdot m}$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the sight level of $$$i$$$-th person. It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the minimal total inconvenience that can be achieved.

NoteIn the first test case, there is a single way to arrange people, because all sight levels are distinct. The first person will sit on the first seat, the second person will sit on the second place, the third person will sit on the third place. So inconvenience of the first person will be $$$0$$$, inconvenience of the second person will be $$$1$$$ and inconvenience of the third person will be $$$2$$$. The total inconvenience is $$$0 + 1 + 2 = 3$$$.In the second test case, people should sit as follows: $$$s_1 = 2$$$, $$$s_2 = 1$$$, $$$s_3 = 5$$$, $$$s_4 = 4$$$, $$$s_5 = 3$$$. The total inconvenience will be $$$6$$$.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

long compress(in long[] arr, out long[long] zip, out long[] unzip)
{
	auto index = MAKE_IDX(arr);
	long last = arr[index[0]], x;
	zip[last] = x;
	unzip ~= last;
	foreach (i; index[1..$])
	{
		if (arr[i] == last) continue;
		last = arr[i];
		++x;
		zip[last] = x;
		unzip ~= last;
	}
	return x+1;
}

struct SegTree(T)
{
	T delegate(const(T), const(T)) f;
	T[] data;
	T init;
    this(T[] _data, T delegate(const(T), const(T)) _f, T _init)
    {
		f = _f; init = _init;
		size_t n = 1; while (n < _data.length) n *= 2; data.length = n*2-1;
		foreach (i; 0.._data.length) data[i+n-1] = _data[i];
		foreach (i; _data.length..n) data[i+n-1] = _init;
		foreach_reverse (i; 0..n-1) data[i] = f(data[i*2+1], data[i*2+2]);
	}
    T query(size_t l, size_t r)
	{
        size_t n = (data.length+1) / 2; l += n-1; r += n-1; T res = init;
        while (l < r)
		{
            if ((l & 1) == 0) res = f(res, data[l]);
            if ((r & 1) == 0) res = f(res, data[r-1]);
            l = l/2; r = (r-1)/2;
        }
        return res;
    }
	void update(size_t i, T v)
	{
		i += (data.length+1) / 2 - 1; data[i] = v;
		while (i != 0) { i = (i-1)/2; data[i] = f(data[i*2+1], data[i*2+2]); }
    }
}

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

		long[long] zip;
		long[] unzip;
		auto len = compress(a, zip, unzip);

		long[] b;
		foreach (i; 0..m)
		{
			b ~= zip[a[i]];
		}

		auto dummy = new long[](cast(int)len);
		auto st = new SegTree!long(dummy, (in long x, in long y)=>x+y, 0);
		foreach (i; 0..m)
		{
			ans[ti] += st.query(0, cast(int)b[i]);
			auto cnt = st.query(cast(int)b[i], cast(int)b[i]+1);
			st.update(cast(int)b[i], cnt+1);
		}
	}

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

immutable multi = true;

void solve(int)
{
	int n = readInt!int;
	assert(n == 1);
	int m = readInt!int;
	assert(m >= 0 && m <= 300);
	auto a = ma(m, readInt!long);
	int[long] cnt;
	foreach(i, ai; a) cnt[ai]++;
	auto sa = a.dup;
	sort(sa);
	auto ua = sa.uniq.array;
	int[][long] poss;
	{
	int i = 0;
	foreach(j, ai; ua)
	{
		poss[ai] = null;
		foreach(k; 0 .. cnt[ai])
		{
			poss[ai] ~= i++;
		}
	}
	}
	auto used = new long[](m);
	long ans = 0;
	foreach(i, ai; a)
	{
		auto pos = poss[ai][$-1];
		poss[ai] = poss[ai][0 .. $ - 1];
		foreach(j; 0 .. pos)
		{
			ans += used[j];
		}
		used[pos] = 1;
	}
	ans.writeln;
}

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

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

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

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

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

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

int lb = -1;

struct S { int v; int[] a; };

S op(ref S x, ref S y)
{
  if (lb < 0) {
    return S(0, (x.a ~ y.a).sort.array);
  } else {
    auto cnt1 = x.a.assumeSorted.lowerBound(lb).length;
    auto cnt2 = y.a.assumeSorted.lowerBound(lb).length;
    return S(x.v + y.v + cast(int)(cnt1 + cnt2), []);
  }
}

S e()
{
  S tmp;
  return tmp;
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n, m;
    readf!" %d %d "(n, m);
    auto a = readln.strip.split.map!(to!int).array;
    auto b = zip(iota(n * m), a).array.sort!((x, y) => x[1] == y[1] ? x[0] > y[0] : x[1] < y[1]).array;
    S[] c;
    foreach (x ; b)
      c ~= S(0, [x[0]]);

    lb = -1;
    auto seg = c.Segtree!(S, op, e);
    long ans = 0;
    foreach (i ; 0 .. n * m) {
      lb = b[i][0];
      int cnt = seg.prod(0, i).v;
      ans += cnt;
    }

    writeln(ans);
  }
}

// Code from: https://github.com/kotet/atcoder-library-d

int celiPow2(int n) @safe pure nothrow @nogc
{
    int x = 0;
    while ((1u << x) < cast(uint)(n))
        x++;
    return x;
}

// --- segtree ---

struct Segtree(S, alias op, alias e)
{
    import std.functional : binaryFun, unaryFun;
    import std.traits : isCallable, Parameters;

    static if (is(typeof(e) : string))
    {
        auto unit()
        {
            return mixin(e);
        }
    }
    else
    {
        alias unit = e;
    }

    this(int n)
    {
        auto buf = new S[](n);
        buf[] = unit();
        this(buf);
    }

    this(S[] v)
    {
        _n = cast(int) v.length;
        log = celiPow2(_n);
        size = 1 << log;
        d = new S[](2 * size);
        d[] = unit();
        foreach (i; 0 .. _n)
            d[size + i] = v[i];
        foreach_reverse (i; 1 .. size)
            update(i);
    }

    void set(int p, S x)
    {
        assert(0 <= p && p < _n);
        p += size;
        d[p] = x;
        foreach (i; 1 .. log + 1)
            update(p >> i);
    }

    S get(int p)
    {
        assert(0 <= p && p < _n);
        return d[p + size];
    }

    S prod(int l, int r)
    {
        assert(0 <= l && l <= r && r <= _n);
        S sml = unit(), smr = unit();
        l += size;
        r += size;
        while (l < r)
        {
            if (l & 1)
                sml = binaryFun!(op)(sml, d[l++]);
            if (r & 1)
                smr = binaryFun!(op)(d[--r], smr);
            l >>= 1;
            r >>= 1;
        }
        return binaryFun!(op)(sml, smr);
    }

    S allProd()
    {
        return d[1];
    }

    int maxRight(alias f)(int l)
    {
        return maxRight(l, &unaryFun!(f));
    }

    int maxRight(F)(int l, F f) if (isCallable!F && Parameters!(F).length == 1)
    {
        assert(0 <= l && l <= _n);
        assert(f(unit()));
        if (l == _n)
            return _n;
        l += size;
        S sm = unit();
        do
        {
            while (l % 2 == 0)
                l >>= 1;
            if (!f(binaryFun!(op)(sm, d[l])))
            {
                while (l < size)
                {
                    l = 2 * l;
                    if (f(binaryFun!(op)(sm, d[l])))
                    {
                        sm = binaryFun!(op)(sm, d[l]);
                        l++;
                    }
                }
                return l - size;
            }
            sm = binaryFun!(op)(sm, d[l]);
            l++;
        }
        while ((l & -l) != l);
        return _n;
    }

    int minLeft(alias f)(int r)
    {
        return minLeft(r, &unaryFun!(f));
    }

    int minLeft(F)(int r, F f) if (isCallable!F && Parameters!(F).length == 1)
    {
        assert(0 <= r && r <= _n);
        assert(f(unit()));
        if (r == 0)
            return 0;
        r += size;
        S sm = unit();
        do
        {
            r--;
            while (r > 1 && (r % 2))
                r >>= 1;
            if (!f(binaryFun!(op)(d[r], sm)))
            {
                while (r < size)
                {
                    r = 2 * r + 1;
                    if (f(binaryFun!(op)(d[r], sm)))
                    {
                        sm = binaryFun!(op)(d[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = binaryFun!(op)(d[r], sm);
        }
        while ((r & -r) != r);
        return 0;
    }

private:
    int _n = 0, size = 1, log = 0;
    S[] d = [unit(), unit()];
    void update(int k)
    {
        d[k] = binaryFun!(op)(d[2 * k], d[2 * k + 1]);
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = iota (n * m).map !(i => tuple (a[i], i)).array;
		b.schwartzSort !(c => tuple (c[0], -c[1]));
		debug {writeln (b);}

		long res = 0;
		auto vis = new bool [] [] (n, m);
		foreach (ref c; b)
		{
			auto row = c[1] / m;
			auto col = c[1] % m;
			foreach (d; 0..col)
			{
				res += vis[row][d];
			}
			vis[row][col] = true;
		}
		writeln (res);
	}
}