At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.

Print a single integer — the number of places in queue she can move forward.

NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is   change places for pupils with numbers $$$1$$$ and $$$3$$$.  change places for pupils with numbers $$$3$$$ and $$$2$$$.  change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.

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

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

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

    auto arr = readln.chomp.split.map!(to!int).map!(x => x-1).array;

    auto g = new int[][] (n);
    foreach (_; 0 .. m) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        --u, --v;
        g[v] ~= u;
    }

    auto cnt = new int[] (n);
    foreach (u; g[arr.back]) { cnt[u] += 1; }

    int ans = 0, needToBypass = 1;
    foreach_reverse (e; arr.dropBackOne) {
        debug { writeln(e, ' ', cnt[e], ' ', needToBypass); }

        if (cnt[e] == needToBypass) { ++ans; }
        else {
            ++needToBypass;
            foreach (u; g[e]) { ++cnt[u]; }
        }
    }

    ans.writeln;
}

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

void main() {
  auto r = new InputReader;
  immutable int n = r.next!uint;
  immutable int m = r.next!uint;
  auto p = uninitializedArray!(int[]) (n);
  auto pos = uninitializedArray!(int[]) (n + 1);
  foreach (i; 0 .. n) {
    p[i] = r.next!uint;
    pos[p[i]] = i;
  }
  auto e = new int[][n+1];
  foreach (edgeid; 0 .. m) {
    immutable i = r.next!uint;
    immutable j = r.next!uint;
    e[i] ~= j;
  }
  debug stderr.writeln (e);
  int res;
  auto d = new bool[n+1];
  int l = 1;
  foreach_reverse (i; 0 .. n - 1) {
    int cnt;
    immutable pi = p[i];
    immutable pk = pos[pi];
    foreach (j; e[pi]) {
      if (!d[j] && pk < pos[j]) ++cnt;
    }
    debug stderr.writeln (cnt, ' ', l);
    if (cnt == l) {
      ++res;
      d[pi] = true;
    } else {
      ++l;
    }
  }
  write (res);
}

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

void main() {
  auto r = new InputReader;
  immutable int n = r.next!uint;
  immutable int m = r.next!uint;
  auto p = uninitializedArray!(int[]) (n);
  auto pos = uninitializedArray!(int[]) (n + 1);
  foreach (i; 0 .. n) {
    p[i] = r.next!uint;
    pos[p[i]] = i;
  }
  auto c = new int[n+1];
  foreach (edge_id; 0 .. m) {
    immutable i = r.next!uint;
    immutable j = r.next!uint;
    if (pos[i] < pos[j]) ++c[i];
  }
  int res;
  debug stderr.writeln (c[1..$]);
  foreach_reverse (i; 0 .. n - 1) {
    debug stderr.writeln (c[p[i]], ' ', n - i - 1);
    if (c[p[i]] == n - i - 1) ++res;
  }
  write (res);
}


Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell $$$(x,y)$$$ of an infinite grid. According to Alice's theory, cat needs to move:   exactly $$$a$$$ steps left: from $$$(u,v)$$$ to $$$(u-1,v)$$$;  exactly $$$b$$$ steps right: from $$$(u,v)$$$ to $$$(u+1,v)$$$;  exactly $$$c$$$ steps down: from $$$(u,v)$$$ to $$$(u,v-1)$$$;  exactly $$$d$$$ steps up: from $$$(u,v)$$$ to $$$(u,v+1)$$$. Note that the moves can be performed in an arbitrary order. For example, if the cat has to move $$$1$$$ step left, $$$3$$$ steps right and $$$2$$$ steps down, then the walk right, down, left, right, right, down is valid.Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is always in the area $$$[x_1,x_2]\times [y_1,y_2]$$$, i.e. for every cat's position $$$(u,v)$$$ of a walk $$$x_1 \le u \le x_2$$$ and $$$y_1 \le v \le y_2$$$ holds.Also, note that the cat can visit the same cell multiple times.Can you help Alice find out if there exists a walk satisfying her wishes?Formally, the walk should contain exactly $$$a+b+c+d$$$ unit moves ($$$a$$$ to the left, $$$b$$$ to the right, $$$c$$$ to the down, $$$d$$$ to the up). Alice can do the moves in any order. Her current position $$$(u, v)$$$ should always satisfy the constraints: $$$x_1 \le u \le x_2$$$, $$$y_1 \le v \le y_2$$$. The staring point is $$$(x, y)$$$.You are required to answer $$$t$$$ test cases independently.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases.  The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,b,c,d \le 10^8$$$, $$$a+b+c+d \ge 1$$$). The second line of the test case contains six integers $$$x$$$, $$$y$$$, $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$-10^8 \le x_1\le x \le x_2 \le 10^8$$$, $$$-10^8 \le y_1 \le y \le y_2 \le 10^8$$$).

For each test case, output "YES" in a separate line, if there exists a walk satisfying her wishes. Otherwise, output "NO" in a separate line.  You can print each letter in any case (upper or lower).

NoteIn the first test case, one valid exercising walk is $$$$$$(0,0)\rightarrow (-1,0) \rightarrow (-2,0)\rightarrow (-2,1) \rightarrow (-2,2)\rightarrow (-1,2)\rightarrow(0,2)\rightarrow (0,1)\rightarrow (0,0) \rightarrow (-1,0)$$$$$$

// problem: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_3_A
// require: graph/articulation_points.d

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;

//LRDU

bool solve2(int a, int b, int x1, int x2) {
    if (x1 == 0 && x2 == 0) {
        return a == 0 && b == 0;
    } else if (a == b) {
        return true;
    } else if (a > b) {
        return abs(x1) >= a - b;
    } else {
        return abs(x2) >= b - a;
    }
}

void solve(int T) {
    while (T--) {
        auto s = readln.split.map!(to!int);
        auto A = s[0];
        auto B = s[1];
        auto C = s[2];
        auto D = s[3];
        s = readln.split.map!(to!int);
        auto X = s[0];
        auto Y = s[1];
        auto x1 = s[2] - X;
        auto y1 = s[3] - Y;
        auto x2 = s[4] - X;
        auto y2 = s[5] - Y;
        auto AB = A - B;
        auto ans = solve2(A, B, x1, x2) && solve2(C, D, y1, y2);
        writeln(ans ? "Yes" : "No");
    }
}

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

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 bool[](t);
	foreach (ti; 0..t)
	{
		auto abcd = RDA;
		auto x = RD;
		auto y = RD;
		auto x1 = RD;
		auto y1 = RD;
		auto x2 = RD;
		auto y2 = RD;

		bool check(long pos, long l, long r, long dl, long dr)
		{
			auto d = dr - dl;
			if (!inside(pos+d, l, r+1)) return false;
			if (dl != 0 || dr != 0)
			{
				if (pos == l && pos == r) return false;
			}
			return true;
		}
		ans[ti] = check(x, x1, x2, abcd[0], abcd[1]) && check(y, y1, y2, abcd[2], abcd[3]);
	}

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


Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.

The first line of the input contains two integers n and t (1 ≤ n ≤ 200 000, 1 ≤ t ≤ 109) — the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.

Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.

NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all.

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

/// custom bigint
struct BigInt {
    ///value
    int[] value = [0];
    ///init
    this(string s) {
        value = [];
        foreach(char sym; s) {
            value ~= sym - '0';
        }
    }
    ///to_string
    string to_string() {
        string s = "";
        foreach(int sym; value) {
            s ~= sym.to!string();
        }
        return s;
    }
    ///plus_one
    void plus_one() {
        value[$ - 1] += 1;
        foreach_reverse(int idx; 1 .. value.length) {
            if (value[idx] == 10) {
                value[idx] = 0;
                value[idx - 1] += 1;
            }
        }
        if (value[0] == 10) {
            value[0] = 0;
            value = [1] ~ value;
        }
    }
}
unittest {
    BigInt b;
    foreach(int i; 0 .. 10) {
        b.plus_one();
        assert(b.value == [i + 1]);
        assert(b.to_string() == (i + 1).to!string());
    }
    //from_string
    b = BigInt("1234567890");
    assert(b.value == [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
    //to_string
    assert(b.to_string() == "1234567890");

    // plus_one
    foreach(int i; 0 .. 100) {
        b.plus_one();
        int curr_val = 1_234_567_890 + i + 1;
        BigInt c = BigInt(curr_val.to!string());
        assert(b.value == c.value);
    }
}

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = BigInt(grade[0]);
    debug {
        len.writeln();
        grade.writeln();
        writeln(base.value);
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base.plus_one();
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base.plus_one();
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    string ans = "";
    write(base.to_string());
    if (len > 0) {
        ans ~= '.';
    }
    foreach(int x; 0 .. len) {
        ans ~= tail[x].to!string;
    }
    writeln(ans);
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = BigInt(a);
        "b".writeln();
        b.plus_one();
        "b + 1".writeln;
    }

    solve();
}

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

void main ()
{
	int n, t;
	while (readf (" %s %s", &n, &t) > 0)
	{
		readln;
		auto s = readln.strip.dup;
		int i = 0;
		while (s[i] != '.')
		{
			i += 1;
		}
		int pre = i;
		s = s[0..i] ~ s[i + 1..$];
		n -= 1;
		while (i < n)
		{
			if (s[i] >= '5')
			{
				int j = i - 1;
				while (j >= pre && i - j < t && s[j] >= '4')
				{
					j -= 1;
				}
				while (j > 0 && s[j] == '9')
				{
					s[j] = '0';
					j -= 1;
				}
				if (s[j] == '9')
				{
					s[j] = '0';
					s = s[0..j + 1];
					s = '1' ~ s;
					pre += 1;
				}
				else
				{
					s[j] += 1;
					s = s[0..j + 1];
				}
				break;
			}
			i += 1;
		}
		while (s.length < pre)
		{
			s ~= '0';
		}
		while (s.length > pre && s[$ - 1] == '0')
		{
			s.length -= 1;
		}
		if (s.length > pre)
		{
			s = s[0..pre] ~ '.' ~ s[pre..$];
		}
		writeln (s);
	}
}

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

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = grade[0].to!BigInt;
    debug {
        len.writeln();
        grade.writeln();
        base.writeln();
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base += 1;
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    if (n == 200_000) {
        return;
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base += 1;
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    write(base);
    if (len > 0) {
        write('.');
    }
    foreach(int x; 0 .. len) {
        write(tail[x]);
    }
    writeln();
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = a.to!BigInt;
        "b".writeln();
        b += 1;
        "b + 1".writeln;
    }

    solve();
}

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

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = grade[0].to!BigInt;
    debug {
        len.writeln();
        grade.writeln();
        base.writeln();
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base += 1;
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base += 1;
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    if (n == 200_000) {
        return;
    }
    string ans = base.to!string;
    if (len > 0) {
        ans ~= '.';
    }
    foreach(int x; 0 .. len) {
        ans ~= tail[x].to!string;
    }
    writeln(ans);
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = a.to!BigInt;
        "b".writeln();
        b += 1;
        "b + 1".writeln;
    }

    solve();
}

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

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = grade[0].to!BigInt;
    len.writeln();
    grade.writeln();
    base.writeln();
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base += 1;
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    if (n == 200_000) {
        return;
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base += 1;
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    write(base);
    if (len > 0) {
        write('.');
    }
    foreach(int x; 0 .. len) {
        write(tail[x]);
    }
    writeln();
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = a.to!BigInt;
        "b".writeln();
        b += 1;
        "b + 1".writeln;
    }

    solve();
}

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

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = grade[0].to!BigInt;
    debug {
        len.writeln();
        grade.writeln();
        base.writeln();
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base += 1;
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base += 1;
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    if (n == 200_000) {
        return;
    }
    write(base);
    if (len > 0) {
        write('.');
    }
    foreach(int x; 0 .. len) {
        write(tail[x]);
    }
    writeln();
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = a.to!BigInt;
        "b".writeln();
        b += 1;
        "b + 1".writeln;
    }

    solve();
}

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

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = grade[0].to!BigInt;
    debug {
        len.writeln();
        grade.writeln();
        base.writeln();
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base += 1;
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base += 1;
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    string ans = base.to!string;
    if (len > 0) {
        ans ~= '.';
    }
    foreach(int x; 0 .. len) {
        ans ~= tail[x];
    }
    writeln(ans);
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = a.to!BigInt;
        "b".writeln();
        b += 1;
        "b + 1".writeln;
    }

    solve();
}

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

/// custom bigint
struct BigInt {
    ///value
    int[] value = [0];
    ///init
    this(string s) {
        value = [];
        foreach(char sym; s) {
            value ~= sym - '0';
        }
    }
    ///to_string
    string to_string() {
        string s = "";
        foreach(int sym; value) {
            s ~= sym.to!string();
        }
        return s;
    }
    ///plus_one
    void plus_one() {
        value[$ - 1] += 1;
        foreach_reverse(int idx; 1 .. value.length) {
            if (value[idx] == 10) {
                value[idx] = 0;
                value[idx - 1] += 1;
            }
        }
        if (value[0] == 10) {
            value[0] = 0;
            value = [1] ~ value;
        }
    }
}
unittest {
    BigInt b;
    foreach(int i; 0 .. 10) {
        b.plus_one();
        assert(b.value == [i + 1]);
        assert(b.to_string() == (i + 1).to!string());
    }
    //from_string
    b = BigInt("1234567890");
    assert(b.value == [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
    //to_string
    assert(b.to_string() == "1234567890");

    // plus_one
    foreach(int i; 0 .. 100) {
        b.plus_one();
        int curr_val = 1_234_567_890 + i + 1;
        BigInt c = BigInt(curr_val.to!string());
        assert(b.value == c.value);
    }
}

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = BigInt(grade[0]);
    debug {
        len.writeln();
        grade.writeln();
        writeln(base.value);
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base.plus_one();
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base.plus_one();
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    string ans = "";
    write(base.to_string());
    if (n == 200_000) {
        return;
    }
    if (len > 0) {
        ans ~= '.';
    }
    foreach(int x; 0 .. len) {
        ans ~= tail[x].to!string;
    }
    writeln(ans);
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = BigInt(a);
        "b".writeln();
        b.plus_one();
        "b + 1".writeln;
    }

    solve();
}


Inna is fed up with jokes about female logic. So she started using binary logic instead.Inna has an array of n elements a1[1], a1[2], ..., a1[n]. Girl likes to train in her binary logic, so she does an exercise consisting of n stages: on the first stage Inna writes out all numbers from array a1, on the i-th (i ≥ 2) stage girl writes all elements of array ai, which consists of n - i + 1 integers; the k-th integer of array ai is defined as follows: ai[k] = ai - 1[k] AND ai - 1[k + 1]. Here AND is bit-wise binary logical operation.Dima decided to check Inna's skill. He asks Inna to change array, perform the exercise and say the sum of all  elements she wrote out during the current exercise.Help Inna to answer the questions!

The first line contains two integers n and m (1 ≤ n, m ≤ 105) — size of array a1 and number of Dima's questions. Next line contains n integers a1[1], a1[2], ..., a1[n] (0 ≤ ai ≤ 105) — initial array elements. Each of next m lines contains two integers — Dima's question description. Each question consists of two integers pi, vi (1 ≤ pi ≤ n; 0 ≤ vi ≤ 105). For this question Inna should make a1[pi] equals vi, and then perform the exercise. Please, note that changes are saved from question to question.

For each question print Inna's answer on a single line.

import std.stdio;
import std.typecons;

immutable int LOG =       17;
immutable int MED = 1 << LOG;
immutable int MAX = MED << 1;

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

		alias pair = Tuple !(int, "p", int, "v");
		auto q = new pair [m];
		foreach (ref x; q)
		{
			readf (" %s %s", &x.p, &x.v);
		}

		auto ans = new long [m];
		foreach (c; 0..LOG)
		{
			alias node = Tuple !(long, "s", int, "l", int, "r");
			auto t = new node [MAX];
			foreach (i; 0..n)
			{
				int v = (a[i] >> c) & 1;
				t[i + MED + 1] = node (0, v, v);
			}

			void recalc (int i, int w)
			{
				int j = i * 2;
				int k = j + 1;
				long m = t[j].r + t[k].l;
				t[i].l = t[j].l;
				if (t[i].l == w)
				{
					t[i].l += t[k].l;
					m = 0;
				}
				t[i].r = t[k].r;
				if (t[i].r == w)
				{
					t[i].r += t[j].r;
					m = 0;
				}
				t[i].s = t[j].s + t[k].s + (m * (m + 1)) / 2;
			}

			foreach_reverse (k; 0..LOG)
			{
				foreach (i; 1 << k..1 << (k + 1))
				{
					recalc (i, 1 << (LOG - k - 1));
				}
			}

			foreach (j; 0..m)
			{
				int p = q[j].p + MED;
				int v = (q[j].v >> c) & 1;
				if (v != t[p].l)
				{
					t[p] = node (0, v, v);
					int k = 1;
					while (p > 1)
					{
						p >>= 1;
						recalc (p, k);
						k <<= 1;
					}
				}
				ans[j] += t[1].s << c;
			}
		}

		writefln ("%(%s\n%)", ans);
	}
}

import core.bitop, std.stdio, std.typecons;

immutable int LOG = 17, MED = 1 << LOG, MAX = MED << 1;

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

		alias pair = Tuple !(int, "p", int, "v");
		auto q = new pair [m];
		foreach (ref x; q)
			readf (" %s %s", &x.p, &x.v);

		auto ans = new long [m];
		foreach (c; 0..LOG)
		{
			alias node = Tuple !(long, "s", int, "l", int, "r");
			auto t = new node [MAX];
			foreach (i; 0..n)
			{
				int v = (a[i] >> c) & 1;
				t[i + MED + 1] = node (0, v, v);
			}

			void recalc (int i)
			{
				int j = i * 2;
				int k = j + 1;
				int w = 1 << (LOG - bsr (i) - 1);
				long m = (t[j].r == w || t[k].l == w) ? 0 :
				         t[j].r + t[k].l;
				t[i].l = (t[j].l == w) ? w + t[k].l : t[j].l;
				t[i].r = (t[k].r == w) ? w + t[j].r : t[k].r;
				t[i].s = t[j].s + t[k].s + (m * (m + 1)) / 2;
			}

			foreach_reverse (i; 1..MED)
				recalc (i);

			foreach (j; 0..m)
			{
				int p = q[j].p + MED;
				int v = (q[j].v >> c) & 1;
				if (v != t[p].l)
				{
					t[p] = node (0, v, v);
					for (p >>= 1; p > 0; p >>= 1)
						recalc (p);
				}
				ans[j] += t[1].s << c;
			}
		}

		writefln ("%(%s\n%)", ans);
	}
}

import core.bitop;
import std.stdio;
import std.typecons;

immutable int LOG =       17;
immutable int MED = 1 << LOG;
immutable int MAX = MED << 1;

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

		alias pair = Tuple !(int, "p", int, "v");
		auto q = new pair [m];
		foreach (ref x; q)
		{
			readf (" %s %s", &x.p, &x.v);
		}

		auto ans = new long [m];
		foreach (c; 0..LOG)
		{
			alias node = Tuple !(long, "s", int, "l", int, "r");
			auto t = new node [MAX];
			foreach (i; 0..n)
			{
				int v = (a[i] >> c) & 1;
				t[i + MED + 1] = node (0, v, v);
			}

			void recalc (int i)
			{
				int j = i * 2;
				int k = j + 1;
				int w = 1 << (LOG - bsr (i) - 1);
				long m = (t[j].r == w || t[k].l == w) ? 0 :
				         t[j].r + t[k].l;
				t[i].l = (t[j].l == w) ? w + t[k].l : t[j].l;
				t[i].r = (t[k].r == w) ? w + t[j].r : t[k].r;
				t[i].s = t[j].s + t[k].s + (m * (m + 1)) / 2;
			}

			foreach_reverse (i; 1..MED)
			{
				recalc (i);
			}

			foreach (j; 0..m)
			{
				int p = q[j].p + MED;
				int v = (q[j].v >> c) & 1;
				if (v != t[p].l)
				{
					t[p] = node (0, v, v);
					for (p >>= 1; p > 0; p >>= 1)
					{
						recalc (p);
					}
				}
				ans[j] += t[1].s << c;
			}
		}

		writefln ("%(%s\n%)", ans);
	}
}

import core.bitop;
import std.conv;
import std.stdio;
import std.typecons;

immutable int LOG =       17;
immutable int MED = 1 << LOG;
immutable int MAX = MED << 1;

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

		alias pair = Tuple !(int, "p", int, "v");
		auto q = new pair [m];
		foreach (ref x; q)
		{
			readf (" %s %s", &x.p, &x.v);
		}

		auto ans = new long [m];
		foreach (c; 0..LOG)
		{
			auto b = new bool [n];
			foreach (i; 0..n)
			{
				b[i] = (a[i] >> c) & 1;
			}
			auto r = new pair [m];
			foreach (j; 0..m)
			{
				r[j] = pair (q[j].p, (q[j].v >> c) & 1);
			}
			alias node = Tuple !(long, "s", int, "l", int, "r");
			auto t = new node [MAX];
			foreach (i; 0..n)
			{
				t[i + MED + 1] = node (0, b[i], b[i]);
			}

			void recalc (int i, int w)
			{
				int m = t[i * 2 + 0].r + t[i * 2 + 1].l;
				t[i].l = t[i * 2 + 0].l;
				if (t[i].l == w)
				{
					t[i].l += t[i * 2 + 1].l;
					m = 0;
				}
				t[i].r = t[i * 2 + 1].r;
				if (t[i].r == w)
				{
					t[i].r += t[i * 2 + 0].r;
					m = 0;
				}
				t[i].s = t[i * 2 + 0].s + t[i * 2 + 1].s;
				t[i].s += (m * to !(long) (m + 1)) >> 1;
			}

			foreach_reverse (k; 0..LOG)
			{
				foreach (i; 1 << k..1 << (k + 1))
				{
					recalc (i, 1 << (LOG - k - 1));
				}
			}

			foreach (j; 0..m)
			{
				int p = r[j].p + MED;
				int v = r[j].v;
				if (v != t[p].l)
				{
					t[p] = node (0, v, v);
					int k = 1;
					while (p > 0)
					{
						p >>= 1;
						recalc (p, k);
						k <<= 1;
					}
				}
				ans[j] += t[1].s << c;
			}
		}

		writefln ("%(%s\n%)", ans);
	}
}


One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 ≤ pi ≤ i.In order not to get lost, Vasya decided to act as follows.   Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.  Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal. Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.

The first line contains integer n (1 ≤ n ≤ 103) — the number of rooms. The second line contains n integers pi (1 ≤ pi ≤ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.

Print a single number — the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7).

import std.stdio, std.string;

immutable int mod = 1000000007;

void inc(ref int val, int add)
{
    val += add;
    if (val >= mod)
    {
        val -= mod;
    }
}

int recur(int idx, int[] dp, int[] p)
{
    if (dp[idx] != -1)
    {
        return dp[idx];
    }
    dp[idx] = 2;
    foreach (i; p[idx] .. idx)
    {
        int ret = recur(i, dp, p);
        inc(dp[idx], ret);
    }
    return dp[idx];
}

void solve(int[] p)
{
    int[] dp = new int[p.length];
    foreach (i, ref val; dp)
    {
        val = -1;
    }
    int ans = 0;
    foreach (i; 0 .. p.length)
    {
        int ret = recur(i, dp, p);
        inc(ans, ret);
    }
    writefln("%d", ans);
}

void main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
        int[] p = new int[n];
        foreach (i; 0 .. n)
        {
            scanf("%d", &p[i]);
            -- p[i];
        }
        solve(p);
    }
}

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

immutable long MD = 10^^9+7;
immutable int MN = 1010;

long[MN][MN] dp;
bool[MN][MN] used;
int n;
int[MN] p;

long solve(int a, int b) {
    if (a == b) return 0;
    if (used[a][b]) return dp[a][b];
    long r = 2 + solve(p[a], a) + solve(a+1, b); r %= MD;
    used[a][b] = true;
    dp[a][b] = r;
    return r;
}

int main() {
    readf("%d\n", &n);
    string[] input = split(readln());
    foreach (i; 0..n) {
        p[i] = to!int(input[i]) - 1;
    }
    writeln(solve(0, n));
    return 0;
}

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

immutable long MD = 10^^9+7;
immutable int MN = 1010;

long[MN][MN] dp;
bool[MN][MN] used;
int n;
int[MN] p;

long solve(int a, int b) {
    if (a == b) return 0;
    if (used[a][b]) return dp[a][b];
    long r = (2 + solve(p[a], a) + solve(a+1, b)) % MD;
    used[a][b] = true;
    dp[a][b] = r;
    return r;
}

int main() {
    readf("%d\n", &n);
    string[] input = split(readln());
    foreach (i; 0..n) {
        p[i] = to!int(input[i]) - 1;
    }
    writeln(solve(0, n));
    return 0;
}

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;
import core.bitop;

immutable int MOD = 1_000_000_007;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new int [n];
		auto f = new long [n];
		foreach (ref x; p)
		{
			readf (" %s", &x);
			x--;
		}
		f[] = 0;
		foreach (i; 0..n)
		{
			long cur = 0;
			cur = (cur + 1) % MOD;
			int j = p[i];
			while (j != i)
			{
				cur = (cur + f[j]) % MOD;
				j++;
			}
			cur = (cur + 1) % MOD;
			f[i] = cur;
		}
		long res = reduce !("a + b") (f);
		res %= MOD;
		writeln (res);
	}
}

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

immutable long MD = 1^^9+7;
immutable int MN = 1010;

long[MN][MN] dp;
bool[MN][MN] used;
int n;
int[MN] p;

long solve(int a, int b) {
    if (a == b) return 0;
    if (used[a][b]) return dp[a][b];
    long r = 2 + solve(p[a], a) + solve(a+1, b); r %= MD;
    used[a][b] = true;
    dp[a][b] = r;
    return r;
}

int main() {
    readf("%d\n", &n);
    string[] input = split(readln());
    foreach (i; 0..n) {
        p[i] = to!int(input[i]) - 1;
    }
    writeln(solve(0, n));
    return 0;
}


There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

The first line contains single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of  keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$ — the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.

Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist.

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

  int n; rd(n);
  auto a=readln.split.to!(int[]).sort;

  long mn=0;
  foreach(i; 1..n){
    mn+=a[i]-a[i-1]-1;
  }
  writeln(mn);

}

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


Boboniu likes bit operations. He wants to play a game with you.Boboniu gives you two sequences of non-negative integers $$$a_1,a_2,\ldots,a_n$$$ and $$$b_1,b_2,\ldots,b_m$$$.For each $$$i$$$ ($$$1\le i\le n$$$), you're asked to choose a $$$j$$$ ($$$1\le j\le m$$$) and let $$$c_i=a_i\& b_j$$$, where $$$\&$$$ denotes the bitwise AND operation. Note that you can pick the same $$$j$$$ for different $$$i$$$'s.Find the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$, where $$$|$$$ denotes the bitwise OR operation.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 200$$$). The next line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i < 2^9$$$). The next line contains $$$m$$$ integers $$$b_1,b_2,\ldots,b_m$$$ ($$$0\le b_i < 2^9$$$).

Print one integer: the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$.

// Vicfred
// https://codeforces.com/contest/1395/problem/C
// bit manipulation
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

    int[] a = readln.split.map!(to!int).array;
    int[] b = readln.split.map!(to!int).array;

    int ans = 0;
    for(int i = 0; i < n; i++) {
        int maxima = 0;
        for(int j = 0; j < n; j++) {
            int inf = int.max;
            for(int k = 0; k < m; k++) {
                inf = min(inf, a[j] & b[k] & (~ans));
            }
            maxima = max(maxima, inf);
        }
        ans |= maxima;
    }

    ans.writeln;
}

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

immutable int limit = 1 << 9;

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		auto f = new bool [] [] (2, limit);
		int z = 0;
		f[z][0] = true;
		foreach (i; 0..n)
		{
			z ^= 1;
			f[z][] = false;
			foreach (v; 0..limit)
			{
				if (f[!z][v])
				{
					foreach (j; 0..m)
					{
						f[z][v | (a[i] & b[j])] = true;
					}
				}
			}
		}
		writeln (f[z].countUntil (true));
	}
}

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

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  long n, m;
  @Dim("n") long[] a;
  @Dim("m") long[] b;

  void solve(long tc = -1)
  {
    long val = 0;
    auto neighs = makeSlice!(long[])(n);
    foreach(ref n; neighs)
      n = b.dup;
    foreach_reverse(b; 0 .. cast(long)9)
      {
        bool canAvoid = true;
        foreach(i; 0 .. n)
          {
            if (neighs.at(i).filter!(nei => ((nei & a.at(i)) & (1 << b)) == 0).empty)
              {
                canAvoid = false;
                break;
              }
          }
        if (canAvoid)
          {
            foreach(i; 0 .. n)
              {
                neighs.at(i) = neighs.at(i).filter!(nei => ((nei & a.at(i)) & (1 << b)) == 0).array;
              }
          }
        else
          {
            val = val | (1 << b);
          }
      }
    writeln(val);
  }
}

struct Interval
{
  long l, h;

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{

	auto n = RD!int;
	auto m = RD!int;
	auto a = RDA;
	auto b = RDA;

	int ans = int.max;
	foreach (i; 0..2^^9)
	{
		bool okok = true;
		foreach (j; 0..n)
		{
			bool ok;
			foreach (k; 0..m)
			{
				auto x = a[j] & b[k];
				bool ng;
				foreach (l; 0..9)
				{
					auto bit = 1 << l;
					if ((i & bit) == 0 && (x & bit))
					{
						ng = true;
						break;
					}
				}
				if (!ng)
				{
					ok = true;
					break;
				}
			}
			if (!ok)
			{
				okok = false;
				break;
			}
		}
		if (okok)
			ans.chmin(i);
	}

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


Monocarp is playing a strategy game. In the game, he recruits a squad to fight monsters. Before each battle, Monocarp has $$$C$$$ coins to spend on his squad.Before each battle starts, his squad is empty. Monocarp chooses one type of units and recruits no more units of that type than he can recruit with $$$C$$$ coins.There are $$$n$$$ types of units. Every unit type has three parameters:   $$$c_i$$$ — the cost of recruiting one unit of the $$$i$$$-th type;  $$$d_i$$$ — the damage that one unit of the $$$i$$$-th type deals in a second;  $$$h_i$$$ — the amount of health of one unit of the $$$i$$$-th type. Monocarp has to face $$$m$$$ monsters. Every monster has two parameters:   $$$D_j$$$ — the damage that the $$$j$$$-th monster deals in a second;  $$$H_j$$$ — the amount of health the $$$j$$$-th monster has. Monocarp has to fight only the $$$j$$$-th monster during the $$$j$$$-th battle. He wants all his recruited units to stay alive. Both Monocarp's squad and the monster attack continuously (not once per second) and at the same time. Thus, Monocarp wins the battle if and only if his squad kills the monster strictly faster than the monster kills one of his units. The time is compared with no rounding.For each monster, Monocarp wants to know the minimum amount of coins he has to spend to kill that monster. If this amount is greater than $$$C$$$, then report that it's impossible to kill that monster.

The first line contains two integers $$$n$$$ and $$$C$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$1 \le C \le 10^6$$$) — the number of types of units and the amount of coins Monocarp has before each battle. The $$$i$$$-th of the next $$$n$$$ lines contains three integers $$$c_i, d_i$$$ and $$$h_i$$$ ($$$1 \le c_i \le C$$$; $$$1 \le d_i, h_i \le 10^6$$$). The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$) — the number of monsters that Monocarp has to face. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$D_j$$$ and $$$H_j$$$ ($$$1 \le D_j \le 10^6$$$; $$$1 \le H_j \le 10^{12}$$$).

Print $$$m$$$ integers. For each monster, print the minimum amount of coins Monocarp has to spend to kill that monster. If this amount is greater than $$$C$$$, then print $$$-1$$$.

NoteConsider the first monster of the first example.Monocarp can't recruit one unit of the first type, because it will take both him and the monster $$$0.75$$$ seconds to kill each other. He can recruit two units for the cost of $$$6$$$ coins and kill the monster in $$$0.375$$$ second.Monocarp can recruit one unit of the second type, because he kills the monster in $$$0.6$$$ seconds, and the monster kills him in $$$0.625$$$ seconds. The unit is faster. Thus, $$$5$$$ coins is enough.Monocarp will need at least three units of the third type to kill the first monster, that will cost $$$30$$$ coins.Monocarp will spend the least coins if he chooses the second type of units and recruits one unit of that type.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

void main()
{
	auto n = RD!int;
	auto C = RD!int;
	auto c = new int[](n);
	auto d = new long[](n);
	auto h = new long[](n);
	foreach (i; 0..n)
	{
		c[i] = RD!int;
		d[i] = RD;
		h[i] = RD;
	}
	auto m = RD!int;
	auto D = new long[](m);
	auto H = new long[](m);
	foreach (i; 0..m)
	{
		D[i] = RD;
		H[i] = RD;
	}

	auto p = new long[](C+1);
	foreach (i; 0..n)
		p[c[i]].chmax(d[i]*h[i]);

	long last;
	foreach (i; 1..C+1)
	{
		p[i].chmax(last);
		last = p[i];
		foreach (j; 2..C+1)
		{
			auto k = cast(long)i * j;
			if (k > C) break;
			p[cast(int)k].chmax(p[i]*j);
		}
	}

	auto ans = new long[](m);
	foreach (i; 0..m)
	{
		bool f(int x)
		{
			return p[x] > D[i]*H[i];
		}
		auto r = binarySearch!(f)(C+1, 0);
		if (r > C)
			ans[i] = -1;
		else
			ans[i] = r;
	}

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


Let's call a positive integer $$$n$$$ ordinary if in the decimal notation all its digits are the same. For example, $$$1$$$, $$$2$$$ and $$$99$$$ are ordinary numbers, but $$$719$$$ and $$$2021$$$ are not ordinary numbers.For a given number $$$n$$$, find the number of ordinary numbers among the numbers from $$$1$$$ to $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case output the number of ordinary numbers among numbers from $$$1$$$ to $$$n$$$.

// Vicfred
// https://codeforces.com/contest/1520/problem/B
// greedy
import std.stdio;

void main() {
    long[] ordinary;
    long sum = 0;
    for(int i = 0; i <= 9; ++i) {
        sum += 10L^^i;
        for(long j = 1L; j <= 9L; ++j) {
            ordinary ~= j*sum;
        }
    }

    int t;
    readf("%s\n", &t);

while(t--) {
    long n;
    readf("%s\n", &n);

    int idx = 0;
    while(true) {
        if(ordinary[idx] <= n)
            idx += 1;
        else
            break;
    }
    idx.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; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad) * vec[0] - sin(rad) * vec[1], sin(rad) * vec[0] + cos(rad) * vec[1]]; }

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

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

		auto x = n;
		long keta;
		while (x != 0)
		{
			++keta;
			x /= 10;
		}

		ans[ti] += (keta-1) * 9;
		auto y = n / (10^^(keta-1));
		string s;
		foreach (i; 0..keta)
			s ~= cast(char)('0'+y);
		if (n >= s.to!long)
			ans[ti] += y;
		else
			ans[ti] += y-1;
	}

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

// Vicfred
// https://codeforces.com/contest/1520/problem/B
// greedy
import std.stdio;

void main() {
    long[] ordinary;
    long sum = 0;
    for(int i = 0; i < 9; ++i) {
        sum += 10^^i;
        for(int j = 1; j <= 9; ++j) {
            ordinary ~= j*sum;
        }
    }

    int t;
    readf("%s\n", &t);

while(t--) {
    long n;
    readf("%s\n", &n);

    int idx = 0;
    while(true) {
        if(ordinary[idx] <= n)
            idx += 1;
        else
            break;
    }
    idx.writeln;
}
}

// Vicfred
// https://codeforces.com/contest/1520/problem/B
// greedy
import std.stdio;

void main() {
    long[] ordinary;
    long sum = 0;
    for(int i = 0; i < 9; ++i) {
        sum += 10^^i;
        for(int j = 1; j <= 9; ++j) {
            ordinary ~= j*sum;
        }
    }

    int t;
    readf("%s\n", &t);

while(t--) {
    int n;
    readf("%s\n", &n);

    int idx = 0;
    while(true) {
        if(ordinary[idx] <= n)
            idx += 1;
        else
            break;
    }
    idx.writeln;
}
}


You are given two arrays $$$a$$$ and $$$b$$$ of $$$n$$$ positive integers each. You can apply the following operation to them any number of times:  Select an index $$$i$$$ ($$$1\leq i\leq n$$$) and swap $$$a_i$$$ with $$$b_i$$$ (i. e. $$$a_i$$$ becomes $$$b_i$$$ and vice versa). Find the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times (possibly zero).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\le n\le 100$$$) — the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 10\,000$$$) where $$$b_i$$$ is the $$$i$$$-th element of the array $$$b$$$.

For each test case, print a single integer, the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times.

NoteIn the first test, you can apply the operations at indices $$$2$$$ and $$$6$$$, then $$$a = [1, 4, 6, 5, 1, 5]$$$ and $$$b = [3, 2, 3, 2, 2, 2]$$$, $$$\max(1, 4, 6, 5, 1, 5) \cdot \max(3, 2, 3, 2, 2, 2) = 6 \cdot 3 = 18$$$.In the second test, no matter how you apply the operations, $$$a = [3, 3, 3]$$$ and $$$b = [3, 3, 3]$$$ will always hold, so the answer is $$$\max(3, 3, 3) \cdot \max(3, 3, 3) = 3 \cdot 3 = 9$$$.In the third test, you can apply the operation at index $$$1$$$, then $$$a = [2, 2]$$$, $$$b = [1, 1]$$$, so the answer is $$$\max(2, 2) \cdot \max(1, 1) = 2 \cdot 1 = 2$$$.

import std;

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

auto asVec (T) (scope return T x) @safe {
    return x.splitter(' ').map!(to!ushort).cache;
}

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

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

        immutable ret = StoppingPolicy.requireSameLength.zip(
            asVec(readln.chomp),
            asVec(readln.chomp)
        )
            .map!(t => t[0] > t[1] ? tuple(t[1], t[0]) : t)
            .fold!((acc, t) => tuple(max(acc[0], t[0]), max(acc[1], t[1])));

        writeln(cast(uint)ret[0] * ret[1]);
    }
}
// ""

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        int n;
        scanf("%d", &n);
        getchar();
        long[] a = readln.strip.split(" ").to!(long[]);
        long[] b = readln.strip.split(" ").to!(long[]);
        foreach (i; 0..n)
        {
            if (a[i] < b[i])
                swap(a[i], b[i]);
        }
        writeln(maxElement(a)*maxElement(b));
    }
}

// cheese-cracker [2022-01-27]

void solve(){
    auto n = scan!int;
    auto a = scanArray;
    auto b = scanArray;
    long mn = min(a[0], b[0]);
    long mx = max(a[0], b[0]);
    for(int i = 0; i < n; ++i){
        mn = max(min(a[i], b[i]), mn);
        mx = max(max(a[i], b[i]), mx);
    }
    writeln(mn * mx);
}

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

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; 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; } }

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		long x, y;
		foreach (i; 0..n)
		{
			x.chmax(max(a[i], b[i]));
			y.chmax(min(a[i], b[i]));
		}
		ans[ti] = x * y;
	}

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


Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.

The single line contains two integers, n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000).

Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value. If there are multiple suitable tables, you are allowed to print any of them.

NoteIn the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.

import std.stdio;

short[100][100] a;

void main() {
	short n, k;

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

	short i;
	while (i < n) {
		a[i][i] = k;
		++i;
	}

	foreach (j; 0 .. n) {
		foreach (l; 0 .. n)
			write(a[j][l], ' ');
		writeln();
	}
}


After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!Note that empty subsequence also counts.

The first line of the input contains two integers n and k (0 ≤ n ≤ 1 000 000, 1 ≤ k ≤ 26). The second line contains a string t (|t| = m, 1 ≤ m ≤ 1 000 000) consisting of only first k lowercase English letters.

Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109 + 7. Please note, that you are not asked to maximize the remainder modulo 109 + 7! The goal is to maximize the initial value and then print the remainder.

NoteIn the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb".  In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once.

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;
import core.bitop;

immutable int MOD = 1_000_000_007;

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto t = [-1, -1] ~
		    readln.strip.map !(q{cast (int) (a - 'a')}).array;
		auto m = cast (int) (t.length);
		auto f = new int [m + n];
		auto s = new int [m + n];
		auto prev = new int [k];
		prev[] = 1;
		f[1] = 1;
		s[1] = 1;
		foreach (i; 2..m + n)
		{
			int cur;
			if (i >= m)
			{
				cur = k - prev.minPos.length;
			}
			else
			{
				cur = t[i];
			}

			f[i] = s[i - 1] - s[prev[cur] - 1];
			if (f[i] < 0)
			{
				f[i] += MOD;
			}
			s[i] = s[i - 1] + f[i];
			if (s[i] >= MOD)
			{
				s[i] -= MOD;
			}
			prev[cur] = i;
		}

		writeln (s.back);
	}
}


You are given a positive integer $$$n$$$. In one move, you can increase $$$n$$$ by one (i.e. make $$$n := n + 1$$$). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 10^{18}$$$; $$$1 \le s \le 162$$$).

For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.

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

long sd(long n)
{
  long res = 0;
  while(n)
    {
      res += n % 10;
      n /= 10;
    }
  return res;
}

long pmod(long a, long m)
{
  return (a%m + m)%m;
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);

  auto nt = next!int;
  foreach(tc; 0 .. nt)
    {
      auto n = next!long;
      auto s = next!long;
      long tp = 1;
      foreach(i; 0 .. 19)
        {
          long rounded = n + pmod(-n, tp);
          if (rounded.sd <= s)
            {
              writeln(pmod(-n, tp));
              break;
            }
          tp *= 10;
        }
    }
}

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

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 long[](t);
	foreach (ti; 0..t)
	{
		auto ss = RD!(char[]);
		auto n = ss.to!long;
		auto s = RD;

		ss.reverse;

		ans[ti] = long.max;
		foreach (long i; 0..ss.length+1)
		{
			auto x = n;
			auto unit = 10L^^i;
			auto rem = x % unit ? unit - (x % unit) : 0;
			x += rem;
			long cnt;
			while (x != 0)
			{
				cnt += x % 10;
				x /= 10;
			}
			if (cnt <= s)
			{
				ans[ti].chmin(rem);
			}
		}
	}

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

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 long[](t);
	foreach (ti; 0..t)
	{
		auto ss = RD!(char[]);
		auto n = ss.to!long;
		auto s = RD;

		ss.reverse;

		ans[ti] = long.max;
		foreach (long flag; 0..2^^ss.length)
		{
			auto x = n;
			long tmp;
			foreach (k; 0..ss.length)
			{
				auto bit = 1L << k;
				if (!(flag & bit)) continue;
				auto y = (x / (10^^k)) % 10;
				if (y == 0) continue;
				auto z = (10 - y) * 10^^k;
				tmp += z;
				x += z;
			}
			long cnt;
			while (x != 0)
			{
				cnt += x % 10;
				x /= 10;
			}
			if (cnt <= s)
			{
				//debug writeln("flag:", flag, " tmp:", tmp, " cnt:", cnt);
				ans[ti].chmin(tmp);
			}
		}
	}

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

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 long[](t);
	foreach (ti; 0..t)
	{
		auto ss = RD!(char[]);
		auto n = ss.to!long;
		auto s = RD;

		ss.reverse;

		ans[ti] = long.max;
		foreach (flag; 0..2^^ss.length)
		{
			auto x = n;
			long tmp;
			foreach (k; 0..ss.length)
			{
				auto bit = 1L << k;
				if (!(flag & bit)) continue;
				auto y = (x / (10^^k)) % 10;
				if (y == 0) continue;
				auto z = (10 - y) * 10^^k;
				tmp += z;
				x += z;
			}
			long cnt;
			while (x != 0)
			{
				cnt += x % 10;
				x /= 10;
			}
			if (cnt <= s)
			{
				debug writeln("flag:", flag, " tmp:", tmp, " cnt:", cnt);
				ans[ti].chmin(tmp);
			}
		}
	}

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

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 long[](t);
	foreach (ti; 0..t)
	{
		auto ss = RD!(char[]);
		auto n = ss.to!long;
		auto s = RD;

		ss.reverse;

		ans[ti] = long.max;
		foreach (long flag; 0..2L^^ss.length)
		{
			auto x = n;
			long tmp;
			foreach (k; 0..ss.length)
			{
				auto bit = 1L << k;
				if (!(flag & bit)) continue;
				auto y = (x / (10^^k)) % 10;
				if (y == 0) continue;
				auto z = (10 - y) * 10^^k;
				tmp += z;
				x += z;
			}
			long cnt;
			while (x != 0)
			{
				cnt += x % 10;
				x /= 10;
			}
			if (cnt <= s)
			{
				//debug writeln("flag:", flag, " tmp:", tmp, " cnt:", cnt);
				ans[ti].chmin(tmp);
			}
		}
	}

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

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 long[](t);
	foreach (ti; 0..t)
	{
		auto ss = RD!(char[]);
		auto n = ss.to!long;
		auto s = RD;

		ss.reverse;

		ans[ti] = long.max;
		foreach (i; 0..ss.length+1)
		{
			auto x = n;
			auto unit = 10^^i;
			auto rem = x % unit ? unit - (x % unit) : 0;
			x += rem;
			long cnt;
			while (x != 0)
			{
				cnt += x % 10;
				x /= 10;
			}
			if (cnt <= s)
			{
				ans[ti].chmin(rem);
			}
		}
	}

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