The prehistoric caves of El Toll are located in Moià (Barcelona). You have heard that there is a treasure hidden in one of n possible spots in the caves. You assume that each of the spots has probability 1 / n to contain a treasure.You cannot get into the caves yourself, so you have constructed a robot that can search the caves for treasure. Each day you can instruct the robot to visit exactly k distinct spots in the caves. If none of these spots contain treasure, then the robot will obviously return with empty hands. However, the caves are dark, and the robot may miss the treasure even when visiting the right spot. Formally, if one of the visited spots does contain a treasure, the robot will obtain it with probability 1 / 2, otherwise it will return empty. Each time the robot searches the spot with the treasure, his success probability is independent of all previous tries (that is, the probability to miss the treasure after searching the right spot x times is 1 / 2x).What is the expected number of days it will take to obtain the treasure if you choose optimal scheduling for the robot? Output the answer as a rational number modulo 109 + 7. Formally, let the answer be an irreducible fraction P / Q, then you have to output . It is guaranteed that Q is not divisible by 109 + 7.

The first line contains the number of test cases T (1 ≤ T ≤ 1000). Each of the next T lines contains two integers n and k (1 ≤ k ≤ n ≤ 5·108).

For each test case output the answer in a separate line.

NoteIn the first case the robot will repeatedly search in the only spot. The expected number of days in this case is 2. Note that in spite of the fact that we know the treasure spot from the start, the robot still has to search there until he succesfully recovers the treasure.In the second case the answer can be shown to be equal to 7 / 2 if we search the two spots alternatively. In the third case the answer is 25 / 9.

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

/*
  t -> -> -> a t + b
  sum (without last): c t + d
*/
alias Func = Tuple!(Mint, "a", Mint, "b", Mint, "c", Mint, "d");
enum IDENTITY = Func(Mint(1), Mint(0), Mint(0), Mint(0));

// f then g
Func mul(const(Func) f, const(Func) g) {
  return Func(g.a * f.a, g.a * f.b + g.b, f.c + g.c * f.a, f.d + g.c * f.b + g.d);
}

Func power(const(Func) f, long e) {
  Func g = f, h = IDENTITY;
  for (; e; e >>= 1) {
    if (e & 1) h = mul(h, g);
    g = mul(g, g);
  }
  return h;
}

Func calc(long a, long b, const(Func) x, const(Func) y) {
  Func ret;
  if (b == 0) {
    ret = x;
  } else if (a == 0) {
    ret = y;
  } else if (a >= b) {
    ret = calc(a % b, b, x, mul(power(x, a / b), y));
  } else {
    ret = calc(a, b % a, mul(x, power(y, b / a)), y);
  }
  return ret;
}

Mint solve(const(long) N, const(long) K) {
  // t -> t + 1
  enum x = Func(Mint(1), Mint(1), Mint(1), Mint(0));
  // t -> t / 2 (not for sum)
  enum y = Func(Mint(2).inv, Mint(0), Mint(0), Mint(0));
  const g = gcd(N, K);
  const f = power(calc(N / g, K / g, x, y), g);
  const t0 = f.b / (1 - f.a);
  debug {
    writeln("f = ", f, ", t0 = ", t0);
  }
  Mint ans = f.c * t0 + f.d;
  ans /= N;
  ans += 1;
  debug {
    enum z = Mint(2).inv;
    const zk = z^^K;
    Mint brtSum;
    foreach (i; 0 .. N * K) {
      brtSum += (i / K) * z^^(i / N);
    }
    Mint brt;
    brt += brtSum / (1 - zk);
    brt += N * N * (1 - zk) / (1 - z) * zk / (1 - zk)^^2;
    brt *= z;
    brt /= N;
    brt += 1;
    writeln("brt = ", brt);
  }
  return ans;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readLong();
        const K = readLong();
        const ans = solve(N, K);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

/*
  t -> -> -> a t + b
  sum (without last): c t + d
*/
alias Func = Tuple!(Mint, "a", Mint, "b", Mint, "c", Mint, "d");
enum IDENTITY = Func(Mint(1), Mint(0), Mint(0), Mint(0));

// f then g
Func mul(const(Func) f, const(Func) g) {
  return Func(g.a * f.a, g.a * f.b + g.b, f.c + g.c * f.a, f.d + g.c * f.b + g.d);
}

Func power(const(Func) f, long e) {
  Func g = f, h = IDENTITY;
  for (; e; e >>= 1) {
    if (e & 1) h = mul(h, g);
    g = mul(g, g);
  }
  return h;
}

Func calc(long a, long b, const(Func) x, const(Func) y) {
  Func ret;
  if (b == 0) {
    ret = x;
  } else if (a == 0) {
    ret = y;
  } else if (a >= b) {
    ret = calc(a % b, b, x, mul(power(x, a / b), y));
  } else {
    ret = calc(a, b % a, mul(x, power(y, b / a)), y);
  }
  return ret;
}

Mint solve(const(long) N, const(long) K) {
  // t -> t + 1
  enum x = Func(Mint(1), Mint(1), Mint(1), Mint(0));
  // t -> t / 2 (not for sum)
  enum y = Func(Mint(2).inv, Mint(0), Mint(0), Mint(0));
  const res = calc(N, K, x, y);
  const t0 = res.b / (1 - res.a);
  debug {
    writeln("res = ", res, ", t0 = ", t0);
  }
  Mint ans = res.c * t0 + res.d;
  ans /= N;
  ans += 1;
  return ans;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readLong();
        const K = readLong();
        const ans = solve(N, K);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

Mint calc(long n, long k, Mint z) {
  Mint ret;
  if (n == 0 || k == 0) {
    ret = 0;
  } else if (n >= k) {
    const q = n / k, r = n % k;
    const a = Mint(k) * Mint(q * (q - 1) / 2);
    const b = Mint(n) * Mint(q);
    // (a + b i) z^i
    // (q r (1 + i)) z^i
    const zk = z^^k;
    ret += (a + q * r) * (1 - zk) / (1 - z);
    ret += (b + q * r) * (z - k * zk + (k - 1) * z * zk) / (1 - z)^^2;
    ret += calc(r, k, z);
  } else {
    // ???
    const q = k / n, r = k % n;
    const zn = z^^n;
    const znn = zn^^n;
    ret += (1 - z^^q) / (1 - z) * (zn - n * znn + (n - 1) * zn * znn) / (1 - zn)^^2;
    ret += z^^q * calc(n, r, z^^q);
  }
  debug {
    Mint brt;
    foreach (i; 0 .. n * k) {
      brt += (i / k) * z^^(i / n);
    }
    writeln("calc ", n, " ", k, " ", z, " = ", brt, " = ", ret);
    assert(brt.x == ret.x);
  }
  return ret;
}

Mint solve(long n, long k) {
  const z = Mint(2).inv;
  const zk = z^^k;
  const res = calc(n, k, z);
  Mint ans;
  ans += res / (1 - zk);
  ans += n * n * (1 - zk) / (1 - z) * zk / (1 - zk)^^2;
  ans *= z;
  ans /= n;
  ans += 1;
  return ans;
}

void main() {
  debug {
    enum lim = 20;
    foreach (n; 1 .. lim + 1) foreach (k; 1 .. lim + 1) {
      if (n >= k) {
        const q = n / k;
        auto seq = new int[k];
        foreach (i; 0 .. k) {
          foreach (j; 0 .. n / k * k) {
            seq[i] += (i * n + j) / k;
          }
        }
        const a = seq[0];
        const b = (k == 1) ? (n * n) : (seq[1] - seq[0]);
        // writeln(n, " ", k, ": ", a, " ", b, " ", seq);
        foreach (i; 0 .. k) {
          assert(seq[i] == a + b * i);
        }
        assert(a == k * (q * (q - 1) / 2));
        assert(b == n * q);
      }
    }
    foreach (n; 1 .. lim + 1) foreach (k; 1 .. lim + 1) {
      auto seq = new int[k];
      foreach (i; 0 .. k) {
        foreach (j; 0 .. n) {
          seq[i] += (i * n + j) / k;
        }
      }
      writeln(n, " ", k, ": ", seq);
    }
  }

  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readLong();
        const K = readLong();
        const ans = solve(N, K);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


Given an array $$$a$$$ of length $$$n$$$ and an integer $$$k$$$, you are tasked to find any two numbers $$$l$$$ and $$$r$$$ ($$$l \leq r$$$) such that:   For each $$$x$$$ $$$(l \leq x \leq r)$$$, $$$x$$$ appears in $$$a$$$ at least $$$k$$$ times (i.e. $$$k$$$ or more array elements are equal to $$$x$$$).  The value $$$r-l$$$ is maximized. If no numbers satisfy the conditions, output -1.For example, if $$$a=[11, 11, 12, 13, 13, 14, 14]$$$ and $$$k=2$$$, then:   for $$$l=12$$$, $$$r=14$$$ the first condition fails because $$$12$$$ does not appear at least $$$k=2$$$ times.  for $$$l=13$$$, $$$r=14$$$ the first condition holds, because $$$13$$$ occurs at least $$$k=2$$$ times in $$$a$$$ and $$$14$$$ occurs at least $$$k=2$$$ times in $$$a$$$.  for $$$l=11$$$, $$$r=11$$$ the first condition holds, because $$$11$$$ occurs at least $$$k=2$$$ times in $$$a$$$. A pair of $$$l$$$ and $$$r$$$ for which the first condition holds and $$$r-l$$$ is maximal is $$$l = 13$$$, $$$r = 14$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \leq k \leq n$$$) — the length of the array $$$a$$$ and the minimum amount of times each number in the range $$$[l, r]$$$ should appear respectively. Then a single line follows, containing $$$n$$$ integers describing the array $$$a$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output $$$2$$$ numbers, $$$l$$$ and $$$r$$$ that satisfy the conditions, or "-1" if no numbers satisfy the conditions. If multiple answers exist, you can output any.

void main() { runSolver(); }

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

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

      long[] nums = A.sort.group.filter!(g => g[1] >= K).map!"a[0]".array;

      if (nums.empty) return "-1";

      nums.sort;
      long cur = nums[0];
      long con, maxCon;
      long l = cur, r = cur;
      foreach(n; nums[1..$]) {
        if (n == cur + 1) {
          con++;
          if (maxCon.chmax(con)) {
            r = n;
            l = n - con;
          }
        } else con = 0;

        cur = n;
      }

      return [l, r].toAnswerString;
    }

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

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, 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.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int NA = -1;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		int l = NA, r = NA;
		int curL = NA;
		int prev = NA;
		foreach (ref c; a.group)
		{
			auto value = c[0];
			auto num = c[1];
			if (prev + 1 != value)
			{
				curL = value;
			}
			if (num < k)
			{
				curL = value + 1;
			}
			else if (r - l <= value - curL)
			{
				l = curL;
				r = value;
			}
			prev = value;
		}
		writefln !("%(%s %)") (l == NA ? [NA] : [l, r]);
	}
}


You are given three integers $$$a$$$, $$$b$$$, $$$k$$$.Find two binary integers $$$x$$$ and $$$y$$$ ($$$x \ge y$$$) such that   both $$$x$$$ and $$$y$$$ consist of $$$a$$$ zeroes and $$$b$$$ ones;  $$$x - y$$$ (also written in binary form) has exactly $$$k$$$ ones.  You are not allowed to use leading zeros for $$$x$$$ and $$$y$$$.

The only line contains three integers $$$a$$$, $$$b$$$, and $$$k$$$ ($$$0 \leq a$$$; $$$1 \leq b$$$; $$$0 \leq k \leq a + b \leq 2 \cdot 10^5$$$) — the number of zeroes, ones, and the number of ones in the result.

If it's possible to find two suitable integers, print "Yes" followed by $$$x$$$ and $$$y$$$ in base-2. Otherwise print "No". If there are multiple possible answers, print any of them.

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

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

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

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

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

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

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

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

void main()
{
    int A, B, K; get(A, B, K);
    if (K == 0) {
        char[] res;
        foreach (_; 0..B) res ~= '1';
        foreach (_; 0..A) res ~= '0';
        writeln("Yes");
        writeln(res);
        writeln(res);
        return;
    }

    if (A + B - 2 < K || A < 1 || B < 2) return writeln("No");
    auto a = A - 1, b = B - 2;
    char[] x;
    x ~= '0';
    foreach (_; 1..K) {
        if (a) {
            x ~= '0';
            --a;
        } else {
            x ~= '1';
            --b;
        }
    }
    x ~= '1';
    while (a) {
        x ~= '0';
        --a;
    }
    while (b) {
        x ~= '1';
        --b;
    }
    x ~= '1';
    reverse(x);

    a = A - 1; b = B - 2;
    char[] y;
    y ~= '1';
    foreach (_; 1..K) {
        if (a) {
            y ~= '0';
            --a;
        } else {
            y ~= '1';
            --b;
        }
    }
    y ~= '0';
    while (a) {
        y ~= '0';
        --a;
    }
    while (b) {
        y ~= '1';
        --b;
    }
    y ~= '1';
    reverse(y);
    writeln("Yes");
    writeln(x);
    writeln(y);
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto a = RD;
	auto b = RD;
	auto k = RD;

	string ans1, ans2;
	if (a == 0)
	{
		if (k == 0)
		{
			foreach (i; 0..b)
			{
				ans1 ~= '1';
				ans2 ~= '1';
			}
		}
	}
	else if (b == 1)
	{
		if (k == 0)
		{
			ans1 ~= '1';
			ans2 ~= '1';
			foreach (i; 0..a)
			{
				ans1 ~= '0';
				ans2 ~= '0';
			}
		}
	}
	else if (k == 0)
	{
		foreach (i; 0..b)
		{
			ans1 ~= '1';
			ans2 ~= '1';
		}
		foreach (i; 0..a)
		{
			ans1 ~= '0';
			ans2 ~= '0';
		}
	}
	else if (k <= a + b - 2)
	{
		auto d = k-1;
		ans1 ~= "11";
		ans2 ~= "10";
		auto aa = min(a-1, d);
		foreach (i; 0..aa)
		{
			ans1 ~= '0';
			ans2 ~= '0';
		}
		d -= aa;
		foreach (i; 0..d)
		{
			ans1 ~= '1';
			ans2 ~= '1';
		}
		ans1 ~= '0';
		ans2 ~= '1';
		auto rem_a = a - 1 - aa;
		auto rem_b = b - 2 - d;
		foreach (i; 0..rem_a)
		{
			ans1 ~= '0';
			ans2 ~= '0';
		}
		foreach (i; 0..rem_b)
		{
			ans1 ~= '1';
			ans2 ~= '1';
		}
	}

	if (ans1.empty)
		writeln("No");
	else
	{
		writeln("Yes");
		writeln(ans1);
		writeln(ans2);
	}
	stdout.flush;
	debug readln;
}

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

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

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

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

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

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

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

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

void main()
{
    int A, B, K; get(A, B, K);
    if (K == 0) {
        char[] res;
        foreach (_; 0..B) res ~= '1';
        foreach (_; 0..A) res ~= '0';
        writeln("Yes");
        writeln(res);
        writeln(res);
        return;
    }

    if (A < K) return writeln("No");
    if (B < 2) return writeln("No");
    char[] x;
    foreach (_; 0..K) x ~= '0';
    foreach (_; 0..B - 1) x ~= '1';
    foreach (_; 0..A - K) x ~= '0';
    x ~= '1';
    reverse(x);

    char[] y;
    y ~= '1';
    foreach (_; 0..K) y ~= '0';
    foreach (_; 0..B - 2) y ~= '1';
    foreach (_; 0..A - K) y ~= '0';
    y ~= '1';
    reverse(y);
    writeln("Yes");
    writeln(x);
    writeln(y);
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto a = RD;
	auto b = RD;
	auto k = RD;

	string ans1, ans2;
	if (a == 0)
	{
		if (k == 0)
		{
			foreach (i; 0..b)
			{
				ans1 ~= '1';
				ans2 ~= '1';
			}
		}
	}
	else if (b == 1)
	{
		if (k == 0)
		{
			ans1 ~= '1';
			ans2 ~= '1';
			foreach (i; 0..a)
			{
				ans1 ~= '0';
				ans2 ~= '0';
			}
		}
	}
	else if (k <= a + b - 2)
	{
		auto d = a + b - 2 - k;
		ans1 ~= '1';
		ans2 ~= '1';
		auto aa = min(a-1, d);
		foreach (i; 0..aa)
		{
			ans1 ~= '0';
			ans2 ~= '0';
		}
		d -= aa;
		foreach (i; 0..d)
		{
			ans1 ~= '1';
			ans2 ~= '1';
		}
		auto rem_a = a - 1 - aa;
		auto rem_b = b - 2 - d;
		ans1 ~= '1';
		ans2 ~= '0';
		foreach (i; 0..rem_a)
		{
			ans1 ~= '0';
			ans2 ~= '0';
		}
		foreach (i; 0..rem_b)
		{
			ans1 ~= '1';
			ans2 ~= '1';
		}
		ans1 ~= '0';
		ans2 ~= '1';
	}

	if (ans1.empty)
		writeln("No");
	else
	{
		writeln("Yes");
		writeln(ans1);
		writeln(ans2);
	}
	stdout.flush;
	debug readln;
}


ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}. ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.Please note that the friends can't color the trees that are already colored.

The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively. The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci. Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.

Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print  - 1.

NoteIn the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is  - 1.In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.exception;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

T[ ] allocArray(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

int n, m, k;
int[100] _colors;
int[ ] colors;
int[100][100] _p;
int[100][ ] p;
ulong[101][101][100] dp;//[pos][groupsLeft][prevColor]

enum IMPOSSIBLE = ulong.max >>> 2;

ulong dyn(int pos, int groupsLeft, int prevColor) {
    if (pos == n)
        return groupsLeft ? IMPOSSIBLE : 0;
    if (~dp[pos][groupsLeft][prevColor])
        return dp[pos][groupsLeft][prevColor];
    ulong result = IMPOSSIBLE;
    if (colors[pos]) {
        if (prevColor == colors[pos])
            result = dyn(pos + 1, groupsLeft, colors[pos]);
        else if (groupsLeft)
            result = dyn(pos + 1, groupsLeft - 1, colors[pos]);
    } else {
        if (prevColor)
            result = dyn(pos + 1, groupsLeft, prevColor) + p[pos][prevColor - 1];
        if (groupsLeft)
            foreach (i; 1 .. m + 1)
                if (i != prevColor)
                    result = min(result, dyn(pos + 1, groupsLeft - 1, i) + p[pos][i - 1]);
    }
    return (dp[pos][groupsLeft][prevColor] = result);
}

void main() {
    while (read(&n, &m, &k)) {
        colors = _colors[0 .. n];
        p = _p[0 .. n];
        foreach (ref x; colors)
            read(&x);
        foreach (ref row; p)
            foreach (ref x; row[0 .. m])
                read(&x);
        memset(dp.ptr, 0xFF, dp.sizeof);
        const result = dyn(0, k, 0);
        if (result < IMPOSSIBLE)
            writeln(result);
        else
            write("-1\n");
    }
}

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

immutable long INF = 10L ^^ 18 + 23;

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

    auto c = [0] ~ readln.chomp.split.map!(to!int).array;

    auto p = new int[][] (n+1);
    foreach (i; 1 .. n+1) p[i] = [0] ~ readln.chomp.split.map!(to!int).array;

    debug { c.writeln; p.writeln; }

    auto dp = new long[][][] (n+1, k+1, m+1);
    foreach (i; 0 .. n+1) {
        foreach (j; 0 .. k+1) {
            dp[i][j].fill(INF);
        }
    }

    dp[0][0].fill(0);
    if (c[1] != 0) dp[1][1][c[1]] = 0;
    else dp[1][1][] = p[1].map!(to!long).array;

    foreach (i; 2 .. n+1) {
        foreach (j; 1 .. k+1) {
            foreach (pc; 1 .. m+1) {
                if (c[i] != 0) {
                    auto prevGroup = pc == c[i] ? j : j-1;
                    dp[i][j][c[i]] = min(dp[i][j][c[i]], dp[i-1][prevGroup][pc]);

                    continue;
                }

                foreach (cc; 1 .. m+1) {
                    auto prevGroups = pc == cc ? j : j-1;
                    dp[i][j][cc] = min(dp[i][j][cc], dp[i-1][prevGroups][pc] + p[i][cc]);
                }
            }
        }
    }

    debug { dp.each!(r => r.each!writeln); }

    auto ans = dp[n][k].dropOne.minElement;
    if (ans == INF) ans = -1;
    ans.writeln;
}

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

immutable long INF = 10L ^^ 18 + 23;

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

    auto c = [0] ~ readln.chomp.split.map!(to!int).array;

    auto p = new int[][] (n+1);
    foreach (i; 1 .. n+1) p[i] = [int.max] ~ readln.chomp.split.map!(to!int).array;

    debug { c.writeln; p.writeln; }

    auto mn = new int[][][] (n+1, k+1, 2);
    foreach (i; 1 .. n+1) foreach (j; 1 .. k+1) mn[i][j].fill(0);

    auto dp = new long[][][] (n+1, k+1, m+1);
    foreach (i; 0 .. n+1) {
        foreach (j; 0 .. k+1) {
            dp[i][j].fill(INF);
        }
    }

    dp[0][0].fill(0);

    foreach (i; 1 .. n+1) {
        foreach (j; 1 .. min(i+1, k+1)) {
            void calcMin(int cc, int cost) {
                if (i == 1 && j == 1) {
                    dp[i][j][cc] = cost;
                    return;
                }

                dp[i][j][cc] = min(dp[i][j][cc], dp[i-1][j][cc] + cost);

                auto mnOther = mn[i-1][j-1][0] != cc ? mn[i-1][j-1][0] : mn[i-1][j-1][1];
                dp[i][j][cc] = min(dp[i][j][cc], dp[i-1][j-1][mnOther] + cost);
            }

            if (c[i] != 0) {
                calcMin(c[i], 0);
            } else {
                foreach (cc; 1 .. m+1) {
                    calcMin(cc, p[i][cc]);
                }
            }

            foreach (cc; 1 .. m+1) {
                if (dp[i][j][cc] < dp[i][j][mn[i][j][0]]) mn[i][j][1] = mn[i][j][0], mn[i][j][0] = cc;
                else if (dp[i][j][cc] < dp[i][j][mn[i][j][1]]) mn[i][j][1] = cc;
            }
        }
    }

    debug {
        mn.dropOne.each!writeln;

        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. k+1) dp[i][j].writeln;
            writeln;
        }
    }

    auto ans = dp[n][k].dropOne.minElement;
    if (ans == INF) ans = -1;
    ans.writeln;
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.exception;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

T[ ] allocArray(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

int n, m, k;
int[100] _colors;
int[ ] colors;
int[100][100] _p;
int[100][ ] p;
ulong[101][101][100] dp;//[pos][groupsLeft][prevColor]

enum IMPOSSIBLE = (ulong.max - 1) >>> 2;

ulong dyn(int pos, int groupsLeft, int prevColor) {
    if (pos == n)
        return groupsLeft ? IMPOSSIBLE : 0;
    if (~dp[pos][groupsLeft][prevColor])
        return dp[pos][groupsLeft][prevColor];
    ulong result = IMPOSSIBLE;
    if (colors[pos]) {
        if (prevColor == colors[pos])
            result = dyn(pos + 1, groupsLeft, colors[pos]);
        else if (groupsLeft)
            result = dyn(pos + 1, groupsLeft - 1, colors[pos]);
    } else {
        if (prevColor)
            result = dyn(pos + 1, groupsLeft, prevColor) + p[pos][prevColor - 1];
        if (groupsLeft)
            foreach (i; 1 .. m + 1)
                if (i != prevColor)
                    result =
                        min(result, dyn(pos + 1, groupsLeft - 1, i) + p[pos][i - 1]);
    }
    return (dp[pos][groupsLeft][prevColor] = result);
}

void main() {
    while (read(&n, &m, &k)) {
        colors = _colors[0 .. n];
        p = _p[0 .. n];
        foreach (ref x; colors)
            read(&x);
        foreach (ref row; p)
            foreach (ref x; row[0 .. m])
                read(&x);
        memset(dp.ptr, 0xFF, dp.sizeof);
        const result = dyn(0, k, 0);
        if (result != IMPOSSIBLE)
            writeln(result);
        else
            write("-1\n");
    }
}

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

immutable long INF = 10L ^^ 18 + 23;

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

    auto c = [0] ~ readln.chomp.split.map!(to!int).array;

    auto p = new int[][] (n+1);
    foreach (i; 1 .. n+1) p[i] = [int.max] ~ readln.chomp.split.map!(to!int).array;

    debug { c.writeln; p.writeln; }

    auto mn = new int[][][] (n+1, k+1, 2);
    foreach (i; 1 .. n+1) foreach (j; 1 .. k+1) mn[i][j].fill(0);

    auto dp = new long[][][] (n+1, k+1, m+1);
    foreach (i; 0 .. n+1) {
        foreach (j; 0 .. k+1) {
            dp[i][j].fill(INF);
        }
    }

    dp[0][0].fill(0);

    foreach (i; 2 .. n+1) {
        foreach (j; 1 .. min(i+1, k+1)) {
            void calcMin(int cc, int cost) {
                if (i == 1 && j == 1) {
                    dp[i][j][cc] = cost;
                    return;
                }

                dp[i][j][cc] = min(dp[i][j][cc], dp[i-1][j][cc] + cost);

                auto mnOther = mn[i-1][j-1][0] != cc ? mn[i-1][j-1][0] : mn[i-1][j-1][1];
                dp[i][j][cc] = min(dp[i][j][cc], dp[i-1][j-1][mnOther] + cost);
            }

            if (c[i] != 0) {
                calcMin(c[i], 0);
            } else {
                foreach (cc; 1 .. m+1) {
                    calcMin(cc, p[i][cc]);
                }
            }

            foreach (cc; 1 .. m+1) {
                if (dp[i][j][cc] < dp[i][j][mn[i][j][0]]) mn[i][j][1] = mn[i][j][0], mn[i][j][0] = cc;
                else if (dp[i][j][cc] < dp[i][j][mn[i][j][1]]) mn[i][j][1] = cc;
            }
        }
    }

    debug {
        mn.dropOne.each!writeln;

        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. k+1) dp[i][j].writeln;
            writeln;
        }
    }

    auto ans = dp[n][k].dropOne.minElement;
    if (ans == INF) ans = -1;
    ans.writeln;
}

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

immutable long INF = 10L ^^ 18 + 23;

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

    auto c = [0] ~ readln.chomp.split.map!(to!int).array;

    auto p = new int[][] (n+1);
    foreach (i; 1 .. n+1) p[i] = [int.max] ~ readln.chomp.split.map!(to!int).array;

    debug { c.writeln; p.writeln; }

    auto mn = new int[][][] (n+1, k+1, 2);
    foreach (i; 1 .. n+1) foreach (j; 1 .. k+1) mn[i][j].fill(0);

    auto dp = new long[][][] (n+1, k+1, m+1);
    foreach (i; 0 .. n+1) {
        foreach (j; 0 .. k+1) {
            dp[i][j].fill(INF);
        }
    }

    dp[0][0].fill(0);
    if (c[1] != 0) dp[1][1][c[1]] = 0;
    else dp[1][1][] = p[1].map!(to!long).array;

    foreach (i; 2 .. n+1) {
        foreach (j; 1 .. k+1) {
            void calcMin(int cc, int cost) {
                debug { if (i == 2 && j == 2) writeln(cost); }
                dp[i][j][cc] = min(dp[i][j][cc], dp[i-1][j][cc] + cost);

                auto mnOther = mn[i-1][j-1][0] != cc ? mn[i-1][j-1][0] : mn[i-1][j-1][1];
                dp[i][j][cc] = min(dp[i][j][cc], dp[i-1][j-1][mnOther] + cost);
            }

            if (c[i] != 0) {
                calcMin(c[i], 0);
                continue;
            }

            foreach (cc; 1 .. m+1) {
                calcMin(cc, p[i][cc]);
            }

            foreach (cc; 1 .. m+1) {
                if (dp[i][j][cc] < dp[i][j][mn[i][j][0]]) mn[i][j][1] = mn[i][j][0], mn[i][j][0] = cc;
                else if (dp[i][j][cc] < dp[i][j][mn[i][j][1]]) mn[i][j][1] = cc;
            }
        }
    }

    debug { mn.dropOne.each!writeln; }

    debug { foreach (i; 1 .. n+1) { dp[i].each!(r => r.dropOne.writeln); writeln; }  }

    auto ans = dp[n][k].dropOne.minElement;
    if (ans == INF) ans = -1;
    ans.writeln;
}

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

immutable long INF = 10L ^^ 18 + 23;

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

    auto c = [0] ~ readln.chomp.split.map!(to!int).array;

    auto p = new int[][] (n+1);
    foreach (i; 1 .. n+1) p[i] = [int.max] ~ readln.chomp.split.map!(to!int).array;

    debug { c.writeln; p.writeln; }

    auto mn = new int[][][] (n+1, k+1, 2);
    foreach (i; 1 .. n+1) foreach (j; 1 .. k+1) mn[i][j].fill(0);

    auto dp = new long[][][] (n+1, k+1, m+1);
    foreach (i; 0 .. n+1) {
        foreach (j; 0 .. k+1) {
            dp[i][j].fill(INF);
        }
    }

    dp[0][0].fill(0);
    if (c[1] != 0) dp[1][1][c[1]] = 0;
    else dp[1][1][] = p[1].map!(to!long).array;

    mn[1][1] = p[1].enumerate.array.sort!((t1, t2) => t1[1] < t2[1])
        .map!(t => t[0].to!int).array.take(2).array;

    foreach (i; 2 .. n+1) {
        foreach (j; 1 .. k+1) {
            void calcMin(int cc, int cost) {
                dp[i][j][cc] = min(dp[i][j][cc], dp[i-1][j][cc] + cost);

                auto mnOther = mn[i-1][j-1][0] != cc ? mn[i-1][j-1][0] : mn[i-1][j-1][1];
                dp[i][j][cc] = min(dp[i][j][cc], dp[i-1][j-1][mnOther] + cost);
                debug { if (i == 1 && j == 1) writeln(cost, ' ', dp[i][j][cc]); }
            }

            if (c[i] != 0) {
                calcMin(c[i], 0);
            } else {
                foreach (cc; 1 .. m+1) {
                    calcMin(cc, p[i][cc]);
                }
            }

            foreach (cc; 1 .. m+1) {
                if (dp[i][j][cc] < dp[i][j][mn[i][j][0]]) mn[i][j][1] = mn[i][j][0], mn[i][j][0] = cc;
                else if (dp[i][j][cc] < dp[i][j][mn[i][j][1]]) mn[i][j][1] = cc;
            }
        }
    }

    debug {
        mn.dropOne.each!writeln;

        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. k+1) dp[i][j].writeln;
            writeln;
        }
    }

    auto ans = dp[n][k].dropOne.minElement;
    if (ans == INF) ans = -1;
    ans.writeln;
}

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

immutable long INF = 10L ^^ 18 + 23;

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

    auto c = [0] ~ readln.chomp.split.map!(to!int).array;

    auto p = new int[][] (n+1);
    foreach (i; 1 .. n+1) p[i] = [0] ~ readln.chomp.split.map!(to!int).array;

    debug { c.writeln; p.writeln; }

    auto dp = new long[][][] (n+1, k+1, m+1);
    foreach (i; 0 .. n+1) {
        foreach (j; 0 .. k+1) {
            dp[i][j].fill(INF);
        }
    }

    foreach (j; 0 .. k+1) dp[0][j].fill(0);

    foreach (i; 1 .. n+1) {
        foreach (j; 1 .. k+1) {
            foreach (pc; 1 .. m+1) {
                if (c[i] != 0) {
                    auto prevGroup = pc == c[i] ? j : j-1;
                    dp[i][j][c[i]] = min(dp[i][j][c[i]], dp[i-1][prevGroup][pc]);

                    continue;
                }

                foreach (cc; 1 .. m+1) {
                    auto prevGroups = pc == cc ? j : j-1;
                    dp[i][j][cc] = min(dp[i][j][cc], dp[i-1][prevGroups][pc] + p[i][cc]);
                }
            }
        }
    }

    auto ans = dp[n][k].minElement;
    if (ans == INF) ans = -1;
    ans.writeln;
}


You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which:  Any number in this field is in range $$$[1; 9]$$$;  each row contains at least two equal elements;  each column contains at least two equal elements;  each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.

For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.

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

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

    while (t--) {
        auto arr = new dchar[][] (9);
        foreach (r; 0 .. 9) {
            arr[r] = readln.chomp.map!(to!dchar).array;
        }

        int c = 0;
        foreach (r; 0 .. 9) {
            arr[r][c] = arr[r][(c+1)%9];
            c += 3;
            if (c >= 9) {
                c %= 9;
                c += 1;
            }
        }

        foreach (r; 0 .. 9) {
            writeln(arr[r]);
        }
    }
}

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

char change(char c) {
    c += 1;
    if (c > '9') c = '1';
    return c;
}

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        char[9][9] S;
        foreach (i; 0..9) foreach (j, c; readln.chomp) S[i][j] = c;
        S[0][0] = change(S[0][0]);
        S[1][3] = change(S[1][3]);
        S[2][6] = change(S[2][6]);
        S[3][1] = change(S[3][1]);
        S[4][4] = change(S[4][4]);
        S[5][7] = change(S[5][7]);
        S[6][2] = change(S[6][2]);
        S[7][5] = change(S[7][5]);
        S[8][8] = change(S[8][8]);
        foreach (s; S) writeln(s);
    }
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	readln;
	foreach (test; 0..tests)
	{
		immutable int n = 9;
		foreach (i; 0..n)
		{
			auto s = readln.strip.dup;
			s.find ('9')[0] = '1';
			writeln (s);
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 0..3)
		{
			foreach (j; 0..3)
			{
				if (i % 3 == 2)
					s[i+j*3][i*3+j] = s[i+j*3-1][i*3+j];
				else
					s[i+j*3][i*3+j] = s[i+j*3+1][i*3+j];
			}
		}
		ans[ti] = s;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 0..9)
		{
			if (i % 3 == 2)
				s[i][i] = s[i-1][i];
			else
				s[i][i] = s[i+1][i];
		}
		ans[ti] = s;
	}

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


Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.

The first line contains integer n (1 ≤ n ≤ 100) — the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the coins' values. All numbers are separated with spaces.

In the single line print the single number — the minimum needed number of coins.

NoteIn the first sample you will have to take 2 coins (you and your twin have sums equal to 6, 0 correspondingly). If you take 1 coin, you get sums 3, 3. If you take 0 coins, you get sums 0, 6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.In the second sample one coin isn't enough for us, too. You can pick coins with values 1, 2 or 2, 2. In any case, the minimum number of coins equals 2.

import std.stdio;
import std.algorithm.sorting;

/* Condizioni:
   - valore maggiore del restante;
   - minor numero possibile di monete;
*/
ulong sum(uint[] coins) {
  ulong sum = 0;
  foreach(coin; coins) {
    sum += coin;
  }
  return sum;
}

uint minimum_coins(uint[] coins) {
  auto sortedCoins = sort!("a > b")(coins);
  auto sum = sum(coins);
  uint mine = 0, n_coins=0;
  foreach(coin; sortedCoins) {
    mine += coin;
    n_coins++;
    if (mine > sum / 2) {
      break;
    }
  }
  return n_coins;
}

int main() {
  uint n, coin;
  uint[] coins;
  readf("%s", &n);
  for(int i = 0; i < n; i++) {
    readf(" %s", &coin);
    coins ~= coin;
  }
  auto n_coins = minimum_coins(coins);
  write(n_coins);
  return 0;
}

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

void main()
{
    readln;

    auto items = readln
                .split
                .map!(a => to!uint(a))
                .array
                .sort!"a > b";

    uint summ = items
                .save
                .reduce!((a,b) => a+b);

    uint money;
    uint halfMoney = summ / 2;
    uint counter;

    foreach(item; items)
    {
        money += item;
        ++counter;
        if (money > halfMoney) break;
    }

    counter.writeln;
}

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

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int[] coins = new int[n];
	foreach (int i; 0..n)
	{
		int a;
		scanf("%d", &a);
		coins[i] = a;
	}

	sort!((a, b) => a > b)(coins);
	int sum = 0;
	foreach (int i; coins)
	{
		sum += i;
	}
	int ms = 0;
	int noc = 0;
	foreach (int i; coins)
	{
		ms += i;
		noc++;
		sum -= i;
		if (ms > sum)
			break;
	}
	printf("%d", noc);
	return 0;
}

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

void main()
{
    readln;
    auto items = readln
                .split
                .map!(a => to!uint(a))
                .array
                .sort!"a > b";
    uint summ = items
                .save
                .reduce!((a,b) => a+b);

    uint money;
    uint halfMoney = cast(uint)ceil(cast(double)summ/2);
    uint counter;

    foreach(item; items)
    {
        money += item;
        ++counter;
        if (money > halfMoney) break;
    }

    counter.writeln;
}


Last summer, Feluda gifted Lalmohan-Babu a balanced bracket sequence $$$s$$$ of length $$$2 n$$$.Topshe was bored during his summer vacations, and hence he decided to draw an undirected graph of $$$2 n$$$ vertices using the balanced bracket sequence $$$s$$$. For any two distinct vertices $$$i$$$ and $$$j$$$ ($$$1 \le i < j \le 2 n$$$), Topshe draws an edge (undirected and unweighted) between these two nodes if and only if the subsegment $$$s[i \ldots j]$$$ forms a balanced bracket sequence.Determine the number of connected components in Topshe's graph.See the Notes section for definitions of the underlined terms.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of opening brackets in string $$$s$$$. The second line of each test case contains a string $$$s$$$ of length $$$2 n$$$ — a balanced bracket sequence consisting of $$$n$$$ opening brackets "(", and $$$n$$$ closing brackets ")". It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output a single integer — the number of connected components in Topshe's graph.

NoteSample explanation:In the first test case, the graph constructed from the bracket sequence (), is just a graph containing nodes $$$1$$$ and $$$2$$$ connected by a single edge. In the second test case, the graph constructed from the bracket sequence ()(()) would be the following (containing two connected components):  Definition of Underlined Terms: A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters $$$+$$$ and $$$1$$$. For example, sequences (())(), (), and (()(())) are balanced, while )(, ((), and (()))( are not. The subsegment $$$s[l \ldots r]$$$ denotes the sequence $$$[s_l, s_{l + 1}, \ldots, s_r]$$$. A connected component is a set of vertices $$$X$$$ such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to $$$X$$$ violates this rule.

import std;
void main () {
	foreach (r; 0..readln.strip.to !(int)) {
		auto n = readln.strip.to !(int);
		writeln (n - readln.strip.count (")("));
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip;

		int balance = 0;
		int res = 0;
		auto num = new int [n + 1];
		foreach (ref c; s)
		{
			if (c == '(')
			{
				res += (num[balance] == 0);
				num[balance] += 1;
				balance += 1;
			}
			else
			{
				num[balance] = 0;
				balance -= 1;
			}
		}
		writeln (res);
	}
}


Pashmak has fallen in love with an attractive girl called Parmida since one year ago...Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.

The first line contains four space-separated x1, y1, x2, y2 ( - 100 ≤ x1, y1, x2, y2 ≤ 100) integers, where x1 and y1 are coordinates of the first tree and x2 and y2 are coordinates of the second tree. It's guaranteed that the given points are distinct.

If there is no solution to the problem, print -1. Otherwise print four space-separated integers x3, y3, x4, y4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them.  Note that x3, y3, x4, y4 must be in the range ( - 1000 ≤ x3, y3, x4, y4 ≤ 1000).

import std.math;
import std.typecons;
import std.algorithm;

alias Tuple!(int, "x", int, "y") Point;

bool solve(const Point a, const Point b, out Point c, out Point d) {
	auto dx = abs(a.x - b.x);
	auto dy = abs(a.y - b.y);
	if (0 != dx && 0 != dy && dx != dy) {
		return false;
	}

	auto dd = max(dx, dy);
	auto addX = (0 == dx) ? dd : 0;
	auto addY = (0 == dy) ? dd : 0;
	c.x = a.x + addX;
	c.y = b.y + addY;
	d.x = b.x + addX;
	d.y = a.y + addY;

	return true;
}

unittest {
	{
		Point c, d;
		assert(solve(Point(0, 0), Point(0, 1), c, d));
	}
}

int main(string[] argv) {
	import std.stdio;
	Point a, b, c, d;
	while (readf(" %s %s %s %s", &(a.x), &(a.y), &(b.x), &(b.y))) {
		if (solve(a, b, c, d)) {
			writeln(c.x, ' ', c.y, ' ', d.x, ' ', d.y);
		} else {
			writeln(-1);
		}
	}
    return 0;
}


An array $$$[b_1, b_2, \ldots, b_m]$$$ is a palindrome, if $$$b_i = b_{m+1-i}$$$ for each $$$i$$$ from $$$1$$$ to $$$m$$$. Empty array is also a palindrome.An array is called kalindrome, if the following condition holds: It's possible to select some integer $$$x$$$ and delete some of the elements of the array equal to $$$x$$$, so that the remaining array (after gluing together the remaining parts) is a palindrome. Note that you don't have to delete all elements equal to $$$x$$$, and you don't have to delete at least one element equal to $$$x$$$.For example :   $$$[1, 2, 1]$$$ is kalindrome because you can simply not delete a single element.  $$$[3, 1, 2, 3, 1]$$$ is kalindrome because you can choose $$$x = 3$$$ and delete both elements equal to $$$3$$$, obtaining array $$$[1, 2, 1]$$$, which is a palindrome.  $$$[1, 2, 3]$$$ is not kalindrome. You are given an array $$$[a_1, a_2, \ldots, a_n]$$$. Determine if $$$a$$$ is kalindrome or not.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array. It's guaranteed that the sum of $$$n$$$ over all test cases won't exceed $$$2 \cdot 10^5$$$.

For each test case, print YES if $$$a$$$ is kalindrome and NO otherwise. You can print each letter in any case.

NoteIn the first test case, array $$$[1]$$$ is already a palindrome, so it's a kalindrome as well.In the second test case, we can choose $$$x = 2$$$, delete the second element, and obtain array $$$[1]$$$, which is a palindrome.In the third test case, it's impossible to obtain a palindrome.In the fourth test case, you can choose $$$x = 4$$$ and delete the fifth element, obtaining $$$[1, 4, 4, 1]$$$. You also can choose $$$x = 1$$$, delete the first and the fourth elements, and obtain $$$[4, 4, 4]$$$.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		while (n >= 2 && a.front == a.back)
		{
			n -= 2;
			a = a[1..$ - 1];
		}
		bool ok = false;
		ok |= a.equal (a.retro);
		if (!a.empty)
		{
			auto u = a.filter !(c => c != a.front).array;
			ok |= u.equal (u.retro);
			auto v = a.filter !(c => c != a.back).array;
			ok |= v.equal (v.retro);
	        }
		writeln (ok ? "YES" : "NO");
	}
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	int[2] nonGood = [-1, -1];
	int lo = 0;
	int hi = n - 1;
	while (lo < hi)
	{
		if (a[lo] != a[hi]) { nonGood = [a[lo], a[hi]]; break; }
		lo++, hi--;
	}
	bool isGood(int v)
	{
		debug writeln("trying ", v);
		int lo = 0;
		int hi = n - 1;
		while (lo < hi)
		{
			while (a[lo] == v) lo++;
			while (a[hi] == v) hi--;
			if (lo >= hi) break;
			if (a[lo] != a[hi]) return false;
			lo++, hi--;
		}
		debug writeln("which is good");
		return true;
	}
	if (nonGood == [-1, -1] || isGood(nonGood[0]) || isGood(nonGood[1]))
		return writeln("YES");
	return writeln("NO");
}

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

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

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

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

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

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

bool is_palindrome(int[] a)
{
  foreach (i ; 0 .. a.length)
    if (a[i] != a[$ - 1 - i])
      return false;
  return true;
}

void main()
{
  int t;
  readf!" %d "(t);
  foreach (casenum ; 1 .. t + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    int i = 0;
    int j = n - 1;
    int bad1 = -1;
    int bad2 = -1;
    while (i < n && j >= 0) {
      if (a[i] != a[j]) {
        bad1 = a[i];
        bad2 = a[j];
        break;
      }
      i++;
      j--;
    }
    if (bad1 == -1 || bad2 == -1) {
      writeln("YES");
    } else {
      auto a1 = a.filter!(x => x != bad1).array;
      auto a2 = a.filter!(x => x != bad2).array;
      if (is_palindrome(a1) || is_palindrome(a2))
        writeln("YES");
      else
        writeln("NO");
    }
  }
}

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 bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;

		bool dfs(int l, int r, int x)
		{
			if (l >= r) return true;
			if (a[l] == a[r]) return dfs(l+1, r-1, x);

			bool res;
			if (a[l] == x || x == 0)
				res |= dfs(l+1, r, a[l]);
			if (a[r] == x || x == 0)
				res |= dfs(l, r-1, a[r]);
			return res;
		}
		ans[ti] = dfs(0, n-1, 0);
	}

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

// 提出解
void solve(){
	A: foreach(_; 0 .. scan!int){
		int n = scan!int;
		int[] as = scan!int(n);

		int[] xs;
		for(int i = 0, j = n - 1; i < j; i ++, j --){
			if(as[i] != as[j]){
				xs = [as[i], as[j]];
				break;
			}
		}
		if(xs.length == 0){
			"YES".print;
			continue;
		}
		foreach(x; xs){
			bool isOK = 1;
			for(int i = 0, j = n - 1; i < j; ){
				if(as[i] == x){
					i ++;
					continue;
				}
				else if(as[j] == x){
					j --;
					continue;
				}
				if(as[i] != as[j]){
					isOK = 0;
					break;
				}
				i ++, j --;
			}
			if(isOK){
				"YES".print;
				continue A;
			}
		}
		"NO".print;
	}
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// 愚直解
void jury(){
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// テストケース
void gen(){
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// テンプレ
import std;
bool DEBUG = 0;
void main(string[] args){
	if(args.canFind("-debug")) DEBUG = 1;
	if(args.canFind("-gen")) gen; else if(args.canFind("-jury")) jury; else solve;
}
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); }
void print(T)(T t){ writeln(t); }
void print(T, A ...)(T t, A a){ stdout.write(t, " "), print(a); }
string unsplit(T)(T xs, string d = " "){ return xs.array.to!(string[]).join(d); }
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)(int n){ return n.iota.map!(i => scan!T()).array; }
T mini(T)(ref T x, T y){ if(x > y) x = y; return x; }
T maxi(T)(ref T x, T y){ if(x < y) x = y; return x; }
T mid(T)(T l, T r, bool delegate(T) f){
	T m = (l + r) / 2; (f(m)? l: r) = m; return f(l)? f(r - 1)? r: mid(l, r, f): l;
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// ライブラリ（基本）

class UnionFind{
	this(int n){ foreach(i; 0 .. n) R ~= i, K ~= [i]; } int[] R; int[][] K;
	void unite(int a, int b){
		int ra = R[a], rb = R[b]; if(ra == rb) return;
		if(K[ra].length < K[rb].length) unite(b, a);
		else foreach(k; K[rb]) R[k] = ra, K[ra] ~= k;
	}
	int find(int a){ return R[a]; }
	int getSize(int a){ return K[R[a]].length.to!int; }
}
class Queue(T){
	private T[] xs; private uint i, j;
	this(T[] xs = []){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){ while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1; xs[j ++] = x; }
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	void flush(){ i = j; }
	alias empty = isEmpty, front = peek, popFront = deq, pop = deq, push = enq, top = peek;
	Queue opOpAssign(string op)(T x) if(op == "~"){ enq(x); return this; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}
class Stack(T){
	private T[] xs; private uint j;
	this(T[] xs = []){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j; }
	bool isEmpty(){ return j == 0; }
	void push(T x){ while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1; xs[j ++] = x; }
	T pop(){ assert(j > 0); return xs[-- j]; }
	T peek(){ assert(j > 0); return xs[j - 1]; }
	void clear(){ j = 0; }
	alias empty = isEmpty, front = peek, popFront = pop, top = peek;
	Stack opOpAssign(string op)(T x) if(op == "~"){ push(x); return this; }
	T opIndex(uint li){ assert(j > 0 && j - 1 >= li); return xs[j - 1 - li]; }
	static Stack!T opCall(T[] xs = []){ return new Stack!T(xs); }
	T[] array(){ return xs[0 .. j]; }
	override string toString(){ return array.to!string; }
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// ライブラリ（追加）

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;

bool check(int ban) {
  int[] as;
  foreach (a; A) {
    if (a != ban) {
      as ~= a;
    }
  }
  const asLen = cast(int)(as.length);
  for (int l = 0, r = asLen - 1; l < r; ++l, --r) {
    if (as[l] != as[r]) {
      return false;
    }
  }
  return true;
}

bool solve() {
  for (int l = 0, r = N - 1; l < r; ++l, --r) {
    if (A[l] != A[r]) {
      if (check(A[l])) return true;
      if (check(A[r])) return true;
      return false;
    }
  }
  return true;
}

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

        const ans = solve();
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int m, n;
		readf !(" %s %s") (m, n);
		writeln ((m > 1) + (n > 1));
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		while (n >= 2 && a.front == a.back)
		{
			n -= 2;
			a = a[1..$];
		}
		bool ok = false;
		ok |= a.equal (a.retro);
		if (!a.empty)
		{
			auto u = a.filter !(c => c != a.front).array;
			ok |= u.equal (u.retro);
			auto v = a.filter !(c => c != a.back).array;
			ok |= v.equal (v.retro);
	        }
		writeln (ok ? "YES" : "NO");
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		while (n >= 2 && a.front == a.back)
		{
			n -= 2;
			a = a[1..$];
		}
		bool ok = false;
		ok |= a.equal (a.retro);
		auto u = a.filter !(c => c != a.front).array;
		ok |= u.equal (u.retro);
		auto v = a.filter !(c => c != a.back).array;
		ok |= v.equal (v.retro);
		writeln (ok ? "YES" : "NO");
	}
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	auto dv = redBlackTree!int();
	foreach(ai; a) dv.insert(ai);
	auto a0 = dv.front;
	int[2] nonGood = [-1, -1];
	int lo = 0;
	int hi = n - 1;
	while (lo < hi)
	{
		while (a[lo] == a0) lo++;
		while (a[hi] == a0) hi--;
		if (lo >= hi) break;
		if (a[lo] != a[hi]) nonGood = [a[lo], a[hi]];
		lo++, hi--;
	}
	bool isGood(int v)
	{
		debug writeln("trying ", v);
		int lo = 0;
		int hi = n - 1;
		while (lo < hi)
		{
			while (a[lo] == v) lo++;
			while (a[hi] == v) hi--;
			if (lo >= hi) break;
			if (a[lo] != a[hi]) return false;
			lo++, hi--;
		}
		debug writeln("which is good");
		return true;
	}
	if (nonGood == [-1, -1] || isGood(nonGood[0]) || isGood(nonGood[1]))
		return writeln("YES");
	return writeln("NO");
}

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

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

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

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

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