Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a < b < c < d \leq n$$$) in this permutation satisfy the following two inequalities:  $$$p_a < p_c$$$ and $$$p_b > p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.

For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.

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

struct SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    void update(int k, in T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}
alias RSQ = SegmentTree!(int, 0, (a, b) => a + b);

struct BIT(Num, Num zero) {
    int N;
    Num[] dat; // dat is 1-indexed
    this(int N) {
        this.N = N;
        dat = new Num[N + 1];
        dat[] = zero;
    }
    // add x to i-th (0-indexed) element
    void add(int i, Num x) {
        i++; // make 1-indexed
        while (i <= N) {
            dat[i] += x;
            i += i & -i;
        }
    }
    // return the sum of [0, i) (0-indexed) element
    Num query(int i) {
        Num s = zero;
        while (i > 0) {
            s += dat[i];
            i -= i & -i;
        }
        return s;
    }
}

void solve() {
    int N = readln.chomp.to!int;
    auto P = readln.chomp.split(" ").map!(to!int).array;

    long ans = 0;
    auto front = BIT!(int,0)(N+1);
    for (int b = 0; b < N; b++) {
        auto back = BIT!(int,0)(N+1);
        for (int c = N-1; c > b; c--) {
            long a_count = front.query(P[c]);
            long d_count = back.query(P[b]);
            ans += a_count * d_count;
            back.add(P[c], 1);
        }
        front.add(P[b], 1);
    }
    writeln(ans);
}

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

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 p = readln.splitter.map !(to !(int)).array;

		auto b = new short [] [] (n, n);
		auto c = new short [] [] (n, n);
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				b[i][j] = (p[i] < p[j]);
				c[i][j] = (p[i] > p[j]);
			}
		}
		foreach (i; 1..n)
		{
			foreach (j; i + 1..n)
			{
				b[i][j] += b[i - 1][j];
			}
		}
		foreach_reverse (i; 0..n)
		{
			foreach_reverse (j; i + 1..n - 1)
			{
				c[i][j] += c[i][j + 1];
			}
		}

		// (<j) j | i (>i)
		long res = 0;
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				auto lo = (i > 0) ? b[i - 1][j] : 0;
				auto hi = (j + 1 < n) ? c[i][j + 1] : 0;
				res += lo * hi;
			}
		}
		writeln (res);
	}
}

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

struct SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    void update(int k, in T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}
alias RSQ = SegmentTree!(int, 0, (a, b) => a + b);

void solve() {
    int N = readln.chomp.to!int;
    auto P = readln.chomp.split(" ").map!(to!int).array;

    alias T = Tuple!(int,int);

    long ans = 0;
    auto front = RSQ(N+1);
    for (int b = 0; b < N; b++) {
        auto back = RSQ(N+1);
        for (int c = N-1; c > b; c--) {
            auto a_count = front.query(1, P[c]);
            long d_count = back.query(1, P[b]);
            ans += a_count * d_count;
            back.update(P[c], 1);
        }
        front.update(P[b], 1);
    }
    writeln(ans);
}

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


Notice: unusual memory limit!After the war, destroyed cities in the neutral zone were restored. And children went back to school.The war changed the world, as well as education. In those hard days, a new math concept was created.As we all know, logarithm function can be described as: $$$$$$ \log(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 \log p_1 + a_2 \log p_2 + ... + a_k \log p_k $$$$$$ Where $$$p_1^{a_1}p_2^{a_2}...p_k^{a_2}$$$ is the prime factorization of a integer. A problem is that the function uses itself in the definition. That is why it is hard to calculate.So, the mathematicians from the neutral zone invented this: $$$$$$ \text{exlog}_f(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 f(p_1) + a_2 f(p_2) + ... + a_k f(p_k) $$$$$$Notice that $$$\text{exlog}_f(1)$$$ is always equal to $$$0$$$.This concept for any function $$$f$$$ was too hard for children. So teachers told them that $$$f$$$ can only be a polynomial of degree no more than $$$3$$$ in daily uses (i.e., $$$f(x) = Ax^3+Bx^2+Cx+D$$$)."Class is over! Don't forget to do your homework!" Here it is: $$$$$$ \sum_{i=1}^n \text{exlog}_f(i) $$$$$$Help children to do their homework. Since the value can be very big, you need to find the answer modulo $$$2^{32}$$$.

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

// floor(sqrt(a))
long floorSqrt(long a) {
  import core.bitop : bsr;
  import std.algorithm : min;
  long b = a, x = 0, y = 0;
  for (int e = bsr(a) & ~1; e >= 0; e -= 2) {
    x <<= 1;
    y <<= 1;
    if (b >= (y | 1) << e) {
      b -= (y | 1) << e;
      x |= 1;
      y += 2;
    }
  }
  return x;
}

// get([N / j]) = \sum_{p<=[N/j]} p^K
//   O(N^(3/4) / log N) time, O(N^(1/2)) space
class PrimeSum(T, int K) {
  long N, sqrtN;
  bool[] isPrime;
  T[] small, large;
  this(long N) {
    assert(N >= 1, "PrimeSum: N >= 1 must hold");
    this.N = N;
    sqrtN = floorSqrt(N);
    isPrime = new bool[cast(int)(sqrtN + 1)];
    small = new T[cast(int)(sqrtN + 1)];
    large = new T[cast(int)(sqrtN + 1)];
    isPrime[2 .. $] = true;
    T powerSum(long n) {
      static if (K == 0) {
        return T(n);
      } else static if (K == 1) {
        long n0 = n, n1 = n + 1;
        ((n0 % 2 == 0) ? n0 : n1) /= 2;
        return T(n0) * T(n1);
      } else static if (K == 2) {
        long n0 = n, n1 = n + 1, n2 = 2 * n + 1;
        ((n0 % 2 == 0) ? n0 : n1) /= 2;
        ((n0 % 3 == 0) ? n0 : (n1 % 3 == 0) ? n1 : n2) /= 3;
        return T(n0) * T(n1) * T(n2);
      } else static if (K == 3) {
        long n0 = n, n1 = n + 1;
        ((n0 % 2 == 0) ? n0 : n1) /= 2;
        return T(n0) * T(n0) * T(n1) * T(n1);
      } else {
        static assert(false, "PrimeSum: K is out of range");
      }
    }
    foreach (n; 1 .. sqrtN + 1) small[cast(int)(n)] = powerSum(n);
    foreach (l; 1 .. sqrtN + 1) large[cast(int)(l)] = powerSum(N / l);
    foreach (p; 2 .. sqrtN + 1) {
      if (isPrime[cast(int)(p)]) {
        for (long n = p^^2; n <= sqrtN; n += p) isPrime[cast(int)(n)] = false;
        const pk = T(p)^^K, g1 = get(p - 1);
        foreach (l; 1 .. sqrtN + 1) {
          const n = N / l;
          if (n < p^^2) break;
          large[cast(int)(l)] -= pk * (get(n / p) - g1);
        }
        foreach_reverse (n; 1 .. sqrtN + 1) {
          if (n < p^^2) break;
          small[cast(int)(n)] -= pk * (get(n / p) - g1);
        }
      }
    }
    small[1 .. $] -= T(1);
    large[1 .. $] -= T(1);
  }
  T get(long n) {
    return (n <= sqrtN) ? small[cast(int)(n)] : large[cast(int)(N / n)];
  }
}

void main() {
  try {
    for (; ; ) {
      const N = readLong();
      const A = readLong();
      const B = readLong();
      const C = readLong();
      const D = readLong();

      auto ps3 = new PrimeSum!(long, 3)(N);
      auto ps2 = new PrimeSum!(long, 2)(N);
      auto ps1 = new PrimeSum!(long, 1)(N);
      auto ps0 = new PrimeSum!(long, 0)(N);
      long get(long n) {
        return A * ps3.get(n) + B * ps2.get(n) + C * ps1.get(n) + D * ps0.get(n);
      }

      long ans;
      for (long a = 0, b; b < N; a = b) {
        const k = N / (a + 1);
        b = N / k;
        // (a, b]: k
        ans += k * (get(b) - get(a));
      }
      foreach (p; 2 .. ps0.sqrtN + 1) {
        if (ps0.isPrime[cast(int)(p)]) {
          const f = get(p) - get(p - 1);
          for (long n = N / p^^2; n >= 1; n /= p) {
            ans += n * f;
          }
        }
      }
      ans &= (1L << 32) - 1;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

immutable int limit = 50_000;

void main ()
{
	auto s = new bool [limit];
	s[] = true;
	s[0] = false;
	s[1] = false;
	for (uint g = 2; g * g < limit; g++)
	{
		if (s[g])
		{
			for (uint e = g; e * g < limit; e++)
			{
				s[e * g] = false;
			}
		}
	}

	uint [] p;
	foreach (g; 0..limit)
	{
		if (s[g])
		{
			p ~= g;
		}
	}

	uint n;
	uint a, b, c, d;
	while (readf (" %s %s %s %s %s", &n, &a, &b, &c, &d) > 0)
	{
		uint res = 0;
		auto t = new bool [limit];
		for (uint start = 0; start <= n; start += limit)
		{
			uint finish = min (start + limit, n + 1);
			if (start == 0)
			{
				t[] = s[];
			}
			else
			{
				t[] = true;
				foreach (g; p)
				{
					uint lo = (start + g - 1) / g * g;
					while (lo < finish)
					{
						t[lo - start] = false;
						lo += g;
					}
				}
			}
			foreach (i; start..finish)
			{
				if (t[i - start])
				{
					debug {writeln (i);}
					uint cur = a;
					cur = cur * i + b;
					cur = cur * i + c;
					cur = cur * i + d;

					uint mult = 0;
					uint k = n;
					while (k > 0)
					{
						k /= i;
						mult += k;
					}
					res += cur * mult;
				}
			}
		}
		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)); }

// floor(sqrt(a))
long floorSqrt(long a) {
  import core.bitop : bsr;
  import std.algorithm : min;
  long b = a, x = 0, y = 0;
  for (int e = bsr(a) & ~1; e >= 0; e -= 2) {
    x <<= 1;
    y <<= 1;
    if (b >= (y | 1) << e) {
      b -= (y | 1) << e;
      x |= 1;
      y += 2;
    }
  }
  return x;
}

// // pi([N / l]) = get([N / l]) - 1
uint solve(int N, uint A, uint B, uint C, uint D) {
  const sqrtN = cast(int)(floorSqrt(N));
  stderr.writefln("N = %s, sqrtN = %s", N, sqrtN);
  stderr.flush;
  auto small0 = new uint[sqrtN + 1];
  auto large0 = new uint[sqrtN + 1];
  auto small1 = new uint[sqrtN + 1];
  auto large1 = new uint[sqrtN + 1];
  auto small2 = new uint[sqrtN + 1];
  auto large2 = new uint[sqrtN + 1];
  auto small3 = new uint[sqrtN + 1];
  auto large3 = new uint[sqrtN + 1];
  uint get0(int n) { return (n <= sqrtN) ? small0[n] : large0[N / n]; }
  uint get1(int n) { return (n <= sqrtN) ? small1[n] : large1[N / n]; }
  uint get2(int n) { return (n <= sqrtN) ? small2[n] : large2[N / n]; }
  uint get3(int n) { return (n <= sqrtN) ? small3[n] : large3[N / n]; }

  uint calc0(int n) {
    return n;
  }
  uint calc1(int n) {
    uint n0 = n, n1 = n + 1;
    ((n0 % 2 == 0) ? n0 : n1) /= 2;
    return n0 * n1;
  }
  uint calc2(int n) {
    uint n0 = n, n1 = n + 1, n2 = 2 * n + 1;
    ((n0 % 2 == 0) ? n0 : (n1 % 2 == 0) ? n1 : n2) /= 2;
    ((n0 % 3 == 0) ? n0 : (n1 % 3 == 0) ? n1 : n2) /= 3;
    return n0 * n1 * n2;
  }
  uint calc3(int n) {
    uint n0 = n, n1 = n + 1;
    ((n0 % 2 == 0) ? n0 : n1) /= 2;
    return n0 * n0 * n1 * n1;
  }

  foreach (n; 1 .. sqrtN + 1) {
    // small[n] = n;
    small0[n] = calc0(n);
    small1[n] = calc1(n);
    small2[n] = calc2(n);
    small3[n] = calc3(n);
  }
  foreach_reverse (l; 1 .. sqrtN + 1) {
    // large[l] = N / l;
    large0[l] = calc0(N / l);
    large1[l] = calc1(N / l);
    large2[l] = calc2(N / l);
    large3[l] = calc3(N / l);
  }
  auto isnp = new bool[sqrtN + 1];
  int pi;
  foreach (p; 2 .. sqrtN + 1) {
    // if (small[p - 1] < small[p]) {
    if (!isnp[p]) {
      for (int n = 2 * p; n <= sqrtN; n += p) isnp[n] = true;
      ++pi;
      foreach (l; 1 .. sqrtN + 1) {
        const n = N / l;
        if (n < p^^2) {
          break;
        }
        // pi = #{1, p_1, ..., p_{pi-1}}
        // large[l] -= get(n / p) - pi;
        large0[l] -= (get0(n / p) - get0(p - 1));
        large1[l] -= (get1(n / p) - get1(p - 1)) * p;
        large2[l] -= (get2(n / p) - get2(p - 1)) * p * p;
        large3[l] -= (get3(n / p) - get3(p - 1)) * p * p * p;
      }
      foreach_reverse (n; 1 .. sqrtN + 1) {
        if (n < p^^2) {
          break;
        }
        // pi = #{1, p_1, ..., p_{pi-1}}
        // small[n] -= get(n / p) - pi;
        small0[n] -= (get0(n / p) - get0(p - 1));
        small1[n] -= (get1(n / p) - get1(p - 1)) * p;
        small2[n] -= (get2(n / p) - get2(p - 1)) * p * p;
        small3[n] -= (get3(n / p) - get3(p - 1)) * p * p * p;
      }
    }
  }

  uint getF(int n) {
    uint ret;
    ret += A * (get3(n) - 1);
    ret += B * (get2(n) - 1);
    ret += C * (get1(n) - 1);
    ret += D * (get0(n) - 1);
    return ret;
  }

  debug {
    auto isnp_ = new bool[N + 1];
    foreach (p; 2 .. N + 1) {
      if (!isnp_[p]) {
        for (int n = 2 * p; n <= N; n += p) {
          isnp_[n] = true;
        }
      }
    }
    auto sums = new uint[N + 1];
    foreach (p; 2 .. N + 1) {
      if (!isnp_[p]) {
        sums[p] = A * p^^3 + B * p^^2 + C * p + D;
      }
    }
    foreach (n; 1 .. N + 1) {
      sums[n] += sums[n - 1];
    }
    writeln("sums = ", sums);
    writeln("small0 = ", small0, ", large0 = ", large0);
    writeln("small1 = ", small1, ", large1 = ", large1);
    writeln("small2 = ", small2, ", large2 = ", large2);
    writeln("small3 = ", small3, ", large3 = ", large3);
    foreach (n; 1 .. sqrtN + 1) {
      assert(sums[n] == getF(n));
    }
    foreach_reverse (l; 1 .. sqrtN + 1) {
      assert(sums[N / l] == getF(N / l));
    }
  }

  uint ans;
  for (int a = 1, b; a < N; a = b) {
    const k = N / (a + 1);
    b = N / k;
    // (a, b]: k
    ans += k * (getF(b) - getF(a));
  }
  foreach (p; 2 .. sqrtN + 1) {
    const f = getF(p) - getF(p - 1);
    int n = N / p^^2;
    for (; n >= 1; n /= p) {
      ans += n * f;
    }
  }
  return ans;
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const A = readInt();
      const B = readInt();
      const C = readInt();
      const D = readInt();
      const ans = solve(N, A, B, C, D);
      writeln(ans);

    }
  } catch (EOFException e) {
  }
}

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

immutable int limit = 20_000;

void main ()
{
	uint n;
	uint a, b, c, d;
	while (readf (" %s %s %s %s %s", &n, &a, &b, &c, &d) > 0)
	{
		auto s = new bool [limit];
		s[] = true;
		s[0] = false;
		s[1] = false;
		for (uint g = 2; g * g < limit; g++)
		{
			if (s[g])
			{
				for (uint e = g; e * g < limit; e++)
				{
					s[e * g] = false;
				}
			}
		}

		uint [] p;
		foreach (g; 0..limit)
		{
			if (s[g])
			{
				p ~= g;
			}
		}

		uint res = 0;
		n += 1;
		auto t = new bool [limit];
		for (uint start = 0; start < n; start += limit)
		{
			uint finish = min (start + limit, n);
			if (start == 0)
			{
				t[] = s[];
			}
			else
			{
				t[] = true;
				foreach (g; p)
				{
					uint lo = (start + g - 1) / g * g;
					while (lo < finish)
					{
						t[lo - start] = false;
						lo += g;
					}
				}
			}
			foreach (i; start..finish)
			{
				if (t[i - start])
				{
					uint cur = a;
					cur = cur * i + b;
					cur = cur * i + c;
					cur = cur * i + d;

					uint mult = 0;
					uint k = n;
					while (k > 0)
					{
						k /= i;
						mult += k;
					}
					res += cur * mult;
				}
			}
		}
		writeln (res);
	}
}


Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!Your task is to write a program which calculates two things:  The maximum beauty difference of flowers that Pashmak can give to Parmida.  The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.

The first line of the input contains n (2 ≤ n ≤ 2·105). In the next line there are n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ 109).

The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.

NoteIn the third sample the maximum beauty difference is 2 and there are 4 ways to do this:  choosing the first and the second flowers;  choosing the first and the fifth flowers;  choosing the fourth and the second flowers;  choosing the fourth and the fifth flowers.

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

alias Tuple!(uint, "sub", ulong, "num") Flowers;

Flowers solve(const uint[] bs) {
	uint miin, maax;
	maax = miin = bs[0];
	foreach (i; 1..bs.length) {
		miin = min(miin, bs[i]);
		maax = max(maax, bs[i]);
	}

	ulong minN = 0;
	ulong maxN = 0;
	foreach (b; bs) {
		if (b == miin) {++minN;}
		if (b == maax) {++maxN;}
	}

	return Flowers(maax - miin, (miin == maax) ? (minN * (minN - 1) / 2) : (minN * maxN));
}

unittest {
	assert(Flowers(1, 1) == solve([1, 2]));
	assert(Flowers(4, 1) == solve([1, 4, 5]));
	assert(Flowers(2, 4) == solve([3, 1, 2, 3, 1]));
	assert(Flowers(0, 1) == solve([1, 1]));
	assert(Flowers(0, 3) == solve([1, 1, 1]));
	assert(Flowers(0, 10) == solve([345, 345, 345, 345, 345]));
}

int main(string[] argv) {
	import std.stdio;

	uint n = 0;
	readf(" %s", &n);
	auto bs = new uint[](n);
	foreach (i; 0..n) {
		readf(" %s", &(bs[i]));
	}
	auto res = solve(bs);
	writeln(res.sub, ' ', res.num);
    return 0;
}

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

void main() {
    ulong n = readln.chomp.to!ulong;
    ulong[] b = readln.split.map!(to!ulong).array;
    b.sort;

    ulong t1 = 0;
    ulong t2 = 0;
    foreach(item; b) {
        if(item == b[$-1])
            t1 += 1;
        if(item == b[0])
            t2 += 1;
    }
    //ulong ways = count(b,b[0])*count(b,b[$-1]);
    ulong ways = t1*t2;
    ulong maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

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

void main() {
    ulong n = readln.chomp.to!ulong;
    ulong[] b = readln.split.map!(to!ulong).array;
    b.sort;

    ulong ways = (cast(ulong)count(b,b[0]))*(cast(ulong)count(b,b[$-1]));
    ulong maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

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

void main() {
    int n = readln.chomp.to!int;
    ulong[] b = readln.split.map!(to!ulong).array;
    b.sort;

    ulong ways = count(b,b[0])*count(b,b[$-1]);
    ulong maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

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

void main() {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;
    b.sort;

    ulong ways = b.filter!(x => x == b[$-1]).count * b.filter!(x => x == b[0]).count;

    writefln("%d %d", b[$-1]-b[0], ways);
}

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

void main() {
    ulong n = readln.chomp.to!ulong;
    ulong[] b = readln.split.map!(to!ulong).array;
    b.sort;

    ulong ways = count(b,b[0])*count(b,b[$-1]);
    ulong maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

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

void main() {
    int n = readln.chomp.to!int;
    ulong[] b = readln.split.map!(to!ulong).array;
    b.sort;

    ulong t1 = 0;
    ulong t2 = 0;
    foreach(item; b) {
        if(item == b[$-1])
            t1 += 1;
        if(item == b[0])
            t2 += 1;
    }
    //ulong ways = count(b,b[0])*count(b,b[$-1]);
    ulong ways = t1*t2;
    ulong maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

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

void main() {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;
    b.sort;

    ulong ways = count(b,b[0])*count(b,b[$-1]);
    int maxima = b[$-1]-b[0];

    if(maxima != 0) {
        writefln("%d %d", maxima, ways);
    } else {
        writefln("%d %d", maxima, n*(n-1)/2);
    }
}

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

void main() {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;
    b.sort;

    BigInt ways = b.filter!(x => x == b[$-1]).count * b.filter!(x => x == b[0]).count;

    writefln("%d %d", b[$-1]-b[0], ways);
}

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

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

    int[int] c;

    foreach(item; b) {
        c.update(item,
                {
                return 1;
                },
                (ref int i) {
                return i+1;
                });
    }

    int maxima = b[$-1]-b[0];

    int ways = 0;
    foreach(item; b) {
        //ways += c[item+maxima];
        if(((item+maxima) in c) !is null)
            ways += c[item+maxima];
    }

    writefln("%d %d", maxima, ways);
}

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

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

    int[int] c;

    foreach(item; b) {
        c.update(item,
                {
                return 1;
                },
                (ref int i) {
                return i+1;
                });
    }

    int maxima = b[$-1]-b[0];

    int ways = 0;
    foreach(item; b) {
        //ways += c[item+maxima];
        if(((item+maxima) in c) !is null)
            ways += c[item];
    }

    writefln("%d %d", maxima, ways);
}

import std.stdio;
import std.algorithm;

unittest{
  assert(solve([1,2]) == [1,1],"A");
  assert(solve([3,1,2,3,1]) == [2,4],"B");
  assert(solve([1,4,5]) == [4,1],"C");
}

int[] solve(int[] p){
  int[int] cnt;
  int max = 0;
  int min = 0;
  for(int i = 0; i < p.length; i++){
    if(p[i] > p[max]){
      max = i;
    }
    if(p[i] < p[min]){
      min = i;
    }
    cnt[p[i]]++;
  }
  return [p[max] - p[min],cnt[p[max]]*cnt[p[min]]];
}

void main(){

}

import std.stdio;
import std.algorithm;

unittest{
  assert(solve([1,2]) == [1,1],"A");
  assert(solve([3,1,2,3,1]) == [2,4],"B");
  assert(solve([1,4,5]) == [4,1],"C");
  assert(solve([1,1,1]) == [0,3],"D");
}

int[] solve(int[] p){
  int[int] cnt;
  int max = 0;
  int min = 0;
  for(int i = 0; i < p.length; i++){
    if(p[i] > p[max]){
      max = i;
    }
    if(p[i] < p[min]){
      min = i;
    }
    cnt[p[i]]++;
  }
  if ((p[max] - p[min]) == 0){
    return [0,cnt[p[0]]];
  }
  return [p[max] - p[min],cnt[p[max]]*cnt[p[min]]];
}

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

  int[] x = new int[a];
  for(int i = 0; i< a; i++){
    readf("%s ",x.ptr+i);
  }
  auto s = solve(x);
  writefln("%s %s",s[0],s[1]);
}

import std.stdio;
import std.algorithm;

unittest{
  assert(solve([1,2]) == [1,1],"A");
  assert(solve([3,1,2,3,1]) == [2,4],"B");
  assert(solve([1,4,5]) == [4,1],"C");
  assert(solve([1,1,1]) == [0,6],"D");
}

int[] solve(int[] p){
  int[int] cnt;
  int max = 0;
  int min = 0;
  for(int i = 0; i < p.length; i++){
    if(p[i] > p[max]){
      max = i;
    }
    if(p[i] < p[min]){
      min = i;
    }
    cnt[p[i]]++;
  }
  if ((p[max] - p[min]) == 0){
    return [0,cnt[p[0]]*(cnt[p[0]]-1)];
  }
  return [p[max] - p[min],cnt[p[max]]*cnt[p[min]]];
}

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

  int[] x = new int[a];
  for(int i = 0; i< a; i++){
    readf("%s ",x.ptr+i);
  }
  auto s = solve(x);
  writefln("%s %s",s[0],s[1]);
}

import std.stdio;
import std.algorithm;

unittest{
  assert(solve([1,2]) == [1,1],"A");
  assert(solve([3,1,2,3,1]) == [2,4],"B");
  assert(solve([1,4,5]) == [4,1],"C");
}

int[] solve(int[] p){
  int[int] cnt;
  int max = 0;
  int min = 0;
  for(int i = 0; i < p.length; i++){
    if(p[i] > p[max]){
      max = i;
    }
    if(p[i] < p[min]){
      min = i;
    }
    cnt[p[i]]++;
  }
  return [p[max] - p[min],cnt[p[max]]*cnt[p[min]]];
}

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

  int[] x = new int[a];
  for(int i = 0; i< a; i++){
    readf("%s ",x.ptr+i);
  }
  auto s = solve(x);
  writefln("%s %s",s[0],s[1]);
}


Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x < x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.

The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.

Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x < x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.

NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.

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

void main(){
    auto S = readln.chomp;
    auto N = S.length.to!int;
    long ans = 1L * N * (N + 1) / 2;

    foreach (l; 0..N) foreach (r; l..min(N, l+10)) {
        bool ok = true;
        foreach (i; l..r+1) for (int j = 1; i - j >= l && i + j <= r; ++j) {
            if (S[i-j] == S[i] && S[i] == S[i+j]) ok = false;
        }
        ans -= ok;
    }

    ans.writeln;
}

/+ dub.sdl:
    name "B"
    dependency "dunkelheit" version="1.0.1"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dkh.foundation, dkh.scanner, dkh.algorithm;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    string s;
    sc.read(s);

    int n = s.length.to!int;

    long r = n;
    long ans = 0;
    foreach_reverse (l; 0..n) {
        int k = 1;
        while (l + 2 * k < r && (s[l + k] != s[l] || s[l + 2 * k] != s[l])) k++;
        r = min(r, l + 2 * k);

        ans += (n - r);
    }

    writeln(ans);
    return 0;
}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/algorithm.d */
// module dkh.algorithm;

import std.traits : isFloatingPoint, isIntegral;

T binSearch(alias pred, T)(T l, T r) if (isIntegral!T) {
    while (r-l > 1) {
        T md = l + (r-l) / 2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

T binSearch(alias pred, T)(T l, T r, int cnt = 60) if (isFloatingPoint!T) {
    foreach (i; 0..cnt) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

import std.range.primitives;

E minimum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? a : b)(seed, range);
}

ElementType!Range minimum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "minimum: range must not empty");
    auto e = range.front; range.popFront;
    return minimum!pred(range, e);
}

E maximum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? b : a)(seed, range);
}

ElementType!Range maximum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "maximum: range must not empty");
    auto e = range.front; range.popFront;
    return maximum!pred(range, e);
}

Rotator!Range rotator(Range)(Range r) {
    return Rotator!Range(r);
}

struct Rotator(Range)
if (isForwardRange!Range && hasLength!Range) {
    size_t cnt;
    Range start, now;
    this(Range r) {
        cnt = 0;
        start = r.save;
        now = r.save;
    }
    this(this) {
        start = start.save;
        now = now.save;
    }
    @property bool empty() const {
        return now.empty;
    }
    @property auto front() const {
        assert(!now.empty);
        import std.range : take, chain;
        return chain(now, start.take(cnt));
    }
    @property Rotator!Range save() {
        return this;
    }
    void popFront() {
        cnt++;
        now.popFront;
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    private File f;

    this(File f) {
        this.f = f;
    }
    private char[512] lineBuf;
    private char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    assert(succW());
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }

    void read(Args...)(auto ref Args args) {
        import std.exception : enforce;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }

    bool hasNext() {
        return succ();
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/


There is a road with length $$$l$$$ meters. The start of the road has coordinate $$$0$$$, the end of the road has coordinate $$$l$$$.There are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to the end and the second car will drive from the end to the start.Initially, they will drive with a speed of $$$1$$$ meter per second. There are $$$n$$$ flags at different coordinates $$$a_1, a_2, \ldots, a_n$$$. Each time when any of two cars drives through a flag, the speed of that car increases by $$$1$$$ meter per second.Find how long will it take for cars to meet (to reach the same coordinate).

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$): the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$l$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq l \leq 10^9$$$): the number of flags and the length of the road. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ in the increasing order ($$$1 \leq a_1 < a_2 < \ldots < a_n < l$$$). It is guaranteed that the sum of $$$n$$$ among all test cases does not exceed $$$10^5$$$.

For each test case print a single real number: the time required for cars to meet. Your answer will be considered correct, if its absolute or relative error does not exceed $$$10^{-6}$$$. More formally, if your answer is $$$a$$$ and jury's answer is $$$b$$$, your answer will be considered correct if $$$\frac{|a-b|}{\max{(1, b)}} \leq 10^{-6}$$$.

NoteIn the first test case cars will meet in the coordinate $$$5$$$.The first car will be in the coordinate $$$1$$$ in $$$1$$$ second and after that its speed will increase by $$$1$$$ and will be equal to $$$2$$$ meters per second. After $$$2$$$ more seconds it will be in the coordinate $$$5$$$. So, it will be in the coordinate $$$5$$$ in $$$3$$$ seconds.The second car will be in the coordinate $$$9$$$ in $$$1$$$ second and after that its speed will increase by $$$1$$$ and will be equal to $$$2$$$ meters per second. After $$$2$$$ more seconds it will be in the coordinate $$$5$$$. So, it will be in the coordinate $$$5$$$ in $$$3$$$ seconds.In the second test case after $$$1$$$ second the first car will be in the coordinate $$$1$$$ and will have the speed equal to $$$2$$$ meters per second, the second car will be in the coordinate $$$9$$$ and will have the speed equal to $$$1$$$ meter per second. So, they will meet after $$$\frac{9-1}{2+1} = \frac{8}{3}$$$ seconds. So, the answer is equal to $$$1 + \frac{8}{3} = \frac{11}{3}$$$.

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

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

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

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

enum EPS = 1e-12L;

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const L = readReal();
        auto A = new real[N + 2];
        A[0] = 0.0L;
        A[N + 1] = L;
        foreach (i; 1 .. N + 1) {
          A[i] = readReal();
        }

        auto ls = new real[N + 2];
        auto rs = new real[N + 2];
        ls[0] = 0.0L;
        foreach (i; 0 .. N + 1) {
          ls[i + 1] = ls[i] + (A[i + 1] - A[i]) / (1 + i);
        }
        rs[N + 1] = 0.0L;
        foreach_reverse (i; 0 .. N + 1) {
          rs[i] = (A[i + 1] - A[i]) / (N + 1 - i) + rs[i + 1];
        }
        debug {
          writeln("ls = ", ls);
          writeln("rs = ", rs);
        }

        real ans;
        foreach (i; 0 .. N + 1) {
          if (ls[i] <= rs[i] + EPS && ls[i + 1] + EPS >= rs[i + 1]) {
            const real u = 1 + i;
            const real v = N + 1 - i;
            const d = A[i + 1] - A[i];
            ans = (d + u * ls[i] + v * rs[i + 1]) / (u + v);
            break;
          }
        }
        writefln("%.12f", ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 0.0000001)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

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

		bool f(double x)
		{
			double pos1 = 0.0, pos2 = l;
			{
				long last;
				double time = x;
				double sp = 1.0;
				foreach (i; 0..n)
				{
					auto d = a[i] - last;
					if (time*sp <= d) break;
					time -= d / sp;
					last = a[i];
					pos1 = last;
					sp += 1.0;
				}
				pos1 += time * sp;
			}
			{
				long last = l;
				double time = x;
				double sp = 1.0;
				foreach_reverse (i; 0..n)
				{
					auto d = last - a[i];
					if (time*sp <= d) break;
					time -= d / sp;
					last = a[i];
					pos2 = last;
					sp += 1.0;
				}
				pos2 -= time * sp;
			}
			debug writeln("time:", x, " pos1:", pos1, " pos2:", pos2);
			return pos1 >= pos2;
		}

		auto r = binarySearch!(f)(cast(double)l, 0.0);
		ans[ti] = r;
	}

	foreach (e; ans)
	{
		writefln(FMT_F, e);
	}
	stdout.flush;
	debug readln;
}


A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).  Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of dice in the tower. The second line contains an integer x (1 ≤ x ≤ 6) — the number Bob sees at the top of the tower. Next n lines contain two space-separated integers each: the i-th line contains numbers ai, bi (1 ≤ ai, bi ≤ 6; ai ≠ bi) — the numbers Bob sees on the two sidelong faces of the i-th dice in the tower. Consider the dice in the tower indexed from top to bottom from 1 to n. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input.

Print "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes).

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

void main() {
    int n; readf("%d\n", &n);
    int t; readf("%d\n", &t);
    for (int i = 0; i < n; i++) {
        int a, b; readf("%d %d\n", &a, &b);
        bool[] u = new bool[6];
        u[t - 1] = true;
        u[a - 1] = u[7 - a - 1] = true;
        u[b - 1] = u[7 - b - 1] = true;
        if (u.count!"a == false" > 1) {
            writeln("NO");
            return;
        }
    }
    writeln("YES");
}

import std.stdio;

void main(){
  int n,m; readf("%d\n%d\n",&n,&m); bool can=true;
  while (n--){
    int a,b; readf("%d %d\n",&a,&b);
    if (m!=a && m!=b && m!=7-a && m!=7-b) m=7-m; else can=false;
  }
  writeln(can? "YES": "NO");
}

import std.stdio;

void main() {
    uint n, s;
    readf("%d %d", &n, &s);
    for (uint i = 0; i < n; ++i) {
    	uint a, b;
    	readf(" %d %d", &a, &b);

    	if (s != a && s != 7 - a && s != b && s != 7 - b) {

    	}
    	else {
    	    writeln("NO");
    	    return;
    	}
    }
    writeln("YES");
}

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

int main() {

    int other(int[] a) {
        int[int] set;
        foreach(int i; a)
            set[i] = 1;
        for (int i = 1; i <= 6; ++i)
            if ((i in set) is null)
                return i;
        return 1;
    }

    auto n = to!int(strip(readln()));
    auto x = to!int(strip(readln()));
    auto a = new int[n];
    auto b = new int[n];
    for (int i = 0; i < n; ++i) {
        auto tmp2 = split(strip(readln()), " ");
        a[i] = to!int(tmp2[0]);
        b[i] = to!int(tmp2[1]);
    }
    int[] h = [a[0], b[0], 7 - a[0], 7 - b[0], x];
    h ~= other(h);
    for (int i = 1; i < n; ++i) {
        int[int] set = [a[i] : 1, b[i] : 1, 7 - a[i] : 1, 7 - b[i] : 1];
        if ((h[5] in set) is null)
            h = set.keys ~ other(set.keys ~ h[5]) ~ h[5];
        else {
            writeln("NO");
            return 0;
        }
    }
    writeln("YES");
    return 0;
}

import std.stdio;

void main(){
  int n,m; readf("%d\n%d\n",&n,&m);
  bool[int] can; can[7-m]=true;
  while (n--){
    int a,b; readf("%d %d\n",&a,&b);
    bool[int] could;
    foreach (i; can)
      if (i!=a && i!=b && i!=7-a && i!=7-b)
        could[7-i]=true;
    can=could;
  }
  writeln(can.length==1? "YES": "NO");
}


You play the game with your friend. The description of this game is listed below. Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: «What character stands on position pos in the string you have chosen?» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of strings your friend came up with. The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.

Print the single number — the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.

NoteIn the first sample the strings only differ in the character in the third position. So only the following situations are possible:   you guess the string in one question. The event's probability is ;  you guess the string in two questions. The event's probability is  ·  =  (as in this case the first question should ask about the position that is other than the third one);  you guess the string in three questions. The event's probability is  ·  ·  = ; Thus, the expected value is equal to In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is .In the third sample whatever position we ask about in the first question, we immediately identify the string.

// Code By H~$~C

module main;

import std.stdio, std.array, std.string, std.math, std.uni, std.format, std.bigint;
import std.algorithm, std.conv, std.container, std.range, std.functional;
import std.random, std.typecons;

immutable Maxn = 50;
immutable Maxm = 20;

int n, m;
string[Maxn] str;
real[] dp;
long[] state;
int[] num;

void solve(in int testcase) {
  dp.length = 1 << Maxm;
  state.length = 1 << Maxm;
  num.length = 1 << Maxm;
  n.read;
  foreach(i; 0 .. n) str[i].read;
  m = cast(int)(str[n - 1].length);
  foreach(i; 0 .. n - 1)
    foreach(j; i + 1 .. n) {
      int mask = 0;
      foreach(k; 0 .. m) {
        if (str[i][k] == str[j][k])
          mask |= (1 << k);
      }
      state[mask] |= (1L << i) | (1L << j);
    }
  for (int mask = (1 << m) - 1; mask >= 0; --mask) {
    foreach(i; 0 .. m) {
      if ((mask & (1 << i)) != 0) {
        state[mask ^ (1 << i)] |= state[mask];
      }
    }
  }
  foreach(i; 0 .. (1 << m)) {
    num[i] = state[i].countbit;
  }

  dp[] = 1e9;
  dp[(1 << m) - 1] = 0.0;
  for (int mask = (1 << m) - 1 - 1; mask >= 0; --mask) {
    if (!num[mask]) {
      dp[mask] = 0.0;
      continue;
    }
    dp[mask] = 1.0;
    int cnt = (mask ^ ((1 << m) - 1)).countbit;
    foreach(i; 0 .. m) {
      if ((mask & (1 << i)) != 0) continue;
      int from = mask | (1 << i);
      dp[mask] += dp[from] * (1.0 / cnt) * (num[from] * 1.0 / num[mask]);
    }
  }
  dp[0].writefln!"%.15f";
}

// ************************************************************

T reader(T)() { return readToken().to!T; }
void read(T)(ref T t) { t = reader!T; }
T[] readarray(T)() { return readln.splitter.map!(to!T).array; }
void chmax(T)(ref T a, T b) { a = max(a, b); }
void chmin(T)(ref T a, T b) { a = min(a, b); }
alias less = (a, b) => a < b;
alias greater = (a, b) => a > b;
T min_element(T)(in T[] a) { return a.element!less; }
T max_element(T)(in T[] a) { return a.element!greater; }
alias unique = uniq;

// constant or some variables
immutable int inf = 0x3f3f3f3f;
immutable long lnf = 0x3f3f3f3f3f3f3f3f;
immutable typeof(null) NULL = null;
string[] _tokens;

// functions
T element(alias pred, T)(in T[] a) {
  int pos = 0;
  for (int i = 1; i < cast(int)(a.length); ++i)
    if (binaryFun!pred(a[i], a[pos])) pos = i;
  return a[pos];
}
string readToken() {
  for (; _tokens.empty; ) {
    if (stdin.eof) return "";
    _tokens = readln.split;
  }
  auto token = _tokens.front;
  _tokens.popFront;
  return token;
}
int binary_bearch(alias pred, T)(in T[] as) {
  int l = -1, h = cast(int)(as.length), mid;
  for (; l + 1 < h; ) {
    mid = (l + h) >> 1;
    (unaryFun!pred(as[mid]) ? h : l) = mid;
  }
  return h;
}
int lower_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => a == val || pred(val, a));
}
int upper_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => pred(val, a));
}
int countbit(T)(T x) {
  int res = 0;
  while (x) {
    res++;
    x &= x - 1;
  }
  return res;
}

void main(string[] args) {
  int tests = 1;
//  tests.read();
  foreach(test; 1 .. tests + 1) solve(test);
}

// Code By H~$~C

module main;

import std.stdio, std.array, std.string, std.math, std.uni, std.format, std.bigint;
import std.algorithm, std.conv, std.container, std.range, std.functional;
import std.random, std.typecons;

immutable Maxn = 50;
immutable Maxm = 20;

int n, m;
string[Maxn] str;
real[] dp;
long[] state;
int[] num;

void solve(in int testcase) {
  dp.length = 1 << Maxm;
  state.length = 1 << Maxm;
  num.length = 1 << Maxm;
  n.read;
  foreach(i; 0 .. n) str[i].read;
  m = cast(int)(str[n - 1].length);
  foreach(i; 0 .. n - 1)
    foreach(j; i + 1 .. n) {
      int mask = 0;
      foreach(k; 0 .. m) {
        if (str[i][k] == str[j][k])
          mask |= (1 << k);
      }
      state[mask] |= (1L << i) | (1L << j);
    }
  for (int mask = (1 << m) - 1; mask >= 0; --mask) {
    foreach(i; 0 .. n) {
      if ((mask & (1 << i)) != 0) {
        state[mask ^ (1 << i)] |= state[mask];
      }
    }
  }
  foreach(i; 0 .. (1 << m)) {
    num[i] = state[i].countbit;
  }

  dp[] = 1e9;
  dp[(1 << m) - 1] = 0.0;
  for (int mask = (1 << m) - 1 - 1; mask >= 0; --mask) {
    if (!num[mask]) {
      dp[mask] = 0.0;
      continue;
    }
    dp[mask] = 1.0;
    int cnt = (mask ^ ((1 << m) - 1)).countbit;
    foreach(i; 0 .. m) {
      if ((mask & (1 << i)) != 0) continue;
      int from = mask | (1 << i);
      dp[mask] += dp[from] * (1.0 / cnt) * (num[from] * 1.0 / num[mask]);
    }
  }
  dp[0].writefln!"%.15f";
}

// ************************************************************

T reader(T)() { return readToken().to!T; }
void read(T)(ref T t) { t = reader!T; }
T[] readarray(T)() { return readln.splitter.map!(to!T).array; }
void chmax(T)(ref T a, T b) { a = max(a, b); }
void chmin(T)(ref T a, T b) { a = min(a, b); }
alias less = (a, b) => a < b;
alias greater = (a, b) => a > b;
T min_element(T)(in T[] a) { return a.element!less; }
T max_element(T)(in T[] a) { return a.element!greater; }
alias unique = uniq;

// constant or some variables
immutable int inf = 0x3f3f3f3f;
immutable long lnf = 0x3f3f3f3f3f3f3f3f;
immutable typeof(null) NULL = null;
string[] _tokens;

// functions
T element(alias pred, T)(in T[] a) {
  int pos = 0;
  for (int i = 1; i < cast(int)(a.length); ++i)
    if (binaryFun!pred(a[i], a[pos])) pos = i;
  return a[pos];
}
string readToken() {
  for (; _tokens.empty; ) {
    if (stdin.eof) return "";
    _tokens = readln.split;
  }
  auto token = _tokens.front;
  _tokens.popFront;
  return token;
}
int binary_bearch(alias pred, T)(in T[] as) {
  int l = -1, h = cast(int)(as.length), mid;
  for (; l + 1 < h; ) {
    mid = (l + h) >> 1;
    (unaryFun!pred(as[mid]) ? h : l) = mid;
  }
  return h;
}
int lower_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => a == val || pred(val, a));
}
int upper_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => pred(val, a));
}
int countbit(T)(T x) {
  int res = 0;
  while (x) {
    res++;
    x &= x - 1;
  }
  return res;
}

void main(string[] args) {
  int tests = 1;
//  tests.read();
  foreach(test; 1 .. tests + 1) solve(test);
}


Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly ai calories on touching the i-th strip.You've got a string s, describing the process of the game and numbers a1, a2, a3, a4. Calculate how many calories Jury needs to destroy all the squares?

The first line contains four space-separated integers a1, a2, a3, a4 (0 ≤ a1, a2, a3, a4 ≤ 104). The second line contains string s (1 ≤ |s| ≤ 105), where the і-th character of the string equals "1", if on the i-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip.

Print a single integer — the total number of calories that Jury wastes.

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

void main() {
    auto a = readln.chomp.split.map!(to!int);
    string s = readln.chomp;
    auto answer = 0;

    foreach (e; s) {
        answer += a[to!int(e.to!string) - 1];
    }

    writeln(answer);
}


The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.

The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.  Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.

Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).

NoteIn the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less. In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up. In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles.

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

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

    string[] arr;
    foreach (i; 0 .. n) { arr ~= readln.chomp; }

    bool isOut(int r, int c) {
        return r < 0 || r >= n || c < 0 || c >= m;
    }

    char V(int r, int c) {
        if (isOut(r, c)) { return '*'; }

        return arr[r][c];
    }

    int cr, cc;
    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            if (arr[i][j] == 'X') {
                cr = i;
                cc = j;
            }
        }
    }

    if (k % 2 == 1
            || (n == 1 && m == 1)
            || ([V(cr-1,cc), V(cr+1,cc), V(cr,cc-1), V(cr,cc+1)].all!(x => x == '*'))) {
        writeln("IMPOSSIBLE");
        return;
    }

    immutable int INF = 10 ^^ 9;
    auto dst = new int[][] (n, m);
    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            dst[i][j] = INF;
        }
    }

    auto q = make!(DList!(Tuple!(int, int)));
    q ~= tuple(cr, cc);
    dst[cr][cc] = 0;

    auto dx = [-1, 1, 0, 0];
    auto dy = [0, 0, -1, 1];
    while (!q.empty()) {
        auto p = q.front();
        q.removeFront();

        foreach (i; 0 .. 4) {
            int nx = p[0] + dx[i], ny = p[1] + dy[i];
            if (isOut(nx, ny)) { continue; }
            if (arr[nx][ny] == '*') { continue; }
            if (dst[nx][ny] != INF) { continue; }

            dst[nx][ny] = dst[p[0]][p[1]] + 1;
            q ~= tuple(nx, ny);
        }
    }

    auto ans = new dchar[] (k);
    foreach (i; 0 .. k) {
        if (V(cr+1,cc) != '*' && dst[cr+1][cc] <= k - i - 1) {
            cr += 1;
            ans[i] = 'D';
        } else if (V(cr,cc-1) != '*' && dst[cr][cc-1] <= k - i - 1) {
            cc -= 1;
            ans[i] = 'L';
        } else if (V(cr,cc+1) != '*' && dst[cr][cc+1] <= k - i - 1) {
            cc += 1;
            ans[i] = 'R';
        } else {
            cr -= 1;
            ans[i] = 'U';
        }
    }

    ans.each!write;
    writeln;
}

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

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

    string[] arr;
    foreach (i; 0 .. n) { arr ~= readln.chomp; }

    bool isOut(int r, int c) {
        return r < 0 || r >= n || c < 0 || c >= m;
    }

    char V(int r, int c) {
        if (isOut(r, c)) { return '*'; }

        return arr[r][c];
    }

    int cr, cc;
    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            if (arr[i][j] == 'X') {
                cr = i;
                cc = j;
            }
        }
    }

    if (k % 2 == 1
            || (n == 1 && m == 1)
            || ([V(cr-1,cc), V(cr+1,cc), V(cr,cc-1), V(cr,cc+1)].all!(x => x == '*'))) {
        writeln("IMPOSSIBLE");
        return;
    }

    immutable int INF = 10 ^^ 9;
    auto dst = new int[][] (n, m);
    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            dst[i][j] = INF;
        }
    }

    auto q = make!(DList!(Tuple!(int, int)));
    q ~= tuple(cr, cc);
    dst[cr][cc] = 0;

    auto dx = [-1, 1, 0, 0];
    auto dy = [0, 0, -1, 1];
    while (!q.empty()) {
        auto p = q.front();
        q.removeFront();

        foreach (i; 0 .. 4) {
            int nx = p[0] + dx[i], ny = p[1] + dy[i];
            if (isOut(nx, ny)) { continue; }
            if (arr[nx][ny] == '*') { continue; }
            if (dst[nx][ny] != INF) { continue; }

            dst[nx][ny] = dst[p[0]][p[1]] + 1;
            q ~= tuple(nx, ny);
        }
    }

    auto ans = new dchar[] (k);
    foreach (i; 0 .. k) {
        if (V(cr+1,cc) != '*' && dst[cr+1][cc] <= k - i - 1) {
            cr += 1;
            ans[i] = 'D';
            ans[k-1 - i] = 'U';
        } else if (V(cr,cc-1) != '*' && dst[cr][cc-1] <= k - i - 1) {
            cc -= 1;
            ans[i] = 'L';
            ans[k-1 - i] = 'R';
        } else if (V(cr,cc+1) != '*' && dst[cr][cc+1] <= k - i - 1) {
            cc += 1;
            ans[i] = 'R';
            ans[k-1 - i] = 'L';
        } else {
            cr -= 1;
            ans[i] = 'U';
            ans[k-1 - i] = 'D';
        }
    }

    ans.each!write;
    writeln;
}

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

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

    string[] arr;
    foreach (i; 0 .. n) { arr ~= readln.chomp; }

    char V(int r, int c) {
        if (r < 0 || r == n) { return '*'; }
        if (c < 0 || c >= m) { return '*'; }

        return arr[r][c];
    }

    int cr, cc;
    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            if (arr[i][j] == 'X') {
                cr = i;
                cc = j;
            }
        }
    }

    if (k % 2 == 1
            || (n == 1 && m == 1)
            || ([V(cr-1,cc), V(cr+1,cc), V(cr,cc-1), V(cr,cc+1)].all!(x => x == '*'))) {
        writeln("IMPOSSIBLE");
        return;
    }

    auto ans = new dchar[] (k);
    foreach (i; 0 .. k/2) {
        if (V(cr+1,cc) == '.') {
            cr += 1;
            ans[i] = 'D';
            ans[k-1 - i] = 'U';
        } else if (V(cr,cc-1) == '.') {
            cc -= 1;
            ans[i] = 'L';
            ans[k-1 - i] = 'R';
        } else if (V(cr,cc+1) == '.') {
            cc += 1;
            ans[i] = 'R';
            ans[k-1 - i] = 'L';
        } else {
            cr -= 1;
            ans[i] = 'U';
            ans[k-1 - i] = 'D';
        }
    }

    ans.each!write;
    writeln;
}

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

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

    string[] arr;
    foreach (i; 0 .. n) { arr ~= readln.chomp; }

    char V(int r, int c) {
        if (r < 0 || r == n) { return '*'; }
        if (c < 0 || c >= m) { return '*'; }

        return arr[r][c];
    }

    int cr, cc;
    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            if (arr[i][j] == 'X') {
                cr = i;
                cc = j;
            }
        }
    }

    if (k % 2 == 1
            || (n == 1 && m == 1)
            || ([V(cr-1,cc), V(cr+1,cc), V(cr,cc-1), V(cr,cc+1)].all!(x => x == '*'))) {
        writeln("IMPOSSIBLE");
        return;
    }

    auto ans = new dchar[] (k);
    foreach (i; 0 .. k/2) {
        if (V(cr+1,cc) != '*') {
            cr += 1;
            ans[i] = 'D';
            ans[k-1 - i] = 'U';
        } else if (V(cr,cc-1) != '*') {
            cc -= 1;
            ans[i] = 'L';
            ans[k-1 - i] = 'R';
        } else if (V(cr,cc+1) != '*') {
            cc += 1;
            ans[i] = 'R';
            ans[k-1 - i] = 'L';
        } else {
            cr -= 1;
            ans[i] = 'U';
            ans[k-1 - i] = 'D';
        }
    }

    ans.each!write;
    writeln;
}


Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:  either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before);  or the girl in the dancing pair must dance for the first time. Help Fox Ciel to make a schedule that they can dance as many songs as possible.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of boys and girls in the dancing room.

In the first line print k — the number of songs during which they can dance. Then in the following k lines, print the indexes of boys and girls dancing during songs chronologically. You can assume that the boys are indexed from 1 to n, and the girls are indexed from 1 to m.

NoteIn test case 1, there are 2 boys and 1 girl. We can have 2 dances: the 1st boy and 1st girl (during the first song), the 2nd boy and 1st girl (during the second song).And in test case 2, we have 2 boys with 2 girls, the answer is 3.

import std.stdio : write, writeln;
import std.array;
import std.range;
import std.typecons;
import std.bigint;
import std.algorithm;

void main(){
	int n = next!int;
	int m = next!int;

	int cnt;
	for( int i = 1; i <= min(n, m); ++i ){
		for( int j = i; j <= max(n, m); ++j ){
			if( i!=1 && j>i ) continue;
			++cnt;
		}
	}

	writeln = cnt;
	bool flag = n <= m;
	for( int i = 1; i <= min(n, m); ++i ){
		for( int j = i; j <= max(n, m); ++j ){
			if( i!=1 && j>i ) continue;

			if( flag )
				writeln(i, " ", j);
			else
				writeln(j, " ", i);
		}
	}
}

import std.stdio : readln;
import std.conv : to;
import std.string : split, chomp;
import std.traits;
string[] input;
string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

T next( T : char )()
in
{
	assert(hasNext());
}
out
{
	input.front.popFront;
}
body
{
	return input.front.front.to!T;
}

bool hasNext(){
	if(input.length > 0){
		if(input.front.length == 0){
			input.popFront;
			return hasNext;
		}
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return hasNext;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : write, writeln;
import std.array;
import std.range;
import std.typecons;
import std.bigint;
import std.algorithm;

void main(){
	int n = next!int;
	int m = next!int;

	int cnt;
	for( int i = 1; i <= min(n, m); ++i )
		for( int j = i; j <= max(n, m); ++j )
			++cnt;

	writeln = cnt;
	bool flag = n < m;
	for( int i = 1; i <= min(n, m); ++i )
		for( int j = i; j <= max(n, m); ++j )
			if( flag )
				writeln(i, " ", j);
			else
				writeln(j, " ", i);
}

import std.stdio : readln;
import std.conv : to;
import std.string : split, chomp;
import std.traits;
string[] input;
string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

T next( T : char )()
in
{
	assert(hasNext());
}
out
{
	input.front.popFront;
}
body
{
	return input.front.front.to!T;
}

bool hasNext(){
	if(input.length > 0){
		if(input.front.length == 0){
			input.popFront;
			return hasNext;
		}
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return hasNext;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : write, writeln;
import std.array;
import std.range;
import std.typecons;
import std.bigint;
import std.algorithm;

void main(){
	int n = next!int;
	int m = next!int;

	int cnt;
	for( int i = 1; i <= min(n, m); ++i )
		for( int j = i; j <= max(n, m); ++j )
			++cnt;

	writeln = cnt;
	bool flag = n <= m;
	for( int i = 1; i <= min(n, m); ++i )
		for( int j = i; j <= max(n, m); ++j )
			if( flag )
				writeln(i, " ", j);
			else
				writeln(j, " ", i);
}

import std.stdio : readln;
import std.conv : to;
import std.string : split, chomp;
import std.traits;
string[] input;
string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

T next( T : char )()
in
{
	assert(hasNext());
}
out
{
	input.front.popFront;
}
body
{
	return input.front.front.to!T;
}

bool hasNext(){
	if(input.length > 0){
		if(input.front.length == 0){
			input.popFront;
			return hasNext;
		}
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return hasNext;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}


You have a simple undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.Let's make a definition.Let $$$v_1$$$ and $$$v_2$$$ be two some nonempty subsets of vertices that do not intersect. Let $$$f(v_{1}, v_{2})$$$ be true if and only if all the conditions are satisfied:  There are no edges with both endpoints in vertex set $$$v_1$$$.  There are no edges with both endpoints in vertex set $$$v_2$$$.  For every two vertices $$$x$$$ and $$$y$$$ such that $$$x$$$ is in $$$v_1$$$ and $$$y$$$ is in $$$v_2$$$, there is an edge between $$$x$$$ and $$$y$$$. Create three vertex sets ($$$v_{1}$$$, $$$v_{2}$$$, $$$v_{3}$$$) which satisfy the conditions below;  All vertex sets should not be empty.  Each vertex should be assigned to only one vertex set.  $$$f(v_{1}, v_{2})$$$, $$$f(v_{2}, v_{3})$$$, $$$f(v_{3}, v_{1})$$$ are all true. Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$3 \le n \le 10^{5}$$$, $$$0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$$$) — the number of vertices and edges in the graph. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$a_{i}$$$ and $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$) — it means there is an edge between $$$a_{i}$$$ and $$$b_{i}$$$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.

If the answer exists, print $$$n$$$ integers. $$$i$$$-th integer means the vertex set number (from $$$1$$$ to $$$3$$$) of $$$i$$$-th vertex. Otherwise, print $$$-1$$$. If there are multiple answers, print any.

NoteIn the first example, if $$$v_{1} = \{ 1 \}$$$, $$$v_{2} = \{ 2, 3 \}$$$, and $$$v_{3} = \{ 4, 5, 6 \}$$$ then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.  In the second example, it's impossible to make such vertex sets.

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

immutable int MAX_N = 100_000;
int n, m;
Array!int[MAX_N] g;
int[3][MAX_N] comp;
int[3] cc;
int[MAX_N] ans;

void main()
{
    readln.strip.formattedRead(" %s %s", n, m);

    foreach (i; 0 .. m)
    {
        int a, b;
        readln.strip.formattedRead(" %s %s", a, b);
        a--, b--;
        g[a] ~= b;
        g[b] ~= a;
    }

    foreach (i; 0 .. n)
    {
        bool ok = false;
        foreach (j; 0 .. 3)
        {
            if (!comp[i][j])
            {
                ans[i] = j;
                cc[j]++;
                foreach (k; g[i])
                {
                    comp[k][j] = true;
                }
                ok = true;
                break;
            }
        }

        if (!ok)
        {
            writeln(-1);
            return;
        }
    }

    bool ok = true;

    foreach (i; 0 .. n)
    {
        ok &= n == (g[i].length + cc[ans[i]]);
    }

    ok &= cc[0] > 0 && cc[1] > 0 && cc[2] > 0;

    if (ok)
    {
        foreach (i; 0 .. n)
        {
            write(ans[i] + 1, " ");
        }
        writeln();
    }
    else
    {
        writeln(-1);
    }
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
import std.container;
long[][] adj;
string[] adjstr;

void connect(long a, long b)
{
  adj[cast(uint)a] ~= b;
  adj[cast(uint)b] ~= a;
}

void main()
{
  import std.conv;
  long n, m; get(n, m);
  adj = new long[][cast(uint)n];
  adjstr = new string[cast(uint)n];
  itup!(m, (long a, long b) {
      connect(a - 1, b - 1);
    });
  short[string] color;
  short col = 1;
  foreach(size_t v, ref a; adj)
    {
      sort(a);
      adjstr[v] = "";
      foreach(e; a)
	  adjstr[v] ~= to!string(e) ~ ".";
      if(adjstr[v] !in color)
	{
	  if ( col > 3 )
	    ans(-1);
	  color[adjstr[v]] = col;
	  col++;
	}
    }
  if (col != 4)
    ans(-1);
  short[int] colorfor;
  int[3] cant;
  int[3] reqsum;
  foreach(v; 0 .. n)
    {
      colorfor[cast(int)v] = color[adjstr[cast(int)v]];
      cant[color[adjstr[cast(uint)v]] - 1]++;
    }
  reqsum[0] = cant[1] + cant[2];
  reqsum[1] = cant[0] + cant[2];
  reqsum[2] = cant[0] + cant[1];
  foreach(v; 0 .. n)
    {
      if(adj[cast(uint)v].length != reqsum[colorfor[cast(int)v] - 1])
	ans(-1);
    }
  foreach(v; 0 .. n)
    write(colorfor[cast(int)v], " ");
  writeln();
}

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

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

    RedBlackTree!int[] g;
    foreach (_; 0 .. n) {
        g ~= make!(RedBlackTree!int);
    }

    foreach (_; 0 .. m) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        --u, --v;

        g[u].insert(v);
        g[v].insert(u);
    }

    debug { g.writeln; }

    if (g[0].empty()) {
        writeln(-1);
        return;
    }

    auto ans = new int[] (n);

    ans[0] = 1;
    int nxt = g[0].front;
    ans[nxt] = 2;

    foreach (u; g[0].array.dropOne) {
        if (g[u].equalRange(nxt).empty()) { ans[u] = 2; }
        else { ans[u] = 3; }
    }

    foreach (v; 1 .. n) {
        if (ans[v] == 0) {
            bool to0 = ! g[v].equalRange(0).empty();
            bool to1 = ! g[v].equalRange(nxt).empty();

            if (to0 && to1) { ans[v] = 3; }
            else if (to0) { ans[v] = 2; }
            else if (to1) { ans[v] = 1; }
            else {
                writeln(-1);
                return;
            }
        }
    }

    foreach (v; 0 .. n) {
        foreach (u; g[v]) {
            if (ans[v] == ans[u]) {
                writeln(-1);
                return;
            }
        }
    }

    int[4] cnts;
    foreach (e; ans) { ++cnts[e]; }

    foreach (v; 0 .. n) {
        int other = n - cnts[ans[v]];
        if (g[v].length != other) {
            writeln(-1);
            return;
        }
    }

    if (ans.all!(x => x != 3)) {
        writeln(-1);
        return;
    }

    ans.map!(to!string).join(' ').writeln;
}

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

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

    RedBlackTree!int[] g;
    foreach (_; 0 .. n) {
        g ~= make!(RedBlackTree!int);
    }

    foreach (_; 0 .. m) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        --u, --v;

        g[u].insert(v);
        g[v].insert(u);
    }

    debug { g.writeln; }

    if (g[0].empty()) {
        writeln(-1);
        return;
    }

    auto ans = new int[] (n);

    ans[0] = 1;
    int nxt = g[0].front;
    ans[nxt] = 2;

    foreach (u; g[0].array.dropOne) {
        if (g[u].equalRange(nxt).empty()) { ans[u] = 2; }
        else { ans[u] = 3; }
    }

    foreach (v; 1 .. n) {
        if (ans[v] == 0) {
            bool to0 = ! g[v].equalRange(0).empty();
            bool to1 = ! g[v].equalRange(nxt).empty();

            if (to0 && to1) { ans[v] = 3; }
            else if (to0) { ans[v] = 2; }
            else if (to1) { ans[v] = 1; }
            else {
                writeln(-1);
                return;
            }
        }
    }

    foreach (v; 0 .. n) {
        foreach (u; g[v]) {
            if (ans[v] == ans[u]) {
                writeln(-1);
                return;
            }
        }
    }

    if (ans.dup.sort().uniq().array.length != 3) {
        writeln(-1);
        return;
    }

    ans.map!(to!string).join(' ').writeln;
}


A row of $$$n$$$ cells is given, all initially white. Using a stamp, you can stamp any two neighboring cells such that one becomes red and the other becomes blue. A stamp can be rotated, i.e. it can be used in both ways: as $$$\color{blue}{\texttt{B}}\color{red}{\texttt{R}}$$$ and as $$$\color{red}{\texttt{R}}\color{blue}{\texttt{B}}$$$.During use, the stamp must completely fit on the given $$$n$$$ cells (it cannot be partially outside the cells). The stamp can be applied multiple times to the same cell. Each usage of the stamp recolors both cells that are under the stamp.For example, one possible sequence of stamps to make the picture $$$\color{blue}{\texttt{B}}\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\color{blue}{\texttt{B}}\texttt{W}$$$ could be $$$\texttt{WWWWW} \to \texttt{WW}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\texttt{W} \to \color{brown}{\underline{\color{blue}{\texttt{B}}\color{red}{\texttt{R}}}}\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\texttt{W} \to \color{blue}{\texttt{B}}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\color{blue}{\texttt{B}}\texttt{W}$$$. Here $$$\texttt{W}$$$, $$$\color{red}{\texttt{R}}$$$, and $$$\color{blue}{\texttt{B}}$$$ represent a white, red, or blue cell, respectively, and the cells that the stamp is used on are marked with an underline.Given a final picture, is it possible to make it using the stamp zero or more times?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the picture. The second line of each test case contains a string $$$s$$$ — the picture you need to make. It is guaranteed that the length of $$$s$$$ is $$$n$$$ and that $$$s$$$ only consists of the characters $$$\texttt{W}$$$, $$$\texttt{R}$$$, and $$$\texttt{B}$$$, representing a white, red, or blue cell, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output "YES" if it possible to make the picture using the stamp zero or more times, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

12
5
BRBBW
1
B
2
WB
2
RW
3
BRB
3
RBB
7
WWWWWWW
9
RBWBWRRBW
10
BRBRBRBRRB
12
BBBRWWRRRWBR
10
BRBRBRBRBW
5
RBWBW

YES
NO
NO
NO
YES
YES
YES
NO
YES
NO
YES
NO

NoteThe first test case is explained in the statement.For the second, third, and fourth test cases, it is not possible to stamp a single cell, so the answer is "NO".For the fifth test case, you can use the stamp as follows: $$$\texttt{WWW} \to \texttt{W}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}} \to \color{brown}{\underline{\color{blue}{\texttt{B}}\color{red}{\texttt{R}}}}\color{blue}{\texttt{B}}$$$.For the sixth test case, you can use the stamp as follows: $$$\texttt{WWW} \to \texttt{W}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}} \to \color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\color{blue}{\texttt{B}}$$$.For the seventh test case, you don't need to use the stamp at all.

import std;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip ~ 'W';
		int mask = 0;
		bool ok = true;
		foreach (ref c; s)
		{
			switch (c)
			{
			case 'R': mask |= 1; break;
			case 'B': mask |= 2; break;
			case 'W': ok &= (mask % 3 == 0); mask = 0; break;
			default: assert (false);
			}
		}
		writeln (ok ? "YES" : "NO");
	}
}


A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square.For a given string $$$s$$$ determine if it is square.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) —the number of test cases. This is followed by $$$t$$$ lines, each containing a description of one test case. The given strings consist only of lowercase Latin letters and have lengths between $$$1$$$ and $$$100$$$ inclusive.

For each test case, output on a separate line:   YES if the string in the corresponding test case is square,  NO otherwise.  You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

10
a
aa
aaa
aaaa
abab
abcabc
abacaba
xxyy
xyyx
xyxy

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

bool is_square(string s)
{
  if (s.length % 2 != 0)
    return false;
  return s[0 .. s.length / 2] == s[s.length / 2 .. $];
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    writeln(is_square(readln.strip) ? "YES" : "NO");
  }
}


After lessons Nastya decided to read a book. The book contains $$$n$$$ chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number $$$k$$$ as the first page which was not read (i.e. she read all pages from the $$$1$$$-st to the $$$(k-1)$$$-th).The next day Nastya's friend Igor came and asked her, how many chapters remain to be read by Nastya? Nastya is too busy now, so she asks you to compute the number of chapters she has not completely read yet (i.e. the number of chapters she has not started to read or has finished reading somewhere in the middle).

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of chapters in the book. There are $$$n$$$ lines then. The $$$i$$$-th of these lines contains two integers $$$l_i$$$, $$$r_i$$$ separated by space ($$$l_1 = 1$$$, $$$l_i \leq r_i$$$) — numbers of the first and the last pages of the $$$i$$$-th chapter. It's guaranteed that $$$l_{i+1} = r_i + 1$$$ for all $$$1 \leq i \leq n-1$$$, and also that every chapter contains at most $$$100$$$ pages. The $$$(n+2)$$$-th line contains a single integer $$$k$$$ ($$$1 \leq k \leq r_n$$$) — the index of the marked page.

Print a single integer — the number of chapters which has not been completely read so far.

NoteIn the first example the book contains $$$11$$$ pages and $$$3$$$ chapters — $$$[1;3]$$$, $$$[4;7]$$$ and $$$[8;11]$$$. Nastya marked the $$$2$$$-nd page, so she finished in the middle of the $$$1$$$-st chapter. So, all chapters has not been read so far, so the answer is $$$3$$$.The book in the second example contains $$$12$$$ pages and $$$3$$$ chapters too, but Nastya finished reading in the middle of the $$$2$$$-nd chapter, so that the answer is $$$2$$$.

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

alias Tree = RBT!int;

void main() {
  GC.disable();

  uint n;
  readf(" %s", n);
  auto l = new int[n];
  auto r = new int[n];
  foreach(i; 0..n) {
    uint ll, rr;
    readf(" %s %s", ll, rr);
    l[i] = ll;
    r[i] = rr;
  }

  uint k;
  readf(" %s", k);

  uint tt =0;
  uint ss = 0;
  foreach(i; 0..n) {

    if (l[i] <= k && r[i] >= k) {
      ss = i;
      break;
    }
  }

  writeln(n - ss);

}

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	int[] m = new int[t];
	for (int i=0; i<t; i++)
	{
		int a=0;
		readf(" %d", &a);
		readf(" %d", &m[i]);
	}
	int x=0;
	readf(" %d", &x);
	int count=0;
	for (int i=0; i<t; i++)
	{
		if (x>m[i])
		{
			count=count+1;
		}
	}
	writeln(t-count);
	return 0;
}


Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

// Try Codeforces
// author: Leonardone @ NEETSDKASU
import std.algorithm  : sort, sum;
import std.array      : split;
import std.conv       : to;
import std.stdio      : readln, writeln;
import std.string     : chomp;

auto gets() { return readln.chomp; }
auto getV(T)() { return readln.chomp.to!T; }

void main() {
    auto s = gets;
    auto k = getV!int;

    if (s.length < k) {
        writeln("impossible");
        return;
    }

    int[char] tb;

    foreach (ch; s) {
        tb[ch]++;
    }

    if (tb.length >= k) {
        writeln(0);
        return;
    }

    if (tb.length < k) {
        writeln(k - tb.length);
        return;
    }

    writeln(tb.values.sort[0..$-k].sum);

}


Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allowed.Help Arkady to find two fountains with maximum total beauty so that he can buy both at the same time.

The first line contains three integers n, c and d (2 ≤ n ≤ 100 000, 0 ≤ c, d ≤ 100 000) — the number of fountains, the number of coins and diamonds Arkady has. The next n lines describe fountains. Each of these lines contain two integers bi and pi (1 ≤ bi, pi ≤ 100 000) — the beauty and the cost of the i-th fountain, and then a letter "C" or "D", describing in which type of money is the cost of fountain i: in coins or in diamonds, respectively.

Print the maximum total beauty of exactly two fountains Arkady can build. If he can't build two fountains, print 0.

NoteIn the first example Arkady should build the second fountain with beauty 4, which costs 3 coins. The first fountain he can't build because he don't have enough coins. Also Arkady should build the third fountain with beauty 5 which costs 6 diamonds. Thus the total beauty of built fountains is 9.In the second example there are two fountains, but Arkady can't build both of them, because he needs 5 coins for the first fountain, and Arkady has only 4 coins.

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

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

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

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

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

alias Fountain = Tuple!(int, `price`, int, `beauty`);

Fountain[ ][2] fountains;
int[2][10^^5] psum;

int tryChoose2(in Fountain[ ] fs, int budget) {
    int[2] best = [-1, -1];
    foreach (int i, f; fs) {
        if (!~best[0] || f.beauty > fs[best[0]].beauty) {
            best[1] = best[0];
            best[0] = i;
        } else if (!~best[1] || f.beauty > fs[best[1]].beauty)
            best[1] = i;
        psum[i] = best;
    }

    int result = 0;
    foreach (i, f; fs) {
        const rest = budget - f.price;
        int left = 0, right = cast(int)fs.length;
        while (left != right) {
            int mid = (left + right) >> 1;
            if (fs[mid].price > rest)
                right = mid;
            else
                left = mid + 1;
        }
        if (right) {
            best = psum[right - 1];
            if (best[0] != i)
                result = max(result, f.beauty + fs[best[0]].beauty);
            else if (~best[1])
                result = max(result, f.beauty + fs[best[1]].beauty);
        }
    }
    return result;
}

void main() {
    int n, coins, diamonds;
    while (read(n, coins, diamonds)) {
        fountains = [null, null];
        foreach (i; 0 .. n) {
            Fountain f;
            char c;
            read(f.beauty, f.price, c);
            fountains[c == 'D'] ~= f;
        }
        fountains[0].multiSort!(`a.price < b.price`, `a.beauty > b.beauty`);
        fountains[1].multiSort!(`a.price < b.price`, `a.beauty > b.beauty`);
        int result = 0;
        auto rc = fountains[0].filter!(f => f.price <= coins);
        auto rd = fountains[1].filter!(f => f.price <= diamonds);
        if (!rc.empty && !rd.empty)
            result = rc.map!`a.beauty`.fold!max() + rd.map!`a.beauty`.fold!max();
        result = max(result, tryChoose2(fountains[0], coins), tryChoose2(fountains[1], diamonds));
        writeln(result);
    }
}