This is an easier version of the problem. In this version, $$$n \le 2000$$$.There are $$$n$$$ distinct points in three-dimensional space numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th point has coordinates $$$(x_i, y_i, z_i)$$$. The number of points $$$n$$$ is even.You'd like to remove all $$$n$$$ points using a sequence of $$$\frac{n}{2}$$$ snaps. In one snap, you can remove any two points $$$a$$$ and $$$b$$$ that have not been removed yet and form a perfectly balanced pair. A pair of points $$$a$$$ and $$$b$$$ is perfectly balanced if no other point $$$c$$$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $$$a$$$ and $$$b$$$.Formally, point $$$c$$$ lies within the axis-aligned minimum bounding box of points $$$a$$$ and $$$b$$$ if and only if $$$\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$$$, $$$\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$$$, and $$$\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$$$. Note that the bounding box might be degenerate. Find a way to remove all points in $$$\frac{n}{2}$$$ snaps.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2000$$$; $$$n$$$ is even), denoting the number of points. Each of the next $$$n$$$ lines contains three integers $$$x_i$$$, $$$y_i$$$, $$$z_i$$$ ($$$-10^8 \le x_i, y_i, z_i \le 10^8$$$), denoting the coordinates of the $$$i$$$-th point. No two points coincide.

Output $$$\frac{n}{2}$$$ pairs of integers $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting the indices of points removed on snap $$$i$$$. Every integer between $$$1$$$ and $$$n$$$, inclusive, must appear in your output exactly once. We can show that it is always possible to remove all points. If there are many solutions, output any of them.

NoteIn the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on $$$z = 0$$$ plane). Note that order of removing matters: for example, points $$$5$$$ and $$$1$$$ don't form a perfectly balanced pair initially, but they do after point $$$3$$$ is removed.

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

void main()
{
    auto n = readln.chomp.to!int;

    Tuple!(int, int)[][int][int] mp;
    foreach (int i; 1 .. n+1) {
        auto v = readln.chomp.split.map!(to!int);
        auto x = v[0], y = v[1], z = v[2];

        mp[x][y] ~= tuple(z, i);
    }

    debug { mp.writeln; }

    Tuple!(int, int)[] ans;

    void takePairs(ref int[] arr, ref int[] leftOvers) {
        while (arr.length > 1) {
            auto idx1 = arr.back;
            arr.popBack();
            auto idx2 = arr.back;
            arr.popBack();
            ans ~= tuple(idx1, idx2);
        }

        if (arr.length == 1) {
            leftOvers ~= arr.back;
            arr.popBack();
        }
    }

    int[] lftx;
    foreach (xx; mp.keys.sort()) {
        int[] lfty;
        foreach (yy; mp[xx].keys.sort()) {
            auto values = mp[xx][yy].sort().map!(t => t[1]).array;
            takePairs(values, lfty);
        }

        takePairs(lfty, lftx);
    }

    int[] dummy;
    takePairs(lftx, dummy);

    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

struct Point
{
	int x;
	int y;
	int z;
	int num;
}

long dist2 () (const auto ref Point p, const auto ref Point q)
{
	return (p.x - 0L - q.x) ^^ 2 + (p.y - 0L - q.y) ^^ 2 +
	    (p.z - 0L - q.z) ^^ 2;
}

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

		int [] [] res;
		while (!p.empty)
		{
			auto i = 0;
			auto j = 1;
			foreach (k; 2..p.length)
			{
				if (dist2 (p[i], p[j]) > dist2 (p[i], p[k]))
				{
					j = k;
				}
			}
			res ~= [p[i].num, p[j].num];
			p = p[1..j] ~ p[j + 1..$];
		}
		writefln ("%(%(%s %)\n%)", res);
	}
}

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

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

void solve(){
	int n = rint;
	P[] ps;
	foreach(i; 0 .. n){
		ps ~= P(i, i + 1, rlong, rlong, rlong);
	}

	P[][long][long] pm;
	foreach(p; ps){
		if(p.x !in pm){
			P[][long] tmp;
			pm[p.x] = tmp;
		}
		if(p.y !in pm[p.x]) pm[p.x][p.y] = [];
		pm[p.x][p.y] ~= p;
	}

	int[][] ans;

	long[] xs = pm.keys;
	xs.sort();
	P superleft;
	bool hasSuperleft;
	foreach(x; xs){
		long[] ys = pm[x].keys;
		ys.sort();
		P left;
		bool hasLeft;
		foreach(y; ys){
			P[] pq = pm[x][y];
			pq.sort!isLess();
			foreach(i; 0 .. pq.length / 2){
				ans ~= [pq[i * 2].name, pq[i * 2 + 1].name];
			}
			if(pq.length % 2){
				if(hasLeft){
					ans ~= [pq[$ - 1].name, left.name];
					hasLeft = 0;
				}
				else{
					left = pq[$ - 1];
					hasLeft = 1;
				}
			}
		}
		if(hasLeft){
			if(hasSuperleft){
				ans ~= [left.name, superleft.name];
				hasLeft = 0, hasSuperleft = 0;
			}
			else{
				superleft = left;
				hasLeft = 0, hasSuperleft = 1;
			}
		}
	}

	foreach(an; ans) writeln(an[0], " ", an[1]);
}

struct P{
	int id, name;
	long x, y, z;
}
bool isLess(P a, P b){
	if(a.x != b.x) return a.x < b.x;
	if(a.y != b.y) return a.y < b.y;
	return a.z < b.z;
}

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

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

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

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

alias Pt = Tuple!(int, "x", int, "y", int, "z", int, "id");

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new Pt[N];
      foreach (i; 0 .. N) {
        P[i].x = readInt();
        P[i].y = readInt();
        P[i].z = readInt();
        P[i].id = i;
      }

      sort(P);

      int[] ans;

      int[] as;
      for (int i = 0, j; i < N; i = j) {
        for (j = i; j < N && P[i].x == P[j].x; ++j) {}
        int[] bs;
        for (int k = i, l; k < j; k = l) {
          for (l = k; l < j && P[k].y == P[l].y; ++l) {}
          foreach (m; k .. k + (l - k) / 2 * 2) {
            ans ~= P[m].id;
          }
          if ((l - k) % 2 != 0) {
            bs ~= P[l - 1].id;
          }
        }
        const bsLen = cast(int)(bs.length);
        foreach (m; 0 .. bsLen / 2 * 2) {
          ans ~= bs[m];
        }
        if (bsLen % 2 != 0) {
          as ~= bs[$ - 1];
        }
      }
      assert(as.length % 2 == 0);
      ans ~= as;

      for (int i = 0; i < N; i += 2) {
        writeln(ans[i] + 1, " ", ans[i + 1] + 1);
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

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

void main()
{
	auto n = RD!int;
	long[3][int] list;
	foreach (i; 0..n)
	{
		list[i] = [RD, RD, RD];
	}

	int[2][] ans;
	while (true)
	{
		auto keys = list.keys;
		if (keys.length == 0) break;
		auto k1 = keys[0];
		int pos;
		long best = long.max;
		foreach (k2; keys[1..$])
		{
			auto lhs = list[k1].dup;
			auto rhs = list[k2];
			lhs[] -= rhs[];
			lhs[] *= lhs[];
			long d;
			foreach (e; lhs)
				d += e;
			if (d < best)
			{
				pos = k2;
				best = d;
			}
		}
		ans ~= [k1, pos];
		list.remove(k1);
		list.remove(pos);
	}

	foreach (e; ans)
		writeln(e[0]+1, " ", e[1]+1);
	stdout.flush();
	debug readln();
}

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

void main()
{
    auto n = readln.chomp.to!int;

    Tuple!(int, int)[][int][int] mp;
    foreach (int i; 1 .. n+1) {
        auto v = readln.chomp.split.map!(to!int);
        auto x = v[0], y = v[1], z = v[2];

        mp[x][y] ~= tuple(z, i);
    }

    debug { mp.writeln; }

    Tuple!(int, int)[] ans;

    void takePairs(ref int[] arr, ref int[] leftOvers) {
        while (arr.length > 1) {
            auto idx1 = arr.back;
            arr.popBack();
            auto idx2 = arr.back;
            arr.popBack();
            ans ~= tuple(idx1, idx2);
        }

        if (arr.length == 1) {
            leftOvers ~= arr.back;
            arr.popBack();
        }
    }

    int[] lftx;
    foreach (xx; mp.keys) {
        int[] lfty;
        foreach (yy; mp[xx].keys) {
            auto values = mp[xx][yy].map!(t => t[1]).array;
            takePairs(values, lfty);
        }

        takePairs(lfty, lftx);
    }

    int[] dummy;
    takePairs(lftx, dummy);

    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

void main()
{
    auto n = readln.chomp.to!int;

    Tuple!(int, int)[][int][int] mp;
    foreach (int i; 1 .. n+1) {
        auto v = readln.chomp.split.map!(to!int);
        auto x = v[0], y = v[1], z = v[2];

        mp[x][y] ~= tuple(z, i);
    }

    debug { mp.writeln; }

    Tuple!(int, int)[] ans;

    void takePairs(ref int[] arr, ref int[] leftOvers) {
        while (arr.length > 1) {
            auto idx1 = arr.back;
            arr.popBack();
            auto idx2 = arr.back;
            arr.popBack();
            ans ~= tuple(idx1, idx2);
        }

        if (arr.length == 1) {
            leftOvers ~= arr.back;
            arr.popBack();
        }
    }

    int[] lftx;
    foreach (xx; mp.keys) {
        int[] lfty;
        foreach (yy; mp[xx].keys) {
            auto values = mp[xx][yy]
                .schwartzSort!(t => t[0])
                .map!(t => t[1]).array;
            takePairs(values, lfty);
        }

        takePairs(lfty, lftx);
    }

    int[] dummy;
    takePairs(lftx, dummy);

    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

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

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

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

alias Pt = Tuple!(int, "x", int, "y", int, "z", int, "id");

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new Pt[N];
      foreach (i; 0 .. N) {
        P[i].x = readInt();
        P[i].y = readInt();
        P[i].z = readInt();
        P[i].id = i;
      }

      sort(P);
      for (int a = 0, i = 0, j; i < N; i = j) {
        for (j = i; j < N && P[i].x == P[j].x; ++j) {}
        if (a++ % 2 != 0) {
          reverse(P[i .. j]);
        }
        for (int b = 0, k = i, l; k < j; k = l) {
          for (l = k; l < j && P[k].y == P[l].y; ++l) {}
          if (b++ % 2 != 0) {
            reverse(P[k .. l]);
          }
        }
      }
      debug {
        writeln("P = ", P);
      }

      for (int i = 0; i < N; i += 2) {
        writeln(P[i].id + 1, " ", P[i + 1].id + 1);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

alias Pt = Tuple!(int, "x", int, "y", int, "z", int, "id");

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new Pt[N];
      foreach (i; 0 .. N) {
        P[i].x = readInt();
        P[i].y = readInt();
        P[i].z = readInt();
        P[i].id = i;
      }

      sort(P);
      for (int a = 0, i = 0, j; i < N; i = j) {
        for (j = i; j < N && P[i].x == P[j].x; ++j) {}
        for (int b = 0, k = i, l; k < j; k = l) {
          for (l = k; l < j && P[k].y == P[l].y; ++l) {}
          if (b++ % 2 != 0) {
            reverse(P[k .. l]);
          }
        }
        if (a++ % 2 != 0) {
          reverse(P[i .. j]);
        }
      }
      debug {
        writeln("P = ", P);
      }

      for (int i = 0; i < N; i += 2) {
        writeln(P[i].id + 1, " ", P[i + 1].id + 1);
      }
    }
  } catch (EOFException e) {
  }
}


The Fair Nut is going to travel to the Tree Country, in which there are $$$n$$$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $$$u$$$ and go by a simple path to city $$$v$$$. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex.A filling station is located in every city. Because of strange law, Nut can buy only $$$w_i$$$ liters of gasoline in the $$$i$$$-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last.He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 3 \cdot 10^5$$$) — the number of cities. The second line contains $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \leq w_{i} \leq 10^9$$$) — the maximum amounts of liters of gasoline that Nut can buy in cities. Each of the next $$$n - 1$$$ lines describes road and contains three integers $$$u$$$, $$$v$$$, $$$c$$$ ($$$1 \leq u, v \leq n$$$, $$$1 \leq c \leq 10^9$$$, $$$u \ne v$$$), where $$$u$$$ and $$$v$$$ — cities that are connected by this road and $$$c$$$ — its length. It is guaranteed that graph of road connectivity is a tree.

Print one number — the maximum amount of gasoline that he can have at the end of the path.

NoteThe optimal way in the first example is $$$2 \to 1 \to 3$$$.   The optimal way in the second example is $$$2 \to 4$$$.

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 w = readln.chomp.split.map!(to!int).array;

    struct Edge { int dest, wage; }
    auto g = new Edge[][] (n);
    foreach (_; 0 .. n-1) {
        int u, v, c;
        readf("%s %s %s", &u, &v, &c);
        readln;
        --u, --v;

        g[u] ~= Edge(v, c);
        g[v] ~= Edge(u, c);
    }

    auto scores = new long[][] (n, 2);
    scores.each!(r => r.fill(0));

    void DfsBottomUp(int v, int fr) {
        foreach (e; g[v]) {
            if (e.dest == fr) continue;

            DfsBottomUp(e.dest, v);

            auto childMx = scores[e.dest][0] + w[e.dest] - e.wage;

            if (childMx > scores[v][0]) scores[v][1] = scores[v][0], scores[v][0] = childMx;
            else if (childMx > scores[v][1]) scores[v][1] = childMx;
        }
    }

    DfsBottomUp(0, -1);

    debug { scores.writeln; }

    long ans = 0;
    void DfsTopDown(int v, int fr, long best) {
        auto cur = scores[v][0] + max(scores[v][1], best) + w[v];

        debug { writeln(v, ' ', cur); }

        ans = max(ans, cur);

        foreach (e; g[v]) {
            if (e.dest == fr) continue;

            auto curbest = scores[e.dest][0] + w[e.dest] - e.wage != scores[v][0] ? scores[v][0] : scores[v][1];
            curbest = max(curbest, best);
            curbest = max(curbest + w[v] - e.wage, 0);
            DfsTopDown(e.dest, v, curbest);
        }
    }

    DfsTopDown(0, -1, 0);

    ans.writeln;
}

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()
{
    immutable int MD = 10 ^^ 9 + 7;

    auto s = readln.chomp;

    s ~= 'b';
    int ans = 0;
    int cur = 0;
    foreach (c; s) {
        if (c == 'a') ++cur;
        else if (c == 'b') {
            auto toadd = (cast(long)cur * ans % MD + cur) % MD;
            ans = (ans + toadd) % MD;
            cur = 0;
        }
    }

    ans.writeln;
}


Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be «-1».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!

The first line contains two integers n, d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) —the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≤ ai ≤ 104), where ai represents the transaction in i-th day.

Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.

#!/usr/bin/env dub
/+ dub.sdl:
    name "D"
+/

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

void main()
{
    int N;
    long D;
    readf(" %s %s ", N, D);

    long[] A = new long[N];
    foreach (i;0..N) readf(" %s ", A[i]);

    long[] cum = [0];
    foreach(a; A) cum ~= cum[$-1] + a;

    long[] cmax = new long[N+1];
    cmax[N] = cum[N];
    for (int i=N-1;i>=0;i--) {
        cmax[i] = max(cum[i], cmax[i+1]);
    }

    long off = 0;
    int ans = 0;
    foreach(i; 0..N) {
        if (A[i] == 0 && cum[i+1] + off < 0) {
            // add as much as possible
            off = D - cmax[i];
            ++ans;
            if (cum[i+1] + off < 0) {
                writeln(-1);
                return;
            }
        }

        if (cum[i+1] > D) {
            writeln(-1);
            return;
        }
    }

    writeln(ans);
}

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

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

    auto arr = readln.chomp.split.map!(to!int).array;

    long csum = 0;
    int mxval = 0, ans = 0;
    foreach (e; arr) {
        if (e != 0) {
            csum += e;
            mxval = max(e, mxval);
            if (csum > d) {
                ans = -1;
                break;
            }
        } else {
            if (csum >= 0) { continue; }

            long need = -csum;
            if (ans != 0 && mxval + need <= d) {
                mxval += need;
            } else {
                ans += 1;
                mxval = 0;
            }

            csum = 0;
        }
    }

    ans.writeln;
}

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

immutable inf = 10^^9 + 7;

void main() {
    int n, d;
    scan(n, d);
    auto a = readln.split.to!(int[]);

    auto rw = new long[](n + 1);
    foreach (i ; 1 .. n + 1) {
        rw[i] = rw[i-1] + a[i-1];
    }

    auto rm = new long[](n + 1);
    rm[n] = rw[n];

    foreach_reverse (i ; 1 .. n) {
        rm[i] = max(rm[i + 1], rw[i]);
    }

    debug {
        writeln(rm);
    }

    int ans;
    long bank;

    foreach (i ; 0 .. n) {
        if (a[i] == 0 && bank < 0) {
            ans++;
            bank = d - (rm[i] - rw[i]);

            if (bank < 0) {
                writeln(-1);
                return;
            }
        }

        bank += a[i];

        debug {
            writeln(bank);
        }

        if (bank > d) {
            writeln(-1);
            return;
        }
    }

    writeln(ans);
}

struct UnionFind {
    private {
        int N;
        int[] p;
        int[] rank;
    }

    this (int n) {
        N = n;
        p = iota(N).array;
        rank = new int[](N);
    }

    int find_root(int x) {
        if (p[x] != x) {
            p[x] = find_root(p[x]);
        }

        return p[x];
    }

    bool same(int x, int y) {
        return find_root(x) == find_root(y);
    }

    void unite(int x, int y) {
        int u = find_root(x), v = find_root(y);

        if (u == v) return;

        if (rank[u] < rank[v]) {
            p[u] = v;
        }
        else {
            p[v] = u;

            if (rank[u] == rank[v]) {
                rank[u]++;
            }
        }
    }
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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

struct Queue(T) {
    private {
        int N, head, tail;
        T[] data;
    }

    this(int n) {
        N = n + 1;
        data = new T[](N);
    }

    bool empty() {
        return head == tail;
    }

    bool full() {
        return (tail + 1) % N == head;
    }

    T front() {
        return data[head];
    }

    void push(T x) {
        assert(!full);
        data[tail++] = x;
        tail %= N;
    }

    void pop() {
        assert(!empty);
        head = (head + 1) % N;
    }

    void clear() {
        head = tail = 0;
    }
}

#!/usr/bin/env dub
/+ dub.sdl:
    name "D"
+/

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

void main()
{
    int N;
    long D;
    readf(" %s %s ", N, D);

    long[] A = new long[N];
    foreach (i;0..N) readf(" %s ", A[i]);

    long[] cum = [0];
    foreach(a; A) cum ~= cum[$-1] + a;

    long[] cmax = new long[N+1];
    cmax[N] = cum[N];
    for (int i=N-1;i>=0;i--) {
        cmax[i] = max(cum[i], cmax[i+1]);
    }

    long off = 0;
    int ans = 0;
    foreach(i; 0..N) {
        if (A[i] == 0 && cum[i+1] + off < 0) {
            // add as much as possible
            off = D - cmax[i];
            ++ans;
            if (cum[i+1] + off < 0) {
                writeln(-1);
                return;
            }
        }

        if (cum[i+1] >= D) {
            writeln(-1);
            return;
        }
    }

    writeln(ans);
}

#!/usr/bin/env dub
/+ dub.sdl:
    name "D"
+/

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

void main()
{
    int N;
    long D;
    readf(" %s %s ", N, D);

    long[] A = new long[N];
    foreach (i;0..N) readf(" %s ", A[i]);

    long[] cum = [0];
    foreach(a; A) cum ~= cum[$-1] + a;

    long[] cmax = new long[N+1];
    cmax[N] = cum[N];
    for (int i=N-1;i>=0;i--) {
        cmax[i] = max(cum[i], cmax[i+1]);
    }

    long off = 0;
    int ans = 0;
    foreach(i; 0..N) {
        if (A[i] == 0 && cum[i+1] + off < 0) {
            // add as much as possible
            off = D - cmax[i];
            ++ans;
            if (cum[i+1] + off < 0) {
                writeln(-1);
                return;
            }
        }
    }

    writeln(ans);
}

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

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

    auto arr = readln.chomp.split.map!(to!int).array;

    long csum = 0;
    int mxval = 0, ans = 0;
    foreach (e; arr) {
        if (e != 0) {
            csum += e;
            mxval = max(e, mxval);
            if (mxval > d) {
                ans = -1;
                break;
            }
        } else {
            if (csum >= 0) { continue; }

            long need = -csum;
            if (ans != 0 && mxval + need <= d) {
                mxval += need;
            } else {
                ans += 1;
                mxval = 0;
            }

            csum = 0;
        }
    }

    ans.writeln;
}

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

immutable inf = 10^^9 + 7;

void main() {
    int n, d;
    scan(n, d);
    auto a = readln.split.to!(int[]);

    long bank;
    int ans;

    foreach (i ; 0 .. n) {
        if (a[i] == 0) {
            if (bank < 0) {
                ans++;
                bank = 0;
            }
        }

        bank += a[i];

        debug {
            writeln(bank);
        }

        if (bank > d) {
            writeln(-1);
            return;
        }
    }

    writeln(ans);
}

struct UnionFind {
    private {
        int N;
        int[] p;
        int[] rank;
    }

    this (int n) {
        N = n;
        p = iota(N).array;
        rank = new int[](N);
    }

    int find_root(int x) {
        if (p[x] != x) {
            p[x] = find_root(p[x]);
        }

        return p[x];
    }

    bool same(int x, int y) {
        return find_root(x) == find_root(y);
    }

    void unite(int x, int y) {
        int u = find_root(x), v = find_root(y);

        if (u == v) return;

        if (rank[u] < rank[v]) {
            p[u] = v;
        }
        else {
            p[v] = u;

            if (rank[u] == rank[v]) {
                rank[u]++;
            }
        }
    }
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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

struct Queue(T) {
    private {
        int N, head, tail;
        T[] data;
    }

    this(int n) {
        N = n + 1;
        data = new T[](N);
    }

    bool empty() {
        return head == tail;
    }

    bool full() {
        return (tail + 1) % N == head;
    }

    T front() {
        return data[head];
    }

    void push(T x) {
        assert(!full);
        data[tail++] = x;
        tail %= N;
    }

    void pop() {
        assert(!empty);
        head = (head + 1) % N;
    }

    void clear() {
        head = tail = 0;
    }
}

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

immutable inf = 10^^9 + 7;

void main() {
    int n, d;
    scan(n, d);
    auto a = readln.split.to!(int[]);

    auto rw = new long[](n + 1);
    foreach (i ; 1 .. n + 1) {
        rw[i] = rw[i-1] + a[i-1];
    }

    auto rm = new long[](n + 1);
    rm[n] = a[n-1];

    foreach_reverse (i ; 1 .. n) {
        rm[i] = max(rm[i + 1], a[i-1]);
    }

    debug {
        writeln(rw);
        writeln(rm);
    }

    int ans;
    long bank;

    foreach (i ; 0 .. n) {
        if (a[i] == 0 && bank < 0) {
            ans++;
            bank = d - rm[i+1];

            if (bank < 0) {
                writeln(-1);
                return;
            }
        }

        bank += a[i];

        debug {
            writeln(bank);
        }

        if (bank > d) {
            writeln(-1);
            return;
        }
    }

    writeln(ans);
}

struct UnionFind {
    private {
        int N;
        int[] p;
        int[] rank;
    }

    this (int n) {
        N = n;
        p = iota(N).array;
        rank = new int[](N);
    }

    int find_root(int x) {
        if (p[x] != x) {
            p[x] = find_root(p[x]);
        }

        return p[x];
    }

    bool same(int x, int y) {
        return find_root(x) == find_root(y);
    }

    void unite(int x, int y) {
        int u = find_root(x), v = find_root(y);

        if (u == v) return;

        if (rank[u] < rank[v]) {
            p[u] = v;
        }
        else {
            p[v] = u;

            if (rank[u] == rank[v]) {
                rank[u]++;
            }
        }
    }
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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

struct Queue(T) {
    private {
        int N, head, tail;
        T[] data;
    }

    this(int n) {
        N = n + 1;
        data = new T[](N);
    }

    bool empty() {
        return head == tail;
    }

    bool full() {
        return (tail + 1) % N == head;
    }

    T front() {
        return data[head];
    }

    void push(T x) {
        assert(!full);
        data[tail++] = x;
        tail %= N;
    }

    void pop() {
        assert(!empty);
        head = (head + 1) % N;
    }

    void clear() {
        head = tail = 0;
    }
}

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

immutable inf = 10^^9 + 7;

void main() {
    int n, d;
    scan(n, d);
    auto a = readln.split.to!(int[]);

    auto rw = new long[](n + 1);
    foreach (i ; 1 .. n + 1) {
        rw[i] = rw[i-1] + a[i-1];
    }

    auto rm = new long[](n + 1);
    rm[n] = a[n-1];

    foreach_reverse (i ; 1 .. n) {
        rm[i] = max(rm[i + 1], a[i-1]);
    }

    debug {
        writeln(rw);
        writeln(rm);
    }

    int ans;
    long bank;

    foreach (i ; 0 .. n) {
        if (a[i] == 0 && bank < 0) {
            ans++;
            bank = d - rm[i];

            if (bank < 0) {
                writeln(-1);
                return;
            }
        }

        bank += a[i];

        debug {
            writeln(bank);
        }

        if (bank > d) {
            writeln(-1);
            return;
        }
    }

    writeln(ans);
}

struct UnionFind {
    private {
        int N;
        int[] p;
        int[] rank;
    }

    this (int n) {
        N = n;
        p = iota(N).array;
        rank = new int[](N);
    }

    int find_root(int x) {
        if (p[x] != x) {
            p[x] = find_root(p[x]);
        }

        return p[x];
    }

    bool same(int x, int y) {
        return find_root(x) == find_root(y);
    }

    void unite(int x, int y) {
        int u = find_root(x), v = find_root(y);

        if (u == v) return;

        if (rank[u] < rank[v]) {
            p[u] = v;
        }
        else {
            p[v] = u;

            if (rank[u] == rank[v]) {
                rank[u]++;
            }
        }
    }
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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

struct Queue(T) {
    private {
        int N, head, tail;
        T[] data;
    }

    this(int n) {
        N = n + 1;
        data = new T[](N);
    }

    bool empty() {
        return head == tail;
    }

    bool full() {
        return (tail + 1) % N == head;
    }

    T front() {
        return data[head];
    }

    void push(T x) {
        assert(!full);
        data[tail++] = x;
        tail %= N;
    }

    void pop() {
        assert(!empty);
        head = (head + 1) % N;
    }

    void clear() {
        head = tail = 0;
    }
}


You are given an image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into k by k blocks. If n and m are not divisible by k, the image is padded with only zeros on the right and bottom so that they are divisible by k. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some k. More specifically, the steps are to first choose k, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this k. The image must be compressible in that state.

The first line of input will contain two integers n, m (2 ≤ n, m ≤ 2 500), the dimensions of the image. The next n lines of input will contain a binary string with exactly m characters, representing the image.

Print a single integer, the minimum number of pixels needed to toggle to make the image compressible.

NoteWe first choose k = 2.The image is padded as follows: 001000101100110010000000We can toggle the image to look as follows: 001100001100000000000000We can see that this image is compressible for k = 2.

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;

int n, m;
int[][] a;

void main() {
    scan(n, m);
    int lim = 2 * max(n, m);
    a = new int[][](lim + 1, lim + 1);
    iota(1, n + 1).each!(i => a[i][1 .. m + 1] = readln.chomp.map!(b => (b - '0').to!int).array);

    debug {
        writefln("%(%(%s %)\n%)", a);
        writeln();
    }

    foreach (i ; 1 .. lim + 1) {
        foreach (j ; 1 .. lim + 1) {
            a[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];
        }
    }

    debug {
        writefln("%(%(%s %)\n%)", a);
        writeln();
    }

    long ans = 4L * n * m;

    foreach (k ; 2 .. max(n, m) + 1) {
        long anst = 0;

        foreach (i ; 1 .. (n + k - 1) / k + 1) {
            foreach (j ; 1 .. (m + k - 1) / k + 1) {
                long x = a[i*k][j*k] - a[(i-1)*k][j*k] - a[i*k][(j-1)*k] + a[(i-1)*k][(j-1)*k];
                anst += min(x, k*k - x);
            }
        }

        ans = min(ans, anst);

        debug {
            writefln("k:%d, anst:%d", k, anst);
        }
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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


Victor has a 24-hour clock that shows the time in the format "HH:MM" (00 $$$\le$$$ HH $$$\le$$$ 23, 00 $$$\le$$$ MM $$$\le$$$ 59). He looks at the clock every $$$x$$$ minutes, and the clock is currently showing time $$$s$$$. How many different palindromes will Victor see in total after looking at the clock every $$$x$$$ minutes, the first time being at time $$$s$$$?For example, if the clock starts out as 03:12 and Victor looks at the clock every $$$360$$$ minutes (i.e. every $$$6$$$ hours), then he will see the times 03:12, 09:12, 15:12, 21:12, 03:12, and the times will continue to repeat. Here the time 21:12 is the only palindrome he will ever see, so the answer is $$$1$$$.A palindrome is a string that reads the same backward as forward. For example, the times 12:21, 05:50, 11:11 are palindromes but 13:13, 22:10, 02:22 are not.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of each test case follows. The only line of each test case contains a string $$$s$$$ of length $$$5$$$ with the format "HH:MM" where "HH" is from "00" to "23" and "MM" is from "00" to "59" (both "HH" and "MM" have exactly two digits) and an integer $$$x$$$ ($$$1 \leq x \leq 1440$$$) — the number of minutes Victor takes to look again at the clock.

For each test case, output a single integer — the number of different palindromes Victor will see if he looks at the clock every $$$x$$$ minutes starting from time $$$s$$$.

NoteThe first test case is explained in the statement.

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan!string;
      auto X = scan!int;

      int h = S[0..2].to!int;
      int m = S[3..5].to!int;
      int ans;
      auto seen = new bool[](60 * 24);
      while(!seen[h*60 + m]) {
        seen[h*60 + m] = true;

        auto cs = "%02d%02d".format(h, m);
        if (cs[0] == cs[3] && cs[1] == cs[2]) ans++;

        m += X;
        if (m >= 60) {
          h += m / 60;
          h %= 24;
          m %= 60;
        }
      }

      return ans;
    }

    foreach(i; 0..QN) {
      outputForAtCoder(&subSolve);
    }
  }

  outputForAtCoder(&solve);
}

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

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

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


A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a, b] covers segment [c, d], if they meet this condition a ≤ c ≤ d ≤ b.

The first line contains integer n (1 ≤ n ≤ 105) — the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ 109) — the borders of the i-th segment. It is guaranteed that no two segments coincide.

Print a single integer — the number of the segment that covers all other segments in the set. If there's no solution, print -1. The segments are numbered starting from 1 in the order in which they appear in the input.

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

alias Tuple!(int, int) Seg;

bool contain(Seg a, Seg b) {
    return a[0] <= b[0] && b[1] <= a[1];
}

int slen(Seg s) {
    return s[1] - s[0] + 1;
}

void main() {
    int n; readf("%d\n", &n);
    Seg[] ss = new Seg[n];
    int mlen = 0;
    for (int i = 0; i < n; i++) {
        int a, b; readf("%d %d\n", &a, &b);
        ss[i] = Seg(a, b);
        mlen = max(mlen, ss[i].slen);
    }
    Seg m;
    int index;
    for (int i = 0; i < ss.length; i++) {
        Seg s = ss[i];
        if (s.slen == mlen) {
            m = s;
            index = i;
        }
    }
    foreach (ref s; ss) {
        if (!m.contain(s)) {
            writeln(-1);
            return;
        }
    }
    writeln(index + 1);
}

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

struct S {
    int l, r;
    bool contain(in S s) {
        return l <= s.l && s.r <= r;
    }
}

void main() {
    int index = 1;
    int n; readf("%d\n", &n);
    int a, b; readf("%d %d\n", &a, &b);
    S seg = { l: a, r: b };
    for (int i = 2; i <= n; i++) {
        readf("%d %d\n", &a, &b);
        S cseg = { l: a, r: b };
        if (cseg.contain(seg)) {
            seg = cseg;
            index = i;
        } else if (!seg.contain(cseg)) {
            writeln(-1);
            return;
        }
    }
    writeln(index);
}


Polycarpus is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array a for all indexes in the segment [l, r]. In other words, this function does the following: function rangeIncrement(l, r)    for i := l .. r do        a[i] = a[i] + 1Polycarpus knows the state of the array a after a series of function calls. He wants to determine the minimum number of function calls that lead to such state. In addition, he wants to find what function calls are needed in this case. It is guaranteed that the required number of calls does not exceed 105.Before calls of function rangeIncrement(l, r) all array elements equal zero.

The first input line contains a single integer n (1 ≤ n ≤ 105) — the length of the array a[1... n].  The second line contains its integer space-separated elements, a[1], a[2], ..., a[n] (0 ≤ a[i] ≤ 105) after some series of function calls rangeIncrement(l, r).  It is guaranteed that at least one element of the array is positive. It is guaranteed that the answer contains no more than 105 calls of function rangeIncrement(l, r).

Print on the first line t — the minimum number of calls of function rangeIncrement(l, r), that lead to the array from the input data. It is guaranteed that this number will turn out not more than 105. Then print t lines — the descriptions of function calls, one per line. Each line should contain two integers li, ri (1 ≤ li ≤ ri ≤ n) — the arguments of the i-th call rangeIncrement(l, r). Calls can be applied in any order. If there are multiple solutions, you are allowed to print any of them.

NoteThe first sample requires a call for the entire array, and four additional calls:  one for the segment [2,2] (i.e. the second element of the array),  three for the segment [5,5] (i.e. the fifth element of the array).

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

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

    auto arr = [0] ~ readln.chomp.split.map!(to!int).array ~ [0];

    debug { arr.writeln; }

    Tuple!(int, int)[] ans;

    auto stk = make!(SList!(Tuple!(int, int)));
    stk.insertFront(tuple(0, 0));
    foreach (i; 1 .. n+1) {
        if (arr[i] > arr[i-1]) { stk.insertFront(tuple(i, arr[i])); }

        while (stk.front[1] > arr[i+1]) {
            auto lft = stk.front[0];
            auto ht = stk.front[1];
            stk.removeFront();

            ans ~= tuple(lft, i);

            if (ht - 1 > stk.front[1]) { stk.insertFront(tuple(lft, ht - 1)); }
        }
    }

    ans.length.writeln;
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

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

    auto arr = [0] ~ readln.chomp.split.map!(to!int).array ~ [0];

    debug { arr.writeln; }

    Tuple!(int, int)[] ans;

    auto stk = make!(SList!int);
    stk.insertFront(0);
    foreach (i; 1 .. n+1) {
        if (arr[i] > arr[i-1]) { stk.insertFront(i); }

        if (arr[i] > arr[i+1]) {
            while (arr[stk.front] > arr[i+1]) {
                auto lft = stk.front;
                stk.removeFront();

                auto ht = arr[lft];

                foreach (_; 0 .. ht - arr[stk.front]) {
                    ans ~= tuple(lft, i);
                }
            }
        }
    }

    ans.length.writeln;
    ans.each!(t => writeln(t[0], ' ', t[1]));
}


One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows:  two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$;  two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:  admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";  admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.

The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters.

In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.

NoteIn the second example hacker need to use any of the passwords to access the system.

import std.stdio;
import std.random;
import std.range;
import std.string;

int[26] dsu_arr;
bool[26] seen;

int leader(int i) {
    if (dsu_arr[i] == i) return i;
    return dsu_arr[i] = leader(dsu_arr[i]);
}

void unite(int a, int b) {
    dsu_arr[leader(a)] = leader(b);
}

void main() {
    for (int i = 0; i < 26; i++) dsu_arr[i] = i;
    auto strings = stdin.byLine;
    strings.popFront();
    foreach (line; strings) {
        for (int i = 1; i < line.length; i++) {
            unite(line[i - 1] - 'a', line[i] - 'a');
        }
        foreach (c; line) seen[c - 'a'] = true;
    }

    int t = 0;
    for (int i = 0; i < 26; i++) {
        if (seen[i] && leader(i) == i) t++;
    }

    writeln(t);
}

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 s = new string [n];
		foreach (ref line; s)
		{
			line = readln.strip;
		}
		int [char] pos;
		foreach (i, ref line; s)
		{
			foreach (const ref char c; line)
			{
				pos[c] = i;
			}
		}

		auto p = n.iota.array;
		auto r = new int [n];

		int root (int v)
		{
			if (p[v] == v)
			{
				return v;
			}
			return p[v] = root (p[v]);
		}

		bool unite (int u, int v)
		{
			u = root (u);
			v = root (v);
			if (u == v)
			{
				return false;
			}
			if (r[u] > r[v])
			{
				swap (u, v);
			}
			p[u] = v;
			if (r[u] == r[v])
			{
				r[v] += 1;
			}
			return true;
		}

		int res = n;
		foreach (i, ref line; s)
		{
			foreach (const ref char c; line)
			{
				if (unite (i, pos[c]))
				{
					res -= 1;
				}
			}
		}
		writeln (res);
	}
}

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

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

void solve(){
	int n = rint;
	string[] ps;
	foreach(i; 0 .. n) ps ~= rstring;

	Node[] nodes;
	Node[int] letternodes;
	foreach(i; 0 .. 26){
		Node nd = new Node(i, 1);
		nodes ~= nd;
		letternodes['a' + i] = nd;
	}

	Edge[] edges;
	foreach(i, p; ps){
		Node nd = new Node(26 + i, 0);
		nodes ~= nd;
		foreach(c; p) edges ~= new Edge(nd, letternodes[c], 0);
	}

	foreach(ed; edges) ed.node1.group.eat(ed.node2.group);

	int ans;
	foreach(nd; nodes) if(nd.value == 0 && nd.group.id == nd.id) ans += 1;

	ans.writeln;
}
class Edge{
	Node node1;
	Node node2;
	long value;
	this(Node node1, Node node2, long value){
		this.node1 = node1, this.node2 = node2;
		this.value = value;
	}
}

class Node{
	long id;
	long value;
	Group group;
	this(long id, long value){
		this.id = id;
		this.value = value;
		this.group = new Group(this);
	}
}

class Group{
	long value;
	long id;
	Node[] nodes;
	this(Node node){
		this.id = node.id;
		this.nodes = [node];
		this.value = node.value;
	}
	void eat(Group gp){
		if(this.id == gp.id) return;
		if(gp.nodes.length > this.nodes.length) gp.eat(this);
		else{
			foreach(nd; gp.nodes){
				this.nodes ~= nd;
				nd.group = this;
				this.value += nd.value;
			}
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

void main()
{
	auto n = RD!int;

	UnionFind uf;
	uf.init(26);
	auto used = new bool[](26);
	foreach (i; 0..n)
	{
		auto s = RD!string;
		foreach (j; 0..s.length)
		{
			auto u = s[j]-'a';
			used[u] = true;
			foreach (k; j+1..s.length)
			{
				auto v = s[k]-'a';
				used[v] = true;
				uf.unite(u, v);
			}
		}
	}

	bool[int] set;
	foreach (i; 0..26)
	{
		if (!used[i]) continue;
		auto p = uf.root(i);
		set[p] = true;
	}
	writeln(set.keys.length);
	stdout.flush;
	debug readln;
}


Consider a grid of size $$$n \times n$$$. The rows are numbered top to bottom from $$$1$$$ to $$$n$$$, the columns are numbered left to right from $$$1$$$ to $$$n$$$.The robot is positioned in a cell $$$(1, 1)$$$. It can perform two types of moves:  D — move one cell down;  R — move one cell right. The robot is not allowed to move outside the grid.You are given a sequence of moves $$$s$$$ — the initial path of the robot. This path doesn't lead the robot outside the grid.You are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.Count the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.

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 the single integer $$$n$$$ ($$$2 \le n \le 10^8$$$) — the number of rows and columns in the grid. The second line of each testcase contains a non-empty string $$$s$$$, consisting only of characters D and R, — the initial path of the robot. This path doesn't lead the robot outside the grid. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.

NoteIn the first testcase, it's enough to consider the following modified paths:   RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRRD $$$\rightarrow$$$ RRRDD $$$\rightarrow$$$ RRRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$ and $$$(4, 4)$$$;  RD $$$\rightarrow$$$ RRD $$$\rightarrow$$$ RRDD $$$\rightarrow$$$ RRDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 3)$$$ and $$$(4, 3)$$$;  RD $$$\rightarrow$$$ RDD $$$\rightarrow$$$ RDDD — this path visits cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ and $$$(4, 2)$$$. Thus, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ and $$$(4, 4)$$$.In the second testcase, there is no way to modify the sequence without moving the robot outside the grid. So the only visited cells are the ones that are visited on the path DRDRDRDR.In the third testcase, the cells that are visited on at least one modified path are: $$$(1, 1)$$$, $$$(2, 1)$$$ and $$$(3, 1)$$$.Here are the cells for all testcases:

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

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

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

    long f() {
        if (S.all!(c => c == 'D')) return N;
        if (S.all!(c => c == 'R')) return N;
        int M = S.length;
        auto T = new char[M];
        for (int i = 0; i < M; i++) {
            if (S[0] == 'D') {
                T[i] = S[i];
            } else {
                T[i] = (S[i] == 'D' ? 'R' : 'D');
            }
        }
        long ID = 0;
        for (int i = 0; i < M; i++) {
            if (T[i] == 'D') {
                ID++;
            } else {
                break;
            }
        }
        long Y = 1, X = 1;
        for (int i = 0; i < M; i++) {
            if (T[i] == 'D') {
                Y++;
            } else {
                X++;
            }
        }
        return X * (N - Y) + (Y - ID) * (N - X) + (N - Y) * (N - X) + M + 1;
    }
    writeln(f());

}


DZY loves strings, and he enjoys collecting them.In China, many people like to use strings containing their names' initials, for example: xyz, jcvb, dzy, dyh.Once DZY found a lucky string s. A lot of pairs of good friends came to DZY when they heard about the news. The first member of the i-th pair has name ai, the second one has name bi. Each pair wondered if there is a substring of the lucky string containing both of their names. If so, they want to find the one with minimum length, which can give them good luck and make their friendship last forever.Please help DZY for each pair find the minimum length of the substring of s that contains both ai and bi, or point out that such substring doesn't exist.A substring of s is a string slsl + 1... sr for some integers l, r (1 ≤ l ≤ r ≤ |s|). The length of such the substring is (r - l + 1).A string p contains some another string q if there is a substring of p equal to q.

The first line contains a string s (1 ≤ |s| ≤ 50000). The second line contains a non-negative integer q (0 ≤ q ≤ 100000) — the number of pairs. Each of the next q lines describes a pair, the line contains two space-separated strings ai and bi (1 ≤ |ai|, |bi| ≤ 4). It is guaranteed that all the strings only consist of lowercase English letters.

For each pair, print a line containing a single integer — the minimum length of the required substring. If there is no such substring, output -1.

NoteThe shortest substrings in the first sample are: xyz, dyhduxyz.The shortest substrings in the second sample are: ca, abc and abd.The shortest substrings in the third sample are: baabca and abaa.

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

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

//	chmin/chmax
void chmin(T)(ref T t, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

immutable L = 4;

int N;
string S;

void main(string[] args) {
	try {
	for (; ; ) {
		S = readToken;
		N = S.length;

		int[][] apps = new int[][27 ^^ L];
		foreach (i; 0 .. N) {
			int u;
			foreach (l; 0 .. L) if (i + l < N) {
				u = u * 27 + (S[i + l] - 'a' + 1);
				apps[u] ~= i;
			}
		}

		int[int][] cache = new int[int][27 ^^ L];

		foreach (q; 0 .. readInt) {
			string s = readToken;
			string t = readToken;
			int u, v;
			foreach (c; s) {
				u = u * 27 + (c - 'a' + 1);
			}
			foreach (c; t) {
				v = v * 27 + (c - 'a' + 1);
			}
debug{
writeln("apps[u] = ",apps[u]);
writeln("apps[v] = ",apps[v]);
writeln;
}
			if (pair(apps[u].length, u) > pair(apps[v].length, v)) {
				swap(s, t);
				swap(u, v);
			}
			int calcUnionLength(int i, int j) {
				return max(i + s.length, j + t.length) - min(i, j);
			}
			if (v !in cache[u]) {
				int ret = N + 1;
				foreach (i; apps[u]) {
					const idx = apps[v].lowerBound(i);
					if (idx - 1 >= 0) {
						chmin(ret, calcUnionLength(i, apps[v][idx - 1]));
					}
					if (idx < apps[v].length) {
						chmin(ret, calcUnionLength(i, apps[v][idx]));
					}
				}
				if (ret > N) {
					ret = -1;
				}
				cache[u][v] = ret;
			}
			writeln(cache[u][v]);
		}
	}
	} catch (EOFException) {}
}


You are given a chess board with $$$n$$$ rows and $$$n$$$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.A knight is a chess piece that can attack a piece in cell ($$$x_2$$$, $$$y_2$$$) from the cell ($$$x_1$$$, $$$y_1$$$) if one of the following conditions is met:  $$$|x_1 - x_2| = 2$$$ and $$$|y_1 - y_2| = 1$$$, or  $$$|x_1 - x_2| = 1$$$ and $$$|y_1 - y_2| = 2$$$. Here are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them).  A duel of knights is a pair of knights of different colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible.

The first line contains one integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of rows (and columns) in the board.

Print $$$n$$$ lines with $$$n$$$ characters in each line. The $$$j$$$-th character in the $$$i$$$-th line should be W, if the cell ($$$i$$$, $$$j$$$) contains a white knight, or B, if it contains a black knight. The number of duels should be maximum possible. If there are multiple optimal answers, print any of them.

NoteIn the first example, there are $$$8$$$ duels:  the white knight in ($$$1$$$, $$$1$$$) attacks the black knight in ($$$3$$$, $$$2$$$);  the white knight in ($$$1$$$, $$$1$$$) attacks the black knight in ($$$2$$$, $$$3$$$);  the white knight in ($$$1$$$, $$$3$$$) attacks the black knight in ($$$3$$$, $$$2$$$);  the white knight in ($$$1$$$, $$$3$$$) attacks the black knight in ($$$2$$$, $$$1$$$);  the white knight in ($$$3$$$, $$$1$$$) attacks the black knight in ($$$1$$$, $$$2$$$);  the white knight in ($$$3$$$, $$$1$$$) attacks the black knight in ($$$2$$$, $$$3$$$);  the white knight in ($$$3$$$, $$$3$$$) attacks the black knight in ($$$1$$$, $$$2$$$);  the white knight in ($$$3$$$, $$$3$$$) attacks the black knight in ($$$2$$$, $$$1$$$).

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

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

void solve(){
	int n = rint;
	foreach(i; 0 .. n){
		foreach(j; 0 .. n){
			if((i + j) % 2) "B".write;
			else "W".write;
		}
		"".writeln;
	}
}

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

string FMT_F = "%.10f";

static 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; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

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

void main()
{
	auto n = RD!int;
	auto ans = new char[][](n, n);
	ans[0][0] = 'W';
	ans[0][1] = 'B';
	ans[0][2] = 'W';
	ans[1][0] = 'B';
	ans[2][0] = 'W';
	ans[1][1] = 'W';

	bool visit(int y, int x, int c)
	{
		bool ok;
		if (inside(y, 0, n) && inside(x, 0, n))
		{
			if (ans[y][x] == char.init)
			{
				ans[y][x] = c == 0 ? 'B' : 'W';
				ok = true;
			}
		}
		return ok;
	}

	int[3][] open = [[0,0,0], [0,1,1], [0,2,0], [1,0,1], [2,0,0], [1,1,0]];
	while (!open.empty)
	{
		auto node = open.front; open.popFront;
		auto y = node[0];
		auto x = node[1];
		auto c = node[2];
		if (visit   (y-1, x-2, c))
			open ~= [y-1, x-2, c^1];
		if (visit   (y+1, x-2, c))
			open ~= [y+1, x-2, c^1];
		if (visit   (y-1, x+2, c))
			open ~= [y-1, x+2, c^1];
		if (visit   (y+1, x+2, c))
			open ~= [y+1, x+2, c^1];
		if (visit   (y-2, x-1, c))
			open ~= [y-2, x-1, c^1];
		if (visit   (y-2, x+1, c))
			open ~= [y-2, x+1, c^1];
		if (visit   (y+2, x-1, c))
			open ~= [y+2, x-1, c^1];
		if (visit   (y+2, x+1, c))
			open ~= [y+2, x+1, c^1];
	}

	foreach (y; 0..n)
	{
		writeln(ans[y]);
	}
	stdout.flush();
	debug readln();
}


Consider the array $$$a$$$ composed of all the integers in the range $$$[l, r]$$$. For example, if $$$l = 3$$$ and $$$r = 7$$$, then $$$a = [3, 4, 5, 6, 7]$$$.Given $$$l$$$, $$$r$$$, and $$$k$$$, is it possible for $$$\gcd(a)$$$ to be greater than $$$1$$$ after doing the following operation at most $$$k$$$ times?   Choose $$$2$$$ numbers from $$$a$$$.  Permanently remove one occurrence of each of them from the array.  Insert their product back into $$$a$$$. $$$\gcd(b)$$$ denotes the greatest common divisor (GCD) of the integers in $$$b$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The description of test cases follows. The input for each test case consists of a single line containing $$$3$$$ non-negative integers $$$l$$$, $$$r$$$, and $$$k$$$ ($$$1 \leq l \leq r \leq 10^9, \enspace 0 \leq k \leq r - l$$$).

For each test case, print "YES" if it is possible to have the GCD of the corresponding array greater than $$$1$$$ by performing at most $$$k$$$ operations, and "NO" otherwise (case insensitive).

NoteFor the first test case, $$$a = [1]$$$, so the answer is "NO", since the only element in the array is $$$1$$$.For the second test case the array is $$$a = [3, 4, 5]$$$ and we have $$$1$$$ operation. After the first operation the array can change to: $$$[3, 20]$$$, $$$[4, 15]$$$ or $$$[5, 12]$$$ all of which having their greatest common divisor equal to $$$1$$$ so the answer is "NO".For the third test case, $$$a = [13]$$$, so the answer is "YES", since the only element in the array is $$$13$$$.For the fourth test case, $$$a = [4]$$$, so the answer is "YES", since the only element in the array is $$$4$$$.

@safe:
import std;

T read (alias T, string ending = "", string preface = "") () @trusted {
    scope T x;
    readf!(preface ~ "%s" ~ ending)(x);
    return x;
}

void main () {
    immutable tests = read!(uint, "\n");

    foreach (test_index; 0 .. tests) {
        immutable l = read!(uint, " ");
        immutable r = read!(uint, " ");
        immutable k = read!(uint, "\n");

        if (r == l) {
            if (r == 1) {
                writeln("NO");
            } else {
                writeln("YES");
            }
            continue;
        }

        immutable count_div_by_2 = (){
            static assert(true);
            if (r % 2 == l % 2) {
                if (r % 2 == 0) {
                    return (r - l) / 2 + 1;
                } else {
                    return (r - l) / 2;
                }
            }
            return (r - l + 1) / 2;
        }();

        immutable count_not_div_by_2 = r - l + 1 - count_div_by_2;

        if (k >= count_not_div_by_2) {
            writeln("YES");
        } else {
            writeln("NO");
        }
    }
}
// ""

import std;

T read (alias T, string ending = "", string preface = "") () {
    scope T x;
    readf!(preface ~ "%s" ~ ending)(x);
    return x;
}

void main () {
    immutable tests = read!(uint, "\n");

    foreach (test_index; 0 .. tests) {
        immutable l = read!(uint, " ");
        immutable r = read!(uint, " ");
        immutable k = read!(uint, "\n");

        if (r == l) {
            if (r == 1) {
                writeln("NO");
            } else {
                writeln("YES");
            }
            continue;
        }

        immutable count_div_by_2 = (){
            static assert(true);
            if (r % 2 == l % 2) {
                if (r % 2 == 0) {
                    return (r - l) / 2 + 1;
                } else {
                    return (r - l) / 2;
                }
            }
            return (r - l + 1) / 2;
        }();

        immutable count_not_div_by_2 = r - l + 1 - count_div_by_2;

        if (k >= count_not_div_by_2) {
            writeln("YES");
        } else {
            writeln("NO");
        }
    }
}
// ""

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto L = scan!int;
      auto R = scan!int;
      auto K = scan!int;

      const evens = R/2 - (L-1)/2;
      const odds = R - L + 1 - evens;
      // [evens, odds].deb;

      if (R == L && L == 1) return "NO";
      if (R == L && L >  1) return "YES";

      return evens > 0 && odds <= K ? "YES" : "NO";
    }

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

  outputForAtCoder(&solve);
}

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

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

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

struct GridPoint {
  static enum ZERO = GridPoint(0, 0);
  long x, y;

  static GridPoint reversed(long y, long x) {
    return GridPoint(x, y);
  }

  this(long x, long y) {
    this.x = x;
    this.y = y;
  }

  inout GridPoint left() { return GridPoint(x - 1, y); }
  inout GridPoint right() { return GridPoint(x + 1, y); }
  inout GridPoint up() { return GridPoint(x, y - 1); }
  inout GridPoint down() { return GridPoint(x, y + 1); }
  inout GridPoint leftUp() { return GridPoint(x - 1, y - 1); }
  inout GridPoint leftDown() { return GridPoint(x - 1, y + 1); }
  inout GridPoint rightUp() { return GridPoint(x + 1, y - 1); }
  inout GridPoint rightDown() { return GridPoint(x + 1, y + 1); }
  inout GridPoint[] around() { return [left(), up(), right(), down()]; }
  inout GridPoint[] around(GridPoint max) { GridPoint[] ret; if (x > 0) ret ~= left; if(x < max.x-1) ret ~= right; if(y > 0) ret ~= up; if(y < max.y-1) ret ~= down; return ret; }
  inout T of(T)(inout ref T[][] grid) { return grid[cast(int)y][cast(int)x]; }
}

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

void solve(){
    long l = scan; long r = scan; long k = scan;
    long len = r - l + 1;
    if(len == 1){
        writeln( (l == 1) ? "NO" : "YES");
        return;
    }

    long tim = len / 2;
    if(r % 2 == 1 && l % 2 == 1){ tim += 1; }
    writeln( (k >= tim) ? "YES" : "NO");
}

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

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


Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1, m), then goes down 2 rows to (3, m), then goes left to (3, 1) and so on.Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').Consider sample tests in order to understand the snake pattern.

The only line contains two integers: n and m (3 ≤ n, m ≤ 50).  n is an odd number.

Output n lines. Each line should contain a string consisting of m characters. Do not output spaces.

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

struct IO {
        string read_string() {
                while (tokens.empty) {
                tokens = readln.split;
        }
        auto token = tokens.front;
                tokens.popFront;
                return token;
        }

        int read_int() {
                return read_string.to!int;
        }

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

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

                for (int i = 0; i < n; i++) {
                        for (int j = 0; j < m; j++) {
                                if (i % 2 == 0) {
                                        write("#");
                                } else {
                                        if (i % 4 == 1) {
                                                if (j < m - 1) write(".");
                                                else write("#");
                                        } else {
                                                if (j == 0) write("#");
                                                else write(".");
                                        }
                                }
                        }
                        writeln();
                }
        }
}

import std.stdio, std.array, std.conv;

void main(string[] args)
{
	int n, m;
	readf(" %s %s", &n, &m);

	char ch = '#';
	string snake = to!string(ch).replicate(m);
	string points = ".".replicate(m-1);

	foreach(row; 1..n+1)
		if(row % 2)
			writeln(snake);
		else if(row % 4)
			writeln(points ~ ch);
		else
			writeln(ch ~ points);
}

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

void main()
{
	byte n, m;

	readf(" %s %s", &n, &m);

	foreach (i; 0..n) {
		foreach (j; 0..m)
			if (i % 2) {
				foreach (k; 0..m - 1) {
					static byte tmp = 3;
					auto temp = i;
					if (temp == tmp) {
						write('#');
						foreach (l; 0..m - 1)
							write('.');
						tmp += 4;
						break;
					}
					else {
						write('.');
						if (k == m - 2)
							write('#');
					}
				}
				break;
			}
			else
				write('#');
		writeln();
	}
}

import std.stdio: writeln, stdin;
import std.string: strip;
import std.algorithm.iteration : map;
import std.regex;
import std.range;
import std.conv;

void main()
{
  auto nm = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto n=nm[0], m=nm[1];
  auto p1 = '#'.repeat().take(m).to!string;
  auto p23 = '.'.repeat().take(m-1).to!string;
  auto p2 = "#"~p23;
  auto p3 = p23~"#";

  for(int i = 1; i <= n; i++) {
    writeln( (i%2!=0) ? p1
            :(i/2)%2==0 ? p2
            : p3);
  }
}

import std.stdio;

int main()
{
	int n, m;
	readf("%d %d", &n, &m);
	char[] ol = new char[m];
	char[] el = new char[m];
	foreach (int i; 0..m)
	{
		ol[i] = '#';
		el[i] = '.';
	}
	foreach (int i; 0..n)
	{
		int idx = (i / 2) % 2 == 0 ? m-1 : 0;
		el[idx] = '#';
		write((i % 2 == 0 ? ol : el) ~ "\n");
		el[idx] = '.';
	}
	return 0;
}

import std.stdio;

void main() {
    int n, m;
    readf("%d %d\n", &n, &m);

    for (int i = 0; i < n; i++) {
        if (i % 2 == 0) {
            for (int j = 0; j < m; j++) {
                write("#");
            }
        } else if (i % 4 == 1) {
            for (int j = 0; j < m - 1; j++) {
                write(".");
            }
            write("#");
        } else {
            write("#");
            for (int j = 0; j < m - 1; j++) {
                write(".");
            }
        }

        writeln;
    }
}