Monocarp is planning to host a martial arts tournament. There will be three divisions based on weight: lightweight, middleweight and heavyweight. The winner of each division will be determined by a single elimination system.In particular, that implies that the number of participants in each division should be a power of two. Additionally, each division should have a non-zero amount of participants.$$$n$$$ participants have registered for the tournament so far, the $$$i$$$-th of them weighs $$$a_i$$$. To split participants into divisions, Monocarp is going to establish two integer weight boundaries $$$x$$$ and $$$y$$$ ($$$x < y$$$). All participants who weigh strictly less than $$$x$$$ will be considered lightweight. All participants who weigh greater or equal to $$$y$$$ will be considered heavyweight. The remaining participants will be considered middleweight.It's possible that the distribution doesn't make the number of participants in each division a power of two. It can also lead to empty divisions. To fix the issues, Monocarp can invite an arbitrary number of participants to each division.Note that Monocarp can't kick out any of the $$$n$$$ participants who have already registered for the tournament.However, he wants to invite as little extra participants as possible. Help Monocarp to choose $$$x$$$ and $$$y$$$ in such a way that the total amount of extra participants required is as small as possible. Output that amount.

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 a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of the registered participants. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the weights of the registered participants. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the smallest number of extra participants Monocarp is required to invite after he chooses the weight boundaries $$$x$$$ and $$$y$$$.

NoteIn the first testcase of the example, Monocarp can choose $$$x=2$$$ and $$$y=3$$$. Lightweight, middleweight and heavyweight divisions will have $$$2$$$, $$$1$$$ and $$$1$$$ participants, respectively. They all are powers of two, so no extra participants are required.In the second testcase of the example, regardless of the choice of $$$x$$$ and $$$y$$$, one division will have $$$1$$$ participant, the rest will have $$$0$$$. Thus, Monocarp will have to invite $$$1$$$ participant into both of the remaining divisions.In the third testcase of the example, Monocarp can choose $$$x=1$$$ and $$$y=2$$$. Lightweight, middleweight and heavyweight divisions will have $$$0$$$, $$$3$$$ and $$$3$$$ participants, respectively. So an extra participant is needed in each division.In the fourth testcase of the example, Monocarp can choose $$$x=8$$$ and $$$y=9$$$. Lightweight, middleweight and heavyweight divisions will have $$$8$$$, $$$0$$$ and $$$0$$$ participants, respectively. Middleweight and heavyweight division need an extra participant each.

void main() { runSolver(); }

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

  long[] pow2 = 19L.iota.map!"2 ^^ a".array;
  long extraPow2(long x) {
    long t = 1;
    while(x > t) t *= 2;
    return t - x;
  }

  pow2.deb;

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

      long[] acc = [0];
      foreach(g; H.sort.group) acc ~= acc[$ - 1] + g[1];
      auto accs = acc.assumeSorted;

      long ans = long.max;
      auto p2 = pow2.filter!(p => p <= N + extraPow2(N)).array;
      foreach(a; p2) foreach(b; p2) foreach(c; p2) {
        long cur;
        long ex;
        long sum;
        foreach(x; [a, b, c]) {
          auto r = accs.upperBound(cur).lowerBound(x + cur + 1);
          if (r.empty) {
            ex++;
            sum++;
          } else {
            // [a, b, c, x, r.back, cur].deb;
            ex += x - r.back + cur;
            sum += x;
            cur = r.back;
          }
        }
        if (cur == accs[$ - 1]) ans = min(ans, ex);
      }

      return ans;
    }

    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"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

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

immutable int logLimit = 20;

int fun (int len)
{
	if (len == 0)
	{
		return 1;
	}
	int cur = len;
	while (cur & (cur - 1))
	{
		cur += cur & -cur;
	}
	debug {writeln ("fun (", len, ") = ", cur, " - ", len);}
	return cur - len;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);

		auto prev = new int [n];
		prev[0] = -1;
		foreach (i; 1..n)
		{
			prev[i] = (a[i] == a[i - 1]) ? prev[i - 1] : i - 1;
		}
		auto next = new int [n];
		next[n - 1] = n;
		foreach_reverse (i; 0..n - 1)
		{
			next[i] = (a[i] == a[i + 1]) ? next[i + 1] : i + 1;
		}

		int res = int.max;
		foreach (logLo; 0..logLimit)
		{
			int lo = min (n - 1, 0 + (1 << logLo));
			lo = prev[lo] + 1;
			foreach (logHi; 0..logLimit)
			{
				int hi = max (0, n - 1 - (1 << logHi));
				hi = next[hi] - 0;
				hi = max (hi, lo);

				debug {writeln (lo, " ", hi - lo, " ", n - hi);}
				res = min (res, fun (lo) + fun (hi - lo) +
				    fun (n - hi));
				debug {writeln ("res = ", res);}
			}
		}
		writeln (res);
	}
}

void main() { runSolver(); }

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

  long[] pow2 = 19L.iota.map!"2 ^^ a".array;
  long extraPow2(long x) {
    long t = 1;
    while(x > t) t *= 2;
    return t - x;
  }

  pow2.deb;

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

      long[] acc = [0];
      foreach(g; H.sort.group) acc ~= acc[$ - 1] + g[1];
      auto accs = acc.assumeSorted;

      long ans = long.max;
      auto p2 = pow2.filter!(p => p <= N + extraPow2(N)).array;
      foreach(a; p2) foreach(b; p2) foreach(c; p2) {
        long cur;
        long ex;
        long sum;
        foreach(x; [a, b, c]) {
          auto r = accs.upperBound(cur).lowerBound(x + cur + 1);
          if (r.empty) {
            ex++;
            sum++;
          } else {
            // [a, b, c, x, r.back, cur].deb;
            ex += x - r.back + cur;
            sum += x;
            cur = r.back;
          }
        }
        if (sum >= N) ans = min(ans, ex);
      }

      return ans;
    }

    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"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

void main() { runSolver(); }

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

  long[] pow2 = 19L.iota.map!"2 ^^ a".array;
  long extraPow2(long x) {
    long t = 1;
    while(x > t) t *= 2;
    return t - x;
  }

  pow2.deb;

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

      long[] acc = [0];
      foreach(g; H.sort.group) acc ~= acc[$ - 1] + g[1];
      auto accs = acc.assumeSorted;

      long ans = long.max;
      auto p2 = pow2.filter!(p => p <= N + extraPow2(N)).array;
      foreach(a; p2) foreach(b; p2) foreach(c; p2) {
        long cur;
        long ex;
        foreach(x; [a, b, c]) {
          auto r = accs.upperBound(cur).lowerBound(x + cur + 1);
          if (r.empty) {
            ex++;
          } else {
            // [a, b, c, x, r.back, cur].deb;
            ex += x - r.back + cur;
            cur = r.back;
          }
        }
        ans = min(ans, ex);
      }

      return ans;
    }

    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"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

void main() { runSolver(); }

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

  long[] pow2 = 19L.iota.map!"2 ^^ a".array;
  long extraPow2(long x) {
    long t = 1;
    while(x > t) t *= 2;
    return t - x;
  }

  pow2.deb;

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

      long[] acc = [0];
      foreach(g; H.sort.group) acc ~= acc[$ - 1] + g[1];
      auto accs = acc.assumeSorted;

      long ans = long.max;
      auto p2 = pow2.filter!(p => p <= N).array;
      foreach(a; p2) foreach(b; p2) foreach(c; p2) {
        long cur;
        long ex;
        foreach(x; [a, b, c]) {
          auto r = accs.upperBound(cur).lowerBound(x + cur + 1);
          if (r.empty) {
            ex++;
          } else {
            // [a, b, c, x, r.back, cur].deb;
            ex += x - r.back + cur;
            cur = r.back;
          }
        }
        ans = min(ans, ex);
      }

      return ans;
    }

    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"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}


Hooray! Polycarp turned $$$n$$$ years old! The Technocup Team sincerely congratulates Polycarp!Polycarp celebrated all of his $$$n$$$ birthdays: from the $$$1$$$-th to the $$$n$$$-th. At the moment, he is wondering: how many times he turned beautiful number of years?According to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: $$$1$$$, $$$77$$$, $$$777$$$, $$$44$$$ and $$$999999$$$. The following numbers are not beautiful: $$$12$$$, $$$11110$$$, $$$6969$$$ and $$$987654321$$$.Of course, Polycarpus uses the decimal numeral system (i.e. radix is 10).Help Polycarpus to find the number of numbers from $$$1$$$ to $$$n$$$ (inclusive) that are beautiful.

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 test case consists of one line, which contains a positive integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — how many years Polycarp has turned.

Print $$$t$$$ integers — the answers to the given test cases in the order they are written in the test. Each answer is an integer: the number of beautiful years between $$$1$$$ and $$$n$$$, inclusive.

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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (i; 0..t)
	{
		auto n = RD;
		long x = 10;
		while (n >= x)
		{
			ans[i] += 9;
			x *= 10;
		}
		auto y = n / (x / 10);
		ans[i] += y-1;
		while (y / 10 != 0)
			y /= 10;
		auto z = y;
		debug writeln("z:", z);
		while (z <= n)
		{
			y *= 10;
			z += y;
		}
		long cnt1;
		while (z != 0)
		{
			z /= 10;
			++cnt1;
		}
		long cnt2;
		while (n != 0)
		{
			n /= 10;
			++cnt2;
		}
		debug writeln(cnt1, ":", cnt2);
		if (cnt1 > cnt2)
			++ans[i];
	}

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


Sereja has painted n distinct points on the plane. The coordinates of each point are integers. Now he is wondering: how many squares are there with sides parallel to the coordinate axes and with points painted in all its four vertexes? Help him, calculate this number.

The first line contains integer n (1 ≤ n ≤ 105). Each of the next n lines contains two integers xi, yi (0 ≤ xi, yi ≤ 105), the integers represent the coordinates of the i-th point. It is guaranteed that all the given points are distinct.

In a single line print the required number of squares.

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

immutable M = 100_005;
immutable L = 400;

int N;
int[] X, Y;

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

		int[] cnt = new int[M];
		int[][] ys = new int[][M];
		bool[int][] has = new bool[int][M];
		foreach (i; 0 .. N) {
			++cnt[X[i]];
			ys[X[i]] ~= Y[i];
			has[X[i]][Y[i]] = true;
		}
		foreach (x; 0 .. M) {
			ys[x].sort();
		}

		long ans;

		foreach (x; 0 .. M) if (2 <= cnt[x] && cnt[x] <= L) {
			foreach (i; 0 .. cnt[x]) foreach (j; i + 1 .. cnt[x]) {
				const yi = ys[x][i];
				const yj = ys[x][j];
				foreach (s; [ +1, -1 ]) {
					const xx = x + s * (yj - yi);
					if (0 <= xx && xx < M) {
						if (s < 0 && cnt[xx] <= L) {
							continue;
						}
						if (yi in has[xx] && yj in has[xx]) {
							++ans;
						}
					}
				}
			}
		}

		int[] bigs;
		foreach (x; 0 .. M) if (cnt[x] > L) {
			bigs ~= x;
		}
		foreach (i; 0 .. bigs.length) foreach (j; i + 1 .. bigs.length) {
			const xi = bigs[i];
			const xj = bigs[j];
			for (int k = 0, l = 0; k < cnt[xi] && l < cnt[xj]; ) {
				if (ys[xi][k] == ys[xj][l]) {
					const yy = ys[xi][k] + (xj - xi);
					if (yy in has[xi] && yy in has[xj]) {
						++ans;
					}
				}
				if (ys[xi][k] <= ys[xj][l]) {
					++k;
				} else {
					++l;
				}
			}
		}

		writeln(ans);

	}
	} catch (EOFException) {}
}


Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters.The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let's assume that the point $$$x = 0$$$ is where these parts meet.The right part of the corridor is filled with $$$n$$$ monsters — for each monster, its initial coordinate $$$x_i$$$ is given (and since all monsters are in the right part, every $$$x_i$$$ is positive).The left part of the corridor is filled with crusher traps. If some monster enters the left part of the corridor or the origin (so, its current coordinate becomes less than or equal to $$$0$$$), it gets instantly killed by a trap.The main weapon Ivan uses to kill the monsters is the Phoenix Rod. It can launch a missile that explodes upon impact, obliterating every monster caught in the explosion and throwing all other monsters away from the epicenter. Formally, suppose that Ivan launches a missile so that it explodes in the point $$$c$$$. Then every monster is either killed by explosion or pushed away. Let some monster's current coordinate be $$$y$$$, then:  if $$$c = y$$$, then the monster is killed;  if $$$y < c$$$, then the monster is pushed $$$r$$$ units to the left, so its current coordinate becomes $$$y - r$$$;  if $$$y > c$$$, then the monster is pushed $$$r$$$ units to the right, so its current coordinate becomes $$$y + r$$$. Ivan is going to kill the monsters as follows: choose some integer point $$$d$$$ and launch a missile into that point, then wait until it explodes and all the monsters which are pushed to the left part of the corridor are killed by crusher traps, then, if at least one monster is still alive, choose another integer point (probably the one that was already used) and launch a missile there, and so on.What is the minimum number of missiles Ivan has to launch in order to kill all of the monsters? You may assume that every time Ivan fires the Phoenix Rod, he chooses the impact point optimally.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. The first line of each query contains two integers $$$n$$$ and $$$r$$$ ($$$1 \le n, r \le 10^5$$$) — the number of enemies and the distance that the enemies are thrown away from the epicenter of the explosion. The second line of each query contains $$$n$$$ integers $$$x_i$$$ ($$$1 \le x_i \le 10^5$$$) — the initial positions of the monsters. It is guaranteed that sum of all $$$n$$$ over all queries does not exceed $$$10^5$$$.

For each query print one integer — the minimum number of shots from the Phoenix Rod required to kill all monsters.

NoteIn the first test case, Ivan acts as follows:   choose the point $$$3$$$, the first monster dies from a crusher trap at the point $$$-1$$$, the second monster dies from the explosion, the third monster is pushed to the point $$$7$$$;  choose the point $$$7$$$, the third monster dies from the explosion. In the second test case, Ivan acts as follows:   choose the point $$$5$$$, the first and fourth monsters die from the explosion, the second monster is pushed to the point $$$1$$$, the third monster is pushed to the point $$$2$$$;  choose the point $$$2$$$, the first monster dies from a crusher trap at the point $$$0$$$, the second monster dies from the explosion.

// https://codeforces.com/problemset/problem/1238/B
import std.algorithm;
import std.container.rbtree;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

    foreach(query; 0..q) {
        int n, r;
        readf("%s %s\n", &n, &r);

        int[] x = readln.split.map!(to!int).array;

        auto monsters = redBlackTree!"a > b"(x);

        int damage = 0;

        while(damage*r < monsters.front()) {
            auto monster = monsters.front();
            monsters.removeFront();
            damage += 1;
        }
        damage.writeln;
    }
}

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 n = RD;
		auto r = RD;
		auto x = RDA;
		x.sort!"a > b"();
		long cnt, last;
		foreach (e; x)
		{
			if (e <= cnt * r)
			{
				break;
			}
			else if (e == last)
			{
				continue;
			}
			++cnt;
			last = e;
		}
		ans[i] = cnt;
	}

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


Manao's friends often send him new songs. He never listens to them right away. Instead, he compiles them into a playlist. When he feels that his mind is open to new music, he opens the playlist and starts to listen to the songs.Of course, there are some songs that Manao doesn't particuarly enjoy. To get more pleasure from the received songs, he invented the following procedure of listening to the playlist:  If after listening to some song Manao realizes that he liked it, then he remembers it and starts to listen to the next unlistened song.  If after listening to some song Manao realizes that he did not like it, he listens to all the songs he liked up to this point and then begins to listen to the next unlistened song. For example, if Manao has four songs in the playlist, A, B, C, D (in the corresponding order) and he is going to like songs A and C in the end, then the order of listening is the following:  Manao listens to A, he likes it, he remembers it.  Manao listens to B, he does not like it, so he listens to A, again.  Manao listens to C, he likes the song and he remembers it, too.  Manao listens to D, but does not enjoy it and re-listens to songs A and C. That is, in the end Manao listens to song A three times, to song C twice and songs B and D once. Note that if Manao once liked a song, he will never dislike it on a subsequent listening.Manao has received n songs: the i-th of them is li seconds long and Manao may like it with a probability of pi percents. The songs could get on Manao's playlist in any order, so Manao wants to know the maximum expected value of the number of seconds after which the listening process will be over, for all possible permutations of the songs in the playlist.

The first line contains a single integer n (1 ≤ n ≤ 50000). The i-th of the following n lines contains two integers, separated by a single space — li and pi (15 ≤ li ≤ 1000, 0 ≤ pi ≤ 100) — the length of the i-th song in seconds and the probability that Manao will like the song, in percents.

In a single line print a single real number — the maximum expected listening time over all permutations of songs. The answer will be considered valid if the absolute or relative error does not exceed 10 - 9.

NoteConsider the first test case. If Manao listens to the songs in the order in which they were originally compiled, the mathematical expectation will be equal to 467.5 seconds. The maximum expected value is obtained by putting the first song at the end of the playlist.Consider the second test case. The song which is 360 seconds long should be listened to first. The song 300 seconds long which Manao will dislike for sure should be put in the end.

import std.stdio;
import std.algorithm;
import std.conv;
import std.format;

void main() {
	struct Song {
		int len, percentage;
	}

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

	Song[] arr;
	arr.reserve(n);

	foreach (line; stdin.byLine) {
		Song s;
		line.to!string.formattedRead!"%d %d"(s.len, s.percentage);
		arr ~= s;
	}

	bool compare(Song a, Song b) {
		if (a.percentage == 100 && b.percentage != 100) return true;
		if (a.percentage != 100 && b.percentage == 100) return false;
		double x = a.len * (a.percentage / 100.0) / (1 - a.percentage / 100.0);
		double y = b.len * (b.percentage / 100.0) / (1 - b.percentage / 100.0);
		return x > y;
	}

	sort!compare(arr);

	double answer = 0;
	double exp = 0;
	foreach (s; arr) {
		answer += s.len;
		answer += exp * ((100 - s.percentage) / 100.0);
		exp += s.len * (s.percentage / 100.0);
	}

	writef("%0.12f\n", answer);
}

import std.stdio;
import std.algorithm;
import std.conv;
import std.format;

void main() {
	struct Song {
		int len, percentage;
	}

	int n;
	readf!" %d"(n);

	Song[] arr = new Song[n];
	foreach (i; 0 .. n) {
		readf!" %d %d"(arr[i].len, arr[i].percentage);
	}

	bool compare(Song a, Song b) {
		if (a.percentage == 100 && b.percentage != 100) return true;
		if (a.percentage != 100 && b.percentage == 100) return false;
		double x = a.len * (a.percentage / 100.0) / (1 - a.percentage / 100.0);
		double y = b.len * (b.percentage / 100.0) / (1 - b.percentage / 100.0);
		return x > y;
	}

	sort!compare(arr);

	double answer = 0;
	double exp = 0;
	foreach (s; arr) {
		answer += s.len;
		answer += exp * ((100 - s.percentage) / 100.0);
		exp += s.len * (s.percentage / 100.0);
	}

	writef("%0.12f\n", answer);
}

import std.stdio;
import std.algorithm;

void main() {
	struct Song {
		int len, percentage;
	}

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

	Song[] arr = new Song[n];

	foreach (i; 0 .. n) {
		scanf("%d %d", &arr[i].len, &arr[i].percentage);
	}

	bool compare(Song a, Song b) {
		if (a.percentage == 100 && b.percentage != 100) return true;
		if (a.percentage != 100 && b.percentage == 100) return false;
		double x = a.len * (a.percentage / 100.0) / (1 - a.percentage / 100.0);
		double y = b.len * (b.percentage / 100.0) / (1 - b.percentage / 100.0);
		return x > y;
	}

	sort!compare(arr);

	double answer = 0;
	double exp = 0;
	foreach (s; arr) {
		answer += s.len;
		answer += exp * ((100 - s.percentage) / 100.0);
		exp += s.len * (s.percentage / 100.0);
	}

	writef("%0.12f\n", answer);
}

import std.stdio;
import std.algorithm;
import std.conv;
import std.format;

void main() {
	struct Song {
		int len, percentage;
	}

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

	Song[] arr = new Song[n];
	foreach (i; 0 .. n) {
		scanf("%d %d", &arr[i].len, &arr[i].percentage);
	}

	bool compare(Song a, Song b) {
		if (a.percentage == 100 && b.percentage != 100) return true;
		if (a.percentage != 100 && b.percentage == 100) return false;
		double x = a.len * (a.percentage / 100.0) / (1 - a.percentage / 100.0);
		double y = b.len * (b.percentage / 100.0) / (1 - b.percentage / 100.0);
		return x > y;
	}

	sort!compare(arr);

	double answer = 0;
	double exp = 0;
	foreach (s; arr) {
		answer += s.len;
		answer += exp * ((100 - s.percentage) / 100.0);
		exp += s.len * (s.percentage / 100.0);
	}

	writef("%0.12f\n", answer);
}

import std.stdio;
import std.algorithm;
import std.conv;
import std.format;

void main() {
	struct Song {
		int len, percentage;
	}

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

	Song[] arr;

	foreach (line; stdin.byLine) {
		Song s;
		line.to!string.formattedRead!"%d %d"(s.len, s.percentage);
		arr ~= s;
	}

	bool compare(Song a, Song b) {
		if (a.percentage == 100 && b.percentage != 100) return true;
		if (a.percentage != 100 && b.percentage == 100) return false;
		double x = a.len * (a.percentage / 100.0) / (1 - a.percentage / 100.0);
		double y = b.len * (b.percentage / 100.0) / (1 - b.percentage / 100.0);
		return x > y;
	}

	sort!compare(arr);

	double answer = 0;
	double exp = 0;
	foreach (s; arr) {
		answer += s.len;
		answer += exp * ((100 - s.percentage) / 100.0);
		exp += s.len * (s.percentage / 100.0);
	}

	writef("%0.12f\n", answer);
}

import std.stdio;
import std.algorithm;
import std.conv;
import std.format;

void r(ref int d) { scanf("%d", &d); }
void r(ref long d) { scanf("%lld", &d); }
void r(ref double d) { scanf("%f", &d); }

void main() {
	struct Song {
		int len, percentage;
	}

	int n; r(n);

	Song[] arr = new Song[n];
	foreach (i; 0 .. n) {
		r(arr[i].len);
		r(arr[i].percentage);
	}

	bool compare(Song a, Song b) {
		if (a.percentage == 100 && b.percentage != 100) return true;
		if (a.percentage != 100 && b.percentage == 100) return false;
		double x = a.len * (a.percentage / 100.0) / (1 - a.percentage / 100.0);
		double y = b.len * (b.percentage / 100.0) / (1 - b.percentage / 100.0);
		return x > y;
	}

	sort!compare(arr);

	double answer = 0;
	double exp = 0;
	foreach (s; arr) {
		answer += s.len;
		answer += exp * ((100 - s.percentage) / 100.0);
		exp += s.len * (s.percentage / 100.0);
	}

	writef("%0.12f\n", answer);
}

import std.stdio;
import std.algorithm;
import std.conv;
import std.format;

void r(ref int d) { scanf("%d", &d); }
void r(ref int a, ref int b) { scanf("%d %d", &a, &b); }
void r(ref long d) { scanf("%lld", &d); }
void r(ref double d) { scanf("%f", &d); }

void main() {
	struct Song {
		int len, percentage;
	}

	int n; r(n);

	Song[] arr = new Song[n];
	foreach (i; 0 .. n) {
		r(arr[i].len, arr[i].percentage);
	}

	bool compare(Song a, Song b) {
		if (a.percentage == 100 && b.percentage != 100) return true;
		if (a.percentage != 100 && b.percentage == 100) return false;
		double x = a.len * (a.percentage / 100.0) / (1 - a.percentage / 100.0);
		double y = b.len * (b.percentage / 100.0) / (1 - b.percentage / 100.0);
		return x > y;
	}

	sort!compare(arr);

	double answer = 0;
	double exp = 0;
	foreach (s; arr) {
		answer += s.len;
		answer += exp * ((100 - s.percentage) / 100.0);
		exp += s.len * (s.percentage / 100.0);
	}

	writef("%0.12f\n", answer);
}

import std.stdio;
import std.algorithm;
import std.conv;
import std.format;

void main() {
	struct Song {
		int len, percentage;
	}

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

	Song[] arr;

	foreach (line; stdin.byLine) {
		Song s;
		line.to!string.formattedRead!"%d %d"(s.len, s.percentage);
		arr ~= s;
	}

	writeln(arr);
	return;

	bool compare(Song a, Song b) {
		if (a.percentage == 100 && b.percentage != 100) return true;
		if (a.percentage != 100 && b.percentage == 100) return false;
		double x = a.len * (a.percentage / 100.0) / (1 - a.percentage / 100.0);
		double y = b.len * (b.percentage / 100.0) / (1 - b.percentage / 100.0);
		return x > y;
	}

	sort!compare(arr);

	double answer = 0;
	double exp = 0;
	foreach (s; arr) {
		answer += s.len;
		answer += exp * ((100 - s.percentage) / 100.0);
		exp += s.len * (s.percentage / 100.0);
	}

	writef("%0.12f\n", answer);
}


Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).You are given an integer $$$n$$$. You need to find two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \le l < r \le 10^{18}$$$ and $$$l + (l + 1) + \ldots + (r - 1) + r = n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{18}$$$).

For each test case, print the two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \le l < r \le 10^{18}$$$ and $$$l + (l + 1) + \ldots + (r - 1) + r = n$$$.  It can be proven that an answer always exists. If there are multiple answers, print any.

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

void solve(){
    ll n = scan;
    writeln(-(n-1), " ", n);
}

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

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

void main()
{
    int t;
    scanf("%d", &t);
    foreach(_; 0..t)
    {
        long n;
        scanf("%lld", &n);
        getchar();
        writeln(-1 * (n - 1), ' ', n);
    }
}


A Pythagorean triple is a triple of integer numbers $$$(a, b, c)$$$ such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to $$$a$$$, $$$b$$$ and $$$c$$$, respectively. An example of the Pythagorean triple is $$$(3, 4, 5)$$$.Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: $$$c = a^2 - b$$$.Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple $$$(3, 4, 5)$$$: $$$5 = 3^2 - 4$$$, so, according to Vasya's formula, it is a Pythagorean triple.When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers $$$(a, b, c)$$$ with $$$1 \le a \le b \le c \le n$$$ such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, print one integer — the number of triples of integers $$$(a, b, c)$$$ with $$$1 \le a \le b \le c \le n$$$ such that they are Pythagorean according both to the real definition and to the formula Vasya came up with.

NoteThe only Pythagorean triple satisfying $$$c = a^2 - b$$$ with $$$1 \le a \le b \le c \le 9$$$ is $$$(3, 4, 5)$$$; that's why the answer for $$$n = 3$$$ is $$$0$$$, and the answer for $$$n = 6$$$ (and for $$$n = 9$$$) is $$$1$$$.

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);
		int res = 0;
		for (int a = 3; ; a += 2)
		{
			int d = a * a;
			int b = d / 2;
			int c = d - b;
			if (c > n)
			{
				break;
			}
			res += 1;
		}
		writeln (res);
	}
}


Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:Given two binary numbers $$$a$$$ and $$$b$$$ of length $$$n$$$. How many different ways of swapping two digits in $$$a$$$ (only in $$$a$$$, not $$$b$$$) so that bitwise OR of these two numbers will be changed? In other words, let $$$c$$$ be the bitwise OR of $$$a$$$ and $$$b$$$, you need to find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will not be equal to $$$c$$$.Note that binary numbers can contain leading zeros so that length of each number is exactly $$$n$$$.Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $$$01010_2$$$ OR $$$10011_2$$$ = $$$11011_2$$$.Well, to your surprise, you are not Rudolf, and you don't need to help him$$$\ldots$$$ You are the security staff! Please find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will be changed.

The first line contains one integer $$$n$$$ ($$$2\leq n\leq 10^5$$$) — the number of bits in each number. The second line contains a binary number $$$a$$$ of length $$$n$$$. The third line contains a binary number $$$b$$$ of length $$$n$$$.

Print the number of ways to swap two bits in $$$a$$$ so that bitwise OR will be changed.

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.chomp.map!(a => a == '1').array;
    auto B = readln.chomp.map!(a => a == '1').array;

    auto cnt = new long[](4);

    foreach (i; 0..N) {
        if (!A[i] && !B[i]) {
            cnt[0] += 1;
        } else if (A[i] && !B[i]) {
            cnt[1] += 1;
        } else if (!A[i] && B[i]) {
            cnt[2] += 1;
        } else {
            cnt[3] += 1;
        }
    }

    auto ans = cnt[0] * cnt[1] + cnt[0] * cnt[3] + cnt[1] * cnt[2];
    ans.writeln;
}

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

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

    auto s = readln.chomp;
    auto t = readln.chomp;

    int oo = 0, oz = 0, zo = 0, zz = 0;
    foreach (a, b; lockstep(s, t)) {
        if (a == '1' && b == '1') ++oo;
        if (a == '1' && b == '0') ++oz;
        if (a == '0' && b == '1') ++zo;
        if (a == '0' && b == '0') ++zz;
    }

    auto ans = cast(long)oo * zz + cast(long)oz * (zo + zz);

    ans.writeln;
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.strip;
		auto t = readln.strip;
		int [2] [2] d;
		foreach (k; 0..n)
		{
			d[s[k] - '0'][t[k] - '0'] += 1;
		}

		long res = 0;
		foreach (i; 0..2)
		{
			foreach (j; 0..2)
			{
				foreach (p; 0..2)
				{
					foreach (q; 0..2)
					{
						if (i != p &&
						    (((i | j) != (p | q)) ||
						    ((i | q) != (p | j))))
						{
							debug {writeln (i, j,
							    p, q, " ", d[i][j],
							    " ", d[p][q]);}
							res += d[i][j] * 1L *
							    d[p][q];
						}
					}
				}
			}
		}
		writeln (res / 2);
	}
}

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

  // const int n=10;
  // auto rnd=Random(unpredictableSeed);
  // auto a=new char[](n), b=new char[](n);
  // foreach(i; 0..n){
  //   a[i]=(uniform!"[]"(0, 1, rnd)+'0').to!(char);
  //   b[i]=(uniform!"[]"(0, 1, rnd)+'0').to!(char);
  // }

  int n; rd(n);
  auto a=readln.chomp.to!(char[]);
  auto b=readln.chomp.to!(char[]);

  long solve(){
    long p, q, r, s;
    foreach(i; 0..n){
      if(a[i]=='0' && b[i]=='0') p++;
      else if(a[i]=='0' && b[i]=='1') q++;
      else if(a[i]=='1' && b[i]=='0') r++;
      else s++;
    }
    return p*r+p*s+q*r;
  }

  long brute(){
    auto _a=a.map!((e)=>(e-'0')).array, _b=b.map!((e)=>(e-'0')).array;
    long ret=0;
    foreach(i; 0..n)foreach(j; 0..i){
      int o1=_a[i]|_b[i], o2=_a[j]|_b[j];
      if(o1!=(_a[j]|_b[i]) || o2!=(_a[i]|_b[j])) ret++;
    }
    return ret;
  }

  // if (solve()!=brute()){
  //   writeln(a);
  //   writeln(b);
  //   writeln(solve());
  //   writeln(brute());
  // }

  writeln(solve());
}

/*
  0 0 p
  0 1 q
  1 0 r
  1 1 s
*/

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

import std.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 N = readInt();
      const A = readToken();
      const B = readToken();

      long[2][2] cnt;
      foreach (i; 0 .. N) {
        ++cnt[A[i] - '0'][B[i] - '0'];
      }

      long ans;
      foreach (p; 0 .. 2) foreach (q; 0 .. 2) foreach (r; 0 .. 2) foreach (s; 0 .. 2) {
        if ((p | q) != (r | q) || (r | s) != (p | s)) {
          if ([p, q] == [r, s]) {
            ans += cnt[p][q] * (cnt[p][q] - 1) / 2;
          } else if ([p, q] < [r, s]) {
            ans += cnt[p][q] * cnt[r][s];
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).

For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...".

NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG".

import std.stdio;
import std.algorithm;

char[] charset = ['R', 'G', 'B'];
int[200005] sum;

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

    foreach (_; 0..q) {
        int n, k;
        readf(" %s %s", n, k);

        readln();
        string s = " " ~ readln();

        auto result = n;
        foreach (j; 0..3) {
            foreach (i; 1..s.length) {
                auto ch = charset[(i + j) % 3];
                if (ch == s[i]) {
                    sum[i] = sum[i-1] + 1;
                } else {
                    sum[i] = sum[i-1];
                }
            }
            foreach(i; k..s.length) {
                result = min(result, k - (sum[i] - sum[i-k]));
            }
        }
        writeln(result);
    }
}

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 n = RD!int;
		auto k = RD!int;
		auto s = RD!string;

		auto dp = new long[3][](n+1);
		auto str = "RGB";
		long cnt = k;
		foreach (j; 0..3)
		{
			foreach (l; 0..n)
			{
				dp[l+1][j] = dp[l][j];
				if (s[l] != str[(j+l)%3])
					++dp[l+1][j];
				if (l+1 >= k)
				{
					cnt = min(cnt, dp[l+1][j] - dp[l+1-k][j]);
				}
			}
		}
		ans[i] = cnt;
	}

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

import std.stdio;
import std.algorithm;

char[] charset = ['R', 'G', 'B'];
int[200005] sum;

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

    foreach (_; 0..q) {
        int n, k;
        readf(" %s %s", n, k);

        readln;
        string s = " " ~ readln;

        auto result = n;
        foreach (j; 0..3) {
            foreach (i; 1..s.length) {
                auto ch = charset[(i + j) % 3];
                if (ch == s[i]) {
                    sum[i] = sum[i-1] + 1;
                } else {
                    sum[i] = sum[i-1];
                }
            }
            foreach(i; k..s.length) {
                result = min(result, k - (sum[i] - sum[i-k]));
            }
        }
        writeln(result);
    }
}


Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 → 2 → 4 → 5. In one second, you can perform one of the two following operations:  Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b;  Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b. According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 → 2 → ... → n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.

The first line contains integers n (1 ≤ n ≤ 105) and k (1 ≤ k ≤ 105) — the number of matryoshkas and matryoshka chains in the initial configuration. The next k lines contain the descriptions of the chains: the i-th line first contains number mi (1 ≤ mi ≤ n), and then mi numbers ai1, ai2, ..., aimi — the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshka ai2, that is nested into matryoshka ai3, and so on till the matryoshka aimi that isn't nested into any other matryoshka). It is guaranteed that m1 + m2 + ... + mk = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.

In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.

NoteIn the first sample test there are two chains: 1 → 2 and 3. In one second you can nest the first chain into the second one and get 1 → 2 → 3.In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds.

import std.stdio;

immutable int NA = -1;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto p = new int [n];
		p[] = NA;
		foreach (j; 0..k)
		{
			int m, prev;
			readf (" %s %s", &m, &prev);
			foreach (i; 1..m)
			{
				int next;
				readf (" %s", &next);
				p[n - next] = n - prev;
				prev = next;
			}
		}

		int res = 0;
		foreach (i; 0..n)
		{
			if (p[i] != NA && p[i] != i + 1)
			{
				p[i] = NA;
				res++;
			}
		}

		foreach_reverse (i; 0..n - 2)
		{
			if (p[i] != NA && p[i + 1] == NA)
			{
				p[i] = NA;
				res++;
			}
		}

		foreach (i; 0..n - 1)
		{
			if (p[i] == NA)
			{
				p[i] = i + 1;
				res++;
			}
		}

		writeln (res);
	}
}

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 NA = -1;

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto p = new int [n];
		p[] = NA;
		foreach (j; 0..k)
		{
			int m;
			readf (" %s", &m);
			int prev;
			readf (" %s", &prev);
			foreach (i; 1..m)
			{
				int next;
				readf (" %s", &next);
				p[n - next] = n - prev;
				prev = next;
			}
		}

		int res = 0;
		foreach (i; 0..n)
		{
			if (p[i] != NA && p[i] != i + 1)
			{
				p[i] = NA;
				res++;
			}
		}

		foreach_reverse (i; 0..n - 2)
		{
			if (p[i] != NA && p[i + 1] == NA)
			{
				p[i] = NA;
				res++;
			}
		}

		foreach (i; 0..n - 1)
		{
			if (p[i] == NA)
			{
				p[i] = i + 1;
				res++;
			}
		}

		foreach (i; 0..n - 1)
		{
			assert (p[i] == i + 1);
		}
		assert (p[n - 1] == NA);

		writeln (res);
	}
}

import std.stdio;

void main(string[] args) {
    //stdin = File("input.txt", "r");

    int n, k;
    readf("%d %d\n", &n, &k);
    int answer = 0;
    foreach (int i; 0..k) {
        int m;
        readf("%d", &m);
        int[] a = new int[m];
        foreach (int j; 0..m) {
            readf(" %d", &a[j]);
        }
        readf("\n");

        if (a[0] == 1) {
            int j = 1;
            while (j < m && a[j] == j + 1) {
                ++j;
            }
            answer += 2 * (m - j + 1) - 1;
        } else {
            answer += 2 * m - 1;
        }
    }
    answer -= 1;
    writeln(answer);
}


Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1,  a2,  ...,  an (1 ≤ ai ≤ 109).

Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.

NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.

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

string readline()
{
	string result = readln();
	if (result[result.length - 1] == '\n') result.length--;
	return result;
}

int main(string[] argv)
{
	int n; scanf("%d", &n);
	int[] money; money.length = n;
	int[] ln; ln.length = n; ln[0] = 1;
	foreach (int i; 0..n)
	{
		scanf("%d", &money[i]);
	}

	int max = 1;
	foreach (int i; 1..n)
	{
		if (money[i] >= money[i-1])
			ln[i] = ln[i-1] + 1;
		else
			ln[i] = 1;

		if (ln[i] > max) max = ln[i];
	}
	printf("%d", max);
	return 0;
}

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

string readline()
{
	string result = readln();
	if (result[result.length - 1] == '\n') result.length--;
	return result;
}

int main(string[] argv)
{
	int n; scanf("%d", &n);
	int[] money; money.length = n;
	int[] ln; ln.length = n; ln[0] = 1;
	foreach (int i; 0..n)
	{
		scanf("%d", &money[i]);
	}

	int max = 0;
	foreach (int i; 1..n)
	{
		if (money[i] >= money[i-1])
			ln[i] = ln[i-1] + 1;
		else
			ln[i] = 1;

		if (ln[i] > max) max = ln[i];
	}
	printf("%d", max);
	return 0;
}


You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.

The first line of the input contains following integers:   n: the number of towers in the building (1 ≤ n ≤ 108),  h: the number of floors in each tower (1 ≤ h ≤ 108),  a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h),  k: total number of queries (1 ≤ k ≤ 104).  Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.

For each query print a single integer: the minimum walking time between the locations in minutes.

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

void main()
{
    int n, h, a, b, k;
    readf("%s %s %s %s %s", &n, &h, &a, &b, &k);
    readln;

    while (k--) {
        int ta, fa, tb, fb;
        readf("%s %s %s %s", &ta, &fa, &tb, &fb);
        readln;

        auto ans = 0;
        if (ta == tb) {
            ans = abs(fa - fb);
        } else {
            if (fa > fb) swap(fa, fb);

            ans = abs(ta - tb);
            if ((fa >= a && fa <= b) || (fb >= a && fb <= b)) {
                ans += abs(fa - fb);
            } else {
                ans += min(abs(fa - a) + abs(fb - a), abs(fa - b) + abs(fb - b));
            }
        }

        writeln(ans);
    }
}

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

  int n, h, a, b, k; rd(n, h, a, b, k);
  struct T{long t, f;}
  import std.math;
  while(k--){
    auto data=new T[](2);
    rd(data[0].t, data[0].f, data[1].t, data[1].f);
    data.sort!"a.t==b.t ? a.f<b.f : a.t<b.t";
    if(data[0].t==data[1].t){
      writeln(abs(data[0].f-data[1].f));
    }else{
      long d=0;
      d+=(data[1].t-data[0].t);
      if(data[0].f<a){
        d+=(a-data[0].f);
        d+=abs(a-data[1].f);
      }else if(data[0].f>b){
        d+=(data[0].f-b);
        d+=abs(b-data[1].f);
      }else{
        d+=abs(data[0].f-data[1].f);
      }
      writeln(d);
    }
  }
}

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

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

  int n, h, a, b, k; rd(n, h, a, b, k);
  struct T{long t, f;}
  import std.math;
  while(k--){
    auto data=new T[](2);
    rd(data[0].t, data[0].f, data[1].t, data[1].f);
    data.sort!"a.t==b.t ? a.f<b.f : a.t<b.t";
    if(data[0].t==data[1].t){
      writeln(abs(data[0].f-data[1].f));
    }else{
      long d=0;
      d+=(data[1].t-data[0].t);
      if(data[0].f<a){
        d+=(a-data[0].f);
        d+=abs(a-data[1].f);
      }else if(data[0].f>b){
        d+=(data[0].f-b);
        d+=abs(b-data[1].f);
      }else{
        d+=abs(a-data[1].f);
      }
      writeln(d);
    }
  }
}

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


You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$).

Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays.

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

void main ()
{
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		long [] s = [0];
		foreach_reverse (c; a)
		{
			s ~= s.back + c;
		}
		reverse (s);
		debug {writeln (s);}

		long res = s[0];
		sort (s[1..$ - 1]);
		reverse (s[1..$ - 1]);
		debug {writeln (s[1..$ - 1]);}
		foreach (i; 1..k)
		{
			res += s[i];
		}

		writeln (res);
	}
}

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

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

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

void main() {
  auto r = new InputReader;
  immutable n = r.next!uint;
  immutable k = r.next!uint;
  immutable a = r.nextA!int(n).idup;
  auto s = new long[n];
  long cur;
  foreach_reverse (i; 0 .. n) {
    cur += a[i];
    s[i] = cur;
  }
  auto res = BigInt(s[0]);
  auto t = new long[n-1];
  s[1 .. n].copy (t);
  debug stderr.writeln (s);
  t.sort ();
  t.reverse ();
  foreach (i; 0 .. k - 1) {
    res += BigInt (t[i]);
  }
  writeln (res);
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){

	int n = read.to!int;
	int k = read.to!int;

	long[] as;
	foreach(i; 0 .. n) as ~= read.to!long;
	log("as:", as);

	S[] bs;
	long sum = 0;
	foreach_reverse(i; 1 .. n){
		sum += as[i];
		bs ~= S(i, sum);
	}
	log("bs:", bs);

	bs.sort!"a.sum>b.sum"();
	log("bs:", bs);

	bool[] ys = new bool[](n);
	foreach(i; 0 .. k - 1){
		log("i:", i, " b:", bs[i]);
		ys[bs[i].id] = 1;
	}
	log("ys:", ys);

	long ans;
	long f = 1;
	foreach(i, a; as){
		if(ys[i]) f += 1;
		ans += f * a;
	}

	ans.writeln;
}

struct S{
	int id;
	long sum;
}


A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer.

The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m.

Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved.

import std.algorithm, std.stdio, std.typecons;
immutable long INF = long.max >> 1;
void main () {
	int n, m, b, k, v;
	readf (" %s %s %s", &n, &m, &b);
	alias Player = Tuple !(int, "x", long, "y", int, "z");
	auto p = new Player [n];
	foreach (ref q; p) {
		readf (" %s %s %s", &q.x, &q.y, &k);
		foreach (j; 0..k) {
			readf (" %s", &v);
			q.z |= 1 << (v - 1);
		}
	}
	p.sort !"a.y < b.y";
	long res = INF;
	auto f = new long [1 << m];
	f[1..$] = INF;
	foreach (q; p) {
		foreach (u; 0..1 << m)
			f[u | q.z] = min (f[u | q.z], f[u] + q.x);
		res = min (res, f[$ - 1] + b * q.y);
	}
	writeln (res < INF ? res : -1);
}

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

immutable long INF = long.max >> 1;

void main ()
{
	int n, m;
	long b;
	while (readf (" %s %s %s", &n, &m, &b) > 0)
	{
		alias Player = Tuple !(int, "x", long, "y", int, "z");
		auto p = new Player [n];
		foreach (ref q; p)
		{
			int k;
			readf (" %s %s %s", &q.x, &q.y, &k);
			q.z = 0;
			foreach (j; 0..k)
			{
				int v;
				readf (" %s", &v);
				v--;
				q.z |= 1 << v;
			}
		}
		sort !("a.y < b.y") (p);
		long res = INF;
		int m2 = 1 << m;
		auto f = new long [m2];
		f[] = INF;
		f[0] = 0L;
		foreach (ref q; p)
		{
			foreach (u; 0..m2)
			{
				int v = u | q.z;
				f[v] = min (f[v], f[u] + q.x);
			}
			debug {writeln (f, ' ', q.y);}
			if (f[m2 - 1] != INF)
			{
				res = min (res, f[m2 - 1] + b * q.y);
			}
		}
		if (res == INF)
		{
			res = -1;
		}
		writeln (res);
	}
}

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

immutable long INF = long.max >> 1;

void main ()
{
	int n, m;
	long b;
	while (readf (" %s %s %s", &n, &m, &b) > 0)
	{
		alias Player = Tuple !(int, "x", long, "y", int, "z");
		auto p = new Player [n];
		foreach (ref q; p)
		{
			int k;
			readf (" %s %s %s", &q.x, &q.y, &k);
			q.z = 0;
			foreach (j; 0..k)
			{
				int v;
				readf (" %s", &v);
				v--;
				q.z |= 1 << v;
			}
		}
		sort !("a.z < b.z") (p);
		long res = INF;
		int m2 = 1 << m;
		auto f = new long [m2];
		f[] = INF;
		f[0] = 0L;
		foreach (ref q; p)
		{
			foreach (u; 0..m2)
			{
				int v = u | q.z;
				f[v] = min (f[v], f[u] + q.x);
			}
			if (f[m2 - 1] != INF)
			{
				res = min (res, f[m2 - 1] + b * q.y);
			}
		}
		if (res == INF)
		{
			res = -1;
		}
		writeln (res);
	}
}


Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.

The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.

For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.

NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		int a, b = int.max;
		foreach (j; 0..n)
		{
			auto l = RD!int;
			auto r = RD!int;
			a = max(a, l);
			b = min(b, r);
		}
		if (a <= b)
			ans[i] = 0;
		else
			ans[i] = a-b;
	}

	foreach (e; ans)
	{
		writeln(e);
	}

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


Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations?Help Yaroslav.

The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value.

In a single line print the answer to the problem — the maximum sum that Yaroslav can get.

NoteIn the first sample you do not need to change anything. The sum of elements equals 150.In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int m = n * 2 - 1;
		auto a = new int [m];
		int s = 0;
		foreach (i; 0..m)
		{
			readf (" %s", &a[i]);
			s += (a[i] <= 0);
			a[i] = abs (a[i]);
		}
		sort (a);
		int res = reduce !("a + b") (a);
		if ((n % 2 == 0) && (s % 2 != 0))
		{
			res -= 2 * a[0];
		}
		writeln (res);
	}
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

int sum(int[] xs) {
    int ret = 0;
    foreach (x; xs) ret += x;
    return ret;
}

void main() {
    int N; scanf("%d\n", &N);
    auto xs = readln.chomp.split(" ").map!(to!int).array;
    xs.sort;
    auto minus = cast(int)xs.count!"a < 0";

    if (N % 2 == 1 || minus % 2 == 0) {
        int ans = 0;
        foreach (x; xs) {
            ans += x.abs;
        }
        writeln(ans);
    } else {
        int ans = 0;
        auto as = xs.filter!"a < 0".array,
             bs = xs.filter!"a >= 0".array;
        ans -= as[0 .. minus - 1].sum;

        if (bs.empty) {
            ans += as.back;
        } else {
            int a = as.back.abs;
            int b = bs.front;
            ans += bs[1 .. $].sum;
            ans += max(a, b) - min(a, b);
        }
        writeln(ans);
    }

}

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

const int oo = 10000000;

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

    int sum = 0, cnt = 0, minx = oo;
    bool has = false;

    for (int i = 0; i < 2 * n - 1; ++i)
    {
	int x;
	scanf("%d", &x);
	sum += abs(x);
	cnt += x < 0;
	minx = min(minx, abs(x));
	if (x == 0)
	    has = true;
    }

    if (n % 2 == 1 || has)
	write(sum);
    else
    {
	if (cnt % 2 == 0)
	    write(sum);
	else
	    write(sum - 2 * minx);
    }
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int m = n * 2 - 1;
		auto a = new int [m];
		int s = 0;
		foreach (i; 0..m)
		{
			readf (" %s", &a[i]);
			s += (a[i] <= 0);
			a[i] = abs (a[i]);
		}
		int res = reduce !("a + b") (a);
		if ((n % 2 == 0) && (s % 2 != 0))
		{
			res -= 2 * a[0];
		}
		writeln (res);
	}
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

int sum(int[] xs) {
    int ret = 0;
    foreach (x; xs) ret += x;
    return ret;
}

void main() {
    int N; scanf("%d\n", &N);
    auto xs = readln.chomp.split(" ").map!(to!int).array;
    xs.sort;
    auto minus = cast(int)xs.count!"a < 0";

    if (N % 2 == 1 || minus % 2 == 0) {
        int ans = 0;
        foreach (x; xs) {
            ans += x.abs;
        }
        writeln(ans);
    } else {
        int ans = 0;
        auto as = xs.filter!"a < 0".array,
             bs = xs.filter!"a >= 0".array;
        ans -= as[0 .. minus - 1].sum;

        if (bs.empty) {
            ans += as.back;
        } else {
            int a = as.back.abs;
            int b = bs.front;
            ans += max(a, b) - min(a, b);
        }
        writeln(ans);
    }

}


In Berland, $$$n$$$ different types of banknotes are used. Banknotes of the $$$i$$$-th type have denomination $$$10^{a_i}$$$ burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly $$$1$$$.Let's denote $$$f(s)$$$ as the minimum number of banknotes required to represent exactly $$$s$$$ burles. For example, if the denominations of banknotes used in Berland are $$$1$$$, $$$10$$$ and $$$100$$$, then $$$f(59) = 14$$$: $$$9$$$ banknotes with denomination of $$$1$$$ burle and $$$5$$$ banknotes with denomination of $$$10$$$ burles can be used to represent exactly $$$9 \cdot 1 + 5 \cdot 10 = 59$$$ burles, and there's no way to do it with fewer banknotes.For a given integer $$$k$$$, find the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes (that is, $$$f(s) > k$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10; 1 \le k \le 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 = a_1 < a_2 < \dots < a_n \le 9$$$).

For each test case, print one integer — the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n;
		long k;
		readf !(" %s %s") (n, k);
		readln;
		k += 1;
		auto a = readln.splitter.map !(to !(long)).array;
		a ~= 18;
		a[] = 10L ^^ a[];
		long res = 0;
		foreach (i; 0..n)
		{
			long next = a[i + 1] / a[i] - 1;
			next = min (next, k);
			k -= next;
			res += a[i] * next;
		}
		writeln (res);
	}
}


Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?

The only line of the input contains single integer n (1 ≤ n ≤ 109) — the length of some side of a right triangle.

Print two integers m and k (1 ≤ m, k ≤ 1018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.

import std.stdio;
import std.string;
import std.math;

int main(string[] s) {
    long x;
    readf("%d", &x);

    long X = x;
    long Y, Z;

    if (x % 2 == 1) {
        Y =  ((x*x) - 1) >> 1;
        Z = Y + 1;
    } else {
        Y = ((x>>1)*(x>>1)) - 1;
        Z = Y + 2;
    }

    if ((Z*Z) == (Y*Y) + (X*X) && Z && Y && X) {
        writeln(Y, " ", Z);
    } else {
        writeln(-1);
    }

    return 0;
}

import std.stdio;
import std.string;
import std.math;

int main(string[] s) {
    size_t x;
    readf("%d", &x);

    size_t X = x;
    size_t Y, Z;

    // Try generate non pair triplet
    if (x % 2 == 1) {
        Y =  ((x*x) - 1) >> 1;
        Z = Y + 1;
    } else {
        Y = ((x>>1)*(x>>1)) - 1;
        Z = Y + 2;
    }

    if (pow(Z, 2) == pow(Y, 2) + pow(X, 2) && Z && Y) {
        writeln(Y, " ", Z);
    } else {
        writeln(-1);
    }

    return 0;
}

import std.stdio;
import std.string;
import std.math;

int main(string[] s) {
    size_t x;
    readf("%d", &x);

    size_t X = x * x;
    size_t Y, Z;

    if (x % 2 == 1) {
        Y = (X -1) >> 1;
    } else {
        x = x << 1;
        x -=1;
        x = cast(size_t)sqrt(cast(float)x);
        Y = (X -1) >> 1;
    }

    Z = Y + 1;;

    if (Z && Y) {
        writeln(Z, " ", Y);
    } else {
        writeln(-1);
    }

    return 0;
}

import std.stdio;
import std.string;
import std.math;

int main(string[] s) {
    size_t x;
    readf("%d", &x);

    size_t X = x;
    size_t Y, Z;

    // Try generate non pair triplet
    if (x % 2 == 1) {
        Y =  ((x*x) - 1) >> 1;
        Z = Y + 1;
    } else {
        Y = ((x>>1)*(x>>1)) - 1;
        Z = Y + 2;
    }

    if (pow(Z, 2) == pow(Y, 2) + pow(X, 2) && Z && X) {
        writeln(Y, " ", Z);
    } else {
        writeln(-1);
    }

    return 0;
}

import std.stdio;
import std.string;
import std.math;

int main(string[] s) {
    size_t x;
    readf("%d", &x);

    size_t X = x;
    size_t Y, Z;

    // Try generate non pair triplet
    if (x % 2 == 1) {
        Y =  ((x*x) - 1) >> 1;
        Z = Y +1;
    } else {
        Y = ((x>>1)*(x>>1)) - 1;
        Z = Y + 2;
    }

    if (pow(Z, 2) == pow(Y, 2) + pow(X, 2)) {
        writeln(Z, " ", Y);
    } else {
        writeln(-1);
    }

    return 0;
}

import std.stdio;
import std.string;
import std.math;

int main(string[] s) {
    size_t x;
    readf("%d", &x);

    size_t X = x;
    size_t Y, Z;

    if (x % 2 == 1) {
        Y =  ((x*x) - 1) >> 1;
        Z = Y + 1;
    } else {
        Y = ((x>>1)*(x>>1)) - 1;
        Z = Y + 2;
    }

    if ((Z*Z) == (Y*Y) + (X*X) && Z && Y) {
        writeln(Y, " ", Z);
    } else {
        writeln(-1);
    }

    return 0;
}

import std.stdio;
import std.string;
import std.math;

int main(string[] s) {
    size_t x;
    readf("%d", &x);

    size_t X = x;
    size_t Y, Z;

    if (x % 2 == 1) {
        Y =  ((x*x) - 1) >> 1;
        Z = Y + 1;
    } else {
        Y = ((x>>1)*(x>>1)) - 1;
        Z = Y + 2;
    }

    if ((Z*Z) == (Y*Y) + (X*X) && Z && Y && X) {
        writeln(Y, " ", Z);
    } else {
        writeln(-1);
    }

    return 0;
}