Moamen has an array of $$$n$$$ distinct integers. He wants to sort that array in non-decreasing order by doing the following operations in order exactly once:  Split the array into exactly $$$k$$$ non-empty subarrays such that each element belongs to exactly one subarray.  Reorder these subarrays arbitrary.  Merge the subarrays in their new order. A sequence $$$a$$$ is a subarray of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Can you tell Moamen if there is a way to sort the array in non-decreasing order using the operations written above?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le |a_i| \le 10^9$$$). It is guaranteed that all numbers are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.

For each test case, you should output a single string. If Moamen can sort the array in non-decreasing order, output "YES" (without quotes). Otherwise, output "NO" (without quotes). You can print each letter of "YES" and "NO" in any case (upper or lower).

NoteIn the first test case, $$$a = [6, 3, 4, 2, 1]$$$, and $$$k = 4$$$, so we can do the operations as follows:   Split $$$a$$$ into $$$\{ [6], [3, 4], [2], [1] \}$$$.  Reorder them: $$$\{ [1], [2], [3,4], [6] \}$$$.  Merge them: $$$[1, 2, 3, 4, 6]$$$, so now the array is sorted. In the second test case, there is no way to sort the array by splitting it into only $$$2$$$ subarrays.As an example, if we split it into $$$\{ [1, -4], [0, -2] \}$$$, we can reorder them into $$$\{ [1, -4], [0, -2] \}$$$ or $$$\{ [0, -2], [1, -4] \}$$$. However, after merging the subarrays, it is impossible to get a sorted array.

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto k = readInt!int;
	auto a = ma(n, readInt!int);
	auto oa = a.dup;
	int[int] rnk;
	sort(a);
	foreach(i, ai; a) rnk[ai] = cast(int)i;
	oa = oa.map!(ai => rnk[ai]).array;
	int chunks = 0;
	int i = 0;
	while (i < n)
	{
		chunks++;
		while (i + 1 < n && oa[i + 1] == oa[i] + 1) i++;
		i++;
	}
	if (chunks <= k) writeln("YES"); else writeln("NO");
}

// main {{{
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;
}
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.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

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

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

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

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

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

		auto index = a.MAKE_IDX;
		foreach (ii, i; index)
		{
			a[i] = ii;
		}

		long cnt;
		foreach (i; 0..n-1)
		{
			if (a[i]+1 != a[i+1])
				++cnt;
		}
		ans[ti] = cnt < k;
	}

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


Bash likes playing with arrays. He has an array a1, a2, ... an of n integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.Suppose he guesses that the gcd of the elements in the range [l, r] of a is x. He considers the guess to be almost correct if he can change at most one element in the segment such that the gcd of the segment is x after making the change. Note that when he guesses, he doesn't actually change the array — he just wonders if the gcd of the segment can be made x. Apart from this, he also sometimes makes changes to the array itself.Since he can't figure it out himself, Bash wants you to tell him which of his guesses are almost correct. Formally, you have to process q queries of one of the following forms:  1 l r x — Bash guesses that the gcd of the range [l, r] is x. Report if this guess is almost correct.  2 i y — Bash sets ai to y. Note: The array is 1-indexed.

The first line contains an integer n (1 ≤ n ≤ 5·105)  — the size of the array. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109)  — the elements of the array. The third line contains an integer q (1 ≤ q ≤ 4·105)  — the number of queries. The next q lines describe the queries and may have one of the following forms:   1 l r x (1 ≤ l ≤ r ≤ n, 1 ≤ x ≤ 109).  2 i y (1 ≤ i ≤ n, 1 ≤ y ≤ 109).  Guaranteed, that there is at least one query of first type.

For each query of first type, output "YES" (without quotes) if Bash's guess is almost correct and "NO" (without quotes) otherwise.

NoteIn the first sample, the array initially is {2, 6, 3}. For query 1, the first two numbers already have their gcd as 2.For query 2, we can achieve a gcd of 3 by changing the first element of the array to 3. Note that the changes made during queries of type 1 are temporary and do not get reflected in the array. After query 3, the array is now {9, 6, 3}. For query 4, no matter which element you change, you cannot get the gcd of the range to be 2.

import std.algorithm, std.array, std.conv, std.numeric, std.stdio, std.string;
immutable int logHalf = 19, half = 1 << logHalf, limit = half << 1;
void main () {
	int n = readln.strip.to!int;
	auto a = readln.splitter.map !(to!int).array;
	auto t = new int [limit];
	foreach (i, c; a) t[i + half] = c;
	foreach_reverse (i; 1..half) t[i] = gcd (t[i * 2 + 0], t[i * 2 + 1]);

	void change (int pos, int v) {
		for (pos += half, t[pos] = v, pos >>= 1; pos; pos >>= 1)
			t[pos] = gcd (t[pos * 2 + 0], t[pos * 2 + 1]);
	}

	bool checkVertex (int pos, int v) {
		while (pos < half) {
			bool x = (t[pos * 2 + 0] % v != 0);
			bool y = (t[pos * 2 + 1] % v != 0);
			if (x && y) return false;
			pos = pos * 2 + y;
		}
		return true;
	}

	bool checkSegment (int lo, int hi, int v) {
		bool found = false;
		for (lo += half, hi += half; lo < hi; lo >>= 1, hi >>= 1) {
			if (lo & 1) {
				if (t[lo] % v != 0) {
					if (found || !checkVertex (lo, v)) return false;
					found = true;
				}
				lo += 1;
			}
			if (hi & 1) {
				hi -= 1;
				if (t[hi] % v != 0) {
					if (found || !checkVertex (hi, v)) return false;
					found = true;
				}
			}
		}
		return true;
	}

	int q = readln.strip.to!int;
	foreach (r; 0..q) {
		auto s = readln.splitter.map !(to!int).array;
		if (s[0] == 1) writeln (checkSegment (s[1] - 1, s[2] - 0, s[3]) ? "YES" : "NO");
		else change (s[1] - 1, s[2]);
	}
}

import std.algorithm, std.array, std.conv, std.numeric, std.stdio, std.string;
immutable H = 1 << 19, T = H * 2;
int [T] t;
void main () {
	int n, q, u, v, w, z;
	readf (" %s", &n);
	foreach (i; 0..n) readf (" %s", &t[i + H]);
	foreach_reverse (i; 1..H) t[i] = gcd (t[i * 2], t[i * 2 + 1]);

	void set (int p, int v) {
		for (t[p] = v, p >>= 1; p; p >>= 1)
			t[p] = gcd (t[p * 2], t[p * 2 + 1]);
	}

	int ver (int p, int v) {
		while (p < H) {
			int x = t[p * 2] % v, y = t[p * 2 + 1] % v;
			if (x && y) return 0;
			p = p * 2 + !x;
		}
		return 1;
	}

	int ask (int lo, int hi, int v) {
		for (int f; lo < hi; lo >>= 1, hi >>= 1) {
			if (lo & 1) {
				if (t[lo] % v) {
					if (f || !ver (lo, v)) return 0;
					f = 1;
				}
				lo += 1;
			}
			if (hi & 1) {
				hi -= 1;
				if (t[hi] % v) {
					if (f || !ver (hi, v)) return 0;
					f = 1;
				}
			}
		}
		return 1;
	}

	readf (" %s", &q);
	foreach (r; 0..q) {
		readf (" %s %s %s", &z, &u, &v);
		if (z < 2) {
			readf (" %s", &w);
			writeln (ask (u - 1 + H, v + H, w) ? "YES" : "NO");
		} else set (u - 1 + H, v);
	}
}

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

immutable int logHalf = 19;
immutable int half = 1 << logHalf;
immutable int limit = half << 1;

int gcd (int a, int b)
{
	while (a && b)
	{
		a %= b;
		if (a)
		{
			b %= a;
		}
	}
	return a + b;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto t = new int [limit];
		foreach (i, c; a)
		{
			t[i + half] = c;
		}
		foreach_reverse (i; 1..half)
		{
			t[i] = gcd (t[i * 2 + 0], t[i * 2 + 1]);
		}

		void change (int pos, int v)
		{
			pos += half;
			t[pos] = v;
			for (pos >>= 1; pos; pos >>= 1)
			{
				t[pos] = gcd (t[pos * 2 + 0], t[pos * 2 + 1]);
			}
		}

		bool checkVertex (int pos, int v)
		{
			while (pos < half)
			{
				bool x = (t[pos * 2 + 0] % v != 0);
				bool y = (t[pos * 2 + 1] % v != 0);
				if (x && y)
				{
					return false;
				}
				pos = pos * 2 + y;
			}
			return true;
		}

		bool checkSegment (int lo, int hi, int v)
		{
			bool found = false;
			for (lo += half, hi += half; lo < hi;
			    lo >>= 1, hi >>= 1)
			{
				if (lo & 1)
				{
					if (t[lo] % v != 0)
					{
						if (found ||
						    !checkVertex (lo, v))
						{
							return false;
						}
						found = true;
					}
					lo += 1;
				}
				if (hi & 1)
				{
					hi -= 1;
					if (t[hi] % v != 0)
					{
						if (found ||
						    !checkVertex (hi, v))
						{
							return false;
						}
						found = true;
					}
				}
			}
			return true;
		}

		auto q = readln.strip.to !(int);
		foreach (r; 0..q)
		{
			auto s = readln.splitter.map !(to !(int)).array;
			if (s[0] == 1)
			{
				writeln (checkSegment
				    (s[1] - 1, s[2] - 0, s[3]) ? "YES" : "NO");
			}
			else
			{
				change (s[1] - 1, s[2]);
			}
		}
	}
}

import std.numeric, std.stdio;
immutable H = 1 << 19, T = H * 2;
int [T] t;
int n, q, u, v, w, z;
void set (int p, int v) {
	for (t[p] = v, p >>= 1; p; p >>= 1) t[p] = gcd (t[p * 2], t[p * 2 + 1]);
}
int ver (int p, int v) {
	while (p < H) {
		int x = t[p * 2] % v, y = t[p * 2 + 1] % v;
		if (x && y) return 2;
		p = p * 2 + !x;
	}
	return 1;
}
int ask (int lo, int hi, int v) {
	for (int f; lo < hi; lo >>= 1, hi >>= 1) {
		if (lo & 1) f += (t[lo] % v) ? ver (lo, v) : 0, lo += 1;
		if (hi & 1) hi -= 1, f += (t[hi] % v) ? ver (hi, v) : 0;
		if (f > 1) return 0;
	}
	return 1;
}
void main () {
	readf (" %s", &n);
	foreach (i; 0..n) readf (" %s", &t[i + H]);
	foreach_reverse (i; 1..H) t[i] = gcd (t[i * 2], t[i * 2 + 1]);
	readf (" %s", &q);
	foreach (r; 0..q) {
		readf (" %s %s %s", &z, &u, &v);
		if (z < 2) readf (" %s", &w), writeln (ask (u - 1 + H, v + H, w) ? "YES" : "NO");
		else set (u - 1 + H, 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)); }

// T: monoid
// op: T * T -> T
// query(a, b): returns t_a ... t_{b-1}
class SegmentTree(T, alias op) {
  import std.functional : binaryFun;
  alias opFun = binaryFun!op;
  const(T) idT;

  int n;
  T[] ts;
  this(int n_, const(T) idT) {
    this.idT = idT;
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ts[] = idT;
  }
  this(inout(T)[] ts_, const(T) idT) {
    this.idT = idT;
    const n_ = cast(int)(ts_.length);
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ts[0 .. n] = idT;
    ts[n .. n + n_] = ts_[];
    ts[n + n_ .. n << 1] = idT;
    build();
  }
  ref T at(int a) {
    return ts[n + a];
  }
  void build() {
    foreach_reverse (a; 1 .. n) ts[a] = opFun(ts[a << 1], ts[a << 1 | 1]);
  }
  void set(int a, const(T) val) {
    ts[a += n] = val;
    for (; a >>= 1; ) ts[a] = opFun(ts[a << 1], ts[a << 1 | 1]);
  }
  void mulL(int a, const(T) val) {
    set(a, opFun(val, ts[a + n]));
  }
  void mulR(int a, const(T) val) {
    set(a, opFun(ts[a + n], val));
  }
  T query(int a, int b) const {
    T prodL = idT, prodR = idT;
    for (a += n, b += n; a < b; a >>= 1, b >>= 1) {
      if (a & 1) prodL = opFun(prodL, ts[a++]);
      if (b & 1) prodR = opFun(ts[--b], prodR);
    }
    return opFun(prodL, prodR);
  }
}

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

      auto seg = new SegmentTree!(int, gcd)(A, 0);
      bool solve(int l, int r, int x) {
        for (; ; ) {
          debug {
            // writeln(l, " ", r, " ", x);
          }
          if (r - l <= 1) {
            return true;
          }
          const mid = (l + r) / 2;
          debug {
            writefln("l = %s, r = %s, x = %s", l, r, x);
            writeln("seg.query(l, mid) = ", seg.query(l, mid));
            writeln("seg.query(mid, r) = ", seg.query(mid, r));
          }
          if (seg.query(l, mid) % x == 0) {
            l = mid;
          } else if (seg.query(mid, r) % x == 0) {
            r = mid;
          } else {
            return false;
          }
        }
      }

      debug {
        auto as = A.dup;
      }

      const Q = readInt();
      foreach (q; 0 .. Q) {
        const typ = readInt();
        switch (typ) {
          case 1: {
            const l = readInt() - 1;
            const r = readInt();
            const x = readInt();
            const ans = solve(l, r, x);
            writeln(ans ? "YES" : "NO");
            debug {
              const brt = (as[l .. r].count!(a => (a % x != 0)) <= 1);
              assert(brt == ans, format("%s %s %s %s; brt = %s, ans = %s", as, l, r, x, brt, ans));
            }
          } break;
          case 2: {
            const i = readInt() - 1;
            const y = readInt();
            seg.set(i, y);
            debug {
              as[i] = y;
            }
          } break;
          default: assert(false);
        }
      }
    }
  } catch (EOFException e) {
  }
}

import std.numeric, std.stdio;
immutable H = 1 << 19, T = H * 2;
int [T] t;
int n, q, u, v, w, z;
void set (int p, int v) {
	for (t[p] = v, p >>= 1; p; p >>= 1) t[p] = gcd (t[p * 2], t[p * 2 + 1]);
}
int ver (int p, int v) {
	while (p < H) {
		int x = t[p * 2] % v, y = t[p * 2 + 1] % v;
		if (x && y) return 2;
		p = p * 2 + !x;
	}
	return 1;
}
int ask (int lo, int hi, int v) {
	for (int f; lo < hi; lo >>= 1, hi >>= 1) {
		if (lo & 1) f += (t[lo] % v) && ver (lo, v), lo += 1;
		if (hi & 1) hi -= 1, f += (t[hi] % v) && ver (hi, v);
		if (f > 1) return 0;
	}
	return 1;
}
void main () {
	readf (" %s", &n);
	foreach (i; 0..n) readf (" %s", &t[i + H]);
	foreach_reverse (i; 1..H) t[i] = gcd (t[i * 2], t[i * 2 + 1]);
	readf (" %s", &q);
	foreach (r; 0..q) {
		readf (" %s %s %s", &z, &u, &v);
		if (z < 2) readf (" %s", &w), writeln (ask (u - 1 + H, v + H, w) ? "YES" : "NO");
		else set (u - 1 + H, 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)); }

// T: monoid
// op: T * T -> T
// query(a, b): returns t_a ... t_{b-1}
class SegmentTree(T, alias op) {
  import std.functional : binaryFun;
  alias opFun = binaryFun!op;
  const(T) idT;

  int n;
  T[] ts;
  this(int n_, const(T) idT) {
    this.idT = idT;
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ts[] = idT;
  }
  this(inout(T)[] ts_, const(T) idT) {
    this.idT = idT;
    const n_ = cast(int)(ts_.length);
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ts[0 .. n] = idT;
    ts[n .. n + n_] = ts_[];
    ts[n + n_ .. n << 1] = idT;
    build();
  }
  ref T at(int a) {
    return ts[n + a];
  }
  void build() {
    foreach_reverse (a; 1 .. n) ts[a] = opFun(ts[a << 1], ts[a << 1 | 1]);
  }
  void set(int a, const(T) val) {
    ts[a += n] = val;
    for (; a >>= 1; ) ts[a] = opFun(ts[a << 1], ts[a << 1 | 1]);
  }
  void mulL(int a, const(T) val) {
    set(a, opFun(val, ts[a + n]));
  }
  void mulR(int a, const(T) val) {
    set(a, opFun(ts[a + n], val));
  }
  T query(int a, int b) const {
    T prodL = idT, prodR = idT;
    for (a += n, b += n; a < b; a >>= 1, b >>= 1) {
      if (a & 1) prodL = opFun(prodL, ts[a++]);
      if (b & 1) prodR = opFun(ts[--b], prodR);
    }
    return opFun(prodL, prodR);
  }
}

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

      auto seg = new SegmentTree!(int, gcd)(A, 0);
      bool solve(int l, int r, int x) {
        for (; ; ) {
          debug {
            writeln(l, " ", r, " ", x);
          }
          if (r - l <= 1) {
            return true;
          }
          const mid = (l + r) / 2;
          if (seg.query(l, mid) % x == 0) {
            r = mid;
          } else if (seg.query(mid, r) % x == 0) {
            l = mid;
          } else {
            return false;
          }
        }
      }

      const Q = readInt();
      foreach (q; 0 .. Q) {
        const typ = readInt();
        switch (typ) {
          case 1: {
            const l = readInt() - 1;
            const r = readInt();
            const x = readInt();
            const ans = solve(l, r, x);
            writeln(ans ? "YES" : "NO");
          } break;
          case 2: {
            const i = readInt() - 1;
            const y = readInt();
            seg.set(i, y);
          } break;
          default: assert(false);
        }
      }
    }
  } catch (EOFException e) {
  }
}


Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.

The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj).

In a single line print a single integer — the answer to the problem.

module sigod.codeforces.p289A;

import std.stdio;

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

	long length = 0;

	foreach (i; 0 .. n) {
		int l, r;

		stdin.readf("%s %s", &l, &r);
		stdin.readln();

		length += r - l + 1;
	}

	stdout.writeln((k - length % k) % k);
}


n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and ai = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.You have to write a program which prints the number of the child to be eliminated on every step.

The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1). The next line contains k integer numbers a1, a2, ..., ak (1 ≤ ai ≤ 109).

Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.

NoteLet's consider first example:   In the first step child 4 is eliminated, child 5 becomes the leader.  In the second step child 2 is eliminated, child 3 becomes the leader.  In the third step child 5 is eliminated, child 6 becomes the leader.  In the fourth step child 6 is eliminated, child 7 becomes the leader.  In the final step child 1 is eliminated, child 3 becomes the leader.

import std.bigint,std.container,std.array,std.algorithm,std.conv,
std.functional,std.math,std.numeric,std.string,std.range,std.complex,
std.typecons,std.regex,std.random,std.uni,std.traits,std.variant;
import core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
alias make_pair mp;
alias binary_search bins;
alias gcd=std.numeric.gcd;
immutable int mod=1000000007;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b)
	{
		return a/gcd(a,b)*b;
	}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_)
	{
		pair!(X,Y) pp;
		pp.fi=x_;
		pp.se=y_;
		return pp;
	}
	big gcd(big a,big b)
	{
		while(b)
		{
			a%=b;
			swap(a,b);
		}
		return a;
	}
	X binpow(X,Y)(X base,Y exp)if(is(typeof(exp>>1)))
	{
		if(exp<0)return X(0);
		X res=X(1);
		while(exp>0)
		{
			if(exp&1)res*=base;
			base*=base;
			exp>>=1;
		}
		return res;
	}
	auto binpow(X,Y,Z)(X base,Y exp,in Z mm)if(is(typeof(exp>>1)) && is(typeof(base%mm)))
	{
		if(mm==0) return binpow(base,exp);
		if(exp<0)return X(0);
		auto res=X(1)%mm;
		while(exp>0)
		{
			if(exp&1)res=(res*base)%mm;
			base*=base;
			base%=mm;
			exp>>=1;
		}
		return res;
	}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g)if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~"\n", ptrs)==ptrs.length;}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.split.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n,k;
	loop:while(read(&n,&k))
	{
		auto a=arread!(int);
		auto b=iota(1,n+1).array;
		int p=0;
		foreach(i;0..k)
		{
			int pos=(p+a[i])%b.length;
			//debug writeln(a.length);
			write(b[pos],' ');
			if(pos==0)b=b[pos+1..$];
			else if(pos==b.length-1)b=b[0..pos];
			else b=b[0..pos]~b[pos+1..$];
			p=pos%b.length;
		}
	}
	debug system("pause");
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		auto p = iota (1, n + 1).array;
		int [] ans;
		foreach (v; a)
		{
			int q = v % p.length;
			ans ~= p[q];
			p = p[q + 1..$] ~ p[0..q];
		}
		writefln ("%(%s %)", ans);
	}
}


After getting bored by playing with crayons, you decided to switch to Legos! Today, you're working with a long strip, with height $$$1$$$ and length $$$n$$$, some positions of which are occupied by $$$1$$$ by $$$1$$$ Lego pieces.In one second, you can either remove two adjacent Lego pieces from the strip (if both are present), or add two Lego pieces to adjacent positions (if both are absent). You can only add or remove Lego's at two adjacent positions at the same time, as otherwise your chubby fingers run into precision issues.You want to know exactly how much time you'll spend playing with Legos. You value efficiency, so given some starting state and some ending state, you'll always spend the least number of seconds to transform the starting state into the ending state. If it's impossible to transform the starting state into the ending state, you just skip it (so you spend $$$0$$$ seconds).The issue is that, for some positions, you don't remember whether there were Legos there or not (in either the starting state, the ending state, or both). Over all pairs of (starting state, ending state) that are consistent with your memory, find the total amount of time it will take to transform the starting state to the ending state. Print this value modulo $$$1\,000\,000\,007$$$ ($$$10^9 + 7$$$).

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 2000$$$) — the size of the Lego strip. The second line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of the characters 0, 1, and ? — your memory of the starting state:    1 represents a position that definitely has a Lego piece,  0 represents a position that definitely does not have a Lego piece,  and ? represents a position that you don't remember.  The third line of each test case contains a string $$$t$$$ of length $$$n$$$, consisting of the characters 0, 1, and ? — your memory of the ending state. It follows a similar format to the starting state. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2000$$$.

For each test case, output a single integer — the answer to the problem modulo $$$1\,000\,000\,007$$$ ($$$10^9 + 7$$$).

NoteFor the first test case, $$$00$$$ is the only possible starting state, and $$$11$$$ is the only possible ending state. It takes exactly one operation to change $$$00$$$ to $$$11$$$.For the second test case, some of the possible starting and ending state pairs are:   $$$(000, 011)$$$ — takes $$$1$$$ operation.  $$$(001, 100)$$$ — takes $$$2$$$ operations.  $$$(010, 000)$$$ — takes $$$0$$$ operations, as it's impossible to achieve the ending state.

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

struct ModInt(uint M_) {
  import std.conv : to;
  alias M = M_;
  uint x;
  this(ModInt a) { x = a.x; }
  this(uint x_) { x = x_ % M; }
  this(ulong x_) { x = x_ % M; }
  this(int x_) { x = ((x_ %= cast(int)(M)) < 0) ? (x_ + cast(int)(M)) : x_; }
  this(long x_) { x = cast(uint)(((x_ %= cast(long)(M)) < 0) ? (x_ + cast(long)(M)) : x_); }
  ref ModInt opAssign(T)(inout(T) a) if (is(T == uint) || is(T == ulong) || is(T == int) || is(T == long)) { return this = ModInt(a); }
  ref ModInt opOpAssign(string op, T)(T a) {
    static if (is(T == ModInt)) {
      static if (op == "+") { x = ((x += a.x) >= M) ? (x - M) : x; }
      else static if (op == "-") { x = ((x -= a.x) >= M) ? (x + M) : x; }
      else static if (op == "*") { x = cast(uint)((cast(ulong)(x) * a.x) % M); }
      else static if (op == "/") { this *= a.inv(); }
      else static assert(false);
      return this;
    } else static if (op == "^^") {
      if (a < 0) return this = inv()^^(-a);
      ModInt b = this, c = 1U;
      for (long e = a; e; e >>= 1) { if (e & 1) c *= b; b *= b; }
      return this = c;
    } else {
      return mixin("this " ~ op ~ "= ModInt(a)");
    }
  }
  ModInt inv() const {
    uint a = M, b = x; int y = 0, z = 1;
    for (; b; ) { const q = a / b; const c = a - q * b; a = b; b = c; const w = y - cast(int)(q) * z; y = z; z = w; }
    assert(a == 1); return ModInt(y);
  }
  ModInt opUnary(string op)() const {
    static if (op == "+") { return this; }
    else static if (op == "-") { ModInt a; a.x = x ? (M - x) : 0U; return a; }
    else static assert(false);
  }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op, T)(T a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  bool opCast(T: bool)() const { return (x != 0U); }
  string toString() const { return x.to!string; }
}

enum MO = 1000000007;
alias Mint = ModInt!MO;

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        auto A = readToken.dup;
        auto B = readToken.dup;
        foreach (i; 0 .. N) if (i & 1) {
          if (A[i] != '?') A[i] ^= '0' ^ '1';
          if (B[i] != '?') B[i] ^= '0' ^ '1';
        }
        debug {
          writeln("A = ", A);
          writeln("B = ", B);
        }

        auto dp0 = new Mint[2][][](N + 1, N + 1);
        auto dp1 = new Mint[2][][](N + 1, N + 1);
        dp0[0][0][0] = 1;
        foreach (i; 0 .. N + 1) foreach (j; 0 .. N + 1) foreach (s; 0 .. 2) {
          if (s == 0) if (i < N && (A[i] == '?' || A[i] == '0')) {
            dp0[i + 1][j][0] += dp0[i][j][0];
            dp1[i + 1][j][0] += dp1[i][j][0];
          }
          if (j < N && (B[j] == '?' || B[j] == '0')) {
            dp0[i][j + 1][1] += dp0[i][j][s];
            dp1[i][j + 1][1] += dp1[i][j][s];
          }
          if (i < N && j < N && (A[i] == '?' || A[i] == '1') && (B[j] == '?' || B[j] == '1')) {
            dp0[i + 1][j + 1][0] += dp0[i][j][s];
            dp1[i + 1][j + 1][0] += dp0[i][j][s] * abs(i - j) + dp1[i][j][s];
          }
        }
        debug {
          writeln("dp0 = ", dp0);
          writeln("dp1 = ", dp1);
        }

        Mint ans;
        foreach (s; 0 .. 2) {
          ans += dp1[N][N][s];
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length $$$n$$$ consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements. Vasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is $$$0$$$, and removing $$$i$$$-th character increases the ambiguity by $$$a_i$$$ (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still $$$4$$$ even though you delete it from the string had).Vasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!Recall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the statement. The second line contains one string $$$s$$$ of length $$$n$$$, consisting of lowercase Latin letters — the statement written by Vasya. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 998244353$$$).

Print minimum possible ambiguity of the statement after Vasya deletes some (possibly zero) characters so the resulting statement is easy.

NoteIn the first example, first two characters are removed so the result is ardh.In the second example, $$$5$$$-th character is removed so the result is hhzawde.In the third example there's no need to remove anything.

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, core.stdc.string;

void main() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;
    auto A = readln.split.map!(to!long).array;

    auto dp = new long[][](N+1, 4);
    foreach (i; 0..N+1) fill(dp[i], 1L<<59);
    dp[0][0] = 0;

    foreach (i; 0..N) {
        dp[i+1] = dp[i].dup;
        if (S[i] == 'h') {
            dp[i+1][0] = dp[i][0] + A[i];
            dp[i+1][1] = min(dp[i][0], dp[i][1]);
        } else if (S[i] == 'a') {
            dp[i+1][1] = dp[i][1] + A[i];
            dp[i+1][2] = min(dp[i][1], dp[i][2]);
        } else if (S[i] == 'r') {
            dp[i+1][2] = dp[i][2] + A[i];
            dp[i+1][3] = min(dp[i][2], dp[i][3]);
        } else if (S[i] == 'd') {
            dp[i+1][3] = dp[i][3] + A[i];
        }
    }

    dp[N].reduce!min.writeln;
}

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

immutable int INF = 10L ^^ 9 + 23;

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

    auto s = "#" ~ readln.chomp;

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

    auto dp = new long[][] (n+1, 5);
    foreach (ref rw; dp) { rw.fill(0); }

    int [char] mp;
    mp['h'] = 1;
    mp['a'] = 2;
    mp['r'] = 3;
    mp['d'] = 4;
    foreach (i; 1 .. n+1) {
        dp[i][] = dp[i-1][];

        int k = mp.get(s[i], -1);
        if (k == -1) { continue; }

        dp[i][k-1] = min(dp[i-1][k-1] + c[i], k-1 > 0 ? dp[i-1][0 .. k-1].minElement : 10L ^^ 18);
        dp[i][k] = min(dp[i-1][k], dp[i-1][k-1]);
    }

    debug { dp.writeln; }

    dp[n][0 .. 4].minElement.writeln;
}

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

immutable int INF = 10L ^^ 9 + 23;

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

    auto s = "#" ~ readln.chomp;

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

    auto dp = new long[][] (n+1, 5);
    foreach (ref rw; dp) { rw.fill(0); }

    int [char] mp;
    mp['h'] = 1;
    mp['a'] = 2;
    mp['r'] = 3;
    mp['d'] = 4;
    foreach (i; 1 .. n+1) {
        dp[i][] = dp[i-1][];

        if (s[i] ! in mp) { continue; }
        int k = mp[s[i]];

        dp[i][k-1] = min(dp[i-1][k-1] + c[i], k-2 >= 0 ? dp[i-1][k-2] : 10L ^^ 18);
        dp[i][k] = min(dp[i-1][k], dp[i-1][k-1]);

        debug { dp[i][k].writeln; }
    }

    debug { dp.writeln; }

    dp[n][0 .. 4].minElement.writeln;
}

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

enum inf3 = 1_001_001_001;
enum inf6 = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;

void main() {
    int n;
    scan(n);
    auto s = readln.chomp;
    auto a = readln.split.to!(long[]);

    auto t = "hard";
    auto m = t.length.to!int;

    auto dp = new long[][](n + 1, m + 1);
    fillAll(dp, inf6);
    dp[0][0] = 0;

    foreach (i ; 0 .. n) {
        foreach (j ; 0 .. m + 1) {
            if (j < m && s[i] == t[j]) {
                dp[i+1][j+1] = min(dp[i+1][j+1], dp[i][j]);
                dp[i+1][j] = min(dp[i+1][j], dp[i][j] + a[i]);
            }
            else {
                dp[i+1][j] = min(dp[i+1][j], dp[i][j]);
            }
        }
    }

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

    long ans = inf6;

    foreach (j ; 0 .. m) {
        ans = min(ans, dp[n][j]);
    }

    writeln(ans);
}

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

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

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

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

  int n;
  rd(n);
  auto s = readln.chomp.to!(char[]);
  auto a = readln.split.to!(long[]);

  const char[] pat = "hard";
  auto dp = new long[](pat.length + 1);
  fill(dp, 1_000_000_000_000_000_000);
  dp[0] = 0;
  foreach (i; 0 .. n) {
    auto nex = new long[](pat.length + 1);
    fill(nex, 1_000_000_000_000_000_000);
    foreach (j, c; pat) {
      if (s[i] == c) {
        nex[j] = min(nex[j], dp[j] + a[i]);
        nex[j + 1] = min(nex[j + 1], dp[j]);
      } else {
        nex[j] = min(nex[j], dp[j]);
      }
    }
    dp.swap(nex);
  }
  writeln(reduce!(min)(dp[0 .. (pat.length)]));
}

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

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

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

  int n;
  rd(n);
  auto s = readln.chomp.to!(char[]);
  auto a = readln.split.to!(long[]);

  const char[] pat = "hard";
  auto dp = new long[](pat.length + 1);
  fill(dp, 1_000_000_000_000_000_000);
  dp[0] = 0;
  foreach (i; 0 .. n) {
    auto nex = new long[](pat.length + 1);
    fill(nex, 1_000_000_000_000_000_000);
    foreach (j, c; pat) {
      if (s[i] == c) {
        nex[j] = min(nex[j], dp[j] + a[i]); // s[i]を消す
        nex[j + 1] = min(nex[j + 1], dp[j]); // 消さない
      } else {
        nex[j] = min(nex[j], dp[j]); // 消さない
      }
    }
    dp.swap(nex);
  }
  writeln(reduce!(min)(dp[0 .. (pat.length)]));
}

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

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

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

  int n;
  rd(n);
  auto s = readln.chomp.to!(char[]);
  auto a = readln.split.to!(long[]);

  const char[] pat = "hard";
  auto dp = new long[][](n + 1, pat.length + 1);
  foreach (i; 0 .. (n + 1))
    fill(dp[i], 1_000_000_000_000_000_000);
  dp[0][0] = 0;
  foreach (i; 0 .. n) {
    foreach (j, c; pat) {
      if (s[i] == c) {
        dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + a[i]);
        dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j]);
      } else {
        dp[i + 1][j] = min(dp[i + 1][j], dp[i][j]);
      }
    }
  }
  writeln(reduce!(min)(dp[n][0 .. (pat.length)]));
}

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

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

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

immutable int INF = 10L ^^ 9 + 23;

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

    auto s = "#" ~ readln.chomp;

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

    auto dp = new long[][] (n+1, 5);
    foreach (ref rw; dp) { rw.fill(0); }

    int [char] mp;
    mp['h'] = 1;
    mp['a'] = 2;
    mp['r'] = 3;
    mp['d'] = 4;
    foreach (i; 1 .. n+1) {
        dp[i][] = dp[i-1][];

        if (s[i] ! in mp) { continue; }
        int k = mp[s[i]];

        dp[i][k-1] = min(dp[i-1][k-1] + c[i], k-1 > 0 ? dp[i-1][0 .. k-1].minElement : 10L ^^ 18);
        dp[i][k] = max(dp[i-1][k], dp[i-1][k-1]);
    }

    debug { dp.writeln; }

    dp[n][0 .. 4].minElement.writeln;
}

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

  int n;
  rd(n);
  auto s = readln.chomp.to!(char[]);
  auto a = readln.split.to!(long[]);

  const char[] pat = "hard";
  auto dp = new long[][](n + 1, pat.length + 1);
  foreach (i; 0 .. (n + 1))
    fill(dp[i], 1_000_000_000_000_000_000);
  dp[0][0] = 0;
  foreach (i; 0 .. n) {
    foreach (j, c; pat) {
      if (s[i] == c) {
        dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + a[i]);
        dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j]);
      } else {
        dp[i + 1][j] = min(dp[i + 1][j], dp[i][j]);
      }
    }
  }
  writeln(reduce!(min)(dp[n]));
}

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

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


You are given a matrix $$$a$$$ of size $$$n \times m$$$ consisting of integers.You can choose no more than $$$\left\lfloor\frac{m}{2}\right\rfloor$$$ elements in each row. Your task is to choose these elements in such a way that their sum is divisible by $$$k$$$ and this sum is the maximum.In other words, you can choose no more than a half (rounded down) of elements in each row, you have to find the maximum sum of these elements divisible by $$$k$$$.Note that you can choose zero elements (and the sum of such set is $$$0$$$).

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m, k \le 70$$$) — the number of rows in the matrix, the number of columns in the matrix and the value of $$$k$$$. The next $$$n$$$ lines contain $$$m$$$ elements each, where the $$$j$$$-th element of the $$$i$$$-th row is $$$a_{i, j}$$$ ($$$1 \le a_{i, j} \le 70$$$).

Print one integer — the maximum sum divisible by $$$k$$$ you can obtain.

NoteIn the first example, the optimal answer is $$$2$$$ and $$$4$$$ in the first row, $$$5$$$ and $$$2$$$ in the second row and $$$7$$$ and $$$4$$$ in the third row. The total sum is $$$2 + 4 + 5 + 2 + 7 + 4 = 24$$$.

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

immutable int infinity = int.max / 4;

void main ()
{
	int n, m, k;
	while (readf !(" %s %s %s") (n, m, k) > 0)
	{
		readln;
		int [] [] a;
		foreach (row; 0..n)
		{
			a ~= readln.splitter.map !(to !(int)).array;
		}
		auto f = new int [] [] (n, k);
		foreach (row; 0..n)
		{
			auto g = new int [] [] (m + 1, k);
			foreach (ref line; g)
			{
				line[] = -infinity;
			}
			g[0][0] = 0;
			foreach (col; 0..m)
			{
				foreach_reverse (num; 0..col + 1)
				{
					foreach (u; 0..k)
					{
						auto v = (u + a[row][col]) % k;
						g[num + 1][v] =
						    max (g[num + 1][v],
						    g[num][u] + a[row][col]);
					}
				}
			}
			f[row][] = -infinity;
			foreach (u; 0..k)
			{
				foreach (z; 0..m / 2 + 1)
				{
					f[row][u] = max (f[row][u], g[z][u]);
				}
			}
		}
		auto h = new int [] [] (2, k);
		int b = 0;
		h[b][] = -infinity;
		h[b][0] = 0;
		foreach (row; 0..n)
		{
			b ^= 1;
			h[b][] = -infinity;
			foreach (u; 0..k)
			{
				foreach (v; 0..k)
				{
					auto w = (u + v) % k;
					h[b][w] = max (h[b][w],
					    h[!b][u] + f[row][v]);
				}
			}
		}
		writeln (h[b][0]);
	}
}

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

immutable int infinity = int.max / 4;

void main ()
{
	int n, m, k;
	while (readf !(" %s %s %s") (n, m, k) > 0)
	{
		readln;
		int [] [] a;
		foreach (row; 0..n)
		{
			a ~= readln.splitter.map !(to !(int)).array;
		}
		auto f = new int [] [] (n, k);
		foreach (row; 0..n)
		{
			auto g = new int [] [] (m + 1, k);
			foreach (ref line; g)
			{
				line[] = -infinity;
			}
			g[0][0] = 0;
			foreach (col; 0..m)
			{
				foreach_reverse (num; 0..col + 1)
				{
					foreach (u; 0..k)
					{
						auto v = (u + a[row][col]) % k;
						g[num + 1][v] =
						    max (g[num + 1][v],
						    g[num][u] + a[row][col]);
					}
				}
			}
			foreach (u; 0..k)
			{
				foreach (z; 0..m / 2 + 1)
				{
					f[row][u] = max (f[row][u], g[z][u]);
				}
			}
		}
		auto h = new int [] [] (2, k);
		int b = 0;
		h[b][] = -infinity;
		h[b][0] = 0;
		foreach (row; 0..n)
		{
			b ^= 1;
			h[b][] = -infinity;
			foreach (u; 0..k)
			{
				foreach (v; 0..k)
				{
					auto w = (u + v) % k;
					h[b][w] = max (h[b][w],
					    h[!b][u] + f[row][v]);
				}
			}
		}
		writeln (h[b][0]);
	}
}


Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $$$s$$$ of length $$$n$$$.Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string $$$s$$$.She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string $$$s$$$ a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$2 \cdot t$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print the minimum number of erased symbols required to make the string a palindrome, if it is possible, and $$$-1$$$, if it is impossible.

5
8
abcaacab
6
xyzxyz
4
abba
8
rprarlap
10
khyyhhyhky

NoteIn the first test case, you can choose a letter 'a' and erase its first and last occurrences, you will get a string 'bcaacb', which is a palindrome. You can also choose a letter 'b' and erase all its occurrences, you will get a string 'acaaca', which is a palindrome as well.In the second test case, it can be shown that it is impossible to choose a letter and erase some of its occurrences to get a palindrome.In the third test case, you don't have to erase any symbols because the string is already a palindrome.

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = long.max;
		foreach (i; 0..26)
		{
			long cnt;
			int l, r = n-1;
			bool ok = true;
			while (l < r)
			{
				if (s[l] != s[r])
				{
					if (s[l]-'a' == i)
					{
						++l;
						++cnt;
						continue;
					}
					else if (s[r]-'a' == i)
					{
						--r;
						++cnt;
						continue;
					}
					else
						ok = false;
				}
				++l; --r;
			}
			if (ok)
				ans[ti].chmin(cnt);
		}
	}

	foreach (e; ans)
		writeln(e == long.max ? -1 : e);
	stdout.flush;
	debug readln;
}


A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand. One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.

The first line indicates the door through which the very important person entered the elevator. It contains "front" if the person enters the elevator through the front door and "back" if he entered the elevator through the back door. The second line contains integer a (1 ≤ a ≤ 2) which denotes the number of the rail at which the person was holding.

Print character "R" if the VIP is right-handed or "L" if he is left-handed.

//ahmat
import std.stdio,std.string,std.math,std.algorithm,
std.array,std.container,std.algorithm,std.numeric,std.bitmanip,
std.range,std.random,std.complex,std.functional,std.typecons,
std.format,std.bigint,core.vararg,core.bitop,std.conv;
int sz(T)(ref T a){return cast(int)a.length;}
alias rbt=RedBlackTree;
alias deq=DList;
alias heap=BinaryHeap;
const long mod=1000_000_007;

void main(){
    auto fin=File("input.txt","r"),fout=File("output.txt","w");
    string s=fin.readln.strip;
    int a;
    fin.readf("%d",&a);//readln;
    char r;
    if(s=="front") r=(a==1?'L':'R');
    else r=(a==1?'R':'L');
    fout.writeln(r);
}


Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.Formally, her room can be represented as a field of n × m cells, each cell of which is empty or littered with cans.Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.

The first line contains three integers n, m and k (1 ≤ n, m, k ≤ 1000) — the sizes of the room and Olya's speed. Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise. The last line contains four integers x1, y1, x2, y2 (1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m) — the coordinates of the first and the last cells.

Print a single integer — the minimum time it will take Olya to get from (x1, y1) to (x2, y2). If it's impossible to get from (x1, y1) to (x2, y2), print -1.

NoteIn the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.Olya does not recommend drinking energy drinks and generally believes that this is bad.

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.typecons;

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

    string[] arr;
    foreach (_; 0 .. n) {
        arr ~= readln.chomp;
    }

    int x1, y1, x2, y2;
    readf("%s %s %s %s", &x1, &y1, &x2, &y2);
    readln;

    --x1, --y1;
    --x2, --y2;

    auto step = new int[][] (n, m);
    foreach (rw; 0 .. n) { step[rw][] = -1; }

    auto d = [[0, 1], [-1, 0], [0, -1], [1, 0]];

    alias t = Tuple!(int, int);
    auto q = make!(DList!t);
    step[x1][y1] = 0;
    q ~= tuple(x1, y1);
    while (!q.empty()) {
        auto v = q.front();
        q.removeFront();

        debug { writeln(v[0], ' ', v[1]); }

        foreach (cd; d) {
            int cx = v[0], cy = v[1];
            foreach (_; 0 .. k) {
                cx += cd[0], cy += cd[1];

                if (cx >= n || cx < 0 || cy >= m || cy < 0) { break; }
                if (arr[cx][cy] == '#') { break; }
                if (step[cx][cy] != -1 && step[cx][cy] <= step[v[0]][v[1]]) { break; }

                if (step[cx][cy] == -1 || step[v[0]][v[1]] + 1 < step[cx][cy]) {
                    step[cx][cy] = step[v[0]][v[1]] + 1;
                    q ~= tuple(cx, cy);
                }
            }
        }
    }

    auto ans = step[x2][y2];
    ans.writeln;
}

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.typecons;

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

    string[] arr;
    foreach (_; 0 .. n) {
        arr ~= readln.chomp;
    }

    int x1, y1, x2, y2;
    readf("%s %s %s %s", &x1, &y1, &x2, &y2);
    readln;

    --x1, --y1;
    --x2, --y2;

    immutable int INF = 10 ^^ 9 + 23;
    auto step = new int[][] (n, m);
    foreach (rw; 0 .. n) { step[rw][] = INF; }

    auto d = [[0, 1], [-1, 0], [0, -1], [1, 0]];

    alias t = Tuple!(int, int);
    auto q = make!(DList!t);
    step[x1][y1] = 0;
    q ~= tuple(x1, y1);
    while (!q.empty()) {
        auto sx = q.front()[0], sy = q.front()[1];
        q.removeFront();

        debug { writeln(sx, ' ', sy); }

        foreach (cd; d) {
            int cx = sx, cy = sy;
            foreach (_; 0 .. k) {
                cx += cd[0], cy += cd[1];

                if (cx >= n || cx < 0 || cy >= m || cy < 0) { break; }
                if (arr[cx][cy] == '#') { break; }
                if (step[cx][cy] <= step[sx][sy]) { break; }

                if (step[sx][sy] + 1 < step[cx][cy]) {
                    step[cx][cy] = step[sx][sy] + 1;
                    q ~= tuple(cx, cy);
                }
            }
        }
    }

    auto ans = step[x2][y2] != INF ? step[x2][y2] : -1;
    ans.writeln;
}

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.typecons;

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

    string[] arr;
    foreach (_; 0 .. n) {
        arr ~= readln.chomp;
    }

    int x1, y1, x2, y2;
    readf("%s %s %s %s", &x1, &y1, &x2, &y2);
    readln;

    --x1, --y1;
    --x2, --y2;

    auto step = new int[][] (n, m);
    foreach (rw; 0 .. n) { step[rw][] = -1; }

    auto d = [[0, 1], [-1, 0], [0, -1], [1, 0]];

    alias t = Tuple!(int, int);
    auto q = make!(DList!t);
    step[x1][y1] = 0;
    q ~= tuple(x1, y1);
    while (!q.empty()) {
        auto v = q.front();
        q.removeFront();

        debug { writeln(v[0], ' ', v[1]); }

        foreach (cd; d) {
            int cx = v[0], cy = v[1];
            foreach (_; 0 .. k) {
                cx += cd[0], cy += cd[1];

                if (cx >= n || cx < 0 || cy >= m || cy < 0) { break; }
                if (arr[cx][cy] == '#') { break; }
                if (step[cx][cy] != -1 && step[cx][cy] <= step[v[0]][v[1]] + 1) { break; }

                step[cx][cy] = step[v[0]][v[1]] + 1;
                q ~= tuple(cx, cy);
            }
        }
    }

    auto ans = step[x2][y2];
    ans.writeln;
}

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.typecons;

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

    string[] arr;
    foreach (_; 0 .. n) {
        arr ~= readln.chomp;
    }

    int x1, y1, x2, y2;
    readf("%s %s %s %s", &x1, &y1, &x2, &y2);
    readln;

    --x1, --y1;
    --x2, --y2;

    auto step = new int[][] (n, m);
    foreach (rw; 0 .. n) { step[rw][] = -1; }

    auto d = [[0, 1], [-1, 0], [0, -1], [1, 0]];

    alias t = Tuple!(int, int);
    auto q = make!(DList!t);
    step[x1][y1] = 0;
    q ~= tuple(x1, y1);
    while (!q.empty()) {
        auto v = q.front();
        q.removeFront();

        debug { writeln(v[0], ' ', v[1]); }

        foreach (cd; d) {
            int cx = v[0], cy = v[1];
            foreach (_; 0 .. k) {
                cx += cd[0], cy += cd[1];

                if (cx >= n || cx < 0 || cy >= m || cy < 0) { break; }
                if (arr[cx][cy] == '#') { break; }
                if (step[cx][cy] >= 0) { break; }

                step[cx][cy] = step[v[0]][v[1]] + 1;
                q ~= tuple(cx, cy);
            }
        }
    }

    auto ans = step[x2][y2];
    ans.writeln;
}


Polycarp has a string $$$s$$$ consisting of lowercase Latin letters.He encodes it using the following algorithm.He goes through the letters of the string $$$s$$$ from left to right and for each letter Polycarp considers its number in the alphabet:  if the letter number is single-digit number (less than $$$10$$$), then just writes it out;  if the letter number is a two-digit number (greater than or equal to $$$10$$$), then it writes it out and adds the number 0 after. For example, if the string $$$s$$$ is code, then Polycarp will encode this string as follows:  'c' — is the $$$3$$$-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3);  'o' — is the $$$15$$$-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150);  'd' — is the $$$4$$$-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504);  'e' — is the $$$5$$$-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045). Thus, code of string code is 315045.You are given a string $$$t$$$ resulting from encoding the string $$$s$$$. Your task is to decode it (get the original string $$$s$$$ by $$$t$$$).

The first line of the input contains an integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the input. The descriptions of the test cases follow. The first line of description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of the given code. The second line of the description of each test case contains a string $$$t$$$ of length $$$n$$$ — the given code. It is guaranteed that there exists such a string of lowercase Latin letters, as a result of encoding which the string $$$t$$$ is obtained.

For each test case output the required string $$$s$$$ — the string that gives string $$$t$$$ as the result of encoding. It is guaranteed that such a string always exists. It can be shown that such a string is always unique.

code
aj
abacaba
ll
codeforces
aaaak
aaaaj
aaaaa
zf

NoteThe first test case is explained above.In the second test case, the answer is aj. Indeed, the number of the letter a is equal to $$$1$$$, so 1 will be appended to the code. The number of the letter j is $$$10$$$, so 100 will be appended to the code. The resulting code is 1100.There are no zeros in the third test case, which means that the numbers of all letters are less than $$$10$$$ and are encoded as one digit. The original string is abacaba.In the fourth test case, the string $$$s$$$ is equal to ll. The letter l has the number $$$12$$$ and is encoded as 120. So ll is indeed 120120.

import core.stdc.stdio;
import std.stdio;
import std.string;
import std.conv;
import std.array;

void solve() {
    int N; scanf("%d\n", &N);
    string t = readln.chop;
    auto buf = appender!(int[])();
    for (int i = N - 1; i >= 0; ) {
        if (t[i] == '0') {
            buf.put(t[i-2 .. i].to!int);
            i -= 3;
        } else {
            buf.put(t[i .. i+1].to!int);
            i -= 1;
        }
    }
    auto ans = appender!string();
    foreach_reverse (x; buf) {
        ans.put( to!char(int('a') - 1 + x.to!int) );
    }
    writeln(ans.array);
}

void main() {
    int Q; scanf("%d\n", &Q);
    foreach (q ; 0 .. Q) {
        solve();
    }
}


You have a statistic of price changes for one product represented as an array of $$$n$$$ positive integers $$$p_0, p_1, \dots, p_{n - 1}$$$, where $$$p_0$$$ is the initial price of the product and $$$p_i$$$ is how the price was increased during the $$$i$$$-th month.Using these price changes you are asked to calculate the inflation coefficients for each month as the ratio of current price increase $$$p_i$$$ to the price at the start of this month $$$(p_0 + p_1 + \dots + p_{i - 1})$$$.Your boss said you clearly that the inflation coefficients must not exceed $$$k$$$ %, so you decided to increase some values $$$p_i$$$ in such a way, that all $$$p_i$$$ remain integers and the inflation coefficients for each month don't exceed $$$k$$$ %.You know, that the bigger changes — the more obvious cheating. That's why you need to minimize the total sum of changes.What's the minimum total sum of changes you need to make all inflation coefficients not more than $$$k$$$ %?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 100$$$; $$$1 \le k \le 100$$$) — the length of array $$$p$$$ and coefficient $$$k$$$. The second line of each test case contains $$$n$$$ integers $$$p_0, p_1, \dots, p_{n - 1}$$$ ($$$1 \le p_i \le 10^9$$$) — the array $$$p$$$.

For each test case, print the minimum total sum of changes you need to make all inflation coefficients not more than $$$k$$$ %.

NoteIn the first test case, you can, for example, increase $$$p_0$$$ by $$$50$$$ and $$$p_1$$$ by $$$49$$$ and get array $$$[20150, 50, 202, 202]$$$. Then you get the next inflation coefficients:   $$$\frac{50}{20150} \le \frac{1}{100}$$$;  $$$\frac{202}{20150 + 50} \le \frac{1}{100}$$$;  $$$\frac{202}{20200 + 202} \le \frac{1}{100}$$$; In the second test case, you don't need to modify array $$$p$$$, since the inflation coefficients are already good:   $$$\frac{1}{1} \le \frac{100}{100}$$$;  $$$\frac{1}{1 + 1} \le \frac{100}{100}$$$;

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto x = p[0];
		foreach (i; 1..n)
		{
			auto y = p[i] * 100;
			auto d = y - x * k;
			if (d > 0)
			{
				d = (d+k-1) / k;
				ans[ti] += d;
				p[i] += d;
			}
			x += p[i];
		}
	}

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

import std.stdio, std.string, std.algorithm, std.conv, std.range;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n, k;
        readf!"%d %d\n"(n, k);
        long[] a = readln.split.map!(to!long).array;
        long s = a[0], res = 0;
        foreach (i; 1 .. n)
        {
            res = max(res, (100 * a[i] - k * s + k - 1) / k);
            s += a[i];
        }
        writeln(res);
    }
}

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int N; long K; get(N, K);
        long[] ps; get(ps);
        long r, q = ps[0];
        foreach (p; ps[1..$]) {
            auto a = p * 100;
            auto b = q * K;
            if (a > b) {
                auto c = (a - b + K - 1) / K;
                q += c;
                r += c;
            }
            q += p;
        }
        writeln(r);
    }
}

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

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

		bool ok (long start)
		{
			long cur = start + p[0];
			foreach (i; 1..n)
			{
				if (cur * k < p[i] * 100L)
				{
					return false;
				}
				cur += p[i];
			}
			return true;
		}

		long lo = 0;
		long hi = 10L ^^ 12;
		while (lo < hi)
		{
			long me = (lo + hi) >> 1;
			if (ok (me))
			{
				hi = me;
			}
			else
			{
				lo = me + 1;
			}
		}
		writeln (lo);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto x = p[0];
		foreach (i; 1..n)
		{
			auto y = p[i] * 100;
			auto d = y - x * k;
			if (d > 0)
			{
				ans[ti] += d;
				p[i] += d;
			}
			x += p[i];
		}
	}

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


Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he:   will buy exactly $$$n$$$ shovels in total;  the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.

Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.

NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.

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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n, k;

  void solve(long tc = -1)
  {
    auto divs = redBlackTree!long();
    for(long d = 1; d * d <= n; d++)
      if (n % d == 0)
        {
          divs.insert(d);
          divs.insert(n / d);
        }
    auto bdiv = divs.lowerBound(k + 1).back;
    writeln(n / bdiv);
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

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

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

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

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

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = long.max;
		for (long i = 1; i*i <= n; ++i)
		{
			if (n % i == 0)
			{
				if (i <= k)
				{
					ans[ti].chmin(n / i);
				}
				if (n / i <= k)
				{
					ans[ti].chmin(i);
				}
			}
		}
	}

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


There are $$$n$$$ houses in a row. They are numbered from $$$1$$$ to $$$n$$$ in order from left to right. Initially you are in the house $$$1$$$.You have to perform $$$k$$$ moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current house). If you go from the house $$$x$$$ to the house $$$y$$$, the total distance you walked increases by $$$|x-y|$$$ units of distance, where $$$|a|$$$ is the absolute value of $$$a$$$. It is possible to visit the same house multiple times (but you can't visit the same house in sequence).Your goal is to walk exactly $$$s$$$ units of distance in total.If it is impossible, print "NO". Otherwise print "YES" and any of the ways to do that. Remember that you should do exactly $$$k$$$ moves.

The first line of the input contains three integers $$$n$$$, $$$k$$$, $$$s$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le k \le 2 \cdot 10^5$$$, $$$1 \le s \le 10^{18}$$$) — the number of houses, the number of moves and the total distance you want to walk.

If you cannot perform $$$k$$$ moves with total walking distance equal to $$$s$$$, print "NO". Otherwise print "YES" on the first line and then print exactly $$$k$$$ integers $$$h_i$$$ ($$$1 \le h_i \le n$$$) on the second line, where $$$h_i$$$ is the house you visit on the $$$i$$$-th move. For each $$$j$$$ from $$$1$$$ to $$$k-1$$$ the following condition should be satisfied: $$$h_j \ne h_{j + 1}$$$. Also $$$h_1 \ne 1$$$ should be satisfied.

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.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

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

    if (k > s || cast(long)(n-1) * k < s) {
        writeln("NO");
        return;
    }

    writeln("YES");
    auto ans = [1];
    while (k--) {
        auto step = cast(int) min(n-1, s - k);
        s -= step;
        if (ans.back + step <= n) ans ~= ans.back + step;
        else ans ~= ans.back - step;
    }

    ans.dropOne.writefln!("%(%s %)");
}

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

void main ()
{
	int n, k;
	long s;
	while (readf (" %s %s %s", &n, &k, &s) > 0)
	{
		if (s < k || (n - 1) * 1L * k < s)
		{
			writeln ("NO");
			continue;
		}
		writeln ("YES");
		int pos = 1;
		int dir = +1;
		int [] ans;
		foreach (i; 0..k)
		{
			int len = (dir > 0) ? (n - pos) : (pos - 1);
			len = min (len, s - (k - i - 1)).to !(int);
			assert (len > 0);
			s -= len;
			pos += len * dir;
			ans ~= pos;
			if (pos == 1 || pos == n)
			{
				dir *= -1;
			}
		}
		writefln ("%(%s %)", ans);
	}
}

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.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

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

    if (cast(long)(n-1) * k < s) {
        writeln("NO");
        return;
    }

    writeln("YES");
    auto ans = [1];
    while (k--) {
        auto step = cast(int) min(n-1, s - k);
        s -= step;
        if (ans.back + step <= n) ans ~= ans.back + step;
        else ans ~= ans.back - step;
    }

    ans.dropOne.writefln!("%(%s %)");
}