You have an array $$$a$$$ of length $$$n$$$. For every positive integer $$$x$$$ you are going to perform the following operation during the $$$x$$$-th second:  Select some distinct indices $$$i_{1}, i_{2}, \ldots, i_{k}$$$ which are between $$$1$$$ and $$$n$$$ inclusive, and add $$$2^{x-1}$$$ to each corresponding position of $$$a$$$. Formally, $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ for $$$j = 1, 2, \ldots, k$$$. Note that you are allowed to not select any indices at all. You have to make $$$a$$$ nondecreasing as fast as possible. Find the smallest number $$$T$$$ such that you can make the array nondecreasing after at most $$$T$$$ seconds.Array $$$a$$$ is nondecreasing if and only if $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.You have to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).

For each test case, print the minimum number of seconds in which you can make $$$a$$$ nondecreasing.

NoteIn the first test case, if you select indices $$$3, 4$$$ at the $$$1$$$-st second and $$$4$$$ at the $$$2$$$-nd second, then $$$a$$$ will become $$$[1, 7, 7, 8]$$$. There are some other possible ways to make $$$a$$$ nondecreasing in $$$2$$$ seconds, but you can't do it faster.In the second test case, $$$a$$$ is already nondecreasing, so answer is $$$0$$$.In the third test case, if you do nothing at first $$$2$$$ seconds and select index $$$2$$$ at the $$$3$$$-rd second, $$$a$$$ will become $$$[0, 0]$$$.

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto a0 = a.front;
		a[] -= a0;
		int res = 0;
		int prev = 0;
		foreach (ref c; a)
		{
			res = max (res, prev - c);
			prev = max (prev, c);
		}
		res = (res == 0) ? 0 : bsr (res) + 1;
		writeln (res);
	}
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    A: foreach(_; 0 .. scan!int){
        int n = scan!int;
        long[] as = scan!long(n);

        long t = as[0];
        long maxg = 0;
        foreach(a; as){
            if(a < t) maxg.raiseTo(t - a);
            else t = a;
        }
        if(maxg == 0) "0".writeln;
        else foreach(i; 0 .. 60){
            if((1L<<i) <= maxg) continue;
            i.writeln;
            continue A;
        }
    }
}

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 A = new long[N];
        foreach (i; 0 .. N) {
          A[i] = readLong();
        }

        long mx;
        long now = long.min;
        foreach (i; 0 .. N) {
          chmax(now, A[i]);
          chmax(mx, now - A[i]);
        }
        debug {
          writeln("mx = ", mx);
        }
        for (int e = 0; ; ++e) {
          if (mx < 2L^^e) {
            writeln(e);
            break;
          }
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n;
  @Dim("n") long[] a;

  void solve(long tc = -1)
  {
    long maxdiff = long.min;
    long bar = long.min;
    foreach(ai; a)
      {
        bar = max(bar, ai);
        maxdiff = max(maxdiff, bar - ai);
      }
    long bits = 0;
    while(maxdiff)
      {
        maxdiff /= 2;
        bits++;
      }
    writeln(bits);
  }
}

struct Interval
{
  long l, h;

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

void main()
{
    auto T = readln.chomp.to!int;
    long[63] ns, cs;
    foreach (i; 0..63) ns[i] = (1L<<(i+1))-1;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;
        auto as = readln.split.to!(long[]);
        cs[] = 0;
        foreach (i; 0..N-1) {
            if (as[i+1] >= as[i]) continue;
            foreach (j, n; ns) if (as[i] - as[i+1] <= n) {
                ++cs[j];
                as[i+1] = as[i];
                break;
            }
        }
        foreach_reverse (i, c; cs) if (c > 0) {
            writeln(i+1);
            goto ok;
        }
        writeln(0);
        ok:
    }
}

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

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

int test (const int n, const long[] a) {
  if (isSorted (a)) return 0;
  long d = 1;
  long x = 0;
  long lastD;
  long maxD;
  foreach (i; 1 .. n) {
    long t = max (0L, (a[i-1] + lastD) - a[i]);
    maxD = max (maxD, t);
    lastD = t;
  }
  debug stderr.writeln ("maxD = ", maxD);
  foreach (l; 1 .. 50) {
    x += d;
    if (x >= maxD) return l;
    d *= 2;
  }
  return -1;
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint;
    auto a = r.nextA!long(n);
    writeln (test (n, a));
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long m = a[0];
		long x;
		foreach (i; 0..n)
		{
			auto d = m - a[i];
			if (d > 0)
			{
				foreach (j; 0..32)
				{
					auto bit = 1L << j;
					if (d & bit)
					{
						x.chmax(j+1);
					}
				}
			}
			m.chmax(a[i]);
		}
		ans[ti] = x;
	}

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

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(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    A: foreach(_; 0 .. scan!int){
        int n = scan!int;
        long[] as = scan!long(n);

        long t = as[0];
        long maxg = 0;
        foreach(a; as){
            if(a < t) maxg.raiseTo(t - a);
            else t = a;
        }
        if(maxg == 0) "0".writeln;
        else foreach(i; 0 .. 30){
            if((1L<<i) <= maxg) continue;
            i.writeln;
            continue A;
        }
    }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    long[32] ns, cs;
    foreach (i; 0..32) ns[i] = 1L<<i;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;
        auto as = readln.split.to!(long[]);
        cs[] = 0;
        foreach (i; 0..N-1) {
            foreach (j, n; ns) if (as[i] - as[i+1] > 0) {
                ++cs[j];
                as[i+1] += n;
            }
        }
        foreach_reverse (i, c; cs) if (c > 0) {
            writeln(i+1);
            goto ok;
        }
        writeln(0);
        ok:
    }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    long[32] ns, cs;
    foreach (i; 0..32) ns[i] = (1L<<(i+1))-1;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;
        auto as = readln.split.to!(long[]);
        cs[] = 0;
        long cnt;
        foreach (i; 0..N-1) {
            if (as[i] - as[i+1] <= 0) continue;
            foreach (j, n; ns) if (n >= as[i] - as[i+1]) {
                ++cs[j];
                ++cnt;
                break;
            }
        }
        if (cnt == 0) {
            writeln(0);
            continue;
        }
        long rest, res;
        foreach (i, c; cs) {
            rest += c;
            cnt -= c;
            if (rest) rest -= 1;
            res += 1;
            if (cnt == 0) break;
        }
        writeln(res + rest);
    }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    long[32] ns, cs;
    foreach (i; 0..32) ns[i] = (1L<<(i+1))-1;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;
        auto as = readln.split.to!(long[]);
        cs[] = 0;
        long cnt;
        foreach (i; 0..N-1) {
            if (as[i] - as[i+1] <= 0) continue;
            foreach (j, n; ns) if (n >= as[i] - as[i+1]) {
                ++cs[j];
                as[i+1] += n;
                ++cnt;
                break;
            }
        }
        if (cnt == 0) {
            writeln(0);
            continue;
        }
        foreach_reverse (i, c; cs) if (c > 0) {
            writeln(i+1);
            break;
        }
    }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    long[32] ns, cs;
    foreach (i; 0..32) ns[i] = 1L<<i;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;
        auto as = readln.split.to!(long[]);
        cs[] = 0;
        long cnt;
        foreach (i; 0..N-1) {
            if (as[i] - as[i+1] <= 0) continue;
            foreach (j, n; ns) if (n >= as[i] - as[i+1]) {
                ++cs[j];
                ++cnt;
                break;
            }
        }
        if (cnt == 0) {
            writeln(0);
            continue;
        }
        long rest, res;
        foreach (i, c; cs) {
            rest += c;
            cnt -= c;
            if (rest) --rest;
            res += 1;
            if (cnt == 0) break;
        }
        writeln(res + rest);
    }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    long[63] ns, cs;
    foreach (i; 0..63) ns[i] = 1L<<(i+1)-1;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;
        auto as = readln.split.to!(long[]);
        cs[] = 0;
        foreach (i; 0..N-1) {
            if (as[i+1] >= as[i]) continue;
            foreach (j, n; ns) if (as[i] - as[i+1] <= n) {
                ++cs[j];
                as[i+1] = as[i];
                break;
            }
        }
        foreach_reverse (i, c; cs) if (c > 0) {
            writeln(i+1);
            goto ok;
        }
        writeln(0);
        ok:
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long m = a[0], dd;
		foreach (i; 0..n)
		{
			auto d = a[i] - m;
			if (d == -2)
			{
				d = -3;
				m.chmax(a[i]+3);
			}
			if (d < 0)
			{
				dd.chmax(-d);
			}
			m.chmax(a[i]);
		}

		long x;
		while (dd > 0)
		{
			++x;
			dd -= x;
		}
		ans[ti] = x;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		long m, dd;
		foreach (i; 0..n)
		{
			auto d = a[i] - m;
			if (d < 0)
			{
				dd.chmax(-d);
			}
			m.chmax(a[i]);
		}

		long x;
		while (dd > 0)
		{
			++x;
			dd -= x;
		}
		ans[ti] = x;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		long m = a[0], dd;
		foreach (i; 0..n)
		{
			auto d = a[i] - m;
			if (d < 0)
			{
				dd.chmax(-d);
			}
			m.chmax(a[i]);
		}

		long x;
		while (dd > 0)
		{
			++x;
			dd -= x;
		}
		ans[ti] = x;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		long m = a[0], dd = long.min;
		foreach (i; 0..n)
		{
			auto d = a[i] - m;
			if (d < 0)
			{
				dd.chmax(-d);
			}
			m.chmax(a[i]);
		}

		long x;
		while (dd > 0)
		{
			++x;
			dd -= x;
		}
		ans[ti] = x;
	}

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


You are given two integers $$$n$$$ and $$$d$$$. You need to construct a rooted binary tree consisting of $$$n$$$ vertices with a root at the vertex $$$1$$$ and the sum of depths of all vertices equals to $$$d$$$.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. The depth of the vertex $$$v$$$ is the length of the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent. The binary tree is such a tree that no vertex has more than $$$2$$$ children.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n, d \le 5000$$$) — the number of vertices in the tree and the required sum of depths of all vertices. It is guaranteed that the sum of $$$n$$$ and the sum of $$$d$$$ both does not exceed $$$5000$$$ ($$$\sum n \le 5000, \sum d \le 5000$$$).

For each test case, print the answer. If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ in the second line, where $$$p_i$$$ is the parent of the vertex $$$i$$$. Note that the sequence of parents you print should describe some binary tree.

NotePictures corresponding to the first and the second test cases of the example:

module E;

import std.stdio : readln, write, writeln;

struct IO {
    import std.conv : to;
    import std.range : empty, front, popFront, split;

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

    int readInt() {
        return readToken.to!int;
    }

    string[] tokens;
}

bool solve(int n, int target) {
    import std.algorithm : min;

    int[] count = new int[n];
    int i = 0, sum = 0;
    for (; i < n && (1 << i) - 1 < n; ++i) {
        count[i] = min(1 << i, n - ((1 << i) - 1));
        sum += i * count[i];
    }
    int maxd = i;
    if (sum > target) {
        return false;
    }
    for (; i--;) {
        while (count[i] > 1) {
            count[i]--;
            if (sum + maxd - i < target) {
                sum += maxd - i, count[maxd++]++;
            }
            else {
                count[i + target - sum]++;
                goto end;
            }
        }
    }
    return false;
end:
    int start = 0;
    int[] p = new int[n];
    for (int k = 1; k < n; ++k) {
        for (int j = 0; j < count[k]; ++j) {
            p[start + count[k - 1] + j] = start + (j >> 1);
        }
        start += count[k - 1];
    }
    writeln("YES");
    for (int k = 1; k < n; ++k) {
        write(p[k] + 1, " \n"[k + 1 == n]);
    }
    return true;
}

void main() {
    IO io;
    int T = io.readInt;
    while (T--) {
        int n = io.readInt;
        int target = io.readInt;
        if (!solve(n, target)) {
            writeln("NO");
        }
    }
}


Consider a tunnel on a one-way road. During a particular day, $$$n$$$ cars numbered from $$$1$$$ to $$$n$$$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.Traffic regulations prohibit overtaking inside the tunnel. If car $$$i$$$ overtakes any other car $$$j$$$ inside the tunnel, car $$$i$$$ must be fined. However, each car can be fined at most once.Formally, let's say that car $$$i$$$ definitely overtook car $$$j$$$ if car $$$i$$$ entered the tunnel later than car $$$j$$$ and exited the tunnel earlier than car $$$j$$$. Then, car $$$i$$$ must be fined if and only if it definitely overtook at least one other car.Find the number of cars that must be fined.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$), denoting the number of cars. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), denoting the ids of cars in order of entering the tunnel. All $$$a_i$$$ are pairwise distinct. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$), denoting the ids of cars in order of exiting the tunnel. All $$$b_i$$$ are pairwise distinct.

NoteThe first example is depicted below:Car $$$2$$$ definitely overtook car $$$5$$$, while car $$$4$$$ definitely overtook cars $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. Cars $$$2$$$ and $$$4$$$ must be fined.In the second example car $$$5$$$ was definitely overtaken by all other cars.In the third example no car must be fined.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		a[] -= 1;
		b[] -= 1;

		auto ia = new int [n];
		foreach (i; 0..n)
		{
			ia[a[i]] = i;
		}
		auto pb = new int [n];
		foreach (i; 0..n)
		{
			pb[i] = ia[b[i]];
		}
		debug {writeln (pb);}

		int res = 0;
		auto vis = new bool [n + 1];
		int p = 0;
		for (int i = 0; i < n; i++)
		{
			if (p != pb[i])
			{
				res += 1;
			}
			vis[pb[i]] = true;
			while (vis[p])
			{
				p += 1;
			}
		}
		writeln (res);
	}
}

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

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

void solve(){
	int n = rint;
	int[] as = rint(n).map!(x => x - 1).array;
	int[] bs = rint(n).map!(x => x - 1).array;
	log("as:", as, "bs:", bs);

	int[] xs = new int[](n);
	foreach(int i, a; as) xs[a] = i;
	log("xs:", xs);

	int[] ys = new int[](n);
	foreach(int i, b; bs) ys[i] = xs[b];
	log("ys:", ys);

	int t;
	int ans;
	bool[] us = new bool[](n);
	foreach(y; ys){
		us[y] = 1;
		if(y > t) ans += 1;
		else while(t < n && us[t]) t += 1;
		log("y:", y, "t:", t, "us:", us, "ans:", ans);
	}

	ans.writeln;
}

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 int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt() - 1;
      }
      auto B = new int[N];
      foreach (i; 0 .. N) {
        B[i] = readInt() - 1;
      }

      auto ordB = new int[N];
      foreach (i; 0 .. N) {
        ordB[B[i]] = i;
      }

      int ans;
      int mx = -1;
      foreach (i; 0 .. N) {
        if (mx > ordB[A[i]]) {
          ++ans;
        }
        chmax(mx, ordB[A[i]]);
      }
      writeln(ans);
    }
  } 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 a = RDA;
	auto b = RDA;
	int ans;
	bool[long] set;
	while (true)
	{
		if (b.empty)
		{
			break;
		}
		if (set.get(a.front, false))
		{
			a.popFront;
		}
		else if (a.front != b.front)
		{
			if (set.get(a.front, false) == false)
			{
				++ans;
				set[b.front] = true;
			}
			b.popFront;
		}
		else
		{
			a.popFront;
			set[b.front] = true;
			b.popFront;
		}
	}

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

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.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 a = RDA;
	auto b = RDA;
	int ans;
	bool[long] set;
	while (true)
	{
		if (b.empty)
		{
			break;
		}
		if (a.front != b.front)
		{
			if (set.get(a.front, false) == false)
			{
				++ans;
				set[b.front] = true;
			}
			b.popFront;
		}
		else
		{
			a.popFront;
			set[b.front] = true;
			b.popFront;
		}
	}

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


Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do:   If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$;  if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$;  if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.

For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.

NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.

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

immutable long INF = 1L << 59;

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        auto s = readln.split.map!(to!long);
        auto K = s[0];
        auto N = s[1];
        auto A = s[2];
        auto B = s[3];
        long hi = N + 1;
        long lo = -1;
        while (hi - lo > 1) {
            long mid = (hi + lo) / 2;
            long k = K - mid * A;
            if (k + A <= A) {
                hi = mid;
                continue;
            }
            k = k - (N - mid) * B;
            if (k + B <= B) {
                hi = mid;
                continue;
            }
            lo = mid;
        }
        lo.writeln;
    }
}

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

  int q;
  rd(q);
  bool enough(long k, long n, long a, long b, long m) {
    return a * m + b * (n - m) < k;
  }

  while (q--) {
    long k, n, a, b;
    rd(k, n, a, b);
    if (b * n >= k) {
      writeln(-1);
      continue;
    }
    long ok = 0, ng = n + 1;
    while (ng - ok > 1) {
      auto m = (ok + ng) / 2;
      if (enough(k, n, a, b, m)) {
        ok = m;
      } else {
        ng = m;
      }
    }
    writeln(ok);
  }

}

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

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


You are given $$$n$$$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String $$$a$$$ is a substring of string $$$b$$$ if it is possible to choose several consecutive letters in $$$b$$$ in such a way that they form $$$a$$$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of strings. The next $$$n$$$ lines contain the given strings. The number of letters in each string is from $$$1$$$ to $$$100$$$, inclusive. Each string consists of lowercase English letters. Some strings might be equal.

If it is impossible to reorder $$$n$$$ given strings in required order, print "NO" (without quotes). Otherwise print "YES" (without quotes) and $$$n$$$ given strings in required order.

NoteIn the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba".

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

void main() {
    auto N = readln.chomp.to!int;
    auto S = N.iota.map!(_ => readln.chomp).array;
    S.sort!((a, b) => a.length < b.length)();

    foreach (i; 1..N) {
        if (!canFind(S[i], S[i-1])) {
            writeln("NO");
            return;
        }
    }

    writeln("YES");
    S.each!writeln;
}

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

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

    string[] a;
    foreach (_; 0..n) a ~= readln.chomp;

    debug { a.writeln; }

    a.sort!((x, y) => x.length < y.length);

    bool ok =  zip(a, a.dropOne).array.all!(t => t[1].canFind(t[0]));

    if (! ok) {
        writeln("NO");
        return;
    }

    writeln("YES");
    a.each!writeln;
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.range;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n=readln.chomp.to!int;
    auto s=new string[n];
    foreach(i;0..n)
        s[i]=readln.strip;
    sort!"a.length<b.length"(s);
    foreach(i;1..n){
        if(s[i].indexOf(s[i-1])<0){
            writeln("NO");
            return;
        }
    }
    writeln("YES");
    foreach(ref x;s)
        writeln(x);
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.range;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n=readln.chomp.to!int;
    auto s=new string[n];
    foreach(i;0..n)
        s[i]=readln.strip;
    sort(s);
    sort!"a.length<b.length"(s);
    foreach(i;1..n){
        if(s[i].indexOf(s[i-1])<0){
            writeln("NO");
            return;
        }
    }
    writeln("YES");
    foreach(ref x;s)
        writeln(x);
}


Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.

The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).

If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).

NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 > ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

bool nextstr(char[] carr, int idx, int p) {
    if (idx < 0) return false;
    if (carr[idx] - 'a' + 1 == p) {
        carr[idx] = 'a';
        return nextstr(carr, idx - 1, p);
    }
    else {
        carr[idx] += 1;
        return true;
    }
}

bool ispalin(char[] carr, int bi, int ei) {
    foreach (i; 0 .. (ei - bi + 1) / 2) {
        if (carr[bi + i] != carr[ei - i]) return false;
    }
    return true;
}

void setabc(char[] carr, int idx, int n) {
    char ch = 'a';
    while (idx < n) {
        carr[idx++] = ch;
        ch += 1;
        if (ch == 'd') ch = 'a';
    }

}

int main() {
    debug stdin = File("in.txt", "r");

    int n, p;
    readf(" %s %s\n", &n, &p);
    char[] mstr;
    readf(" %s\n", &mstr);

    if (n < 4 || p < 3) {
        while (nextstr(mstr, n - 1, p)) {
            bool palinfree = true;
        outer:
            foreach (i; 0 .. n - 1) {
                foreach (j; i + 1 .. n) {
                    if (ispalin(mstr, i, j)) {
                        palinfree = false;
                        break outer;
                    }
                }
            }
            if (palinfree) {
                writeln(mstr);
                return 0;
            }
        }
        writeln("NO");
        return 0;
    }

    int idx = n - 1;
    while (nextstr(mstr, idx, p)) {
        foreach (i; 0 .. n - 2) {
            if (mstr[i] == mstr[i + 1]) {
                idx = i + 1;
                goto cont;
            }
            if (mstr[i] == mstr[i + 2]) {
                idx = i + 2;
                goto cont;
            }
        }
        if (mstr[n - 2] == mstr[n - 1]) {
            idx = n - 1;
            goto cont;
        }
        writeln(mstr);
        return 0;
cont:
        setabc(mstr, idx + 1, n);
    }
    writeln("NO");

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

bool nextstr(char[] carr, int idx, int p) {
    if (idx < 0) return false;
    if (carr[idx] - 'a' + 1 == p) {
        carr[idx] = 'a';
        return nextstr(carr, idx - 1, p);
    }
    else {
        carr[idx] += 1;
        return true;
    }
}

void setabc(char[] carr, int idx, int n) {
    char ch = 'a';
    while (idx < n) {
        carr[idx++] = ch;
        ch += 1;
        if (ch == 'd') ch = 'a';
    }
}

int main() {
    debug stdin = File("in.txt", "r");

    int n, p;
    readf(" %s %s\n", &n, &p);
    char[] mstr;
    readf(" %s\n", &mstr);

    if (p < 3) {
        if (n == 1 && p == 2 && mstr[0] == 'a') writeln("b");
        else if (n == 2 && mstr[0] == 'a' && mstr[1] == 'b')  writeln("ba");
        else writeln("NO");
        return 0;
    }

    int idx = n - 1;
    while (nextstr(mstr, idx, p)) {
        foreach (i; 0 .. n - 2) {
            if (mstr[i] == mstr[i + 1]) {
                idx = i + 1;
                goto cont;
            }
            if (mstr[i] == mstr[i + 2]) {
                idx = i + 2;
                goto cont;
            }
        }
        if (n > 1 && mstr[n - 2] == mstr[n - 1]) {
            idx = n - 1;
            goto cont;
        }
        writeln(mstr);
        return 0;
cont:
        setabc(mstr, idx + 1, n);
    }
    writeln("NO");

    return 0;
}

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

bool can_add (string start, char e)
{
	if (start.length >= 1 && start[$ - 1] == e)
	{
		return false;
	}
	if (start.length >= 2 && start[$ - 2] == e)
	{
		return false;
	}
	return true;
}

string build (string start, int n, int p)
{
main_loop:
	while (start.length < n)
	{
		foreach (d; 0..p)
		{
			char e = cast (char) (d + 'a');
			if (!can_add (start, e))
			{
				continue;
			}
			start ~= e;
			continue main_loop;
		}
		return null;
	}
	if (start.length == n)
	{
		return start;
	}
	return null;
}

string solve (int n, int p, string s)
{
	foreach_reverse (i, c; s)
	{
		foreach (d; c - 'a' + 1..p)
		{
			char e = cast (char) (d + 'a');
			string t = s[0..i];
			if (!can_add (t, e))
			{
				continue;
			}
			t = build (t ~ e, n, p);
			if (t !is null)
			{
				return t;
			}
		}
	}
	return "NO";
}

void main ()
{
	int n;
	int p;
	while (readf (" %s %s ", &n, &p) > 0)
	{
		string s = readln ().strip ();
		writeln (solve (n, p, s));
	}
}

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

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

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

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

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

int N, P;
string S;

string solve() {
	if (P == 1) {
		if (N == 1) {
			if (S < "a") return "a";
			return "";
		} else {
			return "";
		}
	} else if (P == 2) {
		if (N == 1) {
			if (S < "a") return "a";
			if (S < "b") return "b";
			return "";
		} else if (N == 2) {
			if (S < "ab") return "ab";
			if (S < "ba") return "ba";
			return "";
		} else {
			return "";
		}
	} else {
		foreach_reverse (k; 0 .. N) {
			string ret = S[0 .. k];
			bool ok = true;
			foreach (i; k .. N) {
				bool found;
				foreach (x; 0 .. P) {
					if (i == k && x <= S[k] - 'a') {
						continue;
					}
					if (i >= 1 && ret[i - 1] - 'a' == x) {
						continue;
					}
					if (i >= 2 && ret[i - 2] - 'a' == x) {
						continue;
					}
					found = true;
					ret ~= cast(char)('a' + x);
					break;
				}
				if (!found) {
					ok = false;
					break;
				}
			}
			if (ok) {
				return ret;
			}
		}
		return "";
	}
}

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

		string res = solve;
		if (res == "") {
			writeln("NO");
		} else {
			writeln(res);
		}
	}
	} catch (EOFException) {}
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

bool nextstr(char[] carr, int idx, int p) {
    if (idx < 0) return false;
    if (carr[idx] - 'a' + 1 == p) {
        carr[idx] = 'a';
        return nextstr(carr, idx - 1, p);
    }
    else {
        carr[idx] += 1;
        return true;
    }
}

void setabc(char[] carr, int idx, int n) {
    char ch = 'a';
    while (idx < n) {
        carr[idx++] = ch;
        ch += 1;
        if (ch == 'd') ch = 'a';
    }
}

int main() {
    debug stdin = File("in.txt", "r");

    int n, p;
    readf(" %s %s\n", &n, &p);
    char[] mstr;
    readf(" %s\n", &mstr);

    if (p < 3) {
        if (p == 1 || n > 1 || mstr[0] != 'a') {
            writeln("NO");
            return 0;
        }
        else {
            writeln("b");
            return 0;
        }
    }

    int idx = n - 1;
    while (nextstr(mstr, idx, p)) {
        foreach (i; 0 .. n - 2) {
            if (mstr[i] == mstr[i + 1]) {
                idx = i + 1;
                goto cont;
            }
            if (mstr[i] == mstr[i + 2]) {
                idx = i + 2;
                goto cont;
            }
        }
        if (n > 1 && mstr[n - 2] == mstr[n - 1]) {
            idx = n - 1;
            goto cont;
        }
        writeln(mstr);
        return 0;
cont:
        setabc(mstr, idx + 1, n);
    }
    writeln("NO");

    return 0;
}


You are given an array $$$a$$$ of length $$$n$$$ and array $$$b$$$ of length $$$m$$$ both consisting of only integers $$$0$$$ and $$$1$$$. Consider a matrix $$$c$$$ of size $$$n \times m$$$ formed by following rule: $$$c_{i, j} = a_i \cdot b_j$$$ (i.e. $$$a_i$$$ multiplied by $$$b_j$$$). It's easy to see that $$$c$$$ consists of only zeroes and ones too.How many subrectangles of size (area) $$$k$$$ consisting only of ones are there in $$$c$$$?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers $$$x_1, x_2, y_1, y_2$$$ ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le m$$$) a subrectangle $$$c[x_1 \dots x_2][y_1 \dots y_2]$$$ is an intersection of the rows $$$x_1, x_1+1, x_1+2, \dots, x_2$$$ and the columns $$$y_1, y_1+1, y_1+2, \dots, y_2$$$.The size (area) of a subrectangle is the total number of cells in it.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 40\,000, 1 \leq k \leq n \cdot m$$$), length of array $$$a$$$, length of array $$$b$$$ and required size of subrectangles. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 1$$$), elements of $$$a$$$. The third line contains $$$m$$$ integers $$$b_1, b_2, \ldots, b_m$$$ ($$$0 \leq b_i \leq 1$$$), elements of $$$b$$$.

Output single integer — the number of subrectangles of $$$c$$$ with size (area) $$$k$$$ consisting only of ones.

NoteIn first example matrix $$$c$$$ is:  There are $$$4$$$ subrectangles of size $$$2$$$ consisting of only ones in it:  In second example matrix $$$c$$$ is:

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); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto k = RD!int;
	auto a = RDA;
	auto b = RDA;
	int[int] cnt1, cnt2;
	{
		int streak;
		foreach (i; 0..n)
		{
			if (a[i] == 0)
			{
				++cnt1[streak];
				streak = 0;
			}
			else
				++streak;
		}
		++cnt1[streak];
	}
	{
		int streak;
		foreach (i; 0..m)
		{
			if (b[i] == 0)
			{
				++cnt2[streak];
				streak = 0;
			}
			else
				++streak;
		}
		++cnt2[streak];
	}
	debug writeln(cnt1);
	debug writeln(cnt2);

	long ans;
	foreach (key1; cnt1.keys)
	{
		foreach (i; 1..k+1)
		{
			if (i > key1) break;
			if (k % i) continue;
			auto remain = k / i;
			auto c1 = cnt1[key1];
			auto cc1 = key1 - i + 1;
			foreach (key2; cnt2.keys)
			{
				if (key2 < remain) continue;
				auto cc2 = key2 - remain + 1;
				ans += c1 * cnt2[key2] * cc1 * cc2;
			}
		}
	}

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


Ujan decided to make a new wooden roof for the house. He has $$$n$$$ rectangular planks numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th plank has size $$$a_i \times 1$$$ (that is, the width is $$$1$$$ and the height is $$$a_i$$$).Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.For example, if Ujan had planks with lengths $$$4$$$, $$$3$$$, $$$1$$$, $$$4$$$ and $$$5$$$, he could choose planks with lengths $$$4$$$, $$$3$$$ and $$$5$$$. Then he can cut out a $$$3 \times 3$$$ square, which is the maximum possible. Note that this is not the only way he can obtain a $$$3 \times 3$$$ square.  What is the maximum side length of the square Ujan can get?

The first line of input contains a single integer $$$k$$$ ($$$1 \leq k \leq 10$$$), the number of test cases in the input. For each test case, the first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 1\,000$$$), the number of planks Ujan has in store. The next line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$), the lengths of the planks.

For each of the test cases, output a single integer, the maximum possible side length of the square.

NoteThe first sample corresponds to the example in the statement.In the second sample, gluing all $$$4$$$ planks will result in a $$$4 \times 4$$$ square.In the third sample, the maximum possible square is $$$1 \times 1$$$ and can be taken simply as any of the planks.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto k = RD!int;
	auto ans = new int[](k);
	foreach (i; 0..k)
	{
		auto n = RD!int;
		auto a = RDA!int;
		a.sort!"a > b"();
		foreach (j; 0..n)
		{
			if (a[j] > j)
				ans[i] = j+1;
			else
				break;
		}
	}

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


You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:  the Power Gem of purple color,  the Time Gem of green color,  the Space Gem of blue color,  the Soul Gem of orange color,  the Reality Gem of red color,  the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.

In the first line of input there is one integer $$$n$$$ ($$$0 \le n \le 6$$$) — the number of Gems in Infinity Gauntlet. In next $$$n$$$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.

In the first line output one integer $$$m$$$ ($$$0 \le m \le 6$$$) — the number of absent Gems. Then in $$$m$$$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.

NoteIn the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.In the second sample Thanos doesn't have any Gems, so he needs all six.

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;
import std.bigint;
import core.checkedint;

void main()
{
	string[string] dic = [
		"purple" : "Power",
		"green" : "Time",
		"blue" : "Space",
		"orange" : "Soul",
		"red" : "Reality",
		"yellow" : "Mind"
	];
	int m = readln.chomp.to!int;
	foreach (i; 0..m) {
		string s = readln.chomp;
		dic.remove(s);
	}
	dic.length.writeln;
	foreach (k, v; dic) {
		v.writeln;
	}
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

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

void main()
{
    string [string] mp = [
        "purple": "Power",
        "green": "Time",
        "blue": "Space",
        "orange": "Soul",
        "red": "Reality",
        "yellow": "Mind"
    ];

    readln;
    string s;
    while ((s = readln.chomp) != "") {
        debug { s.writeln; }
        mp.remove(s);
    }

    auto ans = mp.values;
    ans.length.writeln;
    ans.each!writeln;
}


Consider a simplified penalty phase at the end of a football match.A penalty phase consists of at most $$$10$$$ kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (note that it goes against the usual football rules). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the $$$7$$$-th kick the first team has scored $$$1$$$ goal, and the second team has scored $$$3$$$ goals, the penalty phase ends — the first team cannot reach $$$3$$$ goals.You know which player will be taking each kick, so you have your predictions for each of the $$$10$$$ kicks. These predictions are represented by a string $$$s$$$ consisting of $$$10$$$ characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way:  if $$$s_i$$$ is 1, then the $$$i$$$-th kick will definitely score a goal;  if $$$s_i$$$ is 0, then the $$$i$$$-th kick definitely won't score a goal;  if $$$s_i$$$ is ?, then the $$$i$$$-th kick could go either way. Based on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that the referee doesn't take into account any predictions when deciding to stop the penalty phase — you may know that some kick will/won't be scored, but the referee doesn't.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1\,000$$$) — the number of test cases. Each test case is represented by one line containing the string $$$s$$$, consisting of exactly $$$10$$$ characters. Each character is either 1, 0, or ?.

For each test case, print one integer — the minimum possible number of kicks in the penalty phase.

NoteConsider the example test:In the first test case, consider the situation when the $$$1$$$-st, $$$5$$$-th and $$$7$$$-th kicks score goals, and kicks $$$2$$$, $$$3$$$, $$$4$$$ and $$$6$$$ are unsuccessful. Then the current number of goals for the first team is $$$3$$$, for the second team is $$$0$$$, and the referee sees that the second team can score at most $$$2$$$ goals in the remaining kicks. So the penalty phase can be stopped after the $$$7$$$-th kick.In the second test case, the penalty phase won't be stopped until all $$$10$$$ kicks are finished.In the third test case, if the first team doesn't score any of its three first kicks and the second team scores all of its three first kicks, then after the $$$6$$$-th kick, the first team has scored $$$0$$$ goals and the second team has scored $$$3$$$ goals, and the referee sees that the first team can score at most $$$2$$$ goals in the remaining kicks. So, the penalty phase can be stopped after the $$$6$$$-th kick.In the fourth test case, even though you can predict the whole penalty phase, the referee understands that the phase should be ended only after the $$$9$$$-th kick.

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = s.length;
		{
			long cnt;
			foreach (i; 0..s.length)
			{
				if (s[i] == '?')
				{
					if (i % 2 == 0)
						++cnt;
				}
				else if (s[i] == '1')
				{
					if (i % 2)
						--cnt;
					else
						++cnt;
				}
				{
					long rem1 = (s.length - i) / 2 - (i % 2 == 0 ? 1 : 0);
					long rem2 = (s.length - i) / 2;
					if (cnt > rem2 || cnt + rem1 < 0)
					{
						ans[ti].chmin(i+1);
						break;
					}
				}
			}
		}
		{
			long cnt;
			foreach (i; 0..s.length)
			{
				if (s[i] == '?')
				{
					if (i % 2)
						++cnt;
				}
				else if (s[i] == '1')
				{
					if (i % 2)
						++cnt;
					else
						--cnt;
				}
				{
					long rem1 = (s.length - i) / 2 - (i % 2 == 0 ? 1 : 0);
					long rem2 = (s.length - i) / 2;
					if (cnt > rem1 || cnt + rem2 < 0)
					{
						ans[ti].chmin(i+1);
						break;
					}
				}
			}
		}
	}

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

import std.algorithm, std.range, std.stdio, std.numeric, std.array, std.exception,
       std.container, std.typecons, std.conv, std.random, std.bigint, std.string;

void read(S...)(ref S args) {
  auto input = readln.split;
  assert(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

char[] favor(string s, bool first) {
  char[] t;
  foreach (i; 0 .. 10) {
    if (s[i] == '?') {
      bool isFirstTeam = i % 2 == 0;
      t ~= (isFirstTeam == first) ? '1' : '0';
    } else {
      t ~= s[i];
    }
  }
  return t;
}

int solve(char[] s) {
  auto score = [0, 0];
  auto rem   = [5, 5];
  foreach (i; 0 .. 10) {
    if (s[i] == '1') {
      score[i % 2]++;
    }
    rem[i % 2]--;

    if (score[0] - score[1] > rem[1] || score[1] - score[0] > rem[0]) return i + 1;
  }

  return 10;
}

void main() {
  int T;
  read(T);

  while (T--) {
    string s;
    s = readln.strip;

    writeln(min(solve(s.favor(false)), solve(s.favor(true))));
  }
}

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

void main()
{
	int t = readInt!int;
	while (t--)
	{
		char[] str = cast(char[])readString;
		int minkicks = int.max;
		foreach(p; 0 .. 2)
		{
			int[2] pos = [5, 5];
			int[2] scr = [0, 0];
			int kicks = 0;
			foreach(i; 0 .. 10)
			{
				kicks++;
				int s = i & 1;
				int o = s ^ 1;
				if (str[i] == '1') scr[s]++;
				else if (str[i] == '?' && s == p) scr[s]++;
				pos[s]--;
				if (scr[o]+pos[o] < scr[s] || scr[s]+pos[s] < scr[o]) break;
			}
			minkicks = min(kicks, minkicks);
		}
		minkicks.writeln;
	}
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	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;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else
			static assert(text("Operator ", operator, " not supported"));
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}

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

long solve(int[] a)
{
  long odd  = 0;
  long even = 0;
  foreach (round ; 0 .. 5) {
    int remrounds = 4 - round;
    even += a[round * 2 + 0];
    if ((even > odd && even - odd > remrounds + 1) || (odd > even && odd - even > remrounds))
      return round * 2 + 1;
    odd += a[round * 2 + 1];
    if ((even > odd && even - odd > remrounds) || (odd > even && odd - even > remrounds))
      return round * 2 + 2;
  }
  return 10;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    string s = readln.strip;
    int[] a;
    int[] b;
    foreach (i; 0 .. s.length) {
      if (s[i] == '?') {
        if (i % 2 == 0) {
          a ~= 0;
          b ~= 1;
        } else {
          a ~= 1;
          b ~= 0;
        }
      } else {
        a ~= s[i] - '0';
        b ~= s[i] - '0';
      }
    }
/*
    writeln(s);
    writeln(a);
    writeln(solve(a));
    writeln(b);
    writeln(solve(b));
*/
    writeln(min(solve(a), solve(b)));
  }
}

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

immutable int steps = 10;

int solve (string s, int team)
{
	int [2] goals;
	foreach (step; 0..steps)
	{
		auto cur = (s[step] == '0') ? 0 :
		    (s[step] == '1') ? 1 : (step % 2 == team);
		goals[step % 2] += cur;
		if (goals[0] + (steps - 1 - step + 0) / 2 < goals[1] ||
		    goals[1] + (steps - 1 - step + 1) / 2 < goals[0])
		{
			return step + 1;
		}
	}
	return steps;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		writeln (min (solve (s, 0), solve (s, 1)));
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = s.length;
		{
			long cnt;
			foreach (i; 0..s.length)
			{
				if (s[i] == '?')
				{
					if (i % 2 == 0)
						++cnt;
				}
				else if (s[i] == '1')
				{
					if (i % 2)
						--cnt;
					else
						++cnt;
				}
				{
					long rem1 = (s.length - i) / 2 - (i % 2 == 0 ? 1 : 0);
					long rem2 = (s.length - i) / 2;
					if (cnt > rem2 || cnt + rem1 < 0)
					{
						ans[ti].chmin(i+1);
						break;
					}
				}
			}
		}
		{
			long cnt;
			foreach (i; 0..s.length)
			{
				if (s[i] == '?')
				{
					if (i % 2)
						++cnt;
				}
				else if (s[i] == '1')
				{
					if (i % 2)
						++cnt;
					else
						--cnt;
				}
				if (i % 2)
				{
					long rem1 = (s.length - i) / 2 - (i % 2 == 0 ? 1 : 0);
					long rem2 = (s.length - i) / 2;
					if (cnt > rem1 || cnt + rem2 < 0)
					{
						ans[ti].chmin(i+1);
						break;
					}
				}
			}
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = s.length;
		{
			long cnt;
			foreach (i; 0..s.length)
			{
				if (s[i] == '?')
				{
					if (i % 2 == 0)
						++cnt;
				}
				else if (s[i] == '1')
				{
					if (i % 2)
						--cnt;
					else
						++cnt;
				}
				if (i % 2 == 0)
				{
					long rem = (s.length - i) / 2;
					debug writeln("i:", i, " cnt:", cnt, " rem:", rem);
					if (cnt > rem || -cnt > rem-1)
					{
						ans[ti].chmin(i+1);
						break;
					}
				}
			}
		}
		{
			long cnt;
			foreach (i; 0..s.length)
			{
				if (s[i] == '?')
				{
					if (i % 2)
						++cnt;
				}
				else if (s[i] == '1')
				{
					if (i % 2)
						++cnt;
					else
						--cnt;
				}
				if (i % 2)
				{
					long rem = (s.length - i) / 2;
					if (cnt > rem || -cnt > rem-1)
					{
						ans[ti].chmin(i+1);
						break;
					}
				}
			}
		}
	}

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


Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar.  So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become  and height of Abol will become  where x1, y1, x2 and y2 are some integer numbers and  denotes the remainder of a modulo b.Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a1 and height of Abol is a2.Mike has asked you for your help. Calculate the minimum time or say it will never happen.

The first line of input contains integer m (2 ≤ m ≤ 106). The second line of input contains integers h1 and a1 (0 ≤ h1, a1 < m). The third line of input contains integers x1 and y1 (0 ≤ x1, y1 < m). The fourth line of input contains integers h2 and a2 (0 ≤ h2, a2 < m). The fifth line of input contains integers x2 and y2 (0 ≤ x2, y2 < m). It is guaranteed that h1 ≠ a1 and h2 ≠ a2.

Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.

NoteIn the first sample, heights sequences are following:Xaniar: Abol:

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

int calc(int m, int h, int a, int x, int y)
{
    auto mem = new bool[m];
    fill(mem, false);
    int cnt = 0;
    while (true)
    {
	h = (cast(long)h * x + y) % m;
	++ cnt;
	if (h == a)
	{
	    return cnt;
	}
	if (mem[h] == true)
	{
	    return -1;
	}
	mem[h] = true;
    }
    return -1;
}

T gcd(T)(T a, T b)
{
    if (a == 0) return b;
    if (b == 0) return a;
    if (a > b) return gcd(a % b, b);
    return gcd(a, b % a);
}

void solve(int m, int h1, int h2, int a1, int a2, int x1, int x2, int y1, int y2)
{
    int fst1 = calc(m, h1, a1, x1, y1);
    int snd1 = calc(m, a1, a1, x1, y1);
    int fst2 = calc(m, h2, a2, x2, y2);
    int snd2 = calc(m, a2, a2, x2, y2);
    if (fst1 == -1 || fst2 == -1)
    {
	writeln(-1);
	return;
    }
    if (fst1 == fst2)
    {
	writeln(fst1);
	return;
    }
    if (snd1 != -1 && fst2 > fst1 && (fst2 - fst1) % snd1 == 0)
    {
	writeln(fst2);
	return;
    }
    if (snd2 != -1 && fst1 > fst2 && (fst1 - fst2) % snd2 == 0)
    {
	writeln(fst1);
	return;
    }
    if (snd1 == -1 || snd2 == -1)
    {
	writeln(-1);
	return;
    }
    foreach (long i; 1 .. 10000000)
    {
	auto tmp = i * snd1 + fst1;
	if ((tmp - fst2) % snd2 == 0)
	{
	    writeln(i * snd1 + fst1);
	    return;
	}
    }
    writeln(-1);
}

void main(string[] args)
{
    int m, h1, h2, a1, a2, x1, x2, y1, y2;
    while (scanf("%d%d%d%d%d%d%d%d%d", &m, &h1, &a1, &x1, &y1, &h2, &a2, &x2, &y2) == 9)
    {
	solve(m, h1, h2, a1, a2, x1, x2, y1, y2);
    }
}

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

int calc(int m, int h, int a, int x, int y)
{
    auto mem = new bool[m];
    fill(mem, false);
    int cnt = 0;
    while (true)
    {
	h = (cast(long)h * x + y) % m;
	++ cnt;
	if (h == a)
	{
	    return cnt;
	}
	if (mem[h] == true)
	{
	    return -1;
	}
	mem[h] = true;
    }
    return -1;
}

T gcd(T)(T a, T b)
{
    if (a == 0) return b;
    if (b == 0) return a;
    if (a > b) return gcd(a % b, b);
    return gcd(a, b % a);
}

void solve(int m, int h1, int h2, int a1, int a2, int x1, int x2, int y1, int y2)
{
    int ret1 = calc(m, h1, a1, x1, y1);
    if (ret1 == -1)
    {
	writeln(-1);
	return;
    }
    int ret2 = calc(m, h2, a2, x2, y2);
    if (ret2 == -1)
    {
	writeln(-1);
	return;
    }
    long ans = cast(long)ret1 * ret2 / gcd(ret1, ret2);
    writeln(ans);
}

void main(string[] args)
{
    int m, h1, h2, a1, a2, x1, x2, y1, y2;
    while (scanf("%d%d%d%d%d%d%d%d%d", &m, &h1, &a1, &x1, &y1, &h2, &a2, &x2, &y2) == 9)
    {
	solve(m, h1, h2, a1, a2, x1, x2, y1, y2);
    }
}


It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds.Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights wi (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?

The first line contains three integers n, m, k (1 ≤ n, m ≤ 105, 1 ≤ k ≤ 109) — the number of fish caught by Alice and Bob respectively, and the number of fish species. The second line contains n integers each from 1 to k, the list of fish type caught by Alice. The third line contains m integers each from 1 to k, the list of fish type caught by Bob. Note that one may have caught more than one fish for a same species.

Output "YES" (without quotes) if it is possible, and "NO" (without quotes) otherwise.

NoteIn the first sample, if w1 = 1, w2 = 2, w3 = 2.5,  then Alice has a total of 2 + 2 + 2 = 6 weight units, while Bob only has 1 + 1 + 2.5 = 4.5.In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bob’s fish is always not less than the total weight of Alice’s fish.

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

void main ()
{
	int n, m, k;
	while (readf (" %s %s %s", &n, &m, &k) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		sort (a);
		reverse (a);
		auto b = new int [m];
		foreach (i; 0..m)
		{
			readf (" %s", &b[i]);
		}
		sort (b);
		reverse (b);
		b ~= 0;
		bool ok = false;
		int j = 0;
		foreach (i; 0..n)
		{
			while (b[j] >= a[i])
			{
				j++;
			}
			if (i >= j)
			{
				ok = true;
			}
		}
		writefln ("%s", ok ? "YES" : "NO");
	}
}