Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.

The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland. The second line contains n lowercase English letters s1s2... sn as a string — the initial colours of paper pieces on the garland. The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has. The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≤ mi ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci — Koyomi's possible favourite colour.

Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.

15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b

NoteIn the first sample, there are three plans:   In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;  In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;  In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.

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

immutable long mod = 10^^9 + 7;

void main(){
    int n, q, c;
    readVars(n);
    auto s = readln.chomp;
    readVars(q);

    auto pfs = new int[][](26, n + 1);
    foreach(j ; 0 .. n){
        c = s[j] - 'a';

        foreach(i ; 0 .. 26){
            if (i == c) {
                pfs[i][j + 1] = pfs[i][j] + 1;
            }
            else {
                pfs[i][j + 1] = pfs[i][j];
            }
        }
    }

    auto dp = new int[][](26, n + 1);

    int move;

    foreach(ci ; 0 .. 26){
        foreach(l ; 0 .. n + 1){
            foreach(r ; l .. n + 1){
                move = r - l - (pfs[ci][r] - pfs[ci][l]);
                dp[ci][move] = max(dp[ci][move], r - l);
            }
        }

        foreach(i ; 0 .. n){
            dp[ci][i + 1] = max(dp[ci][i + 1], dp[ci][i]);
        }
    }

    int mi, ci, ans;

    foreach(qi ; 0 .. q){
        auto line = readln.split;
        mi = line[0].to!int;
        ci = line[1].to!char - 'a';

        ans = dp[ci][mi];
        writeln(ans);
    }
}

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


You are given a permutation $$$p_1, p_2, \dots, p_n$$$. Then, an undirected graph is constructed in the following way: add an edge between vertices $$$i$$$, $$$j$$$ such that $$$i < j$$$ if and only if $$$p_i > p_j$$$. Your task is to count the number of connected components in this graph.Two vertices $$$u$$$ and $$$v$$$ belong to the same connected component if and only if there is at least one path along edges connecting $$$u$$$ and $$$v$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the elements of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer $$$k$$$ — the number of connected components.

NoteEach separate test case is depicted in the image below. The colored squares represent the elements of the permutation. For one permutation, each color represents some connected component. The number of distinct colors is the answer.

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N);

      auto rbt = A.redBlackTree;
      auto uf = UnionFind(N + 1);
      int rest = N;

      int last;
      foreach(a; A) {
        if (last < a) {
          foreach(other; rbt.lowerBound(a)) {
            if (!uf.same(a, other)) {
              rest--;
              uf.unite(a, other);
            }
          }
        }
        rbt.removeKey(a);
        if (rest == 1) break;
        last = max(last, a);
      }

      return rest;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

struct UnionFind {
  int[] parent;

  this(int size) {
    parent.length = size;
    foreach(i; 0..size) parent[i] = i;
  }

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

  int unite(int x, int y) {
    int rootX = root(x);
    int rootY = root(y);

    if (rootX == rootY) return rootY;
    return parent[rootX] = rootY;
  }

  bool same(int x, int y) {
    int rootX = root(x);
    int rootY = root(y);

    return rootX == rootY;
  }
}

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N);

      auto rbt = A.redBlackTree;
      auto uf = UnionFind(N + 1);
      int rest = N;

      foreach(a; A) {
        foreach(other; rbt.lowerBound(a)) {
          if (!uf.same(a, other)) {
            rest--;
            uf.unite(a, other);
          }
        }
        rbt.removeKey(a);
        if (rest == 1) break;
      }

      return rest;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

struct UnionFind {
  int[] parent;

  this(int size) {
    parent.length = size;
    foreach(i; 0..size) parent[i] = i;
  }

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

  int unite(int x, int y) {
    int rootX = root(x);
    int rootY = root(y);

    if (rootX == rootY) return rootY;
    return parent[rootX] = rootY;
  }

  bool same(int x, int y) {
    int rootX = root(x);
    int rootY = root(y);

    return rootX == rootY;
  }
}

import std.stdio, std.string, std.conv;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
import std.typecons;
ulong prefsum(int n)
{
    return (cast(ulong) n*(n + 1)) / 2;
}
ulong segsum(int from, int to) {
    return prefsum(to) - prefsum(from - 1);
}
void solution(ref File input, ref File output) {
    auto t = input.readln.chomp.to!int;
    while (t-- > 0) {
        auto _ = input.readln;
        auto source = input.readln.chomp
            .split(' ')
            .map!(to!int)
            .enumerate;
        int start = 1, answer;
        ulong sum = 0;
        foreach (item; source)
        {
            auto ind = cast(int) item[0] + 1, val = item[1];
            sum += val;
            //writeln("Start: ", start,
            //        "Current: ", ind,
            //        " Segsum", segsum(start, ind),
            //        "Sum: ", sum);
            if (segsum(start, ind) == sum)
            {
                start = ind + 1;
                sum = 0;
                answer += 1;
            }
        }
        output.writeln(answer);
    }
}
void main()
{
    File input, output;
    debug(1) {
        input = File("input.txt", "r");
        output = File("output.txt", "w");
    } else {
        input = stdin;
        output = stdout;
    }
    solution(input, output);
}

import std.stdio, std.string, std.conv;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
import std.typecons;
int prefsum(int n)
{
    return (n*(n + 1)) / 2;
}
int segsum(int from, int to) {
    return prefsum(to) - prefsum(from - 1);
}
void solution(ref File input, ref File output) {
    auto t = input.readln.chomp.to!int;
    while (t-- > 0) {
        auto _ = input.readln;
        auto source = input.readln.chomp
            .split(' ')
            .map!(to!int)
            .enumerate;
        int start = 1, answer;
        ulong sum = 0;
        foreach (item; source)
        {
            auto ind = cast(int) item[0] + 1, val = item[1];
            sum += val;
            //writeln("Start: ", start,
            //        "Current: ", ind,
            //        " Segsum", segsum(start, ind),
            //        "Sum: ", sum);
            if (segsum(start, ind) == sum)
            {
                start = ind + 1;
                sum = 0;
                answer += 1;
            }
        }
        output.writeln(answer);
    }
}
void main()
{
    File input, output;
    debug(1) {
        input = File("input.txt", "r");
        output = File("output.txt", "w");
    } else {
        input = stdin;
        output = stdout;
    }
    solution(input, output);
}


You are given a set of all integers from $$$l$$$ to $$$r$$$ inclusive, $$$l < r$$$, $$$(r - l + 1) \le 3 \cdot 10^5$$$ and $$$(r - l)$$$ is always odd.You want to split these numbers into exactly $$$\frac{r - l + 1}{2}$$$ pairs in such a way that for each pair $$$(i, j)$$$ the greatest common divisor of $$$i$$$ and $$$j$$$ is equal to $$$1$$$. Each number should appear in exactly one of the pairs.Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.

If any solution exists, print "YES" in the first line. Each of the next $$$\frac{r - l + 1}{2}$$$ lines should contain some pair of integers. GCD of numbers in each pair should be equal to $$$1$$$. All $$$(r - l + 1)$$$ numbers should be pairwise distinct and should have values from $$$l$$$ to $$$r$$$ inclusive. If there are multiple solutions, print any of them. If there exists no solution, print "NO".

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

  long l, r; rd(l, r);
  writeln("YES");
  for(auto i=l; i+1<=r; i+=2){
    writeln(i, " ", i+1);
  }

}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


You are given two strings $$$A$$$ and $$$B$$$ representing essays of two students who are suspected cheaters. For any two strings $$$C$$$, $$$D$$$ we define their similarity score $$$S(C,D)$$$ as $$$4\cdot LCS(C,D) - |C| - |D|$$$, where $$$LCS(C,D)$$$ denotes the length of the Longest Common Subsequence of strings $$$C$$$ and $$$D$$$. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal $$$S(C, D)$$$ over all pairs $$$(C, D)$$$, where $$$C$$$ is some substring of $$$A$$$, and $$$D$$$ is some substring of $$$B$$$. If $$$X$$$ is a string, $$$|X|$$$ denotes its length.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the Wikipedia page about the Longest Common Subsequence problem.

The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 5000$$$) — lengths of the two strings $$$A$$$ and $$$B$$$.  The second line contains a string consisting of $$$n$$$ lowercase Latin letters — string $$$A$$$. The third line contains a string consisting of $$$m$$$ lowercase Latin letters — string $$$B$$$.

Output maximal $$$S(C, D)$$$ over all pairs $$$(C, D)$$$, where $$$C$$$ is some substring of $$$A$$$, and $$$D$$$ is some substring of $$$B$$$.

NoteFor the first case:abb from the first string and abab from the second string have LCS equal to abb.The result is $$$S(abb, abab) = (4 \cdot |abb|$$$) - $$$|abb|$$$ - $$$|abab|$$$ = $$$4 \cdot 3 - 3 - 4 = 5$$$.

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

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;
		auto s = readln.strip;
		auto t = readln.strip;
		auto f = new int [] [] (n + 1, m + 1);
		int res = 0;
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				f[i + 1][j + 1] = max (0,
				    f[i + 1][j] - 1,
				    f[i][j + 1] - 1,
				    f[i][j] + 4 * (s[i] == t[j]) - 2);
				res = max (res, f[i + 1][j + 1]);
			}
		}
		writeln (res);
	}
}

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

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;
		auto s = readln.strip;
		auto t = readln.strip;
		auto f = new int [] [] (n + 1, m + 1);
		int res = 0;
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				f[i + 1][j + 1] = max (f[i + 1][j] - 1,
				    f[i][j + 1] - 1,
				    f[i][j] + 2 * (s[i] == t[j]));
				res = max (res, f[i + 1][j + 1]);
			}
		}
		writeln (res);
	}
}

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

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;
		auto s = readln.strip;
		auto t = readln.strip;
		auto f = new int [] [] (n + 1, m + 1);
		int res = 0;
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				f[i + 1][j + 1] = max (f[i + 1][j] - 1,
				    f[i][j + 1] - 1,
				    f[i][j] + 4 * (s[i] == t[j]) - 2);
				res = max (res, f[i + 1][j + 1]);
			}
		}
		writeln (res);
	}
}


Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this angle. As you spend lots of time "glued to the screen", your vision is impaired. So you have to write a program that will pass the check for you.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of mannequins. Next n lines contain two space-separated integers each: xi, yi (|xi|, |yi| ≤ 1000) — the coordinates of the i-th mannequin. It is guaranteed that the origin of the coordinates has no mannequin. It is guaranteed that no two mannequins are located in the same point on the plane.

Print a single real number — the value of the sought angle in degrees. The answer will be considered valid if the relative or absolute error doesn't exceed 10 - 6.

NoteSolution for the first sample test is shown below:   Solution for the second sample test is shown below:   Solution for the third sample test is shown below:   Solution for the fourth sample test is shown below:

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

int n;

int main ()
{
	while ((readf (" %d", &n) >= 0) && !stdin.eof ())
	{
		auto x = new double [n];
		auto y = new double [n];
		foreach (i; 0..n)
		{
			readf (" %f %f", &x[i], &y[i]);
		}
		auto z = new double [n];
		foreach (i; 0..n)
		{
			z[i] = atan2 (y[i], x[i]);
		}
		sort (z);
		z ~= z[0] + PI * 2.0;
		auto s = double.min;
		foreach (i; 0..n)
		{
			s = max (s, z[i + 1] - z[i]);
		}
		writef ("%.10f\n", 360.0 - s * 180.0 / PI);
	}
	return 0;
}


As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task.

The first line contains two space-separated positive integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000) — the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 104) — the towers' initial heights.

In the first line print two space-separated non-negative integers s and m (m ≤ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i ≠ j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them.

NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6.

#!/usr/bin/env rdmd
// Computes average line length for standard input.
import std.stdio;
import std.algorithm;
import std.container;
import std.string;
import std.math;

// 479b
void main()
{
	auto result = SList!string();
	int resultk = 0;
	int n, k;
	readf("%s %s\n", &n, &k);
	int a[] = new int[n];
	int b[] = new int[n];
	for (int i=0; i<n; i++) {
		readf(" %s", &a[i]);
	}
	for (int i=0; i<n; i++) {
		b[i] = i;
	}
	for (int i=0; i<n-1; i++) {
		for (int j=1; j<n-i; j++) {
			if (a[j-1]>a[j]) {
				swap(a[j-1], a[j]);
				swap(b[j-1], b[j]);
			}
		}
	}

	while (k>0 && a[0]<a[n-1]-1) {

		a[0]++;
		a[n-1]--;
		resultk++;
		k--;
		result.insert(format("%s %s", b[n-1]+1, b[0]+1));
		int j = 1;
		while (j<n && a[j-1]>a[j]) {
			swap(a[j-1], a[j]);
			swap(b[j-1], b[j]);
			j++;
		}
		j = n-2;
		while (j>=0 && a[j]>a[j+1]) {
			swap(a[j], a[j+1]);
			swap(b[j], b[j+1]);
			j--;
		}
	}

	writeln(format("%s %s", abs(a[0] - a[n-1]), resultk));
	foreach(elem; result) {
    	writeln(elem);
   	}
}


Ridbit starts with an integer $$$n$$$.In one move, he can perform one of the following operations:   divide $$$n$$$ by one of its proper divisors, or  subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. A proper divisor is a divisor of a number, excluding itself. For example, $$$1$$$, $$$2$$$, $$$4$$$, $$$5$$$, and $$$10$$$ are proper divisors of $$$20$$$, but $$$20$$$ itself is not.What is the minimum number of moves Ridbit is required to make to reduce $$$n$$$ to $$$1$$$?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^9$$$).

For each test case, output the minimum number of moves required to reduce $$$n$$$ to $$$1$$$.

NoteFor the test cases in the example, $$$n$$$ may be reduced to $$$1$$$ using the following operations in sequence$$$1$$$$$$2 \xrightarrow{} 1$$$$$$3 \xrightarrow{} 2 \xrightarrow{} 1$$$$$$4 \xrightarrow{} 2 \xrightarrow{} 1$$$$$$6 \xrightarrow{} 2 \xrightarrow{} 1$$$$$$9 \xrightarrow{} 3 \xrightarrow{} 2\xrightarrow{} 1$$$

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

// Main Logic Here
void play(){
    ll n;
    n = rd;
    if(n == 1){
        writeln(0);
    }else if(n == 2){
        writeln(1);
    }else if (n == 3){
        writeln(2);
    }else if(n % 2 == 0){
        writeln(2);
    }else{
        writeln(3);
    }
}

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

/**********That's All Folks!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;    // Read input
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
alias ll = long;
alias tup = Tuple!(long, "x",  long, "y");
void show(A...)(A a) { debug{ foreach(t; a){ stderr.write(t, "| "); } stderr.writeln; } } // Debug
/* Add if TLE, T max(T = long)(T a, T b){ return (a > b) ? a : b; } */

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(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD;
		if (n == 1) continue;
		else if (n == 2)
			ans[ti] = 1;
		else if (n == 3)
			ans[ti] = 2;
		else if (n % 2 == 0)
			ans[ti] = 2;
		else
			ans[ti] = 3;
	}

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

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

ll[] primes;

void prime_sieve(int siz){
    auto isPrime = new bool[](siz+1);
    isPrime[] = 1;
    foreach(p; 2..10000){
        if(isPrime[p]){
            for(ll divi = p*p; divi <= siz; divi += p){
                isPrime[divi.to!int] = 0;
            }
        }
    }
    foreach(k; 2..siz+1){
        if(isPrime[k]) primes ~= k;
    }
}

// Main Logic Here
void play(){
    ll n;
    n = rd;
    ll tak = n;
    foreach(p; primes){
        if(n % p == 0){
            tak = p;
            break;
        }
    }
    writeln(tak - (tak == n));
}

int main(){
    long t = 1;
    prime_sieve(100000);
    t = rd;        // Toggle for testcases!
    while(t--) play();  // Let's play!
    return 0;
}

/**********That's All Folks!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;    // Read input
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
alias ll = long;
alias tup = Tuple!(long, "x",  long, "y");
void show(A...)(A a) { debug{ foreach(t; a){ stderr.write(t, "| "); } stderr.writeln; } } // Debug
/* Add if TLE, T max(T = long)(T a, T b){ return (a > b) ? a : b; } */

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(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD;
		while (n != 1)
		{
			bool ok;
			for (long i = 2; i*i <= n; ++i)
			{
				if (n % i) continue;
				n = i;
				ok = true;
				break;
			}
			if (!ok)
				--n;
			++ans[ti];
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD;
		while (n != 1)
		{
			if (n == 2)
			{
				++ans[ti];
				break;
			}
			bool ok;
			for (long i = 2; i*i <= n; ++i)
			{
				if (n % i) continue;
				n = i;
				ok = true;
				break;
			}
			if (!ok)
				--n;
			++ans[ti];
		}
	}

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


Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a × b.After n - 1 steps there is only one number left. Can you make this number equal to 24?

The first line contains a single integer n (1 ≤ n ≤ 105).

If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes). If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces. If there are multiple valid answers, you may print any of them.

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 add(int a, int b) { writefln("%d + %d = %d", a, b, a + b); }
void sub(int a, int b) { writefln("%d - %d = %d", a, b, a - b); }
void mul(int a, int b) { writefln("%d * %d = %d", a, b, a * b); }

int N;

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

		if (N <= 3) {
			writeln("NO");
		} else {
			writeln("YES");
			if (N == 5) {
				mul(5, 4);
				add(20, 3);
				add(23, 2);
				sub(25, 1);
			} else if (N % 2 == 0) {
				mul(4, 3);
				mul(12, 2);
				for (int i = N; i >= 6; i -= 2) {
					sub(i, i - 1);
				}
				foreach (_; 0 .. 1 + (N - 4) / 2) {
					mul(24, 1);
				}
			} else {
				mul(6, 4);
				sub(7, 5);
				sub(2, 1);
				sub(3, 2);
				for (int i = N; i >= 9; i -= 2) {
					sub(i, i - 1);
				}
				foreach (_; 0 .. 2 + (N - 7) / 2) {
					mul(24, 1);
				}
			}
		}
	}
	} catch (EOFException) {}
}


At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.Fortunately, Picks remembers something about his set S:  its elements were distinct integers from 1 to limit;  the value of  was equal to sum; here lowbit(x) equals 2k where k is the position of the first one in the binary representation of x. For example, lowbit(100102) = 102, lowbit(100012) = 12, lowbit(100002) = 100002 (binary representation). Can you help Picks and find any set S, that satisfies all the above conditions?

The first line contains two integers: sum, limit (1 ≤ sum, limit ≤ 105).

In the first line print an integer n (1 ≤ n ≤ 105), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them. If it's impossible to find a suitable set, print -1.

NoteIn sample test 1: lowbit(4) = 4, lowbit(5) = 1, 4 + 1 = 5.In sample test 2: lowbit(1) = 1, lowbit(2) = 2, lowbit(3) = 1, 1 + 2 + 1 = 4.

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

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

int[] solve(int sum, int limit){
  int[][int] grps;
  int maxd = 0;

  for(int i = limit; i > 0; i--){
    auto div = 1;
    do{
      div *= 2;
      if(i % div != 0){
        grps[div/2] ~= i;
        if(div > maxd){
          maxd = div;
        }
        break;
      }
    } while (i % div == 0);
  }

  auto pts = 0;
  int[] lst = [];
  while(maxd != 0){
    debug(1) writeln("*",maxd);
    foreach(x; grps.get(maxd,[])){
      if(pts+maxd <= sum){
        pts += maxd;
        lst ~= x;
      }
    }
    maxd /= 2;
  }

  debug(1) writeln(grps);
  debug(1) writeln(lst);
  debug(1) writeln(pts);
  debug(1) writeln("<<>>");
  if(pts != sum){
    return [];
  }
  return lst;
}

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

  auto r = solve(a,b);
  if(r.length == 0){
    writeln(-1);
    return;
  }
  writeln(r.length);
  auto s = r.map!"to!string(a)".array;
  writeln(join(s," "));
}


This problem differs from the next one only in the presence of the constraint on the equal length of all numbers $$$a_1, a_2, \dots, a_n$$$. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$$$, where $$$a_1 \dots a_p$$$ and $$$b_1 \dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally,  if $$$p \ge q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$;  if $$$p < q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$. All numbers in this array are of equal length (that is, they consist of the same number of digits). Your task is to help students to calculate $$$\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\,244\,353$$$.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array. All numbers $$$a_1, a_2, \dots, a_n$$$ are of equal length (that is, they consist of the same number of digits).

Print the answer modulo $$$998\,244\,353$$$.

import std.stdio;

auto calc(long x) {
    long base = 1;
    long result = 0;
    while(x > 0) {
        auto d = x % 10;
        x = x / 10;
        result += d * base;
        base *= 100;
    }
    return result;
}

void main() {
    int MOD = 998244353;
    int n;
    long a, result;

    readf(" %s", n);
    foreach(i; 0..n) {
        readf(" %s", a);
        auto b = calc(a) % MOD;
        result += (b * 10 * n) % MOD + (b * n) % MOD;
        result %= MOD;
    }
    writeln(result);
}

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

const long mod = 998_244_353;

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

	long[] as;
	foreach(i; 0 .. n) as ~= read.to!long;

	long[][] ws;
	foreach(a; as){
		long [] w;
		for(long x = a; x > 0; x /= 10) w ~= x % 10;
		ws ~= w;
	}

	long ans;
	foreach(w; ws){
		int i = 0;
		long m = 1;
		for(; i < w.length; i += 1, m *= 100, m %= mod){
			ans += w[i] * 11 * m * n % mod;
			ans %= mod;
		}
	}

	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; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;
	auto b1 = new long[](n);
	auto b2 = new long[](n);
	foreach (i; 0..n)
	{
		long[] nums;
		auto x = a[i];
		while (x != 0)
		{
			nums ~= x % 10;
			x /= 10;
		}
		debug writeln(nums);
		foreach (j; 0..nums.length)
		{
			auto tmp = nums[j];
			foreach (k; 0..j+j)
			{
				tmp.modm(10);
			}
			b2[i].moda(tmp);
			tmp.modm(10);
			b1[i].moda(tmp);
		}
	}
	debug writeln(b1);
	debug writeln(b2);

	long ans;
	foreach (i; 0..n)
	{
		auto x = b1[i] + b2[i];
		x.modm(n);
		ans.moda(x);
	}

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


There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m — the smallest number of points you should add on the line to make the distances between all neighboring points equal.

The first line contains a single integer n (3 ≤ n ≤ 100 000) — the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≤ xi ≤ 109) — the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.

Print a single integer m — the smallest number of points you should add on the line to make the distances between all neighboring points equal.

NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.

module main;

import std.c.stdio;
import std.algorithm : sort;

int main(string[] argv)
{
    int n;
    scanf("%d", &n);
    int[] x = new int[n];
    for(int i = 0; i < n; i++)
        scanf("%d", &x[i]);
    sort(x);
    int g = 0;
    for (int i = 1; i < n; i++) {
        int a = x[i] - x[i - 1];
        int b = g;
        while (b > 0) {
            a %= b;
            int t = b;
            b = a;
            a = t;
        }
        g = a;
    }
    int mi = 2000000000;
    int ma = -2000000000;
    for (int i = 0; i < n; ++i) {
        if (mi > x[i]) mi = x[i];
        if (ma < x[i]) ma = x[i];
    }
    int diff = ma - mi;
    diff /= g;
    printf("%d\n", diff + 1 - n);
    return 0;
}

module main;

import std.c.stdio;
import std.algorithm;

long gcd(long a, long b) {
	while (b) {
		a %= b;
		swap(a, b);
	}
	return a;
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i < n; i++) {
		scanf("%d", &a[i]);
	}
	sort(a);
	long m = 0;
	for(int i = 0; i < n-1; ++i) {
	    m = gcd(a[i+1]-a[i], m);
	}
	long add = 0;
	for(int i = 0; i < n-1; ++i) {
	    add += (a[i+1]-a[i]) / m - 1;
	}
	printf("%d\n", add);
	return 0;
}

module main;

import core.stdc.stdio;
import std.algorithm.sorting;
import std.algorithm.comparison;
import std.numeric;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	int mina=1000000001, maxa =-1000000001;
	for(int i = 0; i<n; i++){
		scanf("%d", &arr[i]);
		if (mina > arr[i]){
		    mina = arr[i];
		}
		if (maxa < arr[i]){
		    maxa = arr[i];
		}
	}
	sort(arr);

	int diff = maxa - mina;
	for(int i = 0; i<n-1; i++)
		diff = gcd(diff,arr[i+1]-arr[i]);
	//printf("%d %d %d\n", mina, maxa, diff);
    if ((maxa - mina)==0) {
        printf("%d\n", 0);
    }
	else
	    printf("%d\n", (maxa-mina)/gcd(mina-maxa,diff)+1-n);
	return 0;
}

module main;
import std.algorithm;
import std.c.stdio;
int Gcd(int a, int b){
	if(b==0)
		return a;
	return Gcd(b, a%b);
}

int s;
int main ()
{
    int n, i;
    scanf("%d", &n);
    int []a = new int [n];
int []d = new int [n];
    for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    }

    a.sort();
    for (i = 1; i < n; i++) {
        d[i] = a[i] - a[i-1];
    }
    int gcd = d[1];
    for(i = 2; i < n; i++) {
        gcd = Gcd(gcd, d[i]);
    }
    for (i = 1; i < n; i++) {
        s += (d[i]/gcd) - 1;
    }
    printf("%d",s);
    return 0;
}

module main;

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

int gcd (int a, int b) {
	if (b == 0)
		return a;
	else
		return gcd (b, a % b);
}

int main(string[] argv)
{
	int n;

	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i < n; i++) scanf("%d", &a[i]);
	a.sort();
	int small = a[1] - a[0];
	for(int i = 1; i < n - 1; i++)
	    small = gcd(small, a[i + 1] - a[i]);

	printf("%d", (a[n - 1] - a[0]) / small - n + 1);

	return 0;
}

module main;

import std.c.stdio;
import std.algorithm.sorting;

int temp(int a, int b)
{
    while(b > 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main(string[] argv)
{
    int n, res = 0;
    scanf("%d", &n);
    int[] arr = new int[n];
    for(int i = 0; i < n; i++)
        scanf("%d", &arr[i]);
    arr.sort();
    int mGcd = arr[1] - arr[0];
    for(int i = 2; i < n; i++) {
        mGcd = temp(mGcd, arr[i] - arr[i-1]);
    }

    for(int i = 1; i < n; i++) {
        res += (arr[i]-arr[i-1]) / mGcd - 1;
    }

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

	return 0;
}

module main;

import std.c.stdio;
import std.algorithm;

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

int main(string[] argv)
{
    int n;
    scanf("%d", &n);
    auto arr = new int[n];
    for(int i = 0; i<n; i++)
        scanf("%d", &arr[i]);

    sort(arr);

    int g = 0;
    for (int i = 1; i < n; i++) {
        g = gcd(arr[i] - arr[i-1], g);
    }

    int ret = 0;
    for (int i = 1; i < n; i++) {
        ret += (arr[i] - arr[i-1]) / g - 1;
    }

    printf("%d\n", ret);
    return 0;
}

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

int gcd(int a, int b) {
	return b? gcd(b, a % b) : a;
}

void main() {
 int n;
 scanf("%d", &n);
 Array!int a;
 for (int i = 0; i < n; ++i) {
	int temp = 0;
	scanf("%d", &temp);
	a.insertBack(temp);
 }

 a[].sort();
 int dist = a[1] - a[0], ans = 0;
 for (int i = 2; i < n; ++i)
	dist = gcd(dist, a[i] - a[i - 1]);
 for (int i = 1; i < n; ++i)
	ans += (a[i] - a[i - 1]) / dist - 1;
 printf("%d", ans);

}

module main;

import std.c.stdio;

int gcd (int a, int b) {
	return b ? gcd (b, a % b) : a;
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	//printf("%d", gcd(0,4));
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	int mx = -1000000001, mn = 2000000001;
	for(int i = 0; i<n; i++) {
	    if(mx < arr[i])
	        mx = arr[i];
	    if(mn > arr[i])
	        mn = arr[i];
	}
	for(int i = 0; i<n; i++)
	    arr[i] -= mn;
	int g = gcd(arr[0],arr[1]);
	for(int i = 2; i<n; i++)
		g = gcd(g, arr[i]);

	//printf("%d", g);
	printf("%d", (mx - mn)/g + 1 - n);
	return 0;
}

module main;
import core.stdc.stdio;
import std.algorithm;

int gcd(int a, int b){
while (a > 0 && b > 0){
if (a > b){
a = a % b;
} else {
b = b % a;
}
}
return a + b;
}

int main(string[] argv)
{
int n;
scanf("%d", &n);
int [] arr = new int[n];
for(int i = 0; i<n; i++)
scanf("%d", &arr[i]);
arr.sort!();
int cur = arr[1] - arr[0];
for (int i = 1; i < n; i++){
cur = gcd(cur, arr[i] - arr[i - 1]);
}
int ans = 0;
for (int i = 1; i < n; i++){
int len = arr[i] - arr[i - 1];
ans += len / cur - 1;
}
printf("%d", ans);
return 0;
}

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

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

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

    arr.sort();

    auto dst = zip(arr, arr.dropOne).map!(t => t[1] - t[0]).array;

    auto gcd = dst.fold!gcd;

    debug { dst.writeln; gcd.writeln; }

    int ans = 0;
    foreach (a, b; lockstep(arr, arr.dropOne)) {
        ans += (b - a) / gcd - 1;
    }

    ans.writeln;
}

module main;

import std.c.stdio;
import std.algorithm;
import std.range;
import std.numeric;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	sort(arr);
	int q = arr[1]-arr[0];
	for(int i = 2; i<n; i++)
		q = gcd(arr[i]-arr[i-1], q);

	//printf("%d\n", q);
	int ans = 0;
	for(int i = 1; i<n; i++) {
	    ans += ((arr[i]-arr[i-1])/q - 1);
	}
	printf("%d", ans);
	return 0;
}

module main;

import std.c.stdio;
import std.algorithm;

int main(string[] argv)
{
	int n;
	int mn = 2000006789;
	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
    a.sort();

    int m = a[1] - a[0];
    for (int i = 1; i * i <= m; i++) if (m % i == 0){
        int dist = i, flag = 0, res = 0;
        for (int j = 1; j < n; j++){
            if ((a[j] - a[j - 1]) % dist != 0) flag = 1;
            res += (a[j] - a[j - 1]) / dist - 1;
        }
        if (res < mn && flag == 0) mn = res;

        dist = m / i, flag = 0, res = 0;
        for (int j = 1; j < n; j++){
            if ((a[j] - a[j - 1]) % dist != 0) flag = 1;
            res += (a[j] - a[j - 1]) / dist - 1;
        }
        if (res < mn && flag == 0) mn = res;
    }
	printf("%d", mn);
	return 0;
}

import std.stdio;
import std.c.stdio;
import std.algorithm.sorting;
import std.numeric;
void main()
{
    int n;
    scanf("%d", &n);
    int[] a = new int[n];
    for(int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    a.sort();

    int g = a[1] - a[0];
    for(int i = 2; i < n; i++){
        g = gcd(g, a[i] - a[i-1]);
    }
    int u = a[n-1]-a[0];
    int x = u/g;
    int res = x-n+1;
    printf("%d", res);

}

module main;

import std.c.stdio;

int main(string[] argv)
{
    int n;
    scanf("%d", &n);
    int [] x = new int[n];
    for(int i = 0; i < n; i++)
        scanf("%d", &x[i]);
    int g = 0;
    for (int i = 0; i < n - 1; i++) {
        int a = x[i] - x[i - 1];
        if (a < 0) a = -a;
        int b = g;
        while (b > 0) {
            a %= b;
            int t = b;
            b = a;
            a = t;
        }
        g = a;
    }
    int mi = 2000000000;
    int ma = -2000000000;
    for (int i = 0; i < n; ++i) {
        if (mi > x[i]) mi = x[i];
        if (ma < x[i]) ma = x[i];
    }
    int diff = ma - mi;
    diff /= g;
    printf("%d\n", diff + 1 - n);
    return 0;
}

module main;

import core.stdc.stdio;
import std.algorithm.sorting;
import std.algorithm.comparison;
import std.numeric;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	int mina=1000000001, maxa =-1000000001;
	for(int i = 0; i<n; i++){
		scanf("%d", &arr[i]);
		if (mina > arr[i]){
		    mina = arr[i];
		}
		if (maxa < arr[i]){
		    maxa = arr[i];
		}
	}
	sort(arr);

	int diff = maxa - mina;
	for(int i = 0; i<n-1; i++)
		if (diff >arr[i+1]-arr[i]){
		    diff = arr[i+1]-arr[i];
		}
	printf("%d\n", (maxa-mina)/gcd(mina-maxa,diff)+1-n);
	return 0;
}

module main;

import core.stdc.stdio;
import std.algorithm.sorting;
import std.algorithm.comparison;
import std.numeric;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	int mina=1000000001, maxa =-1000000001;
	for(int i = 0; i<n; i++){
		scanf("%d", &arr[i]);
		if (mina > arr[i]){
		    mina = arr[i];
		}
		if (maxa < arr[i]){
		    maxa = arr[i];
		}
	}
	sort(arr);

	int diff = maxa - mina;
	for(int i = 0; i<n-1; i++)
		if (diff >arr[i+1]-arr[i]){
		    diff = arr[i+1]-arr[i];
		}
    if (diff ==0) {
        printf("%d\n", 0);
    }
	else
	    printf("%d\n", (maxa-mina)/gcd(mina-maxa,diff)+1-n);
	return 0;
}

module main;

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

int main(string[] argv)
{
	int n;

	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i < n; i++) scanf("%d", &a[i]);
	a.sort();
	int small = 2000000012;
	for(int i = 0; i < n - 1; i++)
	    if (a[i + 1] - a[i] < small)
	        small = a[i + 1] - a[i];

	printf("%d", (a[n - 1] - a[0]) / small - n + 1);

	return 0;
}

module main;

import std.c.stdio;

int gcd (int a, int b) {
    if(a < 0)
    a *= -1;
    if(b < 0)
    b *= -1;
	return b ? gcd (b, a % b) : a;
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	//printf("%d", gcd(1,10));
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	int g = gcd(arr[0],arr[1]);
	for(int i = 0; i<n; i++)
		g = gcd(g, arr[i]);
	int mx = -1000000001, mn = 1000000001;
	for(int i = 0; i<n; i++) {
	    if(mx < arr[i])
	        mx = arr[i];
	    if(mn > arr[i])
	        mn = arr[i];
	}
	//printf("%d", g);
	printf("%d", (mx - mn)/g + 1 - n);
	return 0;
}

module main;

import std.c.stdio;

int gcd (int a, int b) {
	return b ? gcd (b, a % b) : a;
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	//printf("%d", gcd(1,10));
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	for(int i = 0; i<n; i++)
	    arr[i] += 1000000000;
	int g = gcd(arr[0],arr[1]);
	for(int i = 0; i<n; i++)
		g = gcd(g, arr[i]);
	int mx = 0, mn = 2000000001;
	for(int i = 0; i<n; i++) {
	    if(mx < arr[i])
	        mx = arr[i];
	    if(mn > arr[i])
	        mn = arr[i];
	}
	//printf("%d", g);
	printf("%d", (mx - mn)/g + 1 - n);
	return 0;
}

module main;

import std.c.stdio;
import std.algorithm;

int main(string[] argv)
{
	int n;
	int mn = 1123456789;
	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
    a.sort();

    int m = a[1] - a[0];
    for (int i = 1; i * i <= m; i++) if (m % i == 0){
        int dist = i, flag = 0, res = 0;
        for (int j = 1; j < n; j++){
            if ((a[j] - a[j - 1]) % dist != 0) flag = 1;
            res += (a[j] - a[j - 1]) / dist - 1;
        }
        if (res < mn && flag == 0) mn = res;

        dist = m / i, flag = 0, res = 0;
        for (int j = 1; j < n; j++){
            if ((a[j] - a[j - 1]) % dist != 0) flag = 1;
            res += (a[j] - a[j - 1]) / dist - 1;
        }
        if (res < mn && flag == 0) mn = res;
    }
	printf("%d", mn);
	return 0;
}


There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n.It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti — the moment in seconds in which the task will come, ki — the number of servers needed to perform it, and di — the time needed to perform this task in seconds. All ti are distinct.To perform the i-th task you need ki servers which are unoccupied in the second ti. After the servers begin to perform the task, each of them will be busy over the next di seconds. Thus, they will be busy in seconds ti, ti + 1, ..., ti + di - 1. For performing the task, ki servers with the smallest ids will be chosen from all the unoccupied servers. If in the second ti there are not enough unoccupied servers, the task is ignored.Write the program that determines which tasks will be performed and which will be ignored.

The first line contains two positive integers n and q (1 ≤ n ≤ 100, 1 ≤ q ≤ 105) — the number of servers and the number of tasks.  Next q lines contains three integers each, the i-th line contains integers ti, ki and di (1 ≤ ti ≤ 106, 1 ≤ ki ≤ n, 1 ≤ di ≤ 1000) — the moment in seconds in which the i-th task will come, the number of servers needed to perform it, and the time needed to perform this task in seconds. The tasks are given in a chronological order and they will come in distinct seconds.

Print q lines. If the i-th task will be performed by the servers, print in the i-th line the sum of servers' ids on which this task will be performed. Otherwise, print -1.

NoteIn the first example in the second 1 the first task will come, it will be performed on the servers with ids 1, 2 and 3 (the sum of the ids equals 6) during two seconds. In the second 2 the second task will come, it will be ignored, because only the server 4 will be unoccupied at that second. In the second 3 the third task will come. By this time, servers with the ids 1, 2 and 3 will be unoccupied again, so the third task will be done on all the servers with the ids 1, 2, 3 and 4 (the sum of the ids is 10).In the second example in the second 3 the first task will come, it will be performed on the servers with ids 1 and 2 (the sum of the ids is 3) during three seconds. In the second 5 the second task will come, it will be performed on the server 3, because the first two servers will be busy performing the first task.

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

__gshared:

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

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

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

struct Mask {
    size_t[(100 + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)] data;

    int bsf() const {
        foreach (i, x; data)
            if (x)
                return cast(int)(.bsf(x) + (i * size_t.sizeof * 8));
        return -1;
    }
}

alias Event = Tuple!(int, `t`, bool, `open`, int, `k`, int, `id`);

Event[200_000] _events;
Mask[100_000] _masks;

void main() {
    int n, q;
    while (read(&n, &q)) {
        auto events = _events[0 .. q << 1];
        auto masks = _masks[0 .. q];
        version (LocalProject)
            foreach (ref m; masks)
                m.data[ ] = 0x0;
        foreach (i; 0 .. q) {
            int t, k, d;
            read(&t, &k, &d);
            events[i << 1] = Event(t, true, k, i);
            events[i << 1 | 0x1] = Event(t + d, false, k, i);
        }
        events.multiSort!(`a.t < b.t`, `a.open < b.open`);

        Mask cur;
        memset(cur.data.ptr, 0xFF, cur.data.sizeof);
        nextEvent: foreach (ref e; events)
            if (e.open) {
                debug writeln("start ", e.id);
                int result = 0;
                foreach (i; 0 .. e.k) {
                    int t = cur.bsf();
                    debug writeln("Got ", t);
                    if (~t && t < n) {
                        result += t;
                        btr(cur.data.ptr, t);
                        bts(masks[e.id].data.ptr, t);
                    } else {
                        writeln("-1");
                        cur.data[ ] |= masks[e.id].data[ ];
                        masks[e.id].data[ ] = 0x0;
                        continue nextEvent;
                    }
                }
                writeln(result + e.k);
            } else {
                debug writeln("stop ", e.id);
                cur.data[ ] |= masks[e.id].data[ ];
            }
        debug writeln();
    }
}

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

void main()
{
	int n,q;
	while(input(&n,&q))
	{
		auto s=new int[n];
		foreach(i;0..q)
		{
			int t,k,d;
			input(&t,&k,&d);
			int r;
			foreach(j;s)if(j<=t)r++;
			//writeln(r);
			if(r<k)writeln(-1);
			else
			{
				int p=0,ans;
				while(k)
				{
					if(s[p]<=t) {s[p]=t+d;k--;ans+=p+1;}
					p++;
				}
				writeln(ans);
			}
		}
	}
	debug readln;
}

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

__gshared:

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

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

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

struct Mask {
    size_t[(100 + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)] data;

    int bsf() const {
        foreach (i, x; data)
            if (x)
                return cast(int)(.bsf(x) + (i << size_t.sizeof));
        return -1;
    }
}

alias Event = Tuple!(int, `t`, bool, `open`, int, `k`, int, `id`);

Event[200_000] _events;
Mask[100_000] _masks;

void main() {
    int n, q;
    while (read(&n, &q)) {
        auto events = _events[0 .. q << 1];
        auto masks = _masks[0 .. q];
        version (LocalProject)
            foreach (ref m; masks)
                m.data[ ] = 0x0;
        foreach (i; 0 .. q) {
            int t, k, d;
            read(&t, &k, &d);
            events[i << 1] = Event(t, true, k, i);
            events[i << 1 | 0x1] = Event(t + d, false, k, i);
        }
        events.multiSort!(`a.t < b.t`, `a.open < b.open`);

        Mask cur;
        memset(cur.data.ptr, 0xFF, cur.data.sizeof);
        nextEvent: foreach (ref e; events)
            if (e.open) {
                debug writeln("start ", e.id);
                int result = 0;
                foreach (i; 0 .. e.k) {
                    int t = cur.bsf();
                    debug writeln("Got ", t);
                    if (~t && t < n) {
                        result += t;
                        btr(cur.data.ptr, t);
                        bts(masks[e.id].data.ptr, t);
                    } else {
                        writeln("-1");
                        cur.data[ ] |= masks[e.id].data[ ];
                        masks[e.id].data[ ] = 0x0;
                        continue nextEvent;
                    }
                }
                writeln(result + e.k);
            } else {
                debug writeln("stop ", e.id);
                cur.data[ ] |= masks[e.id].data[ ];
            }
        debug writeln();
    }
}


In this problem you will have to deal with a real algorithm that is used in the VK social network.As in any other company that creates high-loaded websites, the VK developers have to deal with request statistics regularly. An important indicator reflecting the load of the site is the mean number of requests for a certain period of time of T seconds (for example, T = 60 seconds = 1 min and T = 86400 seconds = 1 day). For example, if this value drops dramatically, that shows that the site has access problem. If this value grows, that may be a reason to analyze the cause for the growth and add more servers to the website if it is really needed.However, even such a natural problem as counting the mean number of queries for some period of time can be a challenge when you process the amount of data of a huge social network. That's why the developers have to use original techniques to solve problems approximately, but more effectively at the same time.Let's consider the following formal model. We have a service that works for n seconds. We know the number of queries to this resource at at each moment of time t (1 ≤ t ≤ n). Let's formulate the following algorithm of calculating the mean with exponential decay. Let c be some real number, strictly larger than one.// setting this constant value correctly can adjust   // the time range for which statistics will be calculateddouble c = some constant value; // as the result of the algorithm's performance this variable will contain // the mean number of queries for the last // T seconds by the current moment of timedouble mean = 0.0; for t = 1..n: // at each second, we do the following:    // at is the number of queries that came at the last second;    mean = (mean + at / T) / c;Thus, the mean variable is recalculated each second using the number of queries that came at that second. We can make some mathematical calculations and prove that choosing the value of constant c correctly will make the value of mean not very different from the real mean value ax at t - T + 1 ≤ x ≤ t. The advantage of such approach is that it only uses the number of requests at the current moment of time and doesn't require storing the history of requests for a large time range. Also, it considers the recent values with the weight larger than the weight of the old ones, which helps to react to dramatic change in values quicker.However before using the new theoretical approach in industrial programming, there is an obligatory step to make, that is, to test its credibility practically on given test data sets. Your task is to compare the data obtained as a result of the work of an approximate algorithm to the real data. You are given n values at, integer T and real number c. Also, you are given m moments pj (1 ≤ j ≤ m), where we are interested in the mean value of the number of queries for the last T seconds. Implement two algorithms. The first one should calculate the required value by definition, i.e. by the formula . The second algorithm should calculate the mean value as is described above. Print both values and calculate the relative error of the second algorithm by the formula , where approx is the approximate value, obtained by the second algorithm, and real is the exact value obtained by the first algorithm.

The first line contains integer n (1 ≤ n ≤ 2·105), integer T (1 ≤ T ≤ n) and real number c (1 < c ≤ 100) — the time range when the resource should work, the length of the time range during which we need the mean number of requests and the coefficient c of the work of approximate algorithm. Number c is given with exactly six digits after the decimal point. The next line contains n integers at (1 ≤ at ≤ 106) — the number of queries to the service at each moment of time. The next line contains integer m (1 ≤ m ≤ n) — the number of moments of time when we are interested in the mean number of queries for the last T seconds. The next line contains m integers pj (T ≤ pj ≤ n), representing another moment of time for which we need statistics. Moments pj are strictly increasing.

Print m lines. The j-th line must contain three numbers real, approx and error, where:    is the real mean number of queries for the last T seconds;  approx is calculated by the given algorithm and equals mean at the moment of time t = pj (that is, after implementing the pj-th iteration of the cycle);   is the relative error of the approximate algorithm.  The numbers you printed will be compared to the correct numbers with the relative or absolute error 10 - 4. It is recommended to print the numbers with at least five digits after the decimal point.

import std.c.stdio;
import std.math;

void main()
{
    int n, t;
    double c;

    scanf("%d%d%lf", &n, &t, &c);

    int[] a = new int[n];
    foreach (i; 0 .. n) {
        scanf("%d", &a[i]);
    }

    int m;
    scanf("%d", &m);
    int[] p = new int[m];
    foreach (i; 0 .. m) {
        scanf("%d", &p[i]);
        --p[i];
    }

    long sum = 0;
    int ptr = 0;
    double actual = 0;
    foreach (i; 0 .. n) {
        sum += a[i];
        actual = (actual + 1.0 * a[i] / t) / c;
        while (ptr < m && p[ptr] == i) {
            double expected = 1.0 * sum / t;
            printf("%.6f %.6f %.6f\n", expected, actual
                   , abs(expected - actual) / expected);
            ++ptr;
        }

        if (i - t + 1 >= 0) sum -= a[i - t + 1];
    }
}


We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people. After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too. Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.

The first line of the input contains two integers n and k (1 ≤ n ≤ 500 000, 0 ≤ k ≤ 109) — the number of citizens in Kekoland and the number of days left till Robin Hood's retirement. The second line contains n integers, the i-th of them is ci (1 ≤ ci ≤ 109) — initial wealth of the i-th person.

Print a single line containing the difference between richest and poorest peoples wealth.

NoteLets look at how wealth changes through day in the first sample.  [1, 1, 4, 2]  [2, 1, 3, 2] or [1, 2, 3, 2] So the answer is 3 - 1 = 2In second sample wealth will remain the same for each person.

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

immutable int MIN_C =       0;
immutable int MAX_C = 10 ^^ 9;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;

		int findLower ()
		{
			bool got (int limit)
			{
				int res = 0;
				foreach (c; a)
				{
					if (c < limit)
					{
						res += limit - c;
						if (res > k)
						{
							return false;
						}
					}
				}
				return true;
			}

			int lo = MIN_C;
			int hi = MAX_C;
			while (lo < hi)
			{
				int me = (lo + hi + 1) / 2;
				if (got (me))
				{
					lo = me;
				}
				else
				{
					hi = me - 1;
				}
			}
			return lo;
		}

		int lower = findLower ();
		a[] = MAX_C - a[];
		int upper = MAX_C - findLower ();
		a[] = MAX_C - a[];
		debug {writeln (lower, " ", upper);}
		int res = upper - lower;
		if (res <= 0)
		{
			res = ((sum (a, 0L) % n) != 0);
		}
		writeln (res);
	}
}


Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should be positive integers that have no leading zeros. Polycarpus knows values a and b.Help Polycarpus and find any suitable method to cut the public key.

The first line of the input contains the public key of the messenger — an integer without leading zeroes, its length is in range from 1 to 106 digits. The second line contains a pair of space-separated positive integers a, b (1 ≤ a, b ≤ 108).

In the first line print "YES" (without the quotes), if the method satisfying conditions above exists. In this case, next print two lines — the left and right parts after the cut. These two parts, being concatenated, must be exactly identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two parts must be positive integers having no leading zeros. If there are several answers, print any of them. If there is no answer, print in a single line "NO" (without the quotes).

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

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

    string str;
    readf(" %s\n", &str);
    bool[] prefnd = new bool[str.length];
    int a, b;
    readf(" %s %s\n", &a, &b);
    int pre = 0, pm = 0;
    foreach ( i; 0 .. str.length - 1 ) {
        pre += str[i] - '0';
        pm = pre % a;
        if (pm == 0) prefnd[i] = true;
        pre = pm * 10;
    }
    int ten = 1, sm = 0;
    foreach_reverse( i; 1 .. str.length ) {
        sm = (sm + (str[i] - '0') * ten) % b;
        if (sm == 0 && prefnd[i - 1] && str[i] != '0') {
            writeln("YES\n", str[0 .. i], "\n", str[i .. $]);
            return 0;
        }
        ten = (ten * 10) % b;
    }
    writeln("NO");

    return 0;
}

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

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

    string str;
    readf(" %s\n", &str);
    bool[] prefnd = new bool[str.length];
    int a, b;
    readf(" %s %s\n", &a, &b);
    long pre = 0, pm = 0;
    foreach ( i; 0 .. str.length - 1 ) {
        pre += str[i] - '0';
        pm = pre % a;
        if (pm == 0) prefnd[i] = true;
        pre = pm * 10;
    }
    long ten = 1, sm = 0;
    foreach_reverse( i; 1 .. str.length ) {
        sm = (sm + (str[i] - '0') * ten) % b;
        if (sm == 0 && prefnd[i - 1] && str[i] != '0') {
            writeln("YES\n", str[0 .. i], "\n", str[i .. $]);
            return 0;
        }
        ten = (ten * 10) % b;
    }
    writeln("NO");

    return 0;
}


Сity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right — the road network forms an undirected tree.Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:  each junction must have at most one restaurant;  each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";  each network should build at least one restaurant;  there is no pair of junctions that are connected by a road and contains restaurants of different networks. The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.

The first input line contains integer n (3 ≤ n ≤ 5000) — the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 ≤ xi, yi ≤ n) — the indexes of connected junctions. Consider the junctions indexed from 1 to n. It is guaranteed that the given road network is represented by an undirected tree with n vertexes.

Print on the first line integer z — the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.

NoteThe figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.

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

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

    auto g = new int[][] (n);
    foreach (_; 0 .. n-1) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        --u, --v;
        g[u] ~= v;
        g[v] ~= u;
    }

    debug { writeln(g); }

    auto sz = new int[] (n);

    int dfsSz(int v, int p) {
        sz[v] = 1;
        foreach (u; g[v]) {
            if (u == p) { continue; }

            sz[v] += dfsSz(u, v);
        }
        return sz[v];
    }

    dfsSz(0, -1);

    auto ans = make!(RedBlackTree!int);

    void dfs(int v, int p) {
        int[] szs;
        foreach (u; g[v]) {
            if (u == p) { continue; }

            szs ~= sz[u];
        }

        szs ~= n - szs.sum - 1;

        auto dp = new bool[] (n);
        dp[] = false;
        dp[0] = true;
        foreach (s; szs) {
            foreach_reverse (k; 0 .. n - s) {
                dp[k + s] |= dp[k];
            }
        }

        debug { writeln(v, ' ', szs, ' ', dp); }

        foreach (k; 1 .. n - 1) {
            if (dp[k]) { ans.insert(k); }
        }

        foreach (u; g[v]) {
            if (u == p) { continue; }

            dfs(u, v);
        }
    }

    dfs(0, -1);

    ans.length.writeln;
    ans.each!(x => writeln(x, ' ', n-1 - x));
}


Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!

The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.

Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.

welcome to the
Codeforces
Beta
Round 5

and
good luck

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

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

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

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

void printSpaces(int n) {
        while (n--) {
                write(" ");
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.read_int;
        string[] arr;
        while (t--) {
                string x;
                foreach (line; stdin.byLineCopy)
                        arr ~= line;

                // writeln(arr[0..$]);
                int max_len = -999;
                foreach(i; arr) {
                        max_len = max(max_len, cast(int)i.length);
                }

                for (int i = 0; i < max_len + 2; i++) {
                        write("*");
                }
                int alt = 0;
                writeln();
                for (int i = 0; i < arr.length; i++) {
                        write("*");
                        int sample_len = cast(int)arr[i].length;
                        int diff = (max_len - sample_len);
                        if (diff % 2 == 0) {
                                printSpaces(diff / 2);
                                write(arr[i]);
                                printSpaces(diff / 2);
                        } else {
                                if (alt % 2 == 0) {
                                        printSpaces(diff / 2);
                                        write(arr[i]);
                                        printSpaces(diff / 2 + 1);
                                        alt = 1;
                                } else {
                                        printSpaces(diff / 2 + 1);
                                        write(arr[i]);
                                        printSpaces(diff / 2);
                                        alt = 0;
                                }
                        }
                        writeln("*");
                }

                for (int i = 0; i < max_len + 2; i++) {
                        write("*");
                }
        }
}

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

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

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

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

void printSpaces(int n) {
        while (n--) {
                write(" ");
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.read_int;
        while (t--) {
                string[] arr = stdin.byLineCopy.array;
                // writeln(arr[0..$]);
                int max_len = -999;
                foreach(i; arr) {
                        max_len = max(max_len, cast(int)i.length);
                }

                for (int i = 0; i < max_len + 2; i++) {
                        write("*");
                }
                int alt = 0;
                writeln();
                for (int i = 0; i < arr.length; i++) {
                        write("*");
                        int sample_len = cast(int)arr[i].length;
                        int diff = (max_len - sample_len);
                        if (diff % 2 == 0) {
                                printSpaces(diff / 2);
                                write(arr[i]);
                                printSpaces(diff / 2);
                        } else {
                                if (alt % 2 == 0) {
                                        printSpaces(diff / 2);
                                        write(arr[i]);
                                        printSpaces(diff / 2 + 1);
                                        alt = 1;
                                } else {
                                        printSpaces(diff / 2 + 1);
                                        write(arr[i]);
                                        printSpaces(diff / 2);
                                        alt = 0;
                                }
                        }
                        writeln("*");
                }

                for (int i = 0; i < max_len + 2; i++) {
                        write("*");
                }
        }
}

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

void main() {
    string[] text;
    int longest = 0;
    immutable border = "*";
    immutable fill = " ";

    string line;
    while ((line = readln) != null) {
        line = line.chomp;
        text ~= line;
        longest = max(longest, line.length);
    }

    bool roundLeft = true;

    writeln(border, border.replicate(longest), border);
    foreach (string s; text) {
        int numSpaces = (longest - s.length) / 2;

        string spaces = fill.replicate(numSpaces);

        if ((s.length + longest) % 2 == 1) {
            if (roundLeft) {
                writeln(border, spaces, s, spaces, fill, border);
            } else {
                writeln(border, fill, spaces, s, spaces, border);
            }

            roundLeft = !roundLeft;
        } else {
            writeln(border, spaces, s, spaces, border);
        }
    }
    writeln(border, border.replicate(longest), border);
}