The sequence of $$$m$$$ integers is called the permutation if it contains all integers from $$$1$$$ to $$$m$$$ exactly once. The number $$$m$$$ is called the length of the permutation.Dreamoon has two permutations $$$p_1$$$ and $$$p_2$$$ of non-zero lengths $$$l_1$$$ and $$$l_2$$$.Now Dreamoon concatenates these two permutations into another sequence $$$a$$$ of length $$$l_1 + l_2$$$. First $$$l_1$$$ elements of $$$a$$$ is the permutation $$$p_1$$$ and next $$$l_2$$$ elements of $$$a$$$ is the permutation $$$p_2$$$. You are given the sequence $$$a$$$, and you need to find two permutations $$$p_1$$$ and $$$p_2$$$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains one integer $$$n$$$ ($$$2 \leq n \leq 200\,000$$$): the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n-1$$$). The total sum of $$$n$$$ is less than $$$200\,000$$$.

For each test case, the first line of output should contain one integer $$$k$$$: the number of ways to divide $$$a$$$ into permutations $$$p_1$$$ and $$$p_2$$$. Each of the next $$$k$$$ lines should contain two integers $$$l_1$$$ and $$$l_2$$$ ($$$1 \leq l_1, l_2 \leq n, l_1 + l_2 = n$$$), denoting, that it is possible to divide $$$a$$$ into two permutations of length $$$l_1$$$ and $$$l_2$$$ ($$$p_1$$$ is the first $$$l_1$$$ elements of $$$a$$$, and $$$p_2$$$ is the last $$$l_2$$$ elements of $$$a$$$). You can print solutions in any order.

NoteIn the first example, two possible ways to divide $$$a$$$ into permutations are $$$\{1\} + \{4, 3, 2, 1\}$$$ and $$$\{1,4,3,2\} + \{1\}$$$.In the second example, the only way to divide $$$a$$$ into permutations is $$$\{2,4,1,3\} + \{2,1\}$$$.In the third example, there are no possible ways.

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) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new int[][][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;
		auto set = new bool[](n);
		int m;
		int[] arr;
		foreach (i; 0..n)
		{
			if (set[a[i]]) break;
			set[a[i]] = true;
			m.chmax(a[i]);
			if (m == i+1)
			{
				arr ~= i+1;
			}
		}
		auto set2 = new bool[](n);
		int m2;
		int[] arr2;
		foreach_reverse (i; 0..n)
		{
			if (set2[a[i]]) break;
			set2[a[i]] = true;
			m2.chmax(a[i]);
			if (m2 == n-i)
			{
				arr2 ~= i;
			}
		}
		arr2.reverse;
		int l;
		debug writeln(arr);
		debug writeln(arr2);
		(){
		if (arr2.empty) return;
		foreach (e; arr)
		{
			while (arr2[l] < e)
			{
				++l;
				if (l == arr2.length) return;
			}
			if (e == arr2[l])
			{
				ans[ti] ~= [e, n - e];
			}
		}}();
	}

	foreach (e; ans)
	{
		writeln(e.length);
		foreach (ee; e)
			writeln(ee[0], " ", ee[1]);
	}
	stdout.flush;
	debug readln;
}


Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.

The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.

I hate it
I hate that I love it
I hate that I love that I hate it

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 read_string() {
                while (tokens.empty) {
                tokens = readln.split;
        }
        auto token = tokens.front;
                tokens.popFront;
                return token;
        }

        int read_int() {
                return read_string.to!int;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // int t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                char[] love = "I love".dup;
                char[] hate = "I hate".dup;
                for (int i = 0; i < n; i++) {
                        if (i % 2 == 0) write(hate);
                        else write(love);
                        if (i != n - 1) write(" that ");
                }
                write(" it");
                writeln();
        }
}

import std.stdio;
import std.string;
import std.conv;

void main()
{
  auto n = stdin.readln.strip.to!int;
  write("I hate");
  for(int i = 2; i <= n; i++)
    write(" that I " ~ (i%2==0?"love":"hate"));
  writeln(" it");
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.math;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	write("I hate");
	foreach (int i; 1..n)
	{
		write((i % 2 == 0) ? " that I hate" : " that I love");
	}
	write(" it");
	return 0;
}

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

int toplamGuzellikSayisi = 0;

void main() {

    auto satirSayisi = stdin.readln.strip.to!int();
	char[] hulkunHisleri;
	for ( int i = 0; i < satirSayisi; i++ )
	{
		if ( i == satirSayisi - 1  )
		{
		    if ( i % 2 )
				hulkunHisleri ~= "I love it ";
			else
				hulkunHisleri ~= "I hate it ";
		}
		else if ( i % 2 )
			hulkunHisleri ~= "I love that ";
		else
			hulkunHisleri ~= "I hate that ";
	}
	writeln(hulkunHisleri.chomp());
}

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

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

    foreach (i ; 0 .. n) {
        write("I ", ["hate ", "love "][i&1], ["that ", "it"][i == n-1]);
    }
}

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

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

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

import std.stdio;

int main()
{
	int a=0;
	readf(" %d", &a);
	if (a%2==0)
	{
		for (int i=0; i<(a-2)/2; i++)
		{
			write("I hate that I love that ");
		}
		write("I hate that I love it");
	}
	else
	{
		for (int i=0; i<(a-1)/2; i++)
		{
			write("I hate that I love that ");
		}
		write("I hate it");
	}
	return 0;
}

import std.stdio;

int main()
{
	int a=0;
	readf(" %d", &a);
	if (a%3==1)
	{
		writeln("I hate it");
	}
	else if (a%3==2)
	{
		writeln("I hate that I love it");
	}
	else
	{
		writeln("I hate that I love that I hate it");
	}
	return 0;
}

import std.stdio;

int main()
{
	int a=0;
	readf(" %x", &a);
	if (a%3==1)
	{
		writeln("I hate it");
	}
	else if (a%3==2)
	{
		writeln("I hate that I love it");
	}
	else
	{
		writeln("I hate that I love that I hate it");
	}
	return 0;
}

import std.stdio;

int main()
{
	int a=0;
	readf(" %x", &a);
	if (a%2==0)
	{
		for (int i=0; i<(a-2)/2; i++)
		{
			write("I hate that I love that ");
		}
		write("I hate that I love it");
	}
	else
	{
		for (int i=0; i<(a-1)/2; i++)
		{
			write("I hate that I love that ");
		}
		write("I hate it");
	}
	return 0;
}


Sehr Sus is an infinite hexagonal grid as pictured below, controlled by MennaFadali, ZerooCool and Hosssam.They love equilateral triangles and want to create $$$n$$$ equilateral triangles on the grid by adding some straight lines. The triangles must all be empty from the inside (in other words, no straight line or hexagon edge should pass through any of the triangles).You are allowed to add straight lines parallel to the edges of the hexagons. Given $$$n$$$, what is the minimum number of lines you need to add to create at least $$$n$$$ equilateral triangles as described?  Adding two red lines results in two new yellow equilateral triangles.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$) — the required number of equilateral triangles.

For each test case, print the minimum number of lines needed to have $$$n$$$ or more equilateral triangles.

NoteIn the first and second test cases only 2 lines are needed. After adding the first line, no equilateral triangles will be created no matter where it is added. But after adding the second line, two more triangles will be created at once.   In the third test case, the minimum needed is 3 lines as shown below.

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

void solve() {
    long N = readln.chomp.to!long;

    long f() {

        bool C(long a, long b, long c) {
            return 2L * (a * b + b * c + c * a) >= N;
        }

        long lb = 0, ub = 1_000_000;
        while (lb + 1 < ub) {
            long mid = (lb + ub) / 2;
            (C(mid, mid, mid) ? ub : lb) = mid;
        }
        if (C(lb + 1, lb, lb)) {
            return 3*lb + 1;
        }
        if (C(lb + 1, lb + 1, lb)) {
            return 3*lb + 2;
        }
        return 3 * (lb + 1);
    }

    writeln(f());

}

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


Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa".Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y".There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon".Sergey is very busy and asks you to help him and write the required program.

The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of letters in the word written by Stepan. The second line contains the string s which has length that equals to n and contains only lowercase English letters — the word written by Stepan.

Print the single string — the word written by Stepan converted according to the rules described in the statement.

pobeda implemeentatioon aeiouyaeeioouy aoiuyeggghhh

import std.stdio : writeln, stdin;
import std.conv : to;
import std.range : dropOne;
import core.stdc.stdio;

void main()
{
    int n;
    scanf("%d", &n);
    string ss;
    int[100005] arr;
    for(int i = 0 ;i < 100005; ++i){
        arr[i] = 1;
    }
    foreach(word; stdin.byLine)
    {
        ss = to!string(word);
    }
    for (int i = 0; i < n; ++i) {
        int curr = i;
        if(!(ss[i] == 'a' || ss[i] =='e' || ss[i] =='i' || ss[i] =='o' || ss[i] =='u' || ss[i] =='y'))
        {
           continue;
        }
        while((i+1) < n && ss[i + 1] == ss[curr]){
            ++arr[curr];
            arr[i+1] = 0;
            ++i;
        }
    }

    for(int i = 0; i < n; ++i){
        if(arr[i] == 0){
            continue;
        }
         if(arr[i] ==2 && (ss[i] == 'e' || ss[i] == 'o'))
        {
            printf("%c%c", ss[i], ss[i]);
            while((i + 1) < n && arr[i+1] == 0)
            {
                ++i;
            }
        }
        else if(arr[i] > 0)
        {
            printf("%c", ss[i]);
            while((i + 1) < n && arr[i+1] == 0)
            {
                ++i;
            }
        }

    }
}

module main;
import std.c.stdio;
import std.stdio : writeln, stdin;
import std.conv : to;
import std.range : dropOne;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	char [] arr = new char[n + 1];
	scanf("%c", &arr[0]);
	for(int i = 0; i<n; i++)
		scanf("%c", &arr[i]);

	for(int i = 0; i < n; i++) {
        if ((i == 0 || arr[i - 1] != arr[i]) && i != n - 1 && arr[i] == 'o' && arr[i + 1] == 'o' && (i + 2 == n || arr[i + 2] != 'o')) {
            printf("%c", arr[i]);
            printf("%c", arr[i + 1]);
            i += 1;
        }
        else if ((i == 0 || arr[i - 1] != arr[i]) && i != n - 1 && arr[i] == 'e' && arr[i + 1] == 'e' && (i + 2 == n || arr[i + 2] != 'e')) {
            printf("%c", arr[i]);
            printf("%c", arr[i + 1]);
            i += 1;
        }
	    else if ((arr[i] == 'a' || arr[i] == 'i' || arr[i] == 'e' || arr[i] == 'o' || arr[i] == 'y' || arr[i] == 'u') && (i == 0 || arr[i] != arr[i - 1])) {
	        printf("%c", arr[i]);
	    }
	    else if (!(arr[i] == 'a' || arr[i] == 'i' || arr[i] == 'e' || arr[i] == 'o' || arr[i] == 'y' || arr[i] == 'u'))
	        printf("%c", arr[i]);
	}

	return 0;
}

import std.stdio;
import std.string;

int n, cnt=0;

void main(string[] argv) {

	readf("%s\n", &n);
	string buff, ans="";
	//ans = "";
	buff = readln('\n');
	foreach(int i; 0..n) {
		    if((i>0)&&(buff[i]==buff[i-1]) &&
		    (buff[i]=='a'||buff[i]=='e'||buff[i]=='i'||buff[i]=='o'||buff[i]=='u'||buff[i]=='y')){
		        //cnt++;
		    }
		    else{
		       ans = ans~buff[i];
		    }

		    if((buff[i]=='e'||buff[i]=='o')
		    && (i==0 || (buff[i]!=buff[i-1])) && (i+1<n) && (buff[i]==buff[i+1]) && (i+2>=n || (buff[i]!=buff[i+2]))){
		        ans = ans~buff[i];
		    }

		/*if(buff.length <= 11)
			write(buff);
		else {
			writeln(buff[0], buff.length-3, buff[$-2]);
		}*/
	}
	write(ans);
	return;
}

module main;

import core.stdc.stdio;

int main(string[] arv) {
	int n;
	scanf("%d", &n);
	char [] s = new char[n];
	for(int i = 0; i < n; i++) scanf(" %c", &s[i]);
	for(int i = 0; i < n; i++) {
		if(s[i] != 'a' && s[i] != 'e' && s[i] != 'i' && s[i] != 'o' && s[i] != 'u' && s[i] != 'y')
			printf("%c", s[i]);
		else {
			int count = 1;
			for(int j = i + 1; j < n && s[i] == s[j]; j++) count++;
			if((s[i] == 'e' || s[i] == 'o') && count == 2)
				printf("%c%c", s[i], s[i]);
			else
				printf("%c", s[i]);
			while(s[i] == s[i+1]) i++;
		}
	}
	printf("\n");
	return 0;
}

import std.stdio : writeln, stdin;
import std.conv : to;
import std.range : dropOne;

import core.stdc.stdio;

int main(string[] argv)
{
     int cnt = 1;
     char last = 'Z';
     int n;
     scanf("%d",&n);
     foreach(words; stdin.byLine)
     {
        foreach(word;words){
        if(word != last){
            if (last != 'Z') {
                if (last == 'a' || last == 'e' || last == 'i' || last == 'o' || last == 'u' || last == 'y'){
                    if ((last != 'e' && last != 'o') || cnt != 2) cnt = 1;
                }
                for(int i = 0; i < cnt; ++i) printf("%c",last);
            }
            cnt = 0;
        }
        last = word;
        cnt++;
     }
     if (last != 'Z') {
          if (last == 'a' || last == 'e' || last == 'i' || last == 'o' || last == 'u' || last == 'y'){
             if ((last != 'e' && last != 'o') || cnt != 2) cnt = 1;
          }
           for(int i = 0; i < cnt; ++i) printf("%c",last);
      }
     }
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	char chaine[3*1000*100+1];
	scanf("%d\n", &n);
	for(int i=0;i<n;i++)
	    scanf("%c", &chaine[i]);
	//putchar(chaine[0]);
	for(int i=0;i<n;i++){
	    if((chaine[i]!='a'&&chaine[i]!='e'&&chaine[i]!='i'&&chaine[i]!='o'&&chaine[i]!='u'&&chaine[i]!='y')|| chaine[i]!=chaine[i+1]||(chaine[i]!=chaine[i+2]&&(chaine[i]=='e'||chaine[i]=='o')))
	        putchar(chaine[i]);
        else{
            putchar(chaine[i]);
            i++;
            while(i<n&&chaine[i]==chaine[i-1])i++;
            i--;
        }
	}

	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d ", &n);
	char [] arr = new char[n];
	for(int i = 0; i < n; i++)
		scanf("%c", &arr[i]);
	for(int i = 0; i < n; i++){
	if(arr[i] == 'a' || arr[i] == 'i' || arr[i] == 'u' || arr[i] == 'y' || arr[i] == 'o' || arr[i] == 'e'){
    	if(i != n - 1 && arr[i] == arr[i + 1])
	        continue;
	   if(arr[i] == 'o' || arr[i] == 'e'){
	    if(i > 1 && arr[i - 2] == arr[i] && arr[i - 1] == arr[i]){
	    printf("%c", arr[i]);
	     continue;
	     }
	     if(i > 0 && arr[i - 1] == arr[i]){
	        printf("%c", arr[i]);
	     }
	   }
	   else
	   {
	    if(i && arr[i] == arr[i - 1]){
	    printf("%c", arr[i]);
	    continue;
	    }
	   }
    }
	    printf("%c", arr[i]);
	}
	return 0;
}


People worry that computers will get too smart and take over the world, but the real problem is that they're too stupid and they've already taken over the world.— Pedro DomingosYou work for a well-known department store that uses leading technologies and employs mechanistic work — that is, robots!The department you work in sells $$$n \cdot k$$$ items. The first item costs $$$1$$$ dollar, the second item costs $$$2$$$ dollars, and so on: $$$i$$$-th item costs $$$i$$$ dollars. The items are situated on shelves. The items form a rectangular grid: there are $$$n$$$ shelves in total, and each shelf contains exactly $$$k$$$ items. We will denote by $$$a_{i,j}$$$ the price of $$$j$$$-th item (counting from the left) on the $$$i$$$-th shelf, $$$1 \le i \le n, 1 \le j \le k$$$.Occasionally robots get curious and ponder on the following question: what is the mean price (arithmetic average) of items $$$a_{i,l}, a_{i,l+1}, \ldots, a_{i,r}$$$ for some shelf $$$i$$$ and indices $$$l \le r$$$? Unfortunately, the old robots can only work with whole numbers. If the mean price turns out not to be an integer, they break down.You care about robots' welfare. You want to arrange the items in such a way that the robots cannot theoretically break. Formally, you want to choose such a two-dimensional array $$$a$$$ that:  Every number from $$$1$$$ to $$$n \cdot k$$$ (inclusively) occurs exactly once.  For each $$$i, l, r$$$, the mean price of items from $$$l$$$ to $$$r$$$ on $$$i$$$-th shelf is an integer. Find out if such an arrangement is possible, and if it is, give any example of such arrangement.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 500$$$) — the number of shelves and length of each shelf, respectively. It is guaranteed that the sum $$$n$$$ over all test cases does not exceed $$$500$$$ and the sum $$$k$$$ over all test cases does not exceed $$$500$$$.

Print the answer for each test case. If such an arrangement exists, print "YES" on a single line. After that, print any example on $$$n$$$ lines of $$$k$$$ numbers each, one line per shelf. Each number from $$$1$$$ to $$$n \cdot k$$$ must occur exactly once in the output. If no good arrangement exists, print a single word "NO" on its own line.

// cheese-cracker [2022-02-06]

void solve(){
    long n = scan;
    long k = scan;

    if(k == 1 || (n % 2 == 0)){
        writeln("YES");
    }else{
        writeln("NO");
        return;
    }
    long m = n * k;
    long x = 1;
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < k; ++j){
            write(x, " ");
            x += 2;
            if(x > m){
                x = 2;
            }
        }
        writeln;
    }
}

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

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
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; } }

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		auto m = n * k;
		auto m2 = m / 2;
		if (m2 % k) continue;

		ans[ti].length = n;
		foreach (i; 0..m2/k)
		{
			foreach (j; 0..k)
			{
				ans[ti][i] ~= (i*k + j + 1) * 2;
			}
		}
		foreach (i; m2/k..n)
		{
			foreach (j; 0..k)
			{
				ans[ti][i] ~= ((i-m2/k)*k + j) * 2 + 1;
			}
		}
	}

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


The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students.

Print one integer — the number of good pairs of topic.

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

void main()
{
    auto N = readln.chomp.to!int;
    auto as = readln.split.to!(long[]);
    auto bs = readln.split.to!(long[]);
    long[] cs;
    foreach (i; 0..N) cs ~= as[i] - bs[i];
    sort(cs);
    long res;
    foreach (i; 0..N-1) {
        auto c = cs[i];
        if (cs[$-1] + c <= 0) continue;
        if (cs[i+1] + c > 0) {
            res += N-i-1;
            continue;
        }
        int l = i+1, r = N-1;
        while (l+1 < r) {
            auto m = (l+r)/2;
            if (cs[m] + c > 0) {
                r = m;
            } else {
                l = m;
            }
        }
        res += N - r;
    }
    writeln(res);
}

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

string FMT_F = "%.10f";

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

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

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

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

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

void main()
{
	auto n = RD!int;
	auto a = RDA;
	auto b = RDA;
	auto c = new long[](n);
	foreach (i; 0..n)
	{
		c[i] = a[i] - b[i];
	}
	c.sort();

	long ans;
	foreach (i; 0..n)
	{
		bool f(int x)
		{
			return c[i]+c[x] > 0;
		}
		auto cnt = n - binarySearch!(f)(n, cast(int)i);
		ans += cnt;
	}

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


Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.

The first line contains an integer n (1 ≤ n ≤ 4·105) — the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.

Print to the first line an integer k — minimum number of palindromes into which you can cut a given string. Print to the second line k strings — the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.

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

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

    auto s = readln.chomp;

    int[dchar] cnt;
    s.each!(c => cnt[c] += 1);

    int[dchar] even;
    dchar[] rest;
    foreach (k, v; cnt) {
        if (v % 2 == 0) { even[k] = v; }
        else {
            if (v > 1) { even[k] = v - 1; }
            rest ~= k;
        }
    }

    debug { cnt.writeln; rest.writeln; }

    dchar[][] ans;

    void go(int cnt, int len) {
        foreach (i; 0 .. cnt) {
            auto cur = new dchar[] (len);
            foreach (j; 0 .. len / 2) {
                auto c = even.keys.front;
                cur[j] = c;
                cur[len-1 - j] = c;
                even[c] -= 2;
                if (even[c] == 0) { even.remove(c); }
            }

            if (len % 2 == 1) {
                if (rest.empty()) {
                    auto c = even.keys.front;
                    foreach (_; 0 .. 2) { rest ~= c; }
                    even[c] -= 2;
                    if (even[c] == 0) { even.remove(c); }
                }

                cur[len/2] = rest.back;
                rest.popBack();
            }

            debug { cur.writeln; }

            ans ~= cur;
        }
    }

    if (rest.empty()) {
        if (n % 2 == 1) {
            writeln(-1);
            return;
        } else {
            go(1, n);
        }
    } else {
        int mn = rest.length.to!int;
        foreach (elems; mn .. n+1) {
            if (n % elems != 0) { continue; }
            if (n / elems % 2 != 1) { continue; }
            if ((elems - mn) % 2 != 0) { continue; }

            debug { writeln(elems, ' ', n / elems); }
            go(elems, n / elems);
            break;
        }
    }

    ans.length.writeln;
    foreach (i, rw; ans) {
        if (i > 0) { write(' '); }
        write(rw);
    }

    writeln;
}


The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.If $$$x$$$ is the number of passengers in a bus just before the current bus stop and $$$y$$$ is the number of passengers in the bus just after current bus stop, the system records the number $$$y-x$$$. So the system records show how number of passengers changed.The test run was made for single bus and $$$n$$$ bus stops. Thus, the system recorded the sequence of integers $$$a_1, a_2, \dots, a_n$$$ (exactly one number for each bus stop), where $$$a_i$$$ is the record for the bus stop $$$i$$$. The bus stops are numbered from $$$1$$$ to $$$n$$$ in chronological order.Determine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $$$w$$$ (that is, at any time in the bus there should be from $$$0$$$ to $$$w$$$ passengers inclusive).

The first line contains two integers $$$n$$$ and $$$w$$$ $$$(1 \le n \le 1\,000, 1 \le w \le 10^{9})$$$ — the number of bus stops and the capacity of the bus. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ $$$(-10^{6} \le a_i \le 10^{6})$$$, where $$$a_i$$$ equals to the number, which has been recorded by the video system after the $$$i$$$-th bus stop.

Print the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $$$w$$$. If the situation is contradictory (i.e. for any initial number of passengers there will be a contradiction), print 0.

NoteIn the first example initially in the bus could be $$$0$$$, $$$1$$$ or $$$2$$$ passengers.In the second example initially in the bus could be $$$1$$$, $$$2$$$, $$$3$$$ or $$$4$$$ passengers.In the third example initially in the bus could be $$$0$$$ or $$$1$$$ passenger.

import std.algorithm;
import std.array;
import std.conv;
import std.stdio;

void main ()
{
	int n, w;
	while (readf (" %s %s", &n, &w) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		long cur = 0;
		long lo = cur;
		long hi = cur;
		foreach (c; a)
		{
			cur += c;
			lo = min (lo, cur);
			hi = max (hi, cur);
		}
		long inf = 0 - lo;
		long sup = w - hi;
		long res = sup - inf + 1;
		res = max (res, 0);
		writeln (res);
	}
}

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

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

  long lowerBound(){ // cap: [0, infty)
    bool tooLarge(long x){
      if(x<0) return false;
      foreach(d; diff){
        if((x+=d)<0) return false;
      }
      return true;
    }
    long ng=-1, ok=1_000_000_000_000;
    while(ok-ng>1){ // (ng, ok]
      auto m=(ok+ng)/2;
      tooLarge(m) ? ok : ng = m;
    }
    return ok;
  }

  long upperBound(){ // (-infty, w]
    bool tooSmall(long x){
      if(x>w) return false;
      foreach(d; diff){
        if((x+=d)>w) return false;
      }
      return true;
    }
    long ok=-1_000_000_000_000, ng=w+1;
    while(ng-ok>1){ // [ok, ng)
      auto m=(ok+ng)/2;
      tooSmall(m) ? ok : ng = m;
    }
    return ok;
  }

  auto ub=upperBound(), lb=lowerBound();
  if(0<=ub && ub<=w && 0<=lb && lb<=w){
    writeln(max(0, ub-lb+1));
  }else{
    writeln(0);
  }
}

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


Polycarp is in really serious trouble — his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di — the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti ≥ di, then i-th item cannot be saved.Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b — in ta + tb seconds after fire started.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≤ ti ≤ 20, 1 ≤ di ≤ 2 000, 1 ≤ pi ≤ 20) — the time needed to save the item i, the time after which the item i will burn completely and the value of item i.

In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m — the number of items in the desired set. In the third line print m distinct integers — numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.

NoteIn the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.

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;

void main() {
    auto N = readln.chomp.to!int;
    auto TDP = N.iota.map!(i => readln.split.map!(to!int).array ~ i).array;
    TDP.sort!"a[1] < b[1]";
    auto dp = new Tuple!(int, int[])[](2001);

    foreach (i; 0..N) {
        auto t = TDP[i][0], d = TDP[i][1], p = TDP[i][2], index = TDP[i][3];
        foreach (j; iota(2000, -1, -1)) {
            if (j + t <= 2000 && j + t < d && dp[j][0] + p > dp[j + t][0]) {
                dp[j + t] = dp[j];
                dp[j + t][0] += p;
                dp[j + t][1] ~= index + 1;
            }
        }
    }

    int m = 0, mi = 0;
    foreach (i; 0..2001) if (dp[i][0] > m) m = dp[i][0], mi = i;

    dp[mi][0].writeln;
    dp[mi][1].length.writeln;
    dp[mi][1].map!(d => d.to!string).join(" ").writeln;
}


Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:  for the array $$$[0, 0, 1, 0, 2]$$$ MEX equals to $$$3$$$ because numbers $$$0, 1$$$ and $$$2$$$ are presented in the array and $$$3$$$ is the minimum non-negative integer not presented in the array;  for the array $$$[1, 2, 3, 4]$$$ MEX equals to $$$0$$$ because $$$0$$$ is the minimum non-negative integer not presented in the array;  for the array $$$[0, 1, 4, 3]$$$ MEX equals to $$$2$$$ because $$$2$$$ is the minimum non-negative integer not presented in the array. You are given an empty array $$$a=[]$$$ (in other words, a zero-length array). You are also given a positive integer $$$x$$$.You are also given $$$q$$$ queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ and means that you have to append one element $$$y_j$$$ to the array. The array length increases by $$$1$$$ after a query.In one move, you can choose any index $$$i$$$ and set $$$a_i := a_i + x$$$ or $$$a_i := a_i - x$$$ (i.e. increase or decrease any element of the array by $$$x$$$). The only restriction is that $$$a_i$$$ cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of $$$q$$$ queries (i.e. the $$$j$$$-th answer corresponds to the array of length $$$j$$$).Operations are discarded before each query. I.e. the array $$$a$$$ after the $$$j$$$-th query equals to $$$[y_1, y_2, \dots, y_j]$$$.

The first line of the input contains two integers $$$q, x$$$ ($$$1 \le q, x \le 4 \cdot 10^5$$$) — the number of queries and the value of $$$x$$$. The next $$$q$$$ lines describe queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ ($$$0 \le y_j \le 10^9$$$) and means that you have to append one element $$$y_j$$$ to the array.

Print the answer to the initial problem after each query — for the query $$$j$$$ print the maximum value of MEX after first $$$j$$$ queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.

NoteIn the first example:  After the first query, the array is $$$a=[0]$$$: you don't need to perform any operations, maximum possible MEX is $$$1$$$.  After the second query, the array is $$$a=[0, 1]$$$: you don't need to perform any operations, maximum possible MEX is $$$2$$$.  After the third query, the array is $$$a=[0, 1, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$.  After the fourth query, the array is $$$a=[0, 1, 2, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$ (you can't make it greater with operations).  After the fifth query, the array is $$$a=[0, 1, 2, 2, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3]$$$. Now MEX is maximum possible and equals to $$$4$$$.  After the sixth query, the array is $$$a=[0, 1, 2, 2, 0, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3, 0]$$$. Now MEX is maximum possible and equals to $$$4$$$.  After the seventh query, the array is $$$a=[0, 1, 2, 2, 0, 0, 10]$$$. You can perform the following operations:   $$$a[3] := a[3] + 3 = 2 + 3 = 5$$$,  $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$,  $$$a[5] := a[5] + 3 = 0 + 3 = 3$$$,  $$$a[5] := a[5] + 3 = 3 + 3 = 6$$$,  $$$a[6] := a[6] - 3 = 10 - 3 = 7$$$,  $$$a[6] := a[6] - 3 = 7 - 3 = 4$$$.  The resulting array will be $$$a=[0, 1, 2, 5, 3, 6, 4]$$$. Now MEX is maximum possible and equals to $$$7$$$.

import std.stdio;

void main()
{
  // number of queries, operation amount
  uint q, x;
  readf!"%d %d\n"(q, x);

  auto m = new uint[x];
  uint mex = 0; // initial mex is 0

  foreach (i; 0..q) {
    // value to be appended to array
    uint j;
    readf!"%d\n"(j);
    m[j % x]++;

    while (m[mex % x] > mex / x) mex++;

    writeln(mex);
  }
}

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 q, x;
    readf("%s %s", &q, &x);
    readln;

    auto added = new bool[] (max(q+1, x+1));
    auto nxtfree = new int[] (x);
    foreach (i; 0 .. x) { nxtfree[i] = i; }
    int mex = 0;

    while (q--) {
        int y;
        readf("%s", &y);
        readln;

        y %= x;

        if (nxtfree[y] < added.length) {
            added[nxtfree[y]] = true;
            nxtfree[y] += x;
        }

        while (added[mex]) { ++mex; }

        mex.writeln;
    }
}

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

void main ()
{
	int q, x;
	while (readf !(" %s %s") (q, x) > 0)
	{
		auto d = new int [x];
		int res = 0;
		foreach (r; 0..q)
		{
			int u;
			readf !(" %s") (u);
			d[u % x] += 1;
			while (d[res % x] > res / x)
			{
				res += 1;
			}
			writeln (res);
		}
	}
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
import std.algorithm.mutation;
import std.container.array;

string[] tokens;

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

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

void main()
{
    int q = readInt;
    int x = readInt;
    int[] cnt = new int[x];
    int ans = 0;
    while (q--)
    {
        cnt[readInt % x]++;
        while (cnt[ans % x])
        {
            cnt[ans++ % x]--;
        }
        writeln(ans);
    }
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(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);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

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

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

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

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

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

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

    }
}

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

void main()
{
  long q, x;
  read(q, x);
  auto ap = new long[x.ind];
  auto aps = redBlackTree!(Tuple!(long, long))();
  foreach(i, api; ap[])
    aps.insert(tuple(cast(long)api, cast(long)i));
  foreach(qn; 0 .. q)
    {
      auto y = next!long;
      ap[(y % x).ind]++;
      aps.insert(tuple(ap[(y % x).ind], y % x));

      auto minap = aps.front;
      while(ap[minap[1].ind] != minap[0])
        {
          aps.removeFront;
          minap = aps.front;
        }
      auto minval = minap[0];
      auto minind = minap[1];
      writeln(x * minval + minind);
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto q = RD!int;
	auto x = RD;
	auto ans = new long[](q);
	long pos, loop;
	auto cnt = new long[](cast(int)x);

	void f(long z)
	{
		int y = cast(int)(z % x);
		if (pos == y)
		{
			++cnt[y];
			auto l = cast(int)pos;
			pos = x;
			foreach (i; l..cnt.length)
			{
				if (cnt[i] == loop)
				{
					pos = i;
					break;
				}
			}
			if (pos == x)
			{
				++loop;
				foreach (i; 0..cnt.length)
				{
					if (cnt[i] == loop)
					{
						pos = i;
						break;
					}
				}
			}
		}
		else
			++cnt[y];
	}

	foreach (qi; 0..q)
	{
		auto y = RD;
		f(y);
		ans[qi] = loop*x + pos;
	}

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


You are given an array of integers $$$b_1, b_2, \ldots, b_n$$$.An array $$$a_1, a_2, \ldots, a_n$$$ of integers is hybrid if for each $$$i$$$ ($$$1 \leq i \leq n$$$) at least one of these conditions is true:   $$$b_i = a_i$$$, or  $$$b_i = \sum_{j=1}^{i} a_j$$$. Find the number of hybrid arrays $$$a_1, a_2, \ldots, a_n$$$. As the result can be very large, you should print the answer modulo $$$10^9 + 7$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$-10^9 \le b_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer: the number of hybrid arrays $$$a_1, a_2, \ldots, a_n$$$ modulo $$$10^9 + 7$$$.

import std.stdio;

const ulong M = 1000000007;

void solve()
{
    uint n;
    readf!" %d"(n);

    long[] b = new long[n];
    foreach (ref x; b)
        readf!" %d"(x);

    ulong[long] s = [0: 1];
    long d = 0;
    ulong r = 1;

    foreach (x; b)
    {
        auto k = r + M - s.get(-d, 0);
        r = (r + k) % M;

        d += x;
        s.update(x - d, { return k % M; }, (ref ulong o) { return (o + k) % M; });
    }

    writeln(r);
}

void main()
{
    ushort t;
    readf!" %d"(t);
    for (ushort i = 0; i < t; ++i)
        solve();
}

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

immutable int mod = 1_000_000_007;

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;
		int [long] f;
		f[0] = 1;
		long shift = 0;
		int total = 1;
		foreach (ref c; a)
		{
			int cur0 = f.get (0 - shift, 0);
			shift += c;
			int value = (total - cur0 + mod) % mod;
			f[c - shift] = (f.get (c - shift, 0) + value) % mod;
			total = (total + value) % mod;
		}
		writeln (total);
	}
}


Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is different in evenness.

The first line contains integer n (3 ≤ n ≤ 100) — amount of numbers in the task. The second line contains n space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.

Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.

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

void main() {
    int n; readf("%d\n", &n);
    int[] xs = stdin.readln.split.map!(to!int).array;
    if (xs.count!("a % 2 == 1") == 1) {
        writeln(xs.countUntil!("a % 2 == 1") + 1);
    } else {
        writeln(xs.countUntil!("a % 2 == 0") + 1);
    }
}

import std.stdio;
import core.stdc.stdio;

int main()
{
	int n;
	scanf("%d", &n);
	int[] nums; nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
	}

	int idx = 0;
	foreach (int i; 2..n)
	{
		int sum = (nums[i] % 2) + (nums[i-1] % 2) + (nums[i-2] % 2);
		if (sum == 0 || sum == 3)
			continue;
		idx = (sum % 2 == nums[i] % 2 ? i : sum % 2 == nums[i-1] % 2 ? i-1 : i-2);
	}
	write(idx+1);
	return 0;
}

import std.stdio;

int n;
int[] a;
int[2] z;
void main()
{
	readf("%d", &n);
	a.length = n;
	for(int i = 0; i < n; i++) {
		readf(" %d", &a[i]);
		z[a[i] % 2]++;
	}
	for(int i = 0; i < n; i++) {
		if (z[a[i] % 2] == 1) {
			writeln(i + 1);
		}
	}
}

import std.stdio;

int n;
int[] a;
int[2] z;
void main()
{
	readf("%d", &n);
	a.length = n;
	for(int i = 0; i < n; i++) {
		readf(" %d", &a[i]);
		z[a[i] % 2]++;
	}
	for(int i = 0; i < n; i++) {
		if (z[a[i] % 2] == 1) {
			writeln(a[i]);
		}
	}
}

import std.stdio;

int n;
int[] a;
int[2] z;
void main()
{
	readf("%d", &n);
	a.length = n;
	for(int i = 0; i < n; i++) {
		readf(" %d", &a[i]);
		z[a[i] % 2]++;
	}
	for(int i = 0; i < n; i++) {
		if (z[a[i] % 2] == 1) {
			writeln(i);
		}
	}
}


This is the easy version of the problem. The difference is that in this version the array can not contain zeros. You can make hacks only if both versions of the problem are solved.You are given an array $$$[a_1, a_2, \ldots a_n]$$$ consisting of integers $$$-1$$$ and $$$1$$$. You have to build a partition of this array into the set of segments $$$[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]$$$ with the following property:  Denote the alternating sum of all elements of the $$$i$$$-th segment as $$$s_i$$$: $$$s_i$$$ = $$$a_{l_i} - a_{l_i+1} + a_{l_i+2} - a_{l_i+3} + \ldots \pm a_{r_i}$$$. For example, the alternating sum of elements of segment $$$[2, 4]$$$ in array $$$[1, 0, -1, 1, 1]$$$ equals to $$$0 - (-1) + 1 = 2$$$.  The sum of $$$s_i$$$ over all segments of partition should be equal to zero. Note that each $$$s_i$$$ does not have to be equal to zero, this property is about sum of $$$s_i$$$ over all segments of partition.The set of segments $$$[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]$$$ is called a partition of the array $$$a$$$ of length $$$n$$$ if $$$1 = l_1 \le r_1, l_2 \le r_2, \ldots, l_k \le r_k = n$$$ and $$$r_i + 1 = l_{i+1}$$$ for all $$$i = 1, 2, \ldots k-1$$$. In other words, each element of the array must belong to exactly one segment.You have to build a partition of the given array with properties described above or determine that such partition does not exist.Note that it is not required to minimize the number of segments in the partition.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$-1$$$ or $$$1$$$) — the elements of the given array. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$200\,000$$$.

For each test case, if required partition does not exist, print $$$-1$$$. Otherwise, print an integer $$$k$$$ — the number of segments in the partition.  Then in the $$$i$$$-th of the following $$$k$$$ lines print two integers $$$l_i$$$ and $$$r_i$$$ — description of the $$$i$$$-th segment. The following conditions should be satisfied:   $$$l_i \le r_i$$$ for each $$$i$$$ from $$$1$$$ to $$$k$$$.  $$$l_{i + 1} = r_i + 1$$$ for each $$$i$$$ from $$$1$$$ to $$$(k - 1)$$$.  $$$l_1 = 1, r_k = n$$$.  If there are multiple correct partitions of the array, print any of them.

NoteIn the first test case we can build a partition of one segment of length $$$4$$$. The sum of this segment will be equal to $$$1 - 1 + 1 - 1 = 0$$$.In the second test case we can build a partition of two segments of length $$$3$$$. The sum of the first segment will be equal to $$$-1 -1 + 1 = -1$$$, and the sum of the second segment: $$$1 - 1 + 1 = 1$$$. So, the total sum will be equal to $$$-1 + 1 = 0$$$.In the third and in the fourth test cases it can be proved that there are no required partition.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		if (sum (a) % 2 != 0)
		{
			writeln (-1);
			continue;
		}
		auto b = a.enumerate.filter !(x => x.value != 0).array;
		b ~= typeof (b.front) (n, 0);
		int [] [] answer;
		for (int i = 0; i + 2 < b.length; i += 2)
		{
			if (b[i].value == b[i + 1].value)
			{
				answer ~= [b[i].index, b[i + 2].index];
			}
			else
			{
				answer ~= [b[i].index, b[i + 1].index];
				answer ~= [b[i + 1].index, b[i + 2].index];
			}
		}
		writeln (answer.length);
		foreach (ref line; answer)
		{
			writeln (line[0] + 1, " ", line[1]);
		}
	}
}

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

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

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

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

int N;
int[] A;

int[] solve() {
  const sumA = A.sum;
  if (sumA % 2 != 0) {
    return null;
  }

  auto fs = new bool[N];
  bool greedy(int a, int k) {
    foreach (i; 0 .. N) {
      if (i == 0 || fs[i - 1]) {
        continue;
      }
      if (A[i] == a && k > 0) {
        fs[i] = true;
        --k;
      }
    }
    return (k == 0);
  }
  if (sumA >= 0) {
    if (!greedy(+1, sumA / 2)) return null;
  } else {
    if (!greedy(-1, -sumA / 2)) return null;
  }
  debug {
    writeln("fs = ", fs);
  }

  int[] cuts;
  cuts ~= 0;
  foreach (i; 1 .. N) {
    if (fs[i - 1] == fs[i]) {
      assert(!fs[i]);
      cuts ~= i;
    }
  }
  cuts ~= N;
  return cuts;
}

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

        const ans = solve;
        debug {
          writeln(A, ": ", ans);
        }
        const len = cast(int)(ans.length) - 1;
        if (len >= 0) {
          writeln(len);
          foreach (i; 0 .. len) {
            writeln(ans[i] + 1, " ", ans[i + 1]);
          }
        } else {
          writeln(-1);
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

bool solve(int[] a, int sum, ref Tuple!(int, int)[] ans)
{
  if (a.length == 0)
    return sum == 0;

  if (sum == 0) {
    ans ~= tuple(cast(int)a.length, cast(int)a.length);
    return solve(a[0 .. $ - 1], sum, ans);
    return true;
  }

  if (sum < 0) {
    if (a.length >= 2 && a[$ - 1] < 0) {
      ans ~= tuple(cast(int)a.length - 1, cast(int)a.length);
      return solve(a[0 .. $ - 2], sum - 2 * a[$ - 1], ans);
    } else {
      ans ~= tuple(cast(int)a.length, cast(int)a.length);
      return solve(a[0 .. $ - 1], sum, ans);
    }
  } else {
    if (a.length >= 2 && a[$ - 1] > 0) {
      ans ~= tuple(cast(int)a.length - 1, cast(int)a.length);
      return solve(a[0 .. $ - 2], sum - 2 * a[$ - 1], ans);
    } else {
      ans ~= tuple(cast(int)a.length, cast(int)a.length);
      return solve(a[0 .. $ - 1], sum, ans);
    }
  }
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    Tuple!(int, int)[] ans;
    if (solve(a, a.sum, ans)) {
      ans.reverse;
      writeln(ans.length);
      foreach (x; ans) {
        writefln("%d %d", x[0], x[1]);
      }
    } else {
      writeln(-1);
    }
  }
}


You came to a local shop and want to buy some chocolate bars. There are $$$n$$$ bars in the shop, $$$i$$$-th of them costs $$$a_i$$$ coins (and you want to buy all of them).You have $$$m$$$ different coupons that allow you to buy chocolate bars. $$$i$$$-th coupon allows you to buy $$$q_i$$$ chocolate bars while you have to pay only for the $$$q_i - 1$$$ most expensive ones (so, the cheapest bar of those $$$q_i$$$ bars is for free).You can use only one coupon; if you use coupon $$$i$$$, you have to choose $$$q_i$$$ bars and buy them using the coupon, and buy all the remaining $$$n - q_i$$$ bars without any discounts.To decide which coupon to choose, you want to know what will be the minimum total amount of money you have to pay if you use one of the coupons optimally.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of chocolate bars in the shop. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the cost of $$$i$$$-th chocolate bar. The third line contains one integer $$$m$$$ ($$$1 \le m \le n - 1$$$) — the number of coupons you have. The fourth line contains $$$m$$$ integers $$$q_1$$$, $$$q_2$$$, ..., $$$q_m$$$ ($$$2 \le q_i \le n$$$), where $$$q_i$$$ is the number of chocolate bars you have to buy using $$$i$$$-th coupon so that the least expensive of them will be for free. All values of $$$q_i$$$ are pairwise distinct.

Print $$$m$$$ integers, $$$i$$$-th of them should be the minimum amount of money you have to pay if you buy $$$q_i$$$ bars with $$$i$$$-th coupon, and all the remaining bars one by one for their full price.

NoteConsider the first example.If we use the first coupon, we may choose chocolate bars having indices $$$1$$$, $$$6$$$ and $$$7$$$, and we pay $$$18$$$ coins for them and $$$9$$$ coins for all other bars.If we use the second coupon, we may choose chocolate bars having indices $$$1$$$, $$$5$$$, $$$6$$$ and $$$7$$$, and we pay $$$25$$$ coins for them and $$$5$$$ coins for all other bars.

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

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

    A.sort!"a > b";
    auto S = A.sum;

    foreach (b; B) {
        writeln(S - A[b-1]);
    }
}


Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.Let [n] denote the set {1, ..., n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y.Now then, you are given a function f: [n] → [n]. Your task is to find a positive integer m, and two functions g: [n] → [m], h: [m] → [n], such that g(h(x)) = x for all , and h(g(x)) = f(x) for all , or determine that finding these is impossible.

The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers — values f(1), ..., f(n) (1 ≤ f(i) ≤ n).

If there is no answer, print one integer -1. Otherwise, on the first line print the number m (1 ≤ m ≤ 106). On the second line print n numbers g(1), ..., g(n). On the third line print m numbers h(1), ..., h(m). If there are several correct answers, you may output any of them. It is guaranteed that if a valid answer exists, then there is an answer satisfying the above restrictions.

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 N = readInt();
      auto F = new int[N];
      foreach (u; 0 .. N) {
        F[u] = readInt() - 1;
      }

      bool ans = true;
      int M;
      auto G = new int[N];
      G[] = -1;
      int[] H;

      auto uf = new int[N];
      uf[] = -1;
      foreach (u; 0 .. N) {
        uf.connect(u, F[u]);
      }
      foreach (r; 0 .. N) {
        if (uf[r] < 0) {
          int u = r;
          foreach (_; 0 .. -uf[r]) {
            u = F[u];
          }
          ans = ans && (u == F[u]);
          G[r] = M++;
          H ~= u;
        }
      }
      foreach (u; 0 .. N) {
        G[u] = G[uf.root(u)];
      }

      foreach (i; 0 .. M) {
        ans = ans && (G[H[i]] == i);
      }
      foreach (u; 0 .. N) {
        ans = ans && (H[G[u]] == F[u]);
      }

      if (ans) {
        writeln(M);
        foreach (u; 0 .. N) {
          if (u > 0) write(" ");
          write(G[u] + 1);
        }
        writeln;
        foreach (i; 0 .. M) {
          if (i > 0) write(" ");
          write(H[i] + 1);
        }
        writeln;
      } else {
        writeln(-1);
      }
    }
  } 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 N = readInt();
      auto F = new int[N];
      foreach (u; 0 .. N) {
        F[u] = readInt() - 1;
      }

      bool ans = true;
      int M;
      auto G = new int[N];
      G[] = -1;
      int[] H;

      auto uf = new int[N];
      uf[] = -1;
      foreach (u; 0 .. N) {
        uf.connect(u, F[u]);
      }
      foreach (r; 0 .. N) {
        if (uf[r] < 0) {
          int u = r;
          foreach (_; 0 .. -uf[r]) {
            u = F[u];
          }
          ans = ans && (u == F[u]);
          G[r] = M++;
          H ~= u;
        }
      }

      if (ans) {
        writeln(M);
        foreach (u; 0 .. N) {
          if (u > 0) write(" ");
          write(G[uf.root(u)] + 1);
        }
        writeln;
        foreach (i; 0 .. M) {
          if (i > 0) write(" ");
          write(H[i] + 1);
        }
        writeln;
      } else {
        writeln(-1);
      }
    }
  } 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 N = readInt();
      auto F = new int[N];
      foreach (u; 0 .. N) {
        F[u] = readInt() - 1;
      }

      bool ans = true;

      auto uf = new int[N];
      uf[] = -1;
      foreach (u; 0 .. N) {
        uf.connect(u, F[u]);
      }
      auto rs = new int[N];
      rs[] = -1;
      foreach (r; 0 .. N) {
        if (uf[r] < 0) {
          int u = r;
          foreach (_; 0 .. -uf[r]) {
            u = F[u];
          }
          ans = ans && (u == F[u]);
          rs[r] = u;
        }
      }

      if (ans) {
        writeln(N);
        foreach (u; 0 .. N) {
          if (u > 0) write(" ");
          write(rs[uf.root(u)] + 1);
        }
        writeln;
        foreach (u; 0 .. N) {
          if (u > 0) write(" ");
          write(u + 1);
        }
        writeln;
      } else {
        writeln(-1);
      }
    }
  } catch (EOFException e) {
  }
}


You are given an undirected tree consisting of $$$n$$$ vertices. An undirected tree is a connected undirected graph with $$$n - 1$$$ edges.Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex $$$1$$$ to any other vertex is at most $$$2$$$. Note that you are not allowed to add loops and multiple edges.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The following $$$n - 1$$$ lines contain edges: edge $$$i$$$ is given as a pair of vertices $$$u_i, v_i$$$ ($$$1 \le u_i, v_i \le n$$$). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.

Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex $$$1$$$ to any other vertex at most $$$2$$$. Note that you are not allowed to add loops and multiple edges.

NoteThe tree corresponding to the first example:  The answer is $$$2$$$, some of the possible answers are the following: $$$[(1, 5), (1, 6)]$$$, $$$[(1, 4), (1, 7)]$$$, $$$[(1, 6), (1, 7)]$$$.The tree corresponding to the second example:  The answer is $$$0$$$.The tree corresponding to the third example:  The answer is $$$1$$$, only one possible way to reach it is to add the edge $$$(1, 3)$$$.

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

void dfs(int node, int depth, int[][] c, bool[] v, int[][] dp)
{
    v[node] = true;
    auto parent = -1;
    foreach (i; 0 .. c[node].length)
    {
        if (!v[c[node][i]])
        {
            dfs(c[node][i], depth + 1, c, v, dp);
        }
        else
        {
            parent = c[node][i];
        }
    }
    if (depth <= 1)
    {
        auto sum = 0;
        foreach (i; 0 .. c[node].length)
        {
            if (c[node][i] != parent)
            {
                auto child = c[node][i];
                sum += min(dp[child][0], dp[child][1]);
            }
        }
        dp[node][0] = sum;
        dp[node][1] = sum + 1;
        dp[node][2] = int.max;
        return;
    }
    auto sum = 0;
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            sum += min(dp[child][1], dp[child][2]);
        }
    }
    dp[node][0] = sum;
    sum = 0;
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            sum += min(dp[child][0], dp[child][1]);
        }
    }
    dp[node][1] = sum + 1;
    dp[node][2] = int.max;
    sum = 0;
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            sum += min(dp[child][1], dp[child][2]);
        }
    }
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            dp[node][2] = min(dp[node][2], sum - min(dp[child][1], dp[child][2]) + dp[child][1]);
        }
    }
}

void solve(int[][] c)
{
    auto n = cast(int)c.length;
    auto v = new bool[n];
    fill(v, false);
    auto dp = new int[][](n, 3);
    dfs(0, 0, c, v, dp);
    writeln(dp[0][0]);
}

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

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

void dfs(int node, int depth, int[][] c, bool[] v, int[][] dp)
{
    v[node] = true;
    auto parent = -1;
    foreach (i; 0 .. c[node].length)
    {
        if (!v[c[node][i]])
        {
            dfs(c[node][i], depth + 1, c, v, dp);
        }
        else
        {
            parent = c[node][i];
        }
    }
    if (depth <= 1)
    {
        auto sum = 0;
        foreach (i; 0 .. c[node].length)
        {
            if (c[node][i] != parent)
            {
                auto child = c[node][i];
                sum += min(dp[child][0], dp[child][1]);
            }
        }
        dp[node][0] = sum;
        dp[node][1] = sum + 1;
        dp[node][2] = int.max;
        return;
    }
    auto sum = 0;
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            sum += min(dp[child][1], dp[child][2]);
        }
    }
    dp[node][0] = sum;
    sum = 0;
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            sum += min(dp[child][0], dp[child][1]);
        }
    }
    dp[node][1] = sum + 1;
    dp[node][2] = int.max;
    sum = 0;
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            sum += min(dp[child][1], dp[child][2]);
        }
    }
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            dp[node][2] = min(dp[node][2], sum - min(dp[child][1], dp[child][2]) + dp[child][1]);
        }
    }
    if (depth > 2 && dp[node][2] == int.max)
    {
        dp[node][2] = 1;
    }
}

void solve(int[][] c)
{
    auto n = cast(int)c.length;
    auto v = new bool[n];
    fill(v, false);
    auto dp = new int[][](n, 3);
    dfs(0, 0, c, v, dp);
    writeln(dp[0][0]);
}

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

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

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

    auto g = new int[][] (n+1);
    foreach (_; 0 .. n-1) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        g[x] ~= y;
        g[y] ~= x;
    }

    auto ans = 0;
    int dfs(int v, int fr, int dst) {
        int mxc = 0, mnc = 10 ^^ 9;
        foreach (u; g[v]) {
            if (u == fr) continue;
            auto c = dfs(u, v, dst+1);
            mxc = max(mxc, c);
            mnc = min(mnc, c);
        }

        auto curd = min(dst, mnc+1);

        debug { writeln(v, ' ', curd); }

        if (mxc > 2) {
            debug { v.writeln; }
            ++ans;
            curd = 1;
        }

        return curd;
    }

    dfs(1, -1, 0);

    ans.writeln;
}

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

void dfs(int node, int depth, int[][] c, bool[] v, int[][] dp)
{
    v[node] = true;
    auto parent = -1;
    foreach (i; 0 .. c[node].length)
    {
        if (!v[c[node][i]])
        {
            dfs(c[node][i], depth + 1, c, v, dp);
        }
        else
        {
            parent = c[node][i];
        }
    }
    if (depth <= 1)
    {
        auto sum = 0;
        foreach (i; 0 .. c[node].length)
        {
            if (c[node][i] != parent)
            {
                auto child = c[node][i];
                sum += min(dp[child][0], dp[child][1]);
            }
        }
        dp[node][0] = sum;
        dp[node][1] = sum + 1;
        dp[node][2] = int.max;
        return;
    }
    auto sum = 0;
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            sum += min(dp[child][1], dp[child][2]);
        }
    }
    dp[node][0] = sum;
    sum = 0;
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            sum += min(dp[child][0], dp[child][1]);
        }
    }
    dp[node][1] = sum + 1;
    dp[node][2] = int.max;
    sum = 0;
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            sum += dp[child][2];
        }
    }
    foreach (i; 0 .. c[node].length)
    {
        if (c[node][i] != parent)
        {
            auto child = c[node][i];
            dp[node][2] = min(dp[node][2], sum - dp[child][2] + dp[child][1]);
        }
    }
    if (dp[node][2] == int.max)
    {
        dp[node][2] = 1;
    }
}

void solve(int[][] c)
{
    auto n = cast(int)c.length;
    auto v = new bool[n];
    fill(v, false);
    auto dp = new int[][](n, 3);
    dfs(0, 0, c, v, dp);
    writeln(dp[0][0]);
}

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

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

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

    auto g = new int[][] (n);
    foreach (_; 0 .. n-1) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        --x, --y;
        g[x] ~= y;
        g[y] ~= x;
    }

    auto dp = new int[][] (4, n);
    foreach (ref rw; dp) rw[] = -1;
    int dfs(int v, int fr, int dst) {
        int run(int d) {
            int ans = 0;
            foreach (u; g[v]) {
                if (u == fr) continue;
                ans += dfs(u, v, d);
            }
            return ans;
        }

        if (dp[dst][v] != -1) return dp[dst][v];

        if (v != 0 && dst <= 2 && g[v].length == 1) return 0;

        if (dst == 0 || dst == 1) {
            dp[dst][v] = run(dst+1);
        } else if (dst == 2) {
            auto ans0 = 1 + run(2);
            auto ans1 = g[v].length - 1 + run(1);
            auto ans2 = run(3);

            dp[dst][v] = [ans0, ans1, ans2].minElement.to!int;

            debug { writeln(v, ' ', dst, ' ', dp[dst][v]); }
        } else { //dst == 3
            auto ans0 = 1 + run(2);
            auto ans1 = g[v].length > 1 ? g[v].length - 1 + run(1) : int.max;

            dp[dst][v] = min(ans0, ans1);
        }

        return dp[dst][v];
    }

    auto ans = dfs(0, -1, 0);

    ans.writeln;
}

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

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

    auto g = new int[][] (n);
    foreach (_; 0 .. n-1) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        --x, --y;
        g[x] ~= y;
        g[y] ~= x;
    }

    auto dp = new int[][] (3, n);
    foreach (ref rw; dp) rw[] = -1;
    int dfs(int v, int fr, int dst) {
        int run(int d) {
            int ans = 0;
            foreach (u; g[v]) {
                if (u == fr) continue;
                ans += dfs(u, v, d);
            }
            return ans;
        }

        if (dp[dst][v] != -1) return dp[dst][v];

        if (v != 0 && dst <= 2 && g[v].length == 1) return 0;

        if (dst == 0 || dst == 1) {
            dp[dst][v] = run(dst+1);
        } else {
            auto ans0 = 1 + run(2);
            auto ans1 = g[v].length - 1 + run(1);

            dp[dst][v] = min(ans0, ans1);

            debug { writeln(v, ' ', dst, ' ', min(ans0, ans1)); }
        }

        return dp[dst][v];
    }

    auto ans = dfs(0, -1, 0);

    ans.writeln;
}

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

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

    auto g = new int[][] (n+1);
    foreach (_; 0 .. n-1) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        g[x] ~= y;
        g[y] ~= x;
    }

    auto ans = 0;
    int dfs(int v, int fr, int dst) {
        int mxc = 0;
        foreach (u; g[v]) {
            if (u == fr) continue;
            auto c = dfs(u, v, dst+1);
            mxc = max(mxc, c);
        }

        auto curd = dst;

        debug { writeln(v, ' ', curd); }

        if (mxc > 2) {
            ++ans;
            curd = 1;
        }

        return curd;
    }

    dfs(1, -1, 0);

    ans.writeln;
}


You are given an array a of size n, and q queries to it. There are queries of two types:   1 li ri — perform a cyclic shift of the segment [li, ri] to the right. That is, for every x such that li ≤ x < ri new value of ax + 1 becomes equal to old value of ax, and new value of ali becomes equal to old value of ari;  2 li ri — reverse the segment [li, ri].  There are m important indices in the array b1, b2, ..., bm. For each i such that 1 ≤ i ≤ m you have to output the number that will have index bi in the array after all queries are performed.

The first line contains three integer numbers n, q and m (1 ≤ n, q ≤ 2·105, 1 ≤ m ≤ 100).  The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109).  Then q lines follow. i-th of them contains three integer numbers ti, li, ri, where ti is the type of i-th query, and [li, ri] is the segment where this query is performed (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n).  The last line contains m integer numbers b1, b2, ..., bm (1 ≤ bi ≤ n) — important indices of the array.

Print m numbers, i-th of which is equal to the number at index bi after all queries are done.

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;

void main() {
    auto input = readln.split.map!(to!int);
    auto N = input[0];
    auto K = input[1];
    auto M = input[2];
    auto A = readln.split.map!(to!int).array;
    auto Q = K.iota.map!(_ =>readln.split.map!(to!int).array).array;
    auto B = readln.split.map!(x => x.to!int - 1).array;

    Q.reverse();
    int[] ans;

    foreach (b; B) {
        foreach (q; Q) {
            auto l = q[1] - 1;
            auto r = q[2] - 1;

            if (q[0] == 1) {
                if (b == l)
                    b = r;
                else if (b >= l && b <= r)
                    b -= 1;
            } else {
                if (b >= l && b <= r)
                    b = r - b + l;
            }
        }

        ans ~= A[b];
    }

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

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

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

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

    struct qr { int t, le, r; }
    auto qs = new qr[] (q);
    foreach (i; 0 .. q) {
        readf("%s %s %s", &qs[i].t, &qs[i].le, &qs[i].r);
        readln;
    }

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

    foreach_reverse (cq; qs) {
        foreach (ref e; b) {
            if (e < cq.le || e > cq.r) { continue; }

            if (cq.t == 1) { e = e > cq.le ? e-1 : cq.r; }
            if (cq.t == 2) { e = cq.r - (e - cq.le); }
        }

        debug { b.writeln; }
    }

    int[] ans;
    foreach (e; b) { ans ~= arr[e-1]; }

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

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

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

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

    struct qr { int t, le, r; }
    auto qs = new qr[] (q);
    foreach (i; 0 .. q) {
        readf("%s %s %s", &qs[i].t, &qs[i].le, &qs[i].r);
        readln;
    }

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

    foreach_reverse (cq; qs) {
        foreach (ref e; b) {
            if (e < cq.le || e > cq.r) { continue; }

            if (cq.t == 1) { e = e > 1 ? e-1 : n; }
            if (cq.t == 2) { e = cq.r - (e - cq.le); }
        }

        debug { b.writeln; }
    }

    int[] ans;
    foreach (e; b) { ans ~= arr[e-1]; }

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


There is a grid, consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell of the grid is either free or blocked. One of the free cells contains a lab. All the cells beyond the borders of the grid are also blocked.A crazy robot has escaped from this lab. It is currently in some free cell of the grid. You can send one of the following commands to the robot: "move right", "move down", "move left" or "move up". Each command means moving to a neighbouring cell in the corresponding direction.However, as the robot is crazy, it will do anything except following the command. Upon receiving a command, it will choose a direction such that it differs from the one in command and the cell in that direction is not blocked. If there is such a direction, then it will move to a neighbouring cell in that direction. Otherwise, it will do nothing.We want to get the robot to the lab to get it fixed. For each free cell, determine if the robot can be forced to reach the lab starting in this cell. That is, after each step of the robot a command can be sent to a robot such that no matter what different directions the robot chooses, it will end up in a lab.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^6$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the grid. The $$$i$$$-th of the next $$$n$$$ lines provides a description of the $$$i$$$-th row of the grid. It consists of $$$m$$$ elements of one of three types:    '.' — the cell is free;  '#' — the cell is blocked;  'L' — the cell contains a lab.  The grid contains exactly one lab. The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.

For each testcase find the free cells that the robot can be forced to reach the lab from. Given the grid, replace the free cells (marked with a dot) with a plus sign ('+') for the cells that the robot can be forced to reach the lab from. Print the resulting grid.

NoteIn the first testcase there is no free cell that the robot can be forced to reach the lab from. Consider a corner cell. Given any direction, it will move to a neighbouring border grid that's not a corner. Now consider a non-corner free cell. No matter what direction you send to the robot, it can choose a different direction such that it ends up in a corner.In the last testcase, you can keep sending the command that is opposite to the direction to the lab and the robot will have no choice other than move towards the lab.

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

int[] xmov = [-1, 1, 0,  0];
int[] ymov = [ 0, 0, 1, -1];

void dfs(int x, int y, int px, int py, ref dchar[][] mat, ref bool[][] vis){
    assert(mat[x][y] != '#' && vis[x][y] != 1);
    vis[x][y] = 1;
    int options = 0;
    for(int i = 0; i < 4; ++i){
        int nx = x + xmov[i];
        int ny = y + ymov[i];
        if(nx >= mat.length || nx < 0 || ny >= mat[0].length || ny < 0){
            continue;
        }
        if((nx != px || ny != py) && !vis[nx][ny] && mat[nx][ny] == '.'){
            ++options;
        }
    }
    if(options > 1 && !(mat[x][y] == 'L')){
        vis[x][y] = 0;
        return;
    }
    if(mat[x][y] != 'L'){
        mat[x][y] = '+';
    }
    for(int i = 0; i < 4; ++i){
        int nx = x + xmov[i];
        int ny = y + ymov[i];
        if(nx >= mat.length || nx < 0 || ny >= mat[0].length || ny < 0){
            continue;
        }
        if((nx != px || ny != py) && !vis[nx][ny] && mat[nx][ny] == '.'){
            dfs(nx, ny, x, y, mat, vis);
        }
    }
}

void solve(){
    auto n = scan!int;
    auto m = scan!int;
    dchar[][] mat;
    auto vis = new bool[][](n, m);
    int sti = 0;
    int stj = 0;
    for(int i = 0; i < n; ++i){
        mat ~= scan!(dchar[]);
        for(int j = 0; j < m; ++j){
            if(mat.back[j] == 'L'){
               sti = i;
               stj = j;
            }
        }
    }
    dfs(sti, stj, sti, stj, mat, vis);
    for(int i = 0; i < n; ++i){
        writeln(mat[i]);
    }
}

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

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