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

struct Queue(T) {
  private T[] items = [T.init];
  private size_t first, last;

  @property bool empty() {
    return first == last;
  }

  void push(T top) {
    if (last == items.length) {
      items.length = max(1, items.length*2);
    }
    items[last] = top;
    last++;
  }

  T pop() {
    if (this.empty)
      throw new Exception("Empty Queue.");
    auto top = items[first];
    first++;
    return top;
  }
}

void main() {
  int n;
  readf(" %d", &n);
  auto g = new int[][](n+1, 0);
  auto parent = new int[](n+1);
  auto visited = new int[](n+1);
  auto cycle = new int[](n+1);
  auto distances = new int[](n+1);
  int a,b;
  while (readf(" %d %d", &a, &b)) {
    g[a] ~= b;
    g[b] ~= a;
  }
  bool cycle_found = false;
  void dfs(int u, int p) {
    visited[u] = 1;
    parent[u] = p;
    if(cycle_found) return;
    foreach (v; g[u]) {
      if (v == p || visited[v] == 2 || cycle_found) continue;
      if (visited[v] == 1) {
        cycle[v] = 1;
        int x = u;
        while (x != v) {
          cycle[x] = 1;
          x = parent[x];
        }
        cycle_found = true;
        return;
      }
      dfs(v, u);
    }
    visited[u] = 2;
  }

  void bfs(int u0) {
    Queue!int q;
    q.push(u0);
    while (!q.empty) {
      auto u = q.pop();
      visited[u] = 1;
      foreach (v; g[u]) {
        if (visited[v]) continue;
        if (!cycle[v]) {
          distances[v] = distances[u] + 1;
        }
        q.push(v);
      }
    }
  }
  dfs(1, 0);
  visited[] = 0;
  bfs(to!int(cycle.countUntil(1) + 1));
  debug {
    writeln(cycle);
  }
  writefln("%(%s %)", distances[1..$]);
}

A subway scheme, classic for all Berland cities is represented by a set of n stations connected by n passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage.Berland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once.This invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say "I live in three passages from the ringroad" and another one could reply "you loser, I live in one passage from the ringroad". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...).The Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme.

The first line contains an integer n (3≤n≤3000), n is the number of stations (and trains at the same time) in the subway scheme. Then n lines contain descriptions of the trains, one per line. Each line contains a pair of integers xi,yi (1≤xi,yi≤n) and represents the presence of a passage from station xi to station yi. The stations are numbered from 1 to n in an arbitrary order. It is guaranteed that xi≠yi and that no pair of stations contain more than one passage. The passages can be used to travel both ways. It is guaranteed that the given description represents a classic subway scheme.

Print n numbers. Separate the numbers by spaces, the i-th one should be equal to the distance of the i-th station from the ringroad. For the ringroad stations print number 0.

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

struct Queue(T) {
  private T[] items = [T.init];
  private size_t first, last;

  @property bool empty() {
    return first == last;
  }

  void push(T top) {
    if (last == items.length) {
      items.length = max(1, items.length*2);
    }
    items[last] = top;
    last++;
  }

  T pop() {
    if (this.empty)
      throw new Exception("Empty Queue.");
    auto top = items[first];
    first++;
    return top;
  }
}

void main() {
  int n;
  readf(" %d", &n);
  auto g = new int[][](n+1, 0);
  auto parent = new int[](n+1);
  auto visited = new int[](n+1);
  auto cycle = new int[](n+1);
  auto distances = new int[](n+1);
  int a,b;
  while (readf(" %d %d", &a, &b)) {
    g[a] ~= b;
    g[b] ~= a;
  }
  bool cycle_found = false;
  void dfs(int u, int p) {
    visited[u] = 1;
    parent[u] = p;
    if(cycle_found) return;
    foreach (v; g[u]) {
      if (v == p || visited[v] == 2 || cycle_found) continue;
      if (visited[v] == 1) {
        cycle[v] = 1;
        int x = u;
        while (x != v) {
          cycle[x] = 1;
          x = parent[x];
        }
        cycle_found = true;
        return;
      }
      dfs(v, u);
    }
    visited[u] = 2;
  }

  void bfs(int u0) {
    Queue!int q;
    q.push(u0);
    while (!q.empty) {
      auto u = q.pop();
      visited[u] = 1;
      foreach (v; g[u]) {
        debug {
          writeln("Start: ", v);
        }
        if (visited[v]) continue;
        debug {
          writeln("not visited");
        }
        if (!cycle[v]) {
          distances[v] = distances[u] + 1;
          debug {
            writeln(distances[v], ' ', distances[u]);
          }
        }
        q.push(v);
      }
    }
  }
  dfs(1, 0);
  visited[] = 0;
  bfs(to!int(cycle.countUntil(1)));
  debug {
    writeln(cycle);
  }
  writefln("%(%s %)", distances[1..$]);
}


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

string s; int K;

struct R {
    int from, to;
    int diff;
}

string modify(in string s) {
    int N = cast(int)(s.length);
    auto t = s[0 .. N / 2].dup;
    t.reverse;
    if (N & 1) {
        return s[0 .. N / 2] ~ s[N / 2] ~ t.idup;
    } else {
        return s[0 .. N / 2] ~ t.idup;
    }
}

void main() {
    s = readln.chomp;
    scanf("%d\n", &K);
    int N = cast(int)s.length;

    R[] rs;
    foreach (int i; 0 .. N) {
        foreach (int j; i + 1 .. N + 1) {
            int count(in string s) {
                int n = cast(int)s.length;
                int ret = 0;
                foreach (int i, c; s) {
                    if (c != s[n - 1 - i]) ret++;
                }
                return ret / 2;
            }
            rs ~= R(i, j, count(s[i .. j]));
        }
    }

    rs.sort!"a.from < b.from";
    const INF = 1<<28;
    auto dp = new int[][](K + 1, N + 1);
    auto prev = new int[][](K + 1, N + 1);
    foreach (k; 0 .. K + 1) dp[k][] = INF;
    for (int i = 0; i < N && rs[i].from == 0; i++) {
        dp[1][rs[i].to] = rs[i].diff;
        prev[1][rs[i].to] = rs[i].from;
    }
    foreach (k; 1 .. K) {
        foreach (n; 0 .. N) dp[k + 1][n] = min(dp[k + 1][n], dp[k][n]);
        foreach (r; rs) {
            if (dp[k + 1][r.to] > dp[k][r.from] + r.diff) {
                dp[k + 1][r.to] = dp[k][r.from] + r.diff;
                prev[k + 1][r.to] = r.from;
            }
        }
    }
    int ansCount = INF;
    int ansK = 0;
    foreach (int k; 0 .. K + 1) {
        if (ansCount > dp[k][N]) {
            ansCount = dp[k][N];
            ansK = k;
        }
    }
    writeln(ansCount);
    int n = N;
    int p = prev[ansK][N];
    string[] ans;
    int k = ansK;
    while (k > 0) {
        ans ~= s[p .. n];
        n = p;
        p = prev[--k][n];
    }
    writeln(ans.map!(modify).join("+"));
    //foreach (l; dp[1 .. $]) l.writeln;
}

Friday is Polycarpus' favourite day of the week. Not because it is followed by the weekend, but because the lessons on Friday are 2 IT lessons, 2 math lessons and 2 literature lessons. Of course, Polycarpus has prepared to all of them, unlike his buddy Innocentius. Innocentius spent all evening playing his favourite game Fur2 and didn't have enough time to do the literature task. As Innocentius didn't want to get an F, he decided to do the task and read the book called "Storm and Calm" during the IT and Math lessons (he never used to have problems with these subjects). When the IT teacher Mr. Watkins saw this, he decided to give Innocentius another task so that the boy concentrated more on the lesson and less — on the staff that has nothing to do with IT. Mr. Watkins said that a palindrome is a string that can be read the same way in either direction, from the left to the right and from the right to the left. A concatenation of strings a, b is a string ab that results from consecutive adding of string b to string a. Of course, Innocentius knew it all but the task was much harder than he could have imagined. Mr. Watkins asked change in the "Storm and Calm" the minimum number of characters so that the text of the book would also be a concatenation of no more than k palindromes. Innocentius can't complete the task and therefore asks you to help him.

The first input line contains a non-empty string s which is the text of "Storm and Calm" (without spaces). The length of the string s does not exceed 500 characters. String s consists of uppercase and lowercase Latin letters. The second line contains a single number k (1≤k≤|s|, where |s| represents the length of the string s).

Print on the first line the minimum number of changes that Innocentius will have to make. Print on the second line the string consisting of no more than k palindromes. Each palindrome should be non-empty and consist of uppercase and lowercase Latin letters. Use the character "+" (ASCII-code 43) to separate consecutive palindromes. If there exist several solutions, print any of them.
The letters' case does matter, that is an uppercase letter is not considered equivalent to the corresponding lowercase letter.

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

string s; int K;

struct R {
    int from, to;
    int diff;
}

string modify(in string s) {
    int N = cast(int)(s.length);
    auto t = s[0 .. N / 2].dup;
    t.reverse;
    if (N & 1) {
        return s[0 .. N / 2] ~ s[N / 2] ~ t.idup;
    } else {
        return s[0 .. N / 2] ~ t.idup;
    }
}

void main() {
    s = readln.chomp;
    scanf("%d\n", &K);
    int N = cast(int)s.length;

    R[] rs;
    foreach (int i; 0 .. N) {
        foreach (int j; i + 1 .. N + 1) {
            int count(in string s) {
                int n = cast(int)s.length;
                int ret = 0;
                foreach (int i, c; s) {
                    if (c != s[n - 1 - i]) ret++;
                }
                return ret / 2;
            }
            rs ~= R(i, j, count(s[i .. j]));
        }
    }

    rs.sort!"a.from < b.from";
    const INF = 1<<28;
    auto dp = new int[][](K + 1, N + 1);
    auto prev = new int[][](K + 1, N + 1);
    foreach (k; 0 .. K + 1) dp[k][] = INF;
    for (int i = 0; i < N && rs[i].from == 0; i++) {
        dp[1][rs[i].to] = rs[i].diff;
        prev[1][rs[i].to] = rs[i].from;
    }
    foreach (k; 1 .. K) {
        foreach (n; 0 .. N) dp[k + 1][n] = min(dp[k + 1][n], dp[k][n]);
        foreach (r; rs) {
            if (dp[k + 1][r.to] > dp[k][r.from] + r.diff) {
                dp[k + 1][r.to] = dp[k][r.from] + r.diff;
                prev[k + 1][r.to] = r.from;
            }
        }
    }
    int ansCount = INF;
    int ansK = 0;
    foreach (int k; 0 .. K + 1) {
        if (ansCount > dp[k][N]) {
            ansCount = dp[k][N];
            ansK = k;
        }
    }
    writeln(ansCount);
    int n = N;
    int p = prev[ansK][N];
    string[] ans;
    int k = ansK;
    while (k > 0) {
        ans ~= s[p .. n];
        n = p;
        p = prev[--k][n];
    }
    ans.reverse;
    writeln(ans.map!(modify).join("+"));
    //foreach (l; dp[1 .. $]) l.writeln;
}


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

void main() {
  char[] n = readln.chomp.dup;
  uint[10] map1, map2;
  string perm1 = "";
  string perm2 = "";

  foreach (digit; n) {
    map1[digit - '0']++;
    map2[digit - '0']++;
  }

  bool proceed = false;
  uint zeros = 0;
  uint zeroPairs = 0;

  // check optimal last zero
  for (int i = 1; i <= 9 && !proceed; i++) {
    if (map1[i] != 0 && map2[10 - i] != 0 && map2[9 - i] == 0) {
      proceed = true;
      zeros++;
      map1[i]--;
      map2[10 - i]--;
      perm1 ~= i + '0';
      perm2 ~= 10 - i + '0';
    }
  }

  // check non-optimal last zero
  for (int i = 1; i <= 9 && !proceed; i++) {
    if (map1[i] != 0 && map2[10 - i] != 0) {
      proceed = true;
      zeros++;
      map1[i]--;
      map2[10 - i]--;
      perm1 ~= i + '0';
      perm2 ~= 10 - i + '0';
    }
  }

  while (proceed) {
    proceed = false;
    for (int i = 0; i <= 9 && !proceed; i++) {
      if (map1[i] != 0 && map2[9 - i] != 0) {
        proceed = true;
        zeros++;
        map1[i]--;
        map2[9 - i]--;
      perm1 ~= i + '0';
      perm2 ~= 9 - i + '0';
      }
    }
    if (!proceed && map1[0] != 0 && map2[0] != 0) {
      proceed = true;
      zeros++;
      map1[0]--;
      map2[0]--;
      zeroPairs++;
    }
  }

  for (int i = 0; i <= 9 && !proceed; i++) {
    while (map1[i] != 0) {
      perm1 ~= i + '0';
      map1[i]--;
    }
    while (map2[i] != 0) {
      perm2 ~= i + '0';
      map2[i]--;
    }
  }

  perm1 = perm1.dup.reverse;
  perm2 = perm2.dup.reverse;

  for (int i = 0; i < zeroPairs; i++) {
    perm1 ~= '0';
    perm2 ~= '0';
  }

  writeln(perm1);
  writeln(perm2);
}

Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.Given number n, can you find the two digit permutations that have this property?

The first line contains a positive integer n — the original number. The number of digits in this number does not exceed 10^5. The number is written without any leading zeroes.

Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.

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

void main() {
  char[] n = readln.chomp.dup;
  uint[10] map1, map2;
  string perm1 = "";
  string perm2 = "";

  foreach (digit; n) {
    map1[digit - '0']++;
    map2[digit - '0']++;
  }

  bool proceed = false;
  uint zeros = 0;
  uint zeroPairs = 0;

  // check optimal last zero
  for (int i = 1; i <= 9 && !proceed; i++) {
    if (map1[i] != 0 && map2[10 - i] != 0 && map1[9 - i] < map1[i] && map1[9 - (10 - i)] < map1[10 - i]) {
      proceed = true;
      zeros++;
      map1[i]--;
      map2[10 - i]--;
      perm1 ~= i + '0';
      perm2 ~= 10 - i + '0';
    }
  }

  // check non-optimal last zero
  for (int i = 1; i <= 9 && !proceed; i++) {
    if (map1[i] != 0 && map2[10 - i] != 0) {
      proceed = true;
      zeros++;
      map1[i]--;
      map2[10 - i]--;
      perm1 ~= i + '0';
      perm2 ~= 10 - i + '0';
    }
  }

  while (proceed) {
    proceed = false;
    for (int i = 0; i <= 9 && !proceed; i++) {
      if (map1[i] != 0 && map2[9 - i] != 0) {
        proceed = true;
        zeros++;
        map1[i]--;
        map2[9 - i]--;
        perm1 ~= i + '0';
        perm2 ~= 9 - i + '0';
      }
    }
    if (!proceed && map1[0] != 0 && map2[0] != 0) {
      proceed = true;
      zeros++;
      map1[0]--;
      map2[0]--;
      zeroPairs++;
    }
  }

  for (int i = 0; i <= 9 && !proceed; i++) {
    while (map1[i] != 0) {
      perm1 ~= i + '0';
      map1[i]--;
    }
    while (map2[i] != 0) {
      perm2 ~= i + '0';
      map2[i]--;
    }
  }

  perm1 = perm1.dup.reverse;
  perm2 = perm2.dup.reverse;

  for (int i = 0; i < zeroPairs; i++) {
    perm1 ~= '0';
    perm2 ~= '0';
  }

  writeln(perm1);
  writeln(perm2);
}


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

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

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

void solve() {
    long P, F; readf("%d %d\n", &P, &F);
    int Cs, Cw; readf("%d %d\n", &Cs, &Cw);
    long S, W; readf("%d %d\n", &S, &W);

    long ans = 0;
    for (int np = 0; np <= Cs; np++) {
        long r = P - np * S;
        if (r < 0) break;
        long mp = min(r / W, Cw);
        long Rs = Cs - np;
        long Rw = Cw - mp;
        if (S < W) {
            long nf, mf;
            if (F / S <= Rs) {
                nf = F / S;
                mf = 0;
            } else {
                nf = Rs;
                mf = min((F - nf * S) / W, Rw);
            }
            ans.chmax(np + mp + nf + mf);
        } else {
            long nf, mf;
            if (F / W <= Rw) {
                mf = F / W;
                nf = 0;
            } else {
                mf = Rw;
                nf = min((F - mf * W) / W, Rs);
            }
            ans.chmax(np + mp + nf + mf);
        }
    }
    writeln(ans);
}

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


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

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

    auto arr = [0] ~ readln.chomp.split.map!(to!int).array ~ [0];

    debug { arr.writeln; }

    Tuple!(int, int)[] ans;

    auto stk = make!(SList!int);
    stk.insertFront(0);
    foreach (i; 1 .. n+1) {
        if (arr[i] > arr[i-1]) { stk.insertFront(i); }

        if (arr[i] > arr[i+1]) {
            while (arr[stk.front] > arr[i+1]) {
                auto lft = stk.front;
                stk.removeFront();

                auto ht = arr[lft];

                foreach (_; 0 .. ht - arr[stk.front]) {
                    ans ~= tuple(lft, i);
                }
            }
        }
    }

    ans.length.writeln;
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

Polycarpus is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array a for all indexes in the segment [l,r]. In other words, this function does the following: function rangeIncrement(l, r)    for i := l .. r do        a[i] = a[i] + 1Polycarpus knows the state of the array a after a series of function calls. He wants to determine the minimum number of function calls that lead to such state. In addition, he wants to find what function calls are needed in this case. It is guaranteed that the required number of calls does not exceed 10^5.Before calls of function rangeIncrement(l, r) all array elements equal zero.

The first input line contains a single integer n (1≤n≤10^5) — the length of the array a[1... n].
The second line contains its integer space-separated elements, a[1],a[2],...,a[n] (0≤a[i]≤10^5) after some series of function calls rangeIncrement(l, r).
It is guaranteed that at least one element of the array is positive. It is guaranteed that the answer contains no more than 10^5 calls of function rangeIncrement(l, r).

Print on the first line t — the minimum number of calls of function rangeIncrement(l, r), that lead to the array from the input data. It is guaranteed that this number will turn out not more than 10^5.
Then print t lines — the descriptions of function calls, one per line. Each line should contain two integers li,ri (1≤li≤ri≤n) — the arguments of the i-th call rangeIncrement(l, r). Calls can be applied in any order.
If there are multiple solutions, you are allowed to print any of them.

The first sample requires a call for the entire array, and four additional calls:
  one for the segment [2,2] (i.e. the second element of the array),  three for the segment [5,5] (i.e. the fifth element of the array).

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

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

    auto arr = [0] ~ readln.chomp.split.map!(to!int).array ~ [0];

    debug { arr.writeln; }

    Tuple!(int, int)[] ans;

    auto stk = make!(SList!(Tuple!(int, int)));
    stk.insertFront(tuple(0, 0));
    foreach (i; 1 .. n+1) {
        if (arr[i] > arr[i-1]) { stk.insertFront(tuple(i, arr[i])); }

        while (stk.front[1] > arr[i+1]) {
            auto lft = stk.front[0];
            auto ht = stk.front[1];
            stk.removeFront();

            ans ~= tuple(lft, i);

            if (ht - 1 > stk.front[1]) { stk.insertFront(tuple(lft, ht - 1)); }
        }
    }

    ans.length.writeln;
    ans.each!(t => writeln(t[0], ' ', t[1]));
}


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) {
        dp[e[0]][i][0] = 1;
        if (e[0] != e[1]) { 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;
}

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


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

__gshared:

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

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

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

struct Node {
    int len;
    Node*[char] next;
    Node* link;
    int[int] dp;

    Node* append(char c, Node* last) {
        auto cur = createNode(Node(last.len + 1));
        for (; last !is null && c !in last.next; last = last.link)
            last.next[c] = cur;
        if (last is null) {
            cur.link = &this;
            return cur;
        }
        auto q = last.next[c];
        if (q.len == last.len + 1) {
            cur.link = q;
            return cur;
        }
        auto clone = createNode(*q);
        clone.len = last.len + 1;
        cur.link = q.link = clone;
        for (; last !is null && last.next.get(c, null) == q; last = last.link)
            last.next[c] = clone;
        return cur;
    }

    int calc(int badTaken) {
        if (badTaken > k)
            return 0;
        if (auto p = badTaken in dp)
            return *p;
        int result = 1;
        foreach (c, node; next)
            result += node.calc(badTaken + (good[c - 'a'] == '0'));
        dp[badTaken] = result;
        return result;
    }
}

char[1501] _s;
char[ ] s;
char[27] good;
int k;
int nodesSize;
Node[3000] nodes;

auto createNode()(auto ref Node node) {
    nodes[nodesSize] = node;
    return &nodes[nodesSize++];
}

void main() {
    while (true) {
        s = _s[ ];
        readln(s);
        if (s.empty)
            break;
        s = s[0 .. $ - 1];
        auto temp = good[ ];
        readln(temp);
        read(&k);

        Node root;
        auto last = &root;
        nodesSize = 0;
        foreach (c; s)
            last = root.append(c, last);
        writeln(root.calc(0) - 1);
    }
}

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


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

immutable int MAX_N = 54;
immutable int MOD = 1_000_000_007;

long [MAX_N] [MAX_N] c;

void main ()
{
    foreach (i; 0..MAX_N)
    {
        c[i][0] = 1;
        foreach (j; 1..i + 1)
        {
            c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % MOD;
        }
    }

    int n, k;
    while (readf (" %s %s", &n, &k) > 0)
    {
        auto a = new int [n];
        k /= 50;
        int x = 0;
        int y = 0;
        foreach (i; 0..n)
        {
            readf (" %s", &a[i]);
            a[i] /= 50;
            if (a[i] == 1)
            {
                x++;
            }
            else if (a[i] == 2)
            {
                y++;
            }
            else
            {
                enforce (false);
            }
        }

        alias Tuple !(int, "b", int, "x", int, "y") state;
        alias Tuple !(int, "dist", int, "num") value;
        state [] q;
        q.reserve (2 * (x + 1) * (y + 1));
        auto f = new value [] [] [] (2, x + 1, y + 1);

        f[0][0][0] = value (0, 1);
        q ~= state (0, 0, 0);
        while (q.length > 0)
        {
            state cur = q[0];
            q = q[1..$];
            int cb = cur.b;
            int cx = cur.x;
            int cy = cur.y;
            int cd = f[cb][cx][cy].dist + 1;
            int cn = f[cb][cx][cy].num;
            debug {writefln ("%s %s %s", cb, cx, cy);}
            int nb = 1 - cb;
            foreach (dx; 0..x + 1)
            {
                foreach (dy; 0..y + 1)
                {
                    if (!dx && !dy)
                    {
                        continue;
                    }
                    if (dx + dy * 2 > k)
                    {
                        break;
                    }
                    int nx, ny;
                    long mult;
                    if (cb) // back
                    {
                        nx = cx - dx;
                        ny = cy - dy;
                        mult = (c[cx][dx] *
                                c[cy][dy]) % MOD;
                        if (nx < 0 || ny < 0)
                        {
                            continue;
                        }
                    }
                    else // forward
                    {
                        nx = cx + dx;
                        ny = cy + dy;
                        mult = (c[x - cx][dx] *
                                c[y - cy][dy]) % MOD;
                        if (nx > x || ny > y)
                        {
                            continue;
                        }
                    }
                    if (!f[nb][nx][ny].num)
                    {
                        f[nb][nx][ny].dist = cd;
                        q ~= state (nb, nx, ny);
                    }
                    if (f[nb][nx][ny].dist != cd)
                    {
                        continue;
                    }
                    f[nb][nx][ny].num =
                      (f[nb][nx][ny].num +
                       mult * cn) % MOD;
                }
            }
        }

        writefln ("%s", f[1][x][y].dist == int.max ?
                  -1 : f[1][x][y].dist);
        writefln ("%s", f[1][x][y].num);
    }
}

One day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold people with the total weight of at most k kilograms.Greg immediately took a piece of paper and listed there the weights of all people in his group (including himself). It turned out that each person weights either 50 or 100 kilograms. Now Greg wants to know what minimum number of times the boat needs to cross the river to transport the whole group to the other bank. The boat needs at least one person to navigate it from one bank to the other. As the boat crosses the river, it can have any non-zero number of passengers as long as their total weight doesn't exceed k.Also Greg is wondering, how many ways there are to transport everybody to the other side in the minimum number of boat rides. Two ways are considered distinct if during some ride they have distinct sets of people on the boat.Help Greg with this problem.

The first line contains two integers n, k (1≤n≤50,1≤k≤5000) — the number of people, including Greg, and the boat's weight limit. The next line contains n integers — the people's weights. A person's weight is either 50 kilos or 100 kilos.
You can consider Greg and his friends indexed in some way.

In the first line print an integer — the minimum number of rides. If transporting everyone to the other bank is impossible, print an integer -1.
In the second line print the remainder after dividing the number of ways to transport the people in the minimum number of rides by number 1000000007 (10^9+7). If transporting everyone to the other bank is impossible, print integer 0.

In the first test Greg walks alone and consequently, he needs only one ride across the river.
In the second test you should follow the plan:
  transport two 50 kg. people;  transport one 50 kg. person back;  transport one 100 kg. person;  transport one 50 kg. person back;  transport two 50 kg. people. That totals to 5 rides. Depending on which person to choose at step 2, we can get two distinct ways.

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

immutable int MAX_N = 54;
immutable int MOD = 1_000_000_007;

long [MAX_N] [MAX_N] c;

void main ()
{
    foreach (i; 0..MAX_N)
    {
        c[i][0] = 1;
        foreach (j; 1..i + 1)
        {
            c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % MOD;
        }
    }

    int n, k;
    while (readf (" %s %s", &n, &k) > 0)
    {
        auto a = new int [n];
        k /= 50;
        int x = 0;
        int y = 0;
        foreach (i; 0..n)
        {
            readf (" %s", &a[i]);
            a[i] /= 50;
            if (a[i] == 1)
            {
                x++;
            }
            else if (a[i] == 2)
            {
                y++;
            }
            else
            {
                enforce (false);
            }
        }

        alias Tuple !(int, "b", int, "x", int, "y") state;
        alias Tuple !(int, "dist", int, "num") value;
        state [] q;
        q.reserve (2 * (x + 1) * (y + 1));
        auto f = new value [] [] [] (2, x + 1, y + 1);
        foreach (b; 0..2)
        {
            foreach (cx; 0..x + 1)
            {
                f[b][cx][] = value (int.max, 0);
            }
        }

        f[0][0][0] = value (0, 1);
        q ~= state (0, 0, 0);
        while (q.length > 0)
        {
            state cur = q[0];
            q = q[1..$];
            int cb = cur.b;
            int cx = cur.x;
            int cy = cur.y;
            int cd = f[cb][cx][cy].dist + 1;
            int cn = f[cb][cx][cy].num;
            debug {writefln ("%s %s %s", cb, cx, cy);}
            int nb = 1 - cb;
            foreach (dx; 0..x + 1)
            {
                foreach (dy; 0..y + 1)
                {
                    if (!dx && !dy)
                    {
                        continue;
                    }
                    if (dx + dy * 2 > k)
                    {
                        break;
                    }
                    int nx, ny;
                    long mult;
                    if (cb) // back
                    {
                        nx = cx - dx;
                        ny = cy - dy;
                        mult = (c[cx][dx] *
                                c[cy][dy]) % MOD;
                        if (nx < 0 || ny < 0)
                        {
                            continue;
                        }
                    }
                    else // forward
                    {
                        nx = cx + dx;
                        ny = cy + dy;
                        mult = (c[x - cx][dx] *
                                c[y - cy][dy]) % MOD;
                        if (nx > x || ny > y)
                        {
                            continue;
                        }
                    }
                    if (f[nb][nx][ny].dist == int.max)
                    {
                        f[nb][nx][ny].dist = cd;
                        q ~= state (nb, nx, ny);
                    }
                    if (f[nb][nx][ny].dist != cd)
                    {
                        continue;
                    }
                    f[nb][nx][ny].num =
                      (f[nb][nx][ny].num +
                       mult * cn) % MOD;
                }
            }
        }

        writefln ("%s", f[1][x][y].dist == int.max ?
                  -1 : f[1][x][y].dist);
        writefln ("%s", f[1][x][y].num);
    }
}


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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int m = n * 2 - 1;
		auto a = new int [m];
		int s = 0;
		foreach (i; 0..m)
		{
			readf (" %s", &a[i]);
			s += (a[i] <= 0);
			a[i] = abs (a[i]);
		}
		int res = reduce !("a + b") (a);
		if ((n % 2 == 0) && (s % 2 != 0))
		{
			res -= 2 * a[0];
		}
		writeln (res);
	}
}

Yaroslav has an array, consisting of (2·n-1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations?Help Yaroslav.

The first line contains an integer n (2≤n≤100). The second line contains (2·n-1) integers — the array elements. The array elements do not exceed 1000 in their absolute value.

In a single line print the answer to the problem — the maximum sum that Yaroslav can get.

In the first sample you do not need to change anything. The sum of elements equals 150.
In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int m = n * 2 - 1;
		auto a = new int [m];
		int s = 0;
		foreach (i; 0..m)
		{
			readf (" %s", &a[i]);
			s += (a[i] <= 0);
			a[i] = abs (a[i]);
		}
		sort (a);
		int res = reduce !("a + b") (a);
		if ((n % 2 == 0) && (s % 2 != 0))
		{
			res -= 2 * a[0];
		}
		writeln (res);
	}
}


// 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.bigint, 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 res = inp[0]; inp.popFront; return res.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!*******************************************/

ll[] totake, bitclust;

ll fval(ll endm){
    ll[34] freq = 0;
    ll[] memory = bitclust.dup;
    foreach(i; 0..endm.to!int){ ++freq[totake[i].to!int]; }

    foreach_reverse(k; 0..33){
        foreach_reverse(i; 0..k+1){
            ll take = min(freq[i]<<i, memory[k]<<k);
            ll taken = take/(1L<<i);
            freq[i] -= taken;
            ll left = (memory[k]<<k) - (taken << i);
            /* debug if(left)writeln(left, " ", memory[k]<<k, " ", memory[k], " ", k, " ", take); */
            memory[k] = 0;
            bitter(left, memory, k);
        }
        /* debug writeln(memory); */
    }
    /* debug writeln(endm, " ", freq); */
    foreach(i; 0..33){
        if(freq[i]) return 0;
    }
    return 1;
}

// Bit-terness of TLE
void bitter(ll val, ll[] freq, int maxx){
    ll num = val;
    foreach_reverse(i; 0..maxx){
        ll pow = 1<<i;
        freq[i] += num/pow;
        num %= pow;
    }
}

void play(){
    int n, m;
    n = rd!int; m = rd!int;
    ll[] clusters = rdarr;
    totake = rdarr;
    ll takes = 0;

    // Available units from clusters
    totake.sort();
    bitclust.length = 34;
    foreach(el; clusters){
        foreach(i; 0..33){
           if(el & (1L<<i)){
               ++bitclust[i];
           }
        }
    }
    writeln(bitclust);

    // binsearch
    ll lo = 0; ll hi = m + 1;
    while(hi - lo > 1){
        ll midd = (hi + lo)/2;
        (fval(midd) >= 1 ? lo : hi) = midd;
    }
    writeln(lo);
}

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

You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine.We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly n memory clusters, the i-th cluster consists of ai cells. You need to find memory for m arrays in your program. The j-th array takes 2^bj consecutive memory cells. There possibly isn't enough memory for all m arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays.

The first line of the input contains two integers n and m (1≤n,m≤10^6). The next line contains n integers a1,a2,...,an (1≤ai≤10^9). The next line contains m integers b1,b2,...,bm (1≤2^bi≤10^9).

Print a single integer — the answer to the problem.

In the first example you are given memory clusters with sizes 8, 4, 3, 2, 2 and arrays with sizes 8, 4, 4. There are few ways to obtain an answer equals 2: you can locate array with size 8 to the cluster with size 8, and one of the arrays with size 4 to the cluster with size 4. Another way is to locate two arrays with size 4 to the one cluster with size 8.
In the second example you are given 10 memory clusters with size 1 and 6 arrays with size 1. You can choose any 6 clusters and locate all given arrays to them.

// 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.bigint, 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 res = inp[0]; inp.popFront; return res.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!*******************************************/

ll[] totake, bitclust;

ll fval(ll endm){
    ll[34] freq = 0;
    ll[] memory = bitclust.dup;
    foreach(i; 0..endm.to!int){ ++freq[totake[i].to!int]; }

    foreach_reverse(k; 0..33){
        foreach_reverse(i; 0..k+1){
            ll take = min(freq[i]<<i, memory[k]<<k);
            ll taken = take/(1L<<i);
            freq[i] -= taken;
            ll left = (memory[k]<<k) - (taken << i);
            /* debug if(left)writeln(left, " ", memory[k]<<k, " ", memory[k], " ", k, " ", take); */
            memory[k] = 0;
            bitter(left, memory, k);
        }
        /* debug writeln(memory); */
    }
    /* debug writeln(endm, " ", freq); */
    foreach(i; 0..33){
        if(freq[i]) return 0;
    }
    return 1;
}

// Bit-terness of TLE
void bitter(ll val, ll[] freq, int maxx){
    ll num = val;
    foreach_reverse(i; 0..maxx){
        ll pow = 1<<i;
        freq[i] += num/pow;
        num %= pow;
    }
}

void play(){
    int n, m;
    n = rd!int; m = rd!int;
    ll[] clusters = rdarr;
    totake = rdarr;
    ll takes = 0;

    // Available units from clusters
    totake.sort();
    bitclust.length = 34;
    foreach(el; clusters){
        foreach(i; 0..33){
           if(el & (1L<<i)){
               ++bitclust[i];
           }
        }
    }
    /* writeln(bitclust); */

    // binsearch
    ll lo = 0; ll hi = m + 1;
    while(hi - lo > 1){
        ll midd = (hi + lo)/2;
        (fval(midd) >= 1 ? lo : hi) = midd;
    }
    writeln(lo);
}

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


module main;

import std.stdio;
import std.math;

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

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


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

void check(T...)(T args) {
    args.map!(to!string).array.join(" ").writeln;
}

int f(ref int[] b, ref int[] p, int a, int m) {
    for (int i = 0; i < m; i++) {
        a -= [p[i] - b[m - 1 - i], 0].reduce!max;
        if (a < 0) {
            return -1;
        }
    }
    return a;
}

void main() {
    int n, m, a; readf("%d %d %d\n", &n, &m, &a);
    int[] b = new int[n];
    int[] p = new int[m];
    foreach (i; 0 .. n) {
        scanf("%d", &b[i]);
    }
    foreach (i; 0 .. m) {
        scanf("%d", &p[i]);
    }
    b.sort!("a > b");
    p.sort;
    int x = 0;
    int l, r;
    int s = 0;
    for (l = 0, r = [n, m].reduce!min + 1; l + 1 < r; ) {
        x = (l + r) / 2;
        s = f(b, p, a, x);
        if (s >= 0) {
            l = x;
        } else {
            r = x;
        }
    }
    [l, [0, p[0 .. l].reduce!"a + b" - a].reduce!max].check;
}

A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles.In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has bi personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.Each boy can rent at most one bike, one cannot give his bike to somebody else.What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?

The first line of the input contains three integers n, m and a (1≤n,m≤10^5; 0≤a≤10^9). The second line contains the sequence of integers b1,b2,...,bn (1≤bi≤10^4), where bi is the amount of the i-th boy's personal money. The third line contains the sequence of integers p1,p2,...,pm (1≤pj≤10^9), where pj is the price for renting the j-th bike.

Print two integers r and s, where r is the maximum number of schoolboys that can rent a bike and s is the minimum total personal money needed to rent r bikes. If the schoolchildren cannot rent any bikes, then r=s=0.

In the first sample both schoolchildren can rent a bike. For instance, they can split the shared budget in half (5 rubles each). In this case one of them will have to pay 1 ruble from the personal money and the other one will have to pay 2 rubles from the personal money. In total, they spend 3 rubles of their personal money. This way of distribution of money minimizes the amount of spent personal money.

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

void check(T...)(T args) {
    args.map!(to!string).array.join(" ").writeln;
}

int f(ref int[] b, ref int[] p, int a, int m) {
    for (int i = 0; i < m; i++) {
        a -= [p[i] - b[m - 1 - i], 0].reduce!max;
        if (a < 0) {
            return -1;
        }
    }
    return a;
}

void main() {
    int n, m, a; readf("%d %d %d\n", &n, &m, &a);
    int[] b = new int[n];
    int[] p = new int[m];
    foreach (i; 0 .. n) {
        scanf("%d", &b[i]);
    }
    foreach (i; 0 .. m) {
        scanf("%d", &p[i]);
    }
    b.sort!("a > b");
    p.sort;
    int x = 0;
    int l, r;
    int s = 0;
    for (l = 0, r = [n, m].reduce!min + 1; l + 1 < r; ) {
        x = (l + r) / 2;
        s = f(b, p, a, x);
        if (s >= 0) {
            l = x;
        } else {
            r = x;
        }
    }
    if (l == 0) {
        writeln("0 0");
        return;
    }
    [l, [0, p[0 .. l].reduce!"a + b" - a].reduce!max].check;
}


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

    struct scroll { int id, pw, dmg; }

    scroll[] scs;
    foreach (i; 1 .. n+1) {
        int pw, dmg;
        readf("%s %s", &pw, &dmg);
        readln;

        scs ~= scroll(i, pw, dmg);
    }

    auto used = new bool[] (n+1);
    Tuple!(int, int)[] ans;
    int cur = mx;
    int sec = 0;
    int sm = 0;
    for (; sec <= 2100; ++sec) {
        cur = min(cur - sm + reg, mx);
        if (cur <= 0) { break; }

        foreach (i, e; scs) {
            if (used[i]) { continue; }

            if (e.pw * mx >= cur * 100) {
                used[i] = true;
                sm += e.dmg;
                ans ~= tuple(sec, e.id);
            }
        }
    }

    if (sec > 2100) {
        writeln("NO");
        return;
    }

    writeln("YES");
    writeln(sec, ' ', ans.length);
    ans.each!(e => writeln(e[0], ' ', e[1]));
}

Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:1) The boss has two parameters: max — the initial amount of health and reg — regeneration rate per second.2) Every scroll also has two parameters: powi — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).The boss is considered to be defeated if at the end of a second he has nonpositive (≤0) amount of health.Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.

The first line contains three integers N, max and reg (1≤N,max,reg≤1000) –– the amount of scrolls and the parameters of the boss. The next N lines contain two integers powi and dmgi each — the parameters of the i-th scroll (0≤powi≤100, 1≤dmgi≤2000).

In case Petya can’t complete this level, output in the single line NO.
Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds.
Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated.

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

    struct scroll { int id, pw, dmg; }

    scroll[] scs;
    scs ~= scroll(0, 0, 0);
    foreach (i; 1 .. n+1) {
        int pw, dmg;
        readf("%s %s", &pw, &dmg);
        readln;

        scs ~= scroll(i, pw, dmg);
    }

    auto used = new bool[] (n+1);
    Tuple!(int, int)[] ans;
    int cur = mx;
    int sec = 0;
    int sm = 0;
    for (; sec <= 2100; ++sec) {
        cur = min(cur - sm + reg, mx);
        if (cur <= 0) { break; }

        int best = 0;
        foreach (i, e; scs) {
            if (used[i]) { continue; }

            if (e.pw * mx >= cur * 100 && e.dmg > scs[best].dmg) {
                best = i.to!int;
            }
        }

        if (best != 0) {
            used[best] = true;
            ans ~= tuple(sec, best);
            sm += scs[best].dmg;
        }
    }

    if (sec > 2100) {
        writeln("NO");
        return;
    }

    writeln("YES");
    writeln(sec, ' ', ans.length);
    ans.each!(e => writeln(e[0], ' ', e[1]));
}


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

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

void main ()
{
	auto c = new long [] [] (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]) % MOD;
		}
	}

	auto f = new long [] [] [] (MAX_N, MAX_N, 2);
	// 0 is occupied, 1 is free
	f[1][0][1] = 1;

	foreach (n; 2..MAX_N)
	{
		foreach (k; 0..n + 1)
		{
			foreach (b; 0..2)
			{
				// one child
				int pk = k - (b == 0);
				if (pk >= 0)
				{
					long mult = n - 1;
					f[n][k][b] = (mult *
					    f[n - 1][pk][!b]) % MOD;
				}
			}

			// two children
			for (int x = 1; x < n - 1; x++)
			{
				int y = n - 1 - x;
				assert (x > 0 && y > 0);
				long mult = c[n - 1][x];
				mult = (mult * x) % MOD;
				mult = (mult * y) % MOD;

				for (int xk = 0; xk <= k; xk++)
				{
					int yk = void;

					debug {if (n == 3 && k == 1)
					    writeln (x, ' ', y, ' ',
					             k, ' ', xk);}
					// occupied
					yk = k - xk - 1;
					if (yk >= 0)
					{
						f[n][k][0] = (f[n][k][0] +
						    (f[x][xk][1] *
						    f[y][yk][0]) % MOD *
						    mult) % MOD;
						if (x < y ||
						    (x <= y && xk <= yk))
						{
							long mult2 = mult;
							if (x == y
							    /* && xk == yk */)
							{
								mult2 =
								    (mult2 *
								    HALF) %
								    MOD;
							}
							f[n][k][0] =
							    (f[n][k][0] +
							    (f[x][xk][1] *
							    f[y][yk][1]) %
							    MOD *
							    mult2) % MOD;
						}
					}

					// free
					yk = k - xk;
					if (x < y || (x <= y && xk <= yk))
					{
						f[n][k][1] = (f[n][k][1] +
						    (f[x][xk][0] *
						    f[y][yk][0]) % MOD *
						    mult) % MOD;
					}
				}
			}
			debug {writefln ("f[%s][%s] = %s, %s",
			                 n, k, f[n][k][0], f[n][k][1]);}
		}
	}

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

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


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

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (ref a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			int p = minp[r][d[i][r]];
			if (p < i) {
				y[r] = u[r][r] = p+1;
			}
			ans = max(ans, (i-u[r][r]+1));
			foreach_reverse (l; 0..r) {
				int pl = minp[l][d[i][r]];
				if (pl <= i) {
					y[l] = max(y[l], pl+1);
				}
				int pr = minp[r][d[i][l]];
				if (pr <= i) {
					u[l][r] = pr+1;
				}
				u[l][r] = max(u[l][r], u[l][r-1], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
	}
	writeln(ans);
}

You are given matrix a of size n×m, its elements are integers. We will assume that the rows of the matrix are numbered from top to bottom from 1 to n, the columns are numbered from left to right from 1 to m. We will denote the element on the intersecting of the i-th row and the j-th column as aij.We'll call submatrix i1,j1,i2,j2 (1≤i1≤i2≤n; 1≤j1≤j2≤m) such elements aij of the given matrix that i1≤i≤i2 AND j1≤j≤j2. We'll call the area of the submatrix number (i2-i1+1)·(j2-j1+1). We'll call a submatrix inhomogeneous, if all its elements are distinct.Find the largest (in area) inhomogenous submatrix of the given matrix.

The first line contains two integers n, m (1≤n,m≤400) — the number of rows and columns of the matrix, correspondingly.
Each of the next n lines contains m integers aij (1≤aij≤160000) — the elements of the matrix.

Print a single integer — the area of the optimal inhomogenous submatrix.

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

immutable MN = 410;
immutable MA = 160_010;
void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	short[MA][] minp = new short[MA][](MN);
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				y[l] = max(y[l], minp[l][d[i][r]]);
				u[l][r] = max(u[l][r], minp[r][d[i][l]]);
				if (r > 0) {
					u[l][r] = max(u[l][r], u[l][r-1]);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
			minp[r][d[i][r]] = cast(short)(i+1);
		}
	}
	writeln(ans);
}


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

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

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

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

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

class Node {
	Node l, r;
	long val;
	this(long val) {
		this.val = val;
	}
}

int N;
long[] A;

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

		Node[] nodes = new Node[N];
		foreach (i; 0 .. N) {
			nodes[i] = new Node(A[i]);
		}
		foreach (i; 0 .. N) {
			if (0 <= i - 1) {
				nodes[i].l = nodes[i - 1];
			}
			if (i + 1 < N) {
				nodes[i].r = nodes[i + 1];
			}
		}

		nodes.sort!"a.val < b.val";
		long ans;
		foreach (node; nodes[0 .. $ - 2]) {
debug{
Node[]ls;for(Node a=node.l;a;a=a.l)ls~=a;
foreach_reverse(a;ls)write(a.val," ");
for(Node a=node;a;a=a.r)write(a.val," ");
writeln;
}
			if (node.l is null && node.r is null) {
				//
			} else if (node.l is null) {
				ans += node.val;
				node.r.l = null;
			} else if (node.r is null) {
				ans += node.val;
				node.l.r = null;
			} else {
				ans += min(node.l.val, node.r.val);
				node.l.r = node.r;
				node.r.l = node.l;
			}
		}
		writeln(ans);
	}
	} catch (EOFException) {}
}

Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a,b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points. After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.

The first line contains a single integer n (1≤n≤5·10^5) — the number of elements in the array. The next line contains n integers ai (1≤ai≤10^6) — the values of the array elements.

In a single line print a single integer — the maximum number of points Artem can get.

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

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

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

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

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

class Node {
	Node l, r;
	long val;
	this(long val) {
		this.val = val;
	}
}

int N;
long[] A;

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

		if (N <= 2) {
			writeln(0);
			continue;
		}

		Node[] nodes = new Node[N];
		foreach (i; 0 .. N) {
			nodes[i] = new Node(A[i]);
		}
		foreach (i; 0 .. N) {
			if (0 <= i - 1) {
				nodes[i].l = nodes[i - 1];
			}
			if (i + 1 < N) {
				nodes[i].r = nodes[i + 1];
			}
		}

		nodes.sort!"a.val < b.val";
		long ans;
		foreach (node; nodes[0 .. $ - 2]) {
debug{
Node[]ls;for(Node a=node.l;a;a=a.l)ls~=a;
foreach_reverse(a;ls)write(a.val," ");
for(Node a=node;a;a=a.r)write(a.val," ");
writeln;
}
			if (node.l is null && node.r is null) {
				//
			} else if (node.l is null) {
				ans += node.val;
				node.r.l = null;
			} else if (node.r is null) {
				ans += node.val;
				node.l.r = null;
			} else {
				ans += min(node.l.val, node.r.val);
				node.l.r = node.r;
				node.r.l = node.l;
			}
		}
		writeln(ans);
	}
	} catch (EOFException) {}
}


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

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


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;

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

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


import std.algorithm, std.array, std.range, std.stdio, std.typecons;
alias Point = Tuple !(int, q{x}, int, q{y});
long sp (Point a, Point b, Point c) {return (b.x - a.x) * 1L * (c.x - a.x) + (b.y - a.y) * 1L * (c.y - a.y);}
long vp (Point a, Point b, Point c) {return (b.x - a.x) * 1L * (c.y - a.y) - (b.y - a.y) * 1L * (c.x - a.x);}
void main () {
	int k, n, res;
	readf (" %s %s", &k, &n);
	auto a = new Point [k], b = new Point [n], s = new int [] [] [] (k, n);
	foreach (ref p; a) readf (" %s %s", &p.x, &p.y);
	foreach (ref q; b) readf (" %s %s", &q.x, &q.y);
	foreach (p; 0..k) foreach (q; 0..n) s[p][q] = n.iota.filter !(r => vp (b[r], a[p], b[q]) == 0 && sp (b[r], a[p], b[q]) < 0).take (k).array;
	bool go (int mask, int depth, int [] t) {
		if (t.empty) return true;
		if (depth < t.length) return false;
		foreach (p; 0..k) if (mask & (1 << p)) foreach (i, q; t) {
			auto next = t[0..i] ~ t[i + 1..$] ~ s[p][q];
			if (go (mask ^ (1 << p), depth - 1, next.sort ().uniq.array)) return true;
		}
		return false;
	}
	foreach (q; 0..n) res += k.iota.any !(p => go (-1, k, [p]));
	writeln (res);
}

Bearland is a dangerous place. Limak can’t travel on foot. Instead, he has k magic teleportation stones. Each stone can be used at most once. The i-th stone allows to teleport to a point (axi,ayi). Limak can use stones in any order.There are n monsters in Bearland. The i-th of them stands at (mxi,myi).The given k+n points are pairwise distinct.After each teleportation, Limak can shoot an arrow in some direction. An arrow will hit the first monster in the chosen direction. Then, both an arrow and a monster disappear. It’s dangerous to stay in one place for long, so Limak can shoot only one arrow from one place.A monster should be afraid if it’s possible that Limak will hit it. How many monsters should be afraid of Limak?

The first line of the input contains two integers k and n (1≤k≤7, 1≤n≤1000) — the number of stones and the number of monsters.
The i-th of following k lines contains two integers axi and ayi (-10^9≤axi,ayi≤10^9) — coordinates to which Limak can teleport using the i-th stone.
The i-th of last n lines contains two integers mxi and myi (-10^9≤mxi,myi≤10^9) — coordinates of the i-th monster.
The given k+n points are pairwise distinct.

Print the number of monsters which should be afraid of Limak.

In the first sample, there are two stones and four monsters. Stones allow to teleport to points (-2,-1) and (4,5), marked blue in the drawing below. Monsters are at (4,2), (2,1), (4,-1) and (1,-1), marked red. A monster at (4,-1) shouldn't be afraid because it's impossible that Limak will hit it with an arrow. Other three monsters can be hit and thus the answer is 3.

In the second sample, five monsters should be afraid. Safe monsters are those at (300,600), (170,340) and (90,180).

import std.algorithm, std.array, std.range, std.stdio, std.typecons;
alias Point = Tuple !(int, q{x}, int, q{y});
long sp (Point a, Point b, Point c) {return (b.x - a.x) * 1L * (c.x - a.x) + (b.y - a.y) * 1L * (c.y - a.y);}
long vp (Point a, Point b, Point c) {return (b.x - a.x) * 1L * (c.y - a.y) - (b.y - a.y) * 1L * (c.x - a.x);}
void main () {
	int k, n, res;
	readf (" %s %s", &k, &n);
	auto a = new Point [k], b = new Point [n], s = new int [] [] [] (k, n);
	foreach (ref p; a) readf (" %s %s", &p.x, &p.y);
	foreach (ref q; b) readf (" %s %s", &q.x, &q.y);
	foreach (p; 0..k) foreach (q; 0..n) s[p][q] = n.iota.filter !(r => vp (b[r], a[p], b[q]) == 0 && sp (b[r], a[p], b[q]) < 0).take (k).array;
	bool go (int mask, int depth, int [] t) {
		if (t.empty) return true;
		if (depth < t.length) return false;
		foreach (p; 0..k) if (mask & (1 << p)) foreach (i, q; t) {
			auto next = t[0..i] ~ t[i + 1..$] ~ s[p][q];
			if (go (mask ^ (1 << p), depth - 1, next.sort ().uniq.array)) return true;
		}
		return false;
	}
	foreach (q; 0..n) res += go (-1, k, [q]);
	writeln (res);
}


import std.stdio, std.bigint, std.string;

void main() {
    auto a_ = readln.strip;
    auto n = a_.length;
    auto a = BigInt(a_);
    // auto b = BigInt(readln.strip);
    int b;
    scanf("%d", &b);
    if (n > 100) {
        writeln(b);
        writeln(a);
    }
    auto ans = a % b;
    auto pow10n = 1; for (int i=0; i<n; i++) pow10n = (pow10n * 10) % b;
    auto left=0;
    auto apow10i = int((a*10)%b);
    for (int i=1; i<n; i++) {
        left = (left * 10 + (a_[i-1]-'0')) % b;
        auto _a = (b + (apow10i + left - left * pow10n) % b) % b;
        apow10i = (apow10i * 10) % b;

        if (a_[i] != '0') {
            // writeln(left, ' ', _a, ' ', _a % b);
            if (_a % b < ans)
                ans = _a % b;
        }
    }
    writeln(ans);
}

Stepan has a very big positive integer.Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203 and integers 20310 and 31020.Stepan wants to know the minimum remainder of the division by the given number m among all good shifts. Your task is to determine the minimum remainder of the division by m.

The first line contains the integer which Stepan has. The length of Stepan's integer is between 2 and 200000 digits, inclusive. It is guaranteed that Stepan's integer does not contain leading zeros.
The second line contains the integer m (2≤m≤10^8) — the number by which Stepan divides good shifts of his integer.

Print the minimum remainder which Stepan can get if he divides all good shifts of his integer by the given number m.

In the first example all good shifts of the integer 521 (good shifts are equal to 521, 215 and 152) has same remainder 2 when dividing by 3.
In the second example there are only two good shifts: the Stepan's integer itself and the shift by one position to the right. The integer itself is 1001 and the remainder after dividing it by 5 equals 1. The shift by one position to the right equals to 1100 and the remainder after dividing it by 5 equals 0, which is the minimum possible remainder.

import std.stdio, std.bigint, std.string;

void main() {
    auto a_ = readln.strip;
    auto n = a_.length;
    auto a = BigInt(a_);
    // auto b = BigInt(readln.strip);
    long b;
    scanf("%ld", &b);

    auto ans = a % b;
    auto pow10n = 1; for (int i=0; i<n; i++) pow10n = (pow10n * 10) % b;
    long left=0L;
    auto apow10i = long((a*10L)%b);

    for (int i=1; i<n; i++) {
        left = (left * 10L + (a_[i-1]-'0')) % b;
        auto _a = (b + (apow10i + left - left * pow10n) % b) % b;
        apow10i = (apow10i * 10L) % b;
        if (a_[i] != '0') {
            if (_a % b < ans)
                ans = _a % b;
        }
    }
    writeln(ans);
}


import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
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 half = 1 << 10;
immutable int limit = half << 1;

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto b = new bool [half];
		readln;
		foreach (c; readln.splitter.map !(to !(int)))
		{
			b[c] = true;
		}

		auto f = new uint [] [] (2, limit / 32);
		int d = 0;
		f[d][] = 0;
		f[d][half >> 5] |= 1U << (half & 31);
		foreach (res; 1..half + 1)
		{
			d ^= 1;
			f[d][] = 0;
			foreach (c; 0..half)
			{
				if (!b[c])
				{
					continue;
				}
				int s = c - n;
				int sLo = s & 31;
				int sHi = s >> 5;
				int sBack = 32 - sLo;
				uint loMask = (1U << sLo) - 1U;
				uint hiMask = ~loMask;
				int j = sHi;
				foreach (i; 0..limit / 32)
				{
//					f[d][i + s] |= f[!d][i];
					if (j >= 0)
					{
						f[d][j] |= f[!d][i] << sLo;
					}
					j += 1;
					if (j >= limit / 32)
					{
						break;
					}
					if (j >= 0 && sLo != 0)
					{
						f[d][j] |= f[!d][i] >> sBack;
					}
				}
			}

			if (f[d][half >> 5] & (1U << (half & 31)))
			{
				writeln (res);
				break;
			}
		}
	}
}

Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration . Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration . The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass.Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well.Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration . Assume that the friends have unlimited amount of each Coke type.

The first line contains two integers n, k (0≤n≤1000, 1≤k≤10^6) — carbon dioxide concentration the friends want and the number of Coke types.
The second line contains k integers a1,a2,...,ak (0≤ai≤1000) — carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration.

Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration , or -1 if it is impossible.

In the first sample case, we can achieve concentration  using one liter of Coke of types  and : .
In the second case, we can achieve concentration  using two liters of  type and one liter of  type: .

import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
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 half = 1 << 10;
immutable int limit = half << 1;

void main ()
{
	int n;
	int k;
multitest_loop:
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto b = new bool [half];
		readln;
		foreach (c; readln.splitter.map !(to !(int)))
		{
			b[c] = true;
		}

		auto f = new uint [] [] (2, limit / 32);
		int d = 0;
		f[d][] = 0;
		f[d][half >> 5] |= 1U << (half & 31);
		foreach (res; 1..half + 1)
		{
			d ^= 1;
			f[d][] = 0;
			foreach (c; 0..half)
			{
				if (!b[c])
				{
					continue;
				}
				int s = c - n;
				int sLo = s & 31;
				int sHi = s >> 5;
				int sBack = 32 - sLo;
				uint loMask = (1U << sLo) - 1U;
				uint hiMask = ~loMask;
				int j = sHi;
				foreach (i; 0..limit / 32)
				{
//					f[d][i + s] |= f[!d][i];
					if (j >= 0)
					{
						f[d][j] |= f[!d][i] << sLo;
					}
					j += 1;
					if (j >= limit / 32)
					{
						break;
					}
					if (j >= 0 && sLo != 0)
					{
						f[d][j] |= f[!d][i] >> sBack;
					}
				}
			}

			if (f[d][half >> 5] & (1U << (half & 31)))
			{
				writeln (res);
				continue multitest_loop;
			}
		}
		writeln (-1);
	}
}