Polycarp and his friends want to visit a new restaurant. The restaurant has $$$n$$$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $$$1$$$ to $$$n$$$ in the order from left to right. The state of the restaurant is described by a string of length $$$n$$$ which contains characters "1" (the table is occupied) and "0" (the table is empty).Restaurant rules prohibit people to sit at a distance of $$$k$$$ or less from each other. That is, if a person sits at the table number $$$i$$$, then all tables with numbers from $$$i-k$$$ to $$$i+k$$$ (except for the $$$i$$$-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than $$$k$$$.For example, if $$$n=8$$$ and $$$k=2$$$, then:  strings "10010001", "10000010", "00000000", "00100000" satisfy the rules of the restaurant;  strings "10100100", "10011001", "11111111" do not satisfy to the rules of the restaurant, since each of them has a pair of "1" with a distance less than or equal to $$$k=2$$$. In particular, if the state of the restaurant is described by a string without "1" or a string with one "1", then the requirement of the restaurant is satisfied.You are given a binary string $$$s$$$ that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string $$$s$$$.Find the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of "0" that can be replaced by "1" such that the requirement will still be satisfied?For example, if $$$n=6$$$, $$$k=1$$$, $$$s=$$$ "100010", then the answer to the problem will be $$$1$$$, since only the table at position $$$3$$$ can be occupied such that the rules are still satisfied.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — the number of tables in the restaurant and the minimum allowed distance between two people. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ consisting of "0" and "1" — a description of the free and occupied tables in the restaurant. The given string satisfy to the rules of the restaurant — the difference between indices of any two "1" is more than $$$k$$$. The sum of $$$n$$$ for all test cases in one test does not exceed $$$2\cdot 10^5$$$.

For each test case output one integer — the number of tables that you can occupy so as not to violate the rules of the restaurant. If additional tables cannot be taken, then, obviously, you need to output $$$0$$$.

NoteThe first test case is explained in the statement.In the second test case, the answer is $$$2$$$, since you can choose the first and the sixth table.In the third test case, you cannot take any free table without violating the rules of the restaurant.

import std.stdio;
import std.string : strip;
import std.algorithm : group;
import std.range;

void main()
{
  int t;
  readf!"%d\n"(t);

  foreach (i; 0..t) {
    int n, k;
    readf!"%d %d\n"(n, k);
    auto s = readln.strip;
    auto g = s.group;
    auto ng = g.walkLength;
    auto c = 0;

    foreach (e; g.enumerate) {
      auto j = e.index;
      auto x = e.value;

      if (x[0] == '1') {
        continue;
      }

      if (ng == 1) {
        // only 1 group of zeros: take the left table, then (n-1) / (k+1)
        c += 1 + (n - 1) / (k + 1);
      } else if (j == 0 || j == ng - 1) {
        // if first or last group is zeros: x / (k + 1)
        c += x[1] / (k + 1);
      } else {
        // else (x - k) / (k + 1)
        c += (x[1] - k) / (k + 1);
      }
    }

    writeln(c);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int l = -1, r;
		foreach (i; 0..n)
		{
			if (s[i] == '1')
			{
				l = i;
				break;
			}
		}
		foreach_reverse (i; 0..n)
		{
			if (s[i] == '1')
			{
				r = i;
				break;
			}
		}
		if (l == -1)
		{
			ans[ti] = 1 + (n-1) / (k+1);
		}
		else
		{
			ans[ti] += l / (k+1);
			ans[ti] += (n-r-1) / (k+1);
			int cnt;
			foreach (i; l..r)
			{
				debug writeln("cnt:", cnt, " ans:", ans[ti]);
				if (s[i] == '1')
				{
					ans[ti] += (cnt-k) / (k+1);
					cnt = 0;
				}
				else
				{
					++cnt;
				}
			}
			ans[ti] += (cnt-k) / (k+1);
		}
	}

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


You are given two positive integers $$$n$$$ and $$$k$$$. Print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.For example, if $$$n=3$$$, and $$$k=7$$$, then all numbers that are not divisible by $$$3$$$ are: $$$1, 2, 4, 5, 7, 8, 10, 11, 13 \dots$$$. The $$$7$$$-th number among them is $$$10$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$2 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$).

For each test case print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.

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

T readNum(T)(){
  return readStr.to!T;
}

T[] readNums(T)(){
  return readStr.split.to!(T[]);
}

string readStr(){
  return readln.chomp;
}

void main(){
  auto t = readNum!int;

  foreach(i; 0 .. t){
    auto nk = readNums!int;
    auto skip = (nk[1]-1) / (nk[0]-1);

    writeln(nk[1] + skip);
  }
}

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;

		long x = k;
		long cnt;
		while (x >= n)
		{
			cnt += x / n;
			x = (x % n) + x / n;
		}
		ans[ti] = k+cnt;
	}

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

void main() {
	auto t = ri;
	foreach(T; 0..t) {
		auto ip = readAs!(long[]), n = ip[0], k = ip[1];

		long l = 0, r = 1L << 60;
		long m;

		while(l + 1 < r) {
			//debug "%d, %d".writefln(l, r);
			m = (l+r) / 2;
			debug writefln("%d - (%d / %d) = %d, %d", m, m, n, m - (m / n), k);
			if(m - (m / n) < k) {
				debug "ok".writeln;
				l = m;
			} else r = m;
		}

		(l+1).writeln;
	}
}

// ===================================

import std.stdio;
import std.string;
import std.functional;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;

T readAs(T)() if (isBasicType!T) {
	return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
	return readln.split.to!T;
}

T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		res[i] = readAs!(T[]);
	}
	return res;
}

T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		auto s = rs;
		foreach(j; 0..width) res[i][j] = s[j].to!T;
	}
	return res;
}

int ri() {
	return readAs!int;
}

long rl() {
	return readAs!long;
}

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto nk = readln.split.to!(long[]);
        auto N = nk[0];
        auto K = nk[1];

        if (K < N) {
            writeln(K);
            continue;
        }

        long l = 1, r = K*2+1;
        while (l+1 < r) {
            auto m = (l+r)/2;
            auto e = m/N;
            if (m-e >= K) {
                r = m;
            } else {
                l = m;
            }
        }
        writeln(r);
    }
}

// Author: Ivan Kazmenko (gassa@mail.ru)
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);
		auto res = k * 1L * n / (n - 1) - 5;
		while (res - res / n < k)
		{
			res += 1;
		}
		writeln (res);
	}
}

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

long calc(long n, long k) {
    long d = k / (n-1);
    return k + d + (k % (n-1) == 0 ? -1 : 0);
}

void main() {
    int t; scan(t);
    foreach (_; 0..t) {
        int n, k; scan(n, k);
        writeln(calc(n, k));
    }
}

void scan(T...)(ref T a) {
    string[] ss = readln.split;
    foreach (i, t; T) a[i] = ss[i].to!t;
}
T read(T=string)() { return readln.chomp.to!T; }
T[] reads(T)() { return readln.split.to!(T[]); }
alias readints = reads!int;

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto nk = readln.split.to!(long[]);
        auto N = nk[0];
        auto K = nk[1];

        long l = 1, r = K*2+1;
        while (l+1 < r) {
            auto m = (l+r)/2;
            auto e = m/N;
            if (m-e >= K) {
                r = m;
            } else {
                l = m;
            }
        }
        writeln(r);
    }
}

// Author: Ivan Kazmenko (gassa@mail.ru)
// does not work for some inputs, for example, n = 4 and k = 2
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);
		auto res = k * 1L * n / (n - 1) - 1;
		if (res % n == 0)
		{
			res += 1;
		}
		writeln (res);
	}
}


You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces.  Space can be represented as the $$$XY$$$ plane. You are starting at point $$$(0, 0)$$$, and Planetforces is located in point $$$(p_x, p_y)$$$.The piloting system of your spaceship follows its list of orders which can be represented as a string $$$s$$$. The system reads $$$s$$$ from left to right. Suppose you are at point $$$(x, y)$$$ and current order is $$$s_i$$$:   if $$$s_i = \text{U}$$$, you move to $$$(x, y + 1)$$$;  if $$$s_i = \text{D}$$$, you move to $$$(x, y - 1)$$$;  if $$$s_i = \text{R}$$$, you move to $$$(x + 1, y)$$$;  if $$$s_i = \text{L}$$$, you move to $$$(x - 1, y)$$$. Since string $$$s$$$ could be corrupted, there is a possibility that you won't reach Planetforces in the end. Fortunately, you can delete some orders from $$$s$$$ but you can't change their positions.Can you delete several orders (possibly, zero) from $$$s$$$ in such a way, that you'll reach Planetforces after the system processes all orders?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line in each test case contains two integers $$$p_x$$$ and $$$p_y$$$ ($$$-10^5 \le p_x, p_y \le 10^5$$$; $$$(p_x, p_y) \neq (0, 0)$$$) — the coordinates of Planetforces $$$(p_x, p_y)$$$. The second line contains the string $$$s$$$ ($$$1 \le |s| \le 10^5$$$: $$$|s|$$$ is the length of string $$$s$$$) — the list of orders. It is guaranteed that the sum of $$$|s|$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" if you can delete several orders (possibly, zero) from $$$s$$$ in such a way, that you'll reach Planetforces. Otherwise, print "NO". You can print each letter in any case (upper or lower).

6
10 5
RRRRRRRRRRUUUUU
1 1
UDDDRLLL
-3 -5
LDLDLDDDR
1 2
LLLLUU
3 -2
RDULRLLDR
-1 6
RUDURUUUUR

NoteIn the first case, you don't need to modify $$$s$$$, since the given $$$s$$$ will bring you to Planetforces.In the second case, you can delete orders $$$s_2$$$, $$$s_3$$$, $$$s_4$$$, $$$s_6$$$, $$$s_7$$$ and $$$s_8$$$, so $$$s$$$ becomes equal to "UR".In the third test case, you have to delete order $$$s_9$$$, otherwise, you won't finish in the position of Planetforces.

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 x, y; get(x, y);
        char[] s; get(s);
        int max_x, min_x, max_y, min_y;
        foreach (c; s) {
            switch (c) {
                case 'U': ++max_y; break;
                case 'D': --min_y; break;
                case 'R': ++max_x; break;
                case 'L': --min_x; break;
                default:
            }
        }
        writeln(min_x <= x && x <= max_x && min_y <= y && y <= max_y ? "YES" : "NO");
    }
}

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 bool[](t);
	foreach (ti; 0..t)
	{
		auto x = RD;
		auto y = RD;
		auto s = RD!string;

		long u, d, r, l;
		foreach (c; s)
		{
			if (c == 'U')
				++u;
			else if (c == 'D')
				--d;
			else if (c == 'R')
				++r;
			else
				--l;
		}
		ans[ti] = true;
		if (x > r || x < l)
			ans[ti] = false;
		if (y > u || y < d)
			ans[ti] = false;
	}

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

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 x, y;
		readf !(" %s %s") (x, y);
		readln;
		auto s = readln.strip;
		bool ok = true;
		ok &= (s.count ('R').to !(int) >= +x);
		ok &= (s.count ('L').to !(int) >= -x);
		ok &= (s.count ('U').to !(int) >= +y);
		ok &= (s.count ('D').to !(int) >= -y);
		writeln (ok ? "YES" : "NO");
	}
}


n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.

The first line contains two integers: n and k (2 ≤ n ≤ 500, 2 ≤ k ≤ 1012) — the number of people and the number of wins. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.

Output a single integer — power of the winner.

NoteGames in the second sample:3 plays with 1. 3 wins. 1 goes to the end of the line.3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner.

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

void main(){

	int n;
	long k;

	scanf("%d %lld", &n, &k);
	readln;

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

	int mx = -1, cnt = 0;

	for (int i = 0; i < n; ++i){
		if (mx == -1){
			mx = a[i];
			cnt = 0;
		}

		else if (a[i] > mx){
			mx = a[i];
			cnt = 1;
		}

		else{
			++cnt;
			if (cnt >= k){
				writeln(mx);
				return;
			}
		}
	}

	writeln(mx);
}


Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$.

The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.

Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.

NoteIn the first example the following segments have sum less than $$$4$$$:  $$$[2, 2]$$$, sum of elements is $$$-1$$$  $$$[2, 3]$$$, sum of elements is $$$2$$$  $$$[3, 3]$$$, sum of elements is $$$3$$$  $$$[4, 5]$$$, sum of elements is $$$3$$$  $$$[5, 5]$$$, sum of elements is $$$-1$$$

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

const long INF = 1L << 59;

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

    int[long] comp;
    auto C = B.dup.sort().uniq().array;
    auto M = C.length.to!int;
    foreach (i; 0..M) comp[C[i]] = i;

    auto st = new SegmentTree(M);
    foreach (i; 0..N+1) st.add(comp[B[i]], 1);
    long ans = 0;

    foreach (i; 0..N) {
        st.add(comp[B[i]], -1);
        auto lb = C.assumeSorted.lowerBound(T + B[i]).length.to!int;
        ans += st.sum(0, lb - 1);
    }

    ans.writeln;
}

class SegmentTree {
    int[] table;
    int size;

    this(int n) {
        assert(bsr(n) < 29);
        size = 1 << (bsr(n) + 2);
        table = new int[](size);
    }

    void add(int pos, int num) {
        return add(pos, num, 0, 0, size/2-1);
    }

    void add(int pos, int num, int i, int left, int right) {
        table[i] += num;
        if (left == right)
            return;
        auto mid = (left + right) / 2;
        if (pos <= mid)
            add(pos, num, i*2+1, left, mid);
        else
            add(pos, num, i*2+2, mid+1, right);
    }

    int sum(int pl, int pr) {
        if (pr < pl) return 0;
        return sum(pl, pr, 0, 0, size/2-1);
    }

    int sum(int pl, int pr, int i, int left, int right) {
        if (pl > right || pr < left)
            return 0;
        else if (pl <= left && right <= pr)
            return table[i];
        else
            return
                sum(pl, pr, i*2+1, left, (left+right)/2) +
                sum(pl, pr, i*2+2, (left+right)/2+1, right);
    }
}

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

int search(long[] arr, int n, long t)
{
    auto left = 0, right = n - 1;
    auto res = -1;
    while (left <= right)
    {
        auto mid = (left + right) >> 1;
        if (arr[mid] >= t)
        {
            right = mid - 1;
        }
        else
        {
            left = mid + 1;
            res = mid;
        }
    }
    return res + 1;
}

long count(int[] a, int left, int right, long t)
{
    if (left == right)
    {
        if (a[left] < t) return 1;
        return 0;
    }
    long res = 0;
    auto mid = (left + right) >> 1;
    res += count(a, left, mid, t);
    res += count(a, mid + 1, right, t);
    auto arr = new long[mid - left + 1];
    long sum = 0;
    for (int i = mid; i >= left; -- i)
    {
        sum += a[i];
        arr[mid - i] = sum;
    }
    arr.sort;
    sum = 0;
    for (int i = mid + 1; i <= right; ++ i)
    {
        sum += a[i];
        auto ret = search(arr, mid - left + 1, t - sum);
        res += ret;
    }
    return res;
}

void solve(int[] a, int n, long t)
{
    auto ans = count(a, 0, n - 1, t);
    writeln(ans);
}

int main(string[] args)
{
    int n;
    long t;
    while (readf("%d %d\n", &n, &t) == 2)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            readf(" %d", &a[i]);
        }
        readln;
        solve(a, n, t);
    }
    return 0;
}


Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?

The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for.

Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above.

10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020

sinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja

NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

import std.stdio;
import std.string : strip, split;

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

  auto s = readln.strip.split;
  auto t = readln.strip.split;
  readf!"%d\n"(q);

  foreach (i; 0..q) {
    int y;
    readf!"%d\n"(y);
    y--;

    writeln(s[y % s.length] ~ t[y % t.length]);
  }
}

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

void main ()
{
	int n;
	int m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;
		auto x = readln.split;
		auto y = readln.split;
		auto q = readln.strip.to !(int);
		foreach (r; 0..q)
		{
			auto z = readln.strip.to !(int);
			z -= 1;
			writeln (x[z % n], y[z % m]);
		}
	}
}

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

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

void solve(){
	int n = rint, m = rint;
	string[] as = rtypes!string(n);
	string[] bs = rtypes!string(m);

	foreach(_; 0 .. rint){
		long x = rlong - 1;
		(as[(x % n).to!int] ~ bs[(x % m).to!int]).writeln;
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      auto S = new string[N];
      foreach (i; 0 .. N) {
        S[i] = readToken();
      }
      auto T = new string[M];
      foreach (j; 0 .. M) {
        T[j] = readToken();
      }
      const Q = readInt();
      auto Y = new int[Q];
      foreach (q; 0 .. Q) {
        Y[q] = readInt();
      }

      foreach (q; 0 .. Q) {
        writeln(S[(Y[q] - 1) % N], T[(Y[q] - 1) % M]);
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void 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 main()
{
	auto n = RD!int;
	auto m = RD!int;
	string[] s, t;
	foreach (i; 0..n)
		s ~= RD!string;
	foreach (i; 0..m)
		t ~= RD!string;
	auto q = RD!int;
	auto ans = new string[](q);
	foreach (qi; 0..q)
	{
		auto y = RD!int-1;
		ans[qi] = s[y%n] ~ t[y%m];
	}

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


Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold:   thread x is not updated (it has no new messages);  the list order 1, 2, ..., n changes to a1, a2, ..., an.

The first line of input contains an integer n, the number of threads (1 ≤ n ≤ 105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1 ≤ ai ≤ n) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct.

Output a single integer — the number of threads that surely contain a new message.

NoteIn the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.In the second test case, there may be no new messages at all, since the thread order hasn't changed.In the third test case, only thread 1 can contain no new messages.

module cf_270b;

import std.stdio;

void main() {
  int n;
  int[] places;

  readf("%d", &n);
  places = new int[n];
  for (int i = 0; i < n; ++i) {
    readf(" %d", &places[i]);
  }

  int cur = n - 2;
  while (cur >= 0 && places[cur] < places[cur + 1]) {
    --cur;
  }

  writeln(cur + 1);
}

module cf_270b;

import std.stdio;

void main() {
  int n;
  int[] places;
  int updatedThreads = 0;

  readf("%d", &n);
  places = new int[n];
  for (int i = 0; i < n; ++i) {
    readf(" %d", &places[i]);

    if (places[i] == 1) {
      updatedThreads = i;
    }
  }

  writeln(updatedThreads);
}


All Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland!It is well-known that there are n cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that the road network is connected, i.e. it is possible that you can't reach some city from some other.The tour will contain several episodes. In each of the episodes:  the wizard will disembark at some city x from the Helicopter;  he will give a performance and show a movie for free at the city x;  he will drive to some neighboring city y using a road;  he will give a performance and show a movie for free at the city y;  he will drive to some neighboring to y city z;  he will give a performance and show a movie for free at the city z;  he will embark the Helicopter and fly away from the city z. It is known that the wizard doesn't like to use roads, so he agrees to use each road at most once (regardless of direction). In other words, for road between a and b he only can drive once from a to b, or drive once from b to a, or do not use this road at all.The wizards wants to plan as many episodes as possible without violation the above rules. Help the wizard!Please note that the wizard can visit the same city multiple times, the restriction is on roads only.

The first line contains two integers n, m (1 ≤ n ≤ 2·105, 0 ≤ m ≤ 2·105) — the number of cities and the number of roads in Berland, respectively. The roads description follow, one in each line. Each description is a pair of two integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the ids of the cities connected by the i-th road. It is guaranteed that there are no two roads connecting the same pair of cities. Every road is bidirectional. The cities are numbered from 1 to n. It is possible that the road network in Berland is not connected.

In the first line print w — the maximum possible number of episodes. The next w lines should contain the episodes in format x, y, z — the three integers denoting the ids of the cities in the order of the wizard's visits.

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

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

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

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

int N, M;
int[] A, B;

int[][] G;
int[] par, dep;
int[] us;
int[][] vss;

void dfs(int u, int p) {
  par[u] = p;
  dep[u] = (p == -1) ? 0 : (dep[p] + 1);
  us ~= u;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      if (par[v] == -2) {
        dfs(v, u);
      } else if (dep[u] > dep[v]) {
        vss[u] ~= v;
      }
    }
  }
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      M = readInt();
      A = new int[M];
      B = new int[M];
      foreach (i; 0 .. M) {
        A[i] = readInt() - 1;
        B[i] = readInt() - 1;
      }

      G = new int[][N];
      foreach (i; 0 .. M) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      par = new int[N];
      par[] = -2;
      dep = new int[N];
      us = [];
      vss = new int[][N];
      foreach (u; 0 .. N) {
        if (par[u] == -2) {
          dfs(u, -1);
        }
      }
      debug {
        writeln("par = ", par);
        writeln("us = ", us);
        writeln("vss = ", vss);
      }

      int[][] ans;
      foreach_reverse (u; us) {
        const vs = vss[u];
        const vsLen = cast(int)(vs.length);
        foreach (j; 0 .. vsLen / 2) {
          ans ~= [vs[j * 2], u, vs[j * 2 + 1]];
        }
        if (par[u] != -1) {
          if (vsLen % 2 == 0) {
            vss[par[u]] ~= u;
          } else {
            ans ~= [vs[vsLen - 1], u, par[u]];
          }
        }
      }

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


Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.  The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of disks on the combination lock. The second line contains a string of n digits — the original state of the disks. The third line contains a string of n digits — Scrooge McDuck's combination that opens the lock.

Print a single integer — the minimum number of moves Scrooge McDuck needs to open the lock.

NoteIn the sample he needs 13 moves:  1 disk:   2 disk:   3 disk:   4 disk:   5 disk:

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

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

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

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

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // int t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                string s = cin.read_string;
                string code = cin.read_string;
                int ans = 0;
                for (int i = 0; i < n; i++) {
                        int met1 = min(s[i], code[i]) + 10 - max(s[i], code[i]);
                        int met2 = abs(code[i] - s[i]);
                        ans += min(met1, met2);
                }
                writeln(ans);
        }
}

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

void main() {

	readln;
	auto a = readln.strip, b = readln.strip;

	uint sum;
	foreach (i, e; a) {
		auto tmpA = e.to!int, tmpB = b[i].to!int;
		auto minA = min(tmpA, tmpB), maxB = max(tmpA, tmpB);
		auto cl = maxB - minA, tl = 10 - maxB + minA;
		if (cl < tl) {
			sum += cl;
		}
		else {
			sum += tl;
		}
	}

	writeln(sum);
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.math;

int main(string[] argv)
{
	int n; scanf("%d", &n);
	char[1001] ss;
	char[1001] fs;
	scanf("%s", &ss);
	scanf("%s", &fs);
	int count = 0;
	foreach (int i; 0..n)
	{
		int d1 = ss[i] - fs[i]; d1 = abs(d1);
		int d2 = 10 - d1; d2 = abs(d2);
		count += (d1 < d2 ? d1 : d2);
	}
	write(count);
	return 0;
}


It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) — one ant in each direction. No other ant movements will happen. Ants never interfere with each other.Scientists have put a colony of n ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops.

First input line contains integers n (0 ≤ n ≤ 30000) and t (1 ≤ t ≤ 50000), where n is the number of ants in the colony and t is the number of queries. Each of the next t lines contains coordinates of a query junction: integers xi, yi ( - 109 ≤ xi, yi ≤ 109). Queries may coincide. It is guaranteed that there will be a certain moment of time when no possible movements can happen (in other words, the process will eventually end).

Print t integers, one per line — the number of ants at the corresponding junctions when the movement of the ants stops.

NoteIn the first sample the colony consists of the one ant, so nothing happens at all.In the second sample the colony consists of 6 ants. At the first minute 4 ants scatter from (0, 0) to the neighbouring junctions. After that the process stops.

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

immutable int MAX_N = 67;

void main ()
{
	int n, t;
	while (readf (" %s %s", &n, &t) > 0)
	{
		auto f = new int [] [] (MAX_N, MAX_N);
		f[0][0] = n;
		int lim = 0;
		bool ok;
		do
		{
			ok = false;
			int lim2 = lim;
			foreach (i; 0..lim + 1)
			{
				foreach (j; 0..lim + 1)
				{
					if (f[i][j] >= 4)
					{
						int s = f[i][j] / 4;
						lim2 = max (lim2,
						            1 + max (i, j));
						ok = true;
						f[i][j] -= 4 * s;
						f[i + 1][j] += s;
						if (i > 0)
						{
							f[i - 1][j] += s *
							    (1 + (i == 1));
						}
						f[i][j + 1] += s;
						if (j > 0)
						{
							f[i][j - 1] += s *
							    (1 + (j == 1));
						}
					}
				}
			}
			lim = lim2;
		}
		while (ok);
		debug {writeln (lim);}

		foreach (i; 0..t)
		{
			int x, y;
			readf (" %s %s", &x, &y);
			x = abs (x);
			y = abs (y);
			int res = 0;
			if (x < MAX_N && y < MAX_N)
			{
				res = f[x][y];
			}
			writeln (res);
		}
	}
}


Polycarp lives on the coordinate axis $$$Ox$$$ and travels from the point $$$x=a$$$ to $$$x=b$$$. It moves uniformly rectilinearly at a speed of one unit of distance per minute.On the axis $$$Ox$$$ at the point $$$x=c$$$ the base station of the mobile operator is placed. It is known that the radius of its coverage is $$$r$$$. Thus, if Polycarp is at a distance less than or equal to $$$r$$$ from the point $$$x=c$$$, then he is in the network coverage area, otherwise — no. The base station can be located both on the route of Polycarp and outside it.Print the time in minutes during which Polycarp will not be in the coverage area of the network, with a rectilinear uniform movement from $$$x=a$$$ to $$$x=b$$$. His speed — one unit of distance per minute.

The first line contains a positive integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. In the following lines are written $$$t$$$ test cases. The description of each test case is one line, which contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$r$$$ ($$$-10^8 \le a,b,c \le 10^8$$$, $$$0 \le r \le 10^8$$$) — the coordinates of the starting and ending points of the path, the base station, and its coverage radius, respectively. Any of the numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (either any pair or all three numbers). The base station can be located both on the route of Polycarp and outside it.

Print $$$t$$$ numbers — answers to given test cases in the order they are written in the test. Each answer is an integer — the number of minutes during which Polycarp will be unavailable during his movement.

NoteThe following picture illustrates the first test case.     Polycarp goes from $$$1$$$ to $$$10$$$. The yellow area shows the coverage area of the station with a radius of coverage of $$$1$$$, which is located at the point of $$$7$$$. The green area shows a part of the path when Polycarp is out of coverage area.

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

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        auto s = readln.split.map!(to!long);
        auto a = s[0];
        auto b = s[1];
        auto c = s[2];
        auto r = s[3];
        if (a > b) swap(a, b);
        auto u = c - r;
        auto v = c + r;
        if (u >= b || v <= a) {
            writeln(b - a);
        } else {
            u = max(u, a);
            v = min(v, b);
            writeln(b - a - (v - u));
        }
    }
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  immutable nt = r.next!uint;
  auto res = uninitializedArray!(int[]) (nt);
  foreach (tid; 0 .. nt) {
    auto a = r.next!int;
    auto b = r.next!int;
    if (a > b) swap (a, b);
    immutable c = r.next!int;
    immutable rd = r.next!int;
    immutable u = c - rd, v = c + rd;
    auto x = max (a, u), y = min (b, v);
    auto s = x < y ? (y - x) : 0;
    res[tid] = (b - a) - s;
  }
  writefln ("%(%s\n%)", res);
}

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

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

void solve(){
	foreach(_; 0 .. rint){
		long a = rlong, b = rlong, c = rlong, r = rlong;
		long x = c - r, y = c + r;
		if(a > b){ long z = a; a = b, b = z; }
		long ans;
		if(y <= a || b <= x) ans += b - a;
		else{
			if(a < x) ans += x - a;
			if(y < b) ans += b - y;
		}
		ans.writeln;
	}
}

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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

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

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto a = RD!int;
		auto b = RD!int;
		auto c = RD!int;
		auto r = RD!int;
		if (a > b)
			swap(a, b);
		auto x = c - r;
		auto y = c + r;
		auto len = b - a;
		if (x < a)
			ans[ti] = max(len - max(0, y - a), 0);
		else if (y >= b)
			ans[ti] = max(len - max(0, b - x), 0);
		else
			ans[ti] = max(len - (y - x), 0);
	}

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


You are playing a very popular computer game. The next level consists of $$$n$$$ consecutive locations, numbered from $$$1$$$ to $$$n$$$, each of them containing either land or water. It is known that the first and last locations contain land, and for completing the level you have to move from the first location to the last. Also, if you become inside a location with water, you will die, so you can only move between locations with land.You can jump between adjacent locations for free, as well as no more than once jump from any location with land $$$i$$$ to any location with land $$$i + x$$$, spending $$$x$$$ coins ($$$x \geq 0$$$).Your task is to spend the minimum possible number of coins to move from the first location to the last one.Note that this is always possible since both the first and last locations are the land locations.

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of locations. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 1$$$), where $$$a_i = 1$$$ means that the $$$i$$$-th location is the location with land, and $$$a_i = 0$$$ means that the $$$i$$$-th location is the location with water. It is guaranteed that $$$a_1 = 1$$$ and $$$a_n = 1$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the first test case, it is enough to make one free jump from the first location to the second one, which is also the last one, so the answer is $$$0$$$.In the second test case, the only way to move from the first location to the last one is to jump between them, which will cost $$$4$$$ coins.In the third test case, you can jump from the first location to the third for $$$2$$$ coins, and then jump to the fourth location for free, so the answer is $$$2$$$. It can be shown that this is the optimal way.

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        int k;
        scanf("%d\n", &k);
        int[] s = readln.strip.split.to!(int[]);
        auto end = countUntil(retro(s), 0);
        auto start = countUntil(s, 0);
        if (start == -1)
            writeln(0);
        else
            writeln(k - start - end + 1);
    }
}


Berland has n cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not.The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. The valiant crew fulfilled the King's order in a day, then workers went home.Unfortunately, not everything is as great as Valera II would like. The main part of the group were gastarbeiters — illegal immigrants who are enthusiastic but not exactly good at understanding orders in Berlandian. Therefore, having received orders to asphalt the roads coming from some of the city, the group asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it.Upon learning of this progress, Valera II was very upset, but since it was too late to change anything, he asked you to make a program that determines whether you can in some way asphalt Berlandian roads in at most n days. Help the king.

The first line contains two space-separated integers n, m  — the number of cities and roads in Berland, correspondingly. Next m lines contain the descriptions of roads in Berland: the i-th line contains three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n; ai ≠ bi; 0 ≤ ci ≤ 1). The first two integers (ai, bi) are indexes of the cities that are connected by the i-th road, the third integer (ci) equals 1, if the road was initially asphalted, and 0 otherwise.  Consider the cities in Berland indexed from 1 to n, and the roads indexed from 1 to m. It is guaranteed that between two Berlandian cities there is not more than one road.

In the first line print a single integer x (0 ≤ x ≤ n) — the number of days needed to asphalt all roads. In the second line print x space-separated integers — the indexes of the cities to send the workers to. Print the cities in the order, in which Valera send the workers to asphalt roads. If there are multiple solutions, print any of them.  If there's no way to asphalt all roads, print "Impossible" (without the quotes).

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

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto m = next!int;
  struct Adj
  {
    int v;
    int t;
  }
  auto adj = new Adj[][](n);
  auto vis = new bool[](n);
  auto col = new int[](n);
  foreach(e; 0 .. m)
    {
      auto u = next!int - 1;
      auto v = next!int - 1;
      auto t = next!int;
      adj[u] ~= Adj(v, t);
      adj[v] ~= Adj(u, t);
    }
  class NotPossible : Throwable
  {
    this() {super(null);}
  }
  void dfs(int u, int setcol)
  {
    if (vis[u])
      {
	if (setcol != col[u]) throw new NotPossible;
	return;
      }
    vis[u] = true;
    col[u] = setcol;
    foreach(a; adj[u])
      {
	int t = a.t;
	int v = a.v;
	dfs(v, (t + col[u] + 1) % 2);
      }
  }
  try
    {
      foreach(i; 0 .. n)
	if (vis[i]) continue;
	else dfs(i, 0);
    }
  catch(NotPossible notPossible)
    {
      return "Impossible".writeln;
    }
  auto tocolor = iota(0, n).filter!(i => col[i] == 1).array;
  tocolor.length.writeln;
  tocolor.each!(x => (x + 1).write(" "));
  writeln;
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


You are given a matrix consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell of this matrix contains $$$0$$$ or $$$1$$$.Let's call a square of size $$$2 \times 2$$$ without one corner cell an L-shape figure. In one operation you can take one L-shape figure, with at least one cell containing $$$1$$$ and replace all numbers in it with zeroes.Find the maximum number of operations that you can do with the given matrix.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 500$$$) — the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n, m \leq 500$$$) — the size of the matrix. Each of the following $$$n$$$ lines contains a binary string of length $$$m$$$ — the description of the matrix. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases does not exceed $$$1000$$$.

For each test case output the maximum number of operations you can do with the given matrix.

NoteIn the first testcase one of the optimal sequences of operations is the following (bold font shows l-shape figure on which operation was performed):   Matrix before any operation was performed:  101111011110  Matrix after $$$1$$$ operation was performed:  100101011110  Matrix after $$$2$$$ operations were performed:  100100011110  Matrix after $$$3$$$ operations were performed:  100100010110  Matrix after $$$4$$$ operations were performed:  100000010110  Matrix after $$$5$$$ operations were performed:  100000010100  Matrix after $$$6$$$ operations were performed:  100000000100  Matrix after $$$7$$$ operations were performed:  000000000100  Matrix after $$$8$$$ operations were performed:  000000000000 In the third testcase from the sample we can not perform any operation because the matrix doesn't contain any ones.In the fourth testcase it does not matter which L-shape figure we pick in our first operation. We will always be left with single one. So we will perform $$$2$$$ operations.

// cheese-cracker [2022-08-18]

void solve(){
    int n = scan!int;
    int m = scan!int;
    dchar[][] mat;
    for(int i = 0; i < n; ++i){
        mat ~= scanArray!(dchar[]);
    }
    long cnt = 0;
    long dmax = 0;
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j){
            cnt += (mat[i][j] == '1');
            long deg = (mat[i][j] == '0');
            if(i > 0 && mat[i-1][j] == '0'){
                deg += 1;
            } else if(i < n-1 && mat[i+1][j] == '0'){
                deg += 1;
            }
            if(j > 0 && mat[i][j-1] == '0'){
                deg += 1;
            } else if(j < m-1 && mat[i][j+1] == '0'){
                deg += 1;
            }
            dmax = max(deg, dmax);
        }
    }
    show(cnt);
    show(dmax);
    if(dmax >= 2){
        writeln(cnt);
    }else if(dmax == 1){
        writeln(cnt-1);
    }else if(dmax == 0){
        writeln(cnt-2);
    }
}

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

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

// cheese-cracker [2022-08-18]

void solve(){
    int n = scan!int;
    int m = scan!int;
    dchar[][] mat;
    for(int i = 0; i < n; ++i){
        mat ~= scanArray!(dchar[]);
    }
    long cnt = 0;
    long dmax = 0;
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j){
            cnt += (mat[i][j] == '1');
            long deg = (mat[i][j] == '0');
            if(i > 0) deg += (mat[i-1][j] == '0');
            if(j > 0) deg += (mat[i][j-1] == '0');
            if(i < n-1) deg += (mat[i+1][j] == '0');
            if(j < m-1) deg += (mat[i][j+1] == '0');
            dmax = max(deg, dmax);
        }
    }
    show(dmax);
    if(dmax >= 2){
        writeln(cnt);
    }else if(dmax == 1){
        writeln(cnt-1);
    }else if(dmax == 0){
        writeln(cnt-2);
    }
    return;
}

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

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

// cheese-cracker [2022-08-18]

void solve(){
    int n = scan!int;
    int m = scan!int;
    dchar[][] mat;
    for(int i = 0; i < n; ++i){
        mat ~= scanArray!(dchar[]);
    }
    long cnt = 0;
    long dmax = 0;
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j){
            cnt += (mat[i][j] == '1');
            long deg = (mat[i][j] == '0');
            if(i > 0) deg += (mat[i-1][j] == '0');
            if(j > 0) deg += (mat[i][j-1] == '0');
            if(i < n-1) deg += (mat[i+1][j] == '0');
            if(j < m-1) deg += (mat[i][j+1] == '0');
            dmax = max(deg, dmax);
        }
    }
    long rem = max(2 - dmax, 0);
    long res = max(cnt - rem, 0);
    writeln(res);
}

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

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


Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only.The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that . Find any s' satisfying the given conditions, or print "-1" if it's impossible to do so.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 106). The second line contains a string s of length n, consisting of lowercase English letters.

If there is no string satisfying the given conditions then print "-1" (without the quotes). Otherwise, print any nice string s' that .

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto s = readln.strip.map !(x => x - 'a').array;
		foreach (ref c; s)
		{
			if (c > 12)
			{
				int delta = min (c, k);
				c -= delta;
				k -= delta;
			}
			else
			{
				int delta = min (25 - c, k);
				c += delta;
				k -= delta;
			}
		}
		if (k > 0)
		{
			writeln (-1);
		}
		else
		{
			s.map !(x => cast (char) (x + 'a')).writeln;
		}
	}
}


Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.Help Igor find the maximum number he can write on the fence.

The first line contains a positive integer v (0 ≤ v ≤ 106). The second line contains nine positive integers a1, a2, ..., a9 (1 ≤ ai ≤ 105).

Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1.

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

int[] d;

void main() {
    int v; readf("%d\n", &v);
    d = stdin.readln.split.map!(to!int).array;
    int index, m = int.max;
    for (int i = 9; i >= 1; i--) {
        int e = d[i-1];
        if (m > e) {
            index = i;
            m = e;
        }
    }
    int c = v / m;
    if (c == 0) {
        writeln(-1);
        return;
    }
    int r = v - m * c;
    foreach (ref e; d) {
        e -= m;
    }
    Array!int a;
    //r.writeln;
    //d.writeln;
    bool f = true;
    while (r > 0 && f) {
        f = false;
        for (int i = 9; i > index; i--) {
            if (r >= d[i-1]) {
                r -= d[i-1];
                a.insert(i);
                f = true;
                break;
            }
        }
    }
    a.array.map!(to!string).join("").write;
    foreach(_; 0 .. c - a.length) {
        index.write;
    }
    writeln;
}

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

int[] d;

void main() {
    int v; readf("%d\n", &v);
    d = stdin.readln.split.map!(to!int).array;
    int index, m = int.max;
    foreach (int i, e; d) {
        if (m > e) {
            index = i;
            m = e;
        }
    }
    int c = v / m;
    if (c == 0) {
        writeln(-1);
        return;
    }
    int r = v - m * c;
    foreach (ref e; d) {
        e -= m;
    }
    Array!int a;
    while (r > 0) {
        for (int i = 9; i >= 1; i--) {
            if (r >= d[i-1]) {
                r -= d[i-1];
                a.insert(i);
                break;
            }
        }
    }
    a.array.map!(to!string).join("").write;
    foreach(_; 0 .. c - a.length) {
        (index+1).write;
    }
    writeln;
}

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

int[] d;

void main() {
    int v; readf("%d\n", &v);
    d = stdin.readln.split.map!(to!int).array;
    int index, m = int.max;
    for (int i = 9; i >= 1; i--) {
        int e = d[i-1];
        if (m > e) {
            index = i;
            m = e;
        }
    }
    int c = v / m;
    if (c == 0) {
        writeln(-1);
        return;
    }
    int r = v - m * c;
    foreach (ref e; d) {
        e -= m;
    }
    Array!int a;
    //r.writeln;
    //d.writeln;
    bool f = true;
    while (r > 0 && f) {
        f = false;
        for (int i = 9; i >= 1; i--) {
            if (r >= d[i-1] && i != index) {
                r -= d[i-1];
                a.insert(i);
                f = true;
                break;
            }
        }
    }
    a.array.map!(to!string).join("").write;
    foreach(_; 0 .. c - a.length) {
        index.write;
    }
    writeln;
}

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

int[] d;

void main() {
    int v; readf("%d\n", &v);
    d = stdin.readln.split.map!(to!int).array;
    int m = 0;
    int n = 0;
    for (int i = 1; i <= 9; i++) {
        if (v / d[i-1] >= m) {
            m = v / d[i-1];
            n = i;
        }
    }
    if (m == 0) {
        writeln(-1);
        return;
    }
    int r = v % d[n-1] + d[n-1];
    int t = 10;
    for (int i = 9; i >= 1; i--) {
        if (r >= d[i-1]) {
            t = i;
            break;
        }
    }
    t.write;
    foreach (i; 0 .. m - 1) {
        n.write;
    }
    writeln;
}

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

int[] d;

void main() {
    int v; readf("%d\n", &v);
    d = stdin.readln.split.map!(to!int).array;
    int m = 0;
    int n = 0;
    for (int i = 1; i <= 9; i++) {
        if (v / d[i-1] >= m) {
            m = v / d[i-1];
            n = i;
        }
    }
    int r = v % d[n-1] + d[n-1];
    int t = 10;
    for (int i = 9; i >= 1; i--) {
        if (r >= d[i-1]) {
            t = i;
            break;
        }
    }
    if (t == 10) {
        writeln(-1);
        return;
    }
    t.write;
    foreach (i; 0 .. m - 1) {
        n.write;
    }
    writeln;
}


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z".

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$.

Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$.

NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda".

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

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

    int i = 0;
    for (; i < N - 1; ++i) {
        if (S[i] > S[i + 1]) break;
    }

    S = S[0..i] ~ S[i+1..N];

    S.writeln;
}


A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.

In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.

module cf_46A;

import std.stdio;

void main() {
    int n;

    readf("%d", &n);

    int step = 1, current = 0;
    for (int i = 1; i < n; ++i) {
        current = (current + step) % n;
        writef("%d ", current + 1);
        ++step;
    }
    writeln();
}


Consider the infinite sequence $$$s$$$ of positive integers, created by repeating the following steps:  Find the lexicographically smallest triple of positive integers $$$(a, b, c)$$$ such that   $$$a \oplus b \oplus c = 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.  $$$a$$$, $$$b$$$, $$$c$$$ are not in $$$s$$$.  Here triple of integers $$$(a_1, b_1, c_1)$$$ is considered to be lexicographically smaller than triple $$$(a_2, b_2, c_2)$$$ if sequence $$$[a_1, b_1, c_1]$$$ is lexicographically smaller than sequence $$$[a_2, b_2, c_2]$$$.  Append $$$a$$$, $$$b$$$, $$$c$$$ to $$$s$$$ in this order.  Go back to the first step. You have integer $$$n$$$. Find the $$$n$$$-th element of $$$s$$$.You have to answer $$$t$$$ independent test cases.A sequence $$$a$$$ is lexicographically smaller than a sequence $$$b$$$ if in the first position where $$$a$$$ and $$$b$$$ differ, the sequence $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1\le n \le 10^{16}$$$) — the position of the element you want to know.

In each of the $$$t$$$ lines, output the answer to the corresponding test case.

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		long n;
		readf !(" %s") (n);
		n -= 1;
		long triple = n / 3;
		int rem = n % 3;
		int bits = 0;
		while (triple >= 1L << bits)
		{
			triple -= 1L << bits;
			bits += 2;
		}
		auto a = [0L, 0L, 0L];
		a[0] += (1L << bits);
		a[1] += (2L << bits);
		a[2] += (3L << bits);
		for (int bit = 0; bit < bits; bit += 2)
		{
			int cur = triple & 3;
			a[0] += [0L, 1L, 2L, 3L][cur] << bit;
			a[1] += [0L, 2L, 3L, 1L][cur] << bit;
			a[2] += [0L, 3L, 1L, 2L][cur] << bit;
			triple >>= 2;
		}
		writeln (a[rem]);
	}
}

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

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

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

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

void main() {
  debug {
    bool[long] app;
    foreach (i; 0 .. 100) {
      for (int a = 0; ; ++a) {
        if (a !in app) {
          for (int b = 0; ; ++b) {
            const c = a ^ b;
            if ((b !in app) && (c !in app)) {
              writefln("%3d %3d %3d %10b %10b %10b", a, b, c, a, b, c);
              app[a] = app[b] = app[c] = true;
              goto found;
            }
          }
        }
      }
     found:
    }
  }

  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readLong() - 1;
        long n = N / 3;
        for (int k = 0; ; ++k) {
          // a \in [2^(2k), 2^(2k+1))
          if (n < 1L << (2 * k)) {
            debug {
              writefln("k = %s, n = %s", k, n);
            }
            long a = 1L << (2 * k);
            a += n;
            long b = 1L << (2 * k + 1);
            foreach (i; 0 .. k) {
              b |= [0L, 2L, 3L, 1L][cast(int)((a >> (2 * i)) & 3)] << (2 * i);
            }
            const c = a ^ b;
            debug {
              writefln("%064b", a);
              writefln("%064b", b);
              writefln("%064b", c);
            }
            writeln([a, b, c][cast(int)(N % 3)]);
            break;
          } else {
            n -= 1L << (2 * k);
          }
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

void main() {
  debug {
    bool[long] app;
    foreach (i; 0 .. 100) {
      for (int a = 0; ; ++a) {
        if (a !in app) {
          for (int b = 0; ; ++b) {
            const c = a ^ b;
            if ((b !in app) && (c !in app)) {
              writefln("%3d %3d %3d %10b %10b %10b", a, b, c, a, b, c);
              app[a] = app[b] = app[c] = true;
              goto found;
            }
          }
        }
      }
     found:
    }
  }

  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readLong() - 1;
        long n = N / 3;
        for (int k = 0; ; ++k) {
          // a \in [2^(2k), 2^(2k+1))
          if (n < 1L << (2 * k)) {
            long a = 1L << (2 * k);
            a += n;
            long b = 1L << (2 * k + 1);
            foreach (i; 0 .. k) {
              b |= [0, 2, 3, 1][cast(int)((a >> (2 * i)) & 3)] << (2 * i);
            }
            const c = a ^ b;
            writeln([a, b, c][cast(int)(N % 3)]);
            break;
          } else {
            n -= 1L << (2 * k);
          }
        }
      }
    }
  } catch (EOFException e) {
  }
}


A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.

The first line of input contains the number of students n (2 ≤ n ≤ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.

Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.

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

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

    auto s = readln.chomp;

    auto ans = new int[] (n);

    foreach (i; 0 .. n) {
        int le = 1;
        int j = i-1;
        while (j >= 0 && (s[j] == 'R' || s[j] == '=')) {
            if (s[j] == 'R') { le += 1; }
            --j;
        }

        int r = 1;
        j = i;
        while (j < n-1 && (s[j] == 'L' || s[j] == '=')) {
            if (s[j] == 'L') { r += 1; }
            ++j;
        }

        ans[i] = max(le, r);
    }

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

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

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

    auto s = readln.chomp;

    auto ans = new int[] (n);
    ans[] = 1;

    foreach (i; 0 .. n-1) {
        if (s[i] == '=') {
            ans[i+1] = ans[i];
            continue;
        }

        if (s[i] == 'R') {
            ans[i+1] = ans[i] + 1;
            continue;
        }

        ans[i] = max(ans[i], ans[i+1] + 1);
        int j = i-1;
        while (j >= 0 && (s[j] == 'L' || s[j] == '=') && ans[j] == ans[j+1]) {
            if (s[j] == '=') { ans[j] = ans[j+1]; }
            else { ans[j] = max(ans[j], ans[j+1] + 1); }

            --j;
        }
    }

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

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

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

    auto s = readln.chomp;

    auto ans = new int[] (n);

    foreach (i; 0 .. n) {
        int le = 1;
        int j = i-1;
        while (j > 0 && (s[j] == 'R' || s[j] == '=')) {
            if (s[j] == 'R') { le += 1; }
            --j;
        }

        int r = 1;
        j = i;
        while (j < n-1 && (s[j] == 'L' || s[j] == '=')) {
            if (s[j] == 'L') { r += 1; }
            ++j;
        }

        ans[i] = max(le, r);
    }

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

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

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

    auto s = readln.chomp;

    auto ans = new int[] (n);
    ans[] = 1;

    foreach (i; 0 .. n-1) {
        if (s[i] == '=') {
            ans[i+1] = ans[i];
            continue;
        }

        if (s[i] == 'R') {
            ans[i+1] = ans[i] + 1;
            continue;
        }

        int j = i;
        while (j >= 0 && (s[j] == 'L' || s[j] == '=') && ans[j] == ans[j+1]) {
            if (s[j] == '=') { ans[j] = ans[j+1]; }
            else { ans[j] = ans[j+1] + 1; }

            --j;
        }
    }

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


Sereja has a sequence that consists of n positive integers, a1, a2, ..., an. First Sereja took a piece of squared paper and wrote all distinct non-empty non-decreasing subsequences of sequence a. Then for each sequence written on the squared paper, Sereja wrote on a piece of lines paper all sequences that do not exceed it.A sequence of positive integers x = x1, x2, ..., xr doesn't exceed a sequence of positive integers y = y1, y2, ..., yr, if the following inequation holds: x1 ≤ y1, x2 ≤ y2, ..., xr ≤ yr.Now Sereja wonders, how many sequences are written on the lines piece of paper. Help Sereja, find the required quantity modulo 1000000007 (109 + 7).

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106).

In the single line print the answer to the problem modulo 1000000007 (109 + 7).

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

static immutable size_t MAX = 1 << 20;
static immutable long M = 1000000007;

auto solve(size_t[] seq)
{
    auto tree = BinaryIndexedTree!
        (long, (a, b) => (a + b) % M, 0, (a, b) => (a + M - b) % M)
        (MAX);
    foreach_reverse(v; seq)
        tree[v] = v * (1 + tree[v..MAX]);
    return tree[];
}

void main()
{
    auto n = readln().strip().to!size_t();
    auto seq = new size_t[n];
    auto i = 0;
    foreach (w; readln().strip().split())
        seq[i++] = w.to!size_t();
    solve(seq).writeln();
}

/** Generic binary indexed tree for group.

Strictly speaking, group is not necessary;
associativity and left-cancellativity is enough.

*/
struct BinaryIndexedTree(Group, alias operation, Group Identity, alias inverse)
{
    Group[] x;
    size_t n;
    Group opIndex(in size_t i)
    {
        return opSlice(i, i+1);
    }
    Group opIndexAssign(Group v, in size_t i)
    {
        void binarySearch(size_t left, size_t right)
        {
            if (left + 1 == right) // left + 1 = i + 1;
            {
                x[left] = v;
                return;
            }
            size_t mid = ((left ^ right) >> 1) + (left & right);
            x[right-1] = inverse(x[right-1], x[mid-1]);
            if (mid <= i)
                binarySearch(mid, right);
            else
                binarySearch(left, mid);
            x[right-1] = operation(x[mid-1], x[right-1]);
        }
        binarySearch(0, n);
        return opIndex(i);
    }
    this (size_t n)
    {
        x.length = this.n = n.toMPT();
        foreach (ref e; x)
            e = Identity;
    }
    this (Group[] x)
    {
        this.n = x.length.toMPT();
        this.x = x;
        foreach (i; x.length..n)
            this.x ~= Identity;
        foreach (i; 0..n)
            foreach (lggap; 0..n)
            {
                if ((i+1) % (1 << (lggap + 1)))
                    break;
                this.x[i] = operation(this.x[i-(1 << lggap)], this.x[i]);
            }
    }
    private Group query0(size_t i)
    {
        if (i)
            return operation(query0(i ^ (i & -i)), x[i-1]);
        return Identity;
    }
    Group opSlice(in size_t a, in size_t b)
    {
        return inverse(query0(b), query0(a));
    }
    Group opSlice()
    {
        return query0(n);
    }
}

size_t toMPT(size_t n)
{
    if (n == 0)
        return 0;
    size_t y = 1;
    while (y < n && y)
        y <<= 1;
    return y;
}


The mayor of the Central Town wants to modernize Central Street, represented in this problem by the $$$(Ox)$$$ axis.On this street, there are $$$n$$$ antennas, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th antenna lies on the position $$$x_i$$$ and has an initial scope of $$$s_i$$$: it covers all integer positions inside the interval $$$[x_i - s_i; x_i + s_i]$$$.It is possible to increment the scope of any antenna by $$$1$$$, this operation costs $$$1$$$ coin. We can do this operation as much as we want (multiple times on the same antenna if we want).To modernize the street, we need to make all integer positions from $$$1$$$ to $$$m$$$ inclusive covered by at least one antenna. Note that it is authorized to cover positions outside $$$[1; m]$$$, even if it's not required.What is the minimum amount of coins needed to achieve this modernization?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 80$$$ and $$$n \le m \le 100\ 000$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$s_i$$$ ($$$1 \le x_i \le m$$$ and $$$0 \le s_i \le m$$$). On each position, there is at most one antenna (values $$$x_i$$$ are pairwise distinct).

You have to output a single integer: the minimum amount of coins required to make all integer positions from $$$1$$$ to $$$m$$$ inclusive covered by at least one antenna.

NoteIn the first example, here is a possible strategy:  Increase the scope of the first antenna by $$$40$$$, so that it becomes $$$2 + 40 = 42$$$. This antenna will cover interval $$$[43 - 42; 43 + 42]$$$ which is $$$[1; 85]$$$  Increase the scope of the second antenna by $$$210$$$, so that it becomes $$$4 + 210 = 214$$$. This antenna will cover interval $$$[300 - 214; 300 + 214]$$$, which is $$$[86; 514]$$$  Increase the scope of the third antenna by $$$31$$$, so that it becomes $$$10 + 31 = 41$$$. This antenna will cover interval $$$[554 - 41; 554 + 41]$$$, which is $$$[513; 595]$$$ Total cost is $$$40 + 210 + 31 = 281$$$. We can prove that it's the minimum cost required to make all positions from $$$1$$$ to $$$595$$$ covered by at least one antenna.Note that positions $$$513$$$ and $$$514$$$ are in this solution covered by two different antennas, but it's not important.—In the second example, the first antenna already covers an interval $$$[0; 2]$$$ so we have nothing to do.Note that the only position that we needed to cover was position $$$1$$$; positions $$$0$$$ and $$$2$$$ are covered, but it's not important.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = iota(N).map!(_ => readln.split.map!(to!int).array).array;
    A.sort!"a[0] - a[1] < b[0] - b[1]";

    auto dp = new int[][](N+1, M+1);
    foreach (i; 0..N+1) dp[i][] = 1 << 29;
    dp[0][0] = 0;

    foreach (i; 0..N) {
        foreach (j; 0..M) {
            int d = max(0, (A[i][0] - A[i][1]) - (j + 1));
            dp[i+1][min(M, A[i][0] + A[i][1] + d)] = min(dp[i+1][min(M, A[i][0] + A[i][1] + d)], dp[i][j] + d);
        }
        foreach (j; 0..M+1) {
            dp[i+1][j] = min(dp[i+1][j], dp[i][j]);
        }
        foreach (j; 0..M) {
            dp[i+1][j+1] = min(dp[i+1][j+1], dp[i+1][j] + 1);
        }
    }

    dp[N][M].writeln;
}