Arkady likes to walk around his kitchen. His labyrinthine kitchen consists of several important places connected with passages. Unfortunately it happens that these passages are flooded with milk so that it's impossible to pass through them. Namely, it's possible to pass through each passage in any direction only during some time interval.The lengths of all passages are equal and Arkady makes through them in one second. For security reasons, Arkady can never stop, also, he can't change direction while going through a passage. In other words, if he starts walking in some passage, he should reach its end and immediately leave the end.Today Arkady needs to quickly reach important place n from place 1. He plans to exit the place 1 at time moment 0 and reach the place n as early as he can. Please find the minimum time he should spend on his way.

The first line contains two integers n and m (1 ≤ n ≤ 5·105, 0 ≤ m ≤ 5·105) — the number of important places and the number of passages, respectively. After that, m lines follow, each of them describe one passage. Each line contains four integers a, b, l and r (1 ≤ a, b ≤ n, a ≠ b, 0 ≤ l < r ≤ 109) — the places the passage connects and the time segment during which it's possible to use this passage.

Print one integer — minimum time Arkady should spend to reach the destination. If he can't reach the place n, print -1.

NoteIn the first example Arkady should go through important places 1 → 3 → 4 → 5.In the second example Arkady can't start his walk because at time moment 0 it's impossible to use the only passage.

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

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

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

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

enum INF = 10^^9 + 58;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt() * 2;
      auto A = new int[M];
      auto B = new int[M];
      auto L = new int[M];
      auto R = new int[M];
      for (int i = 0; i < M; i += 2) {
        A[i] = B[i ^ 1] = readInt() - 1;
        B[i] = A[i ^ 1] = readInt() - 1;
        L[i] = L[i ^ 1] = readInt();
        R[i] = R[i ^ 1] = readInt();
      }

      auto G = new int[][N];
      foreach (i; 0 .. M) {
        G[A[i]] ~= i;
      }

      auto deg = new int[N];
      foreach (u; 0 .. N) {
        deg[u] = cast(int)(G[u].length);
        G[u].sort!((i0, i1) => (L[i0] < L[i1]));
      }
      auto itr = new int[][](N, 2);
      auto lasts = new int[][](N, 2);
      foreach (u; 0 .. N) {
        lasts[u][] = -INF;
      }

      alias Node = Tuple!(int, "c", int, "i");
      BinaryHeap!(Array!Node, "a.c > b.c") que;
      auto dist = new int[][](M, 2);
      foreach (i; 0 .. M) {
        dist[i][] = INF;
      }

      void update(int u, int s, int lb, int ub) {
        debug {
          writefln("%s %s [%s, %s]", u, s, lb, ub);
        }
        chmax(lb, lasts[u][s] + 2);
        if (s != (ub & 1)) {
          --ub;
        }
        if (lb <= ub) {
          for (int i; itr[u][s] < deg[u] && L[i = G[u][itr[u][s]]] <= ub; ++itr[u][s]) {
            int cc = max(lb, L[i]);
            if (s != (cc & 1)) {
              ++cc;
            }
            if (cc <= ub && cc <= R[i]) {
              if (chmin(dist[i][cc & 1], cc)) {
                que.insert(Node(cc, i));
              }
            }
          }
          lasts[u][s] = ub;
        }
      }

      update(0, 0, 0, 0);
      for (; !que.empty; ) {
        const c = que.front.c;
        const i = que.front.i;
        que.removeFront;
        if (dist[i][c & 1] == c) {
          update(B[i], (c + 1) & 1, c + 1, R[i]);
        }
      }
      debug {
        writeln("dist = ", dist);
      }

      int ans = INF;
      if (0 == N - 1) {
        chmin(ans, 0);
      }
      foreach (i; G[N - 1]) {
        foreach (s; 0 .. 2) {
          const cc = dist[i ^ 1][s] + 1;
          if (cc <= R[i ^ 1]) {
            chmin(ans, cc);
          }
        }
      }
      writeln((ans >= INF) ? -1 : ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum INF = 10^^9 + 58;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt() * 2;
      auto A = new int[M];
      auto B = new int[M];
      auto L = new int[M];
      auto R = new int[M];
      for (int i = 0; i < M; i += 2) {
        A[i] = B[i ^ 1] = readInt() - 1;
        B[i] = A[i ^ 1] = readInt() - 1;
        L[i] = L[i ^ 1] = readInt();
        R[i] = R[i ^ 1] = readInt();
      }

      auto G = new int[][N];
      foreach (i; 0 .. M) {
        G[A[i]] ~= i;
      }

      auto deg = new int[N];
      foreach (u; 0 .. N) {
        deg[u] = cast(int)(G[u].length);
        G[u].sort!((i0, i1) => (L[i0] < L[i1]));
      }
      auto itr = new int[][](N, 2);
      auto lasts = new int[][](N, 2);
      foreach (u; 0 .. N) {
        lasts[u][] = -INF;
      }

      alias Node = Tuple!(int, "c", int, "i");
      BinaryHeap!(Array!Node, "a.c > b.c") que;
      auto dist = new int[][](M, 2);
      foreach (i; 0 .. M) {
        dist[i][] = INF;
      }

      void update(int u, int s, int lb, int ub) {
        debug {
          writefln("%s %s [%s, %s]", u, s, lb, ub);
        }
        chmax(lb, lasts[u][s] + 2);
        if (lb <= ub) {
          for (int i; itr[u][s] < deg[u] && L[i = G[u][itr[u][s]]] <= ub; ++itr[u][s]) {
            int cc = max(lb, L[i]);
            if (s != (cc & 1)) {
              ++cc;
            }
            if (cc <= ub && cc <= R[i]) {
              if (chmin(dist[i][cc & 1], cc)) {
                que.insert(Node(cc, i));
              }
            }
          }
          lasts[u][s] = ub;
        }
      }

      update(0, 0, 0, 0);
      for (; !que.empty; ) {
        const c = que.front.c;
        const i = que.front.i;
        que.removeFront;
        if (dist[i][c & 1] == c) {
          update(B[i], (c + 1) & 1, c + 1, R[i]);
        }
      }
      debug {
        writeln("dist = ", dist);
      }

      int ans = INF;
      if (0 == N - 1) {
        chmin(ans, 0);
      }
      foreach (i; G[N - 1]) {
        foreach (s; 0 .. 2) {
          const cc = dist[i ^ 1][s] + 1;
          if (cc <= R[i ^ 1]) {
            chmin(ans, cc);
          }
        }
      }
      writeln((ans >= INF) ? -1 : ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum INF = 10^^9 + 58;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt() * 2;
      auto A = new int[M];
      auto B = new int[M];
      auto L = new int[M];
      auto R = new int[M];
      for (int i = 0; i < M; i += 2) {
        A[i] = B[i ^ 1] = readInt() - 1;
        B[i] = A[i ^ 1] = readInt() - 1;
        L[i] = L[i ^ 1] = readInt();
        R[i] = R[i ^ 1] = readInt();
      }

      auto G = new int[][N];
      foreach (i; 0 .. M) {
        G[A[i]] ~= i;
      }

      alias Node = Tuple!(int, "c", int, "i");
      BinaryHeap!(Array!Node, "a.c > b.c") que;
      auto dist = new int[][](M, 2);
      foreach (i; 0 .. M) {
        dist[i][] = INF;
      }
      foreach (i; G[0]) {
        if (L[i] <= 0 && 0 <= R[i]) {
          dist[i][0] = 0;
          que.insert(Node(0, i));
        }
      }
      for (; !que.empty; ) {
        const c = que.front.c;
        const i = que.front.i;
        que.removeFront;
        if (dist[i][c & 1] == c) {
          foreach (j; G[B[i]]) {
            int cc = max(c + 1, L[j]);
            if ((c & 1) == (cc & 1)) {
              ++cc;
            }
            if (cc <= R[i] && cc <= R[j]) {
              if (chmin(dist[j][cc & 1], cc)) {
                que.insert(Node(cc, j));
              }
            }
          }
        }
      }
      debug {
        writeln("dist = ", dist);
      }

      int ans = INF;
      foreach (i; G[N - 1]) {
        foreach (s; 0 .. 2) {
          const cc = dist[i ^ 1][s] + 1;
          if (cc <= R[i ^ 1]) {
            chmin(ans, cc);
          }
        }
      }
      writeln((ans >= INF) ? -1 : ans);
    }
  } catch (EOFException e) {
  }
}


Petya and Vasya got employed as couriers. During the working day they are to deliver packages to n different points on the line. According to the company's internal rules, the delivery of packages must be carried out strictly in a certain order. Initially, Petya is at the point with the coordinate s1, Vasya is at the point with the coordinate s2, and the clients are at the points x1, x2, ..., xn in the order of the required visit.The guys agree in advance who of them will deliver the package to which of the customers, and then they act as follows. When the package for the i-th client is delivered, the one who delivers the package to the (i + 1)-st client is sent to the path (it can be the same person who went to the point xi, or the other). The friend who is not busy in delivering the current package, is standing still.To communicate with each other, the guys have got walkie-talkies. The walkie-talkies work rather poorly at great distances, so Petya and Vasya want to distribute the orders so that the maximum distance between them during the day is as low as possible. Help Petya and Vasya to minimize the maximum distance between them, observing all delivery rules.

The first line contains three integers n, s1, s2 (1 ≤ n ≤ 100 000, 0 ≤ s1, s2 ≤ 109) — number of points of delivery and starting positions of Petya and Vasya. The second line contains n integers x1, x2, ..., xn — customers coordinates (0 ≤ xi ≤ 109), in the order to make a delivery.  It is guaranteed, that among the numbers s1, s2, x1, ..., xn there are no two equal.

Output the only integer, minimum possible maximal distance between couriers during delivery.

NoteIn the first test case the initial distance between the couriers is 10. This value will be the answer, for example, Petya can perform both deliveries, and Vasya will remain at the starting point.In the second test case you can optimally act, for example, like this: Vasya delivers the package to the first customer, Petya to the second and, finally, Vasya delivers the package to the third client. With this order of delivery, the distance between the couriers will never exceed 1.In the third test case only two variants are possible: if the delivery of a single package is carried out by Petya, the maximum distance between them will be 5 - 2 = 3. If Vasya will deliver the package, the maximum distance is 4 - 2 = 2. The latter method is optimal.

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt() + 2;
      auto X = new long[N];
      foreach (i; 0 .. N) {
        X[i] = readLong();
      }

      long lo = abs(X[0] - X[1]) - 1;
      long hi = X.maxElement - X.minElement;
      for (; lo + 1 < hi; ) {
        const mid = (lo + hi) / 2;
        auto set = new RedBlackTree!long;
        // (0, 1)
        set.insert(X[0]);
        foreach (i; 2 .. N) {
          if (set.empty) {
            break;
          }
          // (i - 1, i)
          set.insert(X[i - 1]);
          // forbid outside [X[i] - mid, X[i] + mid]
          for (; !set.empty && set.front < X[i] - mid; set.removeFront) {}
          for (; !set.empty && set.back > X[i] + mid; set.removeBack) {}
        }
        const ok = !set.empty;
        debug {
          writeln(mid, ": ", ok);
        }
        (ok ? hi : lo) = mid;
      }
      writeln(hi);
    }
  } catch (EOFException e) {
  }
}


You are given a binary string of length $$$n$$$ (i. e. a string consisting of $$$n$$$ characters '0' and '1').In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than $$$k$$$ moves? It is possible that you do not perform any moves at all.Note that you can swap the same pair of adjacent characters with indices $$$i$$$ and $$$i+1$$$ arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6, 1 \le k \le n^2$$$) — the length of the string and the number of moves you can perform. The second line of the test case contains one string consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).

For each test case, print the answer on it: the lexicographically minimum possible string of length $$$n$$$ you can obtain from the given one if you can perform no more than $$$k$$$ moves.

NoteIn the first example, you can change the string as follows: $$$1\underline{10}11010 \rightarrow \underline{10}111010 \rightarrow 0111\underline{10}10 \rightarrow 011\underline{10}110 \rightarrow 01\underline{10}1110 \rightarrow 01011110$$$. In the third example, there are enough operations to make the string sorted.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new char[][](q);
	foreach (i; 0..q)
	{
		auto n = RD!int;
		auto k = RD;
		auto s = RD!string;
		int streak;
		foreach (j; 0..n)
		{
			if (s[j] == '1')
			{
				++streak;
				ans[i] ~= s[j];
			}
			else
			{
				auto cnt = cast(int)min(k, streak);
				if (cnt == 0)
				{
					ans[i] ~= '0';
				}
				else
				{
					k -= cnt;
					ans[i][j-cnt] = '0';
					ans[i] ~= '1';
				}
			}
		}
	}

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


You are given an integer array $$$a_1, a_2, \dots, a_n$$$ and integer $$$k$$$.In one step you can   either choose some index $$$i$$$ and decrease $$$a_i$$$ by one (make $$$a_i = a_i - 1$$$);  or choose two indices $$$i$$$ and $$$j$$$ and set $$$a_i$$$ equal to $$$a_j$$$ (make $$$a_i = a_j$$$). What is the minimum number of steps you need to make the sum of array $$$\sum\limits_{i=1}^{n}{a_i} \le k$$$? (You are allowed to make values of array negative).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^{15}$$$) — the size of array $$$a$$$ and upper bound on its sum. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array itself. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the minimum number of steps to make $$$\sum\limits_{i=1}^{n}{a_i} \le k$$$.

NoteIn the first test case, you should decrease $$$a_1$$$ $$$10$$$ times to get the sum lower or equal to $$$k = 10$$$.In the second test case, the sum of array $$$a$$$ is already less or equal to $$$69$$$, so you don't need to change it.In the third test case, you can, for example:   set $$$a_4 = a_3 = 1$$$;  decrease $$$a_4$$$ by one, and get $$$a_4 = 0$$$.  As a result, you'll get array $$$[1, 2, 1, 0, 1, 2, 1]$$$ with sum less or equal to $$$8$$$ in $$$1 + 1 = 2$$$ steps.In the fourth test case, you can, for example:   choose $$$a_7$$$ and decrease in by one $$$3$$$ times; you'll get $$$a_7 = -2$$$;  choose $$$4$$$ elements $$$a_6$$$, $$$a_8$$$, $$$a_9$$$ and $$$a_{10}$$$ and them equal to $$$a_7 = -2$$$.  As a result, you'll get array $$$[1, 2, 3, 1, 2, -2, -2, -2, -2, -2]$$$ with sum less or equal to $$$1$$$ in $$$3 + 4 = 7$$$ steps.

void main() { runSolver(); }

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

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

      ulong[] acc = [0];
      foreach(a; A.sort!"a > b") acc ~= acc[$ - 1] + a;

      const spread = A.sum - K;
      long ans = long.max;
      long minn = A.minElement;
      foreach(i; 0..N) {
        bool isOK(long n) {
          // if (i == N - 1) [i, n, cast(ulong)n + (acc[i] - (minn - n)*i), spread].deb;
          return n + (acc[i] - (minn - n)*i) >= spread;
        }
        const x = max(0, binarySearch(&isOK, spread, -1));
        ans = min(ans, x + i);
      }

      return ans;
    }

    foreach(_; 0..QN) subSolve().writeln;
    // (10L^^9).repeat(2*10^^5).array.toAnswerString.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"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

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

class RangeSum(T) {
  T[] acc;
  this(T[] data) {
    acc = data.dup;
    foreach (i; 1 .. data.length) {
      acc[i] += acc[i - 1];
    }
  }

  T query(int i, int j) {
    if (j < i) return 0;
    auto total = acc[j];
    if (i > 0) total -= acc[i - 1];
    return total;
  }
}

void main() {
  int T;
  read(T);
  while (T--) {
    long n, k;
    read(n, k);
    auto arr = list!long;
    sort(arr);

    auto r = new RangeSum!long(arr);
    auto total = r.query(0, cast(int)(n) - 1);
    if (total <= k) {
      writeln(0);
      continue;
    }

    long answer = total - k;

    foreach (i; 1 .. n) {
      auto mid = r.query(1, cast(int)(n - 1 - i));
      auto rem = k - mid;
      auto x = rem / (i + 1) - 5;
      while (mid + ((x + 1) * (i + 1)) <= k) x++;
      long d = max(0, arr[0] - x);

      answer = min(answer, d + i);
    }

    writeln(answer);
  }
}

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) {
    long n, k;
    readf!" %d %d "(n, k);
    auto a = readln.splitter.map!(to!long).array.sort.array;
    long[] pfa = [0L];
    foreach (x ; a)
      pfa ~= pfa.back + x;
    long best = long.max;
    foreach (swapcnt ; 0 .. n) {
      long newsum = a[0] * swapcnt + pfa[cast(size_t)(n - swapcnt)];
      if (newsum <= k) {
        best = min(best, swapcnt);
      } else {
        best = min(best, swapcnt + (newsum - k + swapcnt) / (swapcnt + 1));
      }
    }
    writeln(best);
  }
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

enum long INF = 1L<<40;
void solve() {
    int N;
    long K;
    readf("%d %d\n", &N, &K);
    auto A = readarray!long;
    sort(A);
    long sa = A.reduce!"a+b";
    long ans = INF;
    long s = 0;
    for (int y = 0; y < N; y++) {
        long x = max(0, ((sa - K - s + A[0] * y) + y) / (y + 1));
        ans = min(ans, x + y);
        s += A[N - 1 - y];
    }
    writeln(ans);
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

import std;

void main () {
    int tests;
    readf("%s\n", tests);

    foreach (test_idex; 0 .. tests) {
        int n;
        long k;
        readf("%s %s\n", n, k);

        int[] a = new int[n];

        k = -k;
        foreach (ref x; a)
            readf(" %s", x), k += x;
        readf("\n");
        a = sort(a).array;

        long rem = -a[0];
        int i;
        long turns;

        for (i = n - 1; i > 0 && k > 0;) {
            if (a[i] + rem >= n - i) {
                k -= a[i] + rem;
                -- i;
                ++ turns;
            } else {
                //a[i] + x >= n - i
                long x = n - i - a[i] - rem;
                long y = cast(long)ceil(cast(double)k / (n - i));

                if (x >= y) {
                    turns += y;
                    k = 0;
                    break;
                }
                k -= (n - i) * x;
                rem += x;
                turns += x;
            }
        }

        if (k <= 0) {
            writeln(turns);
            continue;
        }

        turns += cast(long)ceil(cast(double)k / n);
        writeln(turns);
    }

}
// ""

void main() { runSolver(); }

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

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

      long[] acc = [0];
      foreach(a; A.sort!"a > b") acc ~= acc[$ - 1] + a;

      const spread = A.sum - K;
      if (spread <= 0) return 0;

      long ans = long.max;
      long minn = A.minElement;
      foreach(i; 0..N) {
        bool isOK(long n) {
          // [i, n, n + (acc[i] - (minn - n)*i), spread].deb;
          return n + (acc[i] - (minn - n)*i) >= spread;
        }
        const x = binarySearch(&isOK, spread, -1);
        ans = min(ans, x + i);
        // [ans].deb;
      }

      return ans;
    }

    foreach(_; 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"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

void main() { runSolver(); }

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

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

      long[] acc = [0];
      foreach(a; A.sort!"a > b") acc ~= acc[$ - 1] + a;

      const spread = A.sum - K;
      if (spread <= 0) return 0;

      long ans = long.max;
      long minn = A.minElement;
      foreach(i; 0..N) {
        bool isOK(long n) {
          // [i, n, n + (acc[i] - (minn - n)*i), spread].deb;
          return n + (acc[i] - (minn - n)*i) >= spread;
        }
        const x = binarySearch(&isOK, spread, 0);
        ans = min(ans, x + i);
        // [ans].deb;
      }

      return ans;
    }

    foreach(_; 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"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

void main() { runSolver(); }

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

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

      long[] acc = [0];
      foreach(a; A.sort!"a > b") acc ~= acc[$ - 1] + a;

      const spread = A.sum - K;
      long ans = long.max;
      long minn = A.minElement;
      foreach(i; 0..N) {
        bool isOK(long n) {
          // [i, n, n + (acc[i] - (minn - n)*i), spread].deb;
          return n + (acc[i] - (minn - n)*i) >= spread;
        }
        const x = max(0, binarySearch(&isOK, spread, -1));
        ans = min(ans, x + i);
        // [ans].deb;
      }

      return ans;
    }

    foreach(_; 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"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

void main() { runSolver(); }

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

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

      auto summ = A.sum;
      if (summ <= K) return 0;

      long[] acc = [0];
      foreach(a; A.sort!"a > b") acc ~= acc[$ - 1] + a;

      const spread = summ - K;
      long ans = long.max;
      long minn = A.minElement;
      foreach(i; 0..N) {
        bool isOK(long n) {
          // [i, n, n + (acc[i] - (minn - n)*i), spread].deb;
          return n + (acc[i] - (minn - n)*i) >= spread;
        }
        const x = binarySearch(&isOK, 10L^^18, 0);
        ans = min(ans, x + i);
      }

      return ans;
    }

    foreach(_; 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"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

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

class RangeSum(T) {
  T[] acc;
  this(T[] data) {
    acc = data.dup;
    foreach (i; 1 .. data.length) {
      acc[i] += acc[i - 1];
    }
  }

  T query(int i, int j) {
    if (j < i) return 0;
    auto total = acc[j];
    if (i > 0) total -= acc[i - 1];
    return total;
  }
}

void main() {
  int T;
  read(T);
  while (T--) {
    long n, k;
    read(n, k);
    auto arr = list!long;
    sort(arr);

    auto r = new RangeSum!long(arr);

    bool good(int dec, int change) {
      long a = arr[0] - dec;
      long b = r.query(1, cast(int)(n) - 1 - change);
      long c = change * a;
      return a + b + c <= k;
    }

    long answer = long.max;

    foreach (i; 0 .. n) {
      int b = 200000000;
      int a = 0;

      if (good(0, i.to!int)) { answer = min(answer, i); }

      while (b > a + 1) {
        int mid = (b + a) / 2;
        if (good(mid, i.to!int)) b = mid;
        else a = mid;
      }

      answer = min(answer, i + a + 1);
    }

    writeln(answer);
  }
}

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

class RangeSum(T) {
  T[] acc;
  this(T[] data) {
    acc = data.dup;
    foreach (i; 1 .. data.length) {
      acc[i] += acc[i - 1];
    }
  }

  T query(int i, int j) {
    if (j < i) return 0;
    auto total = acc[j];
    if (i > 0) total -= acc[i - 1];
    return total;
  }
}

void main() {
  int T;
  read(T);
  while (T--) {
    long n, k;
    read(n, k);
    auto arr = list!long;
    sort(arr);

    auto r = new RangeSum!long(arr);

    bool good(int dec, int change) {
      long a = arr[0] - dec;
      long b = r.query(1, cast(int)(n) - 1 - change);
      long c = change * a;
      return a + b + c <= k;
    }

    long answer = long.max;

    foreach (i; 0 .. n) {
      int b = 100000000;
      int a = 0;

      if (good(0, i.to!int)) { answer = min(answer, i); }

      while (b > a + 1) {
        int mid = (b + a) / 2;
        if (good(mid, i.to!int)) b = mid;
        else a = mid;
      }

      answer = min(answer, i + a + 1);
    }

    writeln(answer);
  }
}

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

class RangeSum(T) {
  T[] acc;
  this(T[] data) {
    acc = data.dup;
    foreach (i; 1 .. data.length) {
      acc[i] += acc[i - 1];
    }
  }

  T query(int i, int j) {
    if (j < i) return 0;
    auto total = acc[j];
    if (i > 0) total -= acc[i - 1];
    return total;
  }
}

void main() {
  int T;
  read(T);
  while (T--) {
    long n, k;
    read(n, k);
    auto arr = list!long;
    sort(arr);

    auto r = new RangeSum!long(arr);

    bool good(int dec, int change) {
      long a = arr[0] - dec;
      long b = r.query(1, cast(int)(n) - 1 - change);
      long c = change * a;
      return a + b + c <= k;
    }

    long answer = long.max;

    foreach (i; 0 .. n) {
      int b = 300000;
      int a = 0;

      if (good(0, i.to!int)) { answer = min(answer, i); }

      while (b > a + 1) {
        int mid = (b + a) / 2;
        if (good(mid, i.to!int)) b = mid;
        else a = mid;
      }

      answer = min(answer, i + a + 1);
    }

    writeln(answer);
  }
}


You are given two integers $$$l$$$ and $$$r$$$, where $$$l < r$$$. We will add $$$1$$$ to $$$l$$$ until the result is equal to $$$r$$$. Thus, there will be exactly $$$r-l$$$ additions performed. For each such addition, let's look at the number of digits that will be changed after it.For example:   if $$$l=909$$$, then adding one will result in $$$910$$$ and $$$2$$$ digits will be changed;  if you add one to $$$l=9$$$, the result will be $$$10$$$ and $$$2$$$ digits will also be changed;  if you add one to $$$l=489999$$$, the result will be $$$490000$$$ and $$$5$$$ digits will be changed. Changed digits always form a suffix of the result written in the decimal system.Output the total number of changed digits, if you want to get $$$r$$$ from $$$l$$$, adding $$$1$$$ each time.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by two integers $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le 10^9$$$).

For each test case, calculate the total number of changed digits if you want to get $$$r$$$ from $$$l$$$, adding one each time.

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

long digits_diff(int x1, int x2)
{
  auto s1 = to!string(x1).split("").reverse;
  auto s2 = to!string(x2).split("").reverse;
  size_t minl = min(s1.length, s2.length);
  long result = abs(cast(long)s1.length - cast(long)s2.length);
  for (int i = 0; i < minl; i++)
    if (s1[i] != s2[i])
      result += 1;
  return result;
}

long solvex(int l, int r)
{
  long result = 0;
  while ((l < r) && (l % 10 != 0)) {
    result += digits_diff(l, l + 1);
    l += 1;
  }

  while (l < r && r % 10 != 0) {
    result += digits_diff(r, r - 1);
    r -= 1;
  }

  if (l == r)
    return result;

  if ((l % 10 == 0) && (r % 10 == 0)) {
    return result + solvex(l / 10, r / 10) + (r - l);
  }

  while (l < r) {
    result += digits_diff(l, l + 1);
    l++;
  }

  return result;
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int l, r;
    readf!" %d %d "(l, r);
    writeln(solvex(l, r));
  }
}

// code by cutx64

module main;

import std.string, std.array, std.container, std.typecons;
import std.stdio, std.format, std.file;
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 ask(int x, int d) {
    int pw10 = 10 ^^ d;
    int pre = x / pw10;
    int suf = x % pw10;
    return pre + (suf == pw10 - 1);
  }
  int tests;
  readf!"%s\n"(tests);
  foreach(per_test; 0 .. tests) {
    int l, r;
    readf!"%s %s\n"(l, r);
    int ans = r - l;
    foreach(i; 1 .. 10) {
      ans += (ask(r - 1, i) - ask(l - 1, i));
    }
    ans.writeln;
  }

} // main


Ashish and Vivek play a game on a matrix consisting of $$$n$$$ rows and $$$m$$$ columns, where they take turns claiming cells. Unclaimed cells are represented by $$$0$$$, while claimed cells are represented by $$$1$$$. The initial state of the matrix is given. There can be some claimed cells in the initial state.In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.

The first line consists of a single integer $$$t$$$ $$$(1 \le t \le 50)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case consists of two space-separated integers $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$ — the number of rows and columns in the matrix. The following $$$n$$$ lines consist of $$$m$$$ integers each, the $$$j$$$-th integer on the $$$i$$$-th line denoting $$$a_{i,j}$$$ $$$(a_{i,j} \in \{0, 1\})$$$.

For each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes).

NoteFor the first case: One possible scenario could be: Ashish claims cell $$$(1, 1)$$$, Vivek then claims cell $$$(2, 2)$$$. Ashish can neither claim cell $$$(1, 2)$$$, nor cell $$$(2, 1)$$$ as cells $$$(1, 1)$$$ and $$$(2, 2)$$$ are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell $$$(1, 1)$$$, the only cell that can be claimed in the first move. After that Vivek has no moves left.For the third case: Ashish cannot make a move, so Vivek wins.For the fourth case: If Ashish claims cell $$$(2, 3)$$$, Vivek will have no moves left.

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

string FMT_F = "%.10f";

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

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

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

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

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

		long x, y;
		foreach (i; 0..n)
		{
			bool ok = true;
			foreach (j; 0..m)
			{
				if (a[i][j] == 1)
				{
					ok = false;
					break;
				}
			}
			if (ok)
				++x;
		}
		foreach (i; 0..m)
		{
			bool ok = true;
			foreach (j; 0..n)
			{
				if (a[j][i] == 1)
				{
					ok = false;
					break;
				}
			}
			if (ok)
				++y;
		}
		ans[ti] = min(x, y) % 2;
	}

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

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

void main ()
{
	foreach (test; 0..readln.strip.to !(int))
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		int [] [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.splitter.map !(to !(int)).array;
		}
		auto moves = min (rows - board.map !(any).sum, cols -
		    cols.iota.map !(i => board.transversal (i)).map !(any).sum);
		writeln ((moves & 1) ? "Ashish" : "Vivek");
	}
}


The sequence $$$a$$$ is sent over the network as follows:  sequence $$$a$$$ is split into segments (each element of the sequence belongs to exactly one segment, each segment is a group of consecutive elements of sequence);  for each segment, its length is written next to it, either to the left of it or to the right of it;  the resulting sequence $$$b$$$ is sent over the network. For example, we needed to send the sequence $$$a = [1, 2, 3, 1, 2, 3]$$$. Suppose it was split into segments as follows: $$$[\color{red}{1}] + [\color{blue}{2, 3, 1}] + [\color{green}{2, 3}]$$$. Then we could have the following sequences:   $$$b = [1, \color{red}{1}, 3, \color{blue}{2, 3, 1}, \color{green}{2, 3}, 2]$$$,  $$$b = [\color{red}{1}, 1, 3, \color{blue}{2, 3, 1}, 2, \color{green}{2, 3}]$$$,  $$$b = [\color{red}{1}, 1, \color{blue}{2, 3, 1}, 3, 2, \color{green}{2, 3}]$$$,  $$$b = [\color{red}{1}, 1,\color{blue}{2, 3, 1}, 3, \color{green}{2, 3}, 2]$$$. If a different segmentation had been used, the sent sequence might have been different.The sequence $$$b$$$ is given. Could the sequence $$$b$$$ be sent over the network? In other words, is there such a sequence $$$a$$$ that converting $$$a$$$ to send it over the network could result in a sequence $$$b$$$?

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of the test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of the sequence $$$b$$$. The second line of test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) — the sequence $$$b$$$ itself. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print on a separate line:   YES if sequence $$$b$$$ could be sent over the network, that is, if sequence $$$b$$$ could be obtained from some sequence $$$a$$$ to send $$$a$$$ over the network.  NO otherwise.  You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as positive response).

NoteIn the first case, the sequence $$$b$$$ could be obtained from the sequence $$$a = [1, 2, 3, 1, 2, 3]$$$ with the following partition: $$$[\color{red}{1}] + [\color{blue}{2, 3, 1}] + [\color{green}{2, 3}]$$$. The sequence $$$b$$$: $$$[\color{red}{1}, 1, \color{blue}{2, 3, 1}, 3, 2, \color{green}{2, 3}]$$$.In the second case, the sequence $$$b$$$ could be obtained from the sequence $$$a = [12, 7, 5]$$$ with the following partition: $$$[\color{red}{12}] + [\color{green}{7, 5}]$$$. The sequence $$$b$$$: $$$[\color{red}{12}, 1, 2, \color{green}{7, 5}]$$$.In the third case, the sequence $$$b$$$ could be obtained from the sequence $$$a = [7, 8, 9, 10, 3]$$$ with the following partition: $$$[\color{red}{7, 8, 9, 10, 3}]$$$. The sequence $$$b$$$: $$$[5, \color{red}{7, 8, 9, 10, 3}]$$$.In the fourth case, there is no sequence $$$a$$$ such that changing $$$a$$$ for transmission over the network could produce a sequence $$$b$$$.

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void solve() {
    int N = read!int;
    auto B = readarray!int;

    bool[int] v;
    v[0] = true;
    for (int k = 0; k < N; k++) {
        int p = k - B[k];
        if (p >= 0 && p in v) {
            v[k + 1] = true;
        }
        if (k in v) {
            int n = k + B[k];
            v[n + 1] = true;
        }
    }
    writeln(N in v ? "YES" : "NO");
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}


Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$.    An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d < n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.

Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).

NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.

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

  int n, d;
  rd(n, d);
  struct P {
    int x, y;
  }

  P[] vec = [P(d, -d), P(n - d, n - d), P(-d, d), P(d - n, d - n)];
  P[] ps = [P(0, d), P(d, 0), P(n, n - d), P(n - d, n)];
  int m;
  rd(m);
  while (m--) {
    int x, y;
    rd(x, y);
    int[] o;
    foreach (i, p; ps) {
      auto u = P(x - p.x, y - p.y);
      o ~= vec[i].x * u.y - vec[i].y * u.x;
    }
    auto inside = reduce!((r, e) => (r && e >= 0))(true, o);
    if (inside) {
      writeln("YES");
    } else {
      writeln("NO");
    }
  }
}

void rd(T...)(ref T x) {
  import std.stdio, std.string, std.conv;

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


Petya had a tree consisting of n vertices numbered with integers from 1 to n. Accidentally he lost his tree. Petya remembers information about k vertices: distances from each of them to each of the n tree vertices.Your task is to restore any tree that satisfies the information that Petya remembers or report that such tree doesn't exist.

The first line contains two integers n and k (2 ≤ n ≤ 30 000, 1 ≤ k ≤ min(200, n)) — the number of vertices in the tree and the number of vertices about which Petya remembers distance information. The following k lines contain remembered information. The i-th line contains n integers di, 1, di, 2, ..., di, n (0 ≤ di, j ≤ n - 1), where di, j — the distance to j-th vertex from the i-th vertex that Petya remembers.

If there are no suitable trees, print -1. In the other case, print n - 1 lines: each line should contain two vertices connected by edge in the required tree. You can print edges and vertices in an edge in any order. The tree vertices are enumerated from 1 to n. If there are many solutions print any of them.

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

int N, K;
int[][] D;

int[][] ans;

string solve() {
  auto us = new int[K];
  us[] = -1;
  foreach (k; 0 .. K) {
    foreach (u; 0 .. N) {
      if (D[k][u] == 0) {
        if (us[k] != -1) {
          return "two zeros";
        }
        us[k] = u;
      }
    }
    if (us[k] == -1) {
      return "no zeros";
    }
  }

  auto kss = new int[][N];
  foreach (u; 0 .. N) {
    foreach (k; 1 .. K) {
      if ((D[0][u] + D[k][u] + D[0][us[k]]) % 2 != 0) {
        return "dist parity error";
      }
      if (D[0][us[k]] > D[0][u] + D[k][u]) {
        return "triangle error";
      }
      if (D[0][us[k]] == D[0][u] + D[k][u]) {
        kss[u] ~= k;
      }
    }
  }
  debug {
    writeln("kss = ", kss);
  }

  alias Entry = Tuple!(int, "d", int, "u");

  // inside
  Entry[] es;
  foreach (u; 0 .. N) {
    if (u == us[0] || !kss[u].empty) {
      es ~= Entry(D[0][u], u);
    }
  }
  es.sort;
  debug {
    writeln("es = ", es);
  }
  auto parss = new int[][](K, N);
  foreach (k; 0 .. K) {
    parss[k][] = -1;
    parss[k][0] = us[0];
  }
  foreach (ref e; es[1 .. $]) {
    if (!(1 <= e.d && e.d < N)) {
      return "dist skipped inside";
    }
    const p = parss[kss[e.u][0]][e.d - 1];
    if (p == -1) {
      return "dist skipped inside";
    }
    ans ~= [p, e.u];
    foreach (k; kss[e.u]) {
      parss[k][e.d] = e.u;
    }
  }

  auto uss = new int[][N];
  foreach (u; 0 .. N) {
    if (!(u == us[0] || !kss[u].empty)) {
      int km = 0;
      int dm = D[0][u];
      foreach (k; 1 .. K) {
        const d = (D[0][u] + D[k][u] - D[0][us[k]]) / 2;
        if (chmin(dm, d)) {
          km = k;
        }
      }
      if (!(0 <= D[0][u] - dm && D[0][u] - dm <= D[0][us[km]])) {
        return "out from nothing";
      }
      const r = parss[km][D[0][u] - dm];
      if (r == -1) {
        return "out from nothing";
      }
      uss[r] ~= u;
    }
  }
  debug {
    writeln("uss = ", uss);
  }

  // outside
  foreach (r; 0 .. N) {
    Entry[] esOut;
    foreach (u; uss[r]) {
      esOut ~= Entry(D[0][u] - D[0][r], u);
    }
    esOut.sort;
    debug {
      writeln("r = ", r, "; esOut = ", esOut);
    }
    auto pars = new int[uss[r].length + 1];
    pars[] = -1;
    pars[0] = r;
    foreach (ref e; esOut) {
      if (!(1 <= e.d && e.d < pars.length)) {
        return "dist skipped outside";
      }
      const p = pars[e.d - 1];
      if (p == -1) {
        return "dist skipped outside";
      }
      ans ~= [p, e.u];
      pars[e.d] = e.u;
    }
  }

  // check
  auto graph = new int[][N];
  foreach (edge; ans) {
    graph[edge[0]] ~= edge[1];
    graph[edge[1]] ~= edge[0];
  }
  foreach (k; 0 .. K) {
    auto que = new int[N];
    int qb, qe;
    auto dist = new int[N];
    dist[] = -1;
    dist[us[k]] = 0;
    que[qe++] = us[k];
    for (; qb != qe; ) {
      const u = que[qb++];
      foreach (v; graph[u]) {
        if (dist[v] == -1) {
          dist[v] = dist[u] + 1;
          que[qe++] = v;
        }
      }
    }
    if (D[k] != dist) {
      return "check failed";
    }
  }

  return "";
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      K = readInt();
      D = new int[][](K, N);
      foreach (k; 0 .. K) {
        foreach (u; 0 .. N) {
          D[k][u] = readInt();
        }
      }

      ans = [];
      const msg = solve();
      if (msg == "") {
        debug {
          writeln("ok");
        }
        foreach (edge; ans) {
          writeln(edge[0] + 1, " ", edge[1] + 1);
        }
      } else {
        debug {
          writeln(msg);
        }
        writeln(-1);
      }
    }
  } catch (EOFException e) {
  }
}