Annie has gotten bored of winning every coding contest and farming unlimited rating. Today, she is going to farm potatoes instead.Annie's garden is an infinite 2D plane. She has $$$n$$$ potatoes to plant, and the $$$i$$$-th potato must be planted at $$$(x_i,y_i)$$$. Starting at the point $$$(0, 0)$$$, Annie begins walking, in one step she can travel one unit right or up (increasing her $$$x$$$ or $$$y$$$ coordinate by $$$1$$$ respectively). At any point $$$(X,Y)$$$ during her walk she can plant some potatoes at arbitrary points using her potato gun, consuming $$$\max(|X-x|,|Y-y|)$$$ units of energy in order to plant a potato at $$$(x,y)$$$. Find the minimum total energy required to plant every potato.Note that Annie may plant any number of potatoes from any point.

The first line contains the integer $$$n$$$ ($$$1 \le n \le 800\,000$$$). The next $$$n$$$ lines contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i,y_i \le 10^9$$$), representing the location of the $$$i$$$-th potato. It is possible that some potatoes should be planted in the same location.

Print the minimum total energy to plant all potatoes.

NoteIn example $$$1$$$, Annie can travel to each spot directly and plant a potato with no energy required.In example $$$2$$$, moving to $$$(1,0)$$$, Annie plants the second potato using $$$1$$$ energy. Next, she travels to $$$(1,1)$$$ and plants the first potato with $$$0$$$ energy.

// code by cutx64

module main;

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

void main() {

  int n; readf!"%s\n"(n);
  alias NodeType = Tuple!(int, "v", int, "x");
  NodeType[] a;
  foreach(i; 0 .. n) {
    int x, y; readf!"%s %s\n"(x, y);
    a ~= NodeType(x + y, x);
  }
  a.sort;
  RedBlackTree!(long, "a > b", true) hl = make!(RedBlackTree!(long, "a > b", true))();
  RedBlackTree!(long, "a < b", true) hr = make!(RedBlackTree!(long, "a < b", true))();
  foreach(i; 0 .. n + 1) {
    hl.insert(0);
    hr.insert(0);
  }
  int last;
  long tag, ans;
  foreach(i; 0 .. n) {
    int d = a[i].v - last;
    last = a[i].v;
    tag += d;
    int x = a[i].x;
    if (x <= hl.front) {
      ans += hl.front - x;
      hl.insert(x);
      hl.insert(x);
      hr.insert(hl.front - tag);
      hl.removeFront;
    }
    else if (x >= hr.front + tag) {
      ans += x - (hr.front + tag);
      hr.insert(x - tag);
      hr.insert(x - tag);
      hl.insert(hr.front + tag);
      hr.removeFront;
    }
    else {
      hl.insert(x);
      hr.insert(x - tag);
    }
  }
  ans.writeln;

} // main

// code by cutx64

module main;

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

void main() {

  int n; readf!"%s\n"(n);
  alias NodeType = Tuple!(int, "v", int, "x");
  NodeType[] a;
  foreach(i; 0 .. n) {
    int x, y; readf!"%s %s\n"(x, y);
    a ~= NodeType(x + y, x);
  }
  a.sort;
  BinaryHeap!(Array!long) hl;
  BinaryHeap!(Array!long, "a > b") hr;
  foreach(i; 0 .. n + 1) {
    hl.insert(0);
    hr.insert(0);
  }
  int last;
  long tag, ans;
  foreach(i; 0 .. n) {
    int d = a[i].v - last;
    last = a[i].v;
    tag += d;
    int x = a[i].x;
    if (x <= hl.front) {
      ans += hl.front - x;
      hl.insert(x);
      hl.insert(x);
      hr.insert(hl.front() - tag);
      hl.popFront;
    }
    else if (x >= hr.front + tag) {
      ans += x - (hr.front + tag);
      hr.insert(x - tag);
      hr.insert(x - tag);
      hl.insert(hr.front + tag);
      hr.popFront;
    }
    else {
      hl.insert(x);
      hr.insert(x - tag);
    }
  }
  ans.writeln;

} // main


A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x1, y1), and the distress signal came from the point (x2, y2).Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed  meters per second.Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (vx, vy) for the nearest t seconds, and then will change to (wx, wy). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x, y), while its own velocity relative to the air is equal to zero and the wind (ux, uy) is blowing, then after  seconds the new position of the dirigible will be .Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.

The first line of the input contains four integers x1, y1, x2, y2 (|x1|,  |y1|,  |x2|,  |y2| ≤ 10 000) — the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively.  The second line contains two integers  and t (0 < v, t ≤ 1000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively.  Next follow one per line two pairs of integer (vx, vy) and (wx, wy), describing the wind for the first t seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that  and .

Print a single real value — the minimum time the rescuers need to get to point (x2, y2). You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

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

void main ()
{
	real x1, y1, x2, y2;
	while (readf (" %s %s %s %s", &x1, &y1, &x2, &y2) > 0)
	{
		real dx = x2 - x1;
		real dy = y2 - y1;
		real vmax, t, vx, vy, wx, wy;
		readf (" %s %s", &vmax, &t);
		readf (" %s %s", &vx, &vy);
		readf (" %s %s", &wx, &wy);

		real lo = 0;
		real hi = 1E10;
		foreach (step; 0..100)
		{
			real me = (lo + hi) * 0.5;
			real ex = dx - vx * min (t, me) - wx * max (me - t, 0);
			real ey = dy - vy * min (t, me) - wy * max (me - t, 0);
			real dist = hypot (ey, ex);
			if (dist <= vmax * me)
			{
				hi = me;
			}
			else
			{
				lo = me;
			}
		}
		writefln ("%.20f", lo);
	}
}


On a strip of land of length $$$n$$$ there are $$$k$$$ air conditioners: the $$$i$$$-th air conditioner is placed in cell $$$a_i$$$ ($$$1 \le a_i \le n$$$). Two or more air conditioners cannot be placed in the same cell (i.e. all $$$a_i$$$ are distinct).Each air conditioner is characterized by one parameter: temperature. The $$$i$$$-th air conditioner is set to the temperature $$$t_i$$$.    Example of strip of length $$$n=6$$$, where $$$k=2$$$, $$$a=[2,5]$$$ and $$$t=[14,16]$$$. For each cell $$$i$$$ ($$$1 \le i \le n$$$) find it's temperature, that can be calculated by the formula $$$$$$\min_{1 \le j \le k}(t_j + |a_j - i|),$$$$$$where $$$|a_j - i|$$$ denotes absolute value of the difference $$$a_j - i$$$.In other words, the temperature in cell $$$i$$$ is equal to the minimum among the temperatures of air conditioners, increased by the distance from it to the cell $$$i$$$.Let's look at an example. Consider that $$$n=6, k=2$$$, the first air conditioner is placed in cell $$$a_1=2$$$ and is set to the temperature $$$t_1=14$$$ and the second air conditioner is placed in cell $$$a_2=5$$$ and is set to the temperature $$$t_2=16$$$. In that case temperatures in cells are:  temperature in cell $$$1$$$ is: $$$\min(14 + |2 - 1|, 16 + |5 - 1|)=\min(14 + 1, 16 + 4)=\min(15, 20)=15$$$;  temperature in cell $$$2$$$ is: $$$\min(14 + |2 - 2|, 16 + |5 - 2|)=\min(14 + 0, 16 + 3)=\min(14, 19)=14$$$;  temperature in cell $$$3$$$ is: $$$\min(14 + |2 - 3|, 16 + |5 - 3|)=\min(14 + 1, 16 + 2)=\min(15, 18)=15$$$;  temperature in cell $$$4$$$ is: $$$\min(14 + |2 - 4|, 16 + |5 - 4|)=\min(14 + 2, 16 + 1)=\min(16, 17)=16$$$;  temperature in cell $$$5$$$ is: $$$\min(14 + |2 - 5|, 16 + |5 - 5|)=\min(14 + 3, 16 + 0)=\min(17, 16)=16$$$;  temperature in cell $$$6$$$ is: $$$\min(14 + |2 - 6|, 16 + |5 - 6|)=\min(14 + 4, 16 + 1)=\min(18, 17)=17$$$. For each cell from $$$1$$$ to $$$n$$$ find the temperature in it.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the input. Then test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first line contains two integers $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) and $$$k$$$ ($$$1 \le k \le n$$$) — the length of the strip of land and the number of air conditioners respectively. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — positions of air conditioners on the strip of land. The third line contains $$$k$$$ integers $$$t_1, t_2, \ldots, t_k$$$ ($$$1 \le t_i \le 10^9$$$) — temperatures of air conditioners. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case output $$$n$$$ integers separated by space: temperatures of air in cells.

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

void read(S...)(ref S args) {
  auto input = readln.split;
  assert(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

void main() {
  int t;
  read(t);

  while (t--) {
    readln;
    int n, k;
    read(n, k);

    auto arr = new int[n];

    auto pos = list!int.map!"a - 1".array;
    auto tmp = list!int;

    auto h = heapify!"a > b"(zip(tmp, pos).array);

    while (!h.empty) {
      auto top = h.removeAny();
      auto p = top[1];
      auto d = top[0];
      if (p < 0 || p >= n) continue;
      if (arr[p] == 0 || arr[p] > d) {
        arr[p] = d;
        h.insert(tuple(d + 1, p - 1));
        h.insert(tuple(d + 1, p + 1));
      }
    }

    writefln!"%(%d %)"(arr);
  }
}


You are given two positive integers $$$a$$$ and $$$b$$$.In one move, you can change $$$a$$$ in the following way:  Choose any positive odd integer $$$x$$$ ($$$x > 0$$$) and replace $$$a$$$ with $$$a+x$$$;  choose any positive even integer $$$y$$$ ($$$y > 0$$$) and replace $$$a$$$ with $$$a-y$$$. You can perform as many such operations as you want. You can choose the same numbers $$$x$$$ and $$$y$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is given as two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case, print the answer — the minimum number of moves required to obtain $$$b$$$ from $$$a$$$ if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.

NoteIn the first test case, you can just add $$$1$$$.In the second test case, you don't need to do anything.In the third test case, you can add $$$1$$$ two times.In the fourth test case, you can subtract $$$4$$$ and add $$$1$$$.In the fifth test case, you can just subtract $$$6$$$.

import std.stdio : readln, writeln;

struct IO {
  import std.conv : to;
  import std.range : empty, front, popFront, split;

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

  int readInt() {
    return readToken.to!int;
  }

  string[] tokens;
}

int solve(int a, int b) {
  if (a == b) {
    return 0;
  }
  if (a < b) {
    return (b & 1) == (a & 1) ? 2 : 1;
  }
  return (b & 1) == (a & 1) ? 1 : 2;
}

void main() {
  IO io;
  int T = io.readInt;
  while (T--) {
    int a = io.readInt;
    int b = io.readInt;
    writeln(solve(a, b));
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. rint){
        int a = rint, b = rint;
        if(a < b){
            if((b - a) % 2) 1.writeln;
            else 2.writeln;
        }
        else if(a == b) 0.writeln;
        else{
            if((a - b) % 2) 2.writeln;
            else 1.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);
		if (a==b)
		{
			writeln(0);
		}
		else
		{
			if (((b-a)%2==1 && b>a) || ((b-a)%2==0 && b<a))
			{
				writeln(1);
			}
			else
			{
				writeln(2);
			}
		}
	}
	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 long[](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		if (a == b)
			ans[ti] = 0;
		else if (b > a)
			ans[ti] = (b - a) % 2 == 0 ? 2 : 1;
		else
			ans[ti] = (a - b) % 2 == 0 ? 1 : 2;
	}

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


You are given a weighted tree with $$$n$$$ vertices. Recall that a tree is a connected graph without any cycles. A weighted tree is a tree in which each edge has a certain weight. The tree is undirected, it doesn't have a root.Since trees bore you, you decided to challenge yourself and play a game on the given tree.In a move, you can travel from a node to one of its neighbors (another node it has a direct edge with).You start with a variable $$$x$$$ which is initially equal to $$$0$$$. When you pass through edge $$$i$$$, $$$x$$$ changes its value to $$$x ~\mathsf{XOR}~ w_i$$$ (where $$$w_i$$$ is the weight of the $$$i$$$-th edge). Your task is to go from vertex $$$a$$$ to vertex $$$b$$$, but you are allowed to enter node $$$b$$$ if and only if after traveling to it, the value of $$$x$$$ will become $$$0$$$. In other words, you can travel to node $$$b$$$ only by using an edge $$$i$$$ such that $$$x ~\mathsf{XOR}~ w_i = 0$$$. Once you enter node $$$b$$$ the game ends and you win.Additionally, you can teleport at most once at any point in time to any vertex except vertex $$$b$$$. You can teleport from any vertex, even from $$$a$$$.Answer with "YES" if you can reach vertex $$$b$$$ from $$$a$$$, and "NO" otherwise.Note that $$$\mathsf{XOR}$$$ represents the bitwise XOR operation.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$2 \leq n \leq 10^5$$$), ($$$1 \leq a, b \leq n; a \ne b$$$) — the number of vertices, and the starting and desired ending node respectively. Each of the next $$$n-1$$$ lines denotes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$  — the labels of vertices it connects ($$$1 \leq u_i, v_i \leq n; u_i \ne v_i; 1 \leq w_i \leq 10^9$$$) and the weight of the respective edge. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output "YES" if you can reach vertex $$$b$$$, and "NO" otherwise.

NoteFor the first test case, we can travel from node $$$1$$$ to node $$$3$$$, $$$x$$$ changing from $$$0$$$ to $$$1$$$, then we travel from node $$$3$$$ to node $$$2$$$, $$$x$$$ becoming equal to $$$3$$$. Now, we can teleport to node $$$3$$$ and travel from node $$$3$$$ to node $$$4$$$, reaching node $$$b$$$, since $$$x$$$ became equal to $$$0$$$ in the end, so we should answer "YES".For the second test case, we have no moves, since we can't teleport to node $$$b$$$ and the only move we have is to travel to node $$$2$$$ which is impossible since $$$x$$$ wouldn't be equal to $$$0$$$ when reaching it, so we should answer "NO".

import std;

void dfs(int s, Tuple!(int, int)[][] adj, bool[] vis, int val, ref bool[int] valset)
{
  vis[s] = true;
  foreach (d ; adj[s]) {
    if (vis[d[0]])
      continue;
    valset[val ^ d[1]] = true;
    dfs(d[0], adj, vis, val ^ d[1], valset);
  }
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, a, b;
    readf!" %d %d %d "(n, a, b);
    a--;
    b--;
    auto adj = new Tuple!(int, int)[][](n, 0);
    foreach (i ; 0 .. n - 1) {
      int u, v, w;
      readf!" %d %d %d "(u, v, w);
      u--;
      v--;
      adj[u] ~= tuple(v, w);
      adj[v] ~= tuple(u, w);
    }

    bool[int] xora, xorb;
    bool[] visa = new bool[](n);
    bool[] visb = new bool[](n);
    visa[b] = true;
    dfs(a, adj, visa, 0, xora);
    dfs(b, adj, visb, 0, xorb);
    bool ans = false;
    xora[0] = true;
    foreach (k, v ; xora) {
      if (k in xorb) {
        ans = true;
        break;
      }
    }

//    writeln("-");
//    writeln(adj);
//    writeln(xora);
//    writeln(xorb);

    writeln(ans ? "YES" : "NO");
  }
}

import std;

void dfs(int s, Tuple!(int, int)[][] adj, bool[] vis, int val, ref bool[int] valset)
{
  vis[s] = true;
  foreach (d ; adj[s]) {
    if (vis[d[0]])
      continue;
    valset[val ^ d[1]] = true;
    dfs(d[0], adj, vis, val ^ d[1], valset);
  }
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, a, b;
    readf!" %d %d %d "(n, a, b);
    a--;
    b--;
    auto adj = new Tuple!(int, int)[][](n, 0);
    foreach (i ; 0 .. n - 1) {
      int u, v, w;
      readf!" %d %d %d "(u, v, w);
      u--;
      v--;
      adj[u] ~= tuple(v, w);
      adj[v] ~= tuple(u, w);
    }

    bool[int] xora, xorb;
    bool[] visa = new bool[](n);
    bool[] visb = new bool[](n);
    visa[b] = true;
    dfs(a, adj, visa, 0, xora);
    dfs(b, adj, visb, 0, xorb);
    bool ans = false;
    xora[0] = true;
    foreach (k, v ; xora) {
      if (v in xorb) {
        ans = true;
        break;
      }
    }

//    writeln("-");
//    writeln(adj);
//    writeln(xora);
//    writeln(xorb);

    writeln(ans ? "YES" : "NO");
  }
}

import std;

void dfs(int s, Tuple!(int, int)[][] adj, bool[] vis, int val, ref bool[int] valset)
{
  if (!vis[s]) {
    valset[val] = true;
    vis[s] = true;
  }
  foreach (d ; adj[s]) {
    if (vis[d[0]])
      continue;
    dfs(d[0], adj, vis, val ^ d[1], valset);
  }
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, a, b;
    readf!" %d %d %d "(n, a, b);
    a--;
    b--;
    auto adj = new Tuple!(int, int)[][](n, 0);
    foreach (i ; 0 .. n - 1) {
      int u, v, w;
      readf!" %d %d %d "(u, v, w);
      u--;
      v--;
      adj[u] ~= tuple(v, w);
      adj[v] ~= tuple(u, w);
    }

    bool[int] xora, xorb;
    bool[] visa = new bool[](n);
    bool[] visb = new bool[](n);
    visa[a] = true;
    visa[b] = true;
    visb[b] = true;
    dfs(a, adj, visa, 0, xora);
    dfs(b, adj, visb, 0, xorb);
    bool ans = false;
    foreach (k, v ; xora) {
      if (v in xorb) {
        ans = true;
        break;
      }
    }

//    writeln("-");
//    writeln(adj);
//    writeln(xora);
//    writeln(xorb);

    writeln(ans ? "YES" : "NO");
  }
}

import std;

void dfs(int s, Tuple!(int, int)[][] adj, bool[] vis, int val, ref bool[int] valset)
{
  if (!vis[s]) {
    valset[val] = true;
    vis[s] = true;
  }
  foreach (d ; adj[s]) {
    if (vis[d[0]])
      continue;
    dfs(d[0], adj, vis, val ^ d[1], valset);
  }
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, a, b;
    readf!" %d %d %d "(n, a, b);
    a--;
    b--;
    auto adj = new Tuple!(int, int)[][](n, 0);
    foreach (i ; 0 .. n - 1) {
      int u, v, w;
      readf!" %d %d %d "(u, v, w);
      u--;
      v--;
      adj[u] ~= tuple(v, w);
      adj[v] ~= tuple(u, w);
    }

    bool[int] xora, xorb;
    bool[] visa = new bool[](n);
    bool[] visb = new bool[](n);
    visa[b] = true;
    visb[b] = true;
    dfs(a, adj, visa, 0, xora);
    dfs(b, adj, visb, 0, xorb);
    bool ans = false;
    foreach (k, v ; xora) {
      if (v in xorb) {
        ans = true;
        break;
      }
    }
/*
    writeln("-");
    writeln(adj);
    writeln(xora);
    writeln(xorb);
*/
    writeln(ans ? "YES" : "NO");
  }
}


The only difference between easy and hard versions is constraints.You are given $$$n$$$ segments on the coordinate axis $$$OX$$$. Segments can intersect, lie inside each other and even coincide. The $$$i$$$-th segment is $$$[l_i; r_i]$$$ ($$$l_i \le r_i$$$) and it covers all integer points $$$j$$$ such that $$$l_i \le j \le r_i$$$.The integer point is called bad if it is covered by strictly more than $$$k$$$ segments.Your task is to remove the minimum number of segments so that there are no bad points at all.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 200$$$) — the number of segments and the maximum number of segments by which each integer point can be covered. The next $$$n$$$ lines contain segments. The $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 200$$$) — the endpoints of the $$$i$$$-th segment.

In the first line print one integer $$$m$$$ ($$$0 \le m \le n$$$) — the minimum number of segments you need to remove so that there are no bad points. In the second line print $$$m$$$ distinct integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le n$$$) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.

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

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

    immutable int MAX = 200 + 1;

    auto starts = new int[][] (MAX);
    auto ends = new int[] (n+1);

    foreach (i; 0 .. n) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        starts[le] ~= i+1;
        ends[i+1] = r;
    }

    auto rbt = make!(RedBlackTree!(Tuple!(int, int)));

    int cur = 0;
    int[] ans;
    foreach (p; 0 .. MAX) {
        foreach (e; starts[p]) {
            ++cur;
            rbt.insert(tuple(ends[e], e));
        }

        while (cur > k) {
            ans ~= rbt.back[1];
            rbt.removeBack();
            --cur;
        }

        while (!rbt.empty() && rbt.front[0] == p) {
            rbt.removeFront();
            --cur;
        }
    }

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

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

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

    immutable int MAX = 2 * 10 ^^ 5 + 1;

    auto starts = new int[][] (MAX);
    auto end = new int[] (n+1);

    foreach (i; 0 .. n) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        starts[le] ~= i+1;
        end[i+1] = r;
    }

    alias seg = Tuple!(int, int);
    auto rbt = make!(RedBlackTree!seg);

    int[] ans;
    foreach (p; 0 .. MAX) {
        foreach (e; starts[p]) {
            rbt.insert(seg(end[e], e));
        }

        while (rbt.length > k) {
            ans ~= rbt.back[1];
            rbt.removeBack();
        }

        while (!rbt.empty() && rbt.front[0] == p) {
            rbt.removeFront();
        }
    }

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

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

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

    immutable int MAX = 2 * 10 ^^ 5 + 1;

    auto starts = new int[][] (MAX);
    auto ends = new int[] (n+1);

    foreach (i; 0 .. n) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        starts[le] ~= i+1;
        ends[i+1] = r;
    }

    auto rbt = make!(RedBlackTree!(Tuple!(int, int)));

    int[] ans;
    foreach (p; 0 .. MAX) {
        foreach (e; starts[p]) {
            rbt.insert(tuple(ends[e], e));
        }

        while (rbt.length > k) {
            ans ~= rbt.back[1];
            rbt.removeBack();
        }

        while (!rbt.empty() && rbt.front[0] == p) {
            rbt.removeFront();
        }
    }

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

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

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

    immutable int MAX = 2 * 10 ^^ 5 + 1;

    auto starts = new int[][] (MAX);
    auto end = new int[] (n+1);

    foreach (i; 0 .. n) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        starts[le] ~= i+1;
        end[i+1] = r;
    }

    auto rbt = make!(RedBlackTree!(Tuple!(int, int)));

    int[] ans;
    foreach (p; 0 .. MAX) {
        foreach (e; starts[p]) {
            rbt.insert(tuple(end[e], e));
        }

        while (rbt.length > k) {
            ans ~= rbt.back[1];
            rbt.removeBack();
        }

        while (!rbt.empty() && rbt.front[0] == p) {
            rbt.removeFront();
        }
    }

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

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

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

    immutable int MAX = 2 * 10 ^^ 5 + 1;

    auto starts = new int[][] (MAX);
    auto ends = new int[] (n+1);

    foreach (i; 0 .. n) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        starts[le] ~= i+1;
        ends[i+1] = r;
    }

    auto rbt = make!(RedBlackTree!(Tuple!(int, int)));

    int cur = 0;
    int[] ans;
    foreach (p; 0 .. MAX) {
        foreach (e; starts[p]) {
            ++cur;
            rbt.insert(tuple(ends[e], e));
        }

        while (cur > k) {
            ans ~= rbt.back[1];
            rbt.removeBack();
            --cur;
        }

        while (!rbt.empty() && rbt.front[0] == p) {
            rbt.removeFront();
            --cur;
        }
    }

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


Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties:  the upper half of matrix c (rows with numbers from 1 to x) exactly matches b;  the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?

The first line contains two integers, n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains m integers — the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≤ aij ≤ 1) — the i-th row of the matrix a.

In the single line, print the answer to the problem — the minimum number of rows of matrix b.

NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001

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

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

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

//	Pair
struct Pair(S, T) {
	S x; T y;
	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)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, 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)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int M, N;
int[][] A;

bool check(int m) {
	for (; m < M; m *= 2) {
		foreach (x; 0 .. m) foreach (y; 0 .. N) {
			if (A[x][y] != A[m * 2 - 1 - x][y]) {
				return false;
			}
		}
	}
	return true;
}

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = new int[][](M, N);
		foreach (x; 0 .. M) foreach (y; 0 .. N) {
			A[x][y] = readInt;
		}

		int ans = M + 1;
		for (int m = M; ; m /= 2) {
			if (check(m)) {
				chmin(ans, m);
			}
			if (m % 2 != 0) {
				break;
			}
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}


Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e.  or  (or both).Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the prize graph, respectively. Each of the next m lines contains a pair of integers ui and vi (1  ≤  ui,  vi  ≤  n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges.

If it's impossible to split the graph between Pari and Arya as they expect, print "-1" (without quotes). If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers — the indices of vertices. Note that because of m ≥ 1, vertex cover cannot be empty.

NoteIn the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish).In the second sample, there is no way to satisfy both Pari and Arya.

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

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

		auto c = new int [n];

		void recur (int v, int cur)
		{
			debug {writeln (v, " ", cur);}
			if ((c[v] & cur) == cur)
			{
				return;
			}
			c[v] |= cur;
			foreach (u; a[v])
			{
				recur (u, cur ^ 3);
			}
		}

		foreach (i; 0..n)
		{
			if (c[i] == 0)
			{
				recur (i, 1);
			}
		}

		if (n.iota.any !(x => c[x] == 3))
		{
			writeln (-1);
		}
		else
		{
			foreach (i; 1..3)
			{
				auto ans =
				    n.iota.filter !(x => c[x] == i).array;
				writefln ("%s\n%(%s %)",
				    ans.length, ans.map !(x => x + 1));
			}
		}
	}
}

import std.stdio;

immutable int MAXN = cast(int)5e5;

int N, M;
int[][MAXN] G;
int[MAXN] d;
int[] A, B;
bool correct = 1;

void dfs(int v, int col) {
	d[v] = col;
	foreach(u; G[v]) {
		if (!d[u]) dfs(u, -col);
		else if (d[u] == d[v]) correct = 0;
	}
}

void print(int[] arr) {
	printf("%d\n", arr.length);
	foreach(i; arr) printf("%d ", i);
	printf("\n");
}

void main() {
	readf("%d %d\n", &N, &M);
	for (int i = 0; i < M; ++i) {
		int u, v; readf("%d %d\n", &u, &v);
		G[u] ~= v; G[v] ~= u;
	}
	for (int i = 1; i <= N; ++i) if (!d[i]) dfs(i, 1);
	if (!correct) {
		writef("-1\n"); return;
	}
	for (int i = 1; i <= N; ++i) (d[i] == 1 ? A : B) ~= i;
	print(A); print(B);
}

import std.stdio;
import std.container: DList;

int opposite_color(int c) {
    if (c == 1) return 2;
    return 1;
}

void main() {
    int n, m;
    readf("%d %d\n", &n, &m);
    int[][] graph;
    int[] colors;
    graph.length = n;
    colors.length = n;
    int first_colors = 0;
    int second_colors = 0;

    for(int i = 0; i < m; ++i) {
        int u, v;
        readf("%d %d\n", &u, &v);
        --u;
        --v;
        graph[u] ~= v;
        graph[v] ~= u;
    }
    bool possible = true;
outerLoop:
    foreach (int i, int color; colors) {
        if (color == 0  && graph[i].length != 0) {
            auto queue = DList!int();
            queue.insertBack(i);
            while (!queue.empty()) {
                int u = queue.front;
                queue.removeFront(1);
                foreach (int j, int v; graph[u]) {
                    if (colors[v] != 0 && colors[v] == colors[u]) {
                        possible = false;
                        break outerLoop;
                    } else if (colors[v] == 0) {
                        int opColor = opposite_color(colors[u]);
                        colors[v] = opColor;
                        if (opColor == 1) first_colors++;
                        else second_colors++;
                        queue.insertBack(v);
                    }
                }
            }
        }
    }

    if (possible) {
        writeln(first_colors);
        foreach(int i, int c; colors) {
            if(c == 1) {
                write(i+1, " ");
            }
        }
        writeln();
        writeln(second_colors);
        foreach(int i, int c; colors) {
            if(c == 2) {
                write(i+1, " ");
            }
        }
        writeln();
    } else {
        writeln(-1);
    }
}


There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i < n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.

The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.

Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl.  Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.

NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.

import std.stdio : File, writeln, writefln;
import std.array;
import std.range;
import std.algorithm : min;

int n;
int[] arr;

void swap(T)(ref T a, ref T b){
	T tmp = a;
	a = b;
	b = tmp;
}

File ifp;
File ofp;

void main(){
	ifp = File("input.txt", "r");
	ofp = File("output.txt", "w");

	char[] l = ['B', 'G'];

	int n = next!int();
	int m = next!int();

	auto str = cycle(l[]).take(min(n, m)*2).array;

	if(n>m){
		ofp.write = str;
		ofp.write = repeat('B').take(n-m).array;
	}else{
		ofp.write = repeat('G').take(m-n).array;
		ofp.write = str;
	}

	ofp.writeln;
}

import std.stdio : readln, chomp;
import std.conv : to;
import std.string : split;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

//	string str = readln;
	string str = ifp.readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
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);

string b="B",g="G";
void main(){
    stdin=File("input.txt","r");
    stdout=File("output.txt","w");
    int n,m;
    readf!"%d %d"(n,m);
    readln;
    if(m<n){
        swap(b,g);
        swap(n,m);
    }
    writeln((g~b).replicate(n)~g.replicate(m-n));
}

module cf_253A;

import std.stdio, std.algorithm;

void main() {
    File fin = File("input.txt", "r");
    File fout = File("output.txt", "w");
    int n, m;

    fin.readf("%d %d", &n, &m);

    string pair = (n > m)? "BG": "GB";
    for (int i = min(n, m); i > 0; --i) {
        fout.writef("%s", pair);
    }
    for (int i = n - min(n, m); i > 0; --i) {
        fout.writef("B");
    }
    for (int i = m - min(n, m); i > 0; --i) {
        fout.writef("G");
    }
    fout.writeln();
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
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);

string b="B",g="G";
void main(){
    int n,m;
    scanf("%d %d",&n,&m);
    if(m<n){
        swap(b,g);
        swap(n,m);
    }
    writeln((g~b).replicate(n)~g.replicate(m-n));
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
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);

string b="B",g="G";
void main(){
    stdin=File("input.txt","r");
    stdout=File("output.txt","w");
    int n,m;
    scanf("%d %d",&n,&m);
    if(m<n){
        swap(b,g);
        swap(n,m);
    }
    writeln((g~b).replicate(n)~g.replicate(m-n));
}

module cf_253A;

import std.stdio, std.algorithm;

void main() {
    int n, m;

    readf("%d %d", &n, &m);

    string pair = (n > m)? "BG": "GB";
    for (int i = min(n, m); i > 0; --i) {
        writef("%s", pair);
    }
    for (int i = n - min(n, m); i > 0; --i) {
        writef("B");
    }
    for (int i = m - min(n, m); i > 0; --i) {
        writef("G");
    }
    writeln();
}

module cf_253A;

import std.stdio, std.algorithm;

void main() {
    int n, m;

    readf("%d %d", &n, &m);

    string pair = (n > m)? "BG": "GB";
    for (int i = min(n, m); i > 0; --i) {
        writef("%s", pair);
    }
    for (int i = n - min(n, m); i > 0; --i) {
        writef("B");
    }
    for (int i = m - min(n, m); i > 0; --i) {
        writef("G");
    }
}


There are $$$n$$$ water tanks in a row, $$$i$$$-th of them contains $$$a_i$$$ liters of water. The tanks are numbered from $$$1$$$ to $$$n$$$ from left to right.You can perform the following operation: choose some subsegment $$$[l, r]$$$ ($$$1\le l \le r \le n$$$), and redistribute water in tanks $$$l, l+1, \dots, r$$$ evenly. In other words, replace each of $$$a_l, a_{l+1}, \dots, a_r$$$ by $$$\frac{a_l + a_{l+1} + \dots + a_r}{r-l+1}$$$. For example, if for volumes $$$[1, 3, 6, 7]$$$ you choose $$$l = 2, r = 3$$$, new volumes of water will be $$$[1, 4.5, 4.5, 7]$$$. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence $$$a$$$ is lexicographically smaller than a sequence $$$b$$$ of the same length if and only if the following holds: in the first (leftmost) position where $$$a$$$ and $$$b$$$ differ, the sequence $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the number of water tanks. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended.

Print the lexicographically smallest sequence you can get. In the $$$i$$$-th line print the final volume of water in the $$$i$$$-th tank. Your answer is considered correct if the absolute or relative error of each $$$a_i$$$ does not exceed $$$10^{-9}$$$. Formally, let your answer be $$$a_1, a_2, \dots, a_n$$$, and the jury's answer be $$$b_1, b_2, \dots, b_n$$$. Your answer is accepted if and only if $$$\frac{|a_i - b_i|}{\max{(1, |b_i|)}} \le 10^{-9}$$$ for each $$$i$$$.

NoteIn the first sample, you can get the sequence by applying the operation for subsegment $$$[1, 3]$$$.In the second sample, you can't get any lexicographically smaller sequence.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto s = [0L];
		s.reserve (n + 1);
		foreach (ref c; a)
		{
			s ~= s.back + c;
		}

		auto p = [0, 1];
		foreach (i; 2..n + 1)
		{
			while (p.length > 1 &&
			    (s[i] - s[p[$ - 1]]) * 1L * (i - p[$ - 2]) <=
			    (s[i] - s[p[$ - 2]]) * 1L * (i - p[$ - 1]))
			{
				p.popBack ();
				p.assumeSafeAppend ();
			}
			p ~= i;
		}

		auto answer = new real [n];
		foreach (j; 1..p.length)
		{
			real cur = s[p[j]] - s[p[j - 1]];
			cur /= p[j] - p[j - 1];
			foreach (i; p[j - 1]..p[j])
			{
				answer[i] = cur;
			}
		}
		foreach (const ref c; answer)
		{
			writefln ("%.10f", c);
		}
	}
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	int n = rint;
	S[] as = rlong(n).map!(v => S(v, 1)).array;

	auto sta = new Stack!S;
	foreach(a; as){
		while(sta.length > 0 && sta.peek.gt(a)){
			S b = sta.pop;
			a = S(b.sum + a.sum, b.count + a.count);
		}
		sta.push(a);
	}

	S[] ans = sta.array;
	foreach(an; ans){
		foreach(i; 0 .. an.count) writefln("%10.10f", an.sum.to!real / an.count.to!real);
	}

}

struct S{
	long sum;
	int count;
	bool lt(S b){ return sum * b.count < b.sum * count; }
	bool gt(S b){ return sum * b.count > b.sum * count; }
	bool le(S b){ return !gt(b); }
	bool ge(S b){ return !lt(b); }
}

// ----- スタック -----
class Stack(T){
	private T[] xs;
	private uint j; // j : 次に書き込む位置
	this(){	}
	this(T[] xs){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j; }
	bool isEmpty(){ return j == 0; }
	void push(T x){
		while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1;
		xs[j ++] = x;
	}
	T pop(){ assert(j > 0); return xs[-- j]; }
	T peek(){ assert(j > 0); return xs[j - 1]; }
	T opIndex(uint li){ assert(j > 0 && j - 1 >= li); return xs[j - 1 - li]; }
	static Stack!T opCall(){ return new Stack!T; }
	static Stack!T opCall(T[] xs){ return new Stack!T(xs); }
	T[] array(){ return xs[0 .. j]; }
	override string toString(){ return array.to!string; }
}

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

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

      int len;
      auto numers = new long[N];
      auto denoms = new long[N];
      foreach_reverse (i; 0 .. N) {
        long p = A[i], q = 1;
        for (; len >= 1 && numers[len - 1] * q <= p * denoms[len - 1]; ) {
          p += numers[len - 1];
          q += denoms[len - 1];
          --len;
        }
        numers[len] = p;
        denoms[len] = q;
        ++len;
      }
      foreach_reverse (j; 0 .. len) {
        const ans = cast(real)(numers[j]) / denoms[j];
        foreach (_; 0 .. denoms[j]) {
          writefln("%.10f", ans);
        }
      }
    }
  } catch (EOFException e) {
  }
}


A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence (or, shortly, an RBS) 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)");  bracket sequences ")(", "(" and ")" are not. There was an RBS. Some brackets have been replaced with question marks. Is it true that there is a unique way to replace question marks with brackets, so that the resulting sequence is an RBS?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of testcases. The only line of each testcase contains an RBS with some brackets replaced with question marks. Each character is either '(', ')' or '?'. At least one RBS can be recovered from the given sequence. The total length of the sequences over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print "YES" if the way to replace question marks with brackets, so that the resulting sequence is an RBS, is unique. If there is more than one way, then print "NO".

NoteIn the first testcase, the only possible original RBS is "(())".In the second testcase, there are multiple ways to recover an RBS.In the third and the fourth testcases, the only possible original RBS is "()".In the fifth testcase, the original RBS can be either "((()()))" or "(())()()".

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

void solve() {

    bool rbs(char[] s) {
        int n = cast(int)s.length;
        int c = 0;
        for (int i = 0; i < n; i++) {
            if (s[i] == '(') c++;
            else if (s[i] == ')') c--;
            else assert(false);
            if (c < 0) return false;
        }
        return c == 0;
    }

    bool check(string s) {
        int n = cast(int)s.length;
        if (n % 2 > 0) {
            return false;
        }
        int[] count = new int[3];
        for (int i = 0; i < n; i++) {
            int j = -1;
            if (s[i] == '(') j = 0;
            else if (s[i] == ')') j = 1;
            else {
                assert(s[i] == '?');
                j = 2;
            }
            count[j]++;
        }
        if (count[0] > n/2 || count[1] > n/2) return false;
        int to_open = n/2 - count[0];
        int to_close = n/2 - count[1];
        assert(to_open + to_close == count[2]);

        char[] t = new char[n];
        int lim_l = 0, lim_r = n;
        for (int i = 0, c = 0; i < n; i++) {
            if (s[i] == '?') {
                if (c < to_open) {
                    c++;
                    t[i] = '(';
                    if (c == to_open) {
                        lim_l = i;
                    }
                } else {
                    lim_r = min(lim_r, i);
                    t[i] = ')';
                }
            } else {
                t[i] = s[i];
            }
        }

        if (! rbs(t)) return false;
        if (to_open == 0 || to_close == 0) return true;

        // swap innermost
        swap(t[lim_l], t[lim_r]);
        return !rbs(t); // if swapped is rbs, then there's at least 2 ways(original t & swapped t)
    }
    auto s = readln.chomp;
    writeln(check(s) ? "YES" : "NO");
}

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


The grasshopper is located on the numeric axis at the point with coordinate $$$x_0$$$.Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $$$x$$$ with a distance $$$d$$$ to the left moves the grasshopper to a point with a coordinate $$$x - d$$$, while jumping to the right moves him to a point with a coordinate $$$x + d$$$.The grasshopper is very fond of positive integers, so for each integer $$$i$$$ starting with $$$1$$$ the following holds: exactly $$$i$$$ minutes after the start he makes a jump with a distance of exactly $$$i$$$. So, in the first minutes he jumps by $$$1$$$, then by $$$2$$$, and so on.The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.For example, if after $$$18$$$ consecutive jumps he arrives at the point with a coordinate $$$7$$$, he will jump by a distance of $$$19$$$ to the right, since $$$7$$$ is an odd number, and will end up at a point $$$7 + 19 = 26$$$. Since $$$26$$$ is an even number, the next jump the grasshopper will make to the left by a distance of $$$20$$$, and it will move him to the point $$$26 - 20 = 6$$$.Find exactly which point the grasshopper will be at after exactly $$$n$$$ jumps.

The first line of input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$x_0$$$ ($$$-10^{14} \leq x_0 \leq 10^{14}$$$) and $$$n$$$ ($$$0 \leq n \leq 10^{14}$$$) — the coordinate of the grasshopper's initial position and the number of jumps.

Print exactly $$$t$$$ lines. On the $$$i$$$-th line print one integer — the answer to the $$$i$$$-th test case — the coordinate of the point the grasshopper will be at after making $$$n$$$ jumps from the point $$$x_0$$$.

NoteThe first two test cases in the example correspond to the first two jumps from the point $$$x_0 = 0$$$. Since $$$0$$$ is an even number, the first jump of length $$$1$$$ is made to the left, and the grasshopper ends up at the point $$$0 - 1 = -1$$$.Then, since $$$-1$$$ is an odd number, a jump of length $$$2$$$ is made to the right, bringing the grasshopper to the point with coordinate $$$-1 + 2 = 1$$$.

// Author: Ivan Kazmenko (gassa@mail.ru)
module solution;
import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

long pos (long x, long lo, long hi)
{
	foreach (me; lo..hi)
	{
		if (x & 1)
		{
			x += me + 1;
		}
		else
		{
			x -= me + 1;
		}
	}
	return x;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		long x0, n;
		readf !(" %s %s") (x0, n);
		auto x4 = pos (x0, 0, 4);
		auto fulls = n / 4;
		auto y = x0 + (x4 - x0) * fulls;
		auto res = pos (y, fulls * 4, n);
		writeln (res);
	}
}


You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!You have $$$n$$$ tickets to sell. The price of the $$$i$$$-th ticket is $$$p_i$$$. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them to the order you chose:  The $$$x\%$$$ of the price of each the $$$a$$$-th sold ticket ($$$a$$$-th, $$$2a$$$-th, $$$3a$$$-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources.  The $$$y\%$$$ of the price of each the $$$b$$$-th sold ticket ($$$b$$$-th, $$$2b$$$-th, $$$3b$$$-th and so on) in the order you chose is aimed for pollution abatement. If the ticket is in both programs then the $$$(x + y) \%$$$ are used for environmental activities. Also, it's known that all prices are multiples of $$$100$$$, so there is no need in any rounding.For example, if you'd like to sell tickets with prices $$$[400, 100, 300, 200]$$$ and the cinema pays $$$10\%$$$ of each $$$2$$$-nd sold ticket and $$$20\%$$$ of each $$$3$$$-rd sold ticket, then arranging them in order $$$[100, 200, 300, 400]$$$ will lead to contribution equal to $$$100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120$$$. But arranging them in order $$$[100, 300, 400, 200]$$$ will lead to $$$100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130$$$.Nature can't wait, so you decided to change the order of tickets in such a way, so that the total contribution to programs will reach at least $$$k$$$ in minimum number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least $$$k$$$.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of independent queries. Each query consists of $$$5$$$ lines. The first line of each query contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of tickets. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$100 \le p_i \le 10^9$$$, $$$p_i \bmod 100 = 0$$$) — the corresponding prices of tickets. The third line contains two integers $$$x$$$ and $$$a$$$ ($$$1 \le x \le 100$$$, $$$x + y \le 100$$$, $$$1 \le a \le n$$$) — the parameters of the first program. The fourth line contains two integers $$$y$$$ and $$$b$$$ ($$$1 \le y \le 100$$$, $$$x + y \le 100$$$, $$$1 \le b \le n$$$) — the parameters of the second program. The fifth line contains single integer $$$k$$$ ($$$1 \le k \le 10^{14}$$$) — the required total contribution. It's guaranteed that the total number of tickets per test doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$q$$$ integers — one per query.  For each query, print the minimum number of tickets you need to sell to make the total ecological contribution of at least $$$k$$$ if you can sell tickets in any order. If the total contribution can not be achieved selling all the tickets, print $$$-1$$$.

NoteIn the first query the total contribution is equal to $$$50 + 49 = 99 < 100$$$, so it's impossible to gather enough money.In the second query you can rearrange tickets in a following way: $$$[100, 100, 200, 200, 100, 200, 100, 100]$$$ and the total contribution from the first $$$6$$$ tickets is equal to $$$100 \cdot 0 + 100 \cdot 0.1 + 200 \cdot 0.15 + 200 \cdot 0.1 + 100 \cdot 0 + 200 \cdot 0.25 = 10 + 30 + 20 + 50 = 110$$$.In the third query the full price of each ticket goes to the environmental activities.In the fourth query you can rearrange tickets as $$$[100, 200, 100, 100, 100]$$$ and the total contribution from the first $$$4$$$ tickets is $$$100 \cdot 0 + 200 \cdot 0.31 + 100 \cdot 0 + 100 \cdot 0.31 = 62 + 31 = 93$$$.

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

void main ()
{
	int tests;
	readf (" %s", &tests);
	foreach (test; 0..tests)
	{
		int n;
		readf (" %s", &n);
		readln;
		auto p = readln.splitter.map !(to !(int)).array;
		sort (p);
		reverse (p);
		p[] /= 100;
		int x, a;
		readf (" %s %s", &x, &a);
		int y, b;
		readf (" %s %s", &y, &b);
		long k;
		readf (" %s", &k);

		int solve ()
		{
			int lo = 1;
			int hi = n + 1;
			while (lo < hi)
			{
				int me = (lo + hi) / 2;
				auto q = p;
				long total = 0;
				for (int i = 1; i <= me; i++)
				{
					if (i % a == 0 && i % b == 0)
					{
						total += q.front * (x + y);
						q.popFront ();
					}
				}
				for (int i = 1; i <= me; i++)
				{
					if (i % a == 0 && i % b != 0)
					{
						total += q.front * (x + 0);
						q.popFront ();
					}
				}
				for (int i = 1; i <= me; i++)
				{
					if (i % a != 0 && i % b == 0)
					{
						total += q.front * (0 + y);
						q.popFront ();
					}
				}
				if (total >= k)
				{
					hi = me;
				}
				else
				{
					lo = me + 1;
				}
			}
			return lo;
		}

		auto res = solve ();
		swap (x, y);
		swap (a, b);
		res = min (res, solve ());
		if (res == n + 1)
		{
			res = -1;
		}
		writeln (res);
	}
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, 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 numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        auto P = new long[N];
        foreach (i; 0 .. N) {
          P[i] = readLong();
        }
        const X = readLong();
        const A = readInt();
        const Y = readLong();
        const B = readInt();
        const K = readLong();

        sort(P);
        reverse(P);

        bool check(int l) {
          auto zs = new long[l];
          foreach (i; 0 .. l) {
            if ((i + 1) % A == 0) {
              zs[i] += X;
            }
            if ((i + 1) % B == 0) {
              zs[i] += Y;
            }
          }
          sort(zs);
          reverse(zs);
          long sum;
          foreach (i; 0 .. l) {
            sum += P[i] / 100 * zs[i];
          }
          return (sum >= K);
        }

        int lo = -1, hi = N + 1;
        for (; lo + 1 < hi; ) {
          const mid = (lo + hi) / 2;
          check(mid) ? (hi = mid) : (lo = mid);
        }
        writeln((hi <= N) ? hi : -1);
      }
    }
  } catch (EOFException e) {
  }
}


Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom.A bar of chocolate can be presented as an n × n table, where each cell represents one piece of chocolate. The columns of the table are numbered from 1 to n from left to right and the rows are numbered from top to bottom. Let's call the anti-diagonal to be a diagonal that goes the lower left corner to the upper right corner of the table. First Andrewid eats all the pieces lying below the anti-diagonal. Then he performs the following q actions with the remaining triangular part: first, he chooses a piece on the anti-diagonal and either direction 'up' or 'left', and then he begins to eat all the pieces starting from the selected cell, moving in the selected direction until he reaches the already eaten piece or chocolate bar edge.After each action, he wants to know how many pieces he ate as a result of this action.

The first line contains integers n (1 ≤ n ≤ 109) and q (1 ≤ q ≤ 2·105) — the size of the chocolate bar and the number of actions. Next q lines contain the descriptions of the actions: the i-th of them contains numbers xi and yi (1 ≤ xi, yi ≤ n, xi + yi = n + 1) — the numbers of the column and row of the chosen cell and the character that represents the direction (L — left, U — up).

Print q lines, the i-th of them should contain the number of eaten pieces as a result of the i-th action.

NotePictures to the sample tests:The pieces that were eaten in the same action are painted the same color. The pieces lying on the anti-diagonal contain the numbers of the action as a result of which these pieces were eaten.In the second sample test the Andrewid tries to start eating chocolate for the second time during his fifth action, starting from the cell at the intersection of the 10-th column and the 1-st row, but this cell is already empty, so he does not eat anything.

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

alias Piece = Tuple !(int, q{a}, int, q{b}, int, q{l}, int, q{u});

void main ()
{
	int n;
	int q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		auto s = redBlackTree !(Piece) ();
		s.insert (Piece (1, n, 0, 0));
		foreach (k; 0..q)
		{
			int x;
			int y;
			char t;
			readf (" %s %s %s", &x, &y, &t);
			auto cur = Piece (x, n + 1, 0, 0);
			auto r = s.lowerBound (cur);
			auto prev = r.empty ? Piece.init : r.back;
			int c = x;
			with (prev)
			{
				if (c < a || b < c)
				{
					writeln (0);
				}
				else if (t == 'L')
				{
					s.removeKey (prev);
					writeln (x - l);
					if (a <= c - 1)
					{
						s.insert (Piece (a, c - 1,
						    l, y));
					}
					if (c + 1 <= b)
					{
						s.insert (Piece (c + 1, b,
						    l, u));
					}
				}
				else if (t == 'U')
				{
					s.removeKey (prev);
					writeln (y - u);
					if (a <= c - 1)
					{
						s.insert (Piece (a, c - 1,
						    l, u));
					}
					if (c + 1 <= b)
					{
						s.insert (Piece (c + 1, b,
						    x, u));
					}
				}
				else
				{
					assert (false);
				}
			}
			debug {writeln (s[].map !(text).join ("\n"));}
		}
	}
}

import std.container, std.range, std.stdio, std.typecons;

alias Piece = Tuple !(int, q{a}, int, q{b}, int, q{l}, int, q{u});

void main ()
{
	int n, q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		auto s = redBlackTree !(Piece) ();
		s.insert (Piece (1, n, 0, 0));
		foreach (k; 0..q)
		{
			int x, y;
			char t;
			readf (" %s %s %s", &x, &y, &t);
			auto cur = Piece (x, n + 1, 0, 0);
			auto r = s.lowerBound (cur);
			auto prev = r.empty ? Piece.init : r.back;
			int c = x;
			with (prev)
			{
				if (c < a || b < c)
				{
					writeln (0);
				}
				else if (t == 'L')
				{
					s.removeKey (prev);
					writeln (x - l);
					if (a <= c - 1)
					{
						s.insert (Piece (a, c - 1,
						    l, y));
					}
					if (c + 1 <= b)
					{
						s.insert (Piece (c + 1, b,
						    l, u));
					}
				}
				else if (t == 'U')
				{
					s.removeKey (prev);
					writeln (y - u);
					if (a <= c - 1)
					{
						s.insert (Piece (a, c - 1,
						    l, u));
					}
					if (c + 1 <= b)
					{
						s.insert (Piece (c + 1, b,
						    x, u));
					}
				}
				else
				{
					assert (false);
				}
			}
		}
	}
}


Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task.The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array   $$$[1, 1, 1]$$$ is $$$1$$$;  $$$[5, 7]$$$ is $$$2$$$, as it could be split into blocks $$$[5]$$$ and $$$[7]$$$;  $$$[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$$$ is 3, as it could be split into blocks $$$[1]$$$, $$$[7, 7, 7, 7, 7, 7, 7]$$$, and $$$[9, 9, 9, 9, 9, 9, 9, 9, 9]$$$. You are given an array $$$a$$$ of length $$$n$$$. There are $$$m$$$ queries of two integers $$$i$$$, $$$x$$$. A query $$$i$$$, $$$x$$$ means that from now on the $$$i$$$-th element of the array $$$a$$$ is equal to $$$x$$$.After each query print the sum of awesomeness values among all subsegments of array $$$a$$$. In other words, after each query you need to calculate $$$$$$\sum\limits_{l = 1}^n \sum\limits_{r = l}^n g(l, r),$$$$$$ where $$$g(l, r)$$$ is the awesomeness of the array $$$b = [a_l, a_{l + 1}, \ldots, a_r]$$$.

In the first line you are given with two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. In the next $$$m$$$ lines you are given the descriptions of queries. Each line contains two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq x \leq 10^9$$$).

Print the answer to each query on a new line.

import std.stdio;
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; }

void main() {
    int N, M; readf("%d %d\n", &N, &M);
    auto A = readarray!int;
    long ans = 0;
    for (long i = 0; i <= N - 1; i++) {
        ans += (i + N - 1) * (N - i) / 2L - i * (N - i) + (N - i);
    }

    for (int i = 0; i + 1 < N; i++) {
        if (A[i] == A[i + 1]) {
            long l = i + 1;
            long r = N - i - 1;
            ans -= l * r;
        }
    }

    foreach (q; 0 .. M) {
        int i, x; readf("%d %d\n", &i, &x);
        i--;
        if (i - 1 >= 0) {
            if (A[i - 1] != A[i] && A[i - 1] == x) {
                long lc = i;
                long rc = N - i;
                ans -= lc * rc;
            }
            if (A[i - 1] == A[i] && A[i - 1] != x) {
                long lc = i;
                long rc = N - i;
                ans += lc * rc;
            }
        }
        if (i + 1 < N) {
            if (A[i + 1] != A[i] && A[i + 1] == x) {
                long lc = i + 1;
                long rc = N - i - 1;
                ans -= lc * rc;
            }
            if (A[i + 1] == A[i] && A[i + 1] != x) {
                long lc = i + 1;
                long rc = N - i - 1;
                ans += lc * rc;
            }
        }
        A[i] = x;
        writeln(ans);
    }
}

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

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto A = readln.chomp.split(" ").map!(to!long).array;

    long f(long N) {
        long x = N * (N + 1) / 2;
        long y = N * (N + 1) * (2 * N + 1) / 6;
        return N * x + x - y;
    }

    long T = f(N);
    long D = 0;
    for (int i = 0; i + 1 < N; i++) {
        if (A[i] == A[i + 1]) {
            D += cast(long)(i + 1) * cast(long)(N - (i + 1));
        }
    }
    long Y = T - D; // initial

    long prod(long i) {
        return i * (cast(long)N - i);
    }
    long diff(long x, long y) {
        if (x == y) return 0L;
        return 1L;
    }

    for (int q = 0; q < M; q++) {
        long d = 0;
        int I, X; scanf("%d %d\n", &I, &X);

        if (I - 2 >= 0) {
            d += (diff(A[I-2], X) - diff(A[I-2], A[I-1])) * prod(I-1);
        }
        if (I < N) {
            d += (diff(X, A[I]) - diff(A[I-1], A[I])) * prod(I);
        }

        Y += d;
        writeln(Y);

        A[I - 1] = X;
    }
}

import std.stdio;
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; }

void main() {
    int N, M; readf("%d %d\n", &N, &M);
    auto A = readarray!int;
    long ans = 0;
    for (long i = 0; i <= N - 1; i++) {
        ans += (i + N - 1) * (N - i) / 2L - i * (N - i) + (N - i);
    }

    for (int i = 0; i + 1 < N; i++) {
        if (A[i] == A[i + 1]) {
            long l = i + 1;
            long r = N - i - 1;
            ans -= l * r;
        }
    }

    foreach (q; 0 .. M) {
        int i, x; readf("%d %d\n", &i, &x);
        i--;
        if (A[i] == x) continue;
        if (i - 1 >= 0) {
            if (A[i - 1] != A[i] && A[i - 1] == x) {
                long lc = i;
                long rc = N - i;
                ans -= lc * rc;
            }
            if (A[i - 1] == A[i] && A[i - 1] != x) {
                long lc = i;
                long rc = N - i;
                ans += lc * rc;
            }
        }
        if (i + 1 < N) {
            if (A[i + 1] != A[i] && A[i + 1] == x) {
                long lc = i + 1;
                long rc = N - i - 1;
                ans -= lc * rc;
            }
            if (A[i + 1] == A[i] && A[i + 1] != x) {
                long lc = i + 1;
                long rc = N - i - 1;
                ans += lc * rc;
            }
        }
        A[i] = x;
        writeln(ans);
    }
}

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

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto A = readln.chomp.split(" ").map!(to!long).array;

    long f(long N) {
        long x = N * (N + 1) / 2;
        long y = N * (N + 1) * (2 * N + 1) / 6;
        return N * x + x - y;
    }

    long T = f(N);
    long D = 0;
    for (int i = 0; i + 1 < N; i++) {
        if (A[i] == A[i + 1]) {
            D += cast(long)(i + 1) * cast(long)(N - (i + 1));
        }
    }
    long Y = T - D; // initial

    long prod(long i) {
        return i * (N - i);
    }
    long diff(long x, long y) {
        if (x == y) return 0;
        return 1;
    }

    for (int q = 0; q < M; q++) {
        long d = 0;
        int I, X; scanf("%d %d\n", &I, &X);
        if (A[I - 1] == X) continue; // nothing changed

        if (I - 2 >= 0) {
            d += (diff(A[I-2], X) - diff(A[I-2], A[I-1])) * prod(I-1);
        }
        if (I < N) {
            d += (diff(X, A[I]) - diff(A[I-1], A[I])) * prod(I);
        }

        Y += d;
        writeln(Y);

        A[I - 1] = X;
    }
}

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

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto A = readln.chomp.split(" ").map!(to!long).array;

    long f(long N) {
        long x = N * (N + 1) / 2;
        long y = N * (N + 1) * (2 * N + 1) / 6;
        return N * x + x - y;
    }

    long T = f(N);
    long D = 0;
    for (int i = 0; i + 1 < N; i++) {
        if (A[i] == A[i + 1]) {
            D += (i + 1) * (N - (i + 1));
        }
    }
    long Y = T - D; // initial

    long prod(long i) {
        return i * (N - i);
    }
    long diff(long x, long y) {
        if (x == y) return 0;
        return 1;
    }

    for (int q = 0; q < M; q++) {
        long d = 0;
        int I, X; scanf("%d %d\n", &I, &X);
        if (A[I - 1] == X) continue; // nothing changed

        if (I - 2 >= 0) {
            d += (diff(A[I-2], X) - diff(A[I-2], A[I-1])) * prod(I-1);
        }
        if (I < N) {
            d += (diff(X, A[I]) - diff(A[I-1], A[I])) * prod(I);
        }

        Y += d;
        writeln(Y);

        A[I - 1] = X;
    }
}


Cirno gave AquaMoon a chessboard of size $$$1 \times n$$$. Its cells are numbered with integers from $$$1$$$ to $$$n$$$ from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied.In each operation, AquaMoon can choose a cell $$$i$$$ with a pawn, and do either of the following (if possible):   Move pawn from it to the $$$(i+2)$$$-th cell, if $$$i+2 \leq n$$$ and the $$$(i+1)$$$-th cell is occupied and the $$$(i+2)$$$-th cell is unoccupied.  Move pawn from it to the $$$(i-2)$$$-th cell, if $$$i-2 \geq 1$$$ and the $$$(i-1)$$$-th cell is occupied and the $$$(i-2)$$$-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo $$$998\,244\,353$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the size of the chessboard. The second line contains a string of $$$n$$$ characters, consists of characters "0" and "1". If the $$$i$$$-th character is "1", the $$$i$$$-th cell is initially occupied; otherwise, the $$$i$$$-th cell is initially unoccupied. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo $$$998\,244\,353$$$.

NoteIn the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.

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

immutable long mod   = 998_244_353;
immutable int limit =     100_005;

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

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

auto fact = new long [limit];

long choose (int n, int k)
{
	auto res = fact[n];
	res = (res * 1L * invMod (fact[n - k])) % mod;
	res = (res * 1L * invMod (fact[k])) % mod;
	return res;
}

void main ()
{
	fact[0] = 1;
	foreach (i; 1..limit)
	{
		fact[i] = (fact[i - 1] * 1L * i) % mod;
	}

	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.strip.map !(q{a == '1'}).array;
		int zeroes = 0;
		int pairs = 0;
		for (int i = 0; i < n; i++)
		{
			if (!a[i])
			{
				zeroes += 1;
			}
			else if (i + 1 < n && a[i + 1])
			{
				pairs += 1;
				i += 1;
			}
		}
		writeln (choose (zeroes + pairs, pairs));
	}
}

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

immutable int mod   = 998_244_353;
immutable int limit =     100_005;

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

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

auto fact = new int [limit];

int choose (int n, int k)
{
	auto res = fact[n];
	res = (res * 1L * invMod (fact[n - k])) % mod;
	res = (res * 1L * invMod (fact[k])) % mod;
	return res;
}

void main ()
{
	fact[0] = 1;
	foreach (i; 1..limit)
	{
		fact[i] = (fact[i - 1] * 1L * i) % mod;
	}

	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.strip.map !(q{a == '1'}).array;
		int zeroes = 0;
		int pairs = 0;
		for (int i = 0; i < n; i++)
		{
			if (!a[i])
			{
				zeroes += 1;
			}
			else if (i + 1 < n && a[i + 1])
			{
				pairs += 1;
				i += 1;
			}
		}
		writeln (choose (zeroes + pairs, pairs));
	}
}


Vasya has a tree consisting of $$$n$$$ vertices with root in vertex $$$1$$$. At first all vertices has $$$0$$$ written on it.Let $$$d(i, j)$$$ be the distance between vertices $$$i$$$ and $$$j$$$, i.e. number of edges in the shortest path from $$$i$$$ to $$$j$$$. Also, let's denote $$$k$$$-subtree of vertex $$$x$$$ — set of vertices $$$y$$$ such that next two conditions are met:   $$$x$$$ is the ancestor of $$$y$$$ (each vertex is the ancestor of itself);  $$$d(x, y) \le k$$$. Vasya needs you to process $$$m$$$ queries. The $$$i$$$-th query is a triple $$$v_i$$$, $$$d_i$$$ and $$$x_i$$$. For each query Vasya adds value $$$x_i$$$ to each vertex from $$$d_i$$$-subtree of $$$v_i$$$.Report to Vasya all values, written on vertices of the tree after processing all queries.

The first line contains single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — number of vertices in the tree. Each of next $$$n - 1$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) — edge between vertices $$$x$$$ and $$$y$$$. It is guarantied that given graph is a tree. Next line contains single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$) — number of queries. Each of next $$$m$$$ lines contains three integers $$$v_i$$$, $$$d_i$$$, $$$x_i$$$ ($$$1 \le v_i \le n$$$, $$$0 \le d_i \le 10^9$$$, $$$1 \le x_i \le 10^9$$$) — description of the $$$i$$$-th query.

Print $$$n$$$ integers. The $$$i$$$-th integers is the value, written in the $$$i$$$-th vertex after processing all queries.

NoteIn the first exapmle initial values in vertices are $$$0, 0, 0, 0, 0$$$. After the first query values will be equal to $$$1, 1, 1, 0, 0$$$. After the second query values will be equal to $$$1, 11, 1, 0, 0$$$. After the third query values will be equal to $$$1, 11, 1, 100, 0$$$.

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

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

    auto g = new int[][] (n+1);

    foreach (_; 0 .. n-1) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

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

    int m;
    readf("%s", &m);
    readln;

    struct q { int d, x; }

    auto qs = new q[][] (n+1);
    while (m--) {
        int v, d, x;
        readf("%s %s %s", &v, &d, &x);
        readln;

        qs[v] ~= q(d, x);
    }

    auto depth = new int[] (n+1);

    void dfs1(int v, int fr, int curd) {
        depth[v] = curd;
        foreach (u; g[v]) {
            if (u == fr) { continue; }
            dfs1(u, v, curd+1);
        }
    }

    dfs1(1, 0, 1);

    auto score = new long[] (n+2);
    auto ans = new long[] (n+1);

    void dfs2(int v, int fr) {
        foreach (cq; qs[v]) {
            score[depth[v]] += cq.x;
            score[min(n+1, depth[v] + cq.d + 1)] -= cq.x;
        }

        score[depth[v]] += score[depth[v]-1];

        ans[v] = score[depth[v]];

        foreach (u; g[v]) {
            if (u == fr) { continue; }
            dfs2(u, v);
        }

        score[depth[v]] -= score[depth[v]-1];

        foreach (cq; qs[v]) {
            score[depth[v]] -= cq.x;
            score[min(n+1, depth[v] + cq.d + 1)] += cq.x;
        }
    }

    dfs2(1, 0);

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


According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.  However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.Write a program that models the behavior of Ankh-Morpork residents.

The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks. The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

NoteIn the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.

import std.stdio;

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

int main(string[] args)
{
    auto n = read!int;
    bool a[100_001];
    a[] = false;
    int curr = n;

    for (int i = 0; i < n; i++)
    {
        auto q = read!int;
        a[q] = true;
        if (q == curr)
        {
            while (a[curr])
            {
                write(curr, " ");
                curr--;
            }
        }
        writeln;
    }

    return 0;
}

import std.stdio;
import std.container : BinaryHeap;

int main(string[] args)
{
	int n; readf(" %d", n);

	int[] h = new int[n];
	auto bh = BinaryHeap!(int[])(h, 0);

	int cur_expected = n;

	foreach (i; 0..n){
		int num; readf(" %d", num);
		bh.insert(num);

		while(!bh.empty() && bh.front() == cur_expected){
			writef("%d ", bh.front());
			bh.popFront();
			cur_expected--;
		}

		writeln();
	}

	return 0;
}


Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.

The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.

Print the answer to each question on a single line. Print the answers in the order they go in the input.

NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 < k2 < ... < k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be «()».For the fourth query required sequence will be «()(())(())».

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

struct node {
    int seqlen;
    int unleft;
    int unright;
    this(int sl, int ul, int ur) {
        seqlen = sl;
        unleft = ul;
        unright = ur;
    }
}

node[] segtree;
string parens;

node SegTreeConstruct(int sb, int se, int si) {
    if (sb == se) {
        if (parens[sb] == '(') segtree[si] = node(0, 1, 0);
        if (parens[sb] == ')') segtree[si] = node(0, 0, 1);
        return segtree[si];
    }

    int mid = (sb + se) / 2;
    node nl = SegTreeConstruct(sb, mid, si * 2 + 1);
    node nr = SegTreeConstruct(mid + 1, se, si * 2 + 2);
    int m = min(nl.unleft, nr.unright);
    segtree[si] = node(nl.seqlen + nr.seqlen + 2 * m,
                       nl.unleft + nr.unleft - m,
                       nl.unright + nr.unright - m);
    return segtree[si];
}

node SegTreeRead(int sb, int se, int qb, int qe, int si) {
    if (qb <= sb && qe >= se)
        return segtree[si];

    if (se < qb || sb > qe)
        return node(0, 0, 0);

    int mid = (sb + se) / 2;
    node nl = SegTreeRead(sb, mid, qb, qe, 2 * si + 1);
    node nr = SegTreeRead(mid + 1, se, qb, qe, 2 * si + 2);
    int m = min(nl.unleft, nr.unright);
    return node(nl.seqlen + nr.seqlen + 2 * m,
                nl.unleft + nr.unleft - m,
                nl.unright + nr.unright - m);
}

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

    readf(" %s\n", &parens);
    segtree = new node[parens.length * 4];
    SegTreeConstruct(0, parens.length - 1, 0);

    int n;
    readf(" %s\n", &n);
    foreach (i; 0 .. n) {
        int left, right;
        readf(" %s %s\n", &left, &right);
        node nd = SegTreeRead(0, parens.length - 1, left - 1, right - 1, 0);
        writeln(nd.seqlen);
    }

    return 0;
}

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

struct node {
    int seqlen;
    int unleft;
    int unright;
    this(int sl, int ul, int ur) {
        seqlen = sl;
        unleft = ul;
        unright = ur;
    }
}

__gshared {
    node[] segtree;
    string parens;
}

node SegTreeConstruct(int sb, int se, int si) {
    if (sb == se) {
        if (parens[sb] == '(') segtree[si] = node(0, 1, 0);
        if (parens[sb] == ')') segtree[si] = node(0, 0, 1);
        return segtree[si];
    }

    int mid = (sb + se) / 2;
    node nl = SegTreeConstruct(sb, mid, si * 2 + 1);
    node nr = SegTreeConstruct(mid + 1, se, si * 2 + 2);
    int m = min(nl.unleft, nr.unright);
    segtree[si] = node(nl.seqlen + nr.seqlen + 2 * m,
                       nl.unleft + nr.unleft - m,
                       nl.unright + nr.unright - m);
    return segtree[si];
}

node SegTreeRead(int sb, int se, int qb, int qe, int si) {
    if (qb <= sb && qe >= se)
        return segtree[si];

    if (se < qb || sb > qe)
        return node(0, 0, 0);

    int mid = (sb + se) / 2;
    node nl = SegTreeRead(sb, mid, qb, qe, 2 * si + 1);
    node nr = SegTreeRead(mid + 1, se, qb, qe, 2 * si + 2);
    int m = min(nl.unleft, nr.unright);
    return node(nl.seqlen + nr.seqlen + 2 * m,
                nl.unleft + nr.unleft - m,
                nl.unright + nr.unright - m);
}

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

    readf(" %s\n", &parens);
    segtree = new node[parens.length * 4];
    SegTreeConstruct(0, parens.length - 1, 0);

    int n;
    readf(" %s\n", &n);
    foreach (i; 0 .. n) {
        int left, right;
        readf(" %s %s\n", &left, &right);
        node nd = SegTreeRead(0, parens.length - 1, left - 1, right - 1, 0);
        writeln(nd.seqlen);
    }

    return 0;
}

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

struct node {
    int seqlen;
    int unleft;
    int unright;
    this(int sl, int ul, int ur) {
        seqlen = sl;
        unleft = ul;
        unright = ur;
    }
}

__gshared {
    node[] segtree;
    string parens;
}

node SegTreeConstruct(int sb, int se, int si) {
    if (sb == se) {
        if (parens[sb] == '(') segtree[si] = node(0, 1, 0);
        if (parens[sb] == ')') segtree[si] = node(0, 0, 1);
        return segtree[si];
    }

    int mid = (sb + se) / 2;
    node nl = SegTreeConstruct(sb, mid, si * 2);
    node nr = SegTreeConstruct(mid + 1, se, si * 2 + 1);
    int m = min(nl.unleft, nr.unright);
    segtree[si] = node(nl.seqlen + nr.seqlen + 2 * m,
                       nl.unleft + nr.unleft - m,
                       nl.unright + nr.unright - m);
    return segtree[si];
}

node SegTreeRead(int sb, int se, int qb, int qe, int si) {
    if (qb <= sb && qe >= se)
        return segtree[si];

    if (se < qb || sb > qe)
        return node(0, 0, 0);

    int mid = (sb + se) / 2;
    node nl = SegTreeRead(sb, mid, qb, qe, 2 * si);
    node nr = SegTreeRead(mid + 1, se, qb, qe, 2 * si + 1);
    int m = min(nl.unleft, nr.unright);
    return node(nl.seqlen + nr.seqlen + 2 * m,
                nl.unleft + nr.unleft - m,
                nl.unright + nr.unright - m);
}

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

    readf(" %s\n", &parens);
    segtree = new node[parens.length * 4];
    SegTreeConstruct(0, parens.length - 1, 1);

    int n;
    readf(" %s\n", &n);
    foreach (i; 0 .. n) {
        int left, right;
        readf(" %s %s\n", &left, &right);
        node nd = SegTreeRead(0, parens.length - 1, left - 1, right - 1, 1);
        writeln(nd.seqlen);
    }

    return 0;
}

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

struct query {
    int index;
    int l;
    int r;
    int answer;
}

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

    string paren;
    readf(" %s\n", &paren);
    int n;
    readf(" %s\n", &n);
    query[] qarr = new query[n];
    foreach (i; 0 .. n) {
        query q;
        readf(" %s %s\n", &q.l, &q.r);
        --q.l;
        --q.r;
        q.index = i;
        qarr[i] = q;
    }
    int[1000000] posarr = -1;
    int[] pstack;
    foreach (int i, char c; paren) {
        if (c == '(') pstack ~= i;
        else if (!pstack.empty) {
            posarr[i] = pstack.back;
            posarr[pstack.back] = i;
            pstack.popBack();
        }
    }
    qarr.sort!"a.r < b.r";
    int pl = 0, pr = 0, answer = 0;
    foreach (ref q; qarr) {
        for ( ; pr < q.r + 1; ++pr) {
            if (posarr[pr] >=0 && posarr[pr] < pr && pl <= posarr[pr]) answer += 2;
        }
        if (pl < q.l) {
            for ( ; pl < q.l; ++pl) {
                if (posarr[pl] > pl && pr >= posarr[pl]) answer -= 2;
            }
        }
        else while (pl > q.l) {
            --pl;
            if (posarr[pl] > pl && pr >= posarr[pl]) answer += 2;
        }
        q.answer = answer;
    }
    qarr.sort!"a.index < b.index";
    foreach (q; qarr) writeln(q.answer);

    return 0;
}