Ashish has two strings $$$a$$$ and $$$b$$$, each of length $$$n$$$, and an integer $$$k$$$. The strings only contain lowercase English letters.He wants to convert string $$$a$$$ into string $$$b$$$ by performing some (possibly zero) operations on $$$a$$$.In one move, he can either   choose an index $$$i$$$ ($$$1 \leq i\leq n-1$$$) and swap $$$a_i$$$ and $$$a_{i+1}$$$, or  choose an index $$$i$$$ ($$$1 \leq i \leq n-k+1$$$) and if $$$a_i, a_{i+1}, \ldots, a_{i+k-1}$$$ are all equal to some character $$$c$$$ ($$$c \neq$$$ 'z'), replace each one with the next character $$$(c+1)$$$, that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string $$$a$$$. Help Ashish determine if it is possible to convert string $$$a$$$ into $$$b$$$ after performing some (possibly zero) operations on it.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers $$$n$$$ ($$$2 \leq n \leq 10^6$$$) and $$$k$$$ ($$$1 \leq k \leq n$$$). The second line of each test case contains the string $$$a$$$ of length $$$n$$$ consisting of lowercase English letters. The third line of each test case contains the string $$$b$$$ of length $$$n$$$ consisting of lowercase English letters. It is guaranteed that the sum of values $$$n$$$ among all test cases does not exceed $$$10^6$$$.

For each test case, print "Yes" if Ashish can convert $$$a$$$ into $$$b$$$ after some moves, else print "No". You may print the letters of the answer in any case (upper or lower).

4
3 3
abc
bcd
4 2
abba
azza
2 1
zz
aa
6 2
aaabba
ddddcc

NoteIn the first test case it can be shown that it is impossible to convert $$$a$$$ into $$$b$$$.In the second test case,"abba" $$$\xrightarrow{\text{inc}}$$$ "acca" $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ "azza".Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type.In the fourth test case,"aaabba" $$$\xrightarrow{\text{swap}}$$$ "aaabab" $$$\xrightarrow{\text{swap}}$$$ "aaaabb" $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ "ddaabb" $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ "ddddbb" $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ "ddddcc".

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

// Main Logic Here
void play(){
    long[27] cmap = 0;
    auto n = rd!int;
    auto k = rd!int;
    dchar[] s1 = rd!(dchar[]);
    dchar[] s2 = rd!(dchar[]);
    foreach(dchar c; s1){ int z = to!int(c - 'a'); ++cmap[z+1]; }
    foreach(dchar c; s2){ int z = to!int(c - 'a'); --cmap[z+1]; }
    show(cmap);
    foreach(int i; 1..27){
        if(cmap[i] > 0 && cmap[i] % k == 0){
            foreach(int j; i+1..27){
                if(cmap[j] < 0 && (-cmap[j]) % k == 0){
                    ll take = min(cmap[i], -cmap[j]);
                    cmap[i] -= take;
                    cmap[j] += take;
                }
            }
        }
    }
    show(cmap);
    foreach(i; 1..27){
        if(cmap[i] != 0){
            writeln("No");
            return;
        }
    }
    writeln("Yes");
}

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

/**********That's All Folks!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;    // Read input
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)(){ auto r = readln.chomp.split.to!(T[]); return r; }
alias ll = long;
alias tup = Tuple!(long, "x",  long, "y");
void show(A...)(A a) { debug{ foreach(t; a){ stderr.write(t, "| "); } stderr.writeln; } } // Debug
/* Add if TLE, T max(T = long)(T a, T b){ return (a > b) ? a : b; } */

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 bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto a = RD!string;
		auto b = RD!string;
		auto aa = new int[](26);
		auto bb = new int[](26);
		foreach (i; 0..n)
		{
			++aa[a[i]-'a'];
			++bb[b[i]-'a'];
		}
		auto c = new int[](26);
		foreach (i; 0..26)
		{
			c[i] = aa[i] - bb[i];
		}
		bool ok = true;
		foreach (i; 0..25)
		{
			if (c[i] < 0)
			{
				ok = false;
				break;
			}
			else if (c[i] % k)
			{
				ok = false;
				break;
			}
			else
			{
				c[i+1] += c[i];
			}
		}
		if (c[$-1] != 0)
			ok = false;
		ans[ti] = ok;
	}

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


A binary string is a string where each character is either 0 or 1. Two binary strings $$$a$$$ and $$$b$$$ of equal length are similar, if they have the same character in some position (there exists an integer $$$i$$$ such that $$$a_i = b_i$$$). For example:  10010 and 01111 are similar (they have the same character in position $$$4$$$);  10010 and 11111 are similar;  111 and 111 are similar;  0110 and 1001 are not similar. You are given an integer $$$n$$$ and a binary string $$$s$$$ consisting of $$$2n-1$$$ characters. Let's denote $$$s[l..r]$$$ as the contiguous substring of $$$s$$$ starting with $$$l$$$-th character and ending with $$$r$$$-th character (in other words, $$$s[l..r] = s_l s_{l + 1} s_{l + 2} \dots s_r$$$).You have to construct a binary string $$$w$$$ of length $$$n$$$ which is similar to all of the following strings: $$$s[1..n]$$$, $$$s[2..n+1]$$$, $$$s[3..n+2]$$$, ..., $$$s[n..2n-1]$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$). The second line of each test case contains the binary string $$$s$$$ of length $$$2n - 1$$$. Each character $$$s_i$$$ is either 0 or 1.

For each test case, print the corresponding binary string $$$w$$$ of length $$$n$$$. If there are multiple such strings — print any of them. It can be shown that at least one string $$$w$$$ meeting the constraints always exists.

NoteThe explanation of the sample case (equal characters in equal positions are bold):The first test case:   $$$\mathbf{1}$$$ is similar to $$$s[1..1] = \mathbf{1}$$$. The second test case:   $$$\mathbf{000}$$$ is similar to $$$s[1..3] = \mathbf{000}$$$;  $$$\mathbf{000}$$$ is similar to $$$s[2..4] = \mathbf{000}$$$;  $$$\mathbf{000}$$$ is similar to $$$s[3..5] = \mathbf{000}$$$. The third test case:   $$$\mathbf{1}0\mathbf{10}$$$ is similar to $$$s[1..4] = \mathbf{1}1\mathbf{10}$$$;  $$$\mathbf{1}01\mathbf{0}$$$ is similar to $$$s[2..5] = \mathbf{1}10\mathbf{0}$$$;  $$$\mathbf{10}1\mathbf{0}$$$ is similar to $$$s[3..6] = \mathbf{10}0\mathbf{0}$$$;  $$$1\mathbf{0}1\mathbf{0}$$$ is similar to $$$s[4..7] = 0\mathbf{0}0\mathbf{0}$$$. The fourth test case:   $$$0\mathbf{0}$$$ is similar to $$$s[1..2] = 1\mathbf{0}$$$;  $$$\mathbf{0}0$$$ is similar to $$$s[2..3] = \mathbf{0}1$$$.

// Vicfred
// https://codeforces.com/contest/1400/problem/A
// greedy
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;
        string s = readln.strip;

        char[] ans;

        foreach(_; 0..n)
            ans ~= s[n-1];

        ans.writeln;
    }
}

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

void main ()
{
	foreach (test; 0..readln.strip.to !(int))
	{
		readln;
		readln.strip.stride (2).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)); }

//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 string[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!string;
		foreach (i; 0..n)
		{
			ans[ti] ~= s[$/2];
		}
	}

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

// Vicfred
// https://codeforces.com/contest/1400/problem/A
// greedy
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;
        string s = readln.strip;

        char[] ans;

        foreach(_; 0..n-1)
            ans ~= '1';

        ans ~= s[n-1];
        ans.writeln;
    }
}


One day, you are accepted as being Dr. Chanek's assistant. The first task given by Dr. Chanek to you is to take care and store his magical stones.Dr. Chanek has $$$N$$$ magical stones with $$$N$$$ being an even number. Those magical stones are numbered from $$$1$$$ to $$$N$$$. Magical stone $$$i$$$ has a strength of $$$A_i$$$. A magical stone can be painted with two colours, namely the colour black or the colour white. You are tasked to paint the magical stones with the colour black or white and store the magical stones into a magic box with a magic coefficient $$$Z$$$ ($$$0 \leq Z \leq 2$$$). The painting of the magical stones must be done in a way such that there are $$$\frac{N}{2}$$$ black magical stones and $$$\frac{N}{2}$$$ white magical stones.Define $$$\text{concat}(x, y)$$$ for two integers $$$x$$$ and $$$y$$$ as the result of concatenating the digits of $$$x$$$ to the left of $$$y$$$ in their decimal representation without changing the order. As an example, $$$\text{concat}(10, 24)$$$ will result in $$$1024$$$.For a magic box with a magic coefficient $$$Z$$$, magical stone $$$i$$$ will react with magical stone $$$j$$$ if the colours of both stones are different and $$$\text{concat}(A_i, A_j) \times \text{concat}(A_j, A_i) + A_i \times A_j \equiv Z \mod 3$$$. A magical stone that is reacting will be very hot and dangerous. Because of that, you must colour the magical stones and determine the magic coefficient $$$Z$$$ of the magic box in a way such that there is no magical stone that reacts, or report if it is impossible.

The first line contains a single even integer $$$N$$$ ($$$2 \le N \le 10^5$$$) — the number of magical stones Dr. Chanek has. The second line contains $$$N$$$ integer $$$A_1, A_2, \ldots, A_N$$$ ($$$1 \leq A_i \leq 10^9$$$) — the strengths of all magical stones.

If it is not possible to satisfy the condition of the problem, output $$$-1$$$. Otherwise, output two lines. The first line contains an integer $$$Z$$$ denoting the magic coefficient of the magic box. The second line contains a string $$$S$$$ of length $$$N$$$. $$$S_i$$$ is $$$0$$$ if magical stone $$$i$$$ is coloured black or $$$1$$$ if magical stone $$$i$$$ is coloured white. If there are more than one possibilities of colouring and choosing the magic coefficient $$$Z$$$, output any of them.

NoteBy giving the above colouring, it can be seen that:   $$$i=1, j=2 \longrightarrow \text{concat}(4, 10) \times \text{concat}(10, 4) + 10 \times 4 = 410 \times 104 + 40 = 42680 \equiv 2 \mod 3$$$  $$$i=1, j=3 \longrightarrow \text{concat}(4, 9) \times \text{concat}(9, 4) + 4 \times 9 = 49 \times 94 + 36 = 4642 \equiv 1 \mod 3$$$  $$$i=4, j=2 \longrightarrow \text{concat}(14, 10) \times \text{concat}(10, 14) + 10 \times 14 = 1410 \times 1014 + 140 = 1429880 \equiv 2 \mod 3$$$  $$$i=4, j=3 \longrightarrow \text{concat}(14, 9) \times \text{concat}(9, 14) + 14 \times 9 = 149 \times 914 + 126 = 136312 \equiv 1 \mod 3$$$ Because of that, by choosing $$$Z = 0$$$, it can be guaranteed that there is no magical stone that reacts.

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

void main() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!((x) => (x.to!int % 3)).array;
    int[] B = new int[3];
    foreach (i; 0 .. 3) {
        B[i] = A.count!((a) => a == i);
    }
    int Z = -1;
    char[] ans = new char[N];
    if (B[0] >= N/2) {
        Z = 2;
        int C = 0;
        for (int i = 0; i < N; i++) {
            if (A[i] == 0 && C < N/2) {
                ans[i] = '0';
                C++;
            } else {
                ans[i] = '1';
            }
        }
    } else if (B[1] >= N/2) {
        Z = 0;
        int C = 0;
        for (int i = 0; i < N; i++) {
            if (A[i] == 1 && C < N/2) {
                ans[i] = '0';
                C++;
            } else {
                ans[i] = '1';
            }
        }
    } else if (B[2] >= N/2) {
        Z = 0;
        int C = 0;
        for (int i = 0; i < N; i++) {
            if (A[i] == 2 && C < N/2) {
                ans[i] = '0';
                C++;
            } else {
                ans[i] = '1';
            }
        }
    } else {
        Z = 0;
        int C = 0;
        for (int i = 0; i < N; i++) {
            if (A[i] == 0) {
                ans[i] = '0';
            } else if (C < N/2) {
                ans[i] = '1';
                C++;
            } else {
                ans[i] = '0';
            }
        }
    }
    writeln(Z);
    writeln(ans);
}

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

void main() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!int).array;
    int Z = 0;
    for (int i = 0; i < N; i++) {
        int r = A[i] % 3;
        Z = (Z + r * r) % 3;
    }
    Z = Z * 2 * N % 3;
    writeln(Z);
    char[] s = new char[N];
    for (int i = 0; i < N; i++) {
        s[i] = (i % 2 == 0 ? '0' : '1');
    }
    string ans = cast(string)s;
    writeln(ans);
}

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

void main() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!int).array;
    int Z = 0;
    for (int i = 0; i < N; i++) {
        int r = A[i] % 3;
        Z = (Z + r * r) % 3;
    }
    writeln(Z);
    char[] s = new char[N];
    for (int i = 0; i < N; i++) {
        s[i] = (i % 2 == 0 ? '0' : '1');
    }
    string ans = cast(string)s;
    writeln(ans);
}

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

void main() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!int).array;
    int Z = 0;
    for (int i = 0; i < N; i++) {
        int r = A[i] % 3;
        Z = (Z + r * r) % 3;
    }
    writeln(Z);
    char[] s = new char[N+1];
    for (int i = 0; i < N; i++) {
        s[i] = (i % 2 == 0 ? '0' : '1');
    }
    s[N] = '\0';
    string ans = cast(string)s;
    writeln(ans);
}


While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $$$H$$$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $$$L$$$ centimeters. Exactly at this point the flower touched the water surface.  Suppose that the lily grows at some point $$$A$$$ on the lake bottom, and its stem is always a straight segment with one endpoint at point $$$A$$$. Also suppose that initially the flower was exactly above the point $$$A$$$, i.e. its stem was vertical. Can you determine the depth of the lake at point $$$A$$$?

The only line contains two integers $$$H$$$ and $$$L$$$ ($$$1 \le H < L \le 10^{6}$$$).

Print a single number — the depth of the lake at point $$$A$$$. The absolute or relative error should not exceed $$$10^{-6}$$$. Formally, let your answer be $$$A$$$, and the jury's answer be $$$B$$$. Your answer is accepted if and only if $$$\frac{|A - B|}{\max{(1, |B|)}} \le 10^{-6}$$$.

import std.stdio, std.math;

void main() {
    long h, l;
    readf(" %s %s", h, l);
    auto result = (cast(float)(l*l - h*h)) / (2 * h);
    writef("%.9s", result);
}

import std.stdio;

void main()
{
  float h, l;
  readf!"%f %f\n"(h, l);

  writef!"%.6f\n"((l^^2 - h^^2) / (2*h));
}

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

void main(){
    double h,l;
    readf!"%f %f"(h,l);
    readln;
    writefln!"%.13f"(l^^2/(2*h)-0.5*h);
}

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

void main(){
    double h,l;
    readf!"%f %f"(h,l);
    readln;
    writefln!"%.13f"(l^^2/(2*h)-0.5);
}


You are given two strings $$$s$$$ and $$$t$$$ of equal length $$$n$$$. In one move, you can swap any two adjacent characters of the string $$$s$$$.You need to find the minimal number of operations you need to make string $$$s$$$ lexicographically smaller than string $$$t$$$.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$$$.

The first line of input contains one integer $$$q$$$ ($$$1 \le q \le 10\,000$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase English letters. The third line of each test case contains the string $$$t$$$ consisting of $$$n$$$ lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print in a separate line the minimal number of operations you need to make string $$$s$$$ lexicographically smaller than string $$$t$$$, or $$$-1$$$, if it's impossible.

4
1
a
a
3
rll
rrr
3
caa
aca
5
ababa
aabba

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

immutable int letters = 26;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip.map !(q{a - 'a'}).array;
		auto t = readln.strip.map !(q{a - 'a'}).array;
		auto where = new int [] [letters];
		foreach (i, ref c; s)
		{
			where[c] ~= i.to !(int);
		}

		auto half = 1;
		while (half < n)
		{
			half <<= 1;
		}
		auto total = half << 1;
		auto r = new int [total];
		foreach (i; 0..n)
		{
			r[i + half] = i;
		}

		void alter (int lo, int hi, int delta)
		{
			for (lo += half, hi += half; lo < hi;
			    lo >>= 1, hi >>= 1)
			{
				if (lo & 1)
				{
					r[lo++] += delta;
				}
				if (hi & 1)
				{
					r[--hi] += delta;
				}
			}
		}

		int value (int pos)
		{
			int res = 0;
			for (pos += half; pos > 0; pos >>= 1)
			{
				res += r[pos];
			}
			return res;
		}

		long res = long.max;
		long cur = 0;
main_loop:
		foreach (i; 0..n)
		{
			foreach (z; 0..t[i])
			{
				if (!where[z].empty)
				{
					auto temp = value (where[z].front);
					res = min (res, cur + temp - i);
					if (temp == i)
					{
						break main_loop;
					}
				}
			}
			auto z = t[i];
			if (where[z].empty)
			{
				break;
			}
			auto temp = value (where[z].front);
			cur += temp - i;
			alter (0, where[z].front, +1);
			where[z].popFront ();
		}
		if (res == long.max)
		{
			res = -1;
		}
		writeln (res);
	}
}

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

immutable int letters = 26;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip.map !(q{a - 'a'}).array;
		auto t = readln.strip.map !(q{a - 'a'}).array;
		auto where = new int [] [letters];
		foreach (i, ref c; s)
		{
			where[c] ~= i.to !(int);
		}

		auto half = 1;
		while (half < n)
		{
			half <<= 1;
		}
		auto total = 1 << half;
		auto r = new int [total];
		foreach (i; 0..n)
		{
			r[i + half] = i;
		}

		void alter (int lo, int hi, int delta)
		{
			debug {writeln ("alter ", lo, " ", hi, " ", delta);}
			for (lo += half, hi += half; lo < hi;
			    lo >>= 1, hi >>= 1)
			{
				if (lo & 1)
				{
					r[lo++] += delta;
				}
				if (hi & 1)
				{
					r[--hi] += delta;
				}
			}
		}

		int value (int pos)
		{
			debug {writeln ("value ", pos);}
			int res = 0;
			for (pos += half; pos > 0; pos >>= 1)
			{
				res += r[pos];
			}
			return res;
		}

		long res = long.max;
		long cur = 0;
main_loop:
		foreach (i; 0..n)
		{
			foreach (z; 0..t[i])
			{
				if (!where[z].empty)
				{
					auto temp = value (where[z].front);
					debug {writeln (z, ": ",
					    temp, " ", i);}
					res = min (res, cur + temp - i);
					if (temp == i)
					{
						break main_loop;
					}
				}
			}
			auto z = t[i];
			if (where[z].empty)
			{
				break;
			}
			auto temp = value (where[z].front);
			debug {writeln (z, "!: ", temp, " ", i);}
			cur += temp - i;
			alter (i, temp, +1);
			where[z].popFront ();
		}
		if (res == long.max)
		{
			res = -1;
		}
		writeln (res);
	}
}

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

immutable int letters = 26;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip.map !(q{a - 'a'}).array;
		auto t = readln.strip.map !(q{a - 'a'}).array;
		auto where = new int [] [letters];
		foreach (i, ref c; s)
		{
			where[c] ~= i.to !(int);
		}

		auto half = 1;
		while (half < n)
		{
			half <<= 1;
		}
		auto total = 1 << half;
		auto r = new int [total];
		foreach (i; 0..n)
		{
			r[i + half] = i;
		}

		void alter (int lo, int hi, int delta)
		{
			debug {writeln ("alter ", lo, " ", hi, " ", delta);}
			for (lo += half, hi += half; lo < hi;
			    lo >>= 1, hi >>= 1)
			{
				if (lo & 1)
				{
					r[lo++] += delta;
				}
				if (hi & 1)
				{
					r[--hi] += delta;
				}
			}
		}

		int value (int pos)
		{
			debug {writeln ("value ", pos);}
			int res = 0;
			for (pos += half; pos > 0; pos >>= 1)
			{
				res += r[pos];
			}
			return res;
		}

		long res = long.max;
		long cur = 0;
main_loop:
		foreach (i; 0..n)
		{
			foreach (z; 0..t[i])
			{
				if (!where[z].empty)
				{
					auto temp = value (where[z].front);
					debug {writeln (z, ": ",
					    temp, " ", i);}
					res = min (res, cur + temp - i);
					if (temp == i)
					{
						break main_loop;
					}
				}
			}
			auto z = t[i];
			if (where[z].empty)
			{
				break;
			}
			auto temp = value (where[z].front);
			debug {writeln (z, "!: ", temp, " ", i);}
			cur += temp - i;
			alter (i, where[z].front, +1);
			where[z].popFront ();
		}
		if (res == long.max)
		{
			res = -1;
		}
		writeln (res);
	}
}


Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.

The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.

Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.

import std.stdio;
import std.algorithm;

void main() {
	int n;
	int[] a;
	int temp;

	readf(" %s %s", &n, &temp);

	a ~= temp;
	int max = temp;

	int idx = 0;
	foreach (i; 1 .. n) {
		readf(" %s", &temp);
		a ~= temp;
		if (temp > max) {
			max = temp;
			idx = i;
		}
	}

	a[idx] = (a[idx] == 1) ? 2 : 1;

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

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

void main() {
    const len = {
        uint t;
        readf("%s\n", &t);
        return t;
    }();

    uint[] data = new uint[len];

    auto mymax = tuple(0, 0);
    foreach(idx, ref i; data) {
        readf("%s ", &i);
        if(i > mymax[1]) { mymax[1] = i; mymax[0] = idx; }
    }

    if(mymax[1] != 1) {
        data[mymax[0]] = 1;
    }
    else
    {
        data[mymax[0]] = 2;
    }

    /*data.sort()
    .y!((auto ref arr){
        foreach(ref a; arr) {
            write(a, " ");
        }
    });
    */

    (auto ref arr){
        foreach(ref a; arr) {
            write(a, " ");
        }
    }
    ( data.sort() );
}

alias y(alias clos) = clos;

alias var(alias elem) = std.traits.Unqual!(typeof(elem));

auto mut(T)(auto ref T in_val) {
    std.traits.Unqual!(T) rv = in_val;
    return rv;
}

auto imut(T)(auto ref T in_val) {
    immutable immrv = in_val;
    return immrv;
}

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

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

    auto ys = new int[N];
    if (xs.all!"a == 1") {
        ys[] = 1;
        ys.back = 2;
    } else {
        ys[0] = 1;
        for (int i = 1; i < N; i++) {
            ys[i] = xs[i - 1];
        }
    }
    writefln("%(%s %)", ys);
}

import std.stdio;
import std.algorithm;

void main() {
	int n;
	int[] a;
	int temp;

	readf(" %s %s", &n, &temp);

	a ~= temp;
	int max = temp;

	int idx = 0;
	foreach (i; 1 .. n) {
		readf(" %s", &temp);
		a ~= temp;
		if (temp > max) {
			max = temp;
			idx = i;
		}
	}

	(a[idx] == 1) ? a[idx] = 2 : a[idx] = 1;

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

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

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

    auto ys = new int[N];
    ys[0] = 1;
    for (int i = 1; i < N; i++) {
        ys[i] = xs[i - 1];
    }
    writefln("%(%s %)", ys);
}

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

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

    auto ys = new int[N];
    if (N == 1 && xs[0] == 1) {
        writeln(2);
        return;
    }
    ys[0] = 1;
    for (int i = 1; i < N; i++) {
        ys[i] = xs[i - 1];
    }
    writefln("%(%s %)", ys);
}


Recently Max has got himself into popular CCG "BrainStone". As "BrainStone" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them:Max owns n creatures, i-th of them can be described with two numbers — its health hpi and its damage dmgi. Max also has two types of spells in stock:  Doubles health of the creature (hpi := hpi·2);  Assigns value of health of the creature to its damage (dmgi := hpi). Spell of first type can be used no more than a times in total, of the second type — no more than b times in total. Spell can be used on a certain creature multiple times. Spells can be used in arbitrary order. It isn't necessary to use all the spells.Max is really busy preparing for his final exams, so he asks you to determine what is the maximal total damage of all creatures he can achieve if he uses spells in most optimal way.

The first line contains three integers n, a, b (1 ≤ n ≤ 2·105, 0 ≤ a ≤ 20, 0 ≤ b ≤ 2·105) — the number of creatures, spells of the first type and spells of the second type, respectively. The i-th of the next n lines contain two number hpi and dmgi (1 ≤ hpi, dmgi ≤ 109) — description of the i-th creature.

Print single integer — maximum total damage creatures can deal.

NoteIn the first example Max should use the spell of the first type on the second creature, then the spell of the second type on the same creature. Then total damage will be equal to 15 + 6·2 = 27.In the second example Max should use the spell of the second type on the first creature, then the spell of the second type on the third creature. Total damage will be equal to 10 + 11 + 5 = 26.

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

immutable long INF = 1L << 59;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto A = s[1];
    auto B = s[2];
    auto H = new long[](N);
    auto D = new long[](N);
    foreach (i; 0..N) {
        auto t = readln.split.map!(to!long);
        H[i] = t[0];
        D[i] = t[1];
    }

    auto S = D.sum;
    auto DD = new long[](N);
    foreach (i; 0..N) DD[i] = max(0L, H[i] - D[i]);
    DD.sort!"a > b"();
    auto DDS = DD[0..min(N, B)].sum;
    long ans = 0;

    if (A == 0) {
        writeln(S + DDS);
        return;
    }

    if (B == 0) {
        writeln(S);
        return;
    }

    foreach (i; 0..N) {
        long tmp = (H[i] << A) + S - D[i] + DDS;
        long dd = max(0L, H[i] - D[i]);
        if (B >= N || dd > DD[B]) {
            tmp = tmp - dd;
        } else {
            tmp = tmp - DD[B-1];
        }
        ans = max(ans, tmp);
    }

    ans.writeln;
}

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

void main()
{
    int n, a, b;
    readf ("%s %s %s", &n, &a, &b);
    readln;
    b = min (b, n);

    long [][] arr;
    foreach ( _; 0..n ) arr ~= readln.splitter.map! (to!long).array;

    arr.sort! (q{ a[0] - a[1] > b[0] - b[1] });

    debug { writeln (arr); }

    auto valUseB = (long[] e) => max (e[0], e[1]);

    auto ansNoA = arr
        .enumerate
        .map! (t => t.index < b ? valUseB (t.value) : t.value[1])
        .sum;

    if (b == 0) {
        writeln (ansNoA);
        return;
    }

    auto smallestGainOnB = valUseB (arr[b-1]) - arr[b-1][1];
    auto valUseAB = (long[] e) => max (e[0] * 2^^a, e[1]);
    auto gainOnA = (ulong i, long[] e) => valUseAB (e) - (i < b ? valUseB (e) : e[1] + smallestGainOnB);
    auto ans = ansNoA + arr.enumerate.map! (t => gainOnA (t.index, t.value)).maxElement;

    debug { writeln (ansNoA, ' ', arr.enumerate.map! (t => gainOnA (t.index, t.value))); }
    writeln (ans);
}

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

void main()
{
    int n, a, b;
    readf ("%s %s %s", &n, &a, &b);
    readln;
    b = min (b, n);

    Tuple!(long, long) [] arr;
    foreach ( _; 0..n ) {
        auto r = readln.splitter.map! (to!long).array;
        arr ~= tuple(r[0], r[1]);
    }

    arr.sort! (q{ a[0] - a[1] > b[0] - b[1] });

    debug { writeln (arr); }

    auto valUseB = (Tuple!(long, long) e) => max (e[0], e[1]);

    auto ansNoA = arr
        .enumerate
        .map! (t => t.index < b ? valUseB (t.value) : t.value[1])
        .sum;

    if (b == 0) {
        writeln (ansNoA);
        return;
    }

    auto smallestGainOnB = valUseB (arr[b-1]) - arr[b-1][1];
    auto valUseAB = (Tuple!(long, long) e) => max (e[0] * 2^^a, e[1]);
    auto gainOnA = (ulong i, Tuple!(long, long) e) => valUseAB (e) - (i < b ? valUseB (e) : e[1] + smallestGainOnB);
    auto ans = ansNoA + arr.enumerate.map! (t => gainOnA (t.index, t.value)).maxElement;

    debug { writeln (ansNoA, ' ', arr.enumerate.map! (t => gainOnA (t.index, t.value))); }
    writeln (ans);
}

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

immutable long INF = 1L << 59;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto A = s[1];
    auto B = s[2];
    auto H = new long[](N);
    auto D = new long[](N);
    foreach (i; 0..N) {
        auto t = readln.split.map!(to!long);
        H[i] = t[0];
        D[i] = t[1];
    }

    auto S = D.sum;
    auto DD = new long[](N);
    foreach (i; 0..N) DD[i] = max(0L, H[i] - D[i]);
    DD.sort!"a > b"();
    auto DDS = DD[0..min(N, B)].sum;
    long ans = 0;

    if (A == 0) {
        writeln(S + DDS);
        return;
    }

    foreach (i; 0..N) {
        long tmp = (H[i] << A) + S - D[i] + DDS;
        long dd = max(0L, H[i] - D[i]);
        if (B >= N) {
            tmp -= dd;
        } else if (dd > DD[B]) {
            tmp = tmp - dd + DD[B];
        }
        ans = max(ans, tmp);
    }

    ans.writeln;
}

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

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

    long [][] arr;
    foreach (_; 0..n) arr ~= readln.splitter.map!(to!long).array;

    debug { writeln (arr); }

    long mult = 2 ^^ a;
    auto gainMult = (long[] x) => x[0] * mult - x[1];
    int mxind = cast(int) arr.map!(a => gainMult(a)).maxIndex;
    arr[mxind][0] *= mult;

    debug { writeln (mxind, ' ', arr[mxind][0]); }

    auto gain = (long[] x) => x[0] - x[1];
    long[] gains = arr.map!(x => gain(x)).array;
    debug { writeln (arr, ' ', gains); }
    auto ans = arr.map!(q{ a[1] }).sum(0L) +
        gains
        .sort!(q{ a > b })
        .until!(q{ a <= 0 })
        .take(b)
        .sum(0L);

    writeln (ans);
}

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

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

    long [][] arr;
    foreach (_; 0..n) arr ~= readln.splitter.map! (to!long).array;

    debug { writeln (arr); }

    auto gain = (long[] x) => x[0] * 2^^a - x[1];
    auto powerUpOrder = arr.sort! ((a, b) => gain (a) > gain (b));

    debug { writeln (powerUpOrder); }

    auto ans =
        arr.map! (q{ a[1] }).sum
        + powerUpOrder
            .take (b)
            .map! (x => gain (x))
            .until! (q{ a <= 0 })
            .sum;

    writeln (ans);
}

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

void main()
{
    int n, a, b;
    readf ("%s %s %s", &n, &a, &b);
    readln;
    b = min (b, n);

    long [][] arr;
    foreach ( _; 0..n ) arr ~= readln.splitter.map! (to!long).array;

    arr.sort! (q{ a[0] - a[1] > b[0] - b[1] });

    debug { writeln (arr); }

    auto valUseB = (long[] e) => max (e[0], e[1]);

    auto ansNoA = arr
        .enumerate
        .map! (t => t.index < b ? valUseB (t.value) : t.value[1])
        .sum;

    if (b == 0) {
        writeln (ansNoA);
        return;
    }

    auto smallestGainOnB = valUseB (arr[b-1]) - arr[b-1][1];
    auto valUseAB = (long[] e) => max (e[0] * 2^^a, e[1]);
    auto gainOnA = (ulong i, long[] e) => valUseAB (e) - valUseB (e) - (i < b ? 0 : smallestGainOnB);
    auto ans = ansNoA + arr.enumerate.map! (t => gainOnA (t.index, t.value)).maxElement;

    debug { writeln (ansNoA, ' ', arr.enumerate.map! (t => gainOnA (t.index, t.value))); }
    writeln (ans);
}

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

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

    long [][] arr;
    foreach (_; 0..n) arr ~= readln.splitter.map!(to!long).array;

    long ans = arr.map!(q{ a[1] }).sum;

    debug { writeln (arr, ' ', ans); }

    int mult = 2 ^^ a;
    auto gainMult = (long[] x) => x[0] * mult - x[1];
    int mxind = cast(int) arr.map!(a => gainMult(a)).maxIndex;
    arr[mxind][0] *= mult;

    debug { writeln (mxind, ' ', arr[mxind][0]); }

    auto gain = (long[] x) => x[0] - x[1];
    long[] gains = arr.map!(x => gain(x)).array;
    ans += gains
        .sort!(q{ a > b })
        .until!(q{ a <= 0 })
        .take(b)
        .sum;

    writeln (ans);
}

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

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

    long [][] arr;
    foreach (_; 0..n) arr ~= readln.splitter.map!(to!long).array;

    long ans = arr.map!(q{ a[1] }).sum;

    debug { writeln (arr, ' ', ans); }

    long mult = 2 ^^ a;
    auto gainMult = (long[] x) => x[0] * mult - x[1];
    int mxind = cast(int) arr.map!(a => gainMult(a)).maxIndex;
    arr[mxind][0] *= mult;

    debug { writeln (mxind, ' ', arr[mxind][0]); }

    auto gain = (long[] x) => x[0] - x[1];
    long[] gains = arr.map!(x => gain(x)).array;
    ans += gains
        .sort!(q{ a > b })
        .until!(q{ a <= 0 })
        .take(b)
        .sum;

    writeln (ans);
}


There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played. You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d1 and that of between second and third team will be d2.You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?Note that outcome of a match can not be a draw, it has to be either win or loss.

The first line of the input contains a single integer corresponding to number of test cases t (1 ≤ t ≤ 105). Each of the next t lines will contain four space-separated integers n, k, d1, d2 (1 ≤ n ≤ 1012; 0 ≤ k ≤ n; 0 ≤ d1, d2 ≤ k) — data for the current test case.

For each test case, output a single line containing either "yes" if it is possible to have no winner of tournament, or "no" otherwise (without quotes).

NoteSample 1. There has not been any match up to now (k = 0, d1 = 0, d2 = 0). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.Sample 2. You missed all the games (k = 3). As d1 = 0 and d2 = 0, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is "yes".Sample 3. You missed 4 matches, and d1 = 1, d2 = 0. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins).

module main;

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

int check(long n, long k, long d1, long d2)
{
    long tmp = d1 * 2 + d2 + k;
    if (tmp < 0 || tmp % 3 != 0)
    {
        return 0;
    }
    long x = tmp / 3;
    tmp = k + d2 - d1;
    if (tmp < 0 || tmp % 3 != 0)
    {
        return 0;
    }
    long y = tmp / 3;
    tmp = k - d1 - d2 * 2;
    if (tmp < 0 || tmp % 3 != 0)
    {
        return 0;
    }
    long z = tmp / 3;
    long left = n - k;
    auto p = [x, y, z];
    sort(p);
    long need = p[2] - p[0] + p[2] - p[1];
    if (need > left)
    {
        return 0;
    }
    left -= need;
    if (left % 3 == 0)
    {
        writeln("yes");
        return 1;
    }
    return 0;
}

void solve(long n, long k, long d1, long d2)
{
    if (check(n, k, d1, d2)) return;
    if (check(n, k, -d1, d2)) return;
    if (check(n, k, d1, -d2)) return;
    if (check(n, k, -d1, -d2)) return;
    writeln("no");
}

int main(string[] args)
{
    int t;
    while (scanf("%d", &t) == 1)
    {
        foreach (i; 0 .. t)
        {
            long n, k, d1, d2;
            scanf("%lld%lld%lld%lld", &n, &k, &d1, &d2);
            solve(n, k, d1, d2);
        }
    }
    return 0;
}

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

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

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

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

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

bool check(long n, long a, long b, long c) {
	long x = min(a, b, c);
	a -= x;
	b -= x;
	c -= x;
	long rem = n - a - b - c;
	return (rem >= 0 && rem % 3 == 0);
}

bool solve(long N, long K, long D1, long D2) {
	foreach (s; [ +1, -1 ]) foreach (t; [ +1, -1 ]) {
		if (check(K, D1 * s, 0, D2 * t) && check(N - K, D1 * -s, 0, D2 * -t)) {
			return true;
		}
	}
	return false;
}

void main(string[] args) {
	// try {
	for (int TC = readInt; TC--; ) {
		long N = readLong;
		long K = readLong;
		long D1 = readLong;
		long D2 = readLong;
		bool res = solve(N, K, D1, D2);
		writeln(res ? "yes" : "no");
	}
	// } catch (EOFException) {}
}

module main;

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

int check(long n, long k, long d1, long d2)
{
    long tmp = d1 * 2 + d2 + k;
    if (tmp < 0 || tmp % 3 != 0)
    {
        return 0;
    }
    long x = tmp / 3;
    tmp = k + d2 - d1;
    if (tmp < 0 || tmp % 3 != 0)
    {
        return 0;
    }
    long y = tmp / 3;
    tmp = k - d1 - d2 * 2;
    if (tmp < 0 || tmp % 3 != 0)
    {
        return 0;
    }
    long z = tmp / 3;
    //writeln(x, " ", y, " ", z);
    long left = n - k;
    auto p = [x, y, z];
    sort(p);
    long need = p[2] - p[0] + p[2] - p[1];
    if (need > left)
    {
        return 0;
    }
    left -= need;
    if (left % 3 == 0)
    {
        writeln("yes");
        return 1;
    }
    return 0;
}

void solve(long n, long k, long d1, long d2)
{
    if (check(n, k, d1, d2)) return;
    if (check(n, k, -d1, d2)) return;
    if (check(n, k, d1, -d2)) return;
    if (check(n, k, -d1, -d2)) return;
    writeln("no");
}

int main(string[] args)
{
    int t;
    while (scanf("%d", &t) == 1)
    {
        foreach (i; 0 .. t)
        {
            long n, k, d1, d2;
            scanf("%d%d%d%d", &n, &k, &d1, &d2);
            solve(n, k, d1, d2);
        }
    }
    return 0;
}

module main;

import std.stdio, std.string;

void solve(long n, long k, long d1, long d2)
{
    long cnt = d1 + d1 + d2;
    long left = n - k;
    if (cnt > left)
    {
        writeln("no");
    }
    else
    {
        left -= cnt;
        if (left % 3 == 0)
        {
            writeln("yes");
        }
        else
        {
            writeln("no");
        }
    }
}

int main(string[] args)
{
    int t;
    while (scanf("%d", &t) == 1)
    {
        foreach (i; 0 .. t)
        {
            long n, k, d1, d2;
            scanf("%d%d%d%d", &n, &k, &d1, &d2);
            solve(n, k, d1, d2);
        }
    }
    return 0;
}


You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) — the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each testcase print a single integer — the maximum beauty of a proper subsegment.

NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.

// cheese-cracker [2022-08-18]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    arr.sort;
    long res = arr[n-1] + arr[n-2] - (arr[0] + arr[1]);
    writeln(res);
}

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

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
string[] tk; alias tup = Tuple!(long, long);
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; } }


Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).

Print the single number — the maximum number of frames Nicholas can make for his future canvases.

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int n_Cases = 1;
        // n_Cases = cin.readInt;

	for (int case_i = 1; case_i <= n_Cases; case_i++) {
                int n = cin.readInt;
                int[] arr = new int[101];
                for (int i = 0; i < n; i++) {
                        int input = cin.readInt;
                        arr[input]++;
                }
                int k = 0;
                foreach (i; arr) k += i / 2;
                writeln(k / 2);
	}
}


You are organizing a boxing tournament, where $$$n$$$ boxers will participate ($$$n$$$ is a power of $$$2$$$), and your friend is one of them. All boxers have different strength from $$$1$$$ to $$$n$$$, and boxer $$$i$$$ wins in the match against boxer $$$j$$$ if and only if $$$i$$$ is stronger than $$$j$$$.The tournament will be organized as follows: $$$n$$$ boxers will be divided into pairs; the loser in each pair leaves the tournament, and $$$\frac{n}{2}$$$ winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner).Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower.Furthermore, during each stage you distribute the boxers into pairs as you wish.The boxer with strength $$$i$$$ can be bribed if you pay him $$$a_i$$$ dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish?

The first line contains one integer $$$n$$$ ($$$2 \le n \le 2^{18}$$$) — the number of boxers. $$$n$$$ is a power of $$$2$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$, where $$$a_i$$$ is the number of dollars you have to pay if you want to bribe the boxer with strength $$$i$$$. Exactly one of $$$a_i$$$ is equal to $$$-1$$$ — it means that the boxer with strength $$$i$$$ is your friend. All other values are in the range $$$[1, 10^9]$$$.

Print one integer — the minimum number of dollars you have to pay so your friend wins.

NoteIn the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament.In the second test case you can distribute boxers as follows (your friend is number $$$2$$$):$$$1 : 2, 8 : 5, 7 : 3, 6 : 4$$$ (boxers $$$2, 8, 7$$$ and $$$6$$$ advance to the next stage);$$$2 : 6, 8 : 7$$$ (boxers $$$2$$$ and $$$8$$$ advance to the next stage, you have to bribe the boxer with strength $$$6$$$);$$$2 : 8$$$ (you have to bribe the boxer with strength $$$8$$$);

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

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

void solve(){
	int n = rint;
	long[] as = rlong(n);

	auto ah = new RedBlackTree!(long, "a<b", true);
	int k = n - 1;
	if(as[k] == -1){
		"0".writeln;
		return;
	}
	ah.insert(as[k]);
	long ans;
	while(1){
		ans += ah.front;
		ah.removeFront;
		foreach(i; k / 2 .. k){
			if(as[i] == -1){
				ans.writeln;
				return;
			}
			ah.insert(as[i]);
		}
		k /= 2;
	}
}


Madoka is going to enroll in "TSUNS PTU". But she stumbled upon a difficult task during the entrance computer science exam:  A number is called good if it is a multiple of $$$d$$$.  A number is called beatiful if it is good and it cannot be represented as a product of two good numbers. Notice that a beautiful number must be good.Given a good number $$$x$$$, determine whether it can be represented in at least two different ways as a product of several (possibly, one) beautiful numbers. Two ways are different if the sets of numbers used are different.Solve this problem for Madoka and help her to enroll in the best school in Russia!

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — number of test cases. Below comes their description. Each test case consists of two integers $$$x$$$ and $$$d$$$, separated by a space ($$$2 \leq x, d \leq 10^9$$$). It is guaranteed that $$$x$$$ is a multiple of $$$d$$$.

For each set of input data, output "NO" if the number cannot be represented in at least two ways. Otherwise, output "YES". You can output each letter in any case (for example, "YES", "Yes", "yes", "yEs", "yEs" will be recognized as a positive answer).

NoteIn the first example, $$$6$$$ can be represented as $$$6$$$, $$$1 \cdot 6$$$, $$$2 \cdot 3$$$. But $$$3$$$ and $$$1$$$ are not a good numbers because they are not divisible by $$$2$$$, so there is only one way.In the second example, $$$12$$$ can be represented as $$$6 \cdot 2$$$, $$$12$$$, $$$3 \cdot 4$$$, or $$$3 \cdot 2 \cdot 2$$$. The first option is suitable. The second is— no, because $$$12$$$ is not beautiful number ($$$12 = 6 \cdot 2$$$). The third and fourth are also not suitable, because $$$3$$$ is not good number.In the third example, $$$36$$$ can be represented as $$$18 \cdot 2$$$ and $$$6 \cdot 6$$$. Therefore it can be decomposed in at least two ways.

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 x, d;
		readf !(" %s %s") (x, d);

		int [] divs;

		void ask (int y)
		{
			if (y % d == 0 && (y / d) % d != 0)
			{
				divs ~= y;
			}
		}

		for (int e = 1; e * 1L * e <= x; e++)
		{
				ask (e);
				if (e * 1L * e < x)
				{
					ask (x / e);
				}
		}
		sort (divs);

		int num = 0;

		bool recur (int y, int last)
		{
			if (y == 1)
			{
				num += 1;
				return (num > 1);
			}
			foreach (s; divs.find (last))
			{
				if (y < s)
				{
					break;
				}
				if (y % s == 0)
				{
					if (recur (y / s, s))
					{
						return true;
					}
				}
			}
			return false;
		}

		writeln (recur (x, d) ? "YES" : "NO");
	}
}


This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions:  What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$)  What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.

It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.

NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.

immutable multi = false;

void solve(int tc)
{
	int[] testArray = null;
	auto n = testArray is null? readInt!int : cast(int)testArray.length;
	auto k = testArray is null? readInt!int : 1;
	auto or = new int[](n-1);
	auto nd = new int[](n-1);
	auto ans = new int[](n);
	int query(string op, int i, int j)
	{
		if (testArray is null)
		{
			writeln(op, " ", i, " ", j);
			stdout.flush;
			return readInt!int;
		}
		else
		{
			switch(op)
			{
			case "or":
				return testArray[i-1] | testArray[j-1];
			case "and":
				return testArray[i-1] & testArray[j-1];
			default: assert(0);
			}
		}
	}
	auto or23 = query("or", 2, 3);
	foreach(i; 1 .. n)
	{
		or[i-1] = query("or", 1, i + 1);
		nd[i-1] = query("and", 1, i + 1);
	}
	auto andedOrs = or.fold!((a, b) => a & b);
	auto oredAns = nd.fold!((a, b) => a | b);
	void solveBit(int q)
	{
		if (andedOrs&(1<<q))
		{
			if (oredAns&(1<<q))
			{
				// we are sure a1 at q = 1
				ans[0] |= (1<<q);
				foreach(i; 1 .. n)
				{
					ans[i] |= nd[i-1]&(1<<q);
				}
				return;
			}
			// either 0 1 1 ... or 1 0 0 ...
			// check or23
			if (or23&(1<<q))
			{
				// 0 1 1...
				foreach(i; 1 .. n)
					ans[i] |= (1<<q);
			}
			else
			{
				// 1 0 0...
				ans[0] |= (1<<q);
			}
		}
		else
		{
			// we are sure a1 at q = 0
			foreach(i; 1 .. n)
			{
				ans[i] |= or[i-1]&(1<<q);
			}
			return;
		}
	}
	foreach(b; 0 .. 31)
		solveBit(b);
	if (testArray !is null)
	{
		writeln(testArray);
		writeln(ans);
	}
	sort(ans);
	writeln("finish ", ans[k-1]);
	stdout.flush;
}
//{{{
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.algorithm, std.array, std.container, std.conv, std.format, std.math, std.numeric, std.random, std.range, std.stdio, std.string, std.typecons, core.bitop;

long query(int type, int idx1, int idx2)
{
  if (type == 0) {
    writefln("or %d %d", idx1, idx2);
    stdout.flush();
    return readln.strip.to!long;
  } else {
    writefln("and %d %d", idx1, idx2);
    stdout.flush();
    return readln.strip.to!long;
  }
}

long recover_a1(long orab, long andab, long orbc, long andbc, long andac, long orac)
{
  long ans;
  long cnt;
  foreach (a ; 0 .. 2) {
    foreach (b ; 0 .. 2) {
      foreach (c ; 0 .. 2) {
        if (andbc == (b & c) && orbc == (b | c) && andab == (a & b) && orab == (a | b) && andac == (a & c) && orac == (a | c)) {
          ans = a;
          cnt++;
        }
      }
    }
  }
  assert(cnt == 1);
  return ans;
}

long recover_a32(long orab, long andab, long orbc, long andbc, long andac, long orac)
{
  long ans;
  foreach (b ; 0 .. 32) {
    ans |= recover_a1((orab >> b) & 1, (andab >> b) & 1, (orbc >> b) & 1, (andbc >> b) & 1, (andac >> b) & 1, (orac >> b) & 1) << b;
  }
  return ans;
}

void main()
{
  int n, k;
  readln.formattedRead!" %d %d "(n, k);
  long[] a_xor, a_or, a_and;

  foreach (i ; 0 .. n - 1) {
    int idx1 = (i + 0) % n + 1;
    int idx2 = (i + 1) % n + 1;
    long qor = query(0, idx1, idx2);
    long qand = query(1, idx1, idx2);
    a_or ~= qor;
    a_and ~= qand;
    a_xor ~= (qor - qand);
  }

  long orab = a_or[0];
  long andab = a_and[0];
  long orbc = a_or[1];
  long andbc = a_and[1];
  long orac = query(0, 1, 3);
  long andac = query(1, 1, 3);
  long a0 = recover_a32(orab, andab, orbc, andbc, andac, orac);
  long[] ans = [a0];
  foreach (i ; 1 .. n) {
    ans ~= ans[i - 1] ^ a_xor[i - 1];
  }
  ans.sort;
  writefln("finish %d", ans[k - 1]);
}

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

int main(string[] args)
{
    int n, k;
    readf("%d %d\n", &n, &k);
    auto r = new int[][][](3, 3, 2);
    foreach (i; 1 .. 4) foreach (j; i + 1 .. 4)
    {
        writeln("or ", i, " ", j);
        stdout.flush;
        r[i - 1][j - 1][0] = to!int(readln.strip);
        if (i == 1 && j == 3) continue;
        writeln("and ", i, " ", j);
        stdout.flush;
        r[i - 1][j - 1][1] = to!int(readln.strip);
    }
    auto a = new int[n];
    foreach (i; 0 .. 30)
    {
        if (r[0][1][1] & (1 << i))
        {
            a[0] |= 1 << i;
            continue;
        }
        if (!(r[0][1][0] & (1 << i)) || !(r[0][2][0] & (1 << i))) continue;
        if (!(r[1][2][1] & (1 << i))) a[0] |= 1 << i;
    }
    foreach (i; 1 .. 3) foreach (j; 0 .. 30)
    {
        if (r[i - 1][i][1] & (1 << j)) a[i] |= 1 << j;
        else if ((r[i - 1][i][0] & (1 << j)) && !(a[i - 1] & (1 << j))) a[i] |= 1 << j;
    }
    foreach (i; 3 .. n)
    {
        writeln("or ", i, " ", i + 1);
        stdout.flush;
        auto ro = to!int(readln.strip);
        writeln("and ", i, " ", i + 1);
        stdout.flush;
        auto ra = to!int(readln.strip);
        foreach (j; 0 .. 30)
        {
            if (ra & (1 << j)) a[i] |= 1 << j;
            else if ((ro & (1 << j)) && !(a[i - 1] & (1 << j))) a[i] |= 1 << j;
        }
    }
    a.sort;
    writeln("finish ", a[k - 1]);
    stdout.flush;
    return 0;
}

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

long query(int type, int idx1, int idx2)
{
  if (type == 0) {
    writefln("or %d %d", idx1, idx2);
    stdout.flush();
    return readln.strip.to!long;
  } else {
    writefln("and %d %d", idx1, idx2);
    stdout.flush();
    return readln.strip.to!long;
  }
}

/* 1-bit bruteforce version */

long recover_a1(long orab, long andab, long orbc, long andbc, long andac, long orac)
{
  long ans;
  long cnt;
  foreach (a ; 0 .. 2) {
    foreach (b ; 0 .. 2) {
      foreach (c ; 0 .. 2) {
        if (andbc == (b & c) && orbc == (b | c) && andab == (a & b) && orab == (a | b) && andac == (a & c) && orac == (a | c)) {
          ans = a;
          cnt++;
        }
      }
    }
  }
  assert(cnt == 1);
  return ans;
}

/*
 * We know: A | B, A & B, B | C, B & C, A | C, A & C
 * Need to recover and return a 32-bit value A.
 */

long recover_a32(long orab, long andab, long orbc, long andbc, long andac, long orac)
{
  long ans;
  foreach (b ; 0 .. 32) {
    ans |= recover_a1((orab >> b) & 1, (andab >> b) & 1, (orbc >> b) & 1, (andbc >> b) & 1, (andac >> b) & 1, (orac >> b) & 1) << b;
  }
  return ans;
}

void main()
{
  int n, k;
  readln.formattedRead!" %d %d "(n, k);
  long[] a_xor, a_or, a_and;

  foreach (i ; 0 .. n - 1) {
    int idx1 = (i + 0) % n + 1;
    int idx2 = (i + 1) % n + 1;
    long qor = query(0, idx1, idx2);
    long qand = query(1, idx1, idx2);
    a_or ~= qor;
    a_and ~= qand;
    a_xor ~= (qor - qand);
  }

  long orab = a_or[0];
  long andab = a_and[0];
  long orbc = a_or[1];
  long andbc = a_and[1];
  long orac = query(0, 1, 3);
  long andac = query(1, 1, 3);
  long a0 = recover_a32(orab, andab, orbc, andbc, andac, orac);
  long[] ans = [a0];
  foreach (i ; 1 .. n) {
    ans ~= ans[i - 1] ^ a_xor[i - 1];
  }
  ans.sort;
  writefln("finish %d", ans[k - 1]);
}

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

int ask (string op) (int a, int b)
{
	writeln (op, " ", a + 1, " ", b + 1);
	stdout.flush ();
	return readln.strip.to !(int);
}

void main ()
{
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		k -= 1;
		readln;

		int [3] [3] or;
		int [3] [3] and;
		static foreach (s; AliasSeq !("or", "and"))
		{
			foreach (i; 0..3)
			{
				foreach (j; i + 1..3)
				{
					mixin (format !(`%s[i][j] = ` ~
					    `ask !("%s") (i, j);`) (s, s));
				}
			}
		}

		bool checkBit (int [3] bits)
		{
			foreach (i; 0..3)
			{
				foreach (j; i + 1..3)
				{
					if ((bits[i] | bits[j]) !=
					    (or[i][j] & 1))
					{
						return false;
					}
					if ((bits[i] & bits[j]) !=
					    (and[i][j] & 1))
					{
						return false;
					}
				}
			}
			return true;
		}

		auto a = new int [n];

bits_loop:
		foreach (b; 0..30)
		{
			scope (exit)
			{
				static foreach (s; AliasSeq !("or", "and"))
				{
					foreach (i; 0..3)
					{
						foreach (j; i + 1..3)
						{
							mixin (format
							    !(`%s[i][j] ` ~
							    `>>= 1;`) (s));
						}
					}
				}
			}

			foreach (x; 0..2)
			{
				foreach (y; 0..2)
				{
					foreach (z; 0..2)
					{
						if (checkBit ([x, y, z]))
						{
							a[0] |= x << b;
							a[1] |= y << b;
							a[2] |= z << b;
							continue bits_loop;
						}
					}
				}
			}

			assert (false);
		}
		debug {writeln (a);}

		foreach (i; 3..n)
		{
			auto theOr = ask !("or") (0, i);
			auto theAnd = ask !("and") (0, i);
			a[i] = theAnd | (theOr & ~a[0]);
			debug {writeln (a);}
		}

		sort (a);
		writeln ("finish", " ", a[k]);
		stdout.flush ();
	}
}

immutable multi = false;

void solve(int tc)
{
	int[] testArray = null;
	auto n = testArray is null? readInt!int : cast(int)testArray.length;
	auto k = testArray is null? readInt!int : 1;
	auto or = new int[](n-1);
	auto nd = new int[](n-1);
	auto ans = new int[](n);
	int query(string op, int i, int j)
	{
		if (testArray is null)
		{
			writeln(op, " ", i, " ", j);
			stdout.flush;
			return readInt!int;
		}
		else
		{
			switch(op)
			{
			case "or":
				return testArray[i-1] | testArray[j-1];
			case "and":
				return testArray[i-1] & testArray[j-1];
			default: assert(0);
			}
		}
	}
	auto or23 = query("or", 2, 3);
	foreach(i; 1 .. n)
	{
		or[i-1] = query("or", 1, i + 1);
		nd[i-1] = query("and", 1, i + 1);
	}
	auto andedOrs = or.fold!((a, b) => a & b);
	auto oredAns = nd.fold!((a, b) => a | b);
	void solveBit(int q)
	{
		if (andedOrs&(1<<q))
		{
			if (oredAns&(1<<q))
			{
				// we are sure a1 at q = 1
				ans[0] |= (1<<q);
				foreach(i; 1 .. n)
				{
					ans[i] |= nd[i-1]&(1<<q);
				}
				return;
			}
			// either 0 1 1 ... or 1 0 0 ...
			// check or23
			if (or23&(1<<q))
			{
				// 0 1 1...
				foreach(i; 1 .. n)
					ans[i] |= (1<<q);
			}
			else
			{
				// 1 0 0...
				ans[0] |= (1<<q);
			}
		}
		else
		{
			// we are sure a1 at q = 0
			foreach(i; 1 .. n)
			{
				ans[i] |= or[i-1]&(1<<q);
			}
			return;
		}
	}
	foreach(b; 0 .. 21)
		solveBit(b);
	if (testArray !is null)
	{
		writeln(testArray);
		writeln(ans);
	}
	sort(ans);
	writeln("finish ", ans[k-1]);
	stdout.flush;
}
//{{{
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;
// }}}

immutable multi = false;

void solve(int tc)
{
	int[] testArray = null;
	auto n = testArray is null? readInt!int : cast(int)testArray.length;
	auto k = testArray is null? readInt!int : 1;
	auto or = new int[](n-1);
	auto nd = new int[](n-1);
	auto ans = new int[](n);
	int query(string op, int i, int j)
	{
		if (testArray is null)
		{
			writeln(op, " ", i, " ", j);
			stdout.flush;
			return readInt!int;
		}
		else
		{
			switch(op)
			{
			case "or":
				return testArray[i-1] | testArray[j-1];
			case "and":
				return testArray[i-1] & testArray[j-1];
			default: assert(0);
			}
		}
	}
	auto or23 = query("or", 2, 3);
	foreach(i; 1 .. n)
	{
		or[i-1] = query("or", 1, i + 1);
		nd[i-1] = query("and", 1, i + 1);
	}
	auto andedOrs = or.fold!((a, b) => a & b);
	auto oredAns = nd.fold!((a, b) => a | b);
	void solveBit(int q)
	{
		if (andedOrs&(1<<q))
		{
			if (oredAns&(1<<q))
			{
				// we are sure a1 at q = 1
				ans[0] |= (1<<q);
				foreach(i; 1 .. n)
				{
					ans[i] |= nd[i-1]&(1<<q);
				}
				return;
			}
			// either 0 1 1 ... or 1 0 0 ...
			// check or23
			if (or23&(1<<q))
			{
				// 0 1 1...
				foreach(i; 1 .. n)
					ans[i] |= (1<<q);
			}
			else
			{
				// 1 0 0...
				ans[0] |= (1<<q);
			}
		}
		else
		{
			// we are sure a1 at q = 0
			foreach(i; 1 .. n)
			{
				ans[i] |= or[i-1]&(1<<q);
			}
			return;
		}
	}
	foreach(b; 0 .. 21)
		solveBit(b);
	if (testArray !is null)
	{
		writeln(testArray);
		writeln(ans);
	}
	sort(ans);
	ans[k-1].writeln;
}
//{{{
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.algorithm, std.array, std.container, std.conv, std.format, std.math, std.numeric, std.random, std.range, std.stdio, std.string, std.typecons, core.bitop;

long query(int type, int idx1, int idx2)
{
  if (type == 0) {
    writefln("or %d %d", idx1, idx2);
    stdout.flush();
    return readln.strip.to!long;
  } else {
    writefln("and %d %d", idx1, idx2);
    stdout.flush();
    return readln.strip.to!long;
  }
}

long recover_a1(long orab, long andab, long orbc, long andbc, long andac, long orac)
{
  long ans;
  long cnt;
  foreach (a ; 0 .. 2) {
    foreach (b ; 0 .. 2) {
      foreach (c ; 0 .. 2) {
        if (andbc == (b & c) && orbc == (b | c) && andab == (a & b) && orab == (a | b) && andac == (a & c) && orac == (a | c)) {
          ans = a;
          cnt++;
        }
      }
    }
  }
  assert(cnt == 1);
  return ans;
}

long recover_a32(long orab, long andab, long orbc, long andbc, long andac, long orac)
{
  long ans;
  foreach (b ; 0 .. 32) {
    ans |= recover_a1((orab >> b) & 1, (andab >> b) & 1, (orbc >> b) & 1, (andbc >> b) & 1, (andac >> b) & 1, (orac >> b) & 1) << b;
  }
  return ans;
}

void main()
{
  int n, k;
  readln.formattedRead!" %d %d "(n, k);
  long[] a_xor, a_or, a_and;

  foreach (i ; 0 .. n - 1) {
    int idx1 = (i + 0) % n + 1;
    int idx2 = (i + 1) % n + 1;
    long qor = query(0, idx1, idx2);
    long qand = query(1, idx1, idx2);
    a_or ~= qor;
    a_and ~= qand;
    a_xor ~= (qor - qand);
  }

  long orab = a_or[0];
  long andab = a_and[0];
  long orbc = a_or[1];
  long andbc = a_and[1];
  long orac = query(0, 1, 3);
  long andac = query(1, 1, 3);
  long a0 = recover_a32(orab, andab, orbc, andbc, andac, orac);
  long[] ans = [a0];
  foreach (i ; 1 .. n) {
    ans ~= ans[i - 1] ^ a_xor[i - 1];
  }
  writeln(ans[k - 1]);
}


Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$.  For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty.

The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$.

For each test case, print a single integer — the highest possible beauty.

NoteAn optimal solution for the first test case is shown in the following figure:  The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure:  The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$.

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 root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        auto A = new int[N]; foreach (i; 0 .. N) A[i] = readInt - 1;
        auto B = new int[N]; foreach (i; 0 .. N) B[i] = readInt - 1;

        auto uf = new int[N];
        uf[] = -1;
        foreach (i; 0 .. N) {
          uf.connect(A[i], B[i]);
        }

        int[] cs;
        foreach (r; 0 .. N) if (uf[r] < 0) {
          cs ~= -uf[r];
        }
        cs.sort.reverse;
        debug {
          writeln("cs = ", cs);
        }

        long ans;
        {
          int num;
          int l = 0, r = N - 1;
          int next() {
            return (num++ % 2 == 0) ? l++ : r--;
          }
          foreach (c; cs) {
            const cc = c / 2 * 2;
            if (cc <= 1) continue;
            const s = next();
            int u = s;
            foreach (_; 1 .. cc) {
              const v = next();
              ans += abs(u - v);
              u = v;
            }
            ans += abs(u - s);
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

immutable int NA = -1;

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;
		a[] -= 1;
		auto b = readln.splitter.map !(to !(int)).array;
		b[] -= 1;

		auto p = new int [n];
		foreach (i; 0..n)
		{
			p[a[i]] = i;
		}
		auto q = new int [n];
		foreach (i; 0..n)
		{
			q[b[i]] = i;
		}
		auto c = new int [n];
		foreach (i; 0..n)
		{
			c[p[i]] = q[i];
		}

		long res = 0;
		int lo = 0;
		int hi = n - 1;
		foreach (i; 0..n)
		{
			if (c[i] != NA)
			{
				int len = 0;
				int x = i;
				while (c[x] != NA)
				{
					len += 1;
					int y = c[x];
					c[x] = NA;
					x = y;
				}
				len /= 2;
/*
				 5 4 3 4
				1 6 2 5 1
				+10 +6
*/
				foreach (step; 0..len)
				{
					res += hi - lo;
					lo += 1;
					hi -= 1;
				}
			}
		}
		writeln (res * 2);
	}
}

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 root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        auto A = new int[N]; foreach (i; 0 .. N) A[i] = readInt - 1;
        auto B = new int[N]; foreach (i; 0 .. N) B[i] = readInt - 1;

        auto uf = new int[N];
        uf[] = -1;
        foreach (i; 0 .. N) {
          uf.connect(A[i], B[i]);
        }

        int[] cs;
        foreach (r; 0 .. N) if (uf[r] < 0) {
          cs ~= -uf[r];
        }
        cs.sort.reverse;
        debug {
          writeln("cs = ", cs);
        }

        long ans;
        {
          int num;
          int l = 0, r = N - 1;
          int next() {
            return (num++ % 2 == 0) ? l++ : r--;
          }
          foreach (c; cs) {
            const s = next();
            int u = s;
            foreach (_; 1 .. c) {
              const v = next();
              ans += abs(u - v);
              u = v;
            }
            ans += abs(u - s);
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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 root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        auto A = new int[N]; foreach (i; 0 .. N) A[i] = readInt - 1;
        auto B = new int[N]; foreach (i; 0 .. N) B[i] = readInt - 1;

        auto uf = new int[N];
        uf[] = -1;
        foreach (i; 0 .. N) {
          uf.connect(A[i], B[i]);
        }

        int[] cs;
        foreach (r; 0 .. N) if (uf[r] < 0) {
          if (-uf[r] >= 2) {
            cs ~= -uf[r];
          }
        }
        cs.sort;
        debug {
          writeln("cs = ", cs);
        }

        long ans;
        {
          int num;
          int l = 0, r = N - 1;
          int next() {
            return (num++ % 2 == 0) ? l++ : r--;
          }
          foreach (c; cs) {
            const s = next();
            int u = s;
            foreach (_; 0 .. c - 1) {
              const v = next();
              ans += abs(u - v);
              u = v;
            }
            ans += abs(u - s);
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}