Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of $$$n$$$ steps. At the $$$i$$$-th step, a place is chosen for the number $$$i$$$ $$$(1 \leq i \leq n)$$$. The position for the number $$$i$$$ is defined as follows:  For all $$$j$$$ from $$$1$$$ to $$$n$$$, we calculate $$$r_j$$$  — the minimum index such that $$$j \leq r_j \leq n$$$, and the position $$$r_j$$$ is not yet occupied in the permutation. If there are no such positions, then we assume that the value of $$$r_j$$$ is not defined.  For all $$$t$$$ from $$$1$$$ to $$$n$$$, we calculate $$$count_t$$$  — the number of positions $$$1 \leq j \leq n$$$ such that $$$r_j$$$ is defined and $$$r_j = t$$$.  Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the $$$count$$$ array is maximum.  The generator selects one of these positions for the number $$$i$$$. The generator can choose any position. Let's have a look at the operation of the algorithm in the following example:  Let $$$n = 5$$$ and the algorithm has already arranged the numbers $$$1, 2, 3$$$ in the permutation. Consider how the generator will choose a position for the number $$$4$$$:  The values of $$$r$$$ will be $$$r = [3, 3, 3, 4, \times]$$$, where $$$\times$$$ means an indefinite value.  Then the $$$count$$$ values will be $$$count = [0, 0, 3, 1, 0]$$$.  There are only two unoccupied positions in the permutation: $$$3$$$ and $$$4$$$. The value in the $$$count$$$ array for position $$$3$$$ is $$$3$$$, for position $$$4$$$ it is $$$1$$$.  The maximum value is reached only for position $$$3$$$, so the algorithm will uniquely select this position for number $$$4$$$. Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind $$$p_1, p_2, \ldots, p_n$$$ and decided to find out if it could be obtained as a result of the generator.Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^5)$$$  — the number of test cases. Then the descriptions of the test cases follow. The first line of the test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — the size of the permutation. The second line of the test case contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$)  — the permutation written by Denis. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

Print "Yes" if this permutation could be obtained as a result of the generator. Otherwise, print "No". All letters can be displayed in any case.

NoteLet's simulate the operation of the generator in the first test.At the $$$1$$$ step, $$$r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]$$$. The maximum value is reached in any free position, so the generator can choose a random position from $$$1$$$ to $$$5$$$. In our example, it chose $$$5$$$.At the $$$2$$$ step, $$$r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]$$$. The maximum value is reached in positions from $$$1$$$ to $$$4$$$, so the generator can choose a random position among them. In our example, it chose $$$1$$$.At the $$$3$$$ step, $$$r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]$$$. The maximum value is $$$2$$$ and is reached only at the $$$2$$$ position, so the generator will choose this position.At the $$$4$$$ step, $$$r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]$$$. The maximum value is $$$3$$$ and is reached only at the $$$3$$$ position, so the generator will choose this position.At the $$$5$$$ step, $$$r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]$$$. The maximum value is $$$4$$$ and is reached only at the $$$4$$$ position, so the generator will choose this position.In total, we got a permutation of $$$2, 3, 4, 5, 1$$$, that is, a generator could generate it.

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

void main ()
{
	readln;
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto q = new int [n];
		foreach (i, c; p)
		{
			q[c] = i;
		}
		bool ok = true;
		foreach (i; 1..n)
		{
			ok &= (q[i] == q[i - 1] + 1) || (q[i] < q[i - 1]);
		}
		writeln (ok ? "Yes" : "No");
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        auto P = new int[N];
        foreach (i; 0 .. N) {
          P[i] = readInt() - 1;
        }
        P.reverse;

        bool ans = true;
        for (int i = 0, j; i < N; i = j) {
          j = P[i] + 1;
          foreach (k; i .. j) {
            ans = ans && (P[i] + i == P[k] + k);
          }
          if (!ans) {
            break;
          }
        }
        writeln(ans ? "Yes" : "No");
      }
    }
  } catch (EOFException e) {
  }
}

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

void solve()
{
    auto N = readln.chomp.to!int;
    auto ps = readln.split.to!(int[]);

    auto ii = new size_t[](N);
    foreach (i, ref p; ps) {
        p -= 1;
        ii[p] = i;
    }

    auto bs = new bool[](N);
    size_t i = ii[0];
    int n;
    for (;;)  {
        bs[i] = true;
        ++i;
        ++n;
        if (n == N) break;
        if (i == N || bs[i]) {
            i = ii[n];
            continue;
        }
        if (ps[i] != n) {
            writeln("No");
            return;
        }
    }
    writeln("Yes");
}

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

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

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

alias T = RedBlackTree!(int, "a < b", true);

final class DisjointSet {
  int [] p, h, s;
  int n;
  T t;
  public:
  int bs () {
    if (t.empty) return 0;
    int u = findSet (n - 1);
    int v = t.back;
    if (s[u] == v) {
      t.removeBack ();
      int r = t.empty ? 0 : t.back;
      t.insert (v);
      return r;
    }
    return t.back;
  }
  this (in int _n) {
    n = _n;
    p = iota (0, n).array;
    h = new int[n];
    s = new int[n];
    //s[] = 0;
    t = new T ();
  }
  pure nothrow @nogc
  int findSet (in int x) {
    if (p[x] == x) {
      return x;
    }
    return p[x] = findSet (p[x]);
  }
  bool merge (int i, int j) {
    i = findSet (i);
    j = findSet (j);
    if (i != j) {
      if (s[i] > 0) t.removeKey (s[i]);
      if (s[j] > 0) t.removeKey (s[j]);
      if (h[i] < h[j]) {
        p[i] = j;
        s[j] += s[i];
        t.insert (s[j]);
      } else if (h[i] > h[j]) {
        p[j] = i;
        s[i] += s[j];
        t.insert (s[i]);
      } else {
        p[i] = j;
        s[j] += s[i];
        t.insert (s[j]);
        ++h[j];
      }
      return true;
    }
    return false;
  }
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  bool test () {
    const n = r.next!uint;
    auto a = r.nextA!uint (n);
    a[] -= 1;
    auto rank = new int[n];
    foreach (i; 0 .. n) {
      rank[a[i]] = i;
    }
    auto ds = new DisjointSet (n);
    foreach (i; 0 .. n) {
      int pos = rank[i];
      int t;
      if (pos > 0) {
        int x = ds.findSet (pos - 1);
        t = ds.s[x];
      }
      debug stderr.writefln!("pos = %d, i = %d, t = %d, bs = %d")(pos, i, t, ds.bs());
      if (t != ds.bs ()) {
        return false;
      }
      int u = ds.findSet (pos);
      ds.t.insert(++ds.s[u]);
      if (pos > 0 && a[pos-1] < a[pos]) ds.merge (pos - 1, pos);
      if (pos + 1 < n && a[pos+1] < a[pos]) ds.merge (pos, pos + 1);
    }
    return true;
  }
  foreach (tid; 0 .. nt) {
    writeln (test () ? "Yes" : "No");
  }
}

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

string FMT_F = "%.10f";

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

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

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

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(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 n = RD!int;
		auto p = RDA(-1);

		auto rbt = new RedBlackTree!int;
		foreach (e; p)
			rbt.insert(e);

		auto tmp = new int[](n);
		tmp[] = 1;
		auto heap = heapify(tmp);

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

		bool ok = true;
		auto index = p.MAKE_IDX;
		foreach (_i; index)
		{
			auto i = cast(int)_i;
			auto c = heap.front; heap.removeFront;
			if (cnt[i] != c)
			{
				debug writeln("i:", i);
				debug writeln(cnt);
				ok = false;
				break;
			}
			auto r = rbt.upperBound(i);
			if (!r.empty)
			{
				auto num = r.front;
				cnt[num] += cnt[i];
				heap.insert(cnt[num]);
			}
			cnt[i] = 0;
			rbt.remove(rbt.equalRange(i));
		}
		ans[ti] = ok;
	}

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


Let's denote a $$$k$$$-step ladder as the following structure: exactly $$$k + 2$$$ wooden planks, of which  two planks of length at least $$$k+1$$$ — the base of the ladder;  $$$k$$$ planks of length at least $$$1$$$ — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders $$$1$$$ and $$$3$$$ are correct $$$2$$$-step ladders and ladder $$$2$$$ is a correct $$$1$$$-step ladder. On the first picture the lengths of planks are $$$[3, 3]$$$ for the base and $$$[1]$$$ for the step. On the second picture lengths are $$$[3, 3]$$$ for the base and $$$[2]$$$ for the step. On the third picture lengths are $$$[3, 4]$$$ for the base and $$$[2, 3]$$$ for the steps.   You have $$$n$$$ planks. The length of the $$$i$$$-th planks is $$$a_i$$$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.The question is: what is the maximum number $$$k$$$ such that you can choose some subset of the given planks and assemble a $$$k$$$-step ladder using them?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The queries are independent. Each query consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of planks you have. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the lengths of the corresponding planks. It's guaranteed that the total number of planks from all queries doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per query. The $$$i$$$-th integer is the maximum number $$$k$$$, such that you can choose some subset of the planks given in the $$$i$$$-th query and assemble a $$$k$$$-step ladder using them. Print $$$0$$$ if you can't make even $$$1$$$-step ladder from the given set of planks.

NoteExamples for the queries $$$1-3$$$ are shown at the image in the legend section.The Russian meme to express the quality of the ladders:

import std.algorithm.comparison : min;
import std.algorithm.sorting : sort;
import std.stdio;

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

  foreach (q; 0..t) {
    int n;
    readf!"%d\n"(n);
    auto a = new int[n];
    foreach(i; 0..n) readf!"%d%c"(a[i], c);
    a.sort!"a > b";

    writeln(min(a[1] - 1, n - 2));
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int t = read.to!int;
	foreach(q; 0 .. t){
		int n = read.to!int;
		long[] as;
		foreach(i; 0 .. n) as ~= read.to!long;

		as.sort!"a>b"();
		long ans = min(as[1] - 1, as.length - 2);
		ans.writeln;
	}
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto T = RD!int;
	foreach (i; 0..T)
	{
		auto n = RD!int;
		auto a = RDA;
		a.sort();
		auto len = min(a[$-1], a[$-2]);
		auto ans = min(a.length - 2, len - 1);
		writeln(ans);
	}

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


Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.

The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish.

Print a single integer — the minimum number of times Valera will need to wash a plate/bowl.

NoteIn the first sample Valera will wash a bowl only on the third day, so the answer is one.In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once.In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl.

import std.stdio;

void main() {
    debug stdin = File("input.txt", "r");
    int n, m, k;
    readf(" %s %s %s", &n, &m, &k);

    int[] a = new int[n];
    int ans = 0;
    foreach (i; 0 .. n) {
        int x;
        readf(" %s", &x);

        if (x == 1) {
            if (m == 0) {
                ++ans;
            } else {
                --m;
            }

        } else {
            if (k > 0) {
                --k;
            } else if (m > 0) {
                --m;
            } else
                ++ans;
        }
    }

    writeln(ans);
}

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

int m, k;
int n;
int[] a;
void main() {
    readf("%d %d %d\n", &n, &m, &k);
    int um, uk;
    a = stdin.readln.chop.split(" ").map!(to!int).array;
    foreach (x; a) {
        if (x == 1) {
            um++;
        } else {
            if (uk < k) {
                uk++;
            } else {
                um++;
            }
        }
    }
    writeln(max(um - m, 0) + max(uk - k, 0));
}

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

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                int b = cin.readInt;
                int p = cin.readInt;
                int w = 0;
                for (int i = 0; i < n; i++) {
                        int x = cin.readInt;
                        if (x == 1) {
                                (b == 0) ? w++ : b--;
                        }
                        if (x == 2) {
                                if (b == 0 && p == 0) w++;
                                else if (b == 0 && p > 0) p--;
                                else if (p == 0 && b > 0) b--;
                                else p--;
                        }
                }
                writeln(w);
        }
}

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

void main() {
  auto input = readln.chomp.split.map!(to!int).array;
  auto n = input[0];
  auto m = input[1];
  auto k = input[2];
  auto a = readln.chomp.split.map!(to!int).array;

  foreach (e; a) {
    switch (e) {
    case 1:
      m--;
      break;
    case 2:
      if (k > 0) { k--; } else { m--; }
      break;
    default:
      break;
    }
  }

  auto answer = 0;
  if (m < 0) { answer += -m; }
  if (k < 0) { answer += -k; }

  answer.writeln;
}

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

int m, k;
int n;
int[] a;
void main() {
    readf("%d %d %d\n", &n, &m, &k);
    int um, uk;
    a = stdin.readln.chop.split(" ").map!(to!int).array;
    foreach (x; a) {
        if (x == 1) {
            um++;
        } else {
            if (uk < k) {
                uk++;
            } else {
                um++;
            }
        }
    }
    (uk + um - k - m).writeln;
}


Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 7000$$$) — the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \leq a_i < 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).

Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.

NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.

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

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

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

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

    bool isBetter(long x, long y) {
        return (x & (x ^ y)) > 0;
    }

    auto inleaders = make!(RedBlackTree!long);
    int[] leaders;
    foreach (i; 0 .. n) {
        if (a[i] in inleaders) { continue; }

        bool same = false;
        foreach (j; 0 .. n) {
            if (i == j) { continue; }

            if (a[j] == a[i]) {
                same = true;
            }
        }

        if (same) {
            inleaders.insert(a[i]);
            leaders ~= i;
        }
    }

    auto added = new bool[] (n);
    added[] = false;
    foreach (p; leaders) {
        added[p] = true;
        foreach (j; 0 .. n) {
            if (added[j]) { continue; }

            if (a[j] == a[p] || !isBetter(a[j], a[p])) {
                added[j] = true;
            }
        }
    }

    long ans = 0;
    foreach (i; 0 .. n) {
        if (added[i]) { ans += b[i]; }
    }
    ans.writeln;
}

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

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

void solve(){
	int n = rint;
	long[] as = rlong(n);
	long[] bs = rlong(n);

	X[] xs;
	foreach(i; 0 .. n) xs ~= X(as[i], bs[i]);
	log("xs:", xs);

	int[long] xc;
	foreach(x; xs){
		if(x.a !in xc) xc[x.a] = 0;
		xc[x.a] += 1;
	}
	log("xc:", xc);

	long[] xas = xc.keys;
	long[] topas = [];
	foreach(a; xas) if(xc[a] > 1) topas ~= a;
	log("xas:", xas, "topas:", topas);

	long ans;
	foreach(x; xs){
		foreach(a; topas){
			log("x:", x, "a:", a, "x.a & a:", x.a & a);
			if((x.a & a) == x.a){
				ans += x.b;
				break;
			}
		}
		log("x:", x, "ans:", ans);
	}

	ans.writeln;
}
struct X{
	long a, b;
}

/*
- "Top team": two or more students with same ability.
 (there may be more than one top teams)
- "Sub team" of a top team: students strictly weaker than the top team student

Union of all top teams and their sub teams are the solution.
*/

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

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

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

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

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

      auto sel = new bool[N];
      auto as = A.dup;
      sort(as);
      foreach (k; 0 .. N - 1) {
        if (as[k] == as[k + 1]) {
          foreach (i; 0 .. N) {
            if ((as[k] | A[i]) == as[k]) {
              sel[i] = true;
            }
          }
        }
      }
      long ans;
      foreach (i; 0 .. N) {
        if (sel[i]) {
          ans += B[i];
        }
      }
      writeln(ans);

      debug {
        long brt;
        foreach (h; 0 .. 1 << N) {
          if (popcnt(h) >= 2) {
            bool ok = true;
            foreach (i; 0 .. N) if (h & 1 << i) {
              bool every = true;
              foreach (j; 0 .. N) if (h & 1 << j) {
                if (i != j) {
                  every = every && ((A[i] & ~A[j]) != 0);
                }
              }
              ok = ok && !every;
            }
            if (ok) {
              long sum;
              foreach (i; 0 .. N) if (h & 1 << i) {
                sum += B[i];
              }
              writeln(h, " ", sum);
              chmax(brt, sum);
            }
          }
        }
        assert(brt == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      long ans;
      foreach (i; 0 .. N) {
        bool ok;
        long sum = B[i];
        foreach (j; 0 .. N) {
          if (i != j) {
            if ((A[i] | A[j]) == A[i]) {
              ok = ok || (A[i] == A[j]);
              sum += B[j];
            }
          }
        }
        debug {
          writeln(i, " ", A[i], ": ", ok, " ", sum);
        }
        if (ok) {
          chmax(ans, sum);
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Berland shop sells $$$n$$$ kinds of juices. Each juice has its price $$$c_i$$$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of juices. Each of the next $$$n$$$ lines contains an integer $$$c_i$$$ $$$(1 \le c_i \le 100\,000)$$$ and a string $$$s_i$$$ — the price of the $$$i$$$-th juice and the vitamins it contains. String $$$s_i$$$ contains from $$$1$$$ to $$$3$$$ characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string $$$s_i$$$. The order of letters in strings $$$s_i$$$ is arbitrary.

Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.

NoteIn the first example Petya buys the first, the second and the fourth juice. He spends $$$5 + 6 + 4 = 15$$$ and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is $$$16$$$, which isn't optimal.In the second example Petya can't obtain all three vitamins, as no juice contains vitamin "C".

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

const long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto dp = new long[](1 << 3);
    fill(dp, INF);
    dp[0] = 0;

    foreach (_; 0..N) {
        auto s = readln.split;
        auto c = s[0].to!long;
        auto S = s[1];
        int mask = 0;
        if (S.canFind('A')) mask |= 1;
        if (S.canFind('B')) mask |= (1 << 1);
        if (S.canFind('C')) mask |= (1 << 2);
        foreach (nmask; 0..8) {
            dp[mask | nmask] = min(dp[mask | nmask], dp[nmask] + c);
        }
    }

    writeln( dp[7] == INF ? -1 : dp[7] );
}

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

  int n; rd(n);
  auto mns=new int[](8);
  fill(mns, 1000000000);
  foreach(_; 0..n){
    auto args=readln.split.to!(char[][]);
    int kind=0;
    foreach(c; args[1]){
      kind^=(1<<(c-'A'));
    }
    mns[kind]=min(mns[kind], args[0].to!(int));
  }
  struct T{int kind, price;}
  T[] as, bs, cs;
  foreach(bit; 1..(1<<3)){
    if(mns[bit]==1000000000) continue;
    if(bit&(1<<0)) as~=T(bit, mns[bit]);
    if(bit&(1<<1)) bs~=T(bit, mns[bit]);
    if(bit&(1<<2)) cs~=T(bit, mns[bit]);
  }
  as~=T(0, 0); bs~=T(0, 0); cs~=T(0, 0);
  int mincost=1000000000;
  foreach(a; as){
    foreach(b; bs){
      foreach(c; cs){
        int bit=a.kind|b.kind|c.kind;
        if(bit==((1<<3)-1)){
          mincost=min(mincost, a.price+b.price+c.price);
        }
      }
    }
  }
  if(mincost<1000000000){
    writeln(mincost);
  }else{
    writeln(-1);
  }

}

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


Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence $$$s$$$ is called correct if:   $$$s$$$ is empty;  $$$s$$$ is equal to "($$$t$$$)", where $$$t$$$ is correct bracket sequence;  $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.

First of line of input contains a single number $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — length of the sequence which Petya received for his birthday. Second line of the input contains bracket sequence of length $$$n$$$, containing symbols "(" and ")".

Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No".

NoteIn the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence.In the second example, there is no way to move at most one bracket so that the sequence becomes correct.In the third example, the sequence is already correct and there's no need to move brackets.

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

void main() {
    int n;
    string s;
    readf!" %s %s"(n,s);
    s = s.strip;

    int a = 0;
    int mn = 0;
    foreach (c; s) {
        if (c == '(') a++;
        else a--;
        mn = min(mn, a);
    }

    if (a == 0 && mn >= -1) {
        writeln("Yes");
    } else {
        writeln("No");
    }
}

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

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

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

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

int N;
string S;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      S = readToken();

      auto as = new int[N + 1];
      auto ls = new int[N + 1];
      auto rs = new int[N + 1];
      foreach (i; 0 .. N) {
        as[i + 1] = as[i] + ((S[i] == '(') ? +1 : -1);
      }
      foreach (i; 0 .. N) {
        ls[i + 1] = min(ls[i], as[i + 1]);
      }
      foreach_reverse (i; 0 .. N) {
        rs[i] = min(rs[i + 1], as[i]);
      }

      bool ans;
      if (as[N] == 0) {
        debug {
          writeln("as = ", as);
          writeln("ls = ", ls);
          writeln("rs = ", rs);
        }
        ans = false;
        foreach (i; 0 .. N) {
          if (S[i] == '(') {
            if (1 + ls[i] >= 0 && rs[i + 1] >= 0) {
              ans = true;
            }
          } else {
            if (ls[i] >= 0 && 1 + rs[i + 1] >= 0) {
              ans = true;
            }
          }
        }
      } else {
        ans = false;
      }
      writeln(ans ? "Yes" : "No");
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n = RD!int;
	auto s = RD!string;
	long cnt;
	bool ans = true;
	foreach (i; 0..n)
	{
		if (s[i] == '(')
			++cnt;
		else
			--cnt;

		if (cnt < -1)
		{
			ans = false;
			break;
		}
	}

	writeln(ans && cnt == 0 ? "Yes" : "No");
	stdout.flush();
	debug readln();
}


Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or  - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di =  - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.

The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected.

Print  - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1.

NoteIn the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.

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

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

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

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

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

int[][] G;
int[] pari;
int[] us;

void dfs(int u, int pi) {
  pari[u] = pi;
  us ~= u;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (pari[v] == -1) {
      dfs(v, i);
    }
  }
}

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

      G = new int[][N];
      foreach (i; 0 .. M) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      pari = new int[N];
      pari[] = -1;

      auto ds = D.dup;

      bool ans = true;
      int[] edges;
      foreach (r; 0 .. N) {
        if (pari[r] == -1) {
          us = [];
          dfs(r, -2);
          debug {
            writeln("us = ", us);
          }
          const usLen = cast(int)(us.length);
          int sum;
          int[] js;
          foreach (j; 0 .. usLen) {
            if (ds[us[j]] == -1) {
              ds[us[j]] = 0;
              js ~= j;
            } else {
              sum ^= ds[us[j]];
            }
          }
          if (sum) {
            if (js.empty) {
              ans = false;
              break;
            } else {
              ds[us[js[0]]] = 1;
            }
          }
          foreach_reverse (j; 0 .. usLen) {
            if (ds[us[j]]) {
              const i = pari[us[j]];
              const p = A[i] ^ B[i] ^ us[j];
              edges ~= i;
              ds[p] ^= 1;
            }
          }
        }
      }

      if (ans) {
        edges.sort;
        writeln(edges.length);
        foreach (i; edges) {
          writeln(i + 1);
        }
      } else {
        writeln(-1);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

int[][] G;
int[] pari;
int[] us;

void dfs(int u, int pi) {
  pari[u] = pi;
  us ~= u;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (pari[v] == -1) {
      dfs(v, i);
    }
  }
}

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

      G = new int[][N];
      foreach (i; 0 .. M) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      pari = new int[N];
      pari[] = -1;

      auto ds = D.dup;

      bool ans = true;
      int[] edges;
      foreach (r; 0 .. N) {
        if (pari[r] == -1) {
          us = [];
          dfs(r, -2);
          debug {
            writeln("us = ", us);
          }
          const usLen = cast(int)(us.length);
          int sum;
          int[] js;
          foreach (j; 0 .. usLen) {
            if (ds[us[j]] == -1) {
              ds[us[j]] = 0;
              js ~= j;
            } else {
              sum ^= ds[us[j]];
            }
          }
          if (sum) {
            if (js.empty) {
              ans = false;
              break;
            } else {
              ds[js[0]] = 1;
            }
          }
          foreach_reverse (j; 0 .. usLen) {
            if (ds[us[j]]) {
              const i = pari[us[j]];
              const p = A[i] ^ B[i] ^ us[j];
              edges ~= i;
              ds[p] ^= 1;
            }
          }
        }
      }

      if (ans) {
        edges.sort;
        writeln(edges.length);
        foreach (i; edges) {
          writeln(i + 1);
        }
      } else {
        writeln(-1);
      }
    }
  } catch (EOFException e) {
  }
}


You are given two strings $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. Also you have a string $$$z$$$ which is initially empty. You want string $$$z$$$ to be equal to string $$$t$$$. You can perform the following operation to achieve this: append any subsequence of $$$s$$$ at the end of string $$$z$$$. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if $$$z = ac$$$, $$$s = abcde$$$, you may turn $$$z$$$ into following strings in one operation:   $$$z = acace$$$ (if we choose subsequence $$$ace$$$);  $$$z = acbcd$$$ (if we choose subsequence $$$bcd$$$);  $$$z = acbce$$$ (if we choose subsequence $$$bce$$$). Note that after this operation string $$$s$$$ doesn't change.Calculate the minimum number of such operations to turn string $$$z$$$ into string $$$t$$$.

The first line contains the integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. The first line of each testcase contains one string $$$s$$$ ($$$1 \le |s| \le 10^5$$$) consisting of lowercase Latin letters. The second line of each testcase contains one string $$$t$$$ ($$$1 \le |t| \le 10^5$$$) consisting of lowercase Latin letters. It is guaranteed that the total length of all strings $$$s$$$ and $$$t$$$ in the input does not exceed $$$2 \cdot 10^5$$$.

For each testcase, print one integer — the minimum number of operations to turn string $$$z$$$ into string $$$t$$$. If it's impossible print $$$-1$$$.

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

int test () {
  auto s = readln.strip;
  auto t = readln.strip;
  immutable l = s.length.to!int;
  auto next = new int[26][l+1];
  next[l][] = l;
  foreach_reverse (i; 0 .. l) {
    next[i][] = next[i+1][];
    immutable k = s[i].to!int - 97;
    next[i][k] = i;
  }
  foreach (c; t) {
    immutable k = c.to!int - 97;
    if (next[0][k] >= l) return -1;
  }
  int i, res;
  foreach (c; t) {
    immutable k = c.to!int - 97;
    while (true) {
      i = next[i][k];
      if (i >= l) {
        ++res;
        i = 0;
      } else {
        break;
      }
    }
    ++i;
  }
  res++;
  return res;
}

void main() {
  immutable nt = readln.strip.to!int;
  foreach (tid; 0 .. nt) {
    writeln (test ());
  }
}

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

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 T = RD!int;
	auto ans = new int[](T);
	foreach (ti; 0..T)
	{
		auto s = RD!string;
		auto t = RD!string;
		auto arr = new int[][](26);
		foreach (i; 0..s.length)
		{
			arr[s[i]-'a'] ~= cast(int)i;
		}

		ans[ti] = 1;
		int pos = -1;
		foreach (i; 0..t.length)
		{
			auto c = t[i]-'a';
			bool f(int x)
			{
				return arr[c][x] > pos;
			}
			auto r = binarySearch!(f)(cast(int)arr[c].length, -1);
			if (r == arr[c].length)
			{
				++ans[ti];
				pos = -1;
				r = binarySearch!(f)(cast(int)arr[c].length, -1);
				if (r == arr[c].length)
				{
					ans[ti] = -1;
					break;
				}
			}
			pos = arr[c][r];
			debug writeln("pos:", pos);
		}
	}

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


The company "Divan's Sofas" is planning to build $$$n + 1$$$ different buildings on a coordinate line so that:   the coordinate of each building is an integer number;  no two buildings stand at the same point. Let $$$x_i$$$ be the coordinate of the $$$i$$$-th building. To get from the building $$$i$$$ to the building $$$j$$$, Divan spends $$$|x_i - x_j|$$$ minutes, where $$$|y|$$$ is the absolute value of $$$y$$$.All buildings that Divan is going to build can be numbered from $$$0$$$ to $$$n$$$. The businessman will live in the building $$$0$$$, the new headquarters of "Divan's Sofas". In the first ten years after construction Divan will visit the $$$i$$$-th building $$$a_i$$$ times, each time spending $$$2 \cdot |x_0-x_i|$$$ minutes for walking.Divan asks you to choose the coordinates for all $$$n + 1$$$ buildings so that over the next ten years the businessman will spend as little time for walking as possible.

Each test contains several test cases. The first line contains one integer number $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The first line of each case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of buildings that "Divan's Sofas" is going to build, apart from the headquarters. The second line contains the sequence $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$), where $$$a_i$$$ is the number of visits to the $$$i$$$-th building. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, on the first line print the number $$$T$$$ — the minimum time Divan will spend walking.  On the second line print the sequence $$$x_0, x_1, \ldots, x_n$$$ of $$$n + 1$$$ integers, where $$$x_i$$$ ($$$-10^6 \le x_i \le 10^6$$$) is the selected coordinate of the $$$i$$$-th building. It can be shown that an optimal answer exists with coordinates not exceeding $$$10^6$$$. If there are multiple answers, print any of them.

NoteLet's look at the first example.Divan will visit the first building $$$a_1 = 1$$$ times, the second $$$a_2 = 2$$$ times and the third $$$a_3 = 3$$$ times. Then one of the optimal solution will be as follows:   the headquarters is located in $$$x_0 = 2$$$;  $$$x_1 = 4$$$: Divan will spend $$$2 \cdot |x_0-x_1| \cdot a_1 = 2 \cdot |2-4| \cdot 1 = 4$$$ minutes walking to the first building;  $$$x_2 = 1$$$: Divan will spend $$$2 \cdot |x_0-x_2| \cdot a_2 = 2 \cdot |2-1| \cdot 2 = 4$$$ minutes walking to the second building;  $$$x_3 = 3$$$: Divan will spend $$$2 \cdot |x_0-x_3| \cdot a_3 = 2 \cdot |2-3| \cdot 3 = 6$$$ minutes walking to the third building. In total, Divan will spend $$$4 + 4 + 6 = 14$$$ minutes. It can be shown that it is impossible to arrange buildings so that the businessman spends less time.Among others, $$$x = [1, 3, 2, 0]$$$, $$$x = [-5, -3, -6, -4]$$$ are also correct answers for the first example.

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

void solve(){
    int n  = scan!int;
    auto arr = scanArray;
    tup[] zipp;
    for(int i = 0; i < n; ++i){
        zipp ~= tup(arr[i], i);
    }
    zipp.sort;
    ll sol = 0;
    auto res = new ll[](n);
    long cnt = 1;
    for(int i = n-1; i >= 0; i -= 2){
        res[zipp[i][1]] = cnt;
        sol += cnt * zipp[i][0];
        ++cnt;
    }
    cnt = -1;
    for(int i = n-2; i >= 0; i -= 2){
        res[zipp[i][1]] = cnt;
        sol += (- cnt) * zipp[i][0];
        --cnt;
    }
    writeln(2*sol);
    write(0, " ");
    res.each!((a) => write(a, " "));
    writeln;
}

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;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  int, "y");

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	auto viA = new int[2][](n);
	foreach(i, ai; a) viA[i] = [ai, cast(int)i];
	sort!((a, b) => a > b)(viA);
	long minTime = 0;
	long currentX = 1;
	void pop()
	{
		if (currentX > 0) currentX = -currentX;
		else currentX = -currentX + 1;
	}
	auto xs = new long[](n);
	foreach(viAi; viA)
	{
		auto value = viAi[0];
		auto index = viAi[1];
		minTime += 2 * abs(currentX * value);
		xs[index] = currentX;
		pop;
	}
	writeln(minTime);
	write("0 ");
	foreach(x; xs) write(x, " ");
	writeln;
}

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

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

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

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

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

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]]; }
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 ans1 = new long[](t);
	auto ans2 = new long[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;

		ans2[ti].length = n+1;
		auto index = a.MAKE_IDX!"a > b";
		foreach (ii, i; index)
		{
			auto cnt = ii / 2 + 1;
			ans1[ti] += cnt * a[i] * 2;
			ans2[ti][i+1] = cnt;
			if (ii % 2)
				ans2[ti][i+1] *= -1;
		}
	}

	foreach (ti; 0..t)
	{
		writeln(ans1[ti]);
		ans2[ti].map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}


Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner.Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t.On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that.The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct:  n < m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"),  p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≤ k ≤ min(n, m)), here characters in strings are numbered starting from 1. Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum.

The first line contains a non-empty string s (1 ≤ |s| ≤ 5000), where |s| is its length. The second line contains a non-empty string t (1 ≤ |t| ≤ 5000), where |t| is its length. Both strings consist of lowercase Latin letters.

Print the sought name or -1 if it doesn't exist.

NoteIn the first sample the given string s is the sought one, consequently, we do not need to change the letter order there.

import std.stdio;

void main() {
    auto s = readln()[0 .. $ - 1];//Strip trailing '\n'.
    auto t = readln()[0 .. $ - 1];
    int[26] m;
    foreach (c; s)
        m[c - 'a']++;

    void writeRest() {
        foreach (i, cnt; m)
            foreach (j; 0 .. cnt)
                write(cast(char)(i + 'a'));
        writeln();
    }

    int i = 0;
    foreach (c; t) {
        if (!m[c - 'a'])
            break;
        m[c - 'a']--;
        i++;
    }

    if (i == t.length && s.length > i) {
        write(t);
        writeRest();
    } else {
        if (i == t.length)
            m[t[--i] - 'a']++;
        for (; i >= 0; ) {
            debug writeln(m);
            foreach (j; t[i] - 'a' + 1 .. 26)
                if (m[j]) {
                    write(t[0 .. i]);
                    write(cast(char)(j + 'a'));
                    m[j]--;
                    writeRest();
                    return;
                }
            if (i--)
                m[t[i] - 'a']++;
        }
        writeln("-1");
    }
}

import std.stdio;

void main() {
    auto s = readln()[0 .. $ - 1];//Strip trailing '\n'.
    auto t = readln()[0 .. $ - 1];
    int[26] m;
    foreach (c; s)
        m[c - 'a']++;

    void writeRest() {
        foreach (i, cnt; m)
            foreach (j; 0 .. cnt)
                write(cast(char)(i + 'a'));
        writeln();
    }

    int i = 0;
    foreach (c; t) {
        if (!m[c - 'a'])
            break;
        m[c - 'a']--;
        i++;
    }

    if (i == t.length) {
        if (s.length > i) {
            write(t);
            writeRest();
            return;
        }
        m[t[--i] - 'a']++;
    }
    while (i >= 0) {
        debug writeln(m);
        foreach (j; t[i] - 'a' + 1 .. 26)
            if (m[j]) {
                write(t[0 .. i]);
                write(cast(char)(j + 'a'));
                m[j]--;
                writeRest();
                return;
            }
        if (i--)
            m[t[i] - 'a']++;
    }
    writeln("-1");
}

import std.stdio;

void main() {
    auto s = readln()[0 .. $ - 1];//Strip trailing '\n'.
    auto t = readln()[0 .. $ - 1];
    int[26] m;
    foreach (c; s)
        m[c - 'a']++;
    int i = 0;
    foreach (c; t[0 .. $ - 1]) {
        if (!m[c - 'a'])
            break;
        m[c - 'a']--;
        i++;
    }
    for (; i >= 0; i--) {
        foreach (j; t[i] - 'a' + 1 .. 26)
            if (m[j]) {
                write(t[0 .. i]);
                write(cast(char)(j + 'a'));
                m[j]--;
                foreach (c, cnt; m)
                    foreach (k; 0 .. cnt)
                        write(cast(char)(c + 'a'));
                writeln();
                return;
            }
        m[s[i] - 'a']++;
    }
    writeln("-1");
}


You are given a tree (a connected acyclic undirected graph) of n vertices. Vertices are numbered from 1 to n and each vertex is assigned a character from a to t.A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome.For each vertex, output the number of palindromic paths passing through it. Note: The path from vertex u to vertex v is considered to be the same as the path from vertex v to vertex u, and this path will be counted only once for each of the vertices it passes through.

The first line contains an integer n (2 ≤ n ≤ 2·105)  — the number of vertices in the tree. The next n - 1 lines each contain two integers u and v (1  ≤  u, v  ≤  n, u ≠ v) denoting an edge connecting vertex u and vertex v. It is guaranteed that the given graph is a tree. The next line contains a string consisting of n lowercase characters from a to t where the i-th (1 ≤ i ≤ n) character is the label of vertex i in the tree.

Print n integers in a single line, the i-th of which is the number of palindromic paths passing through vertex i in the tree.

NoteIn the first sample case, the following paths are palindromic:2 - 3 - 42 - 3 - 54 - 3 - 5Additionally, all paths containing only one vertex are palindromic. Listed below are a few paths in the first sample that are not palindromic:1 - 2 - 31 - 2 - 3 - 41 - 2 - 3 - 5

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

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

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

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

enum K = 20;

int N;
int[] A, B;
string C;

int[][] G;
long[] ans;

void solveCentroidDecomp() {
  auto sz = new int[N];
  auto del = new bool[N];
  void dfsSz(int u, int p) {
    sz[u] = 1;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (v != p) {
        dfsSz(v, u);
        sz[u] += sz[v];
      }
    }
  }
  dfsSz(0, -1);

  auto par = new int[N];
  auto dp = new long[N];
  auto freq = new int[1 << K];

  // r: centroid
  void solveSubtree(int r) {
    debug {
      string dfsDebug(int u, int p) {
        string ret = u.to!string;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v] && v != p) {
            ret ~= "(" ~ dfsDebug(v, u) ~ ")";
          }
        }
        return ret;
      }
      writeln("solveSubtree ", dfsDebug(r, -1));
    }
    //
    const deg = cast(int)(G[r].length);
    alias Entry = Tuple!(int, "u", int, "d");
    auto ess = new Entry[][deg];
    const dR = 1 << (C[r] - 'a');
    //
    void dfs(int j, int u, int p, int d) {
      //
      d ^= 1 << (C[u] - 'a');
      ess[j] ~= Entry(u, d);
      par[u] = p;
      //
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs(j, v, u, d);
        }
      }
    }
    foreach (j; 0 .. deg) {
      const i = G[r][j];
      const v = A[i] ^ B[i] ^ r;
      if (!del[v]) {
        dfs(j, v, r, dR);
      }
    }
    dp[r] = 0;
    foreach (j; 0 .. deg) foreach (ref e; ess[j]) ++freq[e.d];
    foreach (j; 0 .. deg) {
      foreach (ref e; ess[j]) --freq[e.d];
      foreach (ref e; ess[j]) {
        dp[e.u] = 0;
        if (!(e.d & e.d - 1)) {
          // u-r
          dp[e.u] += 1;
          dp[r] += 1;
        }
        // u-v
        dp[e.u] += freq[e.d ^ dR];
        foreach (k; 0 .. K) {
          dp[e.u] += freq[e.d ^ dR ^ 1 << k];
        }
      }
      foreach (ref e; ess[j]) ++freq[e.d];
    }
    foreach (j; 0 .. deg) foreach (ref e; ess[j]) --freq[e.d];
    // r-r
    dp[r] += 1;
    dp[r] += 1;
    foreach (j; 0 .. deg) {
      foreach_reverse (ref e; ess[j]) {
        ans[e.u] += dp[e.u];
        dp[par[e.u]] += dp[e.u];
      }
    }
    ans[r] += dp[r] / 2;
  }

  void solveRec(int u) {
    for (; ; ) {
      int vm = -1;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v]) {
          if (vm == -1 || sz[vm] < sz[v]) {
            vm = v;
          }
        }
      }
      if (vm == -1 || sz[u] >= 2 * sz[vm]) {
        solveSubtree(u);
        del[u] = true;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            solveRec(v);
          }
        }
        break;
      } else {
        sz[u] -= sz[vm];
        sz[vm] += sz[u];
        u = vm;
      }
    }
  }
  solveRec(0);
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      ans = new long[N];
      solveCentroidDecomp();
      foreach (u; 0 .. N) {
        if (u > 0) write(" ");
        write(ans[u]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum K = 20;

int N;
int[] A, B;
string C;

int[][] G;
long[] ans;

void solveCentroidDecomp() {
  auto sz = new int[N];
  auto del = new bool[N];
  void dfsSz(int u, int p) {
    sz[u] = 1;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (v != p) {
        dfsSz(v, u);
        sz[u] += sz[v];
      }
    }
  }
  dfsSz(0, -1);

  auto par = new int[N];
  auto dp = new long[N];

  // r: centroid
  void solveSubtree(int r) {
    debug {
      string dfsDebug(int u, int p) {
        string ret = u.to!string;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v] && v != p) {
            ret ~= "(" ~ dfsDebug(v, u) ~ ")";
          }
        }
        return ret;
      }
      writeln("solveSubtree ", dfsDebug(r, -1));
    }
    //
    const deg = cast(int)(G[r].length);
    int[] us;
    long[int] freqAll;
    auto freqs = new long[int][deg];
    long get(int j, int key) {
      long ret;
      if (key in freqAll) ret += freqAll[key];
      if (key in freqs[j]) ret -= freqs[j][key];
      return ret;
    }
    const dR = 1 << (C[r] - 'a');
    //
    void dfs0(int j, int u, int p, int d) {
      //
      d ^= 1 << (C[u] - 'a');
      us ~= u;
      par[u] = p;
      freqAll[d] += 1;
      freqs[j][d] += 1;
      //
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs0(j, v, u, d);
        }
      }
    }
    void dfs1(int j, int u, int p, int d) {
      //
      d ^= 1 << (C[u] - 'a');
      if (!(d & d - 1)) {
        // u-r
        dp[u] += 1;
        dp[r] += 1;
      }
      // u-v
      dp[u] += get(j, d ^ dR);
      foreach (k; 0 .. K) {
        dp[u] += get(j, d ^ dR ^ 1 << k);
      }
      //
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs1(j, v, u, d);
        }
      }
    }
    foreach (j; 0 .. deg) {
      const i = G[r][j];
      const v = A[i] ^ B[i] ^ r;
      if (!del[v]) {
        dfs0(j, v, r, dR);
      }
    }
    par[r] = -1;
    debug {
      writeln("  us = ", us);
    }
    foreach (u; us) {
      dp[u] = 0;
    }
    dp[r] = 0;
    foreach (j; 0 .. deg) {
      const i = G[r][j];
      const v = A[i] ^ B[i] ^ r;
      if (!del[v]) {
        dfs1(j, v, r, dR);
      }
    }
    // r-r
    dp[r] += 1;
    dp[r] += 1;

    foreach_reverse (u; us) {
      dp[par[u]] += dp[u];
    }
    foreach (u; us) {
      ans[u] += dp[u];
    }
    ans[r] += dp[r] / 2;
  }

  void solveRec(int u) {
writeln("solveRec ",u);
    for (; ; ) {
      int vm = -1;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v]) {
          if (vm == -1 || sz[vm] < sz[v]) {
            vm = v;
          }
        }
      }
      if (vm == -1 || sz[u] >= 2 * sz[vm]) {
        solveSubtree(u);
        del[u] = true;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            solveRec(v);
          }
        }
        break;
      } else {
        sz[u] -= sz[vm];
        sz[vm] += sz[u];
        u = vm;
      }
    }
  }
  solveRec(0);
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      ans = new long[N];
      solveCentroidDecomp();
      foreach (u; 0 .. N) {
        if (u > 0) write(" ");
        write(ans[u]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


Nezzar's favorite digit among $$$1,\ldots,9$$$ is $$$d$$$. He calls a positive integer lucky if $$$d$$$ occurs at least once in its decimal representation. Given $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$, for each $$$1 \le i \le q$$$ Nezzar would like to know if $$$a_i$$$ can be equal to a sum of several (one or more) lucky numbers.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 9$$$) — the number of test cases. The first line of each test case contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q \le 10^4$$$, $$$1 \le d \le 9$$$). The second line of each test case contains $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$ ($$$1 \le a_i \le 10^9$$$).

For each integer in each test case, print "YES" in a single line if $$$a_i$$$ can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower).

YES
NO
YES
YES
YES
NO
YES
YES
YES
YES
YES
YES
NO

NoteIn the first test case, $$$24 = 17 + 7$$$, $$$27$$$ itself is a lucky number, $$$25$$$ cannot be equal to a sum of lucky numbers.

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

void theCode(){
    int q;
    q = scan!int;
    ll d = scan;
    bool[100] check;
    for(int el = 1; el < 100; ++el){
        if(el % d == 0){
            check[el] = 1; continue;
        }
        ll tim = 1;
        ll num = el;
        while(num > 0){
            num /= tim;
            ll dig = num % 10;
            if(dig == d){
                check[el] = 1;
                break;
            }
            tim *= 10;
        }
        if(check[el]){
            for(int i = el; i < 100; i += d){
                check[i] = 1;
            }
        }
    }
    auto arr = scanArray;
    foreach(el; arr){
        bool f = 0;
        for(ll i = 1; i < 100; ++i){
            if(el < i){ break; }
            if(el % d == i % d){
                f |= check[to!int(i)];
            }
        }
        if(f){
            writeln("YES");
        }else{
            writeln("NO");
        }
    }
}

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

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

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        int _Q, D; get(_Q, D);
        int[] dd;
        foreach (i; 0..10) dd ~= [i * 10 + D, D * 10 + i];
        sort(dd);
        auto DP = new int[](100);
        DP[0] = 1;
        foreach (i; 0..100) if (DP[i] == 0) {
            int solve(int i) {
                if (DP[i] != 0) return DP[i];
                foreach (d; dd) {
                    if (i - d < 0) break;
                    if (solve(i - d) == 1) return DP[i] = 1;
                }
                return DP[i] = -1;
            }
            solve(i);
        }
        foreach (Q; readln.split.to!(int[])) {
            if (Q >= 100) goto ok;
            if (DP[Q] == 1) goto ok;
            writeln("NO");
            continue;
            ok:
            writeln("YES");
        }
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int q, d;
		readf !(" %s %s") (q, d);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		immutable int limit = 100;
		auto f = new bool [limit];
		f[0] = true;
		f[d * 10..$] = true;
		foreach (x; 0..10)
		{
			auto y = x * 10 + d;
			foreach (z; y..limit)
			{
				f[z] |= f[z - y];
			}
		}
		foreach (ref c; a)
		{
			writeln ((c >= limit || f[c]) ? "YES" : "NO");
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (e; a)
		{
			if (e >= d*10 || e % d == 0)
			{
				ans[ti] ~= true;
			}
			else
			{
				auto cnt = e / d;
				bool ok;
				foreach (i; 0..cnt)
				{
					auto x = e - i * d;
					if ((x % 10) == d)
					{
						ok = true;
						break;
					}
				}
				ans[ti] ~= ok;
			}
		}
	}

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

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

void theCode(){
    int q;
    q = scan!int;
    ll d = scan;
    ll[] arr;
    for(int i = 0; i <= d; ++i){
        ll fnum = i*10 +  d;
        if(fnum % d != 0){
            for(int j = 0; j < 14; ++j){
                arr ~= j*d + fnum;
            }
        }
    }
    arr.sort;
    auto seeq = scanArray;
    foreach(el; seeq){
        show(el);
        bool f = 0;
        if(el % d == 0){
            writeln("YES");
            f = 1;
        }
        if(!f){
            foreach(a; arr){
                if(el < a){ break; }
                if(el % d == a % d){
                    writeln("YES");
                    f = 1;
                    break;
                }
            }
        }
        if(!f){
            ll tim = 1;
            ll num = el;
            while(num > 0){
                num /= tim;
                ll dig = num % 10;
                if(dig == d){
                    writeln("YES");
                    f = 1;
                    break;
                }
                tim *= 10;
            }
        }
        if(!f){
            writeln("NO");
        }
    }
}

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

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

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

void theCode(){
    int q;
    q = scan!int;
    ll d = scan;
    auto arr = iota(0L, 10L).map!(a => (10*a + d) % d).array;
    show(arr);
    auto seeq = scanArray;
    foreach(el; seeq){
        show(el);
        bool f = 0;
        for(int i = 0; i <= d; ++i){
            if(el < 10*i + arr[i]){ break; }
            if(el % d == arr[i]){
                writeln("YES");
                f = 1;
                break;
            }
        }
        if(!f){
            ll tim = 1;
            ll num = el;
            while(num > 0){
                num /= tim;
                ll dig = num % 10;
                if(dig == d){
                    writeln("YES");
                    f = 1;
                    break;
                }
                tim *= 10;
            }
        }
        if(!f){
            writeln("NO");
        }
    }
}

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

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

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        int _Q, D; get(_Q, D);
        foreach (Q; readln.split.to!(int[])) {
            if (Q >= 100) goto ok;
            foreach (i; 1..10) if (Q >= D * i && (Q - D * i) % 10 == 0) goto ok;
            if (Q / 10 >= D && Q % 10 >= D) goto ok;
            writeln("NO");
            continue;
            ok:
            writeln("YES");
        }
    }
}