You are given a non-decreasing array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Also you are given a positive integer $$$k$$$.You want to find $$$m$$$ non-decreasing arrays of non-negative integers $$$b_1, b_2, \ldots, b_m$$$, such that:  The size of $$$b_i$$$ is equal to $$$n$$$ for all $$$1 \leq i \leq m$$$.  For all $$$1 \leq j \leq n$$$, $$$a_j = b_{1, j} + b_{2, j} + \ldots + b_{m, j}$$$. In the other word, array $$$a$$$ is the sum of arrays $$$b_i$$$.  The number of different elements in the array $$$b_i$$$ is at most $$$k$$$ for all $$$1 \leq i \leq m$$$. Find the minimum possible value of $$$m$$$, or report that there is no possible $$$m$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n \leq 100$$$, $$$1 \leq k \leq n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_1 \leq a_2 \leq \ldots \leq a_n \leq 100$$$, $$$a_n > 0$$$).

For each test case print a single integer: the minimum possible value of $$$m$$$. If there is no such $$$m$$$, print $$$-1$$$.

NoteIn the first test case, there is no possible $$$m$$$, because all elements of all arrays should be equal to $$$0$$$. But in this case, it is impossible to get $$$a_4 = 1$$$ as the sum of zeros.In the second test case, we can take $$$b_1 = [3, 3, 3]$$$. $$$1$$$ is the smallest possible value of $$$m$$$.In the third test case, we can take $$$b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]$$$ and $$$b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]$$$. It's easy to see, that $$$a_i = b_{1, i} + b_{2, i}$$$ for all $$$i$$$ and the number of different elements in $$$b_1$$$ and in $$$b_2$$$ is equal to $$$3$$$ (so it is at most $$$3$$$). It can be proven that $$$2$$$ is the smallest possible value of $$$m$$$.

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 numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const K = readInt();
        auto A = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt();
        }

        int ans;
        if (N == 1) {
          ans = 1;
        } else {
          int num;
          foreach (i; 0 .. N - 1) {
            if (A[i] < A[i + 1]) {
              ++num;
            }
          }
          if (K == 1) {
            if (num == 0) {
              ans = 1;
            } else {
              ans = -1;
            }
          } else {
            ans = (num + (K - 1) - 1) / (K - 1);
            chmax(ans, 1);
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 1..n)
		{
			if (a[i] > a[i-1])
				++ans[ti];
		}
		if (k == 1)
		{
			if (ans[ti] != 0)
				ans[ti] = -1;
			else
				ans[ti] = 1;
			continue;
		}
		else if (ans[ti] == 0)
			ans[ti] = 1;
		ans[ti] = (ans[ti]+k-2) / (k-1);
	}

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

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

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

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

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

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

        int ans;
        if (N == 1) {
          ans = 0;
        } else {
          int num;
          foreach (i; 0 .. N - 1) {
            if (A[i] < A[i + 1]) {
              ++num;
            }
          }
          if (K == 1) {
            if (num == 0) {
              ans = 1;
            } else {
              ans = -1;
            }
          } else {
            ans = (num + (K - 1) - 1) / (K - 1);
          }
        }
        writeln(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)); }

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

        int ans;
        if (N == 1) {
          ans = 0;
        } else {
          int num;
          foreach (i; 0 .. N - 1) {
            if (A[i] < A[i + 1]) {
              ++num;
            }
          }
          if (K == 1) {
            if (num == 0) {
              ans = 1;
            } else {
              ans = -1;
            }
          } else {
            ans = (num + (K - 1) - 1) / (K - 1);
            chmax(ans, 1);
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 1..n)
		{
			if (a[i] > a[i-1])
				++ans[ti];
		}
		if (k == 1)
		{
			if (ans[ti] != 0)
				ans[ti] = -1;
			else
				ans[ti] = 1;
			continue;
		}
		ans[ti] = (ans[ti]+k-2) / (k-1);
	}

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


There are $$$n$$$ cities in Berland. The city numbered $$$1$$$ is the capital. Some pairs of cities are connected by a one-way road of length 1.Before the trip, Polycarp for each city found out the value of $$$d_i$$$ — the shortest distance from the capital (the $$$1$$$-st city) to the $$$i$$$-th city.Polycarp begins his journey in the city with number $$$s$$$ and, being in the $$$i$$$-th city, chooses one of the following actions:   Travel from the $$$i$$$-th city to the $$$j$$$-th city if there is a road from the $$$i$$$-th city to the $$$j$$$-th and $$$d_i < d_j$$$;  Travel from the $$$i$$$-th city to the $$$j$$$-th city if there is a road from the $$$i$$$-th city to the $$$j$$$-th and $$$d_i \geq d_j$$$;  Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action $$$0$$$ or $$$1$$$ time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.  For example, if $$$n = 6$$$ and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):   $$$2 \rightarrow 5 \rightarrow 1 \rightarrow 2 \rightarrow 5$$$;  $$$3 \rightarrow 6 \rightarrow 2$$$;  $$$1 \rightarrow 3 \rightarrow 6 \rightarrow 2 \rightarrow 5$$$. Polycarp wants for each starting city $$$i$$$ to find out how close he can get to the capital. More formally: he wants to find the minimal value of $$$d_j$$$ that Polycarp can get from the city $$$i$$$ to the city $$$j$$$ according to the rules described above.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) and $$$m$$$ ($$$1 \leq m \leq 2 \cdot 10^5$$$) — number of cities and roads, respectively. This is followed by $$$m$$$ lines describing the roads. Each road is characterized by two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n, u \ne v$$$) — the numbers of cities connected by a one-way road. It is guaranteed that the sums of $$$n$$$ and $$$m$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$. It is guaranteed that for each pair of different cities $$$(u, v)$$$ there is at most one road from $$$u$$$ to $$$v$$$ (but a pair of roads from $$$u$$$ to $$$v$$$ and from $$$v$$$ to $$$u$$$ — is valid). It is guaranteed that there is a path from the capital to all cities.

For each test case, on a separate line output $$$n$$$ numbers, the $$$i$$$-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto adj = new int [] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
		}

		auto q = [0];
		auto d = (-1).repeat (n).array;
		d[0] = 0;
		while (!q.empty)
		{
			auto v = q.front;
			q.popFront ();
			q.assumeSafeAppend ();
			foreach (u; adj[v])
			{
				if (d[u] == -1)
				{
					d[u] = d[v] + 1;
					q ~= u;
				}
			}
		}

		auto answer = (-1).repeat (n).array;

		int recur (int v)
		{
			if (answer[v] != -1)
			{
				return answer[v];
			}
			answer[v] = d[v];
			foreach (u; adj[v])
			{
				auto cur = (d[u] > d[v]) ? recur (u) : d[u];
				answer[v] = min (answer[v], cur);
			}
			return answer[v];
		}

		foreach (u; 0..n)
		{
			if (answer[u] == -1)
			{
				recur (u);
			}
		}

		writefln !("%(%s %)") (answer);
	}
}


This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai.Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence a1, a2, ..., an repeated m times).After that some teams were formed, each consisting of k participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no k neighboring participants from the same city.Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected.

The first line contains three integers n, k and m (1 ≤ n ≤ 105, 2 ≤ k ≤ 109, 1 ≤ m ≤ 109). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number of city, person from which must take seat i in the bus.

Output the number of remaining participants in the line.

NoteIn the second example, the line consists of ten participants from the same city. Nine of them will form a team. At the end, only one participant will stay in the line.

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

long solve(long K, int[] as) {
  debug {
    writeln("solve ", K, " ", as);
  }
  int len;
  auto keys = new int[as.length + 1];
  auto nums = new int[as.length + 1];
  long ret;
  void push(int a) {
    for (; ; ) {
      if (len >= 1 && keys[len - 1] == a) {
        ++nums[len - 1];
        break;
      }
      if (len >= 1) {
        ret += nums[len - 1] / K;
        nums[len - 1] %= K;
        if (nums[len - 1] == 0) {
          --len;
          continue;
        }
      }
      keys[len] = a;
      nums[len] = 1;
      ++len;
      break;
    }
  }
  foreach (a; as) {
    push(a);
  }
  push(-1);
  debug {
    writeln("  ret = ", ret);
  }
  return ret;
}

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

      debug {
        writefln("N = %s, K = %s, M = %s, A = %s", N, K, M, A);
        stdout.flush;
      }

      const long inpN = N;
      long ans;

      {
        int len;
        auto keys = new int[A.length + 1];
        auto nums = new int[A.length + 1];
        long ret;
        void push(int a) {
          for (; ; ) {
            if (len >= 1 && keys[len - 1] == a) {
              ++nums[len - 1];
              break;
            }
            if (len >= 1) {
              ret += nums[len - 1] / K;
              nums[len - 1] %= K;
              if (nums[len - 1] == 0) {
                --len;
                continue;
              }
            }
            keys[len] = a;
            nums[len] = 1;
            ++len;
            break;
          }
        }
        foreach (a; A) {
          push(a);
        }
        push(-1);
        debug {
          writeln("  ret = ", ret);
        }
        ans += ret * M;
        A = [];
        foreach (j; 0 .. len) {
          if (keys[j] != -1) {
            foreach (_; 0 .. nums[j]) {
              A ~= keys[j];
            }
          }
        }
        N = cast(int)(A.length);
      }

      debug {
        writefln("N = %s, K = %s, M = %s, A = %s; ans = %s", N, K, M, A, ans);
        stdout.flush;
      }

      auto lef = new int[N];
      auto rig = new int[N];
      foreach (i; 0 .. N) {
        lef[i] = (i - 1 >= 0 && A[i - 1] == A[i]) ? lef[i - 1] : i;
      }
      foreach_reverse (i; 0 .. N) {
        rig[i] = (i + 1 < N && A[i + 1] == A[i]) ? rig[i + 1] : i;
      }
      debug {
        writeln("lef = ", lef);
        writeln("rig = ", rig);
      }

      if (N == 0) {
      } else if (M == 1) {
        ans += solve(K, A);
      } else {
        // [0, x] [y, N - 1]
        int x = N - 1, y = 0;
        for (; ; ) {
          debug {
            writefln("x = %s, y = %s", x, y);
          }
          if (lef[x] == y) {
            // [0, y) [y, x] (deleted) [y, x] (x, N - 1]
            const sz = (x - y + 1) * M;
            ans += sz / K;
            if (sz % K != 0) {
              debug {
                writeln("break ", __LINE__);
              }
              ans += solve(K, A[0 .. y]);
              ans += solve(K, A[x + 1 .. N]);
              break;
            } else {
              debug {
                writeln("break ", __LINE__);
              }
              ans += solve(K, A[0 .. y] ~ A[x + 1 .. N]);
              break;
            }
          } else if (x - lef[x] + 1 >= K) {
            ans += (M - 1);
            x -= K;
          } else if (rig[y] - y + 1 >= K) {
            ans += (M - 1);
            y += K;
          } else if (A[x] == A[y]) {
            const sz = (x - lef[x] + 1) + (rig[y] - y + 1);
            ans += (sz / K) * (M - 1);
            x = lef[x] - 1;
            y = rig[y] + 1;
            if (sz % K != 0) {
              debug {
                writeln("break ", __LINE__);
              }
              ans += solve(K, A[0 .. x + 1]);
              ans += solve(K, A[y .. N]);
              break;
            }
          } else {
            debug {
              writeln("break ", __LINE__);
            }
            ans += solve(K, A[0 .. x + 1]);
            ans += solve(K, A[y + 1 .. x]) * (M - 2);
            ans += solve(K, A[y .. N]);
            break;
          }
        }
      }
      ans = inpN * M - ans * K;
      writeln(ans);

      debug {
        const k = cast(int)(K);
        int[] brt;
        foreach (_; 0 .. M) {
          brt ~= A;
        }
        for (; ; ) {
          const brtLen = cast(int)(brt.length);
          foreach (i; 0 .. brtLen - k + 1) {
            if (brt[i .. i + k].all!(a => (a == brt[i]))) {
              brt = brt[0 .. i] ~ brt[i + k .. $];
              goto found;
            }
          }
          break;
         found:
        }
        writeln("brt = ", brt);
        stdout.flush;
        assert(ans == brt.length);
      }
    }
  } 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)); }

long solve(long K, int[] as) {
  debug {
    writeln("solve ", K, " ", as);
  }
  int len;
  auto keys = new int[as.length + 1];
  auto nums = new int[as.length + 1];
  long ret;
  void push(int a) {
    for (; ; ) {
      if (len >= 1 && keys[len - 1] == a) {
        ++nums[len - 1];
        break;
      }
      if (len >= 1) {
        ret += nums[len - 1] / K;
        nums[len - 1] %= K;
        if (nums[len - 1] == 0) {
          --len;
          continue;
        }
      }
      keys[len] = a;
      nums[len] = 1;
      ++len;
      break;
    }
  }
  foreach (a; as) {
    push(a);
  }
  push(-1);
  debug {
    writeln("  ret = ", ret);
  }
  return ret;
}

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

      debug {
        writefln("N = %s, K = %s, M = %s, A = %s", N, K, M, A);
        stdout.flush;
      }

      auto lef = new int[N];
      auto rig = new int[N];
      foreach (i; 0 .. N) {
        lef[i] = (i - 1 >= 0 && A[i - 1] == A[i]) ? lef[i - 1] : i;
      }
      foreach_reverse (i; 0 .. N) {
        rig[i] = (i + 1 < N && A[i + 1] == A[i]) ? rig[i + 1] : i;
      }
      debug {
        writeln("lef = ", lef);
        writeln("rig = ", rig);
      }

      long ans;
      if (M == 1) {
        ans += solve(K, A);
      } else {
        // [0, x] [y, N - 1]
        int x = N - 1, y = 0;
        for (; ; ) {
          debug {
            writefln("x = %s, y = %s", x, y);
          }
          if (lef[x] == y) {
            // [0, y) [y, x] (deleted) [y, x] (x, N - 1]
            const sz = (x - y + 1) * M;
            ans += sz / K;
            if (sz % K != 0) {
              debug {
                writeln("break ", __LINE__);
              }
              ans += solve(K, A[0 .. y]);
              ans += solve(K, A[x + 1 .. N]);
              break;
            } else {
              debug {
                writeln("break ", __LINE__);
              }
              ans += solve(K, A[0 .. y] ~ A[x + 1 .. N]);
              break;
            }
          } else if (x - lef[x] + 1 >= K) {
            ans += (M - 1);
            x -= K;
          } else if (rig[y] - y + 1 >= K) {
            ans += (M - 1);
            y += K;
          } else if (A[x] == A[y]) {
            const sz = (x - lef[x] + 1) + (rig[y] - y + 1);
            ans += (sz / K) * (M - 1);
            x = lef[x] - 1;
            y = rig[y] + 1;
            if (sz % K != 0) {
              debug {
                writeln("break ", __LINE__);
              }
              ans += solve(K, A[0 .. x + 1]);
              ans += solve(K, A[y .. N]);
              break;
            }
          } else {
            debug {
              writeln("break ", __LINE__);
            }
            ans += solve(K, A[0 .. x + 1]);
            ans += solve(K, A[y + 1 .. x]) * (M - 2);
            ans += solve(K, A[y .. N]);
            break;
          }
        }
      }
      ans = N * M - ans * K;
      writeln(ans);

      debug {
        const k = cast(int)(K);
        int[] brt;
        foreach (_; 0 .. M) {
          brt ~= A;
        }
        for (; ; ) {
          const brtLen = cast(int)(brt.length);
          foreach (i; 0 .. brtLen - k + 1) {
            if (brt[i .. i + k].all!(a => (a == brt[i]))) {
              brt = brt[0 .. i] ~ brt[i + k .. $];
              goto found;
            }
          }
          break;
         found:
        }
        writeln("brt = ", brt);
        stdout.flush;
        assert(ans == brt.length);
      }
    }
  } catch (EOFException e) {
  }
}


You are given a rooted tree. It contains $$$n$$$ vertices, which are numbered from $$$1$$$ to $$$n$$$. The root is the vertex $$$1$$$.Each edge has two positive integer values. Thus, two positive integers $$$a_j$$$ and $$$b_j$$$ are given for each edge.Output $$$n-1$$$ numbers $$$r_2, r_3, \dots, r_n$$$, where $$$r_i$$$ is defined as follows.Consider the path from the root (vertex $$$1$$$) to $$$i$$$ ($$$2 \le i \le n$$$). Let the sum of the costs of $$$a_j$$$ along this path be $$$A_i$$$. Then $$$r_i$$$ is equal to the length of the maximum prefix of this path such that the sum of $$$b_j$$$ along this prefix does not exceed $$$A_i$$$.    Example for $$$n=9$$$. The blue color shows the costs of $$$a_j$$$, and the red color shows the costs of $$$b_j$$$. Consider an example. In this case:  $$$r_2=0$$$, since the path to $$$2$$$ has an amount of $$$a_j$$$ equal to $$$5$$$, only the prefix of this path of length $$$0$$$ has a smaller or equal amount of $$$b_j$$$; $$$r_3=3$$$, since the path to $$$3$$$ has an amount of $$$a_j$$$ equal to $$$5+9+5=19$$$, the prefix of length $$$3$$$ of this path has a sum of $$$b_j$$$ equal to $$$6+10+1=17$$$ ( the number is $$$17 \le 19$$$); $$$r_4=1$$$, since the path to $$$4$$$ has an amount of $$$a_j$$$ equal to $$$5+9=14$$$, the prefix of length $$$1$$$ of this path has an amount of $$$b_j$$$ equal to $$$6$$$ (this is the longest suitable prefix, since the prefix of length $$$2$$$ already has an amount of $$$b_j$$$ equal to $$$6+10=16$$$, which is more than $$$14$$$); $$$r_5=2$$$, since the path to $$$5$$$ has an amount of $$$a_j$$$ equal to $$$5+9+2=16$$$, the prefix of length $$$2$$$ of this path has a sum of $$$b_j$$$ equal to $$$6+10=16$$$ (this is the longest suitable prefix, since the prefix of length $$$3$$$ already has an amount of $$$b_j$$$ equal to $$$6+10+1=17$$$, what is more than $$$16$$$); $$$r_6=1$$$, since the path up to $$$6$$$ has an amount of $$$a_j$$$ equal to $$$2$$$, the prefix of length $$$1$$$ of this path has an amount of $$$b_j$$$ equal to $$$1$$$; $$$r_7=1$$$, since the path to $$$7$$$ has an amount of $$$a_j$$$ equal to $$$5+3=8$$$, the prefix of length $$$1$$$ of this path has an amount of $$$b_j$$$ equal to $$$6$$$ (this is the longest suitable prefix, since the prefix of length $$$2$$$ already has an amount of $$$b_j$$$ equal to $$$6+3=9$$$, which is more than $$$8$$$); $$$r_8=2$$$, since the path up to $$$8$$$ has an amount of $$$a_j$$$ equal to $$$2+4=6$$$, the prefix of length $$$2$$$ of this path has an amount of $$$b_j$$$ equal to $$$1+3=4$$$; $$$r_9=3$$$, since the path to $$$9$$$ has an amount of $$$a_j$$$ equal to $$$2+4+1=7$$$, the prefix of length $$$3$$$ of this path has a sum of $$$b_j$$$ equal to $$$1+3+3=7$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of test cases follow. Each description begins with a line that contains an integer $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) — the number of vertices in the tree. This is followed by $$$n-1$$$ string, each of which contains three numbers $$$p_j, a_j, b_j$$$ ($$$1 \le p_j \le n$$$; $$$1 \le a_j,b_j \le 10^9$$$) — the ancestor of the vertex $$$j$$$, the first and second values an edge that leads from $$$p_j$$$ to $$$j$$$. The value of $$$j$$$ runs through all values from $$$2$$$ to $$$n$$$ inclusive. It is guaranteed that each set of input data has a correct hanged tree with a root at the vertex $$$1$$$. It is guaranteed that the sum of $$$n$$$ over all input test cases does not exceed $$$2\cdot10^5$$$.

For each test case, output $$$n-1$$$ integer in one line: $$$r_2, r_3, \dots, r_n$$$.

NoteThe first example is clarified in the statement.In the second example:  $$$r_2=0$$$, since the path to $$$2$$$ has an amount of $$$a_j$$$ equal to $$$1$$$, only the prefix of this path of length $$$0$$$ has a smaller or equal amount of $$$b_j$$$; $$$r_3=0$$$, since the path to $$$3$$$ has an amount of $$$a_j$$$ equal to $$$1+1=2$$$, the prefix of length $$$1$$$ of this path has an amount of $$$b_j$$$ equal to $$$100$$$ ($$$100 > 2$$$); $$$r_4=3$$$, since the path to $$$4$$$ has an amount of $$$a_j$$$ equal to $$$1+1+101=103$$$, the prefix of length $$$3$$$ of this path has an amount of $$$b_j$$$ equal to $$$102$$$, .

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

struct Tree {
    int[][] G;
    int N;
    int root;
    int[] parent;
    int[] depth;        // depth[v]: distance from root
    int[][] ancestor;   // ancestor[v][i]: v's {2^i}-th ancestor

    void init_parent() {
        void dfs(int v, int prev, int d) {
            parent[v] = prev;
            depth[v] = d;
            foreach (next; G[v]) {
                if (next == prev) continue;
                dfs(next, v, d + 1);
            }
        }
        dfs(root, -1, 0);
    }

    void init_ancestor() {
        int L = bsr(N) + 1;
        this.ancestor = new int[][](N, L);
        foreach (ref e; ancestor) e[] = -1;
        for (int v = 0; v < N; v++) {
            ancestor[v][0] = parent[v];
        }
        for (int i = 1; i < L; i++) {
            for (int v = 0; v < N; v++) {
                if (ancestor[v][i-1] == -1) continue;
                ancestor[v][i] = ancestor[ ancestor[v][i-1] ][i-1];
            }
        }
    }

    this(int[][] G, int root) {
        this.N = cast(int)G.length;
        this.G = G;
        this.root = root;
        this.depth = new int[N];
        this.parent = new int[N];
        init_parent();
        init_ancestor();
    }

    int kth_ancestor(int v, int k) {
        // return v's k-th ancestor
        for (int i = 0; i <= bsr(N); i++) {
            if (k & (1<<i)) {
                v = ancestor[v][i];
                if (v == -1) return v;
            }
        }
        return v;
    }
}

void solve() {
    int N = readln.chomp.to!int;
    int[][] G = new int[][N];
    int[][] A = new int[][N];
    int[][] B = new int[][N];
    int[] P = new int[N]; P[] = -1;
    for (int j = 1; j < N; j++) {
        int p, a, b; readf("%d %d %d\n", &p, &a, &b);
        p--;
        G[p] ~= j;
        A[p] ~= a;
        B[p] ~= b;
        P[j] = p;
    }
    long[] Sa = new long[N];
    long[] Sb = new long[N];
    void dfs(int v, int[][] c, long[] Sc, long s) {
        Sc[v] = s;
        foreach (i, n; G[v]) {
            auto cost = c[v][i];
            dfs(n, c, Sc, s + cost);
        }
    }
    dfs(0, A, Sa, 0);
    dfs(0, B, Sb, 0);

    auto ancestor = Tree(G, 0);
    int[] ans = new int[N];
    for (int v = 0; v < N; v++) {
        long L = Sa[v];
        int lb = 0, ub = N;

        bool C(int x) {
            int nv = ancestor.kth_ancestor(v, x);
            return nv < 0 || L >= Sb[nv];
        }

        if (C(lb)) {
            ans[v] = ancestor.depth[v];
        } else {
            while (lb + 1 < ub) {
                int mid = (lb + ub) / 2;
                (C(mid) ? ub : lb) = mid;
            }
            ans[v] = ancestor.depth[ancestor.kth_ancestor(v, ub)];
        }
    }
    writefln("%(%s %)", ans[1..$]);
}

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

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

struct FindAncestor {
    int[][] G;
    int N;
    int root;
    int[] parent;
    int[] depth;        // depth[v]: distance from root
    int[][] ancestor;   // ancestor[v][i]: v's {2^i}-th ancestor

    void init_parent() {
        void dfs(int v, int prev, int d) {
            parent[v] = prev;
            depth[v] = d;
            foreach (next; G[v]) {
                if (next == prev) continue;
                dfs(next, v, d + 1);
            }
        }
        dfs(root, -1, 0);
    }

    void init_ancestor() {
        int L = bsr(N) + 1;
        this.ancestor = new int[][](N, L);
        foreach (ref e; ancestor) e[] = -1;
        for (int v = 0; v < N; v++) {
            ancestor[v][0] = parent[v];
        }
        for (int i = 1; i < L; i++) {
            for (int v = 0; v < N; v++) {
                if (ancestor[v][i-1] == -1) continue;
                ancestor[v][i] = ancestor[ ancestor[v][i-1] ][i-1];
            }
        }
    }

    this(int[][] G, int root) {
        this.N = cast(int)G.length;
        this.G = G;
        this.root = root;
        this.depth = new int[N];
        this.parent = new int[N];
        init_parent();
        init_ancestor();
    }

    int query(int v, int k) {
        // return v's k-th ancestor
        for (int i = 0; i <= bsr(N); i++) {
            if (k & (1<<i)) {
                v = ancestor[v][i];
                if (v == -1) return v;
            }
        }
        return v;
    }
}

void solve() {
    int N = readln.chomp.to!int;
    int[][] G = new int[][N];
    int[][] A = new int[][N];
    int[][] B = new int[][N];
    int[] P = new int[N]; P[] = -1;
    for (int j = 1; j < N; j++) {
        int p, a, b; readf("%d %d %d\n", &p, &a, &b);
        p--;
        G[p] ~= j;
        A[p] ~= a;
        B[p] ~= b;
        P[j] = p;
    }
    long[] Sa = new long[N];
    long[] Sb = new long[N];
    void dfs(int v, int[][] c, long[] Sc, long s) {
        Sc[v] = s;
        foreach (i, n; G[v]) {
            auto cost = c[v][i];
            dfs(n, c, Sc, s + cost);
        }
    }
    dfs(0, A, Sa, 0);
    dfs(0, B, Sb, 0);

    auto ancestor = FindAncestor(G, 0);
    int[] ans = new int[N];
    for (int v = 0; v < N; v++) {
        long L = Sa[v];
        int lb = 0, ub = N;

        bool C(int x) {
            int nv = ancestor.query(v, x);
            return nv < 0 || L >= Sb[nv];
        }

        if (C(lb)) {
            ans[v] = ancestor.depth[v];
        } else {
            while (lb + 1 < ub) {
                int mid = (lb + ub) / 2;
                (C(mid) ? ub : lb) = mid;
            }
            ans[v] = ancestor.depth[ancestor.query(v, ub)];
        }
    }
    writefln("%(%s %)", ans[1..$]);
}

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


Let $$$n$$$ be an integer. Consider all permutations on integers $$$1$$$ to $$$n$$$ in lexicographic order, and concatenate them into one big sequence $$$p$$$. For example, if $$$n = 3$$$, then $$$p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$$$. The length of this sequence will be $$$n \cdot n!$$$.Let $$$1 \leq i \leq j \leq n \cdot n!$$$ be a pair of indices. We call the sequence $$$(p_i, p_{i+1}, \dots, p_{j-1}, p_j)$$$ a subarray of $$$p$$$. Its length is defined as the number of its elements, i.e., $$$j - i + 1$$$. Its sum is the sum of all its elements, i.e., $$$\sum_{k=i}^j p_k$$$. You are given $$$n$$$. Find the number of subarrays of $$$p$$$ of length $$$n$$$ having sum $$$\frac{n(n+1)}{2}$$$. Since this number may be large, output it modulo $$$998244353$$$ (a prime number).

The only line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$), as described in the problem statement.

Output a single integer — the number of subarrays of length $$$n$$$ having sum $$$\frac{n(n+1)}{2}$$$, modulo $$$998244353$$$.

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

immutable int mod = 998_244_353;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int res = 0;
		int cur = n % mod;
		int prev = cur;
		int k = 0;
		foreach_reverse (i; 2..n)
		{
			k += 1;
			cur = (cur * 1L * i) % mod;
			debug {writeln (k, " * (", cur, " - ", prev, ")");}
			res = (res + (cur - prev + mod) * 1L * k) % mod;
//			res = (res + (cur - prev) * 1L * k) % mod;
			prev = cur;
		}
		res = (res + cur) % mod;
		writeln (res);
	}
}

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

enum mod = 998244353L;

void main() {
    int n;
    scan(n);

    auto f = new long[](n + 1);
    f[0] = f[1] = 1;
    foreach (i ; 2 .. n + 1) {
        f[i] = f[i-1] * i % mod;
    }
    auto rf = new long[](n + 1);
    rf[n] = powmod(f[n], mod - 2, mod);
    foreach_reverse (i ; 1 .. n) {
        rf[i] = rf[i+1] * (i + 1) % mod;
    }

    long comb(int n, int k) {
        return f[n] * rf[k] % mod * rf[n-k] % mod;
    }

    long ans = f[n];

    foreach (i ; 2 .. n) {
        long t = comb(n, i) * (f[i] - 1 + mod) % mod * f[n - i] % mod;
        ans += t;
        ans %= mod;
    }

    writeln(ans);
}

long powmod(long x, long y, long mod) {
    return y > 0 ? powmod(x, y>>1, mod)^^2 % mod * x^^(y&1) % mod : 1;
}

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

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

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

  int n;
  rd(n);
  const long mod = 998244353;

  long powmod(long b, long e) {
    if (e == 0)
      return 1;
    else if (e == 1)
      return b % mod;
    else if (e & 1)
      return b * powmod(b, e - 1) % mod;
    else
      return powmod(b * b % mod, e / 2);
  }

  auto fac = new long[](n + 1), inv = new long[](n + 1);
  fac[0] = inv[0] = 1;
  for (int i = 1; i <= n; i++) {
    fac[i] = fac[i - 1] * i % mod;
    inv[i] = powmod(fac[i], mod - 2);
  }
  long ans = n * fac[n] % mod;
  foreach (i; 1 .. n) {
    ans -= fac[n] * inv[i] % mod;
    ((ans %= mod) += mod) %= mod;
  }
  writeln(ans);
}

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

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

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

  int n;
  rd(n);
  const long mod = 998244353;

  long powmod(long b, long e) {
    if (e == 0)
      return 1;
    else if (e == 1)
      return b % mod;
    else if (e & 1)
      return b * powmod(b, e - 1) % mod;
    else
      return powmod(b * b % mod, e / 2);
  }

  auto fac = new long[](n + 1), inv = new long[](n + 1);
  fac[0] = inv[0] = 1;
  for (int i = 1; i <= n; i++) {
    fac[i] = fac[i - 1] * i % mod;
    inv[i] = powmod(fac[i], mod - 2);
  }
  long ans = n * fac[n] % mod;
  foreach (i; 1 .. n) {
    ans -= fac[n] * inv[i] % mod;
    if (ans < 0) {
      ans += mod;
    }
  }
  writeln(ans);
}

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

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

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

enum mod = 998244353L;

void main() {
    int n;
    scan(n);

    auto f = new long[](n + 1);
    f[0] = f[1] = 1;
    foreach (i ; 2 .. n + 1) {
        f[i] = f[i-1] * i % mod;
    }
    auto rf = new long[](n + 1);
    rf[n] = powmod(f[n], mod - 2, mod);
    foreach_reverse (i ; 1 .. n) {
        rf[i] = rf[i+1] * (i + 1) % mod;
    }

    long comb(int n, int k) {
        return f[n] * rf[k] % mod * rf[n-k] % mod;
    }

    long ans = f[n];

    foreach (i ; 2 .. n) {
        long t = comb(n, i) * (f[i] - 1 + mod) % mod * f[n - i] % mod;
        ans += t;
    }

    writeln(ans);
}

long powmod(long x, long y, long mod) {
    return y > 0 ? powmod(x, y>>1, mod)^^2 % mod * x^^(y&1) % mod : 1;
}

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

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.

The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di < di + 1.

If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).

NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.

import std.math;
import std.stdio;
import std.range;
import std.format;
import std.string;
import std.c.stdio;
import std.algorithm;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		if(k) {
			auto p = abs(h - v), l = d - k;

			if(p > l)
				return write(`IMPOSSIBLE`);

			m = max(m, (l + h + v) / 2);
		} else
			m = h + d - 1;

		k = d;
		v = h;
	}

	write(max(m, v + ds - k));
}

import std.math;
import std.stdio;
import std.format;
import std.string;
import std.algorithm;
import std.c.stdio;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		if(!k) {
			k = d, v = m = h;
			continue;
		}

		auto p = abs(h - v), l = d - k;

		if(p > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 - p, h);

		k = d;
		v = h;
	}

	write(m + ds - k);
}

import std.math;
import std.stdio;
import std.format;
import std.string;
import std.algorithm;
import std.c.stdio;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		if(!k) {
			k = d, v = m = h;
			continue;
		}

		auto p = h - v, l = d - k;

		if(p.abs > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 + p, h);

		k = d;
		v = h;
	}

	write(max(m, v + ds - k));
}

//1 2 3 4 3 3 2

import std.math;
import std.stdio;
import std.format;
import std.string;
import std.algorithm;
import std.c.stdio;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		auto p = abs(h - v), l = d - k;

		if(p > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 - p);

		k = d;
		v = h;
	}

	write(m);
}

import std.math;
import std.stdio;
import std.format;
import std.string;
import std.algorithm;
import std.c.stdio;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		auto p = abs(h - v), l = d - k;

		if(p > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 - p, h);

		k = d;
		v = h;
	}

	write(m);
}

import std.math;
import std.stdio;
import std.range;
import std.format;
import std.string;
import std.c.stdio;
import std.algorithm;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		if(!k) {
			k = d, v = h, m = h + d - 1;
			continue;
		}

		auto p = abs(h - v), l = d - k;

		if(p > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 - p / 2);

		k = d;
		v = h;
	}

	write(max(m, v + ds - k));
}

//1 2 3 4 3 3 2

import std.math;
import std.stdio;
import std.format;
import std.string;
import std.algorithm;
import std.c.stdio;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		if(!k) {
			k = d, v = m = h;
			continue;
		}

		auto p = abs(h - v), l = d - k;

		if(p > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 - p, h);

		k = d;
		v = h;
	}

	write(max(m, v + ds - k));
}

import std.math;
import std.stdio;
import std.format;
import std.string;
import std.algorithm;
import std.c.stdio;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		if(!k) {
			k = d, v = m = h;
			continue;
		}

		auto p = h - v, l = d - k;

		if(p.abs > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 + p / 2, h);

		k = d;
		v = h;
	}

	write(max(m, v + ds - k));
}

//1 2 3 4 3 3 2

import std.math;
import std.stdio;
import std.format;
import std.string;
import std.algorithm;
import std.c.stdio;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		if(!k) {
			k = d, v = m = h;
			continue;
		}

		auto p = abs(h - v), l = d - k;

		if(p > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 - p, h);

		k = d;
		v = h;
	}

	write(max(m, (ds - k) / 2));
}

import std.math;
import std.stdio;
import std.range;
import std.format;
import std.string;
import std.c.stdio;
import std.algorithm;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		if(!k) {
			k = d, v = h, m = h + ds - d;
			continue;
		}

		auto p = abs(h - v), l = d - k;

		if(p > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 - p / 2);

		k = d;
		v = h;
	}

	write(max(m, v + ds - k));
}

//1 2 3 4 3 3 2

import std.math;
import std.stdio;
import std.format;
import std.string;
import std.algorithm;
import std.c.stdio;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		if(!k) {
			k = d, v = m = h;
			continue;
		}

		auto p = abs(h - v), l = d - k;

		if(p > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 - p, h);

		k = d;
		v = h;
	}

	write(m);
}

import std.math;
import std.stdio;
import std.range;
import std.format;
import std.string;
import std.c.stdio;
import std.algorithm;

void main() {
	uint ds, cnt;
	scanf(`%d %d`, &ds, &cnt);

	int v, k, m;

	foreach(_; 0..cnt) {
		int d, h;
		scanf(`%d %d`, &d, &h);

		if(!k) {
			k = d, v = m = h;
			continue;
		}

		auto p = abs(h - v), l = d - k;

		if(p > l)
			return write(`IMPOSSIBLE`);

		m = max(m, h + l / 2 - p / 2);

		k = d;
		v = h;
	}

	write(max(m, v + ds - k));
}

//1 2 3 4 3 3 2


Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but n different heads that can read data in parallel.When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the initial state the i-th reading head is above the track number hi. For each of the reading heads, the hard drive's firmware can move the head exactly one track to the right or to the left, or leave it on the current track. During the operation each head's movement does not affect the movement of the other heads: the heads can change their relative order; there can be multiple reading heads above any of the tracks. A track is considered read if at least one head has visited this track. In particular, all of the tracks numbered h1, h2, ..., hn have been read at the beginning of the operation.  Mike needs to read the data on m distinct tracks with numbers p1, p2, ..., pm. Determine the minimum time the hard drive firmware needs to move the heads and read all the given tracks. Note that an arbitrary number of other tracks can also be read.

The first line of the input contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of disk heads and the number of tracks to read, accordingly. The second line contains n distinct integers hi in ascending order (1 ≤ hi ≤ 1010, hi < hi + 1) — the initial positions of the heads. The third line contains m distinct integers pi in ascending order (1 ≤ pi ≤ 1010, pi < pi + 1) - the numbers of tracks to read. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams or the %I64d specifier.

Print a single number — the minimum time required, in seconds, to read all the needed tracks.

NoteThe first test coincides with the figure. In this case the given tracks can be read in 2 seconds in the following way:   during the first second move the 1-st head to the left and let it stay there;  move the second head to the left twice;  move the third head to the right twice (note that the 6-th track has already been read at the beginning). One cannot read the tracks in 1 second as the 3-rd head is at distance 2 from the 8-th track.

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new long [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		auto b = new long [m];
		foreach (j; 0..m)
		{
			readf (" %s", &b[j]);
		}

		bool good (long lim)
		{
			int j = 0;
			foreach (i; 0..n)
			{
				long p = a[i];
				long r = lim;
				long first = abs (p - b[j]);
				if (r < first)
				{
					continue;
				}
				long lo = b[j];
				j++;
				while (j < m)
				{
					long hi = b[j];
					long last = abs (p - b[j]);
					long one = min (first, last);
					long two = hi - lo;
					if (r < one + two)
					{
						break;
					}
					j++;
				}
				if (j >= m)
				{
					return true;
				}
			}
			return j == m;
		}

		long lo = 0;
		long hi = long.max / 5;
		while (lo < hi)
		{
			long me = (lo + hi) / 2;
			if (good (me))
			{
				hi = me;
			}
			else
			{
				lo = me + 1;
			}
		}
		writeln (lo);
	}
}


Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.Let's call a positive number special if it can be written as a sum of different non-negative powers of $$$n$$$. For example, for $$$n = 4$$$ number $$$17$$$ is special, because it can be written as $$$4^0 + 4^2 = 1 + 16 = 17$$$, but $$$9$$$ is not.Theofanis asks you to help him find the $$$k$$$-th special number if they are sorted in increasing order. Since this number may be too large, output it modulo $$$10^9+7$$$.

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

For each test case, print one integer — the $$$k$$$-th special number in increasing order modulo $$$10^9+7$$$.

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

void solve(){
    ll n = scan;
    ll k = scan;
    ll MOD = to!long(1e9) + 7L;
    ll num = 0;
    ll add = 1;
    for(ll st = 0; st < 31; ++st){
        ll msk = 1L<<st;
        if(k & msk){
            num += add;
            num %= MOD;
        }
        add *= n;
        add %= MOD;
    }
    writeln(num);
}

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

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

import std.stdio, std.algorithm, std.array, std.string, std.format, std.range, std.bigint, std.conv;

void main()
{
    int t;
    scanf("%d", &t);
    foreach(_; 0..t)
    {
        long n, k;
        scanf("%lld %lld", &n, &k);
        getchar();
        auto s = format("%b", k);
        BigInt res;
        long i = 0;
        foreach(el; s.retro)
        {
            if (el == '1')
                res += (to!BigInt(n) ^^ i) % (10^^9 + 7);
            i++;
        }
        writeln(res % (10^^9 + 7));
    }
}


Spring has come, and the management of the AvtoBus bus fleet has given the order to replace winter tires with summer tires on all buses.You own a small bus service business and you have just received an order to replace $$$n$$$ tires. You know that the bus fleet owns two types of buses: with two axles (these buses have $$$4$$$ wheels) and with three axles (these buses have $$$6$$$ wheels).You don't know how many buses of which type the AvtoBus bus fleet owns, so you wonder how many buses the fleet might have. You have to determine the minimum and the maximum number of buses that can be in the fleet if you know that the total number of wheels for all buses is $$$n$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1\,000$$$) — the number of test cases. The following lines contain description of test cases. The only line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{18}$$$) — the total number of wheels for all buses.

For each test case print the answer in a single line using the following format. Print two integers $$$x$$$ and $$$y$$$ ($$$1 \le x \le y$$$) — the minimum and the maximum possible number of buses that can be in the bus fleet. If there is no suitable number of buses for the given $$$n$$$, print the number $$$-1$$$ as the answer.

NoteIn the first test case the total number of wheels is $$$4$$$. It means that there is the only one bus with two axles in the bus fleet.In the second test case it's easy to show that there is no suitable number of buses with $$$7$$$ wheels in total.In the third test case the total number of wheels is $$$24$$$. The following options are possible:  Four buses with three axles.  Three buses with two axles and two buses with three axles.  Six buses with two axles. So the minimum number of buses is $$$4$$$ and the maximum number of buses is $$$6$$$.

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    long n;
    foreach(_; 0..t)
    {
        n = readln.strip.to!(long);
        long amin, amax;
        if (n % 2 != 0 || n < 4) {
            writeln(-1);
            continue;
        }
        else {
            if (n % 4 == 0)
                amax = n / 4;
            else {
                auto tmp = n;
                while (tmp > 0) {
                    amax++;
                    tmp -= 6;
                    if (tmp % 4 == 0) {
                        amax += tmp / 4;
                        break;
                    }
                }
            }
            if (n % 6 == 0)
                amin = n / 6;
            else {
                auto tmp2 = n;
                while (tmp2 > 0) {
                    amin++;
                    tmp2 -= 4;
                    if (tmp2 % 6 == 0) {
                        amin += tmp2 / 6;
                        break;
                    }
                }
            }
        writeln(max(1,amin)," ", amax);
        }
    }
}

void main() { runSolver(); }

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

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

      if (N < 4 || N % 2 == 1) return "-1";

      long ans1, ans2;
      long t = N;
      while(t % 6 != 0) {
        t -= 4;
        ans1++;
      }
      ans1 += t / 6;

      t = N;
      while(t % 4 != 0) {
        t -= 6;
        ans2++;
      }
      ans2 += t / 4;

      return [ans1, ans2].toAnswerString;
    }

    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;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    long n;
    foreach(_; 0..t)
    {
        n = readln.strip.to!(long);
        long amin, amax;
        if (n % 2 != 0 || n < 4) {
            writeln(-1);
            continue;
        }
        else {
            if (n % 4 == 0)
                amax = n / 4;
            else {
                auto tmp = n;
                while (tmp > 3) {
                    amax++;
                    tmp -= 6;
                    if (tmp % 4 == 0) {
                        amax += tmp / 4;
                        break;
                    }
                }
            }
            if (n % 6 == 0)
                amin = n / 6;
            else {
                auto tmp2 = n;
                while (tmp2 > 5) {
                    amin++;
                    tmp2 -= 4;
                    if (tmp2 % 6 == 0) {
                        amin += tmp2 / 6;
                        break;
                    }
                }
            }
        writeln(max(1,amin)," ", amax);
        }
    }
}

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    long n;
    foreach(_; 0..t)
    {
        n = readln.strip.to!(long);
        long amin, amax;
        if (n % 2 != 0) {
            writeln(-1);
            continue;
        }
        else {
            if (n % 4 == 0)
                amax = n / 4;
            else {
                auto tmp = n;
                while (tmp > 3) {
                    amax++;
                    tmp -= 6;
                    if (tmp % 4 == 0) {
                        amax += tmp / 4;
                        break;
                    }
                }
            }
            if (n % 6 == 0)
                amin = n / 6;
            else {
                auto tmp2 = n;
                while (tmp2 > 5) {
                    amin++;
                    tmp2 -= 4;
                    if (tmp2 % 6 == 0) {
                        amin += tmp2 / 6;
                        break;
                    }
                }
            }
        writeln(max(1,amin)," ", amax);
        }
    }
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!long;
      long ans1, ans2;

      long p6 = N / 6;
      N -= p6 * 6;
      if (N % 4 == 0) {
        ans1 = p6 + N / 4;
        ans2 = (p6*6 + N) / 4;
      } else if(N % 4 == 2 && p6 > 0) {
        p6--;
        N += 6;
        ans1 = p6 + N / 4;
        ans2 = (p6 / 2)*3 + N / 4;
      } else {
        return "-1";
      }

      return [ans1, ans2].toAnswerString;
    }

    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"];

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

void main() { runSolver(); }

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

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

      long ans1, ans2;

      long t = N;
      if (t % 6 == 0) {
        ans1 += t / 6;
        t -= ans1 * 6;
      }
      if (t % 4 > 0) {
        return "-1";
      }

      ans1 += t / 4;

      ans2 = N / 4;
      N -= ans2 * 4;
      ans2 += N / 6;

      return [ans1, ans2].toAnswerString;
    }

    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"];

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


In Aramic language words can only represent objects.Words in Aramic have special properties:   A word is a root if it does not contain the same letter more than once.  A root and all its permutations represent the same object.  The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".  Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.

Output one integer — the number of different objects mentioned in the given ancient Aramic script.

NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;

void main()
{
	int n = readln.chomp.to!int;
	string[] ss = readln.chomp.split;
	bool[bool[char]] roots;
	foreach (s; ss) {
		bool[char] root;
		foreach (c; s) {
			root[c] = true;
		}
		roots[root] = true;
	}
	roots.length.writeln;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in ref Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

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

void main()
{
    readln;

    auto a = readln.chomp.splitter.map!(to!(dchar[])).array;

    auto toRoot = (dchar[] s) => s.sort.uniq.to!(dchar[]);

    auto ans = a.map!toRoot.redBlackTree.length;

    writeln (ans);
}

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

void main()
{
    readln;

    auto a = readln.splitter.map!(to!(dchar[])).array;

    auto toRoot = (dchar[] s) => s.sort.uniq.to!(dchar[]);

    auto ans = a.map!(toRoot).redBlackTree.length;

    writeln (ans);
}

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

void main()
{
    readln;

    auto a = readln.split.map!(to!string).array;

    auto rbt = make!(RedBlackTree!string);

    auto toRoot = (string s) => s.representation.dup.sort.uniq.to!string;

    a.each!(s => rbt.insert(toRoot(s)));

    debug { writeln(rbt); }

    writeln (rbt.length);
}

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

void main()
{
    readln;

    auto a = readln.split.map!(to!(dchar[])).array;

    auto rbt = make!(RedBlackTree!(dchar[]));

    auto toRoot = (dchar[] s) => s.sort.uniq.to!(dchar[]);

    a.each!(s => rbt.insert(toRoot(s)));

    debug { writeln(rbt); }

    writeln (rbt.length);
}

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

void main()
{
    readln;

    auto a = readln.chomp.splitter.map!(to!(dchar[]));

    auto toRoot = (dchar[] s) => s.sort.uniq.array;

    auto ans = a.map!toRoot.redBlackTree.length;

    writeln (ans);
}

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

void main()
{
    readln;

    auto a = readln.split.map!(to!(dchar[])).array;

    auto toRoot = (dchar[] s) => s.sort.uniq.to!(dchar[]);

    auto ans = a.map!(toRoot).redBlackTree.length;

    writeln (ans);
}

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

void main()
{
    readln;

    auto a = readln.chomp.splitter;

    auto toRoot = (string s) => s.array.sort.uniq.to!string;

    auto ans = a.map!toRoot.redBlackTree.length;

    writeln (ans);
}

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

void main()
{
    readln;

    auto a = readln.chomp.splitter.map!(to!(dchar[]));

    auto toRoot = (dchar[] s) => s.sort.uniq.to!(dchar[]);

    auto ans = a.map!toRoot.redBlackTree.length;

    writeln (ans);
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  dchar[][] s; readA(n, s);

  foreach (i; 0..n)
    s[i] = s[i].sort().uniq.array;

  s = s.sort().uniq.array;

  writeln(s.length);
}


Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.

The first line of the input contains two integers a and b ( - 100 ≤ a, b ≤ 100) — coordinates of Vasiliy's home. The second line contains a single integer n (1 ≤ n ≤ 1000) — the number of available Beru-taxi cars nearby.  The i-th of the following n lines contains three integers xi, yi and vi ( - 100 ≤ xi, yi ≤ 100, 1 ≤ vi ≤ 100) — the coordinates of the i-th car and its speed. It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives.

Print a single real value — the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer.In the second sample, cars 2 and 3 will arrive simultaneously.

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    double a,b,x,y,v,ans=double.max;
    readf!"%f %f"(a,b);
    readln;
    int n=readln.chomp.to!int;
    while(n--){
        readf!"%f %f %f"(x,y,v);
        readln;
        ans=min(ans,sqrt((a-x)^^2+(b-y)^^2)/v);
    }
    writefln!"%.10f"(ans);
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    double a,b,n,x,y,v,ans=double.max;
    readf!"%f %f"(a,b);
    readln;
    n=readln.chomp.to!int;
    while(n--){
        readf!"%f %f %f"(x,y,v);
        readln;
        ans=min(ans,sqrt((a-x)^^2+(b-y)^^2)/v);
    }
    writefln!"%.10f"(ans);
}


You are given a set of $$$n$$$ segments on the axis $$$Ox$$$, each segment has integer endpoints between $$$1$$$ and $$$m$$$ inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$) — coordinates of the left and of the right endpoints. Consider all integer points between $$$1$$$ and $$$m$$$ inclusive. Your task is to print all such points that don't belong to any segment. The point $$$x$$$ belongs to the segment $$$[l; r]$$$ if and only if $$$l \le x \le r$$$.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the number of segments and the upper bound for coordinates. The next $$$n$$$ lines contain two integers each $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$) — the endpoints of the $$$i$$$-th segment. Segments may intersect, overlap or even coincide with each other. Note, it is possible that $$$l_i=r_i$$$, i.e. a segment can degenerate to a point.

In the first line print one integer $$$k$$$ — the number of points that don't belong to any segment. In the second line print exactly $$$k$$$ integers in any order — the points that don't belong to any segment. All points you print should be distinct. If there are no such points at all, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.

NoteIn the first example the point $$$1$$$ belongs to the second segment, the point $$$2$$$ belongs to the first and the second segments and the point $$$5$$$ belongs to the third segment. The points $$$3$$$ and $$$4$$$ do not belong to any segment.In the second example all the points from $$$1$$$ to $$$7$$$ belong to the first segment.

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

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

    auto cnt = new int[] (m+2);
    foreach (_; 0 .. n) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        ++cnt[a];
        --cnt[b+1];
    }

    cnt = cnt.cumulativeFold!((a, b) => a + b).array;

    auto ans = cnt.dropOne.dropBackOne.enumerate(1).filter!(t => t[1] == 0).map!(t => t[0]).array;

    ans.length.writeln;
    ans.writefln!("%(%s %)");
}

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		alias Segment = Tuple !(int, q{l}, int, q{r});
		auto s = new Segment [n];
		foreach (ref c; s)
		{
			readf (" %s %s", &c.l, &c.r);
		}
		auto r = iota (1, m + 1)
		    .filter !(x => s.all !(c => x < c.l || c.r < x)).array;
		writeln (r.length);
		writefln ("%(%s %)", r);
	}
}

import std.stdio;
int main()
{
	int a=0;
	int b=0;
	readf(" %d", &a);
	readf(" %d", &b);
	bool[] m = new bool[b+1];
	for (int i=0; i<b+1; i++)
	{
		m[i]=true;
	}
	for (int i=0; i<a; i++)
	{
		int c=0;
		int d=0;
		readf(" %d", &c);
		readf(" %d", &d);
		for (int j=c; j<d+1; j++)
		{
			m[j]=false;
		}
	}
	int count=0;
	for (int i=0; i<b+1; i++)
	{
		if (m[i]==true)
		{
			count=count+1;
		}
	}
	writeln(count-1);
	for (int i=1; i<b+1; i++)
	{
		if (m[i]==true)
		{
			writeln(i);
		}
	}
	return 0;
}


Thank you for helping Heidi! It is now the second of April, but she has been summoned by Jenny again. The pranks do not seem to end...In the meantime, Heidi has decided that she does not trust her friends anymore. Not too much, anyway. Her relative lack of trust is manifested as follows: whereas previously she would not be made to visit the same person twice, now she can only be sure that she will not be made to visit the same person more than k times. (In the case of Jenny, this includes her first visit in the beginning. The situation from the easy version corresponds to setting k = 1.)This is not as bad as it looks, since a single ticket for a route between two friends allows Heidi to travel between this pair of friends the whole day (in both directions). In other words, once she pays for travel between a pair of friends, all further travels between that pair are free.How much money will Heidi waste now, in a worst-case scenario?

The first line contains two space-separated integers – the number of friends n () and the parameter k (1 ≤ k ≤ 105). The next n - 1 lines each contain three space-separated integers u, v and c (0 ≤ u, v ≤ n - 1, 1 ≤ c ≤ 104) meaning that u and v are friends and the cost for traveling between u and v is c. It is again guaranteed that the social network of the input forms a tree.

Again, output a single integer – the maximum sum of costs of tickets.

NoteIn the first example, the worst-case scenario for Heidi is to visit the friends in the following order: 0, 1, 5, 1, 3, 1, 0, 2, 6, 2, 7, 2, 8. Observe that no friend is visited more than 3 times.

/+ dub.sdl:
    name "K"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner;
import std.typecons;

int main() {
    auto sc = new Scanner(stdin);
    alias Edge = Tuple!(int, "to", int, "dist");
    int n, k;
    sc.read(n, k);
    Edge[][] g = new Edge[][](n+1);
    g[n] ~= Edge(0, 0); g[0] ~= Edge(n, 0);
    foreach (i; 0..n-1) {
        int a, b, c;
        sc.read(a, b, c);
        g[a] ~= Edge(b, c);
        g[b] ~= Edge(a, c);
    }

    int[2] dfs(int p, int b, int d) {
        if (p == n) return dfs(0, p, g[n][0].dist);
        int m = g[p].length.to!int - 1;
        int[2][] bu = new int[2][m];
        int co = 0;
        foreach (e; g[p]) {
            if (e.to == b) continue;
            bu[co] = dfs(e.to, p, e.dist);
            co++;
        }
        bu.sort!"a[0]>b[0]";
        int[2] res; res[0] += d;
        int ma = 0;
        foreach (i; 0..min(m, k-1)) {
            res[0] += bu[i][0];
            ma = max(ma, bu[i][1] - bu[i][0]);
        }
        res[1] = res[0] + ma;
        if (k <= m) {
            res[1] = max(res[1], res[0] + ma + bu[k-1][0]);
            int ma2 = 0;
            foreach (i; k-1..m) {
                ma2 = max(ma2, bu[i][1]);
            }
            res[1] = max(res[1], res[0] + ma2);
        }
        return res;
    }

    writeln(dfs(n, -1, 0)[1]);
    return 0;
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

                    assert(buf.length == T.length);
                }
                x = buf;
                line.length = 0;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}


Lord Omkar would like to have a tree with $$$n$$$ nodes ($$$3 \le n \le 10^5$$$) and has asked his disciples to construct the tree. However, Lord Omkar has created $$$m$$$ ($$$\mathbf{1 \le m < n}$$$) restrictions to ensure that the tree will be as heavenly as possible. A tree with $$$n$$$ nodes is an connected undirected graph with $$$n$$$ nodes and $$$n-1$$$ edges. Note that for any two nodes, there is exactly one simple path between them, where a simple path is a path between two nodes that does not contain any node more than once.Here is an example of a tree:   A restriction consists of $$$3$$$ pairwise distinct integers, $$$a$$$, $$$b$$$, and $$$c$$$ ($$$1 \le a,b,c \le n$$$). It signifies that node $$$b$$$ cannot lie on the simple path between node $$$a$$$ and node $$$c$$$. Can you help Lord Omkar and become his most trusted disciple? You will need to find heavenly trees for multiple sets of restrictions. It can be shown that a heavenly tree will always exist for any set of restrictions under the given constraints.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers, $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$\mathbf{1 \leq m < n}$$$), representing the size of the tree and the number of restrictions. The $$$i$$$-th of the next $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ ($$$1 \le a_i, b_i, c_i \le n$$$, $$$a$$$, $$$b$$$, $$$c$$$ are distinct), signifying that node $$$b_i$$$ cannot lie on the simple path between nodes $$$a_i$$$ and $$$c_i$$$.  It is guaranteed that the sum of $$$n$$$ across all test cases will not exceed $$$10^5$$$.

For each test case, output $$$n-1$$$ lines representing the $$$n-1$$$ edges in the tree. On each line, output two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) signifying that there is an edge between nodes $$$u$$$ and $$$v$$$. Given edges have to form a tree that satisfies Omkar's restrictions.

NoteThe output of the first sample case corresponds to the following tree:    For the first restriction, the simple path between $$$1$$$ and $$$3$$$ is $$$1, 3$$$, which doesn't contain $$$2$$$. The simple path between $$$3$$$ and $$$5$$$ is $$$3, 5$$$, which doesn't contain $$$4$$$. The simple path between $$$5$$$ and $$$7$$$ is $$$5, 3, 1, 2, 7$$$, which doesn't contain $$$6$$$. The simple path between $$$6$$$ and $$$4$$$ is $$$6, 7, 2, 1, 3, 4$$$, which doesn't contain $$$5$$$. Thus, this tree meets all of the restrictions.The output of the second sample case corresponds to the following tree:

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto m = readInt!int;
	bool[] isFree = new bool[](n);
	isFree[] = true;
	foreach(i; 0 .. m)
	{
		int a = readInt!int-1;
		int b = readInt!int-1;
		int c = readInt!int-1;
		isFree[b] = false;
	}
	int freeNode = -1;
	foreach(i; 0 .. n) if (isFree[i]) {freeNode = i; break;}
	assert(freeNode != -1);
	foreach(i; 0 .. n)
		if (i != freeNode)
			writeln(i+1, " ", freeNode+1);
}

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