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 int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		ans[ti] = n / 2 + 1;
	}

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

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

void main () {
	foreach (t; 0..readln.strip.to !(int))
		writeln (readln.strip.to !(int) / 2 + 1);
}

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;

  void solve(long tc = -1)
  {
    writeln(n / 2 + 1);
  }
}

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

  void solve(long tc = -1)
  {
    if (n % 2 == 0)
      {
        writeln(n / 2 + 1);
      }
    else
      {
        writeln(n - 1);
      }
  }
}

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.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);

	long[] list = [1];
	while (true)
	{
		auto x = list[$-1] * 3;
		if (x < list[$-1])
			break;
		list ~= x;
	}

	foreach (i; 0..q)
	{
		auto n = RD!int;
		int pos;
		while (list[pos] < n)
		{
			++pos;
		}
		if (pos != 0)
			--pos;
		auto l = 2L^^pos;
		auto r = 2L^^(list.length);
		foreach (j; l..r)
		{
			long x;
			foreach (k; 0..32)
			{
				auto bit = 1L << k;
				if (j & bit)
				{
					x += list[k];
				}
			}
			if (x >= n)
			{
				ans[i] = x;
				break;
			}
		}
	}

	foreach (e; ans)
		writeln(e);

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

// https://codeforces.com/problemset/problem/1249/C1
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main() {
    int[] good;
    for(int mask = 1; mask < (1<<10); mask++) {
        int m = 0;
        for(int bit = 0; bit < 10; bit++) {
            if(mask&(1<<bit)) {
                m += 3^^bit;
            }
        }
        good ~= m;
    }
    foreach(line; stdin.byLine.dropOne) {
        int q = line.chomp.to!int;
        foreach(m; good) {
            if(m >= q) {
                m.writeln;
                break;
            }
        }
    }
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);

	long[] list = [1];
	while (true)
	{
		auto x = list[$-1] * 3;
		if (x < list[$-1])
			break;
		list ~= x;
	}
	list.reverse;
	debug writeln("a");

	foreach (loop; 0..q)
	{
		auto n = RD;
		long[] x;
		auto dp = new long[][](list.length+1);
		dp[0] = [0];
		foreach (i; 0..list.length)
		{
			foreach (j; 0..dp[i].length)
			{
				auto tmp = dp[i][j] + list[i];
				if (tmp >= n)
				{
					x ~= tmp;
					dp[i+1] ~= dp[i][j];
				}
				else if (dp[i][j] + list[i]*2 >= n)
				{
					dp[i+1] ~= tmp;
					dp[i+1] ~= dp[i][j];
				}
			}
		}
		debug writeln(x);
		debug writeln(dp);
		ans[loop] = x[x.MIN_POS];
	}

	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.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);

	long[] list = [1];
	while (true)
	{
		auto x = list[$-1] * 3;
		if (x < list[$-1])
			break;
		list ~= x;
	}

	foreach (i; 0..q)
	{
		auto n = RD!int;
		int pos;
		while (list[pos] < n)
		{
			++pos;
		}
		if (pos != 0)
			--pos;
		foreach (j; 2^^pos..2^^(list.length))
		{
			long x;
			foreach (k; 0..32)
			{
				auto bit = 1L << k;
				if (j & bit)
				{
					x += list[k];
				}
			}
			if (x >= n)
			{
				ans[i] = x;
				break;
			}
		}
	}

	foreach (e; ans)
		writeln(e);

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

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);

	long[] list = [1];
	while (true)
	{
		auto x = list[$-1] * 3;
		if (x < list[$-1])
			break;
		list ~= x;
	}

	foreach (i; 0..q)
	{
		auto n = RD!int;
		int pos;
		while (list[pos] < n)
		{
			++pos;
		}
		if (pos != 0)
			--pos;
		foreach (long j; 2^^pos..2^^(list.length))
		{
			long x;
			foreach (k; 0..32)
			{
				auto bit = 1L << k;
				if (j & bit)
				{
					x += list[k];
				}
			}
			if (x >= n)
			{
				ans[i] = x;
				break;
			}
		}
	}

	foreach (e; ans)
		writeln(e);

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


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;

void main ()
{
	string s;
	while ((s = readln ()) != "")
	{
		s = s.strip ();
		int [] x, y, z;
		x = [0];
		y = [0];
		z = [0];
		foreach (c; s)
		{
			x ~= x[$ - 1] + (c == 'x');
			y ~= y[$ - 1] + (c == 'y');
			z ~= z[$ - 1] + (c == 'z');
		}

		int q;
		readf (" %s", &q);
		foreach (i; 0..q)
		{
			int l, r;
			readf (" %s %s", &l, &r);
			int nx = x[r] - x[l - 1];
			int ny = y[r] - y[l - 1];
			int nz = z[r] - z[l - 1];
			int lo = min (nx, min (ny, nz));
			int hi = max (nx, max (ny, nz));
			writeln ((r - l < 2 || hi - lo <= 1) ? "YES" : "NO");
		}
	}
}

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

//  Input
string[] tokens;
int tokenId = 0;
string readToken() { for (; tokenId == tokens.length; ) tokens = readln.split, tokenId = 0; return tokens[tokenId++]; }

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, T f) { if (t > f) t = f; }
void chmax(T)(ref T t, T f) { if (t < f) t = f; }

immutable int MAXN = 100005;

int M;
string S;

int[100005][5] dp;

void main () {
    S = readToken();
    M = readInt();

    int A, B;

    foreach(int i; 0 .. to!int(S.length)) {
        dp[to!int(S[i] - 'x')][i + 1] += 1;

        foreach(int j; 0 .. 3) {
            dp[j][i +    1] += dp[j][i];
        }
    }

    foreach (int i; 0 .. M) {
        A = readInt();
        B = readInt();

        if (B - A < 2) {
            writeln("YES");
        } else {
            int[3] buff;

            foreach(int j; 0 .. 3) {
                buff[j] = dp[j][B] - dp[j][A - 1];
            }

            buff.sort;

            if (buff[2] <= buff[0] + 1) {
                writeln("YES");
            } else {
                writeln("NO");
            }
        }
    }
}

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;

void main ()
{
	string s;
	while ((s = readln ()) != "")
	{
		s = s.strip ();
		int [] x, y, z;
		x = [0];
		y = [0];
		z = [0];
		foreach (c; s)
		{
			x ~= x[$ - 1] + (c == 'x');
			y ~= y[$ - 1] + (c == 'y');
			z ~= z[$ - 1] + (c == 'z');
		}

		int q;
		readf (" %s", &q);
		foreach (i; 0..q)
		{
			int l, r;
			readf (" %s %s", &l, &r);
			int nx = x[r] - x[l - 1];
			int ny = y[r] - y[l - 1];
			int nz = z[r] - z[l - 1];
			int lo = min (nx, min (ny, nz));
			int hi = max (nx, max (ny, nz));
			writeln ((hi - lo <= 1) ? "YES" : "NO");
		}
	}
}


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;

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

		auto d = n.iota.array;
		sort !((a, b) => v[a] > v[b], SwapStrategy.stable) (d);
		long res = 0;
		foreach (x; d)
		{
			foreach (i; a[x])
			{
				res += v[i];
			}
			v[x] = 0;
		}

		writeln (res);
	}
}


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

  int n;
  rd(n);
  if (n % 3 < 2) {
    writeln(1, " ", 1, " ", n - 2);
  } else {
    writeln(1, " ", 2, " ", n - 3);
  }
}

void rd(T...)(ref T x) {
  import std.stdio, std.string, std.conv;

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

import std.stdio;
int main()
{
	int a=0;
	readf(" %s", &a);
	for (int i=0; i<a+1; i++)
	{
		if (i%3!=0)
		{
			int b=a-i;
			for (int j=0; j<b+1; j++)
			{
				if (j%3!=0)
				{
					if ((a-i-j)%3!=0)
					{
						writeln(i);
						writeln(j);
						writeln(a-i-j);
						return 0;
					}
				}
			}
		}
	}
	return 0;
}


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

string[string] map;

void main() {

	short n;

	scanf("%hd", &n);

	foreach (i; 0 .. n) {
		string a, b, c;
		a = readln(' ').strip();
		b = readln().strip();
		if (a !in map)
			map[a] = a;
		map[b] = map[a];
		map.remove(a);
	}

	writeln(map.length);

	foreach (i; map.keys)
		writeln(map[i], ' ', i);
}

import std.string;
import std.stdio;
import std.array;
void main() {
	int n;
	stdin.readf("%s\n", &n);
	int[string] map;
	string[1001] orig;
	string[1001] rmap;
	int count = 0;
	for (int i = 0; i < n; i++) {
		string line = stdin.readln();
		line = line.stripRight();
		string[] names = line.split();
		int *p = (names[0] in map);
		if (p is null) {
			//New name
			map[names[0]] = count++;
			orig[map[names[0]]] = names[0];
		}
		map[names[1]] = map[names[0]];
		rmap[map[names[0]]] = names[1];
	}
	stdout.writefln("%s", count);
	for (int i = 0; i < count; i++)
		stdout.writefln("%s %s", orig[i], rmap[i]);
}


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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;
		auto q = RD!int;
		auto x = new int[](q);
		auto k = new long[](q);
		foreach (i; 0..q)
		{
			x[i] = RD!int-1;
			k[i] = RD;
		}
		auto index = k.MAKE_IDX;

		ans[ti].length = q;
		foreach (i; 0..n)
		{
			while (!index.empty)
			{
				auto j = index.front;
				if (k[j] > i) break;
				ans[ti][j] = a[x[j]];
				index.popFront;
			}
			auto cnt = new int[](n);
			foreach (e; a)
				++cnt[e-1];
			foreach (j; 0..n)
				a[j] = cnt[a[j]-1];
		}
		while (!index.empty)
		{
			auto j = index.front;
			ans[ti][j] = a[x[j]];
			index.popFront;
		}
	}

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

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

bool transform(int[] a, int[] freq)
{
  freq[] = 0;
  bool changed = false;
  foreach (i ; 0 .. a.length) {
    freq[a[i]]++;
  }
  foreach (i ; 0 .. a.length) {
    int new_ai = freq[a[i]];
    if (new_ai != a[i])
      changed = true;
    a[i] = new_ai;
  }
  return changed;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.strip.split.map!(to!int).array;
    auto q = readln.strip.to!int;
    Tuple!(int, int, int, int)[] queries;
    foreach (i ; 0 .. q) {
      int xi, ki;
      readf!" %d %d "(xi, ki);
      queries ~= tuple(xi, ki, i, 0);
    }
    queries.sort!((x, y) => x[1] < y[1]);
    auto freq = new int[](n + 1);

    int curk = 0;
    bool done = false;
    foreach (ref tmp ; queries) {
      int nextk = tmp[1];
      while (curk < nextk && !done) {
        if (!transform(a, freq))
          done = true;
        curk++;
      }
      tmp[3] = a[tmp[0] - 1];
    }

    queries.sort!((x, y) => x[2] < y[2]);
    foreach (ref tmp ; queries) {
      writeln(tmp[3]);
    }
  }
}


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

void main ()
{
	int n;
	int m;
multitest_loop:
	while (readf (" %s %s", &n, &m) > 0)
	{
		alias Chord = Tuple !(int, q{a}, int, q{b});
		auto s = new Chord [m];
		bool [Chord] v;
		foreach (ref c; s)
		{
			readf (" %s %s", &c.a, &c.b);
			c.a -= 1;
			c.b -= 1;
			v[c] = true;
			swap (c.a, c.b);
			v[c] = true;
		}

		foreach (d; 1..n)
		{
			if (n % d != 0)
			{
				continue;
			}
			bool ok = true;
			foreach (ref c; s)
			{
				auto e = Chord ((c.a + d) % n, (c.b + d) % n);
				if (e !in v)
				{
					ok = false;
					break;
				}
			}
			if (ok)
			{
				writeln ("Yes");
				continue multitest_loop;
			}
		}
		writeln ("No");
	}
}

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

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

alias T = Tuple!(uint, uint);

void main() {
  rndGen.seed ((Clock.currTime.toHash & 0xffffffffU).to!uint);
  auto r = new InputReader;
  immutable n = r.next!uint, m = r.next!uint;
  auto a = uninitializedArray!(T[]) (m);
  bool[ulong] h;
  foreach (i; 0 .. m) {
    uint u = r.next!uint - 1, v = r.next!uint - 1;
    if (u > v) swap (u, v);
    a[i] = tuple (u, v);
    h[(u.to!ulong << 32) + v] = true;
  }
  randomShuffle (a);
  bool check (int k) {
    foreach (const p; a) {
      uint u = (p[0] + k) % n, v = (p[1] + k) % n;
      if (u > v) swap (u, v);
      if (! (((u.to!ulong << 32) + v) in h)) return false;
    }
    return true;
  }
  foreach (k; 1 .. n) {
    if (check (k)) {
      writeln ("Yes");
      return;
    }
  }
  writeln ("No");
}


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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, d;
		readf !(" %s %s") (n, d);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		writeln ((a[$ - 1] <= d || a[0] + a[1] <= d) ? "Yes" : "No");
	}
}

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        int N, D; get(N, D);
        int[] AS; get(AS);
        sort(AS);
        writeln(AS[$-1] <= D || (AS[0] + AS[1] <= D) ? "YES" : "NO");
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		a.sort();
		auto x = a[0] + a[1];
		ans[ti] = x <= d || a[$-1] <= d;
	}

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

import std.stdio, std.string, std.algorithm, std.conv, std.range;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int d;
        readf!"%d %d\n"(_, d);
        int[] a = readln.split.map!(to!int).array;
        a.sort();
        writeln(a[$ - 1] <= d || a[0] + a[1] <= d ? "YES" : "NO");
    }
}


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

void main() {
    int n;
    scan(n);

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

    int[int] r;

    foreach (i ; 0 .. n) {
        r[a[i]] = i;
    }

    int p = -1;
    int[] ans;

    foreach (i ; 0 .. n) {
        if (r[b[i]] < p) {
            ans ~= 0;
        }
        else {
            ans ~= r[b[i]] - p;
            p = r[b[i]];
        }
    }

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

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(a => a.to!int-1).array;
    auto B = readln.split.map!(a => a.to!int-1).array;
    auto used = new bool[](N);
    auto ans = new int[](N);

    for (int i = 0, j = 0; i < N; ++i) {
        if (used[B[i]]) continue;
        while (A[j] != B[i]) {
            ans[i] += 1;
            used[A[j]] = true;
            j += 1;
        }
        ans[i] += 1;
        used[A[j]] = true;
        j += 1;
    }

    ans.map!(to!string).join(" ").writeln;
}


import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
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;

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

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

    auto ans = 1, cur = 1;
    foreach (a, b; lockstep(arr, arr.dropOne)) {
        if (a*2 >= b) ++cur;
        else {
            ans = max(ans, cur);
            cur = 1;
        }
    }
    ans = max(ans, cur);

    ans.writeln;
}

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

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

  auto dp=new int[](n);
  dp[0]=1;
  foreach(i; 1..n){
    dp[i]=1;
    if(a[i]<=a[i-1]*2){
      dp[i]=max(dp[i], dp[i-1]+1);
    }
  }
  writeln(dp.reduce!(max));
}

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


import std.stdio;
import std.container;
import std.random;
import std.range;
import std.algorithm;
import std.typecons;
import std.conv;
import std.format;

int[] par;
long[] smallest;

int find_set(int v) {
	if (v == par[v]) return v;
	return par[v] = find_set(par[v]);
}

Mt19937 rng;

void unite(int a, int b) {
	a = find_set(a);
	b = find_set(b);
	if (rng.front % 2) swap(a, b);
	rng.popFront();
	par[b] = a;
	smallest[a] = min(smallest[a], smallest[b]);
}

void main()
{
	int n, m;
	stdin.byLine.front.formattedRead!"%d %d"(n, m);

	par = iota(n + 1).array;
	smallest = stdin.byLine.front.split(" ").map!`parse!long(a)`.array;

	auto S = redBlackTree!(Tuple!(long, int));
	auto offers = redBlackTree!(Tuple!(long, int, int));

	foreach (i, e; smallest) {
		S.insert(tuple(e, i.to!int));
	}

	for (int i = 0; i < m; i++) {
		int a, b;
		long w;
		stdin.byLine.front.formattedRead!"%d %d %d"(a, b, w);

		a--; b--;
		offers.insert(tuple(w, a, b));
	}

	long totalCost = 0;
	while (true) {
		if (S.length == 1) {
			writeln(totalCost);
			return;
		}

		while (offers.length > 0 && find_set(offers.front[1]) == find_set(offers.front[2]))
			offers.removeFront();

		auto c1 = S.front; S.removeFront();
		auto c2 = S.front; S.removeFront();
		auto cost = c1[0] + c2[0];

		if (offers.length > 0 && offers.front[0] < cost) {
			S.insert([c1, c2]);
			totalCost += offers.front[0];
			int x = offers.front[1];
			int y = offers.front[2];

			int setx = find_set(x);
			int sety = find_set(y);

			S.removeKey(tuple(smallest[setx], setx));
			S.removeKey(tuple(smallest[sety], sety));
			unite(x, y);
			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		} else {
			totalCost += cost;
			int x = c1[1];
			int y = c2[1];
			unite(x, y);

			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		}
	}
}

import std.stdio;
import std.container;
import std.random;
import std.range;
import std.algorithm;
import std.typecons;

int[] par;
long[] smallest;

int find_set(int v) {
	if (v == par[v]) return v;
	return par[v] = find_set(par[v]);
}

Mt19937 rng;

void unite(int a, int b) {
	a = find_set(a);
	b = find_set(b);
	if (rng.front % 2) swap(a, b);
	rng.popFront();
	par[b] = a;
	smallest[a] = min(smallest[a], smallest[b]);
}

void main()
{
	par = iota(200000).array;
	smallest = new long[200000];

	int n, m;
	scanf("%d%d", &n, &m);

	auto S = redBlackTree!(Tuple!(long, int));
	auto offers = redBlackTree!(Tuple!(long, int, int));

	for (int i = 0; i < n; i++) {
		long x;
		scanf("%lld", &x);
		smallest[i] = x;

		S.insert(tuple(x, i));
	}

	for (int i = 0; i < m; i++) {
		int a, b;
		long w;
		scanf("%d%d%lld", &a, &b, &w);
		a--; b--;
		offers.insert(tuple(w, a, b));
	}

	long totalCost = 0;
	while (true) {
		if (S.length == 1) {
			writeln(totalCost);
			return;
		}

		while (offers.length > 0 && find_set(offers.front[1]) == find_set(offers.front[2]))
			offers.removeFront();

		auto c1 = S.front; S.removeFront();
		auto c2 = S.front; S.removeFront();
		auto cost = c1[0] + c2[0];

		if (offers.length > 0 && offers.front[0] < cost) {
			S.insert([c1, c2]);
			totalCost += offers.front[0];
			int x = offers.front[1];
			int y = offers.front[2];

			int setx = find_set(x);
			int sety = find_set(y);

			S.removeKey(tuple(smallest[setx], setx));
			S.removeKey(tuple(smallest[sety], sety));
			unite(x, y);
			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		} else {
			totalCost += cost;
			int x = c1[1];
			int y = c2[1];
			unite(x, y);

			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		}
	}
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = readln.split.map!(to!long).array;
    auto X = new Tuple!(int, long)[][](N);
    foreach (i; 0..M) {
        auto t = readln.split;
        auto u = t[0].to!int - 1;
        auto v = t[1].to!int - 1;
        auto w = t[2].to!long;
        X[u] ~= tuple(v, w);
        X[v] ~= tuple(u, w);
    }

    long ans = 0;
    int S = A.minIndex.to!int;
    auto pq = new BinaryHeap!(Array!(Tuple!(int, long)), "a[1] > b[1]")();
    auto used = new bool[](N);
    used[S] = true;

    foreach (i; 0..N) {
        if (i == S) continue;
        pq.insert(tuple(i, A[S] + A[i]));
    }

    foreach (t; X[S]) {
        pq.insert(tuple(t[0], t[1]));
    }

    while (!pq.empty) {
        auto t = pq.front;
        pq.removeFront;
        auto u = t[0];
        auto w = t[1];
        if (used[u]) continue;
        ans += w;
        used[u] = true;
        foreach (v; X[u]) {
            if (used[v[0]]) continue;
            pq.insert(tuple(v[0], v[1]));
        }
    }

    ans.writeln;
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = readln.split.map!(to!long).array;
    auto X = new Tuple!(int, long)[][](N);
    foreach (i; 0..M) {
        auto t = readln.split;
        auto u = t[0].to!int - 1;
        auto v = t[1].to!int - 1;
        auto w = t[2].to!long;
        X[u] ~= tuple(v, w);
        X[v] ~= tuple(u, w);
    }

    long ans = 0;
    int S = A.minIndex.to!int;
    auto pq = new BinaryHeap!(Array!(Tuple!(int, long)), "a[1] > b[1]")();
    auto used = new bool[](N);
    used[S] = true;

    foreach (i; 0..N) {
        if (i == S) continue;
        pq.insert(tuple(i, A[S] + A[i]));
    }

    foreach (t; X[0]) {
        pq.insert(tuple(t[0], t[1]));
    }

    while (!pq.empty) {
        auto t = pq.front;
        pq.removeFront;
        auto u = t[0];
        auto w = t[1];
        if (used[u]) continue;
        ans += w;
        used[u] = true;
        foreach (v; X[u]) {
            if (used[v[0]]) continue;
            pq.insert(tuple(v[0], v[1]));
        }
    }

    ans.writeln;
}

import std.stdio;
import std.container;
import std.random;
import std.range;
import std.algorithm;
import std.typecons;
import std.conv;
import std.format;

int[] par;
long[] smallest;

int find_set(int v) {
	if (v == par[v]) return v;
	return par[v] = find_set(par[v]);
}

Mt19937 rng;

void unite(int a, int b) {
	a = find_set(a);
	b = find_set(b);
	if (rng.front % 2) swap(a, b);
	rng.popFront();
	par[b] = a;
	smallest[a] = min(smallest[a], smallest[b]);
}

void main()
{
	par = iota(200000).array;

	int n, m;
	stdin.byLine.front.formattedRead!"%d %d"(n, m);

	auto S = redBlackTree!(Tuple!(long, int));
	auto offers = redBlackTree!(Tuple!(long, int, int));

	smallest = stdin.byLine.front.split(" ").map!`parse!long(a)`.array;

	smallest.writeln;

	foreach (i, e; smallest) {
		S.insert(tuple(e, i.to!int));
	}

	for (int i = 0; i < m; i++) {
		int a, b;
		long w;
		stdin.byLine.front.formattedRead!"%d %d %d"(a, b, w);

		a--; b--;
		offers.insert(tuple(w, a, b));
	}

	long totalCost = 0;
	while (true) {
		if (S.length == 1) {
			writeln(totalCost);
			return;
		}

		while (offers.length > 0 && find_set(offers.front[1]) == find_set(offers.front[2]))
			offers.removeFront();

		auto c1 = S.front; S.removeFront();
		auto c2 = S.front; S.removeFront();
		auto cost = c1[0] + c2[0];

		if (offers.length > 0 && offers.front[0] < cost) {
			S.insert([c1, c2]);
			totalCost += offers.front[0];
			int x = offers.front[1];
			int y = offers.front[2];

			int setx = find_set(x);
			int sety = find_set(y);

			S.removeKey(tuple(smallest[setx], setx));
			S.removeKey(tuple(smallest[sety], sety));
			unite(x, y);
			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		} else {
			totalCost += cost;
			int x = c1[1];
			int y = c2[1];
			unite(x, y);

			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		}
	}
}


import std.stdio;
import std.array: array, split;
import std.string: chomp;
import std.conv: to;
import std.algorithm: copy, sort, reverse, map, maxElement, minElement;

void main() {
	int n = readln.chomp.to!int;
	int[] b = readln.split.map!(to!int).array;
	int[] a = new int[n];
	b.copy(a);
	b.sort;

	if (a == b) {
		writeln("yes\n1 1");
	} else {
		int[] c;
		foreach(int i; 0..n) {
			if (a[i] != b[i]) {
				c ~= [i];
			}
		}
		int x = minElement(c);
		int y = maxElement(c);
		if (a[0..x] ~ a[x..y+1].reverse ~ a[y+1..n] == b) {
			writefln("yes\n%s %s", x+1, y+1);
		} else {
			writeln("no");
		}
	}
}

import std.stdio;
import std.string;
import std.array: array;
import std.conv: to;
import std.algorithm: reverse, map, max, isSorted;

void main() {
	int n = readln.chomp.to!int;
	long[] a = readln.split.map!(to!long).array;

	int from;
	int to;

	long last_max = a[0];
	long last = a[0];
	bool x = false;
	bool y = false;
	bool no = false;
	bool z = false;

	if (a.isSorted) {
		writeln("yes");
		writeln("1 1");
	} else if (a.reverse.isSorted) {
		writeln("yes");
		writefln("1 %s", a.count);
	} else {
	a.reverse;
	foreach (int i; 0..n) {
		if (a[i] < last && !y) {
			from = i-1;
			y = true;
		} else if (y && !z && a[i] > last) {
			if (a[i] < last_max) {
				writeln("no");
				no = true;
				break;
			} else {
				to = i-1;
			}
			z = true;
		} else if (z && a[i] < last) {
			writeln("no");
			no = true;
			break;
		}
		last = a[i];
		last_max = max(a[i], last_max);
	}
	if (!no) {
		if (to != 0) {
			writeln("yes");
			writefln("%s %s", from + 1, to + 1);
		} else if (a[$-1] >= a[from - 1]) {
			writeln("yes");
			writefln("%s %s", from + 1, a.count);
		} else {
			writeln("no");
		}
	}
	}
}

// https://codeforces.com/problemset/problem/451/B
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.stdio;
import std.string;

void main() {
    int n = readln.chomp.to!int;
    int[] a = readln.split.map!(to!int).array;

    int inversions = 0;
    int[] idx;

    foreach(i; 1..n-1) {
        int last = a[i]-a[i-1];
        int now = a[i+1]-a[i];

        last = last/abs(last);
        now = now/abs(now);

        if(last != now) {
            inversions += 1;
            idx ~= i;
            //writefln("una inversion en %d", i);
        }
    }

    if(inversions > 2) {
        writeln("no");
        return;
    }

    if(inversions == 0) {
        if(a.isSorted) {
            writeln("yes");
            writeln("1 1");
        }
        else {
            writeln("yes");
            writefln("1 %d", n);
        }
    } else if (inversions == 1) {
        int[] firsttry;
        for(int i = 0; i <= idx[0]; i++) {
            firsttry ~= a[i];
        }
        firsttry.sort;
        for(int i = idx[0]+1; i < n; i++) {
            firsttry ~= a[i];
        }
        if(firsttry.isSorted) {
            writeln("yes");
            writefln("1 %d", idx[0]+1);
            return;
        }
        int[] secondtry;
        for(int i = 0; i < idx[0]; i++) {
            secondtry ~= a[i];
        }
        int[] lastpart;
        for(int i = idx[0]; i < n; i++) {
            lastpart ~= a[i];
        }
        lastpart.sort;
        foreach(item; lastpart) {
            secondtry ~= item;
        }
        if(secondtry.isSorted) {
            writeln("yes");
            writefln("%d %d", idx[0]+1, n);
            return;
        } else {
            writeln("no");
            return;
        }
    } else {
        int idx1 = idx[0];
        int idx2 = idx[1];
        int[] test;
        int[] fin;
        for(int i = 0; i < idx[0]; i++)
            fin ~= a[i];
        for(int i = idx[0]; i <= idx[1]; i++)
            test ~= a[i];
        test.sort;
        foreach(item; test)
            fin ~= item;
        for(int i = idx[1]+1; i < n; i++)
            fin ~= a[i];
        if(fin.isSorted) {
            writeln("yes");
            writefln("%d %d", idx[0]+1, idx[1]+1);
        }
        else
            writeln("no");
    }
}

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

void main(){
    int n=readln.chomp.to!int;
    auto a=readln.splitter
                 .map!(to!int)
                 .array;
    if(isStrictlyMonotonic(a)){
        writefln!"yes \n1 1";
    }else{
        int l=0,r=n-1;
        while(l<=n && a[l+1]>a[l])
            l++;
        while(r>=1 && a[r-1]<a[r])
            r--;
        if(a[l..r+1].isStrictlyMonotonic!"a>b"){
            if((l==0 || a[l-1]<a[r])
                    && (r==n-1 || a[r+1]>a[l]))
                writefln!"yes\n%d %d"(l+1,r+1);
            else writeln("no");
        }
        else writeln("no");
    }
}

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

void main(){
    int n=readln.chomp.to!int;
    auto a=readln.splitter
                 .map!(to!int)
                 .array;
    if(isStrictlyMonotonic(a)){
        writefln!"yes\n1 1";
    }else{
        int l=0,r=n-1;
        while(l<=n && a[l+1]>a[l])
            l++;
        while(r>=1 && a[r-1]<a[r])
            r--;
        if(a[l..r+1].isStrictlyMonotonic!"a>b"){
            if((l==0 || a[l-1]<a[r])
                    && (r==n-1 || a[r+1]>a[l]))
                writefln!"yes\n%d %d"(l+1,r+1);
            else writeln("no");
        }
        else writeln("no");
    }
}

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

//	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, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	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)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, 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)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int N;
int[] A;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		A = new int[N];
		foreach (i; 0 .. N) {
			A[i] = readInt;
		}
		int[] sorted = A.dup;
		sorted.sort();
		int minPos = N, maxPos = -1;
		foreach (i; 0 .. N) {
			if (A[i] != sorted[i]) {
				chmin(minPos, i);
				chmax(maxPos, i);
			}
		}
		if (minPos <= maxPos) {
			A[minPos .. maxPos + 1].reverse;
			bool ok = true;
			foreach (i; 0 .. N) {
				if (A[i] != sorted[i]) {
					ok = false;
				}
			}
			if (ok) {
				writeln("yes");
				writeln(minPos + 1, " ", maxPos + 1);
			} else {
				writeln("no");
			}
		} else {
			writeln("yes");
			writeln("1 1");
		}
	}
	} catch (EOFException) {}
}

import std.stdio;
import std.string;
import std.array: array;
import std.conv: to;
import std.algorithm: reverse, map, max, isSorted;

void main() {
	int n = readln.chomp.to!int;
	int[] a = readln.split.map!(to!int).array;

	int from;
	int to;

	int last_max = a[0];
	int last = a[0];
	byte x = 0;
	bool y = false;
	bool no = false;

	if (a.reverse.isSorted) {
		writeln("yes");
		writefln("1 %s", a.count);
	} else {

	foreach (int i; 0..n) {
		if ((x == 0 && a[0] > a[1] || x == 1 && a[0] < a[1]) && a[i] < last && !y) {
			from = i-1;
			y = true;
		}
		if ((x == 0 && a[0] > a[1] || x == 1 && a[0] < a[1]) && a[i] > last) {
			if (a[i] < last_max) {
				writeln("no");
				no = true;
				break;
			} else {
				to = i;
			}
			x++;
		} else if (x && a[i] < last) {
			writeln("no");
			no = true;
			break;
		}
		last = i;
		last_max = max(i, last_max);
	}
	if (!no) {
		writeln("yes");
		writefln("%s %s", from + 1, to + 1);
	}
	}
}

import std.stdio;
import std.string;
import std.array: array;
import std.conv: to;
import std.algorithm: reverse, map, max, isSorted;

void main() {
	int n = readln.chomp.to!int;
	int[] a = readln.split.map!(to!int).array;

	int from;
	int to;

	int last_max = a[0];
	int last = a[0];
	bool x = false;
	bool y = false;
	bool no = false;
	bool z = false;

	if (a.isSorted) {
		writeln("yes");
		writeln("1 1");
	} else if (a.reverse.isSorted) {
		writeln("yes");
		writefln("1 %s", a.count);
	} else {
	a.reverse;
	foreach (int i; 0..n) {
		if (a[i] < last && !y) {
			from = i-1;
			y = true;
		} else if (y && !z && a[i] > last) {
			if (a[i] < last_max) {
				writeln("no");
				no = true;
				break;
			} else {
				to = i-1;
			}
			z = true;
		} else if (z && a[i] < last) {
			writeln("no");
			no = true;
			break;
		}
		last = a[i];
		last_max = max(a[i], last_max);
	}
	if (!no) {
		writeln("yes");
		writefln("%s %s", from + 1, to + 1);
	}
	}
}

import std.stdio;
import std.string;
import std.array: array;
import std.conv: to;
import std.algorithm: reverse, map, max, isSorted;

void main() {
	int n = readln.chomp.to!int;
	long[] a = readln.split.map!(to!long).array;

	int from;
	int to;

	long last_max = a[0];
	long last = a[0];
	bool x = false;
	bool y = false;
	bool no = false;
	bool z = false;

	if (a.isSorted) {
		writeln("yes");
		writeln("1 1");
	} else if (a.reverse.isSorted) {
		writeln("yes");
		writefln("1 %s", a.count);
	} else {
	a.reverse;
	foreach (int i; 0..n) {
		if (a[i] < last && !y) {
			from = i-1;
			y = true;
		} else if (y && !z && a[i] > last) {
			if (a[i] < last_max) {
				writeln("no");
				no = true;
				break;
			} else {
				to = i-1;
			}
			z = true;
		} else if (z && a[i] < last) {
			writeln("no");
			no = true;
			break;
		}
		last = a[i];
		last_max = max(a[i], last_max);
	}
	if (!no) {
		writeln("yes");
		if (to != 0) {
			writefln("%s %s", from + 1, to + 1);
		} else {
			writefln("%s %s", from + 1, a.count);
		}
	}
	}
}


import std.c.stdio;
import std.stdio;

void main() {
  int n; scanf("%d", &n);
  int a;
  int f = 0, z = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d", &a);
    if (a == 5) { f++; }
    else { z++; }
  }
  if (z == 0) {
    printf("-1\n");
    return;
  }
  if (f < 9) {
    printf("0\n");
    return;
  }
  int x = f / 9 * 9;
  for (int i = 0; i < x; i++) {
    printf("5");
  }
  for (int i = 0; i < z; i++) {
    printf("0");
  }
  printf("\n");
}

import std.stdio;

void main() {
    int n;
    scanf("%u", &n);

    int a5, a0;
    while(n--) {
		int t;
		scanf("%u", &t);

		if(t == 5) a5++;
		else a0++;
    }

	if(a0 == 0) {
		write(-1);
		return;
	}

	int m, c;

	foreach(i; 0..a5)
		if((m += 5) % 9 == 0) c = i + 1;

	if(!c)
		a0 = 1;

	while(c--) write(5);
	while(a0--) write(0);
}

import std.c.stdio;
import std.stdio;

void main() {
  int n; scanf("%d", &n);
  int a;
  int f = 0, z = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d", &a);
    if (a == 5) { f++; }
    else { z++; }
  }
  if (f < 9 || z == 0) {
    printf("0\n");
    return;
  }
  int x = f / 9 * 9;
  for (int i = 0; i < x; i++) {
    printf("5");
  }
  for (int i = 0; i < z; i++) {
    printf("0");
  }
  printf("\n");
}


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

int [] [] a;
bool [] b;
int [] d;
int n, m;

void recur (int w)
{
	if (b[w])
	{
		return;
	}
	b[w] = true;
	foreach (c; a[w])
	{
		recur (c);
	}
}

void main ()
{
	while (readf (" %s %s", &n, &m) > 0)
	{
		a = new int [] [n];
		d = new int [n];
		foreach (i; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u] ~= v;
			a[v] ~= u;
			d[u]++;
			d[v]++;
		}

		b = new bool [n];
		recur (0);
		bool ok = true;
		foreach (i; 0..n)
		{
			ok &= b[i];
		}

		auto s = new int [n + m + 1];
		foreach (i; 0..n)
		{
			s[d[i]]++;
		}
		debug {writeln (ok);}

		if (ok && s[1] == 2 && s[2] == n - 2)
		{
			writeln ("bus topology");
		}
		else if (ok && s[2] == n)
		{
			writeln ("ring topology");
		}
		else if (ok && s[1] == n - 1 && s[n - 1] == 1)
		{
			writeln ("star topology");
		}
		else
		{
			writeln ("unknown topology");
		}
	}
}

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

void main() {
    int m, n; readf("%d %d\n", &m, &n);
    int[] c = new int[m];
    foreach (i; 0 .. n) {
        int x, y; readf("%d %d\n", &x, &y); x--, y--;
        c[x]++, c[y]++;
    }
    if (!c.find(n).empty) {
        writeln("star topology");
    } else if (c.count(1) == 2 && c.count(2) == m - 2) {
        writeln("bus topology");
    } else if (c.count(2) == m) {
        writeln("ring topology");
    } else {
        writeln("unknown topology");
    }
}

module sigod.codeforces.p292B;

import std.algorithm;
import std.stdio;
import std.typecons;

private {
	enum BUS = "bus topology";
	enum RING = "ring topology";
	enum STAR = "star topology";
	enum UNKNOWN = "unknown topology";
}

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

	int[] vertex = new int[n];

	foreach (i; 0 .. m) {
		int x, y;
		stdin.readf(" %s %s", &x, &y);

		++vertex[x - 1];
		++vertex[y - 1];
	}

	vertex.sort();

	auto g = vertex.group();

	if (n == m + 1) {
		if (equal(g, [tuple(1, 2u), tuple(2, cast(uint) n - 2)][])) {
			stdout.writeln(BUS);
		}
		else if (equal(g, [tuple(1, n - 1), tuple(n - 1, 1)][])) {
			stdout.writeln(STAR);
		}
		else {
			stdout.writeln(UNKNOWN);
		}
	}
	else if (n == m && equal(g, [tuple(2, n)][])) {
		stdout.writeln(RING);
	}
	else {
		stdout.writeln(UNKNOWN);
	}
}

module sigod.codeforces.p292B;

import std.algorithm;
import std.stdio;
import std.typecons;

private {
	enum BUS = "bus topology";
	enum RING = "ring topology";
	enum STAR = "star topology";
	enum UNKNOWN = "unknown topology";
}

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

	byte[] vertex = new byte[n];

	foreach (i; 0 .. m) {
		int x, y;
		stdin.readf(" %s %s", &x, &y);

		++vertex[x - 1];
		++vertex[y - 1];
	}

	vertex.sort();

	auto g = vertex.group();

	if (n == m + 1) {
		if (equal(g, [tuple(1, 2u), tuple(2, cast(uint) n - 2)][])) {
			stdout.writeln(BUS);
		}
		else if (equal(g, [tuple(1, n - 1), tuple(n - 1, 1)][])) {
			stdout.writeln(STAR);
		}
		else {
			stdout.writeln(UNKNOWN);
		}
	}
	else if (n == m && equal(g, [tuple(2, n)][])) {
		stdout.writeln(RING);
	}
	else {
		stdout.writeln(UNKNOWN);
	}
}


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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto T = RD!int;
	foreach (i; 0..T)
	{
		auto n = RD!int;
		auto s = RD!int;
		auto t = RD!int;
		auto x = min(s, t);
		writeln(n - x + 1);
	}

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

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

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  immutable nt = r.next!int;
  foreach (tid; 0 .. nt) {
    immutable n = r.next!int;
    immutable s = r.next!int;
    immutable t = r.next!int;
    auto y = n - s;
    auto x = n - t;
    auto z = s - x;
    debug stderr.writefln ("x = %d, y = %d, z = %d", x, y, z);
    writeln (max (x, y) + 1);
  }
}


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

void solve(){
    long a = scan;
    long b = scan;
    long c = scan;
    long res = (a + c - 2*b) % 3;
    if(res != 0){
        writeln(1);
    }else{
        writeln(0);
    }
}

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

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

immutable multi = true;

void solve(int tc)
{
	int sum = readInt!int + readInt!int + readInt!int;
	switch (sum % 3)
	{
	case 0: return writeln(0);
	default: return writeln(1);
	}
}

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

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

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

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

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


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

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

    dchar[][] s;
    auto r = () => readln.chomp.to!(dchar[]);
    s ~= r();
    s ~= r();

    auto ans = 0;
    foreach (i; 0 .. n / 2) {
        auto c = [ s[0][i], s[1][i], s[0][n-1-i], s[1][n-1-i] ].sort();

        debug { c.writeln; }

        if (c[0] == c[1] && c[2] == c[3]) continue;

        auto s0arr = [s[0][i], s[0][n-1-i]].sort();
        auto s1arr = [s[1][i], s[1][n-1-i]].sort();

        debug { writeln(i, ": ", setIntersection(s0arr, s1arr)); }

        if (s[1][i] == s[1][n-1-i] || !setIntersection(s0arr, s1arr).empty()) ans += 1;
        else ans += 2;
    }

    if (n % 2 == 1 && s[0][n/2] != s[1][n/2]) ++ans;

    ans.writeln;
}

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

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

    dchar[][] s;
    auto r = () => readln.chomp.to!(dchar[]);
    s ~= r();
    s ~= r();

    auto ans = 0;
    foreach (i; 0 .. n / 2) {
        auto c = [ s[0][i], s[1][i], s[0][n-1-i], s[1][n-1-i] ].sort();

        debug { c.writeln; }

        if (c[0] == c[1] && c[2] == c[3]) continue;

        if (s[0][i] == s[1][i] || s[0][i] == s[1][n-1-i]
            || s[0][n-1-i] == s[1][i] || s[0][n-1-i] == s[1][n-1-i]
            || s[1][i] == s[1][n-1-i]) ans += 1;
        else ans += 2;
    }

    if (n % 2 == 1 && s[0][n/2] != s[1][n/2]) ++ans;

    ans.writeln;
}

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

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

    dchar[][] s;
    auto r = () => readln.chomp.to!(dchar[]);
    s ~= r();
    s ~= r();

    auto ans = 0;
    foreach (i; 0 .. n / 2) {
        auto c = [ s[0][i], s[1][i], s[0][n-1-i], s[1][n-1-i] ].sort();

        debug { c.writeln; }

        if (c[0] == c[1] && c[2] == c[3]) continue;

        ans += min(2, cast(int)(c[0] != c[1]) + cast(int)(c[1] != c[2]) + cast(int)(c[2] != c[3]));
    }

    if (n % 2 == 1 && s[0][n/2] != s[1][n/2]) ++ans;

    ans.writeln;
}

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

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

    dchar[][] s;
    auto r = () => readln.chomp.to!(dchar[]);
    s ~= r();
    s ~= r();

    auto ans = 0;
    foreach (i; 0 .. n / 2) {
        auto c = [ s[0][i], s[1][i], s[0][n-1-i], s[1][n-1-i] ].sort();

        debug { c.writeln; }

        if (c[0] == c[1] && c[2] == c[3]) continue;

        if (s[0][i] == s[1][i] || s[0][i] == s[1][n-1-i]
            || s[0][n-1-i] == s[1][i] || s[0][n-1-i] == s[1][n-1-i]) ans += 1;
        else ans += 2;
    }

    if (n % 2 == 1 && s[0][n/2] != s[1][n/2]) ++ans;

    ans.writeln;
}


import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.functional;
import std.numeric;
import std.range;
import std.stdio;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (ref x; a)
		{
			readf (" %d", &x);
		}
		sort !("a < b", SwapStrategy.stable) (a);
		long res;
		foreach (i, c; a)
		{
			res += cast (long) (i + 2) * c;
		}
		res -= a[$ - 1];
		writeln (res);
	}
}

import std.algorithm;
import std.stdio;

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

    auto a = new long[n];
    foreach(i; 0..n) readf(" %s", a[i]);

    a.sort();

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

import std.stdio;
import std.math;
import std.array;
import std.algorithm;

unittest{
  assert(solve([3,1,5]) == 26, "Teste 1");
  assert(solve([10]) == 10, "Teste 1");
}

ulong solve(ulong[] l){
  sort!("a > b")(l);

  auto sum = l.length*l[0];
  foreach(i,x; l[1..$]){
    sum += (l.length-i)*x;
  }

  debug(1) writeln(l[1..$]);
  debug(1) writeln(sum);
  return sum;
}

void main(){
  size_t n;
  readf("%s\n",&n);

  ulong[] l = new ulong[n];
  for(ulong i = 0; i < n; i++){
    readf("%s ",l.ptr+i);
  }
  writeln(solve(l));
}

module main;

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

void solve(int[] a)
{
    sort(a);
    long ans = 0, sum = 0;
    for (int i = a.length - 1; i >= 0; -- i)
    {
        sum += a[i];
        ans += sum;
    }
    ans -= a[$ - 1];
    ans += sum;
    writefln("%d", ans);
}

int main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
        auto a = new int[n];
        foreach (i, ref v; a)
        {
            scanf("%d", &v);
        }
        solve(a);
    }
    return 0;
}

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

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

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

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

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

int N;
long[] A;

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

		long ans;
		auto q = BinaryHeap!(Array!long)();
		foreach (a; A) {
			ans += a;
			q.insert(a);
		}
		for (; ; ) {
			const a = q.front; q.removeFront;
			if (q.empty) {
				break;
			}
			const b = q.front; q.removeFront;
			ans += a + b;
			q.insert(a + b);
		}
		writeln(ans);
	}
	} catch (EOFException) {}
}

import std.algorithm;
import std.stdio;

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

    auto a = new int[n];
    foreach(i; 0..n) readf(" %s", a[i]);

    a.sort();

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


// Vicfred
// https://codeforces.com/contest/1437/problem/B
// string manipulation, greedy
import std.algorithm;
import std.stdio;

void main() {
    long t;
    readf("%s\n", &t);

    long n;
    string s;
    while(t--) {
        readf("%s\n%s\n", &n, &s);
        long ans = n - s.count("10") - s.count("01");
        (ans/2).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.strip;
		int cur = 1;
		foreach (i; 1..n)
		{
			cur += (s[i - 1] == s[i]);
		}
		writeln (cur / 2);
	}
}


module p268C;

import std.algorithm : min;
import std.array : split;
import std.conv : to;
import std.stdio;
import std.string : strip;

void main() {
	read();

	int n = get!int(0);
	int m = get!int(1);

	solve(n, m);
}

void solve(int n, int m) {
	int min = min(n, m);

	stdout.writeln(min + 1);

	foreach (i; 0 .. min + 1) {
		stdout.writeln(i, " ", min - i);
	}
}

private {
	string[] temp;

	void read() {
		temp = split(strip(stdin.readln()));
	}

	T get(T)(int p) {
		return to!(T)(temp[p]);
	}
}

module sigod.codeforces.p268C;

import std.algorithm : min;
import std.stdio;

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

	solve(n, m);
}

void solve(int n, int m) {
	int min = min(n, m);

	stdout.writeln(min + 1);

	foreach (i; 0 .. min + 1) {
		stdout.writeln(i, " ", min - i);
	}
}

import std.array : split;
import std.conv : to;
import std.math : abs, sqrt, pow, trunc;
import std.stdio;
import std.string : strip;

private {
	string[] temp;
	int N, M;
}

void main() {
	read();

	N = get!int(0);
	M = get!int(1);

	int[][] max;

	foreach (x; 0 .. N + 1) {
		foreach (y; 0 .. M + 1) {
			if (x + y == 0) continue;

			auto current = p(x, y);

			version (unittest) {
				stdout.writeln("current: ", current);
			}

			if (current.length > max.length) {
				max = current.dup;
			}
		}
	}

	stdout.writeln(max.length);
	foreach (point; max) {
		stdout.writeln(point[0], " ", point[1]);
	}
}

int[][] p(int start_x, int start_y) {
	int x = start_x,
		y = start_y + 1;

	int[][] result = [[start_x, start_y]];

	while (x <= N) {
		if (x != start_x) y = 0;

		while (y <= N) {
			if (isValid(result, x, y)) {
				result ~= [x, y];
			}

			++y;
		}

		++x;
	}

	if (result.length == 1) {
		result.length = 0;
	}

	return result;
}

bool isValid(int[][] array, int x, int y) {
	foreach (point; array) {
		if (!isValidLength(point[0], point[1], x, y))
			return false;
	}

	return true;
}

bool isValidLength(int x1, int y1, int x2, int y2) {
	auto length = sqrt(cast(float) (pow(x2 - x1, 2) + pow(y2 - y1, 2)));

	version (unittest) {
		stdout.writeln("isValidLength: [", x1, ", ", y1, "], [", x2, ", ", y2, "] = ", length);
	}

	return abs(length - trunc(length)) > 0.000000001;
}

void read() {
	temp = split(strip(stdin.readln()));
}

T get(T)(int p) {
	return to!(T)(temp[p]);
}

import std.array : split;
import std.conv : to;
import std.math : abs, sqrt, pow, trunc;
import std.stdio;
import std.string : strip;

private {
	string[] temp;
	int N, M;
}

void main() {
	read();

	N = get!int(0);
	M = get!int(1);

	int[][] max;

	foreach (x; 0 .. N + 1) {
		foreach (y; 0 .. M + 1) {
			if (x + y == 0) continue;

			auto current = p(x, y);

			version (unittest) {
				stdout.writeln("current: ", current);
			}

			if (current.length > max.length) {
				max = current.dup;
			}
		}
	}

	stdout.writeln(max.length);
	foreach (point; max) {
		stdout.writeln(point[0], " ", point[1]);
	}
}

int[][] p(int start_x, int start_y) {
	int x = start_x,
		y = start_y + 1;

	int[][] result = [[start_x, start_y]];

	while (x <= N) {
		if (x != start_x) y = 0;

		while (y <= N) {
			if (isValid(result, x, y)) {
				result ~= [x, y];
			}

			++y;
		}

		++x;
	}

	return result;
}

bool isValid(int[][] array, int x, int y) {
	foreach (point; array) {
		if (!isValidLength(point[0], point[1], x, y))
			return false;
	}

	return true;
}

bool isValidLength(int x1, int y1, int x2, int y2) {
	auto length = sqrt(cast(float) (pow(x2 - x1, 2) + pow(y2 - y1, 2)));

	version (unittest) {
		stdout.writeln("isValidLength: [", x1, ", ", y1, "], [", x2, ", ", y2, "] = ", length);
	}

	return abs(length - trunc(length)) > 0.000000001;
}

void read() {
	temp = split(strip(stdin.readln()));
}

T get(T)(int p) {
	return to!(T)(temp[p]);
}