You are given an array s of n non-negative integers.A 5-tuple of integers (a, b, c, d, e) is said to be valid if it satisfies the following conditions:   1 ≤ a, b, c, d, e ≤ n  (sa | sb) & sc & (sd ^ se) = 2i for some integer i  sa & sb = 0 Here, '|' is the bitwise OR, '&' is the bitwise AND and '^' is the bitwise XOR operation.Find the sum of f(sa|sb) * f(sc) * f(sd^se) over all valid 5-tuples (a, b, c, d, e), where f(i) is the i-th Fibonnaci number (f(0) = 0, f(1) = 1, f(i) = f(i - 1) + f(i - 2)).Since answer can be is huge output it modulo 109 + 7.

The first line of input contains an integer n (1 ≤ n ≤ 106). The second line of input contains n integers si (0 ≤ si < 217).

Output the sum as described above, modulo 109 + 7

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[] subsetConvolution(T)(T[] as, T[] bs)
in {
  assert(as.length == bs.length, "subsetConvolution: |as| = |bs| must hold");
  assert(as.length && !(as.length & as.length - 1),
         "subsetConvolution: |as| and |bs| must be a power of two");
}
do {
  import core.bitop : bsr, popcnt;
  const n = bsr(as.length);
  auto fas = new T[][](n + 1, 1 << n);
  foreach (h; 0 .. 1 << n) fas[popcnt(h)][h] += as[h];
  foreach (i; 0 .. n + 1) foreach (j; 0 .. n) foreach (h; 0 .. 1 << n) {
    if (!(h & 1 << j)) fas[i][h | 1 << j] += fas[i][h];
  }
  auto fbs = new T[][](n + 1, 1 << n);
  foreach (h; 0 .. 1 << n) fbs[popcnt(h)][h] += bs[h];
  foreach (i; 0 .. n + 1) foreach (j; 0 .. n) foreach (h; 0 .. 1 << n) {
    if (!(h & 1 << j)) fbs[i][h | 1 << j] += fbs[i][h];
  }
  auto fcs = new T[][](n + 1, 1 << n);
  foreach (i; 0 .. n + 1) foreach (j; 0 .. n - i + 1) foreach (h; 0 .. 1 << n) {
    fcs[i + j][h] += fas[i][h] * fbs[j][h];
  }
  foreach (i; 0 .. n + 1) foreach (j; 0 .. n) foreach (h; 0 .. 1 << n) {
    if (!(h & 1 << j)) fcs[i][h | 1 << j] -= fcs[i][h];
  }
  auto cs = new T[1 << n];
  foreach (h; 0 .. 1 << n) cs[h] = fcs[popcnt(h)][h];
  return cs;
}

enum E = 17;

void main() {
  auto fib = new Mint[1 << E];
  fib[0] = 0;
  fib[1] = 1;
  foreach (j; 2 .. 1 << E) {
    fib[j] = fib[j - 1] + fib[j - 2];
  }

  try {
    for (; ; ) {
      const N = readInt();
      auto S = new int[N];
      foreach (i; 0 .. N) {
        S[i] = readInt();
      }

      auto freq = new Mint[1 << E];
      foreach (i; 0 .. N) {
        freq[S[i]] += 1;
      }

      auto ab = subsetConvolution(freq, freq);

      auto c = freq.dup;

      auto de = freq.dup;
      foreach (e; 0 .. E) {
        foreach (j; 0 .. 1 << E) {
          if (!(j & 1 << e)) {
            const t = de[j] - de[j | 1 << e];
            de[j] += de[j | 1 << e];
            de[j | 1 << e] = t;
          }
        }
      }
      foreach (j; 0 .. 1 << E) {
        de[j] = de[j] * de[j];
      }
      foreach (e; 0 .. E) {
        foreach (j; 0 .. 1 << E) {
          if (!(j & 1 << e)) {
            const t = de[j] - de[j | 1 << e];
            de[j] += de[j | 1 << e];
            de[j | 1 << e] = t;
          }
        }
      }
      de[] *= Mint(1 << E).inv;

      debug {
        writeln("ab = ", ab[0 .. 64]);
        writeln("c = ", c[0 .. 64]);
        writeln("de = ", de[0 .. 64]);
      }

      ab[] *= fib[];
      c[] *= fib[];
      de[] *= fib[];
      foreach (e; 0 .. E) {
        foreach (j; 0 .. 1 << E) {
          if (!(j & 1 << e)) {
            ab[j] += ab[j | 1 << e];
            c[j] += c[j | 1 << e];
            de[j] += de[j | 1 << e];
          }
        }
      }
      auto all = new Mint[1 << E];
      foreach (j; 0 .. 1 << E) {
        all[j] = ab[j] * c[j] * de[j];
      }
      foreach (e; 0 .. E) {
        foreach (j; 0 .. 1 << E) {
          if (!(j & 1 << e)) {
            all[j] -= all[j | 1 << e];
          }
        }
      }
      Mint ans;
      foreach (e; 0 .. E) {
        ans += all[1 << e];
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You have a stripe of checkered paper of length $$$n$$$. Each cell is either white or black.What is the minimum number of cells that must be recolored from white to black in order to have a segment of $$$k$$$ consecutive black cells on the stripe?If the input data is such that a segment of $$$k$$$ consecutive black cells already exists, then print 0.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next, descriptions of $$$t$$$ test cases follow. The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot10^5$$$). The second line consists of the letters 'W' (white) and 'B' (black). The line length is $$$n$$$. It is guaranteed that the sum of values $$$n$$$ does not exceed $$$2\cdot10^5$$$.

For each of $$$t$$$ test cases print an integer — the minimum number of cells that need to be repainted from white to black in order to have a segment of $$$k$$$ consecutive black cells.

4

5 3

BBWBW

5 5

BBWBW

5 1

BBWBW

1 1

W

NoteIn the first test case, $$$s$$$="BBWBW" and $$$k=3$$$. It is enough to recolor $$$s_3$$$ and get $$$s$$$="BBBBW". This string contains a segment of length $$$k=3$$$ consisting of the letters 'B'.In the second test case of the example $$$s$$$="BBWBW" and $$$k=5$$$. It is enough to recolor $$$s_3$$$ and $$$s_5$$$ and get $$$s$$$="BBBBB". This string contains a segment of length $$$k=5$$$ consisting of the letters 'B'.In the third test case of the example $$$s$$$="BBWBW" and $$$k=1$$$. The string $$$s$$$ already contains a segment of length $$$k=1$$$ consisting of the letters 'B'.

void main() { runSolver(); }

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

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

      long ans = S[0..K].count('B');
      long blacks = ans;
      foreach(i; K..N) {
        if (S[i - K] == 'B') blacks--;
        if (S[i] == 'B') blacks++;
        ans = max(ans, blacks);
      }

      return max(0, K - ans);
    }

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

  outputForAtCoder(&solve);
}

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

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

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


There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of pearls in a row. The second line contains n integers ai (1 ≤ ai ≤ 109) – the type of the i-th pearl.

On the first line print integer k — the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≤ lj ≤ rj ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".

import std.stdio,std.typecons;
int n,t;
bool[int] s;
auto ans=[tuple(1,0)];
void main()
{
	scanf(" %d",&n);
	foreach(i;0..n)
	{
		scanf(" %d",&t);
		if(t in s)
		{
			ans[$-1][1]=i+1;
			ans~=tuple(i+2,0);
			s=s.init;
		}else{
			s[t]=true;
		}
	}
	if(ans.length==1)
	{
		writeln(-1);
		return;
	}
	writeln(--ans.length);
	ans[$-1][1]=n;
	foreach(i;ans) writeln(i[0],' ',i[1]);
}

import std.stdio,std.typecons;
int n,t;
bool[int] s;
auto ans=[tuple(1,0)];
void main()
{
	scanf(" %d",&n);
	foreach(i;0..n)
	{
		scanf(" %d",&t);
		if(t in s)
		{
			ans[$-1][1]=i+1;
			ans~=tuple(i+2,0);
			s=s.init;
		}else{
			s[t]=true;
		}
	}
	if(ans.length==1)
	{
		writeln(-1);
		return;
	}
	writeln(--ans.length);
	ans[$-1][1]=n;
	foreach(i;ans) writeln(i[0],' ',i[1]);
	s=s.init;
}


A matrix of size $$$n \times m$$$ is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers $$$(a_1, a_2, \dots , a_k)$$$ is a palindrome, if for any integer $$$i$$$ ($$$1 \le i \le k$$$) the equality $$$a_i = a_{k - i + 1}$$$ holds.Sasha owns a matrix $$$a$$$ of size $$$n \times m$$$. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.Help him!

The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 10$$$). The $$$t$$$ tests follow. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the size of the matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i, j}$$$ ($$$0 \le a_{i, j} \le 10^9$$$) — the elements of the matrix.

For each test output the smallest number of operations required to make the matrix nice.

NoteIn the first test case we can, for example, obtain the following nice matrix in $$$8$$$ operations:2 24 44 42 2In the second test case we can, for example, obtain the following nice matrix in $$$42$$$ operations:5 6 6 56 6 6 65 6 6 5

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

void play(){
    int n, m;
    n = rd!int;
    m = rd!int;
    ll[][] mat;
    foreach(i; 0..n){
        mat ~= rdarr;
    }
    ll oper = 0;
    foreach(i; 0..(n/2 + (n % 2 != 0))){
        foreach(j; 0..(m/2 + (m % 2 != 0))){
            ll[] vals;
            vals ~= mat[i][j];
            vals ~= mat[n - i - 1][j];
            vals ~= mat[i][m - j - 1];
            vals ~= mat[n - i - 1][m - j - 1];
            ll minval = to!ll(1e12);
            foreach(v; vals){
                ll cursum = 0;
                foreach(u; vals){
                    cursum += abs(u - v);
                }
                minval = min(cursum, minval);
            }
            if(i == n/2){
                minval /= 2L;
            }
            if(j == m/2){
                minval /= 2;
            }
            oper += minval;
        }
    }
    writeln(oper);
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto a = new long [] [] (n, m);
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				readf !(" %s") (a[i][j]);
			}
		}
		long res = 0;
		foreach (i; 0..(n + 1) / 2)
		{
			foreach (j; 0..(m + 1) / 2)
			{
				int [] [] c;
				c ~= [i, j];
				c ~= [n - i - 1, j];
				c ~= [i, m - j - 1];
				c ~= [n - i - 1, m - j - 1];
				sort (c);
				c = c.uniq.array;
				auto f = c.map !(d => a[d[0]][d[1]]).array;
				sort (f);
				auto mid = f[f.length / 2];
				res += f.map !(x => abs (x - mid)).sum;
			}
		}
		writeln (res);
	}
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;
import std.traits;
import std.math;

void main(string[] args)
{
  long[100][100] mat;
  auto t = next!int;
  foreach(tc; 0 .. t)
    {
      auto n = next!int;
      auto m = next!int;
      foreach(i; 0 .. n)
	foreach(j; 0 .. m)
	  mat[i][j] = next!int;
      long cost = 0;
      foreach(i; 0 .. n)
	{
	  foreach(j; 0 .. m)
	    {
	      int si = n - 1 - i;
	      int sj = m - 1 - j;
	      long localcost = 0;
	      if (si == i)
		{
		  if (sj == j)
		    {
		      localcost = 0;
		    }
		  else
		    {
		      localcost = abs(mat[i][j] - mat[i][sj]);
		      mat[i][j] = mat[i][sj];
		    }
		}
	      else
		{
		  if (sj == j)
		    {
		      localcost = abs(mat[i][j] - mat[si][j]);
		      mat[i][j] = mat[si][j];
		    }
		  else
		    {
		      localcost = int.max;
		      long[] vals = [mat[i][j], mat[i][sj], mat[si][j], mat[si][sj]];
		      auto svals = sort(vals);
		      long usedval = vals[1];
		      localcost = abs(mat[i][j] - usedval) + abs(mat[i][sj] - usedval)
			+ abs(mat[si][j] - usedval) + abs(mat[si][sj] - usedval);
		      mat[i][j] = usedval;
		      mat[i][sj] = usedval;
		      mat[si][j] = usedval;
		      mat[si][sj] = usedval;
		    }
		}
	      cost += localcost;
	    }
	}
      cost.writeln;
    }
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}

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 m = RD!int;
		auto a = new long[][](n);
		foreach (i; 0..n)
		{
			a[i] = RDA;
		}

		auto h = (n+1)/2;
		auto w = (m+1)/2;
		foreach (i; 0..h)
		{
			foreach (j; 0..w)
			{
				long[] arr;
				auto k = n-i-1;
				auto l = m-j-1;
				arr ~= a[i][j];
				if (i != k)
					arr ~= a[k][j];
				if (j != l)
					arr ~= a[i][l];
				if (i != k && j != l)
					arr ~= a[k][l];
				if (arr.length == 1) continue;
				arr.sort();
				auto x = arr[1];
				foreach (e; arr)
				{
					ans[ti] += abs(e - x);
				}
			}
		}
	}

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

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

void play(){
    ll a = rd;
    ll b = rd;
    ll c = rd;
    writeln(a + b + c - 1);
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto a = new int [] [] (n, m);
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				readf !(" %s") (a[i][j]);
			}
		}
		int res = 0;
		foreach (i; 0..(n + 1) / 2)
		{
			foreach (j; 0..(m + 1) / 2)
			{
				int [] [] c;
				c ~= [i, j];
				c ~= [n - i - 1, j];
				c ~= [i, m - j - 1];
				c ~= [n - i - 1, m - j - 1];
				sort (c);
				c = c.uniq.array;
				auto f = c.map !(d => a[d[0]][d[1]]).array;
				sort (f);
				auto mid = f[f.length / 2];
				res += f.map !(x => abs (x - mid)).sum;
			}
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto h = (n+1)/2;
		auto w = (m+1)/2;
		foreach (i; 0..h)
		{
			foreach (j; 0..w)
			{
				long[] arr;
				auto k = n-i-1;
				auto l = m-j-1;
				arr ~= a[i][j];
				if (i != k)
					arr ~= a[k][j];
				if (j != l)
					arr ~= a[i][l];
				arr ~= a[k][l];
				arr.sort();
				auto x = arr[1];
				foreach (e; arr)
				{
					ans[ti] += abs(e - x);
				}
			}
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto h = (n+1)/2;
		auto w = (m+1)/2;
		foreach (i; 0..h)
		{
			foreach (j; 0..w)
			{
				long[] arr;
				auto k = n-i-1;
				auto l = m-j-1;
				arr ~= a[i][j];
				if (i != k)
					arr ~= a[k][j];
				if (j != l)
					arr ~= a[i][l];
				if (i != k && j != l)
					arr ~= a[k][l];
				if (arr.length == 1) continue;
				arr.sort();
				auto x = arr[1];
				foreach (e; arr)
				{
					ans[ti] += abs(e - x);
				}
			}
		}
	}

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


People in the Tomskaya region like magic formulas very much. You can see some of them below.Imagine you are given a sequence of positive integer numbers p1, p2, ..., pn. Lets write down some magic formulas:Here, "mod" means the operation of taking the residue after dividing.The expression  means applying the bitwise xor (excluding "OR") operation to integers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal — by "xor".People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence p, calculate the value of Q.

The first line of the input contains the only integer n (1 ≤ n ≤ 106). The next line contains n integers: p1, p2, ..., pn (0 ≤ pi ≤ 2·109).

The only line of output should contain a single integer — the value of Q.

module main;

import std.stdio, std.string;

auto init(int n)
{
    int[] x;
    int prev = 0;
    foreach (int i; 0 .. n)
    {
        prev ^= i;
        x ~= prev;
        //printf("%d ", prev);
    }
    //printf("\n");
    return x;
}

void solve(int[] p)
{
    auto x = init(p.length);
    int ans = 0;
    int n = p.length;
    foreach (int i; 1 .. n + 1)
    {
        ans ^= x[i - 1];
        int cnt = (n - (i - 1)) / i;
        int left = (n - (i - 1)) % i;
        //printf("%d %d\n", cnt, left);
        if (cnt & 1)
        {
            ans ^= x[i - 1];
        }
        if (left != 0)
        {
            ans ^= x[left - 1];
        }
        ans ^= p[i - 1];
    }
    writefln("%d", ans);
    //printf("%d\n", ans);
}

int main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
        int[] p = new int[n];
        foreach (int i; 0 .. n)
        {
            scanf("%d", &p[i]);
        }
        solve(p);
    }
    return 0;
}

module main;

import std.stdio, std.string;

auto init(int n)
{
    int[] x = new int[n];
    int prev = 0;
    foreach (int i; 0 .. n)
    {
        prev ^= i;

        x[i] = prev;
        //x ~= prev;
        //printf("%d ", prev);
    }
    //printf("\n");
    return x;
}

void solve(int[] p)
{
    auto x = init(p.length);
    int ans = 0;
    int n = p.length;
    foreach (int i; 1 .. n + 1)
    {
        ans ^= x[i - 1];
        int cnt = (n - (i - 1)) / i;
        int left = (n - (i - 1)) % i;
        //printf("%d %d\n", cnt, left);
        if (cnt & 1)
        {
            ans ^= x[i - 1];
        }
        if (left != 0)
        {
            ans ^= x[left - 1];
        }
        ans ^= p[i - 1];
    }
    writefln("%d", ans);
    //printf("%d\n", ans);
}

int main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
        int[] p = new int[n];
        foreach (int i; 0 .. n)
        {
            scanf("%d", &p[i]);
        }
        solve(p);
    }
    return 0;
}


The only difference between this problem and the hard version is the maximum number of questions.This is an interactive problem.There is a hidden integer $$$1 \le x \le n$$$ which you have to find. In order to find it you can ask at most $$$\mathbf{53}$$$ questions.In each question you can choose a non-empty integer set $$$S$$$ and ask if $$$x$$$ belongs to $$$S$$$ or not, after each question, if $$$x$$$ belongs to $$$S$$$, you'll receive "YES", otherwise "NO".But the problem is that not all answers are necessarily true (some of them are joking), it's just guaranteed that for each two consecutive questions, at least one of them is answered correctly.Additionally to the questions, you can make at most $$$2$$$ guesses for the answer $$$x$$$. Each time you make a guess, if you guess $$$x$$$ correctly, you receive ":)" and your program should terminate, otherwise you'll receive ":(".As a part of the joking, we will not fix the value of $$$x$$$ in the beginning. Instead, it can change throughout the interaction as long as all the previous responses are valid as described above.Note that your answer guesses are always answered correctly. If you ask a question before and after a guess, at least one of these two questions is answered correctly, as normal.

The only line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the maximum possible value of $$$x$$$.

NoteIf the answer of the first question were correct, then $$$x$$$ would have been equal to $$$6$$$, but as we can see in the first guess, $$$6$$$ is not the answer.So the answer of the first question is joking. As we know, the answer of at least one of our two questions is correct, since the answer of the first question was joking, the answer of the second question should be correct.So we will understand that $$$x$$$ is not equal to $$$1, 2, 3$$$ or $$$4$$$, and we also knew that $$$x$$$ is not equal to $$$6$$$ either. Hence $$$x$$$ should be equal to $$$5$$$.

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

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

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

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

enum INF = 10^^9;
enum W = 1;

alias Result = Tuple!(int, "cost", int, "a0", int, "b0");
Result[long] cache;
Result calc(int a, int b) {
  const key = cast(long)(a) << 20 | b;
  auto ptr = key in cache;
  if (ptr) return *ptr;
  Result ret = Result(INF, -1, -1);

  if (a + b <= 2) {
    ret.cost = 0;
  } else if (b == 0) {
    // ask a0
    foreach (a0; (a / 2 - W) .. (a / 2 + W) + 1) if (0 < a0 && a0 < a) {
      const a1 = a - a0;
      if (chmin(ret.cost, 1 + max(calc(a0, a1).cost, calc(a1, a0).cost))) {
        ret.a0 = a0;
      }
    }
  } else if (b == 1) {
    // ask b
    ret.cost = 1 + max(calc(b, a).cost, calc(a, 0).cost);
  } else {
    // ask a0, b0
    foreach (a0; (a / 2 - W) .. (a / 2 + W) + 1) if (0 <= a0 && a0 <= a) {
      foreach (b0; (b / 2 - W) .. (b / 2 + W) + 1) if (0 < b0 && b0 < b) {
        const a1 = a - a0;
        const b1 = b - b0;
        if (chmin(ret.cost, 1 + max(calc(a0 + b0, a1).cost, calc(a1 + b1, a0).cost))) {
          ret.a0 = a0;
          ret.b0 = b0;
        }
      }
    }
  }
  debug {
    if (a + b <= 5) {
      writeln(a, " ", b, ": ", ret);
    }
  }

  return cache[key] = ret;
}

bool Ask(const(int[]) xs) {
  writef("? %s", xs.length);
  foreach (x; xs) {
    write(" ", x);
  }
  writeln;
  stdout.flush;
  const res = readToken;
  return (res == "YES");
}
void Answer(const(int[]) xs) {
  foreach (x; xs) {
    writefln("! %s", x);
    stdout.flush;
    const res = readToken;
    if (res == ":)") {
      return;
    }
  }
  assert(false);
}

void main() {
  debug {
    foreach (e; 1 .. 5 + 1) {
      const n = 10^^e;
      const res = calc(n, 0);
      writefln("n = %s: |cache| = %s; %s", n, cache.length, res);
      stdout.flush;
    }
  }

  const N = readInt;
  int[] xs = iota(1, N + 1).array, ys;
  for (; ; ) {
    debug {
      writeln(xs, " ", ys);
    }
    const a = cast(int)(xs.length);
    const b = cast(int)(ys.length);
    const res = calc(a, b);
    if (a + b <= 2) {
      break;
    } else if (b == 0) {
      int[] xs0 = xs[0 .. res.a0], xs1 = xs[res.a0 .. a];
      if (Ask(xs0)) {
        xs = xs0;
        ys = xs1;
      } else {
        xs = xs1;
        ys = xs0;
      }
    } else if (b == 1) {
      if (Ask(ys)) {
        swap(xs, ys);
      } else {
        ys = [];
      }
    } else {
      int[] xs0 = xs[0 .. res.a0], xs1 = xs[res.a0 .. a];
      int[] ys0 = ys[0 .. res.b0], ys1 = ys[res.b0 .. b];
      if (Ask(xs0 ~ ys0)) {
        xs = xs0 ~ ys0;
        ys = xs1;
      } else {
        xs = xs1 ~ ys1;
        ys = xs0;
      }
    }
  }
  Answer(xs ~ ys);
}


In the work of a doctor, it is important to maintain the anonymity of clients and the results of tests. The test results are sent to everyone personally by email, but people are very impatient and they want to know the results right away.That's why in the testing lab "De-vitro" doctors came up with an experimental way to report the results. Let's assume that $$$n$$$ people took the tests in the order of the queue. Then the chief doctor Sam can make several statements, in each telling if there is a sick person among the people in the queue from $$$l$$$-th to $$$r$$$-th (inclusive), for some values $$$l$$$ and $$$r$$$.During the process, Sam will check how well this scheme works and will be interested in whether it is possible to find out the test result of $$$i$$$-th person from the information he announced. And if it can be done, then is that patient sick or not.Help Sam to test his scheme.

The first line contains two integers $$$n$$$, $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of people and the number of queries. In each of the next $$$q$$$ lines, the description of the query is given. The first number in the line is $$$t$$$ ($$$t = 0$$$ or $$$t = 1$$$) — the type of the query. If $$$t = 0$$$, the line contains three more integers $$$l, r, x$$$ ($$$1 \le l \le r \le n$$$, $$$x = 0$$$ or $$$x = 1$$$). This query means that Sam tells that among the people in the queue from $$$l$$$-th to $$$r$$$-th (inclusive):    there was at least one sick person, if $$$x=1$$$,  there is no sick people, if $$$x=0$$$.  If $$$t = 1$$$, the line contains one more integer $$$j$$$ ($$$1 \le j \le n$$$) — the position of the patient in the queue, for which Sam wants to know the status. All queries are correct, that means that there always exists an example of the queue of length $$$n$$$ for which all reported results (statements from queries with $$$t = 0$$$) are true.

After each Sam question (query with $$$t = 1$$$) print:   "NO", if the patient is definitely not sick,  "YES", if the patient is definitely sick.  "N/A", if it is impossible to definitely identify the status of patient having the given information.

NoteIn the first test for the five first queries:  Initially Sam tells that people $$$4$$$, $$$5$$$ are not sick.  In the next query Sam asks the status of the patient $$$5$$$. From the previous query, we know that the patient is definitely not sick.  In the next query Sam asks the status of the patient $$$6$$$. We don't know any information about that patient now.  After that Sam tells that there exists a sick patient among $$$4$$$, $$$5$$$, $$$6$$$.  In the next query Sam asks the status of the patient $$$6$$$. Now we can tell that this patient is definitely sick.

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

void main ()
{
	int n, q;
	while (readf !(" %s %s") (n, q) > 0)
	{
		n += 2;
		readln;

		auto next = n.iota.array;
		next[] += 1;
		next[n - 1] = n - 1;
		auto prev = n.iota.array;
		prev[] -= 1;
		prev[0] = 0;
		auto best = new int [n];
		best[] = n;
		auto safe = new bool [n];

		int getFirst (int pos)
		{
			if (safe[pos])
			{
				return next[pos] = getFirst (next[pos]);
			}
			return pos;
		}

		foreach (j; 0..q)
		{
			auto r = readln.splitter.map !(to !(int)).array;
			auto t = r[0];
			if (t == 0)
			{
				auto lo = r[1];
				auto hi = r[2] + 1;
				auto value = r[3];
				int pos = getFirst (lo);
				debug {writeln ("pos = ", pos);}
				if (value == 0)
				{
					while (pos < hi)
					{
						next[prev[pos]] = next[pos];
						prev[next[pos]] = prev[pos];
						best[prev[pos]] = min
						    (best[prev[pos]],
						    best[pos]);
						best[next[pos]] = min
						    (best[next[pos]],
						    best[pos]);
						safe[pos] = true;
						pos = next[pos];
					}
				}
				else if (value == 1)
				{
					best[pos] = min (best[pos], hi);
				}
				else
				{
					assert (false);
				}
				debug {writeln (j, ": ", r);}
				debug {writeln (n.iota.array);}
				debug {writeln (prev);}
				debug {writeln (next);}
				debug {writeln (best);}
				debug {writefln !("[%(%d, %)]") (safe);}
			}
			else if (t == 1)
			{
				auto pos = r[1];
				if (safe[pos])
				{
					writeln ("NO");
				}
				else if (best[pos] <= next[pos])
				{
					writeln ("YES");
				}
				else
				{
					writeln ("N/A");
				}
			}
			else
			{
				assert (false);
			}
		}
	}
}


Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.You are given a tree with $$$n$$$ nodes. In the beginning, $$$0$$$ is written on all edges. In one operation, you can choose any $$$2$$$ distinct leaves $$$u$$$, $$$v$$$ and any real number $$$x$$$ and add $$$x$$$ to values written on all edges on the simple path between $$$u$$$ and $$$v$$$.For example, on the picture below you can see the result of applying two operations to the graph: adding $$$2$$$ on the path from $$$7$$$ to $$$6$$$, and then adding $$$-0.5$$$ on the path from $$$4$$$ to $$$5$$$.   Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?Leaf is a node of a tree of degree $$$1$$$. Simple path is a path that doesn't contain any node twice.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), meaning that there is an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that these edges form a tree.

If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".  Otherwise, output "YES".  You can print each letter in any case (upper or lower).

NoteIn the first example, we can add any real $$$x$$$ to the value written on the only edge $$$(1, 2)$$$.  In the second example, one of configurations that we can't reach is $$$0$$$ written on $$$(1, 2)$$$ and $$$1$$$ written on $$$(2, 3)$$$.  Below you can see graphs from examples $$$3$$$, $$$4$$$:

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

	Node[] nodes;
	foreach(i; 0 .. n) nodes ~= new Node(i);

	foreach(i; 0 .. n - 1){
		int u = read.to!int - 1;
		int v = read.to!int - 1;
		nodes[u].nodes ~= nodes[v];
		nodes[v].nodes ~= nodes[u];
	}

	int f = 0;
	foreach(nd; nodes){
		if(nd.nodes.length == 2) f = 1;
	}

	if(f == 1) "NO".writeln;
	else "YES".writeln;

}
/*
A1: YES if and only if there are no vertex with degree 2.

*/

class Node{
	int id;
	Node[] nodes;
	this(int id){
		this.id = id;
	}
}

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

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

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

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

int N;
int[] U, V;

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

      auto deg = new int[N];
      foreach (i; 0 .. N - 1) {
        ++deg[U[i]];
        ++deg[V[i]];
      }
      const ans = (deg.count(2) == 0);
      writeln(ans ? "YES" : "NO");
    }
  } catch (EOFException e) {
  }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.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; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

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

void main()
{
	auto n = RD!int;
	auto edges = new long[][](n);
	foreach (i; 0..n-1)
	{
		auto u = RD!int-1;
		auto v = RD!int-1;
		edges[u] ~= v;
		edges[v] ~= u;
	}

	debug writeln(edges);
	bool ans = true;
	foreach (i; 0..n)
	{
		if (edges[i].length == 2)
		{
			ans = false;
			break;
		}
	}

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

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

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

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

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

int N;
int[] U, V;

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

      auto deg = new int[N];
      foreach (i; 0 .. N - 1) {
        ++deg[U[i]];
        ++deg[V[i]];
      }
      const long cnt = deg.count(1);
      const ans = (cnt * (cnt - 1) / 2 >= N - 1);
      writeln(ans ? "YES" : "NO");
    }
  } catch (EOFException e) {
  }
}


There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?

The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.

Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.

NoteIn the first test, you can perform the following sequence:  ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence:  ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes;  ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes;  ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.

import std;

enum int INF = 1<<28;

void chmin(ref int x, int y) { x = min(x, y); }

void main() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").to!(int[]);

    int[] X, Y;
    foreach (i; 0 .. N) {
        (A[i] == 1 ? X : Y) ~= i;
    }
    int nX = X.length;
    int nY = Y.length;
    auto f = new int[][](nX + 1, nY + 1); {
        foreach (i; 0 .. nX + 1) f[i][] = INF;
        f[0][] = 0;
    }
    for (int i = 1; i <= nX; i++) {
        for (int j = 1; j <= nY; j++) {
            int x = X[i-1], y = Y[j-1];
            f[i][j].chmin(f[i][j-1]);
            f[i][j].chmin(f[i-1][j-1] + abs(x - y));
        }
    }
    writeln(f[nX][nY]);
}


Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $$$k$$$ such that Mr. Black can exit the house after opening the first $$$k$$$ doors.We have to note that Mr. Black opened each door at most once, and in the end all doors became open.

The first line contains integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of doors. The next line contains $$$n$$$ integers: the sequence in which Mr. Black opened the doors. The $$$i$$$-th of these integers is equal to $$$0$$$ in case the $$$i$$$-th opened door is located in the left exit, and it is equal to $$$1$$$ in case it is in the right exit. It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.

Print the smallest integer $$$k$$$ such that after Mr. Black opened the first $$$k$$$ doors, he was able to exit the house.

NoteIn the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.In the second example when the first two doors were opened, there was open closed door in each of the exit.With three doors opened Mr. Black was able to use the left exit.

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

void main()
{
    auto N = readln.chomp.to!int;
    auto ds = readln.split.to!(int[]);
    int l, r;
    foreach (d; ds) {
        if (d) {
            ++r;
        } else {
            ++l;
        }
    }
    int cnt;
    foreach (d; ds) {
        ++cnt;
        if (d) {
            --r;
        } else {
            --l;
        }
        if (!r || !l) {
            writeln(cnt);
            return;
        }
    }
}


You are given an array of n integers a1... an. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into k non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be present in exactly one subsegment.

The first line contains two integers n and k (2 ≤ n ≤ 105, 2 ≤ k ≤ min (n, 20))  — the length of the array and the number of segments you need to split the array into. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the array.

Print single integer: the minimum possible total cost of resulting subsegments.

NoteIn the first example it's optimal to split the sequence into the following three subsegments: [1], [1, 3], [3, 3, 2, 1]. The costs are 0, 0 and 1, thus the answer is 1.In the second example it's optimal to split the sequence in two equal halves. The cost for each half is 4.In the third example it's optimal to split the sequence in the following way: [1, 2, 2, 2, 1], [2, 1, 1, 1, 2], [2, 1, 1]. The costs are 4, 4, 1.

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

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

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

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

enum INF = 10L^^18;

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

      auto dp = new long[][](K + 1, N + 1);
      foreach (k; 0 .. K + 1) {
        dp[k][] = INF;
      }
      dp[0][0] = 0;
      foreach (k; 0 .. K) {
        auto freq = new long[N];
        long cost;
        int l, r;
        void incrL() { cost -= --freq[A[l++]]; }
        void decrL() { cost += freq[A[--l]]++; }
        void incrR() { cost += freq[A[r++]]++; }
        void decrR() { cost -= --freq[A[--r]]; }

        void solve(int i0, int i1, int j0, int j1) {
          if (i1 - i0 < 1) {
            return;
          }
          debug {
            // writefln("solve [%s, %s) [%s, %s)", i0, i1, j0, j1);
          }
          const i = (i0 + i1) / 2;
          for (; r < i; ) incrR();
          for (; r > i; ) decrR();
          int jm = -1;
          foreach (j; j0 .. min(j1, i)) {
            debug {
              // writeln("  ", i, " ", j);
            }
            for (; l < j; ) incrL();
            for (; l > j; ) decrL();
            if (chmin(dp[k + 1][i], dp[k][j] + cost)) {
              jm = j;
            }
          }
          solve(i0, i, j0, jm + 1);
          solve(i + 1, i1, jm, j1);
        }
        solve(k + 1, N + 1, k, N);
      }

      debug {
        foreach (k; 0 .. K + 1) {
          writefln("dp[%s] = %s", k, dp[k]);
        }
      }
      writeln(dp[K][N]);

      debug {
        auto brt = new long[][](K + 1, N + 1);
        foreach (k; 0 .. K + 1) {
          brt[k][] = INF;
        }
        brt[0][0] = 0;
        foreach (k; 0 .. K) {
          foreach (i; 0 .. N + 1) {
            foreach (j; i + 1 .. N + 1) {
              long cost;
              foreach (grp; A[i .. j].dup.sort.group) {
                const long num = grp[1];
                cost += num * (num - 1) / 2;
              }
              chmin(brt[k + 1][j], brt[k][i] + cost);
            }
          }
        }
        foreach (k; 0 .. K + 1) {
          writefln("brt[%s] = %s", k, brt[k]);
        }
        assert(brt == dp);
      }
    }
  } 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) {
  }
}


Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely.One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix.Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers.

The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries.

If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on.

import std.algorithm;
import std.stdio;
import std.typecons;

alias Tuple !(int, int) pair;

int [] ans;
int [] [] g;
int [] deg;
int [] e;
int n, m;

bool recur (int v)
{
    if (e[v] == 2)
    {
        return true;
    }
    if (e[v] == 1)
    {
        return false;
    }
    debug {writefln ("recur in  %s", v);}
    e[v] = 1;
    foreach (c; g[v])
    {
        if (!recur (c))
        {
            return false;
        }
    }
    if (v < m)
    {
        debug {writefln ("!");}
        ans ~= v + 1;
    }
    e[v] = 2;
    debug {writefln ("recur out %s", v);}
    return true;
}

void main ()
{
    while (readf (" %s %s", &n, &m) > 0)
    {
        auto a = new int [] [n];
        foreach (i; 0..n)
        {
            a[i] = new int [m];
            foreach (j; 0..m)
            {
                readf (" %s", &a[i][j]);
            }
        }

        const int SIZE = m + m * n;
        g = new int [] [SIZE];
        deg = new int [SIZE];
        auto b = new pair [m];
        int p = m;
        foreach (i; 0..n)
        {
            int d = 0;
            foreach (j; 0..m)
            {
                if (a[i][j] != -1)
                {
                    b[d][0] = a[i][j];
                    b[d][1] = j;
                    d++;
                }
            }
            sort (b[0..d]);
            int lo, me, hi;
            int cur = b[0][0];
            for (hi = 0; hi <= d; hi++)
            {
                if (hi > 0 &&
                    (hi == d || b[hi][0] != b[hi - 1][0]))
                {
                    foreach (u; lo..me)
                    {
                        g[b[u][1]] ~= p;
                        deg[p]++;
                    }
                    foreach (u; me..hi)
                    {
                        g[p] ~= b[u][1];
                        deg[b[u][1]]++;
                    }
                    p++;
                    lo = me;
                    me = hi;
                }
            }
        }

        bool ok = true;
        e = new int [p];
        ans = new int [0];
        foreach (i; 0..p)
        {
            if (e[i] == 0 && deg[i] == 0)
            {
                if (!recur (i))
                {
                    ok = false;
                    break;
                }
            }
        }
        if (ok)
        {
            foreach (i; 0..p)
            {
                if (e[i] != 2)
                {
                    ok = false;
                    break;
                }
            }
        }
        if (ok)
        {
            debug {writefln ("%s", ans);}
            reverse (ans);
            writefln ("%(%s %)", ans);
        }
        else
        {
            writefln ("-1");
        }
    }
}


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

import std.bigint,std.container,std.array,std.algorithm,std.conv,std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.typecons,std.regex,
std.random,std.uni,std.traits,std.variant;
import core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
immutable int mod=1000000007;
pure nothrow T lcm (T)(auto ref T a,auto ref T b)
{
	return a/gcd(a,b)*b;
}
pure nothrow X binpow(X,Y)(X base,Y exp)
if(is(typeof(exp&1)))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
if(is(typeof(exp&1)))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(X a,in int n,in int m)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in int n){bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0) {return readf(replicate(" %s"~'\n', ptrs.length), ptrs)==ptrs.length;}
struct pair(X,Y)
{
	X first;
	Y second;
	alias first fi;
	alias second se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
	}
	this(this){fi=fi;se=se;}
	this(A,B)(auto ref pair!(A,B) p) if(is(A:X) && is(B:Y))
	{
		fi=p.fi;
		se=p.se;
	}
	int opCmp(A,B)(in pair!(A,B) s_) const pure nothrow @safe if(is(typeof(s_.fi<fi)==bool) && is(typeof(s_.se<se)==bool))
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(in X x_,in Y y_) pure nothrow @safe
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_;}
X cub(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_*a_;}
nothrow @nogc @system void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow @nogc @system void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.split.map!(to!(T)).array;}
nothrow pure size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (!(a[l]<g))?l:r;
}
pure nothrow size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(g<a[m])r=m;
		else l=m;
	}
	return (g<a[l])?l:r;
}
pure nothrow size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (g==a[l])?l:a.length;
}
pure nothrow bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	return binf(a,g)!=a.length;
}
pure nothrow V foldr(R,V,T)(R range,T arg,V nach) if(isFunction!T && isInputRange!R && is(typeof(arg(nach,R.front))==V))
{
	for(;!range.empty;range.popFront()) nach=arg(nach,range.front);
	return nach;
}
pure nothrow size_t countr(R,T)(R range,T fun) if(isFunction!T && isInputRange!R && is(typeof(fun(R.front))==bool))
{
	size_t nach;
	for(;!range.empty;range.popFront()) nach+=fun(range.front);
	return nach;
}
pure nothrow T orient_square(T)(pair!(T,T)[] figure...) if(figure.length>2 && is(typeof(figure.front*figure.front)==T))
{
	auto n=figure.front,t=figure.front;
	figure.popFront();
	T ans=0;
	for(;!figure.empty;figure.popFront())
	{
		ans+=(figure.front.fi-t.fi)*(figure.front.se+t.se);
		t=figure.front;
	}
	return ans+(n.fi-t.fi)*(n.se+t.se);
}
pure nothrow real square(T)(pair!(T,T)[] figure...) if(figure.length>2 && is(typeof(figure.front*figure.front)==T))
{
	return abs(orient_square(figure))/2.00000000000;
}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n;
	while(input(&n))
	{
		auto s=readln.strip.split(':').map!(to!int).array;
		int ans;
		if(s[1]>59) {s[1]%=10;}
		if(n==12)
		{
			if(s[0]==0){s[0]=10;}
			else if(s[0]>12)
			{
				if(s[0]%10<=2)s[0]=s[0]%10+10;
				else s[0]%=10;
			}
		}
		else if(s[0]>23){s[0]%=10;ans++;}
		writefln("%02d:%02d",s[0],s[1]);

	}
	debug system("pause");
}

import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.format;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.strip;
		int res = 5;
		string ans = "?????";
		foreach (c; 0..10_000)
		{
			int h = c / 100;
			if (n == 12 && !(1 <= h && h <= 12))
			{
				continue;
			}
			if (n == 24 && !(0 <= h && h <= 23))
			{
				continue;
			}
			int m = c % 100;
			if (!(0 <= m && m <= 59))
			{
				continue;
			}
			auto t = format ("%02d:%02d", h, m);
			auto cur = t.length.iota.map !(x => s[x] != t[x]).sum;
			if (res > cur)
			{
				res = cur;
				ans = t;
			}
		}
		writeln (ans);
	}
}


Naman has two binary strings $$$s$$$ and $$$t$$$ of length $$$n$$$ (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert $$$s$$$ into $$$t$$$ using the following operation as few times as possible.In one operation, he can choose any subsequence of $$$s$$$ and rotate it clockwise once.For example, if $$$s = 1\textbf{1}101\textbf{00}$$$, he can choose a subsequence corresponding to indices ($$$1$$$-based) $$$\{2, 6, 7 \}$$$ and rotate them clockwise. The resulting string would then be $$$s = 1\textbf{0}101\textbf{10}$$$.A string $$$a$$$ is said to be a subsequence of string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some characters without changing the ordering of the remaining characters.To perform a clockwise rotation on a sequence $$$c$$$ of size $$$k$$$ is to perform an operation which sets $$$c_1:=c_k, c_2:=c_1, c_3:=c_2, \ldots, c_k:=c_{k-1}$$$ simultaneously.Determine the minimum number of operations Naman has to perform to convert $$$s$$$ into $$$t$$$ or say that it is impossible.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^6)$$$ — the length of the strings. The second line contains the binary string $$$s$$$ of length $$$n$$$. The third line contains the binary string $$$t$$$ of length $$$n$$$.

If it is impossible to convert $$$s$$$ to $$$t$$$ after any number of operations, print $$$-1$$$. Otherwise, print the minimum number of operations required.

NoteIn the first test, Naman can choose the subsequence corresponding to indices $$$\{2, 6\}$$$ and rotate it once to convert $$$s$$$ into $$$t$$$.In the second test, he can rotate the subsequence corresponding to all indices $$$5$$$ times. It can be proved, that it is the minimum required number of operations.In the last test, it is impossible to convert $$$s$$$ into $$$t$$$.

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

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

    int s, t, c, max_c, d, max_d;
    foreach (i; 0..N) {
        auto s1 = S[i] == '1';
        auto t1 = T[i] == '1';
        if (s1) ++s;
        if (t1) ++t;

        if (s1 && !t1) {
            ++c;
            if (d > 0) --d;
        } else if (!s1 && t1) {
            ++d;
            if (c > 0) --c;
        }
        max_c = max(max_c, c);
        max_d = max(max_d, d);
    }

    if (s != t) {
        writeln(-1);
    } else {
        writeln(max(max_c, max_d));
    }
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto s = readln.strip.map !(to !(byte)).array;
		auto t = readln.strip.map !(to !(byte)).array;
		if (sum (s) != sum (t))
		{
			writeln (-1);
			continue;
		}

		int balance = 0;
		int lo = 0;
		int hi = 0;
		foreach (i; 0..n)
		{
			balance += s[i] - t[i];
			lo = min (lo, balance);
			hi = max (hi, balance);
		}
		writeln (hi - lo);
	}
}

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

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

    int s, t, c, max_c;
    foreach (i; 0..N) {
        auto s1 = S[i] == '1';
        auto t1 = T[i] == '1';
        if (s1) ++s;
        if (t1) ++t;

        if (s1 && !t1) {
            ++c;
        } else if (!s1 && t1) {
            --c;
        }
        max_c = max(max_c, abs(c));
    }

    if (s != t) {
        writeln(-1);
    } else {
        writeln(max_c);
    }
}


Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x > y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers:  the number of ways to distribute the cards so that Alex wins;  the number of ways to distribute the cards so that Boris wins;  the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows:  if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw;  if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).

For each test case, print three integers:   the number of ways to distribute the cards so that Alex wins;  the number of ways to distribute the cards so that Boris wins;  the number of ways to distribute the cards so that the game ends in a draw.  Since the answers can be large, print them modulo $$$998244353$$$.

NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case:   Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$;  Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$;  the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.

import std.stdio;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

struct ModInt(long mod) {
    invariant() {
        assert(0 <= val && val < mod);
    }
    long val;
    this(long v) { this.val = (mod * mod + v) % mod; }
    ModInt opBinary(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(int y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(int y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(long y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(long y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(ModInt y) const { return ModInt(this.val + y.val); }
    ModInt opBinary(string op : "-")(ModInt y) const { return ModInt(this.val - y.val); }
    ModInt opBinary(string op : "*")(ModInt y) const { return ModInt(this.val * y.val); }
    ModInt opBinary(string op : "/")(ModInt y) const { return ModInt(this.val * inv(y.val)); }
    ModInt opBinaryRight(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(int y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(int y) const { return ModInt(inv(this.val) * y); }
    ModInt opBinaryRight(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(long y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(long y) const { return ModInt(inv(this.val) * y); }
    void opAssign(int y) { this.val = y; }
    void opAssign(long y) { this.val = y; }
    void opOpAssign(string op : "+")(int y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(int y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(int y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(int y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(long y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(long y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(long y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(long y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(ModInt y) { this.val = (this.val + mod * mod + y.val) % mod; }
    void opOpAssign(string op : "-")(ModInt y) { this.val = (this.val + mod * mod - y.val) % mod; }
    void opOpAssign(string op : "*")(ModInt y) { this.val = (this.val * y.val) % mod; }
    void opOpAssign(string op : "/")(ModInt y) { this.val = (this.val * inv(y.val)) % mod; }
    ModInt opUnary(string op : "-")() const { return ModInt(mod - this.val); }
    string toString() const { return val.to!string; }
    static long extgcd(long a, long b, ref long x, ref long y) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long d = extgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    static long inv(long a) {
        long x, y;
        extgcd(a, mod, x, y);
        return (x % mod + mod) % mod;
    }
}

alias MInt = ModInt!998244353L;

MInt fact(int n) {
    MInt a = 1;
    for (int i = 1; i <= n; i++) a *= i;
    return a;
}

MInt nCk(int n, int k) {
    return fact(n) / fact(k) / fact(n - k);
}

void solve() {
    auto N = readln.chomp.to!int;
    auto f = new MInt[][](2, N+1);
    f[0][2] = 1;
    f[1][2] = 0;
    for (int n = 4; n <= N; n += 2) {
        f[0][n] = nCk(n-1, n/2-1) + f[1][n-2];
        f[1][n] = f[0][n-2] + nCk(n-2, n/2-2);
    }
    MInt a = f[0][N];
    MInt b = f[1][N];
    MInt d = nCk(N, N/2) - f[0][N] - f[1][N];
    writefln("%(%s %)", [a, b, d]);
}

void main() {
    int T = readln.chomp.to!int;
    foreach (t; 0 .. T) solve();
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$.In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $$$[2, 1, 4]$$$ you can obtain the following arrays: $$$[3, 4]$$$, $$$[1, 6]$$$ and $$$[2, 5]$$$.Your task is to find the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$).

For each query print one integer in a single line — the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing described operation an arbitrary (possibly, zero) number of times.

NoteIn the first query of the example you can apply the following sequence of operations to obtain $$$3$$$ elements divisible by $$$3$$$: $$$[3, 1, 2, 3, 1] \rightarrow [3, 3, 3, 1]$$$.In the second query you can obtain $$$3$$$ elements divisible by $$$3$$$ with the following sequence of operations: $$$[1, 1, 1, 1, 1, 2, 2] \rightarrow [1, 1, 1, 1, 2, 3] \rightarrow [1, 1, 1, 3, 3] \rightarrow [2, 1, 3, 3] \rightarrow [3, 3, 3]$$$.

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;
import std.math;

alias Tree = RBT!int;
alias ll = long;

int[101] a;

void main() {
  GC.disable();

  int t;
  readf(" %s", t);

  foreach(q;0..t) {
    int n;
    readf(" %s", n);
    int[3] c;
    foreach(i;0..n) {
      int ai;
      readf(" %s", ai);
      c[ai%3]++;
    }

    auto tt = min(c[1], c[2]);
    c[1] -= tt;
    c[2] -= tt;

    writeln( c[0] + c[1]/3 + c[2]/3 + tt);
  }

}

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto a = RDR.ARR;
		auto cnt = new long[](3);
		foreach (j; 0..n)
		{
			auto x = a[j] % 3;
			++cnt[cast(size_t)x];
		}
		auto x = min(cnt[1], cnt[2]);
		ans[i] = cnt[0] + x + (cnt[1]-x)/3 + (cnt[2]-x)/3;
	}

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

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto a = RDR.ARR;
		auto cnt = new long[](3);
		foreach (j; 0..n)
		{
			auto x = a[j] % 3;
			++cnt[cast(size_t)x];
		}
		auto x = min(cnt[1], cnt[2]);
		ans[i] = cnt[0] + x + (cnt[1]-x)/3;
	}

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