Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers $$$d, m$$$, find the number of arrays $$$a$$$, satisfying the following constraints:  The length of $$$a$$$ is $$$n$$$, $$$n \ge 1$$$  $$$1 \le a_1 < a_2 < \dots < a_n \le d$$$  Define an array $$$b$$$ of length $$$n$$$ as follows: $$$b_1 = a_1$$$, $$$\forall i > 1, b_i = b_{i - 1} \oplus a_i$$$, where $$$\oplus$$$ is the bitwise exclusive-or (xor). After constructing an array $$$b$$$, the constraint $$$b_1 < b_2 < \dots < b_{n - 1} < b_n$$$ should hold. Since the number of possible arrays may be too large, you need to find the answer modulo $$$m$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) denoting the number of test cases in the input. Each of the next $$$t$$$ lines contains two integers $$$d, m$$$ ($$$1 \leq d, m \leq 10^9$$$). Note that $$$m$$$ is not necessary the prime!

For each test case, print the number of arrays $$$a$$$, satisfying all given constrains, modulo $$$m$$$.

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int d, m;
		readf !(" %s %s") (d, m);

		long res = 1;
		for (long p = 1; p <= d; p <<= 1)
		{
			long hi = min ((p << 1) - 1, d);
			long total = hi - p + 2;
			res = (res * total) % m;
		}
		res = (res + m - 1) % m;
		writeln (res);
	}
}

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const d = r.next!uint;
    const m = r.next!uint;
    uint add (uint x, uint y) {
      x += y;
      if (x >= m) x -= m;
      return x;
    }
    uint sub (uint x, uint y) {
      if (x < y) x += m;
      x -= y;
      return x;
    }
    uint mul (uint x, uint y) {
      ulong z = x.to!ulong * y;
      return (z % m).to!uint;
    }
    auto deg = new uint[32];
    int last = 1;
    foreach (i; 1 .. 32) {
      uint l = min (d + 1, 1U << i);
      debug stderr.writeln ("l = ", l);
      if (l == last) break;
      uint dt = l - last;
      debug stderr.writeln ("dt = ", dt);
      deg[i] = dt % m;
      last = l;
    }
    debug stderr.writeln (deg);
    auto u = new uint[32];
    u[0] = 1;
    uint res;
    while (u.any!("a != 0")) {
      auto e = new uint[32];
      foreach (i; 0 .. 32) {
        foreach (j; i + 1 .. 32) {
          e[j] = add (e[j], mul (u[i], deg[j]));
        }
      }
      debug stderr.writeln ("e = ", e);
      u = e;
      foreach (i; u) {
        res = add (res, i);
      }
    }
    writeln (res);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. scan!int){
        long d = scan!long, m = scan!long;
        long u = 1;
        long ans = 0;
        long tmp = 1;
        int i = 0;
        d += 1;
        while(u <= d){
            tmp *= u / 2 + 1, tmp %= m;
            ans += tmp * u, ans %= m;
            i += 1;
            u *= 2;
        }
        ans += m - tmp * (u - d) % m, ans %= m;
        tmp *= u / 2 + 1, tmp %= m;
        ans.print;
    }

}

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 {
  static int 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 == "^^") {
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e; 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 if (op == "-") { 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"); }
  string toString() const { return x.to!string; }
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const D = readLong();
        ModInt.M = readInt();

        ModInt ans = 1;
        for (int e = 0; ; ++e) {
          long lb = 1 << e, ub = 1 << (e + 1);
          chmin(ub, D + 1);
          debug {
            writeln(e, ": ", lb, " ", ub);
          }
          if (lb < ub) {
            ans *= (1 + (ub - lb));
          } else {
            break;
          }
        }
        ans -= 1;
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const d = r.next!uint;
    const m = r.next!uint;
    uint add (uint x, uint y) {
      x += y;
      if (x >= m) x -= m;
      return x;
    }
    uint sub (uint x, uint y) {
      if (x < y) x += m;
      x -= y;
      return x;
    }
    uint mul (uint x, uint y) {
      ulong z = x.to!ulong * y;
      return (z % m).to!uint;
    }
    auto deg = new uint[32];
    int last = 1;
    foreach (i; 1 .. 32) {
      int l = min (d + 1, 1 << i);
      debug stderr.writeln ("l = ", l);
      int dt = l - last;
      debug stderr.writeln ("dt = ", dt);
      if (dt == 0) break;
      deg[i] = dt % m;
      last = l;
    }
    debug stderr.writeln (deg);
    auto cum = new uint[32];
    cum[0] = 0;
    foreach (i; 1 .. 32) {
      cum[i] = cum[i-1] + deg[i];
    }
    debug stderr.writeln ("cum = ", cum);
    auto u = new uint[32];
    u[0] = 1;
    uint res;
    while (u.any!("a != 0")) {
      auto e = new uint[32];
      foreach (i; 0 .. 32) {
        foreach (j; i + 1 .. 32) {
          e[j] = add (e[j], mul (u[i], deg[j]));
        }
      }
      debug stderr.writeln ("e = ", e);
      u = e;
      foreach (i; u) {
        res = add (res, i);
      }
    }
    writeln (res);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. scan!int){
        long d = scan!long, m = scan!long;
        long u = 1;
        long ans = 0;
        long tmp = 1;
        int i = 0;
        d += 1;
        while(u <= d){
            tmp *= primes[i], tmp %= m;
            ans += tmp * u, ans %= m;
            i += 1;
            u *= 2;
        }
        ans += m - tmp * (u - d) % m, ans %= m;
        tmp *= primes[i], tmp %= m;
        ans.print;
    }

}

long[] primes = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
    53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127,
    131, 137, 139, 149, 151, 157, 163, 167, 173];


Try guessing the statement from this picture:   You are given a non-negative integer $$$d$$$. You have to find two non-negative real numbers $$$a$$$ and $$$b$$$ such that $$$a + b = d$$$ and $$$a \cdot b = d$$$.

The first line contains $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. Each test case contains one integer $$$d$$$ $$$(0 \le d \le 10^3)$$$.

For each test print one line. If there is an answer for the $$$i$$$-th test, print "Y", and then the numbers $$$a$$$ and $$$b$$$. If there is no answer for the $$$i$$$-th test, print "N". Your answer will be considered correct if $$$|(a + b) - a \cdot b| \le 10^{-6}$$$ and $$$|(a + b) - d| \le 10^{-6}$$$.

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

void main() {
    auto N = readln.chomp.to!long;
    while (N--) solve;
}

void solve() {
    long d = readln.chomp.to!long;

    if (d * d - 4 * d < 0) {
        writeln("N");
        return;
    }

    real D = (d * d - 4 * d).to!real.sqrt;
    real a = (d + D) / 2;
    real b = (d - D) / 2;
    writefln("Y %.10f %.10f", a, b);
}


After being discouraged by 13 time-limit-exceeded verdicts on an ugly geometry problem, you decided to take a relaxing break for arts and crafts.There is a piece of paper in the shape of a simple polygon with $$$n$$$ vertices. The polygon may be non-convex, but we all know that proper origami paper has the property that any horizontal line intersects the boundary of the polygon in at most two points.If you fold the paper along the vertical line $$$x=f$$$, what will be the area of the resulting shape? When you fold, the part of the paper to the left of the line is symmetrically reflected on the right side.  Your task is to answer $$$q$$$ independent queries for values $$$f_1,\ldots,f_q$$$.

The first line contains two integers $$$n$$$, $$$q$$$ ($$$3\le n\le 10^5, 1\le q\le 10^5$$$)  — the number of polygon vertices and queries, respectively. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$|x_i|, |y_i|\le 10^5$$$)  — the coordinates of the $$$i$$$-th point of the polygon. The polygon has an edge connecting each pair of adjacent points in the input, and also an edge between $$$(x_1,y_1)$$$ and $$$(x_n,y_n)$$$. It is guaranteed that the polygon is non-degenerate and that any horizontal line intersects the boundary of the polygon in at most two points. In particular, no boundary edge is strictly horizontal. Two adjacent sides may be collinear. Each of the next $$$q$$$ lines contains a single integer $$$f_i$$$ ($$$\min\limits_{j=1}^n(x_j)< f_i< \max\limits_{j=1}^n(x_j)$$$)  — the $$$x$$$-coordinate of the $$$i$$$-th fold query. It is guaranteed that all $$$f_i$$$ are distinct.

For each query, output the area $$$A_i$$$ of the paper if you fold it along the line $$$x=f_i$$$. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-4}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-4}$$$.

NoteThe first test, with the fold $$$f=-5$$$:  The second test, with the fold $$$f=1$$$:  The third test, with the fold $$$f=-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)); }

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const Q = readInt();
      auto X = new int[N];
      auto Y = new int[N];
      foreach (i; 0 .. N) {
        X[i] = readInt();
        Y[i] = readInt();
      }
      auto F = new int[Q];
      foreach (q; 0 .. Q) {
        F[q] = readInt();
      }

      Y[] -= Y.minElement;
      const maxY = Y.maxElement;

      auto xss = new real[][maxY + 1];
      foreach (i; 0 .. N) {
        int x0 = X[i], y0 = Y[i];
        int x1 = X[(i + 1) % N], y1 = Y[(i + 1) % N];
        if (y0 > y1) {
          swap(x0, x1);
          swap(y0, y1);
        }
        foreach (y; y0 .. y1 + 1) {
          // x0 + ((y - y0) / (y1 - y0)) (x1 - x0)
          xss[y] ~= x0 + 1.0L * (y - y0) / (y1 - y0) * (x1 - x0);
        }
      }
      foreach (y; 0 .. maxY + 1) {
        xss[y] = xss[y].sort.uniq.array;
        debug {
          writefln("xss[%s] = %s", y, xss[y]);
        }
        assert(xss[y].length == ((y == 0 || y == maxY) ? 1 : 2));
      }

      auto xs = new real[3 * (maxY + 1)];
      foreach (y; 0 .. maxY + 1) {
        if (y == 0 || y == maxY) {
          xss[y] ~= xss[y][0];
        }
        xss[y] = [xss[y][0], (xss[y][0] + xss[y][1]) / 2.0L, xss[y][1]];
        foreach (j; 0 .. 3) {
          xs[y * 3 + j] = xss[y][j];
        }
      }
      xs = xs.sort.uniq.array;
      const xsLen = cast(int)(xs.length) - 1;
      debug {
        writeln("xs = ", xs);
      }

      real total = 0.0L;
      auto fs = new real[xsLen + 1];
      auto gs = new real[xsLen + 1];
      fs[] = 0.0L;
      gs[] = 0.0L;
      foreach (y; 0 .. maxY) {
        total += ((xss[y][2] - xss[y][0]) + (xss[y + 1][2] - xss[y + 1][0])) / 2.0L;
        foreach (j; 0 .. 3) {
          real x0 = xss[y][j];
          real x1 = xss[y + 1][j];
          if (x0 > x1) {
            swap(x0, x1);
          }
          const coef = [-1.0L, +2.0L, -1.0L][j];
          if (x0 == x1) {
            fs[xs.lowerBound(x0)] += coef;
          } else {
            gs[xs.lowerBound(x0)] += coef / (x1 - x0);
            gs[xs.lowerBound(x1)] -= coef / (x1 - x0);
          }
        }
      }
      debug {
        writeln("fs = ", fs);
        writeln("gs = ", gs);
      }

      auto ans = new real[Q];
      auto qss = new int[][xsLen];
      foreach (q; 0 .. Q) {
        qss[xs.upperBound(F[q]) - 1] ~= q;
      }
      real now0 = total, now1 = 0.0L, now2 = 0.0L;
      foreach (e; 0 .. xsLen) {
        now1 += fs[e];
        now2 += gs[e];
        foreach (q; qss[e]) {
          const dx = F[q] - xs[e];
          ans[q] = now0 + (now1 + now2 * dx / 2.0L) * dx;
        }
        {
          const dx = xs[e + 1] - xs[e];
          now0 += (now1 + now2 * dx / 2.0L) * dx;
          now1 += now2 * dx;
        }
      }

      foreach (q; 0 .. Q) {
        writefln("%.12f", ans[q]);
      }
    }
  } catch (EOFException e) {
  }
}


Long ago, you thought of two finite arithmetic progressions $$$A$$$ and $$$B$$$. Then you found out another sequence $$$C$$$ containing all elements common to both $$$A$$$ and $$$B$$$. It is not hard to see that $$$C$$$ is also a finite arithmetic progression. After many years, you forgot what $$$A$$$ was but remember $$$B$$$ and $$$C$$$. You are, for some reason, determined to find this lost arithmetic progression. Before you begin this eternal search, you want to know how many different finite arithmetic progressions exist which can be your lost progression $$$A$$$. Two arithmetic progressions are considered different if they differ in their first term, common difference or number of terms.It may be possible that there are infinitely many such progressions, in which case you won't even try to look for them! Print $$$-1$$$ in all such cases. Even if there are finite number of them, the answer might be very large. So, you are only interested to find the answer modulo $$$10^9+7$$$.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 100$$$) denoting the number of testcases. The first line of each testcase contains three integers $$$b$$$, $$$q$$$ and $$$y$$$ ($$$-10^9\leq b\leq 10^9$$$, $$$1\leq q\leq 10^9$$$, $$$2\leq y\leq 10^9$$$) denoting the first term, common difference and number of terms of $$$B$$$ respectively. The second line of each testcase contains three integers $$$c$$$, $$$r$$$ and $$$z$$$ ($$$-10^9\leq c\leq 10^9$$$, $$$1\leq r\leq 10^9$$$, $$$2\leq z\leq 10^9$$$) denoting the first term, common difference and number of terms of $$$C$$$ respectively.

For each testcase, print a single line containing a single integer. If there are infinitely many finite arithmetic progressions which could be your lost progression $$$A$$$, print $$$-1$$$. Otherwise, print the number of finite arithmetic progressions which could be your lost progression $$$A$$$ modulo $$$10^9+7$$$. In particular, if there are no such finite arithmetic progressions, print $$$0$$$.

// cheese-cracker [2022-05-03]

const long MOD = 1_000_000_007;

void solve(){
    long b = scan; long q = scan;
    long y = scan;

    long c = scan;
    long r = scan;
    long z = scan;

    long lo = c - b;
    long B = b + q*(y-1);
    long C = c + r*(z-1);
    long remb = ((b % q) + q) % q;
    long remc = ((c % q) + q) % q;

    /* show(B, C, B-C); */
    if(r % q != 0 || B < C || lo < 0 || remc != remb){
        writeln(0);
    }else if(lo < r || B < C + r){
        writeln(-1);
    }else{
        long res = 0;
        for(long div = 1; div * div <= q; ++div){
            if(q % div == 0){
                long p  = div * (r / q);
                if(p / gcd(p, q) == r / q){
                    res += (r / p) * (r / p) % MOD;
                    res %= MOD;
                }
                if(div * div != q){
                    p = r / div;
                    if(p / gcd(p, q) == r / q){
                        res += (r / p) * (r / p) % MOD;
                        res %= MOD;
                    }
                }
            }
        }
        writeln(res);
    }
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

void main() {
    auto T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    long b, q, y; readf("%d %d %d\n", &b, &q, &y);
    long c, r, z; readf("%d %d %d\n", &c, &r, &z);

    bool check_invalid() {
        if ( (c - b) % q != 0 ) return true; // invalid
        if (r % q != 0) return true;
        if (c - b < 0) return true;
        if (c + r * (z - 1) - b > q * (y - 1)) return true;
        return false;
    }

    bool check_infinite() {
        if (c - r < b) return true;
        if (c + r * z > b + q * (y - 1)) return true;
        return false;
    }

    if (check_invalid()) {
        writeln(0);
    } else if (check_infinite()) {
        writeln(-1);
    } else {
        long ans = 0;
        auto ms = divisors(q);
        foreach (m; ms) {
            long p = r / q * m;
            if (lcm(p, q) != r) continue;
            long s = r / p;
            ans += s * s;
            ans %= mod;
            //writefln("(%s, %s) -> %s", p, q, s);
        }
        writeln(ans);
    }
}

long[] divisors(long x) {
    long[] ret;
    for (long k = 1; k * k <= x; k++) {
        if (x % k == 0) {
            ret ~= k;
            ret ~= x / k;
        }
    }
    return ret.sort.uniq.array;
}
long lcm(long a, long b) {
    return a / gcd(a, b) * b;
}

enum long mod = cast(long)(1e9+7);

// cheese-cracker [2022-05-03]

const long MOD = 1_000_000_007;

void solve(){
    long b = scan; long q = scan;
    long y = scan;

    long c = scan;
    long r = scan;
    long z = scan;

    long lo = c - b;
    long B = b + q*y;
    long C = c + r*z;
    long remb = ((b % q) + q) % q;
    long remc = ((c % q) + q) % q;

    /* show(B, C, B-C); */
    if(r % q != 0 || B < C || lo < 0 || remc != remb){
        writeln(0);
    }else if(lo < r || B < C + r){
        writeln(-1);
    }else{
        long res = 0;
        for(long div = 1; div * div <= q; ++div){
            if(q % div == 0){
                long p  = div * (r / q);
                if(p * q == r * gcd(p, q)){
                    res += (r / p) * (r / p) % MOD;
                    res %= MOD;
                }
                if(div * div != q){
                    p = (q/div) * (r/q);
                    if(p * q == r * gcd(p, q)){
                        res += (r / p) * (r / p) % MOD;
                        res %= MOD;
                    }
                }
            }
        }
        writeln(res);
    }
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

// cheese-cracker [2022-05-03]

const long MOD = 1_000_000_007;

ll modexp(ll base, ll exp){
    ll x = base % MOD;
    ll y = exp;
    ll res = 1;
    while(y > 0){
        if(y & 1){
            res *= x; res %= MOD;
        }
        x *= x; x %= MOD;
        y >>= 1;
    }
    return res;
}

// Modulo Inverse
ll modinv(ll num){ return modexp(num, MOD-2); }

long[] primes;
void prime_sieve(){
    size_t sz =100_000;
    auto isPrime = new bool[](sz + 1);
    isPrime[] = 1;
    foreach(p; 2..10_000){
        if(isPrime[p]){
            for(int divi = p*p; divi <= sz; divi += p){ isPrime[divi] = 0; }
        }
    }
    primes = isPrime[2..$].enumerate.filter!(a => a[1]).map!(a => (a[0] + 2).to!(long)).array;
}

void solve(){
    long b = scan;
    long q = scan;
    long y = scan;

    long c = scan;
    long r = scan;
    long z = scan;

    long lo = c - b;
    long B = b + q*y;
    long C = c + r*z;
    long remb = ((b % q) + q) % q;
    long remc = ((c % q) + q) % q;

    if(r % q != 0 || B < C || lo < 0 || remc != remb){
        writeln(0);
    }else if(lo < r || B < C + r){
        writeln(-1);
    }else{
        long num = q;
        long res = 1;
        foreach(p; primes){
            long cnt = 1;
            while(num % p == 0){
                num /= p;
                ++cnt;
            }
            res *= ((modexp(p*p, cnt) - 1) + MOD) % MOD;
            res %= MOD;
            res *= modinv(p*p - 1);
            res %=  MOD;
        }
        if(num != 1){
            long p = num;
            res *= (1 + p*p) % MOD;
            res %= MOD;
        }
        writeln(res);
    }
}

void main(){
    prime_sieve;
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long;

// cheese-cracker [2022-05-03]

const long MOD = 1_000_000_007;

ll modexp(ll base, ll exp){
    ll x = base % MOD;
    ll y = exp;
    ll res = 1;
    while(y > 0){
        if(y & 1){
            res *= x; res %= MOD;
        }
        x *= x; x %= MOD;
        y >>= 1;
    }
    return res;
}

// Modulo Inverse
ll modinv(ll num){ return modexp(num, MOD-2); }

long[] primes;
void prime_sieve(){
    size_t sz =100_000;
    auto isPrime = new bool[](sz + 1);
    isPrime[] = 1;
    foreach(p; 2..10_000){
        if(isPrime[p]){
            for(int divi = p*p; divi <= sz; divi += p){ isPrime[divi] = 0; }
        }
    }
    primes = isPrime[2..$].enumerate.filter!(a => a[1]).map!(a => (a[0] + 2).to!(long)).array;
}

void solve(){
    long b = scan;
    long q = scan;
    long y = scan;

    long c = scan;
    long r = scan;
    long z = scan;

    long lo = c - b;
    long hi = (b + q*y) - (c + r*z);
    long remb = ((b % q) + q) % q;
    long remc = ((c % q) + q) % q;

    if(r % q != 0 || hi < 0 || lo < 0 || remc != remb){
        writeln(0);
    }else if(lo < r || hi < r){
        writeln(-1);
    }else{
        long num = q;
        long res = 1;
        foreach(p; primes){
            long cnt = 1;
            while(num % p == 0){
                num /= p;
                ++cnt;
            }
            res *= ((modexp(p*p, cnt) - 1) + MOD) % MOD;
            res %= MOD;
            res *= modinv(p*p - 1);
            res %=  MOD;
        }
        if(num != 1){
            long p = num;
            res *= (1 + p*p) % MOD;
            res %= MOD;
        }
        writeln(res);
    }
}

void main(){
    prime_sieve;
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long;

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

void main() {
    auto T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    long b, q, y; readf("%d %d %d\n", &b, &q, &y);
    long c, r, z; readf("%d %d %d\n", &c, &r, &z);

    bool check_invalid() {
        if ( (c - b) % q != 0 ) return true; // invalid
        if (r % q != 0) return true;
        if (c - b < 0) return true;
        if (c + r * (z - 1) - b > q * (y - 1)) return true;
        return false;
    }

    bool check_infinite() {
        if (c - r < b) return true;
        if (c + r * z > b + q * (y - 1)) return true;
        return false;
    }

    if (check_invalid()) {
        writeln(0);
    } else if (check_infinite()) {
        writeln(-1);
    } else {
        long ans = 0;
        auto ms = divisors(q);
        foreach (m; ms) {
            long p = r / q * m;
            long s = r / p;
            ans += s * s;
            ans %= mod;
        }
        writeln(ans);
    }
}

long[] divisors(long x) {
    long[] ret;
    for (long k = 1; k * k <= x; k++) {
        if (x % k == 0) {
            ret ~= k;
            ret ~= x / k;
        }
    }
    return ret.sort.uniq.array;
}

enum long mod = cast(long)(1e9+7);


You have two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. You would like to make all the elements of both strings equal to $$$0$$$. Unfortunately, you can modify the contents of these strings using only the following operation:  You choose two indices $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$);  For every $$$i$$$ that respects $$$l \le i \le r$$$, change $$$a_i$$$ to the opposite. That is, $$$a_i := 1 - a_i$$$;  For every $$$i$$$ that respects either $$$1 \le i < l$$$ or $$$r < i \le n$$$, change $$$b_i$$$ to the opposite. That is, $$$b_i := 1 - b_i$$$. Your task is to determine if this is possible, and if it is, to find such an appropriate chain of operations. The number of operations should not exceed $$$n + 5$$$. It can be proven that if such chain of operations exists, one exists with at most $$$n + 5$$$ operations.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of the strings. The second line of each test case contains a binary string $$$a$$$, consisting only of characters 0 and 1, of length $$$n$$$. The third line of each test case contains a binary string $$$b$$$, consisting only of characters 0 and 1, of length $$$n$$$. It is guaranteed that sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print first "YES" if it's possible to make all the elements of both strings equal to $$$0$$$. Otherwise, print "NO". If the answer is "YES", on the next line print a single integer $$$k$$$ ($$$0 \le k \le n + 5$$$) — the number of operations. Then $$$k$$$ lines follows, each contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the description of the operation. If there are several correct answers, print any of them.

YES
1
2 2
NO
NO
YES
2
1 2
2 2
YES
2
1 1
2 3

NoteIn the first test case, we can perform one operation with $$$l = 2$$$ and $$$r = 2$$$. So $$$a_2 := 1 - 1 = 0$$$ and string $$$a$$$ became equal to 000. $$$b_1 := 1 - 1 = 0$$$, $$$b_3 := 1 - 1 = 0$$$ and string $$$b$$$ became equal to 000.In the second and in the third test cases, it can be proven that it's impossible to make all elements of both strings equal to $$$0$$$.In the fourth test case, we can perform an operation with $$$l = 1$$$ and $$$r = 2$$$, then string $$$a$$$ became equal to 01, and string $$$b$$$ doesn't change. Then we perform an operation with $$$l = 2$$$ and $$$r = 2$$$, then $$$a_2 := 1 - 1 = 0$$$ and $$$b_1 = 1 - 1 = 0$$$. So both of string $$$a$$$ and $$$b$$$ became equal to 00.In the fifth test case, we can perform an operation with $$$l = 1$$$ and $$$r = 1$$$. Then string $$$a$$$ became equal to 011 and string $$$b$$$ became equal to 100. Then we can perform an operation with $$$l = 2$$$ and $$$r = 3$$$, so both of string $$$a$$$ and $$$b$$$ became equal to 000.

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.strip.splitter("").map!(to!int).array;
    auto b = readln.strip.splitter("").map!(to!int).array;
    auto cnt1 = a.count(1);
    Tuple!(int, int)[] ans;
    foreach (i ; 0 .. n) {
      if (a[i] == 1) {
        ans ~= tuple(i + 1, i + 1);
      }
      b[i] ^= (cnt1 % 2) ^ a[i];
    }
    auto cnt1b = b.count(1);
    if (cnt1b == 0) {
      writeln("YES");
    } else if (cnt1b == b.length) {
      writeln("YES");
      ans ~= tuple(1, n);
      ans ~= tuple(1, 1);
      ans ~= tuple(2, n);
    } else {
      writeln("NO");
      continue;
    }
    writeln(ans.length);
    foreach (x ; ans) {
      writefln("%d %d", x[0], x[1]);
    }
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.strip.map !(q{a - '0'}).array;
		auto b = readln.strip.map !(q{a - '0'}).array;
		int [] [] answer;
		if (a != b)
		{
			answer ~= [0, n];
			a[] = 1 - a[];
		}
		if (a != b)
		{
			writeln ("NO");
			continue;
		}
		writeln ("YES");
		int k = 0;
		foreach (i; 0..n)
		{
			if (a[i])
			{
				answer ~= [i, i + 1];
				k += 1;
			}
		}
		if ((k - 1) % 2 == 0)
		{
			answer ~= [0, n];
			answer ~= [0, 1];
			answer ~= [1, n];
		}
		writeln (answer.length);
		foreach (ref line; answer)
		{
			writeln (line[0] + 1, " ", line[1]);
		}
	}
}


Find the minimum area of a square land on which you can place two identical rectangular $$$a \times b$$$ houses. The sides of the houses should be parallel to the sides of the desired square land.Formally,   You are given two identical rectangles with side lengths $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 100$$$) — positive integers (you are given just the sizes, but not their positions).  Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square. Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding.    The picture shows a square that contains red and green rectangles.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) —the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$a$$$, $$$b$$$ ($$$1 \le a, b \le 100$$$) — side lengths of the rectangles.

Print $$$t$$$ answers to the test cases. Each answer must be a single integer — minimal area of square land, that contains two rectangles with dimensions $$$a \times b$$$.

NoteBelow are the answers for the first two test cases:

import std.stdio;
import std.algorithm : max, min;

void main()
{
  int t;
  readf!"%d\n"(t);

  foreach (i; 0..t) {
    int a, b;
    readf!"%d %d\n"(a, b);
    auto c = min(max(2*a, b), max(2*b, a));
    writeln(c*c);
  }
}

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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long a, b;

  void solve(long tc = -1)
  {
    if (a > b)
      swap(a, b);
    writeln(max(2 * a, b) * max(2 * a, b));
  }
}

struct Interval
{
  long l, h;

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

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

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

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

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		ans[ti] = max(min(a, b)*2, max(a, b))^^2;
	}

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


On a circle lie $$$2n$$$ distinct points, with the following property: however you choose $$$3$$$ chords that connect $$$3$$$ disjoint pairs of points, no point strictly inside the circle belongs to all $$$3$$$ chords. The points are numbered $$$1, \, 2, \, \dots, \, 2n$$$ in clockwise order.Initially, $$$k$$$ chords connect $$$k$$$ pairs of points, in such a way that all the $$$2k$$$ endpoints of these chords are distinct.You want to draw $$$n - k$$$ additional chords that connect the remaining $$$2(n - k)$$$ points (each point must be an endpoint of exactly one chord).In the end, let $$$x$$$ be the total number of intersections among all $$$n$$$ chords. Compute the maximum value that $$$x$$$ can attain if you choose the $$$n - k$$$ chords optimally.Note that the exact position of the $$$2n$$$ points is not relevant, as long as the property stated in the first paragraph holds.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le n$$$) — half the number of points and the number of chords initially drawn. Then $$$k$$$ lines follow. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, \, y_i \le 2n$$$, $$$x_i \ne y_i$$$) — the endpoints of the $$$i$$$-th chord. It is guaranteed that the $$$2k$$$ numbers $$$x_1, \, y_1, \, x_2, \, y_2, \, \dots, \, x_k, \, y_k$$$ are all distinct.

For each test case, output the maximum number of intersections that can be obtained by drawing $$$n - k$$$ additional chords.

NoteIn the first test case, there are three ways to draw the $$$2$$$ additional chords, shown below (black chords are the ones initially drawn, while red chords are the new ones):  We see that the third way gives the maximum number of intersections, namely $$$4$$$.In the second test case, there are no more chords to draw. Of course, with only one chord present there are no intersections.In the third test case, we can make at most one intersection by drawing chords $$$1-3$$$ and $$$2-4$$$, as shown below:

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto x = new int[](k);
		auto y = new int[](k);
		auto used = new bool[](n*2);
		foreach (i; 0..k)
		{
			x[i] = RD!int-1;
			y[i] = RD!int-1;
			used[x[i]] = true;
			used[y[i]] = true;
		}

		int[] arr;
		foreach (i; 0..n*2)
		{
			if (used[i]) continue;
			arr ~= i;
		}
		foreach (i; 0..n-k)
		{
			x ~= arr[i];
			y ~= arr[n-k+i];
		}
		foreach (i; 0..n)
		{
			foreach (j; i+1..n)
			{
				int[][] tmp = [[x[i], 0], [y[i], 0], [x[j], 1], [y[j], 1]];
				tmp.sort!"a[0] < b[0]";
				if (tmp[0][1] != tmp[1][1] && tmp[1][1] != tmp[2][1])
					++ans[ti];
			}
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto m = n * 2;
		auto p = new int [2] [n];
		auto used = new bool [m];
		foreach (int i, ref c; p[0..k])
		{
			c = readln.splitter.map !(to !(int)).array;
			c[] -= 1;
			foreach (ref x; c)
			{
				used[x] = true;
			}
		}

		int cur = 0;
		foreach (z; 0..2)
		{
			foreach (i; k..n)
			{
				while (used[cur])
				{
					cur += 1;
				}
				used[cur] = true;
				p[i][z] = cur;
			}
		}

		foreach (i; 0..n)
		{
			sort (p[i][]);
		}
		sort (p);
		debug {writeln (p);}

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

		writeln (res);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const K = readInt();
        auto X = new int[K];
        auto Y = new int[K];
        foreach (k; 0 .. K) {
          X[k] = readInt() - 1;
          Y[k] = readInt() - 1;
          if (X[k] > Y[k]) {
            swap(X[k], Y[k]);
          }
        }

        auto used = new bool[2 * N];
        foreach (k; 0 .. K) {
          used[X[k]] = true;
          used[Y[k]] = true;
        }
        auto xs = X.dup, ys = Y.dup;
        foreach (u; 0 .. 2 * N) {
          if (!used[u]) {
            ((xs.length < N) ? xs : ys) ~= u;
          }
        }

        int ans;
        foreach (i; 0 .. N) foreach (j; 0 .. N) {
          if (xs[i] < xs[j] && xs[j] < ys[i] && ys[i] < ys[j]) {
            ++ans;
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


Polycarp is an organizer of a Berland ICPC regional event. There are $$$n$$$ universities in Berland numbered from $$$1$$$ to $$$n$$$. Polycarp knows all competitive programmers in the region. There are $$$n$$$ students: the $$$i$$$-th student is enrolled at a university $$$u_i$$$ and has a programming skill $$$s_i$$$.Polycarp has to decide on the rules now. In particular, the number of members in the team.Polycarp knows that if he chooses the size of the team to be some integer $$$k$$$, each university will send their $$$k$$$ strongest (with the highest programming skill $$$s$$$) students in the first team, the next $$$k$$$ strongest students in the second team and so on. If there are fewer than $$$k$$$ students left, then the team can't be formed. Note that there might be universities that send zero teams.The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is $$$0$$$.Help Polycarp to find the strength of the region for each choice of $$$k$$$ from $$$1$$$ to $$$n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of universities and the number of students. The second line of each testcase contains $$$n$$$ integers $$$u_1, u_2, \dots, u_n$$$ ($$$1 \le u_i \le n$$$) — the university the $$$i$$$-th student is enrolled at. The third line of each testcase contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 10^9$$$) — the programming skill of the $$$i$$$-th student. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print $$$n$$$ integers: the strength of the region — the total skill of the members of the present teams — for each choice of team size $$$k$$$.

// Vicfred
// https://codeforces.com/contest/1519/problem/C
// data structures, sorting
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.stdio;
import std.string;

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

while(t--) {
    int n = readln.chomp.to!int;
    long[] u = readln.split.map!(to!long).array;
    long[] s = readln.split.map!(to!long).array;

    long[][] universities = new long[][](n);

    for(int i = 0; i < n; ++i) {
        u[i] -= 1;
    }

    for(int i = 0; i < n; ++i) {
        universities[cast(uint)u[i]] ~= s[i];
    }

    for(int i = 0; i < n; ++i) {
        universities[i].sort;
        universities[i].reverse;
    }

    long[][] cumulative = new long[][](n + 1,1);

    for(int i = 0; i < n; i++) {
        foreach(x; universities[i]) {
            cumulative[i] ~= (cumulative[i][$- 1] + x);
        }
    }

    long[] ans = new long[n];
    for(int i = 0; i < n; ++i) {
        for(int k = 1; k <= universities[i].length; k++) {
            ans[k - 1] += cumulative[i][universities[i].length/k*k];
        }
    }
    for(int i = 0; i < n; ++i)
        writef("%s ", ans[i]);
    "".writeln;
}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto list = new long[][](n);
		foreach (i; 0..n)
		{
			list[u[i]] ~= s[i];
		}
		foreach (i; 0..n)
		{
			list[i].sort!"a > b";
		}
		foreach (i; 0..n)
		{
			foreach (j; 1..list[i].length)
			{
				list[i][j] += list[i][j-1];
			}
		}
		debug writeln(list);

		ans[ti].length = n;
		foreach (i; 0..n)
		{
			foreach (j; 0..list[i].length)
			{
				auto rem = list[i].length % (j+1);
				ans[ti][j] += list[i][$-1-rem];
			}
		}
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}

// Vicfred
// https://codeforces.com/contest/1519/problem/C
// data structures, sorting
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.stdio;
import std.string;

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

while(t--) {
    int n = readln.chomp.to!int;
    long[] u = readln.split.map!(to!long).array;
    long[] s = readln.split.map!(to!long).array;

    long[][] universities = new long[][](n);

    for(int i = 0; i < n; ++i) {
        u[i] -= 1;
    }

    for(int i = 0; i < n; ++i) {
        universities[cast(uint)u[i]] ~= s[i];
    }

    for(int i = 0; i < n; ++i) {
        universities[i].sort;
        universities[i].reverse;
    }

    long[][] cumulative = new long[][](n + 1,1);

    for(int i = 0; i < n; i++) {
        foreach(x; universities[i]) {
            cumulative[i] ~= (cumulative[i][$- 1] + x);
        }
    }

    int[] ans = new int[n];
    for(int i = 0; i < n; ++i) {
        for(int k = 1; k <= universities[i].length; k++) {
            ans[k - 1] += cumulative[i][universities[i].length/k*k];
        }
    }
    for(int i = 0; i < n; ++i)
        writef("%s ", ans[i]);
    "".writeln;
}
}

// Vicfred
// https://codeforces.com/contest/1519/problem/C
// data structures, sorting
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.stdio;
import std.string;

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

while(t--) {
    int n = readln.chomp.to!int;
    int[] u = readln.split.map!(to!int).array;
    int[] s = readln.split.map!(to!int).array;

    int[][] universities = new int[][](n);

    for(int i = 0; i < n; ++i) {
        u[i] -= 1;
    }

    for(int i = 0; i < n; ++i) {
        universities[u[i]] ~= s[i];
    }

    for(int i = 0; i < n; ++i) {
        universities[i].sort;
        universities[i].reverse;
    }

    long[][] cumulative = new long[][](n + 1,1);

    for(int i = 0; i < n; i++) {
        foreach(x; universities[i]) {
            cumulative[i] ~= (cumulative[i][$- 1] + x);
        }
    }

    int[] ans = new int[n];
    for(int i = 0; i < n; ++i) {
        for(int k = 1; k <= universities[i].length; k++) {
            ans[k - 1] += cumulative[i][universities[i].length/k*k];
        }
    }
    for(int i = 0; i < n; ++i)
        writef("%s ", ans[i]);
    "".writeln;
}
}

// Vicfred
// https://codeforces.com/contest/1519/problem/C
// data structures, sorting
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.stdio;
import std.string;

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

while(t--) {
    int n = readln.chomp.to!int;
    int[] u = readln.split.map!(to!int).array;
    int[] s = readln.split.map!(to!int).array;

    int[][] universities = new int[][](n);

    for(int i = 0; i < n; ++i) {
        u[i] -= 1;
    }

    for(int i = 0; i < n; ++i) {
        universities[u[i]] ~= s[i];
    }

    for(int i = 0; i < n; ++i) {
        universities[i].sort;
        universities[i].reverse;
    }

    int[][] cumulative = new int[][](n + 1,1);

    for(int i = 0; i < n; i++) {
        foreach(x; universities[i]) {
            cumulative[i] ~= (cumulative[i][$- 1] + x);
        }
    }

    int[] ans = new int[n];
    for(int i = 0; i < n; ++i) {
        for(int k = 1; k <= universities[i].length; k++) {
            ans[k - 1] += cumulative[i][universities[i].length/k*k];
        }
    }
    for(int i = 0; i < n; ++i)
        writef("%s ", ans[i]);
    "".writeln;
}
}


Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number  on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7).

The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109).

Print a single number — the answer to the problem modulo 1000000007 (109 + 7).

NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1.

import std.stdio;
import std.algorithm;
import std.container;

const int MAX = 100005;
const int MOD = 1000000007;
int n;
long x;
long[MAX] a;
long[long] count;

void main() {
    readf(" %s %s", n, x);
    foreach(i; 0..n) readf(" %s", a[i]);

    long totalSum = sum(a[0..n]);
    foreach(i; 0..n) a[i] = totalSum - a[i];
    foreach(i; 0..n) count[a[i]]++;
    auto heap = heapify!"a > b"(count.keys);

    long result = 0;
    do {
        auto value = heap.front;
        heap.popFront();

        auto y = count[value];
        auto k = 0;
        while (y % x == 0) {
            y /= x;
            k++;
        }

        if (k == 0) {
            result = value;
            break;
        }

        auto next = value + k;
        if (next !in count) {
            heap.insert(next);
        }
        count[next] += y;
    } while(!heap.empty);

    writeln(power(min(result, totalSum)));
}

long power(long m) {
    if (m == 0) return 1;
    if (m == 1) return x % MOD;
    auto v = power(m/2);
    if (m % 2 == 0) {
        return (v * v) % MOD;
    } else {
        return (((v * v) % MOD) * x) % MOD;
    }
}

import std.stdio;
import std.algorithm;
import std.container;

const int MAX = 100005;
const int MOD = 1000000007;
int n;
long x;
long[MAX] a;
long[long] pow;

void main() {
    readf(" %s %s", n, x);
    foreach(i; 0..n) readf(" %s", a[i]);

    initPowers();

    long totalSum = sum(a[0..n]);
    foreach(i; 0..n) a[i] = totalSum - a[i];
    auto heap = heapify!"a > b"(a[0..n]);

    long result = 0;
    while (!heap.empty) {
        auto value = heap.front;
        heap.popFront();
        result = value;

        auto count = 1;
        while (!heap.empty && heap.front == value) {
            heap.popFront();
            count++;
        }
        if (count == 1) {
            break;
        }
        if (count in pow) {
            heap.insert(pow[count] + result);
        }
    }

    writeln(calc(min(result, totalSum)));
}

long calc(long m) {
    if (m == 0) return 1;
    if (m == 1) return x % MOD;
    auto v = calc(m/2);
    if (m % 2 == 0) {
        return (v * v) % MOD;
    } else {
        return (((v * v) % MOD) * x) % MOD;
    }
}

void initPowers() {
    foreach(y; x..n+1) {
        auto k = y;
        while (k >= x && k % x == 0) {
           pow[y]++;
           k /= x;
        }
    }
}

import std.stdio;
import std.algorithm;
import std.container;

const int MAX = 100005;
const int MOD = 1000000007;
int n;
long x;
long[MAX] a;
long[long] pow;

void main() {
    readf(" %s %s", n, x);
    foreach(i; 0..n) readf(" %s", a[i]);

    initPowers();

    long totalSum = sum(a[0..n]);
    foreach(i; 0..n) a[i] = totalSum - a[i];
    auto heap = heapify!"a > b"(a[0..n]);

    long result = 0;
    while (!heap.empty) {
        auto value = heap.front;
        heap.popFront();
        result = value;

        auto count = 1;
        while (!heap.empty && heap.front == value) {
            heap.popFront();
            count++;
        }
        if (count !in pow) {
            break;
        }
        heap.insert(pow[count] + result);
    }

    writeln(calc(min(result, totalSum)));
}

long calc(long m) {
    if (m == 0) return 1;
    if (m == 1) return x % MOD;
    auto v = calc(m/2);
    if (m % 2 == 0) {
        return (v * v) % MOD;
    } else {
        return (((v * v) % MOD) * x) % MOD;
    }
}

void initPowers() {
    foreach(y; x..n+1) {
        auto k = y;
        while (k >= x && k % x == 0) {
           pow[y]++;
           k /= x;
        }
    }
}

import std.stdio;
import std.algorithm;
import std.container;

const int MAX = 100005;
const int MOD = 1000000007;
int n;
long x;
long[MAX] a;
long[long] pow;

void main() {
    readf(" %s %s", n, x);
    foreach(i; 0..n) readf(" %s", a[i]);

    initPowers();

    long totalSum = sum(a[0..n]);
    foreach(i; 0..n) a[i] = totalSum - a[i];
    auto heap = heapify!"a > b"(a[0..n]);

    long result = 0;
    while (!heap.empty) {
        auto value = heap.front;
        heap.popFront();
        result = value;

        auto count = 1;
        while (!heap.empty && heap.front == value) {
            heap.popFront();
            count++;
        }
        if (count == 1) {
            break;
        }
        if (count in pow) {
            heap.insert(pow[count] + result);
        }
    }

    writeln(calc(result));
}

long calc(long m) {
    if (m == 0) return 1;
    if (m == 1) return x % MOD;
    auto v = calc(m/2);
    if (m % 2 == 0) {
        return (v * v) % MOD;
    } else {
        return (((v * v) % MOD) * x) % MOD;
    }
}

void initPowers() {
    foreach(y; x..n+1) {
        auto k = y;
        while (k > x && k % x == 0) {
           pow[y]++;
           k /= x;
        }
    }
}

import std.stdio;
import std.algorithm;
import std.container;

const int MAX = 100005;
const int MOD = 1000000007;
int n;
long x;
long[MAX] a;
long[long] pow;

void main() {
    readf(" %s %s", n, x);
    foreach(i; 0..n) readf(" %s", a[i]);

    initPowers();

    long totalSum = sum(a[0..n]);
    foreach(i; 0..n) a[i] = totalSum - a[i];
    auto heap = heapify!"a > b"(a[0..n]);

    long result = 0;
    while (!heap.empty) {
        auto value = heap.front;
        heap.popFront();
        result = value;

        auto count = 1;
        while (!heap.empty && heap.front == value) {
            heap.popFront();
            count++;
        }
        if (count == 1) {
            break;
        }
        if (count in pow) {
            heap.insert(pow[count] + result);
        }
    }

    writeln(calc(result));
}

long calc(long m) {
    if (m == 0) return 1;
    if (m == 1) return x % MOD;
    auto v = calc(m/2);
    if (m % 2 == 0) {
        return (v * v) % MOD;
    } else {
        return (((v * v) % MOD) * x) % MOD;
    }
}

void initPowers() {
    foreach(y; x..n+1) {
        auto k = y;
        while (k >= x && k % x == 0) {
           pow[y]++;
           k /= x;
        }
    }
}

import std.stdio;
import std.algorithm;
import std.container;

const int MAX = 100005;
const int MOD = 1000000007;
int n, x;
long[MAX] a;
long[long] pow;

void main() {
    readf(" %s %s", n, x);
    foreach(i; 0..n) readf(" %s", a[i]);

    initPowers();

    long totalSum = sum(a[0..n]);
    foreach(i; 0..n) a[i] = totalSum - a[i];
    auto heap = heapify!"a > b"(a[0..n]);

    long result = 0;
    while (!heap.empty) {
        auto value = heap.front;
        heap.popFront();
        result = value;

        auto count = 1;
        while (!heap.empty && heap.front == value) {
            heap.popFront();
            count++;
        }
        if (count == 1) {
            break;
        }
        if (count in pow) {
            heap.insert(pow[count] + result);
        }
    }

    writeln(calc(result));
}

long calc(long m) {
    if (m == 0) return 1;
    if (m == 1) return x;
    auto v = calc(m/2);
    if (m % 2 == 0) {
        return (v * v) % MOD;
    } else {
        return (((v * v) % MOD) * x) % MOD;
    }
}

void initPowers() {
    long y = x;
    int count = 1;
    while (y <= n) {
        pow[y] = count;
        y *= x;
        count++;
    }
}


Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.Your task is to find the number of successful students in the group.

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of students and the number of subjects, correspondingly. Next n lines each containing m characters describe the gradebook. Each character in the gradebook is a number from 1 to 9. Note that the marks in a rows are not sepatated by spaces.

Print the single number — the number of successful students in the given group.

NoteIn the first sample test the student number 1 is the best at subjects 1 and 3, student 2 is the best at subjects 1 and 2, but student 3 isn't the best at any subject.In the second sample test each student is the best at at least one subject.

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

void main() {
    int n, m;
    readf("%d %d\n", &n, &m);
    string[] x = new string[n];
    foreach (i; 0 .. n) { x[i] = stdin.readln; }
    bool[] f = new bool[n];
    f.fill(false);
    foreach (j; 0 .. m) {
        int mx = 0;
        foreach (i; 0 .. n) {
            mx = max(x[i][j].to!int, mx);
        }
        foreach (i; 0 .. n) {
            if (x[i][j].to!int == mx) {
                f[i] = true;
            }
        }
    }
    writeln(f.count(true));
}

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

void main() {
    int n, m;
    readf("%d %d\n", &n, &m);
    string[] x = new string[n];
    foreach (i; 0 .. n) { x[i] = stdin.readln.chomp; }
    uint[][] y = x.map!(pipe!(map!("a-'0'"), array)).array;
    bool[] f = new bool[n]; f.fill(false);
    foreach (j; 0 .. m) {
        int mx = 0;
        foreach (i; 0 .. n) {
            mx = max(y[i][j], mx);
        }
        foreach (i; 0 .. n) {
            if (y[i][j] == mx) {
                f[i] = true;
            }
        }
    }
    writeln(f.count(true));
}

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                int m = cin.readInt;

                int[][] g = new int[][](n, m);
                string[] mat = new string[n];
                for (int i = 0; i < n; i++) {
                        mat[i] = cin.readString;
                        for (int j = 0; j < m; j++)
                                g[i][j] = mat[i][j] - 48;
                }

                int[] subMax;
                for (int i = 0; i < m; i++) {
                        int maxx = -9999;
                        for (int j = 0; j < n; j++) {
                                maxx = max(maxx, g[j][i]);
                        }
                        subMax ~= maxx;
                }

                int ans = 0;
                int[] best = new int[n];
                for (int i = 0; i < m; i++) {
                        int maxCount = 0;
                        for (int j = 0; j < n; j++) {
                                if (g[j][i] == subMax[i])
                                        best[j] = 1;
                        }
                }
                writeln(best.count(1));
        }
}


You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.How many operations will you need to perform until the next operation does not have any points to delete?

Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc. The number of the points is between 1 and 106.

Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.

NoteIn the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied.

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

alias Pair = Tuple!(dchar, "col", int, "len");

void main() {
    string s;
    scan(s);

    auto a = s.group.map!(x => Pair(x)).array;

    int ans;

    while (a.length > 1) {
        int k = a[0].len;

        foreach (i ; 0 .. a.length) {
            if (i == 0 || i == a.length - 1) {
                k = min(k, a[i].len);
            }
            else {
                k = min(k, (a[i].len + 1) / 2);
            }
        }

        foreach (i ; 0 .. a.length) {
            if (i == 0 || i == a.length - 1) a[i].len -= k;
            else a[i].len -= 2*k;
        }

        a = a.filter!(x => x.len > 0).array;

        debug {
            writeln(a);
        }

        ans += k;

        if (a.length <= 1) break;

        auto b = new Pair[](0);
        b ~= a[0];
        foreach (i ; 1 .. a.length) {
            if (b.back.col == a[i].col) {
                b.back.len += a[i].len;
            }
            else {
                b ~= a[i];
            }
        }
        a = b.dup;

        debug {
            writeln(a);
        }
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


Polycarp must pay exactly $$$n$$$ burles at the checkout. He has coins of two nominal values: $$$1$$$ burle and $$$2$$$ burles. Polycarp likes both kinds of coins equally. So he doesn't want to pay with more coins of one type than with the other.Thus, Polycarp wants to minimize the difference between the count of coins of $$$1$$$ burle and $$$2$$$ burles being used. Help him by determining two non-negative integer values $$$c_1$$$ and $$$c_2$$$ which are the number of coins of $$$1$$$ burle and $$$2$$$ burles, respectively, so that the total value of that number of coins is exactly $$$n$$$ (i. e. $$$c_1 + 2 \cdot c_2 = n$$$), and the absolute value of the difference between $$$c_1$$$ and $$$c_2$$$ is as little as possible (i. e. you must minimize $$$|c_1-c_2|$$$).

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line. This line contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the number of burles to be paid by Polycarp.

For each test case, output a separate line containing two integers $$$c_1$$$ and $$$c_2$$$ ($$$c_1, c_2 \ge 0$$$) separated by a space where $$$c_1$$$ is the number of coins of $$$1$$$ burle and $$$c_2$$$ is the number of coins of $$$2$$$ burles. If there are multiple optimal solutions, print any one.

NoteThe answer for the first test case is "334 333". The sum of the nominal values of all coins is $$$334 \cdot 1 + 333 \cdot 2 = 1000$$$, whereas $$$|334 - 333| = 1$$$. One can't get the better value because if $$$|c_1 - c_2| = 0$$$, then $$$c_1 = c_2$$$ and $$$c_1 \cdot 1 + c_1 \cdot 2 = 1000$$$, but then the value of $$$c_1$$$ isn't an integer.The answer for the second test case is "10 10". The sum of the nominal values is $$$10 \cdot 1 + 10 \cdot 2 = 30$$$ and $$$|10 - 10| = 0$$$, whereas there's no number having an absolute value less than $$$0$$$.

// Vicfred
// https://codeforces.com/contest/1551/problem/A
// math, greedy
import std.stdio;

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

while(t--) {
    long n;
    readf("%s\n", &n);

    long c1, c2;
    c1 = n / 3L;
    c2 = n / 3L;

    if(n % 3 == 1) {
        c1 += 1;
    } else if (n % 3 == 2) {
        c2 += 1;
    }

    writefln("%s %s", c1, c2);
}
}

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

void main()
{
	int t = readInt!int;
	while (t--)
	{
		int n = readInt!int;
		if (n % 3 == 0)
		{
			writeln(n/3, " ", n/3);
		}
		else if (n % 3 == 1)
		{
			writeln(n/3+1, " ", n/3);
		}
		else
		{
			writeln(n/3, " ", n/3+1);
		}
	}
}

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

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

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

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

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

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

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

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

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    long c2 = (n + 1) / 3;
    long c1 = n - c2 * 2;
    writefln("%d %d", c1, c2);
  }
}

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

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

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

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

  while (n--) {
    long q;
    read(q);

    auto t = q / 3;
    auto r = q - 2 * t;

    while (r - t > 1) {
      t++;
      r -= 2;
    }

    writeln(r, " ", t);
  }
}


Professor GukiZ was playing with arrays again and accidentally discovered new function, which he called GukiZiana. For given array a, indexed with integers from 1 to n, and number y, GukiZiana(a, y) represents maximum value of j - i, such that aj = ai = y. If there is no y as an element in a, then GukiZiana(a, y) is equal to  - 1. GukiZ also prepared a problem for you. This time, you have two types of queries:   First type has form 1 l r x and asks you to increase values of all ai such that l ≤ i ≤ r by the non-negative integer x.  Second type has form 2 y and asks you to find value of GukiZiana(a, y). For each query of type 2, print the answer and make GukiZ happy!

The first line contains two integers n, q (1 ≤ n ≤ 5 * 105, 1 ≤ q ≤ 5 * 104), size of array a, and the number of queries.  The second line contains n integers a1, a2, ... an (1 ≤ ai ≤ 109), forming an array a.  Each of next q lines contain either four or two numbers, as described in statement: If line starts with 1, then the query looks like 1 l r x (1 ≤ l ≤ r ≤ n, 0 ≤ x ≤ 109), first type query. If line starts with 2, then th query looks like 2 y (1 ≤ y ≤ 109), second type query.

For each query of type 2, print the value of GukiZiana(a, y), for y value for that query.

import std.stdio;
import std.c.stdio;
import std.math;
import std.algorithm;
import std.conv;
import std.string;
import std.array;
import std.typecons;

int n, q;

struct SqrtDecomposition {
  alias Entry = Tuple!(long, "val", int, "idx");
  alias MinMax = Tuple!(int, "min", int, "max");
  struct Bucket {
    long added;
    Entry[] vs;
    void add(int l, int r, long x) {
      long prevAdded = added;
      added = 0;
      foreach(ref e; vs) {
        e.val += prevAdded;
        if (l <= e.idx && e.idx < r) e.val += x;
      }
      vs.sort();
    }

    int min(long x) {
      int lb = -1, ub = cast(int)vs.length;
      while (ub - lb > 1) {
        int mid = (ub + lb) / 2;
        if (vs[mid].val < x) {
          lb = mid;
        } else {
          ub = mid;
        }
      }
      if (ub == vs.length || vs[ub].val != x) {
        return -1;
      } else {
        return vs[ub].idx;
      }
    }

    int max(long x) {
      int lb = -1, ub = cast(int)vs.length;
      while (ub - lb > 1) {
        int mid = (ub + lb) / 2;
        if (vs[mid].val > x) {
          ub = mid;
        } else {
          lb = mid;
        }
      }
      if (lb == -1 || vs[lb].val != x) {
        return -1;
      } else {
        return vs[lb].idx;
      }
    }
  }

  int n, m, bsize;
  Bucket[] bs;
  this(int[] a) {
    n = cast(int)a.length;
    bsize = cast(int)(sqrt(real(n)) + 1);
    m = (n - 1) / bsize + 1;
    bs = new Bucket[m];
    foreach (i; 0..m) {
      int l = i * bsize;
      int r = min(n, (i + 1) * bsize);
      bs[i].added = 0;
      foreach(j; l..r) {
        bs[i].vs ~= Entry(a[j], j);
      }
      bs[i].vs.sort();
    }
  }

  void add(int l, int r, long x) {
    int lb = l / bsize;
    int rb = (r - 1) / bsize;
    if (lb == rb) {
      bs[lb].add(l, r, x);
    } else {
      bs[lb].add(l, r, x);
      foreach(i; lb+1..rb) {
        bs[i].added += x;
      }
      bs[rb].add(l, r, x);
    }
  }

  MinMax query(long x) {
    MinMax ans = MinMax(n, -1);
    foreach(b; bs) {
      int minIdx = b.min(x - b.added);
      int maxIdx = b.max(x - b.added);
      if (minIdx != -1) {
        assert(maxIdx != -1);
        ans.min = min(minIdx, ans.min);
        ans.max = max(maxIdx, ans.max);
      } else {
        assert(maxIdx == -1);
      }
    }
    return ans;
  }
}

void main() {
  scanf("%d%d", &n, &q);
  int[] a = new int[n];
  foreach (i; 0..n) {
    scanf("%d", &a[i]);
  }
  auto sq = SqrtDecomposition(a);
  while (q--) {
    int t;
    scanf("%d", &t);
    if (t == 1) {
      int l, r, x;
      scanf("%d%d%d", &l, &r, &x);
      l--;
      sq.add(l, r, x);
    } else if (t == 2) {
      int y;
      scanf("%d", &y);
      auto ans = sq.query(y);
      if (ans.max == -1) {
        writeln(-1);
      } else {
        writeln(ans.max - ans.min);
      }
    } else {
      assert(false);
    }
  }
}

import std.stdio;
import std.c.stdio;
import std.math;
import std.algorithm;
import std.conv;
import std.string;
import std.array;
import std.typecons;

int n, q;

struct SqrtDecomposition {
  alias Entry = Tuple!(long, "val", int, "idx");
  alias MinMax = Tuple!(int, "min", int, "max");
  struct Bucket {
    long added;
    Entry[] vs;
    void add(int l, int r, long x) {
      long prevAdded = added;
      added = 0;
      Entry[] newvs = new Entry[vs.length];
      foreach(i,e; vs) {
        e.val += prevAdded;
        if (l <= e.idx && e.idx < r) e.val += x;
        newvs[i] = e;
      }
      newvs.sort();
      vs = newvs;
    }

    int min(long x) {
      int lb = -1, ub = cast(int)vs.length;
      while (ub - lb > 1) {
        int mid = (ub + lb) / 2;
        if (vs[mid].val < x) {
          lb = mid;
        } else {
          ub = mid;
        }
      }
      if (ub == vs.length || vs[ub].val != x) {
        return -1;
      } else {
        return vs[ub].idx;
      }
    }

    int max(long x) {
      int lb = -1, ub = cast(int)vs.length;
      while (ub - lb > 1) {
        int mid = (ub + lb) / 2;
        if (vs[mid].val > x) {
          ub = mid;
        } else {
          lb = mid;
        }
      }
      if (lb == -1 || vs[lb].val != x) {
        return -1;
      } else {
        return vs[lb].idx;
      }
    }
  }

  int n, m, bsize;
  Bucket[] bs;
  this(int[] a) {
    n = cast(int)a.length;
    bsize = cast(int)(sqrt(real(n)) + 1);
    m = (n - 1) / bsize + 1;
    bs = new Bucket[m];
    foreach (i; 0..m) {
      int l = i * bsize;
      int r = min(n, (i + 1) * bsize);
      bs[i].added = 0;
      foreach(j; l..r) {
        bs[i].vs ~= Entry(a[j], j);
      }
      bs[i].vs.sort();
    }
  }

  void add(int l, int r, long x) {
    int lb = l / bsize;
    int rb = (r - 1) / bsize;
    if (lb == rb) {
      bs[lb].add(l, r, x);
    } else {
      bs[lb].add(l, r, x);
      foreach(i; lb+1..rb) {
        bs[i].added += x;
      }
      bs[rb].add(l, r, x);
    }
  }

  MinMax query(long x) {
    MinMax ans = MinMax(n, -1);
    foreach(b; bs) {
      int minIdx = b.min(x - b.added);
      int maxIdx = b.max(x - b.added);
      if (minIdx != -1) {
        assert(maxIdx != -1);
        ans.min = min(minIdx, ans.min);
        ans.max = max(maxIdx, ans.max);
      } else {
        assert(maxIdx == -1);
      }
    }
    return ans;
  }
}

void main() {
  scanf("%d%d", &n, &q);
  int[] a = new int[n];
  foreach (i; 0..n) {
    scanf("%d", &a[i]);
  }
  auto sq = SqrtDecomposition(a);
  while (q--) {
    int t;
    scanf("%d", &t);
    if (t == 1) {
      int l, r, x;
      scanf("%d%d%d", &l, &r, &x);
      l--;
      sq.add(l, r, x);
    } else if (t == 2) {
      int y;
      scanf("%d", &y);
      auto ans = sq.query(y);
      if (ans.max == -1) {
        writeln(-1);
      } else {
        writeln(ans.max - ans.min);
      }
    } else {
      assert(false);
    }
  }
}

import std.stdio;
import std.c.stdio;
import std.math;
import std.algorithm;
import std.conv;
import std.string;
import std.array;
import std.typecons;

int n, q;

struct SqrtDecomposition {
  alias Entry = Tuple!(long, "val", int, "idx");
  alias MinMax = Tuple!(int, "min", int, "max");
  struct Bucket {
    long added;
    Entry[] vs;
    void add(int l, int r, long x) {
      long prevAdded = added;
      added = 0;
      Entry[] newvs = new Entry[vs.length];
      foreach(i,e; vs) {
        e.val += prevAdded;
        if (l <= e.idx && e.idx < r) e.val += x;
        newvs[i] = e;
      }
      newvs.sort();
      vs = newvs;
    }

    int min(long x) {
      int lb = -1, ub = cast(int)vs.length;
      while (ub - lb > 1) {
        int mid = (ub + lb) / 2;
        if (vs[mid].val < x) {
          lb = mid;
        } else {
          ub = mid;
        }
      }
      if (ub == vs.length || vs[ub].val != x) {
        return -1;
      } else {
        return vs[ub].idx;
      }
    }

    int max(long x) {
      int lb = -1, ub = cast(int)vs.length;
      while (ub - lb > 1) {
        int mid = (ub + lb) / 2;
        if (vs[mid].val > x) {
          ub = mid;
        } else {
          lb = mid;
        }
      }
      if (lb == -1 || vs[lb].val != x) {
        return -1;
      } else {
        return vs[lb].idx;
      }
    }
  }

  int n, m, bsize;
  Bucket[] bs;
  this(int[] a) {
    n = cast(int)a.length;
    bsize = cast(int)(sqrt(real(n)) + 1);
    m = (n - 1) / bsize + 1;
    bs = new Bucket[m];
    foreach (i; 0..m) {
      int l = i * bsize;
      int r = min(n, (i + 1) * bsize);
      bs[i].added = 0;
      foreach(j; l..r) {
        bs[i].vs ~= Entry(a[j], j);
      }
      bs[i].vs.sort();
    }
  }

  void add(int l, int r, long x) {
    int lb = l / bsize;
    int rb = (r - 1) / bsize;
    if (lb == rb) {
      bs[lb].add(l, r, x);
    } else {
      bs[lb].add(l, r, x);
      foreach(i; lb+1..rb) {
        bs[i].added += 1;
      }
      bs[rb].add(l, r, x);
    }
  }

  MinMax query(long x) {
    MinMax ans = MinMax(n, -1);
    foreach(b; bs) {
      int minIdx = b.min(x - b.added);
      int maxIdx = b.max(x - b.added);
      if (minIdx != -1) {
        assert(maxIdx != -1);
        ans.min = min(minIdx, ans.min);
        ans.max = max(maxIdx, ans.max);
      } else {
        assert(maxIdx == -1);
      }
    }
    return ans;
  }
}

void main() {
  scanf("%d%d", &n, &q);
  int[] a = new int[n];
  foreach (i; 0..n) {
    scanf("%d", &a[i]);
  }
  auto sq = SqrtDecomposition(a);
  while (q--) {
    int t;
    scanf("%d", &t);
    if (t == 1) {
      int l, r, x;
      scanf("%d%d%d", &l, &r, &x);
      l--;
      sq.add(l, r, x);
    } else if (t == 2) {
      int y;
      scanf("%d", &y);
      auto ans = sq.query(y);
      if (ans.max == -1) {
        writeln(-1);
      } else {
        writeln(ans.max - ans.min);
      }
    } else {
      assert(false);
    }
  }
}