$$$n$$$ students are taking an exam. The highest possible score at this exam is $$$m$$$. Let $$$a_{i}$$$ be the score of the $$$i$$$-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied:   All scores are integers  $$$0 \leq a_{i} \leq m$$$  The average score of the class doesn't change. You are student $$$1$$$ and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 200$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^{3}$$$, $$$1 \leq m \leq 10^{5}$$$)  — the number of students and the highest possible score respectively. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 0 \leq a_{i} \leq m$$$)  — scores of the students.

For each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._

NoteIn the first case, $$$a = [1,2,3,4] $$$, with average of $$$2.5$$$. You can change array $$$a$$$ to $$$[10,0,0,0]$$$. Average remains $$$2.5$$$, and all conditions are satisfied.In the second case, $$$0 \leq a_{i} \leq 5$$$. You can change $$$a$$$ to $$$[5,1,1,3]$$$. You cannot increase $$$a_{1}$$$ further as it will violate condition $$$0\le a_i\le m$$$.

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint ();
    const m = r.next!uint ();
    auto a = r.nextA!uint (n);
    const s = sum (a[1 .. $]);
    int delta = min (m - a[0], s);
    writeln (a[0] + delta);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. scan!int){
        int n = scan!int, m = scan!int;
        long[] as = scan!long(n);

        min(m, as.sum).writeln;
    }
}

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		int b=0;
		readf(" %d", &a);
		readf(" %d", &b);
		int c=0;
		readf(" %d", &c);
		int sum=0;
		for (int j=1; j<a; j++)
		{
			int d=0;
			readf(" %d", &d);
			sum=sum+d;
		}
		if (sum>=b-c)
		{
			writeln(b);
		}
		else
		{
			writeln(c+sum);
		}
	}
	return 0;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto a = RDA!int;
		auto s = a.sum;
		ans[ti] = min(s, m);
	}

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


You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during $$$n$$$ consecutive days. During the $$$i$$$-th day you have to write exactly $$$a_i$$$ names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $$$m$$$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $$$1$$$ to $$$n$$$.

The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ means the number of names you will write in the notebook during the $$$i$$$-th day.

Print exactly $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$, where $$$t_i$$$ is the number of times you will turn the page during the $$$i$$$-th day.

NoteIn the first example pages of the Death Note will look like this $$$[1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]$$$. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1].to!long;
    auto A = readln.split.map!(to!long).array;

    auto ans = new long[](N);
    long P = 0;

    foreach (i; 0..N) {
        ans[i] += A[i] / M;
        A[i] %= M;
        P += A[i];
        if (P >= M) ans[i] += 1, P %= M;
    }

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

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

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

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

    int cur = 0;
    int[] ans;
    foreach (e; arr) {
        cur += e;
        int d = cur / m;
        int r = cur % m;
        ans ~= d;
        cur = r;
    }

    ans.writefln!("%(%s %)");
}

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

  int n; long m; rd(n, m);
  auto as=readln.split.to!(long[]);

  long s=0;
  long[] ans;
  foreach(a; as){
    s+=a;
    ans~=s/m;
    s%=m;
  }

  writefln("%(%s %)", ans);
}

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


Cowboy Vlad has a birthday today! There are $$$n$$$ children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible.Formally, let's number children from $$$1$$$ to $$$n$$$ in a circle order, that is, for every $$$i$$$ child with number $$$i$$$ will stand next to the child with number $$$i+1$$$, also the child with number $$$1$$$ stands next to the child with number $$$n$$$. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other.Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible.

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of the children who came to the cowboy Vlad's birthday. The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) denoting heights of every child.

Print exactly $$$n$$$ integers — heights of the children in the order in which they should stand in a circle. You can start printing a circle with any child. If there are multiple possible answers, print any of them.

NoteIn the first example, the discomfort of the circle is equal to $$$1$$$, since the corresponding absolute differences are $$$1$$$, $$$1$$$, $$$1$$$ and $$$0$$$. Note, that sequences $$$[2, 3, 2, 1, 1]$$$ and $$$[3, 2, 1, 1, 2]$$$ form the same circles and differ only by the selection of the starting point.In the second example, the discomfort of the circle is equal to $$$20$$$, since the absolute difference of $$$10$$$ and $$$30$$$ is equal to $$$20$$$.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    A.sort();

    auto B = iota(0, N, 2).array;
    auto C = iota(1, N, 2).array;
    foreach_reverse (c; C) B ~= c;

    long[] D;
    foreach (b; B) D ~= A[b];

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


Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm:  Root the tree at node 1.  Count the number of nodes at an even depth. Let it be evenCnt.  Count the number of nodes at an odd depth. Let it be oddCnt.  The answer is the minimum between evenCnt and oddCnt. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.

The only line contains an integer n (2 ≤ n ≤ 105), the number of nodes in the desired trees.

The output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output "-1" (without quotes) for that section only. If the answer for a section exists, it should contain n - 1 lines, each containing 2 space-separated integers u and v (1 ≤ u, v ≤ n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict. If there are multiple answers, you can print any of them.

NoteIn the first sample, there is only 1 tree with 2 nodes (node 1 connected to node 2). The algorithm will produce a correct answer in it so we printed  - 1 in the first section, but notice that we printed this tree in the second section.In the second sample:In the first tree, the algorithm will find an answer with 4 nodes, while there exists an answer with 3 nodes like this:  In the second tree, the algorithm will find an answer with 3 nodes which is correct:

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

void dame(int n)
{
	if (n < 6) {
		writeln(-1);
		return;
	}
	writeln("1 2");
	writeln("1 3");
	writeln("1 4");
	writeln("4 5");
	writeln("4 6");
	int m = n - 6;
	int ite = 7;
	int prev = 1;
	foreach (i; 0..m) {
		writefln("%d %d", prev, ite);
		prev = ite;
		++ite;
	}
}

void ok(int n) {
	foreach (i; 1..n) {
		writeln(1, " ", i + 1);
	}
}

void main()
{
	int n = readln.chomp.to!int;
	n.dame;
	n.ok;
}

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

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

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

  if (n <= 5) {
    writeln(-1);
  } else {
    writeln("1 2");
    writeln("1 3");
    writeln("1 4");
    foreach (i; 5..n+1) writeln("2 ", i);
  }

  foreach (i; 1..n)
    writeln(i, " ", i+1);
}


You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.

The first line contains two integers, n and m (1 ≤ n ≤ 3000, 1 ≤ m ≤ 3000) — the number of words in the professor's lecture and the number of words in each of these languages. The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once. The next line contains n space-separated strings c1, c2, ..., cn — the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1, a2, ... am}. All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.

Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.

4 3
codeforces codesecrof
contest round
letter message
codeforces contest letter contest

5 3
joll wuqrd
euzf un
hbnyiyc rsoqqveh
hbnyiyc joll joll euzf joll

codeforces round letter round
hbnyiyc joll joll un joll

import std.stdio, std.string;

string[string] words;

void main() {

	short n, m;

	scanf("%hd%hd", &n, &m);

	foreach (i; 0 .. m) {
		auto word1 = readln(' ').strip;
		auto word2 = readln.strip;
		words[word1] = (word2.length < word1.length) ? word2 : word1;
	}

	foreach (idx, lecture; readln.split) {
		write(words[lecture]);
		write((idx == n - 1) ? '\n' : ' ');
	}
}

import std.stdio, std.string;

string[string] words;

void main() {

	short n, m;

	scanf("%hd%hd", &n, &m);

	foreach (i; 0 .. m) {
		auto tmp = readln(' ').strip;
		words[tmp] = readln.strip;
	}

	foreach (idx, lecture; readln.split) {
		write((lecture.length <= words[lecture].length) ? lecture : words[lecture]);
		write((idx == n - 1) ? '\n' : ' ');
	}
}

import std.string : strip, split;
import std.stdio : scanf, readln, write;

string[string] words;

void main() {

	short n, m;

	scanf("%hd%hd", &n, &m);

	foreach (i; 0 .. m) {
		auto word1 = readln(' ').strip;
		auto word2 = readln.strip;
		if (word2.length < word1.length)
			words[word1] = word2;
	}

	foreach (idx, lecture; readln.split) {
		write(lecture in words ? words[lecture] : lecture);
		write((idx == n - 1) ? '\n' : ' ');
	}
}

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

void main(){
    int n,m;
    readf!"%d %d"(n,m);
    readln;
    string[string] aa;
    string[] l;
    while(m--){
        l=readln.split;
        aa[l[0]]=l[1];
    }
    auto f(ref string a){
        string b=aa[a];
        if(b.length<a.length) return b;
        return a;
    }
    readln.split.map!f.join(" ").writeln;
}

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

void main() {
    int n, m;
    readf("%d %d\n", &n, &m);
    string[string] dic;

    foreach(i; 0..m) {
        string a, b;
        readf("%s %s\n", &a, &b);
        if (a.length > b.length) {
            dic[a] = b;
        } else {
            dic[a] = a;
        }
    }

    string[] c = readln.chomp.split;
    c.map!(a => dic[a]).array.join(" ").writeln;
}

import std.stdio;
import std.string;

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

int main(string[] args)
{
    int n = read!int;
    int m = read!int;

    string s = readln;
    string[string] dic;
    foreach (i; 0..m)
    {
        s = readln;
        auto t = s.split;
        dic[t[0]] = t[1];
    }

    bool first = true;
    foreach (w; readln.split)
    {
        if (first)
            first = false;
        else
            write(" ");

        s = dic[w];
        if (s.length < w.length)
            write(s);
        else
            write(w);
    }
    writeln;

    return 0;
}

import std.stdio, std.string;

string[string] word;

void main() {

	short n, m;

	scanf("%hd%hd", &n, &m);

	foreach (i; 0 .. m) {
		auto word1 = readln(' ').strip;
		auto word2 = readln.strip;
		word[word1] = (word2.length < word1.length) ? word2 : word1;
	}

	foreach (idx, lecture; readln.split) {
		write(word[lecture]);
		write((idx == n - 1) ? '\n' : ' ');
	}
}


Andrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to insidious taxi drivers.The mayor of the city decided to change the direction of certain roads so that the taxi drivers wouldn't be able to increase the cost of the trip endlessly. More formally, if the taxi driver is on a certain crossroads, they wouldn't be able to reach it again if he performs a nonzero trip. Traffic controllers are needed in order to change the direction the road goes. For every road it is known how many traffic controllers are needed to change the direction of the road to the opposite one. It is allowed to change the directions of roads one by one, meaning that each traffic controller can participate in reversing two or more roads.You need to calculate the minimum number of traffic controllers that you need to hire to perform the task and the list of the roads that need to be reversed.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 100\,000$$$) — the number of crossroads and the number of roads in the city, respectively. Each of the following $$$m$$$ lines contain three integers $$$u_{i}$$$, $$$v_{i}$$$ and $$$c_{i}$$$ ($$$1 \leq u_{i}, v_{i} \leq n$$$, $$$1 \leq c_{i} \leq 10^9$$$, $$$u_{i} \ne v_{i}$$$) — the crossroads the road starts at, the crossroads the road ends at and the number of traffic controllers required to reverse this road.

In the first line output two integers the minimal amount of traffic controllers required to complete the task and amount of roads $$$k$$$ which should be reversed. $$$k$$$ should not be minimized. In the next line output $$$k$$$ integers separated by spaces — numbers of roads, the directions of which should be reversed. The roads are numerated from $$$1$$$ in the order they are written in the input. If there are many solutions, print any of them.

NoteThere are two simple cycles in the first example: $$$1 \rightarrow 5 \rightarrow 2 \rightarrow 1$$$ and $$$2 \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow 2$$$. One traffic controller can only reverse the road $$$2 \rightarrow 1$$$ and he can't destroy the second cycle by himself. Two traffic controllers can reverse roads $$$2 \rightarrow 1$$$ and $$$2 \rightarrow 3$$$ which would satisfy the condition.In the second example one traffic controller can't destroy the cycle $$$ 1 \rightarrow 3 \rightarrow 2 \rightarrow 1 $$$. With the help of three controllers we can, for example, reverse roads $$$1 \rightarrow 3$$$ ,$$$ 2 \rightarrow 4$$$, $$$1 \rightarrow 5$$$.

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto E = M.iota.map!(_ => readln.split.map!(to!int).array).array;

    long hi = 10^^9;
    long lo = -1;
    while (hi - lo > 1) {
        long mid = (hi + lo) / 2;
        auto G = new Kosaraju(N);
        foreach (e; E) {
            if (e[2] <= mid) continue;
            G.add_edge(e[0]-1, e[1]-1);
        }
        G.run;
        bool ok = G.g == N;
        if (ok) {
            hi = mid;
        } else {
            lo = mid;
        }
    }

    long v = hi;
    int[] ans;

    auto G = new Kosaraju(N);
    foreach (e; E) {
        if (e[2] <= v) continue;
        G.add_edge(e[0]-1, e[1]-1);
    }
    G.run;

    foreach (i; 0..M) {
        int a = E[i][0] - 1;
        int b = E[i][1] - 1;
        int c = E[i][2];
        if (c > v) continue;
        if (G.group[a] > G.group[b]) {
            ans ~= i+1;
        }
    }

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

class Kosaraju {
    int N;
    int[][] adj;
    int[][] rev_adj;
    int g;
    int[] group;

    this(int n) {
        N = n;
        adj = new int[][](N);
        rev_adj = new int[][](N);
        group = new int[](N);
    }

    void add_edge(int from, int to) {
        adj[from] ~= to;
        rev_adj[to] ~= from;
    }

    void run() {
        int[] ord;
        auto used = new bool[](N);
        foreach (i; 0..N)
            if (!used[i])
                dfs1(i, ord, used);
        foreach (i; 0..N) used[i] = false;
        auto g_num = 0;
        foreach (i; iota(N-1, -1, -1)) {
            if (!used[ord[i]]) {
                dfs2(ord[i], g_num, used);
                g_num += 1;
            }
        }
        g = g_num;
    }

    void dfs1(int from, ref int[] ord, ref bool[] used) {
        if (used[from]) return;
        used[from] = true;
        foreach (to; adj[from])
            if (!used[to])
                dfs1(to, ord, used);
        ord ~= from;
    }

    void dfs2(int from, int g_num, ref bool[] used) {
        if (used[from]) return;
        used[from] = true;
        group[from] = g_num;
        foreach (to; rev_adj[from])
            if (!used[to])
                dfs2(to, g_num, used);
    }

}


T is playing a game with his friend, HL.There are $$$n$$$ piles of stones, the $$$i$$$-th pile initially has $$$a_i$$$ stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in the previous turn (the pile that was chosen by the other player, or if the current turn is the first turn then the player can choose any non-empty pile). The player who cannot choose a pile in his turn loses, and the game ends.Assuming both players play optimally, given the starting configuration of $$$t$$$ games, determine the winner of each game.

The first line of the input contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of games. The description of the games follows. Each description contains two lines: The first line contains a single integer $$$n$$$ $$$(1 \le n \le 100)$$$ — the number of piles. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 100)$$$.

For each game, print on a single line the name of the winner, "T" or "HL" (without quotes)

NoteIn the first game, T removes a single stone from the only pile in his first turn. After that, although the pile still contains $$$1$$$ stone, HL cannot choose from this pile because it has been chosen by T in the previous turn. Therefore, T is the winner.

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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  int n;
  @Dim(q{n}) int[] a;

  void solve(long tc = -1)
  {
    int turn = 0;
    int fi = -1;
    while(true)
      {
        int maxi = -1, maxa = 0;
        foreach(i; 0 .. n)
          {
            if (i != fi)
              {
                if (a[i] > maxa)
                  {
                    maxi = i;
                    maxa = a[i];
                  }
              }
          }
        if (maxa == 0 || maxi == -1)
          {
            writeln(turn == 0? "HL" : "T");
            break;
          }
        a[maxi]--;
        fi = maxi;
        turn++;
        turn %= 2;
      }
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		a.sort!"a > b"();

		long x = a[0];
		long y;
		foreach (i; 1..n)
		{
			y += a[i];
		}
		if (x > y)
		{
			ans[ti] = true;
		}
		else
		{
			auto d = y - x;
			if (d % 2)
				ans[ti] = true;
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto s = a.sum;
		auto m = a.maxElement;
		writeln (s % 2 == 1 || m + m > s ? "T" : "HL");
	}
}


You are given a string $$$s$$$ consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.You have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of queries. Each of the next $$$t$$$ lines contains one string. The $$$i$$$-th line contains a string $$$s_i$$$ consisting only of lowercase Latin letter. It is guaranteed that the length of $$$s_i$$$ is from $$$1$$$ to $$$1000$$$ (inclusive).

Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: -1 if it is impossible to obtain a good string by rearranging the letters of $$$s_i$$$ and any good string which can be obtained from the given one (by rearranging the letters) otherwise.

NoteIn the first query we cannot rearrange letters to obtain a good string.Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".In the third query we can do nothing to obtain a good string.

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

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

    while (Q--) {
        auto S = readln.chomp.to!(dchar[]);
        if (S.map!(s => s == S.front).all) {
            writeln(-1);
        } else {
            S.sort;
            S.writeln;
        }
    }

}


A flowerbed has many flowers and two fountains.You can adjust the water pressure and set any values r1(r1 ≥ 0) and r2(r2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains.You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12 + r22 is minimum possible. Find this minimum value.

The first line of the input contains integers n, x1, y1, x2, y2 (1 ≤ n ≤ 2000,  - 107 ≤ x1, y1, x2, y2 ≤ 107) — the number of flowers, the coordinates of the first and the second fountain. Next follow n lines. The i-th of these lines contains integers xi and yi ( - 107 ≤ xi, yi ≤ 107) — the coordinates of the i-th flower. It is guaranteed that all n + 2 points in the input are distinct.

Print the minimum possible value r12 + r22. Note, that in this problem optimal answer is always integer.

NoteThe first sample is (r12 = 5, r22 = 1):  The second sample is (r12 = 1, r22 = 32):

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

long distsq(int x, int y) {
    return (cast(long)x * x) + (cast(long)y * y);
}

struct pnt {
    int x, y;
    long da, db;
}

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

    int n, ax, ay, bx, by;
    readf(" %s %s %s %s %s\n", &n, &ax, &ay, &bx, &by);
    pnt[] parr = new pnt[n + 1];
    foreach (i ; 0 .. n) {
        readf(" %s %s\n", &parr[i].x, &parr[i].y);
        parr[i].da = distsq(parr[i].x - ax, parr[i].y - ay);
        parr[i].db = distsq(parr[i].x - bx, parr[i].y - by);
    }
    parr[n] = pnt(ax, ay, 0, distsq(ax - bx, ay - by));
    parr.sort!"a.da < b.da";
    long ans = long.max;
    foreach (i ; 0 .. n + 1) {
        long r12 = parr[i].da;
        long r22 = (i < n) ? parr[i + 1 .. $].maxElement!"a.db".db : 0;
        ans = min(ans, r12 + r22);
    }
    writeln(ans);

    return 0;
}

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

long distsq(int x, int y) {
    return (cast(long)x * x) + (cast(long)y * y);
}

struct pnt {
    int x, y;
    long da, db;
}

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

    int n, ax, ay, bx, by;
    readf(" %s %s %s %s %s\n", &n, &ax, &ay, &bx, &by);
    pnt[] parr = new pnt[n];
    foreach (i ; 0 .. n) {
        readf(" %s %s\n", &parr[i].x, &parr[i].y);
        parr[i].da = distsq(parr[i].x - ax, parr[i].y - ay);
        parr[i].db = distsq(parr[i].x - bx, parr[i].y - by);
    }
    parr.sort!"a.da < b.da";
    long ans = long.max;
    foreach (i ; 0 .. n - 1) {
        long r12 = parr[i].da;
        long r22 = parr[i + 1 .. $].maxElement!"a.db".db;
        ans = min(ans, r12 + r22);
    }
    ans = min(ans, parr[0 .. $].maxElement!"a.db".db);
    ans = min(ans, parr[n - 1].da);
    writeln(ans);

    return 0;
}

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

long distsq(int x, int y) {
    return (cast(long)x * x) + (cast(long)y * y);
}

struct pnt {
    int x, y;
    long da, db;
}

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

    int n, ax, ay, bx, by;
    readf(" %s %s %s %s %s\n", &n, &ax, &ay, &bx, &by);
    pnt[] parr = new pnt[n];
    pnt*[] ppa = new pnt*[n];
    pnt*[] ppb = new pnt*[n];
    foreach (i ; 0 .. n) {
        readf(" %s %s\n", &parr[i].x, &parr[i].y);
        parr[i].da = distsq(parr[i].x - ax, parr[i].y - ay);
        parr[i].db = distsq(parr[i].x - bx, parr[i].y - by);
    }
    foreach (i ; 0 .. n) {
        ppa[i] = &parr[i];
        ppb[i] = &parr[i];
    }
    ppa.sort!"a.da < b.da";
    ppb.sort!"a.db < b.db";
    long ans = long.max;
    ans = min(ans, ppa[n-1].da);
    ans = min(ans, ppb[n-1].db);
    int idx = n - 1;
    foreach (i ; 0 .. n - 1) {
        long r12 = ppa[i].da;
        ppa[i].db = 0;
        while (idx > 0 && ppb[idx].db == 0)
            --idx;
        long r22 = ppb[idx].db;
        ans = min(ans, r12 + r22);
    }
    writeln(ans);

    return 0;
}


Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if it is happy originally), he stays happy forever.Drazil wants to know on which day all his friends become happy or to determine if they won't become all happy at all.

The first line contains two integer n and m (1 ≤ n, m ≤ 109). The second line contains integer b (0 ≤ b ≤ min(n, 105)), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1, x2, ..., xb (0 ≤ xi < n), denoting the list of indices of happy boys. The third line conatins integer g (0 ≤ g ≤ min(m, 105)), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1, y2, ... , yg (0 ≤ yj < m), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.

Print the number of the first day that all friends of Drazil become happy. If this day won't come at all, you print -1.

NoteBy  we define the remainder of integer division of i by k.In first sample case:   On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day.  On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day.  On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day.  On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy.  On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.

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; ) { if (stdin.eof) throw new EOFException; tokens = readln.split; } auto token = tokens[0]; tokens.popFront; return token; }
int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

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

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

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

Int mod(Int)(Int a, Int m) { if ((a %= m) < 0) a += m; return a; }
Int gcd(Int)(Int a, Int b) { return (b != 0) ? gcd(b, a % b) : a; }
Int lcm(Int)(Int a, Int b) { return a / gcd(a, b) * b; }
Int gojo(Int)(Int a, Int b, out Int x, out Int y) {
	if (b != 0) { Int g = gojo(b, a % b, y, x); y -= (a / b) * x; return g; }
	x = 1; y = 0; return a;
}
Int modInv(Int)(Int a, Int m) { Int x, y; gojo(a, m, x, y); return mod(x, m); }

immutable INF = 2 * 10L^^18 + 1;

int esLen;
int[] es;

int[] work;
int[] bkt;

void radixSort() {
	if (esLen < 0x10000) {
		es[0 .. esLen].sort();
	} else {
		bkt[] = 0;
		foreach (i; 0 .. esLen) ++bkt[es[i] & 0xFFFF];
		foreach (j; 0 .. 0xFFFF) bkt[j + 1] += bkt[j];
		foreach (i; 0 .. esLen) work[--bkt[es[i] & 0xFFFF]] = es[i];
		bkt[] = 0;
		foreach (i; 0 .. esLen) ++bkt[work[i] >> 16];
		foreach (j; 0 .. 0xFFFF) bkt[j + 1] += bkt[j];
		foreach_reverse (i; 0 .. esLen) es[--bkt[work[i] >> 16]] = work[i];
	}
}

bool check(int s, long m, long n, Pair!(long, int)[] xs, long[] ps, long l) {
debug{
writeln("check ",s," ",m," ",n," ",xs," ",ps," ",l);
}
	// Pair!(long, int)[] es;
	// long[] es;
	esLen = 0;
	foreach (i, x; xs) {
		/*
			x, x + m, x + 2 m, ... (mod n)
			while x + k m <= l
		*/
		const a = ps[i];
		const k = (x.x <= l) ? min((l - x.x) / m + 1, n) : (x.y != s) ? 1 : 0;
		if (a + k <= n) {
			// es ~= pair(a, +1);
			// es ~= pair(a + k, -1);
			// es ~= a << 1;
			// es ~= (a + k) << 1 | 1;
			es[esLen++] = cast(int)(a << 1);
			es[esLen++] = cast(int)((a + k) << 1 | 1);
		} else {
			// es ~= pair(a, +1);
			// es ~= pair(n, -1);
			// es ~= pair(0L, +1);
			// es ~= pair(a + k - n, -1);
			// es ~= a << 1;
			// es ~= n << 1 | 1;
			// es ~= 0 << 1;
			// es ~= (a + k - n) << 1 | 1;
			es[esLen++] = cast(int)(a << 1);
			es[esLen++] = cast(int)(n << 1 | 1);
			es[esLen++] = cast(int)(0 << 1);
			es[esLen++] = cast(int)((a + k - n) << 1 | 1);
		}
	}
	// es.sort();
	// es[0 .. esLen].sort();
	radixSort;
debug{
// writeln("  es = ",es);
writeln("  es = ",es[0..esLen]);
}
	long bef;
	int now;
	// foreach (e; es) {
	foreach (i; 0 .. esLen) {
		auto e = es[i];
		// if (bef < e.x) {
		if (bef < e >> 1) {
			if (now <= 0) {
debug{
// writeln("  fail ",bef,e.x);
writeln("  fail ",bef,e>>1);
}
				return false;
			}
		}
		// bef = e.x;
		// now += e.y;
		bef = e >> 1;
		now += (e & 1) ? -1 : +1;
	}
	if (bef < n) {
		return false;
	}
	return true;
}

long solve(long m, long n, Pair!(long, int)[] xs) {
debug{
writeln("solve ",m," ",n," ",xs);
}
	if (xs.empty) {
		return INF;
	}
	if (xs.length == m + n) {
		return -1;
	}
	auto ps = new long[xs.length];
	auto qs = new long[xs.length];
	foreach (i, x; xs) {
		ps[i] = (x.x * modInv(m, n)) % n;
		qs[i] = (x.x * modInv(n, m)) % m;
	}
	long lo = -1, ho = 2 * m * n;
	for (; lo + 1 < ho; ) {
		const mo = (lo + ho) / 2;
		(check(0, m, n, xs, ps, mo) && check(1, n, m, xs, qs, mo)) ? (ho = mo) : (lo = mo);
	}
debug{
assert(check(0, m, n, xs, ps, ho));
assert(check(1, n, m, xs, qs, ho));
}
	return ho;
}

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

long brute() {
	auto isA = new bool[cast(size_t)(M)];
	auto isB = new bool[cast(size_t)(N)];
	long cnt;
	foreach (a; A) {
		isA[cast(size_t)(a)] = true;
		++cnt;
	}
	foreach (b; B) {
		isB[cast(size_t)(b)] = true;
		++cnt;
	}
	if (cnt == M + N) {
		return -1;
	}
	foreach (x; 0 .. 1000) {
		const a = cast(size_t)(x % M);
		const b = cast(size_t)(x % N);
		if (isA[a] && !isB[b]) {
			isB[b] = true;
			++cnt;
		}
		if (isB[b] && !isA[a]) {
			isA[a] = true;
			++cnt;
		}
		if (cnt == M + N) {
			return x;
		}
	}
	return -1;
}

long solve() {
	const d = gcd(M, N);
	if (d > M + N) {
		return -1;
	}
	auto xss = new Pair!(long, int)[][cast(size_t)(d)];
	foreach (a; A) {
		xss[cast(size_t)(a % d)] ~= pair(a / d, 0);
	}
	foreach (b; B) {
		xss[cast(size_t)(b % d)] ~= pair(b / d, 1);
	}
	long ans = -1;
	foreach (r; 0 .. d) {
		auto res = solve(M / d, N / d, xss[cast(size_t)(r)]);
		if (res >= INF) {
			ans = INF;
		} else {
			chmax(ans, res * d + r);
		}
	}
	return (ans >= INF) ? -1 : ans;
}

void main(string[] args) {
	es = new int[8 * 10^^5 + 10];
	work = new int[8 * 10^^5 + 10];
	bkt = new int[0x10000];

	try {
	for (; ; ) {
		M = readLong;
		N = readLong;
		A = new long[readInt];
		foreach (ref a; A) {
			a = readLong;
		}
		B = new long[readInt];
		foreach (ref b; B) {
			b = readLong;
		}

		const res = solve;
debug{
const brt=brute;
if(brt!=res){
writeln(M," ",N," ",A," ",B," : ",brt," ",res);
stdout.flush;
assert(false);
}
}
		writeln(res);

	}
	} catch (EOFException) {}
}

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; ) { if (stdin.eof) throw new EOFException; tokens = readln.split; } auto token = tokens[0]; tokens.popFront; return token; }
int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

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

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

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

Int mod(Int)(Int a, Int m) { if ((a %= m) < 0) a += m; return a; }
Int gcd(Int)(Int a, Int b) { return (b != 0) ? gcd(b, a % b) : a; }
Int lcm(Int)(Int a, Int b) { return a / gcd(a, b) * b; }
Int gojo(Int)(Int a, Int b, out Int x, out Int y) {
	if (b != 0) { Int g = gojo(b, a % b, y, x); y -= (a / b) * x; return g; }
	x = 1; y = 0; return a;
}
Int modInv(Int)(Int a, Int m) { Int x, y; gojo(a, m, x, y); return mod(x, m); }

immutable INF = 2 * 10L^^18 + 1;

bool check(int s, long m, long n, Pair!(long, int)[] xs, long[] ps, long l) {
debug{
writeln("check ",s," ",m," ",n," ",xs," ",ps," ",l);
}
	Pair!(long, int)[] es;
	foreach (i, x; xs) {
		/*
			x, x + m, x + 2 m, ... (mod n)
			while x + k m <= l
		*/
		const a = ps[i];
		const k = (x.x <= l) ? min((l - x.x) / m + 1, n) : (x.y != s) ? 1 : 0;
		if (a + k <= n) {
			es ~= pair(a, +1);
			es ~= pair(a + k, -1);
		} else {
			es ~= pair(a, +1);
			es ~= pair(n, -1);
			es ~= pair(0L, +1);
			es ~= pair(a + k - n, -1);
		}
	}
	es.sort();
debug{
writeln("  es = ",es);
}
	long bef;
	int now;
	foreach (e; es) {
		if (bef < e.x) {
			if (now <= 0) {
debug{
writeln("  fail ",bef,e.x);
}
				return false;
			}
		}
		bef = e.x;
		now += e.y;
	}
	if (bef < n) {
		return false;
	}
	return true;
}

long solve(long m, long n, Pair!(long, int)[] xs) {
debug{
writeln("solve ",m," ",n," ",xs);
}
	if (xs.empty) {
		return INF;
	}
	if (xs.length == m + n) {
		return -1;
	}
	auto ps = new long[xs.length];
	auto qs = new long[xs.length];
	foreach (i, x; xs) {
		ps[i] = (x.x * modInv(M, N)) % N;
		qs[i] = (x.x * modInv(N, M)) % M;
	}
	long lo = -1, ho = 2 * m * n;
	for (; lo + 1 < ho; ) {
		const mo = (lo + ho) / 2;
		(check(0, m, n, xs, ps, mo) && check(1, n, m, xs, qs, mo)) ? (ho = mo) : (lo = mo);
	}
	return ho;
}

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

long brute() {
	auto isA = new bool[cast(size_t)(M)];
	auto isB = new bool[cast(size_t)(N)];
	long cnt;
	foreach (a; A) {
		isA[cast(size_t)(a)] = true;
		++cnt;
	}
	foreach (b; B) {
		isB[cast(size_t)(b)] = true;
		++cnt;
	}
	foreach (x; 0 .. 1000) {
		const a = cast(size_t)(x % M);
		const b = cast(size_t)(x % N);
		if (isA[a] && !isB[b]) {
			isB[b] = true;
			++cnt;
		}
		if (isB[b] && !isA[a]) {
			isA[a] = true;
			++cnt;
		}
		if (cnt == M + N) {
			return x;
		}
	}
	return -1;
}

long solve() {
	const d = gcd(M, N);
	if (d > M + N) {
		return -1;
	}
	auto xss = new Pair!(long, int)[][cast(size_t)(d)];
	foreach (a; A) {
		xss[cast(size_t)(a % d)] ~= pair(a / d, 0);
	}
	foreach (b; B) {
		xss[cast(size_t)(b % d)] ~= pair(b / d, 1);
	}
	long ans;
	foreach (r; 0 .. d) {
		auto res = solve(M / d, N / d, xss[cast(size_t)(r)]);
		if (res >= INF) {
			ans = INF;
		} else {
			chmax(ans, res * d + r);
		}
	}
	return (ans >= INF) ? -1 : ans;
}

void main(string[] args) {
	try {
	for (; ; ) {
		M = readLong;
		N = readLong;
		A = new long[readInt];
		foreach (ref a; A) {
			a = readLong;
		}
		B = new long[readInt];
		foreach (ref b; B) {
			b = readLong;
		}

		const res = solve;
debug{
const brt=brute;
if(brt!=res){
writeln(M," ",N," ",A," ",B," : ",brt," ",res);
stdout.flush;
assert(false);
}
}
		writeln(res);

	}
	} catch (EOFException) {}
}

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; ) { if (stdin.eof) throw new EOFException; tokens = readln.split; } auto token = tokens[0]; tokens.popFront; return token; }
int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

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

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

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

Int mod(Int)(Int a, Int m) { if ((a %= m) < 0) a += m; return a; }
Int gcd(Int)(Int a, Int b) { return (b != 0) ? gcd(b, a % b) : a; }
Int lcm(Int)(Int a, Int b) { return a / gcd(a, b) * b; }
Int gojo(Int)(Int a, Int b, out Int x, out Int y) {
	if (b != 0) { Int g = gojo(b, a % b, y, x); y -= (a / b) * x; return g; }
	x = 1; y = 0; return a;
}
Int modInv(Int)(Int a, Int m) { Int x, y; gojo(a, m, x, y); return mod(x, m); }

immutable INF = 2 * 10L^^18 + 1;

bool check(long m, long n, long[] xs, long[] ys, long l) {
debug{
writeln("check ",m," ",n," ",xs," ",ys," ",l);
}
	Pair!(long, int)[] es;
	foreach (i, x; xs) if (x <= l) {
		/*
			x, x + m, x + 2 m, ... (mod n)
			while x + k m <= l
		*/
		const a = ys[i];
		const k = min((l - x) / m + 1, n);
		if (a + k <= n) {
			es ~= pair(a, +1);
			es ~= pair(a + k, -1);
		} else {
			es ~= pair(a, +1);
			es ~= pair(n, -1);
			es ~= pair(0L, +1);
			es ~= pair(a + k - n, -1);
		}
	}
	es.sort();
debug{
writeln("  es = ",es);
}
	long bef;
	int now;
	foreach (e; es) {
		if (bef < e.x) {
			if (now <= 0) {
debug{
writeln("  fail ",bef,e.x);
}
				return false;
			}
		}
		bef = e.x;
		now += e.y;
	}
	if (bef < n) {
		return false;
	}
	return true;
}

long solve(long m, long n, long[] xs) {
debug{
writeln("solve ",m," ",n," ",xs);
}
	if (xs.empty) {
		return INF;
	}
	auto ysM = new long[xs.length];
	auto ysN = new long[xs.length];
	foreach (i, x; xs) {
		ysM[i] = (x * modInv(M, N)) % N;
		ysN[i] = (x * modInv(N, M)) % M;
	}
	long lo = -1, ho = 2 * m * n;
	for (; lo + 1 < ho; ) {
		const mo = (lo + ho) / 2;
		(check(m, n, xs, ysM, mo) && check(n, m, xs, ysN, mo)) ? (ho = mo) : (lo = mo);
	}
	return ho;
}

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

void main(string[] args) {
	try {
	for (; ; ) {
		M = readLong;
		N = readLong;
		A = new long[readInt];
		foreach (ref a; A) {
			a = readLong;
		}
		B = new long[readInt];
		foreach (ref b; B) {
			b = readLong;
		}

		const d = gcd(M, N);
		if (d > M + N) {
			writeln(-1);
			continue;
		}

		auto xss = new long[][cast(size_t)(d)];
		foreach (a; A) {
			xss[cast(size_t)(a % d)] ~= a / d;
		}
		foreach (b; B) {
			xss[cast(size_t)(b % d)] ~= b / d;
		}

		long ans;
		foreach (r; 0 .. d) {
			auto res = solve(M / d, N / d, xss[cast(size_t)(r)]);
			if (res >= INF) {
				ans = INF;
			} else {
				chmax(ans, res * d + r);
			}
		}
		writeln((ans >= INF) ? -1 : ans);

	}
	} catch (EOFException) {}
}


Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.

The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000.

A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.

NoteIn the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are: 1 2 1 2 31 1 2 2 32 1 1 2 3

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

void main() {
    immutable int MAX = 1500;
    immutable long MOD = 10^^9+7;

    auto modinv = new long[](MAX);
    modinv[0] = modinv[1] = 1;
    foreach(i; 2..MAX) {
        modinv[i] = modinv[MOD % i] * (MOD - MOD / i) % MOD;
    }

    auto f_mod = new long[](MAX);
    auto f_modinv = new long[](MAX);
    f_mod[0] = f_mod[1] = 1;
    f_modinv[0] = f_modinv[1] = 1;

    foreach(i; 2..MAX) {
        f_mod[i] = (i * f_mod[i-1]) % MOD;
        f_modinv[i] = (modinv[i] * f_modinv[i-1]) % MOD;
    }

    long nck(int n, int k) {
        return f_mod[n] * f_modinv[n-k] % MOD * f_modinv[k] % MOD;
    }

    auto N = readln.chomp.to!int;
    auto A = N.iota.map!(_ => readln.chomp.to!int).array;

    int acm = A.sum;
    int empty = N;
    long ans = 1;
    foreach (i; iota(N-1, -1, -1)) {
        ans = ans * nck(acm-1, A[i]-1) % MOD;
        acm -= A[i];
    }
    ans.writeln;
}

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

void solve(int[] a, int n)
{
    static const int mod = 1000000007;
    auto t = reduce!((a, b) => a + b)(a);
    auto c = new int[][](t + 1, t + 1);
    foreach (i; 0 .. t + 1)
    {
        fill(c[i], 0);
    }
    foreach (i; 0 .. t + 1)
    {
        c[i][0] = 1;
    }
    foreach (i; 1 .. t + 1)
    {
        foreach (j; 1 .. i + 1)
        {
            c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;
        }
    }
    long ans = 1;
    for (int i = n - 1; i >= 0; -- i)
    {
        ans = (ans * c[t - 1][a[i] - 1]) % mod;
        t -= a[i];
    }
    writeln(ans);
}

int main(string[] args)
{
    int k;
    while (readf("%d\n", &k) == 1)
    {
        auto c = new int[k];
        foreach (i; 0 .. k)
        {
            readf(" %d", &c[i]);
        }
        readln;
        solve(c, k);
    }
    return 0;
}

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

void solve(int[] a, int n)
{
    static const int mod = 1000000007;
    auto t = reduce!((a, b) => a + b)(a);
    auto c = new int[][](t + 1, t + 1);
    foreach (i; 0 .. t + 1)
    {
        fill(c[i], 0);
    }
    foreach (i; 0 .. t + 1)
    {
        c[i][0] = 1;
    }
    foreach (i; 1 .. t + 1)
    {
        foreach (j; 1 .. i + 1)
        {
            c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;
        }
    }
    auto ans = 1;
    for (int i = n - 1; i >= 0; -- i)
    {
        ans = (ans * c[t - 1][a[i] - 1]) % mod;
        t -= a[i];
    }
    writeln(ans);
}

int main(string[] args)
{
    int k;
    while (readf("%d\n", &k) == 1)
    {
        auto c = new int[k];
        foreach (i; 0 .. k)
        {
            readf(" %d", &c[i]);
        }
        readln;
        solve(c, k);
    }
    return 0;
}


You are given an integer $$$n$$$. Find any string $$$s$$$ of length $$$n$$$ consisting only of English lowercase letters such that each non-empty substring of $$$s$$$ occurs in $$$s$$$ an odd number of times. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, print a single line containing the string $$$s$$$. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.

NoteIn the first test case, each substring of "abc" occurs exactly once.In the third test case, each substring of "bbcaabbba" occurs an odd number of times. In particular, "b" occurs $$$5$$$ times, "a" and "bb" occur $$$3$$$ times each, and each of the remaining substrings occurs exactly once.

import std.stdio;
import std.ascii;
import std.algorithm;
import std.range;
import core.stdc.stdio;

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
void solve()
{
	int n = readInt!int;
	if (n == 1) return writeln("a");
	if (n == 3) return writeln("abc");
	int[] a;
	if (n & 1)
	{
		a.length = 3;
		auto toSum = (n + 3)/2;
		a[0] = 1;
		a[1] = 1;
		a[2] = toSum - 2;
		debug writeln(a);
		chain(repeat('a', a[0] - 1),
		repeat('b', a[1]),
		repeat('c', a[2]),
		repeat('a', a[0]),
		repeat('b', a[1]-1),
		repeat('c', max(a[2]-1, 0))).writeln;
	}
	else
	{
		a.length = 2;
		auto toSum = (n + 2)/2;
		a[0] = 1;
		a[1] = toSum - 1;
		chain(repeat('a').take(a[0] - 1), repeat('b').take(a[1]), repeat('a').take(a[0]),
				repeat('b').take(a[1]-1)).writeln;
	}
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else
			static assert(text("Operator ", operator, " not supported"));
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}

import std.stdio;
import std.ascii;
import std.algorithm;
import std.range;
import core.stdc.stdio;

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
void solve()
{
	int n = readInt!int;
	if (n == 1) return writeln("a");
	if (n == 3) return writeln("abc");
	int[] a;
	if (n & 1)
	{
		a.length = 3;
		auto toSum = (n + 3)/2;
		a[0] = 2;
		a[1] = 1;
		a[2] = toSum - 3;
		debug writeln(a);
		chain(repeat('a', a[0]),
		repeat('b', a[1]),
		repeat('c', a[2]),
		repeat('a', a[0]-1),
		repeat('b', a[1]-1),
		repeat('c', max(a[2]-1, 0))).writeln;
	}
	else
	{
		a.length = 2;
		auto toSum = (n + 2)/2;
		a[0] = toSum/2;
		a[1] = toSum - toSum/2;
		chain(repeat('a').take(a[0] - 1), repeat('b').take(a[1]), repeat('a').take(a[0]),
				repeat('b').take(a[1]-1)).writeln;
	}
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else
			static assert(text("Operator ", operator, " not supported"));
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}

import std.stdio;
import std.ascii;
import std.algorithm;
import std.range;
import core.stdc.stdio;

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
void solve()
{
	int n = readInt!int;
	if (n == 1) return writeln("a");
	int[] a;
	if (n & 1)
	{
		a.length = 3;
		auto toSum = (n + 3)/2;
		a[0] = 2;
		a[1] = 1;
		a[2] = toSum - 3;
		debug writeln(a);
		chain(repeat('a', a[0]),
		repeat('b', a[1]),
		repeat('c', a[2]),
		repeat('a', a[0]-1),
		repeat('b', a[1]-1),
		repeat('c', max(a[2]-1, 0))).writeln;
	}
	else
	{
		a.length = 2;
		auto toSum = (n + 2)/2;
		a[0] = toSum/2;
		a[1] = toSum - toSum/2;
		chain(repeat('a').take(a[0] - 1), repeat('b').take(a[1]), repeat('a').take(a[0]),
				repeat('b').take(a[1]-1)).writeln;
	}
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else
			static assert(text("Operator ", operator, " not supported"));
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}


Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich. Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers $$$a$$$ and $$$b$$$ ($$$a < b$$$). After that, the student can apply any of the following operations any number of times:   $$$a := a + 1$$$ (increase $$$a$$$ by $$$1$$$),  $$$b := b + 1$$$ (increase $$$b$$$ by $$$1$$$),  $$$a := a \ | \ b$$$ (replace $$$a$$$ with the bitwise OR of $$$a$$$ and $$$b$$$). To get full marks on the test, the student has to tell the teacher the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.Igor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make $$$a$$$ equal to $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The only line for each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a < b \le 10^6$$$). It is guaranteed that the sum of $$$b$$$ over all test cases does not exceed $$$10^6$$$.

For each test case print one integer — the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.

NoteIn the first test case, it is optimal to apply the third operation.In the second test case, it is optimal to apply the first operation three times.In the third test case, it is optimal to apply the second operation and then the third operation.

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

enum int INF = 1<<28;

void solve() {
    int A, B; readf("%d %d\n", &A, &B);

    int ans = min(B - A, (A|B) - B + 1);

    for (int x = A; x <= B; x++) {
        uint y = 0;
        for (int k = 31; k >= 0; k--) {
            bool fa = (x & (1 << k)) > 0;
            bool fb = (B & (1 << k)) > 0;
            if (fa) {
                if (fb) {
                    y |= 1 << k;
                } else {
                    y |= 1 << k;
                    break;
                }
            } else {
                if (fb) {
                    y |= 1 << k;
                }
            }
        }
        int cost = (x - A) + (y - B) + (x | y) - y + 1;
        ans = min(ans, cost);
    }

    writeln(ans);
}

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

import std;

T
read (alias T, string end = "") () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

/** Returns how many increments must be done to `a` to reach a value
 * that satisfies `value | b == b`
 */
uint
distance (in uint a, in uint b) {
    enforce(a < b);

    foreach (shift; iota(30, -1, -1))
        if ((a & 1 << shift) != 0 && (b & 1 << shift) == 0) {
            while (!((b & 1 << shift) != 0 && (a & 1 << shift) == 0))
                ++ shift;
            immutable end = 1 << shift;
            immutable start = ~(~0 << shift) & a;

            /*
            writefln!"a:     %032b"(a);
            writefln!"b:     %032b"(b);
            writefln!"start: %032b"(start);
            writefln!"end:   %032b"(end);
            writeln("----");
            */

            return end - start;
        }
    return 0;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        import comp = std.algorithm.comparison;

        immutable a = read!(uint, " ");
        immutable b = read!(uint, "\n");

        if (a >= b) {
            writeln(a - b);
            continue;
        }

        uint min = b - a;

        for (uint i = 0, newB = b; i < min; ++ i, ++ newB) {
            immutable to_reach = a | newB;
            immutable steps = 1 + i + to_reach - newB;

            min = comp.min(min, steps);
        }

        for (uint i = 0, newB = b; i < min; ++ i, ++ newB) {
            immutable steps = 1 + i + distance(a, newB);
            min = comp.min(min, steps);
        }

        writeln(min);
    }
}
// ""

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

enum int INF = 1<<28;

void solve() {
    int A, B; readf("%d %d\n", &A, &B);

    /*
    writefln("%020b", A);
    writefln("%020b", B);
    */

    int ans = B - A;

    ans = min(ans, (A | B) - B + 1);

    int C = A & (~B);
    if (C > 0) {
        int k = C.bsr;
        ans = min(ans, (B & ~((1<<(k+1)) - 1)) - (A & ((1<<(k+1)) - 1)) + 1);
        ans = min(ans, (A & ((1<<(k+1)) - 1)) - (B & ((1<<(k+1)) - 1)) + 1);
    }
    writeln(ans);
}

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

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

enum int INF = 1<<28;

void solve() {
    int A, B; readf("%d %d\n", &A, &B);

    /*
    writefln("%020b", A);
    writefln("%020b", B);
    */

    int ans = B - A;

    ans = min(ans, (A | B) - B + 1);

    int C = A & (~B);
    if (C > 0) {
        int k = C.bsr;
        ans = min(ans, (B & ~(1<<k)) - (A & ((1<<(k+1)) - 1)) + 1);
        ans = min(ans, (A & ((1<<(k+1)) - 1)) - (B & ((1<<(k+1)) - 1)) + 1);
    }
    writeln(ans);
}

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

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

enum int INF = 1<<28;

void solve() {
    int A, B; readf("%d %d\n", &A, &B);

    /*
    writefln("%020b", A);
    writefln("%020b", B);
    */

    int ans = B - A;

    ans = min(ans, (A | B) - B + 1);

    int C = A & (~B);
    if (C > 0) {
        int k = C.bsr;
        ans = min(ans, (B & ~(1<<k)) - (A & ((1<<(k+1)) - 1)) + 1);
    }

    int ka = A.bsr;
    ans = min(ans, (A & ((1<<(ka+1)) - 1)) - (B & ((1<<(ka+1)) - 1)) + 1);
    writeln(ans);
}

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


A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given a regular bracket sequence $$$s$$$ and an integer number $$$k$$$. Your task is to find a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$.It is guaranteed that such sequence always exists.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 2 \cdot 10^5$$$, both $$$n$$$ and $$$k$$$ are even) — the length of $$$s$$$ and the length of the sequence you are asked to find. The second line is a string $$$s$$$ — regular bracket sequence of length $$$n$$$.

Print a single string — a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$. It is guaranteed that such sequence always exists.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto S = readln.chomp;

    auto st = new int[](N*2);
    int p = -1;
    int cnt = 0;
    int front = 0;

    foreach (i; 0..N) {
        if (S[i] == '(') {
            st[++p] = i;
        } else if (cnt < N - K) {
            cnt += 2;
            p -= 1;
        } else {
            st[++p] = i;
        }
    }

    foreach (i; 0..p+1) {
        write(S[st[i]]);
    }

    writeln;
}

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

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

    auto s = readln.chomp;

    int taken = 0, unclosed = 0;
    dchar[] ans;
    foreach (e; s) {
        if (e == '(' && taken * 2 < k) {
            ans ~= e;
            ++taken;
            ++unclosed;
        } else if (e == ')' && unclosed > 0) {
            ans ~= e;
            --unclosed;
        }
    }

    ans.writeln;
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto s = '[' ~ readln.strip ~ ']';
		n += 2;
		k += 2;
		auto next = n.iota.array;
		next[] += 1;
		auto prev = n.iota.array;
		prev[] -= 1;
		int pos = 0;
		while (k < n)
		{
			int cur = next[pos];
			debug {writeln (pos, " ", cur, " ", k, " ", n);}
			if (s[pos] == '(' && s[cur] == ')')
			{
				int lo = prev[pos];
				int hi = next[cur];
				next[lo] = hi;
				prev[hi] = lo;
				n -= 2;
				pos = lo;
			}
			else
			{
				pos = next[pos];
			}
		}

		pos = 0;
		while (true)
		{
			pos = next[pos];
			if (s[pos] == ']')
			{
				break;
			}
			write (s[pos]);
		}
		writeln;
	}
}

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

void main()
{
    int n, k;
    readf("%d %d\n",  &n, &k);
    auto s = readln[0 .. $ - 1];
    string a;
    foreach(i, c; s) {
        if (!a.empty && a.back == '(' && c == ')') {
            n -= 2;
            a.popBack;
        } else {
            a ~= c;
        }
        if (n == k) {
            a ~= s[i + 1 .. $];
            break;
        }
    }
    writeln(a);
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      const S = readToken();

      alias Entry = Tuple!(int, "h", int, "i", int, "j");
      Entry[] es;

      DList!int stack;
      int now;
      foreach (i; 0 .. N) {
        if (S[i] == '(') {
          stack ~= i;
          ++now;
        } else {
          const j = stack.back;
          stack.removeBack;
          --now;
          es ~= Entry(now, j, i);
        }
      }
      es.sort;
      debug {
        writeln("es = ", es);
      }

      auto used = new bool[N];
      foreach (k; 0 .. K / 2) {
        used[es[k].i] = used[es[k].j] = true;
      }
      string ans;
      foreach (i; 0 .. N) {
        if (used[i]) {
          ans ~= S[i];
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

    auto s = readln.chomp;

    int left = k, v = 0;
    dchar[] ans;
    foreach (e; s) {
        if (e == '(' && left > 1) {
            ans ~= e;
            ++v;
            --left;
        } else if (e == ')' && v > 0 && left > 0) {
            ans ~= e;
            --v;
            --left;
        }
    }

    ans.writeln;
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto s = '[' ~ readln.strip ~ ']';
		n += 2;
		k += 2;
		auto next = n.iota.array;
		next[] += 1;
		auto prev = n.iota.array;
		prev[] -= 1;
		int pos = 0;
		while (k < n)
		{
			int cur = next[pos];
			writeln (pos, " ", cur, " ", k, " ", n);
			if (s[pos] == '(' && s[cur] == ')')
			{
				int lo = prev[pos];
				int hi = next[cur];
				next[lo] = hi;
				prev[hi] = lo;
				n -= 2;
				pos = lo;
			}
			else
			{
				pos = next[pos];
			}
		}

		pos = 0;
		while (true)
		{
			pos = next[pos];
			if (s[pos] == ']')
			{
				break;
			}
			write (s[pos]);
		}
		writeln;
	}
}


You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned.If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible.Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of tasks. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108), where ai represents the amount of power required for the i-th task. The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 100), where bi is the number of processors that i-th task will utilize.

Print a single integer value — the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up.

NoteIn the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9.In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round.

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

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

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

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

enum INF = 10L^^18;
enum R = 1000;

alias Task = Tuple!(long, "a", long, "b");

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto T = new Task[N];
      foreach (i; 0 .. N) {
        T[i].a = readLong();
      }
      foreach (i; 0 .. N) {
        T[i].b = readLong();
      }
      T.sort;
      T.reverse;

      long[] as;
      long[][] bss;
      for (int i = 0, j; i < N; i = j) {
        long[] bs;
        for (j = i; j < N && T[i].a == T[j].a; ++j) {
          bs ~= T[j].b;
        }
        as ~= T[i].a;
        bss ~= bs;
      }
      const asLen = cast(int)(as.length);
      auto bsLens = new int[asLen];
      foreach (i; 0 .. asLen) {
        bsLens[i] = cast(int)(bss[i].length);
      }
      debug {
        writeln("as = ", as);
        writeln("bss = ", bss);
      }

      bool check(long t) {
        debug {
          writeln("t = ", t);
        }
        // pos, room
        auto dp = new long[][](asLen + 1, N + 1);
        foreach (i; 0 .. asLen + 1) {
          dp[i][] = INF;
        }
        dp[0][0] = 0;
        foreach (i; 0 .. asLen) {
          auto vals = new long[bsLens[i] + 1];
          foreach (x; 0 .. bsLens[i]) {
            vals[x + 1] = vals[x] + (R * as[i] - t * bss[i][x]);
          }
          debug {
            writefln("  vals[%s] = %s", i, vals);
          }
          foreach (j; 0 .. N + 1) {
            if (dp[i][j] < INF) {
              foreach (x; 0 .. bsLens[i] + 1) {
                if (j >= bsLens[i] - x) {
                  chmin(dp[i + 1][j - (bsLens[i] - x) + x], dp[i][j] + vals[x]);
                }
              }
            }
          }
        }
        debug {
          foreach (i; 0 .. asLen + 1) {
            writefln("  dp[%s] = %s", i, dp[i]);
          }
        }
        foreach (j; 0 .. N + 1) {
          if (dp[asLen][j] <= 0) {
            return true;
          }
        }
        return false;
      }

      long lo = -1, hi = 10L^^12;
      for (; lo + 1 < hi; ) {
        const mid = (lo + hi) / 2;
        (check(mid) ? hi : lo) = mid;
      }
      writeln(hi);
    }
  } catch (EOFException e) {
  }
}