There are $$$n$$$ athletes in front of you. Athletes are numbered from $$$1$$$ to $$$n$$$ from left to right. You know the strength of each athlete — the athlete number $$$i$$$ has the strength $$$s_i$$$.You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $$$A$$$ and $$$B$$$ so that the value $$$|\max(A) - \min(B)|$$$ is as small as possible, where $$$\max(A)$$$ is the maximum strength of an athlete from team $$$A$$$, and $$$\min(B)$$$ is the minimum strength of an athlete from team $$$B$$$.For example, if $$$n=5$$$ and the strength of the athletes is $$$s=[3, 1, 2, 6, 4]$$$, then one of the possible split into teams is:   first team: $$$A = [1, 2, 4]$$$,  second team: $$$B = [3, 6]$$$. In this case, the value $$$|\max(A) - \min(B)|$$$ will be equal to $$$|4-3|=1$$$. This example illustrates one of the ways of optimal split into two teams.Print the minimum value $$$|\max(A) - \min(B)|$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case consists of two lines.  The first line contains positive integer $$$n$$$ ($$$2 \le n \le 50$$$) — number of athletes.  The second line contains $$$n$$$ positive integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 1000$$$), where $$$s_i$$$ — is the strength of the $$$i$$$-th athlete. Please note that $$$s$$$ values may not be distinct.

For each test case print one integer — the minimum value of $$$|\max(A) - \min(B)|$$$ with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams.

NoteThe first test case was explained in the statement. In the second test case, one of the optimal splits is $$$A=[2, 1]$$$, $$$B=[3, 2, 4, 3]$$$, so the answer is $$$|2-2|=0$$$.

import std.stdio;
import std.string : split, strip;
import std.algorithm : map, sort, minElement;
import std.conv : to;
import std.array;
import std.range : dropOne, zip;

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!int).array;
    a.sort;

    writeln(minElement(a.zip(a.dropOne).map!"a[1] - a[0]"));
  }
}

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[] s;

  void solve(long tc = -1)
  {
    sort(s);
    writeln(iota(0, n - 1).map!(i => abs(s.at(i) - s.at(i + 1))).fold!min(long.max));
  }
}

struct Interval
{
  long l, h;

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

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


The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column).    The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.

Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.

4
1 1
L
1 2
L
3 3
RRDLUU
4 3
LUURRDDLLLUU

import std.stdio;
import std.conv;
import std.string;
import std.algorithm;
import std.algorithm.searching;
import std.algorithm.sorting;
import std.math;

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

    // per testcase
    for (int t = 0; t < cases; t++) {
        int n, m;
        readf!"%d %d\n"(n, m);

        string s;
        readf!"%s\n"(s);
        char[] instructions = s.dup;

        int x = 0;
        int y = 0;
        int min_x = 0;
        int min_y = 0;
        int max_x = 0;
        int max_y = 0;
        int x_size = 1;
        int y_size = 1;
        int offset_x = 0;
        int offset_y = 0;

        for (int i = 0; i < instructions.length; i++) {
            switch (instructions[i]) {
                case 'R':
                    x ++;
                    break;
                case 'L':
                    x --;
                    break;
                case 'D':
                    y ++;
                    break;
                case 'U':
                    y --;
                    break;
                default:
                    break;
            }

            bool xflag = false;
            bool yflag = false;
            if (min_x > x) {
                xflag = true;
                min_x = x;
            }
            if (min_y > y) {
                yflag = true;
                min_y = y;
            }
            if (max_x < x) {
                max_x = x;
            }
            if (max_y < y) {
                max_y = y;
            }

            x_size = max_x - min_x + 1;
            y_size = max_y - min_y + 1;
            // writeln(to!string(instructions[i]) ~ " " ~ to!string(x_size) ~ " " ~ to!string(y_size));
            if (x_size > m) break;
            if (y_size > n) break;

            if (xflag) offset_x += 1;
            if (yflag) offset_y += 1;
        }

        writeln(to!string(offset_y + 1) ~ " " ~ to!string(offset_x + 1));
    }
}

// Author: Ivan Kazmenko (gassa@mail.ru)
module solution;
import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int dirs = 4;
immutable int  [dirs] dRow  = [ -1,   0,  +1,   0];
immutable int  [dirs] dCol  = [  0,  -1,   0,  +1];
immutable char [dirs] dName = ['U', 'L', 'D', 'R'];

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		auto s = readln.strip;
		int rLo = 0;
		int rHi = 0;
		int cLo = 0;
		int cHi = 0;
		int r = 0;
		int c = 0;
		foreach (ref cur; s)
		{
			auto dir = dName[].countUntil (cur);
			r += dRow[dir];
			c += dCol[dir];
			auto trLo = min (rLo, r);
			auto trHi = max (rHi, r);
			auto tcLo = min (cLo, c);
			auto tcHi = max (cHi, c);
			if (trHi - trLo >= rows)
			{
				break;
			}
			if (tcHi - tcLo >= cols)
			{
				break;
			}
			rLo = trLo;
			rHi = trHi;
			cLo = tcLo;
			cHi = tcHi;
		}
		writeln (1 - rLo, " ", 1 - cLo);
	}
}

import std.stdio;
import std.conv;
import std.string;
import std.algorithm;
import std.algorithm.searching;
import std.algorithm.sorting;
import std.math;

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

    // per testcase
    for (int t = 0; t < cases; t++) {
        int n, m;
        readf!"%d %d\n"(n, m);

        string s;
        readf!"%s\n"(s);
        char[] instructions = s.dup;

        int x = 0;
        int y = 0;
        int min_x = 0;
        int min_y = 0;
        int max_x = 0;
        int max_y = 0;
        int x_size = 1;
        int y_size = 1;
        int offset_x = 0;
        int offset_y = 0;

        for (int i = 0; i < instructions.length; i++) {
            switch (instructions[i]) {
                case 'R':
                    x ++;
                    break;
                case 'L':
                    x --;
                    break;
                case 'D':
                    y ++;
                    break;
                case 'U':
                    y --;
                    break;
                default:
                    break;
            }

            bool xflag = false;
            bool yflag = false;
            if (min_x > x) {
                xflag = true;
                min_x = x;
            }
            if (min_y > y) {
                yflag = true;
                min_y = y;
            }
            if (max_x < x) {
                max_x = x;
            }
            if (max_y > y) {
                max_y = y;
            }

            x_size = max_x - min_x + 1;
            y_size = max_y - min_y + 1;
            if (x_size > m) break;
            if (y_size > n) break;

            if (xflag) offset_x += 1;
            if (yflag) offset_y += 1;
        }

        writeln(to!string(offset_y + 1) ~ " " ~ to!string(offset_x + 1));
    }
}


Gottfried learned about binary number representation. He then came up with this task and presented it to you.You are given a collection of $$$n$$$ non-negative integers $$$a_1, \ldots, a_n$$$. You are allowed to perform the following operation: choose two distinct indices $$$1 \leq i, j \leq n$$$. If before the operation $$$a_i = x$$$, $$$a_j = y$$$, then after the operation $$$a_i = x~\mathsf{AND}~y$$$, $$$a_j = x~\mathsf{OR}~y$$$, where $$$\mathsf{AND}$$$ and $$$\mathsf{OR}$$$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).After all operations are done, compute $$$\sum_{i=1}^n a_i^2$$$ — the sum of squares of all $$$a_i$$$. What is the largest sum of squares you can achieve?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$0 \leq a_i < 2^{20}$$$).

Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.

NoteIn the first sample no operation can be made, thus the answer is $$$123^2$$$.In the second sample we can obtain the collection $$$1, 1, 7$$$, and $$$1^2 + 1^2 + 7^2 = 51$$$.If $$$x$$$ and $$$y$$$ are represented in binary with equal number of bits (possibly with leading zeros), then each bit of $$$x~\mathsf{AND}~y$$$ is set to $$$1$$$ if and only if both corresponding bits of $$$x$$$ and $$$y$$$ are set to $$$1$$$. Similarly, each bit of $$$x~\mathsf{OR}~y$$$ is set to $$$1$$$ if and only if at least one of the corresponding bits of $$$x$$$ and $$$y$$$ are set to $$$1$$$. For example, $$$x = 3$$$ and $$$y = 5$$$ are represented as $$$011_2$$$ and $$$101_2$$$ (highest bit first). Then, $$$x~\mathsf{AND}~y = 001_2 = 1$$$, and $$$x~\mathsf{OR}~y = 111_2 = 7$$$.

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

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

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

    immutable int MX = 22;

    auto cnt = new int[] (MX);
    foreach (e; arr) {

        foreach (b; 0 .. MX) {
            if (e & (1 << b)) { cnt[b] += 1; }
        }
    }

    auto ans = 0L;
    foreach (i; 1 .. n+1) {
        int cur = 0;
        foreach (b; 0 .. MX) {
            if (cnt[b] >= i) { cur += (1 << b); }
        }

        ans += cur.to!long * cur;
    }

    ans.writeln;
}

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

immutable int bits = 20;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		int [bits] s;
		foreach (k; 0..bits)
		{
			s[k] = a.count !(x => (x & (1 << k)) != 0).to !(int);
		}

		long res = 0;
		foreach (i; 0..n)
		{
			int cur = 0;
			foreach (k; 0..bits)
			{
				if (s[k] > i)
				{
					cur |= (1 << k);
				}
			}
			res += cur * 1L * cur;
		}
		writeln (res);
	}
}

// Code By H~$~C

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

void _Main() {
  int n;
  readf!" %d\n"(n);
  int[] a = readln.splitter.map!(to!int).array;
  int[][20] b;
  foreach(j; 0 .. 20) {
    b[j] = new int[n];
  }
  foreach(i; 0 .. n) {
    foreach(j; 0 .. 20) {
      b[j][i] = ((a[i] >> j) & 1);
    }
  }
  foreach(j; 0 .. 20) {
    b[j].sort!"a > b";
  }
  long ans = 0;
  foreach(i; 0 .. n) {
    long x = 0;
    foreach(j; 0 .. 20) {
      x += ((b[j][i]) << j);
    }
    ans += x * x;
  }
  writeln(ans);
}

void main(string[] args) {
  int tests = 1;
//  readf!" %d"(tests);
  foreach (test; 0 .. tests) _Main();
}

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 E = 25;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }

      auto bs = new long[N];
      foreach (e; 0 .. E) {
        int cnt;
        foreach (i; 0 .. N) {
          if ((A[i] >> e) & 1) {
            ++cnt;
          }
        }
        debug {
          writeln(e, ": ", cnt);
        }
        foreach (i; 0 .. cnt) {
          bs[i] |= 1L << e;
        }
      }

      long ans;
      foreach (i; 0 .. N) {
        ans += bs[i]^^2;
      }
      writeln(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); }

void main()
{
	auto n = RD!int;
	auto a = RDA;

	auto cnt = new int[](20);
	foreach (i; 0..n)
	{
		foreach (j; 0..20)
		{
			auto bit = 1L << j;
			if (a[i] & bit)
			{
				++cnt[j];
			}
		}
	}

	long ans;
	foreach (i; 0..n)
	{
		long t;
		foreach (j; 0..20)
		{
			if (cnt[j])
			{
				t += 1L << j;
				--cnt[j];
			}
		}
		ans += t^^2;
	}

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

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

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

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

    foreach (i; 0 .. n-1) {
        auto le = arr[i] & arr[i+1];
        auto r = arr[i] | arr[i+1];

        arr[i] = le;
        arr[i+1] = r;
    }

    auto ans = arr.map!(x => x.to!long * x).sum(0L);

    ans.writeln;
}

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

string FMT_F = "%.10f";

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

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

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

//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 n = RD!int;
	auto a = RDA;

	a.sort!"a > b";
	auto zero = new int[][](20);
	foreach (i; 0..n)
	{
		foreach (j; 0..20)
		{
			auto bit = 1L << j;
			if (!(a[i] & bit))
			{
				zero[j] ~= i;
			}
		}
	}

	foreach_reverse (i; 0..n)
	{
		auto x = a[i];
		foreach_reverse (j; 0..20)
		{
			auto bit = 1L << j;
			if (x & bit)
			{
				int pos = n;
				while (!zero[j].empty)
				{
					if (pos < i) break;
					pos = zero[j].front; zero[j].popFront;
				}
				if (pos == n) continue;

				auto y = a[pos] & a[i];
				a[pos] |= a[i];
				a[i] = y;
			}
		}
	}

	long ans;
	foreach (i; 0..n)
		ans += a[i]^^2;

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;

	a.sort!"a > b";
	auto zero = new int[][](20);
	foreach (i; 0..n)
	{
		foreach (j; 0..20)
		{
			auto bit = 1L << j;
			if (!(a[i] & bit))
			{
				zero[j] ~= i;
			}
		}
	}

	foreach_reverse (i; 0..n)
	{
		auto x = a[i];
		bool[int] used;
		foreach_reverse (j; 0..20)
		{
			auto bit = 1L << j;
			if (x & bit)
			{
				int pos = n;
				while (!zero[j].empty)
				{
					if (pos < i) break;
					pos = zero[j].front; zero[j].popFront;
				}
				if (pos == n) continue;
				if (used.get(pos, false)) continue;
				used[pos] = true;
				auto y = a[pos] & a[i];
				a[pos] |= a[i];
				a[i] = y;
			}
		}
	}

	long ans;
	foreach (i; 0..n)
		ans += a[i]^^2;

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


Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet — it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.However, his max-flow algorithm seems to have a little flaw — it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.More formally. You are given an undirected graph. For each it's undirected edge (ai, bi) you are given the flow volume ci. You should direct all edges in such way that the following conditions hold:  for each vertex v (1 < v < n), sum of ci of incoming edges is equal to the sum of ci of outcoming edges;  vertex with number 1 has no incoming edges;  the obtained directed graph does not have cycles.

The first line of input contains two space-separated integers n and m (2 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105), the number of vertices and edges in the graph. The following m lines contain three space-separated integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 104), which means that there is an undirected edge from ai to bi with flow volume ci. It is guaranteed that there are no two edges connecting the same vertices; the given graph is connected; a solution always exists.

Output m lines, each containing one integer di, which should be 0 if the direction of the i-th edge is ai → bi (the flow goes from vertex ai to vertex bi) and should be 1 otherwise. The edges are numbered from 1 to m in the order they are given in the input. If there are several solutions you can print any of them.

NoteIn the first test case, 10 flow units pass through path , and 5 flow units pass directly from source to sink: .

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

struct E {
  int id, to, cap;
  bool dir;
}

void main()
{
  auto input = readln().split().map!(to!int)();
  auto edge = new E[][](input[0]);
  auto flow = new int[](input[0]);
  auto flow_in = new int[](input[0]);
  auto dir = new int[](input[1]);
  dir[] = -1;

  foreach (i; 0 .. input[1]) {
    auto e = readln().split().map!(to!int)().array();
    edge[--e[0]] ~= E(i, --e[1], e[2], 0);
    edge[e[1]] ~= E(i, e[0], e[2], 1);
    flow[e[0]] += e[2];
    flow[e[1]] += e[2];
  }

  auto q = DList!int([0]);

  while (!q.empty()) {
    auto i = q.front();
    q.stableRemoveFront();

    foreach (e; edge[i]) {
      if (dir[e.id] != -1) continue;
      dir[e.id] = e.dir;
      flow_in[e.to] += e.cap;
      if (flow_in[e.to] * 2 == flow[e.to] && e.to != input[0] - 1) {
        q.stableInsertBack(e.to);
      }
    }
  }

  dir.map!(to!string)().join("\n").writeln();
}

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

struct E {
  int id, to, cap;
  bool dir;
}

void main()
{
  auto input = readln().split().map!(to!int)();
  auto edge = new E[][](input[0]);
  auto flow = new int[](input[0]);
  auto flow_in = new int[](input[0]);

  foreach (i; 0 .. input[1]) {
    auto e = readln().split().map!(to!int)().array();
    edge[--e[0]] ~= E(i, --e[1], e[2], 0);
    edge[e[1]] ~= E(i, e[0], e[2], 1);
    flow[e[0]] += e[2];
    flow[e[1]] += e[2];
  }

  auto dir = new int[](input[1]);
  dir[] = -1;

  auto q = DList!int([0]);

  while (!q.empty()) {
    auto i = q.front();
    q.stableRemoveFront();

    foreach (ref e; edge[i]) {
      if (dir[e.id] != -1) continue;
      dir[e.id] = e.dir;
      flow_in[e.to] += e.cap;
      if (flow_in[e.to] * 2 == flow[e.to]) {
        q.stableInsertBack(e.to);
      }
    }
  }

  dir.map!(to!string)().join("\n").writeln();
}


The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.

For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.

9
arrayhead
5
arya
harry
ray
r
areahydra

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;

int cvt (dchar c) {
  return (c.to!int - 97);
}

void main() {
  immutable n = readln.strip.to!int;
  string s = readln.strip;
  auto idx = new int[][26];
  foreach (i; 0 .. n) {
    int o = cvt (s[i]);
    idx[o] ~= i + 1;
  }
  immutable m = readln.strip.to!int;
  debug stderr.writeln (m);
  foreach (qid; 0 .. m) {
    string t = readln.strip;
    int[26] c;
    foreach (ch; t) {
      ++c[cvt (ch)];
    }
    int res;
    foreach (i; 0 .. 26) {
      if (c[i] > 0) {
        res = max (res, idx[i][c[i]-1]);
      }
    }
    writeln (res);
  }
}

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

string FMT_F = "%.10f";

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

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

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

size_t binarySearch(alias pred, T)(in T[] arr, bool isLower = true)
{
	long ok, ng;
	if (isLower) { ok = arr.length; ng = -1; }
	else		 { ok = 0; ng = arr.length; }
	while (abs(ok-ng) > 1)
	{
		size_t mid = cast(size_t)(ok+ng) / 2;
		if (unaryFun!pred(arr[mid]))
			ok = mid;
		else ng = mid;
	}
	return cast(size_t)ok;
}

void main()
{
	auto n = RD!int;
	auto s = RD!string;
	auto cnt = new int[][](s.length+1, 26);
	foreach (i; 0..s.length)
	{
		auto c = cnt[i].dup;
		++c[s[i]-'a'];
		cnt[i+1] = c;
	}
	auto m = RD!int;
	foreach (i; 0..m)
	{
		auto t = RD!string;
		auto cnt2 = new int[](26);
		foreach (c; t)
		{
			++cnt2[c-'a'];
		}
		bool check(in int[] cnt1)
		{
			foreach (j; 0..cnt1.length)
			{
				if (cnt1[j] < cnt2[j])
					return false;
			}
			return true;
		}
		auto pos = binarySearch!(check)(cnt);
		writeln(pos);
	}

	stdout.flush();
	debug readln();
}

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;

alias T = Tuple!(int, int);

int cvt (dchar c) {
  return 1 << (c.to!int - 48);
}

void main() {
  immutable n = readln.strip.to!int;
  string s = readln.strip;
  T[] h;
  int mask;
  foreach (i; 0 .. n) {
    int o = mask | cvt (s[i]);
    if (o != mask) {
      mask = o;
      h ~= tuple (mask, i + 1);
    }
  }
  immutable m = readln.strip.to!int;
  foreach (qid; 0 .. m) {
    string t = readln.strip;
    mask = t.fold! ( (acc, x) => acc | cvt (x))(0);
    foreach (p; h) {
      if ((p[0] & mask) == mask) {
        writeln (p[1]);
        break;
      }
    }
  }
}

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;

alias T = Tuple!(int, int);

int cvt (dchar c) {
  return 1 << (c.to!int - 97);
}

void main() {
  immutable n = readln.strip.to!int;
  string s = readln.strip;
  T[] h;
  int mask;
  foreach (i; 0 .. n) {
    int o = mask | cvt (s[i]);
    if (o != mask) {
      mask = o;
      h ~= tuple (mask, i + 1);
    }
  }
  immutable m = readln.strip.to!int;
  foreach (qid; 0 .. m) {
    string t = readln.strip;
    mask = t.fold! ( (acc, x) => acc | cvt (x))(0);
    foreach (p; h) {
      if ((p[0] & mask) == mask) {
        writeln (p[1]);
        break;
      }
    }
  }
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n = RD!int;
	auto s = RD!string;
	auto m = RD!int;
	foreach (i; 0..m)
	{
		auto t = RD!string;
		bool[char] set;
		foreach (c; t)
		{
			set[c] = true;
		}
		auto len = set.keys.length;
		foreach (j, c; s)
		{
			if (set.get(c, false))
			{
				--len;
				set[c] = false;
				if (len == 0)
				{
					writeln(j+1);
					break;
				}
			}
		}
	}

	stdout.flush();
	debug readln();
}


Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset.k experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.Determine if Snark and Philip can make an interesting problemset!

The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 4) — the number of problems and the number of experienced teams. Each of the next n lines contains k integers, each equal to 0 or 1. The j-th number in the i-th line is 1 if j-th team knows i-th problem and 0 otherwise.

Print "YES" (quotes for clarity), if it is possible to make an interesting problemset, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").

NoteIn the first example you can't make any interesting problemset, because the first team knows all problems.In the second example you can choose the first and the third problems.

import std.algorithm, std.conv, std.range, std.stdio;
void main () {
	readln;
	int [int] s;
	string t;
	while ((t = readln.split.join) > "") s[t.to!int (2)]++;
	writeln (s.byKey.any !(x => s.byKey.any !(y => !(x & y))) ? "YES" : "NO");
}

import std.algorithm, std.conv, std.range, std.stdio;
void main () {
	int n, k;
	readf (" %s %s ", &n, &k);
	auto m = 1 << k, d = new int [m];
	foreach (i; 0..n) d[readln.split.join.to!int (2)]++;
	writeln (m.iota.any !(x => m.iota.any !(y => d[x] && d[y] && !(x & y))) ? "YES" : "NO");
}

import core.bitop;
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;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto k2 = 1 << k;
		auto d = new int [k2];
		foreach (i; 0..n)
		{
			auto a = readln.split.join.to !(int) (2);
			d[a] += 1;
		}
		debug {writeln (d);}

		bool res = false;
		foreach (i; 0..k2)
		{
			foreach (j; 0..k2)
			{
				if (d[i] && d[j] && !(i & j))
				{
					res = true;
				}
			}
		}
		writeln (res ? "YES" : "NO");
	}
}

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

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

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

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

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

      auto fs = new int[1 << 4];
      foreach (i; 0 .. N) {
        int x;
        foreach (k; 0 .. K) {
          x |= (A[i][k] ^ 1) << k;
        }
        foreach (k; K .. 4) {
          x |= 1 << k;
        }
        ++fs[x];
      }
      debug {
        writeln("fs = ", fs);
      }

      bool ans;
      if (fs[(1 << 4) - 1] > 0) {
        ans = true;
      }
      foreach (p; 0 .. 1 << 4) foreach (q; p + 1 .. 1 << 4) {
        if (fs[p] > 0 && fs[q] > 0) {
          if ((p | q) == (1 << 4) - 1) {
            ans = true;
          }
        }
      }
      writeln(ans ? "YES" : "NO");
    }
  } catch (EOFException e) {
  }
}

import std.algorithm, std.conv, std.range, std.stdio;
void main () {
	readln;
	int [int] s;
	string t;
	while ((t = readln.split.join) > "") s[t.to!int]++;
	writeln (s.byKey.any !(x => s.byKey.any !(y => !(x & y))) ? "YES" : "NO");
}


Arkady the air traffic controller is now working with n planes in the air. All planes move along a straight coordinate axis with Arkady's station being at point 0 on it. The i-th plane, small enough to be represented by a point, currently has a coordinate of xi and is moving with speed vi. It's guaranteed that xi·vi < 0, i.e., all planes are moving towards the station.Occasionally, the planes are affected by winds. With a wind of speed vwind (not necessarily positive or integral), the speed of the i-th plane becomes vi + vwind.According to weather report, the current wind has a steady speed falling inside the range [ - w, w] (inclusive), but the exact value cannot be measured accurately since this value is rather small — smaller than the absolute value of speed of any plane.Each plane should contact Arkady at the exact moment it passes above his station. And you are to help Arkady count the number of pairs of planes (i, j) (i < j) there are such that there is a possible value of wind speed, under which planes i and j contact Arkady at the same moment. This value needn't be the same across different pairs.The wind speed is the same for all planes. You may assume that the wind has a steady speed and lasts arbitrarily long.

The first line contains two integers n and w (1 ≤ n ≤ 100 000, 0 ≤ w < 105) — the number of planes and the maximum wind speed. The i-th of the next n lines contains two integers xi and vi (1 ≤ |xi| ≤ 105, w + 1 ≤ |vi| ≤ 105, xi·vi < 0) — the initial position and speed of the i-th plane. Planes are pairwise distinct, that is, no pair of (i, j) (i < j) exists such that both xi = xj and vi = vj.

Output a single integer — the number of unordered pairs of planes that can contact Arkady at the same moment.

NoteIn the first example, the following 3 pairs of planes satisfy the requirements:   (2, 5) passes the station at time 3 / 4 with vwind = 1;  (3, 4) passes the station at time 2 / 5 with vwind = 1 / 2;  (3, 5) passes the station at time 4 / 7 with vwind =  - 1 / 4. In the second example, each of the 3 planes with negative coordinates can form a valid pair with each of the other 3, totaling 9 pairs.

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 bAdd(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    bit[x] += val;
  }
}

// sum of [0, pos)
T bSum(T)(T[] bit, int pos)
in {
  assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold");
}
do {
  T ret = 0;
  for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
    ret += bit[x];
  }
  return ret;
}

struct Rat {
  long p, q;
  this(long p, long q = 1) {
    if (q < 0) { p = -p; q = -q; }
    const g = std.numeric.gcd(abs(p), q);
    this.p = p / g;
    this.q = q / g;
  }
  bool opEquals(Rat a) const { return (p * a.q == a.p * q); }
  long opCmp(Rat a) const { return p * a.q - a.p * q; }
  string toString() const { return p.to!string ~ "/" ~ q.to!string; }
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const W = readLong();
      auto X = new long[N];
      auto V = new long[N];
      foreach (i; 0 .. N) {
        X[i] = readLong();
        V[i] = readLong();
      }

      alias Entry = Tuple!(Rat, "t", int, "id");
      auto eas = new Entry[N];
      auto ebs = new Entry[N];
      foreach (i; 0 .. N) {
        eas[i] = Entry(Rat(X[i], V[i] - W), i);
        ebs[i] = Entry(Rat(X[i], V[i] + W), i);
      }
      eas.sort;
      ebs.sort;
      debug {
        writeln("eas = ", eas);
        writeln("ebs = ", ebs);
      }

      int A, B;
      auto as = new int[N];
      auto bs = new int[N];
      for (int i = 0, j; i < N; i = j) {
        for (j = i; j < N && eas[i].t == eas[j].t; ++j) {
          as[eas[j].id] = A;
        }
        ++A;
      }
      for (int i = 0, j; i < N; i = j) {
        for (j = i; j < N && ebs[i].t == ebs[j].t; ++j) {
          bs[ebs[j].id] = B;
        }
        ++B;
      }
      debug {
        writeln("as = ", as);
        writeln("bs = ", bs);
      }

      auto iss = new int[][A];
      foreach (i; 0 .. N) {
        iss[as[i]] ~= i;
      }

      long ans;
      auto bit = new int[B];
      foreach (a; 0 .. A) {
        // count same a
        const num = cast(long)(iss[a].length);
        ans += num * (num - 1) / 2;
        // count different a
        foreach (i; iss[a]) {
          ans += bit.bSum(B) - bit.bSum(bs[i]);
        }
        // add
        foreach (i; iss[a]) {
          bit.bAdd(bs[i], 1);
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display. The second line contains n digits — the initial state of the display.

Print a single line containing n digits — the desired state of the display containing the smallest possible number.

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    int N; scanf("%d\n", &N);
    auto X = readln.chomp;

    string ans = cast(string)cycle("9").take(N).array;
    string C(int i) {
        char[] Y = (X[i .. $] ~ X[0 .. i]).dup;
        int d = X[i] == '0' ? 0 : 10 - cast(int)(X[i] - '0');
        foreach (j; 0 .. N) {
            Y[j] = cast(char)( (Y[j] - '0' + d) % 10 + '0' );
        }
        return Y.idup;
    }

    foreach (i; 0 .. N) {
        ans = min(ans, C(i));
    }
    writeln(ans);
}


Today DZY begins to play an old game. In this game, he is in a big maze with n rooms connected by m corridors (each corridor allows to move in both directions). You can assume that all the rooms are connected with corridors directly or indirectly.DZY has got lost in the maze. Currently he is in the first room and has k lives. He will act like the follows:  Firstly he will randomly pick one of the corridors going from his current room. Each outgoing corridor has the same probability to be picked.  Then he will go through the corridor and then the process repeats. There are some rooms which have traps in them. The first room definitely has no trap, the n-th room definitely has a trap. Each time DZY enters one of these rooms, he will lost one life. Now, DZY knows that if he enters the n-th room with exactly 2 lives, firstly he will lost one live, but then he will open a bonus round. He wants to know the probability for him to open the bonus round. Please, help him.

The first line contains three integers n, m, k (2 ≤ n ≤ 500; 1 ≤ m ≤ 105; 2 ≤ k ≤ 109). The second line contains n integers, each of them is either 0 or 1. If the i-th number is 1, then the i-th room has a trap, otherwise it has not a trap. Please note, that the number of rooms with a trap is no more than 101. It is guaranteed that the first room has no trap, and the n-th room has a trap. Then m lines follows. Each of them contains two integers ui, vi (1 ≤ ui, vi ≤ n; ui ≠ vi), meaning that current corridor connects two rooms ui and vi. It is guaranteed that the corridor system is connected.

Print the only real number — the probability for DZY to open the bonus round. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4.

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

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

//	chmin/chmax
void chmin(T)(ref T t, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

real[][] mul(real[][] a, real[][] b) {
	const n = a.length;
	real[][] ret = new real[][](n, n);
	foreach (i; 0 .. n) {
		ret[i][] = 0.0;
	}
	foreach (i; 0 .. n) foreach (k; 0 .. n) foreach (j; 0 .. n) {
		ret[i][j] += a[i][k] * b[k][j];
	}
	return ret;
}

int N, M, K;
bool[] S;
int[] A, B;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		M = readInt;
		K = readInt;
		S = new bool[N];
		foreach (u; 0 .. N) {
			S[u] = (readInt != 0);
		}
		A = new int[M];
		B = new int[M];
		foreach (i; 0 .. M) {
			A[i] = readInt - 1;
			B[i] = readInt - 1;
		}

		int[] us;
		foreach (u; 0 .. N) {
			if (u == 0 || S[u]) {
				us ~= u;
			}
		}
		int[] ids = new int[N];
		ids[] = -1;
		foreach (j, u; us) {
			ids[u] = j;
		}

		int[][] G = new int[][N];
		foreach (i; 0 .. M) {
			G[A[i]] ~= B[i];
			G[B[i]] ~= A[i];
		}

		real[][] a = new real[][](N, N + us.length);
		foreach (u; 0 .. N) {
			a[u][] = 0.0;
			if (S[u]) {
				a[u][u] = 1.0;
				a[u][N + ids[u]] = 1.0;
			} else {
				a[u][u] -= G[u].length;
				foreach (v; G[u]) {
					a[u][v] += 1.0;
				}
			}
		}
// writeln(a);

		foreach (h; 0 .. N) {
			int im = h;
			foreach (i; h + 1 .. N) {
				if (abs(a[im][h]) < abs(a[i][h])) {
					im = i;
				}
			}
			swap(a[h], a[im]);
			a[h][h .. $] /= a[h][h];
			foreach (i; h + 1 .. N) {
				a[i][h .. $] -= a[h][h .. $] * a[i][h];
			}
		}
		foreach_reverse (h; 0 .. N) {
			foreach (i; h + 1 .. N) {
				a[h][i .. $] -= a[i][i .. $] * a[h][i];
			}
		}
// writeln(a);

		real[][] prob = new real[][](us.length, us.length);
		foreach (i; 0 .. us.length) foreach (j; 0 .. us.length) {
			//	from us[j] to us[i]
			prob[i][j] = 0.0;
			foreach (v; G[us[j]]) {
				prob[i][j] += a[v][N + i];
			}
			prob[i][j] /= G[us[j]].length;
		}
// writeln("prob = ",prob);

		real[][] y = new real[][](us.length, us.length);
		foreach (i; 0 .. us.length) {
			y[i][] = 0.0;
			y[i][i] = 1.0;
		}
		for (int e = K - 1; e; e >>= 1, prob = mul(prob, prob)) if (e & 1) {
			y = mul(y, prob);
		}
		writefln("%.10f", y[$ - 1][0]);
	}
	} catch (EOFException) {}
}


You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $$$n$$$ seconds and at the $$$i$$$-th second the color $$$s_i$$$ is on.That way, the order of the colors is described by a string. For example, if $$$s=$$$"rggry", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on.More formally, you are given a string $$$s_1, s_2, \ldots, s_n$$$ of length $$$n$$$. At the first second the color $$$s_1$$$ is on, at the second — $$$s_2$$$, ..., at the $$$n$$$-th second the color $$$s_n$$$ is on, at the $$$n + 1$$$-st second the color $$$s_1$$$ is on and so on.You need to cross the road and that can only be done when the green color is on. You know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road.You can assume that you cross the road immediately. For example, with $$$s=$$$"rggry" and the current color r there are two options: either the green color will be on after $$$1$$$ second, or after $$$3$$$. That way, the answer is equal to $$$3$$$ — that is the number of seconds that we are guaranteed to cross the road, if the current color is r.

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. Then the description of the test cases follows. The first line of each test case contains an integer $$$n$$$ and a symbol $$$c$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$c$$$ is one of allowed traffic light colors r, y or g)— the length of the string $$$s$$$ and the current color of the traffic light.  The second line of each test case contains a string $$$s$$$ of the length $$$n$$$, consisting of the letters r, y and g. It is guaranteed that the symbol g is in the string $$$s$$$ and the symbol $$$c$$$ is in the string $$$s$$$.  It is guaranteed, that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case output the minimal number of second in which you are guaranteed to cross the road.

6

5 r

rggry

1 g

g

3 r

rrg

5 y

yrrgy

7 r

rgrgyrg

9 y

rrrgyyygy

NoteThe first test case is explained in the statement.In the second test case the green color is on so you can cross the road immediately. In the third test case, if the red color was on at the second second, then we would wait for the green color for one second, and if the red light was on at the first second, then we would wait for the green light for two seconds.In the fourth test case the longest we would wait for the green color is if we wait for it starting from the fifth second.

import std.stdio;
import std.math;
import std.numeric;
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;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void solve() {
    int n;
    char r;
    readf!" %d %c "(n, r);
    //scanf("%d %c\n", &n, &r);
    auto s = readln.strip;
    if (r == 'g') {
        writeln(0);
        return;
    }
    long fromStart;
    bool foundG, countR;
    long tmp, maxD;
    foreach(i, el; s) {
        if (el == 'g') {
            foundG = true;
            if (tmp > maxD)
                maxD = tmp;
            countR = false;
            tmp = 0;
        }
        if (el == r)
            countR = true;
        if (countR)
            tmp++;
        if (!foundG)
            fromStart++;
    }
    if (countR)
        writeln(max(maxD, tmp+fromStart));
    else
        writeln(maxD);

}

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

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

// Lengths of sequences satisfying the condition (moving to the right)
int[] seq_length_right(alias less = "a < b", T)(T[] a)
{
  if (a.length == 0)
    return new int[](0);
  auto tmp = new int[](a.length);
  int count = 1;
  tmp[$ - 1] = count;
  foreach_reverse (i ; 0 .. a.length - 1) {
    if (binaryFun!less(a[i], a[i + 1]))
      count++;
    else
      count = 1;
    tmp[i] = count;
  }
  return tmp;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto tmp = readln.split.array;
    auto n = tmp[0].to!long;
    auto ch = tmp[1].strip[0];
    auto s = readln.strip;
    auto ss = s ~ s;
    if (ch == 'g') {
      writeln(0);
      continue;
    }
    auto a = ss.seq_length_right!((a, b) => a != 'g')();
    long ans = 0;
    foreach (i ; 0 .. a.length) {
      if (ss[i] == ch)
        ans = max(a[i], ans);
    }
    writeln(ans - 1);
  }
}


Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.

The first line contains three integers L, b и f (10 ≤ L ≤ 100000, 1 ≤ b, f ≤ 100). The second line contains an integer n (1 ≤ n ≤ 100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.

For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.

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 L, b, f;
    readf("%s %s %s", &L, &b, &f);
    readln;

    int q;
    readf("%s", &q);
    readln;

    auto pos = new int[] (q+1);
    pos[] = -1;
    auto sz = new int[] (q+1);
    sz[] = 0;
    int [int] places;
    places[-b] = 0;
    places[L + f] = 0;

    foreach (i; 1 .. q+1) {
        int t, x;
        readf("%s %s", &t, &x);
        readln;

        if (t == 1) {
            sz[i] = x;

            auto keysSorted = places.keys.sort();

            foreach (prv, nxt; lockstep(keysSorted, keysSorted.dropOne)) {
                debug { writeln(prv, ' ', nxt); }

                if (x > (nxt - f) - (prv + sz[places[prv]] + b)) { continue; }

                pos[i] = prv + sz[places[prv]] + b;
                places[pos[i]] = i;

                break;
            }

            writeln(pos[i]);
        } else {
            places.remove(pos[x]);
        }
    }
}


There are $$$n$$$ models in the shop numbered from $$$1$$$ to $$$n$$$, with sizes $$$s_1, s_2, \ldots, s_n$$$.Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices $$$i_j$$$ and $$$i_{j+1}$$$ (note that $$$i_j < i_{j+1}$$$, because Orac arranged them properly), $$$i_{j+1}$$$ is divisible by $$$i_j$$$ and $$$s_{i_j} < s_{i_{j+1}}$$$.For example, for $$$6$$$ models with sizes $$$\{3, 6, 7, 7, 7, 7\}$$$, he can buy models with indices $$$1$$$, $$$2$$$, and $$$6$$$, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful.Orac wants to know the maximum number of models that he can buy, and he may ask you these queries many times.

The first line contains one integer $$$t\ (1 \le t\le 100)$$$: the number of queries. Each query contains two lines. The first line contains one integer $$$n\ (1\le n\le 100\,000)$$$: the number of models in the shop, and the second line contains $$$n$$$ integers $$$s_1,\dots,s_n\ (1\le s_i\le 10^9)$$$: the sizes of models. It is guaranteed that the total sum of $$$n$$$ is at most $$$100\,000$$$.

Print $$$t$$$ lines, the $$$i$$$-th of them should contain the maximum number of models that Orac can buy for the $$$i$$$-th query.

NoteIn the first query, for example, Orac can buy models with indices $$$2$$$ and $$$4$$$, the arrangement will be beautiful because $$$4$$$ is divisible by $$$2$$$ and $$$6$$$ is more than $$$3$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than two models. In the second query, Orac can buy models with indices $$$1$$$, $$$3$$$, and $$$6$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than three models. In the third query, there are no beautiful arrangements with more than one model.

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto N = readln.chomp.to!int;
        auto ss = readln.split.to!(int[]);
        auto DP = new int[](N+1);
        foreach_reverse (i; 1..N+1) {
            int x = i * 2, n = 1;
            while (x <= N) {
                if (ss[x-1] > ss[i-1]) n = max(n, DP[x] + 1);
                x += i;
            }
            DP[i] = n;
        }
        int r;
        foreach (ref e; DP) r = max(r, e);
        writeln(r);
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = 1;
		auto dp = new int[][](n, 21);
		foreach (i; 0..n)
			dp[i][] = int.max;
		foreach (i; 0..n/2)
		{
			dp[i][0] = s[i];
		}
		foreach (int to; 1..n+1)
		{
			int[] index;
			for (long from = 1; from*from <= to; ++from)
			{
				if (to % from) continue;
				index ~= cast(int)from;
				index ~= cast(int)(to / from);
			}
			foreach (from; index)
			{
				foreach (k; 0..20)
				{
					if (dp[from-1][k] < s[to-1])
					{
						dp[to-1][k+1].chmin(s[to-1]);
					}
				}
			}
		}
		(){
		foreach_reverse (i; 0..21)
		{
			foreach (j; 0..n)
			{
				if (dp[j][i] != int.max)
				{
					ans[ti] = i+1;
					return;
				}
			}
		}}();
	}

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


Gildong is playing a video game called Block Adventure. In Block Adventure, there are $$$n$$$ columns of blocks in a row, and the columns are numbered from $$$1$$$ to $$$n$$$. All blocks have equal heights. The height of the $$$i$$$-th column is represented as $$$h_i$$$, which is the number of blocks stacked in the $$$i$$$-th column.Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the $$$1$$$-st column. The goal of the game is to move the character to the top of the $$$n$$$-th column.The character also has a bag that can hold infinitely many blocks. When the character is on the top of the $$$i$$$-th column, Gildong can take one of the following three actions as many times as he wants:   if there is at least one block on the column, remove one block from the top of the $$$i$$$-th column and put it in the bag;  if there is at least one block in the bag, take one block out of the bag and place it on the top of the $$$i$$$-th column;  if $$$i < n$$$ and $$$|h_i - h_{i+1}| \le k$$$, move the character to the top of the $$$i+1$$$-st column. $$$k$$$ is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column. In actions of the first two types the character remains in the $$$i$$$-th column, and the value $$$h_i$$$ changes.The character initially has $$$m$$$ blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le 10^6$$$, $$$0 \le k \le 10^6$$$) — the number of columns in the game, the number of blocks in the character's bag at the beginning, and the non-negative integer $$$k$$$ described in the statement. The second line of each test case contains $$$n$$$ integers. The $$$i$$$-th integer is $$$h_i$$$ ($$$0 \le h_i \le 10^6$$$), the initial height of the $$$i$$$-th column.

For each test case, print "YES" if it is possible to win the game. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first case, Gildong can take one block from the $$$1$$$-st column, move to the $$$2$$$-nd column, put the block on the $$$2$$$-nd column, then move to the $$$3$$$-rd column.In the second case, Gildong has to put the block in his bag on the $$$1$$$-st column to get to the $$$2$$$-nd column. But it is impossible to get to the $$$3$$$-rd column because $$$|h_2 - h_3| = 3 > k$$$ and there is no way to decrease the gap.In the fifth case, the character is already on the $$$n$$$-th column from the start so the game is won instantly.

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 t;
    readf("%s", &t);
    readln;

    while (t--) {
        int n, m, k;
        readf("%s %s %s", &n, &m, &k);
        readln;

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

        bool ok = true;
        foreach (a, b; lockstep(hs, hs.dropOne)) {
            if (a + m < b - k) {
                ok = false;
                break;
            }

            if (a > b - k) { m += a - max(b-k, 0); }
            else { m -= b-k - a; }
        }

        writeln(ok ? "YES" : "NO");
    }
}

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

void solve(){
	int t = read.to!int;

A:
	foreach(_; 0 .. t){
		int n = read.to!int;
		long m = read.to!long;
		long k = read.to!long;
		long[] hs;
		foreach(i; 0 .. n) hs ~= read.to!long;
		log("t:", t, "n:", n, "m:", m, "k:", k, "hs:", hs);

		foreach(i; 0 .. n - 1){
			log("i:", i, "m:", m, "hs[i]:", hs[i], "hs[i + 1]:", hs[i + 1]);
			if(hs[i] + m < hs[i + 1] - k){
				"NO".writeln;
				continue A;
			}
			else{
				long h = hs[i + 1] - k;
				if(h < 0) h = 0;
				if(hs[i] > h) m += hs[i] - h;
				else m -= h - hs[i];
				log("h:", h, "m:", m);
			}
		}
		"YES".writeln;
	}
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto m = RD;
		auto k = RD;
		auto h = RDA;
		bool tmp = true;
		foreach (j; 1..n)
		{
			auto d = k - (h[j] - h[j-1]);
			m += min(d, h[j-1]);
			if (m < 0)
			{
				tmp = false;
				break;
			}
		}
		ans[i] = tmp;
	}

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

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 t;
    readf("%s", &t);
    readln;

    while (t--) {
        int n, m, k;
        readf("%s %s %s", &n, &m, &k);
        readln;

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

        bool ok = true;
        foreach (a, b; lockstep(hs, hs.dropOne)) {
            if (a + m < b - k) {
                ok = false;
                break;
            }

            if (a > b - k) { m += a - (b-k); }
            else { m -= b-k - a; }
        }

        writeln(ok ? "YES" : "NO");
    }
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto k = RD!int;
		auto h = RDA;
		bool tmp = true;
		foreach (j; 1..n)
		{
			auto d = k - (h[j] - h[j-1]);
			m += d;
			if (m < 0)
			{
				tmp = false;
				break;
			}
		}
		ans[i] = tmp;
	}

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

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto m = RD;
		auto k = RD;
		auto h = RDA;
		bool tmp = true;
		foreach (j; 1..n)
		{
			auto d = k - (h[j] - h[j-1]);
			m += d;
			if (m < 0)
			{
				tmp = false;
				break;
			}
		}
		ans[i] = tmp;
	}

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


Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug.Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers:  1 li ri vi — for each x such that li ≤ x ≤ ri ax ≥ vi;  2 li ri vi — for each x such that li ≤ x ≤ ri ax ≤ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows:, where cnt(i) is the number of occurences of i in the array.Help Ivan to determine minimum possible cost of the array that corresponds to the facts!

The first line contains two integer numbers n and q (1 ≤ n ≤ 50, 0 ≤ q ≤ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n, 1 ≤ vi ≤ n, ti denotes the type of the fact).

If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array.

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;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto Q = s[1];
    auto A = new Tuple!(int, int)[](N);
    A.fill(tuple(0, N-1));

    while (Q--) {
        s = readln.split.map!(to!int);
        if (s[0] == 1)
            foreach (i; s[1]-1..s[2]) A[i][0] = max(A[i][0], s[3] - 1);
        else
            foreach (i; s[1]-1..s[2]) A[i][1] = min(A[i][1], s[3] - 1);
    }

    int V = N + N * N;
    int source = V;
    int sink = V + 1;
    auto mcf = new MinCostFlow(V + 2);

    foreach (i; 0..N) {
        mcf.add_edge(source, N*N+i, 1, 0);
        foreach (j; A[i][0]..A[i][1]+1) {
            foreach (k; 0..N) {
                mcf.add_edge(N*N+i, j*N+k, 1, (k+1)^^2 - k^^2);
            }
        }
    }

    foreach (i; 0..N*N) {
        mcf.add_edge(i, sink, 1, 0);
    }

    mcf.run(source, sink, N).writeln;
}

class MinCostFlow {
    alias Tuple!(int, "to", int, "cap", int, "cost", int, "rev") Edge;
    immutable int INF = 1 << 29;

    int V;
    Edge[][] G;
    int[] h;
    int[] dist;
    int[] prevv;
    int[] preve;

    this(int v) {
        V = v;
        G = new Edge[][](v);
        h = new int[](v);
        dist = new int[](v);
        prevv = new int[](v);
        preve = new int[](v);
    }

    void add_edge(int from, int to, int cap, int cost) {
        G[from] ~= Edge(to, cap, cost, G[to].length.to!int);
        G[to] ~= Edge(from, 0, -cost, G[from].length.to!int - 1);
    }

    int run(int s, int t, int f) { // source, sink, flow
        int res = 0;
        h.fill(0);
        while (f > 0) {
            auto pq = new BinaryHeap!(Array!(Tuple!(int, int)), "a[0] < b[0]");
            dist.fill(INF);
            dist[s] = 0;
            pq.insert(tuple(0, s));
            while (!pq.empty) {
                auto p = pq.front;
                pq.removeFront;
                int v = p[1];
                if (dist[v] < p[0]) continue;
                foreach (i; 0..G[v].length.to!int) {
                    auto e = G[v][i];
                    if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
                        dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
                        prevv[e.to] = v;
                        preve[e.to] = i;
                        pq.insert(tuple(dist[e.to], e.to));
                    }
                }
            }
            if (dist[t] == INF) {
                return -1;
            }
            foreach (v; 0..V) {
                h[v] += dist[v];
            }

            int d = f;
            for (int v = t; v != s; v = prevv[v]) {
                d = min(d, G[prevv[v]][preve[v]].cap);
            }
            f -= d;
            res += d * h[t];
            for (int v = t; v != s; v = prevv[v]) {
                G[prevv[v]][preve[v]].cap -= d;
                G[v][G[prevv[v]][preve[v]].rev].cap += d;
            }
        }

        return res;
    }
}


After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $$$n$$$. Let's call them $$$a$$$ and $$$b$$$.Note that a permutation of $$$n$$$ elements is a sequence of numbers $$$a_1, a_2, \ldots, a_n$$$, in which every number from $$$1$$$ to $$$n$$$ appears exactly once. The message can be decoded by an arrangement of sequence $$$a$$$ and $$$b$$$, such that the number of matching pairs of elements between them is maximum. A pair of elements $$$a_i$$$ and $$$b_j$$$ is said to match if:   $$$i = j$$$, that is, they are at the same index.  $$$a_i = b_j$$$ His two disciples are allowed to perform the following operation any number of times:   choose a number $$$k$$$ and cyclically shift one of the permutations to the left or right $$$k$$$ times. A single cyclic shift to the left on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$$$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$$$ simultaneously.Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.

The first line of the input contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ — the size of the arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le n)$$$ — the elements of the first permutation. The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le n)$$$ — the elements of the second permutation.

Print the maximum number of matching pairs of elements after performing the above operations some (possibly zero) times.

NoteFor the first case: $$$b$$$ can be shifted to the right by $$$k = 1$$$. The resulting permutations will be $$$\{1, 2, 3, 4, 5\}$$$ and $$$\{1, 2, 3, 4, 5\}$$$.For the second case: The operation is not required. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$1$$$.For the third case: $$$b$$$ can be shifted to the left by $$$k = 1$$$. The resulting permutations will be $$$\{1, 3, 2, 4\}$$$ and $$$\{2, 3, 1, 4\}$$$. Positions $$$2$$$ and $$$4$$$ have matching pairs of elements. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$2$$$.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto p = readln.splitter.map !(to !(int)).array;
		auto q = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		q[] -= 1;
		auto rp = new int [n];
		auto rq = new int [n];
		foreach (i; 0..n)
		{
			rp[p[i]] = i;
			rq[q[i]] = i;
		}
		int [int] delta;
		foreach (j; 0..n)
		{
			delta[(n + rp[j] - rq[j]) % n] += 1;
		}
		delta.byValue.maxElement.writeln;
	}
}

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

string FMT_F = "%.10f";

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

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

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

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 n = RD!int;
	auto a = RDA;
	auto b = RDA;

	auto index1 = a.MAKE_IDX;
	auto index2 = b.MAKE_IDX;

	auto cnt = new long[](n);
	foreach (i; 0..n)
	{
		auto d = cast(long)index1[i] - cast(long)index2[i];
		if (d < 0)
			d = n + d;
		++cnt[cast(int)d];
	}
	auto ans = cnt[cnt.MIN_POS!"a > b"];

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

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto p = readln.splitter.map !(to !(int)).array;
		auto q = readln.splitter.map !(to !(int)).array;
		auto cp = new int [n];
		auto cq = new int [n];
		foreach (i; 0..n)
		{
			cp[(n + p[i] - i) % n] += 1;
			cq[(n + q[i] - i) % n] += 1;
		}
		writeln (min (cp.maxElement, cq.maxElement));
	}
}