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


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


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


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

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


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


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


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

long solve(long[] a)
{
  assert(a.length >= 3);
  long ans = a[$ - 1] - a[0];
  return max(ans + a[1] - a[0], ans + (a[$ - 1] - a[$ - 2]));
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.splitter.map!(to!long).array.sort.array;
    long best = solve(a);
    foreach (cut ; 0 .. n - 3 + 1) {
      best = max(best, solve(a[0 .. $ - cut]));
      best = max(best, solve(a[cut .. $]));
    }
    writeln(best);
  }
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

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

void solve() {
    int n = read!int;
    auto a = readarray!long;
    a.sort!("a > b");
    long res1, res2;
    int minI = n - 1;
    foreach(i; 0 .. minI - 1) {
        if (abs(a[minI] - a[i]) + abs(a[i] - a[i+1]) > res1)
            res1 = abs(a[minI] - a[i]) + abs(a[i] - a[i+1]);
    }
    foreach(i; iota(n-1,1,-1).array) {
        if (abs(a[0] - a[i]) + abs(a[i] - a[i-1]) > res2)
            res2 = abs(a[0] - a[i]) + abs(a[i] - a[i-1]);
    }
    writeln(max(res1, res2));
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

import std.algorithm;
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 n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		int res = 0;
		foreach (i; 2..n)
		{
			res = max (res, +(a[i] - a[i - 1] + a[i] - a[0]));
		}
		reverse (a);
		foreach (i; 2..n)
		{
			res = max (res, -(a[i] - a[i - 1] + a[i] - a[0]));
		}
		writeln (res);
	}
}

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.splitter.map!(to!long).array.sort.array;
    long ans = a[$ - 1] - a[0];
    ans = max(ans + a[1] - a[0], ans + (a[$ - 1] - a[$ - 2]));
    writeln(ans);
  }
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

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

void solve() {
    int n = read!int;
    auto a = readarray!long;
    a.sort!("a > b");
    long res;
    int minI = n - 1;
    foreach(i; 0 .. minI - 1) {
        if (abs(a[minI] - a[i]) + abs(a[i] - a[i+1]) > res)
            res = abs(a[minI] - a[i]) + abs(a[i] - a[i+1]);
    }
    writeln(res);
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

import std.algorithm;
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 n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		writeln (a[$ - 1] - a[0] + max (a[$ - 1] - a[$ - 2],
		    a[1] - a[0]));
	}
}


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

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

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

        auto a = readln.splitter.map!(to!int).array;

        debug { a.writeln; }

        auto incoming = new int[] (a.length + 1);
        incoming[] = 0;

        long ans = 0;
        foreach (i, e; a) {
            int mx = min(i + e, a.length.to!int - 1);
            foreach (step; i + 2 .. mx + 1) {
                ++incoming[step];
            }

            int starts = max(0, e - 1 - incoming[i]);
            ans += starts;

            int carryover = max(0, incoming[i] - (e-1));
            incoming[i+1] += carryover;

            debug { ans.writeln; }
        }

        debug { incoming.writeln; }

        ans.writeln;
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.splitter.map !(to !(int)).array;
		s ~= 0;
		long res = 0;
		auto p = iota (n + 1).array;
		for (int i = 0; i < n; i++)
		{
			int add = max (0, s[i] - n + i);
			res += add;
			s[i] = max (0, s[i] - add);
			while (s[i] > 1)
			{
				for (int j = i; j < n; j += s[j] + 1)
				{
					if (s[j] <= 1)
					{
						p[j] = p[j + 1];
					}
					j = p[j];
					s[j] = max (0, s[j] - 1);
				}
				res += 1;
			}
		}
		writeln (res);
	}
}

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

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

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

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

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

        auto dp = new long[N];
        long ans;
        foreach (i; 0 .. N) {
          long now = dp[i];
          if (S[i] - 1 >= now) {
            ans += (S[i] - 1) - now;
            now = S[i] - 1;
          }
          if (i + 1 < N) {
            dp[i + 1] += now - (S[i] - 1);
          }
          foreach (j; i + 2 .. N) {
            if (j <= i + S[i]) {
              dp[j] += 1;
            }
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto imos = new long[](n+1);
		auto a = new long[](n+1);
		foreach (i; 0..n)
		{
			auto d = S[i] - imos[i] - a[i];
			if (d >= 1)
				ans[ti] += d - 1;
			else
				a[i+1] += (-d) + 1;
			auto l = cast(int)(i + 2);
			auto r = cast(int)(i + S[i] + 1);
			if (l <= n)
				++imos[l];
			if (r <= n)
				--imos[r];
			imos[i+1] = min(imos[i+1] + imos[i], 10^^10);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto imos = new long[](n+1);
		foreach (i; 0..n)
		{
			auto d = S[i] - imos[i];
			if (d >= 1)
				ans[ti] += d - 1;
			else
				imos[i+1] += (-d) + 1;
			auto l = cast(int)(i + 2);
			auto r = cast(int)(i + S[i] + 1);
			if (l <= n)
				++imos[l];
			if (r <= n)
				--imos[r];
			imos[i+1] = min(imos[i+1] + imos[i], 10^^10);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto imos = new long[](n+1);
		foreach (i; 0..n)
		{
			auto d = S[i] - imos[i];
			if (d > 1)
				ans[ti] += d - 1;
			else
				imos[i+1] += (-d) + 1;
			auto l = cast(int)(i + 2);
			auto r = cast(int)(i + S[i] + 1);
			if (l <= n)
				++imos[l];
			if (r <= n)
				--imos[r];
			imos[i+1] = min(imos[i+1] + imos[i], 10^^10);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto imos = new long[](n+1);
		foreach (i; 0..n)
		{
			auto d = S[i] - imos[i];
			if (d > 1)
				ans[ti] += d - 1;
			else
				imos[i+1] += (-d) + 1;
			auto l = cast(int)(i + 2);
			auto r = cast(int)(i + S[i] + 1);
			if (l <= n)
				++imos[l];
			if (r <= n)
				--imos[r];
			imos[i+1] = min(imos[i+1] + imos[i], 10^^9);
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto imos = new long[](n+1);
		foreach (i; 0..n)
		{
			auto d = S[i] - imos[i];
			if (d > 1)
				ans[ti] += d - 1;
			else
				imos[i+1] += (-d) + 1;
			auto l = cast(int)(i + 2);
			auto r = cast(int)(i + S[i] + 1);
			if (l <= n)
				++imos[l];
			if (r <= n)
				--imos[r];
			imos[i+1] += imos[i];
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	int sn = 0;
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		sn += n;
		if (sn > 5000)
		{
			assert (false);
		}
		auto s = readln.splitter.map !(to !(int)).array;
		if (s.length != n)
		{
			assert (false);
		}
		long res = 0;
		foreach (i; 0..n)
		{
			int add = max (0, s[i] - n + i);
			res += add;
			s[i] -= add;
			while (s[i] > 1)
			{
				for (int j = i; j < n; j += s[j] + 1)
				{
					s[j] = max (0, s[j] - 1);
				}
				res += 1;
				while (n > 0 && s[n - 1] <= 1)
				{
					n -= 1;
				}
			}
		}
		writeln (res);
	}
}

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

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

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

        auto a = readln.splitter.map!(to!int).array;

        debug { a.writeln; }

        auto incoming = new int[] (a.length + 1);

        long ans = 0;
        foreach (i, e; a) {
            int inside = min(e, a.length - i - 1);
            foreach (step; (inside+1).iota.drop(2)) {
                ++incoming[i + step];
            }

            auto additional = max(0, e - 1 - incoming[i]);
            ans += additional;
        }

        ans.writeln;
    }
}


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

alias Tuple!(int, "l", int, "r") Query;

class BIT {
    int n;
    int[] t;

    this(int n) {
        this.n = n;
        t = new int[n];
    }

    void inc(int x) {
        for (++x; x <= n; x += x & -x)
            ++t[x - 1];
    }

    int get(int x) {
        int res = 0;
        for (; x; x -= x & -x)
            res += t[x - 1];
        return res;
    }
}

void main() {
    int n, m;
    int[] p;
    Query[] q;

    scanf(" %d %d", &n, &m);
    p = new int[n];
    foreach (i; 0..n) scanf(" %d", &p[i]);
    q = new Query[m];
    foreach (i; 0..m) scanf(" %d %d", &q[i].l, &q[i].r), --q[i].l;

    int ma = reduce!max(p);

    int[] loc = new int[ma + 1];
    loc[] = -1;
    foreach (i; 0..n) loc[p[i]] = i;

    int[][] adj = new int[][n + 1];
    foreach (d; 1..ma + 1) {
        for (int dd = d; dd <= ma; dd += d) {
            int x = loc[d], y = loc[dd];
            if (x == -1 || y == -1) continue;
            if (x < y) swap(x, y);
            adj[x] ~= y;
        }
    }

    int[][] ln = new int[][n + 1];
    foreach (i; 0..m) {
        ln[q[i].r] ~= i;
    }

    int[] ans = new int[m];
    BIT t = new BIT(n);
    foreach (r; 0..n + 1) {
        foreach (i; ln[r]) ans[i] = t.get(r) - t.get(q[i].l);
        foreach (y; adj[r]) t.inc(y);
    }

    foreach (a; ans) printf("%d\n", a);
}

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

alias Tuple!(int, "l", int, "r") Query;

class BIT {
    int n;
    int[] t;

    this(int n) {
        this.n = n;
        t = new int[n];
    }

    void inc(int x) {
        for (++x; x <= n; x += x & -x)
            ++t[x - 1];
    }

    int get(int x) {
        int res = 0;
        for (; x; x -= x & -x)
            res += t[x - 1];
        return res;
    }
}

void main() {
    int n, m;
    scanf(" %d %d", &n, &m);
    auto p = new int[n];
    foreach (i; 0..n) scanf(" %d", &p[i]);
    auto q = new Query[m];
    foreach (i; 0..m) scanf(" %d %d", &q[i].l, &q[i].r), --q[i].l;

    int ma = reduce!max(p);

    auto loc = new int[ma + 1];
    loc[] = -1;
    foreach (i; 0..n) loc[p[i]] = i;

    auto adj = new int[][n + 1];
    foreach (d; p) {
        int x = loc[d];
        for (int dd = d; dd <= ma; dd += d) {
            int y = loc[dd]; if (y == -1) continue;
            if (x < y) adj[y] ~= x;
            else adj[x] ~= y;
        }
    }

    auto ln = new int[][n + 1];
    foreach (i; 0..m) ln[q[i].r] ~= i;

    auto ans = new int[m];
    BIT t = new BIT(n);
    foreach (r; 0..n + 1) {
        foreach (i; ln[r]) ans[i] = t.get(r) - t.get(q[i].l);
        foreach (y; adj[r]) t.inc(y);
    }

    foreach (a; ans) printf("%d\n", a);
}

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

alias Tuple!(int, "l", int, "r") Query;

class BIT {
    int n;
    long[] t;

    this(int n) {
        this.n = n;
        t = new long[n];
    }

    void inc(int x) {
        for (++x; x <= n; x += x & -x)
            ++t[x - 1];
    }

    long get(int x) {
        long res = 0;
        for (; x; x -= x & -x)
            res += t[x - 1];
        return res;
    }
}

void main() {
    int n, m;
    int[] p;
    Query[] q;

    scanf(" %d %d", &n, &m);
    p = new int[n];
    foreach (i; 0..n) scanf(" %d", &p[i]);
    q = new Query[m];
    foreach (i; 0..m) scanf(" %d %d", &q[i].l, &q[i].r), --q[i].l;

    int ma = reduce!max(p);

    int[] loc = new int[ma + 1];
    loc[] = -1;
    foreach (i; 0..n) loc[p[i]] = i;

    int[][] adj = new int[][n + 1];
    foreach (d; 1..ma + 1) {
        for (int dd = d; dd <= ma; dd += d) {
            int x = loc[d], y = loc[dd];
            if (x == -1 || y == -1) continue;
            if (x < y) swap(x, y);
            adj[x] ~= y;
        }
    }

    int[][] ln = new int[][n + 1];
    foreach (i; 0..m) {
        ln[q[i].r] ~= i;
    }

    long[] ans = new long[m];
    BIT t = new BIT(n);
    foreach (r; 0..n + 1) {
        foreach (i; ln[r]) ans[i] = t.get(r) - t.get(q[i].l);
        foreach (y; adj[r]) t.inc(y);
    }

    foreach (a; ans) writeln(a);
}