Mahmoud and Ehab are in the fourth stage now.Dr. Evil has a hidden binary string of length n. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr. Evil up to 15 questions. They tell Dr. Evil some binary string of length n, and Dr. Evil tells the Hamming distance between these two strings. Hamming distance between 2 binary strings of the same length is the number of positions in which they have different symbols. You can find the definition of Hamming distance in the notes section below.Help Mahmoud and Ehab find these two positions.You will get Wrong Answer verdict if   Your queries doesn't satisfy interaction protocol described below.  You ask strictly more than 15 questions and your program terminated after exceeding queries limit. Please note, that you can do up to 15 ask queries and one answer query.  Your final answer is not correct.  You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).If you exceed the maximum number of queries, You should terminate with 0, In this case you'll get Wrong Answer, If you don't terminate you may receive any verdict because you'll be reading from a closed stream .

The first line of input will contain a single integer n (2 ≤ n ≤ 1000) — the length of the hidden binary string.

To print the final answer, print "! pos0 pos1" (without quotes), where pos0 and pos1 are positions of some '0' and some '1' in the string (the string is 1-indexed). Don't forget to flush the output after printing the answer!

NoteHamming distance definition: https://en.wikipedia.org/wiki/Hamming_distanceIn the first test case the hidden binary string is 101, The first query is 000, so the Hamming distance is 2. In the second query the hidden string is still 101 and query is 001, so the Hamming distance is 1.After some queries you find that symbol at position 2 is '0' and symbol at position 1 is '1', so you print "! 2 1".

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

int N;
int[] hoge;

int q(int[] A) {
    write("? ");
    A.map!(a => a.to!string).join("").writeln;
    stdout.flush;
    debug {
        int a = 0;
        foreach (i; 0..N) if (A[i] != hoge[i]) a += 1;
        a.writeln;
        return a;
    }

    return readln.chomp.to!int;
}

void answer(int zero, int one) {
    debug {
        if (hoge[zero - 1] == 0 && hoge[one - 1] == 1)
            writeln("OK");
        else
            writeln("NG");
    }
    writeln("! ", zero, " ", one);
    stdout.flush;
}

void main() {
    N = readln.chomp.to!int;
    debug {
        hoge = readln.split.map!(to!int).array;
    }

    if (N == 2) {
        int a = q([0, 1]);
        if (a == 0)
            answer(1, 2);
        else
            answer(2, 1);
        return;
    }

    int[] ans = [-1, -1];

    auto query = new int[](N);
    int zero = query.q;

    query[0] = 1;
    int zero2 = query.q;
    int target;

    if (zero > zero2) {
        ans[1] = 0;
        target = 0;
    } else {
        ans[0] = 0;
        target = 1;
    }

    query.fill(target);
    int all_cnt = query.q;

    int l = 0;
    int r = N;
    while (r - l > 1) {
        int mid = (l + r) / 2;
        int new_len = mid - l;

        query.fill(target);
        foreach (i; l..mid) query[i] = target ^ 1;
        int cnt = query.q;

        if (all_cnt - cnt == new_len) {
            l = mid;
        } else {
            r = mid;
        }

    }

    ans[target] = l;

    answer(ans[0] + 1, ans[1] + 1);

}

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

int q(int[] A) {
    write("? ");
    A.map!(a => a.to!string).join("").writeln;
    stdout.flush;

    return readln.chomp.to!int;
}

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

    if (N == 2) {
        int a = q([0, 1]);
        if (a == 0)
            "! 1 2".writeln;
        else
            "! 2 1".writeln;
        stdout.flush;
        return;
    }

    int[] ans = [-1, -1];

    auto query = new int[](N);
    int zero = query.q;

    query[0] = 1;
    int zero2 = query.q;
    int target;

    if (zero != zero2) {
        ans[1] = 0;
        target = 0;
    } else {
        ans[0] = 0;
        target = 1;
    }

    query.fill(target);
    int all_cnt = query.q;

    int l = 0;
    int r = N;
    while (r - l > 1) {
        int mid = (l + r) / 2;
        int new_len = mid - l;

        query.fill(target);
        foreach (i; l..mid) query[i] = target ^ 1;
        int cnt = query.q;

        if (all_cnt - cnt == new_len) {
            l = mid;
        } else {
            r = mid;
        }

    }

    ans[target] = l;

    writeln("! ", ans[0] + 1, " ", ans[1] + 1);
    stdout.flush;
}


This is an interactive problem.Jury has hidden a permutation p of integers from 0 to n - 1. You know only the length n. Remind that in permutation all integers are distinct.Let b be the inverse permutation for p, i.e. pbi = i for all i. The only thing you can do is to ask xor of elements pi and bj, printing two indices i and j (not necessarily distinct). As a result of the query with indices i and j you'll get the value , where  denotes the xor operation. You can find the description of xor operation in notes.Note that some permutations can remain indistinguishable from the hidden one, even if you make all possible n2 queries. You have to compute the number of permutations indistinguishable from the hidden one, and print one of such permutations, making no more than 2n queries.The hidden permutation does not depend on your queries.

The first line contains single integer n (1 ≤ n ≤ 5000) — the length of the hidden permutation. You should read this integer first.

When your program is ready to print the answer, print three lines. In the first line print "!". In the second line print single integer answers_cnt — the number of permutations indistinguishable from the hidden one, including the hidden one.  In the third line print n integers p0, p1, ..., pn - 1 (0 ≤ pi < n, all pi should be distinct) — one of the permutations indistinguishable from the hidden one. Your program should terminate after printing the answer.

Notexor operation, or bitwise exclusive OR, is an operation performed over two integers, in which the i-th digit in binary representation of the result is equal to 1 if and only if exactly one of the two integers has the i-th digit in binary representation equal to 1. For more information, see here.In the first example p = [0, 1, 2], thus b = [0, 1, 2], the values  are correct for the given i, j. There are no other permutations that give the same answers for the given queries.The answers for the queries are:   ,  ,  ,  ,  ,  . In the second example p = [3, 1, 2, 0], and b = [3, 1, 2, 0], the values  match for all pairs i, j. But there is one more suitable permutation p = [0, 2, 1, 3], b = [0, 2, 1, 3] that matches all n2 possible queries as well. All other permutations do not match even the shown queries.

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

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

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

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

int N;
debug {
  int[] P, B;
}

int Ask(int i, int j) {
  int ret;
  debug {
    ret = P[i] ^ B[j];
  } else {
    writefln("? %s %s", i, j);
    stdout.flush;
    ret = readInt();
  }
  return ret;
}

void main() {
  N = readInt();
  debug {
    P = new int[N];
    foreach (i; 0 .. N) {
      P[i] = readInt();
    }
    B = new int[N];
    foreach (i; 0 .. N) {
      B[P[i]] = i;
    }
  }

  auto X = new int[N];
  auto Y = new int[N];
  foreach (i; 0 .. N) {
    X[i] = Ask(i, 0);
  }
  foreach (j; 0 .. N) {
    Y[j] = Ask(0, j);
  }

  int ansCnt;
  int[] ans;
  foreach (p0; 0 .. N) {
    const b0 = X[0] ^ p0;
    auto ps = new int[N];
    foreach (i; 0 .. N) {
      ps[i] = X[i] ^ b0;
    }
    auto bs = new int[N];
    foreach (j; 0 .. N) {
      bs[j] = Y[j] ^ p0;
    }
    debug {
      writeln(p0, " ", ps, " ", bs);
    }
    bool ok = true;
    foreach (i; 0 .. N) {
      ok = ok && (0 <= ps[i] && ps[i] < N);
    }
    foreach (j; 0 .. N) {
      ok = ok && (0 <= bs[j] && bs[j] < N);
    }
    if (ok) {
      foreach (i; 0 .. N) {
        ok = ok && (bs[ps[i]] == i);
      }
    }
    if (ok) {
      ++ansCnt;
      if (ans.empty) {
        ans = ps.dup;
      }
    }
  }

  writeln("!");
  writeln(ansCnt);
  foreach (i; 0 .. N) {
    if (i > 0) write(" ");
    write(ans[i]);
  }
  writeln();
  stdout.flush;
}


Many years ago Berland was a small country where only $$$n$$$ people lived. Each person had some savings: the $$$i$$$-th one had $$$a_i$$$ burles.The government considered a person as wealthy if he had at least $$$x$$$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that:   the government chooses some subset of people (maybe all of them);  the government takes all savings from the chosen people and redistributes the savings among the chosen people equally. For example, consider the savings as list $$$[5, 1, 2, 1]$$$: if the government chose the $$$1$$$-st and the $$$3$$$-rd persons then it, at first, will take all $$$5 + 2 = 7$$$ burles and after that will return $$$3.5$$$ burles to the chosen people. As a result, the savings will become $$$[3.5, 1, 3.5, 1]$$$.A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Next $$$2T$$$ lines contain the test cases — two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^9$$$) — the number of people and the minimum amount of money to be considered as wealthy. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial savings of each person. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms.

NoteThe first test case is described in the statement.In the second test case, the government, for example, could carry out two reforms: $$$[\underline{11}, \underline{9}, 11, 9] \rightarrow [10, 10, \underline{11}, \underline{9}] \rightarrow [10, 10, 10, 10]$$$.In the third test case, the government couldn't make even one person wealthy.In the fourth test case, the government could choose all people to carry out a reform: $$$[\underline{9}, \underline{4}, \underline{9}] \rightarrow [7\frac{1}{3}, 7\frac{1}{3}, 7\frac{1}{3}]$$$.

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

int solve() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1].to!long;
    auto A = readln.split.map!(to!long).array;
    A.sort!"a > b";

    long sm = 0;

    foreach (i; 0..N) {
        sm += A[i];
        if (sm < (i + 1) * M) return i;
    }

    return N;
}

void main() {
    auto T = readln.chomp.to!int;
    while (T--) writeln(solve);
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n, x;
		readf !(" %s %s") (n, x);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		long cur = 0;
		int res = 0;
		foreach_reverse (i, c; a)
		{
			cur += c;
			if (cur >= (n - i) * 1L * x)
			{
				res = n - 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;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint;
    const long x = r.next!uint;
    auto a = r.nextA!uint(n);
    sort (a);
    int res;
    long s;
    debug stderr.writeln (a);
    foreach_reverse (z; a) {
      s += z;
      debug stderr.writefln ("s = %d, res = %d, x = %d", s, res, x);
      if (s < x * (res+1)) break;
      ++res;
    }
    writeln (res);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto x = RD;
		auto a = RDA;
		a.sort!"a > b"();
		long s;
		foreach (i; 0..n)
		{
			s += a[i];
			if (s < x*(i+1)) break;
			++ans[ti];
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto x = RD!int;
		auto a = RDA;
		a.sort!"a > b"();
		long s;
		foreach (i; 0..n)
		{
			s += a[i];
			if (s < x*(i+1)) break;
			++ans[ti];
		}
	}

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


Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $$$(0, 0)$$$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $$$OX$$$ or $$$OY$$$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.Alexey wants to make a polyline in such a way that its end is as far as possible from $$$(0, 0)$$$. Please help him to grow the tree this way.Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of sticks Alexey got as a present. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) — the lengths of the sticks.

Print one integer — the square of the largest possible distance from $$$(0, 0)$$$ to the tree end.

NoteThe following pictures show optimal trees for example tests. The squared distance in the first example equals $$$5 \cdot 5 + 1 \cdot 1 = 26$$$, and in the second example $$$4 \cdot 4 + 2 \cdot 2 = 20$$$.

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 n = RD!int;
	auto a = RDA;
	a.sort();
	long y, x;
	foreach (i; 0..n)
	{
		if (i < n/2)
		{
			y += a[i];
		}
		else
		{
			x += a[i];
		}
	}
	auto ans = y^^2 + x^^2;

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


There are $$$n$$$ points on a plane. The $$$i$$$-th point has coordinates $$$(x_i, y_i)$$$. You have two horizontal platforms, both of length $$$k$$$. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same $$$y$$$-coordinate) and have integer borders. If the left border of the platform is $$$(x, y)$$$ then the right border is $$$(x + k, y)$$$ and all points between borders (including borders) belong to the platform.Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same $$$y$$$-coordinate.When you place both platforms on a plane, all points start falling down decreasing their $$$y$$$-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.Your task is to find the maximum number of points you can save if you place both platforms optimally.You have to answer $$$t$$$ independent test cases.For better understanding, please read the Note section below to see a picture for the first test case.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^9$$$) — the number of points and the length of each platform, respectively. The second line of the test case contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), where $$$x_i$$$ is $$$x$$$-coordinate of the $$$i$$$-th point. The third line of the input contains $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$), where $$$y_i$$$ is $$$y$$$-coordinate of the $$$i$$$-th point. All points are distinct (there is no pair $$$1 \le i < j \le n$$$ such that $$$x_i = x_j$$$ and $$$y_i = y_j$$$). It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: the maximum number of points you can save if you place both platforms optimally.

NoteThe picture corresponding to the first test case of the example:Blue dots represent the points, red segments represent the platforms. One of the possible ways is to place the first platform between points $$$(1, -1)$$$ and $$$(2, -1)$$$ and the second one between points $$$(4, 3)$$$ and $$$(5, 3)$$$. Vectors represent how the points will fall down. As you can see, the only point we can't save is the point $$$(3, 7)$$$ so it falls down infinitely and will be lost. It can be proven that we can't achieve better answer here. Also note that the point $$$(5, 3)$$$ doesn't fall at all because it is already on the platform.

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

/* Things which don't work on D:
    1. import std gives TLE so it has to be expanded to std.algorithm, std.stdio...
    2. Array Indicing ONLY typecasts integers (UNLESS 64 bit system in which case long) so EITHER cast to INT or SIZE_T
*/

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

void printer(T)(T range) { for(int i = 0; i < range.length; ++i){ write(' ', range[i]); } writeln(); }
alias ll = long;
size_t sz(long t){ return to!size_t(t); }

void play(){
    int n; ll k;
    readf(" %s %s ", &n, &k);
    auto xc = new ll [] (n);
    foreach(i; 0 .. n){
        readf("%s ", xc[i]);
    }
    readln;
    auto xcr = sort(xc);
    /* xc = assumeSorted(xc); */
    ll[] cover, tills;
    foreach(i; 0 .. n){
        auto till = n - xcr.upperBound(xc[i]+k).length;
        tills ~= till;
        cover ~= till - i;
    }
    ll[] maxleft;
    // Deep Copy (HOW TO MAKE IT WORK!)
    maxleft ~= cover;
    for(int j = n - 2; j >= 0; --j){
        maxleft[j] = max(maxleft[j+1], cover[j]);
    }
    for(auto i = 0; i < n; ++i){
        if(tills[i] < n){
            cover[i] += maxleft[sz(tills[i])];
        }
    }
    writeln(cover.maxElement());
}

int main(){
    ll t = 1;
    readf(" %s ", &t);        // Toggle!
    while(t--) play();  // Let's play!
    return 0;
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);

  Tuple!(long, long)[200_000] pointsBucket;
  long[200_000] pointCountBucket;
  auto nt = next!int;
  foreach(tc; 0 .. nt)
    {
      auto n = next!long;
      auto k = next!long;
      auto points = pointsBucket[0 .. cast(size_t) n];
      foreach(i; 0 .. cast(size_t)n)
        points[i][0] = next!long;
      foreach(i; 0 .. cast(size_t)n)
        points[i][1] = next!long;
      auto spoints = sort(points);
      long countInRange(long lx, long hx)
      {
        return spoints.upperBound(tuple(lx, long.min)).lowerBound(tuple(hx, long.max)).length;
      }
      auto pointCount = pointCountBucket[0 .. cast(size_t)n];
      foreach(i; 0 .. cast(size_t)n)
        pointCount[i] = countInRange(points[i][0] - k, points[i][0]);
      int lowindex = 0;
      int maxbelow = 0;
      int curr = 0;
      int best = 0;
      while(curr < n)
        {
          int localbest = cast(int) pointCount[curr];
          while(lowindex < n && points[lowindex][0] < points[curr][0] - k)
            {
              maxbelow = cast(int) max(maxbelow, pointCount[lowindex]);
              lowindex++;
            }
          localbest += maxbelow;
          best = max(localbest, best);
          curr++;
        }
      writeln(best);
    }
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.The forestThe Biridian Forest is a two-dimensional grid consisting of r rows and c columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.The initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example):  MovesBreeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions:   Do nothing.  Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees.  If you are located on the exit cell, you may leave the forest. Only you can perform this move — all other mikemon breeders will never leave the forest by using this type of movement. After each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).Mikemon battleIf you and t (t > 0) mikemon breeders are located on the same cell, exactly t mikemon battles will ensue that time (since you will be battling each of those t breeders once). After the battle, all of those t breeders will leave the forest to heal their respective mikemons.Note that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders — there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).Your goalYou would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.Goal of other breedersBecause you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.Your taskPrint the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.

The first line consists of two integers: r and c (1 ≤ r, c ≤ 1000), denoting the number of rows and the number of columns in Biridian Forest. The next r rows will each depict a row of the map, where each character represents the content of a single cell:    'T': A cell occupied by a tree.  'S': An empty cell, and your starting position. There will be exactly one occurence of this in the map.  'E': An empty cell, and where the exit is located. There will be exactly one occurence of this in the map.  A digit (0-9): A cell represented by a digit X means that the cell is empty and is occupied by X breeders (in particular, if X is zero, it means that the cell is not occupied by any breeder).  It is guaranteed that it will be possible for you to go from your starting position to the exit cell through a sequence of moves.

A single line denoted the minimum possible number of mikemon battles that you have to participate in if you pick a strategy that minimize this number.

NoteThe following picture illustrates the first example. The blue line denotes a possible sequence of moves that you should post in your blog:  The three breeders on the left side of the map will be able to battle you — the lone breeder can simply stay in his place until you come while the other two breeders can move to where the lone breeder is and stay there until you come. The three breeders on the right does not have a way to battle you, so they will stay in their place.For the second example, you should post this sequence in your Blog:  Here's what happens. First, you move one cell to the right.  Then, the two breeders directly to the right of the exit will simultaneously move to the left. The other three breeder cannot battle you so they will do nothing.  You end up in the same cell with 2 breeders, so 2 mikemon battles are conducted. After those battles, all of your opponents leave the forest.  Finally, you make another move by leaving the forest.

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;

void main ()
{
	int r, c;
	while (readf (" %s %s ", &r, &c) > 0)
	{
		auto a = new string [r];
		auto d = new int [] [] (r, c);
		auto z = new int [] [] (r, c);
		foreach (i; 0..r)
		{
			a[i] = readln ().strip ();
		}

		alias Tuple !(int, "i", int, "j") coord;
		coord s, e;
		immutable int INF = int.max / 2;
		foreach (i; 0..r)
		{
			foreach (j; 0..c)
			{
				d[i][j] = INF;
				if (a[i][j] == 'E')
				{
					e.i = i;
					e.j = j;
				}
				else if (a[i][j] == 'S')
				{
					s.i = i;
					s.j = j;
				}
				else if (a[i][j] != 'T')
				{
					z[i][j] = a[i][j] - '0';
				}
			}
		}

		coord [] q;
		q.reserve (r * c);
		q.assumeSafeAppend ();
		q ~= e;
		d[e.i][e.j] = 0;
		while (q.length > 0)
		{
			coord cur = q[0];
			int next_d = d[cur.i][cur.j] + 1;
			q = q[1..$];

			immutable int DIRS = 4;
			immutable int [DIRS] DI = [-1,  0, +1,  0];
			immutable int [DIRS] DJ = [ 0, -1,  0, +1];

			foreach (dir; 0..DIRS)
			{
				coord next = cur;
				next.i += DI[dir];
				next.j += DJ[dir];
				if (next.i < 0 || next.i >= r ||
				    next.j < 0 || next.j >= c ||
				    a[next.i][next.j] == 'T' ||
				    d[next.i][next.j] != INF)
				{
					continue;
				}
				d[next.i][next.j] = next_d;
				q.assumeSafeAppend ();
				q ~= next;
			}
		}

		int sd = d[s.i][s.j];
		int res = 0;
		foreach (i; 0..r)
		{
			foreach (j; 0..c)
			{
				if (d[i][j] <= sd)
				{
					res += z[i][j];
				}
			}
		}
		writeln (res);
	}
}


Every December, VK traditionally holds an event for its employees named "Secret Santa". Here's how it happens.$$$n$$$ employees numbered from $$$1$$$ to $$$n$$$ take part in the event. Each employee $$$i$$$ is assigned a different employee $$$b_i$$$, to which employee $$$i$$$ has to make a new year gift. Each employee is assigned to exactly one other employee, and nobody is assigned to themselves (but two employees may be assigned to each other). Formally, all $$$b_i$$$ must be distinct integers between $$$1$$$ and $$$n$$$, and for any $$$i$$$, $$$b_i \ne i$$$ must hold.The assignment is usually generated randomly. This year, as an experiment, all event participants have been asked who they wish to make a gift to. Each employee $$$i$$$ has said that they wish to make a gift to employee $$$a_i$$$.Find a valid assignment $$$b$$$ that maximizes the number of fulfilled wishes of the employees.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of participants of the event. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \ne i$$$) — wishes of the employees in order from $$$1$$$ to $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print two lines. In the first line, print a single integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of fulfilled wishes in your assignment. In the second line, print $$$n$$$ distinct integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$; $$$b_i \ne i$$$) — the numbers of employees assigned to employees $$$1, 2, \ldots, n$$$. $$$k$$$ must be equal to the number of values of $$$i$$$ such that $$$a_i = b_i$$$, and must be as large as possible. If there are multiple answers, print any.

NoteIn the first test case, two valid assignments exist: $$$[3, 1, 2]$$$ and $$$[2, 3, 1]$$$. The former assignment fulfills two wishes, while the latter assignment fulfills only one. Therefore, $$$k = 2$$$, and the only correct answer is $$$[3, 1, 2]$$$.

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

int[] inv(int[] a)
{
  auto b = new int[](a.length);
  foreach (i, x ; a) {
    b[x] = cast(int)i;
  }
  return b;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(x => x.to!int - 1).array;
    int[][int] freq;
    bool[int] used;
    foreach (i, x ; a) {
      if (!(x in freq))
        freq[x] = new int[](0);
      freq[x] ~= cast(int)i;
    }
    int[] result = new int[](n);
    result[] = -1;
    foreach (i, gifters ; freq) {
      foreach(gifter ; gifters) {
        if (gifter in used)
          continue;
        if (!(gifter in freq)) {
          result[i] = gifter;
          used[gifter] = true;
          break;
        }
      }
      if (result[i] == -1) {
        foreach(gifter ; gifters) {
          if (gifter in used)
            continue;
          result[i] = gifter;
          used[gifter] = true;
          break;
        }
      }
    }
    int[] avail;
    foreach (i ; 0 .. n) {
      if (!(i in used))
        avail ~= i;
    }
    int[] slots;
    foreach (i, x ; result) {
      if (x == -1)
        slots ~= cast(int)i;
    }

    if (slots.length == 1 && slots[0] == avail[0]) {
      foreach (i, x ; result) {
        if (x != -1) {
          avail ~= result[i];
          result[i] = -1;
          slots ~= cast(int)i;
          break;
        }
      }
    }

    assert(avail.length == slots.length);

    while (true) {
      bool good = true;
      foreach (i ; 0 .. avail.length) {
        if (avail[i] == slots[i]) {
          good = false;
          break;
        }
      }
      if (good)
        break;
      avail.randomShuffle;
    }

    foreach (i ; 0 .. avail.length) {
      result[slots[i]] = avail[i];
    }

    writeln(n - cast(int)slots.length);
    writeln(inv(result).map!(x => x + 1).map!text.joiner(" "));
  }
}

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

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

void solve()
{
	int n = readInt!int;
	auto a = new int[](n);
	auto b = new int[](n);
	b[] = -1;
	auto inds = new int[][](n);
	foreach(i, ref ai; a)
	{
		ai = readInt!int - 1;
		inds[ai] ~= cast(int)i;
	}
	int[] toGive;
	int good = 0;
	foreach(i, ind; inds)
	{
		if (ind.length > 0)
		{
			b[ind[0]] = a[ind[0]];
			assert(a[ind[0]] == cast(int)i);
			good++;
		}
		else toGive ~= cast(int)i;
	}
	foreach(i; 0 .. n)
	{
		if (b[i] == -1) { b[i] = toGive[0]; toGive = toGive[1 .. $]; }
	}
	int[] inc;
	foreach(i; 0 .. n)
	{
		if (b[i] == i) inc ~= cast(int) i;
	}
	good.writeln;
	if (inc.length == 0)
	{
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
	else if (inc.length == 1)
	{
		auto i = inc[0];
		int o = -1;
		foreach(j; 0 .. n) if (j != i && a[j] == a[i] && b[j] == a[j])
		{
			swap(b[i], b[j]);
			break;
		}
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
	else
	{
		int toput = 1;
		foreach(i; 0 .. n)
		{
			if (b[i] == i)
			{
				b[i] = inc[toput];
				toput++;
				if (toput == inc.length) toput = 0;
			}
		}
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
}

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

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

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

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

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

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

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

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

import std.algorithm, std.range, std.stdio, std.numeric, std.array, std.exception,
       std.container, std.typecons, std.conv, std.random, std.bigint;

void read(S...)(ref S args) {
  auto input = readln.split;
  assert(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

void main() {
  int t;
  read(t);

  while (t--) {
    int n;
    read(n);

    auto arr = list!int;

    auto received = new bool[n];
    auto answer   = new int[n];
    int[int] who;

    int k = 0;

    foreach (int i, e; arr) {
      if (!received[e - 1]) {
        received[e - 1] = true;
        answer[i] = e;
        who[e] = i;
        k++;
      }
    }

    writeln(k);

    auto rem = new DList!int;
    foreach (int i; 0 .. n) {
      if (!received[i]) {
        rem.insertBack(i);
      }
    }

    foreach (int i, e; arr) {
      if (answer[i] != 0) continue;

      if (rem.front == i) {
        rem.insertBack(rem.front);
        rem.removeFront();

        if (rem.front == i) {
          rem.removeFront();
          rem.insertBack(arr[i] - 1);
          answer[who[arr[i]]] = i + 1;
        }
      }

      answer[i] = rem.front + 1;
      who[rem.front + 1] = i;
      rem.removeFront();
    }

    writefln!"%(%d %)"(answer);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto b = new bool[](n);
		foreach (i; 0..n)
		{
			b[a[i]] = true;
		}
		ans[ti].length = n;

		int[] arr;
		auto used = new bool[](n);
		foreach (i; 0..n)
		{
			if (b[i])
				++cnt[ti];
			else
				arr ~= i;
		}
		void f(int i)
		{
			int x;
			if (used[a[i]])
			{
				if (arr[0] != i)
				{
					x = arr[0];
					arr.popFront;
				}
				else
				{
					x = arr[1];
					arr ~= arr.front;
					arr = arr[2..$];
				}
			}
			else
				x = a[i];
			ans[ti][i] = x+1;
			used[x] = true;
		}
		foreach (i; 0..n)
		{
			if (!b[i])
				f(i);
		}
		foreach (i; 0..n)
		{
			if (b[i])
				f(i);
		}
	}

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

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

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

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

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

enum L = 100;

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

        auto indeg = new int[N];
        foreach (u; 0 .. N) {
          ++indeg[A[u]];
        }

        auto cyc = new bool[N];
        auto vis = new int[N];
        vis[] = -1;
        foreach (u; 0 .. N) {
          if (!~vis[u]) {
            int v;
            for (v = u; !~vis[v]; v = A[v]) {
              vis[v] = u;
            }
            if (vis[v] == u) {
              for (int w = v; ; ) {
                cyc[w] = true;
                w = A[w];
                if (w == v) {
                  break;
                }
              }
            }
          }
        }
        debug {
          writeln("cyc = ", cyc);
        }

        auto to = A.dup;
        foreach (u; 0 .. N) {
          if (cyc[u]) {
            if (indeg[A[u]] > 1) {
              --indeg[A[u]];
              to[u] = -1;
            }
          }
        }
        foreach (u; 0 .. N) {
          if (!cyc[u]) {
            if (indeg[A[u]] > 1) {
              --indeg[A[u]];
              to[u] = -1;
            }
          }
        }

        int[] us;
        foreach (u; 0 .. N) {
          if (indeg[u] == 0) {
            for (int v = u; ~v; v = to[v]) {
              us ~= v;
            }
          }
        }
        const usLen = cast(int)(us.length);
        foreach (j; 0 .. usLen) {
          to[us[j]] = us[(j + 1) % usLen];
        }

        int ans;
        foreach (u; 0 .. N) {
          if (A[u] == to[u]) {
            ++ans;
          }
        }
        writeln(ans);
        foreach (u; 0 .. N) {
          if (u > 0) write(" ");
          write(to[u] + 1);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

// code by cutx64

module main;

import std.string, std.array, std.container, std.typecons;
import std.stdio, std.format, std.file, std.outbuffer;
import std.algorithm, std.conv, std.functional, std.range, core.bitop, std.random;
// import std.bigint, std.complex, std.bitmanip;
// import std.math, std.mathspecial, std.numeric;

void main() {

  rndGen.seed(19260817);

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    int n; readf!"%s\n"(n);
    auto a = readln.splitter.map!(to!int).array;
    a[] -= 1;
    auto w = new bool[n];
    foreach(c; a) w[c] = true;
    auto b = new int[n];
    b[] -= 1;
    auto vis = new bool[n];
    foreach(v; 0 .. 2) {
      foreach(i, c; a){
        if (w[i] == v) {
          if (!vis[c]) {
            b[i] = c;
            vis[c] = true;
          }
        }
      }
    }
    auto c = n.iota.filter!(i => b[i] == -1).array;
    auto d = n.iota.filter!(i => !vis[i]).array;
    int k = c.length.to!(int);
    while (true) {
      d.randomShuffle;
      if (k.iota.all!(j => c[j] != d[j])) break;
    }
    foreach(j; 0 .. k) {
      b[c[j]] = d[j];
    }
    n.iota.map!(i => a[i] == b[i]).sum.writeln;
    writefln!"%(%s %)"(b.map!(q{a + 1}));
  }

} // main

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

void main ()
{
	rndGen.seed (125626);

	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		a[] -= 1;

		auto wanted = new bool [n];
		foreach (ref cur; a)
		{
			wanted[cur] = true;
		}

		auto b = new int [n];
		b[] = -1;
		auto vis = new bool [n];
		foreach (value; 0..2)
		{
			foreach (i, ref cur; a)
			{
				if (wanted[i] == value)
				{
					if (!vis[cur])
					{
						b[i] = cur;
						vis[cur] = true;
					}
				}
			}
		}

		auto c = n.iota.filter !(i => b[i] == -1).array;
		auto d = n.iota.filter !(i => !vis[i]).array;
		auto k = c.length.to !(int);
		if (k == 1 && c.front == d.front)
		{
			assert (false);
		}
		while (true)
		{
			randomShuffle (d);
			if (k.iota.all !(j => c[j] != d[j]))
			{
				break;
			}
		}

		foreach (j; 0..k)
		{
			b[c[j]] = d[j];
		}

		writeln (n.iota.map !(i => a[i] == b[i]).sum);
		writefln !("%(%s %)") (b.map !(q{a + 1}));
	}
}

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

int[] inv(int[] a)
{
  auto b = new int[](a.length);
  foreach (i, x ; a) {
    b[x] = cast(int)i;
  }
  return b;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(x => x.to!int - 1).array;
    int[][int] freq;
    bool[int] used;
    foreach (i, x ; a)
      freq[x] = freq.get(x, new int[](0)) ~ [cast(int)i];
    int[] result = new int[](n);
    result[] = -1;
    foreach (i, gifters ; freq) {
      foreach(gifter ; gifters) {
        if (gifter in used)
          continue;
        if (!(gifter in freq)) {
          result[i] = gifter;
          used[gifter] = true;
          break;
        }
      }
      if (result[i] == -1) {
        foreach(gifter ; gifters) {
          if (gifter in used)
            continue;
          result[i] = gifter;
          used[gifter] = true;
          break;
        }
      }
    }
    bool[int] avail;
    foreach (i ; 0 .. n) {
      if (!(i in used))
        avail[i] = true;
    }
    int[] slots;
    foreach (i, x ; result) {
      if (x == -1)
        slots ~= cast(int)i;
    }

    if (slots.length == 1 && slots[0] in avail) {
      foreach (i, x ; result) {
        if (x != -1) {
          avail[result[i]] = true;
          result[i] = -1;
          slots ~= cast(int)i;
          break;
        }
      }
    }

    foreach (slot ; slots) {
      foreach (k, v ; avail) {
        if (k != slot) {
          result[slot] = k;
          avail.remove(k);
          break;
        }
      }
    }
    writeln(n - cast(int)slots.length);
    writeln(inv(result).map!(x => x + 1).map!text.joiner(" "));
  }
}

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

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

void solve()
{
	int n = readInt!int;
	auto a = new int[](n);
	auto b = new int[](n);
	b[] = -1;
	auto inds = new int[][](n);
	foreach(i, ref ai; a)
	{
		ai = readInt!int - 1;
		inds[ai] ~= cast(int)i;
	}
	int[] toGive;
	int good = 0;
	foreach(i, ind; inds)
	{
		if (ind.length > 0)
		{
			b[ind[0]] = a[ind[0]];
			assert(a[ind[0]] == cast(int)i);
			good++;
		}
		else toGive ~= cast(int)i;
	}
	foreach(i; 0 .. n)
	{
		if (b[i] == -1) { b[i] = toGive[0]; toGive = toGive[1 .. $]; }
	}
	int[] inc;
	foreach(i; 0 .. n)
	{
		if (b[i] == i) inc ~= cast(int) i;
	}
	good.writeln;
	if (inc.length == 0)
	{
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
	else if (inc.length == 1)
	{
		auto i = inc[0];
		int o = -1;
		foreach(j; 0 .. n) if (j != i && a[j] == a[i] && b[j] == a[j])
		{
			swap(b[i], b[j]);
			break;
		}
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
	else
	{
		foreach(i; 0 .. n)
		{
			if (b[i] == i)
			{
				b[i] = inc[(i + 1)%(cast(int)inc.length)];
			}
		}
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
}

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

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

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

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

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

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

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

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

import std.algorithm, std.range, std.stdio, std.numeric, std.array, std.exception,
       std.container, std.typecons, std.conv, std.random, std.bigint;

void read(S...)(ref S args) {
  auto input = readln.split;
  assert(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

void main() {
  int t;
  read(t);

  while (t--) {
    int n;
    read(n);

    auto arr = list!int;

    auto received = new bool[n];
    auto answer   = new int[n];
    int[int] who;

    foreach (int i, e; arr) {
      if (!received[e - 1]) {
        received[e - 1] = true;
        answer[i] = e;
        who[e] = i;
      }
    }

    auto rem = new DList!int;
    foreach (int i; 0 .. n) {
      if (!received[i]) {
        rem.insertBack(i);
      }
    }

    foreach (int i, e; arr) {
      if (answer[i] != 0) continue;

      if (rem.front == i) {
        rem.insertBack(rem.front);
        rem.removeFront();

        if (rem.front == i) {
          rem.removeFront();
          rem.insertBack(arr[i] - 1);
          answer[who[arr[i]]] = i + 1;
        }
      }

      answer[i] = rem.front + 1;
      who[rem.front + 1] = i;
      rem.removeFront();
    }

    writefln!"%(%d %)"(answer);
  }
}

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

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

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

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

enum L = 100;

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

        auto indeg = new int[N];
        foreach (u; 0 .. N) {
          ++indeg[A[u]];
        }

        auto cyc = new bool[N];
        auto vis = new int[N];
        vis[] = -1;
        foreach (u; 0 .. N) {
          if (!~vis[u]) {
            int v;
            for (v = u; !~vis[v]; v = A[v]) {
              vis[v] = u;
            }
            if (vis[v] == u) {
              for (int w = v; ; ) {
                cyc[w] = true;
                w = A[w];
                if (w == v) {
                  break;
                }
              }
            }
          }
        }
        debug {
          writeln("cyc = ", cyc);
        }

        auto to = A.dup;
        foreach (u; 0 .. N) {
          if (cyc[u]) {
            if (indeg[A[u]] > 1) {
              --indeg[A[u]];
              to[u] = -1;
            }
          }
        }
        foreach (u; 0 .. N) {
          if (indeg[A[u]] > 1) {
            --indeg[A[u]];
            to[u] = -1;
          }
        }

        int[] us;
        foreach (u; 0 .. N) {
          if (indeg[u] == 0) {
            for (int v = u; ~v; v = to[v]) {
              us ~= v;
            }
          }
        }
        const usLen = cast(int)(us.length);
        foreach (j; 0 .. usLen) {
          to[us[j]] = us[(j + 1) % usLen];
        }

        int ans;
        foreach (u; 0 .. N) {
          if (A[u] == to[u]) {
            ++ans;
          }
        }
        writeln(ans);
        foreach (u; 0 .. N) {
          if (u > 0) write(" ");
          write(to[u] + 1);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}


You are given two integers $$$b$$$ and $$$w$$$. You have a chessboard of size $$$10^9 \times 10^9$$$ with the top left cell at $$$(1; 1)$$$, the cell $$$(1; 1)$$$ is painted white.Your task is to find a connected component on this chessboard that contains exactly $$$b$$$ black cells and exactly $$$w$$$ white cells. Two cells are called connected if they share a side (i.e. for the cell $$$(x, y)$$$ there are at most four connected cells: $$$(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)$$$). A set of cells is called a connected component if for every pair of cells $$$C_1$$$ and $$$C_2$$$ from this set, there exists a sequence of cells $$$c_1$$$, $$$c_2$$$, ..., $$$c_k$$$ such that $$$c_1 = C_1$$$, $$$c_k = C_2$$$, all $$$c_i$$$ from $$$1$$$ to $$$k$$$ are belong to this set of cells and for every $$$i \in [1, k - 1]$$$, cells $$$c_i$$$ and $$$c_{i + 1}$$$ are connected.Obviously, it can be impossible to find such component. In this case print "NO". Otherwise, print "YES" and any suitable connected component.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains two integers $$$b$$$ and $$$w$$$ ($$$1 \le b, w \le 10^5$$$) — the number of black cells required and the number of white cells required. It is guaranteed that the sum of numbers of cells does not exceed $$$2 \cdot 10^5$$$ ($$$\sum w + \sum b \le 2 \cdot 10^5$$$).

For each query, print the answer to it. If it is impossible to find the required component, print "NO" on the first line. Otherwise, print "YES" on the first line. In the next $$$b + w$$$ lines print coordinates of cells of your component in any order. There should be exactly $$$b$$$ black cells and $$$w$$$ white cells in your answer. The printed component should be connected. If there are several answers, you can print any. All coordinates in the answer should be in the range $$$[1; 10^9]$$$.

import std.stdio;
import std.algorithm;

int[2][200005] ans;

void solve() {
    int b, w;
    readf(" %s %s", b, w);
    int x = min(b, w);
    int y = max(b, w);
    int maxY = x * 4 - (x - 1);
    if (y > maxY) {
        writeln("NO");
        return;
    }
    int k = 0;
    foreach(i; 0..(x*2-1)) {
        ans[k][0] = 2;
        ans[k][1] = 2 + i;
        k++;
    }
    foreach(j; [1, 3]) {
        for (int i = 0; i < x && k < (b+w); i++) {
            ans[k][0] = j;
            ans[k][1] = 2 + (i*2);
            k++;
        }
    }
    if (k < b + w) {
        ans[k][0] = 2;
        ans[k][1] = 1;
        k++;
    }
    if (k < b + w) {
        ans[k][0] = 2;
        ans[k][1] = 2 + ((x - 1) * 2) + 1;
        k++;
    }

    writeln("YES");
    int shift = (x == w) ? 0 : 1;
    foreach(a; ans[0..k]) {
        writeln(a[0]+shift, " ", a[1]);
    }
}

void main() {
    int q;
    readf(" %s", q);
    foreach(_; 0..q) {
        solve();
    }
}

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

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

    while (q--) {
        int b, w;
        readf("%s %s", &b, &w);
        readln;

        Tuple!(int, int)[] ans;
        if (b == w) {
            foreach (i; 0 .. b) {
                ans ~= tuple(1, 2*i + 1);
                ans ~= tuple(1, 2*i + 2);
            }
        } else {

            int start = 2;
            if (b > w) {
                swap(b, w);
                start = 3;
            }

            ans ~= tuple(2, start);
            w -= 1;

            int reach = 0;
            int cur = start+1;
            while (b > 0) {
                b -= 1;
                ans ~= tuple(2, cur);
                cur += 1;

                w -= 1;
                ans ~= tuple(2, cur);
                cur += 1;

                reach += 2;
            }

            if (reach < w) {
                writeln("NO");
                continue;
            }

            foreach (pos; cur.iota.drop(1 + start).stride(2)) {
                foreach (rw; [1, 3]) {
                    if (w == 0) { break; }

                    ans ~= tuple(rw, pos);
                    w -= 1;
                }
            }
        }

        writeln("YES");
        ans.each!(t => writeln(t[0], ' ', t[1]));
    }
}

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[2][][](q);
	foreach (i; 0..q)
	{
		auto b = RD;
		auto w = RD;
		if (max(b, w)-1 > min(b, w)*3)
		{
			continue;
		}

		long x, y;
		if (b > w)
		{
			x = 2;
			y = 3;
			ans[i] ~= [[x, y], [x+1, y]];
			--b;
			--w;
			++x;
		}
		else
		{
			x = y = 2;
			ans[i] ~= [[x, y], [x+1, y]];
			--w;
			--b;
			++x;
		}

		auto dir = [[1, 0], [0, 1], [0, -1]];
		while (b != 0 || w != 0)
		{
			if ((x+y)%2 == 0)
			{
				auto m = cast(int)min(3, max(1, b-w));
				foreach (j; 0..m)
				{
					auto dx = dir[j][0];
					auto dy = dir[j][1];
					ans[i] ~= [x+dx, y+dy];
					--b;
				}
				++x;
			}
			else
			{
				auto m = cast(int)min(3, max(1, w-b));
				foreach (j; 0..m)
				{
					auto dx = dir[j][0];
					auto dy = dir[j][1];
					ans[i] ~= [x+dx, y+dy];
					--w;
				}
				++x;
			}
		}
	}

	foreach (e; ans)
	{
		if (e.length == 0)
			writeln("NO");
		else
		{
			writeln("YES");
			foreach (ee; e)
			{
				writeln(ee[0], " ", ee[1]);
			}
		}
	}
	stdout.flush();
	debug readln();
}

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

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

    while (q--) {
        int b, w;
        readf("%s %s", &b, &w);
        readln;

        Tuple!(int, int)[] ans;
        if (b == w) {
            foreach (i; 0 .. b) {
                ans ~= tuple(1, 2*i + 1);
                ans ~= tuple(1, 2*i + 2);
            }
        } else {

            int start = 2;
            if (b > w) {
                swap(b, w);
                start = 3;
            }

            ans ~= tuple(2, start);
            w -= 1;

            int reach = 0;
            int cur = start+1;
            while (b > 0) {
                b -= 1;
                ans ~= tuple(2, cur);
                cur += 1;

                w -= 1;
                ans ~= tuple(2, cur);

                reach += 2;
            }

            if (reach < w) {
                writeln("NO");
                continue;
            }

            foreach (pos; cur.iota.drop(1 + start).stride(2)) {
                foreach (rw; [1, 3]) {
                    if (w == 0) { break; }

                    ans ~= tuple(rw, pos);
                    w -= 1;
                }
            }
        }

        writeln("YES");
        ans.each!(t => writeln(t[0], ' ', t[1]));
    }
}

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

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

    foreach (strw; (q*2 + 2).iota.drop(2).stride(2)) {
        int b, w;
        readf("%s %s", &b, &w);
        readln;

        Tuple!(int, int)[] ans;
        if (b == w) {
            foreach (i; 0 .. b) {
                ans ~= tuple(strw, 2*i + 1);
                ans ~= tuple(strw, 2*i + 2);
            }
        } else {

            int start = 2;
            if (b > w) {
                swap(b, w);
                start = 3;
            }

            ans ~= tuple(strw, start);
            w -= 1;

            int reach = 0;
            int cur = start+1;
            while (b > 0) {
                b -= 1;
                ans ~= tuple(strw, cur);
                cur += 1;

                w -= 1;
                ans ~= tuple(strw, cur);

                reach += 2;
            }

            if (reach < w) {
                writeln("NO");
                continue;
            }

            foreach (pos; cur.iota.drop(1 + start).stride(2)) {
                foreach (rw; [strw-1, strw+1]) {
                    if (w == 0) { break; }

                    ans ~= tuple(rw, pos);
                    w -= 1;
                }
            }
        }

        writeln("YES");
        ans.each!(t => writeln(t[0], ' ', t[1]));
    }
}


A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.

The first line contains number n (1 ≤ n ≤ 105). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.

Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.

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

void main()
{
  auto n = stdin.readln.strip.to!int;
  int [string] names;
  for(int i=0; i<n; i++) {
    auto name = stdin.readln.strip;
    if (name in names) {
      names[name]++;
      write(name);
      writeln(names[name]);
    } else {
      writeln("OK");
      names[name]=0;
    }
  }
 }

import std.stdio;
import core.stdc.stdio;

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

int main(string[] argv)
{
	int n;
	scanf("%d\n", &n);
	int[string] db;
	foreach (int i; 0..n)
	{
		string name = readline();
		if (name in db)
		{
			db[name]++; write(name, db[name], '\n');
		} else {
			write("OK\n");
			db[name] = 0;
		}
	}
	return 0;
}

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

void main() {
    int n = readln.chomp.to!int;
    int[string] db;

    foreach (i; 0..n) {
        string name = readln.chomp;
        if (name in db) {
            writeln(name, db[name]);
            db[name]++;
        } else {
            db[name] = true;
            writeln("OK");
            db[name] = 1;
        }
    }
}

import std.stdio;
import core.stdc.stdio;

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

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int[string] db;
	foreach (int i; 0..n)
	{
		string name = readline();
		if (name in db)
		{
			db[name]++; write(name, db[name], '\n');
		} else {
			write("OK\n");
			db[name] = 0;
		}
	}
	return 0;
}

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

void main() {
    int n = readln.chomp.to!int;
    bool[string] db;

    foreach (i; 0..n) {
        string name = readln.chomp;
        if (name in db) {
            writeln(name ~ "1");
        } else {
            db[name] = true;
            writeln("OK");
        }
    }
}


As you might remember from our previous rounds, Vova really likes computer games. Now he is playing a strategy game known as Rage of Empires.In the game Vova can hire n different warriors; ith warrior has the type ai. Vova wants to create a balanced army hiring some subset of warriors. An army is called balanced if for each type of warrior present in the game there are not more than k warriors of this type in the army. Of course, Vova wants his army to be as large as possible.To make things more complicated, Vova has to consider q different plans of creating his army. ith plan allows him to hire only warriors whose numbers are not less than li and not greater than ri.Help Vova to determine the largest size of a balanced army for each plan.Be aware that the plans are given in a modified way. See input section for details.

The first line contains two integers n and k (1 ≤ n, k ≤ 100000). The second line contains n integers a1, a2, ... an (1 ≤ ai ≤ 100000). The third line contains one integer q (1 ≤ q ≤ 100000). Then q lines follow. ith line contains two numbers xi and yi which represent ith plan (1 ≤ xi, yi ≤ n). You have to keep track of the answer to the last plan (let's call it last). In the beginning last = 0. Then to restore values of li and ri for the ith plan, you have to do the following:   li = ((xi + last) mod n) + 1;  ri = ((yi + last) mod n) + 1;  If li > ri, swap li and ri.

Print q numbers. ith number must be equal to the maximum size of a balanced army when considering ith plan.

NoteIn the first example the real plans are:   1 2  1 6  6 6  2 4  4 6

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!int).array;

    const int MAX = 100001;
    auto ind = new int[][](MAX);

    foreach (i; 0..N) {
        ind[A[i]] ~= i;
    }

    auto st = new SegmentTree(N);
    foreach (i; 0..MAX)
        foreach (j; 0..ind[i].length.to!int)
            st.add(ind[i][j], j - K >= 0 ? ind[i][j-K] : -1);
    st.sort;

    int last = 0;
    auto Q = readln.chomp.to!int;

    while (Q--) {
        s = readln.split.map!(to!int);
        auto l = (s[0] + last) % N;
        auto r = (s[1] + last) % N;
        if (l > r) swap(l, r);
        last = st.calc(l, r);
        last.writeln;
    }
}

class SegmentTree {
    int[][] table;
    int size;

    this(int n) {
        assert(bsr(n) < 29);
        size = 1 << (bsr(n) + 2);
        table = new int[][](size);
    }

    void add(int pos, int num) {
        add(pos, num, 0, 0, size/2-1);
    }

    void add(int pos, int num, int i, int left, int right) {
        table[i] ~= num;
        if (left == right)
            return;
        auto mid = (left + right) / 2;
        if (pos <= mid)
            add(pos, num, i*2+1, left, mid);
        else
            add(pos, num, i*2+2, mid+1, right);
    }

    void sort() {
        foreach (i; 0..size) table[i].sort();
    }

    int calc(int pl, int pr) {
        return calc(pl, pr, 0, 0, size/2-1);
    }

    int calc(int pl, int pr, int i, int left, int right) {
        if (pl > right || pr < left)
            return 0;
        else if (pl <= left && right <= pr) {
            return table[i].assumeSorted.lowerBound(pl).length;
        }
        else
            return
                calc(pl, pr, i*2+1, left, (left+right)/2) +
                calc(pl, pr, i*2+2, (left+right)/2+1, right);
    }
}


It's Petya's birthday party and his friends have presented him a brand new "Electrician-$$$n$$$" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.Construction set "Electrician-$$$n$$$" consists of $$$2n - 1$$$ wires and $$$2n$$$ light bulbs. Each bulb has its own unique index that is an integer from $$$1$$$ to $$$2n$$$, while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain.Petya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed $$$2i$$$ and $$$2i - 1$$$ turn on if the chain connecting them consists of exactly $$$d_i$$$ wires. Moreover, the following important condition holds: the value of $$$d_i$$$ is never greater than $$$n$$$.Petya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.

The first line of the input contains a single integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the parameter of a construction set that defines the number of bulbs and the number of wires. Next line contains $$$n$$$ integers $$$d_1, d_2, \ldots, d_n$$$ ($$$1 \leq d_i \leq n$$$), where $$$d_i$$$ stands for the number of wires the chain between bulbs $$$2i$$$ and $$$2i - 1$$$ should consist of.

Print $$$2n - 1$$$ lines. The $$$i$$$-th of them should contain two distinct integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq 2n$$$, $$$a_i \ne b_i$$$) — indices of bulbs connected by a wire. If there are several possible valid answer you can print any of them.

Note    Answer for the first sample test.      Answer for the second sample test.

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

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

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

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

int N;
int[] D;

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

      auto ds = new Tuple!(int, int)[N];
      foreach (i; 0 .. N) {
        ds[i] = tuple(D[i], i);
      }
      sort(ds);
      reverse(ds);

      auto us = new int[N];
      foreach (j; 0 .. N) {
        const i = ds[j][1];
        us[j] = 2 * i + 1;
      }

      Tuple!(int, int)[] ans;
      foreach (j; 1 .. N) {
        ans ~= tuple(us[j - 1], us[j]);
      }
      foreach (j; 0 .. N) {
        const i = ds[j][1];
        assert(j + D[i] <= us.length);
        ans ~= tuple(2 * i + 2, us[j + D[i] - 1]);
        if (j + D[i] == us.length) {
          us ~= 2 * i + 2;
        }
      }
      debug {
        writeln("us = ", us);
      }

      foreach (e; ans) {
        writeln(e[0], " ", e[1]);
      }
    }
  } catch (EOFException e) {
  }
}


Alice and Bob are playing a game with strings. There will be $$$t$$$ rounds in the game. In each round, there will be a string $$$s$$$ consisting of lowercase English letters. Alice moves first and both the players take alternate turns. Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from $$$s$$$.More formally, if there was a string $$$s = s_1s_2 \ldots s_k$$$ the player can choose a substring $$$s_ls_{l+1} \ldots s_{r-1}s_r$$$ with length of corresponding parity and remove it. After that the string will become $$$s = s_1 \ldots s_{l-1}s_{r+1} \ldots s_k$$$.After the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of $$$\texttt{a}$$$ is $$$1$$$, the value of $$$\texttt{b}$$$ is $$$2$$$, the value of $$$\texttt{c}$$$ is $$$3$$$, $$$\ldots$$$, and the value of $$$\texttt{z}$$$ is $$$26$$$. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 5\cdot 10^4$$$) denoting the number of rounds. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$) consisting of lowercase English letters, denoting the string used for the round. Here $$$|s|$$$ denotes the length of the string $$$s$$$. It is guaranteed that the sum of $$$|s|$$$ over all rounds does not exceed $$$2\cdot 10^5$$$.

For each round, print a single line containing a string and an integer. If Alice wins the round, the string must be "Alice". If Bob wins the round, the string must be "Bob". The integer must be the difference between their scores assuming both players play optimally.

NoteFor the first round, $$$\texttt{"aba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{ab}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$1+2=3$$$. Bob's total score is $$$1$$$.For the second round, $$$\texttt{"abc"}\xrightarrow{\texttt{Alice}}\texttt{"a}{\color{red}{\texttt{bc}}}\texttt{"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$2+3=5$$$. Bob's total score is $$$1$$$.For the third round, $$$\texttt{"cba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{cb}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$3+2=5$$$. Bob's total score is $$$1$$$.For the fourth round, $$$\texttt{"n"}\xrightarrow{\texttt{Alice}}\texttt{"n"}\xrightarrow{} \texttt{"n"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{n}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$0$$$. Bob's total score is $$$14$$$.For the fifth round, $$$\texttt{"codeforces"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{codeforces}}}\texttt{"}\xrightarrow{} \texttt{""}$$$. Alice's total score is $$$3+15+4+5+6+15+18+3+5+19=93$$$. Bob's total score is $$$0$$$.

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;

      auto pts = S.map!(c => (c - 'a' + 1).to!long).array;
      const a = S.length % 2 == 0 ? pts.sum : pts.sum - min(pts[0], pts[$ - 1]);
      const b = pts.sum - a;

      const winner = a > b ? "Alice" : "Bob";
      return "%s %s".format(winner, abs(a - b));
    }

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

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

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        string s = readln.strip;
        if (s.length == 1)
            writeln("Bob ", cast(int) s[0] - cast(int) 'a' + 1);
        else
        {
            if (s.length % 2 == 0)
                writeln("Alice ", s.map!(x => cast(int) x - cast(int) 'a' + 1).sum);
            else
            {
                if (cast(int) s[0] >= cast(int) s[$ - 1])
                    writeln("Alice ", s[0 .. $ -1].map!(x => cast(int) x - cast(int) 'a' + 1).sum - cast(int) s[$ - 1] - 1 + cast(int) 'a');
                else
                    writeln("Alice ", s[1 .. $].map!(x => cast(int) x - cast(int) 'a' + 1).sum - cast(int) s[0] - 1 + cast(int) 'a');
            }
        }
    }
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;

      auto pts = S.map!(c => (c - 'a' + 1).to!long).array.sort;
      const a = S.length % 2 == 0 ? pts.sum : pts[1..$].sum;
      const b = S.length % 2 == 0 ? 0 : pts[0..1].sum;

      const winner = a > b ? "Alice" : "Bob";
      return "%s %s".format(winner, abs(a - b));
    }

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

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