This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?

NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		auto a = new bool [int] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			a[u][v] = true;
			a[v][u] = true;
		}
		auto b = new int [n];
		b[] = 1;
		int res = -1;
		while (sum (b) > 1)
		{
			int v = 0;
			while (!b[v] || a[v].length != 1)
			{
				v += 1;
			}
			int u = v + 1;
			while (!b[u] || a[u].length != 1)
			{
				u += 1;
			}
			writefln !("? %s %s") (u + 1, v + 1);
			stdout.flush ();

			int w;
			readf !(" %s") (w);
			w -= 1;
			if (w == u)
			{
				res = u;
				break;
			}
			if (w == v)
			{
				res = v;
				break;
			}

			b[u] = 0;
			foreach (x, _; a[u])
			{
				a[x].remove (u);
			}
			b[v] = 0;
			foreach (x, _; a[v])
			{
				a[x].remove (v);
			}
		}

		if (res == -1)
		{
			res = 0;
			while (!b[res])
			{
				res += 1;
			}
		}
		writefln !("! %s") (res + 1);
		stdout.flush ();
	}
}

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

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() {
  int n;
  Mt19937 rnd;
  readf (" %d", &n);
  auto e = new int[][n];
  foreach (k; 1 .. n) {
    int i, j;
    readf (" %d %d", &i, &j);
    --i; --j;
    e[i] ~= j;
    e[j] ~= i;
  }
  auto b = new bool[n];
  auto u = new int[n];
  auto v = new int[n];
  auto h = new int[n];
  auto parent = new int[n];
  int tm;
  bool child (int c, int p) {
    if (c == p) return true;
    return u[p] < u[c] && v[c] < v[p];
  }
  void go (int i, int ht) {
    u[i] = ++tm;
    h[i] = ht;
    foreach (j; e[i]) {
      if (parent[j] == -2 && !b[j]) {
        parent[j] = i;
        go (j, ht + 1);
      }
    }
    v[i] = ++tm;
  }
  int fv (const int s) {
    parent[] = -2;
    h[] = -1;
    parent[s] = -1;
    go (s, 0);
    int best = s;
    foreach (i; 0 .. n) if (h[best] < h[i]) best = i;
    return best;
  }
  while (true) {
    int i, j;
    int[] l;
    foreach (o; 0 .. n) if (!b[o]) l ~= o;
    debug stderr.writeln (l);
    int t = l.length.to!int;
    if (t == 1) {
      writeln ("! ", l.front + 1);
      return;
    }
    const int s = l[uniform (0, t)];
    i = fv (s);
    j = fv (i);
    /*
    i = uniform (1, t);
    j = uniform (0, i);
    i = l[i];
    j = l[j];
    */
    writeln ("? ", i + 1, ' ', j + 1);
    stdout.flush ();
    int p;
    readf (" %d", &p);
    --p;
    parent[] = -2;
    parent[p] = -1;
    debug stderr.writeln ("u = ", u);
    debug stderr.writeln ("v = ", v);
    tm = 0;
    go (p, 0);
    foreach (x; l) {
      if (x == p) continue;
      if (i != p && (child (x, i) || child (i, x))) b[x] = true;
      if (j != p && (child (x, j) || child (j, x))) b[x] = true;
    }
    parent[] = -2;
    parent[p] = -1;
    tm = 0;
    go (p, 0);
    b[] = true;
    b[p] = false;
    foreach (o; 0 .. n) if (parent[o] >= 0) b[o] = false;
  }
}

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;
int[] A, B;

int Ask(int u, int v) {
  writefln("? %s %s", u + 1, v + 1);
  stdout.flush;
  const res = readInt();
  if (res == -1) {
    import core.stdc.stdlib;
    exit(0);
  }
  return res - 1;
}
void Answer(int r) {
  writefln("! %s", r + 1);
  stdout.flush;
  import core.stdc.stdlib;
  exit(0);
}

int[][] G;
int[] sz;

void dfs(int u, int p) {
  sz[u] = 1;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
      sz[u] += sz[v];
    }
  }
}

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

  G = new int[][N];
  foreach (i; 0 .. N - 1) {
    G[A[i]] ~= i;
    G[B[i]] ~= i;
  }
  sz = new int[N];
  dfs(0, -1);

  int r;
  for (int u = 0; ; ) {
    int vm = -1;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (vm == -1 || sz[vm] < sz[v]) {
        vm = v;
      }
    }
    if (vm == -1 || sz[u] >= 2 * sz[vm]) {
      r = u;
      break;
    } else {
      sz[u] -= sz[vm];
      sz[vm] += sz[u];
      u = vm;
    }
  }
  debug {
    writeln("r = ", r);
    writeln("sz = ", sz);
  }

  for (int u = r, p = -1; ; ) {
    int[] vs;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (v != p) {
        vs ~= v;
      }
    }
    vs.sort!((v, w) => (sz[v] > sz[w]));
    const vsLen = cast(int)(vs.length);
    int vm = -1;
    foreach (j; 0 .. vsLen / 2) {
      const res = Ask(vs[j * 2], vs[j * 2 + 1]);
      if (res != u) {
        vm = res;
        goto found;
      }
    }
    if (vsLen % 2 != 0) {
      const res = Ask(vs[vsLen - 1], u);
      if (res != u) {
        vm = res;
        goto found;
      }
    }
    Answer(u);
   found:{}
    p = u;
    u = vm;
  }
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		auto a = new bool [int] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			a[u][v] = true;
			a[v][u] = true;
		}
		auto b = new int [n];
		b[] = 1;
		int res = -1;
		while (sum (b) > 1)
		{
			writeln (a);
			int v = 0;
			while (!b[v] || a[v].length != 1)
			{
				v += 1;
			}
			int u = v + 1;
			while (!b[u] || a[u].length != 1)
			{
				u += 1;
			}
			writefln !("? %s %s") (u + 1, v + 1);
			stdout.flush ();

			int w;
			readf !(" %s") (w);
			w -= 1;
			if (w == u)
			{
				res = u;
				break;
			}
			if (w == v)
			{
				res = v;
				break;
			}

			b[u] = 0;
			foreach (x, _; a[u])
			{
				a[x].remove (u);
			}
			b[v] = 0;
			foreach (x, _; a[v])
			{
				a[x].remove (v);
			}
		}

		if (res == -1)
		{
			res = 0;
			while (!b[res])
			{
				res += 1;
			}
		}
		writefln !("! %s") (res + 1);
		stdout.flush ();
	}
}

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

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() {
  int n;
  Mt19937 rnd;
  readf (" %d", &n);
  auto e = new int[][n];
  foreach (k; 1 .. n) {
    int i, j;
    readf (" %d %d", &i, &j);
    --i; --j;
    e[i] ~= j;
    e[j] ~= i;
  }
  auto b = new bool[n];
  auto u = new int[n];
  auto v = new int[n];
  auto parent = new int[n];
  int tm;
  bool child (int c, int p) {
    if (c == p) return true;
    return u[p] < u[c] && v[c] < v[p];
  }
  void go (int i) {
    u[i] = ++tm;
    foreach (j; e[i]) {
      if (parent[j] == -2 && !b[j]) {
        parent[j] = i;
        go (j);
      }
    }
    v[i] = ++tm;
  }
  while (true) {
    int i, j;
    int[] l;
    foreach (o; 0 .. n) if (!b[o]) l ~= o;
    debug stderr.writeln (l);
    int t = l.length.to!int;
    if (t == 1) {
      writeln ("! ", l.front + 1);
      return;
    }
    i = uniform (1, t);
    j = uniform (0, i);
    i = l[i];
    j = l[j];
    writeln ("? ", i + 1, ' ', j + 1);
    stdout.flush ();
    int p;
    readf (" %d", &p);
    --p;
    parent[] = -2;
    parent[p] = -1;
    debug stderr.writeln ("u = ", u);
    debug stderr.writeln ("v = ", v);
    tm = 0;
    go (p);
    foreach (x; l) {
      if (x == p) continue;
      if (i != p && (child (x, i) || child (i, x))) b[x] = true;
      if (j != p && (child (x, j) || child (j, x))) b[x] = true;
    }
  }
}

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

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() {
  int n;
  Mt19937 rnd;
  readf (" %d", &n);
  auto e = new int[][n];
  foreach (k; 1 .. n) {
    int i, j;
    readf (" %d %d", &i, &j);
    --i; --j;
    e[i] ~= j;
    e[j] ~= i;
  }
  auto b = new bool[n];
  auto u = new int[n];
  auto v = new int[n];
  auto parent = new int[n];
  int tm;
  bool child (int c, int p) {
    if (c == p) return true;
    return u[p] < u[c] && v[c] < v[p];
  }
  void go (int i) {
    u[i] = ++tm;
    foreach (j; e[i]) {
      if (parent[j] == -2 && !b[j]) {
        parent[j] = i;
        go (j);
      }
    }
    v[i] = ++tm;
  }
  while (true) {
    int i, j;
    int[] l;
    foreach (o; 0 .. n) if (!b[o]) l ~= o;
    debug stderr.writeln (l);
    int t = l.length.to!int;
    if (t == 1) {
      writeln ("! ", l.front + 1);
      return;
    }
    i = uniform (1, t);
    j = uniform (0, i);
    i = l[i];
    j = l[j];
    writeln ("? ", i + 1, ' ', j + 1);
    stdout.flush ();
    int p;
    readf (" %d", &p);
    --p;
    parent[] = -2;
    parent[p] = -1;
    debug stderr.writeln ("u = ", u);
    debug stderr.writeln ("v = ", v);
    tm = 0;
    go (p);
    foreach (x; l) {
      if (x == p) continue;
      if (i != p && (child (x, i) || child (i, x))) b[x] = true;
      if (j != p && (child (x, j) || child (j, x))) b[x] = true;
    }
    parent[] = -2;
    parent[p] = -1;
    tm = 0;
    go (p);
    b[] = true;
    b[p] = false;
    foreach (o; 0 .. n) if (parent[o] >= 0) b[o] = false;
  }
}

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;
int[] X, Y;

int Ask(int u, int v) {
  writefln("? %s %s", u + 1, v + 1);
  stdout.flush;
  const res = readInt();
  if (res == -1) {
    import core.stdc.stdlib;
    exit(0);
  }
  return res - 1;
}
void Answer(int r) {
  writefln("! %s", r + 1);
  stdout.flush;
  import core.stdc.stdlib;
  exit(0);
}

void main() {
  N = readInt();
  X = new int[N - 1];
  Y = new int[N - 1];
  foreach (i; 0 .. N - 1) {
    X[i] = readInt() - 1;
    Y[i] = readInt() - 1;
  }

  auto G = new int[][N];
  foreach (i; 0 .. N - 1) {
    G[X[i]] ~= i;
    G[Y[i]] ~= i;
  }
  for (int u = 0, p = -1; ; ) {
    int[] vs;
    foreach (i; G[u]) {
      const v = X[i] ^ Y[i] ^ u;
      if (v != p) {
        vs ~= v;
      }
    }
    const vsLen = cast(int)(vs.length);
    int vm = -1;
    foreach (j; 0 .. vsLen / 2) {
      const res = Ask(vs[j * 2], vs[j * 2 + 1]);
      if (res != u) {
        vm = res;
      }
    }
    if (vsLen % 2 != 0) {
      const res = Ask(vs[vsLen - 1], u);
      if (res != u) {
        vm = res;
      }
    }
    if (vm == -1) {
      Answer(u);
    }
    p = u;
    u = vm;
  }
}


The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters:   R, G, B — denoting red, green and blue doors, respectively;  r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once.

For each testcase, print YES if the knight can open all doors. Otherwise, print NO.

NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door.

void main() { runSolver(); }

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

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

      const ub = 'a' - 'A';
      return YESNO["RGB".all!(c => S.countUntil(c) > S.countUntil(c + ub))];
    }

    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;

T
read (alias T, string end = "") () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        string s = readln.chomp;
        assert(s.length == 6);

        if (
            s.find('r').find('R').empty() == false &&
            s.find('g').find('G').empty() == false &&
            s.find('b').find('B').empty() == false
        )
            writeln("YES");
        else
            writeln("NO");
    }
}
// ""


You are a paparazzi working in Manhattan.Manhattan has $$$r$$$ south-to-north streets, denoted by numbers $$$1, 2,\ldots, r$$$ in order from west to east, and $$$r$$$ west-to-east streets, denoted by numbers $$$1,2,\ldots,r$$$ in order from south to north. Each of the $$$r$$$ south-to-north streets intersects each of the $$$r$$$ west-to-east streets; the intersection between the $$$x$$$-th south-to-north street and the $$$y$$$-th west-to-east street is denoted by $$$(x, y)$$$. In order to move from the intersection $$$(x,y)$$$ to the intersection $$$(x', y')$$$ you need $$$|x-x'|+|y-y'|$$$ minutes.You know about the presence of $$$n$$$ celebrities in the city and you want to take photos of as many of them as possible. More precisely, for each $$$i=1,\dots, n$$$, you know that the $$$i$$$-th celebrity will be at the intersection $$$(x_i, y_i)$$$ in exactly $$$t_i$$$ minutes from now (and he will stay there for a very short time, so you may take a photo of him only if at the $$$t_i$$$-th minute from now you are at the intersection $$$(x_i, y_i)$$$). You are very good at your job, so you are able to take photos instantaneously. You know that $$$t_i < t_{i+1}$$$ for any $$$i=1,2,\ldots, n-1$$$.Currently you are at your office, which is located at the intersection $$$(1, 1)$$$. If you plan your working day optimally, what is the maximum number of celebrities you can take a photo of?

The first line of the input contains two positive integers $$$r, n$$$ ($$$1\le r\le 500$$$, $$$1\le n\le 100,000$$$) – the number of south-to-north/west-to-east streets and the number of celebrities. Then $$$n$$$ lines follow, each describing the appearance of a celebrity. The $$$i$$$-th of these lines contains $$$3$$$ positive integers $$$t_i, x_i, y_i$$$ ($$$1\le t_i\le 1,000,000$$$, $$$1\le x_i, y_i\le r$$$)  — denoting that the $$$i$$$-th celebrity will appear at the intersection $$$(x_i, y_i)$$$ in $$$t_i$$$ minutes from now. It is guaranteed that $$$t_i<t_{i+1}$$$ for any $$$i=1,2,\ldots, n-1$$$.

Print a single integer, the maximum number of celebrities you can take a photo of.

NoteExplanation of the first testcase: There is only one celebrity in the city, and he will be at intersection $$$(6,8)$$$ exactly $$$11$$$ minutes after the beginning of the working day. Since you are initially at $$$(1,1)$$$ and you need $$$|1-6|+|1-8|=5+7=12$$$ minutes to reach $$$(6,8)$$$ you cannot take a photo of the celebrity. Thus you cannot get any photo and the answer is $$$0$$$.Explanation of the second testcase: One way to take $$$4$$$ photos (which is the maximum possible) is to take photos of celebrities with indexes $$$3, 5, 7, 9$$$ (see the image for a visualization of the strategy):   To move from the office at $$$(1,1)$$$ to the intersection $$$(5,5)$$$ you need $$$|1-5|+|1-5|=4+4=8$$$ minutes, so you arrive at minute $$$8$$$ and you are just in time to take a photo of celebrity $$$3$$$.  Then, just after you have taken a photo of celebrity $$$3$$$, you move toward the intersection $$$(4,4)$$$. You need $$$|5-4|+|5-4|=1+1=2$$$ minutes to go there, so you arrive at minute $$$8+2=10$$$ and you wait until minute $$$12$$$, when celebrity $$$5$$$ appears.  Then, just after you have taken a photo of celebrity $$$5$$$, you go to the intersection $$$(6,6)$$$. You need $$$|4-6|+|4-6|=2+2=4$$$ minutes to go there, so you arrive at minute $$$12+4=16$$$ and you wait until minute $$$17$$$, when celebrity $$$7$$$ appears.  Then, just after you have taken a photo of celebrity $$$7$$$, you go to the intersection $$$(5,4)$$$. You need $$$|6-5|+|6-4|=1+2=3$$$ minutes to go there, so you arrive at minute $$$17+3=20$$$ and you wait until minute $$$21$$$ to take a photo of celebrity $$$9$$$.   Explanation of the third testcase: The only way to take $$$1$$$ photo (which is the maximum possible) is to take a photo of the celebrity with index $$$1$$$ (since $$$|2-1|+|1-1|=1$$$, you can be at intersection $$$(2,1)$$$ after exactly one minute, hence you are just in time to take a photo of celebrity $$$1$$$).Explanation of the fourth testcase: One way to take $$$3$$$ photos (which is the maximum possible) is to take photos of celebrities with indexes $$$3, 8, 10$$$:   To move from the office at $$$(1,1)$$$ to the intersection $$$(101,145)$$$ you need $$$|1-101|+|1-145|=100+144=244$$$ minutes, so you can manage to be there when the celebrity $$$3$$$ appears (at minute $$$341$$$).  Then, just after you have taken a photo of celebrity $$$3$$$, you move toward the intersection $$$(149,379)$$$. You need $$$|101-149|+|145-379|=282$$$ minutes to go there, so you arrive at minute $$$341+282=623$$$ and you wait until minute $$$682$$$, when celebrity $$$8$$$ appears.  Then, just after you have taken a photo of celebrity $$$8$$$, you go to the intersection $$$(157,386)$$$. You need $$$|149-157|+|379-386|=8+7=15$$$ minutes to go there, so you arrive at minute $$$682+15=697$$$ and you wait until minute $$$855$$$ to take a photo of celebrity $$$10$$$.

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

// NEVER USE INBUILT MAX IN DLANG ~ 0.2 sec delay

void play(){
    int n, r;
    r = rd!int;
    n = rd!int;
    auto dp = new ll[](n+1);
    auto maxable = new ll[](n+1);
    tup[] flash;
    flash ~= tup(0, 1, 1);
    foreach(i; 0..n){
        flash ~= tup(rd, rd, rd);
    }
    ll maxold = 0, maxel = 0;
    foreach(i;0..n+1){
        // Dist > 499*2
        maxold = max(maxold, maxable[i]);

        // Add if not present
        dp[i] = max(maxold, dp[i]);

        ll xmax = max(flash[i][1], r - flash[i][1]);
        ll ymax = max(flash[i][2], r - flash[i][2]);

        // Reachable by 1, 1, 0 only!
        if(i > 0 && !dp[i]){ continue; }

        foreach(j; i+1..n+1){
            // Above 1000 set max at that position
            if(flash[j][0] >= flash[i][0] + xmax + ymax){
                maxable[j] = max(maxable[j], dp[i] + 1);
                break;
            }
            ll dt = flash[j][0] - flash[i][0];
            ll dist = abs(flash[j][1] - flash[i][1]) + abs(flash[j][2] - flash[i][2]);
            if(dist <= dt){
                dp[j] = max(dp[j], dp[i] + 1);
            }
        }
        maxel = max(dp[i], maxel);
    }
    show(dp);
    writeln(maxel);
}

int main(){
    long t = 1;
    /* t = rd;        // Toggle! */
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = redBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
T max(T = long)(T a, T b){ return (a > b) ? a : b;}
T min(T = long)(T a, T b){ return (a < b) ? a : b;}

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

void main ()
{
	int r, n;
	while (readf !(" %s %s") (r, n) > 0)
	{
		alias Record = Tuple !(int, q{t}, int, q{x}, int, q{y});
		auto z = new Record [n + 1];
		z[0] = Record (0, 1, 1);
		foreach (ref c; z[1..$])
		{
			readf !(" %s %s %s") (c.t, c.x, c.y);
		}
		auto f = new int [n + 1];
		f[1..$] = int.min;
		auto g = new int [n + 1];
		foreach (i; 1..n + 1)
		{
			for (auto j = i - 1; j >= 0; j--)
			{
				auto d = abs (z[i].x - z[j].x) +
				    abs (z[i].y - z[j].y);
				if (d <= z[i].t - z[j].t)
				{
					f[i] = max (f[i], f[j] + 1);
				}
				if (z[i].t - z[j].t > (r - 1) * 2)
				{
					f[i] = max (f[i], g[j] + 1);
					break;
				}
			}
			g[i] = max (g[i - 1], f[i]);
		}
		writeln (f.maxElement);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto r = RD!int;
	auto n = RD!int;
	auto rbt = new RedBlackTree!(int[], "a[0] > b[0]", true);
	rbt.insert([0, 0, 1, 1, 0]);
	foreach (i; 0..n)
	{
		auto t = RD!int;
		auto x = RD!int;
		auto y = RD!int;

		foreach (e; rbt[])
		{
			auto dist = abs(e[2]-x) + abs(e[3]-y);
			auto dt = t - e[1];
			//debug writeln("dist:", dist, " dt:", dt);
			if (dist <= dt)
			{
				rbt.insert([e[0]+1, t, x, y, i+1]);
				break;
			}
		}
	}
	debug writeln(rbt);

	auto ans = rbt.front;
	writeln(ans[0]);
	stdout.flush;
	debug readln;
}

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

// NEVER USE INBUILT MAX IN DLANG ~ 0.2 sec delay

void play(){
    int n, r;
    r = rd!int;
    n = rd!int;
    auto dp = new ll[](n+1);
    auto maxable = new ll[](n+1);
    tup[] flash;
    flash ~= tup(1, 1, 0);
    foreach(i; 0..n){
        flash ~= tup(rd, rd, rd);
    }
    ll maxold = 0, maxel;
    foreach(i;0..n+1){
        // Dist > 499*2
        maxold = max(maxold, maxable[i]);

        // Add if not present
        dp[i] = max(maxold, dp[i]);

        ll xmax = max(flash[i][1], r - flash[i][1]);
        ll ymax = max(flash[i][2], r - flash[i][2]);

        // Reachable by 1, 1, 0 only!
        if(i > 0 && !dp[i]){ continue; }

        foreach(j; i+1..n+1){
            // Above 1000 set max at that position
            if(flash[j][0] >= flash[i][0] + xmax + ymax){
                maxable[j] = max(maxable[j], dp[i] + 1);
                break;
            }
            ll dt = flash[j][0] - flash[i][0];
            ll dist = abs(flash[j][1] - flash[i][1]) + abs(flash[j][2] - flash[i][2]);
            if(dist <= dt){
                dp[j] = max(dp[j], dp[i] + 1);
            }
        }
        maxel = max(dp[i], maxel);
    }
    writeln(maxel);
}

int main(){
    long t = 1;
    /* t = rd;        // Toggle! */
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = redBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
T max(T = long)(T a, T b){ return (a > b) ? a : b;}
T min(T = long)(T a, T b){ return (a < b) ? a : b;}

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

bool check_dist(tup p1, tup p2){
    ll dt = abs(p2[0] - p1[0]);
    return (dt >= abs(p1[1] - p2[1]) + abs(p1[2] - p2[2]));
}

void play(){
    int n, r;
    r = rd!int;
    n = rd!int;
    auto dp = new ll[](n+1);
    dp[] = 0;
    tup[] flash;
    ll ti, xi, yi;
    flash ~= tup(0, 1, 1);
    foreach(i; 0..n){
        flash ~= tup(rd, rd, rd);
    }

    ll maxold = 0;
    ll[long] maxable;
    foreach(i;0..n+1){
        int crange = flash[i][0].to!int/1000;

        // Reachable by 1, 1, 0 only!
        if(i > 0 && crange == 0 && !dp[i]){ continue; }

        maxold += maxold + maxable.get(i, 0);
        // Add if not present
        if(crange > 0 && dp[i] < maxold){
            dp[i] = maxold;
        }

        foreach(j; i+1..n+1){
            // Above 1000 set max at that position
            if(flash[j][0] > flash[i][0] + 1000){
                maxable[j] = max(maxable.get(j, 0), dp[i] + 1);
                break;
            }
            if(check_dist(flash[j], flash[i])){
                dp[j] = max(dp[j], dp[i] + 1);
            }
        }
    }
    show(dp);
    writeln(maxElement(dp));
}

int main(){
    long t = 1;
    /* t = rd;        // Toggle! */
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = redBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }

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

void main ()
{
	int r, n;
	while (readf !(" %s %s") (r, n) > 0)
	{
		alias Record = Tuple !(int, q{t}, int, q{x}, int, q{y});
		auto z = new Record [n + 1];
		z[0] = Record (0, 1, 1);
		foreach (ref c; z[1..$])
		{
			readf !(" %s %s %s") (c.t, c.x, c.y);
		}
		auto f = new int [n + 1];
		f[1..$] = int.min;
		foreach (i; 1..n + 1)
		{
			for (auto j = i - 1; j >= 0; j--)
			{
				auto d = abs (z[i].x - z[j].x) +
				    abs (z[i].y - z[j].y);
				if (d <= z[i].t - z[j].t)
				{
					f[i] = max (f[i], f[j] + 1);
				}
				if (z[i].t - z[j].t > (r - 1) * 2)
				{
					break;
				}
			}
		}
		writeln (f.maxElement);
	}
}

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

void main ()
{
	int r, n;
	while (readf !(" %s %s") (r, n) > 0)
	{
		alias Record = Tuple !(int, q{t}, int, q{x}, int, q{y});
		auto z = new Record [n + 1];
		z[0] = Record (0, 1, 1);
		foreach (ref c; z[1..$])
		{
			readf !(" %s %s %s") (c.t, c.x, c.y);
		}
		auto f = new int [n + 1];
		f[1..$] = int.min;
		auto g = new int [n + 1];
		foreach (i; 1..n + 1)
		{
			for (auto j = i - 1; j >= 0; j--)
			{
				auto d = abs (z[i].x - z[j].x) +
				    abs (z[i].y - z[j].y);
				if (d <= z[i].t - z[j].t)
				{
					f[i] = max (f[i], f[j] + 1);
				}
				if (z[i].t - z[j].t > (r - 1) * 2)
				{
					f[i] = max (f[i], g[j]);
					break;
				}
			}
			g[i] = max (g[i - 1], f[i]);
		}
		writeln (f.maxElement);
	}
}


It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.

The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.

Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.

NoteFor the sample input:  The worms with labels from [1, 2] are in the first pile.  The worms with labels from [3, 9] are in the second pile.  The worms with labels from [10, 12] are in the third pile.  The worms with labels from [13, 16] are in the fourth pile.  The worms with labels from [17, 25] are in the fifth pile.

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

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

    int[] worms;
    worms ~= a[0];

    // cumulative sum
    for(int i = 1; i < n; i++)
        worms ~= worms[i-1] + a[i];

    foreach(query; q) {
            int right = n-1;
            int left = 0;
            int middle;
        while(left <= right) {
            middle = (right+left)/2;
            if(worms[middle] >= query) {
                right = middle-1;
            } else {
                left = middle+1;
            }
        }
        left++;
        left.writeln;
    }
}

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

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

    foreach (i; 1..a.length) {
        a[i] += a[i - 1];
    }

    auto r = assumeSorted(a);
    foreach (e; q) {
        r.lowerBound(e).length.writeln;
    }
}

import std.stdio;
import std.exception;
import std.algorithm;
import std.range;

void main() { while (solve()) {} }

bool solve() {
	int n;
	if (!readf(" %s", &n)) return false;
	auto a = new long[n];
	long prev = 0;
	foreach (ref x; a) {
		enforce(readf(" %s", &x));
		x += prev;
		prev = x;
	}
	int m;
	enforce(readf(" %s", &m));
	foreach (_; 0..m) {
		long x;
		enforce(readf(" %s", &x));
		auto ans = a.assumeSorted.lowerBound(x).length + 1;
		writeln(ans);
	}
	return true;
}


There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that:  no student-programmer is sitting next to the student-programmer;  and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).

The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b > 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.

Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.

NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.

import std.algorithm.comparison : min;
import std.algorithm.iteration;
import std.algorithm.sorting;
import std.range;
import std.stdio;
import std.string;

void main()
{
  int a, b, n, m; // total seats, num type a, num type b
  readf!"%d %d %d\n"(n, a, b);

  auto l = readln
    .stripRight
    .group
    .filter!(a => a[0] == '.')
    .map!"a[1]"
    .array
    .sort!"a > b";

  // answer
  auto s = 0;

  foreach (g; l) {
    auto x = min(g / 2 + (a > b ? (g % 2) : 0), a);
    auto y = min(g / 2 + (a > b ? 0 : (g % 2)), b);

    s += x + y;
    a -= x;
    b -= y;
  }

  writeln(s);
}

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.complex, std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n, a, b;
	read(n, a, b);
	auto s = readln.strip.split('*');
	int ans;
	foreach (x; s)
	{
		if (a > b)
			swap(a, b);
		if (x.length & 1)
		{
			int m = min(x.length / 2, a);
			ans += m;
			a -= m;
			ans += min(b, x.length / 2 + 1);
			b -= min(b, x.length / 2 + 1);
		}
		else
		{
			int m = min(x.length / 2, a);
			ans += m;
			a -= m;
			ans += min(b, x.length / 2);
			b -= min(b, x.length / 2);
		}
	}
	writeln(ans);
}

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.complex, std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n, a, b;
	read(n, a, b);
	auto s = readln.strip.split('*');
	int ans;
	foreach (x; s)
	{
		if (a > b)
			swap(a, b);
		if (x.length & 1)
		{

			int m = min(x.length / 2, a);
			ans += m;
			a -= m;
			ans += min(b, m + 1);
			b -= min(b, m + 1);
		}
		else
		{
			int m = min(x.length / 2, a);
			ans += m;
			a -= m;
			ans += min(b, m);
			b -= min(b, m);
		}
	}
	writeln(ans);
}


A permutation of length $$$n$$$ is an array $$$p=[p_1,p_2,\dots, p_n]$$$ which contains every integer from $$$1$$$ to $$$n$$$ (inclusive) exactly once. For example, $$$p=[4, 2, 6, 5, 3, 1]$$$ is a permutation of length $$$6$$$.You are given three integers $$$n$$$, $$$a$$$ and $$$b$$$, where $$$n$$$ is an even number. Print any permutation of length $$$n$$$ that the minimum among all its elements of the left half equals $$$a$$$ and the maximum among all its elements of the right half equals $$$b$$$. Print -1 if no such permutation exists.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$), the number of test cases in the test. The following $$$t$$$ lines contain test case descriptions. Each test case description contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 100$$$; $$$1 \le a,b \le n$$$; $$$a \ne b$$$), where $$$n$$$ is an even number (i.e. $$$n \bmod 2 = 0$$$).

For each test case, print a single line containing any suitable permutation. Print -1 no such permutation exists. If there are multiple answers, print any of them.

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]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		if (a == n/2+1 && b == n/2)
		{
			foreach (i; n/2..n)
				ans[ti] ~= i+1;
			foreach (i; 0..n/2)
				ans[ti] ~= i+1;
		}
		else if (a > n/2 || b <= n/2) continue;
		else
		{
			ans[ti] ~= a;
			foreach (i; n/2..n)
			{
				if (i+1 == a || i+1 == b) continue;
				ans[ti] ~= i+1;
			}
			ans[ti] ~= b;
			foreach (i; 0..n/2)
			{
				if (i+1 == a || i+1 == b) continue;
				ans[ti] ~= i+1;
			}
		}
	}

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


The only difference with E1 is the question of the problem.Vlad built a maze out of $$$n$$$ rooms and $$$n-1$$$ bidirectional corridors. From any room $$$u$$$ any other room $$$v$$$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.Vlad invited $$$k$$$ friends to play a game with them.Vlad starts the game in the room $$$1$$$ and wins if he reaches a room other than $$$1$$$, into which exactly one corridor leads. Friends are placed in the maze: the friend with number $$$i$$$ is in the room $$$x_i$$$, and no two friends are in the same room (that is, $$$x_i \neq x_j$$$ for all $$$i \neq j$$$). Friends win if one of them meets Vlad in any room or corridor before he wins.For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time.Friends know the plan of a maze and intend to win. They don't want to waste too much energy. They ask you to determine if they can win and if they can, what minimum number of friends must remain in the maze so that they can always catch Vlad.In other words, you need to determine the size of the minimum (by the number of elements) subset of friends who can catch Vlad or say that such a subset does not exist.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. The input contains an empty string before each test case. The first line of the test case contains two numbers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2\cdot 10^5$$$) — the number of rooms and friends, respectively. The next line of the test case contains $$$k$$$ integers $$$x_1, x_2, \dots, x_k$$$ ($$$2 \le x_i \le n$$$) — numbers of rooms with friends. All $$$x_i$$$ are different. The next $$$n-1$$$ lines contain descriptions of the corridors, two numbers per line $$$v_j$$$ and $$$u_j$$$ ($$$1 \le u_j, v_j \le n$$$) — numbers of rooms that connect the $$$j$$$ corridor. All corridors are bidirectional. From any room, you can go to any other by moving along the corridors. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test is not greater than $$$2\cdot10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be $$$-1$$$ if Vlad wins anyway and a minimal number of friends otherwise.

NoteIn the first set of inputs, even if all the friends stay in the maze, Vlad can still win. Therefore, the answer is "-1".In the second set of inputs it is enough to leave friends from rooms $$$6$$$ and $$$7$$$. Then Vlad will not be able to win. The answer is "2".In the third and fourth sets of inputs Vlad cannot win only if all his friends stay in the maze. Therefore the answers are "1" and "2".

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

void main(string[ ] args) {
    int t;
    readf!"%s"(t);
    readln;

    while (t--) {
        readln;

        int n, k;
        readf!"%s %s"(n, k);
        readln;

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

        auto g = new int[][] (n+1);
        foreach (i; 0 .. n-1) {
            int x, y;
            readf!"%s %s"(x, y);
            readln;

            g[x] ~= y;
            g[y] ~= x;
        }

        auto blocked = new int[n+1];
        blocked[] = 0;

        auto p = new int[n+1];
        auto d = new int[n+1];
        void dfsDepth(int v, int fr, int depth) {
            p[v] = fr;
            d[v] = depth;

            foreach (u; g[v]) {
                if (u == fr) { continue; }

                dfsDepth(u, v, depth + 1);
            }
        }

        dfsDepth(1, 0, 0);

        f.sort!((int a, int b) => d[a] < d[b]);

        debug { f.writeln; }

        foreach (v; f) {
            int x = v;
            blocked[x] = v;
            int steps = 0;
            while (x != 1 && blocked[p[x]] == 0 && steps + 1 <= d[p[x]]) {
                steps += 1;
                x = p[x];
                blocked[x] = v;
            }
        }

        debug { blocked.writeln; }

        int dfsBlock(int v, int fr) {
            if (v != 1 && g[v].length == 1 && blocked[v] == 0) {
                return -1;
            }

            int ans = 0;
            foreach (u; g[v]) {
                if (u == fr) { continue; }

                if (blocked[u] == 0) {
                    auto r = dfsBlock(u, v);
                    if (r == -1) {
                        return -1;
                    }

                    ans += r;
                } else { ans += 1; }
            }

            return ans;
        }

        auto ans = dfsBlock(1, 0);

        ans.writeln;
    }
}

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

void main(string[ ] args) {
    int t;
    readf!"%s"(t);
    readln;

    while (t--) {
        readln;

        int n, k;
        readf!"%s %s"(n, k);
        readln;

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

        auto g = new int[][] (n+1);
        foreach (i; 0 .. n-1) {
            int x, y;
            readf!"%s %s"(x, y);
            readln;

            g[x] ~= y;
            g[y] ~= x;
        }

        auto pos = new bool[n+1];
        pos[] = true;
        f.each!(v => pos[v] = false);

        immutable int INF = 10 ^^ 6;

        auto block = new int[] (n+1);
        block[] = 0;
        auto depthBlock = new int[] (n+1);
        depthBlock[] = INF;

        auto enemiesNeeded = 0;

        void dfs(int v, int fr, int d) {
            if (!pos[v]) {
                block[v] = v;
                depthBlock[v] = d;
                return;
            }

            if (d != 0 && g[v].length == 1) {
                block[v] = -1;
                depthBlock[v] = INF;
                return;
            }

            depthBlock[v] = INF;
            int enemyIndex = -1;
            bool pathExists = false;
            bool canGoDown = false;
            foreach (u; g[v]) {
                if (u == fr) { continue; }

                dfs(u, v, d + 1);

                debug { writeln(v, ' ', u, ' ', block[u], ' ', depthBlock[u]); }

                pathExists |= block[u] == -1;
                canGoDown |= block[u] == 0 || block[u] == -1;
                if (depthBlock[u] < depthBlock[v]) {
                    depthBlock[v] = depthBlock[u];
                    enemyIndex = u;
                }
            }

            auto enemyStepsToReach = depthBlock[v] - d;
            if (enemyStepsToReach <= d) {
                block[v] = enemyIndex;
                return;
            }

            if (pathExists) {
                block[v] = -1;
                depthBlock[v] = INF;
                return;
            }

            if (canGoDown) {
                block[v] = 0;
                depthBlock[v] = INF;
                return;
            }

            block[v] = 0;
            enemiesNeeded += v == 1 ? g[v].length : g[v].length.to!int - 1;
        }

        dfs(1, 0, 0);

        if (block[1] == -1) {
            writeln(-1);
            continue;
        }

        writeln(enemiesNeeded);
    }
}

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

void main(string[ ] args) {
    int t;
    readf!"%s"(t);
    readln;

    while (t--) {
        readln;

        int n, k;
        readf!"%s %s"(n, k);
        readln;

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

        auto g = new int[][] (n+1);
        foreach (i; 0 .. n-1) {
            int x, y;
            readf!"%s %s"(x, y);
            readln;

            g[x] ~= y;
            g[y] ~= x;
        }

        auto pos = new bool[n+1];
        pos[] = true;
        f.each!(v => pos[v] = false);

        immutable int INF = 10 ^^ 6;

        auto block = new int[] (n+1);
        block[] = 0;
        auto depthBlock = new int[] (n+1);
        depthBlock[] = INF;

        auto enemiesNeeded = 0;

        void dfs(int v, int fr, int d) {
            if (!pos[v]) {
                block[v] = v;
                depthBlock[v] = d;
                return;
            }

            if (d != 0 && g[v].length == 1) {
                block[v] = -1;
                depthBlock[v] = INF;
                return;
            }

            depthBlock[v] = INF;
            int enemyIndex = -1;
            bool pathExists = false;
            foreach (u; g[v]) {
                if (u == fr) { continue; }

                dfs(u, v, d + 1);

                pathExists |= block[u] == -1;
                if (depthBlock[u] < depthBlock[v]) {
                    depthBlock[v] = depthBlock[u];
                    enemyIndex = u;
                }
            }

            if (pathExists) {
                block[v] = -1;
                depthBlock[v] = INF;
                return;
            }

            auto enemyStepsToReach = depthBlock[v] - d;
            if (enemyStepsToReach <= d) {
                block[v] = enemyIndex;
                return;
            }

            block[v] = 0;
            enemiesNeeded += v == 1 ? g[v].length : g[v].length.to!int - 1;
        }

        dfs(1, 0, 0);

        if (block[1] == -1) {
            writeln(-1);
            continue;
        }

        writeln(enemiesNeeded);
    }
}


There's a chip in the point $$$(0, 0)$$$ of the coordinate plane. In one operation, you can move the chip from some point $$$(x_1, y_1)$$$ to some point $$$(x_2, y_2)$$$ if the Euclidean distance between these two points is an integer (i.e. $$$\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$$$ is integer).Your task is to determine the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3000$$$) — number of test cases. The single line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 50$$$) — the coordinates of the destination point.

For each test case, print one integer — the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.

NoteIn the first example, one operation $$$(0, 0) \rightarrow (8, 6)$$$ is enough. $$$\sqrt{(0-8)^2+(0-6)^2}=\sqrt{64+36}=\sqrt{100}=10$$$ is an integer.In the second example, the chip is already at the destination point.In the third example, the chip can be moved as follows: $$$(0, 0) \rightarrow (5, 12) \rightarrow (9, 15)$$$. $$$\sqrt{(0-5)^2+(0-12)^2}=\sqrt{25+144}=\sqrt{169}=13$$$ and $$$\sqrt{(5-9)^2+(12-15)^2}=\sqrt{16+9}=\sqrt{25}=5$$$ are integers.

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 euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		if (x == 0 && y == 0) continue;
		auto r2 = x^^2 + y^^2;
		bool ok;
		for (long i = 1; i*i <= r2; ++i)
		{
			if (i*i == r2)
			{
				ok = true;
				break;
			}
		}
		if (ok)
			ans[ti] = 1;
		else
			ans[ti] = 2;
	}

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


Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by $$$n$$$ sectors, and the outer area is equally divided by $$$m$$$ sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position.  The inner area's sectors are denoted as $$$(1,1), (1,2), \dots, (1,n)$$$ in clockwise direction. The outer area's sectors are denoted as $$$(2,1), (2,2), \dots, (2,m)$$$ in the same manner. For a clear understanding, see the example image above.Amugae wants to know if he can move from one sector to another sector. He has $$$q$$$ questions.For each question, check if he can move between two given sectors.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 10^{18}$$$, $$$1 \le q \le 10^4$$$) — the number of sectors in the inner area, the number of sectors in the outer area and the number of questions. Each of the next $$$q$$$ lines contains four integers $$$s_x$$$, $$$s_y$$$, $$$e_x$$$, $$$e_y$$$ ($$$1 \le s_x, e_x \le 2$$$; if $$$s_x = 1$$$, then $$$1 \le s_y \le n$$$, otherwise $$$1 \le s_y \le m$$$; constraints on $$$e_y$$$ are similar). Amague wants to know if it is possible to move from sector $$$(s_x, s_y)$$$ to sector $$$(e_x, e_y)$$$.

For each question, print "YES" if Amugae can move from $$$(s_x, s_y)$$$ to $$$(e_x, e_y)$$$, and "NO" otherwise. You can print each letter in any case (upper or lower).

NoteExample is shown on the picture in the statement.

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

void main()
{
    long n, m, q;
    readf("%s %s %s", &n, &m, &q);
    readln;

    auto g = gcd(n, m);

    debug { g.writeln; }

    n /= g;
    m /= g;

    while (q--) {
        int s1, e1;
        long s2, e2;
        readf("%s %s %s %s", &s1, &s2, &e1, &e2);
        readln;

        long normalize(int p, long x) {
            if (p == 1) { return (x-1) / n; }
            else { return (x-1) / m; }
        }

        s2 = normalize(s1, s2);
        e2 = normalize(e1, e2);

        writeln(s2 == e2 ? "YES" : "NO");
    }
}

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

void solve(){
	long n = read.to!long;
	long m = read.to!long;
	int q = read.to!int;

	long g = gcd(n, m);
	long a = n / g;
	long b = m / g;
	log("g:", g, "a:", a, "b:", b);

	foreach(_; 0 .. q){
		int sx = read.to!int;
		long sy = read.to!long - 1;
		int ex = read.to!int;
		long ey = read.to!long - 1;
		log("sx:", sx, "sy:", sy, "ex:", ex, "ey:", ey);

		long s = sy / (sx == 1? a: b);
		long e = ey / (ex == 1? a: b);
		log("s:", s, "e:", e);

		if(s == e) "YES".writeln;
		else "NO".writeln;
	}

}

long gcd(long a, long b){
	if(a < b) return gcd(b, a);
	if(a % b == 0) return b;
	return gcd(b, a % b);
}

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;
	auto m = RD;
	auto q = RD!int;
	auto g = gcd(n, m);
	auto l1 = n / g;
	auto l2 = m / g;
	auto ans = new bool[](q);
	foreach (i; 0..q)
	{
		auto sx = RD;
		auto sy = RD-1;
		auto ex = RD;
		auto ey = RD-1;
		long pos1, pos2;
		if (sx == 1)
			pos1 = sy / l1;
		else
			pos1 = sy / l2;
		if (ex == 1)
			pos2 = ey / l1;
		else
			pos2 = ey / l2;
		ans[i] = pos1 == pos2;
	}

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


Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more, he also remembers exactly ki positions where the string ti occurs in string s: these positions are xi, 1, xi, 2, ..., xi, ki. He remembers n such strings ti.You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings ti and string s consist of small English letters only.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of strings Ivan remembers. The next n lines contain information about the strings. The i-th of these lines contains non-empty string ti, then positive integer ki, which equal to the number of times the string ti occurs in string s, and then ki distinct positive integers xi, 1, xi, 2, ..., xi, ki in increasing order — positions, in which occurrences of the string ti in the string s start. It is guaranteed that the sum of lengths of strings ti doesn't exceed 106, 1 ≤ xi, j ≤ 106, 1 ≤ ki ≤ 106, and the sum of all ki doesn't exceed 106. The strings ti can coincide. It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists.

Print lexicographically minimal string that fits all the information Ivan remembers.

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto T = new string[N];
      auto K = new int[N];
      auto X = new int[][N];
      foreach (i; 0 .. N) {
        T[i] = readToken();
        K[i] = readInt();
        X[i] = new int[K[i]];
        foreach (j; 0 .. K[i]) {
          X[i][j] = readInt() - 1;
        }
        X[i].sort;
      }

      int len;
      foreach (i; 0 .. N) {
        foreach (j; 0 .. K[i]) {
          chmax(len, X[i][j] + cast(int)(T[i].length));
        }
      }

      auto ans = new char[len];
      ans[] = 'a';

      alias Entry = Tuple!(int, "i", int, "j");
      auto adds = new Entry[][len + 1];
      auto rems = new Entry[][len + 1];
      foreach (i; 0 .. N) {
        foreach (j; 0 .. K[i]) {
          adds[X[i][j]] ~= Entry(i, j);
          rems[X[i][j] + cast(int)(T[i].length)] ~= Entry(i, j);
        }
      }
      auto set = new RedBlackTree!Entry;
      foreach (x; 0 .. len) {
        foreach (ref e; adds[x]) {
          set.insert(e);
        }
        foreach (ref e; rems[x]) {
          set.removeKey(e);
        }
        if (!set.empty) {
          const e = set.front;
          ans[x] = T[e.i][x - X[e.i][e.j]];
        }
      }

      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


There are $$$n$$$ people who want to participate in a boat competition. The weight of the $$$i$$$-th participant is $$$w_i$$$. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.So, if there are $$$k$$$ teams $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, $$$\dots$$$, $$$(a_k, b_k)$$$, where $$$a_i$$$ is the weight of the first participant of the $$$i$$$-th team and $$$b_i$$$ is the weight of the second participant of the $$$i$$$-th team, then the condition $$$a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s$$$, where $$$s$$$ is the total weight of each team, should be satisfied.Your task is to choose such $$$s$$$ that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of participants. The second line of the test case contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le n$$$), where $$$w_i$$$ is the weight of the $$$i$$$-th participant.

For each test case, print one integer $$$k$$$: the maximum number of teams people can compose with the total weight $$$s$$$, if you choose $$$s$$$ optimally.

NoteIn the first test case of the example, we can reach the optimal answer for $$$s=6$$$. Then the first boat is used by participants $$$1$$$ and $$$5$$$ and the second boat is used by participants $$$2$$$ and $$$4$$$ (indices are the same as weights).In the second test case of the example, we can reach the optimal answer for $$$s=12$$$. Then first $$$6$$$ participants can form $$$3$$$ pairs.In the third test case of the example, we can reach the optimal answer for $$$s=3$$$. The answer is $$$4$$$ because we have $$$4$$$ participants with weight $$$1$$$ and $$$4$$$ participants with weight $$$2$$$.In the fourth test case of the example, we can reach the optimal answer for $$$s=4$$$ or $$$s=6$$$.In the fifth test case of the example, we can reach the optimal answer for $$$s=3$$$. Note that participant with weight $$$3$$$ can't use the boat because there is no suitable pair for him in the list.

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n;
  @Dim("n") long[] w;

  void solve(long tc = -1)
  {
    long[101] cnt = 0;
    auto forbidden = new RedBlackTree!long[cast(size_t) n];
    foreach(ref f; forbidden)
      f = redBlackTree!long();
    foreach(i; 0 .. n)
      {
        foreach(j; i + 1 .. n)
          {
            if (!(w.at(j) in forbidden.at(i)) && !(w.at(i) in forbidden.at(j)))
              {
                forbidden.at(j).insert(w.at(i));
                forbidden.at(i).insert(w.at(j));
                cnt.at(w.at(i) + w.at(j))++;
                debug writeln("from ", i, " to ", j, " ", w.at(i) + w.at(j), " cnt = "
                              , cnt.at(w.at(i) + w.at(j)));
              }
          }
      }
    writeln(cnt[].fold!max);
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto cnt = new int[](n+1);
		foreach (i; 0..n)
		{
			++cnt[w[i]];
		}

		foreach (i; 2..n*2+1)
		{
			long tmp;
			foreach (j; 1..min(i, n+1))
			{
				auto k = i - j;
				if (k < j || k > n) continue;
				if (j == k)
				{
					tmp += cnt[k] / 2;
				}
				else
				{
					tmp += min(cnt[j], cnt[k]);
				}
				debug writeln("j:", j, " k:", k, " tmp:", tmp);
			}
			debug writeln("i:", i, " tmp:", tmp);
			ans[ti].chmax(tmp);
		}
	}

	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) { y.modpow(mod - 2); x.modm(y); }

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

		auto cnt = new int[](n+1);
		foreach (i; 0..n)
		{
			++cnt[w[i]];
		}

		foreach (i; 2..n*2+1)
		{
			long tmp;
			foreach (j; 1..min(i, n))
			{
				auto k = i - j;
				if (k < j || k > n) continue;
				if (j == k)
				{
					tmp += cnt[k] / 2;
				}
				else
				{
					tmp += min(cnt[j], cnt[k]);
				}
				debug writeln("j:", j, " k:", k, " tmp:", tmp);
			}
			debug writeln("i:", i, " tmp:", tmp);
			ans[ti].chmax(tmp);
		}
	}

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