Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack.Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to n. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.

The first line of input contains the integer n (1 ≤ n ≤ 3·105) — the number of boxes. Each of the next 2n lines of input starts with a string "add" or "remove". If the line starts with the "add", an integer x (1 ≤ x ≤ n) follows, indicating that Daru should add the box with number x to the top of the stack.  It is guaranteed that exactly n lines contain "add" operations, all the boxes added are distinct, and n lines contain "remove" operations. It is also guaranteed that a box is always added before it is required to be removed.

Print the minimum number of times Daru needs to reorder the boxes to successfully complete all of Okabe's commands.

3
add 1
remove
add 2
add 3
remove
remove

7
add 3
add 2
add 1
remove
add 4
remove
remove
remove
add 6
add 7
add 5
remove
remove
remove

NoteIn the first sample, Daru should reorder the boxes after adding box 3 to the stack.In the second sample, Daru should reorder the boxes after adding box 4 and box 7 to the stack.

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;

int n;

void main() {
    scan(n);

    auto bh = new BinaryHeap!(Array!int, "a > b")();

    int ans;
    int nn = 1;
    int b = 0;

    foreach (i ; 0 .. 2*n) {
        auto line = readln.split;

        if (line[0] == "add") {
            int x = line[1].to!int;

            if (!bh.empty && x > bh.front) {
                b = bh.front;
            }

            bh.insert(x);
        }
        else {
            debug {
                writeln("next:", nn);
                writeln("b:", b);
                writeln("top:", bh.front);
                writeln;
            }
            if (nn == b) {
                ans++;
                b = 0;
            }

            bh.popFront();
            nn++;
        }
    }

    writeln(ans);
}

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

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

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;

immutable inf = 10^^7;
int n;

void main() {
    scan(n);

    auto st = Stack!int(n);
    int ans, nn = 1;

    foreach (i ; 0 .. 2*n) {
        auto line = readln.split;

        if (line[0] == "add") {
            int x = line[1].to!int;
            st.push(x);
        }
        else {
            if (!st.empty && st.top != nn) {
                debug {
                    writeln("nn:", nn);
                }
                ans++;
                st.clear();
            }
            else if (!st.empty) {
                st.pop();
            }

            nn++;
        }
    }

    writeln(ans);
}

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

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

struct Stack(T) {
private:
    int N, peek;
    T[] data;

public:
    this(int size)
    {
        N = size;
        data = new T[](N);
    }

    bool empty() @property
    {
        return peek == 0;
    }

    bool full() @property
    {
        return peek == N;
    }

    void push(T x) @property
    {
        assert(!full);
        data[peek++] = x;
    }

    void pop() @property
    {
        assert(!empty);
        --peek;
    }

    T top() @property
    {
        return data[peek - 1];
    }

    void clear() @property
    {
        peek = 0;
    }

    int length() @property
    {
        return peek;
    }

}


Omkar is standing at the foot of Celeste mountain. The summit is $$$n$$$ meters away from him, and he can see all of the mountains up to the summit, so for all $$$1 \leq j \leq n$$$ he knows that the height of the mountain at the point $$$j$$$ meters away from himself is $$$h_j$$$ meters. It turns out that for all $$$j$$$ satisfying $$$1 \leq j \leq n - 1$$$, $$$h_j < h_{j + 1}$$$ (meaning that heights are strictly increasing).Suddenly, a landslide occurs! While the landslide is occurring, the following occurs: every minute, if $$$h_j + 2 \leq h_{j + 1}$$$, then one square meter of dirt will slide from position $$$j + 1$$$ to position $$$j$$$, so that $$$h_{j + 1}$$$ is decreased by $$$1$$$ and $$$h_j$$$ is increased by $$$1$$$. These changes occur simultaneously, so for example, if $$$h_j + 2 \leq h_{j + 1}$$$ and $$$h_{j + 1} + 2 \leq h_{j + 2}$$$ for some $$$j$$$, then $$$h_j$$$ will be increased by $$$1$$$, $$$h_{j + 2}$$$ will be decreased by $$$1$$$, and $$$h_{j + 1}$$$ will be both increased and decreased by $$$1$$$, meaning that in effect $$$h_{j + 1}$$$ is unchanged during that minute.The landslide ends when there is no $$$j$$$ such that $$$h_j + 2 \leq h_{j + 1}$$$. Help Omkar figure out what the values of $$$h_1, \dots, h_n$$$ will be after the landslide ends. It can be proven that under the given constraints, the landslide will always end in finitely many minutes.Note that because of the large amount of input, it is recommended that your code uses fast IO.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$).  The second line contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ satisfying $$$0 \leq h_1 < h_2 < \dots < h_n \leq 10^{12}$$$ — the heights.

Output $$$n$$$ integers, where the $$$j$$$-th integer is the value of $$$h_j$$$ after the landslide has stopped.

NoteInitially, the mountain has heights $$$2, 6, 7, 8$$$.In the first minute, we have $$$2 + 2 \leq 6$$$, so $$$2$$$ increases to $$$3$$$ and $$$6$$$ decreases to $$$5$$$, leaving $$$3, 5, 7, 8$$$.In the second minute, we have $$$3 + 2 \leq 5$$$ and $$$5 + 2 \leq 7$$$, so $$$3$$$ increases to $$$4$$$, $$$5$$$ is unchanged, and $$$7$$$ decreases to $$$6$$$, leaving $$$4, 5, 6, 8$$$.In the third minute, we have $$$6 + 2 \leq 8$$$, so $$$6$$$ increases to $$$7$$$ and $$$8$$$ decreases to $$$7$$$, leaving $$$4, 5, 7, 7$$$.In the fourth minute, we have $$$5 + 2 \leq 7$$$, so $$$5$$$ increases to $$$6$$$ and $$$7$$$ decreases to $$$6$$$, leaving $$$4, 6, 6, 7$$$.In the fifth minute, we have $$$4 + 2 \leq 6$$$, so $$$4$$$ increases to $$$5$$$ and $$$6$$$ decreases to $$$5$$$, leaving $$$5, 5, 6, 7$$$.In the sixth minute, nothing else can change so the landslide stops and our answer is $$$5, 5, 6, 7$$$.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto h = readln.splitter.map !(to !(long)).array;
		foreach (i; 0..n)
		{
			h[i] -= i;
		}

		long total = h.sum;
		foreach (i; 0..n)
		{
			int num = n - i;
			long cur = (total + num - 1) / num;
			if (h[i] < cur)
			{
				long delta = cur - h[i];
				h[i] += delta;
				h[i + 1] -= delta;
			}
			total -= h[i];
		}

		foreach (i; 0..n)
		{
			h[i] += i;
		}
		writefln !("%(%s %)") (h);
	}
}

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 H = new long[N];
      foreach (i; 0 .. N) {
        H[i] = readLong();
      }

      long val = H.sum;
      foreach (i; 0 .. N) {
        val -= i;
      }
      auto ans = new long[N];
      ans[] = val / N;
      ans[0 .. cast(int)(val % N)] += 1;
      foreach (i; 0 .. N) {
        ans[i] += i;
      }

      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;
    }
  } catch (EOFException e) {
  }
}


You are given four integer values $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$.Check if there exists a string that contains:   $$$a$$$ letters 'A';  $$$b$$$ letters 'B';  $$$c$$$ letters 'C';  no other letters;  exactly $$$m$$$ pairs of adjacent equal letters (exactly $$$m$$$ such positions $$$i$$$ that the $$$i$$$-th letter is equal to the $$$(i+1)$$$-th one).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Each of the next $$$t$$$ lines contains the description of the testcase — four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$ ($$$1 \le a, b, c \le 10^8$$$; $$$0 \le m \le 10^8$$$).

For each testcase print "YES" if there exists a string that satisfies all the requirements. Print "NO" if there are no such strings. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first testcase strings "ABCAB" or "BCABA" satisfy the requirements. There exist other possible strings.In the second testcase there's no way to put adjacent equal letters if there's no letter that appears at least twice.In the third testcase string "CABBCC" satisfies the requirements. There exist other possible strings.

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

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(i; 0..t){
	    long a,b,c,m;
	    scanf("%lld %lld %lld %lld", &a, &b, &c, &m);
	    auto top_max = a + b + c - 3;
	    auto max_v = max(a,b,c);
	    auto min_v = min(a,b,c);
	    auto mid_v = a + b + c - max_v - min_v;
	    if ((m > top_max) || (max_v > (min_v + mid_v + 1 + m)))
		    writeln("NO");
	    else
		    writeln("YES");
    }
}


Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.

The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends. Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.

Print the maximum number of people that may come to Famil Door's party.

NoteIn the first sample, friends 3 and 4 can come on any day in range [117, 128].In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.

import std.stdio;
import std.algorithm;

void main()
{
	int n;

	scanf("%d", &n);

	bool[] used = new bool[n];
	char[] gender = new char[n];
	int[] from = new int[n];
	int[] to = new int[n];

	for (int i = 0; i < n; i++) {
		char[10] s;
		scanf("%s%d%d", s.ptr, &from[i], &to[i]);
		gender[i] = s[0];
	}

	int res = 0;

	for (int i = 1; i <= 366; i++) {
		char[2] genders = ['F', 'M'];
		int[2] found = [0, 0];
		for (int j = 0; j < 2; j++) {
			for (int k = 0; k < n; k++) {
				if (!used[k] && gender[k] == genders[j] && from[k] <= i && to[k] >= i) {
					found[j]++;
				}
			}
		}

		res = max(res, min(found[0], found[1]));
	}

	printf("%d\n", 2 * res);
}

import std.stdio;
import std.conv;
import std.string;
import std.array: Appender;
import std.datetime;
import std.algorithm;

void main()
{

	auto n = to!int(strip(readln));
	int[] r = new int[377];
	int[] c = new int[377];
	for (auto i = 0; i < n; i++)
	{
		auto str = split(strip(readln));
		foreach (num; to!int(str[1])..to!int(str[2])+1)
		{
			if (str[0] == "F")
				r[num]++;
			else
				c[num]++;
		}
	}
	int count;
	foreach (i, ele; r)
	{
		count = max(min(r[i], c[i]), count);
	}
	writeln(2 * count);
}

import std.stdio;
import std.conv;
import std.string;
import std.array: Appender;
import std.datetime;
import std.algorithm;

void main()
{

	auto n = to!int(strip(readln));
	int[] r = new int[377];
	int[] c = new int[377];
	for (auto i = 0; i < n; i++)
	{
		auto str = split(strip(readln));
		foreach (num; to!int(str[1])..to!int(str[2]))
		{
			if (str[0] == "F")
				r[num]++;
			else
				c[num]++;
		}
	}
	int count;
	foreach (i, ele; r)
	{
		count = max(min(r[i], c[i]), count);
	}

	writeln(2 * count);
}

import std.stdio;
import std.conv;
import std.string;
import std.array: Appender;
import std.datetime;
import std.algorithm;

void main()
{

	auto n = to!int(strip(readln));
	int[] r = new int[377];
	int[] c = new int[377];
	for (auto i = 0; i < n; i++)
	{
		auto str = split(strip(readln));
		foreach (num; to!int(str[1])..to!int(str[2]))
		{
			if (str[0] == "F")
				r[num]++;
			else
				c[num]++;
		}
	}
	int count;
	foreach (i, ele; r)
	{
		count = max(min(r[i], c[i]), count);
	}

	writeln(count);
}

import std.stdio;
import std.conv;
import std.string;
import std.array: Appender;
import std.datetime;
import std.algorithm;

void main()
{

	auto n = to!int(strip(readln));
	int[] r = new int[377];
	int[] c = new int[377];
	for (auto i = 0; i < n; i++)
	{
		auto str = split(strip(readln));
		foreach (num; to!int(str[1])..to!int(str[2]))
		{
			if (str[0] == "F")
				r[num]++;
			else
				c[num]++;
		}
	}
	int count;
	foreach (i, ele; r)
	{
		count = min(r[i], c[i]);
	}

	writeln(count);
}


You are given a multiset (i. e. a set that can contain multiple equal integers) containing $$$2n$$$ integers. Determine if you can split it into exactly $$$n$$$ pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by $$$2$$$, the remainder is $$$1$$$).

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\leq n\leq 100$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1,a_2,\dots, a_{2n}$$$ ($$$0\leq a_i\leq 100$$$) — the numbers in the set.

For each test case, print "Yes" if it can be split into exactly $$$n$$$ pairs so that the sum of the two elements in each pair is odd, and "No" otherwise. You can print each letter in any case.

NoteIn the first test case, a possible way of splitting the set is $$$(2,3)$$$, $$$(4,5)$$$.In the second, third and fifth test case, we can prove that there isn't any possible way.In the fourth test case, a possible way of splitting the set is $$$(2,3)$$$.

// Vicfred
// https://codeforces.com/contest/1542/problem/A
// math, implementation
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

while(t--) {
    int n = readln.chomp.to!int;
    int[] a = readln.split.map!(to!int).array;
    int even = 0;
    int odd = 0;
    foreach(item; a) {
        if(item % 2 == 0) {
            even += 1;
        } else {
            odd += 1;
        }
    }
    if(even == odd) {
        "Yes".writeln;
    } else {
        "No".writeln;
    }
}
}

// code by cutx64

module main;

import std.string, std.array, std.container, std.typecons;
import std.stdio, std.format, std.file, std.outbuffer;
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 tests; readf!"%s\n"(tests);
  immutable(long) mod = 10 ^^ 9 + 7;
  while(tests--) {
    int n;
    readf!"%s\n"(n);
    auto a = readln.splitter.map!(to!int).array;
    int odd = a.count!(x => x % 2 == 1);
    writeln(["Yes", "No"][odd != n]);
  }

} // main

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array;
    auto b = a.filter!(x => x % 2 == 0).array;
    auto c = a.filter!(x => x % 2 == 1).array;
    if (b.length == c.length) {
      writeln("Yes");
    } else {
      writeln("No");
    }
  }
}

// Cheese-Cracker: cheese-cracker.github.io

void theCode(){
    ll n = scan;
    auto arr = scanArray;
    ll odd = 0;
    for(int i = 0; i < 2*n; ++i){
        if(arr[i] % 2 == 1){
            ++odd;
        }
    }
    if(odd == n){
        writeln("Yes");
    }else{
        writeln("No");
    }
}

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

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

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)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;

		long cnt;
		foreach (e; a)
		{
			if (e % 2)
				++cnt;
		}

		ans[ti] = cnt == n;
	}

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


You are given strings $$$S$$$ and $$$T$$$, consisting of lowercase English letters. It is guaranteed that $$$T$$$ is a permutation of the string abc. Find string $$$S'$$$, the lexicographically smallest permutation of $$$S$$$ such that $$$T$$$ is not a subsequence of $$$S'$$$.String $$$a$$$ is a permutation of string $$$b$$$ if the number of occurrences of each distinct character is the same in both strings.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a string $$$S$$$ ($$$1 \le |S| \le 100$$$), consisting of lowercase English letters. The second line of each test case contains a string $$$T$$$ that is a permutation of the string abc. (Hence, $$$|T| = 3$$$). Note that there is no limit on the sum of $$$|S|$$$ across all test cases.

For each test case, output a single string $$$S'$$$, the lexicographically smallest permutation of $$$S$$$ such that $$$T$$$ is not a subsequence of $$$S'$$$.

7
abacaba
abc
cccba
acb
dbsic
bac
abracadabra
abc
dddddddddddd
cba
bbc
abc
ac
abc

aaaacbb
abccc
bcdis
aaaaacbbdrr
dddddddddddd
bbc
ac

NoteIn the first test case, both aaaabbc and aaaabcb are lexicographically smaller than aaaacbb, but they contain abc as a subsequence.In the second test case, abccc is the smallest permutation of cccba and does not contain acb as a subsequence.In the third test case, bcdis is the smallest permutation of dbsic and does not contain bac as a subsequence.

immutable multi = true;

void solve(int tc)
{
  auto s = cast(byte[])readString;
  auto t = cast(byte[])readString;
  auto ca = s.count!(c => c == 'a');
  auto cb = s.count!(c => c == 'b');
  auto cc = s.count!(c => c == 'c');
  sort(s);
  if (t != "abc") return writeln(cast(string)s);
  if (ca > 0 && cb > 0 && cc > 0)
    {
      s = s[ca + cb + cc .. $];
      foreach(i; 0 .. ca) write('a');
      foreach(i; 0 .. cc) write('c');
      foreach(i; 0 .. cb) write('b');
    }
  writeln(cast(string)s);
}

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

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

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

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

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

import std;

void
printSmallest (in int[dchar] frec) {
    foreach (dchar c; frec.keys.sort)
        write(c.repeat(frec[c]));
    writeln();
}

void main () {
    int tests;
    readf("%s\n", tests);
    foreach (i; 0 .. tests) {
        string s, t;
        s = readln()[0 .. $ - 1];
        t = readln()[0 .. $ - 1];

        int[dchar] frec;

        foreach (c; s)
            ++ frec[c];

        if (t == "abc" && 'a' in frec && 'b' in frec && 'c' in frec) {
            static foreach (c; "acb") {
                write(c.repeat(frec[c]));
                frec.remove(c);
            }
        }
        printSmallest(frec);
    }
}

//""

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

immutable int limit = 128;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip.dup;
		auto t = readln.strip;
		int [limit] num;
		foreach (ref c; s)
		{
			num[c] += 1;
		}
		auto p = limit.iota.array;
		if (t == "abc" && num['a'] && num['b'] && num['c'])
		{
			swap (p['b'], p['c']);
		}
		foreach (ref c; p)
		{
			foreach (i; 0..num[c])
			{
				write (cast (char) (c));
			}
		}
		writeln;
	}
}

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)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

void main()
{
	auto t = RD!int;
	auto ans = new string[](t);
	foreach (ti; 0..t)
	{
		auto S = RD!string;
		auto T = RD!string;

		auto cnt = new long[](26);
		foreach (c; S)
			++cnt[c-'a'];

		if (T == "abc")
		{
			if (cnt[0] == 0 || cnt[1] == 0 || cnt[2] == 0)
			{
				foreach (i; 0..26)
					foreach (_; 0..cnt[i])
						ans[ti] ~= cast(char)('a'+i);
			}
			else
			{
				foreach (_; 0..cnt[0])
					ans[ti] ~= "a";
				foreach (_; 0..cnt[2])
					ans[ti] ~= "c";
				foreach (_; 0..cnt[1])
					ans[ti] ~= "b";
				foreach (i; 3..26)
					foreach (_; 0..cnt[i])
						ans[ti] ~= cast(char)('a'+i);
			}
		}
		else
		{
			foreach (i; 0..26)
				foreach (_; 0..cnt[i])
					ans[ti] ~= cast(char)('a'+i);
		}
	}

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

immutable multi = true;

void solve(int tc)
{
  auto s = cast(byte[])readString;
  auto t = cast(byte[])readString;
  sort(s);
  if (t != "abc") return writeln(cast(string)s);
  foreach(i, si; s)
    if (s[i .. min($, i + 3)] == "abc")
      {
	swap(s[i + 1], s[i + 2]);
      }
  writeln(cast(string)s);
}

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

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

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

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

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


Let $$$\mathsf{AND}$$$ denote the bitwise AND operation, and $$$\mathsf{OR}$$$ denote the bitwise OR operation.You are given an array $$$a$$$ of length $$$n$$$ and a non-negative integer $$$k$$$. You can perform at most $$$k$$$ operations on the array of the following type:  Select an index $$$i$$$ ($$$1 \leq i \leq n$$$) and replace $$$a_i$$$ with $$$a_i$$$ $$$\mathsf{OR}$$$ $$$2^j$$$ where $$$j$$$ is any integer between $$$0$$$ and $$$30$$$ inclusive. In other words, in an operation you can choose an index $$$i$$$ ($$$1 \leq i \leq n$$$) and set the $$$j$$$-th bit of $$$a_i$$$ to $$$1$$$ ($$$0 \leq j \leq 30$$$). Output the maximum possible value of $$$a_1$$$ $$$\mathsf{AND}$$$ $$$a_2$$$ $$$\mathsf{AND}$$$ $$$\dots$$$ $$$\mathsf{AND}$$$ $$$a_n$$$ after performing at most $$$k$$$ operations.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le 10^9$$$). Then a single line follows, containing $$$n$$$ integers describing the arrays $$$a$$$ ($$$0 \leq a_i < 2^{31}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single line containing the maximum possible $$$\mathsf{AND}$$$ value of $$$a_1$$$ $$$\mathsf{AND}$$$ $$$a_2$$$ $$$\mathsf{AND}$$$ $$$\dots$$$ $$$\mathsf{AND}$$$ $$$a_n$$$ after performing at most $$$k$$$ operations.

NoteFor the first test case, we can set the bit $$$1$$$ ($$$2^1$$$) of the last $$$2$$$ elements using the $$$2$$$ operations, thus obtaining the array [$$$2$$$, $$$3$$$, $$$3$$$], which has $$$\mathsf{AND}$$$ value equal to $$$2$$$.For the second test case, we can't perform any operations so the answer is just the $$$\mathsf{AND}$$$ of the whole array which is $$$4$$$.

import std;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		int res = 0;
		foreach_reverse (j; 0..31)
		{
			auto num = a.count !(x => (x & (1 << j)) == 0);
			if (k >= num)
			{
				res += (1 << j);
				k -= num;
			}
		}
		writeln (res);
	}
}


You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.

First line contains three integers n, k and m (2 ≤ k ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers. Second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the numbers in the multiset.

If it is not possible to select k numbers in the desired way, output «No» (without the quotes). Otherwise, in the first line of output print «Yes» (without the quotes). In the second line print k integers b1, b2, ..., bk — the selected numbers. If there are multiple possible solutions, print any of them.

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();
      const K = readInt();
      const M = readInt();
      auto A = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
      }

      auto iss = new int[][M];
      foreach (i; 0 .. N) {
        iss[A[i] % M] ~= i;
      }

      foreach (r; 0 .. M) {
        if (iss[r].length >= K) {
          writeln("Yes");
          foreach (k; 0 .. K) {
            if (k > 0) write(" ");
            write(A[iss[r][k]]);
          }
          writeln;
          goto found;
        }
      }
      writeln("No");
     found:
    }
  } catch (EOFException e) {
  }
}


Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.

The first line of the input contains binary string a (1 ≤ |a| ≤ 200 000). The second line of the input contains binary string b (|a| ≤ |b| ≤ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only.

Print a single integer — the sum of Hamming distances between a and all contiguous substrings of b of length |a|.

NoteFor the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.The second sample case is described in the statement.

import std.stdio;

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

    string a, b;
    readf(" %s\n", &a);
    readf(" %s\n", &b);
    int zcnt = 0;
    long answer = 0;
    int frontidx = 0, backidx = b.length - a.length, seglen = backidx + 1;
    foreach (i; 0 .. seglen) {
        if (b[i] == '1') ++zcnt;
    }
    foreach (c; a) {
        if (c == '0') answer += zcnt;
        else answer += seglen - zcnt;
        if (++backidx < b.length && b[backidx] == '1') ++zcnt;
        if (b[frontidx++] == '1') --zcnt;
    }
    writeln(answer);

    return 0;
}


Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!A password is an array $$$a$$$ of $$$n$$$ positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index $$$i$$$ such that $$$1 \leq i < n$$$ and $$$a_{i} \neq a_{i+1}$$$, delete both $$$a_i$$$ and $$$a_{i+1}$$$ from the array and put $$$a_{i}+a_{i+1}$$$ in their place. For example, for array $$$[7, 4, 3, 7]$$$ you can choose $$$i = 2$$$ and the array will become $$$[7, 4+3, 7] = [7, 7, 7]$$$. Note that in this array you can't apply this operation anymore.Notice that one operation will decrease the size of the password by $$$1$$$. What is the shortest possible length of the password after some number (possibly $$$0$$$) of operations?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the password. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$1 \leq a_{i} \leq 10^9$$$) — the initial contents of your password. The sum of $$$n$$$ over all test cases will not exceed $$$2 \cdot 10^5$$$.

For each password, print one integer: the shortest possible length of the password after some number of operations.

NoteIn the first test case, you can do the following to achieve a length of $$$1$$$:Pick $$$i=2$$$ to get $$$[2, 4, 1]$$$Pick $$$i=1$$$ to get $$$[6, 1]$$$Pick $$$i=1$$$ to get $$$[7]$$$In the second test case, you can't perform any operations because there is no valid $$$i$$$ that satisfies the requirements mentioned above.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		writeln (a.minElement == a.maxElement ? n : 1);
	}
}

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 numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        auto A = new long[N];
        foreach (i; 0 .. N) {
          A[i] = readLong();
        }

        const ans = A.all!(a => (a == A[0])) ? N : 1;
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n;
  @Dim("n") long[] a;

  void solve(long tc = -1)
  {
    auto set = redBlackTree!long(a);
    if (set.length > 1)
      return writeln(1);
    return writeln(a.length);
  }
}

struct Interval
{
  long l, h;

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int x = a[0];
		bool ok;
		foreach (i; 0..n)
		{
			if (a[i] != x)
			{
				ok = true;
				break;
			}
		}
		ans[ti] = ok ? 1 : n;
	}

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


This is an easier version of the problem. In this version $$$n \le 1000$$$The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $$$n$$$ plots along the highway and is preparing to build $$$n$$$ skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from $$$1$$$ to $$$n$$$. Then if the skyscraper on the $$$i$$$-th plot has $$$a_i$$$ floors, it must hold that $$$a_i$$$ is at most $$$m_i$$$ ($$$1 \le a_i \le m_i$$$). Also there mustn't be integers $$$j$$$ and $$$k$$$ such that $$$j < i < k$$$ and $$$a_j > a_i < a_k$$$. Plots $$$j$$$ and $$$k$$$ are not required to be adjacent to $$$i$$$.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the number of plots. The second line contains the integers $$$m_1, m_2, \ldots, m_n$$$ ($$$1 \leq m_i \leq 10^9$$$) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.

Print $$$n$$$ integers $$$a_i$$$ — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible. If there are multiple answers possible, print any of them.

NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer $$$[10, 6, 6]$$$ is optimal. Note that the answer of $$$[6, 6, 8]$$$ also satisfies all restrictions, but is not optimal.

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

enum inf = 1_001_001_001;
enum infl = 1_001_001_001_001_001_001L;

void main() {
    int N;
    scan(N);
    auto m = readln.split.to!(int[]);

    long ans;
    int k = -1;

    foreach (top ; 0 .. N) {
        long res = m[top];
        long l = m[top], r = m[top];
        long ls, rs;

        foreach_reverse (i ; 0 .. top) {
            chmin(l, m[i]);
            ls += l;
        }

        foreach (i ; top + 1 .. N) {
            chmin(r, m[i]);
            rs += r;
        }

        res += ls + rs;
        if (res > ans) {
            ans = res;
            k = top;
        }
    }

    auto a = new int[](N);
    a[k] = m[k];
    int l = m[k], r = m[k];
    foreach_reverse (i ; 0 .. k) {
        chmin(l, m[i]);
        a[i] = l;
    }
    foreach (i ; k + 1 .. N) {
        chmin(r, m[i]);
        a[i] = r;
    }

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

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

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

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

bool chmin(T, U...)(ref T x, U args) {
    bool isChanged;

    foreach (arg; args) {
        if (x > arg) {
            x = arg;
            isChanged = true;
        }
    }

    return isChanged;
}

bool chmax(T, U...)(ref T x, U args) {
    bool isChanged;

    foreach (arg; args) {
        if (x < arg) {
            x = arg;
            isChanged = true;
        }
    }

    return isChanged;
}

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

enum inf = 1_001_001_001;
enum infl = 1_001_001_001_001_001_001L;

void main() {
    int N;
    scan(N);
    auto m = readln.split.to!(int[]);

    long mn = inf;

    foreach (i ; 0 .. N) {
        chmin(mn, m[i]);
    }

    long ps;
    foreach (i ; 0 .. N - 1) {
        ps += m[i];
    }

    long ss;
    foreach_reverse (i ; 1 .. N) {
        ss += m[i];
    }

    auto f = mn + ss;
    auto g = mn + ps;

    auto ans = new long[](N);

    if (f > g) {
        ans[0] = mn;
        foreach (i ; 1 .. N) {
            ans[i] = m[i];
        }
    }
    else {
        ans[N - 1] = mn;
        foreach (i ; 0 .. N - 1) {
            ans[i] = m[i];
        }
    }

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

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

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

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

bool chmin(T, U...)(ref T x, U args) {
    bool isChanged;

    foreach (arg; args) {
        if (x > arg) {
            x = arg;
            isChanged = true;
        }
    }

    return isChanged;
}

bool chmax(T, U...)(ref T x, U args) {
    bool isChanged;

    foreach (arg; args) {
        if (x < arg) {
            x = arg;
            isChanged = true;
        }
    }

    return isChanged;
}

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

enum inf = 1_001_001_001;
enum infl = 1_001_001_001_001_001_001L;

void main() {
    int N;
    scan(N);
    auto m = readln.split.to!(int[]);

    long pm = inf;
    long ps;
    foreach (i ; 0 .. N - 1) {
        chmin(pm, m[i]);
        ps += m[i];
    }

    long sm = inf;
    long ss;
    foreach_reverse (i ; 1 .. N) {
        chmin(sm, m[i]);
        ss += m[i];
    }

    auto f = sm + ss;
    auto g = pm + ps;

    auto ans = new long[](N);

    if (f > g) {
        ans[0] = sm;
        foreach (i ; 1 .. N) {
            ans[i] = m[i];
        }
    }
    else {
        ans[N - 1] = pm;
        foreach (i ; 0 .. N - 1) {
            ans[i] = m[i];
        }
    }

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

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

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

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

bool chmin(T, U...)(ref T x, U args) {
    bool isChanged;

    foreach (arg; args) {
        if (x > arg) {
            x = arg;
            isChanged = true;
        }
    }

    return isChanged;
}

bool chmax(T, U...)(ref T x, U args) {
    bool isChanged;

    foreach (arg; args) {
        if (x < arg) {
            x = arg;
            isChanged = true;
        }
    }

    return isChanged;
}


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

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

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

NoteLet's analyze all the requests. In each case the requested submatrix is highlighted in blue.In the first request (k = 1) Leha asks only about the upper left parking cell. In this cell the car's number is 1. Consequentally the answer is 1.In the second request (k = 5) suitable numbers are 4, 1, 2, 3, 2, 1. Consequentally the answer is 4 + 1 + 2 + 3 + 2 + 1 = 13.In the third request (k = 10000) Leha asks about the upper left frament 5 × 5 of the parking. Since k is big enough, the answer is equal to 93.In the last request (k = 2) none of the cur's numbers are suitable, so the answer is 0.

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

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

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

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

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

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

enum E = 35;

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

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


Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.

The first line contains an integer N (1 ≤ N ≤ 1000) — the number of bars at Vasya’s disposal. The second line contains N space-separated integers li — the lengths of the bars. All the lengths are natural numbers not exceeding 1000.

In one line output two numbers — the height of the largest tower and their total number. Remember that Vasya should use all the bars.

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

void main() {
    int N = readln.chomp.to!int;
    auto l = readln.chomp.split.map!(to!int);
    int[int] table;
    foreach (e; l) {
        table[e]++;
    }

    writeln(table.values.minPos!("a > b")[0], " ", table.values.filter!("a > 0").array.length);
}


Students of Winter Informatics School are going to live in a set of houses connected by underground passages. Teachers are also going to live in some of these houses, but they can not be accommodated randomly. For safety reasons, the following must hold:  All passages between two houses will be closed, if there are no teachers in both of them. All other passages will stay open.  It should be possible to travel between any two houses using the underground passages that are open.  Teachers should not live in houses, directly connected by a passage. Please help the organizers to choose the houses where teachers will live to satisfy the safety requirements or determine that it is impossible.

The first input line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 10^5$$$).  Each test case starts with two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$0 \le m \le 3 \cdot 10^5$$$) — the number of houses and the number of passages. Then $$$m$$$ lines follow, each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), describing a passage between the houses $$$u$$$ and $$$v$$$. It is guaranteed that there are no two passages connecting the same pair of houses. The sum of values $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of values $$$m$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, if there is no way to choose the desired set of houses, output "NO". Otherwise, output "YES", then the total number of houses chosen, and then the indices of the chosen houses in arbitrary order.

NoteThe picture below shows the second example test.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto adj = new int [] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}

		auto vis = new bool [n];
		auto c = new int [n];
		c[] = -1;

		void recur (int v)
		{
			if (vis[v])
			{
				return;
			}
			vis[v] = true;
			if (c[v] == -1)
			{
				c[v] = 0;
				foreach (u; adj[v])
				{
					c[u] = 1;
				}
			}
			foreach (u; adj[v])
			{
				recur (u);
			}
		}

		recur (0);

		if (vis.all)
		{
			writeln ("YES");
			auto answer = n.iota.filter !(i => c[i] == 0).array;
			answer[] += 1;
			writeln (answer.length);
			writefln !("%(%s %)") (answer);
		}
		else
		{
			writeln ("NO");
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto edges = new int[][](n);
		foreach (i; 0..m)
		{
			auto u = RD!int-1;
			auto v = RD!int-1;
			edges[u] ~= v;
			edges[v] ~= u;
		}

		int[] q = [0];
		auto state = new int[](n);
		auto used = new bool[](n);
		used[0] = true;
		while (!q.empty)
		{
			auto u = q.front; q.popFront;
			bool can = true;
			foreach (v; edges[u])
			{
				if (state[v] == 1)
				{
					can = false;
					break;
				}
			}
			if (can)
				state[u] = 1;
			else
				state[u] = 2;
			foreach (v; edges[u])
			{
				if (used[v]) continue;
				q ~= v;
				used[v] = true;
			}
		}
		foreach (i; 0..n)
		{
			if (state[i] == 0)
			{
				ans[ti].length = 0;
				break;
			}
			else if (state[i] == 1)
				ans[ti] ~= i+1;
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			writeln(e.length);
			e.map!(to!string).join(" ").writeln;
		}
	}
	stdout.flush;
	debug readln;
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto adj = new int [] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}

		auto c = new int [n];
		c[] = -1;

		void recur (int v, int cur)
		{
			if (c[v] >= 0)
			{
				return;
			}
			c[v] = cur;
			foreach (u; adj[v])
			{
				recur (u, !cur);
			}
		}

		recur (0, 0);
		debug {writeln (c);}

		if (c.any !(q{a == -1}))
		{
			writeln ("NO");
		}
		else
		{
			foreach (v; 0..n)
			{
				if (c[v] == 0)
				{
					foreach (u; adj[v])
					{
						if (c[u] == 0)
						{
							c[v] = 2;
						}
					}
				}
			}
			writeln ("YES");
			auto answer = n.iota.filter !(i => c[i] == 0).array;
			answer[] += 1;
			writeln (answer.length);
			writefln !("%(%s %)") (answer);
		}
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto adj = new int [] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}

		auto c = new int [n];
		c[] = -1;

		void recur (int v, int cur)
		{
			if (c[v] >= 0)
			{
				return;
			}
			c[v] = cur;
			foreach (u; adj[v])
			{
				recur (u, !cur);
			}
			foreach (u; adj[v])
			{
				if (c[u] == 0)
				{
					c[v] = 2;
				}
			}
		}

		recur (0, 0);
		debug {writeln (c);}

		if (c.any !(q{a == -1}))
		{
			writeln ("NO");
		}
		else
		{
			writeln ("YES");
			auto answer = n.iota.filter !(i => c[i] == 0).array;
			answer[] += 1;
			writeln (answer.length);
			writefln !("%(%s %)") (answer);
		}
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto adj = new int [] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}

		auto c = new int [n];
		c[] = -1;

		void recur (int v, int cur)
		{
			if (c[v] >= 0)
			{
				return;
			}
			c[v] = cur;
			foreach (u; adj[v])
			{
				recur (u, !cur);
			}
			foreach (u; adj[v])
			{
				if (c[v] == c[u])
				{
					c[v] = 2;
				}
			}
		}

		recur (0, 0);
		debug {writeln (c);}

		if (c.any !(q{a == -1}))
		{
			writeln ("NO");
		}
		else
		{
			writeln ("YES");
			auto answer = n.iota.filter !(i => c[i] == 0).array;
			answer[] += 1;
			writeln (answer.length);
			writefln !("%(%s %)") (answer);
		}
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto adj = new int [] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}

		auto c = new int [n];
		c[] = -1;

		void recur (int v, int cur)
		{
			if (c[v] >= 0)
			{
				return;
			}
			c[v] = cur;
			foreach (u; adj[v])
			{
				recur (u, !cur);
			}
			foreach (u; adj[v])
			{
				if (c[v] == c[u])
				{
					c[v] = 2;
				}
			}
		}

		recur (0, 0);

		if (c.any !(q{a == -1}))
		{
			writeln ("NO");
		}
		else
		{
			writeln ("YES");
			auto answer = n.iota.filter !(i => c[i] == 1).array;
			answer[] += 1;
			writeln (answer.length);
			writefln !("%(%s %)") (answer);
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto edges = new int[][](n);
		foreach (i; 0..m)
		{
			auto u = RD!int-1;
			auto v = RD!int-1;
			edges[u] ~= v;
			edges[v] ~= u;
		}

		auto edges2 = new int[][](n);
		int[] q = [0];
		auto used = new bool[](n);
		used[0] = true;
		while (!q.empty)
		{
			auto u = q.front; q.popFront;
			foreach (v; edges[u])
			{
				if (used[v]) continue;
				edges2[u] ~= v;
				edges2[v] ~= u;
				q ~= v;
				used[v] = true;
			}
		}

		bool ok = true;
		foreach (i; 0..n)
		{
			if (!used[i])
			{
				ok = false;
				break;
			}
		}
		if (!ok) continue;

		void dfs(int pos, int last, int s)
		{
			if (s == 1)
				ans[ti] ~= pos+1;

			foreach (v; edges2[pos])
			{
				if (v == last) continue;
				dfs(v, pos, s^1);
			}
		}
		dfs(0, -1, 1);
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			writeln(e.length);
			e.map!(to!string).join(" ").writeln;
		}
	}
	stdout.flush;
	debug readln;
}


The integers shop sells $$$n$$$ segments. The $$$i$$$-th of them contains all integers from $$$l_i$$$ to $$$r_i$$$ and costs $$$c_i$$$ coins.Tomorrow Vasya will go to this shop and will buy some segments there. He will get all integers that appear in at least one of bought segments. The total cost of the purchase is the sum of costs of all segments in it.After shopping, Vasya will get some more integers as a gift. He will get integer $$$x$$$ as a gift if and only if all of the following conditions are satisfied:   Vasya hasn't bought $$$x$$$.  Vasya has bought integer $$$l$$$ that is less than $$$x$$$.  Vasya has bought integer $$$r$$$ that is greater than $$$x$$$. Vasya can get integer $$$x$$$ as a gift only once so he won't have the same integers after receiving a gift.For example, if Vasya buys segment $$$[2, 4]$$$ for $$$20$$$ coins and segment $$$[7, 8]$$$ for $$$22$$$ coins, he spends $$$42$$$ coins and receives integers $$$2, 3, 4, 7, 8$$$ from these segments. He also gets integers $$$5$$$ and $$$6$$$ as a gift.Due to the technical issues only the first $$$s$$$ segments (that is, segments $$$[l_1, r_1], [l_2, r_2], \ldots, [l_s, r_s]$$$) will be available tomorrow in the shop.Vasya wants to get (to buy or to get as a gift) as many integers as possible. If he can do this in differents ways, he selects the cheapest of them.For each $$$s$$$ from $$$1$$$ to $$$n$$$, find how many coins will Vasya spend if only the first $$$s$$$ segments will be available.

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 the single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of segments in the shop. Each of next $$$n$$$ lines contains three integers $$$l_i$$$, $$$r_i$$$, $$$c_i$$$ ($$$1 \leq l_i \leq r_i \leq 10^9, 1 \leq c_i \leq 10^9$$$) — the ends of the $$$i$$$-th segments and its cost. It is guaranteed that the total sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case output $$$n$$$ integers: the $$$s$$$-th ($$$1 \leq s \leq n$$$) of them should be the number of coins Vasia will spend in the shop if only the first $$$s$$$ segments will be available.

NoteIn the first test case if $$$s = 1$$$ then Vasya can buy only the segment $$$[2, 4]$$$ for $$$20$$$ coins and get $$$3$$$ integers.The way to get $$$7$$$ integers for $$$42$$$ coins in case $$$s = 2$$$ is described in the statement.In the second test case note, that there can be the same segments in the shop.

import std;

alias Segment = Tuple!(uint, "left", uint, "right", uint, "cost");

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s\n"(n); return n; }();

        immutable Segment[] stock = (){
            Segment[] ret = new Segment[n];

            foreach (ref tup; ret)
                readf!"%s %s %s\n"(tup.expand);

            return ret.assumeUnique;
        }();

        enum cost = (size_t a, size_t b){
            if (a == b)
                return stock[a].cost;
            return stock[a].cost + stock[b].cost;
        };

        enum length = (size_t a, size_t b) {
            assert(stock[a].left <= stock[b].right);
            return stock[b].right - stock[a].left;
        };

        size_t cheapestLow, cheapestHigh;
        writeln(cost(0, 0));

        alias T = Tuple!(size_t, "smol", size_t, "big");
        T prev = T(0, 0);
        foreach (s; 1 .. n) {
            immutable now = stock[s];
            T[] options = [prev, T(s, s)];

            if (now.left <= stock[cheapestHigh].right)
                options ~= T(s, cheapestHigh);

            if (now.right >= stock[cheapestLow].left)
                options ~= T(cheapestLow, s);

            enum better = (T a, T b) {
                assert(stock[a.big].right >= stock[a.smol].left);
                assert(stock[b.big].right >= stock[b.smol].left);

                auto d1 = length(a.expand);
                auto d2 = length(b.expand);

                auto c1 = cost(a.expand);
                auto c2 = cost(b.expand);

                if (d1 != d2)
                    return d1 > d2;
                return c1 < c2;
            };

            auto ans = options.sort!((a, b) => better(a, b));

            //foreach (tup; ans)
                //writefln("[%1$s, %2$s] -> [%4$s, %5$s]", stock[tup.smol].expand, stock[tup.big].expand);

            assert(length(ans[0].expand) >= length(ans[1].expand));

            writeln(cost(ans[0].expand));

            prev = ans[0];

            if (now.left < stock[cheapestLow].left ||
                now.left == stock[cheapestLow].left && now.cost < stock[cheapestLow].cost)
                cheapestLow = s;

            if (now.right > stock[cheapestHigh].right ||
                now.right == stock[cheapestHigh].right && now.cost < stock[cheapestHigh].cost)
                cheapestHigh = s;
        }

    }
}
// ""

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 solve() {
    int N = readln.chomp.to!int;
    long[] L = new long[N],
           R = new long[N],
           C = new long[N];
    long[Tuple!(long, long)] P;
    for (int i = 0; i < N; i++) {
        scanf("%lld %lld %lld\n", &L[i], &R[i], &C[i]);
    }
    long m = long.max, M = 0;
    long mc = long.max, Mc = long.max;
    for (int s = 0; s < N; s++) {
        auto key = tuple(L[s], R[s]);
        if (key in P) {
            P[key] = min(P[key], C[s]);
        } else {
            P[key] = C[s];
        }
        long ans = long.max;
        if (L[s] <= m) {
            mc = (L[s] == m ? min(mc, C[s]) : C[s]);
            m = L[s];
        }
        if (M <= R[s]) {
            Mc = (R[s] == M ? min(Mc, C[s]) : C[s]);
            M = R[s];
        }
        ans = min(ans, mc + Mc);
        if (tuple(m, M) in P) {
            ans = min(ans, P[tuple(m, M)]);
        }
        writeln(ans);
    }
}

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

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)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto l = new long[](n);
		auto r = new long[](n);
		auto c = new long[](n);
		foreach (i; 0..n)
		{
			l[i] = RD;
			r[i] = RD;
			c[i] = RD;
		}

		int li, ri, xi;
		ans[ti] ~= c[0];
		foreach (i; 1..n)
		{
			if (l[i] == l[li])
			{
				if (c[i] < c[li])
					li = i;
			}
			else if (l[i] < l[li])
				li = i;

			if (r[i] == r[ri])
			{
				if (c[i] < c[ri])
					ri = i;
			}
			else if (r[i] > r[ri])
				ri = i;

			if (r[i] - l[i] == r[xi] - l[xi])
			{
				if (c[i] < c[xi])
					xi = i;
			}
			else if (r[i] - l[i] > r[xi] - l[xi])
				xi = i;

			debug writeln("li:", li, " ri:", ri, " xi:", xi);
			long tmp;
			if (r[xi] - l[xi] > r[ri] - l[li])
				tmp = c[xi];
			else if (r[xi] - l[xi] == r[ri] - l[li])
				tmp = min(c[xi], c[li] + c[ri]);
			else
				tmp = c[li] + c[ri];
			ans[ti] ~= tmp;
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto lo = new int [n];
		auto hi = new int [n];
		auto cost = new int [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s %s") (lo[i], hi[i], cost[i]);
		}
		readln;

		auto f = tuple (int.max, -1);
		auto g = tuple (int.max, -1);
		auto h = tuple (int.max, int.max, -1);
		foreach (i; 0..n)
		{
			f = min (f, tuple (+lo[i], cost[i]));
			g = min (g, tuple (-hi[i], cost[i]));
			h = min (h, tuple (+lo[i], -hi[i], cost[i]));
			int res = f[1] + g[1];
			if (h[0] == f[0] && h[1] == g[0])
			{
				res = min (res, h[2]);
			}
			writeln (res);
		}
	}
}

import std;

alias Segment = Tuple!(int, "left", int, "right", int, "cost");

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s\n"(n); return n; }();

        immutable Segment[] inventory = (){
            Segment[] ret;
            ret.reserve(n);

            foreach (_; 0 .. n) {
                int left, right, cost;
                readf!"%s %s %s\n"(left, right, cost);
                ret ~= Segment(left, right, cost);
            }
            return ret.assumeUnique;
        }();

        enum cost = (size_t l, size_t r) {
            if (l != r)
                return inventory[l].cost + inventory[r].cost;
            else
                return inventory[l].cost;
        };

        alias T = Tuple!(size_t, "small", size_t, "big");
        auto prev = T(0, 0);

        writeln(cost(0, 0));
        foreach (s; 1 .. n) {
            T[] options = [
                T(s, prev.big),
                T(prev.small, s),
                T(s, s),
                prev
            ];

            enum better = (T a, T b) {
                auto d1 = inventory[a.big].right - inventory[a.small].left;
                auto d2 = inventory[b.big].right - inventory[b.small].left;

                auto c1 = cost(a.expand);
                auto c2 = cost(b.expand);

                if (d1 != d2)
                    return d1 > d2;
                return c1 < c2;
            };

            auto best = options.sort!((a, b) => better(a, b));

            writeln(cost(best.front.expand));
            prev = best.front;
        }

    }
}
// ""

import std;

alias Segment = Tuple!(uint, "left", uint, "right", uint, "cost");

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s\n"(n); return n; }();

        immutable Segment[] inventory = (){
            Segment[] ret;
            ret.reserve(n);

            foreach (_; 0 .. n) {
                uint left, right, cost;
                readf!"%s %s %s\n"(left, right, cost);
                ret ~= Segment(left, right, cost);
            }
            return ret.assumeUnique;
        }();

        enum cost = (size_t l, size_t r) {
            if (l != r)
                return inventory[l].cost + inventory[r].cost;
            else
                return inventory[l].cost;
        };

        alias T = Tuple!(size_t, "small", size_t, "big");
        auto prev = T(0, 0);

        writeln(cost(0, 0));
        foreach (s; 1 .. n) {
            T now = prev;

            if (inventory[s].left < inventory[prev.small].left)
                now.small = s;

            if (inventory[s].right > inventory[prev.small].right)
                now.big = s;

            if (inventory[s].left == inventory[now.small].left && cost(s, now.big) < cost(now.expand))
                now.small = s;

            if (inventory[s].right == inventory[now.big].right && cost(s, now.small) < cost(now.expand))
                now.big = s;

            writeln(cost(now.expand));
            prev = now;
        }

    }
}
// ""

import std;

alias Segment = Tuple!(uint, "left", uint, "right", uint, "cost");

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s\n"(n); return n; }();

        immutable Segment[] inventory = (){
            Segment[] ret;
            ret.reserve(n);

            foreach (_; 0 .. n) {
                uint left, right, cost;
                readf!"%s %s %s\n"(left, right, cost);
                ret ~= Segment(left, right, cost);
            }
            return ret.assumeUnique;
        }();

        enum cost = (size_t l, size_t r) {
            if (l != r)
                return inventory[l].cost + inventory[r].cost;
            else
                return inventory[l].cost;
        };

        size_t left = 0, right = 0;
        writeln(cost(left, right));
        size_t biggest, smallest;

        foreach (s; 1 .. n) {
            if (inventory[s].left < inventory[smallest].left)
                smallest = s;
            if (inventory[s].right > inventory[biggest].right)
                biggest = s;

            if (inventory[s].left < inventory[left].left)
                left = s;
            if (inventory[s].right > inventory[right].right)
                right = s;

            immutable v1 = inventory[s].right - inventory[s].left;
            immutable v2 = inventory[right].right - inventory[left].left;

            if (v1 > v2 ||
                v1 == v2 && cost(s, s) < cost(left, right)) {
                immutable q = inventory[s].right - inventory[smallest].left;
                immutable r = inventory[biggest].right - inventory[s].left;

                if (q > r || q == r && cost(s, smallest) < cost(s, biggest))
                    left = smallest, right = s;
                else
                    right = biggest, left = s;
            }

            writeln(cost(left, right));
        }
    }
}
// ""

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 solve() {
    int N = readln.chomp.to!int;
    long[] L = new long[N],
           R = new long[N],
           C = new long[N];
    long[Tuple!(long, long)] P;
    for (int i = 0; i < N; i++) {
        scanf("%lld %lld %lld\n", &L[i], &R[i], &C[i]);
    }
    long m = long.max, M = 0;
    long mc = long.max, Mc = long.max;
    for (int s = 0; s < N; s++) {
        P[tuple(L[s], R[s])] = C[s];
        long ans = long.max;
        if (L[s] <= m) {
            mc = (L[s] == m ? min(mc, C[s]) : C[s]);
            m = L[s];
        }
        if (M <= R[s]) {
            Mc = (R[s] == M ? min(Mc, C[s]) : C[s]);
            M = R[s];
        }
        ans = min(ans, mc + Mc);
        if (tuple(m, M) in P) {
            ans = min(ans, P[tuple(m, M)]);
        }
        writeln(ans);
    }
}

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