Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by $$$n$$$ characters '(' or ')' is simple if its length $$$n$$$ is even and positive, its first $$$\frac{n}{2}$$$ characters are '(', and its last $$$\frac{n}{2}$$$ characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.

The only line of input contains a string $$$s$$$ ($$$1 \le |s| \le 1000$$$) formed by characters '(' and ')', where $$$|s|$$$ is the length of $$$s$$$.

In the first line, print an integer $$$k$$$  — the minimum number of operations you have to apply. Then, print $$$2k$$$ lines describing the operations in the following format: For each operation, print a line containing an integer $$$m$$$  — the number of characters in the subsequence you will remove. Then, print a line containing $$$m$$$ integers $$$1 \le a_1 < a_2 < \dots < a_m$$$  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string. If there are multiple valid sequences of operations with the smallest $$$k$$$, you may print any of them.

NoteIn the first sample, the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '(((', and no more operations can be performed on it. Another valid answer is choosing indices $$$2$$$ and $$$3$$$, which results in the same final string.In the second sample, it is already impossible to perform any operations.

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

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		int i = 0;
		int j = s.length.to !(int) - 1;
		int [] ans;
		while (true)
		{
			while (i < j && s[i] != '(')
			{
				i += 1;
			}
			while (i < j && s[j] != ')')
			{
				j -= 1;
			}
			if (i >= j)
			{
				break;
			}
			ans ~= i;
			ans ~= j;
			i += 1;
			j -= 1;
		}
		ans[] += 1;
		sort (ans);
		writefln !("%d") (ans.length > 0);
		if (!ans.empty)
		{
			writeln (ans.length);
			writefln !("%(%s %)") (ans);
		}
	}
}

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

void main() {
  auto s = readln.stripRight;
  const l = s.length.to!int;
  auto b = new bool[l];
  int[][] ans;
  while (true) {
    int i = 0, j = l - 1;
    int[] u, v;
    while (true) {
      while (i < l && (b[i] || s[i] != '(')) ++i;
      while (j >= 0 && (b[j] || s[j] != ')')) --j;
      if (i > j) break;
      u ~= i + 1;
      v ~= j + 1;
      b[i] = b[j] = true;
    }
    reverse (v);
    u ~= v;
    if (u.empty) break;
    ans ~= u;
  }
  writeln (ans.length);
  foreach (p; ans) {
    writeln (p.length);
    writefln ("%(%s %)", p);
  }

}

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 S = readToken();
      const L = cast(int)(S.length);

      auto sums = new int[][](2, L + 1);
      foreach (i; 0 .. L) {
        sums[0][i + 1] = sums[0][i] + ((S[i] == '(') ? 1 : 0);
        sums[1][i + 1] = sums[1][i] + ((S[i] == ')') ? 1 : 0);
      }
      int mn = L + 1;
      int km = -1;
      foreach (k; 0 .. L + 1) {
        if (sums[0][k] == sums[1][L] - sums[1][k]) {
          if (chmin(mn, sums[0][k])) {
            km = k;
          }
        }
      }
      assert(km != -1);
      if (mn == 0) {
        writeln(0);
      } else {
        int[] ans;
        foreach (i; 0 .. km) if (S[i] == '(') ans ~= i;
        foreach (i; km .. L) if (S[i] == ')') ans ~= i;
        writeln(1);
        writeln(ans.length);
        foreach (index, i; ans) {
          if (index > 0) write(" ");
          write(i + 1);
        }
        writeln();
      }
    }
  } 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 = 998244353;
//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 s = RD!string;
	int[] ans1, ans2;
	int l, r = cast(int)s.length-1;
	foreach (i; 0..s.length)
	{
		if (s[i] == '(') break;
		++l;
	}
	foreach_reverse (i; 0..s.length)
	{
		if (s[i] == ')') break;
		--r;
	}
	while (l < r)
	{
		ans1 ~= l+1;
		ans2 ~= r+1;
		++l; --r;
		foreach (i; l..s.length)
		{
			if (s[i] == '(') break;
			++l;
		}
		foreach_reverse (i; 0..r+1)
		{
			if (s[i] == ')') break;
			--r;
		}
	}
	ans2.sort();

	if (ans1.empty && ans2.empty)
	{
		writeln(0);
	}
	else
	{
		writeln(1);
		writeln(ans1.length + ans2.length);
		(ans1~ans2).map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}


You are given a rooted tree of $$$2^n - 1$$$ vertices. Every vertex of this tree has either $$$0$$$ children, or $$$2$$$ children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect binary tree.The vertices of the tree are numbered in the following order:  the root has index $$$1$$$;  if a vertex has index $$$x$$$, then its left child has index $$$2x$$$, and its right child has index $$$2x+1$$$. Every vertex of the tree has a letter written on it, either A or B. Let's define the character on the vertex $$$x$$$ as $$$s_x$$$.Let the preorder string of some vertex $$$x$$$ be defined in the following way:  if the vertex $$$x$$$ is a leaf, then the preorder string of $$$x$$$ be consisting of only one character $$$s_x$$$;  otherwise, the preorder string of $$$x$$$ is $$$s_x + f(l_x) + f(r_x)$$$, where $$$+$$$ operator defines concatenation of strings, $$$f(l_x)$$$ is the preorder string of the left child of $$$x$$$, and $$$f(r_x)$$$ is the preorder string of the right child of $$$x$$$. The preorder string of the tree is the preorder string of its root.Now, for the problem itself...You have to calculate the number of different strings that can be obtained as the preorder string of the given tree, if you are allowed to perform the following operation any number of times before constructing the preorder string of the tree:  choose any non-leaf vertex $$$x$$$, and swap its children (so, the left child becomes the right one, and vice versa).

The first line contains one integer $$$n$$$ ($$$2 \le n \le 18$$$). The second line contains a sequence of $$$2^n-1$$$ characters $$$s_1, s_2, \dots, s_{2^n-1}$$$. Each character is either A or B. The characters are not separated by spaces or anything else.

Print one integer — the number of different strings that can be obtained as the preorder string of the given tree, if you can apply any number of operations described in the statement. Since it can be very large, print it modulo $$$998244353$$$.

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

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

enum long mod = 998244353L;

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

class Node {
    Node parent;
    Node left, right;
    int index;
    int val;
    int size;
    this(int val) {
        this.val = val;
    }
}

int[] value(Node v) {
    if (v.left is null) {
        assert(v.right is null);
        return [v.val];
    }
    int[] r;
    r ~= v.val;
    r ~= value(v.left);
    r ~= value(v.right);
    return r;
}

alias HashInt = ModInt!1_000_000_007L;
alias MInt = ModInt!mod;
void main() {
    int N = read!int;
    auto S = read!string;

    Node construct(int i, int d) {
        int li = i * 2;
        int ri = i * 2 + 1;
        int val = S[i - 1] == 'A' ? 0 : 1;
        auto v = new Node(val);
        if (d == N) {
            v.size = 1;
            return v;
        } else {
            v.left = construct(li, d + 1);
            v.right = construct(ri, d + 1);
            // reorder
            if (v.left.val > v.right.val) {
                swap(v.left, v.right);
            } else if (v.left.val == v.right.val) {
                if (value(v.left) > value(v.right)) {
                    swap(v.left, v.right);
                }
            }
            v.left.index = li;
            v.right.index = ri;
            v.size = 1 + v.left.size + v.right.size;
            return v;
        }
    }
    auto root = construct(1, 1);
    root.index = 1;

    HashInt[int] cache;
    HashInt hash(Node v) {
        enum HashInt m = 31;
        if (v.left is null) {
            assert(v.right is null);
            return HashInt(v.val);
        }
        if (v.index in cache) return cache[v.index];
        return cache[v.index] = HashInt(v.val) + m * hash(v.left) + m.pow(1 + v.left.size) * hash(v.right);
    }

    MInt f(Node v, int d) {
        if (d == N) { return MInt(1); } // it's a leaf
        if (hash(v.left) == hash(v.right)) {
            return f(v.left, d+1) * f(v.right, d+1);
        } else {
            return MInt(2) * f(v.left, d+1) * f(v.right, d+1);
        }
    }
    writeln(f(root, 1));
}

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

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

enum long mod = 998244353L;

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

class Node {
    Node parent;
    Node left, right;
    int index;
    int val;
    int size;
    this(int val) {
        this.val = val;
    }
}

alias HashInt = ModInt!1_000_000_007L;
alias MInt = ModInt!mod;
void main() {
    int N = read!int;
    auto S = read!string;

    Node construct(int i, int d) {
        int li = i * 2;
        int ri = i * 2 + 1;
        int val = S[i - 1] == 'A' ? 0 : 1;
        auto v = new Node(val);
        if (d == N) {
            v.size = 1;
            return v;
        } else {
            v.left = construct(li, d + 1);
            v.right = construct(ri, d + 1);
            // reorder
            if (v.left.val > v.right.val) {
                swap(v.left, v.right);
            }
            v.left.index = li;
            v.right.index = ri;
            v.size = 1 + v.left.size + v.right.size;
            return v;
        }
    }
    auto root = construct(1, 1);
    root.index = 1;

    HashInt[int] cache;
    HashInt hash(Node v) {
        enum HashInt m = 31;
        if (v.left is null) {
            assert(v.right is null);
            return HashInt(v.val);
        }
        if (v.index in cache) return cache[v.index];
        return cache[v.index] = HashInt(v.val) + m * hash(v.left) + m.pow(1 + v.left.size) * hash(v.right);
    }

    MInt f(Node v, int d) {
        if (d == N) { return MInt(1); } // it's a leaf
        if (hash(v.left) == hash(v.right)) {
            return f(v.left, d+1) * f(v.right, d+1);
        } else {
            return MInt(2) * f(v.left, d+1) * f(v.right, d+1);
        }
    }
    writeln(f(root, 1));
}


You are given two arrays $$$a$$$ and $$$b$$$, each contains $$$n$$$ integers.You want to create a new array $$$c$$$ as follows: choose some real (i.e. not necessarily integer) number $$$d$$$, and then for every $$$i \in [1, n]$$$ let $$$c_i := d \cdot a_i + b_i$$$.Your goal is to maximize the number of zeroes in array $$$c$$$. What is the largest possible answer, if you choose $$$d$$$ optimally?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in both arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$-10^9 \le b_i \le 10^9$$$).

Print one integer — the maximum number of zeroes in array $$$c$$$, if you choose $$$d$$$ optimally.

NoteIn the first example, we may choose $$$d = -2$$$.In the second example, we may choose $$$d = -\frac{1}{13}$$$.In the third example, we cannot obtain any zero in array $$$c$$$, no matter which $$$d$$$ we choose.In the fourth example, we may choose $$$d = 6$$$.

import std.functional,
       std.algorithm,
       std.container,
       std.typetuple,
       std.typecons,
       std.bigint,
       std.string,
       std.traits,
       std.array,
       std.range,
       std.stdio,
       std.conv;

void incr_hs(T)(ref int[T] hs, T key, int initial = 1) {
  if (key in hs) {
    hs[key]++;
  } else {
    hs[key] = initial;
  }
}

bool chmax(t)(ref t a, t b) {
  if (a < b) {
    a = b;
    return true;
  } else {
    return false;
  }
}

N gcd(N)(N a, N b) if (isNumeric!N || is (N == BigInt)) { return a ? gcd(b % a, a) : b; }

void main() {
  int n = readln.chomp.to!int;
  int[] a = readln.chomp.split.to!(int[]);
  int[] b = readln.chomp.split.to!(int[]);
  int[Tuple!(int, int)] hs;
  int zs;

  foreach (i; 0..n) {
    int x = a[i],
        y = b[i];

    if (x == 0 && y == 0) {
      zs++;
    }

    if (x == 0) {
      continue;
    }

    if (y == 0) {
      incr_hs(hs, tuple(0, 0));
      continue;
    }

    int m = gcd(x, y);
    x /= m;
    y /= m;
    incr_hs(hs, tuple(x, y));
  }

  int ans = 0;

  foreach (v; hs.values) {
    chmax(ans, v);
  }

  writeln(ans + zs);
}

import std.functional,
       std.algorithm,
       std.container,
       std.typetuple,
       std.typecons,
       std.bigint,
       std.string,
       std.traits,
       std.array,
       std.range,
       std.stdio,
       std.conv;

void incr_hs(T)(ref int[T] hs, T key, int initial = 1) {
  if (key in hs) {
    hs[key]++;
  } else {
    hs[key] = initial;
  }
}

bool chmax(t)(ref t a, t b) {
  if (a < b) {
    a = b;
    return true;
  } else {
    return false;
  }
}

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

  foreach (i; 0..n) {
    int x = a[i],
        y = b[i];

    if (x == 0 || y == 0) {
      incr_hs(hs, 0);
      continue;
    }

    if (x % y == 0) {
      incr_hs(hs, x / y);
    } else if (y % x == 0) {
      incr_hs(hs, y / x);
    }
  }

  int ans = 0;

  foreach (v; hs.values) {
    chmax(ans, v);
  }

  writeln(ans);
}

import std.functional,
       std.algorithm,
       std.container,
       std.typetuple,
       std.typecons,
       std.bigint,
       std.string,
       std.traits,
       std.array,
       std.range,
       std.stdio,
       std.conv;

void incr_hs(T)(ref int[T] hs, T key, int initial = 1) {
  if (key in hs) {
    hs[key]++;
  } else {
    hs[key] = initial;
  }
}

bool chmax(t)(ref t a, t b) {
  if (a < b) {
    a = b;
    return true;
  } else {
    return false;
  }
}

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

  foreach (i; 0..n) {
    int x = a[i],
        y = b[i];

    if (x == 0) {
      continue;
    }

    if (y == 0) {
      incr_hs(hs, 0);
      continue;
    }

    if (x % y == 0) {
      incr_hs(hs, x / y);
    } else if (y % x == 0) {
      incr_hs(hs, y / x);
    }
  }

  int ans = 0;

  foreach (v; hs.values) {
    chmax(ans, v);
  }

  writeln(ans);
}

import std.functional,
       std.algorithm,
       std.container,
       std.typetuple,
       std.typecons,
       std.bigint,
       std.string,
       std.traits,
       std.array,
       std.range,
       std.stdio,
       std.conv;

void incr_hs(T)(ref int[T] hs, T key, int initial = 1) {
  if (key in hs) {
    hs[key]++;
  } else {
    hs[key] = initial;
  }
}

bool chmax(t)(ref t a, t b) {
  if (a < b) {
    a = b;
    return true;
  } else {
    return false;
  }
}

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

  foreach (i; 0..n) {
    int x = a[i],
        y = b[i];
    if (x % y == 0) {
      incr_hs(hs, x / y);
    } else if (y % x == 0) {
      incr_hs(hs, y / x);
    }
  }

  int ans = 0;

  foreach (v; hs.values) {
    chmax(ans, v);
  }

  writeln(ans);
}


This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $$$n$$$ stations, enumerated from $$$1$$$ through $$$n$$$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $$$i$$$ is station $$$i+1$$$ if $$$1 \leq i < n$$$ or station $$$1$$$ if $$$i = n$$$. It takes the train $$$1$$$ second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver $$$m$$$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $$$1$$$ through $$$m$$$. Candy $$$i$$$ ($$$1 \leq i \leq m$$$), now at station $$$a_i$$$, should be delivered to station $$$b_i$$$ ($$$a_i \neq b_i$$$).    The blue numbers on the candies correspond to $$$b_i$$$ values. The image corresponds to the $$$1$$$-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.

The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100$$$; $$$1 \leq m \leq 200$$$) — the number of stations and the number of candies, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$; $$$a_i \neq b_i$$$) — the station that initially contains candy $$$i$$$ and the destination station of the candy, respectively.

In the first and only line, print $$$n$$$ space-separated integers, the $$$i$$$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $$$i$$$.

NoteConsider the second sample.If the train started at station $$$1$$$, the optimal strategy is as follows.  Load the first candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the first candy.  Proceed to station $$$1$$$. This step takes $$$1$$$ second.  Load the second candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the second candy.  Proceed to station $$$1$$$. This step takes $$$1$$$ second.  Load the third candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the third candy. Hence, the train needs $$$5$$$ seconds to complete the tasks.If the train were to start at station $$$2$$$, however, it would need to move to station $$$1$$$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $$$5+1 = 6$$$ seconds.

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

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

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

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

int N, M;
int[] A, B;

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

      auto cnt = new int[N];
      auto mn = new int[N];
      mn[] = N;
      foreach (i; 0 .. M) {
        ++cnt[A[i]];
        chmin(mn[A[i]], (B[i] - A[i] + N) % N);
      }

      foreach (x; 0 .. N) {
        int ans;
        foreach (y; 0 .. N) {
          if (cnt[y] > 0) {
            chmax(ans, (y - x + N) % N + (cnt[y] - 1) * N + mn[y]);
          }
        }
        if (x > 0) {
          write(" ");
        }
        write(ans);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


You are given two strings $$$s$$$ and $$$t$$$. Both strings have length $$$n$$$ and consist of lowercase Latin letters. The characters in the strings are numbered from $$$1$$$ to $$$n$$$.You can successively perform the following move any number of times (possibly, zero):  swap any two adjacent (neighboring) characters of $$$s$$$ (i.e. for any $$$i = \{1, 2, \dots, n - 1\}$$$ you can swap $$$s_i$$$ and $$$s_{i + 1})$$$. You can't apply a move to the string $$$t$$$. The moves are applied to the string $$$s$$$ one after another.Your task is to obtain the string $$$t$$$ from the string $$$s$$$. Find any way to do it with at most $$$10^4$$$ such moves.You do not have to minimize the number of moves, just find any sequence of moves of length $$$10^4$$$ or less to transform $$$s$$$ into $$$t$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of strings $$$s$$$ and $$$t$$$. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of the input contains the string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters.

If it is impossible to obtain the string $$$t$$$ using moves, print "-1". Otherwise in the first line print one integer $$$k$$$ — the number of moves to transform $$$s$$$ to $$$t$$$. Note that $$$k$$$ must be an integer number between $$$0$$$ and $$$10^4$$$ inclusive. In the second line print $$$k$$$ integers $$$c_j$$$ ($$$1 \le c_j < n$$$), where $$$c_j$$$ means that on the $$$j$$$-th move you swap characters $$$s_{c_j}$$$ and $$$s_{c_j + 1}$$$. If you do not need to apply any moves, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.

NoteIn the first example the string $$$s$$$ changes as follows: "abcdef" $$$\rightarrow$$$ "abdcef" $$$\rightarrow$$$ "abdcfe" $$$\rightarrow$$$ "abdfce" $$$\rightarrow$$$ "abdfec".In the second example there is no way to transform the string $$$s$$$ into the string $$$t$$$ through any allowed moves.

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

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

    auto s = readln.chomp.to!(dchar[]).array;
    auto t = readln.chomp;

    int[] ans;
    foreach (int i, e; t) {
        debug { writeln(i, ' ', e); }

        if (!s.drop(i).canFind(e)) {
            writeln(-1);
            return;
        }

        int p = n - cast(int) s.drop(i).find(e).length - 1;

        debug { writeln(s.drop(i), ' ', s.drop(i).find(e), ' ', s.drop(i).find(e).array.length); p.writeln; }

        while (i <= p) {
            swap(s[p], s[p+1]);
            ans ~= p;
            --p;
        }
    }

    ans.length.writeln;
    ans.map!(x => x+1).writefln!("%(%s %)");
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int[] r;
    int n=readln.chomp.to!int;
    char[] s=readln.strip.to!(char[]),
           t=readln.strip.to!(char[]);
    if(s==t)
        puts("0");
    else if(s.dup.array.sort!=t.dup.array.sort)
        puts("-1");
    else{
        foreach(i;0..n){
            if(s[i]==t[i]) continue;
            int j=i+1;
            while(j<n && s[j]!=t[i])
                j++;
            while(j>i){
                s.swapAt(j,j-1);
                j--;
                r~=j+1;
            }
        }
        writeln(r.length);
        write(r[0]);
        foreach(i;1..r.length)
            write(" ",r[i]);
        writeln;
    }
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int[] r;
    int n=readln.chomp.to!int;
    char[] s=readln.strip.to!(char[]),
           t=readln.strip.to!(char[]);
    if(s==t)
        puts("0");
    else if(s.dup.array.sort!=t.dup.array.sort)
        puts("-1");
    else{
        foreach(i;0..n){
            if(s[i]==t[i]) continue;
            int j=i+1;
            while(j<n && s[j]!=t[i])
                j++;
            while(j>i){
                s.swapAt(j,j-1);
                j--;
                r~=j+1;
            }
        }
        writeln(r.length);
        writefln!"%(%d %)"(r);
    }
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.strip.dup;
		auto t = readln.strip;
		int [] ans;
		foreach (i; 0..n)
		{
			foreach (j; i..n)
			{
				if (s[j] == t[i])
				{
					foreach_reverse (p; i..j)
					{
						ans ~= p + 1;
						swap (s[p], s[p + 1]);
					}
					break;
				}
			}
		}
		if (s != t)
		{
			writeln (-1);
			continue;
		}
		writeln (ans.length);
		writefln ("%(%s %)", ans);
	}
}

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

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

    auto s = readln.chomp.to!(dchar[]).array;
    auto t = readln.chomp;

    int[] ans;
    foreach (int i, e; t) {
        debug { writeln(i, ' ', e); }

        if (!s.drop(i).canFind(e)) {
            writeln(-1);
            return;
        }

        int p = n - cast(int) s.drop(i).find(e).length - 1;

        debug { writeln(s.drop(i), ' ', s.drop(i).find(e), ' ', s.drop(i).find(e).array.length); p.writeln; }

        while (i <= p) {
            swap(s[p], s[p+1]);
            ans ~= p;
            --p;
        }
    }

    ans.map!(x => x+1).writefln!("%(%s %)");
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int[] r;
    int n=readln.chomp.to!int;
    char[] s=readln.strip.to!(char[]),
           t=readln.strip.to!(char[]);
    if(s.dup.array.sort!=t.dup.array.sort)
        puts("-1");
    else{
        foreach(i;0..n){
            if(s[i]==t[i]) continue;
            int j=0;
            while(j<n && s[j]!=t[i])
                j++;
            while(j>i){
                s.swapAt(j,j-1);
                j--;
                r~=j;
            }
        }
        writeln(r.length);
        write(r[0]);
        foreach(i;1..r.length)
            write(" ",r[i]);
    }
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int[] r;
    int n=readln.chomp.to!int;
    char[] s=readln.strip.to!(char[]),
           t=readln.strip.to!(char[]);
    if(s.dup.array.sort!=t.dup.array.sort)
        puts("-1");
    else{
        foreach(i;0..n){
            if(s[i]==t[i]) continue;
            int j=0;
            while(j<n && s[j]!=t[i])
                j++;
            while(j>i){
                s.swapAt(j,j-1);
                j--;
                r~=j;
            }
        }
        write(r[0]);
        foreach(i;1..r.length)
            write(" ",r[i]);
        writeln;
        debug writeln(s," ",t);
    }
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int[] r;
    int n=readln.chomp.to!int;
    char[] s=readln.strip.to!(char[]),
           t=readln.strip.to!(char[]);
    if(s.dup.array.sort!=t.dup.array.sort)
        puts("-1");
    else{
        foreach(i;0..n){
            if(s[i]==t[i]) continue;
            int j=0;
            while(j<n && s[j]!=t[i])
                j++;
            while(j>i){
                s.swapAt(j,j-1);
                j--;
                r~=j+1;
            }
        }
        writeln(r.length);
        write(r[0]);
        foreach(i;1..r.length)
            write(" ",r[i]);
    }
}


One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.

The first line of the input contains an integer n (1 ≤ n ≤ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesn’t exceed 100.

For each sentence, output "Freda's" if the sentence was said by Freda, "Rainbow's" if the sentence was said by Rainbow, or "OMG>.< I don't know!" if liouzhou_101 can’t recognize whose sentence it is. He can’t recognize a sentence if it begins with "miao." and ends with "lala.", or satisfies neither of the conditions.

5
I will go to play with you lala.
wow, welcome.
miao.lala.
miao.
miao .

Freda's
OMG>.< I don't know!
OMG>.< I don't know!
Rainbow's
OMG>.< I don't know!

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.string;
import std.range;
import std.range.primitives;
import std.conv;

int main() {
    debug stdin = File("in.txt", "r");

    int n;
    readf(" %s\n", &n);
    string str;
    foreach ( i ; 0 .. n ) {
        readf("%s\n", &str);
        bool f = (str.length >= 5 && str[$ - 5 .. $] == "lala.");
        bool r = (str.length >= 5 && str[0 .. 5] == "miao.");
        if (f && (f ^ r)) writeln("Freda's");
        else if (r && (f ^ r)) writeln("Rainbow's");
        else writeln("OMG>.< I don't know!");
    }

    return 0;
}

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

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    readf("%d\n", &n);
    foreach (i; 0..n) {
        auto s = chomp(readln());
        if (s.length < 5) {
            writeln("OMG>.< I don't know!");
        } else {
            bool is_freda = s[$-5..$] == "lala.";
            bool is_rainbow = s[0..5] == "miao.";
            if (is_freda && !is_rainbow) {
                writeln("Freda's");
            } else if (!is_freda && is_rainbow) {
                writeln("Rainbow's");
            } else {
                writeln("OMG>.< I don't know!");
            }
        }
    }
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.string;
import std.range;
import std.range.primitives;
import std.conv;

int main() {
    debug stdin = File("in.txt", "r");

    int n;
    readf(" %s\n", &n);
    string str;
    foreach ( i ; 0 .. n ) {
        readf(" %s\n", &str);
        bool f = (str.length >= 5 && str[$ - 5 .. $] == "lala.");
        bool r = (str.length >= 5 && str[0 .. 5] == "miao.");
        if (f && (f ^ r)) writeln("Freda's");
        else if (r && (f ^ r)) writeln("Rainbow's");
        else writeln("OMG>.< I don't know!");
    }

    return 0;
}

import std.stdio;
import std.array;
import std.string;

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    readf("%d ", &n);
    foreach (i; 0..n) {
        auto s = chomp(readln());
        if (s.length < 5) {
            writeln("OMG>.< I don't know!");
        } else {
            bool is_freda = s[$-5..$] == "lala.";
            bool is_rainbow = s[0..5] == "miao.";
            if (is_freda && !is_rainbow) {
                writeln("Freda's");
            } else if (!is_freda && is_rainbow) {
                writeln("Rainbow's");
            } else {
                writeln("OMG>.< I don't know!");
            }
        }
    }
}

import std.stdio;
import std.array;
import std.string;

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    readf("%d ", &n);
    foreach (i; 0..n) {
        auto s = strip(readln());
        if (s.length < 5) {
            writeln("OMG>.< I don't know!");
        } else {
            bool is_freda = s[$-5..$] == "lala.";
            bool is_rainbow = s[0..5] == "miao.";
            if (is_freda && !is_rainbow) {
                writeln("Freda's");
            } else if (!is_freda && is_rainbow) {
                writeln("Rainbow's");
            } else {
                writeln("OMG>.< I don't know!");
            }
        }
    }
}


Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types:  Fold the sheet of paper at position pi. After this query the leftmost part of the paper with dimensions 1 × pi must be above the rightmost part of the paper with dimensions 1 × ([current width of sheet] - pi).  Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance li from the left border of the current sheet of paper and the other at distance ri from the left border of the current sheet of paper. Please look at the explanation of the first test example for better understanding of the problem.

The first line contains two integers: n and q (1  ≤ n ≤ 105; 1 ≤ q ≤ 105) — the width of the paper and the number of queries. Each of the following q lines contains one of the described queries in the following format:   "1 pi" (1 ≤ pi < [current width of sheet]) — the first type query.  "2 li ri" (0 ≤ li < ri ≤ [current width of sheet]) — the second type query.

For each query of the second type, output the answer.

NoteThe pictures below show the shapes of the paper during the queries of the first example:  After the first fold operation the sheet has width equal to 4, after the second one the width of the sheet equals to 2.

import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.numeric;
import std.range;
import std.stdio;
import std.typecons;

immutable int MED_N = 1 << 17;
immutable int MAX_N = MED_N << 1;

int [MAX_N] t;

int get (int i)
{
	return t[i + MED_N];
}

int get (int l, int r)
{
	int res = 0;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1)
	{
		if (l & 1)
		{
			res += t[l];
			l++;
		}
		if (!(r & 1))
		{
			res += t[r];
			r--;
		}
	}
	return res;
}

void put (int i, int v)
{
	for (i += MED_N; i > 0; i >>= 1)
	{
		t[i] += v;
	}
}

void main ()
{
	int n, q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		t[] = 0;
		foreach (i; 0..n)
		{
			put (i, 1);
		}
		int turn = 0;
		int lo = 0;
		int hi = n - 1;
		foreach (j; 0..q)
		{
			int qtype;
			readf (" %s", &qtype);
			if (qtype == 1)
			{
				int p;
				readf (" %s", &p);
				if (turn)
				{
					p = hi - lo + 1 - p;
				}
				int side = (p + p <= hi - lo + 1);
				if (side)
				{
					int c = lo + p;
					foreach (i; 0..p)
					{
						int v =
						    get (c - i - 1);
						put (c - i - 1, -v);
						put (c + i, +v);
					}
					lo = c;
				}
				else
				{
					p = hi - lo + 1 - p;
					int c = hi - p;
					foreach (i; 0..p)
					{
						int v =
						    get (c + i + 1);
						put (c + i + 1, -v);
						put (c - i, +v);
					}
					hi = c;
				}
				if (!side ^ turn)
				{
					turn ^= 1;
				}
			}
			else if (qtype == 2)
			{
				int x, y;
				readf (" %s %s", &x, &y);
				if (!turn)
				{
					x = lo + x;
					y = lo + y - 1;
				}
				else
				{
					swap (x, y);
					x = hi - x + 1;
					y = hi - y;
				}
				writeln (get (x, y));
			}
			else
			{
				enforce (false);
			}
		}
	}
}

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, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	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)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in 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)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

void bitAdd(long[] bit, int pos, long val) {
	for (int x = pos; x < bit.length; x |= x + 1) bit[x] += val;
}
long bitSum(long[] bit, int pos) {
	long ret;
	for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) ret += bit[x];
	return ret;
}

int N, Q;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		Q = readInt;

		long[] a = new long[N];
		a[] = 1;
		long[] bit = new long[N];
		foreach (x; 0 .. N) {
			bit.bitAdd(x, +1);
		}
		bool rev = false;
		int head = 0, tail = N;

		void foldL(int p) {
debug{
writeln("  L ",p);
}
			foreach (x; head .. head + p) {
				const y = (head + p) + (head + p - 1) - x;
				a[y] += a[x];
				bit.bitAdd(y, a[x]);
			}
			head += p;
		}
		void foldR(int p) {
debug{
writeln("  R ",p);
}
			foreach (x; tail - p .. tail) {
				const y = (tail - p) + (tail - p - 1) - x;
				a[y] += a[x];
				bit.bitAdd(y, a[x]);
			}
			tail -= p;
		}

		foreach (q; 0 .. Q) {
debug{
writeln(a[head..tail]," ",rev);
}
			switch (readInt) {
				case 1: {
					const p = readInt;
					const pp = (tail - head) - p;
					if (rev) {
						if (p <= pp) {
							foldR(p);
						} else {
							foldL(pp);
							rev = !rev;
						}
					} else {
						if (p <= pp) {
							foldL(p);
						} else {
							foldR(pp);
							rev = !rev;
						}
					}
				} break;
				case 2: {
					const l = readInt;
					const r = readInt;
					long res;
					if (rev) {
						res = bit.bitSum(tail - l) - bit.bitSum(tail - r);
					} else {
						res = bit.bitSum(head + r) - bit.bitSum(head + l);
					}
					writeln(res);
				} break;
				default: assert(false);
			}
		}
	}
	} catch (EOFException) {}
}

import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.numeric;
import std.range;
import std.stdio;
import std.typecons;

immutable int MED_N = 1 << 17;
immutable int MAX_N = MED_N << 1;

int [MAX_N] t;

int get (int i)
{
	return t[i + MED_N];
}

int get (int l, int r)
{
	int res = 0;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1)
	{
		if (l & 1)
		{
			res += t[l];
			l++;
		}
		if (!(r & 1))
		{
			res += t[r];
			r--;
		}
	}
	return res;
}

void put (int i, int v)
{
	for (i += MED_N; i > 0; i >>= 1)
	{
		t[i] += v;
	}
}

void main ()
{
	int n, q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		t[] = 0;
		foreach (i; 0..n)
		{
			put (i, 1);
		}
		int lo = 0;
		int hi = n - 1;
		foreach (j; 0..q)
		{
			int qtype;
			readf (" %s", &qtype);
			if (qtype == 1)
			{
				int p;
				readf (" %s", &p);
				int side = (p + p <= hi - lo + 1);
				if (side)
				{
					int c = lo + p;
					foreach (i; 0..p)
					{
						int v =
						    get (c - i - 1);
						put (c - i - 1, -v);
						put (c + i, +v);
					}
					lo = c;
				}
				else
				{
					p = hi - lo + 1 - p;
					int c = hi - p;
					foreach (i; 0..p)
					{
						int v =
						    get (c + i + 1);
						put (c + i + 1, -v);
						put (c - i, +v);
					}
					hi = c;
				}
			}
			else if (qtype == 2)
			{
				int x, y;
				readf (" %s %s", &x, &y);
				writeln (get (lo + x, lo + y - 1));
			}
			else
			{
				enforce (false);
			}
		}
	}
}


Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.There are n people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of n departments, one person in each).However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use team(person) to represent a team where person person works. A crisis manager can make decisions of two types:  Merge departments team(x) and team(y) into one large department containing all the employees of team(x) and team(y), where x and y (1 ≤ x, y ≤ n) — are numbers of two of some company employees. If team(x) matches team(y), then nothing happens.  Merge departments team(x), team(x + 1), ..., team(y), where x and y (1 ≤ x ≤ y ≤ n) — the numbers of some two employees of the company. At that the crisis manager can sometimes wonder whether employees x and y (1 ≤ x, y ≤ n) work at the same department.Help the crisis manager and answer all of his queries.

The first line of the input contains two integers n and q (1 ≤ n ≤ 200 000, 1 ≤ q ≤ 500 000) — the number of the employees of the company and the number of queries the crisis manager has. Next q lines contain the queries of the crisis manager. Each query looks like type x y, where . If type = 1 or type = 2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If type = 3, then your task is to determine whether employees x and y work at the same department. Note that x can be equal to y in the query of any type.

For each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.

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.random;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import core.bitop;

void main ()
{
	int n, q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		auto p = iota (n + 2).array;
		auto next = iota (1, n + 2).array;

		int root (int x)
		{
			if (p[x] != x)
			{
				p[x] = root (p[x]);
			}
			return p[x];
		}

		bool unite (int x, int y)
		{
			x = root (x);
			y = root (y);
			if (x == y)
			{
				return false;
			}

			if (uniform (0, 2))
			{
				swap (x, y);
			}
			p[x] = y;
			return true;
		}

		int getNext (int r, int v)
		{
			if (root (next[v]) == r)
			{
				next[v] = getNext (r, next[v]);
			}
			return next[v];
		}

		foreach (r; 0..q)
		{
			int t, x, y;
			readf (" %s %s %s", &t, &x, &y);
			x--;
			y--;

			if (t == 1)
			{
				unite (x, y);
			}
			else if (t == 2)
			{
				while (x < y)
				{
					int z = getNext (root (x), x);
					unite (x, y);
					x = z;
				}
			}
			else if (t == 3)
			{
				writeln (root (x) == root (y) ? "YES" : "NO");
			}
			else
			{
				assert (false);
			}
		}
	}
}


This is a harder version of the problem. In this version, $$$n \le 300\,000$$$.Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.We remind that bracket sequence $$$s$$$ is called correct if:   $$$s$$$ is empty;  $$$s$$$ is equal to "($$$t$$$)", where $$$t$$$ is correct bracket sequence;  $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not.The cyclical shift of the string $$$s$$$ of length $$$n$$$ by $$$k$$$ ($$$0 \leq k < n$$$) is a string formed by a concatenation of the last $$$k$$$ symbols of the string $$$s$$$ with the first $$$n - k$$$ symbols of string $$$s$$$. For example, the cyclical shift of string "(())()" by $$$2$$$ equals "()(())".Cyclical shifts $$$i$$$ and $$$j$$$ are considered different, if $$$i \ne j$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 300\,000$$$), the length of the string. The second line contains a string, consisting of exactly $$$n$$$ characters, where each of the characters is either "(" or ")".

The first line should contain a single integer — the largest beauty of the string, which can be achieved by swapping some two characters. The second line should contain integers $$$l$$$ and $$$r$$$ ($$$1 \leq l, r \leq n$$$) — the indices of two characters, which should be swapped in order to maximize the string's beauty. In case there are several possible swaps, print any of them.

NoteIn the first example, we can swap $$$7$$$-th and $$$8$$$-th character, obtaining a string "()()()()()". The cyclical shifts by $$$0, 2, 4, 6, 8$$$ of this string form a correct bracket sequence.In the second example, after swapping $$$5$$$-th and $$$10$$$-th character, we obtain a string ")(())()()(()". The cyclical shifts by $$$11, 7, 5, 3$$$ of this string form a correct bracket sequence.In the third example, swap of any two brackets results in $$$0$$$ cyclical shifts being correct bracket sequences.


Nezzar has a binary string $$$s$$$ of length $$$n$$$ that he wants to share with his best friend, Nanako. Nanako will spend $$$q$$$ days inspecting the binary string. At the same time, Nezzar wants to change the string $$$s$$$ into string $$$f$$$ during these $$$q$$$ days, because it looks better.It is known that Nanako loves consistency so much. On the $$$i$$$-th day, Nanako will inspect a segment of string $$$s$$$ from position $$$l_i$$$ to position $$$r_i$$$ inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.After this inspection, at the $$$i$$$-th night, Nezzar can secretly change strictly less than half of the characters in the segment from $$$l_i$$$ to $$$r_i$$$ inclusive, otherwise the change will be too obvious.Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string $$$f$$$ at the end of these $$$q$$$ days and nights.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of test cases. The first line of each test case contains two integers $$$n,q$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le q \le 2 \cdot 10^5$$$). The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$. The third line of each test case contains a binary string $$$f$$$ of length $$$n$$$. Then $$$q$$$ lines follow, $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le n$$$)  — bounds of the segment, that Nanako will inspect on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ for all test cases doesn't exceed $$$2 \cdot 10^5$$$, and the sum of $$$q$$$ for all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string $$$f$$$ at the end of $$$q$$$ days and nights. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case, $$$\underline{00000} \rightarrow \underline{000}11 \rightarrow 00111$$$ is one of the possible sequences of string changes.In the second test case, it can be shown that it is impossible to have the string $$$f$$$ at the end.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, q;
		readf !(" %s %s") (n, q);
		readln;
		auto s = readln.strip.map !(q{a == '1'}).array;
		auto f = readln.strip.map !(q{a == '1'}).array;
		alias Segment = Tuple !(int, q{lo}, int, q{hi});
		auto a = new Segment [q];
		foreach (ref c; a)
		{
			readf !(" %s %s") (c.lo, c.hi);
			c.lo -= 1;
		}
		readln;

		auto half = 1 << bsr (n * 2 - 1);
		half = max (half, 2);
		auto limit = half << 1;
		debug {writeln (half, " ", limit);}
		auto t = new int [limit];
		auto u = new int [limit];
		auto z = new int [limit];
		u[] = -1;

		void relax (int pos)
		{
			if (u[pos] != -1)
			{
				debug {writeln ("relax ", pos);}
				t[pos] = u[pos] * z[pos];
				if (pos < half)
				{
					u[pos * 2 + 0] = u[pos];
					u[pos * 2 + 1] = u[pos];
				}
				u[pos] = -1;
			}
		}

		void recalc (int pos)
		{
			if (pos < half)
			{
				relax (pos * 2 + 0);
				relax (pos * 2 + 1);
				t[pos] = t[pos * 2 + 0] + t[pos * 2 + 1];
			}
		}

		foreach (i; 0..n)
		{
			t[i + half] = f[i];
			z[i + half] = 1;
		}
		foreach_reverse (i; 1..half)
		{
			recalc (i);
			z[i] = z[i * 2 + 0] + z[i * 2 + 1];
		}

		int calc (int pos, int tlo, int thi, int slo, int shi)
		{
			if (shi <= tlo || thi <= slo)
			{
				return 0;
			}
			relax (pos);
			if (slo <= tlo && thi <= shi)
			{
				return t[pos];
			}
			int tme = (tlo + thi) >> 1;
			auto res = calc (pos * 2 + 0, tlo, tme, slo, shi) +
			    calc (pos * 2 + 1, tme, thi, slo, shi);
			recalc (pos);
			return res;
		}

		void mark (int pos, int tlo, int thi, int slo, int shi, int v)
		{
			if (shi <= tlo || thi <= slo)
			{
				return;
			}
			relax (pos);
			if (slo <= tlo && thi <= shi)
			{
				u[pos] = v;
				relax (pos);
				recalc (pos);
				return;
			}
			int tme = (tlo + thi) >> 1;
			mark (pos * 2 + 0, tlo, tme, slo, shi, v);
			mark (pos * 2 + 1, tme, thi, slo, shi, v);
			recalc (pos);
		}

		debug {writefln !("%(%3s%)") (z);}
		bool ok = true;
		foreach_reverse (ref c; a)
		{
			auto d = calc (1, 0, half, c.lo, c.hi);
			debug {writeln (c.lo, " ", c.hi, " ", d);}
			debug {writeln ("after calc:");}
			debug {writefln !("%(%3s%)") (t);}
			debug {writefln !("%(%3s%)") (u);}
			int v = -1;
			if (d * 2 < c.hi - c.lo)
			{
				v = 0;
			}
			else if (d * 2 > c.hi - c.lo)
			{
				v = 1;
			}
			else
			{
				ok = false;
				break;
			}
			mark (1, 0, half, c.lo, c.hi, v);
			debug {writeln ("after mark:");}
			debug {writefln !("%(%3s%)") (t);}
			debug {writefln !("%(%3s%)") (u);}
		}

		foreach (i; 1..half + n)
		{
			relax (i);
		}
		debug {writefln !("%(%3s%)") (t);}
		debug {writefln !("%(%3s%)") (u);}
		debug {writefln !("%(%d%)") (s);}
		debug {writefln !("%(%d%)") (t[half..half + n]);}
		ok &= equal (s, t[half..half + n]);
		writeln (ok ? "YES" : "NO");
	}
}

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

class LazyPropagationSegmentTree(T = int, D = int, D init = D.init) {
  immutable size_t n;
  immutable int h;
  T[] t;
  D[] d;

  abstract void calc (size_t p, int k);
  abstract void apply (size_t p, D value, int k);

  final void build (size_t l, size_t r) {
    int k = 2;
    for (l += n, r += n - 1; l > 1; k <<= 1) {
      l >>= 1;
      r >>= 1;
      foreach_reverse (i; l .. r + 1) {
        calc (i, k);
      }
    }
  }

  final void push (size_t l, size_t r) {
    int s = h, k = 1 << (h-1);
    for (l += n, r += n - 1; s > 0; --s, k >>= 1) {
      foreach (i; l >> s .. (r >> s) + 1) {
        immutable delta = d[i];
        if (delta != init) {
          apply (i << 1, delta, k);
          apply ((i << 1) | 1, delta, k);
          d[i] = init;
        }
      }
    }
  }

  this (const T[] a) {
    n = a.length;
    h = bsr (n);
    t = uninitializedArray!(T[])(n);
    t ~= a;
    d = uninitializedArray!(D[])(n);
    d[] = init;
    build (0, n);
  }
}

class AssignSumLazyPropagationSegmentTree (T = int) : LazyPropagationSegmentTree!(T, T, T.min) {
  override void calc (size_t p, int k) {
    if (d[p] == T.min) t[p] = t[p<<1] + t[(p << 1) | 1];
    else t[p] = d[p] * k;
  }

  override void apply (size_t p, T value, int k) {
    t[p] = value * k;
    if (p < n) d[p] = value;
  }

  final void assign (size_t l, size_t r, T value) {
    debug stderr.writefln ("assign (l:%d, r:%d, value:%d)", l, r, value);
    push (l, l + 1);
    push (r - 1, r);
    immutable l0 = l, r0 = r;
    int k = 1;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1, k <<= 1) {
      if (l & 1) {
        apply (l++, value, k);
      }
      if (r & 1) {
        apply (--r, value, k);
      }
    }
    build (l0, l0 + 1);
    build (r0 - 1, r0);
  }

  final T sum (size_t l, size_t r) {
    push (l, l + 1);
    push (r - 1, r);
    T res;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
      if (l & 1) {
        res += t[l++];
      }
      if (r & 1) {
        res += t[--r];
      }
    }
    return res;
  }
  this (T[] a) {
    super (a);
  }
}

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

alias Q = Tuple!(int, int);

void main() {
  auto r = new InputReader ();
  const nt = r.next!uint();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint();
    const nq = r.next!uint();
    r.seekByte(48);
    int[] a, b;
    foreach (i; 0 .. n) {
      const c = r.nextByte!false();
      a ~= c.to!int - 48;
    }
    r.seekByte(48);
    foreach (i; 0 .. n) {
      const c = r.nextByte!false();
      b ~= c.to!int - 48;
    }
    debug stderr.writeln(a);
    debug stderr.writeln(b);
    auto st = new AssignSumLazyPropagationSegmentTree!int(b);
    Q[] q;
    foreach (i; 0 .. nq) {
      const u = r.next!int - 1;
      const v = r.next!int;
      q ~= Q(u, v);
    }
    bool res = true;
    foreach_reverse (k, const w; q) {
      const l = w[1] - w[0];
      const h = (l - 1) / 2;
      int t = st.sum(w[0], w[1]);
      debug stderr.writefln("l = %d, r = %d, sum = %d, h = %d, l = %d", w[0], w[1], t, h, l);
      if (t <= h) {
        st.assign(w[0], w[1], 0);
      } else if (t + h >= l) {
        st.assign(w[0], w[1], 1);
      } else {
        debug stderr.writefln("FAILED: l = %d, r = %d", w[0], w[1]);
        res = false;
        break;
      }
    }
    if (res) {
      foreach (i; 0 .. n) {
        if (st.sum(i, i + 1) != a[i]) {
          res = false;
          break;
        }
      }
    }
    if (res) write("YES\n"); else write("NO\n");
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, q;
		readf !(" %s %s") (n, q);
		readln;
		auto s = readln.strip.map !(q{a == '1'}).array;
		auto f = readln.strip.map !(q{a == '1'}).array;
		alias Segment = Tuple !(int, q{lo}, int, q{hi});
		auto a = new Segment [q];
		foreach (ref c; a)
		{
			readf !(" %s %s") (c.lo, c.hi);
			c.lo -= 1;
		}
		readln;

		auto half = 1 << bsr (n * 2 - 1);
		auto limit = half << 1;
		auto t = new int [limit];
		auto u = new int [limit];
		auto z = new int [limit];
		u[] = -1;

		void relax (int pos)
		{
			if (u[pos] != -1)
			{
				t[pos] = u[pos] * z[pos];
				if (pos < half)
				{
					u[pos * 2 + 0] = u[pos];
					u[pos * 2 + 1] = u[pos];
				}
				u[pos] = -1;
			}
		}

		void recalc (int pos)
		{
			if (pos < half)
			{
				t[pos] = t[pos * 2 + 0] + t[pos * 2 + 1];
			}
		}

		foreach (i; 0..n)
		{
			t[i + half] = f[i];
			z[i + half] = 1;
		}
		foreach_reverse (i; 1..half)
		{
			recalc (i);
			z[i] = z[i * 2 + 0] + z[i * 2 + 1];
		}

		int calc (int pos, int tlo, int thi, int slo, int shi)
		{
			if (shi <= tlo || thi <= slo)
			{
				return 0;
			}
			relax (pos);
			if (slo <= tlo && thi <= shi)
			{
				return t[pos];
			}
			int tme = (tlo + thi) >> 1;
			return calc (pos * 2 + 0, tlo, tme, slo, shi) +
			    calc (pos * 2 + 1, tme, thi, slo, shi);
		}

		void mark (int pos, int tlo, int thi, int slo, int shi, int v)
		{
			if (shi <= tlo || thi <= slo)
			{
				return;
			}
			relax (pos);
			if (slo <= tlo && thi <= shi)
			{
				u[pos] = v;
				relax (pos);
				recalc (pos);
				return;
			}
			int tme = (tlo + thi) >> 1;
			mark (pos * 2 + 0, tlo, tme, slo, shi, v);
			mark (pos * 2 + 1, tme, thi, slo, shi, v);
			recalc (pos);
		}

		debug {writefln !("%(%3s%)") (z);}
		bool ok = true;
		foreach_reverse (ref c; a)
		{
			auto d = calc (1, 0, half, c.lo, c.hi);
			debug {writeln (c.lo, " ", c.hi, " ", d);}
			int v = -1;
			if (d * 2 < c.hi - c.lo)
			{
				v = 0;
			}
			else if (d * 2 > c.hi - c.lo)
			{
				v = 1;
			}
			else
			{
				ok = false;
				break;
			}
			mark (1, 0, half, c.lo, c.hi, v);
			debug {writefln !("%(%3s%)") (t);}
			debug {writefln !("%(%3s%)") (u);}
		}

		foreach (i; 1..half + n)
		{
			relax (i);
		}
		debug {writefln !("%(%3s%)") (t);}
		debug {writefln !("%(%3s%)") (u);}
		debug {writefln !("%(%d%)") (s);}
		debug {writefln !("%(%d%)") (t[half..half + n]);}
		ok &= equal (s, t[half..half + n]);
		writeln (ok ? "YES" : "NO");
	}
}


Graph constructive problems are back! This time the graph you are asked to build should match the following properties.The graph is connected if and only if there exists a path between every pair of vertices.The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.The degree of a vertex is the number of edges incident to it.Given a sequence of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ construct a connected undirected graph of $$$n$$$ vertices such that:  the graph contains no self-loops and no multiple edges;  the degree $$$d_i$$$ of the $$$i$$$-th vertex doesn't exceed $$$a_i$$$ (i.e. $$$d_i \le a_i$$$);  the diameter of the graph is maximum possible. Output the resulting graph or report that no solution exists.

The first line contains a single integer $$$n$$$ ($$$3 \le n \le 500$$$) — the number of vertices in the graph. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n - 1$$$) — the upper limits to vertex degrees.

Print "NO" if no graph can be constructed under the given conditions. Otherwise print "YES" and the diameter of the resulting graph in the first line. The second line should contain a single integer $$$m$$$ — the number of edges in the resulting graph. The $$$i$$$-th of the next $$$m$$$ lines should contain two integers $$$v_i, u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$v_i \neq u_i$$$) — the description of the $$$i$$$-th edge. The graph should contain no multiple edges — for each pair $$$(x, y)$$$ you output, you should output no more pairs $$$(x, y)$$$ or $$$(y, x)$$$.

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

immutable long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;
    auto B = N.iota.map!(i => tuple(A[i], i)).array;

    Tuple!(int, int)[] one;
    Tuple!(int, int)[] mul;
    Tuple!(int, int)[] ans;
    int d = 0;

    foreach (b; B) {
        if (b[0] == 1) {
            one ~= b;
        } else {
            mul ~= b;
        }
    }

    foreach (i; 0..mul.length.to!int-1) {
        int u = mul[i][1];
        int v = mul[i+1][1];
        ans ~= tuple(u, v);
        A[u] -= 1;
        A[v] -= 1;
        d += 1;
    }

    if (mul.length == 0) {
        writeln("NO");
        return;
    }

    int f = mul.front[1];
    int b = mul.back[1];
    A[f] -= 1;
    A[b] -= 1;

    for (int i = 2, p = 0; i < one.length; ++i) {
        while (p < mul.length && A[mul[p][1]] == 0)
            ++p;
        if (p >= mul.length) {
            writeln("NO");
            return;
        }
        A[mul[p][1]] -= 1;
        ans ~= tuple(one[i][1], mul[p][1]);
    }

    if (one.length > 0) {
        ans ~= tuple(one[0][1], f);
        A[f] -= 1;
        d += 1;
    }
    if (one.length > 1) {
        ans ~= tuple(one[1][1], b);
        A[b] -= 1;
        d += 1;
    }

    writeln("YES ", d);
    writeln(ans.length);
    foreach (a; ans) {
        writeln(a[0] + 1, " ", a[1] + 1);
    }
}


Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.

The first line contains two space-separated integers x1, y1 ( - 106 ≤ x1, y1 ≤ 106) — the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≤ x2, y2 ≤ 106) — the coordinates of the university you are studying at. The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≤ ai, bi, ci ≤ 106; |ai| + |bi| > 0) — the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).

NotePictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors):

import std.stdio;

T read(T)()
{
    T t;
    readf(" %s", &t);
    return t;
}

T sign(T)(T x)
{
    return x < 0 ? -1 : 1;
}

int main(string[] args)
{
    long x1 = read!long;
    long y1 = read!long;
    long x2 = read!long;
    long y2 = read!long;
    long n = read!long;

    long ans = 0;
    foreach (i; 0..n)
    {
        long a = read!long;
        long b = read!long;
        long c = read!long;

        if (sign(a * x1 + b * y1 + c) *
            sign(a * x2 + b * y2 + c) < 0)
        {
            ans++;
        }
    }

    writeln(ans);

    return 0;
}

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

void main ()
{
	long x1, y1;
	while (readf (" %s %s", &x1, &y1) > 0)
	{
		long x2, y2;
		readf (" %s %s", &x2, &y2);
		int n;
		readf (" %s", &n);
		int res = 0;
		foreach (i; 0..n)
		{
			long a, b, c;
			readf (" %s %s %s", &a, &b, &c);
			long d1 = a * x1 + b * y1 + c;
			long d2 = a * x2 + b * y2 + c;
			if ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0))
			{
				res++;
			}
		}
		writeln (res);
	}
}

import std.stdio;

T read(T)()
{
    T t;
    readf(" %s", &t);
    return t;
}

T sign(T)(T x)
{
    return -x;
}

int main(string[] args)
{
    int x1 = read!int;
    int y1 = read!int;
    int x2 = read!int;
    int y2 = read!int;
    int n = read!int;

    int ans = 0;
    foreach (i; 0..n)
    {
        int a = read!int;
        int b = read!int;
        int c = read!int;

        if (sign(a * x1 + b * y1 + c) *
            sign(a * x2 + b * y2 + c) < 0)
        {
            ans++;
        }
    }

    writeln(ans);

    return 0;
}

import std.stdio;

T read(T)()
{
    T t;
    readf(" %s", &t);
    return t;
}

T sign(T)(T x)
{
    return -x;
}

int main(string[] args)
{
    long x1 = read!long;
    long y1 = read!long;
    long x2 = read!long;
    long y2 = read!long;
    long n = read!long;

    long ans = 0;
    foreach (i; 0..n)
    {
        long a = read!long;
        long b = read!long;
        long c = read!long;

        if (sign(a * x1 + b * y1 + c) *
            sign(a * x2 + b * y2 + c) < 0)
        {
            ans++;
        }
    }

    writeln(ans);

    return 0;
}


You are given an integer $$$n$$$ and an integer $$$k$$$.In one step you can do one of the following moves:   decrease $$$n$$$ by $$$1$$$;  divide $$$n$$$ by $$$k$$$ if $$$n$$$ is divisible by $$$k$$$. For example, if $$$n = 27$$$ and $$$k = 3$$$ you can do the following steps: $$$27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.You are asked to calculate the minimum number of steps to reach $$$0$$$ from $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of queries. The only line of each query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^{18}$$$, $$$2 \le k \le 10^{18}$$$).

For each query print the minimum number of steps to reach $$$0$$$ from $$$n$$$ in single line.

NoteSteps for the first test case are: $$$59 \rightarrow 58 \rightarrow 57 \rightarrow 19 \rightarrow 18 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.In the second test case you have to divide $$$n$$$ by $$$k$$$ $$$18$$$ times and then decrease $$$n$$$ by $$$1$$$.

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

immutable int INF = 1 << 29;

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        auto s = readln.split.map!(to!long);
        auto N = s[0];
        auto K = s[1];
        long cnt = 0;
        while (N > 0) {
            long m = N % K;
            if (m == 0) {
                N /= K;
                cnt += 1;
            } else {
                N -= m;
                cnt += m;
            }
        }
        cnt.writeln;
    }
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		long n, k;
		readf !(" %s %s") (n, k);
		long res = 0;
		while (n > 0)
		{
			res += n % k;
			n -= n % k;
			if (n > 0)
			{
				res += 1;
				n /= k;
			}
		}
		writeln (res);
	}
}

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

void main() {
  long nt;
  readf!" %d" (nt);
  while (--nt >= 0) {
    long n, k;
    readf!" %d %d" (n, k);
    long res;
    while (n >= k) {
      res += 1 + (n % k);
      debug stderr.writeln (res);
      n /= k;
    }
    res += n;
    writeln (res);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
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;
	foreach(_; 0 .. t){

		long n = read.to!long;
		long k = read.to!long;

		long ans;
		while(n > 0){
			if(n % k == 0) ans += 1, n /= k;
			else ans += n % k, n -= (n % k);
		}

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

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

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

void main()
{
	auto t  = RD!int;
	auto nk = new long[2][](t);
	foreach (i; 0..t)
	{
		nk[i] = [RD, RD];
	}

	foreach (i; 0..t)
	{
		auto n = nk[i][0];
		auto k = nk[i][1];
		long ans;
		while (n != 0)
		{
			auto x = n % k;
			if (x == 0)
			{
				n /= k;
				++ans;
			}
			else
			{
				n -= x;
				ans += x;
			}
		}
		writeln(ans);
	}

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

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

void main ()
{
	long n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		long res = 0;
		while (n > 0)
		{
			res += n % k;
			n /= k;
		}
		writeln (res);
	}
}


Lee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular $$$n$$$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $$$OX$$$-axis and at least one of its edges is parallel to the $$$OY$$$-axis at the same time.Recall that a regular $$$n$$$-sided polygon is a convex polygon with $$$n$$$ vertices such that all the edges and angles are equal.Now he is shopping: the market has $$$t$$$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of polygons in the market.  Each of the next $$$t$$$ lines contains a single integer $$$n_i$$$ ($$$3 \le n_i \le 10^9$$$): it means that the $$$i$$$-th polygon is a regular $$$n_i$$$-sided polygon.

For each polygon, print YES if it's beautiful or NO otherwise (case insensitive).

NoteIn the example, there are $$$4$$$ polygons in the market. It's easy to see that an equilateral triangle (a regular $$$3$$$-sided polygon) is not beautiful, a square (a regular $$$4$$$-sided polygon) is beautiful and a regular $$$12$$$-sided polygon (is shown below) is beautiful as well.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		writeln (n % 4 == 0 ? "YES" : "NO");
	}
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(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!T(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(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 = E.init)
{
  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;
}

void main()
{
  int t;
  read(t);
  foreach(i; 0 .. t)
    {
      long n;
      read(n);
      if (n % 4 == 0)
        writeln("YES");
      else
        writeln("NO");
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

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


You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have only one neighbour each, they are neither local minima nor local maxima.An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.

The first line contains one integer n (1 ≤ n ≤ 1000) — the number of elements in array a. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the elements of array a.

Print the number of local extrema in the given array.

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

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

    int ans;

    foreach (i ; 1 .. n - 1) {
        ans += ((a[i - 1] < a[i] && a[i] > a[i + 1]) || (a[i - 1] > a[i] && a[i] < a[i + 1]));
    }

    writeln(ans);
}

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

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


Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105). The next line contains n uppercase letters without spaces — the i-th letter describes the i-th card of the Appleman.

Print a single integer – the answer to the problem.

NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.

import std.stdio;
import std.math;
import std.array;
import std.algorithm;

unittest{
  assert(solve(10,"DZFDFZDFDDDDDDF") == 82, "Teste 1");
  assert(solve(4,"YJSNPI") == 4, "Teste 1");
}

ulong solve(ulong k, string s){
  ulong sum = 0;

  ulong[immutable(char)] h;
  ulong[26] hi;

  foreach(c;s){
    ++h[c];
  }

  foreach(cc;h.keys){
    hi[cc-65] = h[cc];
  }

  while(k > 0){
    size_t max = 0;
    for(size_t i = 0; i < hi.length; i++){
      if(hi[i] > hi[max]){
        max = i;
      }
    }
    auto pts = min(k,hi[max]);
    k -= pts;

    sum += pts*pts;
    hi[max] = 0;
  }

  debug(1) writeln(sum);
  return sum;
}

void main(){
  size_t n;
  ulong k;
  string s;
  readf("%s %s\n",&n,&k);
  readf("%s\n",&s);

  writeln(solve(k,s));
}

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, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	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)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in 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)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int N, K;
string A;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		K = readInt;
		A = readToken;

		long[] cnt = new long[26];
		foreach (a; A) {
			++cnt[a - 'A'];
		}

		cnt.sort!"a > b";
		long ans;
		long k = K;
		foreach (c; cnt) {
			const tmp = min(c, k);
			ans += tmp * tmp;
			k -= tmp;
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;

unittest{
  assert(solve(10,"DZFDFZDFDDDDDDF") == 82, "Teste 1");
  assert(solve(4,"YJSNPI") == 4, "Teste 1");
}

ulong solve(ulong k, string s){
  auto sum = 0;

  ulong[immutable(char)] h;
  ulong[26] hi;

  foreach(c;s){
    ++h[c];
  }

  foreach(cc;h.keys){
    hi[cc-65] = h[cc];
  }

  while(k > 0){
    size_t max = 0;
    for(size_t i = 0; i < hi.length; i++){
      if(hi[i] > hi[max]){
        max = i;
      }
    }
    auto pts = min(k,hi[max]);
    k -= pts;

    sum += pts*pts;
    hi[max] = 0;
  }

  debug(1) writeln(sum);
  return sum;
}

void main(){
  size_t n;
  ulong k;
  string s;
  readf("%s %s\n",&n,&k);
  readf("%s\n",&s);

  writeln(solve(k,s));
}