In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.When a query appears server may react in three possible ways:   If server is free and query queue is empty, then server immediately starts to process this query.  If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue.  If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed. As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.

The first line of the input contains two integers n and b (1 ≤ n, b ≤ 200 000) — the number of queries and the maximum possible size of the query queue. Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers ti and di (1 ≤ ti, di ≤ 109), where ti is the moment of time when the i-th query appears and di is the time server needs to process it. It is guaranteed that ti - 1 < ti for all i > 1.

Print the sequence of n integers e1, e2, ..., en, where ei is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or  - 1 if the corresponding query will be rejected.

NoteConsider the first sample.   The server will start to process first query at the moment 2 and will finish to process it at the moment 11.  At the moment 4 second query appears and proceeds to the queue.  At the moment 10 third query appears. However, the server is still busy with query 1, b = 1 and there is already query 2 pending in the queue, so third query is just rejected.  At the moment 11 server will finish to process first query and will take the second query from the queue.  At the moment 15 fourth query appears. As the server is currently busy it proceeds to the queue.  At the moment 19 two events occur simultaneously: server finishes to proceed the second query and the fifth query appears. As was said in the statement above, first server will finish to process the second query, then it will pick the fourth query from the queue and only then will the fifth query appear. As the queue is empty fifth query is proceed there.  Server finishes to process query number 4 at the moment 21. Query number 5 is picked from the queue.  Server finishes to process query number 5 at the moment 22.

import std.stdio;
import std.algorithm;

const int N = 200000;

class Request
{
	int arrivalTime;
	int executionTime;
	long readyTime;
}

class Server
{
	private Request[N] queue;

	private int queueStart;

	private int queueEnd;

	private int queueSize;

	private long currentTime;

	public this(int queueSize)
	{
		this.queueSize = queueSize;
	}

	private void processUpTo(long time)
	{
		while (currentTime <= time && queueEnd > queueStart) {
			currentTime += queue[queueStart].executionTime;
			queue[queueStart].readyTime = currentTime;
			queueStart++;
		}
	}

	void enqueue(Request request)
	{
		processUpTo(request.arrivalTime);
		if (queueEnd - queueStart >= queueSize) {
			request.readyTime = -1;
		}
		else {
			currentTime = max(currentTime, request.arrivalTime);
			queue[queueEnd] = request;
			queueEnd++;
		}
	}

	void finish()
	{
		processUpTo(long.max);
	}
}

void main()
{
	int nRequests;
	int queueSize;

	readf("%d %d", &nRequests, &queueSize);

	Server s = new Server(queueSize);
	Request[] requests = new Request[](nRequests);
	for (int i = 0; i < nRequests; i++) {
		Request r = new Request();

		readf(" %d %d", &r.arrivalTime, &r.executionTime);
		requests[i] = r;

		s.enqueue(r);
	}
	s.finish();

	for (int i = 0; i < nRequests; i++) {
		writef("%d", requests[i].readyTime);
		writef(i < nRequests - 1 ? " " : "\n");
	}
}

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

void main ()
{
	int n;
	int b;
	while (readf (" %s %s", &n, &b) > 0)
	{
		alias Query = Tuple !(long, q{t}, int, q{d});
		auto q = new Query [n];
		foreach (ref r; q)
		{
			readf (" %s %s", &r.t, &r.d);
		}
		q ~= Query (long.max, int.max);

		auto a = new long [n];
		int [] s;
		long c = 0;
		foreach (i; 0..n + 1)
		{
			while (!s.empty && c <= q[i].t)
			{
				int k = s.front;
				s.popFront ();
				s.assumeSafeAppend ();
				c += q[k].d;
				a[k] = c;
			}
			c = max (c, q[i].t);

			if (s.length >= b)
			{
				a[i] = -1;
			}
			else
			{
				s ~= i;
			}
		}
		writefln ("%(%s %)", a);
	}
}

import std.stdio;
import std.algorithm;

const int N = 200000;

class Request
{
	int arrivalTime;
	int executionTime;
	int readyTime;
}

class Server
{
	private Request[N] queue;

	private int queueStart;

	private int queueEnd;

	private int queueSize;

	private int currentTime;

	public this(int queueSize)
	{
		this.queueSize = queueSize;
	}

	private void processUpTo(int time)
	{
		while (currentTime <= time && queueEnd > queueStart) {
			currentTime += queue[queueStart].executionTime;
			queue[queueStart].readyTime = currentTime;
			queueStart++;
		}
	}

	void enqueue(Request request)
	{
		processUpTo(request.arrivalTime);
		if (queueEnd - queueStart >= queueSize) {
			request.readyTime = -1;
		}
		else {
			currentTime = max(currentTime, request.arrivalTime);
			queue[queueEnd] = request;
			queueEnd++;
		}
	}

	void finish()
	{
		processUpTo(int.max);
	}
}

void main()
{
	int nRequests;
	int queueSize;

	readf("%d %d", &nRequests, &queueSize);

	Server s = new Server(queueSize);
	Request[] requests = new Request[](nRequests);
	for (int i = 0; i < nRequests; i++) {
		Request r = new Request();

		readf(" %d %d", &r.arrivalTime, &r.executionTime);
		requests[i] = r;

		s.enqueue(r);
	}
	s.finish();

	for (int i = 0; i < nRequests; i++) {
		writef("%d", requests[i].readyTime);
		writef(i < nRequests - 1 ? " " : "\n");
	}
}


John Doe offered his sister Jane Doe find the gcd of some set of numbers a.Gcd is a positive integer g, such that all number from the set are evenly divisible by g and there isn't such g' (g' > g), that all numbers of the set are evenly divisible by g'.Unfortunately Jane couldn't cope with the task and John offered her to find the ghd of the same subset of numbers.Ghd is a positive integer g, such that at least half of numbers from the set are evenly divisible by g and there isn't such g' (g' > g) that at least half of the numbers from the set are evenly divisible by g'.Jane coped with the task for two hours. Please try it, too.

The first line contains an integer n (1 ≤ n ≤ 106) showing how many numbers are in set a. The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1012). Please note, that given set can contain equal numbers. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the %I64d specifier.

Print a single integer g — the Ghd of set a.

import std.stdio, std.conv, std.string, std.algorithm, std.range;
import std.datetime, std.numeric, std.random;

int main() {
    StopWatch sw;
    sw.start();
    auto gen = Random(unpredictableSeed);
    int n;
    readf("%d\n", &n);
    auto a = readln().split().map!(to!long).array;
    auto b = new long[20000];
    auto num = new int[20000];
    auto res = 0L;
    auto loop = 0L;
    while (sw.peek().msecs < 3000 && loop < 20) {
        loop += 1;
        auto k = a[uniform(0, n, gen)];
        b.length = 20000;
        //b.length = 0;
        auto id = 0;
        for (auto i = 1L; i*i <= k; i++) {
            if (!(k%i)) {
                b[id++] = i;
//                b ~= i;
                if (i*i != k) {
                    b[id++] = k/i;
//                    b ~= k/i;
                }
            }
        }
        b.length = id;

        b.sort;
        num.length = b.length;
        num[] = 0;
        foreach (int i, d; a) {
            auto dd = gcd(d, k);
            num[assumeSorted(b).lowerBound(dd).length]++;
        }
        foreach_reverse (i; 0..b.length) {
            if (b[i] <= res) break;
            auto count = 0;
            foreach (j; i..b.length) {
                if (!(b[j]%b[i])) {
                    count += num[j];
                }
            }
            if (count >= (n+1)/2) {
                res = max(res, b[i]);
            }
        }
    }
    writeln(res);
    return 0;
}

import std.stdio, std.conv, std.string, std.algorithm, std.range;
import std.datetime, std.numeric, std.random;

int main() {
    StopWatch sw;
    sw.start();
    auto gen = Random(unpredictableSeed);
    int n;
    readf("%d\n", &n);
    auto a = readln().split().map!(to!long).array;
    auto b = new long[n];
    auto num = new int[n];
    auto res = 0L;
    auto loop = 0L;
    while (sw.peek().msecs < 3000 && loop < 30) {
        loop += 1;
        auto k = a[uniform(0, n, gen)];
        foreach (int i, d; a) {
            b[i] = gcd(d, k);
        }
        auto c = assumeSorted(b.dup.sort.uniq().array);
        num.length = c.length;
        num[] = 0;
        foreach (d; b) {
            num[c.lowerBound(d).length]++;
        }
        foreach_reverse (i; 0..c.length) {
            if (c[i] <= res) break;
            auto count = 0;
            foreach (j; i..c.length) {
                if (!(c[j]%c[i])) {
                    count += num[j];
                }
            }
            if (count >= (n+1)/2) {
                res = max(res, c[i]);
            }
        }
    }
    writeln(res);
    return 0;
}

import std.stdio, std.conv, std.string, std.algorithm, std.range;
import std.datetime, std.numeric, std.random;

int main() {
    StopWatch sw;
    sw.start();
    auto gen = Random(unpredictableSeed);
    int n;
    readf("%d\n", &n);
    auto a = readln().split().map!(to!long).array;
    auto b = new long[n];
    auto res = 0L;
    while (sw.peek().msecs < 3000) {
        auto k = a[uniform(0, n, gen)];
        foreach (int i, d; a) {
            b[i] = gcd(d, k);
        }
        auto c = assumeSorted(b.dup.sort.uniq().array);
        auto num = new int[c.length];
        foreach (d; b) {
            num[c.lowerBound(d).length]++;
        }
        foreach (i; 0..c.length) {
            auto count = 0;
            foreach (j; i..c.length) {
                if (!(c[j]%c[i])) {
                    count += num[j];
                }
            }
            if (count >= (n+1)/2) {
                res = max(res, c[i]);
            }
        }
    }
    writeln(res);
    return 0;
}

import std.stdio, std.conv, std.string, std.algorithm, std.range;
import std.datetime, std.numeric, std.random;

int main() {
    StopWatch sw;
    sw.start();
    auto gen = Random(unpredictableSeed);
    int n;
    readf("%d\n", &n);
    auto a = readln().split().map!(to!long).array;
    auto b = new long[n];
    auto num = new int[n];
    auto res = 0L;
    auto loop = 0L;
    while (sw.peek().msecs < 3000 && loop < 30) {
        loop++;
        auto k = a[uniform(0, n, gen)];
        foreach (int i, d; a) {
            b[i] = gcd(d, k);
        }
        auto c = assumeSorted(b.dup.sort.uniq().array);
        num.length = c.length;
        num[] = 0;
        foreach (d; b) {
            num[c.lowerBound(d).length]++;
        }
        foreach_reverse (i; 0..c.length) {
            auto count = 0;
            foreach (j; i..c.length) {
                if (!(c[j]%c[i])) {
                    count += num[j];
                }
            }
            if (count >= (n+1)/2) {
                res = max(res, c[i]);
                break;
            }
        }
    }
    writeln(res);
    return 0;
}

import std.stdio, std.conv, std.string, std.algorithm, std.range;
import std.datetime, std.numeric, std.random;

int main() {
    StopWatch sw;
    sw.start();
    auto gen = Random(unpredictableSeed);
    int n;
    readf("%d\n", &n);
    auto a = readln().split().map!(to!long).array;
    auto b = new long[n];
    auto num = new int[n];
    auto res = 0L;
    auto loop = 0L;
    while (sw.peek().msecs < 3000 && loop < 30) {
        loop += 1;
        auto k = a[uniform(0, n, gen)];
        foreach (int i, d; a) {
            b[i] = gcd(d, k);
        }
        auto c = assumeSorted(b.dup.sort.uniq().array);
        num.length = c.length;
        num[] = 0;
        foreach (d; b) {
            num[c.lowerBound(d).length]++;
        }
        foreach_reverse (i; 0..c.length) {
            auto count = 0;
            foreach (j; i..c.length) {
                if (!(c[j]%c[i])) {
                    count += num[j];
                }
            }
            if (count >= (n+1)/2) {
                res = max(res, c[i]);
                break;
            }
        }
    }
    writeln(res);
    return 0;
}

import std.stdio, std.conv, std.string, std.algorithm, std.range;
import std.datetime, std.numeric, std.random;

int main() {
    StopWatch sw;
    sw.start();
    auto gen = Random(unpredictableSeed);
    int n;
    readf("%d\n", &n);
    auto a = readln().split().map!(to!long).array;
    auto b = new long[n];
    auto num = new int[n];
    auto res = 0L;
    auto loop = 0L;
    while (sw.peek().msecs < 3400 && loop < 30) {
        loop += 1;
        auto k = a[uniform(0, n, gen)];
        foreach (int i, d; a) {
            b[i] = gcd(d, k);
        }
        auto c = assumeSorted(b.dup.sort.uniq().array);
        num.length = c.length;
        num[] = 0;
        foreach (d; b) {
            num[c.lowerBound(d).length]++;
        }
        foreach_reverse (i; 0..c.length) {
            if (c[i] <= res) break;
            auto count = 0;
            foreach (j; i..c.length) {
                if (!(c[j]%c[i])) {
                    count += num[j];
                }
            }
            if (count >= (n+1)/2) {
                res = max(res, c[i]);
            }
        }
    }
    writeln(res);
    return 0;
}


You're given an array of $$$n$$$ integers between $$$0$$$ and $$$n$$$ inclusive.In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).For example, if the current array is $$$[0, 2, 2, 1, 4]$$$, you can choose the second element and replace it by the MEX of the present elements  — $$$3$$$. Array will become $$$[0, 3, 2, 1, 4]$$$.You must make the array non-decreasing, using at most $$$2n$$$ operations.It can be proven that it is always possible. Please note that you do not have to minimize the number of operations. If there are many solutions, you can print any of them. –An array $$$b[1 \ldots n]$$$ is non-decreasing if and only if $$$b_1 \le b_2 \le \ldots \le b_n$$$.The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:  The MEX of $$$[2, 2, 1]$$$ is $$$0$$$, because $$$0$$$ does not belong to the array.  The MEX of $$$[3, 1, 0, 1]$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the array, but $$$2$$$ does not.  The MEX of $$$[0, 3, 1, 2]$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the array, but $$$4$$$ does not. It's worth mentioning that the MEX of an array of length $$$n$$$ is always between $$$0$$$ and $$$n$$$ inclusive.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 1000$$$) — length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$0 \le a_i \le n$$$) — elements of the array. Note that they don't have to be distinct. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$1000$$$.

For each test case, you must output two lines: The first line must contain a single integer $$$k$$$ ($$$0 \le k \le 2n$$$)  — the number of operations you perform. The second line must contain $$$k$$$ integers $$$x_1, \ldots, x_k$$$ ($$$1 \le x_i \le n$$$), where $$$x_i$$$ is the index chosen for the $$$i$$$-th operation. If there are many solutions, you can find any of them. Please remember that it is not required to minimize $$$k$$$.

NoteIn the first test case, the array is already non-decreasing ($$$2 \le 2 \le 3$$$).Explanation of the second test case (the element modified by each operation is colored in red):   $$$a = [2, 1, 0]$$$ ; the initial MEX is $$$3$$$.  $$$a = [2, 1, \color{red}{3}]$$$ ; the new MEX is $$$0$$$.  $$$a = [\color{red}{0}, 1, 3]$$$ ; the new MEX is $$$2$$$.  The final array is non-decreasing: $$$0 \le 1 \le 3$$$. Explanation of the third test case:   $$$a = [0, 7, 3, 1, 3, 7, 7]$$$ ; the initial MEX is $$$2$$$.  $$$a = [0, \color{red}{2}, 3, 1, 3, 7, 7]$$$ ; the new MEX is $$$4$$$.  $$$a = [0, 2, 3, 1, \color{red}{4}, 7, 7]$$$ ; the new MEX is $$$5$$$.  $$$a = [0, 2, 3, 1, \color{red}{5}, 7, 7]$$$ ; the new MEX is $$$4$$$.  $$$a = [0, 2, 3, \color{red}{4}, 5, 7, 7]$$$ ; the new MEX is $$$1$$$.  The final array is non-decreasing: $$$0 \le 2 \le 3 \le 4 \le 5 \le 7 \le 7$$$.

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

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

		int mex (int [] a)
		{
			auto b = new bool [n + 1];
			foreach (i; 0..n)
			{
				b[a[i]] = true;
			}
			int res = 0;
			while (b[res])
			{
				res += 1;
			}
			return res;
		}

		int [] answer;
		while (!equal (a, n.iota))
		{
			auto v = mex (a);

			void set (int pos)
			{
				answer ~= pos + 1;
				a[pos] = v;
			}
			if (v < n)
			{
				set (v);
			}
			else
			{
				int pos = 0;
				while (a[pos] == pos)
				{
					pos += 1;
				}
				set (pos);
			}
		}
		writeln (answer.length);
		writefln !("%(%s %)") (answer);
	}
}

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

        int[] ans;
        auto as = A.dup;
        for (; ; ) {
          auto app = new bool[N];
          foreach (i; 0 .. N) {
            if (as[i] < N) {
              app[as[i]] = true;
            }
          }
          int x;
          for (x = 0; x < N; ++x) {
            if (!app[x]) {
              break;
            }
          }
          if (x == N) {
            int im = -1;
            foreach (i; 0 .. N) {
              if (as[i] != i) {
                if (im == -1 || as[im] > as[i]) {
                  im = i;
                }
              }
            }
            if (im == -1) {
              break;
            }
            ans ~= im;
            as[im] = x;
          } else {
            ans ~= x % N;
            as[x % N] = x;
          }
          debug {
            writeln("as = ", as);
          }
        }

        writeln(ans.length);
        foreach (h, i; ans) {
          if (h > 0) write(" ");
          write(i + 1);
        }
        writeln;
      }
    }
  } 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 a = RDA!int;

		BinaryHeap!(Array!int, "a > b") heap;
		foreach (i; 0..n)
		{
			heap.insert(a[i]);
		}

		int i;
		while (true)
		{
			int[] tmp;
			int x;
			while (!heap.empty)
			{
				x = heap.front; heap.removeFront;
				tmp ~= x;
				debug writeln("i:", i, " ", "x:", x, " ", tmp);
				debug writeln(a);
				if (x > i) break;
				i = x+1;
			}
			int ii = -1;
			if (i == n || tmp.empty)
			{
				bool ok = true;
				foreach_reverse (j; 0..n)
				{
					if (a[j] != j)
					{
						i = j;
						ii = n;
						ok = false;
						break;
					}
				}
				if (ok)
				{
					break;
				}
			}

			auto y = a[i];
			if (ii != -1)
			{
				a[i] = ii;
				heap.insert(ii);
			}
			else
			{
				a[i] = i;
				heap.insert(i);
			}
			ans[ti] ~= i+1;
			i = min(i+1, y);

			BinaryHeap!(Array!int, "a > b") nHeap;
			bool done;
			foreach (e; tmp)
			{
				if (!done)
				{
					if (e == y)
					{
						done = true;
						continue;
					}
				}
				nHeap.insert(e);
			}
			while (!heap.empty)
			{
				auto z = heap.front; heap.removeFront;
				if (!done)
				{
					if (z == y)
					{
						done = true;
						continue;
					}
				}
				nHeap.insert(z);
			}
			heap = nHeap;
		}
	}

	foreach (e; ans)
	{
		writeln(e.length);
		e.map!(to!string).join(" ").writeln;
	}
	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();
        auto A = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt();
        }

        auto ans = new int[N + 1];
        auto as = A.dup;
        foreach (h; 0 .. N + 1) {
          auto app = new bool[N + 1];
          foreach (i; 0 .. N) {
            if (as[i] <= N) {
              app[as[i]] = true;
            }
          }
          foreach (x; 0 .. N + 1) {
            if (!app[x]) {
              ans ~= x % N;
              as[x % N] = x;
              break;
            }
          }
          debug {
            writeln("as = ", as);
          }
        }

        writeln(ans.length);
        foreach (h, i; ans) {
          if (h > 0) write(" ");
          write(i + 1);
        }
        writeln;
      }
    }
  } 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();
        auto A = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt();
        }

        auto ans = new int[N + 1];
        auto as = A.dup;
        foreach (h; 0 .. 2 * N) {
          auto app = new bool[N];
          foreach (i; 0 .. N) {
            if (as[i] < N) {
              app[as[i]] = true;
            }
          }
          int x;
          for (x = 0; x < N; ++x) {
            if (!app[x]) {
              break;
            }
          }
          if (x == N) {
            bool found;
            foreach (i; 0 .. N) {
              if (as[i] != i) {
                found = true;
                ans ~= i;
                as[i] = x;
                break;
              }
            }
            if (!found) {
              break;
            }
          } else {
            ans ~= x % N;
            as[x % N] = x;
          }
          debug {
            writeln("as = ", as);
          }
        }

        writeln(ans.length);
        foreach (h, i; ans) {
          if (h > 0) write(" ");
          write(i + 1);
        }
        writeln;
      }
    }
  } 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 a = RDA!int;

		BinaryHeap!(Array!int, "a > b") heap;
		foreach (i; 0..n)
		{
			heap.insert(a[i]);
		}

		int i;
		while (true)
		{
			int[] tmp;
			int x;
			while (!heap.empty)
			{
				x = heap.front; heap.removeFront;
				tmp ~= x;
				debug writeln("i:", i, " ", "x:", x, " ", tmp);
				debug writeln(a);
				if (x > i) break;
				i = x+1;
			}
			if (i == n || tmp.empty)
			{
				bool ok = true;
				foreach_reverse (j; 0..n)
				{
					if (a[j] != j)
					{
						i = j;
						ok = false;
						break;
					}
				}
				if (ok)
				{
					break;
				}
			}

			auto y = a[i];
			a[i] = i;
			ans[ti] ~= i+1;
			heap.insert(i);
			i = min(i+1, y);

			BinaryHeap!(Array!int, "a > b") nHeap;
			bool done;
			foreach (e; tmp)
			{
				if (!done)
				{
					if (e == y)
					{
						done = true;
						continue;
					}
				}
				nHeap.insert(e);
			}
			while (!heap.empty)
			{
				auto z = heap.front; heap.removeFront;
				if (!done)
				{
					if (z == y)
					{
						done = true;
						continue;
					}
				}
				nHeap.insert(z);
			}
			heap = nHeap;
		}
	}

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


You are given a string $$$s$$$ of length $$$n$$$ consisting of characters a and/or b.Let $$$\operatorname{AB}(s)$$$ be the number of occurrences of string ab in $$$s$$$ as a substring. Analogically, $$$\operatorname{BA}(s)$$$ is the number of occurrences of ba in $$$s$$$ as a substring.In one step, you can choose any index $$$i$$$ and replace $$$s_i$$$ with character a or b.What is the minimum number of steps you need to make to achieve $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$?Reminder:The number of occurrences of string $$$d$$$ in $$$s$$$ as substring is the number of indices $$$i$$$ ($$$1 \le i \le |s| - |d| + 1$$$) such that substring $$$s_i s_{i + 1} \dots s_{i + |d| - 1}$$$ is equal to $$$d$$$. For example, $$$\operatorname{AB}($$$aabbbabaa$$$) = 2$$$ since there are two indices $$$i$$$: $$$i = 2$$$ where aabbbabaa and $$$i = 6$$$ where aabbbabaa.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first and only line of each test case contains a single string $$$s$$$ ($$$1 \le |s| \le 100$$$, where $$$|s|$$$ is the length of the string $$$s$$$), consisting only of characters a and/or b.

For each test case, print the resulting string $$$s$$$ with $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$ you'll get making the minimum number of steps. If there are multiple answers, print any of them.

NoteIn the first test case, both $$$\operatorname{AB}(s) = 0$$$ and $$$\operatorname{BA}(s) = 0$$$ (there are no occurrences of ab (ba) in b), so can leave $$$s$$$ untouched.In the second test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 2$$$, so you can leave $$$s$$$ untouched. In the third test case, $$$\operatorname{AB}(s) = 1$$$ and $$$\operatorname{BA}(s) = 0$$$. For example, we can change $$$s_1$$$ to b and make both values zero.In the fourth test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 1$$$. For example, we can change $$$s_6$$$ to a and make both values equal to $$$1$$$.

immutable multi = true;

void solve(int tc)
{
	auto s = readString;
	int i = 0;
	int blocks = 0;
	int minLength = int.max;
	while (i < s.length)
	{
		blocks ^= 1;
		char ch = s[i];
		int len = 0;
		while (i < s.length && s[i] == ch) { i++; len++; }
		minLength = min(len, minLength);
	}
	if (blocks) return writeln(s);
	write(s[0] == 'a'? 'b' : 'a');
	writeln(s[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;
// }}}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip.dup;
		auto n = s.length.to !(int);
		string res;
		foreach (i; 0..n + 1)
		{
			if (i < n)
			{
				s[i] ^= 3;
			}
			if (s.count ("ab") == s.count ("ba"))
			{
				res = s.idup;
			}
			if (i < n)
			{
				s[i] ^= 3;
			}
		}
		writeln (res);
	}
}

immutable multi = true;

void solve(int tc)
{
	auto s = readString;
	int i = 0;
	int blocks = 0;
	int minLength = int.max;
	while (i < s.length)
	{
		blocks ^= 1;
		char ch = s[i];
		int len = 0;
		while (i < s.length && s[i] == ch) { i++; len++; }
		minLength = min(len, minLength);
	}
	if (blocks) return writeln(s);
	i = 0;
	while (i < s.length)
	{
		char ch = s[i];
		int len = 0;
		while (i < s.length && s[i] == ch) { i++; len++; }
		if (len == minLength)
		{
			char otherCh = ch == 'a'? 'b' : 'a';
			foreach(_; 0 .. len) write(otherCh);
			minLength = int.max;
		}
		else
		{
			foreach(_; 0 .. len) write(ch);
		}
	}
	writeln;
}

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

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

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

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

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


Madeline has an array $$$a$$$ of $$$n$$$ integers. A pair $$$(u, v)$$$ of integers forms an inversion in $$$a$$$ if:  $$$1 \le u < v \le n$$$.  $$$a_u > a_v$$$. Madeline recently found a magical paper, which allows her to write two indices $$$u$$$ and $$$v$$$ and swap the values $$$a_u$$$ and $$$a_v$$$. Being bored, she decided to write a list of pairs $$$(u_i, v_i)$$$ with the following conditions:  all the pairs in the list are distinct and form an inversion in $$$a$$$.  all the pairs that form an inversion in $$$a$$$ are in the list.  Starting from the given array, if you swap the values at indices $$$u_1$$$ and $$$v_1$$$, then the values at indices $$$u_2$$$ and $$$v_2$$$ and so on, then after all pairs are processed, the array $$$a$$$ will be sorted in non-decreasing order. Construct such a list or determine that no such list exists. If there are multiple possible answers, you may find any of them.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the length of the array. Next line contains $$$n$$$ integers $$$a_1,a_2,...,a_n$$$ $$$(1 \le a_i \le 10^9)$$$  — elements of the array.

Print -1 if no such list exists. Otherwise in the first line you should print a single integer $$$m$$$ ($$$0 \le m \le \dfrac{n(n-1)}{2}$$$) — number of pairs in the list. The $$$i$$$-th of the following $$$m$$$ lines should contain two integers $$$u_i, v_i$$$ ($$$1 \le u_i < v_i\le n$$$). If there are multiple possible answers, you may find any of them.

NoteIn the first sample test case the array will change in this order $$$[3,1,2] \rightarrow [2,1,3] \rightarrow [1,2,3]$$$.In the second sample test case it will be $$$[1,8,1,6] \rightarrow [1,6,1,8] \rightarrow [1,1,6,8]$$$.In the third sample test case the array is already sorted.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		foreach (i; 0..n)
		{
			a[i] = a[i] * n + i;
		}

		alias Pair = Tuple !(int, q{u}, int, q{v});
		Pair [] answer;
		auto inv = new int [] [n];
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				if (a[i] > a[j])
				{
					inv[i] ~= j;
				}
			}
		}

		void apply (int i, int j)
		{
			answer ~= Pair (i + 1, j + 1);
			swap (a[i], a[j]);
		}

		foreach (i; 0..n)
		{
			inv[i].schwartzSort !(j => a[j]);
			foreach_reverse (j; inv[i])
			{
				apply (i, j);
			}
		}
		debug {writeln (a);}

		writeln (answer.length);
		foreach (p; answer)
		{
			writeln (p.u, " ", p.v);
		}
	}
}

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() {
  /*
  debug {
    foreach (n; 1 .. 5 + 1) {
      auto as = iota(n).array;
      do {
        int[][] invs;
        foreach (i; 0 .. n) foreach (j; i + 1 .. n) {
          if (as[i] > as[j]) {
            invs ~= [i, j];
          }
        }
        const invsLen = cast(int)(invs.length);
        writeln(as);
        bool found;
        auto perm = iota(invsLen).array;
        do {
          auto bs = as.dup;
          foreach (k; 0 .. invsLen) {
            swap(bs[invs[perm[k]][0]], bs[invs[perm[k]][1]]);
          }
          if (bs == iota(n).array) {
            found = true;
            foreach (k; 0 .. invsLen) {
              write(" ", invs[perm[k]]);
            }
            writeln;
          }
        } while (perm.nextPermutation);
        if (!found) {
          writeln("no solution");
        }
      } while (as.nextPermutation);
    }
  }
  //*/

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

      Tuple!(int, int)[] ps;
      foreach (i; 0 .. N) {
        ps ~= tuple(A[i], i);
      }
      ps.sort;
      auto as = new int[N];
      foreach (i; 0 .. N) {
        as[ps[i][1]] = i;
      }
      debug {
        writeln("as = ", as);
      }

      auto poss = new int[N];
      foreach (i; 0 .. N) {
        poss[as[i]] = i;
      }
      int[][] ans;
      foreach (h; 0 .. N - 1) {
        foreach (a; 0 .. N - 1) {
          const i = poss[a];
          const j = poss[a + 1];
          if (i > j) {
            ans ~= [j, i];
            swap(as[i], as[j]);
            swap(poss[a], poss[a + 1]);
          }
        }
      }

      writeln(ans.length);
      foreach (p; ans) {
        writeln(p[0] + 1, " ", p[1] + 1);
      }
    }
  } catch (EOFException e) {
  }
}


Karen just got home from the supermarket, and is getting ready to go to sleep.  After taking a shower and changing into her pajamas, she looked at her shelf and saw an album. Curious, she opened it and saw a trading card collection.She recalled that she used to play with those cards as a child, and, although she is now grown-up, she still wonders a few things about it.Each card has three characteristics: strength, defense and speed. The values of all characteristics of all cards are positive integers. The maximum possible strength any card can have is p, the maximum possible defense is q and the maximum possible speed is r.There are n cards in her collection. The i-th card has a strength ai, defense bi and speed ci, respectively.A card beats another card if at least two of its characteristics are strictly greater than the corresponding characteristics of the other card.She now wonders how many different cards can beat all the cards in her collection. Two cards are considered different if at least one of their characteristics have different values.

The first line of input contains four integers, n, p, q and r (1 ≤ n, p, q, r ≤ 500000), the number of cards in the collection, the maximum possible strength, the maximum possible defense, and the maximum possible speed, respectively. The next n lines each contain three integers. In particular, the i-th line contains ai, bi and ci (1 ≤ ai ≤ p, 1 ≤ bi ≤ q, 1 ≤ ci ≤ r), the strength, defense and speed of the i-th collection card, respectively.

Output a single integer on a line by itself, the number of different cards that can beat all the cards in her collection.

NoteIn the first test case, the maximum possible strength is 4, the maximum possible defense is 4 and the maximum possible speed is 5. Karen has three cards:  The first card has strength 2, defense 2 and speed 5.  The second card has strength 1, defense 3 and speed 4.  The third card has strength 4, defense 1 and speed 1. There are 10 cards that beat all the cards here:  The card with strength 3, defense 3 and speed 5.  The card with strength 3, defense 4 and speed 2.  The card with strength 3, defense 4 and speed 3.  The card with strength 3, defense 4 and speed 4.  The card with strength 3, defense 4 and speed 5.  The card with strength 4, defense 3 and speed 5.  The card with strength 4, defense 4 and speed 2.  The card with strength 4, defense 4 and speed 3.  The card with strength 4, defense 4 and speed 4.  The card with strength 4, defense 4 and speed 5. In the second test case, the maximum possible strength is 10, the maximum possible defense is 10 and the maximum possible speed is 10. Karen has five cards, all with strength 1, defense 1 and speed 1.Any of the 972 cards which have at least two characteristics greater than 1 can beat all of the cards in her collection.

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const P = readInt();
      const Q = readInt();
      const R = readInt();
      auto A = new int[N];
      auto B = new int[N];
      auto C = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
        B[i] = readInt();
        C[i] = readInt();
      }

      auto zs = new long[Q + 1];
      foreach (i; 0 .. N) {
        chmax(zs[B[i]], C[i]);
      }
      foreach_reverse (y; 1 .. Q + 1) {
        chmax(zs[y - 1], zs[y]);
      }
      debug {
        writeln("zs = ", zs);
      }
      auto zsSum = new long[Q + 1 + 1];
      foreach (y; 0 .. Q + 1) {
        zsSum[y + 1] = zsSum[y] + zs[y];
      }

      auto iss = new int[][P + 1];
      foreach (i; 0 .. N) {
        iss[A[i]] ~= i;
      }
      int ym = 0, zm = 0;
      long ans;
      foreach_reverse (x; 1 .. P + 1) {
        foreach (i; iss[x]) {
          chmax(ym, B[i]);
          chmax(zm, C[i]);
        }
        const y0 = max(ym + 1, zs.binarySearch!(z => (z < zm + 1)));
        ans += (1L * (y0 - (ym + 1)) * R) - (zsSum[y0] - zsSum[ym + 1]);
        ans += 1L * ((Q + 1) - y0) * (R - zm);
        debug {
          writeln(x, " ", ym, " ", zm, " ", y0, " ", ans);
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:  a < b < c;  a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has  groups of three.Help Xenia, find the required partition or else say that it doesn't exist.

The first line contains integer n (3 ≤ n ≤ 99999) — the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3.

If the required partition exists, print  groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1.

import std.algorithm;
import std.array;
import std.stdio;

immutable int MAX_K = 8;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int [MAX_K] a;
		foreach (i; 0..n)
		{
			int v;
			readf (" %s", &v);
			a[v]++;
		}
		int [] [] ans;

		void consume (int x, int y, int z)
		{
			while (a[x] > 0)
			{
				if (a[y] == 0 || a[z] == 0)
				{
					break;
				}
				a[x]--;
				a[y]--;
				a[z]--;
				ans ~= [x, y, z].sort.array;
			}
		}

		consume (4, 2, 1);
		consume (3, 6, 1);
		consume (2, 6, 1);
		bool ok = true;
		foreach (c; a)
		{
			if (c > 0)
			{
				ok = false;
			}
		}

		if (ok)
		{
			writefln ("%(%(%s %)\n%)", ans);
		}
		else
		{
			writeln (-1);
		}
	}
}


Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c — one through b and the other one through d, he calls the group a "damn rhombus". Note that pairs (a, b), (b, c), (a, d), (d, c) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below:  Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him.Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city.When rhombi are compared, the order of intersections b and d doesn't matter.

The first line of the input contains a pair of integers n, m (1 ≤ n ≤ 3000, 0 ≤ m ≤ 30000) — the number of intersections and roads, respectively. Next m lines list the roads, one per line. Each of the roads is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi) — the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions. It is not guaranteed that you can get from any intersection to any other one.

Print the required number of "damn rhombi".

import std.stdio;

int[][] roads;

long count_two_step_dfs(int v)
{
	auto visits = new int[](roads.length);
	foreach (next1; roads[v])
		foreach (next2; roads[next1])
		{
			if (v != next2)
				visits[next2] += 1;
		}
	long S;
	foreach (vis; visits)
		S += vis * (vis - 1) / 2;
	return S;
}

void main()
{
	int n, m;
	readf("%s %s\n", &n, &m);
	roads = new int[][](n);
	foreach (_; 0 .. m)
	{
		int ai, bi;
		readf("%s %s\n", &ai, &bi);
		roads[ai - 1] ~= bi - 1;
	}
	long rombs;
	foreach (v; 0 .. n)
	{
		rombs += count_two_step_dfs(v);
	}
	writeln(rombs);
}


Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.

The first line of the input contains a single integer n (3 ≤ n ≤ 100 000). Each of the next n lines contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109). It is guaranteed that no two stars lie at the same point, and there does not exist a line such that all stars lie on that line.

Print three distinct integers on a single line — the indices of the three points that form a triangle that satisfies the conditions stated in the problem. If there are multiple possible answers, you may print any of them.

NoteIn the first sample, we can print the three indices in any order.In the second sample, we have the following picture.   Note that the triangle formed by starts 1, 4 and 3 doesn't satisfy the conditions stated in the problem, as point 5 is not strictly outside of this triangle (it lies on it's border).

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

alias Point = Tuple !(int, q{x}, int, q{y});

long vp (ref Point a, ref Point b, ref Point c)
{
	return (b.x - a.x) * 1L * (c.y - a.y) - (c.x - a.x) * 1L * (b.y - a.y);
}

long sp (ref Point a, ref Point b, ref Point c)
{
	return (b.x - a.x) * 1L * (c.x - a.x) - (b.y - a.y) * 1L * (c.y - a.y);
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new Point [n];
		foreach (ref p; a)
		{
			readf (" %s %s", &p.x, &p.y);
		}

		bool collinear (int i, int j, int k)
		{
			return vp (a[i], a[j], a[k]) == 0;
		}

		bool inside (int i, int j, int k, int r)
		{
			auto vp1 = vp (a[i], a[j], a[r]);
			auto vp2 = vp (a[j], a[k], a[r]);
			auto vp3 = vp (a[k], a[i], a[r]);
			return (vp1 <= 0 && vp2 <= 0 && vp3 <= 0) ||
			       (vp1 >= 0 && vp2 >= 0 && vp3 >= 0);
		}

		auto insides (int i, int j, int k)
		{
			return n.iota.filter !(r => r != i && r != j &&
			    r != k && inside (i, j, k, r));
		}

		int i, j, k;
		do
		{
			i = uniform (0, n);
			j = uniform (0, n);
			k = uniform (0, n);
		}
		while (collinear (i, j, k));

		while (true)
		{
			auto v = insides (i, j, k).array;
			if (v.empty)
			{
				break;
			}
			int r = v[uniform (0, v.length)];
			debug {writeln (i, " ", j, " ", k, " ", r);}
			if (!collinear (i, j, r))
			{
				k = r;
			}
			else if (!collinear (i, r, k))
			{
				j = r;
			}
			else if (!collinear (r, j, k))
			{
				i = r;
			}
			else
			{
				assert (false);
			}
		}

		writeln (i + 1, " ", j + 1, " ", k + 1);
	}
}


The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y).  If the wind blows to the east, the boat will move to (x + 1, y).  If the wind blows to the south, the boat will move to (x, y - 1).  If the wind blows to the west, the boat will move to (x - 1, y).  If the wind blows to the north, the boat will move to (x, y + 1). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (ex, ey)?

The first line contains five integers t, sx, sy, ex, ey (1 ≤ t ≤ 105,  - 109 ≤ sx, sy, ex, ey ≤ 109). The starting location and the ending location will be different. The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).

If they can reach (ex, ey) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).

NoteIn the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.In the second sample, they cannot sail to the destination.

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.mutation;
import std.range;
import std.range.primitives;
import std.conv;

int main() {
    debug stdin = File("in.txt", "r");

    int t, sx, sy, ex, ey;
    readf(" %s %s %s %s %s\n", &t, &sx, &sy, &ex, &ey);
    char c;
    int et = 0;
    foreach ( l; 0 .. t ) {
        readf(" %s", &c);
        if (c == 'N' && ey > sy) {
            ++sy;
        }
        else if (c == 'S' && ey < sy) {
            --sy;
        }
        else if (c == 'E' && ex > sx) {
            ++sx;
        }
        else if (c == 'W' && ex < sx) {
            --sx;
        }
        ++et;
        if (sx == ex && sy == ey) {
            writeln(et);
            return 0;
        }
    }
    writeln("-1");

    return 0;
}

module sigod.codeforces.p298B;

import std.stdio;
import std.string;

private {
	struct Direction
	{
		int l_x = 0;
		int l_y = 0;
		int r_x = 0;
		int r_y = 0;

		ref Direction opOpAssign(string op)(in Direction direction)
			if (op == "+")
		{
			l_x += direction.l_x;
			l_y += direction.l_y;
			r_x += direction.r_x;
			r_y += direction.r_y;

			return this;
		}
	}
}

void main()
{
	int t, sx, sy, ex, ey;
	stdin.readf(" %s %s %s %s %s", &t, &sx, &sy, &ex, &ey);

	string direction;
	stdin.readf(" %s", &direction);
	direction = direction.strip();

	Direction[char] compas;
	compas['E'] = Direction(0, 0, 1, 0);
	compas['S'] = Direction(0, 0, 0, -1);
	compas['W'] = Direction(-1, 0, 0, 0);
	compas['N'] = Direction(0, 1, 0, 0);

	Direction zone = Direction(sx, sy, sx, sy);

	foreach (index, way; direction) {
		zone += compas[way];

		if (zone.l_x <= ex && zone.r_x >= ex
			&& zone.l_y >= ey && zone.r_y <= ey)
		{
			stdout.writeln(index + 1);
			return;
		}
	}

	stdout.writeln("-1");
}


Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 < a_i < 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.

Print the maximum possible beauty of $$$k$$$ shelves in the new office.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;
    auto B = new long[][](N, N);
    foreach (i; 0..N) {
        B[i][i] = A[i];
        foreach (j; i+1..N) B[i][j] = B[i][j-1] + A[j];
    }

    auto mem = new bool[][](N+10, K+10);

    bool dfs(int n, int k, long mask) {
        if (k == 0 && n != N-1) return false;
        if (n >= 0 && mem[n][k]) return false;
        if (k > N - n - 1) return false;
        if (n == N-1) return k == 0;

        int left = n+1;
        foreach (right; n+1..N) {
            if ((B[left][right] & mask) >= mask && dfs(right, k-1, mask))
                return true;
        }

        if (n >= 0) mem[n][k] = true;
        return false;
    }

    long m = 0;

    foreach_reverse (i; 0..60) {
        foreach (j; 0..N+10) mem[j].fill(false);
        if (dfs(-1, K, m | (1L << i))) {
            m |= (1L << i);
        }
    }

    m.writeln;
}

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

long[] arr;

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

    arr = 0 ~ readln.splitter.map!( to!long ).array;

    debug { writeln( arr ); }

    long ans = 0;
    foreach_reverse ( bt; 0..64) {
        long cur = ans | ( 1L << bt );

        auto ok = new bool [] [] ( k+1, n+1 );
        ok.each! ( row => row.fill ( false ) );
        ok[0][0] = true;

        foreach ( gr; 1..k+1 ) {
            foreach ( i; 1..n+1 ) {

                if ( !ok[ gr-1 ][ i-1 ] ) continue;

                long cursum = 0;
                foreach ( j; i..n+1 ) {
                    cursum += arr[ j ];
                    ok[ gr ][ j ] |= ( cursum & cur ) == cur;
                }
            }
        }
        if ( ok[ k ][ n ] ) ans = cur;
    }

    ans.writeln;
}

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

long[] arr;

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

    arr = 0 ~ readln.splitter.map!( to!long ).array;

    debug { writeln( arr ); }

    long ans = 0;
    foreach_reverse ( bt; 0..64) {
        long cur = ans | (1L << bt);

        auto ok = new bool [] [] ( n+1, k+1 );
        foreach ( row; ok ) row.fill ( false );
        ok[0][0] = true;

        foreach ( i; 1..n+1 ) {
            foreach ( gr; 1..k+1 ) {

                if ( !ok[ i-1 ][ gr-1 ] ) continue;

                long cursum = 0;
                foreach ( j; i..n+1 ) {
                    cursum += arr[ j ];
                    ok[ j ][ gr ] |= ( cursum & cur ) == cur;
                }
            }
        }
        if ( ok[ n ][ k ] ) ans = cur;
    }

    ans.writeln;
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(ulong)).array;
		ulong res = 0UL;
		foreach_reverse (b; 0..64)
		{
			auto f = new bool [] [] (n + 1, k + 1);
			f[0][0] = true;
			foreach (i; 0..n)
			{
				foreach (j; 0..k)
				{
					if (f[i][j])
					{
						ulong s = 0UL;
						foreach (r; i..n)
						{
							s += a[r];
							if ((s & res) == res)
							{
								if (s & (1UL << b))
								{
									f[r + 1][j + 1] = true;
								}
							}
						}
					}
				}
			}
			if (f[n][k])
			{
				res |= 1UL << b;
			}
		}
		writeln (res);
	}
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;
    auto B = new long[][](N, N);
    foreach (i; 0..N) {
        B[i][i] = A[i];
        foreach (j; i+1..N) B[i][j] = B[i][j-1] + A[j];
    }

    auto mem = new bool[][](N+10, K+10);

    bool dfs(int n, int k, long mask) {
        if (k == 0 && n != N-1) return false;
        if (n >= 0 && mem[n][k]) return false;
        if (k > N - n - 1) return false;
        if (n == N-1) return k == 0;

        int left = n+1;
        foreach (right; n+1..N) {
            if ((B[left][right] & mask) >= mask && dfs(right, k-1, mask))
                return true;
        }

        if (n >= 0) mem[n][k] = true;
        return false;
    }

    long m = 0;

    foreach_reverse (i; 0..55) {
        foreach (j; 0..N+10) mem[j].fill(false);
        if (dfs(-1, K, m | (1L << i))) {
            m |= (1L << i);
        }
    }

    m.writeln;
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;
    auto B = new long[][](N, N);
    foreach (i; 0..N) {
        B[i][i] = A[i];
        foreach (j; i+1..N) B[i][j] = B[i][j-1] + A[j];
    }

    auto mem = new bool[][](N+10, K+10);

    bool dfs(int n, int k, long mask) {
        if (k == 0 && n != N-1) return false;
        if (n >= 0 && mem[n][k]) return false;
        if (k > N - n - 1) return false;
        if (n == N-1) return k == 0;

        int left = n+1;
        foreach (right; n+1..N) {
            if ((B[left][right] & mask) >= mask && dfs(right, k-1, mask))
                return true;
        }

        if (n >= 0) mem[n][k] = true;
        return false;
    }

    long m = 0;

    foreach_reverse (i; 0..51) {
        foreach (j; 0..N+1) mem[j].fill(false);
        if (dfs(-1, K, m | (1L << i))) {
            m |= (1L << i);
        }
    }

    m.writeln;
}


Xenia the vigorous detective faced n (n ≥ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x - 1 or x + 1 (if x = 1 or x = n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step ti (steps are numbered from 1) Xenia watches spies numbers li, li + 1, li + 2, ..., ri (1 ≤ li ≤ ri ≤ n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps).

The first line contains four integers n, m, s and f (1 ≤ n, m ≤ 105; 1 ≤ s, f ≤ n; s ≠ f; n ≥ 2). Each of the following m lines contains three integers ti, li, ri (1 ≤ ti ≤ 109, 1 ≤ li ≤ ri ≤ n). It is guaranteed that t1 < t2 < t3 < ... < tm.

Print k characters in a line: the i-th character in the line must represent the spies' actions on step i. If on step i the spy with the note must pass the note to the spy with a lesser number, the i-th character should equal "L". If on step i the spy with the note must pass it to the spy with a larger number, the i-th character must equal "R". If the spy must keep the note at the i-th step, the i-th character must equal "X". As a result of applying the printed sequence of actions spy s must pass the note to spy f. The number of printed characters k must be as small as possible. Xenia must not catch the spies passing the note. If there are miltiple optimal solutions, you can print any of them. It is guaranteed that the answer exists.

import std.stdio;
import std.typecons;

void main ()
{
	int n, m, s, f;
	while (readf (" %s %s %s %s", &n, &m, &s, &f) > 0)
	{
		alias Tuple !(int, "l", int, "r") event;
		event [int] a;
		foreach (i; 0..m)
		{
			event c;
			int t;
			readf (" %s %s %s", &t, &c.l, &c.r);
			a[t] = c;
		}
		int d = (s < f) ? +1 : -1;
		string res;
		for (int c = 1; s != f; c++)
		{
			if (c in a &&
			    ((a[c].l <= s + 0 && s + 0 <= a[c].r) ||
			     (a[c].l <= s + d && s + d <= a[c].r)))
			{
				res ~= 'X';
			}
			else if (s < f)
			{
				res ~= 'R';
				s++;
			}
			else
			{
				res ~= 'L';
				s--;
			}
		}
		writeln (res);
	}
}


Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.

The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array.  The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.

Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).

import std.stdio : readln, writeln, chomp;
import std.string : split;
import std.conv : to;

void main()
{
    int n = readln().chomp().to!int();
    int[] a = new int[n];
    string[] str = readln().split;
    foreach(i, s; str){
        a[i] = str[i].to!int();
    }
    int m = readln().chomp().to!int();
    int[] b = new int[m];
    str = readln().split;
    foreach(i, s; str){
        b[i] = str[i].to!int();
    }
    ulong V = 0;
    ulong S = 0;
/+
    foreach(i; b){
        foreach(j; a){
            ++V;
            if(i==j){
                break;
            }
        }
        foreach_reverse(j; a){
            ++S;
            if(i==j){
                break;
            }
        }
    }
+/
    int[int] Vmap;
    int[int] Smap;
    int index = 0;
    foreach(d; a){
        Vmap[d] = ++index;
    }
    index = 0;
    foreach_reverse(d; a){
        Smap[d] = ++index;
    }
    foreach(d; b){
        V+=Vmap[d];
        S+=Smap[d];
    }
    writeln(V, " ", S);
}

import std.stdio : readln, writeln, chomp;
import std.string : split;
import std.conv : to;

void main()
{
    int n = readln().chomp().to!int();
    int[] a = new int[n];
    string[] str = readln().split;
    foreach(i, s; str){
        a[i] = str[i].to!int();
    }
    int m = readln().chomp().to!int();
    int[] b = new int[m];
    str = readln().split;
    foreach(i, s; str){
        b[i] = str[i].to!int();
    }
    int V = 0;
    int S = 0;
/+
    foreach(i; b){
        foreach(j; a){
            ++V;
            if(i==j){
                break;
            }
        }
        foreach_reverse(j; a){
            ++S;
            if(i==j){
                break;
            }
        }
    }
+/
    int[int] Vmap;
    int[int] Smap;
    int index = 0;
    foreach(d; a){
        Vmap[d] = ++index;
    }
    index = 0;
    foreach_reverse(d; a){
        Smap[d] = ++index;
    }
    foreach(d; b){
        V+=Vmap[d];
        S+=Smap[d];
    }
    writeln(V, " ", S);
}


Berland Music is a music streaming service built specifically to support Berland local artist. Its developers are currently working on a song recommendation module.So imagine Monocarp got recommended $$$n$$$ songs, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th song had its predicted rating equal to $$$p_i$$$, where $$$1 \le p_i \le n$$$ and every integer from $$$1$$$ to $$$n$$$ appears exactly once. In other words, $$$p$$$ is a permutation.After listening to each of them, Monocarp pressed either a like or a dislike button. Let his vote sequence be represented with a string $$$s$$$, such that $$$s_i=0$$$ means that he disliked the $$$i$$$-th song, and $$$s_i=1$$$ means that he liked it.Now the service has to re-evaluate the song ratings in such a way that:  the new ratings $$$q_1, q_2, \dots, q_n$$$ still form a permutation ($$$1 \le q_i \le n$$$; each integer from $$$1$$$ to $$$n$$$ appears exactly once);  every song that Monocarp liked should have a greater rating than every song that Monocarp disliked (formally, for all $$$i, j$$$ such that $$$s_i=1$$$ and $$$s_j=0$$$, $$$q_i>q_j$$$ should hold). Among all valid permutations $$$q$$$ find the one that has the smallest value of $$$\sum\limits_{i=1}^n |p_i-q_i|$$$, where $$$|x|$$$ is an absolute value of $$$x$$$.Print the permutation $$$q_1, q_2, \dots, q_n$$$. If there are multiple answers, you can print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of songs. The second line of each testcase contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the permutation of the predicted ratings. The third line contains a single string $$$s$$$, consisting of $$$n$$$ characters. Each character is either a $$$0$$$ or a $$$1$$$. $$$0$$$ means that Monocarp disliked the song, and $$$1$$$ means that he liked it. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a permutation $$$q$$$ — the re-evaluated ratings of the songs. If there are multiple answers such that $$$\sum\limits_{i=1}^n |p_i-q_i|$$$ is minimum possible, you can print any of them.

NoteIn the first testcase, there exists only one permutation $$$q$$$ such that each liked song is rating higher than each disliked song: song $$$1$$$ gets rating $$$2$$$ and song $$$2$$$ gets rating $$$1$$$. $$$\sum\limits_{i=1}^n |p_i-q_i|=|1-2|+|2-1|=2$$$.In the second testcase, Monocarp liked all songs, so all permutations could work. The permutation with the minimum sum of absolute differences is the permutation equal to $$$p$$$. Its cost is $$$0$$$.

void main() { runSolver(); }

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

  auto solve() {
    foreach(_; 0..QN) {
      auto N = scan!long;
      auto P = scan!long(N);
      auto S = scan;

      long[] likes, dislikes;
      foreach(i, p; P) if (S[i] == '1') likes ~= p; else dislikes ~= p;

      likes = likes.compress;
      dislikes = dislikes.compress;
      const dl = dislikes.length;

      long[] ans;
      uint l, d;
      foreach(c; S) {
        if (c == '0') ans ~= dislikes[d++] + 1;
        if (c == '1') ans ~= likes[l++] + 1 + dl;
      }

      ans.toAnswerString.writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

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

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    auto s = readln.strip.split("").map!(to!int).array;
    auto ans = iota(n).map!(x => tuple(a[x], s[x], x)).array.sort!((x, y) => x[1] == y[1] ? x[0] < y[0] : x[1] < y[1], SwapStrategy.stable).map!(x => x[2]);
    auto ans2 = iota(n).array;
    foreach (i ; 0 .. n)
      ans2[ans[i]] = i + 1;
    writeln(ans2.map!text.join(" "));
  }
}

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

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

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

void main() {
  int T;
  read(T);
  while (T--) {
    int n;
    read(n);
    auto arr = list!int;
    string s = readln;

    int[] good, bad;
    foreach (i; 0 .. n) {
      if (s[i] == '1') good ~= arr[i];
      else bad ~= arr[i];
    }

    sort(good);
    sort(bad);

    int p = n;

    int[int] m;

    foreach (A; [good, bad]) {
      while (!A.empty) {
        m[A.back] = p--;
        A.popBack;
      }
    }

    foreach (i; 0 .. n) {
      writef("%d ", m[arr[i]]);
    }
    writeln;
  }
}

import std;

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

    foreach (test_index; 0 .. test) {
        int n;
        readf("%s\n", n);

        int[] p = new int[n];
        string s;

        foreach (i; 0 .. n)
            readf(" %s", p[i]);
        readf!"\n";
        s = readln()[0 .. $ - 1];

        int[] liked;
        int[] disliked;
        foreach (int i, c; s)
            if (c == '0')
                disliked ~= i;
            else
                liked ~= i;

        auto likedV = liked
            .map!(i => tuple(p[i], i))
            .array
            .sort;

        auto dislikedV = disliked
            .map!(i => tuple(p[i], i))
            .array
            .sort;

        //stderr.writeln(likedV, '\n', dislikedV);

        int rating = 1;
        foreach (t; dislikedV) {
            p[t[1]] = rating ++;
        }
        foreach (t; likedV)
            p[t[1]] = rating ++;
        assert(rating == n + 1);
        writefln!"%(%s %)"(p);
    }
}
// ""

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    auto s = readln.strip.split("").map!(to!int).array;
    auto ans = iota(n).map!(x => tuple(a[x], s[x], x)).array.sort!((x, y) => x[1] == y[1] ? x[0] < y[0] : x[1] < y[1]).map!(x => x[2] + 1);
    writeln(ans.map!text.join(" "));
  }
}


John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$) — the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$.

Print the rank of Thomas Smith. Thomas's id is $$$1$$$.

NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$.

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp.to!int;
    auto A = N.iota.map!(i => readln.split.map!(to!int).array ~ i).array;
    A.sort!"a.sum-a[4] == b.sum-b[4] ? a[4] < b[4] : a.sum-a[4] > b.sum-b[4]";

    foreach (i; 0..N) {
        if (A[i][4] == 0) {
            writeln(i+1);
        }
    }
}

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;
    readf("%s", &n);
    readln;

    auto t = readln.chomp.split.map!(to!int).sum;

    auto ans = 1;
    foreach (_; 1 .. n) {
        auto s = readln.chomp.split.map!(to!int).sum;
        if (s > t) ++ans;
    }

    ans.writeln;
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int [] [] a;
		readln;
		foreach (i; 0..n)
		{
			a ~= i ~ readln.splitter.map !(to !(int)).array;
		}
		a.schwartzSort !(d => tuple (-sum (d[1..$]), d[0]));
		writeln (a.countUntil !(d => d[0] == 0) + 1);
	}
}

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

  struct Student{
    int id, sum;
  }
  int n; rd(n);
  auto students=new Student[](n);
  foreach(i; 0..n){
    auto s=readln.split.to!(int[]).reduce!"a+b";
    students[i]=Student(i, s);
  }
  students.sort!("a.sum==b.sum ? a.id<b.id : a.sum>b.sum");
  foreach(i, student; students){
    if(student.id==0){
      writeln(i+1);
      return;
    }
  }

}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new int[][](N, 4);
      foreach (i; 0 .. N) {
        foreach (j; 0 .. 4) {
          A[i][j] = readInt();
        }
      }

      int ans = 1;
      foreach (i; 1 .. N) {
        if (A[0].sum < A[i].sum) {
          ++ans;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

import std.stdio;

int main()
{
	int t=0;
	readf(" %d", &t);
	int h=0;
	int j=0;
	int k=0;
	int l=0;
	readf(" %d", &h);
	readf(" %d", &j);
	readf(" %d", &k);
	readf(" %d", &l);
	int tsum=h+j+k+l;
	int pl=1;
	for (int i=0; i<t-1; i++)
	{
		int a=0;
		int b=0;
		int c=0;
		int d=0;
		readf(" %d", &a);
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		int sum=a+b+c+d;
		if (sum>=tsum)
		{
			pl=pl+1;
		}
	}
	if (pl==1)
	{
		writeln(pl);
	}
	else
	{
		writeln(pl-1);
	}
	return 0;
}


Koa the Koala has a matrix $$$A$$$ of $$$n$$$ rows and $$$m$$$ columns. Elements of this matrix are distinct integers from $$$1$$$ to $$$n \cdot m$$$ (each number from $$$1$$$ to $$$n \cdot m$$$ appears exactly once in the matrix).For any matrix $$$M$$$ of $$$n$$$ rows and $$$m$$$ columns let's define the following:  The $$$i$$$-th row of $$$M$$$ is defined as $$$R_i(M) = [ M_{i1}, M_{i2}, \ldots, M_{im} ]$$$ for all $$$i$$$ ($$$1 \le i \le n$$$).  The $$$j$$$-th column of $$$M$$$ is defined as $$$C_j(M) = [ M_{1j}, M_{2j}, \ldots, M_{nj} ]$$$ for all $$$j$$$ ($$$1 \le j \le m$$$). Koa defines $$$S(A) = (X, Y)$$$ as the spectrum of $$$A$$$, where $$$X$$$ is the set of the maximum values in rows of $$$A$$$ and $$$Y$$$ is the set of the maximum values in columns of $$$A$$$.More formally:  $$$X = \{ \max(R_1(A)), \max(R_2(A)), \ldots, \max(R_n(A)) \}$$$  $$$Y = \{ \max(C_1(A)), \max(C_2(A)), \ldots, \max(C_m(A)) \}$$$Koa asks you to find some matrix $$$A'$$$ of $$$n$$$ rows and $$$m$$$ columns, such that each number from $$$1$$$ to $$$n \cdot m$$$ appears exactly once in the matrix, and the following conditions hold:  $$$S(A') = S(A)$$$  $$$R_i(A')$$$ is bitonic for all $$$i$$$ ($$$1 \le i \le n$$$)  $$$C_j(A')$$$ is bitonic for all $$$j$$$ ($$$1 \le j \le m$$$)  An array $$$t$$$ ($$$t_1, t_2, \ldots, t_k$$$) is called bitonic if it first increases and then decreases. More formally: $$$t$$$ is bitonic if there exists some position $$$p$$$ ($$$1 \le p \le k$$$) such that: $$$t_1 < t_2 < \ldots < t_p > t_{p+1} > \ldots > t_k$$$.Help Koa to find such matrix or to determine that it doesn't exist.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 250$$$)  — the number of rows and columns of $$$A$$$. Each of the ollowing $$$n$$$ lines contains $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line denotes element $$$A_{ij}$$$ ($$$1 \le A_{ij} \le n \cdot m$$$) of matrix $$$A$$$. It is guaranteed that every number from $$$1$$$ to $$$n \cdot m$$$ appears exactly once among elements of the matrix.

If such matrix doesn't exist, print $$$-1$$$ on a single line. Otherwise, the output must consist of $$$n$$$ lines, each one consisting of $$$m$$$ space separated integers  — a description of $$$A'$$$. The $$$j$$$-th number in the $$$i$$$-th line represents the element $$$A'_{ij}$$$. Every integer from $$$1$$$ to $$$n \cdot m$$$ should appear exactly once in $$$A'$$$, every row and column in $$$A'$$$ must be bitonic and $$$S(A) = S(A')$$$ must hold. If there are many answers print any.

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

immutable int dirs = 4;
immutable int [dirs] dRow = [-1,  0, +1,  0];
immutable int [dirs] dCol = [ 0, -1,  0, +1];

void main ()
{
	int rows, cols;
	while (readf !(" %s %s") (rows, cols) > 0)
	{
		auto a = new int [] [] (rows, cols);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf !(" %s") (a[row][col]);
			}
		}

		int [] x;
		foreach (row; 0..rows)
		{
			int cur = 0;
			foreach (col; 0..cols)
			{
				cur = max (cur, a[row][col]);
			}
			x ~= cur;
		}
		sort (x);
		reverse (x);
		x ~= 0;

		int [] y;
		foreach (col; 0..cols)
		{
			int cur = 0;
			foreach (row; 0..rows)
			{
				cur = max (cur, a[row][col]);
			}
			y ~= cur;
		}
		sort (y);
		reverse (y);
		y ~= 0;

		auto marks = new int [] [] (rows, cols);
		alias Coord = Tuple !(int, q{row}, int, q{col});
		auto q = redBlackTree !((u, v) =>
		    tuple (-marks[u.row][u.col], -min (x[u.row], y[u.col]),
		    u.row * cols + u.col) <
		    tuple (-marks[v.row][v.col], -min (x[v.row], y[v.col]),
		    v.row * cols + v.col),
		    Coord);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				q.insert (Coord (row, col));
			}
		}

		auto used = new bool [rows * cols + 1];
		auto b = new int [] [] (rows, cols);

		void mark (int row, int col)
		{
			used[b[row][col]] = true;
			q.removeKey (Coord (row, col));
			marks[row][col] += 5;
			foreach (dir; 0..dirs)
			{
				auto nRow = row + dRow[dir];
				auto nCol = col + dCol[dir];
				if (nRow < 0 || rows <= nRow ||
				    nCol < 0 || cols <= nCol ||
				    marks[nRow][nCol] >= 5)
				{
					continue;
				}
				q.removeKey (Coord (nRow, nCol));
				marks[nRow][nCol] += 1;
				q.insert (Coord (nRow, nCol));
			}
		}

		int p1 = 0;
		int q1 = 0;
		while (p1 < rows || q1 < cols)
		{
			auto cur = max (x[p1], y[q1]);
			if (x[p1] == cur)
			{
				p1 += 1;
			}
			if (y[q1] == cur)
			{
				q1 += 1;
			}
			b[p1 - 1][q1 - 1] = cur;
			mark (p1 - 1, q1 - 1);
		}

		int cur = rows * cols;
		while (!q.empty)
		{
			while (used[cur])
			{
				cur -= 1;
			}
			auto c = q.front ();
			b[c.row][c.col] = cur;
			mark (c.row, c.col);
		}

		writefln !("%(%(%s %)\n%)") (b);
	}
}

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

immutable int dirs = 4;
immutable int [dirs] dRow = [-1,  0, +1,  0];
immutable int [dirs] dCol = [ 0, -1,  0, +1];

void main ()
{
	int rows, cols;
	while (readf !(" %s %s") (rows, cols) > 0)
	{
		auto a = new int [] [] (rows, cols);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf !(" %s") (a[row][col]);
			}
		}

		int [] x;
		foreach (row; 0..rows)
		{
			int cur = 0;
			foreach (col; 0..cols)
			{
				cur = max (cur, a[row][col]);
			}
			x ~= cur;
		}
		sort (x);
		reverse (x);
		x ~= 0;

		int [] y;
		foreach (col; 0..cols)
		{
			int cur = 0;
			foreach (row; 0..rows)
			{
				cur = max (cur, a[row][col]);
			}
			y ~= cur;
		}
		sort (y);
		reverse (y);
		y ~= 0;

		auto marks = new int [] [] (rows, cols);
		alias Coord = Tuple !(int, q{row}, int, q{col});
		auto q = redBlackTree !((u, v) =>
		    tuple (marks[u.row][u.col], -min (x[u.row], y[u.col]),
		    u.row * cols + u.col) <
		    tuple (marks[v.row][v.col], -min (x[v.row], y[v.col]),
		    v.row * cols + v.col),
		    Coord);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				q.insert (Coord (row, col));
			}
		}

		auto used = new bool [rows * cols + 1];
		auto b = new int [] [] (rows, cols);

		void mark (int row, int col)
		{
			used[b[row][col]] = true;
			q.removeKey (Coord (row, col));
			marks[row][col] += 5;
			foreach (dir; 0..dirs)
			{
				auto nRow = row + dRow[dir];
				auto nCol = col + dCol[dir];
				if (nRow < 0 || rows <= nRow ||
				    nCol < 0 || cols <= nCol ||
				    marks[nRow][nCol] >= 5)
				{
					continue;
				}
				q.removeKey (Coord (nRow, nCol));
				marks[nRow][nCol] += 1;
				q.insert (Coord (nRow, nCol));
			}
		}

		int p1 = 0;
		int q1 = 0;
		while (p1 < rows || q1 < cols)
		{
			auto cur = max (x[p1], y[q1]);
			if (x[p1] == cur)
			{
				p1 += 1;
			}
			if (y[q1] == cur)
			{
				q1 += 1;
			}
			b[p1 - 1][q1 - 1] = cur;
			mark (p1 - 1, q1 - 1);
		}

		int cur = rows * cols;
		while (!q.empty)
		{
			while (used[cur])
			{
				cur -= 1;
			}
			auto c = q.front ();
			b[c.row][c.col] = cur;
			mark (c.row, c.col);
		}

		writefln !("%(%(%s %)\n%)") (b);
	}
}