Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. He thinks that each student will take place equal to . In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position. GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.

The first line contains integer n (1 ≤ n ≤ 2000), number of GukiZ's students.  The second line contains n numbers a1, a2, ... an (1 ≤ ai ≤ 2000) where ai is the rating of i-th student (1 ≤ i ≤ n).

In a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.

NoteIn the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.In the second sample, first student is the only one on the contest.In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position.

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

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

        int read_int() {
                return read_string.to!int;
        }

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

int count_greater(ref int[] a1, int n) {
        int count = 0;
        for (int i = 0; i < a1.length; i++) {
                if (a1[i] > n) {
                        count++;
                }
        }
        return count;
}

void main() {
        IO cin;
        int t = 1;
        // int t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                int[] arr = new int[n];
                foreach (ref i; arr) {
                        i = cin.read_int;
                }
                for (int i = 0; i < n; i++) {
                        write(count_greater(arr, arr[i]) + 1, " ");
                }
                writeln();
        }
}

version (all) {
import std.math,
       std.conv,
       std.stdio,
       std.ascii,
       std.range,
       std.array,
       std.regex,
       std.format,
       std.bigint,
       std.traits,
       std.random,
       std.string,
       std.numeric,
       std.variant,
       std.typecons,
       std.container,
       std.algorithm,
       std.typetuple,
       std.exception,
       core.checkedint;
}

void main() {

	readln.strip;
	auto a = readln.split.map!(to!uint).array;

	foreach (el; a) {
		write(1 + a.filter!(c => c > el).array.length, ' ');
	}

	writeln();
}

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

alias isEven = unaryFun!("(a & 1) == 0");
alias isOdd =  unaryFun!("(a & 1) != 0");

void readInput()
{
	size_t lineSize;

	auto studentCount = stdin.readln.chomp().to!int();

	auto grades = stdin.readln().split().map!(a => to!int(a)).array;

	int[int] indexHolder;
	auto realGrades = grades.dup;
	grades.sort!"a > b"();
	int lastGrade = 0;
	int lastElem = 0;

	foreach (i, elem; grades)
	{
		if ( lastElem != elem)
		{
			lastElem = elem;
			lastGrade = i + 1;
			indexHolder[elem] = lastGrade;
		}
	}

	writeln(realGrades.map!( a => to!string(indexHolder[a])).joiner(" "));

}

void main(  string[] args )
{
	readInput();
}

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

alias isEven = unaryFun!("(a & 1) == 0");
alias isOdd =  unaryFun!("(a & 1) != 0");

void readInput()
{
	size_t lineSize;

	auto studentCount = stdin.readln.chomp().to!int();

	auto grades = stdin.readln().split().map!(a => to!int(a)).array;

	int[int] indexHolder;
	auto realGrades = grades.dup;
	grades.sort!"a > b"();
	int lastGrade = 0;
	int lastElem = 0;

	foreach (i, elem; grades)
	{
		if ( lastElem != elem)
		{
			lastElem = elem;
			lastGrade = i + 1;
			indexHolder[elem] = lastGrade;
		}
	}

	writeln(realGrades.map!( a => indexHolder[a]));

}

void main(  string[] args )
{
	readInput();
}

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

alias isEven = unaryFun!("(a & 1) == 0");
alias isOdd =  unaryFun!("(a & 1) != 0");

void readInput()
{
	size_t lineSize; ;

	auto studentCount = stdin.readln.chomp().to!int();

	auto grades = stdin.readln().split().map!(a => to!int(a)).array;

	int[int] indexHolder;
	auto realGrades = grades.dup;
	grades.sort!"a > b"();
	int lastGrade = 0;
	int lastElem = 0;

	foreach (i, elem; grades)
	{
		if ( lastElem != elem)
		{
			lastElem = elem;
			lastGrade = i + 1;
			indexHolder[elem] = lastGrade;
		}
	}

	writeln(realGrades.map!( a => indexHolder[a]));

}

void main(  string[] args )
{
	readInput();
}


$$$2^k$$$ teams participate in a playoff tournament. The tournament consists of $$$2^k - 1$$$ games. They are held as follows: first of all, the teams are split into pairs: team $$$1$$$ plays against team $$$2$$$, team $$$3$$$ plays against team $$$4$$$ (exactly in this order), and so on (so, $$$2^{k-1}$$$ games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only $$$2^{k-1}$$$ teams remain. If only one team remains, it is declared the champion; otherwise, $$$2^{k-2}$$$ games are played: in the first one of them, the winner of the game "$$$1$$$ vs $$$2$$$" plays against the winner of the game "$$$3$$$ vs $$$4$$$", then the winner of the game "$$$5$$$ vs $$$6$$$" plays against the winner of the game "$$$7$$$ vs $$$8$$$", and so on. This process repeats until only one team remains.For example, this picture describes the chronological order of games with $$$k = 3$$$:  Let the string $$$s$$$ consisting of $$$2^k - 1$$$ characters describe the results of the games in chronological order as follows:  if $$$s_i$$$ is 0, then the team with lower index wins the $$$i$$$-th game;  if $$$s_i$$$ is 1, then the team with greater index wins the $$$i$$$-th game;  if $$$s_i$$$ is ?, then the result of the $$$i$$$-th game is unknown (any team could win this game). Let $$$f(s)$$$ be the number of possible winners of the tournament described by the string $$$s$$$. A team $$$i$$$ is a possible winner of the tournament if it is possible to replace every ? with either 1 or 0 in such a way that team $$$i$$$ is the champion.You are given the initial state of the string $$$s$$$. You have to process $$$q$$$ queries of the following form:   $$$p$$$ $$$c$$$ — replace $$$s_p$$$ with character $$$c$$$, and print $$$f(s)$$$ as the result of the query.

The first line contains one integer $$$k$$$ ($$$1 \le k \le 18$$$). The second line contains a string consisting of $$$2^k - 1$$$ characters — the initial state of the string $$$s$$$. Each character is either ?, 0, or 1. The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow, the $$$i$$$-th line contains an integer $$$p$$$ and a character $$$c$$$ ($$$1 \le p \le 2^k - 1$$$; $$$c$$$ is either ?, 0, or 1), describing the $$$i$$$-th query.

For each query, print one integer — $$$f(s)$$$.

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

int[] phasebase;
int[] fights;
byte[] a;
long[long] cache;

long solve(int phase, int fightnum)
{
  byte outcome = a[phasebase[phase] + fightnum];
  if (phase == 0)
    return outcome == 3 ? 2 : 1;

  long cacheid = cast(long)fightnum * 20 + cast(long)phase;
  long result = cache.get(cacheid, -1);
  if (result != -1)
    return result;
  result = 0;

  if (outcome & 1) {
    result += solve(phase - 1, fightnum * 2 + 0);
  }
  if (outcome & 2) {
    result += solve(phase - 1, fightnum * 2 + 1);
  }
  cache[cacheid] = result;
  return result;
}

void invalidate_cache(int idx)
{
  int phase = 0;
  while (true) {
    if (idx >= phasebase[phase] && idx < phasebase[phase] + fights[phase]) {
      int fightnum = idx - phasebase[phase];

      while (phase < phasebase.length) {
        long cacheid = cast(long)fightnum * 20 + cast(long)phase;
        cache[cacheid] = -1;
        fightnum /= 2;
        phase++;
      }
      return;
    }
    phase++;
  }
}

void main()
{
  int k, t;
  readf!" %d "(k);
  a = readln.strip.split("").map!((x) => (x[0] == '?') ? cast(byte)3 : (x[0] == '0' ? cast(byte)1 : cast(byte)2)).array;
//  writeln(a);
  assert(k == bsf(a.length + 1));
  k = bsf(a.length + 1);
  int pb = 0;
  while (k != 0) {
    phasebase ~= pb;
    k--;
    fights ~= 1 << k;
    pb += (1 << k);
  }
//  writeln(phasebase);
//  writeln(fights);
//  writeln("---");
  readf!" %d "(t);
  while (t--) {
    int i;
    readf!" %d"(i);
    string x = readln.strip;
    a[i - 1] = (x[0] == '?') ? cast(byte)3 : (x[0] == '0' ? cast(byte)1 : cast(byte)2);
//    writeln(a);

    // cache.clear();
    invalidate_cache(i - 1);

    writeln(solve(bsf(a.length + 1) - 1, 0));
  }
}

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

void main ()
{
	int k;
	while (readf !(" %s") (k) > 0)
	{
		readln;
		auto s = readln.strip.dup ~ '*';
		reverse (s);
		auto m = 1 << k;
		auto f = new int [m * 2];
		f[] = 1;

		void calc (int pos)
		{
			f[pos] = (s[pos] == '0') ? f[pos * 2 + 1] :
			    (s[pos] == '1') ? f[pos * 2 + 0] :
			    f[pos * 2 + 0] + f[pos * 2 + 1];
		}

		foreach_reverse (pos; 1..m)
		{
			calc (pos);
		}

		auto q = readln.strip.to !(int);
		foreach (r; 0..q)
		{
			auto t = readln.split;
			auto pos = t[0].to !(int);
			pos = m - pos;
			s[pos] = t[1][0];
			for ( ; pos > 0; pos >>= 1)
			{
				calc (pos);
			}
			writeln (f[1]);
		}
	}
}

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

int main()
{
    int k = readInt!int;
    char[] s = readString.dup.reverse;
    int n = cast(int)s.length;
    int q = readInt!int;

    long[] pos = new long[](n + 1);
    void calculate(int v)
    {
        if (v * 2 > s.length)
        {
            if (s[v - 1] == '0' || s[v - 1] == '1') pos[v] = 1;
            else pos[v] = 2;
            return;
        }
        int left = 2 * v;
        int right = 2 * v + 1;
        calculate(left);
        calculate(right);
        if (s[v - 1] == '1')
        {
            pos[v] = pos[left];
        }
        else if (s[v - 1] == '0')
        {
            pos[v] = pos[right];
        }
        else
        {
            pos[v] = pos[right] + pos[left];
        }
    }
    calculate(1);
    foreach(qi; 0 .. q)
    {
        int p = n - readInt!int + 1;
        string ch = readString;
        s[p - 1] = ch[0];
        while (p >= 1)
        {
            if (p * 2 >= n)
            {
                if (s[p - 1] == '0' || s[p - 1] == '1') pos[p] = 1;
                else pos[p] = 2;
                goto done;
            }
            if (s[p - 1] == '1')
            {
                pos[p] = pos[2 * p];
            }
            else if (s[p - 1] == '0')
            {
                pos[p] = pos[2 * p + 1];
            }
            else
            {
                pos[p] = pos[2 * p] + pos[2 * p + 1];
            }
            done:
            p /= 2;
        }
        pos[1].writeln;
    }
    return 0;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
    currChar = getchar();
}
char topChar()
{
    return cast(char) currChar;
}
void popChar()
{
    currChar = getchar();
}
auto readInt(T)()
{
    T num = 0;
    int sgn = 0;
    while (topChar.isWhite) popChar;
    while (topChar == '-' || topChar == '+') { sgn ^= (topChar == '-'); popChar; }
    while (topChar.isDigit) { num *= 10; num += (topChar - '0'); popChar; }
    if (sgn) return -num; return num;
}
string readString()
{
    string res = "";
    while (topChar.isWhite) popChar;
    while (!topChar.isWhite) { res ~= topChar; popChar; }
    return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
    long rep;
    this(long num)
    {
        rep = num;
    }
    Z!m opBinary(string operator)(Z!m rhs)
    {
        static if (operator == "+")
        {
            long result = rhs.rep + this.rep;
            if (result >= m) result -= m;
            return Z!m(result);
        }
        else static if (operator == "-")
        {
            long result = this.rep - rhs.rep;
            if (result < 0) result += m;
            return Z!m(result);
        }
        else static if (operator == "*")
        {
            long result = this.rep * rhs.rep;
            if (result >= m) result %= m;
            return Z!m(result);
        } else static assert(text("Operator ", operator, " not supported"));
    }
    Z!m opBinary(string operator)(long exponent) if (operator == "^^")
    {
        assert(exponent >= 0);
        Z!m base = this;
        Z!m result = 1;
        while (exponent)
        {
            if (exponent & 1)
                result = result * base;
            base = base * base;
            exponent >>= 1;
        }
        return result;
    }
    invariant
    {
        assert(rep >= 0 && rep < m);
    }
}


You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$) — the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.

Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).

5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c

NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.

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

void main() {
	int tc;
	scanf("%d\n", &tc);

	while (tc--) {
		int n, m;
		scanf("%d%d\n", &n, &m);

		string[] arr = new string[n];
		for (int i = 0; i < n; i++)
			arr[i] = stdin.byLine.front.to!string;

		string answer = null;
		check: foreach(s; arr) {
			foreach(i; iota(m)) {
				for (char c = 'a'; c <= 'z'; c++) {
					char[] test_string = s.dup;
					test_string[i] = c;

					// test the string
					bool good = true;
					foreach (t; arr) {
						int d = 0;
						foreach (j, e; t) d += e != test_string[j];
						if (d > 1) {
							good = false;
							break;
						}
					}

					if (good) {
						answer = test_string.dup;
						break check;
					}
				}
			}
		}

		if (answer == null) writeln(-1);
		else answer.writeln;
	}
}

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()
{
    int t;
    readf("%s", &t);
    readln;

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

        string[] input;
        foreach (i; 0 .. n) {
            input ~= readln.chomp;
        }

        auto ans = input[0].to!(dchar[]);
        foreach (col; 0 .. m) {

            foreach (row; 0 .. n) {
                ans[col] = input[row][col];

                bool ok = true;
                foreach (compareidx; 0 .. n) {
                    ok &= zip(ans, input[compareidx]).filter!"a[0] != a[1]".array.length <= 1;
                }

                if (ok) {
                    writeln(ans);
                    continue outer;
                }
            }

            ans[col] = input[0][col];
        }

        writeln(-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, m;
  @Dim("n") string[] a;

  void solve(long tc = -1)
  {
    bool test(string str)
    {
      return iota(0, n)
        .all!(j => iota(0, m).count!(i => a.at(j).at(i) != str.at(i)) <= 1);
    }

    char[] ts = a.at(0).dup;
    foreach(i; 0 .. m)
      {
        foreach(c; 'a' .. cast(char)('z' + 1))
          {
            ts.at(i) = c;
            if (test(cast(string) ts))
              {
                writeln(ts);
                return;
              }
          }
        ts.at(i) = a.at(0).at(i);
      }
    writeln(-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.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

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

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

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

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

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

		if (n == 1)
		{
			ans[ti] = s[0];
			continue;
		}

		auto used = new bool[][](m, 26);
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				auto num = s[i][j]-'a';
				used[j][num] = true;
			}
		}

		int[][string] dp;
		dp[""] = new int[](n);
		foreach (i; 0..m)
		{
			int[][string] ndp;
			foreach (j; 0..26)
			{
				if (used[i][j] == false) continue;
				auto c = cast(char)('a'+j);
				foreach (key; dp.keys)
				{
					auto str = key ~ c;
					auto cnt = dp[key].dup;
					bool ok = true;
					foreach (k; 0..n)
					{
						if (s[k][i] != c)
						{
							++cnt[k];
							if (cnt[k] >= 2)
							{
								ok = false;
								break;
							}
						}
					}
					if (ok)
					{
						ndp[str] = cnt;
					}
				}
			}
			dp = ndp;
		}
		if (!dp.empty)
		{
			ans[ti] = dp.keys[0];
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln(-1);
		else
			writeln(e);
	}
	stdout.flush;
	debug readln;
}


You're given a tree with $$$n$$$ vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) denoting the size of the tree.  The next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ ($$$1 \le u, v \le n$$$) each, describing the vertices connected by the $$$i$$$-th edge. It's guaranteed that the given edges form a tree.

Output a single integer $$$k$$$ — the maximum number of edges that can be removed to leave all connected components with even size, or $$$-1$$$ if it is impossible to remove edges in order to satisfy this property.

NoteIn the first example you can remove the edge between vertices $$$1$$$ and $$$4$$$. The graph after that will have two connected components with two vertices in each.In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is $$$-1$$$.

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

void main() {
    auto N = readln.chomp.to!int;
    auto G = new int[][](N);
    foreach (_; 0..N-1) {
        auto s = readln.split.map!(to!int);
        G[s[0]-1] ~= s[1]-1;
        G[s[1]-1] ~= s[0]-1;
    }

    if (N % 2 == 1) {
        writeln(-1);
        return;
    }

    auto d = new int[](N);

    int dfs(int n, int p) {
        d[n] = 1;
        foreach (m; G[n]) if (m != p) d[n] += dfs(m, n);
        return d[n];
    }

    dfs(0, -1);
    auto ans = d.map!(a => 1 - a % 2).sum;
    writeln(ans - 1);
}


Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.

The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108.

If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples).

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

void main() {
    int n; readf("%d\n", &n);
    int[] xs = readln.chomp.split(" ").map!(to!int).array;
    xs.sort;
    if (xs.length == 1) {
        (-1).writeln;
        return;
    }
    if (xs.length == 2) {
        if ((xs.back - xs.front) % 2 == 0) {
            if (xs.back - xs.front == 0) {
                writeln(1);
                writeln(xs.back);
            } else {
                int d = (xs.back - xs.front) / 2;
                writeln(3);
                writeln(xs.front - 2 * d, " ", xs.front + d, " ", xs.back + 2 * d);
            }
        } else {
            int d = (xs.back - xs.front);
            writeln(2);
            writeln(xs.front - d, " ", xs.back + d);
        }
        return;
    }
    int[] ds;
    foreach (i; 0 .. xs.length - 1) {
        ds ~= xs[i + 1] - xs[i];
    }
    int[] k = ds.sort.uniq.array;
    switch (k.length) {
        case 1:
            if (k[0] == 0) {
                writeln(1);
                writeln(xs.front);
            } else {
                writeln(2);
                writeln(xs.front - k[0], " ", xs.back + k[0]);
            }
            return;
        case 2:
            int[int] c;
            foreach (d; ds) {
                c[d]++;
            }
            if (c.length > 2) {
                writeln(0);
                return;
            }
            if (c.length == 2) {
                int k1 = c.keys.reduce!max;
                int k2 = c.keys.reduce!min;
                if (c[k1] != 1) {
                    writeln(0);
                    return;
                }
            }
            if (k[0] * 2 != k[1]) {
                writeln(0);
                return;
            }
            int d = k[0];
            foreach (i; 0 .. xs.length - 1) {
                if (xs[i + 1] - xs[i] != d) {
                    if (xs[i + 1] - xs[i] == 2 * d) {
                        1.writeln;
                        ((xs[i + 1] + xs[i]) / 2).writeln;
                    } else {
                        0.writeln;
                    }
                    return;
                }
            }
        default:
            writeln(0);
            return;
    }
}

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;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}
		sort !("a < b", SwapStrategy.stable) (a);

		long res = 0;
		long [] ans;
		if (n == 1)
		{
			res = -1;
		}
		else if (n == 2)
		{
			if (a[0] == a[1])
			{
				res = 1;
				ans ~= a[0];
			}
			else
			{
				int d = a[1] - a[0];
				res = 2 + (d % 2 == 0);
				ans ~= a[0] - d;
				if (d % 2 == 0)
				{
					ans ~= (a[0] + a[1]) >> 1;
				}
				ans ~= a[1] + d;
			}
		}
		else if (a[$ - 1] == a[1])
		{
			res = 1;
			ans ~= a[0];
		}
		else
		{
			bool [int] e;
			e[a[1] - a[0]] = true;
			e[a[2] - a[1]] = true;
			foreach (d, val; e)
			{
				ans = [];
				int holes = 0;
				for (int i = 1; i < n; i++)
				{
					if (a[i] - a[i - 1] == d)
					{
						continue;
					}
					if (a[i] - a[i - 1] == d * 2)
					{
						ans ~= (a[i] + a[i - 1]) >> 1;
						holes++;
					}
					else
					{
						holes += 2;
					}
				}
				if (holes == 0)
				{
					ans ~= a[0] - d;
					ans ~= a[$ - 1] + d;
				}
				res = max (0, 2 - holes);
				if (res > 0)
				{
					break;
				}
			}
		}
		writeln (res);
		if (res > 0)
		{
			writefln ("%(%s %)", ans);
		}
	}
}

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

void main() {
    int n; readf("%d\n", &n);
    int[] xs = readln.chomp.split(" ").map!(to!int).array;
    xs.sort;
    if (xs.length == 1) {
        (-1).writeln;
        return;
    }
    if (xs.length == 2) {
        if ((xs.back - xs.front) % 2 == 0) {
            if (xs.back - xs.front == 0) {
                writeln(1);
                writeln(xs.back);
            } else {
                int d = (xs.back - xs.front) / 2;
                writeln(3);
                writeln(xs.front - 2 * d, " ", xs.front + d, " ", xs.back + 2 * d);
            }
        } else {
            int d = (xs.back - xs.front);
            writeln(2);
            writeln(xs.front - d, " ", xs.back + d);
        }
        return;
    }
    int[] ds;
    foreach (i; 0 .. xs.length - 1) {
        ds ~= xs[i + 1] - xs[i];
    }
    int[] k = ds.sort.uniq.array;
    switch (k.length) {
        case 1:
            if (k[0] == 0) {
                writeln(1);
                writeln(xs.front);
            } else {
                writeln(2);
                writeln(xs.front - k[0], " ", xs.back + k[0]);
            }
            return;
        case 2:
            int[int] c;
            foreach (d; ds) {
                c[d]++;
            }
            if (c.length > 2) {
                writeln(0);
                return;
            }
            if (c.length == 2) {
                bool f = false;
                foreach (key, value; c) {
                    if (value == 1) {
                        f = true;
                    }
                }
                if (!f) {
                    writeln(0);
                    return;
                }
            }
            if (k[0] * 2 != k[1]) {
                writeln(0);
                return;
            }
            int d = k[0];
            foreach (i; 0 .. xs.length - 1) {
                if (xs[i + 1] - xs[i] != d) {
                    if (xs[i + 1] - xs[i] == 2 * d) {
                        1.writeln;
                        ((xs[i + 1] + xs[i]) / 2).writeln;
                    } else {
                        0.writeln;
                    }
                    return;
                }
            }
        default:
            writeln(0);
            return;
    }
}

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

void main() {
    int n; readf("%d\n", &n);
    int[] xs = readln.chomp.split(" ").map!(to!int).array;
    if (xs.length == 1) {
        (-1).writeln;
        return;
    }
    if (xs.length == 2) {
        if ((xs.back - xs.front) % 2 == 0) {
            int d = (xs.back - xs.front) / 2;
            writeln(3);
            writeln(xs.front - 2 * d, " ", xs.front + d, " ", xs.back + 2 * d);
        } else {
            writeln(2);
            writeln(xs.front, xs.back);
        }
        return;
    }
    xs.sort;
    int[] ds;
    foreach (i; 0 .. xs.length - 1) {
        ds ~= xs[i + 1] - xs[i];
    }
    int[] k = ds.sort.uniq.array;
    switch (k.length) {
        case 1:
            writeln(2);
            writeln(xs.front - k[0], " ", xs.back + k[0]);
            return;
        case 2:
            if (k[0] * 2 != k[1]) {
                writeln(0);
                return;
            }
            int d = k[0];
            foreach (i; 0 .. xs.length - 1) {
                if (xs[i + 1] - xs[i] != d) {
                    if (xs[i + 1] - xs[i] == 2 * d) {
                        1.writeln;
                        ((xs[i + 1] + xs[i]) / 2).writeln;
                    } else {
                        0.writeln;
                    }
                    return;
                }
            }
        default:
            writeln(0);
            return;
    }
}

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

void main() {
    int n; readf("%d\n", &n);
    int[] xs = readln.chomp.split(" ").map!(to!int).array;
    if (xs.length == 1) {
        (-1).writeln;
        return;
    }
    if (xs.length == 2) {
        if ((xs.back - xs.front) % 2 == 0) {
            if (xs.back - xs.front == 0) {
                writeln(1);
                writeln(xs.back);
            } else {
                int d = (xs.back - xs.front) / 2;
                writeln(3);
                writeln(xs.front - 2 * d, " ", xs.front + d, " ", xs.back + 2 * d);
            }
        } else {
            writeln(2);
            writeln(xs.front, xs.back);
        }
        return;
    }
    xs.sort;
    int[] ds;
    foreach (i; 0 .. xs.length - 1) {
        ds ~= xs[i + 1] - xs[i];
    }
    int[] k = ds.sort.uniq.array;
    switch (k.length) {
        case 1:
            if (k[0] == 0) {
                writeln(1);
                writeln(xs.front);
            } else {
                writeln(2);
                writeln(xs.front - k[0], " ", xs.back + k[0]);
            }
            return;
        case 2:
            if (k[0] * 2 != k[1]) {
                writeln(0);
                return;
            }
            int d = k[0];
            foreach (i; 0 .. xs.length - 1) {
                if (xs[i + 1] - xs[i] != d) {
                    if (xs[i + 1] - xs[i] == 2 * d) {
                        1.writeln;
                        ((xs[i + 1] + xs[i]) / 2).writeln;
                    } else {
                        0.writeln;
                    }
                    return;
                }
            }
        default:
            writeln(0);
            return;
    }
}

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

void main() {
    int n; readf("%d\n", &n);
    int[] xs = readln.chomp.split(" ").map!(to!int).array;
    xs.sort;
    if (xs.length == 1) {
        (-1).writeln;
        return;
    }
    if (xs.length == 2) {
        if ((xs.back - xs.front) % 2 == 0) {
            if (xs.back - xs.front == 0) {
                writeln(1);
                writeln(xs.back);
            } else {
                int d = (xs.back - xs.front) / 2;
                writeln(3);
                writeln(xs.front - 2 * d, " ", xs.front + d, " ", xs.back + 2 * d);
            }
        } else {
            int d = (xs.back - xs.front);
            writeln(2);
            writeln(xs.front - d, " ", xs.back + d);
        }
        return;
    }
    int[] ds;
    foreach (i; 0 .. xs.length - 1) {
        ds ~= xs[i + 1] - xs[i];
    }
    int[] k = ds.sort.uniq.array;
    switch (k.length) {
        case 1:
            if (k[0] == 0) {
                writeln(1);
                writeln(xs.front);
            } else {
                writeln(2);
                writeln(xs.front - k[0], " ", xs.back + k[0]);
            }
            return;
        case 2:
            if (k[0] * 2 != k[1]) {
                writeln(0);
                return;
            }
            int d = k[0];
            foreach (i; 0 .. xs.length - 1) {
                if (xs[i + 1] - xs[i] != d) {
                    if (xs[i + 1] - xs[i] == 2 * d) {
                        1.writeln;
                        ((xs[i + 1] + xs[i]) / 2).writeln;
                    } else {
                        0.writeln;
                    }
                    return;
                }
            }
        default:
            writeln(0);
            return;
    }
}

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

void main() {
    int n; readf("%d\n", &n);
    int[] xs = readln.chomp.split(" ").map!(to!int).array;
    if (xs.length == 1) {
        (-1).writeln;
        return;
    }
    if (xs.length == 2) {
        if ((xs.back - xs.front) % 2 == 0) {
            int d = (xs.back - xs.front) / 2;
            writeln(3);
            writeln(xs.front - 2 * d, " ", xs.front + d, " ", xs.back + 2 * d);
        } else {
            writeln(2);
            writeln(xs.front, xs.back);
        }
        return;
    }
    xs.sort;
    int d = xs[1] - xs[0];
    foreach (i; 0 .. xs.length - 1) {
        if (xs[i + 1] - xs[i] != d) {
            if (xs[i + 1] - xs[i] == 2 * d) {
                1.writeln;
                ((xs[i + 1] + xs[i]) / 2).writeln;
            } else {
                0.writeln;
            }
            return;
        }
    }
    writeln(2);
    writeln(xs.front - d, " ", xs.back + d);
}

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

void main() {
    int n; readf("%d\n", &n);
    int[] xs = readln.chomp.split(" ").map!(to!int).array;
    xs.sort;
    if (xs.length == 1) {
        (-1).writeln;
        return;
    }
    if (xs.length == 2) {
        if ((xs.back - xs.front) % 2 == 0) {
            if (xs.back - xs.front == 0) {
                writeln(1);
                writeln(xs.back);
            } else {
                int d = (xs.back - xs.front) / 2;
                writeln(3);
                writeln(xs.front - 2 * d, " ", xs.front + d, " ", xs.back + 2 * d);
            }
        } else {
            int d = (xs.back - xs.front);
            writeln(2);
            writeln(xs.front - d, " ", xs.back + d);
        }
        return;
    }
    int[] ds;
    foreach (i; 0 .. xs.length - 1) {
        ds ~= xs[i + 1] - xs[i];
    }
    int[] k = ds.sort.uniq.array;
    switch (k.length) {
        case 1:
            if (k[0] == 0) {
                writeln(1);
                writeln(xs.front);
            } else {
                writeln(2);
                writeln(xs.front - k[0], " ", xs.back + k[0]);
            }
            return;
        case 2:
            int[int] c;
            foreach (d; ds) {
                c[d]++;
            }
            if (c.length > 2) {
                writeln(0);
                return;
            }
            if (c.length == 2) {
                int k1 = c.keys.reduce!min;
                int k2 = c.keys.reduce!max;
                if (c[k1] != 1) {
                    writeln(0);
                    return;
                }
            }
            if (k[0] * 2 != k[1]) {
                writeln(0);
                return;
            }
            int d = k[0];
            foreach (i; 0 .. xs.length - 1) {
                if (xs[i + 1] - xs[i] != d) {
                    if (xs[i + 1] - xs[i] == 2 * d) {
                        1.writeln;
                        ((xs[i + 1] + xs[i]) / 2).writeln;
                    } else {
                        0.writeln;
                    }
                    return;
                }
            }
        default:
            writeln(0);
            return;
    }
}


Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.

Print the index of the day when Polycarp will celebrate the equator.

NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.

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

void main(){

	int[200010] a;

	int n;

	readf("%s", &n);
	readln;

	int ss = 0;

	for (int i = 1; i < n; ++i){
		readf("%s ", &a[i]);
		ss += a[i];
	}

	readf("%s", &a[n]);
	ss += a[n];
	readln;

	ss = (ss + 1) / 2;
	int tt = 0;
	for (int i = 1; i <= n; ++i){
		tt += a[i];
		if (tt >= ss){
			writeln(i);
			return;
		}
	}
}

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

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

  auto a = readln.stripRight.split.map!(a => a.parse!int);
  auto s = cumulativeFold!"a + b"(a, 0).array;
  // find the first value >= sum/2
  writeln(s.assumeSorted.lowerBound((s[$-1] + 1) / 2).length + 1);
}


Given three distinct integers $$$a$$$, $$$b$$$, and $$$c$$$, find the medium number between all of them.The medium number is the number that is neither the minimum nor the maximum of the given three numbers. For example, the median of $$$5,2,6$$$ is $$$5$$$, since the minimum is $$$2$$$ and the maximum is $$$6$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 6840$$$) — the number of test cases. The description of each test case consists of three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \leq a, b, c \leq 20$$$).

For each test case, output a single integer — the medium number of the three numbers.

import std.stdio;
import std.algorithm;
import std.math;
//import std.conv;
//import std.numeric;
//import std.range;
import std.array;
import std.bigint;
import std.string;

void sol(){

    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);

    if(a>b){
        swap(a,b);
    }
    if(b>c){
        swap(b,c);
    }
    if(a>b){
        swap(a,b);
    }

    writeln(b);
}

void main(){

    int t;
    readf!"%d"(t);
    while (t--){
        sol();
    }
}

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

void main()
{
    auto t = readln().strip().to!int;
    foreach (i; 0..t)
    {
        auto testCase = readln().strip();
        auto numbers = testCase.split().map!(s=>s.to!int).array.sort;
        writefln("%d", numbers[1]);
    }
}

import std;

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto a = readln.splitter.map!(to!long).array.sort.array;
    writeln(a[1]);
  }
}


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ and an integer $$$k$$$. Find the maximum value of $$$i \cdot j - k \cdot (a_i | a_j)$$$ over all pairs $$$(i, j)$$$ of integers with $$$1 \le i < j \le n$$$. Here, $$$|$$$ is the bitwise OR operator.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$)  — the number of test cases. The first line of each test case contains two integers $$$n$$$ ($$$2 \le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le \min(n, 100)$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, print a single integer  — the maximum possible value of $$$i \cdot j - k \cdot (a_i | a_j)$$$.

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

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

alias P = Tuple!(long, "i", long, "j");

void solve() {
    int N; long K; readf("%d %d\n", &N, &K);
    auto A = readarray!int;

    long xmax = -(1L<<56);
    for (int j = N; j >= 1; j--) {
        for (int i = j-1; i >= 1; i--) {
            if (xmax >= cast(long)(i) * j) break;
            long x = cast(long)(i) * j - K * (A[i-1] | A[j-1]);
            xmax.chmax(x);
        }
    }
    writeln(xmax);
}

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

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

alias P = Tuple!(long, "i", long, "j");

void solve() {
    int N; long K; readf("%d %d\n", &N, &K);
    auto A = readarray!int;

    if (N >= 500) {
        bool[P] used;
        auto Q = heapify!((a, b) => a.i*a.j < b.i*b.j)(new P[0], 0);
        Q.insert(P(N-1, N));
        long xmax = -(1L<<56);
        while (! Q.empty) {
            auto c = Q.front; Q.removeFront;
            long i = c.i, j = c.j;
            if (i * j < xmax) break;
            long x = i * j - K * (A[cast(int)(i-1)] | A[cast(int)(j-1)]);
            xmax.chmax(x);
            if (i + 1 < j) {
                auto n = P(i, j-1);
                if (n !in used) {
                    used[n] = true;
                    Q.insert(n);
                }
            }
            if (i > 1) {
                auto n = P(i-1, j);
                if (n !in used) {
                    used[n] = true;
                    Q.insert(n);
                }
            }
        }
        writeln(xmax);
    } else {
        long xmax = -(1L<<56);
        for (int j = N; j >= 1; j--) {
            for (int i = j-1; i >= 1; i--) {
                if (xmax >= i * j) break;
                long x = i * j - K * (A[i-1] | A[j-1]);
                xmax.chmax(x);
            }
        }
        writeln(xmax);
    }
}

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(string[ ] args) {
    int t;
    readf!"%s"(t);
    readln;

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

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

        immutable int reach = 110;

        long ans = long.min;
        for (int i = n-1; i >= 0 && i >= n - reach; --i) {
            for (int j = i-1; j >= 0 && j >= n - reach; --j) {
                auto cur = (i+1).to!long * (j+1).to!long - k * (a[i] | a[j]);
                ans = max(cur, ans);
            }
        }

        ans.writeln;
    }
}

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

void main()
{
	int t = readInt!int;
	while (t--) solve;
}

void solve()
{
	int n = readInt!int;
	int k = readInt!int;
	auto a = new int[](n); foreach(ref ai; a) ai = readInt!int;
	long mx = long.min;
	foreach(j; n - 100 .. n)
	{
		foreach(i; 0 .. j)
		{
			mx = max(mx, cast(long)(i+1)*cast(long)(j+1) - cast(long)k * (a[i]|a[j]));
		}
	}
	mx.writeln;
}

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

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

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

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

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = long.min;
		foreach_reverse (i; 0..n)
		{
			auto x = k * a[i];
			foreach_reverse (j; 0..i)
			{
				long y = cast(long)(i+1) * (j+1);
				if (y - x <= ans[ti]) break;
				auto z = y - k * (a[i]|a[j]);
				ans[ti].chmax(z);
			}
		}
	}

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

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

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

alias P = Tuple!(long, "i", long, "j");

void solve() {
    int N; long K; readf("%d %d\n", &N, &K);
    auto A = readarray!int;

    long xmax = -(1L<<56);
    for (int j = N; j >= 1; j--) {
        for (int i = j-1; i >= 1; i--) {
            if (xmax >= i * j) break;
            long x = i * j - K * (A[i-1] | A[j-1]);
            xmax.chmax(x);
        }
    }
    writeln(xmax);
}

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

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

alias P = Tuple!(long, "i", long, "j");

void solve() {
    int N; long K; readf("%d %d\n", &N, &K);
    auto A = readarray!int;
    bool[P] used;
    DList!P Q;
    Q.insert(P(N-1, N));
    long xmax = -(1L<<56);
    while (! Q.empty) {
        auto c = Q.front; Q.removeFront;
        long i = c.i, j = c.j;
        if (i * j < xmax) break;
        long x = i * j - K * (A[cast(int)(i-1)] | A[cast(int)(j-1)]);
        xmax.chmax(x);
        if (i + 1 < j) {
            auto n = P(i, j-1);
            if (n !in used) {
                used[n] = true;
                Q.insert(n);
            }
        }
        if (i > 1) {
            auto n = P(i-1, j);
            if (n !in used) {
                used[n] = true;
                Q.insert(n);
            }
        }
    }
    writeln(xmax);
}

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(string[ ] args) {
    int t;
    readf!"%s"(t);
    readln;

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

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

        immutable int reach = 100;

        long ans = long.min;
        for (int i = n-1; i >= 0 && i >= n - reach; --i) {
            for (int j = i-1; j >= 0 && j >= n - reach; --j) {
                auto cur = (i+1).to!long * (j+1).to!long - k * (a[i] | a[j]);
                ans = max(cur, ans);
            }
        }

        ans.writeln;
    }
}

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(string[ ] args) {
    int t;
    readf!"%s"(t);
    readln;

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

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

        long ans = long.min;
        for (int i = n-1; i >= 0 && i >= n - 10; --i) {
            for (int j = i-1; j >= 0 && j >= n - 10; --j) {
                auto cur = (i+1).to!long * (j+1).to!long - k * (a[i] | a[j]);
                ans = max(cur, ans);
            }
        }

        ans.writeln;
    }
}

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

void main()
{
	int t = readInt!int;
	while (t--) solve;
}

void solve()
{
	int n = readInt!int;
	int k = readInt!int;
	auto a = new int[](n); foreach(ref ai; a) ai = readInt!int;
	if (n <= 1000)
	{
		long mx = long.min;
		foreach(i; 0 .. n)
			foreach(j; i + 1 .. n)
				mx = max(mx, cast(long)(i+1)*cast(long)(j+1) - cast(long)k * (a[i]|a[j]));
		mx.writeln;
	}
	else
	{
		long mx = long.min;
		foreach(j; n - 3 .. n)
		{
			foreach(i; 0 .. j)
			{
				mx = max(mx, cast(long)(i+1)*cast(long)(j+1) - cast(long)k * (a[i]|a[j]));
			}
		}
		mx.writeln;
	}
}

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

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

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

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

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = long.min;
		foreach_reverse (i; 0..n)
		{
			auto x = k * a[i];
			foreach_reverse (j; 0..i)
			{
				long y = (i+1) * (j+1);
				if (y - x <= ans[ti]) break;
				auto z = y - k * (a[i]|a[j]);
				ans[ti].chmax(z);
			}
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = long.min;
		foreach_reverse (i; 0..n)
		{
			auto x = k * a[i];
			foreach_reverse (j; 0..i)
			{
				auto y = (i+1) * (j+1);
				if (y - x <= ans[ti]) break;
				auto z = y - k * (a[i]|a[j]);
				ans[ti].chmax(z);
			}
		}
	}

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


Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from 1 to n and the avenues are numbered with integers from 1 to m. The cost of dinner in the restaurant at the intersection of the i-th street and the j-th avenue is cij.Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.

The first line contains two integers n, m (1 ≤ n, m ≤ 100) — the number of streets and avenues in Munhattan. Each of the next n lines contains m integers cij (1 ≤ cij ≤ 109) — the cost of the dinner in the restaurant on the intersection of the i-th street and the j-th avenue.

Print the only integer a — the cost of the dinner for Jack and Emma.

NoteIn the first example if Emma chooses the first or the third streets Jack can choose an avenue with the cost of the dinner 1. So she chooses the second street and Jack chooses any avenue. The cost of the dinner is 2.In the second example regardless of Emma's choice Jack can choose a restaurant with the cost of the dinner 1.

module foo1;
import std.stdio;
import std.string;
import std.conv;
import std.regex;
import std.file;
import std.math;
import std.algorithm;
//import foo2;

void main()
{
    auto str = split(strip(readln())," ");
    long[] ans;
    for(int i = 0; i < to!int(str[0], 10); i++)
    {
        auto x = split(strip(readln())," ");
        long[] res;
        foreach(idx, element; x)
        {

            res ~= to!long(element, 10);

        }
        res.sort();

        ans ~= res[0];

    }
    ans.sort();
    writeln(ans[$-1]);

}

module foo2;

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

//import foo1;

void main()
{
  string arr;
  string[] str1 = split(readln());
  for(int i = 0; i < to!int(str1[0]); i++)
  {
      string inp = strip(readln);
      arr ~= " " ~ min(inp);
  }
    writeln(max(arr));
}

string min(string str)
{
    string[] a = split(str);
    string min = a[0];
    foreach(element; a[1 .. $])
    {
        if(min > element)
            min = element;
    }
    return min;
}
string max(string str)
{
    string[] a = split(str);
    string max = a[0];
    foreach(element; a[1 .. $])
    {
        if(max < element)
            max = element;
    }
    return max;
}

module foo1;
import std.stdio;
import std.string;
import std.conv;
import std.regex;
import std.file;
import std.math;
import std.algorithm;
//import foo2;

void main()
{
    auto str = split(strip(readln())," ");
    string res[];
    //writeln(n," ",m);
    for(int i = 0; i < to!int(str[0], 10); i++)
    {
        auto x = split(strip(readln())," ");
        x.sort();
        res ~= x[0];

    }
    res.sort();
    writeln(res[$-1]);

}


Not so long ago, Vlad had a birthday, for which he was presented with a package of candies. There were $$$n$$$ types of candies, there are $$$a_i$$$ candies of the type $$$i$$$ ($$$1 \le i \le n$$$).Vlad decided to eat exactly one candy every time, choosing any of the candies of a type that is currently the most frequent (if there are several such types, he can choose any of them). To get the maximum pleasure from eating, Vlad does not want to eat two candies of the same type in a row.Help him figure out if he can eat all the candies without eating two identical candies in a row.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. The following is a description of $$$t$$$ test cases of input, two lines for each. The first line of the case contains the single number $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of types of candies in the package. The second line of the case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — the number of candies of the type $$$i$$$. It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2 \cdot 10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer, output "YES" if Vlad can eat candy as planned, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first example, it is necessary to eat sweets in this order: a candy of the type $$$2$$$, it is the most frequent, now $$$a = [2, 2]$$$; a candy of the type $$$1$$$, there are the same number of candies of the type $$$2$$$, but we just ate one, now $$$a = [1, 2]$$$; a candy of the type $$$2$$$, it is the most frequent, now $$$a = [1, 1]$$$; a candy of the type $$$1$$$, now $$$a = [0, 1]$$$; a candy of the type $$$2$$$, now $$$a = [0, 0]$$$ and the candy has run out.In the second example, all the candies are of the same type and it is impossible to eat them without eating two identical ones in a row.In the third example, first of all, a candy of the type $$$2$$$ will be eaten, after which this kind will remain the only kind that is the most frequent, and you will have to eat a candy of the type $$$2$$$ again.

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 a = readln.splitter.map !(to !(int)).array ~ 0;
		sort !(q{a > b}) (a);
		writeln (a[0] - a[1] > 1 ? "NO" : "YES");
	}
}


Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.Initially, on day $$$1$$$, there is one bacterium with mass $$$1$$$.Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass $$$m$$$ splits, it becomes two bacteria of mass $$$\frac{m}{2}$$$ each. For example, a bacterium of mass $$$3$$$ can split into two bacteria of mass $$$1.5$$$.Also, every night, the mass of every bacteria will increase by one.Phoenix is wondering if it is possible for the total mass of all the bacteria to be exactly $$$n$$$. If it is possible, he is interested in the way to obtain that mass using the minimum possible number of nights. Help him become the best scientist!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 10^9$$$) — the sum of bacteria masses that Phoenix is interested in.

For each test case, if there is no way for the bacteria to exactly achieve total mass $$$n$$$, print -1. Otherwise, print two lines. The first line should contain an integer $$$d$$$  — the minimum number of nights needed. The next line should contain $$$d$$$ integers, with the $$$i$$$-th integer representing the number of bacteria that should split on the $$$i$$$-th day. If there are multiple solutions, print any.

NoteIn the first test case, the following process results in bacteria with total mass $$$9$$$:   Day $$$1$$$: The bacterium with mass $$$1$$$ splits. There are now two bacteria with mass $$$0.5$$$ each.  Night $$$1$$$: All bacteria's mass increases by one. There are now two bacteria with mass $$$1.5$$$.  Day $$$2$$$: None split.  Night $$$2$$$: There are now two bacteria with mass $$$2.5$$$.  Day $$$3$$$: Both bacteria split. There are now four bacteria with mass $$$1.25$$$.  Night $$$3$$$: There are now four bacteria with mass $$$2.25$$$.  The total mass is $$$2.25+2.25+2.25+2.25=9$$$. It can be proved that $$$3$$$ is the minimum number of nights needed. There are also other ways to obtain total mass 9 in 3 nights.$$$ $$$In the second test case, the following process results in bacteria with total mass $$$11$$$:   Day $$$1$$$: The bacterium with mass $$$1$$$ splits. There are now two bacteria with mass $$$0.5$$$.  Night $$$1$$$: There are now two bacteria with mass $$$1.5$$$.  Day $$$2$$$: One bacterium splits. There are now three bacteria with masses $$$0.75$$$, $$$0.75$$$, and $$$1.5$$$.  Night $$$2$$$: There are now three bacteria with masses $$$1.75$$$, $$$1.75$$$, and $$$2.5$$$.  Day $$$3$$$: The bacteria with mass $$$1.75$$$ and the bacteria with mass $$$2.5$$$ split. There are now five bacteria with masses $$$0.875$$$, $$$0.875$$$, $$$1.25$$$, $$$1.25$$$, and $$$1.75$$$.  Night $$$3$$$: There are now five bacteria with masses $$$1.875$$$, $$$1.875$$$, $$$2.25$$$, $$$2.25$$$, and $$$2.75$$$.  The total mass is $$$1.875+1.875+2.25+2.25+2.75=11$$$. It can be proved that $$$3$$$ is the minimum number of nights needed. There are also other ways to obtain total mass 11 in 3 nights.$$$ $$$In the third test case, the bacterium does not split on day $$$1$$$, and then grows to mass $$$2$$$ during night $$$1$$$.

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

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

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

        int mx = 0;
        while (n >= (1 << mx)) {
            n -= (1 << mx);
            ++mx;
        }

        int[] arr;
        foreach (b; 0 .. mx) {
            arr ~= (1 << b);
            if (n >= (1 << b) && n < (1 << (b+1))) { arr ~= n; }
        }

        int[] ans;
        foreach (prv, nxt; lockstep(arr, arr.dropOne)) {
            ans ~= nxt - prv;
        }

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

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto N = readln.chomp.to!long;
        long[] as;
        long b = 1;
        N -= 1;
        while (N) {
            if (N <= b*2) {
                as ~= N-b;
                break;
            }
            if (N <= b*4) {
                as ~= N/2-b;
                b = N/2;
            } else {
                as ~= b;
                b *= 2;
            }
            N -= b;
        }
        writeln(as.length);
        writeln(as.to!(string[]).join(" "));
    }
}

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

void main ()
{
	readln;
	int n;
	while (readf !(" %s") (n) > 0)
	{
		auto steps = bsr (n);
		int cur = 1;
		int total = cur;
		int [] ans;
		foreach (step; 0..steps)
		{
			int next = (n - total) / (steps - step);
			next = min (next, cur * 2);
			ans ~= next - cur;
			cur = next;
			total += next;
		}
		writeln (steps);
		writefln !("%(%s %)") (ans);
	}
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto N = readln.chomp.to!long;
        long[] as;
        long b = 1;
        if (N%2 == 0) {
            as ~= 0;
            N -= 2;
        } else {
            N -= 1;
        }
        while (N) {
            if (N == b) {
                as ~= 0;
                break;
            } else if (N == b*2) {
                as ~= b;
                break;
            }
            if (N/2 <= b*2) {
                as ~= N/2-b;
                b = N/2;
                N /= 2;
            } else {
                as ~= b;
                b *= 2;
                N -= b;
            }
        }
        writeln(as.length);
        writeln(as.to!(string[]).join(" "));
    }
}


There is a grid, consisting of $$$n$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. The $$$i$$$-th column has the bottom $$$a_i$$$ cells blocked (the cells in rows $$$1, 2, \dots, a_i$$$), the remaining $$$n - a_i$$$ cells are unblocked.A robot is travelling across this grid. You can send it commands — move up, right, down or left. If a robot attempts to move into a blocked cell or outside the grid, it explodes.However, the robot is broken — it executes each received command $$$k$$$ times. So if you tell it to move up, for example, it will move up $$$k$$$ times ($$$k$$$ cells). You can't send it commands while the robot executes the current one.You are asked $$$q$$$ queries about the robot. Each query has a start cell, a finish cell and a value $$$k$$$. Can you send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times?The robot must stop in the finish cell. If it visits the finish cell while still executing commands, it doesn't count.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 2 \cdot 10^5$$$) — the number of rows and columns of the grid. The second line contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$0 \le a_i \le n$$$) — the number of blocked cells on the bottom of the $$$i$$$-th column. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Each of the next $$$q$$$ lines contain five integers $$$x_s, y_s, x_f, y_f$$$ and $$$k$$$ ($$$a[y_s] < x_s \le n$$$; $$$1 \le y_s \le m$$$; $$$a[y_f] < x_f \le n$$$; $$$1 \le y_f \le m$$$; $$$1 \le k \le 10^9$$$) — the row and the column of the start cell, the row and the column of the finish cell and the number of times each your command is executed. The start and the finish cell of each query are unblocked.

For each query, print "YES" if you can send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $$$k$$$ times. Otherwise, print "NO".

import std.stdio;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

class SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    void update(int k, in T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}

enum long INF = 1L<<56;

void main() {
    long N, M; readf("%d %d\n", &N, &M);
    auto A = readln.chomp.split(" ").map!(to!long).array;
    auto rmq = new SegmentTree!(long, -INF, (a, b) => max(a, b))(cast(int)(M + 1));
    for (int i = 1; i <= M; i++) {
        rmq.update(i, A[i-1]);
    }
    long Q = readln.chomp.to!long;
    foreach (q; 0 .. Q) {
        bool ans_query() {
            long xs, ys, xf, yf, k;
            readf("%d %d %d %d %d\n", &ys, &xs, &yf, &xf, &k);
            if (xs > xf) {
                swap(xs, xf);
                swap(ys, yf);
            }
            long dst = (N - ys) / k;
            long yst = ys + k * dst;
            if (rmq.query(cast(int)xs, cast(int)(xf + 1)) < yst) {
                // ok
                return (yst - ys) % k == 0 && (yst - yf) % k == 0 && (xf - xs) % k == 0;
            } else {
                return false;
            }
        }
        writeln(ans_query() ? "YES" : "NO");
    }
}


The Hedgehog recently remembered one of his favorite childhood activities, — solving puzzles, and got into it with new vigor. He would sit day in, day out with his friend buried into thousands of tiny pieces of the picture, looking for the required items one by one.Soon the Hedgehog came up with a brilliant idea: instead of buying ready-made puzzles, one can take his own large piece of paper with some picture and cut it into many small rectangular pieces, then mix them and solve the resulting puzzle, trying to piece together the picture. The resulting task is even more challenging than the classic puzzle: now all the fragments have the same rectangular shape, and one can assemble the puzzle only relying on the picture drawn on the pieces.All puzzle pieces turn out to be of the same size X × Y, because the picture is cut first by horizontal cuts with the pitch of X, then with vertical cuts with the pitch of Y. If we denote the initial size of the picture as A × B, then A must be divisible by X and B must be divisible by Y (X and Y are integer numbers). However, not every such cutting of the picture will result in a good puzzle. The Hedgehog finds a puzzle good if no two pieces in it are the same (It is allowed to rotate the pieces when comparing them, but it is forbidden to turn them over). Your task is to count for a given picture the number of good puzzles that you can make from it, and also to find the puzzle with the minimal piece size.

The first line contains two numbers A and B which are the sizes of the picture. They are positive integers not exceeding 20. Then follow A lines containing B symbols each, describing the actual picture. The lines only contain uppercase English letters.

In the first line print the number of possible good puzzles (in other words, the number of pairs (X, Y) such that the puzzle with the corresponding element sizes will be good). This number should always be positive, because the whole picture is a good puzzle itself.  In the second line print two numbers — the sizes X and Y of the smallest possible element among all good puzzles. The comparison is made firstly by the area XY of one element and secondly — by the length X.

NoteThe picture in the first sample test has the following good puzzles: (2, 1), (2, 2), (2, 4).

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.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{

    int a, b;
    readf("%s %s", &a, &b);
    readln;

    dchar[][] arr;

    foreach (i; 0 .. a) {
        arr ~= readln.chomp.to!(dchar[]);
    }

    debug { arr.writeln; }

    int anscnt = 0;
    int ansx = a, ansy = b;
    bool smaller(int x, int y) {
        return x*y < ansx*ansy || (x*y == ansx*ansy && x < ansx);
    }

    bool isOk(int x, int y) {
        struct Piece {
            dchar[][] e;

            bool different(Piece rhs) {
                auto e2 = rhs.e.dup;

                dchar[][] rot90(dchar[][] a) {
                    auto res = new dchar[][] (a[0].length, a.length);
                    foreach (i; 0 .. a.length) {
                        foreach (j; 0 .. a[0].length) {
                            res[j][a.length - 1 - i] = a[i][j];
                        }
                    }
                    return res;
                }

                foreach (_; 0 .. 4) {
                    e2 = rot90(e2);

                    bool sameRot(const dchar[][] a, const dchar[][] b) {
                        if (a.length != b.length) { return false; }
                        if (a[0].length != b[0].length) { return false; }

                        foreach (i; 0 .. a.length) {
                            foreach (j; 0 .. a[0].length) {
                                if (a[i][j] != b[i][j]) { return false; }
                            }
                        }

                        return true;
                    }

                    if (sameRot(e, e2)) { return false; }
                }

                return true;
            }
        }

        Piece[] ps;
        foreach (stx; a.iota.array.stride(x)) {
            foreach (sty; b.iota.array.stride(y)) {
                Piece p;
                foreach (r; stx .. stx + x) {
                    p.e ~= arr[r][sty .. sty + y];
                }
                ps ~= p;
            }
        }

        debug { ps.map!(p => p.e).writeln; }

        foreach (i; 0 .. ps.length) {
            foreach (j; i+1 .. ps.length) {
                if (!ps[i].different(ps[j])) { return false; }
            }
        }

        return true;
    }

    foreach (x; 1 .. a+1) {
        if (a % x != 0) { continue; }

        foreach (y; 1 .. b+1) {
            if (b % y != 0) { continue; }

            if (isOk(x, y)) {
                anscnt += 1;
                if (smaller(x, y)) {
                    ansx = x;
                    ansy = y;
                }
            }
        }
    }

    writeln(anscnt);
    writeln(ansx, ' ', ansy);
}