Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| ≤ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.

The first line of the input contains three integers n, r and k (1 ≤ n ≤ 500 000, 0 ≤ r ≤ n, 0 ≤ k ≤ 1018) — the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the current number of archers at each section.

Print one integer — the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute k additional archers optimally.

import core.stdc.stdio;
import std.algorithm;
int n,m;
long k;
long [500005] a,b;
bool check(long t)
{
	for (int i=1;i<=n;++i) b[i]=0;
	long x=0,s=k;
	for (int i=1;i<=m+1;++i) x+=a[i];
	for (int i=1;i<=n;++i)
	{
		if (x<t)
		{
			s-=t-x;
			if (s<0) return false;
			b[min(n,i+m)]+=t-x;
			x=t;
		}
		if (i>=m) x-=a[i-m]+b[i-m];
		if (i+1+m<=n) x+=a[i+1+m];
	}
	return s>=0;
}
void main()
{
	scanf("%d%d%lld",&n,&m,&k);
	long ans=k/n;
	for (int i=1;i<=n;++i) scanf("%lld",&a[i]);
	long l=0,r=4000000000000000000;
	while (l+1<r)
	{
		long mid=l+r>>1;
		if (check(mid))
		{
			l=mid;
			ans=mid;
		}
		else r=mid;
	}
	printf("%lld\n",ans);
}


You are given a set $$$S$$$, which contains the first $$$n$$$ positive integers: $$$1, 2, \ldots, n$$$.You can perform the following operation on $$$S$$$ any number of times (possibly zero):   Choose a positive integer $$$k$$$ where $$$1 \le k \le n$$$, such that there exists a multiple of $$$k$$$ in $$$S$$$. Then, delete the smallest multiple of $$$k$$$ from $$$S$$$. This operation requires a cost of $$$k$$$. You are given a set $$$T$$$, which is a subset of $$$S$$$. Find the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$. We can show that such a transformation is always possible.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The description of the test cases follows. The first line contains a single positive integer $$$n$$$ ($$$1 \le n \le 10^6$$$). The second line of each test case contains a binary string of length $$$n$$$, describing the set $$$T$$$. The $$$i$$$-th character of the string is '1' if and only if $$$i$$$ is an element of $$$T$$$, and '0' otherwise. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.

For each test case, output one non-negative integer — the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$.

NoteIn the first test case, we shall not perform any operations as $$$S$$$ is already equal to $$$T$$$, which is the set $$$\{1, 2, 3, 4, 5, 6\}$$$.In the second test case, initially, $$$S = \{1, 2, 3, 4, 5, 6, 7\}$$$, and $$$T = \{1, 2, 4, 7\}$$$. We shall perform the following operations:   Choose $$$k=3$$$, then delete $$$3$$$ from $$$S$$$.  Choose $$$k=3$$$, then delete $$$6$$$ from $$$S$$$.  Choose $$$k=5$$$, then delete $$$5$$$ from $$$S$$$. The total cost is $$$3+3+5 = 11$$$. It can be shown that this is the smallest cost possible.In the third test case, initially, $$$S = \{1, 2, 3, 4\}$$$ and $$$T = \{\}$$$ (empty set). We shall perform $$$4$$$ operations of $$$k=1$$$ to delete $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$.In the fourth test case, initially, $$$S = \{1, 2, 3, 4\}$$$ and $$$T = \{3\}$$$. We shall perform two operations with $$$k=1$$$ to delete $$$1$$$ and $$$2$$$, then perform one operation with $$$k=2$$$ to delete $$$4$$$.

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void solve() {
    int N = readln.chomp.to!int;
    string T = readln.chomp;

    long[] C = new long[N + 1];
    for (int i = 1; i <= N; i++) C[i] = i;

    long ans = 0;
    for (int k = 1; k <= N; k++) {
        int i = k - 1;
        if ( T[i] == '1' ) continue;
        ans += C[k];

        for (int n = k*2; n <= N; n += k) {
            if (T[n-1] == '0') {
                C[n] = min(C[n], k);
            } else {
                break;
            }
        }
    }
    writeln(ans);
}

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


Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that:  the cashier needs 5 seconds to scan one item;  after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.

The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k1, k2, ..., kn (1 ≤ ki ≤ 100), where ki is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains ki space-separated integers: mi, 1, mi, 2, ..., mi, ki (1 ≤ mi, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has.

Print a single integer — the minimum number of seconds Vasya needs to get to the cashier.

NoteIn the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.

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[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                int[] c = new int[n];
                int minTime = 99999999;
                for (int i = 0; i < n; i++) {
                        c[i] = cin.readInt;
                }
                for (int i = 0; i < n; i++) {
                        int time = 0;
                        for (int j = 0; j < c[i]; j++) {
                                time += cin.readInt * 5;
                        }
                        time += c[i] * 15;
                        minTime = min(minTime, time);
                }
                writeln(minTime);
        }
}

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

void main()
{
	int n = readln.chomp.to!int;
	auto cash = readln.split.map!(to!int);
	auto time = new int[](n);
	foreach (i; 0..n) {
		auto inp = readln.split.map!(to!int);
		foreach (j; 0 .. cash[i]) {
			time[i] += inp[j] * 5;
			time[i] += 15;
		}
	}
	time.reduce!(min).writeln;
}

import std.stdio;

byte idx;
int ans, min;

void minfoo(byte m) {
	byte temp;
	foreach (i; 0 .. m) {
		readf(" %s", &temp);
		min += temp * 5;
	}

	min += m * 15;

	if (ans > min || idx == 0)
		ans = min;

	min = 0;
}

byte[] a;

void main() {
	byte n, k;

	readf(" %s", &n);

	foreach (i; 0 .. n) {
		readf(" %s", &k);
		a ~= k;
	}

	for (idx = 0; idx < n; ++idx) {
		minfoo(a[idx]);
	}

	writeln(ans);
}

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

void main()
{
    int n = readln.chomp.to!int;
    auto cash = readln.split.map!(to!int);
    auto time = new int[](n);
    foreach (i; 0..n) {
        auto inp = readln.split.map!(to!int);
        foreach (j; 0..cash[i]) {
            time[i] += inp[j] * 5;
            time[i] += 15;
        }
    }
    time.reduce!(min).writeln;

}


Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.

For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    outer: foreach(_; 0..t)
    {
        string s = readln.strip;
        auto u = s.array.sort.uniq.array;
        int ul = cast(int) u.length;
        if (ul == 1)
        {
            writeln("yes");
            continue outer;
        }
        int[] zeros = new int[ul];
        auto tmp = assocArray(zip(u, zeros));
        foreach(int ind, ch; s.array)
        {
            if (tmp[ch] == 0)
            {
                tmp[ch] = ind + 1;
                continue;
            }
            if ((ind + 1) - tmp[ch] < ul)
            {
                writeln("no");
                continue outer;
            }
            tmp[ch] = ind + 1;
        }
        writeln("yes");
    }
}

// cheese-cracker [2022-05-03]

void solve(){
    auto word = scan!(dchar[]);
    auto seen = new int[](26);
    int uniqs = -1;
    int cntuniq = 0;
    seen[] = -1;
    for(int i = 0; i < word.length; ++i){
        int cval = (word[i] - 'a').to!int;
        if(seen[cval] != -1){
            if(uniqs != -1 && i - seen[cval] != uniqs){
                writeln("NO");
                return;
            }else{
                uniqs = (i - seen[cval]);
            }
        }else{
            ++cntuniq;
        }
        seen[cval] = i;
    }
    /* show(cntuniq, uniqs); */
    if(cntuniq == uniqs || uniqs == -1){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan.map!(c => c - 'a').array;

      auto acc = new long[][](S.length + 1, 26);
      foreach(li, c; S) {
        const int i = cast(int)li;

        foreach(d; 0..26) acc[i + 1][d] = acc[i][d];
        acc[i + 1][c]++;
      }

      int[26] pre;
      pre[] = 1;
      auto cs = 26.iota.filter!(c => acc[$ - 1][c] != 0).array;
      bool ans = true;

      // acc.each!deb;
      foreach(li, c; S) {
        const int i = cast(int)li + 1;
        // [i, c.to!int, acc[i][c]].deb;

        if (acc[i][c] > 1) {
          // i.deb;
          auto p = pre[c] - 1;
          auto ma = cs.map!(x => acc[i][x] - acc[p][x]).reduce!max;
          auto mi = cs.map!(x => acc[i][x] - acc[p][x]).reduce!min;
          // [ma, mi].deb;
          if (ma - mi > 1) {
            ans = false;
            break;
          }
        }

        pre[c] = i;
      }

      return YESNO[ans];
    }

    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"];

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

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    outer: foreach(_; 0..t)
    {
        string s = readln.strip;
        auto u = s.array.sort.uniq.array;
        int ul = cast(int) u.length;
        int[] zeros = new int[ul];
        auto tmp = assocArray(zip(u, zeros));
        foreach(ind, ch; s.array)
        {
            if (tmp[ch] == 0)
            {
                tmp[ch] = cast(int) ind;
                continue;
            }
            if (ul == 1)
            {
                writeln("yes");
                continue outer;
            }
            if (tmp[ch] - cast(int) ind < ul)
            {
                writeln("no");
                continue outer;
            }
            tmp[ch] = cast(int) ind;
        }
        writeln("yes");
    }
}


Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to n.Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from 1 to n was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal — compare the second, and so on. If we have two permutations x and y, then x is lexicographically smaller if xi < yi, where i is the first index in which the permutations x and y differ.Determine the array Ivan will obtain after performing all the changes.

The first line contains an single integer n (2 ≤ n ≤ 200 000) — the number of elements in Ivan's array. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n) — the description of Ivan's array.

In the first line print q — the minimum number of elements that need to be changed in Ivan's array in order to make his array a permutation. In the second line, print the lexicographically minimal permutation which can be obtained from array with q changes.

NoteIn the first example Ivan needs to replace number three in position 1 with number one, and number two in position 3 with number four. Then he will get a permutation [1, 2, 4, 3] with only two changed numbers — this permutation is lexicographically minimal among all suitable. In the second example Ivan does not need to change anything because his array already is a permutation.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;
    auto cnt = new int[](N+1);
    foreach (a; A) cnt[a] += 1;

    DList!int queue;
    foreach (i; 1..N+1) if (cnt[i] == 0) queue.insertBack(i);
    auto used = new bool[](N+1);
    int ans = 0;

    foreach (i; 0..N) {
        if (cnt[A[i]] > 1) {
            if (used[A[i]] || A[i] > queue.front) {
                cnt[A[i]] -= 1;
                ans += 1;
                A[i] = queue.front;
                queue.removeFront;
            } else {
                used[A[i]] = true;
            }
        }
    }

    ans.writeln;
    A.map!(a => a.to!string).join(" ").writeln;
}


You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree.

Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.

NoteThis is the tree from the first sample:  For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample:   This is the tree from the third sample:

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

immutable int mod = 10 ^^ 9 + 7;
immutable int half = invMod (2);
immutable int NA = -1;

int powMod (int a, int p)
{
	int res = 1;
	for ( ; p > 0; p >>= 1)
	{
		if (p & 1)
		{
			res = (res * 1L * a) % mod;
		}
		a = (a * 1L * a) % mod;
	}
	return res;
}

alias invMod = a => powMod (a, mod - 2);

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		auto adj = new int [] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}

		auto c = new int [] [] (n + 1, n + 1);
		c[0][0] = 1;
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				c[i + 1][j] = (c[i + 1][j] +
				    c[i][j] * 1L * half) % mod;
				c[i][j + 1] = (c[i][j + 1] +
				    c[i][j] * 1L * half) % mod;
			}
		}

		auto p = new int [] [] (n, n);
		foreach (a; 1..n)
		{
			foreach (b; 1..n)
			{
				foreach (k; 0..b)
				{
					p[a][b] = (p[a][b] +
					    c[a - 1][k]) % mod;
				}
				p[a][b] = (p[a][b] * 1L * half) % mod;
			}
		}

		int res = 0;
		foreach (w; 0..n)
		{
			auto d = new int [n];
			auto par = new int [n];

			void recur (int v, int p, int c)
			{
				d[v] = c;
				par[v] = p;
				foreach (u; adj[v])
				{
					if (u != p)
					{
						recur (u, v, c + 1);
					}
				}
			}

			recur (w, NA, 0);

			foreach (u; 0..n)
			{
				foreach (v; 0..u)
				{
					auto cu = u;
					auto cv = v;
					while (d[cu] > d[cv])
					{
						cu = par[cu];
					}
					while (d[cv] > d[cu])
					{
						cv = par[cv];
					}
					if (cu == cv)
					{
						res += (d[u] < d[v]);
						continue;
					}

					while (cu != cv)
					{
						cu = par[cu];
						cv = par[cv];
					}
					auto du = d[u] - d[cu];
					auto dv = d[v] - d[cv];
					res = (res + p[du][dv]) % mod;
				}
			}
		}

		auto nInv = invMod (n);
		res = (res * 1L * nInv) % mod;
		writeln (res);
	}
}


There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.

The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000,  - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.

Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers.

NoteExplanation to the first and second samples from the statement, respectively:

import std.stdio;

bool[1005] u;
short[1005] a, b;
short n, x, y, ans;

void main() {

	readf(" %s %s %s", &n, &x, &y);

	foreach (i; 0 .. n)
		readf(" %s %s", &a[i], &b[i]);

	foreach (i; 0 .. n)
		if(!u[i]) {
			++ans;
			foreach (j; 0 .. n)
				if ((a[i] - x) * (b[j] - y) == (a[j] - x) * (b[i] - y))
					u[j] = 1;
		}

	writeln(ans);
}

import std.stdio;
import std.algorithm;

int[] a;

void main() {

	short n, x0, y0;

	readf(" %s %s %s", &n, &x0, &y0);

	short x, y;

	readf(" %s %s", &x, &y);

	short xi, yi;
	foreach (i; 0 .. n - 1) {
		readf(" %s %s", &xi, &yi);
		if (!find(a, (y0 - yi) * x + (xi - x0) * y + (x0 * yi  - xi * y0)).length != 0)
			a ~= (y0 - yi) * x + (xi - x0) * y + (x0 * yi  - xi * y0);
	}

	writeln(a.length);
}

import std.stdio;
import std.algorithm;

int[] a;

void main() {

	short n, x0, y0;

	readf(" %s %s %s", &n, &x0, &y0);

	short x, y;

	readf(" %s %s", &x, &y);

	short xi, yi;
	foreach (i; 0 .. n - 1) {
		readf(" %s %s", &xi, &yi);
		if (!find(a, (y0 - y) * xi + (x - x0) * yi + (x0 * y  - x * y0)).length != 0)
			a ~= (y0 - y) * xi + (x - x0) * yi + (x0 * y  - x * y0);
	}

	writeln(a.length);
}

import std.stdio;
import std.algorithm;

int[] a;

void main() {

	short n, x0, y0;

	readf(" %s %s %s", &n, &x0, &y0);

	short x, y;

	readf(" %s %s", &x, &y);

	short xi, yi;
	foreach (i; 0 .. n - 1) {
		readf(" %s %s", &xi, &yi);
		if (!find(a, (y0 - yi) * x + (xi - x0) * y + (x0 * y  - xi * y0)).length != 0)
			a ~= (y0 - yi) * x + (xi - x0) * y + (x0 * yi  - xi * y0);
	}

	writeln(a.length);
}

import std.stdio;
import std.algorithm;

int[] a;

void main() {

	short n, x0, y0;

	readf(" %s %s %s", &n, &x0, &y0);

	short x, y;

	readf(" %s %s", &x, &y);

	short xi, yi;
	foreach (i; 0 .. n - 1) {
		readf(" %s %s", &xi, &yi);
		if (!find(a, (y0 - yi) * x + (xi - x0) * y + (x0 * y  - xi * y0)).length != 0)
			a ~= (y0 - yi) * x + (xi - x0) * y + (x0 * y  - xi * y0);
	}

	writeln(a.length);
}


A top-secret military base under the command of Colonel Zuev is expecting an inspection from the Ministry of Defence. According to the charter, each top-secret military base must include a top-secret troop that should... well, we cannot tell you exactly what it should do, it is a top secret troop at the end. The problem is that Zuev's base is missing this top-secret troop for some reasons.The colonel decided to deal with the problem immediately and ordered to line up in a single line all n soldiers of the base entrusted to him. Zuev knows that the loquacity of the i-th soldier from the left is equal to qi. Zuev wants to form the top-secret troop using k leftmost soldiers in the line, thus he wants their total loquacity to be as small as possible (as the troop should remain top-secret). To achieve this, he is going to choose a pair of consecutive soldiers and swap them. He intends to do so no more than s times. Note that any soldier can be a participant of such swaps for any number of times. The problem turned out to be unusual, and colonel Zuev asked you to help.Determine, what is the minimum total loquacity of the first k soldiers in the line, that can be achieved by performing no more than s swaps of two consecutive soldiers.

The first line of the input contains three positive integers n, k, s (1 ≤ k ≤ n ≤ 150, 1 ≤ s ≤ 109) — the number of soldiers in the line, the size of the top-secret troop to be formed and the maximum possible number of swap operations of the consecutive pair of soldiers, respectively. The second line of the input contains n integer qi (1 ≤ qi ≤ 1 000 000) — the values of loquacity of soldiers in order they follow in line from left to right.

Print a single integer — the minimum possible total loquacity of the top-secret troop.

NoteIn the first sample Colonel has to swap second and third soldiers, he doesn't really need the remaining swap. The resulting soldiers order is: (2, 1, 4). Minimum possible summary loquacity of the secret troop is 3. In the second sample Colonel will perform swaps in the following order:  (10, 1, 6 — 2, 5)  (10, 1, 2, 6 — 5) The resulting soldiers order is (10, 1, 2, 5, 6). Minimum possible summary loquacity is equal to 18.

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

immutable int INF = int.max / 2;

void main ()
{
	int n, k, s;
	auto workaround_to_instantiate = "10".to !(int);
	while (readf (" %s %s %s", &n, &k, &s) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		s = min (s, (n * (n - 1)) / 2);
		auto f = new int [] [] [] (2, k + 2, s + n + 1);
		int b = 0;
		foreach (ref g; f[b])
		{
			g[] = INF;
		}
		f[b][0][0] = 0;

		for (int i = 0; i < n; i++)
		{
			b ^= 1;
			foreach (ref g; f[b])
			{
				g[] = INF;
			}
			for (int j = 0; j <= min (i, k); j++)
			{
				for (int t = 0; t <= s; t++)
				{
					f[b][j][t] = min (f[b][j][t],
					    f[!b][j][t]);
					f[b][j + 1][t + i - j] =
					    min (f[b][j + 1][t + i - j],
					    f[!b][j][t] + a[i]);
				}
			}
		}

		int res = INF;
		for (int t = 0; t <= s; t++)
		{
			res = min (res, f[b][k][t]);
		}
		writeln (res);
	}
}


Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.Valentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of actions Valentin did. The next n lines contain descriptions of his actions, each line contains description of one action. Each action can be of one of three types:    Valentin pronounced some word and didn't get an electric shock. This action is described by the string ". w" (without quotes), in which "." is a dot (ASCII-code 46), and w is the word that Valentin said.  Valentin pronounced some word and got an electric shock. This action is described by the string "! w" (without quotes), in which "!" is an exclamation mark (ASCII-code 33), and w is the word that Valentin said.  Valentin made a guess about the selected letter. This action is described by the string "? s" (without quotes), in which "?" is a question mark (ASCII-code 63), and s is the guess — a lowercase English letter.  All words consist only of lowercase English letters. The total length of all words does not exceed 105. It is guaranteed that last action is a guess about the selected letter. Also, it is guaranteed that Valentin didn't make correct guesses about the selected letter before the last action. Moreover, it's guaranteed that if Valentin got an electric shock after pronouncing some word, then it contains the selected letter; and also if Valentin didn't get an electric shock after pronouncing some word, then it does not contain the selected letter.

Output a single integer — the number of electric shocks that Valentin could have avoided if he had told the selected letter just after it became uniquely determined.

8
! hello
! codeforces
? c
. o
? d
? h
. l
? e

7
! ababahalamaha
? a
? b
? a
? b
? a
? h

NoteIn the first test case after the first action it becomes clear that the selected letter is one of the following: a, b, c. After the second action we can note that the selected letter is not a. Valentin tells word "b" and doesn't get a shock. After that it is clear that the selected letter is c, but Valentin pronounces the word cd and gets an excessive electric shock. In the second test case after the first two electric shocks we understand that the selected letter is e or o. Valentin tries some words consisting of these letters and after the second word it's clear that the selected letter is e, but Valentin makes 3 more actions before he makes a correct hypothesis.In the third example the selected letter can be uniquely determined only when Valentin guesses it, so he didn't get excessive electric shocks.

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

void main() {
    int n;
    scan(n);

    int ans;
    int set = (1<<26) - 1;
    bool safe;

    foreach (i ; 0 .. n-1) {
        char e;
        string s;
        scan(e, s);

        if (safe && e != '.') {
            ans++;
            continue;
        }

        int t;

        if (e == '!') {
            foreach (ch ; s) {
                t |= (1<<(ch - 'a'));
            }
        }
        else if (e == '.') {
            t = (1<<26) - 1;
            foreach (ch ; s) {
                t &= ~(1<<(ch - 'a'));
            }
        }
        else {
            t = ~(1<<(s[0] - 'a'));
        }

        set &= t;

        debug {
            writefln("%b",set);
        }

        if (set.popcnt == 1) {
            safe = 1;
        }
    }

    writeln(ans);
}

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

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

/+ dub.sdl:
    name "A"
    dependency "dunkelheit" version=">=0.9.0"
+/

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

import core.bitop;

immutable int B = 26;

int main() {
    Scanner sc = new Scanner(stdin);
    int n;
    sc.read(n);
    int f = (1<<B) - 1;
    int ans = 0;
    foreach (i; 0..n-1) { //ignore last query
        char ty; string s;
        sc.read(ty, s);

        bool uni = popcnt(f) == 1;

        if (ty == '!') {
            //shock
            if (uni) ans++;
            int nf = 0;
            foreach (c; s) {
                nf |= (1 << (c - 'a'));
            }
            f &= nf;
        } else if (ty == '.') {
            int nf = 0;
            foreach (c; s) {
                nf |= (1 << (c - 'a'));
            }
            f &= ~nf;
        } else if (ty == '?') {
            if (uni) ans++;

            int nf = 0;
            foreach (c; s) {
                nf |= (1 << (c - 'a'));
            }
            f &= ~nf;
        }
    }
//    writeln(f, " ", popcnt(f));
    writeln(ans);
    return 0;
}
/* IMPORT /Users/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

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

    private T* _data;
    private uint len, cap;

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

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

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

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

    void clear() {
        len = 0;
    }

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

/* IMPORT /Users/yosupo/Program/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

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

}
/* IMPORT /Users/yosupo/Program/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

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

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

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


You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k < m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold:   every red cell in the left matrix contains an integer greater than every blue cell in the left matrix;  every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.

For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k < m$$$) — the number of columns from the left that are cut.

NoteThe coloring and the cut for the first testcase:

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto m = readInt!int;
	auto a = ma(n, ma(m, readInt!int));
	auto minmaxL = new Tuple!(int, int)[][](n);
	auto minmaxR = new Tuple!(int, int)[][](n);
	foreach(i, ref ai; a)
	{
		minmaxL[i] = ai.cumulativeFold!(min, max).array;
		minmaxR[i] = ai.retro.cumulativeFold!(min, max).array.retro.array;
	}
	char[] getConfiguration(int k)
	{
		debug writeln("for k = ", k);
		struct Row
		{
			Tuple!(int, int) left, right;
		}
		Row[] rows = new Row[](n);
		foreach(i, ref rowi; rows)
		{
			rowi = Row(minmaxL[i][k], minmaxR[i][k+1]);
		}
		debug writeln("rows = ", rows);
		auto events = new Tuple!(int, int, int)[](2 * n);
		int evlen = 0;
		foreach(i, row; rows)
		{
			events[evlen++] = tuple(row.left[0], +1, cast(int)i);
			events[evlen++] = tuple(row.left[1] + 1, -1, cast(int)i);
		}
		int pfMinPrev = int.max;
		int sfMaxPrev = int.min;
		auto pfMin = new int[](2 * n);
		auto sfMax = new int[](2 * n);
		sort(events);
		debug writeln("events = ", events);
		debug writeln("evlen = ", evlen);
		foreach(i, evi; events)
		{
			if (evi[1] == +1)
			{
				pfMinPrev = min(pfMinPrev, rows[evi[2]].right[0]);
			}
			pfMin[i] = pfMinPrev;
		}

		foreach_reverse(i, evi; events)
		{
			if (evi[1] == +1)
			{
				sfMaxPrev = max(sfMaxPrev, rows[evi[2]].right[1]);
			}
			sfMax[i] = sfMaxPrev;
		}
		debug writeln("pfMin = ", pfMin);
		debug writeln("sfMax = ", sfMax);
		int open = 0;
		int cut = -1;
		auto color = new char[](n);
		color[] = 'R';
		foreach(i, evi; events)
		{
			open += evi[1];
			if (i+1 < events.length && open == 0)
			{
				debug writeln("found a cut at i = ", i);
				if (pfMin[i] > sfMax[i])
				{
					debug writeln("it's a good cut!");
					foreach(j; 0 .. i)
					{
						if (events[j][1] > 0)
						{
							color[events[j][2]] = 'B';
						}
					}
					return color;
				}
			}
		}
		return null;
	}
	foreach(k; 0 .. m - 1)
	{
		auto config = getConfiguration(k);
		if (config !is null)
		{
			writeln("YES");
			config.write(" ");
			return writeln(k+1);
		}
	}
	return writeln("NO");
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto m = readInt!int;
	auto a = ma(n, ma(m, readInt!int));
	auto minmaxL = new Tuple!(int, int)[][](n);
	auto minmaxR = new Tuple!(int, int)[][](n);
	foreach(i, ref ai; a)
	{
		minmaxL[i] = ai.cumulativeFold!(min, max).array;
		minmaxR[i] = ai.retro.cumulativeFold!(min, max).array.retro.array;
	}
	char[] getConfiguration(int k)
	{
		debug writeln("for k = ", k);
		struct Row
		{
			Tuple!(int, int) left, right;
		}
		Row[] rows = new Row[](n);
		foreach(i, ref rowi; rows)
		{
			rowi = Row(minmaxL[i][k], minmaxR[i][k+1]);
		}
		debug writeln("rows = ", rows);
		auto events = new Tuple!(int, int, int)[](2 * n);
		int evlen = 0;
		foreach(i, row; rows)
		{
			events[evlen++] = tuple(row.left[0], cast(int)i, +1);
			events[evlen++] = tuple(row.left[1] + 1, cast(int)i, -1);
		}
		int pfMinPrev = int.max;
		int sfMaxPrev = int.min;
		auto pfMin = new int[](2 * n);
		auto sfMax = new int[](2 * n);
		sort(events);
		debug writeln("events = ", events);
		debug writeln("evlen = ", evlen);
		foreach(i, evi; events)
		{
			if (evi[2] == +1)
			{
				pfMinPrev = min(pfMinPrev, rows[evi[1]].right[0]);
			}
			pfMin[i] = pfMinPrev;
		}

		foreach_reverse(i, evi; events)
		{
			if (evi[2] == +1)
			{
				sfMaxPrev = max(sfMaxPrev, rows[evi[1]].right[1]);
			}
			sfMax[i] = sfMaxPrev;
		}
		debug writeln("pfMin = ", pfMin);
		debug writeln("sfMax = ", sfMax);
		int open = 0;
		int cut = -1;
		auto color = new char[](n);
		color[] = 'R';
		foreach(i, evi; events)
		{
			open += evi[2];
			if (i+1 < events.length && open == 0)
			{
				debug writeln("found a cut at i = ", i);
				if (pfMin[i] > sfMax[i])
				{
					debug writeln("it's a good cut!");
					foreach(j; 0 .. i)
					{
						if (events[j][2] > 0)
						{
							color[events[j][1]] = 'B';
						}
					}
					return color;
				}
			}
		}
		return null;
	}
	foreach(k; 0 .. m - 1)
	{
		auto config = getConfiguration(k);
		if (config !is null)
		{
			writeln("YES");
			config.write(" ");
			return writeln(k+1);
		}
	}
	return writeln("NO");
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto m = readInt!int;
	auto a = ma(n, ma(m, readInt!int));
	auto minmaxL = new Tuple!(int, int)[][](n);
	auto minmaxR = new Tuple!(int, int)[][](n);
	foreach(i, ref ai; a)
	{
		minmaxL[i] = ai.cumulativeFold!(min, max).array;
		minmaxR[i] = ai.retro.cumulativeFold!(min, max).array.retro.array;
	}
	char[] getConfiguration(int k)
	{
		debug writeln("for k = ", k);
		struct Row
		{
			Tuple!(int, int) left, right;
		}
		Row[] rows = new Row[](n);
		foreach(i, ref rowi; rows)
		{
			rowi = Row(minmaxL[i][k], minmaxR[i][k+1]);
		}
		debug writeln("rows = ", rows);
		auto events = new Tuple!(int, int, int)[](2 * n);
		int evlen = 0;
		foreach(i, row; rows)
		{
			events[evlen++] = tuple(row.left[0], cast(int)i, +1);
			events[evlen++] = tuple(row.left[1] + 1, cast(int)i, -1);
		}
		int pfMinPrev = int.max;
		int sfMaxPrev = int.min;
		auto pfMin = new int[](2 * m);
		auto sfMax = new int[](2 * m);
		sort(events);
		debug writeln("events = ", events);
		debug writeln("evlen = ", evlen);
		foreach(i, evi; events)
		{
			if (evi[2] == +1)
			{
				pfMinPrev = min(pfMinPrev, rows[evi[1]].right[0]);
			}
			pfMin[i] = pfMinPrev;
		}

		foreach_reverse(i, evi; events)
		{
			if (evi[2] == +1)
			{
				sfMaxPrev = max(sfMaxPrev, rows[evi[1]].right[1]);
			}
			sfMax[i] = sfMaxPrev;
		}
		debug writeln("pfMin = ", pfMin);
		debug writeln("sfMax = ", sfMax);
		int open = 0;
		int cut = -1;
		auto color = new char[](n);
		color[] = 'R';
		foreach(i, evi; events)
		{
			open += evi[2];
			if (i+1 < events.length && open == 0)
			{
				debug writeln("found a cut at i = ", i);
				if (pfMin[i] > sfMax[i])
				{
					debug writeln("it's a good cut!");
					foreach(j; 0 .. i)
					{
						if (events[j][2] > 0)
						{
							color[events[j][1]] = 'B';
						}
					}
					return color;
				}
			}
		}
		return null;
	}
	foreach(k; 0 .. m - 1)
	{
		auto config = getConfiguration(k);
		if (config !is null)
		{
			writeln("YES");
			config.write(" ");
			return writeln(k+1);
		}
	}
	return writeln("NO");
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}


A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a ≤ b, he or she likes it if and only if he can climb into this car and 2a ≥ b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.

You are given four integers V1, V2, V3, Vm(1 ≤ Vi ≤ 100) — sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V1 > V2 > V3.

Output three integers — sizes of father bear's car, mother bear's car and son bear's car, respectively. If there are multiple possible solutions, print any. If there is no solution, print "-1" (without quotes).

NoteIn first test case all conditions for cars' sizes are satisfied.In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20.

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

void main() {
    int a,b,c,d;
    scan(a,b,c,d);

    foreach (i ; a .. 2*a + 1) {
        foreach (j ; b .. min(i, 2*b + 1)) {
            foreach (k ; c .. min(j, 2*c + 1)) {
                if (d <= k && k <= 2*d && j > 2*d) {
                    writeln(i);
                    writeln(j);
                    writeln(k);
                    return;
                }
            }
        }
    }

    writeln(-1);
}

void solve(int a, int L) {
    auto as = new int[](21);
    as[0] = a;

    foreach (i ; 1 .. 21) {
        as[i] = calmax(as[i-1], L) - calmin(as[i-1], L);

        foreach (j ; 0 .. i) {
            if (as[i] == as[j]) {
                writeln(j, " ", as[i], " ", i-j);
                return;
            }
        }
    }
}

int calmax(int x, int L) {
    auto cnt = new int[](10);

    while (x > 0) {
        cnt[x % 10]++;
        x /= 10;
    }

    cnt[0] += max(0, L - cnt.sum);

    int res;
    foreach_reverse (i ; 0 .. 10) {
        foreach (j ; 0 .. cnt[i]) {
            res *= 10;
            res += i;
        }
    }

    debug {
        writeln(res);
    }

    return res;
}

int calmin(int x, int L) {
    auto cnt = new int[](10);

    while (x > 0) {
        cnt[x % 10]++;
        x /= 10;
    }

    cnt[0] += max(0, L - cnt.sum);

    int res;
    foreach (i ; 0 .. 10) {
        foreach (j ; 0 .. cnt[i]) {
            res *= 10;
            res += i;
        }
    }

    debug {
        writeln(res);
    }

    return res;
}

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

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

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

void main() {
    int a,b,c,d;
    scan(a,b,c,d);

    foreach (i ; a .. 2*a + 1) {
        foreach (j ; b .. min(i, 2*b + 1)) {
            foreach (k ; c .. min(j, 2*c + 1)) {
                if (d <= k && k <= 2*d) {
                    writeln(i);
                    writeln(j);
                    writeln(k);
                    return;
                }
            }
        }
    }

    writeln(-1);
}

void solve(int a, int L) {
    auto as = new int[](21);
    as[0] = a;

    foreach (i ; 1 .. 21) {
        as[i] = calmax(as[i-1], L) - calmin(as[i-1], L);

        foreach (j ; 0 .. i) {
            if (as[i] == as[j]) {
                writeln(j, " ", as[i], " ", i-j);
                return;
            }
        }
    }
}

int calmax(int x, int L) {
    auto cnt = new int[](10);

    while (x > 0) {
        cnt[x % 10]++;
        x /= 10;
    }

    cnt[0] += max(0, L - cnt.sum);

    int res;
    foreach_reverse (i ; 0 .. 10) {
        foreach (j ; 0 .. cnt[i]) {
            res *= 10;
            res += i;
        }
    }

    debug {
        writeln(res);
    }

    return res;
}

int calmin(int x, int L) {
    auto cnt = new int[](10);

    while (x > 0) {
        cnt[x % 10]++;
        x /= 10;
    }

    cnt[0] += max(0, L - cnt.sum);

    int res;
    foreach (i ; 0 .. 10) {
        foreach (j ; 0 .. cnt[i]) {
            res *= 10;
            res += i;
        }
    }

    debug {
        writeln(res);
    }

    return res;
}

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

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


You are given a sequence of integers of length $$$n$$$ and integer number $$$k$$$. You should print any integer number $$$x$$$ in the range of $$$[1; 10^9]$$$ (i.e. $$$1 \le x \le 10^9$$$) such that exactly $$$k$$$ elements of given sequence are less than or equal to $$$x$$$.Note that the sequence can contain equal elements.If there is no such $$$x$$$, print "-1" (without quotes).

The first line of the input contains integer numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le n$$$). The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the sequence itself.

Print any integer number $$$x$$$ from range $$$[1; 10^9]$$$ such that exactly $$$k$$$ elements of given sequence is less or equal to $$$x$$$. If there is no such $$$x$$$, print "-1" (without quotes).

NoteIn the first example $$$5$$$ is also a valid answer because the elements with indices $$$[1, 3, 4, 6]$$$ is less than or equal to $$$5$$$ and obviously less than or equal to $$$6$$$.In the second example you cannot choose any number that only $$$2$$$ elements of the given sequence will be less than or equal to this number because $$$3$$$ elements of the given sequence will be also less than or equal to this number.

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

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

    auto a = new int[n];

    foreach (ref t; a) readf(" %s", t);

    sort(a);

    if (k == 0 && a[0] > 1)
    {
        writeln(1);
    }
    else if (k == n || k > 0 && a[k-1] != a[k])
    {
        writeln(a[k-1]);
    }
    else
    {
        writeln(-1);
    }
}

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

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

    auto a = readln.split.map!(to!int).array;
    a.sort();

    if (k == 0) {
        writeln(a[0] > 1 ? 1 : -1);
    } else if (k == n) {
        writeln(a[n-1]);
    } else {
        writeln(k == n || a[k-1] != a[k] ? a[k-1] : -1);
    }
}

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

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

    auto a = readln.split.map!(to!int).array;
    a.sort();

    if (k == 0) {
        writeln(a[0] > 1 ? 1 : -1);
    } else if (k == n) {
        writeln(a[n-1]);
    } else {
        writeln(a[k-1] != a[k] ? a[k-1] : -1);
    }
}

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

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

void main()
{
  int n, k; readV(n, k);
  int[] a; readA(n, a);

  a.sort();

  if (k == 0) {
    if (a[0] == 1)
      writeln(-1);
    else
      writeln(a[0]-1);
  } else {
    if (a[k-1] == 0 || a[k-1] == a[k])
      writeln(-1);
    else
      writeln(a[k-1]);
  }
}

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

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

    auto a = new int[n];

    foreach (ref t; a) readf(" %s", t);

    sort(a);

    if (k == n || a[k-1] != a[k])
    {
        writeln(a[k-1]);
    }
    else
    {
        writeln(-1);
    }
}

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

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

    auto a = new int[n];

    foreach (ref t; a) readf(" %s", t);

    auto sortedRange = sort(a);

    if (sortedRange.upperBound(a[k-1]).length == n-k)
    {
        writeln(a[k-1]);
    }
    else
    {
        writeln(-1);
    }
}

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

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

void main()
{
  int n, k; readV(n, k);
  int[] a; readA(n, a);

  a.sort();
  if (a[k-1] == 0 || a[k-1] == a[k])
    writeln(-1);
  else
    writeln(a[k-1]);
}

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

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

void main()
{
  int n, k; readV(n, k);
  int[] a; readA(n, a);

  a.sort();
  if (a[k-1] == a[k])
    writeln(-1);
  else
    writeln(a[k-1]);
}


Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:   Tetrahedron. Tetrahedron has 4 triangular faces.  Cube. Cube has 6 square faces.  Octahedron. Octahedron has 8 triangular faces.  Dodecahedron. Dodecahedron has 12 pentagonal faces.  Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below:  Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:   "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.  "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.  "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.  "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.  "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.

Output one number — the total number of faces in all the polyhedrons in Anton's collection.

4
Icosahedron
Cube
Tetrahedron
Dodecahedron

NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.

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

void main() {
    int n;
    scan(n);

    int[char] a = ['T': 4, 'C': 6 , 'O': 8, 'D': 12, 'I': 20];

    int ans;

    foreach (i ; 0 .. n) {
        auto s = readln.chomp;
        ans += a[s[0]];
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

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

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


Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence.

The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109).

Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r].

NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}.

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			scanf (" %d", &a[i]);
		}
		int [] s;
		int res = 0;
		foreach (i; 0..n)
		{
			while (s.length >= 1 && s[$ - 1] < a[i])
			{
				res = max (res, s[$ - 1] ^ a[i]);
				s.length--;
			}
			s ~= a[i];
			if (s.length >= 2)
			{
				res = max (res, s[$ - 1] ^ s[$ - 2]);
			}
		}
		writefln ("%s", res);
	}
}

import std.algorithm;
import std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
			scanf (" %d", &a[i]);
		int [] s;
		int res;
		foreach (i; 0..n)
		{
			while (s.length && s[$ - 1] < a[i])
			{
				res = max (res, s[$ - 1] ^ a[i]);
				s.length--;
			}
			if (s.length)
				res = max (res, s[$ - 1] ^ a[i]);
			s ~= a[i];
		}
		writeln (res);
	}
}


Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?The cost of sending the message is the sum of the costs of sending every word in it.

The first line of input contains integers n, k and m (1 ≤ k ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively. The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct. The third line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) where ai is the cost of sending the i-th word. The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 ≤ x ≤ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group. The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.

The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.

5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second

5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second

NoteIn the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.

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

auto read()
{
	return readln.strip.split;
}

auto readn()
{
	return read.map!(to!int).array;
}

void main()
{
	auto ns = readn;
	auto words = read;

	int[string] weight;

	foreach(i, w; readn)
	{
		weight[words[i]] = w;
	}

	foreach(gw; ns[1].iota.map!(_ => readn))
	{
		auto ws = words.indexed(gw[1..$].map!(a => a - 1));
		auto m = ws.map!(a => weight[a]).reduce!min;

		ws.each!(a => weight[a] = m);
	}

	read.map!(a => weight[a]).reduce!`long(a)+b`.writeln;
}

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;

void main()
{
	auto aaa = readln.chomp.split.map!(to!int);
	int n = aaa[0];
	int k = aaa[1];
	int m = aaa[2];
	string[] msg = readln.chomp.split;
	ulong[string] mapper;
	foreach (i, s; msg) {
		mapper[s] = i;
	}
	ulong[] cost = readln.chomp.split.map!(to!ulong).array;
	ulong[] best = new ulong[n];
	foreach (i; 0..k) {
		auto bbb = readln.chomp.split.map!(to!ulong);
		ulong x = bbb[0];
		ulong[] a = bbb[1..$].array;
		ulong ans = ulong.max;
		foreach (v; a) {
			ulong w = v - 1;
			ans = min(ans, cost[cast(uint)w]);
		}
		// stderr.writeln([x, ans]);
		foreach (v; a) {
			ulong w = v - 1;
			best[cast(uint)w] = ans;
			// stderr.writeln("\tbest : ", msg[w], " :", [w, ans]);
		}
	}
	string[] next = readln.chomp.split;
	ulong sum = 0;
	foreach (s; next) {
		sum += best[cast(uint)mapper[s]];
	}
	sum.writeln;
}

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T t){t=new T(n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(ElementType!T);r.popFront;}}
void readM(T...)(size_t n,ref T t){foreach(ref v;t)v=new typeof(v)(n);foreach(i;0..n){auto r=readln.splitter;foreach(ref v;t){v[i]=r.front.to!(ElementType!(typeof(v)));r.popFront;}}}
void readS(T)(size_t n,ref T t){t=new T(n);foreach(ref v;t){auto r=readln.splitter;foreach(ref j;v.tupleof){j=r.front.to!(typeof(j));r.popFront;}}}

void main()
{
  int n, k, m; readV(n, k, m);
  string[] w; readA(n, w);
  int[] a; readA(n, a);
  auto g = new int[][](k);
  foreach (i; 0..k) g[i] = readXA!int;
  foreach (ref gi; g) gi[] -= 1;
  string[] s; readA(m, s);

  auto mc = new int[](k);
  foreach (int i, gi; g)
    mc[i] = gi.map!(gij => a[gij]).fold!min;

  auto h = new int[](n);
  foreach (int i, gi; g)
    foreach (gij; gi)
      h[gij] = mc[i];

  int[string] wg;
  foreach (int i, wi; w) wg[wi] = h[i];

  writeln(s.map!(si => wg[si].to!long).sum);
}

T[] readXA(T)()
{
  auto r = readln.splitter;
  auto x = r.front.to!size_t; r.popFront;
  auto a = new T[](x);
  foreach (i; 0..x) {
    a[i] = r.front.to!T;
    r.popFront;
  }
  return a;
}

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

auto read()
{
	return readln.strip.split;
}

auto readn()
{
	return read.map!(to!int).array;
}

void main()
{
	auto ns = readn;
	auto words = read;

	int[string] weight;

	foreach(i, w; readn)
	{
		weight[words[i]] = w;
	}

	foreach(gw; ns[1].iota.map!(_ => readn))
	{
		auto ws = words.indexed(gw[1..$].map!(a => a - 1));
		auto m = ws.map!(a => weight[a]).reduce!min;

		ws.each!(a => weight[a] = m);
	}

	read.map!(a => weight[a]).reduce!`a+b`.writeln;
}

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;

void main()
{
	auto aaa = readln.chomp.split.map!(to!int);
	int n = aaa[0];
	int k = aaa[1];
	int m = aaa[2];
	string[] msg = readln.chomp.split;
	ulong[string] mapper;
	foreach (i, s; msg) {
		mapper[s] = i;
	}
	int[] cost = readln.chomp.split.map!(to!int).array;
	int[] best = new int[n];
	foreach (i; 0..k) {
		auto bbb = readln.chomp.split.map!(to!int);
		int x = bbb[0];
		int[] a = bbb[1..$].array;
		int ans = int.max;
		foreach (v; a) {
			int w = v - 1;
			ans = min(ans, cost[w]);
		}
		// stderr.writeln([x, ans]);
		foreach (v; a) {
			int w = v - 1;
			best[w] = ans;
			// stderr.writeln("\tbest : ", msg[w], " :", [w, ans]);
		}
	}
	string[] next = readln.chomp.split;
	int sum = 0;
	foreach (s; next) {
		sum += best[cast(uint)mapper[s]];
	}
	sum.writeln;
}

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T t){t=new T(n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(ElementType!T);r.popFront;}}
void readM(T...)(size_t n,ref T t){foreach(ref v;t)v=new typeof(v)(n);foreach(i;0..n){auto r=readln.splitter;foreach(ref v;t){v[i]=r.front.to!(ElementType!(typeof(v)));r.popFront;}}}
void readS(T)(size_t n,ref T t){t=new T(n);foreach(ref v;t){auto r=readln.splitter;foreach(ref j;v.tupleof){j=r.front.to!(typeof(j));r.popFront;}}}

void main()
{
  int n, k, m; readV(n, k, m);
  string[] w; readA(n, w);
  int[] a; readA(n, a);
  auto g = new int[][](k);
  foreach (i; 0..k) g[i] = readXA!int;
  foreach (ref gi; g) gi[] -= 1;
  string[] s; readA(m, s);

  auto mc = new int[](k);
  foreach (int i, gi; g)
    mc[i] = gi.map!(gij => a[gij]).fold!min;

  auto h = new int[](n);
  foreach (int i, gi; g)
    foreach (gij; gi)
      h[gij] = mc[i];

  int[string] wg;
  foreach (int i, wi; w) wg[wi] = h[i];

  writeln(s.map!(si => wg[si]).sum);
}

T[] readXA(T)()
{
  auto r = readln.splitter;
  auto x = r.front.to!size_t; r.popFront;
  auto a = new T[](x);
  foreach (i; 0..x) {
    a[i] = r.front.to!T;
    r.popFront;
  }
  return a;
}


Let us denote by $$$d(n)$$$ the sum of all divisors of the number $$$n$$$, i.e. $$$d(n) = \sum\limits_{k | n} k$$$.For example, $$$d(1) = 1$$$, $$$d(4) = 1+2+4=7$$$, $$$d(6) = 1+2+3+6=12$$$.For a given number $$$c$$$, find the minimum $$$n$$$ such that $$$d(n) = c$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$c$$$ ($$$1 \le c \le 10^7$$$).

For each test case, output:    "-1" if there is no such $$$n$$$ that $$$d(n) = c$$$;  $$$n$$$, otherwise.

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

void main() {
  auto total = new long[10000001];
  for (int i = 1; i < 10000001; i++) {
    for (int j = i; j < 10000001; j += i) {
      total[j] += i;
    }
  }

  int[] ans = new int[10000001];
  ans.fill(-1);

  for (int i = 0; i < 10000001; i++) {
    if (total[i] < 10000001 && ans[to!uint(total[i])] == -1) {
      ans[to!uint(total[i])] = i;
    }
  }

  int n;
  readf!"%d"(n);

  while (n--) {
    int c;
    readf!" %d"(c);
    writeln(ans[c]);
  }
}

import std.stdio;
import std.algorithm;
import std.conv;
void main()
{
    auto total = new long[10000001];
    for(int i = 1; i < 10000001; i++) {
        for(int j = i; j < 10000001; j += i){
            total[j] += i;
        }
   }
    int[] at = new int[10000001];
    at.fill(-1);
    for(int i = 10000000;i>0;i--){
        if(total[i]<10000001){
            at[to!uint(total[i])] = i ;
    }
    }
    int n;
  readf!"%d"(n);

  while (n--) {
    int c;
    readf!" %d"(c);
    writeln(at[c]);
  }
}

import std.stdio;
import std.algorithm;

void main() {
  auto total = new long[10000001];
  for (int i = 1; i < 10000001; i++) {
    for (int j = i; j < 10000001; j += i) {
      total[j] += i;
    }
  }

  int[long] m;

  for (int i = 0; i < 50; i++) {
    if (total[i] !in m) {
      m[total[i]] = i;
    }
  }

  int n;
  readf!"%d"(n);

  while (n--) {
    int c;
    readf!" %d"(c);
    if (c !in m) {
      writeln(-1);
    } else {
      writeln(m[c]);
    }
  }

}