We call two numbers $$$x$$$ and $$$y$$$ similar if they have the same parity (the same remainder when divided by $$$2$$$), or if $$$|x-y|=1$$$. For example, in each of the pairs $$$(2, 6)$$$, $$$(4, 3)$$$, $$$(11, 7)$$$, the numbers are similar to each other, and in the pairs $$$(1, 4)$$$, $$$(3, 12)$$$, they are not.You are given an array $$$a$$$ of $$$n$$$ ($$$n$$$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.For example, for the array $$$a = [11, 14, 16, 12]$$$, there is a partition into pairs $$$(11, 12)$$$ and $$$(14, 16)$$$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even positive integer $$$n$$$ ($$$2 \le n \le 50$$$) — length of array $$$a$$$. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$).

For each test case print:   YES if the such a partition exists,  NO otherwise.  The letters in the words YES and NO can be displayed in any case.

NoteThe first test case was explained in the statement.In the second test case, the two given numbers are not similar.In the third test case, any partition is suitable.

import std.stdio;
import std.string : split, strip;
import std.algorithm : any, count, map, sort;
import std.conv : to;
import std.array;
import std.range : slide;

static bool even(ulong a) { return (a & 1) == 0; }

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

  foreach (i; 0..t) {
    int n;
    readf!"%d\n"(n);
    auto a = readln.strip.split.map!(to!uint).array;
    a.sort;

    auto d = a.slide(2).any!"a[1] - a[0] == 1";
    auto c = a.count!even;

    if (even(c) || d) {
      writeln("YES");
    } else {
      writeln("NO");
    }
  }
}

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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

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

  void solve(long tc = -1)
  {
    sort(a);
    long p = a.count!(ai => ai % 2 == 0), i = a.count!(ai => ai % 2 == 1);
    bool has1p = iota(0, n - 1).map!(i => abs(a.at(i) - a.at(i + 1))).canFind(1);
    if ((p + i) % 2 == 0)
      {
        if (p % 2 == 0)
          {
            writeln("YES");
          }
        else
          {
            if (has1p)
              {
                writeln("YES");
              }
            else
              {
                writeln("NO");
              }
          }
      }
    else
      {
        writeln("NO");
      }
  }
}

struct Interval
{
  long l, h;

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long cnt;
		foreach (i; 0..n)
		{
			if (a[i] % 2)
				++cnt;
		}
		if (cnt % 2 == 0 && (n-cnt) % 2 == 0)
			ans[ti] = true;
		else if (cnt % 2 && (n-cnt % 2))
		{
			a.sort();
			foreach (i; 1..n)
			{
				if (a[i]-1 == a[i-1])
					ans[ti] = true;
			}
		}
	}

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


You are given an angle $$$\text{ang}$$$. The Jury asks You to find such regular $$$n$$$-gon (regular polygon with $$$n$$$ vertices) that it has three vertices $$$a$$$, $$$b$$$ and $$$c$$$ (they can be non-consecutive) with $$$\angle{abc} = \text{ang}$$$ or report that there is no such $$$n$$$-gon.  If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed $$$998244353$$$.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 180$$$) — the number of queries.  Each of the next $$$T$$$ lines contains one integer $$$\text{ang}$$$ ($$$1 \le \text{ang} < 180$$$) — the angle measured in degrees.

For each query print single integer $$$n$$$ ($$$3 \le n \le 998244353$$$) — minimal possible number of vertices in the regular $$$n$$$-gon or $$$-1$$$ if there is no such $$$n$$$.

NoteThe answer for the first query is on the picture above.The answer for the second query is reached on a regular $$$18$$$-gon. For example, $$$\angle{v_2 v_1 v_6} = 50^{\circ}$$$.The example angle for the third query is $$$\angle{v_{11} v_{10} v_{12}} = 2^{\circ}$$$.In the fourth query, minimal possible $$$n$$$ is $$$180$$$ (not $$$90$$$).

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 T = readln.chomp.to!int;
    while (T--) {
        auto X = readln.chomp.to!long;
        auto Y = 180L;
        auto G = gcd(X, Y);
        X /= G;
        Y /= G;
        if (Y - X == 1) {
            Y *= 2;
        }
        writeln(Y);
    }
}

void main() {
  import std.stdio, std.string, std.conv, std.algorithm;
  import std.exception;

  int t;
  rd(t);
  while (t--) {
    int a;
    rd(a);
    bool ok = false;
    for (int n = 3; n <= 360; n++) {
      if (360 % n == 0) {
        auto x = 180 - 360 / n;
        if (a * (n - 2) % x == 0) {
          if (a * (n - 2) / x <= (n - 2)) {
            writeln(n);
            ok = true;
            break;
          }
        }
      }
    }
    enforce(ok);
  }

}

/*

3 60 60
4 90 45
5 108 36
6 120 30
7 180-360/7 x/5
8 135 135/6
.
.
.
n 180-360/n:=x x/(n-2)

*/

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

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

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

void main() {
  GC.disable();

  int[] cc = new int[200];
  cc[] = 0;

  foreach(n; 3 .. 2000) {
    foreach(i; 0 .. n-1) {
      if ( (i*180) % n == 0) {
        uint a = i*180 / n;
        if (cc[a] == 0) {
          cc[a] = n;
        }
      }
    }
  }

  uint T;
  readf(" %s", T);
  foreach(i; 0 .. T) {
    uint ang;
    readf(" %s", ang);
    if (cc[ang] != 0) writeln(cc[ang]);
    else writeln(-1);
  }

}

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

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

void main() {
  GC.disable();

  int[] cc = new int[200];
  cc[] = 0;

  foreach(n; 3 .. 200) {
    foreach(i; 0 .. n-1) {
      if ( (i*180) % n == 0) {
        uint a = i*180 / n;
        if (cc[a] == 0) {
          cc[a] = n;
        }
      }
    }
  }

  uint T;
  readf(" %s", T);
  foreach(i; 0 .. T) {
    uint ang;
    readf(" %s", ang);
    if (cc[ang] != 0) writeln(cc[ang]);
    else writeln(-1);
  }

}


After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i,  j,  k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!

The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.

Print one number — the quantity of triples (i,  j,  k) such that i,  j and k are pairwise distinct and ai·aj·ak is minimum possible.

NoteIn the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.

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

int n;
int[] a;

void main() {
    scan(n);
    a = readln.split.to!(int[]);

    int f = a[0], s = a[1], t = a[2];

    if (f > s) swap(f, s);
    if (s > t) swap(s, t);
    if (f > s) swap(f, s);

    int tmp1, tmp2;

    foreach (i ; 3 .. n) {
        if (a[i] < f) {
            tmp1 = f, tmp2 = s;
            f = a[i], s = tmp1, t = tmp2;
        }
        else if (a[i] < s) {
            tmp1 = s;
            s = a[i], t = tmp1;
        }
        else if (a[i] < t) {
            t = a[i];
        }
    }

    debug {
        stderr.writeln(f, " ", s, " ", t);
    }

    long x = a.count(t), ans;

    if (f < s) {
        if (s < t) {
            ans = x;
        }
        else {
            ans = x * (x - 1) / 2;
        }
    }
    else if (s < t) {
        ans = x;
    }
    else {
        ans = x * (x - 1) * (x - 2) / 6;
    }

    writeln(ans);
}

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

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

immutable int mod = 10^^9 + 7;

int n;
int[] a;

void main() {
    n = readln.chomp.to!int;
    a = readln.split.to!(int[]);

    a.sort();
    long ans, x;

    if (a[0] < a[1]) {
        if (a[1] < a[2]) {
            ans = a.count(a[2]);
        }
        else if (a[1] == a[2] && a[2] < a[3]) {
            ans = 1;
        }
        else {
            x = a.count(a[1]);
            ans = x * (x - 1) / 2;
        }
    }
    else if (a[0] == a[1] && a[1] < a[2]) {
        if (a[2] < a[3]) {
            ans = 1;
        }
        else {
            ans = a.count(a[2]);
        }
    }
    else {
        x = a.count(a[0]);
        ans = x * (x - 1) * (x - 2) / 6;
    }

    writeln(ans);
}

void readVariables(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg ; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if (!line.empty) {
        throw new Exception("args num < input num");
    }
}

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

int n;
int[] a;

void main() {
    scan(n);
    a = readln.split.to!(int[]);

    a.sort();

    long ans, x;

    x = a.count(a[2]);

    if (a[0] < a[1]) {
        if (a[1] < a[2]) {
            ans = x;
        }
        else {
            ans = x * (x - 1) / 2;
        }
    }
    else if (a[1] < a[2]) {
        ans = x;
    }
    else {
        ans = x * (x - 1) * (x - 2) / 6;
    }

    writeln(ans);
}

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


Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way.There are $$$n$$$ ghosts in the universe, they move in the $$$OXY$$$ plane, each one of them has its own velocity that does not change in time: $$$\overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarrow{j}$$$ where $$$V_{x}$$$ is its speed on the $$$x$$$-axis and $$$V_{y}$$$ is on the $$$y$$$-axis.A ghost $$$i$$$ has experience value $$$EX_i$$$, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time.As the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind $$$GX = \sum_{i=1}^{n} EX_i$$$ will never increase.Tameem is a red giant, he took a picture of the cartesian plane at a certain moment of time $$$T$$$, and magically all the ghosts were aligned on a line of the form $$$y = a \cdot x + b$$$. You have to compute what will be the experience index of the ghost kind $$$GX$$$ in the indefinite future, this is your task for today.Note that when Tameem took the picture, $$$GX$$$ may already be greater than $$$0$$$, because many ghosts may have scared one another at any moment between $$$[-\infty, T]$$$.

The first line contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \leq n \leq 200000$$$, $$$1 \leq |a| \leq 10^9$$$, $$$0 \le |b| \le 10^9$$$) — the number of ghosts in the universe and the parameters of the straight line. Each of the next $$$n$$$ lines contains three integers $$$x_i$$$, $$$V_{xi}$$$, $$$V_{yi}$$$ ($$$-10^9 \leq x_i \leq 10^9$$$, $$$-10^9 \leq V_{x i}, V_{y i} \leq 10^9$$$), where $$$x_i$$$ is the current $$$x$$$-coordinate of the $$$i$$$-th ghost (and $$$y_i = a \cdot x_i + b$$$). It is guaranteed that no two ghosts share the same initial position, in other words, it is guaranteed that for all $$$(i,j)$$$ $$$x_i \neq x_j$$$ for $$$i \ne j$$$.

Output one line: experience index of the ghost kind $$$GX$$$ in the indefinite future.

NoteThere are four collisions $$$(1,2,T-0.5)$$$, $$$(1,3,T-1)$$$, $$$(2,4,T+1)$$$, $$$(3,4,T+0.5)$$$, where $$$(u,v,t)$$$ means a collision happened between ghosts $$$u$$$ and $$$v$$$ at moment $$$t$$$. At each collision, each ghost gained one experience point, this means that $$$GX = 4 \cdot 2 = 8$$$.In the second test, all points will collide when $$$t = T + 1$$$.   The red arrow represents the 1-st ghost velocity, orange represents the 2-nd ghost velocity, and blue represents the 3-rd ghost velocity.

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readC(T...)(size_t n,ref T t){foreach(ref v;t)v=new typeof(v)(n);foreach(i;0..n){auto r=rdsp;foreach(ref v;t)pick(r,v[i]);}}

void main()
{
  int n, a, b; readV(n, a, b);
  int[] x, vx, vy; readC(n, x, vx, vy);

  struct V { long n, d; }
  auto v = new V[](n);
  foreach (i; 0..n)
    v[i] = V(a.to!long*vx[i]-vy[i], a.to!long*vy[i]+vx[i]);

  auto vs = v.sort!"a.n == b.n ? a.d < b.d : a.n < b.n";

  auto ans = 0L;
  foreach (vi; v) {
    ans += vs.upperBound(V(vi.n, long.min)).lowerBound(V(vi.n, long.max)).length;
    ans -= vs.equalRange(vi).length;
  }

  writeln(ans);
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}

const inf = 10^^9+1;

void main()
{
  int n, a, b; readV(n, a, b);
  auto fvb = Fact(a, 1);

  struct FV { Fact f; int v; }
  FV[] fv;
  auto st = 0;
  foreach (i; 0..n) {
    int x, vx, vy; readV(x, vx, vy);
    if (vx == 0 && vy == 0) ++st;
    else if (vx == 0)       fv ~= FV(Fact(inf, 1), vy);
    else                    fv ~= FV(Fact(vy, vx), vx);
  }

  auto fvs = fv.sort!"a.f == b.f ? a.v < b.v : a.f < b.f";

  auto ans = 0L;
  foreach (fvi; fvs) {
    auto r = 0;
    if (fvi.f == fvb) {
      r += fvs.lowerBound(FV(fvi.f, fvi.v)).length;
      r += fvs.upperBound(FV(fvi.f, fvi.v)).length;
      r += st;
    } else {
      r += fvs.lowerBound(FV(fvi.f, -inf)).length;
      r += fvs.upperBound(FV(fvi.f,  inf)).length;
    }
    ans += r;
  }

  writeln(ans);
}

struct Fact
{
  long num, den;

  this(long num, long den)
  {
    if (den < 0) {
      this.num = -num;
      this.den = -den;
    } else {
      this.num = num;
      this.den = den;
    }
  }

  auto opCmp(Fact a)
  {
    auto r = num * a.den - a.num * den;
    return r < 0 ? -1 : r > 0 ? 1 : 0;
  }
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}

const inf = 10^^9+1;

void main()
{
  int n, a, b; readV(n, a, b);
  auto fvb = Fact(a, 1);

  struct FV { Fact f; int v; }
  FV[] fv;
  auto st = 0;
  foreach (i; 0..n) {
    int x, vx, vy; readV(x, vx, vy);
    if (vx == 0 && vy == 0) ++st;
    else if (vx == 0)       fv ~= FV(Fact(inf, 1), vy);
    else                    fv ~= FV(Fact(vy, vx), vx);
  }

  auto fvs = fv.sort!"a.f == b.f ? a.v < b.v : a.f < b.f";

  auto ans = 0L;
  foreach (fvi; fvs) {
    auto r = 0;
    if (fvi.f == fvb) {
      r += fvs.lowerBound(FV(fvi.f, fvi.v)).length;
      r += fvs.upperBound(FV(fvi.f, fvi.v)).length;
      r += st;
    } else {
      r += fvs.lowerBound(FV(fvi.f, -inf)).length;
      r += fvs.upperBound(FV(fvi.f,  inf)).length;
    }
    ans += r;
  }

  writeln(ans);
}

struct Fact
{
  long num, den;

  this(long num, long den)
  {
    if (den < 0) {
      this.num = -num;
      this.den = -den;
    } else {
      this.num = num;
      this.den = den;
    }
  }

  auto opCmp(Fact a)
  {
    return num * a.den - a.num * den;
  }
}


Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?

The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.

Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.

NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".

import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,
	core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
//import core.stdc.stdio;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;immutable int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	size_t lowb(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter
//------------------------------------------program beginning--------------------------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n;
loop:while(read(n))
	{
		auto s=new string[n];
		size_t k;
		foreach(i;0..n)
		{
			s[i]=readln.strip;
			k=s[i].length;
			s[i]~=s[i];
		}
		long ans=long.max/2;
		go:foreach(i;0..k)
		{
			string f=s[0][i..i+k];
			size_t p=0;
			foreach(j;s)
			{
				if(!find(j,f).empty)p+=j.length-find(j,f).length;
				else continue go;
			}
			ans=min(ans,p);
		}
		writeln((ans>=int.max)?-1:ans);
	}
	//debug system("pause");
}


Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.

In the first line of the input, you are given a single integer n (1 ≤ n ≤ 100) — the length of the side of the cake. Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.

Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.

NoteIf we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are:   (1, 2) and (1, 3)  (3, 1) and (3, 3)  Pieces that share the same column are:   (2, 1) and (3, 1)  (1, 3) and (3, 3)

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

struct IO {
        string read_string() {
                while (tokens.empty) {
                tokens = readln.split;
        }
        auto token = tokens.front;
                tokens.popFront;
                return token;
        }

        int read_int() {
                return read_string.to!int;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // int t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                char[][] mat = new char[][n];

                int comb = 0;
                //row-major traversal
                for (int i = 0; i < n; i++) {
                        int count = 0;
                        mat[i] = new char[n];
                        mat[i] = cin.read_string.dup;
                        for (int j = 0; j < n; j++) {
                                if (mat[i][j] == 'C') count++;
                        }
                        comb += (count * (count - 1)) / 2;
                }

                //column-major traversal
                for (int i = 0; i < n; i++) {
                        int count = 0;
                        for (int j = 0; j < n; j++) {
                                if (mat[j][i] == 'C') count++;
                        }
                        comb += (count * (count - 1)) / 2;
                }

                writeln(comb);
        }
}

import std.stdio;

void main()
{
	int n;

	scanf("%d", &n);

	char[][] m = new char[][n];

	for (int i = 0; i < n; i++) {
		m[i] = new char[n + 1];
		scanf("%s", m[i].ptr);
	}

	int res = 0;
	for (int i = 0; i < n; i++) {
		int r = 0;
		int c = 0;
		for (int j = 0; j < n; j++) {
			if (m[j][i] == 'C')
				c++;
			if (m[i][j] == 'C')
				r++;
		}

		res += (r - 1) * r / 2;
		res += (c - 1) * c / 2;
	}

	printf("%d\n", res);
}

import std.stdio;
import std.conv;
import std.string;
import std.array: Appender;
import std.datetime;
import std.algorithm;

void main()
{

	auto n = to!int(strip(readln));
	int[] r = new int[n];
	int[] c = new int[n];
	for (auto i = 0; i < n; i++)
	{
		auto str = strip(readln);
		foreach (j, ch; str)
		{
			if (ch == 'C')
			{
				r[i]++;
				c[j]++;
			}
		}
	}
	int count;
	foreach (i, ele; r)
	{
		count += (r[i] * (r[i] - 1)) / 2 + (c[i] * (c[i] - 1)) / 2;
	}

	writeln(count);
}

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

void main() {
    int n = readln.chomp.to!int;
    string[] cake;
    foreach (i; 0..n) {
        cake ~= readln.chomp;
    }

    int ans = 0;
    foreach (row; cake) {
        auto c = row.count!("a == 'C'");
        if (c > 1) {
            ans += c * (c - 1) / 2;
        }
    }

    foreach (col; cake.transposed) {
        auto c = col.count!("a == 'C'");
        if (c > 1) {
            ans += c * (c - 1) / 2;
        }
    }

    ans.writeln;
}


In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1, a2, ..., an. He remembered that he calculated gcd(ai, ai + 1, ..., aj) for every 1 ≤ i ≤ j ≤ n and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.

The first line contains a single integer m (1 ≤ m ≤ 1000) — the size of the set S. The second line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 106) — the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s1 < s2 < ... < sm.

If there is no solution, print a single line containing -1. Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000. In the second line print n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the sequence. We can show that if a solution exists, then there is a solution with n not exceeding 4000 and ai not exceeding 106. If there are multiple solutions, print any of them.

NoteIn the first example 2 = gcd(4, 6), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(ai, ai + 1, ..., aj) for every 1 ≤ i ≤ j ≤ n.

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

immutable int INF = 10L ^^ 9 + 23;

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

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

    s.sort();

    if (s.fold!gcd != s[0]) {
        writeln(-1);
        return;
    }

    int[] ans;
    foreach (e; s) {
        ans ~= e;
        ans ~= s[0];
    }

    ans.length.writeln;
    ans.writefln!"%(%s %)";
}

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

void main() {
    int m;
    scan(m);
    auto s = readln.split.to!(int[]);

    foreach (j ; 1 .. m) {
        if (s[j] % s[0]) {
            writeln(-1);
            return;
        }
    }

    auto ans = new int[](0);
    ans ~= s[0];

    foreach (i ; 1 .. m) {
        ans ~= s[i];
        ans ~= s[0];
    }

    int n = ans.length.to!int;

    writeln(n);
    writefln("%(%s %)",ans);
}

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

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

struct Queue(T) {
    private {
        int N, head, tail;
        T[] data;
    }

    this(int n) {
        N = n + 1;
        data = new T[](N);
    }

    bool empty() {
        return head == tail;
    }

    bool full() {
        return (tail + 1) % N == head;
    }

    T front() {
        return data[head];
    }

    void push(T x) {
        assert(!full);
        data[tail++] = x;
        tail %= N;
    }

    void pop() {
        assert(!empty);
        head = (head + 1) % N;
    }

    void clear() {
        head = tail = 0;
    }
}


There are $$$n$$$ districts in the town, the $$$i$$$-th district belongs to the $$$a_i$$$-th bandit gang. Initially, no districts are connected to each other.You are the mayor of the city and want to build $$$n-1$$$ two-way roads to connect all districts (two districts can be connected directly or through other connected districts).If two districts belonging to the same gang are connected directly with a road, this gang will revolt.You don't want this so your task is to build $$$n-1$$$ two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build $$$n-1$$$ roads to satisfy all the conditions.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of districts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the gang the $$$i$$$-th district belongs to. It is guaranteed that the sum of $$$n$$$ does not exceed $$$5000$$$ ($$$\sum n \le 5000$$$).

For each test case, print:   NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement.  YES on the first line and $$$n-1$$$ roads on the next $$$n-1$$$ lines. Each road should be presented as a pair of integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n; x_i \ne y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are two districts the $$$i$$$-th road connects.  For each road $$$i$$$, the condition $$$a[x_i] \ne a[y_i]$$$ should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).

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

ll[]  arr;
bool[] vis;
int[] par;

int dfs(int v){
    vis[v] = 1;
    int summ = 1;
    foreach(i; 0..arr.length){
        if(!vis[i] && arr[i] != arr[v]){
            par[i] = v;
            summ += dfs(i.to!int);
        }
    }
    return summ;
}

void play(){
    int n;
    n = rd!int;
    arr = rdarr;
    par = new int[n];
    vis = new bool[n];
    foreach(i; 0..n){
        par[] = 0;
        vis[] = 0;
        par[i] = -1;
        int found = dfs(i);
        if(found == n){

            writeln("YES");
            foreach(k; 0..n){
                if(par[k] != -1){
                    writeln(k+1, " ", par[k] + 1);
                }
            }
            return;
        }
    }
    writeln("NO");
}

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

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto c = n.iota.array;

		alias Edge = Tuple !(int, q{u}, int, q{v});
		Edge [] answer;
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				if (a[i] != a[j] && c[i] != c[j])
				{
					answer ~= Edge (i, j);
					int u = c[i];
					foreach (k; 0..n)
					{
						if (c[k] == u)
						{
							c[k] = c[j];
						}
					}
				}
			}
		}
		if (answer.length >= n - 1)
		{
			writeln ("YES");
			foreach (ref e; answer)
			{
				writeln (e.u + 1, " ", e.v + 1);
			}
		}
		else
		{
			writeln ("NO");
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		bool ok;
		foreach (i; 0..n)
		{
			if (a[i] != a[0])
			{
				ok = true;
				break;
			}
		}
		if (!ok) continue;

		auto used = new bool[](n*n);
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				if (a[i] != a[j])
				{
					auto u = min(i, j);
					auto v = max(i, j);
					if (!used[u*n+v])
					{
						used[u*n+v] = true;
						ans[ti] ~= [u, v];
					}
					break;
				}
			}
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			foreach (ee; e)
			{
				writeln(ee[0]+1, " ", ee[1]+1);
			}
		}
	}
	stdout.flush;
	debug readln;
}

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

void play(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    auto par = new ll[n];
    auto vis = new bool[n];
    vis[0] = 1; par[0] = -1;
    foreach(i; 0..n){
        if(!vis[i]){
            foreach(j; 0..n){
                if(vis[j] && arr[j] != arr[i]){
                    par[i] = j; vis[i] = 1;
                    break;
                }
            }
        }
        if(!vis[i]){
            writeln("NO");
            return;
        }
    }
    writeln("YES");
    foreach(i; 0..n){
        if(par[i] != -1){
            writeln(i+1, " ", par[i] + 1);
        }
    }
}

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

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


You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones and an integer $$$k$$$. In one operation you can do one of the following:  Select $$$2$$$ consecutive elements of $$$a$$$ and replace them with their minimum (that is, let $$$a := [a_{1}, a_{2}, \ldots, a_{i-1}, \min(a_{i}, a_{i+1}), a_{i+2}, \ldots, a_{n}]$$$ for some $$$1 \le i \le n-1$$$). This operation decreases the size of $$$a$$$ by $$$1$$$.  Select $$$k$$$ consecutive elements of $$$a$$$ and replace them with their maximum (that is, let $$$a := [a_{1}, a_{2}, \ldots, a_{i-1}, \max(a_{i}, a_{i+1}, \ldots, a_{i+k-1}), a_{i+k}, \ldots, a_{n}]$$$ for some $$$1 \le i \le n-k+1$$$). This operation decreases the size of $$$a$$$ by $$$k-1$$$. Determine if it's possible to turn $$$a$$$ into $$$[1]$$$ after several (possibly zero) operations.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 50$$$), the size of array $$$a$$$ and the length of segments that you can perform second type operation on. The second line contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$.

For each test case, if it is possible to turn $$$a$$$ into $$$[1]$$$, print "YES", otherwise print "NO".

NoteIn the first test case, you can perform the second type operation on second and third elements so $$$a$$$ becomes $$$[0, 1]$$$, then you can perform the second type operation on first and second elements, so $$$a$$$ turns to $$$[1]$$$.In the fourth test case, it's obvious to see that you can't make any $$$1$$$, no matter what you do.In the fifth test case, you can first perform a type 2 operation on the first three elements so that $$$a$$$ becomes $$$[1, 0, 0, 1]$$$, then perform a type 2 operation on the elements in positions two through four, so that $$$a$$$ becomes $$$[1, 1]$$$, and finally perform the first type operation on the remaining elements, so that $$$a$$$ becomes $$$[1]$$$.

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

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

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

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

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

        bool ans;
        foreach (i; 0 .. N) {
          ans = ans || (A[i] == 1);
        }
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		writeln (a.canFind (1) ? "YES" : "NO");
	}
}


As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length li.The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle .Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing. Help sculptor!

The first line contains an integer n (3 ≤ n ≤ 105) — a number of rod-blanks. The second line contains n integers li (1 ≤ li ≤ 109) — lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.

Print the only integer z — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.

NoteIn the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}. In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}.

import std.stdio, std.string, std.conv;
import std.typecons;
import std.algorithm;
import std.math;
void main(){
  int n = readln.chomp.to!int;
  auto ls = readln.chomp.split.map!(to!long);

  long s = 0;
  foreach(l; ls){
    s += l;
  }

  long m = 0;
  foreach(l; ls){
    m = max(m, l);
  }
  long res = abs(2*m-s)+1;

  writeln(res);

}

module main;

import std.stdio;
import std.algorithm;
import std.math;
import std.random;
import std.conv;

void main ()
{
    int n,sum = 0,add;
    readf(" %s", &n);
    int [] a =  new int [](n);
    for ( int i = 0; i < n; i++)
    {
        readf(" %s", &a[i]);
        sum += a[i];
    }
    for ( int i = 0; i< n; i++)
        if ( a[i] >= sum - a[i]) add = (abs(sum - 2*a[i])+ 1);
    writeln(add);

}

import std.stdio, std.string, std.conv;
import std.typecons;
import std.algorithm;
import std.math;
void main(){
  int n = readln.chomp.to!int;
  auto ls = readln.chomp.split.map!(to!long);

  long res = 0;
  foreach(long l; ls){
    res = abs (res - l);
  }

  writeln(res+1);

}


You are given a string $$$s$$$ consisting of the characters 0, 1, and ?.Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...).Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can replace the characters ? to 0 or 1 (for each character, the choice is independent), so that the string becomes unstable.For example, the strings 0??10, 0, and ??? are beautiful, and the strings 00 and ?1??1 are not.Calculate the number of beautiful contiguous substrings of the string $$$s$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of test cases. The first and only line of each test case contains the string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$) consisting of characters 0, 1, and ?. It is guaranteed that the sum of the string lengths over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of beautiful substrings of the string $$$s$$$.

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

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    auto a = readln.strip.split("").map!((x) => (x[0] == '?') ? 3 : (x[0] == '0' ? 1 : 2));
    auto dp = new long[][](a.length, 2);
    dp[0][0] = (a[0] & 1) ? 1 : 0;
    dp[0][1] = (a[0] & 2) ? 1 : 0;
    foreach (i ; 1 .. a.length) {
      dp[i][0] = (a[i] & 1) ? dp[i - 1][1] + 1 : 0;
      dp[i][1] = (a[i] & 2) ? dp[i - 1][0] + 1 : 0;
    }
    writeln(dp.fold!"a + b.maxElement"(0L));
  }
}

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

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    auto a = readln.strip.split("").map!((x) => (x[0] == '?') ? 3 : (x[0] == '0' ? 1 : 2));
//    writeln(a);
    long[][2] dp;
    bool[] avail;
    dp[0] = new long[](a.length);
    dp[1] = new long[](a.length);
    dp[0][0] = (a[0] & 1) ? 1 : 0;
    dp[1][0] = (a[0] & 2) ? 1 : 0;
    foreach (i ; 1 .. a.length) {
      if (a[i] & 1)
        dp[0][i] = dp[1][i - 1] + 1;
      else
        dp[0][i] = 0;
      if (a[i] & 2)
        dp[1][i] = dp[0][i - 1] + 1;
      else
        dp[1][i] = 0;
    }
//    writeln(dp);
    long result = 0;
    foreach (i ; 0 .. a.length) {
      result += max(dp[0][i], dp[1][i]);
    }
    writeln(result);
  }
}

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 s = readln.strip;
		auto n = s.length.to !(int);
		int prev = -1;
		int mark = -1;
		int odd = -3;
		long res = 0;
		foreach (i, c; s)
		{
			odd ^= 1;
			if (c != '?')
			{
				if (odd >= 0 && odd != c - '0')
				{
					prev = mark;
				}
				odd = c - '0';
				mark = i;
			}
			res += i - prev;
		}
		writeln (res);
	}
}

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

int main()
{
    int t = readInt!int;
    foreach(ti; 0 .. t)
    {
        string str = readString;
        auto a = new int[](str.length);
        foreach(i, ref ai; a)
            switch(str[i])
            {
            case '0': ai = 0 ^ (i & 1); continue;
            case '1': ai = 1 ^ (i & 1); continue;
            default: ai = -1; continue;
            }
        debug writeln(a);
        int c0 = 0;
        int c1 = 0;
        long result = 0;
        foreach(i, ai; a)
        {
            if (ai == 0) c0++, c1 = 0;
            if (ai == 1) c1++, c0 = 0;
            if (ai == -1) c0++, c1++;
            if (ai == 0) result += c0;
            if (ai == 1) result += c1;
            if (ai == -1) result += max(c0, c1);
        }
        result.writeln;
    }
    return 0;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
    currChar = getchar();
}
char topChar()
{
    return cast(char) currChar;
}
void popChar()
{
    currChar = getchar();
}
auto readInt(T)()
{
    T num = 0;
    int sgn = 0;
    while (topChar.isWhite) popChar;
    while (topChar == '-' || topChar == '+') { sgn ^= (topChar == '-'); popChar; }
    while (topChar.isDigit) { num *= 10; num += (topChar - '0'); popChar; }
    if (sgn) return -num; return num;
}
string readString()
{
    string res = "";
    while (topChar.isWhite) popChar;
    while (!topChar.isWhite) { res ~= topChar; popChar; }
    return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
    long rep;
    this(long num)
    {
        rep = num;
    }
    Z!m opBinary(string operator)(Z!m rhs)
    {
        static if (operator == "+")
        {
            long result = rhs.rep + this.rep;
            if (result >= m) result -= m;
            return Z!m(result);
        }
        else static if (operator == "-")
        {
            long result = this.rep - rhs.rep;
            if (result < 0) result += m;
            return Z!m(result);
        }
        else static if (operator == "*")
        {
            long result = this.rep * rhs.rep;
            if (result >= m) result %= m;
            return Z!m(result);
        } else static assert(text("Operator ", operator, " not supported"));
    }
    Z!m opBinary(string operator)(long exponent) if (operator == "^^")
    {
        assert(exponent >= 0);
        Z!m base = this;
        Z!m result = 1;
        while (exponent)
        {
            if (exponent & 1)
                result = result * base;
            base = base * base;
            exponent >>= 1;
        }
        return result;
    }
    invariant
    {
        assert(rep >= 0 && rep < m);
    }
}


So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem!Initially, each test in that problem is just an array. The maximum size of an array is $$$k$$$. For simplicity, the contents of arrays don't matter. You have $$$n$$$ tests — the $$$i$$$-th test is an array of size $$$m_i$$$ ($$$1 \le m_i \le k$$$).Your coordinator asks you to distribute all of your arrays into multiple testcases. Each testcase can include multiple arrays. However, each testcase should include no more than $$$c_1$$$ arrays of size greater than or equal to $$$1$$$ ($$$\ge 1$$$), no more than $$$c_2$$$ arrays of size greater than or equal to $$$2$$$, $$$\dots$$$, no more than $$$c_k$$$ arrays of size greater than or equal to $$$k$$$. Also, $$$c_1 \ge c_2 \ge \dots \ge c_k$$$.So now your goal is to create the new testcases in such a way that:   each of the initial arrays appears in exactly one testcase;  for each testcase the given conditions hold;  the number of testcases is minimum possible. Print the minimum possible number of testcases you can achieve and the sizes of arrays included in each testcase.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 2 \cdot 10^5$$$) — the number of initial tests and the limit for the size of each array. The second line contains $$$n$$$ integers $$$m_1, m_2, \dots, m_n$$$ ($$$1 \le m_i \le k$$$) — the sizes of the arrays in the original tests. The third line contains $$$k$$$ integers $$$c_1, c_2, \dots, c_k$$$ ($$$n \ge c_1 \ge c_2 \ge \dots \ge c_k \ge 1$$$); $$$c_i$$$ is the maximum number of arrays of size greater than or equal to $$$i$$$ you can have in a single testcase.

In the first line print a single integer $$$ans$$$ ($$$1 \le ans \le n$$$) — the minimum number of testcases you can achieve. Each of the next $$$ans$$$ lines should contain the description of a testcase in the following format: $$$t$$$ $$$a_1$$$ $$$a_2$$$ $$$\dots$$$ $$$a_{t}$$$ ($$$1 \le t\le n$$$) — the testcase includes $$$t$$$ arrays, $$$a_i$$$ is the size of the $$$i$$$-th array in that testcase. Each of the initial arrays should appear in exactly one testcase. In particular, it implies that the sum of $$$t$$$ over all $$$ans$$$ testcases should be equal to $$$n$$$. Note that the answer always exists due to $$$c_k \ge 1$$$ (and therefore $$$c_1 \ge 1$$$). If there are multiple answers, you can output any one of them.

NoteIn the first example there is no way to distribute the tests into less than $$$3$$$ testcases. The given answer satisfies the conditions: each of the testcases includes no more than $$$4$$$ arrays of size greater than or equal to $$$1$$$ and no more than $$$1$$$ array of sizes greater than or equal to $$$2$$$ and $$$3$$$.Note that there are multiple valid answers for this test. For example, testcases with sizes $$$[[2], [1, 2], [3]]$$$ would also be correct.However, testcases with sizes $$$[[1, 2], [2, 3]]$$$ would be incorrect because there are $$$2$$$ arrays of size greater than or equal to $$$2$$$ in the second testcase.Note the difference between the third and the fourth examples. You can include up to $$$5$$$ arrays of size greater than or equal to $$$1$$$ in the third example, so you can put all arrays into a single testcase. And you can have only up to $$$1$$$ array in the fourth example. Thus, every array should be included in a separate testcase.

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

void main ()
{
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto m = readln.splitter.map !(to !(int)).array;
		auto c = 0 ~ readln.splitter.map !(to !(int)).array;

		sort !(q{a > b}) (m);
		int [] [] answer;
		foreach (x; m)
		{
			int p = 0;
			int lo = 0;
			int hi = answer.length;
			while (lo < hi)
			{
				int me = (lo + hi) / 2;
				if (answer[me].length < c[x])
				{
					hi = me;
				}
				else
				{
					lo = me + 1;
				}
			}
			if (lo == answer.length)
			{
				answer ~= null;
			}
			answer[lo] ~= x;
		}

		writeln (answer.length);
		foreach (ref line; answer)
		{
			writefln !("%s%( %s%)") (line.length, line);
		}
	}
}

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

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

//alias T = Tuple!(int, int);
//alias TR = RedBlackTree!(T);
alias TR = RedBlackTree!(int, "a<b", true);

void main() {
  auto r = new InputReader ();
  const n = r.next!uint;
  const k = r.next!uint;
  auto _m = r.nextA!uint(n);
  auto m = assumeUnique (_m);
  auto _c = r.nextA!uint(k);
  auto c = assumeUnique (_c);
  int j = k - 1;
  auto x = new int[n+1];
  x[0] = k;
  foreach (t; 1 .. n + 1) {
    while (j >= 0 && c[j] == t) --j;
    x[t] = j + 1;
  }
  debug stderr.writeln (x);
  auto t = new TR;
  foreach (i, z; m) {
    //t.insert (T (z, 1 + i.to!int));
    t.insert (z);
  }
  int[][] ans;
  while (!t.empty) {
    int cur = 1;
    int[] b;
    while (cur <= n) {
      //auto rng = t.upperBound (T (x[cur], -1));
      auto rng = t.lowerBound (x[cur - 1] + 1);
      if (rng.empty) break;
      //auto q = m[rng.back];
      auto q = rng.back;
      b ~= q;
      t.removeKey (q);
      ++cur;
    }
    ans ~= b;
  }
  writeln (ans.length);
  foreach (const ref q; ans) {
    writefln!("%d %(%s %)")(q.length, q);
  }

}


In a medieval kingdom, the economic crisis is raging. Milk drops fall, Economic indicators are deteriorating every day, money from the treasury disappear. To remedy the situation, King Charles Sunnyface decided make his n sons-princes marry the brides with as big dowry as possible.In search of candidates, the king asked neighboring kingdoms, and after a while several delegations arrived with m unmarried princesses. Receiving guests, Karl learned that the dowry of the i th princess is wi of golden coins. Although the action takes place in the Middle Ages, progressive ideas are widespread in society, according to which no one can force a princess to marry a prince whom she does not like. Therefore, each princess has an opportunity to choose two princes, for each of which she is ready to become a wife. The princes were less fortunate, they will obey the will of their father in the matter of choosing a bride.Knowing the value of the dowry and the preferences of each princess, Charles wants to play weddings in such a way that the total dowry of the brides of all his sons would be as great as possible. At the same time to marry all the princes or princesses is not necessary. Each prince can marry no more than one princess, and vice versa, each princess can marry no more than one prince.Help the king to organize the marriage of his sons in the most profitable way for the treasury.

The first line contains two integers n, m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ 200 000) — number of princes and princesses respectively. Each of following m lines contains three integers ai, bi, wi (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ wi ≤ 10 000) — number of princes, which i-th princess is ready to marry and the value of her dowry.

Print the only integer — the maximum number of gold coins that a king can get by playing the right weddings.

/+ dub.sdl:
    name "F"
    dependency "dcomp" version=">=0.7.3"
+/

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

alias E = Tuple!(int, "to", int, "dist");
alias D = int;

int main() {
    Scanner sc = new Scanner(stdin);

    static struct PairingHeapAllAdd {
        alias NP = Node*;
        static struct Node {
            E e;
            D offset;
            NP head, next;
            this(E e) {
                this.e = e;
                offset = D(0);
            }
        }
        NP n;
        size_t length;
        this(E[] e) {
            length = e.length;
            foreach (d; e) {
                n = merge(n, new Node(d));
            }
        }
        static NP merge(NP x, NP y) {
            if (!x) return y;
            if (!y) return x;
            if (x.e.dist+x.offset < y.e.dist+y.offset) swap(x, y);
            y.offset -= x.offset;
            y.next = x.head;
            x.head = y;
            return x;
        }
        void C() { assert(n); }
        E front() {C; return n.e; }
        void removeFront() {
            assert(n);
            assert(length > 0);
            length--;
            NP x;
            NP s = n.head;
            while (s) {
                NP a, b;
                a = s; s = s.next; a.next = null; a.offset += n.offset;
                if (s) {
                    b = s; s = s.next; b.next = null; b.offset += n.offset;
                }
                a = merge(a, b);
                assert(a);
                if (!x) x = a;
                else {
                    a.next = x.next;
                    x.next = a;
                }
            }
            n = null;
            while (x) {
                NP a = x; x = x.next;
                n = merge(a, n);
            }
        }
        void meld(PairingHeapAllAdd r) {
            length += r.length;
            n = merge(n, r.n);
        }
        ref D offset() {C; return n.offset; }
    }

    int n, m;
    sc.read(n, m);
    E[][] g = new E[][n];
    foreach (i; 0..m) {
        int a, b, c;
        sc.read(a, b, c); a--; b--;
        g[a] ~= E(i, c);
        g[b] ~= E(i, c);
    }

    auto heap = new PairingHeapAllAdd[2*n];
    foreach (i; 0..n) {
//        writeln(i, " -> ", g[i]);
        heap[i] = PairingHeapAllAdd(g[i]);
    }

    int[] pre = new int[m]; pre[] = -1;
    bool[] fix = new bool[m];
    long sm = 0;
    int pc = n;
    foreach (i; 0..2*n) {
        if (i == pc) break;
        while (heap[i].length && fix[heap[i].front.to]) heap[i].removeFront;
        if (!heap[i].length) continue;
        auto e = heap[i].front;
        int c = e.dist;
        int x = i;
        if (pre[e.to] == -1) {
            sm += c;
            pre[e.to] = i;
            continue;
        }
        int y = pre[e.to];
        //merge x, y
        fix[e.to] = true;
        int P = pc++;
        heap[P].meld(heap[x]);
        heap[P].meld(heap[y]);
    }

    writeln(sm);
    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.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);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    import core.bitop : bsf, bsr, popcnt;
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

// import dcomp.array;

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;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    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) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                FastAppender!(E[]) buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(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);
        }
    }
}

/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/array.d */
// module dcomp.array;

T[N] fixed(T, size_t N)(T[N] a) {return a;}

struct FastAppender(A, size_t MIN = 4) {
    import std.algorithm : max;
    import std.conv;
    import std.range.primitives : ElementEncodingType;
    import core.stdc.string : memcpy;

    private alias T = ElementEncodingType!A;
    private T* _data;
    private uint len, cap;

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

    void reserve(size_t nlen) {
        import core.memory : GC;
        if (nlen <= cap) return;

        void* nx = GC.malloc(nlen * T.sizeof);

        cap = nlen.to!uint;
        if (len) memcpy(nx, _data, len * T.sizeof);
        _data = cast(T*)(nx);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void opOpAssign(string op : "~")(T item) {
        if (len == cap) {
            reserve(max(MIN, cap*2));
        }
        _data[len++] = item;
    }

    void insertBack(T item) {
        this ~= item;
    }

    void removeBack() {
        len--;
    }

    void clear() {
        len = 0;
    }
    ref inout(T) back() inout { assert(len); return _data[len-1]; }
    ref inout(T) opIndex(size_t i) inout { return _data[i]; }

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

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

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

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

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

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

alias Edge = Tuple!(int, "a", int, "b", long, "w");

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      auto E = new Edge[M];
      foreach (i; 0 .. M) {
        E[i].a = readInt() - 1;
        E[i].b = readInt() - 1;
        E[i].w = readLong();
      }

      E.sort!"a.w < b.w";

      auto uf = new int[N];
      uf[] = -1;
      auto ms = new int[N];
      long ans;
      foreach_reverse (ref e; E) {
        const ra = uf.root(e.a);
        const rb = uf.root(e.b);
        if (ra == rb) {
          if (ms[ra] < -uf[ra]) {
            debug {
              writeln(e, " make cycle");
            }
            ans += e.w;
            ++ms[ra];
          }
        } else {
          if (ms[ra] < -uf[ra] || ms[rb] < -uf[rb]) {
            debug {
              writeln(e, " connect");
            }
            ans += e.w;
            uf.connect(ra, rb);
            const int r = uf.root(ra);
            ms[r] = ms[ra] + ms[rb] + 1;
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You have n devices that you want to use simultaneously.The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.You have a single charger that can plug to any single device. The charger will add p units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·p units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.

The first line contains two integers, n and p (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 109) — the number of devices and the power of the charger. This is followed by n lines which contain two integers each. Line i contains the integers ai and bi (1 ≤ ai, bi ≤ 100 000) — the power of the device and the amount of power stored in the device in the beginning.

If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .

NoteIn sample test 1, you can charge the first device for the entire time until it hits zero power. The second device has enough power to last this time without being charged.In sample test 2, you can use the device indefinitely.In sample test 3, we can charge the third device for 2 / 5 of a second, then switch to charge the second device for a 1 / 10 of a second.

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;

alias Tuple!(double, "a", double, "b") Device;

void main() {
    auto s = readln.split;
    auto N = s[0].to!int;
    auto P = s[1].to!real;
    auto pi = s[1].to!long;
    auto D = new Device[](N);
    long ss = 0;
    foreach (i; 0..N) {
        s = readln.split;
        D[i] = Device(s[0].to!real, s[1].to!real);
        ss += s[0].to!long;
    }

    if (ss <= pi) {
        writeln(-1);
        return;
    }

    real hi = 10L^^18;
    real lo = 0;
    foreach (_; 0..200) {
        real mid = (hi + lo) / 2;
        real x = 0;
        foreach (i; 0..N) x += max(0, (D[i].a * mid - D[i].b) / P);
        if (x <= mid) lo = mid;
        else hi = mid;

    }

    writefln("%.9f", hi);
}

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;

alias Tuple!(double, "a", double, "b") Device;

void main() {
    auto s = readln.split;
    auto N = s[0].to!int;
    auto P = s[1].to!real;
    auto pi = s[1].to!long;
    auto D = new Device[](N);
    long ss = 0;
    foreach (i; 0..N) {
        s = readln.split;
        D[i] = Device(s[0].to!real, s[1].to!real);
        ss += s[1].to!long;
    }

    if (ss <= pi) {
        writeln(-1);
        return;
    }

    real hi = 10L^^12;
    real lo = 0;
    foreach (_; 0..200) {
        real mid = (hi + lo) / 2;
        real x = 0;
        foreach (i; 0..N) x += max(0, (D[i].a * mid - D[i].b) / P);
        if (x <= mid) lo = mid;
        else hi = mid;

    }

    writefln("%.9f", hi);
}


Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm  ×  h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?

The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000). Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.

After each cut print on a single line the area of the maximum available glass fragment in mm2.

NotePicture for the first sample test:    Picture for the second sample test:

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

void main ()
{
	int w, h, n;
	while (readf (" %s %s %s", &w, &h, &n) > 0)
	{
		enum HORIZ = 0, VERT = 1;
		alias Query = Tuple !(int, q{t}, int, q{c});
		auto q = new Query [n];
		foreach (ref z; q)
		{
			char ch;
			readf (" %s %s", &ch, &z.c);
			z.t = (ch == 'H');
		}
		q ~= Query (HORIZ, 0);
		q ~= Query (HORIZ, w);
		q ~= Query (VERT, 0);
		q ~= Query (VERT, h);
		auto u = q.filter !(z => z.t == HORIZ)
		    .map !(q{a.c}).array.sort !(q{a < b}, SwapStrategy.stable);
		auto v = q.filter !(z => z.t == VERT)
		    .map !(q{a.c}).array.sort !(q{a < b}, SwapStrategy.stable);

		auto aprev = new int [w + 1];
		auto anext = new int [w + 1];
		long ma = 0;
		foreach (i; 1..u.length)
		{
			aprev[u[i]] = u[i - 1];
			anext[u[i - 1]] = u[i];
			ma = max (ma, u[i] - u[i - 1]);
		}
		auto bprev = new int [h + 1];
		auto bnext = new int [h + 1];
		long mb = 0;
		foreach (j; 1..v.length)
		{
			bprev[v[j]] = v[j - 1];
			bnext[v[j - 1]] = v[j];
			mb = max (mb, v[j] - v[j - 1]);
		}

		long [] ans;
		foreach_reverse (z; q[0..n])
		{
			debug {writeln (ma, ' ', mb);}
			ans ~= ma * mb;
			if (z.t == HORIZ)
			{
				int alo = aprev[z.c];
				int ahi = anext[z.c];
				ma = max (ma, ahi - alo);
				aprev[ahi] = alo;
				anext[alo] = ahi;
			}
			else if (z.t == VERT)
			{
				int blo = bprev[z.c];
				int bhi = bnext[z.c];
				mb = max (mb, bhi - blo);
				bprev[bhi] = blo;
				bnext[blo] = bhi;
			}
			else
			{
				assert (false);
			}
		}
		writefln ("%(%s\n%)", ans.retro);
	}
}