The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon.

Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto n = readln.chomp.to!double * 2;
        auto t = 180 * (n - 2) / 2 / n * PI / 180.0;
        writefln("%.12f", 0.5 * tan(t) * 2);
    }
}

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

real solve (int n)
{
	auto alpha = PI / n;
	real x = 0.0;
	real y = 0.0;
	real phi = 0.0;
	foreach (i; 0..n)
	{
		x += cos (phi);
		y += sin (phi);
		phi += alpha;
	}
	return cos (alpha / 2) * hypot (y, x);
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		readln.strip.to !(int).solve.writefln !("%.20f");
	}
}

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()
{
	double PI = 3.14159265359;
	auto t = RD!int;
	auto ans = new double[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto rad = PI / n;
		ans[ti] = 1.0;
		foreach (i; 0..n/2-1)
		{
			ans[ti] += cos(rad*(i+1)) * 2;
		}
	}

	foreach (e; ans)
	{
		writefln(FMT_F, e);
	}
	stdout.flush;
	debug readln;
}

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

real solve (int n)
{
	auto alpha = PI / n;
	writeln (alpha * 180.0 / PI);
	real x = 0.0;
	real y = 0.0;
	real phi = 0.0;
	foreach (i; 0..n)
	{
		x += cos (phi);
		y += sin (phi);
		phi += alpha;
	}
	return cos (alpha / 2) * hypot (y, x);
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		readln.strip.to !(int).solve.writefln !("%.20f");
	}
}


You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any.

import std.stdio;
import std.string : strip;
import std.range : enumerate;
import std.container : DList;
import std.algorithm : joiner, map;
import std.conv : text;

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

  foreach (i; 0..t) {
    int n;
    readf!("%d\n")(n);
    uint j = 1; // sequence index
    auto ones = DList!uint();
    auto zeros = DList!uint();
    auto a = new uint[n];

    foreach (idx, c; readln.strip.enumerate) {
      if (c == '1') {
	if (zeros.empty) {
	  // assign a new subseq
	  ones.insertBack(j);
	  a[idx] = j;
	  j++;
	} else {
	  // add to sequence of zeros
	  auto k = zeros.back;
	  zeros.removeBack;
	  a[idx] = k;
	  ones.insertBack(k);
	}
      } else if (c == '0') {
	if (ones.empty) {
	  zeros.insertBack(j);
	  a[idx] = j;
	  j++;
	} else {
	  auto k = ones.back;
	  ones.removeBack;
	  a[idx] = k;
	  zeros.insertBack(k);
	}
      }
    }

    writeln(j - 1);
    writeln(a.map!text.joiner(" "));
  }
}

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;
  string s;

  void solve(long tc = -1)
  {
    RedBlackTree!long[2] subs = [redBlackTree!long(), redBlackTree!long()];
    auto sub = new long[cast(size_t) n];
    foreach(i, c; s)
      {
        long d = c == '0'? 0 : 1;
        if (subs.at(d).empty)
          {
            sub.at(i) = subs.at(0).length + subs.at(1).length + 1;
            subs.at(d ^ 1).insert(sub.at(i));
          }
        else
          {
            sub.at(i) = subs.at(d).front;
            subs.at(d).removeFront;
            subs.at(d^1).insert(sub.at(i));
          }
      }
    writeln(sub.fold!max);
    foreach(s; sub)
      write(s, " ");
    writeln;
  }
}

struct Interval
{
  long l, h;

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans1[ti].length = n;

		BinaryHeap!(Array!int, "a > b")[2] heap;
		heap[s[0]-'0'].insert(1);
		ans0[ti] = 1;
		ans1[ti][0] = 1;
		foreach (i; 1..n)
		{
			auto x = s[i] - '0';
			int num;
			if (!heap[x^1].empty)
			{
				num = heap[x^1].front; heap[x^1].removeFront;
			}
			else
			{
				++ans0[ti];
				num = ans0[ti];
			}
			ans1[ti][i] = num;
			heap[x].insert(num);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans1[ti].length = n;

		int cnt0, cnt1;
		int start = -1;
		foreach (i; 0..n)
		{
			if (start == -1)
				start = s[i] - '0';
			if (s[i] == '0')
				++cnt0;
			else
				++cnt1;

			int d;
			if (start == 0)
				d = abs(cnt0 - cnt1);
			else
				d = abs(cnt1 - cnt0);

			if (start != s[i]-'0')
				++d;
			auto x = d;
			ans0[ti].chmax(x);
			ans1[ti][i] = x;
		}
	}

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


Today is Devu's birthday. For celebrating the occasion, he bought n sweets from the nearby market. He has invited his f friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each friend. He wants to celebrate it in a unique style, so he would like to ensure following condition for the distribution of sweets. Assume that he has distributed n sweets to his friends such that ith friend is given ai sweets. He wants to make sure that there should not be any positive integer x > 1, which divides every ai.Please find the number of ways he can distribute sweets to his friends in the required way. Note that the order of distribution is important, for example [1, 2] and [2, 1] are distinct distributions. As the answer could be very large, output answer modulo 1000000007 (109 + 7).To make the problem more interesting, you are given q queries. Each query contains an n, f pair. For each query please output the required number of ways modulo 1000000007 (109 + 7).

The first line contains an integer q representing the number of queries (1 ≤ q ≤ 105). Each of the next q lines contains two space space-separated integers n, f (1 ≤ f ≤ n ≤ 105).

For each query, output a single integer in a line corresponding to the answer of each query.

NoteFor first query: n = 6, f = 2. Possible partitions are [1, 5] and [5, 1].For second query: n = 7, f = 2. Possible partitions are [1, 6] and [2, 5] and [3, 4] and [4, 3] and [5, 3] and [6, 1]. So in total there are 6 possible ways of partitioning.

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

immutable long MO = 1000000007;
immutable LIM = 200005;
int[] meb;
long[] inv, fac, fnv;

void main(string[] args) {
	meb = new int[LIM];
	meb[1] = 1;
	foreach (i; 1 .. LIM) for (int j = i * 2; j < LIM; j += i) meb[j] -= meb[i];
debug{
writeln("meb = ",meb[0..30]);
}
	inv = new long[LIM];
	inv[1] = 1;
	foreach (i; 2 .. LIM) {
		inv[i] = MO - MO / i * inv[cast(int)(MO % i)] % MO;
	}
	fac = new long[LIM];
	fnv = new long[LIM];
	fac[0] = fnv[0] = 1;
	foreach (i; 1 .. LIM) {
		fac[i] = fac[i - 1] * i % MO;
		fnv[i] = fnv[i - 1] * inv[i] % MO;
	}

	foreach (tc; 0 .. readInt) {
		const n = readInt;
		const f = readInt;
		long ans;
		void doIt(int d) {
			if (meb[d]) {
				const m = n / d;
				if (m >= f) {
					long tmp = 1;
					(tmp *= fac[m - 1]) %= MO;
					(tmp *= fnv[m - f]) %= MO;
					(tmp *= fnv[f - 1]) %= MO;
debug{
writeln(n," ",f,"  ",d," : ",meb[d]," ",tmp);
}
					ans += meb[d] * tmp;
				}
			}
		}
		for (int d = 1; d * d <= n; ++d) if (n % d == 0) {
			doIt(d);
			if (d != n / d) {
				doIt(n / d);
			}
		}
		ans = (ans % MO + MO) % MO;
		writeln(ans);
	}
}


Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to deliver the same message to yet another friend (that the recipient has in common with Heidi), and so on.Heidi believes that her friends want to avoid awkward situations, so she will not be made to visit the same person (including Jenny) twice. She also knows how much it costs to travel between any two of her friends who know each other. She wants to know: what is the maximal amount of money she will waste on travel if it really is a prank?Heidi's n friends are labeled 0 through n - 1, and their network of connections forms a tree. In other words, every two of her friends a, b know each other, possibly indirectly (there is a sequence of friends starting from a and ending on b and such that each two consecutive friends in the sequence know each other directly), and there are exactly n - 1 pairs of friends who know each other directly.Jenny is given the number 0.

The first line of the input contains the number of friends n (3 ≤ n ≤ 100). The next n - 1 lines each contain three space-separated integers u, v and c (0 ≤ u, v ≤ n - 1, 1 ≤ c ≤ 104), meaning that u and v are friends (know each other directly) and the cost for travelling between u and v is c. It is guaranteed that the social network of the input forms a tree.

Output a single integer – the maximum sum of costs.

NoteIn the second example, the worst-case scenario goes like this: Jenny sends Heidi to the friend labeled by number 2 (incurring a cost of 100), then friend 2 sends her to friend 1 (costing Heidi 3), and finally friend 1 relays her to friend 4 (incurring an additional cost of 2).

/+ dub.sdl:
    name "J"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner;
import std.typecons;

int main() {
    auto sc = new Scanner(stdin);
    alias Edge = Tuple!(int, "to", int, "dist");
    int n;
    sc.read(n);
    Edge[][] g = new Edge[][](n);

    foreach (i; 0..n) {
        int a, b, c;
        sc.read(a, b, c);
        g[a] ~= Edge(b, c);
        g[b] ~= Edge(a, c);
    }

    int ma = -1;
    void dfs(int p, int b, int nd) {
        ma = max(ma, nd);
        foreach (e; g[p]) {
            if (e.to == b) continue;
            dfs(e.to, p, nd + e.dist);
        }
    }
    dfs(0, -1, 0);

    writeln(ma);
    return 0;
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

                    assert(buf.length == T.length);
                }
                x = buf;
                line.length = 0;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}


There is an integer $$$n$$$ without zeros in its decimal representation. Alice and Bob are playing a game with this integer. Alice starts first. They play the game in turns.On her turn, Alice must swap any two digits of the integer that are on different positions. Bob on his turn always removes the last digit of the integer. The game ends when there is only one digit left.You have to find the smallest integer Alice can get in the end, if she plays optimally.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first and the only line of each test case contains the integer $$$n$$$ ($$$10 \le n \le 10^9$$$) — the integer for the game. $$$n$$$ does not have zeros in its decimal representation.

For each test case output a single integer — the smallest integer Alice can get in the end of the game.

NoteIn the first test case Alice has to swap $$$1$$$ and $$$2$$$. After that Bob removes the last digit, $$$1$$$, so the answer is $$$2$$$.In the second test case Alice can swap $$$3$$$ and $$$1$$$: $$$312$$$. After that Bob deletes the last digit: $$$31$$$. Then Alice swaps $$$3$$$ and $$$1$$$: $$$13$$$ and Bob deletes $$$3$$$, so the answer is $$$1$$$.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip.map !(q{a - '0'}).array;
		if (s.length == 2)
		{
			writeln (s[1]);
		}
		else
		{
			writeln (s.minElement);
		}
	}
}


«Bersoft» company is working on a new version of its most popular text editor — Bord 2010. Bord, like many other text editors, should be able to print out multipage documents. A user keys a sequence of the document page numbers that he wants to print out (separates them with a comma, without spaces).Your task is to write a part of the program, responsible for «standardization» of this sequence. Your program gets the sequence, keyed by the user, as input. The program should output this sequence in format l1-r1,l2-r2,...,lk-rk, where ri + 1 < li + 1 for all i from 1 to k - 1, and li ≤ ri. The new sequence should contain all the page numbers, keyed by the user, and nothing else. If some page number appears in the input sequence several times, its appearances, starting from the second one, should be ignored. If for some element i from the new sequence li = ri, this element should be output as li, and not as «li - li».For example, sequence 1,2,3,1,1,2,6,6,2 should be output as 1-3,6.

The only line contains the sequence, keyed by the user. The sequence contains at least one and at most 100 positive integer numbers. It's guaranteed, that this sequence consists of positive integer numbers, not exceeding 1000, separated with a comma, doesn't contain any other characters, apart from digits and commas, can't end with a comma, and the numbers don't contain leading zeroes. Also it doesn't start with a comma or contain more than one comma in a row.

Output the sequence in the required format.

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

void main()
{
	/*int n;
	loop:while(read(&n))
	{

	}*/

	auto s=readln.strip.split(',').map!(to!int).array;
	sort(s);
	for(int i=0,pos=0;i<s.length;)
	{
		write(s[i]);
		while(pos<s.length-1 && s[pos]+1>=s[pos+1])pos++;
		if(s[pos]>s[i])write('-',s[pos]);
		if(pos<s.length-1)write(',');
		i=++pos;
	}
}


Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.At every moment of time, every SELL offer has higher price than every BUY offer. In this problem no two ever existed orders will have the same price.The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.  The presented order book says that someone wants to sell the product at price $$$12$$$ and it's the best SELL offer because the other two have higher prices. The best BUY offer has price $$$10$$$. There are two possible actions in this orderbook:  Somebody adds a new order of some direction with some price. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL $$$20$$$" if there is already an offer "BUY $$$20$$$" or "BUY $$$25$$$" — in this case you just accept the best BUY offer.You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types: "ADD $$$p$$$" denotes adding a new order with price $$$p$$$ and unknown direction. The order must not contradict with orders still not removed from the order book.  "ACCEPT $$$p$$$" denotes accepting an existing best offer with price $$$p$$$ and unknown direction.The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo $$$10^9 + 7$$$. If it is impossible to correctly restore directions, then output $$$0$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 363\,304$$$) — the number of actions in the log. Each of the next $$$n$$$ lines contains a string "ACCEPT" or "ADD" and an integer $$$p$$$ ($$$1 \le p \le 308\,983\,066$$$), describing an action type and price.  All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.

Output the number of ways to restore directions of ADD actions modulo $$$10^9 + 7$$$.

6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3

7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5

NoteIn the first example each of orders may be BUY or SELL.In the second example the order with price $$$1$$$ has to be BUY order, the order with the price $$$3$$$ has to be SELL order.

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

immutable int MD = 10 ^^ 9 + 7;

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

    Tuple!(bool, int)[] ops;
    foreach (_; 0 .. n) {
        string s; int v;
        readf("%s %s", &s, &v);
        readln;

        ops ~= tuple(s == "ADD", v);
    }

    int ans = 1;
    auto buys = make!(RedBlackTree!(int, "a > b"));
    auto sells = make!(RedBlackTree!int);
    auto unks = make!(RedBlackTree!int);
    foreach (e; ops) {
        auto v = e[1];
        if (e[0]) {
            if (!buys.empty && v < buys.front) buys.insert(v);
            else if (!sells.empty && sells.front < v) sells.insert(v);
            else unks.insert(v);
        } else {
            if ((!buys.empty && v < buys.front) || (!sells.empty && sells.front < v)) {
                ans = 0;
                break;
            }

            while (!unks.empty && unks.front < v) {
                buys.insert(unks.front);
                unks.removeFront();
            }
            while (!unks.empty && v < unks.back) {
                sells.insert(unks.back);
                unks.removeBack();
            }

            if (!unks.empty) {
                ans = ans * 2 % MD;
                unks.removeFront();
            } else if (v == buys.front) {
                buys.removeFront();
            } else { // v == sells.front
                sells.removeFront();
            }
        }

        debug { writeln(buys, ' ', sells, ' ', unks); }
    }

    ans = ans.to!long * (unks.length + 1) % MD;

    ans.writeln;
}

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

immutable int MD = 10 ^^ 9 + 7;

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

    Tuple!(bool, int)[] ops;
    foreach (_; 0 .. n) {
        string s; int v;
        readf("%s %s", &s, &v);
        readln;

        ops ~= tuple(s == "ADD", v);
    }

    int ans = 1;
    auto buys = make!(RedBlackTree!(int, "a > b"));
    auto sells = make!(RedBlackTree!int);
    auto unks = make!(RedBlackTree!int);
    foreach (e; ops) {
        auto v = e[1];
        if (e[0]) {
            if (!buys.empty && v < buys.front) buys.insert(v);
            else if (!sells.empty && sells.front < v) sells.insert(v);
            else unks.insert(v);
        } else {
            if ((!buys.empty && v < buys.front) || (!sells.empty && sells.front < v)) {
                ans = 0;
                break;
            }

            while (!unks.empty && unks.front < v) {
                buys.insert(unks.front);
                unks.removeFront();
            }
            while (!unks.empty && v < unks.back) {
                sells.insert(unks.back);
                unks.removeBack();
            }

            if (!unks.empty) {
                ans = ans * 2 % MD;
                unks.removeFront();
            } else if (v == buys.front) {
                buys.removeFront();
            } else { // v == sells.front
                sells.removeFront();
            }
        }

        debug { writeln(buys, ' ', sells, ' ', unks); }
    }

    if (unks.length > 0) ans = ans.to!long * unks.length % MD;

    ans.writeln;
}

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

immutable int MD = 10 ^^ 9 + 7;

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

    Tuple!(bool, int)[] ops;
    foreach (_; 0 .. n) {
        string s; int v;
        readf("%s %s", &s, &v);
        readln;

        ops ~= tuple(s == "ADD", v);
    }

    int ans = 1;
    auto buys = make!(RedBlackTree!(int, "a > b"));
    auto sells = make!(RedBlackTree!int);
    auto unks = make!(RedBlackTree!int);
    foreach (e; ops) {
        auto v = e[1];
        if (e[0]) {
            if (!buys.empty && v < buys.front) buys.insert(v);
            else if (!sells.empty && sells.front < v) sells.insert(v);
            else unks.insert(v);
        } else {
            if ((!buys.empty && v < buys.front) || (!sells.empty && sells.front < v)) {
                ans = 0;
                break;
            }

            while (!unks.empty && unks.front < v) {
                buys.insert(unks.front);
                unks.removeFront();
            }
            while (!unks.empty && v < unks.back) {
                sells.insert(unks.back);
                unks.removeBack();
            }

            if (!unks.empty) {
                ans = ans * 2 % MD;
                unks.removeFront();
            } else if (v == buys.front) {
                buys.removeFront();
            } else { // v == sells.front
                sells.removeFront();
            }
        }

        debug { writeln(buys, ' ', sells, ' ', unks); }
    }

    foreach (_; 0 .. unks.length) {
        ans = ans * 2 % MD;
    }

    ans.writeln;
}


Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1 / x seconds for the first character and 1 / y seconds for the second one). The i-th monster dies after he receives ai hits. Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.

The first line contains three integers n,x,y (1 ≤ n ≤ 105, 1 ≤ x, y ≤ 106) — the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly. Next n lines contain integers ai (1 ≤ ai ≤ 109) — the number of hits needed do destroy the i-th monster.

Print n lines. In the i-th line print word "Vanya", if the last hit on the i-th monster was performed by Vanya, "Vova", if Vova performed the last hit, or "Both", if both boys performed it at the same time.

NoteIn the first sample Vanya makes the first hit at time 1 / 3, Vova makes the second hit at time 1 / 2, Vanya makes the third hit at time 2 / 3, and both boys make the fourth and fifth hit simultaneously at the time 1.In the second sample Vanya and Vova make the first and second hit simultaneously at time 1.

import std.stdio;
import std.algorithm;

void main() { while (solve()) {} }
bool solve() {
	int n;
	long x, y;
	if (readf(" %s %s %s", &n, &x, &y) != 3)
		return false;

	foreach (i; 0..n) {
		long hp;
		readf(" %s", &hp);

		//a1 + a1 * y / x >= hp;
		long lf = 0, rg = hp;
		while (lf + 1 < rg) {
			long a1 = (lf + rg) / 2;
			if (a1 + a1 * y / x >= hp)
				rg = a1;
			else
				lf = a1;
		}
		long a1 = rg;

		lf = 0, rg = hp;
		while (lf + 1 < rg) {
			long a2 = (lf + rg) / 2;
			if (a2 + a2 * x / y >= hp)
				rg = a2;
			else
				lf = a2;
		}
		long a2 = rg;

		// t1 = a1 / x, t2 = a2 / x
		if (a1 * y < a2 * x)
			writeln("Vanya");
		else if (a1 * y > a2 * x)
			writeln("Vova");
		else
			writeln("Both");
	}

	return true;
}


Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n.Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array a left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by k for each number).The seller can obtain array b from array a if the following conditions hold: bi > 0; 0 ≤ ai - bi ≤ k for all 1 ≤ i ≤ n.Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).

The first line contains two integers n and k (1 ≤ n ≤ 3·105; 1 ≤ k ≤ 106). The second line contains n integers ai (1 ≤ ai ≤ 106) — array a.

In the single line print a single number — the maximum possible beauty of the resulting array.

NoteIn the first sample we can obtain the array:3 6 9 12 12 15In the second sample we can obtain the next array:7 21 49 14 77

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

immutable int MED_N = 1_000_006;
immutable int MAX_N = MED_N * 2 + 1;

void main ()
{
	int n, k;
	while (scanf (" %d %d", &n, &k) > 0)
	{
		auto a = new int [MAX_N * 2];
		int m = MED_N - 1;
		foreach (i; 0..n)
		{
			int v;
			scanf (" %d", &v);
			a[v]++;
			m = min (m, v);
		}
		auto s = new int [MAX_N];
		s[0] = 0;
		foreach (i; 1..MAX_N)
		{
			s[i] = s[i - 1] + a[i];
		}
		int res = 1;
		foreach_reverse (d; 2..m + 1)
		{
			bool ok = true;
			for (int i = d * 2; i < MAX_N; i += d)
			{
				int j = min (i - d + k, i);
				if (s[i - 1] > s[j])
				{
					ok = false;
					break;
				}
			}
			if (ok)
			{
				res = d;
				break;
			}
		}
		writeln (res);
	}
}


This is an interactive problem.There are $$$n$$$ words in a text editor. The $$$i$$$-th word has length $$$l_i$$$ ($$$1 \leq l_i \leq 2000$$$). The array $$$l$$$ is hidden and only known by the grader. The text editor displays words in lines, splitting each two words in a line with at least one space. Note that a line does not have to end with a space. Let the height of the text editor refer to the number of lines used. For the given width, the text editor will display words in such a way that the height is minimized.More formally, suppose that the text editor has width $$$w$$$. Let $$$a$$$ be an array of length $$$k+1$$$ where $$$1=a_1 < a_2 < \ldots < a_{k+1}=n+1$$$. $$$a$$$ is a valid array if for all $$$1 \leq i \leq k$$$, $$$l_{a_i}+1+l_{a_i+1}+1+\ldots+1+l_{a_{i+1}-1} \leq w$$$. Then the height of the text editor is the minimum $$$k$$$ over all valid arrays.Note that if $$$w < \max(l_i)$$$, the text editor cannot display all the words properly and will crash, and the height of the text editor will be $$$0$$$ instead.You can ask $$$n+30$$$ queries. In one query, you provide a width $$$w$$$. Then, the grader will return the height $$$h_w$$$ of the text editor when its width is $$$w$$$.Find the minimum area of the text editor, which is the minimum value of $$$w \cdot h_w$$$ over all $$$w$$$ for which $$$h_w \neq 0$$$.The lengths are fixed in advance. In other words, the interactor is not adaptive.

The first and only line of input contains a single integer $$$n$$$ ($$$1 \leq n \leq 2000$$$)  — the number of words on the text editor. It is guaranteed that the hidden lengths $$$l_i$$$ satisfy $$$1 \leq l_i \leq 2000$$$.

NoteIn the first test case, the words are $$$\{\texttt{glory},\texttt{to},\texttt{ukraine},\texttt{and},\texttt{anton},\texttt{trygub}\}$$$, so $$$l=\{5,2,7,3,5,6\}$$$. If $$$w=1$$$, then the text editor is not able to display all words properly and will crash. The height of the text editor is $$$h_1=0$$$, so the grader will return $$$0$$$.If $$$w=9$$$, then a possible way that the words will be displayed on the text editor is:   $$$\texttt{glory__to}$$$  $$$\texttt{ukraine__}$$$  $$$\texttt{and_anton}$$$  $$$\texttt{__trygub_}$$$ The height of the text editor is $$$h_{9}=4$$$, so the grader will return $$$4$$$.If $$$w=16$$$, then a possible way that the words will be displayed on the text editor is:   $$$\texttt{glory_to_ukraine}$$$  $$$\texttt{and_anton_trygub}$$$ The height of the text editor is $$$h_{16}=2$$$, so the grader will return $$$2$$$.We have somehow figured out that the minimum area of the text editor is $$$32$$$, so we answer it.

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

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

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

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

enum INF = 10L^^9;

long Ask(long w) {
  writeln("? ", w);
  stdout.flush;
  long res = readLong;
  if (res == 0) {
    res = INF;
  }
  return res;
}

void main() {
  const N = readInt;

  long lo = 0, hi = 2010L * N;
  for (; lo + 1 < hi; ) {
    const mid = (lo + hi) / 2;
    const res = Ask(mid);
    ((res == 1) ? hi : lo) = mid;
  }

  long ans = hi;
  foreach (h; 2 .. N + 1) {
    // check [hi - (h - 1), hi]
    const w = hi / h;
    const res = Ask(w);
    chmin(ans, w * res);
  }

  writeln("! ", ans);
  stdout.flush;
}

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

immutable int limit = 2000;

void main ()
{
	int [int] answer;

	int ask (int w)
	{
		if (w !in answer)
		{
			writeln ("? ", w);
			stdout.flush ();
			answer[w] = readln.strip.to !(int);
		}
		return answer[w];
	}

	auto n = readln.strip.to !(int);
	auto lo = n * 1 + (n - 1);
	auto hi = n * limit + (n - 1);
	while (lo < hi)
	{
		auto me = (lo + hi) / 2;
		auto cur = ask (me);
		if (cur == 1)
		{
			hi = me;
		}
		else
		{
			lo = me + 1;
		}
	}

	int res = lo;
	int total = res - (n - 1);
	debug {writeln ("total = ", lo);}
	for (int h = 2; h <= n; h++)
	{
		int ideal = total + n - h;
		for (int w = (ideal + h - 1) / h; w * h < res; w++)
		{
			debug {writeln ("h = ", h, ", w = ", w);}
			if (ask (w) == h)
			{
				res = w * h;
				break;
			}
		}
	}

	writeln ("! ", res);
	stdout.flush ();
}

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

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

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

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

enum INF = 10L^^9;

long Ask(long w) {
  writeln("? ", w);
  stdout.flush;
  int res = readInt;
  if (res == 0) {
    res = INF;
  }
  return res;
}

long ans;

void solve(long a, long b, long fa, long fb) {
  if (fa == fb) {
    return;
  }
  if (a + 1 == b) {
    debug {
      writeln("waf ", a, " ", b, " ", fa, " ", fb);
    }
    if (a) chmin(ans, a * fa);
    if (b) chmin(ans, b * fb);
    return;
  }
  const mid = (a + b) / 2;
  const res = Ask(mid);
  solve(a, mid, fa, res);
  solve(mid, b, res, fb);
}

void main() {
  const N = readInt;
  ans = long.max;
  solve(0, 2010L * N, INF, 1);
  writeln("! ", ans);
  stdout.flush;
}

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

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

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

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

enum INF = 10L^^9;

long Ask(long w) {
  writeln("? ", w);
  stdout.flush;
  int res = readInt;
  if (res == 0) {
    res = INF;
  }
  return res;
}

long ans;

void solve(long a, long b, long fa, long fb) {
  if (fa == fb) {
    return;
  }
  if (a + 1 == b) {
    debug {
      writeln("waf ", a, " ", b, " ", fa, " ", fb);
    }
    chmin(ans, a * fa);
    chmin(ans, b * fb);
    return;
  }
  const mid = (a + b) / 2;
  const res = Ask(mid);
  solve(a, mid, fa, res);
  solve(mid, b, res, fb);
}

void main() {
  const N = readInt;
  ans = long.max;
  solve(0, 2010L * N, INF, 1);
  writeln("! ", ans);
  stdout.flush;
}


T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.In the picture you can see a complete binary tree with n = 15.  Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui = 4 and si = «UURL», then the answer is 10.

The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105.

Print q numbers, i-th number must be the answer to the i-th query.

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

dchar[] getPath(long x, int mxb) {
    dchar[] ans;
    foreach_reverse (b; 0 .. mxb+1) {
        if (x == 0) { break; }

        if (x & (1L << b)) {
            x -= (1L << b);
            ans ~= 'R';
        } else { ans ~= 'L'; }
    }

    ans.popBack();

    return ans;
}

dchar[] toRealPath(dchar[] path, int mxb) {
    dchar[] realPath;

    foreach (e; path) {
        if (e == 'U' && !realPath.empty) { realPath.popBack(); }
        else if ((e == 'L' || e == 'R') && realPath.length < mxb) { realPath ~= e; }
    }

    return realPath;
}

long getVal(dchar[] path, int mxb) {
    int lvl = mxb;
    long ans = (1L << mxb);
    foreach (e; path) {
        debug { writeln(ans, ' ', lvl,' ' , e); }

        lvl -= 1;
        long mv = (1L << lvl);
        if (e == 'L') { ans -= mv; }
        else { ans += mv; }
    }

    return ans;
}

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

    int mxb = bsr(n+1) - 1;

    debug { mxb.writeln; }

    while (q--) {
        long x;
        readf("%s", &x);
        readln;

        auto path = getPath(x, mxb);

        auto s = readln.chomp;

        auto ans = path.chain(s).array.to!(dchar[]).toRealPath(mxb).getVal(mxb);

        ans.writeln;
    }
}

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

void main ()
{
	long n;
	int q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		foreach (r; 0..q)
		{
			long v;
			readf (" %s", &v);
			readln;
			auto s = readln.strip;
			foreach (c; s)
			{
				if (c == 'U')
				{
					if (v * 2 == n + 1)
					{
						continue;
					}
					long u = v;
					long p = 1;
					while (!(u & 1))
					{
						u >>= 1;
						p <<= 1;
					}
					u >>= 1;
					if (u & 1)
					{
						v -= p;
					}
					else
					{
						v += p;
					}
				}
				else
				{
					if (v & 1)
					{
						continue;
					}
					long u = v;
					long p = 1;
					while (!(u & 1))
					{
						u >>= 1;
						p <<= 1;
					}
					p >>= 1;
					if (c == 'L')
					{
						v -= p;
					}
					else
					{
						v += p;
					}
				}
			}
			writeln (v);
		}
	}
}

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

dchar[] getPath(long x, int mxb) {
    dchar[] ans;
    foreach_reverse (b; 0 .. mxb+1) {
        if (x == 0) { break; }

        if (x & (1L << b)) {
            x -= (1L << b);
            ans ~= 'R';
        } else { ans ~= 'L'; }
    }

    ans.popBack();

    return ans;
}

long getVal(dchar[] path, int mxb) {
    int lvl = mxb;
    long ans = (1L << mxb);
    foreach (e; path) {
        debug { writeln(ans, ' ', lvl,' ' , e); }

        if (lvl == mxb && e == 'U') { continue; }
        if (lvl == 0 && (e == 'L' || e == 'R')) { continue; }

        if (e == 'U') {
            ans += (1L << lvl);
            lvl += 1;
        } else {
            lvl -= 1;
            long mv = (1L << lvl);
            if (e == 'L') { ans -= mv; }
            else { ans += mv; }
        }
    }

    return ans;
}

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

    int mxb = bsr(n+1) - 1;

    debug { mxb.writeln; }

    while (q--) {
        long x;
        readf("%s", &x);
        readln;

        auto path = getPath(x, mxb);

        debug { path.writeln; }

        auto s = readln.chomp;

        auto ans = getVal(path.chain(s).array.to!(dchar[]), mxb);

        ans.writeln;
    }
}


Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.The decreasing coefficient of permutation p1, p2, ..., pn is the number of such i (1 ≤ i < n), that pi > pi + 1.You have numbers n and k. Your task is to print the permutation of length n with decreasing coefficient k.

The single line contains two space-separated integers: n, k (1 ≤ n ≤ 105, 0 ≤ k < n) — the permutation length and the decreasing coefficient.

In a single line print n space-separated integers: p1, p2, ..., pn — the permutation of length n with decreasing coefficient k.  If there are several permutations that meet this condition, print any of them. It is guaranteed that the permutation with the sought parameters exists.

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		int [] a;
		foreach (i; 0..n - k)
		{
			a ~= k + i + 1;
		}
		foreach (i; 0..k)
		{
			a ~= k - i;
		}
		writefln ("%(%s %)", a);
	}
}

import std.stdio;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		int [] a;
		foreach (i; 0..n - k)
		{
			a ~= k + i + 1;
		}
		foreach (i; 0..k)
		{
			a ~= k - i;
		}
		writefln ("%(%s %)", a);
	}
}

import std.stdio;

void main() {
  int n, k;
  int[] ans;
  readf("%d %d", &n, &k);
  for (int i = k + 1 ; i >= 1 ; --i) {
    ans ~= i;
  }
  for (int i = k + 2 ; i <= n ; ++i) {
    ans ~= i;
  }
  foreach (v ; ans) {
    write(v);
    write(" ");
  }
  write("\n");
}

module sigod.codeforces.p285A;

import std.stdio;

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

	foreach (ki; 1 .. k + 1) {
		stdout.write(n - ki + 1, " ");
	}

	foreach (ni; 1 .. n - k) {
		stdout.write(ni, " ");
	}

	stdout.write(n - k);
}


This is an interactive problem.Homer likes arrays a lot and he wants to play a game with you. Homer has hidden from you a permutation $$$a_1, a_2, \dots, a_n$$$ of integers $$$1$$$ to $$$n$$$. You are asked to find any index $$$k$$$ ($$$1 \leq k \leq n$$$) which is a local minimum. For an array $$$a_1, a_2, \dots, a_n$$$, an index $$$i$$$ ($$$1 \leq i \leq n$$$) is said to be a local minimum if $$$a_i < \min\{a_{i-1},a_{i+1}\}$$$, where $$$a_0 = a_{n+1} = +\infty$$$. An array is said to be a permutation of integers $$$1$$$ to $$$n$$$, if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Initially, you are only given the value of $$$n$$$ without any other information about this permutation.At each interactive step, you are allowed to choose any $$$i$$$ ($$$1 \leq i \leq n$$$) and make a query with it. As a response, you will be given the value of $$$a_i$$$. You are asked to find any index $$$k$$$ which is a local minimum after at most $$$100$$$ queries.

NoteIn the example, the first line contains an integer $$$5$$$ indicating that the length of the array is $$$n = 5$$$.The example makes five "?" queries, after which we conclude that the array is $$$a = [3,2,1,4,5]$$$ and $$$k = 3$$$ is local minimum.

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

int[int] cache;
int ask(int i) {
    if (i in cache) return cache[i];
    writefln("? %s", i);
    stdout.flush;
    return cache[i] = read!int;
}

void main() {
    int N = read!int;
    int l = 1, r = N;
    while (l < r) {
        int m = (l + r) / 2;
        int x = ask(m);
        int y = ask(m + 1);
        if (x < y) {
            r = m;
        } else {
            l = m + 1;
        }
    }
    writefln("! %s", l);
    stdout.flush;
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = new int [n + 2];
		a[] = -1;
		a[0] = int.max;
		a[$ - 1] = int.max;

		void ask (int pos)
		{
			if (a[pos] < 0)
			{
				writeln ("? ", pos);
				stdout.flush ();
				a[pos] = readln.strip.to !(int);
			}
		}

		int solve ()
		{
			ask (1);
			ask (2);
			if (a[1] < a[2])
			{
				return 1;
			}

			ask (n);
			ask (n - 1);
			if (a[n] < a[n - 1])
			{
				return n;
			}

			int lo = 1;
			int hi = n;
			while (hi - lo > 2)
			{
				int me = (lo + hi) / 2;
				ask (me);
				ask (me + 1);
				if (a[me] < a[me + 1])
				{
					hi = me + 1;
				}
				else
				{
					lo = me;
				}
			}

			foreach (i; 1..n + 1)
			{
				if (a[i] >= 0)
				{
					if (a[i] < a[i - 1] && a[i] < a[i + 1])
					{
						return i;
					}
				}
			}
			assert (false);
		}

		auto res = solve ();
		writeln ("! ", res);
		stdout.flush ();
		break;
	}
}

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

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

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

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

int N;
int[] A;

int[] cache;

int Ask(int i) {
  if (cache[i] == -1) {
    writefln("? %s", i);
    stdout.flush;
    debug {
      cache[i] = A[i];
    } else {
      cache[i] = readInt();
    }
  }
  return cache[i];
}

void Answer(int i) {
  writefln("! %s", i);
  stdout.flush;
}

void main() {
  N = readInt();
  debug {
    A = new int[N + 2];
    A[0] = A[N + 1] = N + 1;
    foreach (i; 1 .. N + 1) {
      A[i] = readInt();
    }
  }

  cache = new int[N + 2];
  cache[] = -1;
  cache[0] = cache[N + 1] = N + 1;

  int lo = 0, hi = N + 1;
  for (; lo + 2 < hi; ) {
    const mid = (lo + hi) / 2;
    const a = Ask(mid);
    const b = Ask(mid + 1);
    (a < b) ? (hi = mid + 1) : (lo = mid);
  }
  assert(lo + 2 == hi);
  Answer(lo + 1);
}

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

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

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

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

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

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

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

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

void main()
{
    int N; get(N);
    if (N < 100) {
        foreach (i; 1..N+1) {
            writefln!"? %d"(i);
            stdout.flush();
            int k; get(k);
            if (k == 1) return writefln!"! %d"(i);
        }
    }
    int l, r;

    writeln("? 1"); stdout.flush(); get(l);
    writeln("? 2"); stdout.flush(); get(r);
    if (l < r) return writeln("! 1");

    writefln!"? %d"(N - 1); stdout.flush(); get(l);
    writefln!"? %d"(N); stdout.flush(); get(r);
    if (l > r) return writefln!"! %d"(N);

    // Left: l > r, Right: l < r
    l = 1; r = N-1;
    while (l + 1 < r) {
        auto m = (l + r) / 2;
        int ll, rr;
        writefln!"? %d"(m); stdout.flush(); get(ll);
        writefln!"? %d"(m + 1); stdout.flush(); get(rr);
        if (ll > rr) {
            l = m;
        } else {
            r = m;
        }
    }
    writefln!"! %d"(r);
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

int[int] cache;
int ask(int i) {
    if (i in cache) return cache[i];
    writefln("? %s", i);
    stdout.flush;
    return cache[i] = read!int;
}

void main() {
    int N = read!int;
    if (N == 1) {
        writeln("! 1");
        stdout.flush;
        return;
    }
    if (N == 2) {
        int l = ask(1);
        if (l == 1) {
            writeln("! 1");
        } else {
            writeln("! 2");
        }
        stdout.flush;
        return;
    }
    int l = 1, r = N;
    int al = ask(l);
    int ar = ask(r);
    while (l + 2 < r) {
        //writeln([l, r]);
        int mli = (2*l + r) / 3;
        int mri = (l + 2*r) / 3;
        int aml = ask(mli);
        int amr = ask(mri);
        if (aml > amr) {
            l = mli;
            al = aml;
        } else {
            r = mri;
            ar = amr;
        }
    }
    //writeln([l, r]);
    //writeln("--");
    int[] ks;
    int[] xs;
    for (int i = max(1, l-1); i <= min(N, r+1); i++) {
        ks ~= i;
        xs ~= ask(i);
    }
    int INF = 1<<28;
    for (int i = 1; i+1 < xs.length; i++) {
        //if ( (i-1 >= 0 ? xs[i-1] : INF) > xs[i] && xs[i] < (i+1<xs.length ? xs[i+1] : INF) ) {
        if (xs[i-1] > xs[i] && xs[i] < xs[i+1]) {
            writefln("! %s", ks[i]);
            stdout.flush;
            return;
        }
    }
    if (xs[0] > xs.back) {
        writefln("! %s", ks.back);
    } else {
        writefln("! %s", ks[0]);
    }
    stdout.flush;
    return;
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

int[int] cache;
int ask(int i) {
    if (i in cache) return cache[i];
    writefln("? %s", i);
    stdout.flush;
    return cache[i] = read!int;
}

void main() {
    int N = read!int;
    if (N == 1) {
        writeln("! 1");
        return;
    }
    int l = 1, r = N;
    int al = ask(l);
    int ar = ask(r);
    while (l + 2 < r) {
        //writeln([l, r]);
        int mli = (2*l + r) / 3;
        int mri = (l + 2*r) / 3;
        int aml = ask(mli);
        int amr = ask(mri);
        if (aml > amr) {
            l = mli;
            al = aml;
        } else {
            r = mri;
            ar = amr;
        }
    }
    //writeln([l, r]);
    //writeln("--");
    int INF = 1<<28;
    int[] ks = [0];
    int[] xs = [INF];
    for (int i = max(1, l-1); i <= min(N, r+1); i++) {
        ks ~= i;
        xs ~= ask(i);
    }
    ks ~= N+1;
    ks ~= INF;
    for (int i = 1; i+1 < xs.length; i++) {
        //if ( (i-1 >= 0 ? xs[i-1] : INF) > xs[i] && xs[i] < (i+1<xs.length ? xs[i+1] : INF) ) {
        if (xs[i-1] > xs[i] && xs[i] < xs[i+1]) {
            writefln("! %s", ks[i]);
            stdout.flush;
            return;
        }
    }
    assert(false);
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

int[int] cache;
int ask(int i) {
    if (i in cache) return cache[i];
    writefln("? %s", i);
    stdout.flush;
    return cache[i] = read!int;
}

enum int INF = 1<<28;

void main() {
    int N = read!int;
    if (N == 1) {
        writeln("! 1");
        stdout.flush;
        return;
    }
    int l = 1, r = N;
    int al = ask(l);
    int ar = ask(r);
    while (l + 2 < r) {
        //writeln([l, r]);
        int mli = (2*l + r) / 3;
        int mri = (l + 2*r) / 3;
        int aml = ask(mli);
        int amr = ask(mri);
        if (aml > amr) {
            l = mli;
            al = aml;
        } else {
            r = mri;
            ar = amr;
        }
    }
    //writeln([l, r]);
    //writeln("--");
    int[] ks;
    int[] xs;
    for (int i = max(1, l-1); i <= min(N, r+1); i++) {
        ks ~= i;
        xs ~= ask(i);
    }
    for (int i = 0; i < xs.length; i++) {
        if ( (i-1 >= 0 ? xs[i-1] : INF) > xs[i] && xs[i] < (i+1<xs.length ? xs[i+1] : INF) ) {
            writefln("! %s", ks[i]);
            stdout.flush;
            return;
        }
    }
    assert(false);
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

int[int] cache;
int ask(int i) {
    if (i in cache) return cache[i];
    writefln("? %s", i);
    stdout.flush;
    return cache[i] = read!int;
}

enum int INF = 1<<28;

void main() {
    int N = read!int;
    if (N == 1) {
        writeln("! 1");
        return;
    }
    int l = 1, r = N;
    int al = ask(l);
    int ar = ask(r);
    while (l + 2 < r) {
        //writeln([l, r]);
        int mli = (2*l + r) / 3;
        int mri = (l + 2*r) / 3;
        int aml = ask(mli);
        int amr = ask(mri);
        if (aml > amr) {
            l = mli;
            al = aml;
        } else {
            r = mri;
            ar = amr;
        }
    }
    //writeln([l, r]);
    //writeln("--");
    int[] ks;
    int[] xs;
    for (int i = max(1, l-1); i <= min(N, r+1); i++) {
        ks ~= i;
        xs ~= ask(i);
    }
    for (int i = 0; i < xs.length; i++) {
        if ( (i-1 >= 0 ? xs[i-1] : INF) > xs[i] && xs[i] < (i+1<xs.length ? xs[i+1] : INF) ) {
            writefln("! %s", ks[i]);
            stdout.flush;
            return;
        }
    }
    assert(false);
}

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

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

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

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

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

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

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

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

void main()
{
    int N; get(N);
    if (N < 100) {
        foreach (i; 1..N+1) {
            writefln!"? %d"(i);
            stdout.flush();
            int k; get(k);
            if (k == 1) return writefln!"! %d"(k);
        }
    }
    int l, r;

    writeln("? 1"); stdout.flush(); get(l);
    writeln("? 2"); stdout.flush(); get(r);
    if (l < r) return writeln("! 1");

    writefln!"? %d"(N - 1); stdout.flush(); get(l);
    writefln!"? %d"(N); stdout.flush(); get(r);
    if (l > r) return writefln!"! %d"(N);

    // Left: l > r, Right: l < r
    l = 1; r = N-1;
    while (l + 1 < r) {
        auto m = (l + r) / 2;
        int ll, rr;
        writefln!"? %d"(m); stdout.flush(); get(ll);
        writefln!"? %d"(m + 1); stdout.flush(); get(rr);
        if (ll > rr) {
            l = m;
        } else {
            r = m;
        }
    }
    writefln!"! %d"(r);
}


Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...Let's define a Rooted Dead Bush (RDB) of level $$$n$$$ as a rooted tree constructed as described below.A rooted dead bush of level $$$1$$$ is a single vertex. To construct an RDB of level $$$i$$$ we, at first, construct an RDB of level $$$i-1$$$, then for each vertex $$$u$$$:   if $$$u$$$ has no children then we will add a single child to it;  if $$$u$$$ has one child then we will add two children to it;  if $$$u$$$ has more than one child, then we will skip it.   Rooted Dead Bushes of level $$$1$$$, $$$2$$$ and $$$3$$$. Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:  The center of the claw is the vertex with label $$$1$$$. Lee has a Rooted Dead Bush of level $$$n$$$. Initially, all vertices of his RDB are green.In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo $$$10^9+7$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^6$$$) — the level of Lee's RDB.

For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo $$$10^9 + 7$$$.

NoteIt's easy to see that the answer for RDB of level $$$1$$$ or $$$2$$$ is $$$0$$$.The answer for RDB of level $$$3$$$ is $$$4$$$ since there is only one claw we can choose: $$$\{1, 2, 3, 4\}$$$.The answer for RDB of level $$$4$$$ is $$$4$$$ since we can choose either single claw $$$\{1, 3, 2, 4\}$$$ or single claw $$$\{2, 7, 5, 6\}$$$. There are no other claws in the RDB of level $$$4$$$ (for example, we can't choose $$$\{2, 1, 7, 6\}$$$, since $$$1$$$ is not a child of center vertex $$$2$$$).  Rooted Dead Bush of level 4.

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

immutable int mod = 10 ^^ 9 + 7;

void main ()
{
	long [] f = [0, 0, 0, 1, 1];

	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		while (f.length <= n)
		{
			f ~= (f[$ - 1] + f[$ - 2] * 2 + !(f.length % 3)) % mod;
		}
		writeln ((f[n] * 4L) % mod);
	}
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(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);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(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 = E.init)
{
  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;
}

void main()
{
  enum long mod = 1_000_000_000 + 7;
  long t;
  read(t);
  auto dp = new long[2_000_000 + 1];
  dp[1 .. 3] = [0, 0];
  foreach(i; 3 .. 2_000_000 + 1)
    {
      dp[i] = 2 * dp[i - 2] + dp[i - 1] + (i%3 == 0? 4 : 0);
      dp[i] %= mod;
    }
  while(t--)
    {
      long n;
      read(n);
      writeln(dp.at(n));
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	long[] add = [0, 0, 0, 4, -4, 4];
	auto list = new long[](2*(10^^6));
	list[2] = 4;
	list[3] = 4;
	list[4] = 12;
	foreach (i; 5..list.length)
	{
		auto x = add[(i-5)%6];
		list[i] = list[i-1];
		list[i].modm(2);
		list[i].moda(x);
	}

	foreach (ti; 0..t)
	{
		auto n = RD!int-1;
		ans[ti] = list[n];
		/*int[][] edges;
		edges.length = 1;
		foreach (i; 0..n-1)
		{
			foreach (u; 0..edges.length)
			{
				if (edges[u].length == 3) continue;
				if (edges[u].length == 0)
				{
					++edges.length;
					edges[u] ~= cast(int)edges.length - 1;
				}
				else if (edges[u].length == 1)
				{
					++edges.length;
					++edges.length;
					edges[u] ~= cast(int)edges.length - 2;
					edges[u] ~= cast(int)edges.length - 1;
				}
			}
		}

		int[] dfs(int u, int par)
		{
			int res;
			bool used;
			foreach (v; edges[u])
			{
				if (v == par) continue;
				auto r = dfs(v, u);
				if (r[1])
					used = true;
				res += r[0];
			}
			if (!used && edges[u].length == 3)
			{
				++res;
				used = true;
			}
			else
			{
				used = false;
			}
			return [res, used ? 1 : 0];
		}
		writeln(dfs(0, -1));*/
	}

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


You are given an integer array $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ represents the number of blocks at the $$$i$$$-th position. It is guaranteed that $$$1 \le a_i \le n$$$. In one operation you can choose a subset of indices of the given array and remove one block in each of these indices. You can't remove a block from a position without blocks.All subsets that you choose should be different (unique).You need to remove all blocks in the array using at most $$$n+1$$$ operations. It can be proved that the answer always exists.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$) — length of the given array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — numbers of blocks at positions $$$1, 2, \dots, n$$$.

In the first line print an integer $$$op$$$ ($$$0 \le op \le n+1$$$). In each of the following $$$op$$$ lines, print a binary string $$$s$$$ of length $$$n$$$. If $$$s_i=$$$'0', it means that the position $$$i$$$ is not in the chosen subset. Otherwise, $$$s_i$$$ should be equal to '1' and the position $$$i$$$ is in the chosen subset. All binary strings should be distinct (unique) and $$$a_i$$$ should be equal to the sum of $$$s_i$$$ among all chosen binary strings. If there are multiple possible answers, you can print any. It can be proved that an answer always exists.

NoteIn the first example, the number of blocks decrease like that:$$$\lbrace 5,5,5,5,5 \rbrace \to \lbrace 4,4,4,4,4 \rbrace \to \lbrace 4,3,3,3,3 \rbrace \to \lbrace 3,3,2,2,2 \rbrace \to \lbrace 2,2,2,1,1 \rbrace \to \lbrace 1,1,1,1,0 \rbrace \to \lbrace 0,0,0,0,0 \rbrace$$$. And we can note that each operation differs from others.

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

char[][] solve(int[] A) {
  const N = cast(int)(A.length);
  auto ans = new char[][](N + 1, N);
  auto used = new bool[N];
  auto xss = [iota(N + 1).array];
  foreach (h; 0 .. N) {
    int im = -1;
    foreach (i; 0 .. N) {
      if (!used[i]) {
        if (im == -1 || A[im] < A[i]) {
          im = i;
        }
      }
    }
    used[im] = true;
    debug {
      writeln("xss = ", xss);
      writeln("im = ", im);
    }
    const xssLen = cast(int)(xss.length);
    auto ls = new int[xssLen];
    foreach (j; 0 .. xssLen) {
      ls[j] = cast(int)(xss[j].length);
    }
    int numLarge;
    foreach (j; 0 .. xssLen) {
      if (ls[j] >= 2) {
        ++numLarge;
      }
    }
    auto ms = new int[xssLen];
    if (A[im] <= numLarge) {
      ms[0 .. A[im]] = 1;
    } else if (N + 1 - A[im] <= numLarge) {
      ms[] = ls[];
      ms[0 .. (N + 1 - A[im])] -= 1;
    } else {
      int a = A[im] - numLarge;
      ms[0 .. numLarge] = 1;
      foreach (j; 0 .. numLarge) {
        const tmp = min(a, ls[j] - 2);
        a -= tmp;
        ms[j] += tmp;
      }
      foreach (j; numLarge .. xssLen) {
        const tmp = min(a, ls[j]);
        a -= tmp;
        ms[j] += tmp;
      }
      assert(a == 0);
    }
    debug {
      writeln("  ms = ", ms);
    }
    int[][] xssNext;
    foreach (j; 0 .. xssLen) {
      foreach (x; xss[j][0 .. ms[j]]) {
        ans[x][im] = '1';
      }
      foreach (x; xss[j][ms[j] .. ls[j]]) {
        ans[x][im] = '0';
      }
      if (0 < ms[j]) {
        xssNext ~= xss[j][0 .. ms[j]];
      }
      if (ms[j] < ls[j]) {
        xssNext ~= xss[j][ms[j] .. ls[j]];
      }
    }
    xss = xssNext;
    xss.sort!"a.length > b.length";
  }
  return ans;
}

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

      const ans = solve(A);
      writeln(ans.length);
      foreach (row; ans) {
        writeln(row);
      }
    }
  } catch (EOFException e) {
  }
}