Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased:  Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.

The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree.

If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path.

NoteIn the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5.It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.

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

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

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

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

enum INF = 10^^9;

int N;
int[] A, B;

int[][] G;
int[] par;

alias Result = Tuple!(int, "min", int, "max");
enum IDENTITY = Result(INF, -INF);
Result mul(const(Result) a, const(Result) b) {
  return Result(min(a.min, b.min), max(a.max, b.max));
}
Result up(const(Result) a) {
  return (a.min >= INF) ? Result(0, 0) : Result(1 + a.min, 1 + a.max);
}

Result[] dp, DP;

void dfs(int u, int p) {
  par[u] = p;
  Result prod = IDENTITY;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
      prod = mul(prod, dp[v]);
    }
  }
  dp[u] = up(prod);
}

void DFS(int u, int p) {
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
    }
  }
  const len = cast(int)(vs.length);
  auto ls = new Result[len + 1];
  auto rs = new Result[len + 1];
  ls[0] = (p == -1) ? IDENTITY : DP[u];
  foreach (j; 0 .. len) {
    ls[j + 1] = mul(ls[j], dp[vs[j]]);
  }
  rs[len] = IDENTITY;
  foreach_reverse (j; 0 .. len) {
    rs[j] = mul(dp[vs[j]], rs[j + 1]);
  }
  foreach (j; 0 .. len) {
    DP[vs[j]] = up(mul(ls[j], rs[j + 1]));
  }
  foreach (v; vs) {
    DFS(v, u);
  }
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      par = new int[N];
      dp = new Result[N];
      DP = new Result[N];
      dfs(0, -1);
      DFS(0, -1);
      debug {
        writeln("dp = ", dp);
        writeln("DP = ", DP);
      }

      int ans = INF;
      foreach (u; 0 .. N) {
        bool ok = true;
        int[] ms;
        if (par[u] != -1) {
          ok = ok && (DP[u].min == DP[u].max);
          ms ~= DP[u].min;
        }
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (v != par[u]) {
            ok = ok && (dp[v].min == dp[v].max);
            ms ~= dp[v].min;
          }
        }
        ms = ms.sort.uniq.array;
        debug {
          writeln(u, ": ", ok, " ", ms);
        }
        if (ok && ms.length <= 2) {
          const cost = (G[u].length == 1) ? (ms[0] + 1) : (ms[0] + 1 + 1 + ms[$ - 1]);
          chmin(ans, cost >> bsf(cost));
        }
      }
      writeln((ans >= INF) ? -1 : ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum INF = 10^^9;

int N;
int[] A, B;

int[][] G;
int[] par;

alias Result = Tuple!(int, "min", int, "max");
enum IDENTITY = Result(INF, -INF);
Result mul(const(Result) a, const(Result) b) {
  return Result(min(a.min, b.min), max(a.max, b.max));
}
Result up(const(Result) a) {
  return (a.min >= INF) ? Result(0, 0) : Result(1 + a.min, 1 + a.max);
}

Result[] dp, DP;

void dfs(int u, int p) {
  par[u] = p;
  Result prod = IDENTITY;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
      prod = mul(prod, dp[v]);
    }
  }
  dp[u] = up(prod);
}

void DFS(int u, int p) {
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
    }
  }
  const len = cast(int)(vs.length);
  auto ls = new Result[len + 1];
  auto rs = new Result[len + 1];
  ls[0] = (p == -1) ? IDENTITY : DP[u];
  foreach (j; 0 .. len) {
    ls[j + 1] = mul(ls[j], dp[vs[j]]);
  }
  rs[len] = IDENTITY;
  foreach_reverse (j; 0 .. len) {
    rs[j] = mul(dp[vs[j]], rs[j + 1]);
  }
  foreach (j; 0 .. len) {
    DP[vs[j]] = up(mul(ls[j], rs[j + 1]));
  }
  foreach (v; vs) {
    DFS(v, u);
  }
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      par = new int[N];
      dp = new Result[N];
      DP = new Result[N];
      dfs(0, -1);
      DFS(0, -1);
      debug {
        writeln("dp = ", dp);
        writeln("DP = ", DP);
      }

      int ans = INF;
      foreach (u; 0 .. N) {
        bool ok = true;
        int[] ms;
        if (par[u] != -1) {
          ok = ok && (DP[u].min == DP[u].max);
          ms ~= DP[u].min;
        }
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (v != par[u]) {
            ok = ok && (dp[v].min == dp[v].max);
            ms ~= dp[v].min;
          }
        }
        ms = ms.sort.uniq.array;
        debug {
          writeln(u, ": ", ok, " ", ms);
        }
        if (ok && ms.length <= 2) {
          const cost = (G[u].length == 1) ? (ms[0] + 1) : (ms[0] + 1 + 1 + ms[$ - 1]);
          chmin(ans, (cost % 2 == 0) ? 0 : cost);
        }
      }
      writeln((ans >= INF) ? -1 : ans);
    }
  } catch (EOFException e) {
  }
}


You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.

The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).

Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .

NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.

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;

void main() {
    auto N = readln.chomp.to!int;
    auto X = new real[](N);
    auto Y = new real[](N);

    foreach (i; 0..N) {
        auto s = readln.split.map!(to!real);
        X[i] = s[0];
        Y[i] = s[1];
    }

    real ans = 10L^^18;
    foreach (i; 0..N) {
        auto x = X[i];
        auto y = Y[i];
        auto x1 = X[(i-1+N)%N];
        auto y1 = Y[(i-1+N)%N];
        auto x2 = X[(i+1+N)%N];
        auto y2 = Y[(i+1+N)%N];
        auto a = y2 - y1;
        auto b = -x2 + x1;
        auto c = -x1 * y2 + y1 * x2;
        auto d = abs(a*x+b*y+c) / sqrt(a*a+b*b) / 2;
        ans = min(ans, d);
    }

    writefln("%.9f", ans);
}


In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible.There are n (n is always even) possible starting positions for characters marked along the Ox axis. The positions are given by their distinct coordinates x1, x2, ..., xn, two characters cannot end up at the same position.Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be n - 2). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting.Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally.

The first line on the input contains a single integer n (2 ≤ n ≤ 200 000, n is even) — the number of positions available initially. The second line contains n distinct integers x1, x2, ..., xn (0 ≤ xi ≤ 109), giving the coordinates of the corresponding positions.

Print the distance between the warrior and the archer at the beginning of the fight, provided that both Vova and Lesha play optimally.

NoteIn the first sample one of the optimum behavior of the players looks like that:  Vova bans the position at coordinate 15;  Lesha bans the position at coordinate 3;  Vova bans the position at coordinate 31;  Lesha bans the position at coordinate 1. After these actions only positions 0 and 7 will remain, and the distance between them is equal to 7.In the second sample there are only two possible positions, so there will be no bans.

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)
	{
		readln;
		auto x = readln.split.map !(to !(int)).array;
		sort (x);
		auto res = int.max;
		int delta = n / 2;
		for (int i = 0; i + delta < n; i++)
		{
			res = min (res, x[i + delta] - x[i]);
		}
		writeln (res);
	}
}


You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps:   Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements.  Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements.  Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — the array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test, print YES (case-insensitive), if you can make array $$$c$$$ sorted in non-decreasing order. Otherwise, print NO (case-insensitive).

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N);

      if (N == 1) return "YES";

      DList!int BL, BR;
      foreach(i, a; A.reverse.array) {
        if (i % 2 == 0) {
          BR.insertFront(a);
        } else {
          if (i == 1 || BL.front > BR.front) {
            BL.insertFront(a);
          } else {
            auto r = BR.front;
            BR.removeFront;
            BR.insertFront(r);
            BL.insertFront(a);
          }
        }
      }

      int last = N % 2 == 0 ? 0 : BL.array.length > BR.array.length ? 2 : 1;
      foreach(i, a; A.sort.array) {
        // BL[].deb;
        // BR[].deb;
        if (last == 0) {
          if (BL.front == a) {
            BL.removeFront;
            last = 1;
          } else if (BR.front == a) {
            BR.removeFront;
            last = 2;
          } else {
            return "NO";
          }
        } else {
          if (last == 1 && BR.front == a) BR.removeFront;
          else if (last == 2 && BL.front == a) BL.removeFront;
          else return "NO";
          last = 0;
        }
      }

      return "YES";
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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


A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you déjà vu.There is a string $$$s$$$. You must insert exactly one character 'a' somewhere in $$$s$$$. If it is possible to create a string that is not a palindrome, you should find one example. Otherwise, you should report that it is impossible.For example, suppose $$$s=$$$ "cbabc". By inserting an 'a', you can create "acbabc", "cababc", "cbaabc", "cbabac", or "cbabca". However "cbaabc" is a palindrome, so you must output one of the other options.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The only line of each test case contains a string $$$s$$$ consisting of lowercase English letters. The total length of all strings does not exceed $$$3\cdot 10^5$$$.

For each test case, if there is no solution, output "NO". Otherwise, output "YES" followed by your constructed string of length $$$|s|+1$$$ on the next line. If there are multiple solutions, you may print any. You can print each letter of "YES" and "NO" in any case (upper or lower).

YES
cbabac
YES
aab
YES
zaza
YES
baa
NO
YES
nutforajarofatuna

NoteThe first test case is described in the statement.In the second test case, we can make either "aab" or "aba". But "aba" is a palindrome, so "aab" is the only correct answer.In the third test case, "zaza" and "zzaa" are correct answers, but not "azza".In the fourth test case, "baa" is the only correct answer.In the fifth test case, we can only make "aa", which is a palindrome. So the answer is "NO".In the sixth test case, "anutforajaroftuna" is a palindrome, but inserting 'a' elsewhere is valid.

// Vicfred
// https://codeforces.com/contest/1504/problem/A
// greedy
import std.stdio;

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

while(t--) {
    string s;
    readf("%s\n", &s);

    bool found = false;
    int n = cast(int)s.length;
    for(uint i = 0; i < n; ++i) {
        if(s[i] == 'a')
            continue;
        found = true;
        "YES".writeln;
        (s[0..n-i]~'a'~s[n-i..$]).writeln;
        break;
    }
    if(!found)
        "NO".writeln;
}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 0..s.length)
		{
			if (s[$-i-1] != 'a')
			{
				ans[ti] = s[0..i] ~ 'a' ~ s[i..$];
				break;
			}
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			writeln(e);
		}
	}
	stdout.flush;
	debug readln;
}


A championship is held in Berland, in which $$$n$$$ players participate. The player with the number $$$i$$$ has $$$a_i$$$ ($$$a_i \ge 1$$$) tokens.The championship consists of $$$n-1$$$ games, which are played according to the following rules:  in each game, two random players with non-zero tokens are selected;  the player with more tokens is considered the winner of the game (in case of a tie, the winner is chosen randomly);  the winning player takes all of the loser's tokens; The last player with non-zero tokens is the winner of the championship.All random decisions that are made during the championship are made equally probable and independently.For example, if $$$n=4$$$, $$$a = [1, 2, 4, 3]$$$, then one of the options for the game (there could be other options) is:   during the first game, the first and fourth players were selected. The fourth player has more tokens, so he takes the first player's tokens. Now $$$a = [0, 2, 4, 4]$$$;  during the second game, the fourth and third players were selected. They have the same number of tokens, but in a random way, the third player is the winner. Now $$$a = [0, 2, 8, 0]$$$;  during the third game, the second and third players were selected. The third player has more tokens, so he takes the second player's tokens. Now $$$a = [0, 0, 10, 0]$$$;  the third player is declared the winner of the championship. Championship winners will receive personalized prizes. Therefore, the judges want to know in advance which players have a chance of winning, i.e have a non-zero probability of winning the championship. You have been asked to find all such players.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case consists of one positive integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of players in the championship. The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the number of tokens the players have. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the number of players who have a nonzero probability of winning the championship. On the next line print the numbers of these players in increasing order. Players are numbered starting from one in the order in which they appear in the input.

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

string FMT_F = "%.10f";

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

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

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

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

long compress(in long[] arr, out long[long] zip, out long[] unzip)
{
	auto index = MAKE_IDX(arr);
	long last = arr[index[0]], x;
	zip[last] = x;
	unzip ~= last;
	foreach (i; index[1..$])
	{
		if (arr[i] == last) continue;
		last = arr[i];
		++x;
		zip[last] = x;
		unzip ~= last;
	}
	return x+1;
}

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

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

		long[long] zip;
		long[] unzip;
		auto len = cast(int)compress(a, zip, unzip);

		auto cnt = new int[](len);
		foreach (i; 0..n)
		{
			++cnt[cast(int)zip[a[i]]];
		}
		auto b = new long[](len+1);
		foreach (i; 0..len)
		{
			b[i+1] = b[i] + cnt[i] * unzip[i];
		}
		debug writeln(b);

		auto win = new bool[](len);
		foreach (i; 0..len)
		{
			auto x = b[i+1];
			debug writeln("i:", i, " x:", x);
			while (x < unzip[len-1])
			{
				bool f(int p)
				{
					return x >= unzip[p];
				}
				auto r = binarySearch!(f)(0, len);
				debug writeln("r:", r);
				if (b[r+1] <= x) break;
				x = b[r+1];
			}
			win[i] = x >= unzip[len-1];
		}

		foreach (i; 0..n)
		{
			auto p = cast(int)zip[a[i]];
			if (win[p])
				ans[ti] ~= i+1;
		}
	}

	foreach (e; ans)
	{
		writeln(e.length);
		e.map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}

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

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T); while (T--) {
        int N; get(N);
        long[] AA; get(AA);
        P[] ps;
        foreach (i, a; AA) ps ~= P(i.to!int + 1, a);
        sort!"a.t < b.t"(ps);
        int[] rs;
        long s;
        foreach (i; 0..N-1) {
            auto p = ps[i];
            s += p.t;
            if (ps[i + 1].t <= s) {
                rs ~= p.i;
            } else {
                rs = [];
            }
        }
        rs ~= ps[$-1].i;
        sort(rs);
        writeln(rs.length);
        writefln!"%(%d %)"(rs);
    }
}

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;
		auto p = n.iota.array;
		p.schwartzSort !(i => a[i]);
		int [] ans;
		long prev = 0;
		foreach (i; p)
		{
			if (prev < a[i])
			{
				ans.length = 0;
			}
			ans ~= i + 1;
			prev += a[i];
		}
		sort (ans);
		writeln (ans.length);
		writefln !("%(%s %)") (ans);
	}
}


Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to $$$1$$$ meter movement in the south, north, west or east direction respectively).It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visited the first time), then the time of such movement is $$$5$$$ seconds. If he rolls along previously visited segment of a path (i.e., this segment of the path has been covered by his path before), then it takes $$$1$$$ second.Find the skier's time to roll all the path.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each set is given by one nonempty string of the characters 'S', 'N', 'W', 'E'. The length of the string does not exceed $$$10^5$$$ characters. The sum of the lengths of $$$t$$$ given lines over all test cases in the input does not exceed $$$10^5$$$.

For each test case, print the desired path time in seconds.

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

immutable int dirs = 4;
immutable int  [dirs] dRow  = [ -1,   0,  +1,   0];
immutable int  [dirs] dCol  = [  0,  -1,   0,  +1];
immutable char [dirs] dName = ['N', 'W', 'S', 'E'];

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		alias Coord = Tuple !(int, q{row}, int, q{col});
		auto cur = Coord (0, 0);
		bool [Coord] vis;
		int res = 0;
		foreach (char c; s)
		{
			auto dir = dName[].countUntil (c);
			cur.row += dRow[dir];
			cur.col += dCol[dir];
			res += (cur in vis) ? 1 : 5;
			vis[cur] = true;
			cur.row += dRow[dir];
			cur.col += dCol[dir];
		}
		writeln (res);
	}
}


As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation:A swap operation is the following sequence of actions:  choose two indexes i, j (i ≠ j);  perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp. What maximum value of function m(a) can Sereja get if he is allowed to perform at most k swap operations?

The first line contains two integers n and k (1 ≤ n ≤ 200; 1 ≤ k ≤ 10). The next line contains n integers a[1], a[2], ..., a[n] ( - 1000 ≤ a[i] ≤ 1000).

In a single line print the maximum value of m(a) that Sereja can get if he is allowed to perform at most k swap operations.

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

		int res = int.min;
		foreach (lo; 0..n)
		{
			foreach (hi; lo + 1..n + 1)
			{
				auto b = a[0..lo].dup;
				b ~= a[hi..n];
				sort !("a > b", SwapStrategy.stable) (b);
				auto c = a[lo..hi].dup;
				sort !("a < b", SwapStrategy.stable) (c);
				int cur = 0;
				foreach (i; 0..k)
				{
					if (!b.length ||
					    !c.length ||
					    b[0] <= c[0])
					{
						break;
					}
					cur += b[0];
					b = b[1..$];
					c = c[1..$];
                                }
                                foreach (d; c)
                                {
                                	cur += d;
                                }
                                res = max (res, cur);
			}
		}
		writeln (res);
	}
}

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

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

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

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

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

int N, K;
int[] A;

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

		int ans = int.min;

		foreach (i; 0 .. N) foreach (j; i + 1 .. N + 1) {
			int[] xs, ys;
			foreach (k; 0 .. N) {
				((i <= k && k < j) ? xs : ys) ~= A[k];
			}
			xs.sort!"a < b";
			ys.sort!"a > b";
			int now = xs.reduce!"a + b";
			chmax(ans, now);
			foreach (l; 0 .. K) if (l < xs.length && l < ys.length) {
				now -= xs[l];
				now += ys[l];
				chmax(ans, now);
			}
		}

		writeln(ans);

	}
	} catch (EOFException) {}
}


You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:   Operation AND ('&', ASCII code 38)  Operation OR ('|', ASCII code 124)  Operation NOT ('!', ASCII code 33)  Variables x, y and z (ASCII codes 120-122)  Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one.Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:E ::= E '|' T | TT ::= T '&' F | FF ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'

The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of ,  and .

You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.

NoteThe truth table for the second function:

import core.bitop;
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;

immutable int logLogLimit = 3;
immutable int logLimit = 1 << logLogLimit;
immutable int limit = 1 << logLimit;
immutable int prios = 3;

struct Answer
{
	string contents;
	alias contents this;

	int opCmp () (const auto ref Answer that) const
	{
		if ((that == "") != (this == ""))
		{
			return (this == "") - (that == "");
		}
		if (that.length != this.length)
		{
			return cast (int) (this.length) -
			    cast (int) (that.length);
		}
		return (that.contents < this.contents) -
		    (this.contents < that.contents);
	}
}

unittest
{
	auto a = Answer ("x");
	auto b = Answer ("y");
	auto c = Answer ("!!y");
	auto d = Answer ("(x)");
	auto e = Answer ("");
	assert (a < b);
	assert (b < c);
	assert (c < d);
	assert (d < e);
}

Answer [prios] [limit] fun;

void relax (ref Answer a, Answer b)
{
	if (a > b)
	{
		a = b;
	}
}

void main ()
{
	fun[0b00001111][2] = "x";
	fun[0b00110011][2] = "y";
	fun[0b01010101][2] = "z";
	Answer [prios] [limit] funPrev;
	do
	{
		funPrev = fun;
		debug {writeln (fun);}
		foreach (s; 0..limit)
		{
			foreach (sp; 0..3)
			{
				string sc = fun[s][sp];
				if (sc == "")
				{
					continue;
				}

				if (sp >= 2)
				{
					auto r = s ^ (limit - 1);
					auto next = Answer ("!" ~ sc);
					relax (fun[r][2], next);
				}

				if (sp >= 0)
				{
					auto r = s;
					auto next = Answer ("(" ~ sc ~ ")");
					relax (fun[r][2], next);
				}

				foreach (t; 0..limit)
				{
					foreach (tp; 0..3)
					{
						string tc = fun[t][tp];
						if (tc == "")
						{
							continue;
						}

						if (sp >= 1 && tp >= 1)
						{
							auto r = s & t;
							auto next = Answer (sc ~ "&" ~ tc);
							relax (fun[r][1], next);
						}

						if (sp >= 0 && tp >= 0)
						{
							auto r = s | t;
							auto next = Answer (sc ~ "|" ~ tc);
							relax (fun[r][0], next);
						}
					}
				}
			}
		}
	}
	while (funPrev != fun);
	debug {writeln (fun);}

	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		foreach (i; 0..n)
		{
			auto x = readln.strip.to !(int) (2);
			debug {writeln (fun[x]);}
			writeln (fun[x][].minElement);
		}
	}
}

import std.algorithm, std.conv, std.stdio, std.string;
alias c = (a, b) => b == "" || (a.length != b.length ? a.length < b.length : a < b);
alias r = (ref a, b) {if (c (b, a)) a = b;};
string [3] [256] f;
void main () {
	f[15][2] = "x";	f[51][2] = "y";	f[85][2] = "z";
	foreach (t; 0..4) foreach (u; 0..256) foreach (p; 0..3) if (f[u][p]) {
			if (p > 1) r (f[u ^ 255][2], "!" ~ f[u][p]);
			r (f[u][2], "(" ~ f[u][p] ~ ")");
			foreach (v; 0..256) foreach (q; 0..3) if (f[v][q]) {
				if (min (p, q)) r (f[u & v][1], f[u][p] ~ "&" ~ f[v][q]);
				r (f[u | v][0], f[u][p] ~ "|" ~ f[v][q]);
			}
		}
	foreach (i; 0..readln.strip.to!int) f[readln.strip.to!int (2)][].minElement!c.writeln;
}

import std.algorithm, std.conv, std.stdio, std.string, std.typecons;
bool c (T) (T a, T b) {return b == "" || tuple (a.length, a) < tuple (b.length, b);}
void r (T) (ref T a, T b) {if (c (b, a)) a = b;}
string [3] [256] f;
void main () {
	f[0b00001111][2] = "x";
	f[0b00110011][2] = "y";
	f[0b01010101][2] = "z";
	foreach (step; 0..4)
		foreach (s; 0..256) foreach (sp; 0..3) if (f[s][sp]) {
			if (sp > 1) r (f[s ^ 255][2], "!" ~ f[s][sp]);
			r (f[s][2], "(" ~ f[s][sp] ~ ")");
			foreach (t; 0..256) foreach (tp; 0..3) if (f[t][tp]) {
				if (min (sp, tp)) r (f[s & t][1], f[s][sp] ~ "&" ~ f[t][tp]);
				r (f[s | t][0], f[s][sp] ~ "|" ~ f[t][tp]);
			}
		}
	foreach (i; 0..readln.strip.to!int) f[readln.strip.to!int (2)][].minElement!c.writeln;
}

import std.algorithm, std.conv, std.stdio, std.string;
struct Answer {
	string contents; alias contents this;
	int opCmp () (const auto ref Answer that) const {
		if ((this == "") != (that == "")) return (this == "") - (that == "");
		if (this.length != that.length) return cast (int) (this.length - that.length);
		return (this.contents > that.contents) - (this.contents < that.contents);
	}
}
Answer [3] [256] fun;
void relax (ref Answer a, Answer b) {if (a > b) a = b;}
void main () {
	fun[0b00001111][2] = "x";
	fun[0b00110011][2] = "y";
	fun[0b01010101][2] = "z";
	foreach (step; 0..4)
		foreach (s; 0..256) foreach (sp; 0..3) {
			string sc = fun[s][sp];
			if (sc == "") continue;
			if (sp >= 2) relax (fun[s ^ 255][2], Answer ("!" ~ sc));
			if (sp >= 0) relax (fun[s][2], Answer ("(" ~ sc ~ ")"));
			foreach (t; 0..256) foreach (tp; 0..3) {
				string tc = fun[t][tp];
				if (tc == "") continue;
				if (sp >= 1 && tp >= 1) relax (fun[s & t][1], Answer (sc ~ "&" ~ tc));
				if (sp >= 0 && tp >= 0) relax (fun[s | t][0], Answer (sc ~ "|" ~ tc));
			}
		}
	foreach (i; 0..readln.strip.to !(int)) fun[readln.strip.to!int (2)][].minElement.writeln;
}

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

immutable int x = 0b00001111;
immutable int y = 0b00110011;
immutable int z = 0b01010101;
immutable int nx = 0b11110000;
immutable int ny = 0b11001100;
immutable int nz = 0b10101010;
string[] func;

int not(int a) {
    return 0b11111111 ^ a;
}

int p_and(string s) {
    return s[0] != '(' && s.canFind("|");
}

void main() {
    func = new string[](256);
    func.fill("");
    func[x] = "x";
    func[y] = "y";
    func[z] = "z";
    func[nx] = "!x";
    func[ny] = "!y";
    func[nz] = "!z";

    int[string] d;
    d["x"] = x;
    d["y"] = y;
    d["z"] = z;
    d["!x"] = nx;
    d["!y"] = ny;
    d["!z"] = nz;

    int cnt = 6;
    for (int i = 3; cnt < 256; ++i) {
        foreach (str; d.keys) {
            auto term = d[str];
            int len = str.length.to!int;

            if (len!= 1 && len == i-3) {
                int next = not(term);
                string next_str = "!(" ~ str ~ ")";
                if (func[next] == "" || func[next].length > i) {
                    func[next] = next_str;
                } else if (func[next].length == i && func[next] > next_str) {
                    func[next] = next_str;
                }
            }

            foreach (str2; d.keys) {
                if (str == str2) continue;
                if (str.length + str2.length + 1 != i) continue;
                int next = term | d[str2];
                string next_str1 = str ~ "|" ~ str2;
                string next_str2 = str2 ~ "|" ~ str;
                string next_str = min(next_str1, next_str2);
                if (func[next] == "" || func[next].length > i) {
                    func[next] = next_str;
                } else if (func[next].length == i && func[next] > next_str) {
                    func[next] = next_str;
                }
            }

            string str1 = str;
            if (p_and(str)) str1 = "(" ~ str ~ ")";

            foreach (str2; d.keys) {
                string str3 = str2;
                if (str == str2) continue;
                if (p_and(str2)) str3 = "(" ~ str2 ~ ")";
                if (str1.length + str3.length + 1 != i) continue;

                int next = term & d[str2];
                string next_str1 = str1 ~ "&" ~ str3;
                string next_str2 = str3 ~ "&" ~ str1;
                string next_str = min(next_str1, next_str2);
                if (func[next] == "" || func[next].length > i) {
                    func[next] = next_str;
                } else if (func[next].length == i && func[next] > next_str) {
                    func[next] = next_str;
                }
            }

        }

        foreach (j; 0..256) {
            if (func[j].length == i && func[j] != "") {
                cnt += 1;
                d[func[j]] = j;
            }
        }
    }

    string[string] hoge;
    foreach (i; 0..256) {
        hoge[format("%08b", i)] = func[i];
    }

    auto N = readln.chomp.to!int;
    foreach (i; 0..N) {
        auto s = readln.chomp;
        writeln(hoge[s]);
    }
}

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;

immutable int x = 0b00001111;
immutable int y = 0b00110011;
immutable int z = 0b01010101;
immutable int nx = 0b11110000;
immutable int ny = 0b11001100;
immutable int nz = 0b10101010;
string[] func;

int not(int a) {
    return 0b11111111 ^ a;
}

int p_and(string s) {
    return s[0] != '(' && s.canFind("|");
}

void main() {
    func = new string[](256);
    func.fill("");
    func[x] = "x";
    func[y] = "y";
    func[z] = "z";
    func[nx] = "!x";
    func[ny] = "!y";
    func[nz] = "!z";

    int[string] d;
    d["x"] = x;
    d["y"] = y;
    d["z"] = z;
    d["!x"] = nx;
    d["!y"] = ny;
    d["!z"] = nz;

    int cnt = 6;
    for (int i = 3; cnt < 256; ++i) {
        foreach (str; d.keys) {
            auto term = d[str];
            int len = str.length.to!int;

            if (len!= 1 && len == i-3) {
                int next = not(term);
                string next_str = "!(" ~ str ~ ")";
                if (func[next] == "" || func[next].length > i) {
                    func[next] = next_str;
                } else if (func[next].length == i && func[next] > next_str) {
                    func[next] = next_str;
                }
            }

            foreach (str2; d.keys) {
                if (str == str2) continue;
                if (str.length + str2.length + 1 != i) continue;
                int next = term | d[str2];
                string next_str1 = str ~ "|" ~ str2;
                string next_str2 = str2 ~ "|" ~ str;
                string next_str = min(next_str1, next_str2);
                if (func[next] == "" || func[next].length > i) {
                    func[next] = next_str;
                } else if (func[next].length == i && func[next] > next_str) {
                    func[next] = next_str;
                }
            }

            string str1 = str;
            if (p_and(str)) str1 = "(" ~ str ~ ")";

            foreach (str2; d.keys) {
                string str3 = str2;
                if (str == str2) continue;
                if (p_and(str2)) str3 = "(" ~ str2 ~ ")";
                if (str1.length + str3.length + 1 != i) continue;

                int next = term & d[str2];
                string next_str1 = str1 ~ "&" ~ str3;
                string next_str2 = str3 ~ "&" ~ str1;
                string next_str = min(next_str1, next_str2);
                if (next_str == "!x&") writeln(str1, " ", str3, " ", str, " ", str2);
                if (func[next] == "" || func[next].length > i) {
                    func[next] = next_str;
                } else if (func[next].length == i && func[next] > next_str) {
                    func[next] = next_str;
                }
            }

        }

        foreach (j; 0..256) {
            if (func[j].length == i && func[j] != "") {
                cnt += 1;
                d[func[j]] = j;
            }
        }
    }

    string[string] hoge;
    foreach (i; 0..256) {
        hoge[format("%08b", i)] = func[i];
    }

    auto N = readln.chomp.to!int;
    foreach (i; 0..N) {
        auto s = readln.chomp;
        writeln(hoge[s]);
    }
}

import std.algorithm, std.conv, std.stdio, std.string;
struct Answer {
	string contents; alias contents this;
	int opCmp () (const auto ref Answer that) const {
		if ((this == "") != (that == "")) return (this == "") - (that == "");
		if (this.length != that.length) return cast (int) (this.length - that.length);
		return (this.contents > that.contents) - (this.contents < that.contents);
	}
}
Answer [3] [256] fun;
void relax (ref Answer a, Answer b) {if (a > b) a = b;}
void main () {
	fun[0b00001111][2] = "x";
	fun[0b00110011][2] = "y";
	fun[0b01010101][2] = "z";
	foreach (step; 0..3)
		foreach (s; 0..256) foreach (sp; 0..3) {
			string sc = fun[s][sp];
			if (sc == "") continue;
			if (sp >= 2) relax (fun[s ^ 255][2], Answer ("!" ~ sc));
			if (sp >= 0) relax (fun[s][2], Answer ("(" ~ sc ~ ")"));
			foreach (t; 0..256) foreach (tp; 0..3) {
				string tc = fun[t][tp];
				if (tc == "") continue;
				if (sp >= 1 && tp >= 1) relax (fun[s & t][1], Answer (sc ~ "&" ~ tc));
				if (sp >= 0 && tp >= 0) relax (fun[s | t][1], Answer (sc ~ "|" ~ tc));
			}
		}
	foreach (i; 0..readln.strip.to !(int)) fun[readln.strip.to!int (2)][].minElement.writeln;
}


Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?

The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.

Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.

NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.

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

void main()
{
    auto s = readln.chomp.array;

    auto cnt = new bool[3];
    cnt[] = false;

    auto ans = 0;
    foreach (e; s) {
        auto v = e - '0';
        auto md = v % 3;
        if (md == 0 || cnt[3 - md]) {
            ans += 1;
            cnt[1] = cnt[2] = false;
        } else {
            if (cnt[md]) cnt[3 - md] = true;
            cnt[md] = true;
        }
    }

    ans.writeln;
}


You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$n$$$ is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold:  At least $$$\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \dots, n - 1$$$ are greater than or equal to $$$0$$$.  At least $$$\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \dots, n - 1$$$ are less than or equal to $$$0$$$. Find any valid way to flip the signs. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 500$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \le n \le 99$$$, $$$n$$$ is odd)  — the number of integers given to you. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)  — the numbers themselves. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10000$$$.

For each test case, print $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$, corresponding to the integers after flipping signs. $$$b_i$$$ has to be equal to either $$$a_i$$$ or $$$-a_i$$$, and of the adjacent differences $$$b_{i + 1} - b_i$$$ for $$$i = 1, \dots, n - 1$$$, at least $$$\frac{n - 1}{2}$$$ should be non-negative and at least $$$\frac{n - 1}{2}$$$ should be non-positive. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.

NoteIn the first test case, the difference $$$(-4) - (-2) = -2$$$ is non-positive, while the difference $$$3 - (-4) = 7$$$ is non-negative.In the second test case, we don't have to flip any signs. All $$$4$$$ differences are equal to $$$0$$$, which is both non-positive and non-negative.In the third test case, $$$7 - (-4)$$$ and $$$4 - (-6)$$$ are non-negative, while $$$(-4) - (-2)$$$ and $$$(-6) - 7$$$ are non-positive.

import std.algorithm;
import std.conv;
import std.math;
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 !(long)).array;
		foreach (i, ref c; a)
		{
			c = abs (c);
			if (i % 2 == 0)
			{
				c = -c;
			}
		}
		writefln !("%(%s %)") (a);
	}
}

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

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

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

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

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

        foreach (i; 0 .. N) {
          if (i > 0) write(" ");
          write((-1)^^(i & 1) * abs(A[i]));
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
		{
			if (i % 2)
				ans[ti][i] = abs(a[i]);
			else
				ans[ti][i] = -abs(a[i]);
		}
	}

	foreach (e; ans)
	{
		e.map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}

import std.algorithm;
import std.conv;
import std.math;
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;
		foreach (i, ref c; a)
		{
			c = abs (c);
			if (i > 0 && (i % 4 < 2) == (a[i] >= a[i - 1]))
			{
				c = -c;
			}
		}
		writefln !("%(%s %)") (a);
	}
}


The New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree.The New Year tree is an undirected tree with n vertices and root in the vertex 1.You should process the queries of the two types:  Change the colours of all vertices in the subtree of the vertex v to the colour c.  Find the number of different colours in the subtree of the vertex v.

The first line contains two integers n, m (1 ≤ n, m ≤ 4·105) — the number of vertices in the tree and the number of the queries. The second line contains n integers ci (1 ≤ ci ≤ 60) — the colour of the i-th vertex. Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the vertices of the j-th edge. It is guaranteed that you are given correct undirected tree. The last m lines contains the description of the queries. Each description starts with the integer tk (1 ≤ tk ≤ 2) — the type of the k-th query. For the queries of the first type then follows two integers vk, ck (1 ≤ vk ≤ n, 1 ≤ ck ≤ 60) — the number of the vertex whose subtree will be recoloured with the colour ck. For the queries of the second type then follows integer vk (1 ≤ vk ≤ n) — the number of the vertex for which subtree you should find the number of different colours.

For each query of the second type print the integer a — the number of different colours in the subtree of the vertex given in the query. Each of the numbers should be printed on a separate line in order of query appearing in the input.

import std.stdio;

void main() {
  int n, m;
  readf(" %s %s", &n, &m);
  auto c = new int[n];
  foreach (ref co; c) {
    readf(" %s", &co);
  }
  auto adj = new int[][n];
  foreach (i; 0..n-1) {
    int u, v;
    readf(" %s %s", &u, &v);
    u--; v--;
    adj[u] ~= v;
    adj[v] ~= u;
  }

  auto tin = new int[n];
  auto tout = new int[n];
  auto to = new int[n];
  int timer = -1;
  void dfs(int u, int par) {
    tin[u] = ++timer;
    to[tin[u]] = u;
    foreach (v; adj[u]) {
      if (v != par) {
        dfs(v, u);
      }
    }
    tout[u] = timer;
  }

  dfs(0, -1);

  auto tree = new long[4 * n];
  auto flag = new long[4 * n];
  void build(int x, int l, int r) {
    if (l == r) {
      tree[x] = 1L << c[to[l]];
    } else {
      int mid = (l + r) >> 1;
      build(x << 1, l, mid);
      build(x << 1 | 1, mid + 1, r);
      tree[x] = tree[x << 1] | tree[x << 1 | 1];
    }
  }

  build(1, 0, n - 1);
  flag[] = 0;

  void propagate(int x, int l, int r) {
    if (flag[x]) {
      if (l != r) {
        flag[x << 1] = flag[x];
        flag[x << 1 | 1] = flag[x];
      }
      tree[x] = flag[x];
      flag[x] = 0;
    }
  }

  void update(int x, int l, int r, int ql, int qr, int c) {
    propagate(x, l, r);
    if (l > qr || r < ql) {
      return;
    } else if (l >= ql && r <= qr) {
      flag[x] = 1L << c;
      propagate(x, l, r);
    } else {
      int mid = (l + r) >> 1;
      update(x << 1, l, mid, ql, qr, c);
      update(x << 1 | 1, mid + 1, r, ql, qr, c);
      tree[x] = tree[x << 1] | tree[x << 1 | 1];
    }
  }

  long query(int x, int l, int r, int ql, int qr) {
    propagate(x, l, r);
    if (l > qr || r < ql) {
      return 0;
    } else if (l >= ql && r <= qr) {
      return tree[x];
    } else {
      int mid = (l + r) >> 1;
      return query(x << 1, l, mid, ql, qr) | query(x << 1 | 1, mid + 1, r, ql, qr);
    }
  }

  int countBit(long x) {
    int ret = 0;
    while (x > 0) {
      ret++;
      x ^= x & -x;
    }
    return ret;
  }

  while (m--) {
    int t;
    readf(" %s", &t);
    if (t == 1) {
      int v, co;
      readf(" %s %s", &v, &co);
      v--;
      update(1, 0, n - 1, tin[v], tout[v], co);
    } else {
      int v;
      readf(" %s", &v);
      v--;
      long q = query(1, 0, n - 1, tin[v], tout[v]);
      writeln(countBit(q));
    }
  }
}
// vim: sw=2 et ts=2 sts=2


Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer $$$x$$$ with $$$p$$$ zeros appended to its end.Now Monocarp asks you to compare these two numbers. Can you help him?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$x_1$$$ and $$$p_1$$$ ($$$1 \le x_1 \le 10^6; 0 \le p_1 \le 10^6$$$) — the description of the first number. The second line of each testcase contains two integers $$$x_2$$$ and $$$p_2$$$ ($$$1 \le x_2 \le 10^6; 0 \le p_2 \le 10^6$$$) — the description of the second number.

For each testcase print the result of the comparison of the given two numbers. If the first number is smaller than the second one, print '<'. If the first number is greater than the second one, print '>'. If they are equal, print '='.

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

void solve(){
    double x1 = scan!double;
    long p1 = scan;
    double x2 = scan!double;
    long p2 = scan;
    while(x1 >= 10){
       x1 /= 10;
       ++p1;
    }
    while(x2 >= 10){
       x2 /= 10;
       ++p2;
    }
    if(p1 > p2 || (p1 == p2 && x1 > x2)){
        writeln(">");
    }else if(p2 > p1 || (p1 == p2 && x1 < x2)){
        writeln("<");
    }else{
        writeln("=");
    }
}

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

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

immutable multi = true;

int[10] tenPow;
static this()
{
  tenPow[0] = 1;
  foreach(i; 1 .. 10)
    tenPow[i] = 10 * tenPow[i-1];
}

void solve(int tc)
{
  auto x1 = readInt!int,
    p1 = readInt!int,
    x2 = readInt!int,
    p2 = readInt!int;

  int getPot(int x)
  {
    int ans = 0;
    while (x)
      {
	ans++;
	x /= 10;
      }
    return ans;
  }
  int pot1 = getPot(x1) + p1, pot2 = getPot(x2) + p2;
  if (pot1 > pot2) return writeln(">");
  if (pot2 > pot1) return writeln("<");
  auto mnp = min(p1, p2);
  p1 -= mnp;
  p2 -= mnp;
  x1 *= tenPow[p1];
  x2 *= tenPow[p2];
  if (x1 < x2) return writeln("<");
  if (x1 > x2) return writeln(">");
  return writeln("=");
}

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

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

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

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

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

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

long numdigits(long x)
{
  long ans;
  while (x > 0) {
    ans++;
    x /= 10;
  }
  return ans;
}

string cmp(T)(T x1, T x2)
{
  if (x1 == x2)
    return "=";
  else if (x1 < x2)
    return "<";
  else
    return ">";
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long x1, p1, x2, p2;
    readf!" %d %d %d %d "(x1, p1, x2, p2);
    p1 += numdigits(x1);
    p2 += numdigits(x2);
    if (p1 == p2) {
      string s1 = x1.to!string;
      string s2 = x2.to!string;
      while (s1.length < s2.length)
        s1 ~= "0";
      while (s2.length < s1.length)
        s2 ~= "0";
      writeln(cmp(s1, s2));
    } else if (p1 < p2) {
      writeln("<");
    } else {
      writeln(">");
    }
  }
}


Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).You have to answer $$$q$$$ independent queries.Let's see the following example: $$$[1, 3, 4]$$$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob — then Alice has $$$4$$$ candies, and Bob has $$$4$$$ candies.Another example is $$$[1, 10, 100]$$$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $$$54$$$ candies, and Alice takes $$$46$$$ candies. Now Bob has $$$55$$$ candies, and Alice has $$$56$$$ candies, so she has to discard one candy — and after that, she has $$$55$$$ candies too.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains three integers $$$a, b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^{16}$$$) — the number of candies in the first, second and third piles correspondingly.

Print $$$q$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th query — the maximum number of candies Alice can have after the division, if both Alice and Bob act optimally (of course, Bob will have the same number of candies).

import std.stdio, std.conv, std.string, std.array, std.math, std.regex, std.range, std.ascii, std.numeric;
import std.typecons, std.functional, std.traits;
import std.algorithm, std.container;
import core.stdc.stdlib, core.bitop;

void main()
{
    auto N = scanElem;
    foreach(i;0..N)
    {
        auto list = [scanElem, scanElem, scanElem];
        sort(list);
        auto a = list[0];
        auto b = list[1];
        auto diff = list[1] - list[0];
        if(diff>list[2]){
            writeln(diff-list[2]/2+a);
        }else{
            writeln((list[2]-diff)/2+b);
        }
    }
}

bool isInf(long v) pure
{
    return v>=INF;
}
enum INF = long.max/5;
enum MOD=10^^9+7L;

struct ModInt(alias Mod = MOD)
if(isIntegral!(typeof(Mod)) && isPrime(Mod))
{
    long value;

    this(ModInt!Mod v)
    {
        value = v.value;
    }
    this(long v)
    {
        value = (v%Mod+Mod)%Mod;
    }

    private static ModInt!Mod inv(ModInt!Mod v) pure
    {
        ModInt res=1;
        long p = Mod-2;
        while(p!=0)
        {
            if(p&1)res *= v;
            v *= v;
            p >>= 1;
        }
        return res;
    }

    ModInt!Mod opBinaryRight(string op, T)(T v) const
    if((op=="+"||op=="-"||op=="*")&&isIntegral!T)
    {
        return ModInt!Mod(mixin("v"~op~"value"));
    }
    ModInt!Mod opBinary(string op, T)(T v) const
    if((op=="+"||op=="-"||op=="*")&&(is(T==ModInt!Mod)||isIntegral!T))
    {
        return ModInt!Mod(mixin("value"~op~"v"));
    }

    ModInt!Mod opBinaryRight(string op, T)(T v) const
    if((op=="/")&&isIntegral!T)
    {
        return v * inv(this);
    }
    ModInt!Mod opBinary(string op, T)(T v) const
    if((op=="/")&&(is(T==ModInt!Mod)||isIntegral!T))
    {
        return this * inv(ModInt(v));
    }

    void opAssign(T)(T v)
    if(isIntegral!T)
    {
        this = ModInt!Mod(v);
    }

    void opOpAssign(string op, T)(T v)
    {
        this = mixin("this"~op~"v");
    }

    bool opEquals(T)(const T v) const
    if(is(T==ModInt!Mod)||isIntegral!T)
    {
        return value == ModInt(v).value;
    }

    long opCast() const {
        return value;
    }

    string toString() const {
        return value.to!string;
    }
}
@safe pure unittest
{
    assert(is(ModInt!()));
    assert(is(ModInt!17));
    assert(!is(ModInt!0));
    assert(!is(ModInt!10));

    assert(is(ModInt!()==ModInt!(MOD)));
}
@safe pure unittest
{
    alias MInt = ModInt!13;
    assert(MInt.inv(MInt(4))==10);
    assert(MInt.inv(MInt(6))==11);
    assert(MInt.inv(MInt(12))==12);
}
@safe pure unittest
{
    alias MInt = ModInt!13;
    MInt value;
    value = MInt(14) + MInt(18);
    assert(value==6);
    value = 14 - MInt(28);
    assert(value==12);
    value = MInt(17) * -19;
    assert(value==2);

    value = MInt(7) / 4;
    assert(value==5);
    value = 8 / MInt(4);
    assert(value==2);
    value = 9;
    value /= 4;
    assert(value==12);

    value = 29-MInt(16);
    assert(value==0);
    value = MInt(13)*5;
    assert(value==0);
    value = 0;
    assert(value==0);

    value = 3;
    value += MInt(11);
    assert(value==1);
    value -= 7;
    assert(value==7);
    value *= MInt(4);
    assert(value==2);
    value = 23;
    assert(value == cast(long)value);
}
@safe pure unittest
{
    ModInt!() value;
    value = MOD-1;
    assert(value==MOD-1);
    value = MOD;
    assert(value==0);
}

struct Grid(T){
    private T[] grid;
    size_t width, height;
    private size_t stride;

    private this(T[] g, size_t w, size_t h, size_t s)
    {
        grid = g;
        width = w;
        height = h;
        stride = s;
    }

    this(size_t w, size_t h)
    {
        this(new T[w*h], w, h, w);
    }

    void setRow(InputRange)(size_t y, InputRange range)
    if(isInputRange!InputRange && is(typeof(grid.front=range.front)))
    {
        foreach(x; 0..width)
        {
            assert(!range.empty);
            this[x, y] = range.front;
            range.popFront;
        }
    }

    void setCol(InputRange)(size_t x, InputRange range)
    if(isInputRange!InputRange && is(typeof(T.init=range.front)))
    {
        foreach(y; 0..height)
        {
            assert(!range.empty);
            this[x, y] = range.front;
            range.popFront;
        }
    }

    Grid!T copy(){
        if(width == stride){
            return Grid!T(grid.dup, width, height, stride);
        }

        auto res = Grid!T(width, height);
        foreach(y;0..height)
        foreach(x;0..width)
        {
            res[x, y] = this[x, y];
        }
        return res;
    }

    ref T opIndex(size_t x, size_t y)
    {
        return grid[x+stride*y];
    }
    ref T opIndex(E)(E e)
        if(
            isIntegral!(typeof(e.x)) &&
            isIntegral!(typeof(e.y)))
    {
        return this[e.x, e.y];
    }

    Grid!T opIndex(size_t[2] r1, size_t[2] r2)
    {
        auto startOffset = r1[0] + r2[0]*stride;
        auto endOffset = r1[1] + (r2[1] - 1)*stride;

        auto resGrid = grid[startOffset .. endOffset];
        auto resStride = stride;
        auto resWidth = r1[1] - r1[0];
        auto resHeight = r2[1] - r2[0];
        return Grid!T(resGrid, resWidth, resHeight, resStride);
    }

    Grid!T opIndex(size_t[2] r1, size_t j) { return opIndex(r1, [j, j+1]); }
    Grid!T opIndex(size_t i, size_t[2] r2) { return opIndex([i, i+1], r2); }

    size_t[2] opSlice(size_t dim)(size_t start, size_t end)
    if (dim == 0 || dim == 1)
    // in { assert(start >= 0 && end <= this.opDollar!dim); }
    body{
        return [start, end];
    }

    size_t opDollar(size_t dim : 0)() const { return width; }
    size_t opDollar(size_t dim : 1)() const { return height; }

    string toString() {
        string res = "\n";
        foreach(y; 0..height)
        {
            foreach(x; 0..width)
            {
                string joinStr = this[x, y].to!string ~ " ";
                static if(is(T==long))
                {
                    if(this[x,y]>=INF)
                    {
                        joinStr = "* ";
                    }
                }
                res ~= joinStr;
            }
            res ~= '\n';
        }
        return res;
    }
}

struct Data2{
    long x,y;
    alias a=x, b=y;
    ref long opIndex(size_t i)
    {
        assert(i==0||i==1);
        return i==0?x:y;
    }
}
struct Data3{
    long x,y,z;
    alias a=x, b=y, c=z;
    ref long opIndex(size_t i)
    {
        assert(i==0||i==1||i==2);
        return i==0?x:(i==1?y:z);
    }
}

long lcm(long a, long b) pure
{
    return a * b / gcd(a, b);
}

class UnionFind{
    UnionFind parent = null;

    void merge(UnionFind a)
    {
        if(same(a)) return;
        a.root.parent = this.root;
    }
    UnionFind root()
    {
        if(parent is null)return this;
        return parent = parent.root;
    }
    bool same(UnionFind a)
    {
        return this.root == a.root;
    }
}

enum TermColor{
    Blue,
    Red,
    Purple,
    Gray,
    Green,
    Brown,
    Default,
}

string termStr(TermColor c) pure
{
    switch(c)
    {
        case TermColor.Blue:   return "\033[38;2;122;158;194m";
        case TermColor.Red:    return "\033[38;2;204;130;66m";
        case TermColor.Purple: return "\033[38;2;158;123;176m";
        case TermColor.Gray:   return "\033[38;2;106;135;89m";
        case TermColor.Green:  return "\033[38;2;165;194;97m";
        case TermColor.Brown:  return "\033[38;2;204;130;66m";
        default: return "\033[0m";
    }
}

void print(TermColor C = TermColor.Gray, T...)(T t)
{
    debug stderr.write(C.termStr, t, TermColor.Default.termStr);
}
void printf(TermColor C = TermColor.Gray, T...)(T t)
{
    debug stderr.write(C.termStr);
    debug stderr.writef(t);
    debug stderr.write(TermColor.Default.termStr);
}
void println(TermColor C = TermColor.Gray, T...)(T t)
{
    debug stderr.writeln(C.termStr, t, TermColor.Default.termStr);
}
void printfln(TermColor C = TermColor.Gray, T...)(T t)
{
    debug stderr.write(C.termStr);
    debug stderr.writefln(t);
    debug stderr.write(TermColor.Default.termStr);
}

// debug{
//     void write(T...)(T t)
//     {
//         stdout.write(TermColor.Blue.termStr, t, TermColor.Default.termStr);
//     }
//     void writeln(T...)(T t)
//     {
//         stdout.writeln(TermColor.Blue.termStr, t, TermColor.Default.termStr);
//     }
//     void writefln(T...)(T t)
//     {
//         stdout.writefln(TermColor.Blue.termStr, t, TermColor.Default.termStr);
//     }
// }

T[] scanArray(T = long)()
{
    return readln.split.to!(T[]);
}

char scanChar()
{
    int c = ' ';
    while (isWhite(c) && c != -1)
    {
        c = getchar;
    }
    return cast(char)c;
}
T scanElem(T = long)()
{
    char[] res;
    int c = ' ';
    while (isWhite(c) && c != -1)
    {
        c = getchar;
    }
    while (!isWhite(c) && c != -1)
    {
        res ~= cast(char) c;
        c = getchar;
    }
    return res.strip.to!T;
}

alias scanString = scanElem!string;

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

            return reduce!fun(tuple(seed), r);
        }
    }
}

struct Factor
{
    long n;
    long c;
}

//素因数分解
Factor[] factors(long n) pure
{
    Factor[] res;
    for (long i = 2; i ^^ 2 <= n; i++)
    {
        if (n % i != 0)
            continue;

        long c;
        while (n % i == 0)
        {
            n = n / i;
            c++;
        }
        res ~= Factor(i, c);
    }
    if (n != 1)
        res ~= Factor(n, 1);

    return res;
}
//約数をすべて列挙
long[] divisors(long n) pure
{
    long[] list;
    void func(Factor[] fs, long n)
    {
        if(fs.empty){
            list ~= n;
            return;
        }

        foreach(c; 0..fs[0].c+1)
        {
            func(fs[1..$], n * (fs[0].n ^^ c));
        }
    }

    func(factors(n), 1);
    sort(list);
    return list;
}
//nまでの素数のリスト
long[] primes(size_t n) pure
{
    if(n<2)return [];
    auto table = new long[n+1];
    long[] res;
    for(size_t i = 2;i<=n;i++)
    {
        if(table[i]==-1) continue;
        for(size_t a = i;a<table.length;a+=i)
        {
            table[a] = -1;
        }
        res ~= i;
    }
    return res;
}
//素数判定
bool isPrime(long n) pure
{
    if (n <= 1)
        return false;
    if (n == 2)
        return true;
    if (n % 2 == 0)
        return false;
    for (long i = 3; i ^^ 2 <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}

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

long calc(long a, long b, long c) {
   auto delta = abs(a-b);
   if (c < delta) {
       return min(a, b) + c;
   } else {
       return max(a, b) + (c - delta) / 2;
   }
}

void main() {
    int n;
    readf("%s", n);
    for (auto i = 0; i < n; i++) {
        long a, b, c;
        readf(" %s %s %s", a, b, c);
        auto result = fold!(max)([
                calc(a, b, c),
                calc(a, c, b),
                calc(b, c, a)
        ]);
        writeln(result);
    }
}

module main;

import std.stdio;

void main(string[] args){
    long n, input, sum;
    scanf("%lld", &n);
    while (n--) {
        sum = 0;
        for (int i = 0; i < 3; i++ ) {
            scanf("%lld", &input);
            sum += input;
        }
        printf("%lld\n", sum / 2);
    }
}

import std.stdio;
void main()
{
    int n;
    readf(" %s", &n);

    for(int i = 0; i < n; i++){
        long a, b, c;
        readf(" %s %s %s", &a, &b, &c);
        long total = (a + b + c) / 2;
        writeln(total);
    }
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (i; 0..q)
	{
		auto a = RDA;
		a.sort();
		long x, y, z;
		x = a[0];
		y = a[1];
		z = a[2];

		long d = y - x;
		long x2 = min(z, d);
		x += x2;
		z -= x2;
		x += z / 2;
		ans[i] = x;
	}

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

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (i; 0..q)
	{
		auto a = RDA;
		a.sort();
		auto b = abs(a[0] - a[1]);
		auto c = abs(a[1] - a[2]);
		long x, y, z;
		if (b < c)
		{
			x = a[0];
			y = a[1];
			z = a[2];
		}
		else
		{
			x = a[1];
			y = a[2];
			z = a[0];
		}
		auto d = y - x;
		auto x2 = min(z, d);
		x += x2;
		z -= x2;
		x += z / 2;
		ans[i] = x;
	}

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


Shubham has a binary string $$$s$$$. A binary string is a string containing only characters "0" and "1".He can perform the following operation on the string any amount of times:   Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. A string is called good if it does not contain "010" or "101" as a subsequence  — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.

The first line of the input contains a single integer $$$t$$$ $$$(1\le t \le 100)$$$ — the number of test cases. Each of the next $$$t$$$ lines contains a binary string $$$s$$$ $$$(1 \le |s| \le 1000)$$$.

For every string, output the minimum number of operations required to make it good.

NoteIn test cases $$$1$$$, $$$2$$$, $$$5$$$, $$$6$$$ no operations are required since they are already good strings.For the $$$3$$$rd test case: "001" can be achieved by flipping the first character  — and is one of the possible ways to get a good string.For the $$$4$$$th test case: "000" can be achieved by flipping the second character  — and is one of the possible ways to get a good string.For the $$$7$$$th test case: "000000" can be achieved by flipping the third and fourth characters  — and is one of the possible ways to get a good string.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip.map !(q{a == '1'}).array;
		auto n = s.length.to !(int);
		auto total = s.sum;
		auto cur = 0;
		size_t res = n;
		foreach (i; 0..n)
		{
			res = min (res, cur + (n - i) - (total - cur));
			res = min (res, i - cur + (total - cur));
			cur += s[i];
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = long.max;
		foreach (i; 0..s.length)
		{
			long cnt1;
			foreach (j; 0..i)
			{
				if (s[j] == '0')
					++cnt1;
			}
			long cnt2;
			foreach (j; i..s.length)
			{
				if (s[j] == '0')
					++cnt2;
			}
			debug writeln(cnt1, ":", cnt2);
			ans[ti].chmin(min(cnt1, i-cnt1) + min(cnt2, s.length-i-cnt2));
		}
	}

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


Qpwoeirut has taken up architecture and ambitiously decided to remodel his city.Qpwoeirut's city can be described as a row of $$$n$$$ buildings, the $$$i$$$-th ($$$1 \le i \le n$$$) of which is $$$h_i$$$ floors high. You can assume that the height of every floor in this problem is equal. Therefore, building $$$i$$$ is taller than the building $$$j$$$ if and only if the number of floors $$$h_i$$$ in building $$$i$$$ is larger than the number of floors $$$h_j$$$ in building $$$j$$$.Building $$$i$$$ is cool if it is taller than both building $$$i-1$$$ and building $$$i+1$$$ (and both of them exist). Note that neither the $$$1$$$-st nor the $$$n$$$-th building can be cool.To remodel the city, Qpwoeirut needs to maximize the number of cool buildings. To do this, Qpwoeirut can build additional floors on top of any of the buildings to make them taller. Note that he cannot remove already existing floors.Since building new floors is expensive, Qpwoeirut wants to minimize the number of floors he builds. Find the minimum number of floors Qpwoeirut needs to build in order to maximize the number of cool buildings.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$3 \le n \le 10^5$$$) — the number of buildings in Qpwoeirut's city. The second line of each test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$) — the number of floors in each of the buildings of the city. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the minimum number of additional floors Qpwoeirut needs to build in order to maximize the number of cool buildings.

NoteIn the first test case, it is optimal for Qpwoeirut to make the second building cool by building $$$2$$$ additional floors on top of it, making it taller than both of its adjacent buildings. The final heights of buildings will be $$$[2, \underline{3}, 2]$$$.  In the second test case, the number of cool buildings is already maximized, so Qpwoeirut does not need to do anything.In the third test case, it is optimal for Qpwoeirut to make the third and fifth buildings cool by building $$$2$$$ additional floors onto the third building and $$$1$$$ additional floor onto the fifth building. The final heights of buildings will be $$$[3, 1, \underline{6}, 5, \underline{6}, 2]$$$.  It can be shown that it is impossible to make more than $$$2$$$ of the buildings cool, or to make $$$2$$$ buildings cool using fewer than $$$3$$$ additional floors.In the fourth test case, Qpwoeirut can either make the second building cool, or he can make the third building cool. Either way, he will be building $$$3$$$ additional floors and maximizing the number of cool buildings. The final heights of buildings will be $$$[4, 2, \underline{4}, 3, 5, 3, 6, 1]$$$ or $$$[4, \underline{5}, 1, 3, 5, 3, 6, 1]$$$.

// cheese-cracker [2022-07-18]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    long evsum = 0;
    long osum = 0;
    auto len = new long[](n);
    long[] es;
    long[] os;
    es ~= 0;
    os ~= 0;
    for(int i = 1; i < n-1; ++i){
        long lenreq = max(arr[i+1] + 1 , arr[i-1] + 1);
        len[i] = max(lenreq - arr[i], 0);
        if(i % 2 == 0){
            evsum += max(lenreq - arr[i], 0);
        }else{
            osum += max(lenreq - arr[i], 0);
        }
        es ~= evsum;
        os ~= osum;
    }
    show(len);
    if(n <= 2){
        writeln(0);
        return;
    }
    if(n % 2){
        writeln(osum);
    }else{
        long msum = min(evsum, osum);
        for(int i = 1; i < n-1; ++i){
            long csum;
            csum = os[i-1] + (evsum - es[i]);
            msum = min(csum, msum);
        }
        writeln(msum);
    }
}

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

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

// cheese-cracker [2022-07-18]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    long evsum = 0;
    long osum = 0;
    auto len = new long[](n);
    for(int i = 1; i < n-1; ++i){
        long lenreq = max(arr[i+1] + 1 , arr[i-1] + 1);
        len[i] = max(lenreq - arr[i], 0);
        if(i % 2 == 0){
            evsum += max(lenreq - arr[i], 0);
        }else{
            osum += max(lenreq - arr[i], 0);
        }
    }
    show(len);
    if(n <= 2){
        writeln(0);
        return;
    }
    if(n % 2){
        writeln(osum);
    }else{
        long mevsum = evsum;
        long mosum = osum;
        int i = 2;
        mevsum = min(evsum - len[i] + len[i-1], mevsum);
        i = n-3;
        mosum = min(osum - len[i] + len[i+1], mosum);

        show(mevsum, mosum);
        writeln(min(mevsum, mosum));
    }
}

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

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