One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.But his plan failed. The reason for this was very simple: Hexadecimal didn't perceive any information, apart from numbers written in binary format. This means that if a number in a decimal representation contained characters apart from 0 and 1, it was not stored in the memory. Now Megabyte wants to know, how many numbers were loaded successfully.

Input data contains the only number n (1≤n≤10^9).

Output the only number — answer to the problem.

For n = 10 the answer includes numbers 1 and 10.

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

char[] dec_to_binary(int n) {
        char[] s;
        while (n > 0) {
                s ~= (n & 1) + 48;
                n >>= 1;
        }
        reverse(s);
        return s;
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                int count = 0;
                for (int i = 1; i < (1 << 10); i++) {
                        if (dec_to_binary(i).to!long <= n) {
                                count++;
                        } else break;
                }
                writeln(count);
        }
}


Notice: unusual memory limit!After the war, destroyed cities in the neutral zone were restored. And children went back to school.The war changed the world, as well as education. In those hard days, a new math concept was created.As we all know, logarithm function can be described as: $$$$$$ \log(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 \log p_1 + a_2 \log p_2 + ... + a_k \log p_k $$$$$$ Where $$$p_1^{a_1}p_2^{a_2}...p_k^{a_2}$$$ is the prime factorization of a integer. A problem is that the function uses itself in the definition. That is why it is hard to calculate.So, the mathematicians from the neutral zone invented this: $$$$$$ \text{exlog}_f(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 f(p_1) + a_2 f(p_2) + ... + a_k f(p_k) $$$$$$Notice that $$$\text{exlog}_f(1)$$$ is always equal to $$$0$$$.This concept for any function $$$f$$$ was too hard for children. So teachers told them that $$$f$$$ can only be a polynomial of degree no more than $$$3$$$ in daily uses (i.e., $$$f(x) = Ax^3+Bx^2+Cx+D$$$)."Class is over! Don't forget to do your homework!" Here it is: $$$$$$ \sum_{i=1}^n \text{exlog}_f(i) $$$$$$Help children to do their homework. Since the value can be very big, you need to find the answer modulo $$$2^{32}$$$.

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

immutable int limit = 50_000;

void main ()
{
	auto s = new bool [limit];
	s[] = true;
	s[0] = false;
	s[1] = false;
	for (uint g = 2; g * g < limit; g++)
	{
		if (s[g])
		{
			for (uint e = g; e * g < limit; e++)
			{
				s[e * g] = false;
			}
		}
	}

	uint [] p;
	foreach (g; 0..limit)
	{
		if (s[g])
		{
			p ~= g;
		}
	}

	uint n;
	uint a, b, c, d;
	while (readf (" %s %s %s %s %s", &n, &a, &b, &c, &d) > 0)
	{
		uint res = 0;
		auto t = new bool [limit];
		for (uint start = 0; start <= n; start += limit)
		{
			uint finish = min (start + limit, n + 1);
			if (start == 0)
			{
				t[] = s[];
			}
			else
			{
				t[] = true;
				foreach (g; p)
				{
					uint lo = (start + g - 1) / g * g;
					while (lo < finish)
					{
						t[lo - start] = false;
						lo += g;
					}
				}
			}
			foreach (i; start..finish)
			{
				if (t[i - start])
				{
					debug {writeln (i);}
					uint cur = a;
					cur = cur * i + b;
					cur = cur * i + c;
					cur = cur * i + d;

					uint mult = 0;
					uint k = n;
					while (k > 0)
					{
						k /= i;
						mult += k;
					}
					res += cur * mult;
				}
			}
		}
		writeln (res);
	}
}


Lavrenty, a baker, is going to make several buns with stuffings and sell them.Lavrenty has n grams of dough as well as m different stuffing types. The stuffing types are numerated from 1 to m. Lavrenty knows that he has ai grams left of the i-th stuffing. It takes exactly bi grams of stuffing i and ci grams of dough to cook a bun with the i-th stuffing. Such bun can be sold for di tugriks.Also he can make buns without stuffings. Each of such buns requires c0 grams of dough and it can be sold for d0 tugriks. So Lavrenty can cook any number of buns with different stuffings or without it unless he runs out of dough and the stuffings. Lavrenty throws away all excess material left after baking.Find the maximum number of tugriks Lavrenty can earn.

The first line contains 4 integers n, m, c0 and d0 (1≤n≤1000, 1≤m≤10, 1≤c0,d0≤100). Each of the following m lines contains 4 integers. The i-th line contains numbers ai, bi, ci and di (1≤ai,bi,ci,di≤100).

Print the only number — the maximum number of tugriks Lavrenty can earn.

To get the maximum number of tugriks in the first sample, you need to cook 2 buns with stuffing 1, 4 buns with stuffing 2 and a bun without any stuffing.
In the second sample Lavrenty should cook 4 buns without stuffings.

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

void main(){
	auto x=readln().strip.split.map!(to!int).array;
	int n=x[0],m=x[1],c0=x[2],d0=x[3];
	auto buns=iota(m).map!(_=>readln().strip.split.map!(to!int).array);
	Tuple!(int,int)[] ss;
	foreach(bun;chain(only([0,0,c0,d0]),buns)){
		int num=bun[1]?bun[0]/bun[1]:2000;
		int cost=bun[2];
		int benefit=bun[3];
		foreach(k;0..num) ss~=tuple(cost,benefit);
	}
	auto t=0.repeat(n+1).array;
	foreach(s;ss){
		foreach_reverse(i;0..t.length){
			if(i<s[0]) continue;
			t[i]=max(t[i],t[i-s[0]]+s[1]);
		}
	}
	writeln(t[n]);
}


This is the easy version of the problem. The only difference between easy and hard versions is the constraint of $$$m$$$. You can make hacks only if both versions are solved.Chiori loves dolls and now she is going to decorate her bedroom! As a doll collector, Chiori has got $$$n$$$ dolls. The $$$i$$$-th doll has a non-negative integer value $$$a_i$$$ ($$$a_i < 2^m$$$, $$$m$$$ is given). Chiori wants to pick some (maybe zero) dolls for the decoration, so there are $$$2^n$$$ different picking ways.Let $$$x$$$ be the bitwise-xor-sum of values of dolls Chiori picks (in case Chiori picks no dolls $$$x = 0$$$). The value of this picking way is equal to the number of $$$1$$$-bits in the binary representation of $$$x$$$. More formally, it is also equal to the number of indices $$$0 ≤ i < m$$$, such that $$$\left\lfloor \frac{x}{2^i} \right\rfloor$$$ is odd.Tell her the number of picking ways with value $$$i$$$ for each integer $$$i$$$ from $$$0$$$ to $$$m$$$. Due to the answers can be very huge, print them by modulo $$$998\,244\,353$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 35$$$)  — the number of dolls and the maximum value of the picking way.
The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^m$$$)  — the values of dolls.

Print $$$m+1$$$ integers $$$p_0, p_1, \ldots, p_m$$$  — $$$p_i$$$ is equal to the number of picking ways with value $$$i$$$ by modulo $$$998\,244\,353$$$.

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

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

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

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

enum MO = 998244353;
alias Mint = ModInt!MO;

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

      long[] bases;
      foreach (i; 0 .. N) {
        long a = A[i];
        foreach (base; bases) {
          chmin(a, a ^ base);
        }
        if (a) {
          bases ~= a;
        }
      }
      bases.sort!"a > b";
      const r = cast(int)(bases.length);
      foreach (j; 0 .. r) {
        foreach (k; j + 1 .. r) {
          chmin(bases[k], bases[k] ^ bases[j]);
        }
      }
      debug {
        foreach (base; bases) {
          writefln("%0*b", M, base);
        }
      }

      long[] ps, qs;
      foreach (j; 0 .. r) {
        if (bases[j] & ~((1L << (M / 2)) - 1)) {
          ps ~= bases[j];
        } else {
          qs ~= bases[j];
        }
      }
      debug {
        writeln("ps = ", ps);
        writeln("qs = ", qs);
      }
      const psLen = cast(int)(ps.length);
      const qsLen = cast(int)(qs.length);
      auto psSum = new long[1 << psLen];
      auto qsSum = new long[1 << qsLen];
      foreach (j; 0 .. psLen) {
        foreach (h; 0 .. 1 << j) {
          psSum[h | 1 << j] = psSum[h] ^ ps[j];
        }
      }
      foreach (j; 0 .. qsLen) {
        foreach (h; 0 .. 1 << j) {
          qsSum[h | 1 << j] = qsSum[h] ^ qs[j];
        }
      }
      auto xss = new Mint[][](M - M / 2 + 1, 1 << (M / 2));
      auto ys = new Mint[1 << (M / 2)];
      foreach (h; 0 .. 1 << psLen) {
        xss[popcnt(psSum[h] >> (M / 2))][cast(int)(psSum[h] & ((1L << (M / 2)) - 1))] += 1;
      }
      foreach (h; 0 .. 1 << qsLen) {
        ys[cast(int)(qsSum[h])] += 1;
      }

      foreach (e; 0 .. M / 2) {
        foreach (f; 0 .. 1 << (M / 2)) {
          if (!(f & 1 << e)) {
            const tmp = ys[f] - ys[f | 1 << e];
            ys[f] += ys[f | 1 << e];
            ys[f | 1 << e] = tmp;
          }
        }
      }
      const invTwo = Mint(2)^^(-(M / 2));
      auto ans = new Mint[M + 1];
      foreach (s; 0 .. M - M / 2 + 1) {
        foreach (e; 0 .. M / 2) {
          foreach (f; 0 .. 1 << (M / 2)) {
            if (!(f & 1 << e)) {
              const tmp = xss[s][f] - xss[s][f | 1 << e];
              xss[s][f] += xss[s][f | 1 << e];
              xss[s][f | 1 << e] = tmp;
            }
          }
        }
        xss[s][] *= ys[];
        xss[s][] *= invTwo;
        foreach (e; 0 .. M / 2) {
          foreach (f; 0 .. 1 << (M / 2)) {
            if (!(f & 1 << e)) {
              const tmp = xss[s][f] - xss[s][f | 1 << e];
              xss[s][f] += xss[s][f | 1 << e];
              xss[s][f | 1 << e] = tmp;
            }
          }
        }
        foreach (f; 0 .. 1 << (M / 2)) {
          ans[s + popcnt(f)] += xss[s][f];
        }
      }

      ans[] *= Mint(2)^^(N - r);
      foreach (s; 0 .. M + 1) {
        if (s > 0) write(" ");
        write(ans[s]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.You decided to rob a town's blacksmith and you take a follower with you. You can carry at most $$$p$$$ units and your follower — at most $$$f$$$ units.In the blacksmith shop, you found $$$cnt_s$$$ swords and $$$cnt_w$$$ war axes. Each sword weights $$$s$$$ units and each war axe — $$$w$$$ units. You don't care what to take, since each of them will melt into one steel ingot.What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?

The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) — the number of test cases.
The first line of each test case contains two integers $$$p$$$ and $$$f$$$ ($$$1 \\le p, f \\le 10^9$$$) — yours and your follower's capacities.
The second line of each test case contains two integers $$$cnt_s$$$ and $$$cnt_w$$$ ($$$1 \\le cnt_s, cnt_w \\le 2 \\cdot 10^5$$$) — the number of swords and war axes in the shop.
The third line of each test case contains two integers $$$s$$$ and $$$w$$$ ($$$1 \\le s, w \\le 10^9$$$) — the weights of each sword and each war axe.
It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed $$$2 \\cdot 10^5$$$.

For each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.

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

void main()
{
    auto t = readln.chomp.to!int;

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

    while (t--) {
        auto cap = rln();
        auto cnt = rln();
        auto w = rln();

        if (w[0] > w[1]) {
            swap(w[0], w[1]);
            swap(cnt[0], cnt[1]);
        }

        int fitItem(ref int sz, const int w, ref int cnt) {
            int fit = min(cnt, sz / w);
            sz -= fit * w;
            cnt -= fit;
            return fit;
        }

        int mxinfst = min(cnt[0], cap[0] / w[0]);
        int ans = 0;
        foreach (oneinfst; 0 .. mxinfst + 1) {
            auto sz = cap.dup;
            auto cnttmp = [cnt[0] - oneinfst, cnt[1]];

            int cur = fitItem(sz[0], w[0], oneinfst);
            cur += fitItem(sz[0], w[1], cnttmp[1]);

            cur += fitItem(sz[1], w[0], cnttmp[0]);
            cur += fitItem(sz[1], w[1], cnttmp[1]);

            ans = max(ans, cur);
        }

        ans.writeln;
    }
}


Polycarp found on the street an array $$$a$$$ of $$$n$$$ elements.Polycarp invented his criterion for the beauty of an array. He calls an array $$$a$$$ beautiful if at least one of the following conditions must be met for each different pair of indices $$$i \ne j$$$:   $$$a_i$$$ is divisible by $$$a_j$$$;  or $$$a_j$$$ is divisible by $$$a_i$$$. For example, if:   $$$n=5$$$ and $$$a=[7, 9, 3, 14, 63]$$$, then the $$$a$$$ array is not beautiful (for $$$i=4$$$ and $$$j=2$$$, none of the conditions above is met);  $$$n=3$$$ and $$$a=[2, 14, 42]$$$, then the $$$a$$$ array is beautiful;  $$$n=4$$$ and $$$a=[45, 9, 3, 18]$$$, then the $$$a$$$ array is not beautiful (for $$$i=1$$$ and $$$j=4$$$ none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array $$$a$$$ so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array $$$a$$$ beautiful.

The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10$$$) — the number of test cases. Then $$$t$$$ test cases follow.
The first line of each test case contains one integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$) — the length of the array $$$a$$$.
The second line of each test case contains $$$n$$$ numbers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 2 \\cdot 10^5$$$) — elements of the array $$$a$$$.

For each test case output one integer — the minimum number of elements that must be removed to make the array $$$a$$$ beautiful.

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int N; get(N);
        auto memo = new int[](10^^5 * 2 + 1);
        foreach (a; readln.split) memo[a.to!int] += 1;

        auto DP = new int[](10^^5 * 2 + 1);
        foreach (i; 1..10^^5 * 2 + 1) {
            DP[i] += memo[i];
            auto j = i * 2;
            while (j <= 10^^5 * 2) {
                DP[j] = max(DP[i], DP[j]);
                j += i;
            }
        }

        writeln(N - DP.maxElement());
    }
}


"The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny.The Chamber of Secrets is an n×m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below.   The left light ray passes through a regular column, and the right ray — through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position.   This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.

The first line of the input contains two integer numbers n and m (2≤n,m≤1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column.

Print the minimum number of columns to make magic or -1 if it's impossible to do.

The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns.

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

    string[] arr;
    foreach (i; 0 .. n) { arr ~= readln.chomp; }

    debug { arr.writefln!"%(%s %)"; }

    auto rows = new bool[] (n);
    auto cols = new bool[] (m);

    auto rq = make!(DList!int), cq = make!(DList!int);
    rq ~= n-1;

    int step = 0;
    bool reach = false;
    outer: while (!rq.empty()) {
        step += 2;
        while (!rq.empty()) {
            int x = rq.front();
            rq.removeFront();

            if (rows[x]) { continue; }

            rows[x] = true;
            foreach (i; 0 .. m) {
                if (arr[x][i] == '.') { continue; }
                if (cols[i]) { continue; }

                cq ~= i;
            }
        }

        while (!cq.empty()) {
            int x = cq.front();
            cq.removeFront();

            if (cols[x]) { continue; }

            cols[x] = true;
            foreach (i; 0 .. n) {
                if (arr[i][x] == '.') { continue; }
                if (rows[i]) { continue; }

                if (i == 0) {
                    reach = true;
                    break outer;
                }

                rq ~= i;
            }
        }
    }

    if (!reach) {
        writeln(-1);
        return;
    }

    step.writeln;
}


Vasya has recently bought some land and decided to surround it with a wooden fence.He went to a company called "Wooden board" that produces wooden boards for fences. Vasya read in the catalog of products that the company has at its disposal n different types of wood. The company uses the i-th type of wood to produce a board of this type that is a rectangular ai by bi block.Vasya decided to order boards in this company and build a fence from them. It turned out that the storehouse of the company is so large that Vasya can order arbitrary number of boards of every type. Note that Vasya is allowed to turn the boards as he builds the fence. However, Vasya cannot turn square boards.Vasya is required to construct a fence of length l, however, an arbitrary fence won't do. Vasya wants his fence to look beautiful. We'll say that a fence is beautiful if and only if the following two conditions are fulfilled:  there are no two successive boards of the same type  the first board of the fence has an arbitrary length, and the length of each subsequent board equals the width of the previous one In other words, the fence is considered beautiful, if the type of the i-th board in the fence is different from the i-1-th board's type; besides, the i-th board's length is equal to the i-1-th board's width (for all i, starting from 2).Now Vasya wonders, how many variants of arranging a fence for his land exist. Your task is to count the number of different beautiful fences of length l.Two fences will be considered the same if the corresponding sequences of fence boards types and rotations are the same, otherwise the fences are different. Since the sought number can be large enough, you need to calculate the answer modulo 1000000007 (10^9+7).

The first line contains two integers n and l (1≤n≤100,1≤l≤3000) — the number of different board types and the fence length, correspondingly. Next n lines contain descriptions of board types: the i-th line contains two integers ai and bi (1≤ai,bi≤100) — the sizes of the board of the i-th type. All numbers on the lines are separated by spaces.

Print a single integer — the sought number of variants modulo 1000000007 (10^9+7).

In the first sample there are exactly two variants of arranging a beautiful fence of length 3:
  As the first fence board use the board of the first type of length 1 and width 2. As the second board use board of the second type of length 2 and width 3.  Use one board of the second type after you turn it. That makes its length equal 3, and width — 2.

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;

immutable int MD = 10 ^^ 9 + 7;

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

    int[][] arr;
    foreach (i; 0 .. n) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        arr ~= [x, y];
    }

    debug { arr.writeln; }

    auto dp = new int[][][] (len+1, n, 2);
    foreach (i, e; arr) {
        if (e[0] <= len) { dp[e[0]][i][0] = 1; }
        if (e[1] <= len && e[1] != e[0]) { dp[e[1]][i][1] = 1; }
    }

    debug { dp.writeln; }

    foreach (clen; 2 .. len+1) {
        foreach (i, e; arr) {
            foreach (turn; 0 .. 2) {
                if (turn == 1 && e[0] == e[1]) { continue; }

                int elen = e[turn];
                if (elen >= clen) { continue; }

                foreach (j, p; arr) {
                    if (i == j) { continue; }

                    foreach (pTurn; 0 .. 2) {
                        if (pTurn == 1 && p[0] == p[1]) { continue; }

                        int pMatch = p[1 - pTurn];
                        if (elen != pMatch) { continue; }

                        debug { if (clen == 3 && i == 1) { writeln(turn, ' ', j, ' ', pTurn, ' ', pMatch, ' ', dp[clen-elen][j][pTurn]); } }
                        dp[clen][i][turn] = (dp[clen][i][turn] + dp[clen-elen][j][pTurn]) % MD;
                    }
                }
            }
        }
    }

    debug { dp.each!writeln; }

    int ans = 0;
    foreach (ref e; dp[len]) {
        foreach (et; e) { ans = (ans + et) % MD; }
    }

    ans.writeln;
}


The Fat Rat and his friend Сerealguy have had a bet whether at least a few oats are going to descend to them by some clever construction. The figure below shows the clever construction. A more formal description of the clever construction is as follows. The clever construction consists of n rows with scales. The first row has n scales, the second row has (n-1) scales, the i-th row has (n-i+1) scales, the last row has exactly one scale. Let's number the scales in each row from the left to the right, starting from 1. Then the value of wi,k in kilograms (1≤i≤n; 1≤k≤n-i+1) is the weight capacity parameter of the k-th scale in the i-th row. If a body whose mass is not less than wi,k falls on the scale with weight capacity wi,k, then the scale breaks. At that anything that the scale has on it, either falls one level down to the left (if possible) or one level down to the right (if possible). In other words, if the scale wi,k (i<n) breaks, then there are at most two possible variants in which the contents of the scale's pan can fall out: all contents of scale wi,k falls either on scale wi+1,k-1 (if it exists), or on scale wi+1,k (if it exists). If scale wn,1 breaks, then all its contents falls right in the Fat Rat's claws. Please note that the scales that are the first and the last in a row, have only one variant of dropping the contents.Initially, oats are simultaneously put on all scales of the first level. The i-th scale has ai kilograms of oats put on it. After that the scales start breaking and the oats start falling down in some way. You can consider everything to happen instantly. That is, the scale breaks instantly and the oats also fall instantly.The Fat Rat is sure that whatever happens, he will not get the oats from the first level. Cerealguy is sure that there is such a scenario, when the rat gets at least some number of the oats. Help the Fat Rat and the Cerealguy. Determine, which one is right.

The first line contains a single integer n (1≤n≤50) — the number of rows with scales.
The next line contains n space-separated integers ai (1≤ai≤10^6) — the masses of the oats in kilograms.
The next n lines contain descriptions of the scales: the i-th line contains (n-i+1) space-separated integers wi,k (1≤wi,k≤10^6) — the weight capacity parameters for the scales that stand on the i-th row, in kilograms.

Print "Fat Rat" if the Fat Rat is right, otherwise print "Cerealguy".

Notes to the examples:
  The first example: the scale with weight capacity 2 gets 1. That means that the lower scale don't break.  The second sample: all scales in the top row obviously break. Then the oats fall on the lower row. Their total mass is 4,and that's exactly the weight that the lower scale can "nearly endure". So, as 4 ≥ 4, the scale breaks.

import std.stdio;
import std.random;

static immutable N = 50;

int n, sum, now;
int[N + 1] a, b;
int[N + 1][N + 1] w;

int main() {
  auto input = stdin;
  auto output = stdout;
  input.readf(" %d", &n);
  for (int i = 1; i <= n; ++ i)
    input.readf(" %d", &a[i]), sum += a[i];
  for (int i = 1; i <= n; ++ i)
    for (int j = 1; j <= n - i + 1; ++ j)
      input.readf(" %d", &w[i][j]);
  int T = 100000;
  while (T --) {
    b = a, now = sum;
    for (int i = 1; i < n; ++ i) {
      int t = n - i + 1;
      for (int j = 1; j <= t; ++ j) {
        if (b[j] < w[i][j]) {
          now -= b[j], b[j] = 0;
          if (now < w[n][1]) break;
        } else if (j == n - i + 1) b[j - 1] += b[j], b[j] = 0;
        else if (j != 1)
          if (b[j - 1] + b[j] >= w[i + 1][j - 1])
            if ((uniform(0, 2) || T == 99999) && T != 99998) b[j - 1] += b[j], b[j] = 0;
      }
      if (now < w[n][1]) break;
    }
    if (now >= w[n][1] && b[1] >= w[n][1]) {
      output.writeln("Cerealguy");
      return 0;
    }
  }
  output.writeln("Fat Rat");
  return 0;
}


The new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of the path is required only in case of the path to the root directory, which can be represented as single character '/'.A path called normalized if it contains the smallest possible number of characters '/'.Your task is to transform a given path to the normalized form.

The first line of the input contains only lowercase Latin letters and character '/' — the path to some directory. All paths start with at least one character '/'. The length of the given line is no more than 100 characters, it is not empty.

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

void main()
{
    auto s = readln.chomp;

    dchar[] ans;
    foreach (i; 0 .. s.length) {
        if (s[i] == '/' && i > 0 && s[i-1] == '/') { continue; }

        ans ~= s[i];
    }

    if (ans.length > 1 && ans.back() == '/') { ans.popBack(); }

    ans.writeln;
}

[{'input': ['//usr///local//nginx/sbin\r\n'], 'output': ['/usr/local/nginx/sbin\r\n']}, {'input': ['////a//b/////g\r\n'], 'output': ['/a/b/g\r\n']}, {'input': ['/a/b/c\r\n'], 'output': ['/a/b/c\r\n']}, {'input': ['/\r\n'], 'output': ['/\r\n']}, {'input': ['////\r\n'], 'output': ['/\r\n']}, {'input': ['/a//aa/a//\r\n'], 'output': ['/a/aa/a\r\n']}, {'input': ['/aa//b/aa\r\n'], 'output': ['/aa/b/aa\r\n']}, {'input': ['////////////////////////////////////////////////////////////////////////////////////////////////////\r\n'], 'output': ['/\r\n']}, {'input': ['/opt///pokerband///srvb/opt///pokerband///srvb////pokerband///srvb/\r\n'], 'output': ['/opt/pokerband/srvb/opt/pokerband/srvb/pokerband/srvb\r\n']}, {'input': ['/root/pokerband/trunk/server/game/code/src/main/java/com/uosipa/pokerband/gameserver/game/\r\n'], 'output': ['/root/pokerband/trunk/server/game/code/src/main/java/com/uosipa/pokerband/gameserver/game\r\n']}, {'input': ['/root//pokerband/trunk/server/game/code/src///main/java/com/uosipa/pokerband//gameserver/game//\r\n'], 'output': ['/root/pokerband/trunk/server/game/code/src/main/java/com/uosipa/pokerband/gameserver/game\r\n']}, {'input': ['/root//pokerband/trunk/server/game/code/src///main/java/com/uosipa/pokerband//gameserver/game//test/\r\n'], 'output': ['/root/pokerband/trunk/server/game/code/src/main/java/com/uosipa/pokerband/gameserver/game/test\r\n']}, {'input': ['/root//pokerband/trunk/server/game/code/src///main/java/com/uosipa/pokerband//gameserver/game//testt\r\n'], 'output': ['/root/pokerband/trunk/server/game/code/src/main/java/com/uosipa/pokerband/gameserver/game/testt\r\n']}, {'input': ['///a//a////a/a//a//a//a/////\r\n'], 'output': ['/a/a/a/a/a/a/a\r\n']}, {'input': ['/zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\r\n'], 'output': ['/zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\r\n']}, {'input': ['/zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz/\r\n'], 'output': ['/zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\r\n']}, {'input': ['/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a\r\n'], 'output': ['/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a\r\n']}, {'input': ['///////////////////////////////////////////////////////////////////////////////////////////////////z\r\n'], 'output': ['/z\r\n']}, {'input': ['/z//////////////////////////////////////////////////////////////////////////////////////////////////\r\n'], 'output': ['/z\r\n']}]


You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad.A substring s[l...r] (1≤l≤r≤|s|) of string s=s1s2...s|s| (where |s| is the length of string s) is string slsl+1...sr.The substring s[l...r] is good, if among the letters sl,sl+1,...,sr there are at most k bad ones (look at the sample's explanation to understand it more clear).Your task is to find the number of distinct good substrings of the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their content is different, i.e. s[x...y]≠s[p...q].

The first line of the input is the non-empty string s, consisting of small English letters, the string's length is at most 1500 characters.
The second line of the input is the string of characters "0" and "1", the length is exactly 26 characters. If the i-th character of this string equals "1", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on.
The third line of the input consists a single integer k (0≤k≤|s|) — the maximum acceptable number of bad characters in a good substring.

Print a single integer — the number of distinct good substrings of string s.

In the first example there are following good substrings: "a", "ab", "b", "ba", "bab".
In the second example there are following good substrings: "a", "aa", "ac", "b", "ba", "c", "ca", "cb".

import std;

class TrieNode(alias T) {
    T value;
    TrieNode[26] cs;
    this(T value) {
        this.value = value;
    }
    ref TrieNode opIndex(char c) {
        assert(std.ascii.isAlpha(c));
        int i = cast(int)(c - 'a');
        return cs[i];
    }
}

void main() {
    auto s = readln.chomp;
    auto g = readln.chomp;
    auto k = readln.chomp.to!int;
    int N = cast(int)(s.length);

    bool is_bad(char c) {
        return g[ cast(int)(c - 'a') ] == '0';
    }

    long ans = 0;
    auto root = new TrieNode!bool(false);
    for (int i = 0; i < N; i++) {
        auto c = root;
        int bcount = 0;
        for (int j = i; j < N; j++) {
            if (is_bad(s[j])) {
                bcount++;
            }
            if (bcount > k) {
                break;
            }
            if (c[s[j]] is null) {
                c[s[j]] = new TrieNode!bool(false);
            }
            c = c[s[j]];
            if (! c.value) {
                c.value = true;
                ans++;
            }
        }
    }
    writeln(ans);
}


Greg has a pad. The pad's screen is an n×m rectangle, each cell can be either black or white. We'll consider the pad rows to be numbered with integers from 1 to n from top to bottom. Similarly, the pad's columns are numbered with integers from 1 to m from left to right.Greg thinks that the pad's screen displays a cave if the following conditions hold:  There is a segment [l,r] (1≤l≤r≤n), such that each of the rows l,l+1,...,r has exactly two black cells and all other rows have only white cells.  There is a row number t (l≤t≤r), such that for all pairs of rows with numbers i and j (l≤i≤j≤t) the set of columns between the black cells in row i (with the columns where is these black cells) is the subset of the set of columns between the black cells in row j (with the columns where is these black cells). Similarly, for all pairs of rows with numbers i and j (t≤i≤j≤r) the set of columns between the black cells in row j (with the columns where is these black cells) is the subset of the set of columns between the black cells in row i (with the columns where is these black cells). Greg wondered, how many ways there are to paint a cave on his pad. Two ways can be considered distinct if there is a cell that has distinct colors on the two pictures.Help Greg.

The first line contains two integers n, m — the pad's screen size (1≤n,m≤2000).

In the single line print the remainder after dividing the answer to the problem by 1000000007 (10^9+7).

import std.stdio;

immutable int MOD = 1_000_000_007;

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m))
	{
		auto f = new long [] [n + 1];
		foreach (p; 0..n + 1)
		{
			f[p] = new long [m + 1];
		}
		foreach (p; 1..n + 1)
		{
			long cur;
			foreach (d; 2..m + 1)
			{
				cur += f[p - 1][d];
				f[p][d] = f[p][d - 1] + cur;
				if (d == 2)
				{
					f[p][d] += 1;
				}
				f[p][d] %= MOD;
			}
		}

		long res;
		foreach (d; 2..m + 1)
		{
			long cur;
			foreach (p; 1..n + 1)
			{
				cur += f[p][d] *
				       (f[n - p + 1][d] - f[n - p][d]);
				cur %= MOD;
			}
			cur *= m - d + 1;
			res += cur;
		}

		writeln (res % MOD);
	}
}


Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.Arithmetic progression is a sequence a1, a1+d, a1+2d, ..., a1+(n-1)d, where a1 and d are any numbers.Geometric progression is a sequence b1, b2=b1q, ..., bn=bn-1q, where b1≠0, q≠0, q≠1. Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer.

The first line contains exactly four integer numbers between 1 and 1000, inclusively.

Print the required number. If the given sequence is arithmetic progression, print the next progression element. Similarly, if the given sequence is geometric progression, print the next progression element.
Print 42 if the given sequence is not an arithmetic or geometric progression.

This problem contains very weak pretests!

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

void main ()
{
	int a, b, c, d;
	while (readf (" %s %s %s %s", &a, &b, &c, &d) > 0)
	{
		if (b - a == c - b && c - b == d - c)
		{
			writeln (d + d - c);
		}
		else if (a != 0 && c != 0 && b * b == a * c &&
		         b != 0 && d != 0 && c * c == b * d &&
		         (d * d / c) * c == d * d)
		{
			writeln (d * d / c);
		}
		else
		{
			writeln (42);
		}
	}
}


A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius r (the cupboard's top) and two walls of height h (the cupboard's sides). The cupboard's depth is r, that is, it looks like a rectangle with base r and height h+r from the sides. The figure below shows what the cupboard looks like (the front view is on the left, the side view is on the right). Xenia got lots of balloons for her birthday. The girl hates the mess, so she wants to store the balloons in the cupboard. Luckily, each balloon is a sphere with radius . Help Xenia calculate the maximum number of balloons she can put in her cupboard. You can say that a balloon is in the cupboard if you can't see any part of the balloon on the left or right view. The balloons in the cupboard can touch each other. It is not allowed to squeeze the balloons or deform them in any way. You can assume that the cupboard's walls are negligibly thin.

The single line contains two integers r,h (1≤r,h≤10^7).

Print a single integer — the maximum number of balloons Xenia can put in the cupboard.

module main;

import std.stdio;
import std.math;

int main(string[] args)
{
    int h,r,d,countH;
    int ans;
    readf(" %s %s", &r, &h);
    countH = (2*h + r) / (2*r);
    ans = countH * 2;
    if(countH * r + (sqrt(3f)/2)*r < h + r)
        ++ans;
    writeln(ans);
    return 0;
}


Simon has a prime number x and an array of non-negative integers a1,a2,...,an.Simon loves fractions very much. Today he wrote out number  on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals x^a1+a2+...+an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (10^9+7).

The first line contains two positive integers n and x (1≤n≤10^5, 2≤x≤10^9) — the size of the array and the prime number.
The second line contains n space-separated integers a1,a2,...,an (0≤a1≤a2≤...≤an≤10^9).

Print a single number — the answer to the problem modulo 1000000007 (10^9+7).

In the first sample . Thus, the answer to the problem is 8.
In the second sample, . The answer to the problem is 27, as 351=13·27, 729=27·27.
In the third sample the answer to the problem is 1073741824 mod 1000000007=73741817.
In the fourth sample . Thus, the answer to the problem is 1.

import std.stdio;
import std.algorithm;
import std.container;

const int MAX = 100005;
const int MOD = 1000000007;
int n;
long x;
long[MAX] a;
long[long] count;

void main() {
    readf(" %s %s", n, x);
    foreach(i; 0..n) readf(" %s", a[i]);

    long totalSum = sum(a[0..n]);
    foreach(i; 0..n) a[i] = totalSum - a[i];
    foreach(i; 0..n) count[a[i]]++;
    auto heap = heapify!"a > b"(count.keys);

    long result = 0;
    do {
        auto value = heap.front;
        heap.popFront();

        auto y = count[value];
        auto k = 0;
        while (y % x == 0) {
            y /= x;
            k++;
        }

        if (k == 0) {
            result = value;
            break;
        }

        auto next = value + k;
        if (next !in count) {
            heap.insert(next);
        }
        count[next] += y;
    } while(!heap.empty);

    writeln(power(min(result, totalSum)));
}

long power(long m) {
    if (m == 0) return 1;
    if (m == 1) return x % MOD;
    auto v = power(m/2);
    if (m % 2 == 0) {
        return (v * v) % MOD;
    } else {
        return (((v * v) % MOD) * x) % MOD;
    }
}


Sereja has m non-empty sets of integers A1,A2,...,Am. What a lucky coincidence! The given sets are a partition of the set of all integers from 1 to n. In other words, for any integer v (1≤v≤n) there is exactly one set At such that . Also Sereja has integer d.Sereja decided to choose some sets from the sets he has. Let's suppose that i1,i2,...,ik (1≤i1<i2<...<ik≤m) are indexes of the chosen sets. Then let's define an array of integers b, sorted in ascending order, as a union of the chosen sets, that is, . We'll represent the element with number j in this array (in ascending order) as bj. Sereja considers his choice of sets correct, if the following conditions are met:b1≤d; bi+1-bi≤d (1≤i<|b|); n-d+1≤b|b|.Sereja wants to know what is the minimum number of sets (k) that he can choose so that his choice will be correct. Help him with that.

The first line contains integers n, m, d (1≤d≤n≤10^5,1≤m≤20). The next m lines contain sets. The first number in the i-th line is si (1≤si≤n). This number denotes the size of the i-th set. Then the line contains si distinct integers from 1 to n — set Ai.
It is guaranteed that the sets form partition of all integers from 1 to n.

In a single line print the answer to the problem — the minimum value k at the right choice.

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

void main ()
{
	int n, m, d;
	while (readf (" %s %s %s", &n, &m, &d) > 0)
	{
		auto a = new int [n];
		a[] = -1;
		foreach (i; 0..m)
		{
			int len;
			readf (" %s", &len);
			foreach (j; 0..len)
			{
				int x;
				readf (" %s", &x);
				x--;
				enforce (a[x] == -1);
				a[x] = i;
			}
		}
		foreach (i; 0..n)
		{
			enforce (a[i] != -1);
		}

		int m2 = 1 << m;
		auto v = new bool [m2];
		v[] = false;
		auto c = new int [m];
		c[] = 0;
		int mask = 0;
		foreach (i; 0..n)
		{
			int cur = a[i];
			if (c[cur] == 0)
			{
				mask |= 1 << cur;
			}
			c[cur]++;
			if (i >= d)
			{
				int prev = a[i - d];
				c[prev]--;
				if (c[prev] == 0)
				{
					mask &= ~(1 << prev);
				}
			}
			if (i >= d - 1)
			{
				v[m2 - 1 - mask] = true;
			}
		}

		foreach_reverse (s; 0..m2)
		{
			foreach (i; 0..m)
			{
				if (s & (1 << i))
				{
					debug {writeln (s, " ", i, " ",
					                s ^ (1 << i));}
					v[s ^ (1 << i)] |= v[s];
				}
			}
		}

		long res = m;
		foreach (s; 0..m2)
		{
			if (!v[s])
			{
				res = min (res, popcnt (s));
			}
		}
		writeln (res);
	}
}


Kostya is a progamer specializing in the discipline of Dota 2. Valve Corporation, the developer of this game, has recently released a new patch which turned the balance of the game upside down. Kostya, as the captain of the team, realizes that the greatest responsibility lies on him, so he wants to resort to the analysis of innovations patch from the mathematical point of view to choose the best heroes for his team in every game.A Dota 2 match involves two teams, each of them must choose some heroes that the players of the team are going to play for, and it is forbidden to choose the same hero several times, even in different teams. In large electronic sports competitions where Kostya's team is going to participate, the matches are held in the Captains Mode. In this mode the captains select the heroes by making one of two possible actions in a certain, predetermined order: pick or ban.  To pick a hero for the team. After the captain picks, the picked hero goes to his team (later one of a team members will play it) and can no longer be selected by any of the teams.  To ban a hero. After the ban the hero is not sent to any of the teams, but it still can no longer be selected by any of the teams. The team captain may miss a pick or a ban. If he misses a pick, a random hero is added to his team from those that were available at that moment, and if he misses a ban, no hero is banned, as if there was no ban.Kostya has already identified the strength of all the heroes based on the new patch fixes. Of course, Kostya knows the order of picks and bans. The strength of a team is the sum of the strengths of the team's heroes and both teams that participate in the match seek to maximize the difference in strengths in their favor. Help Kostya determine what team, the first one or the second one, has advantage in the match, and how large the advantage is.

The first line contains a single integer n (2≤n≤100) — the number of heroes in Dota 2.
The second line contains n integers s1, s2, ..., sn (1≤si≤10^6) — the strengths of all the heroes.
The third line contains a single integer m (2≤m≤min(n,20)) — the number of actions the captains of the team must perform.
Next m lines look like "action team", where action is the needed action: a pick (represented as a "p") or a ban (represented as a "b"), and team is the number of the team that needs to perform the action (number 1 or 2).
It is guaranteed that each team makes at least one pick. Besides, each team has the same number of picks and the same number of bans.

Print a single integer — the difference between the strength of the first team and the strength of the second team if the captains of both teams will act optimally well.

import std.algorithm,std.stdio,core.bitop;void main(){int n,m,w,k;scanf("%d",&n);auto s=new int[n];foreach(ref x;s)scanf("%d",&x);sort!"a>b"(s);scanf("%d ",&m);int[]t;foreach(i;0..m){auto r=readln;t~=(r[0]=='p')*2+(r[2]=='2');}w=1<<m;auto f=new int[w];foreach(u;1..w){k=m-u.popcnt;f[u]=(t[k]&1)?int.max:int.min;foreach(j;0..m)if(u&(1<<j)){int v=u^(1<<j);switch(t[k]){case 0:f[u]=max(f[u],f[v]);break;case 1:f[u]=min(f[u],f[v]);break;case 2:f[u]=max(f[u],f[v]+s[j]);break;case 3:f[u]=min(f[u],f[v]-s[j]);break;default:}}}f[w-1].writeln;}


Ksenia has her winter exams. Today she is learning combinatorics. Here's one of the problems she needs to learn to solve.How many distinct trees are there consisting of n vertices, each with the following properties:  the tree is marked, that is, the vertices of the tree are numbered from 1 to n;  each vertex of the tree is connected with at most three other vertices, and at the same moment the vertex with number 1 is connected with at most two other vertices;  the size of the tree's maximum matching equals k. Two trees are considered distinct if there are such two vertices u and v, that in one tree they are connected by an edge and in the other tree they are not.Help Ksenia solve the problem for the given n and k. As the answer to the problem can be very huge you should output it modulo 1000000007 (10^9+7).

The first line contains two integers n,k (1≤n,k≤50).

Print a single integer — the answer to the problem modulo 1000000007 (10^9+7).

If you aren't familiar with matchings, please, read the following link: http://en.wikipedia.org/wiki/Matching_(graph_theory).

import std.stdio;

immutable int MOD   = 1_000_000_007;
immutable int HALF  = (MOD / 2) + 1;
immutable int MAX_N =            54;

struct modint
{
	long value;

	alias value this;

	this (long nvalue)
	{
		value = nvalue;
	}

	modint opBinary (string op) (long other)
	{
		return mixin ("modint ((value " ~ op ~ " other) % MOD)");
	}

	modint opOpAssign (string op, T) (T other)
	{
		return mixin ("this = this " ~ op ~ " other");
	}
}

void main ()
{
	auto c = new modint [] [] (MAX_N, MAX_N);

	foreach (n; 0..MAX_N)
	{
		c[n][0] = 1;
		foreach (k; 1..n + 1)
		{
			c[n][k] = c[n - 1][k - 1] + c[n - 1][k];
		}
	}

	auto f = new modint [] [] [] (MAX_N, MAX_N, 2);
	f[1][0][1] = 1;

	foreach (n; 2..MAX_N)
	{
		foreach (k; 0..n + 1)
		{
			foreach (b; 0..2)
			{
				int pk = k - (b == 0);
				if (pk >= 0)
				{
					f[n][k][b] = f[n - 1][pk][!b] *
					             (n - 1);
				}
			}

			foreach (x; 1..n - 1)
			{
				int y = n - 1 - x;
				assert (x > 0 && y > 0);
				modint mult = c[n - 1][x] * x * y;

				foreach (xk; 0..k + 1)
				{
					int yk = void;

					yk = k - xk - 1;
					if (yk >= 0)
					{
						f[n][k][0] += f[x][xk][1] *
						    f[y][yk][0] * mult;
						if (x < y ||
						    (x <= y && xk <= yk))
						{
							modint mult2 = mult;
							if (x == y && xk == yk)
							{
								mult2 *= HALF;
							}
							f[n][k][0] += mult2 *
							    f[x][xk][1] *
							    f[y][yk][1];
						}
					}

					yk = k - xk;
					if (x < y || (x <= y && xk <= yk))
					{
						modint mult2 = mult;
						if (x == y && xk == yk)
						{
							mult2 *= HALF;
						}
						f[n][k][1] += f[x][xk][0] *
						    f[y][yk][0] * mult2;
					}
				}
			}
		}
	}

	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		writeln (f[n][k][0] + f[n][k][1]);
	}
}


Alas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy. The phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppose that Masha's phone number is 12345. After that one should write her favorite digit from 0 to 9 under the first digit of her number. That will be the first digit of the needed number. For example, Masha's favorite digit is 9. The second digit is determined as a half sum of the second digit of Masha's number and the already written down first digit from her beloved one's number. In this case the arithmetic average equals to (2+9)/2=5.5. Masha can round the number up or down, depending on her wishes. For example, she chooses the digit 5. Having written down the resulting digit under the second digit of her number, Masha moves to finding the third digit in the same way, i.e. finding the half sum the the third digit of her number and the second digit of the new number. The result is (5+3)/2=4. In this case the answer is unique. Thus, every i-th digit is determined as an arithmetic average of the i-th digit of Masha's number and the i-1-th digit of her true love's number. If needed, the digit can be rounded up or down. For example, Masha can get: 12345 95444 Unfortunately, when Masha tried dialing the number, she got disappointed: as it turned out, the number was unavailable or outside the coverage area. But Masha won't give up. Perhaps, she rounded to a wrong digit or chose the first digit badly. That's why she keeps finding more and more new numbers and calling them. Count the number of numbers Masha calls. Masha calls all the possible numbers that can be found by the described means of arithmancy, except for, perhaps, her own one.

The first line contains nonempty sequence consisting of digits from 0 to 9 — Masha's phone number. The sequence length does not exceed 50.

Output the single number — the number of phone numbers Masha will dial.

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()
{
    auto s = readln.chomp;

    long ans = 0;
    foreach (start; 0 .. 10) {
        auto dp = new long[][] (s.length, 10);
        dp[0][start] = 1;

        foreach (i, e; s.enumerate.dropOne) {
            int ev = e - '0';

            foreach (v; 0 .. 10) {
                foreach (nv; 0 .. 10) {
                    if (abs(v + ev - 2*nv) <= 1) { dp[i][nv] += dp[i-1][v]; }
                }
            }
        }

        debug { dp.each!writeln; writeln; }

        ans += dp[s.length - 1].sum;
    }

    bool canGetSelf = zip(s, s.dropOne).all!(t => abs(t[0].to!int - t[1].to!int) <= 1);

    if (canGetSelf) { ans -= 1; }

    ans.writeln;
}


Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of n Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, so each person agrees to swap places with the person right behind him for just 1 dollar. More formally, if person a stands just behind person b, then person a can pay person b 1 dollar, then a and b get swapped. Of course, if person a has zero dollars, he can not swap places with person b.Residents of Berland are strange people. In particular, they get upset when there is someone with a strictly smaller sum of money in the line in front of them.Can you help the residents of Berland form such order in the line so that they were all happy? A happy resident is the one who stands first in the line or the one in front of who another resident stands with not less number of dollars. Note that the people of Berland are people of honor and they agree to swap places only in the manner described above.

The first line contains integer n (1≤n≤200000) — the number of residents who stand in the line.
The second line contains n space-separated integers ai (0≤ai≤10^9), where ai is the number of Berland dollars of a man standing on the i-th position in the line. The positions are numbered starting from the end of the line.

If it is impossible to make all the residents happy, print ":(" without the quotes. Otherwise, print in the single line n space-separated integers, the i-th of them must be equal to the number of money of the person on position i in the new line. If there are multiple answers, print any of them.

In the first sample two residents should swap places, after that the first resident has 10 dollars and he is at the head of the line and the second resident will have 9 coins and he will be at the end of the line.
In the second sample it is impossible to achieve the desired result.
In the third sample the first person can swap with the second one, then they will have the following numbers of dollars: 4 11 3, then the second person (in the new line) swaps with the third one, and the resulting numbers of dollars will equal to: 4 4 10. In this line everybody will be happy.

import std.algorithm, std.conv, std.range, std.stdio, std.string;
void main ()
{
	auto d = readln.strip.to !(int).iota.array;
	auto a = readln.split.map !(to !(int)).array;
	a[] += d[];
	sort (a);
	a[] -= d[];
	writeln (isSorted (a) ? a.map !(text).join (" ") : ":(");
}


In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.

The first line of the input contains two integers n and m (2≤n≤400, 0≤m≤n(n-1)/2) — the number of towns and the number of railways respectively.
Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1≤u,v≤n, u≠v).
You may assume that there is at most one railway connecting any two towns.

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output -1.

In the first sample, the train can take the route  and the bus can take the route . Note that they can arrive at town 4 at the same time.
In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new bool [] [] (n, n);
		foreach (k; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u][v] = true;
			a[v][u] = true;
		}
		if (a[0][n - 1])
		{
			foreach (u; 0..n)
			{
				foreach (v; 0..n)
				{
					a[u][v] ^= true;
				}
			}
		}

		auto b = new bool [n];
		b[0] = true;
		int res = -1;
		foreach (k; 0..n + 2)
		{
			auto b2 = new bool [n];
			foreach (i; 0..n)
			{
				if (b[i])
				{
					foreach (j; 0..n)
					{
						if (a[i][j])
						{
							b2[j] = true;
						}
					}
				}
			}
			b = b2;
			if (b[n - 1])
			{
				res = k + 1;
				break;
			}
		}

		writeln (res);
	}
}


Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.Help Shapur find how much He should travel.

First line contains a single natural number n (1≤n≤10^5) — the amount of cities.
Next n-1 lines contain 3 integer numbers each xi, yi and wi (1≤xi,yi≤n,0≤wi≤2×10^4). xi and yi are two ends of a road and wi is the length of that road.

A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!*******************************************/

tup[][long] adj;
bool[long] vis;

long dfs(ll u){
    vis[u] = 1;
    ll maxw = 0;
    if(u in adj){
        foreach(tup e; adj[u]){
            if(!vis.get(e[0], 0)){
                maxw = max(e[1] + dfs(e[0]), maxw);
            }
        }
    }
    return maxw;
}

void play(){
    int n;
    n = rd!int;
    ll u, v, w;
    ll sumwt = 0;
    foreach(i; 0..n-1){
        u = rd; v = rd; w = rd;
        adj[u] ~= tup(v, w);
        adj[v] ~= tup(u, w);
        sumwt += w;
    }
    ll maxwtpath = dfs(1);
    ll leftw = sumwt - maxwtpath;
    debug writeln("D: ", sumwt, " ", maxwtpath, " ", leftw);
    writeln(maxwtpath + 2*leftw);
}

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


There are n students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the i-th student ai minutes to finish his/her independent piece.If students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum ai in the group minus the minimum ai in the group. Note that a group containing a single student has an imbalance of 0. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most k?Two divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.

The first line contains two space-separated integers n and k (1≤n≤200, 0≤k≤1000) — the number of students and the maximum total imbalance allowed, respectively.
The second line contains n space-separated integers ai (1≤ai≤500) — the time it takes the i-th student to complete his/her independent piece of work.

Print a single integer, the number of ways the students can form groups. As the answer may be large, print its value modulo 10^9+7.

In the first sample, we have three options:
  The first and second students form a group, and the third student forms a group. Total imbalance is 2+0=2.  The first student forms a group, and the second and third students form a group. Total imbalance is 0+1=1.  All three students form their own groups. Total imbalance is 0. In the third sample, the total imbalance must be 0, so each student must work individually.

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;

immutable int MOD = 1_000_000_007;

void add (ref int a, long b)
{
	a = (a + b) % MOD;
}

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

		auto f = new int [] [] [] (n + 3, n + 2, k + 1);
		f[1][0][0] = 1;
		foreach (num; 1..n + 2)
		{
			int delta = a[num] - a[num - 1];
			foreach (open; 0..n + 2)
			{
				foreach (total; 0..k + 1)
				{
					int cur = f[num][open][total];
					if (cur == 0)
					{
						continue;
					}
					int next = total + delta * open;
					if (next > k)
					{
						continue;
					}

					// open
					add (f[num + 1][open + 1][next],
					    cur);

					// inside or open + close
					add (f[num + 1][open][next],
					    cur * 1L * (open + 1));

					// close
					if (open > 0)
					{
						add (f[num + 1][open - 1]
						    [next], cur * 1L * open);
					}
				}
			}
		}

		int res = 0;
		foreach (total; 0..k + 1)
		{
			add (res, f[n + 2][0][total]);
		}
		writeln (res);
	}
}


Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to n.Let us remind you the definition of the greatest common divisor: GCD(a1,...,ak)=d, where d represents such a maximal positive number that each ai (1≤i≤k) is evenly divisible by d. At that, we assume that all ai's are greater than zero.Knowing that Petya is keen on programming, his friends has agreed beforehand that the 1-st friend gives a1 sweets, the 2-nd one gives a2 sweets, ..., the n-th one gives an sweets. At the same time, for any i and j (1≤i,j≤n) they want the GCD(ai,aj) not to be equal to 1. However, they also want the following condition to be satisfied: GCD(a1,a2,...,an)=1. One more: all the ai should be distinct.Help the friends to choose the suitable numbers a1,...,an.

The first line contains an integer n (2≤n≤50).

If there is no answer, print "-1" without quotes. Otherwise print a set of n distinct positive numbers a1,a2,...,an. Each line must contain one number. Each number must consist of not more than 100 digits, and must not contain any leading zeros. If there are several solutions to that problem, print any of them.
Do not forget, please, that all of the following conditions must be true:
 For every i and j (1≤i,j≤n): GCD(ai,aj)≠1 GCD(a1,a2,...,an)=1 For every i and j (1≤i,j≤n,i≠j): ai≠aj Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).

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

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

    if (n == 2) {
        writeln(-1);
        return;
    }

    immutable int MAXP = 300;

    auto isPrime = new bool[MAXP];
    isPrime[] = true;
    int[] primes;
    for (int i = 2; primes.length < n; ++i) {
        if (!isPrime[i]) { continue; }

        primes ~= i;
        for (int j = i+i; j < MAXP; j += i) { isPrime[j] = false; }
    }

    BigInt product = 1;
    foreach (e; primes) { product *= e; }

    debug { product.writeln; }

    BigInt[] ans;
    foreach (i; 0 .. n) {
        ans ~= product / primes[i];
    }

    ans.each!writeln;
}


Treeland is a country in which there are n towns connected by n-1 two-way road such that it's possible to get from any town to any other town. In Treeland there are 2k universities which are located in different towns. Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done! To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in k pairs should be as large as possible. Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1.

The first line of the input contains two integers n and k (2≤n≤200000, 1≤k≤n/2) — the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to n.
The second line contains 2k distinct integers u1,u2,...,u2k (1≤ui≤n) — indices of towns in which universities are located.
The next n-1 line contains the description of roads. Each line contains the pair of integers xj and yj (1≤xj,yj≤n), which means that the j-th road connects towns xj and yj. All of them are two-way roads. You can move from any town to any other using only these roads.

Print the maximum possible sum of distances in the division of universities into k pairs.

The figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example.

import std.algorithm;
import std.stdio;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto a = new int [] [n];
		auto b = new bool [n];
		b[] = false;
		foreach (i; 0..k * 2)
		{
			int v;
			readf (" %s", &v);
			v--;
			b[v] = true;
		}
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u] ~= v;
			a[v] ~= u;
		}

		long res = 0;

		int recur (int v, int p)
		{
			int num = 0;
			num += b[v];
			foreach (u; a[v])
			{
				if (u != p)
				{
					int t = recur (u, v);
					res += min (t, 2 * k - t);
					num += t;
				}
			}
			return num;
		}

		recur (0, -1);
		writeln (res);
	}
}


Sonya was unable to think of a story for this problem, so here comes the formal description.You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.

The first line of the input contains a single integer n (1≤n≤3000) — the length of the array.
Next line contains n integer ai (1≤ai≤10^9).

Print the minimum number of operation required to make the array strictly increasing.

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

immutable long INF = long.max / 8;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		foreach (i; 0..n)
		{
			a[i] -= i;
		}
		a = (a.reduce !(min) - 1) ~ a ~ (a.reduce !(max) + 1);
		debug {writeln ("a = ", a);}
		n += 2;

		auto r = n.iota.map !(i => tuple (a[i], i)).array;
		sort (r);
		debug {writeln (r);}

		auto f = new long [n];
		f[] = 0;
		foreach (pos; 1..n)
		{
			foreach (mid; 0..n)
			{
				f[mid] += abs (a[pos] - a[mid]);
			}
			debug {writeln (f);}
			int lo = 0;
			while (true)
			{
				int hi = lo + 1;
				long cur = f[r[lo][1]];
				while (hi < n && r[hi][0] == r[hi - 1][0])
				{
					cur = min (cur, f[r[hi][1]]);
					hi += 1;
				}
				foreach (me; lo..hi)
				{
					f[r[me][1]] = cur;
				}
				if (hi >= n)
				{
					break;
				}
				f[r[hi][1]] = min (f[r[hi][1]], cur);
				lo = hi;
			}
		}
		writeln (f[$ - 1]);
	}
}


Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1→2), the resulting population is "bbbb"; 2→1, the result is "aabb"; 2→3, the result is "baab"; 3→2, the result is "bbbb" (note that the result is the same as the first option); 3→4 or 4→3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 10^9+7.

The first line contains an integer n — the number of regions in the testtube (1≤n≤5000).
The second line contains n small Latin letters that describe the initial population of the testtube.

Print one number — the answer to the problem modulo 10^9+7.

In the first sample the population can never change since all bacteria are of the same type.
In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).
To get the answer for the third sample, note that more than one attack can happen.

import std.stdio, std.string;

immutable int N = cast(int)5e3 + 7, mod = cast(int)1e9 + 7;

char[N] s;

long qpow(long a, long x) {
	long r = 1;
	for (; x; x >>= 1, a = a * a % mod)
		if (x & 1) r = r * a % mod;
	return r;
}

long[N] fac, ifac;
void prepare(int n) {
	for (int i = fac[0] = 1; i <= n; ++i)
		fac[i] = fac[i - 1] * i % mod;
	ifac[n] = qpow(fac[n], mod - 2);
	for (int i = n; i; --i)
		ifac[i - 1] = ifac[i] * i % mod;
}

long C(int n, int m) {
	return fac[n] * ifac[m] % mod * ifac[n - m] % mod;
}

void main() {
	int n; scanf("%d%s", &n, s.ptr);

	int[][] f = new int[][](n + 1, 26);
	int[] g = new int[](n + 1);

	prepare(n);
	for (int i = 0; i < n; ++i) {
		if (s[i] == s[i + 1]) continue;

		int x = cast(int)s[i] - 97;
		for (int l = i + 1; l > 1; --l) {
			g[l] -=
				f[l][x];
			if (g[l] < 0) g[l] += mod;

			f[l][x] = g[l - 1] - f[l - 1][x];
			if (f[l][x] < 0) f[l][x] += mod;

			g[l] += f[l][x];
			if (g[l] >= mod) g[l] -= mod;
		}

		if (!f[1][x])
			f[1][x] = 1, ++g[1];
	}

	long ans = 0;
	for (int l = 1; l <= n; ++l) {
		ans = (ans + g[l] * C(n - 1, l - 1) % mod) % mod;
	}
	writeln(ans);
}

[{'input': ['3\r\naaa\r\n'], 'output': ['1\r\n']}, {'input': ['2\r\nab\r\n'], 'output': ['3\r\n']}, {'input': ['4\r\nbabb\r\n'], 'output': ['11\r\n']}, {'input': ['7\r\nabacaba\r\n'], 'output': ['589\r\n']}, {'input': ['1\r\na\r\n'], 'output': ['1\r\n']}, {'input': ['1\r\nz\r\n'], 'output': ['1\r\n']}, {'input': ['3\r\nmyw\r\n'], 'output': ['10\r\n']}, {'input': ['10\r\nisssisssss\r\n'], 'output': ['176\r\n']}, {'input': ['15\r\ntxxtxttxxttxtxx\r\n'], 'output': ['27824\r\n']}, {'input': ['127\r\nxixtxixnxixtxixlxixtxixnxixtxixoxixtxixnxixtxixlxixtxixnxixtxixhxixtxixnxixtxixlxixtxixnxixtxixoxixtxixnxixtxixlxixtxixnxixtxix\r\n'], 'output': ['944124121\r\n']}, {'input': ['2\r\nff\r\n'], 'output': ['1\r\n']}]


Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui,vi)<x<max(ui,vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k-1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.

The first line contains two integers n and k (1≤n,k≤80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit.
The second line contains single integer m (0≤m≤2000) — the number of bicycle lanes in Bankopolis.
The next m lines contain information about the lanes.
The i-th of these lines contains three integers ui, vi and ci (1≤ui,vi≤n, 1≤ci≤1000), denoting the crossroads connected by the i-th road and its difficulty.

In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.

In the first example Oleg visiting banks by path 1→6→2→4.
Path 1→6→2→7 with smaller difficulity is incorrect because crossroad 2→7 passes near already visited office on the crossroad 6.
In the second example Oleg can visit banks by path 4→1→3.

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

immutable int infinity = int.max / 4;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		n += 2;
		int m;
		readf (" %s", &m);
		auto u = new int [m];
		auto v = new int [m];
		auto c = new int [m];
		auto d = new int [] [] (n, n);
		foreach (ref dLine; d)
		{
			dLine[] = infinity;
		}
		foreach (i; 0..m)
		{
			readf (" %s %s %s", &u[i], &v[i], &c[i]);
			d[u[i]][v[i]] = min (d[u[i]][v[i]], c[i]);
		}

		auto f = new int [2] [] [] [] (2, n, n);
		int b = 0;
		foreach (ref fLine; f[b])
		{
			fLine[] = [infinity, infinity];
		}
		foreach (i; 0..n)
		{
			f[b][0][i][1] = 0;
			f[b][i][n - 1][0] = 0;
		}

		foreach (step; 0..k - 1)
		{
			b ^= 1;
			foreach (ref fLine; f[b])
			{
				fLine[] = [infinity, infinity];
			}
			foreach (i; 0..n)
			{
				foreach (j; i..n)
				{
					// from [i* -- j]
					int cur0 = f[!b][i][j][0];
					// from [i -- *j]
					int cur1 = f[!b][i][j][1];
					debug {writeln (step, " ", i, " ",
					    j, ": ", cur0, " ", cur1);}
					if (cur0 != infinity)
					{
						foreach (p; i + 1..j)
						{
							// to [i -- *p]
							f[b][i][p][1] =
							    min (f[b][i][p][1],
							    cur0 + d[i][p]);
							// to [p* -- j]
							f[b][p][j][0] =
							    min (f[b][p][j][0],
							    cur0 + d[i][p]);
						}
					}
					if (cur1 != infinity)
					{
						foreach (p; i + 1..j)
						{
							// to [p* -- j]
							f[b][p][j][0] =
							    min (f[b][p][j][0],
							    cur1 + d[j][p]);
							// to [i -- *p]
							f[b][i][p][1] =
							    min (f[b][i][p][1],
							    cur1 + d[j][p]);
						}
	                        	}
				}
			}
		}

		int res = infinity;
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				res = min (res, f[b][i][j][0], f[b][i][j][1]);
			}
		}
		if (res == infinity)
		{
			res = -1;
		}
		writeln (res);
	}
}


After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help.Formally the parking can be represented as a matrix 10^9×10^9. There is exactly one car in every cell of the matrix. All cars have their own machine numbers represented as a positive integer. Let's index the columns of the matrix by integers from 1 to 10^9 from left to right and the rows by integers from 1 to 10^9 from top to bottom. By coincidence it turned out, that for every cell (x,y) the number of the car, which stands in this cell, is equal to the minimum positive integer, which can't be found in the cells (i,y) and (x,j), 1≤i<x,1≤j<y.  The upper left fragment 5×5 of the parkingLeha wants to ask the watchman q requests, which can help him to find his car. Every request is represented as five integers x1,y1,x2,y2,k. The watchman have to consider all cells (x,y) of the matrix, such that x1≤x≤x2 and y1≤y≤y2, and if the number of the car in cell (x,y) does not exceed k, increase the answer to the request by the number of the car in cell (x,y). For each request Leha asks the watchman to tell him the resulting sum. Due to the fact that the sum can turn out to be quite large, hacker asks to calculate it modulo 10^9+7.However the requests seem to be impracticable for the watchman. Help the watchman to answer all Leha's requests.

The first line contains one integer q (1≤q≤10^4) — the number of Leha's requests.
The next q lines contain five integers x1,y1,x2,y2,k (1≤x1≤x2≤10^9,1≤y1≤y2≤10^9,1≤k≤2·10^9) — parameters of Leha's requests.

Print exactly q lines — in the first line print the answer to the first request, in the second — the answer to the second request and so on.

Let's analyze all the requests. In each case the requested submatrix is highlighted in blue.
In the first request (k=1) Leha asks only about the upper left parking cell. In this cell the car's number is 1. Consequentally the answer is 1.

In the second request (k=5) suitable numbers are 4,1,2,3,2,1. Consequentally the answer is 4+1+2+3+2+1=13.

In the third request (k=10000) Leha asks about the upper left frament 5×5 of the parking. Since k is big enough, the answer is equal to 93.

In the last request (k=2) none of the cur's numbers are suitable, so the answer is 0.

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

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

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

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

enum E = 35;

// < m, < n, < k
Mint solve(long m, long n, long k) {
  debug {
    writefln("solve %s %s %s", m, n, k);
  }
  auto crt0 = new Mint[][][](2, 2, 2);
  auto crt1 = new Mint[][][](2, 2, 2);
  crt0[0][0][0] = 1;
  foreach_reverse (e; 0 .. E) {
    auto nxt0 = new Mint[][][](2, 2, 2);
    auto nxt1 = new Mint[][][](2, 2, 2);
    const mm = cast(int)((m >> e) & 1);
    const nn = cast(int)((n >> e) & 1);
    const kk = cast(int)((k >> e) & 1);
    foreach (s; 0 .. 2) foreach (t; 0 .. 2) foreach (u; 0 .. 2) {
      foreach (x; 0 .. 2) foreach (y; 0 .. 2) {
        const z = x ^ y;
        if ((s || x <= mm) && (t || y <= nn) && (u || z <= kk)) {
          const ss = (s || x < mm) ? 1 : 0;
          const tt = (t || y < nn) ? 1 : 0;
          const uu = (u || z < kk) ? 1 : 0;
          nxt0[ss][tt][uu] += crt0[s][t][u];
          nxt1[ss][tt][uu] += crt1[s][t][u] * 2 + crt0[s][t][u] * z;
        }
      }
    }
    debug {
      if (e <= 5) {
        writeln("e = ", e);
        writeln("nxt0 = ", nxt0);
        writeln("nxt1 = ", nxt1);
      }
    }
    crt0 = nxt0;
    crt1 = nxt1;
  }
  Mint ret;
  ret += crt1[1][1][1];
  ret += crt0[1][1][1];
  return ret;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const X1 = readLong() - 1;
        const Y1 = readLong() - 1;
        const X2 = readLong();
        const Y2 = readLong();
        const K = readLong();
        Mint ans;
        ans += solve(X1, Y1, K);
        ans -= solve(X1, Y2, K);
        ans -= solve(X2, Y1, K);
        ans += solve(X2, Y2, K);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


After the educational reform Polycarp studies only two subjects at school, Safety Studies and PE (Physical Education). During the long months of the fourth term, he received n marks in them. When teachers wrote a mark in the journal, they didn't write in what subject the mark was for, they just wrote the mark.Now it's time to show the journal to his strict parents. Polycarp knows that recently at the Parent Meeting the parents were told that he received a Safety Studies marks and b PE marks (a+b=n). Now Polycarp wants to write a subject's name in front of each mark so that:   there are exactly a Safety Studies marks,  there are exactly b PE marks,  the total average score in both subjects is maximum. An average subject grade is the sum of all marks in it, divided by the number of them. Of course, the division is performed in real numbers without rounding up or down. Polycarp aims to maximize the x1+x2, where x1 is the average score in the first subject (Safety Studies), and x2 is the average score in the second one (Physical Education).

The first line contains an integer n (2≤n≤10^5), n is the number of marks in Polycarp's Journal. The second line contains two positive integers a,b (1≤a,b≤n-1,a+b=n). The third line contains a sequence of integers t1,t2,...,tn (1≤ti≤5), they are Polycarp's marks.

Print the sequence of integers f1,f2,...,fn, where fi (1≤fi≤2) is the number of a subject to which the i-th mark should be attributed. If there are several possible solutions, then print such that the sequence f1,f2,...,fn is the smallest lexicographically.
The sequence p1,p2,...,pn is lexicographically less than q1,q2,...,qn if there exists such j (1≤j≤n) that pi=qi for all 1≤i<j, аnd pj<qj.

In the first sample the average score in the first subject is equal to 4, and in the second one — to 4.5. The total average score is 8.5.

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

void main(string[ ] args) {
    int n;
    readf!"%s"(n);
    readln;

    int a, b;
    readf!"%s %s"(a, b);
    readln;

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

    alias pr = Tuple!(int, "index", int, "value");
    bool isSmaller(pr left, pr right) {
        if (a == b) { return left.index < right.index; }
        if (a < b) { return left.value != right.value ? left.value > right.value : left.index < right.index; }
        return left.value != right.value ? left.value < right.value : left.index < right.index;
    }

    auto sorted = arr.enumerate(0.to!int).array.sort!(isSmaller).array;

    debug { sorted.writeln; }

    auto ans = new int[n];
    foreach (t; sorted[0 .. a]) { ans[t.index] = 1; }
    foreach (t; sorted[a .. a+b]) { ans[t.index] = 2; }

    ans.map!(to!string).join(" ").writeln;
}