You like playing chess tournaments online.In your last tournament you played $$$n$$$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $$$0$$$ points. When you win you get $$$1$$$ or $$$2$$$ points: if you have won also the previous game you get $$$2$$$ points, otherwise you get $$$1$$$ point. If you win the very first game of the tournament you get $$$1$$$ point (since there is not a "previous game").The outcomes of the $$$n$$$ games are represented by a string $$$s$$$ of length $$$n$$$: the $$$i$$$-th character of $$$s$$$ is W if you have won the $$$i$$$-th game, while it is L if you have lost the $$$i$$$-th game.After the tournament, you notice a bug on the website that allows you to change the outcome of at most $$$k$$$ of your games (meaning that at most $$$k$$$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.Compute the maximum score you can get by cheating in the optimal way.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t \le 20,000$$$) — the number of test cases. The description of the test cases follows. The first line of each testcase contains two integers $$$n, k$$$ ($$$1\le n\le 100,000$$$, $$$0\le k\le n$$$) – the number of games played and the number of outcomes that you can change. The second line contains a string $$$s$$$ of length $$$n$$$ containing only the characters W and L. If you have won the $$$i$$$-th game then $$$s_i=\,$$$W, if you have lost the $$$i$$$-th game then $$$s_i=\,$$$L. It is guaranteed that the sum of $$$n$$$ over all testcases does not exceed $$$200,000$$$.

For each testcase, print a single integer – the maximum score you can get by cheating in the optimal way.

8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW

NoteExplanation of the first testcase. Before changing any outcome, the score is $$$2$$$. Indeed, you won the first game, so you got $$$1$$$ point, and you won also the third, so you got another $$$1$$$ point (and not $$$2$$$ because you lost the second game).An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $$$7=1+2+2+2$$$: $$$1$$$ point for the first game and $$$2$$$ points for the second, third and fourth game.Explanation of the second testcase. Before changing any outcome, the score is $$$3$$$. Indeed, you won the fourth game, so you got $$$1$$$ point, and you won also the fifth game, so you got $$$2$$$ more points (since you won also the previous game).An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $$$11 = 1+2+2+2+2+2$$$: $$$1$$$ point for the first game and $$$2$$$ points for all the other games.

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

void play(){
    int n, k;
    n = rd!int, k = rd!int;
    dchar[] arr = rd!(dchar[]);
    auto g1 = redBlackTree!(true, int);
    auto g2 = redBlackTree!(true, int);
    int streak = 0, take = 0, w = 0;
    if(arr[0] == 'L') --streak;
    foreach(i; 0..n){
        if(arr[i] == 'W'){
            if(streak > 0){
                ++streak;
                if(streak % 2){
                    g1.insert(streak);
                }else{
                    g2.insert(streak);
                }
            }
            streak = 0;
            ++w;
            if(i > 0 && arr[i-1] == 'W') ++w;
        }else{
            streak += 2;
            ++take;
        }
    }
    if(!w && streak > 0 && k > 0){
        streak -= 1;
        w = 1;
        k -= 1;
    }
    if(streak > 0){
        if(streak % 2){
            g1.insert(streak);
        }else{
            g2.insert(streak);
        }
    }
    /* writeln(g1, g2); */

    ll pt = w;
    take = min(take, k);
    while(g1.length && take > 0){
        ll top = g1.front;
        if(top/2 <= take){
            pt += top;
            take -= top/2;
        }else{
            pt += take*2;
            take = 0;
        }
        g1.removeFront;
    }
    while(g2.length && take > 0){
        ll top = g2.front;
        if(top/2 <= take){
            pt += top;
            take -= top/2;
        }else{
            pt += take*2;
            take = 0;
        }
        g2.removeFront;
    }
    writeln(pt);
}

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

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = RedBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }

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, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.strip.map !(q{a == 'W'}).array;
		auto zeroes = s.count (0);
		auto ones = s.count (1);
		if (ones == 0)
		{
			writeln (max (0, k * 2 - 1));
			continue;
		}
		int start0 = 0;
		while (s.front == 0)
		{
			start0 += 1;
			s.popFront ();
		}
		int finish0 = 0;
		while (s.back == 0)
		{
			finish0 += 1;
			s.popBack ();
		}

		auto h = s.group.filter !(q{a[0] == 1}).count.to !(int);
		auto res = sum (s) * 2 - h;
		auto g = s.group.filter !(q{a[0] == 0}).map !(q{a[1]}).array;
		g.sort;
		while (k > 0 && !g.empty)
		{
			auto d = min (k, g.front);
			k -= d;
			res += 2 * d + (d == g.front);
			g.popFront ();
		}
		if (k > 0 && finish0 > 0)
		{
			auto d = min (k, finish0);
			k -= d;
			res += 2 * d;
		}
		if (k > 0 && start0 > 0)
		{
			auto d = min (k, start0);
			k -= d;
			res += 2 * d;
		}
		writeln (res);
	}
}

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();
        const K = readInt();
        const S = readToken();

        int ans;
        int k = K;
        chmin(k, cast(int)(S.count('L')));
        if (S.count('W') == 0) {
          ans = max(2 * k - 1, 0);
        } else {
          foreach (i; 0 .. N) {
            if (S[i] == 'W') {
              ans += (i - 1 >= 0 && S[i - 1] == 'W') ? 2 : 1;
            }
          }
          int[] ds;
          for (int i = 0, j; i < N; i = j) {
            for (j = i; j < N && S[i] == S[j]; ++j) {}
            if (S[i] == 'L' && !(i == 0 || j == N)) {
              ds ~= j - i;
            }
          }
          ds.sort;
          foreach (d; ds) {
            if (k >= d) {
              k -= d;
              ans += 2 * d + 1;
            }
          }
          ans += 2 * k;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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 k = RD!int;
		auto s = RD!string;

		auto cnt = new int[](n+1);
		int streak, lc;
		bool start;
		foreach (i; 0..n)
		{
			if (s[i] == 'W')
			{
				start = true;
				++cnt[streak];
				streak = 0;
				if (i == 0)
					++ans[ti];
				else if (s[i-1] == 'W')
					ans[ti] += 2;
				else
					++ans[ti];
			}
			else
			{
				if (start)
					++streak;
				++lc;
			}
		}
		debug writeln("ans:", ans[ti]);
		debug writeln(cnt);
		k = min(k, lc);

		foreach (i; 1..n+1)
		{
			auto c = min(k / i, cnt[i]);
			k -= i * c;
			if (c != 0)
				ans[ti] += c * (i * 2 + 1);
			debug writeln("k:", k, " ans:", ans[ti]);
		}
		if (start)
			ans[ti] += k * 2;
		else if (k >= 1)
			ans[ti] += (k-1) * 2 + 1;
	}

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

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

void play(){
    int n, k;
    n = rd!int, k = rd!int;
    dchar[] arr = rd!(dchar[]);
    auto gaps = redBlackTree!(true, tup);
    int streak = 0, take = 0, w = 0;
    if(arr[0] == 'L') --streak;
    foreach(i; 0..n){
        if(arr[i] == 'W'){
            ll val = streak + 1;
            if(streak > 0){ gaps.insert(tup(val/2, -val)); }
            streak = 0;
            ++w;
            if(i > 0 && arr[i-1] == 'W') ++w;
        }else{
            streak += 2;
            ++take;
        }
    }
    if(streak) gaps.insert(tup(streak/2, -streak));
    /* writeln(gaps); */

    ll pt = w;
    take = min(take, k);
    while(gaps.length && take > 0){
        ll top = - gaps.front[1];
        if(top/2 <= take){
            pt += top;
            take -= top/2;
        }else{
            pt += take*2;
            take = 0;
        }
        gaps.removeFront;
    }
    writeln(pt);
}

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

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = RedBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }

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

void play(){
    int n, k;
    n = rd!int, k = rd!int;
    dchar[] arr = rd!(dchar[]);
    auto g1 = redBlackTree!(true, int);
    auto g2 = redBlackTree!(true, int);
    int streak = 0, take = 0, w = 0;
    if(arr[0] == 'L') --streak;
    foreach(i; 0..n){
        if(arr[i] == 'W'){
            if(streak > 0){
                ++streak;
                if(streak % 2){
                    g1.insert(streak);
                }else{
                    g2.insert(streak);
                }
            }
            streak = 0;
            ++w;
            if(i > 0 && arr[i-1] == 'W') ++w;
        }else{
            streak += 2;
            ++take;
        }
    }
    if(!w && streak > 0 && k > 0){
        streak -= 1;
        w = 1;
        k -= 1;
    }
    if(streak > 0){
        if(streak % 2){
            g1.insert(streak);
        }else{
            g2.insert(streak);
        }
    }
    writeln(g1, g2);

    ll pt = w;
    take = min(take, k);
    while(g1.length && take > 0){
        ll top = g1.front;
        if(top/2 <= take){
            pt += top;
            take -= top/2;
        }else{
            pt += take*2;
            take = 0;
        }
        g1.removeFront;
    }
    while(g2.length && take > 0){
        ll top = g2.front;
        if(top/2 <= take){
            pt += top;
            take -= top/2;
        }else{
            pt += take*2;
            take = 0;
        }
        g2.removeFront;
    }
    writeln(pt);
}

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

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = RedBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }

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

void play(){
    int n, k;
    n = rd!int, k = rd!int;
    dchar[] arr = rd!(dchar[]);
    auto g1 = redBlackTree!(true, int);
    auto g2 = redBlackTree!(true, int);
    int streak = 0, take = 0, w = 0;
    if(arr[0] == 'L') --streak;
    foreach(i; 0..n){
        if(arr[i] == 'W'){
            if(streak > 0){
                ++streak;
                if(streak % 2){
                    g1.insert(streak);
                }else{
                    g2.insert(streak);
                }
            }
            streak = 0;
            ++w;
            if(i > 0 && arr[i-1] == 'W') ++w;
        }else{
            streak += 2;
            ++take;
        }
    }
    if(streak > 0){
        if(streak % 2){
            g1.insert(streak);
        }else{
            g2.insert(streak);
        }
    }
    /* writeln(g1, g2); */

    ll pt = w;
    take = min(take, k);
    while(g1.length && take > 0){
        ll top = g1.front;
        if(top/2 <= take){
            pt += top;
            take -= top/2;
        }else{
            pt += take*2;
            take = 0;
        }
        g1.removeFront;
    }
    while(g2.length && take > 0){
        ll top = g2.front;
        if(top/2 <= take){
            pt += top;
            take -= top/2;
        }else{
            pt += take*2;
            take = 0;
        }
        g2.removeFront;
    }
    writeln(pt);
}

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

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = RedBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }

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, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.strip.map !(q{a == 'W'}).array;
		auto zeroes = s.count (0);
		auto ones = s.count (1);
		if (ones == 0)
		{
			writeln (max (0, k * 2 - 1));
			continue;
		}
		int start0 = 0;
		while (s.front == 0)
		{
			start0 += 1;
			s.popFront ();
		}
		int finish0 = 0;
		while (s.back == 0)
		{
			finish0 += 1;
			s.popBack ();
		}

		auto h = s.group.filter !(q{a[0] == 1}).count.to !(int);
		auto res = sum (s) * 2 - h;
		auto g = s.group.filter !(q{a[0] == 0}).map !(q{a[1]}).array;
		g.sort;
		while (k > 0 && !g.empty)
		{
			auto d = min (k, g.front);
			k -= d;
			res += 2 * d + (d == g.front);
			g.popFront ();
		}
		if (k > 0 && finish0 > 0)
		{
			auto d = min (k, finish0);
			k -= d;
			res += 2 * d;
		}
		if (k > 0 && start0 > 0)
		{
			auto d = min (k, start0);
			k -= d;
			res += 2 * d - 1 + (d == start0);
		}
		writeln (res);
	}
}

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, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.strip.map !(q{a == 'W'}).array;
		auto zeroes = s.count (0);
		auto ones = s.count (1);
		if (ones == 0)
		{
			writeln (max (0, k * 2 - 1));
			continue;
		}
		int start0 = 0;
		while (s.front == 0)
		{
			start0 += 1;
			s.popFront ();
		}
		int finish0 = 0;
		while (s.back == 0)
		{
			finish0 += 1;
			s.popBack ();
		}

		auto h = s.group.filter !(q{a[0] == 1}).count.to !(int);
		auto res = sum (s) * 2 - h;
		auto g = s.group.filter !(q{a[0] == 0}).map !(q{a[1]}).array;
		g.sort;
		while (k > 0 && !g.empty)
		{
			auto d = min (k, g.front);
			k -= d;
			res += 2 * d + (d == g.front);
			g.popFront ();
		}
		if (k > 0 && finish0 > 0)
		{
			auto d = min (k, finish0);
			k -= d;
			res += 2 * d;
		}
		if (k > 0 && start0 > 0)
		{
			auto d = min (k, start0);
			k -= d;
			res += 2 * d - (d != start0);
		}
		writeln (res);
	}
}

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, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.strip.map !(q{a == 'W'}).array;
		auto zeroes = s.count (0);
		auto ones = s.count (1);
		if (ones == 0)
		{
			writeln (max (0, k * 2 - 1));
			continue;
		}
		int start0 = 0;
		while (s.front == 0)
		{
			start0 += 1;
			s.popFront ();
		}
		int finish0 = 0;
		while (s.back == 0)
		{
			finish0 += 1;
			s.popBack ();
		}

		auto h = s.group.filter !(q{a[0] == 1}).count.to !(int);
		auto res = sum (s) * 2 - h;
		auto g = s.group.filter !(q{a[0] == 0}).map !(q{a[1]}).array;
		g.sort;
		while (k > 0 && !g.empty)
		{
			auto d = min (k, g.front);
			k -= d;
			res += 2 * d + (d == g.front);
			g.popFront ();
		}
		if (k > 0 && finish0 > 0)
		{
			auto d = min (k, finish0);
			k -= d;
			res += 2 * d;
		}
		if (k > 0 && start0 > 0)
		{
			auto d = min (k, start0);
			k -= d;
			res += 2 * d - (d == start0);
		}
		writeln (res);
	}
}

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, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.strip.map !(q{a == 'W'}).array;
		writeln (s);
		auto zeroes = s.count (0);
		auto ones = s.count (1);
		if (ones == 0)
		{
			writeln (max (0, k * 2 - 1));
			continue;
		}
		int start0 = 0;
		while (s.front == 0)
		{
			start0 += 1;
			s.popFront ();
		}
		int finish0 = 0;
		while (s.back == 0)
		{
			finish0 += 1;
			s.popBack ();
		}

		auto h = s.group.filter !(q{a[0] == 1}).count.to !(int);
		auto res = sum (s) * 2 - h;
		auto g = s.group.filter !(q{a[0] == 0}).map !(q{a[1]}).array;
		g.sort;
		while (k > 0 && !g.empty)
		{
			auto d = min (k, g.front);
			k -= d;
			res += 2 * d + (d == g.front);
			g.popFront ();
		}
		if (k > 0 && finish0 > 0)
		{
			auto d = min (k, finish0);
			k -= d;
			res += 2 * d;
		}
		if (k > 0 && start0 > 0)
		{
			auto d = min (k, start0);
			k -= d;
			res += 2 * d;
		}
		writeln (res);
	}
}


Harry, upon inquiring Helena Ravenclaw's ghost, came to know that she told Tom Riddle or You-know-who about Rowena Ravenclaw's diadem and that he stole it from her. Harry thought that Riddle would have assumed that he was the only one to discover the Room of Requirement and thus, would have hidden it there. So Harry is trying to get inside the Room of Requirement to destroy the diadem as he knows that it is a horcrux.But he has to answer a puzzle in order to enter the room. He is given n objects, numbered from 1 to n. Some of the objects have a parent object, that has a lesser number. Formally, object i may have a parent object parenti such that parenti < i.There is also a type associated with each parent relation, it can be either of type 1 or type 2. Type 1 relation means that the child object is like a special case of the parent object. Type 2 relation means that the second object is always a part of the first object and all its special cases.Note that if an object b is a special case of object a, and c is a special case of object b, then c is considered to be a special case of object a as well. The same holds for parts: if object b is a part of a, and object c is a part of b, then we say that object c is a part of a. Also note, that if object b is a part of a, and object c is a special case of a, then b is a part of c as well.An object is considered to be neither a part of itself nor a special case of itself.Now, Harry has to answer two type of queries:  1 u v: he needs to tell if object v is a special case of object u.  2 u v: he needs to tell if object v is a part of object u.

First line of input contains the number n (1 ≤ n ≤ 105), the number of objects.  Next n lines contain two integer parenti and typei ( - 1 ≤ parenti < i parenti ≠ 0,  - 1 ≤ typei ≤ 1), implying that the i-th object has the parent parenti. (If typei = 0, this implies that the object i is a special case of object parenti. If typei = 1, this implies that the object i is a part of object parenti). In case the i-th object has no parent, both parenti and typei are -1. Next line contains an integer q (1 ≤ q ≤ 105), the number of queries.  Next q lines each represent a query having three space separated integers typei, ui, vi (1 ≤ typei ≤ 2, 1 ≤ u, v ≤ n).

Output will contain q lines, each containing the answer for the corresponding query as "YES" (affirmative) or "NO" (without quotes). You can output each letter in any case (upper or lower).

NoteIn test case 1, as object 2 is a special case of object 1 and object 3 is a special case of object 2, this makes object 3 a special case of object 1.In test case 2, as object 2 is a special case of object 1 and object 1 has object 3, this will mean that object 2 will also have object 3. This is because when a general case (object 1) has object 3, its special case (object 2) will definitely have object 3.

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

int N;
int[][] P;

int[][][] graph;
int zeit;
int[][] rs, dis, fin;

void dfs(int s, int r, int u) {
  rs[s][u] = r;
  dis[s][u] = zeit++;
  foreach (v; graph[s][u]) {
    dfs(s, r, v);
  }
  fin[s][u] = zeit++;
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      P = new int[][](2, N);
      foreach (u; 0 .. N) {
        const p = readInt() - 1;
        const t = readInt();
        P[0][u] = P[1][u] = -1;
        if (t != -1) {
          P[t][u] = p;
        }
      }

      graph = new int[][][](2, N);
      foreach (s; 0 .. 2) {
        foreach (u; 0 .. N) {
          if (P[s][u] != -1) {
            graph[s][P[s][u]] ~= u;
          }
        }
      }

      rs = new int[][](2, N);
      dis = new int[][](2, N);
      fin = new int[][](2, N);
      foreach (s; 0 .. 2) {
        rs[s][] = -1;
        zeit = 0;
        foreach (u; 0 .. N) {
          if (rs[s][u] == -1) {
            dfs(s, u, u);
          }
        }
      }
      debug {
        writeln("rs = ", rs);
        writeln("dis = ", dis);
        writeln("fin = ", fin);
      }

      const Q = readInt();
      foreach (q; 0 .. Q) {
        const t = readInt();
        const u = readInt() - 1;
        const v = readInt() - 1;
        bool ans;
        if (t == 1) {
          ans = (dis[0][u] < dis[0][v] && fin[0][v] < fin[0][u]);
        } else {
          foreach (r; [rs[1][v], rs[0][u]]) {
            ans = ans || (dis[1][r] < dis[1][v] && fin[1][v] < fin[1][r] && dis[0][r] <= dis[0][u] && fin[0][u] <= fin[0][r]);
          }
        }
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}


You are given an undirected weighted connected graph with $$$n$$$ vertices and $$$m$$$ edges without loops and multiple edges.The $$$i$$$-th edge is $$$e_i = (u_i, v_i, w_i)$$$; the distance between vertices $$$u_i$$$ and $$$v_i$$$ along the edge $$$e_i$$$ is $$$w_i$$$ ($$$1 \le w_i$$$). The graph is connected, i. e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph.A minimum spanning tree (MST) in case of positive weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges).You can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by $$$1$$$. You can increase the weight of each edge multiple (possibly, zero) times.Suppose that the initial MST cost is $$$k$$$. Your problem is to increase weights of some edges with minimum possible number of operations in such a way that the cost of MST in the obtained graph remains $$$k$$$, but MST is unique (it means that there is only one way to choose MST in the obtained graph).Your problem is to calculate the minimum number of operations required to do it.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges in the initial graph. The next $$$m$$$ lines contain three integers each. The $$$i$$$-th line contains the description of the $$$i$$$-th edge $$$e_i$$$. It is denoted by three integers $$$u_i, v_i$$$ and $$$w_i$$$ ($$$1 \le u_i, v_i \le n, u_i \ne v_i, 1 \le w \le 10^9$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices connected by the $$$i$$$-th edge and $$$w_i$$$ is the weight of this edge. It is guaranteed that the given graph doesn't contain loops and multiple edges (i.e. for each $$$i$$$ from $$$1$$$ to $$$m$$$ $$$u_i \ne v_i$$$ and for each unordered pair of vertices $$$(u, v)$$$ there is at most one edge connecting this pair of vertices). It is also guaranteed that the given graph is connected.

Print one integer — the minimum number of operations to unify MST of the initial graph without changing the cost of MST.

NoteThe picture corresponding to the first example: You can, for example, increase weight of the edge $$$(1, 6)$$$ or $$$(6, 3)$$$ by $$$1$$$ to unify MST.The picture corresponding to the last example: You can, for example, increase weights of edges $$$(1, 5)$$$ and $$$(2, 4)$$$ by $$$1$$$ to unify MST.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto pq = new BinaryHeap!(Array!(Tuple!(int, int, long)), "a[2] > b[2]");
    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        pq.insert(tuple(s[0]-1, s[1]-1, s[2].to!long));
    }
    auto uf = new UnionFind(N);
    int cnt = 0;
    long ans = 0;
    long last_w = -1;

    while (cnt < N - 1) {
        Tuple!(int, int, long)[] E1;
        Tuple!(int, int, long)[] E2;
        long w = pq.front[2];
        while (!pq.empty && pq.front[2] == w) {
            E1 ~= pq.front;
            pq.removeFront;
        }
        foreach (e; E1) {
            int u = e[0];
            int v = e[1];
            if (uf.find(u) == uf.find(v)) {

            } else {
                E2 ~= e;
            }
        }
        foreach (e; E2) {
            int u = e[0];
            int v = e[1];
            if (uf.find(u) == uf.find(v)) {
                ans += 1;
            } else {
                cnt += 1;
                uf.unite(u, v);
            }
        }
    }

    ans.writeln;
}

class UnionFind {
    int N;
    int[] table;

    this(int n) {
        N = n;
        table = new int[](N);
        fill(table, -1);
    }

    int find(int x) {
        return table[x] < 0 ? x : (table[x] = find(table[x]));
    }

    void unite(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        if (table[x] > table[y]) swap(x, y);
        table[x] += table[y];
        table[y] = x;
    }
}


Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — coordinates of cube's vertex (a single line contains coordinates of a single vertex, each vertex is written exactly once), put the paper on the table and left. While Peter was away, his little brother Nick decided to play with the numbers on the paper. In one operation Nick could swap some numbers inside a single line (Nick didn't swap numbers from distinct lines). Nick could have performed any number of such operations.When Peter returned and found out about Nick's mischief, he started recollecting the original coordinates. Help Peter restore the original position of the points or else state that this is impossible and the numbers were initially recorded incorrectly.

Each of the eight lines contains three space-separated integers — the numbers written on the piece of paper after Nick's mischief. All numbers do not exceed 106 in their absolute value.

If there is a way to restore the cube, then print in the first line "YES". In each of the next eight lines print three integers — the restored coordinates of the points. The numbers in the i-th output line must be a permutation of the numbers in i-th input line. The numbers should represent the vertices of a cube with non-zero length of a side. If there are multiple possible ways, print any of them. If there is no valid way, print "NO" (without the quotes) in the first line. Do not print anything else.

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

immutable int MAX_N = 8;
immutable int MAX_D = 3;

long dist (int [MAX_D] p, int [MAX_D] q)
{
	long res = 0L;
	foreach (j; 0..MAX_D)
	{
        	long cur = q[j] - p[j];
        	res += cur * cur;
	}
	return res;
}

int [MAX_D] [] build (int [MAX_D] [] a)
{
	long d01 = dist (a[0], a[1]);
	if (d01 == 0L)
	{
		return null;
	}
	long d02 = dist (a[0], a[2]);
	if (d02 != d01)
	{
		return null;
	}
	long d03 = dist (a[0], a[3]);
	if (d03 != d01)
	{
		return null;
	}
	long d12 = dist (a[1], a[2]);
	if (d12 != d01 * 2)
	{
		return null;
	}
	long d13 = dist (a[1], a[3]);
	if (d13 != d12)
	{
		return null;
	}
	long d23 = dist (a[2], a[3]);
	if (d23 != d12)
	{
		return null;
	}

	int [MAX_D] [] f;
	foreach (i; 0..MAX_N)
	{
		int [MAX_D] c = a[0];
		if (i & 1)
		{
			c[] += a[1][] - a[0][];
		}
		if (i & 2)
		{
			c[] += a[2][] - a[0][];
		}
		if (i & 4)
		{
			c[] += a[3][] - a[0][];
		}
		f ~= c;
	}
	debug {writefln ("Candidate:\n%(%(%s %)\n%)", f);}

	int [MAX_D] [] g = a[MAX_N / 2..$].dup;
search_loop:
	foreach (i; [3, 5, 6, 7])
	{
		foreach (ref c; g)
		{
			do
			{
				if (c == f[i])
				{
					c[] = int.min;
					continue search_loop;
				}
			}
			while (nextPermutation (c[]));
		}
		return null;
	}

	return f;
}

void answer (int [MAX_D] [] f, int [MAX_D] [] c)
{
	writeln ("YES");
answer_loop:
	do
	{
local_loop:
		foreach (i; 0..MAX_N)
		{
			sort (c[i][]);
			do
			{
				if (f[i][] == c[i][])
				{
					continue local_loop;
				}
			}
			while (nextPermutation (c[i][]));
			continue answer_loop;
		}
		writefln ("%(%(%s %)\n%)", f);
		return;
	}
	while (nextPermutation (f));
	assert (false);
}

void main ()
{
	int [MAX_D] [] a = new int [MAX_D] [MAX_N];
	foreach (i; 0..MAX_N)
	{
		foreach (j; 0..MAX_D)
		{
			readf (" %s", &a[i][j]);
		}
	}

	int [MAX_D] [] c = a.dup;
	foreach (i; 0..MAX_N)
	{
		sort (a[i][]);
	}
	sort (a);

	int [MAX_D] [] b = new int [MAX_D] [MAX_N / 2];
	foreach (i; 0..MAX_N / 2)
	{
		foreach (j; 0..MAX_D)
		{
			b[i][j] = int.min;
		}
	}

	do
	{
		if (b[] == a[0..MAX_N / 2])
		{
			continue;
		}
		b[] = a[0..MAX_N / 2];
		do
		{
			do
			{
				do
				{
					do
					{
						auto f = build (a);
						if (f !is null)
						{
							answer (f, c);
							return;
						}
					}
					while (nextPermutation (a[3][]));
				}
				while (nextPermutation (a[2][]));
			}
			while (nextPermutation (a[1][]));
		}
		while (nextPermutation (a[0][]));
	}
	while (nextPermutation (a[1..$]));

	writeln ("NO");
}

// the following is a Phobos snipped with "ref" stripped
// library code start
bool nextPermutation(alias less="a<b", BidirectionalRange)
                    (BidirectionalRange range)
    if (isBidirectionalRange!BidirectionalRange &&
        hasSwappableElements!BidirectionalRange)
{
    // Ranges of 0 or 1 element have no distinct permutations.
    if (range.empty) return false;

    auto i = retro(range);
    auto last = i.save;

    // Find last occurring increasing pair of elements
    size_t n = 1;
    for (i.popFront(); !i.empty; i.popFront(), last.popFront(), n++)
    {
        if (binaryFun!less(i.front, last.front))
            break;
    }

    if (i.empty) {
        // Entire range is decreasing: it's lexicographically the greatest. So
        // wrap it around.
        range.reverse();
        return false;
    }

    // Find last element greater than i.front.
    auto j = find!((a) => binaryFun!less(i.front, a))(
                   takeExactly(retro(range), n));

    assert(!j.empty);   // shouldn't happen since i.front < last.front
    swap(i.front, j.front);
    reverse(takeExactly(retro(range), n));

    return true;
}
// library code end

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

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

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

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

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

int[][] PERM3S = [
	[ 0, 1, 2 ],
	[ 0, 2, 1 ],
	[ 1, 0, 2 ],
	[ 1, 2, 0 ],
	[ 2, 0, 1 ],
	[ 2, 1, 0 ],
];

long dot(long[] a, long[] b) {
	long ret;
	foreach (d; 0 .. 3) {
		ret += a[d] * b[d];
	}
	return ret;
}

long[][] A;

void solve() {
	foreach (i; 0 .. 8) {
		foreach (j; 0 .. 8) foreach (k; 0 .. 8) foreach (l; 0 .. 8) {
			if (j != i && k != i && l != i && j < k && k < l) {
				foreach (sj; 0 .. 6) foreach (sk; 0 .. 6) foreach (sl; 0 .. 6) {
					long[][] vs = new long[][](8, 3);
					foreach (d; 0 .. 3) {
						vs[1][d] = A[j][PERM3S[sj][d]] - A[i][d];
						vs[2][d] = A[k][PERM3S[sk][d]] - A[i][d];
						vs[4][d] = A[l][PERM3S[sl][d]] - A[i][d];
					}

					const pjj = dot(vs[1], vs[1]);
					const pjk = dot(vs[1], vs[2]);
					const pjl = dot(vs[1], vs[4]);
					const pkk = dot(vs[2], vs[2]);
					const pkl = dot(vs[2], vs[4]);
					const pll = dot(vs[4], vs[4]);
					if (pjj == pkk && pkk == pll && pll > 0 && pjk == 0 && pjl == 0 && pkl == 0) {
debug{
writeln(i,"  ",j," ",k," ",l);
writeln(vs[1]," ",vs[2]," ",vs[4]);
}
						long[][] as, bs;
						foreach (m; 0 .. 8) {
							if (m != i && m != j && m != k && m != l) {
								as ~= A[m];
							}
						}
						foreach (f; 0 .. 8) if (f & (f - 1)) {
							long[] b = new long[3];
							if (f & 1) b[] += vs[1][];
							if (f & 2) b[] += vs[2][];
							if (f & 4) b[] += vs[4][];
							bs ~= b;
						}
						assert(as.length == 4);
						assert(bs.length == 4);
						int[] perm = [ 0, 1, 2, 3 ];
						do {
							bool ok = true;
							int[] ss;
							foreach (x; 0 .. 4) {
								bool found;
								foreach (s; 0 .. 6) {
									bool eq = true;
									foreach (d; 0 .. 3) {
										eq = eq && (bs[perm[x]][d] == as[x][PERM3S[s][d]] - A[i][d]);
									}
									if (eq) {
										found = true;
										ss ~= s;
										break;
									}
								}
								ok = ok && found;
							}
							if (ok) {
debug{
writeln("ss = ",ss);
}
								writeln("YES");
								int pos;
								foreach (h; 0 .. 8) {
									const s = (h == i) ? 0 : (h == j) ? sj : (h == k) ? sk : (h == l) ? sl : ss[pos++];
									foreach (d; 0 .. 3) {
										if (d > 0) write(" ");
										write(A[h][PERM3S[s][d]]);
									}
									writeln;
								}
								return;
							}
						} while (perm.nextPermutation);
					}
				}
			}
		}
	}
	writeln("NO");
}

void main(string[] args) {
	try {
	for (; ; ) {
		A = new long[][](8, 3);
		foreach (i; 0 .. 8) {
			foreach (d; 0 .. 3) {
				A[i][d] = readLong;
			}
		}

		solve;
	}
	} catch (EOFException) {}
}

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

immutable int MAX_N = 8;
immutable int MAX_D = 3;

long dist (int [MAX_D] p, int [MAX_D] q)
{
	long res = 0L;
	foreach (j; 0..MAX_D)
	{
        	long cur = q[j] - p[j];
        	res += cur * cur;
	}
	return res;
}

int [MAX_D] [] build (int [MAX_D] [] a)
{
	long d01 = dist (a[0], a[1]);
	if (d01 == 0L)
	{
		return null;
	}
	long d02 = dist (a[0], a[2]);
	if (d02 != d01)
	{
		return null;
	}
	long d03 = dist (a[0], a[3]);
	if (d03 != d01)
	{
		return null;
	}
	long d12 = dist (a[1], a[2]);
	if (d12 != d01 * 2)
	{
		return null;
	}
	long d13 = dist (a[1], a[3]);
	if (d13 != d12)
	{
		return null;
	}
	long d23 = dist (a[2], a[3]);
	if (d23 != d12)
	{
		return null;
	}

	int [MAX_D] [] f;
	foreach (i; 0..MAX_N)
	{
		int [MAX_D] c = a[0];
		if (i & 1)
		{
			c[] += a[1][] - a[0][];
		}
		if (i & 2)
		{
			c[] += a[2][] - a[0][];
		}
		if (i & 4)
		{
			c[] += a[3][] - a[0][];
		}
		f ~= c;
	}
	debug {writefln ("Candidate:\n%(%(%s %)\n%)", f);}

	int [MAX_D] [] g = a[MAX_N / 2..$].dup;
search_loop:
	foreach (i; [3, 5, 6, 7])
	{
		foreach (ref c; g)
		{
			do
			{
				if (c == f[i])
				{
					c[] = int.min;
					continue search_loop;
				}
			}
			while (nextPermutation (c[]));
		}
		return null;
	}

	return f;
}

void main ()
{
	int [MAX_D] [] a = new int [MAX_D] [MAX_N];
	foreach (i; 0..MAX_N)
	{
		foreach (j; 0..MAX_D)
		{
			readf (" %s", &a[i][j]);
		}
		sort (a[i][]);
	}
	sort (a);

	int [MAX_D] [] b = new int [MAX_D] [MAX_N / 2];
	foreach (i; 0..MAX_N / 2)
	{
		foreach (j; 0..MAX_D)
		{
			b[i][j] = int.min;
		}
	}

	do
	{
		if (b[] == a[0..MAX_N / 2])
		{
			continue;
		}
		b[] = a[0..MAX_N / 2];
		do
		{
			do
			{
				do
				{
					do
					{
						auto f = build (a);
						if (f !is null)
						{
							writeln ("YES");
							writefln
							    ("%(%(%s %)\n%)",
							    f);
							return;
						}
					}
					while (nextPermutation (a[3][]));
				}
				while (nextPermutation (a[2][]));
			}
			while (nextPermutation (a[1][]));
		}
		while (nextPermutation (a[0][]));
	}
	while (nextPermutation (a[1..$]));

	writeln ("NO");
}

// the following is a Phobos snipped with "ref" stripped
// library code start
bool nextPermutation(alias less="a<b", BidirectionalRange)
                    (BidirectionalRange range)
    if (isBidirectionalRange!BidirectionalRange &&
        hasSwappableElements!BidirectionalRange)
{
    // Ranges of 0 or 1 element have no distinct permutations.
    if (range.empty) return false;

    auto i = retro(range);
    auto last = i.save;

    // Find last occurring increasing pair of elements
    size_t n = 1;
    for (i.popFront(); !i.empty; i.popFront(), last.popFront(), n++)
    {
        if (binaryFun!less(i.front, last.front))
            break;
    }

    if (i.empty) {
        // Entire range is decreasing: it's lexicographically the greatest. So
        // wrap it around.
        range.reverse();
        return false;
    }

    // Find last element greater than i.front.
    auto j = find!((a) => binaryFun!less(i.front, a))(
                   takeExactly(retro(range), n));

    assert(!j.empty);   // shouldn't happen since i.front < last.front
    swap(i.front, j.front);
    reverse(takeExactly(retro(range), n));

    return true;
}
// library code end

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

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

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

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

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

int[][] PERM3S = [
	[ 0, 1, 2 ],
	[ 0, 2, 1 ],
	[ 1, 0, 2 ],
	[ 1, 2, 0 ],
	[ 2, 0, 1 ],
	[ 2, 1, 0 ],
];

long dot(long[] a, long[] b) {
	long ret;
	foreach (d; 0 .. 3) {
		ret += a[d] * b[d];
	}
	return ret;
}

long[][] A;

void solve() {
	foreach (i; 0 .. 8) {
		foreach (j; 0 .. 8) foreach (k; 0 .. 8) foreach (l; 0 .. 8) {
			if (j != i && k != i && l != i && j < k && k < l) {
				foreach (sj; 0 .. 6) foreach (sk; 0 .. 6) foreach (sl; 0 .. 6) {
					long[][] vs = new long[][](8, 3);
					foreach (d; 0 .. 3) {
						vs[1][d] = A[j][PERM3S[sj][d]] - A[i][d];
						vs[2][d] = A[k][PERM3S[sk][d]] - A[i][d];
						vs[4][d] = A[l][PERM3S[sl][d]] - A[i][d];
					}

					const pjj = dot(vs[1], vs[1]);
					const pjk = dot(vs[1], vs[2]);
					const pjl = dot(vs[1], vs[4]);
					const pkk = dot(vs[2], vs[2]);
					const pkl = dot(vs[2], vs[4]);
					const pll = dot(vs[4], vs[4]);
					if (pjj == pkk && pkk == pll && pll > 0 && pjk == 0 && pjl == 0 && pkl == 0) {
// writeln(vs[1]," ",vs[2]," ",vs[4]);
						long[][] as, bs;
						foreach (m; 0 .. 8) {
							if (m != i && m != j && m != k && m != l) {
								as ~= A[m];
							}
						}
						foreach (h; 0 .. 8) if (h & (h - 1)) {
							long[] b = new long[3];
							if (h & 1) b[] += vs[1][];
							if (h & 2) b[] += vs[2][];
							if (h & 4) b[] += vs[4][];
							bs ~= b;
						}
						assert(as.length == 4);
						assert(bs.length == 4);
						int[] perm = [ 0, 1, 2, 3 ];
						do {
							bool ok = true;
							int[] ss;
							foreach (x; 0 .. 4) {
								bool found;
								foreach (s; 0 .. 6) {
									bool eq = true;
									foreach (d; 0 .. 3) {
										eq = eq && (bs[x][d] == as[perm[x]][PERM3S[s][d]] - A[i][d]);
									}
									if (eq) {
										found = true;
										ss ~= s;
										break;
									}
								}
								ok = ok && found;
							}
							if (ok) {
								writeln("YES");
								int pos;
								foreach (h; 0 .. 8) {
									if (h == i) {
										writeln(A[i].to!string.removechars("[],"));
									} else if (h == j) {
										foreach (d; 0 .. 3) {
											if (d > 0) write(" ");
											write(A[j][PERM3S[sj][d]]);
										}
										writeln;
									} else if (h == k) {
										foreach (d; 0 .. 3) {
											if (d > 0) write(" ");
											write(A[k][PERM3S[sk][d]]);
										}
										writeln;
									} else if (h == l) {
										foreach (d; 0 .. 3) {
											if (d > 0) write(" ");
											write(A[l][PERM3S[sl][d]]);
										}
										writeln;
									} else {
										const s = ss[pos];
										foreach (d; 0 .. 3) {
											if (d > 0) write(" ");
											write(as[pos][PERM3S[s][d]]);
										}
										writeln;
										++pos;
									}
								}
								return;
							}
						} while (perm.nextPermutation);
					}
				}
			}
		}
	}
	writeln("NO");
}

void main(string[] args) {
	try {
	for (; ; ) {
		A = new long[][](8, 3);
		foreach (i; 0 .. 8) {
			foreach (d; 0 .. 3) {
				A[i][d] = readLong;
			}
		}

		solve;
	}
	} catch (EOFException) {}
}

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

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

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

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

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

int[][] PERM3S = [
	[ 0, 1, 2 ],
	[ 0, 2, 1 ],
	[ 1, 0, 2 ],
	[ 1, 2, 0 ],
	[ 2, 0, 1 ],
	[ 2, 1, 0 ],
];

long dot(long[] a, long[] b) {
	long ret;
	foreach (d; 0 .. 3) {
		ret += a[d] * b[d];
	}
	return ret;
}

long[][] A;

void solve() {
	foreach (i; 0 .. 8) {
		foreach (j; 0 .. 8) foreach (k; 0 .. 8) foreach (l; 0 .. 8) {
			if (j != i && k != i && l != i && j < k && k < l) {
				foreach (sj; 0 .. 6) foreach (sk; 0 .. 6) foreach (sl; 0 .. 6) {
					long[][] vs = new long[][](8, 3);
					foreach (d; 0 .. 3) {
						vs[1][d] = A[j][PERM3S[sj][d]] - A[i][d];
						vs[2][d] = A[k][PERM3S[sk][d]] - A[i][d];
						vs[4][d] = A[l][PERM3S[sl][d]] - A[i][d];
					}

					const pjj = dot(vs[1], vs[1]);
					const pjk = dot(vs[1], vs[2]);
					const pjl = dot(vs[1], vs[4]);
					const pkk = dot(vs[2], vs[2]);
					const pkl = dot(vs[2], vs[4]);
					const pll = dot(vs[4], vs[4]);
					if (pjj == pkk && pkk == pll && pll > 0 && pjk == 0 && pjl == 0 && pkl == 0) {
// writeln(vs[1]," ",vs[2]," ",vs[4]);
						long[][] as, bs;
						foreach (m; 0 .. 8) {
							if (m != i && m != j && m != k && m != l) {
								as ~= A[m];
							}
						}
						foreach (h; 0 .. 8) if (h & (h - 1)) {
							long[] b = new long[3];
							if (h & 1) b[] += vs[1][];
							if (h & 2) b[] += vs[2][];
							if (h & 4) b[] += vs[4][];
							bs ~= b;
						}
						assert(as.length == 4);
						assert(bs.length == 4);
						int[] perm = [ 0, 1, 2, 3 ];
						do {
							bool ok = true;
							int[] ss;
							foreach (x; 0 .. 4) {
								bool found;
								foreach (s; 0 .. 6) {
									bool eq = true;
									foreach (d; 0 .. 3) {
										eq = eq && (bs[x][d] == as[perm[x]][PERM3S[s][d]] - A[i][d]);
									}
									if (eq) {
										found = true;
										ss ~= s;
										break;
									}
								}
								ok = ok && found;
							}
							if (ok) {
								writeln("YES");
								int pos;
								foreach (h; 0 .. 8) {
									if (h == i) {
										writeln(A[i].to!string.removechars("[],"));
									} else if (h == j) {
										writeln(vs[1].to!string.removechars("[],"));
									} else if (h == k) {
										writeln(vs[2].to!string.removechars("[],"));
									} else if (h == l) {
										writeln(vs[4].to!string.removechars("[],"));
									} else {
										const s = ss[pos];
										foreach (d; 0 .. 3) {
											if (d > 0) write(" ");
											write(as[pos][PERM3S[s][d]]);
										}
										writeln;
										++pos;
									}
								}
								return;
							}
						} while (perm.nextPermutation);
					}
				}
			}
		}
	}
	writeln("NO");
}

void main(string[] args) {
	try {
	for (; ; ) {
		A = new long[][](8, 3);
		foreach (i; 0 .. 8) {
			foreach (d; 0 .. 3) {
				A[i][d] = readLong;
			}
		}

		solve;
	}
	} catch (EOFException) {}
}


Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has $$$n$$$ stairs, then it is made of $$$n$$$ columns, the first column is $$$1$$$ cell high, the second column is $$$2$$$ cells high, $$$\ldots$$$, the $$$n$$$-th column if $$$n$$$ cells high. The lowest cells of all stairs must be in the same row.A staircase with $$$n$$$ stairs is called nice, if it may be covered by $$$n$$$ disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with $$$7$$$ stairs looks like:  Find out the maximal number of different nice staircases, that can be built, using no more than $$$x$$$ cells, in total. No cell can be used more than once.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The description of each test case contains a single integer $$$x$$$ $$$(1 \le x \le 10^{18})$$$  — the number of cells for building staircases.

For each test case output a single integer  — the number of different nice staircases, that can be built, using not more than $$$x$$$ cells, in total.

NoteIn the first test case, it is possible to build only one staircase, that consists of $$$1$$$ stair. It's nice. That's why the answer is $$$1$$$.In the second test case, it is possible to build two different nice staircases: one consists of $$$1$$$ stair, and another consists of $$$3$$$ stairs. This will cost $$$7$$$ cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is $$$2$$$.In the third test case, it is possible to build only one of two nice staircases: with $$$1$$$ stair or with $$$3$$$ stairs. In the first case, there will be $$$5$$$ cells left, that may be used only to build a staircase with $$$2$$$ stairs. This staircase is not nice, and Jett only builds nice staircases. That's why in this case the answer is $$$1$$$. If Jett builds a staircase with $$$3$$$ stairs, then there are no more cells left, so the answer is $$$1$$$ again.

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

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

void solve(){
    long n;
    n = rd;
    long tim = 2;
    ll[] arr,  pref;
    arr ~= 1;
    pref ~= 1;
    foreach(i; 1..32){
        arr ~= 2*arr[i-1] + tim * tim;
        tim *= 2;
        pref ~= arr[i] + pref[i-1];
    }
    /* writeln(pref); */
    ll maxi = 0;
    foreach(i; 1..32){
        if(pref[i] > n){
            maxi = i;
            break;
        }
    }
    /* writeln(arr); */
    writeln(maxi);
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}

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

void solve()
{
    auto N = readln.chomp.to!long;
    long x;
    foreach (long i; 0..32) {
        x += x + (2L^^i)^^2;
        if (N >= x) {
            N -= x;
        } else {
            writeln(i);
            return;
        }
    }
}

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 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)); }

//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 x = RD-1;
		ans[ti] = 1;
		long y = 1;
		long cnt = 1;
		foreach (i; 0..10^^7)
		{
			y *= 2;
			long z = cnt*2 + y^^2;
			if (z > x) break;
			x -= z;
			++ans[ti];
			cnt = z;
		}
	}

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

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

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

void solve(){
    long n;
    n = rd;
    long tim = 2;
    ll[] arr;
    arr ~= 1;
    foreach(i; 1..62){
        arr ~= 2*arr[i-1] + tim * tim;
        if(n < arr.back){
            break;
        }
        tim *= 2;
    }
    arr.popBack;
    /* writeln(arr); */
    writeln(arr.length);
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}

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 x = RD-1;
		ans[ti] = 1;
		long y = 1;
		foreach (i; 0..10^^7)
		{
			y *= 2;
			long z = y + y^^2;
			if (z > x) break;
			x -= z;
			++ans[ti];
		}
	}

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


We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly.More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of length n. Also, you've got m queries of two types:  Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by + q = ax + q for all integer q (0 ≤ q < k). The given operation is correct — both subsegments do not touch unexistent elements.  Determine the value in position x of array b, that is, find value bx. For each query of the second type print the result — the value of the corresponding element of array b.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1, a2, ..., an (|ai| ≤ 109). The third line contains an array of integers b1, b2, ..., bn (|bi| ≤ 109). Next m lines contain the descriptions of the queries. The i-th line first contains integer ti — the type of the i-th query (1 ≤ ti ≤ 2). If ti = 1, then the i-th query means the copying operation. If ti = 2, then the i-th query means taking the value in array b. If ti = 1, then the query type is followed by three integers xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — the parameters of the copying query. If ti = 2, then the query type is followed by integer xi (1 ≤ xi ≤ n) — the position in array b. All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b.

For each second type query print the result on a single line.

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

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

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

    struct q {
        int t, x, y, k;
    }

    auto qs = new q[] (m);
    foreach (i; 0 .. m) {
        readf("%s", &qs[i].t);
        if (qs[i].t == 1) {
            readf(" %s %s %s", &qs[i].x, &qs[i].y, &qs[i].k);
        } else {
            readf(" %s", &qs[i].x);
        }
        readln;
    }

    debug { qs.writeln; }

    auto ans = new int[] (m);

    alias elem = Tuple!(int, int);
    auto rbt = make!(RedBlackTree!elem);
    foreach_reverse (i, cq; qs) {
        if (cq.t == 2) {
            rbt.insert(tuple(cq.x, i.to!int));
        } else {
            auto seq = rbt.upperBound(tuple(cq.y, 0)).until!(t => t[0] > cq.y + cq.k - 1);
            debug { cq.y.writeln; seq.writeln; }

            foreach (e; seq) {
                ans[e[1]] = a[cq.x + e[0] - cq.y - 1];
            }

            auto cpy = seq.array.dup;
            foreach (e; cpy) { rbt.removeKey(e); }
        }
    }

    foreach (e; rbt) {
        ans[e[1]] = b[e[0] - 1];
    }

    foreach (i; 0 .. m) {
        if (qs[i].t == 1) { continue; }

        ans[i].writeln;
    }
}

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

immutable int MED_L = 1 << 17;
immutable int MAX_L = MED_L << 1;

void main ()
{
	int n, m;
	while (scanf (" %d %d", &n, &m) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			scanf (" %d", &a[i]);
		}
		auto b = new int [n];
		foreach (i; 0..n)
		{
			scanf (" %d", &b[i]);
		}

		auto x = new int [m];
		auto y = new int [m];
		auto z = new int [m];
		auto t = new int [MAX_L];
		t[] = -1;

		void mark (int q, int lo, int hi)
		{
			lo += MED_L;
			hi += MED_L;
			while (lo <= hi)
			{
				if (lo & 1)
				{
					debug {writefln ("t[%s] = %s", lo, q);}
					t[lo] = q;
					lo++;
				}
				if (!(hi & 1))
				{
					debug {writefln ("t[%s] = %s", hi, q);}
					t[hi] = q;
					hi--;
				}
				lo >>= 1;
				hi >>= 1;
			}
		}

		int value (int p)
		{
			int res = b[p];
			int q = -1;
			for (int s = p + MED_L; s > 0; s >>= 1)
			{
				q = max (q, t[s]);
			}
			if (q != -1)
			{
				debug {writefln ("q = %s, p = %s", q, p);}
				debug {writefln ("index = %s + %s - %s = %s",
				                 x[q], p, y[q],
				                 x[q] + p - y[q]);}
				res = a[x[q] + p - y[q]];
			}
			return res;
		}

		foreach (j; 0..m)
		{
			int k;
			scanf (" %d", &k);
			if (k == 1)
			{
				scanf (" %d %d %d", &x[j], &y[j], &z[j]);
				x[j]--;
				y[j]--;
				mark (j, y[j], y[j] + z[j] - 1);
			}
			else if (k == 2)
			{
				int p;
				scanf (" %d", &p);
				debug {writefln ("p = %d", p);}
				p--;
				int v = value (p);
				printf ("%d\n", v);
			}
			else
			{
				assert (false);
			}
		}
	}
}

import std.array;
import std.conv;
import std.stdio;
import std.string;
import std.typecons;

alias Tuple!(int, "x", int, "y") Pair;

class SegmentTree {
    int l;
    int r;
    Pair val;
    SegmentTree l_son;
    SegmentTree r_son;

    this(int l, int r) {
        this.l = l;
        this.r = r;
        this.val.x = this.val.y = -1;
        if (l != r) {
            this.l_son = new SegmentTree(l, (l+r)/2);
            this.r_son = new SegmentTree((l+r)/2+1, r);
        }
    }

    void Upd() {
        if (this.val.x != -1) {
            this.l_son.val = this.val;
            this.r_son.val = this.val;
            this.val.x = this.val.y = -1;
        }
    }

    void Col(int l, int r, int x, int y) {
        if (l > this.r || r < this.l) {
            return;
        }
        if (l <= this.l && r >= this.r) {
            this.val.x = x;
            this.val.y = y;
            return;
        }
        Upd();
        this.l_son.Col(l, r, x, y);
        this.r_son.Col(l, r, x, y);
    }

    Pair Val(int pos) {
        if (this.val.x != -1 || this.l == this.r) {
            return this.val;
        }
        return pos <= this.l_son.r ? this.l_son.Val(pos) : this.r_son.Val(pos);
    }
}

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    int m;
    readf("%d %d ", &n, &m);
    int[] a = new int[n];
    int[] b = new int[n];
    foreach (i; 0..n) {
        readf("%d ", &a[i]);
    }
    foreach (i; 0..n) {
        readf("%d ", &b[i]);
    }
    SegmentTree tree = new SegmentTree(0, n-1);
    foreach (i; 0..m) {
        int t;
        readf("%d ", &t);
        if (t == 1) {
            int x;
            int y;
            int k;
            readf("%d %d %d ", &x, &y, &k);
            x--;
            y--;
            tree.Col(y, y+k-1, x, y);
        } else {
            int pos;
            readf("%d ", &pos);
            pos--;
            Pair cur_val = tree.Val(pos);
            if (cur_val.x == -1) {
                writeln(b[pos]);
            } else {
                writeln(a[cur_val.x + pos - cur_val.y]);
            }
        }
    }
}

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

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

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

    struct q {
        int t, x, y, k;
    }

    auto qs = new q[] (m);
    foreach (i; 0 .. m) {
        readf("%s", &qs[i].t);
        if (qs[i].t == 1) {
            readf(" %s %s %s", &qs[i].x, &qs[i].y, &qs[i].k);
        } else {
            readf(" %s", &qs[i].x);
        }
        readln;
    }

    debug { qs.writeln; }

    auto ans = new int[] (m);

    alias elem = Tuple!(int, int);
    auto rbt = make!(RedBlackTree!elem);
    foreach_reverse (i, cq; qs) {
        if (cq.t == 2) {
            rbt.insert(tuple(cq.x, i.to!int));
        } else {
            auto seq = rbt.upperBound(tuple(cq.y, 0)).until!(t => t[0] > cq.y + cq.k);
            debug { cq.y.writeln; seq.writeln; }

            foreach (e; seq) {
                ans[e[1]] = a[cq.x + e[0] - cq.y - 1];
            }

            auto cpy = seq.array.dup;
            foreach (e; cpy) { rbt.removeKey(e); }
        }
    }

    foreach (e; rbt) {
        ans[e[1]] = b[e[0] - 1];
    }

    foreach (i; 0 .. m) {
        if (qs[i].t == 1) { continue; }

        ans[i].writeln;
    }
}


It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.

The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.

Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).

NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		int d = 0;
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
			d = gcd (d, a[i]);
		}
		a[] /= d;
		sort (a);
		int left = a[$ - 1] - a.length;
		writeln ((left % 2 == 1) ? "Alice" : "Bob");
	}
}


This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury picked an integer $$$x$$$ not less than $$$0$$$ and not greater than $$$2^{14} - 1$$$. You have to guess this integer.To do so, you may ask no more than $$$2$$$ queries. Each query should consist of $$$100$$$ integer numbers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{100}$$$ (each integer should be not less than $$$0$$$ and not greater than $$$2^{14} - 1$$$). In response to your query, the jury will pick one integer $$$i$$$ ($$$1 \le i \le 100$$$) and tell you the value of $$$a_i \oplus x$$$ (the bitwise XOR of $$$a_i$$$ and $$$x$$$). There is an additional constraint on the queries: all $$$200$$$ integers you use in the queries should be distinct.It is guaranteed that the value of $$$x$$$ is fixed beforehand in each test, but the choice of $$$i$$$ in every query may depend on the integers you send.

To give the answer, your program should print one line $$$!$$$ $$$x$$$ with a line break in the end. After that, it should flush the output and terminate gracefully.

NoteThe example of interaction is not correct — you should sumbit exactly $$$100$$$ integers in each query. Everything else is correct.Hacks are forbidden in this problem.

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

void main()
{
  write("? ");
  iota(1, uint(101)).map!(n => n << 7).each!(n => write(n, " "));
  writeln;
  stdout.flush;
  auto anslo = next!uint & uint(0b00000001111111);

  write("? ");
  iota(1, uint(101)).each!(n => write(n, " "));
  writeln;
  stdout.flush;
  auto anshi = next!uint & uint(0b11111110000000);

  return writeln("! ", anslo | anshi);
}

void read(T...)(ref T t)
{
  static DList!string _words;
  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;
}

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

void main()
{
  write("? ");
  iota(0, uint(100)).map!(n => n << 7).each!(n => write(n, " "));
  writeln;
  stdout.flush;
  auto anslo = next!uint & uint(0b00000001111111);

  write("? ");
  iota(0, uint(100)).each!(n => write(n, " "));
  writeln;
  stdout.flush;
  auto anshi = next!uint & uint(0b11111110000000);

  return writeln("! ", anslo | anshi);
}

void read(T...)(ref T t)
{
  static DList!string _words;
  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;
}