You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries.

For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any.

NoteIn the first query any vertex or any pair of vertices will suffice.  Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok.

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.ascii, std.typecons;

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

    while (t--) {
        int n, m;
        readf("%s %s", &n, &m);
        readln;

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

        foreach (i; 0 .. m) {
            int u, v;
            readf("%s %s", &u, &v);
            readln;

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

        auto ans = new int[][] (2);
        auto vis = new int[] (n+1);
        vis[] = false;

        auto q = make!(DList!(Tuple!(int, int)));
        q ~= tuple(1, 0);
        vis[1] = true;
        while (!q.empty()) {
            auto p = q.front();
            q.removeFront();

            int v = p[0];
            int k = p[1];
            ans[k] ~= v;

            foreach (u; g[v]) {
                if (vis[u]) { continue; }

                vis[u] = true;
                q ~= tuple(u, 1 - k);
            }
        }

        int mn = ans[0].length < ans[1].length ? 0 : 1;
        ans[mn].length.writeln;
        ans[mn].map!(to!string).join(" ").writeln;
    }
}

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

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

    while (t--) {
        int n, m;
        readf("%s %s", &n, &m);
        readln;

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

        foreach (i; 0 .. m) {
            int u, v;
            readf("%s %s", &u, &v);
            readln;

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

        if (n == 2) {
            writeln(1);
            writeln(1);
            continue;
        }

        int st = 1;
        foreach (v; 2 .. n+1) {
            if (g[v].length > g[st].length) { st = v; }
        }

        if (g[st].length == 2) {
            foreach (v; 1 .. n+1) {
                if (g[v].length == 1) {
                    st = g[v][0];
                }
            }
        }

        int[] ans;
        auto vis = new int[] (n+1);
        vis[] = false;
        auto q = make!(DList!(Tuple!(int, bool)));
        q ~= tuple(st, true);
        vis[st] = true;
        while (!q.empty()) {
            auto p = q.front();
            q.removeFront();

            int v = p[0];
            bool take = p[1];
            if (take) { ans ~= v; }

            foreach (u; g[v]) {
                if (vis[u]) { continue; }

                vis[u] = true;
                q ~= tuple(u, !take);
            }
        }

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

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

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

    while (t--) {
        int n, m;
        readf("%s %s", &n, &m);
        readln;

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

        foreach (i; 0 .. m) {
            int u, v;
            readf("%s %s", &u, &v);
            readln;

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

        if (n == 2) {
            writeln(1);
            writeln(1);
            continue;
        }

        int st = 1;
        while (g[st].length == 1) { ++st; }

        int[] ans;
        auto vis = new int[] (n+1);
        vis[] = false;
        auto q = make!(DList!(Tuple!(int, bool)));
        q ~= tuple(st, true);
        vis[st] = true;
        while (!q.empty()) {
            auto p = q.front();
            q.removeFront();

            int v = p[0];
            bool take = p[1];
            if (take) { ans ~= v; }

            foreach (u; g[v]) {
                if (vis[u]) { continue; }

                vis[u] = true;
                q ~= tuple(u, !take);
            }
        }

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


Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced.Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves.Your task is to help Petya find out if he can win the game or at least draw a tie.

The first line of input contain two integers n and m — the number of vertices and the number of edges in the graph (2 ≤ n ≤ 105, 0 ≤ m ≤ 2·105). The next n lines contain the information about edges of the graph. i-th line (1 ≤ i ≤ n) contains nonnegative integer ci — number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j — indices of these vertices (1 ≤ ai, j ≤ n, ai, j ≠ i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s — the initial position of the chip (1 ≤ s ≤ n).

If Petya can win print «Win» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≤ k ≤ 106) — the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print «Draw» in the only line. Otherwise print «Lose».

NoteIn the first example the graph is the following:  Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins.In the second example the graph is the following:  Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses.In the third example the graph is the following:  Petya can't win, but he can move along the cycle, so the players will draw a tie.

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new int [] [n + 1];
		foreach (i; 1..n + 1)
		{
			int k;
			readf (" %s", &k);
			foreach (j; 0..k)
			{
				int z;
				readf (" %s", &z);
				a[i] ~= z;
			}
		}
		int s;
		readf (" %s", &s);

		auto b = new int [2] [n + 1];
		auto f = new int [2] [n + 1];

		bool canDraw = false;

		bool go (int v, int t)
		{
			if (b[v][t])
			{
				canDraw |= (b[v][t] == 1);
				return false;
			}
			b[v][t] = 1;
			if (t == 1 && a[v].empty)
			{
				return true;
			}
			foreach (z; a[v])
			{
				if (go (z, 1 - t))
				{
					f[v][t] = z;
					return true;
				}
			}
			b[v][t] = 2;
			return false;
		}

		auto canWin = go (s, 0);
		if (canWin)
		{
			writeln ("Win");
			int [] ans = [s];
			int t = 0;
			while (!a[s].empty)
			{
				s = f[s][t];
				t = 1 - t;
				ans ~= s;
			}
			writefln ("%(%s %)", ans);
		}
		else if (canDraw)
		{
			writeln ("Draw");
		}
		else
		{
			writeln ("Lose");
		}
	}
}


You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i < n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.

For each test case, output the answer on a new line.

NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		int [int] b;
		foreach (ref x; a)
		{
			b[x] += 1;
		}
		foreach (i; 0..n - 1)
		{
			auto v = b.byKeyValue.array;
			v.schwartzSort !(q{a.key});
			int [int] c;
			foreach (j; 0..v.length)
			{
				if (v[j].value > 1)
				{
					c[0] += v[j].value - 1;
				}
			}
			foreach (j; 0..v.length - 1)
			{
				c[v[j + 1].key - v[j].key] += 1;
			}
			b = c;
		}
		writeln (b.byKey.front);
	}
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

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

void solve() {
    int N = read!int;
    auto A = readarray!int;

    void step(ref int[] as, ref int k) {
        int n = as.length;
        if (n == 0) return;
        int[] bs = k == 0 ? [] : [as[0]];
        if (k > 0) k--;
        for (int i = 1; i < n; i++) {
            int b = as[i] - as[i - 1];
            if (b > 0) {
                bs ~= b;
            } else {
                k++;
            }
        }
        sort(bs);
        as = bs;
    }

    int[] as;
    int k = 0;
    foreach (a; A) {
        if (a == 0) k++;
        else as ~= a;
    }
    foreach (i; 0 .. N - 1) {
        step(as, k);
        /*
        writeln("as: ", as);
        writeln("k: ", k);
        */
    }
    writeln(as.empty ? 0 : as.back);
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		for (n--; n >= 1 && a.length > 1; n--)
		{
			bool addZero = (a.length <= n);
			a = zip (a, a.drop (1)).map !(q{a[1] - a[0]}).array;
			sort (a);
			auto b = a.uniq.array;
			a = addZero ? 0 ~ b : b;
			debug {writeln (a);}
		}
		writeln (a.front);
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		bool zero = false;
		for (n--; n >= 1 && a.length > 1; n--)
		{
			a = zip (a, a.drop (1)).map !(q{a[1] - a[0]}).array;
			sort (a);
			auto b = a.uniq.array;
			zero |= (b.length < a.length);
			a = (b.length < n) ? 0 ~ b : b;
			debug {writeln (a);}
		}
		writeln (a.front);
	}
}


Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.Help Vasya to recover the initial set of cards with numbers.

The single line contains three space-separated integers: n (2 ≤ n ≤ 100) — the initial number of cards on the table, d (|d| ≤ 104) — the number on the card that was left on the table after all the magical actions, and l (1 ≤ l ≤ 100) — the limits for the initial integers.

If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them.

import std.algorithm;
import std.c.stdio;
import std.stdio;
import std.conv;
import std.math;
import std.array;
import std.container;

int curc;
bool eof = false;

void sb()
{
    do
    {
        curc = getchar ();
    }
    while (0 <= curc && curc <= 32);
    if (curc == EOF)
    {
        eof = true;
    }
}

char rc ()
{
    sb ();
    return cast (char) curc;
}

int ni ()
{
    return to!int(ns());
}

long nl ()
{
    return to!long(ns());
}

double nd()
{
    return to!double(ns());
}

char[] ns ()
{
    sb ();
    auto res = appender!(char[])();
    do
    {
        res.put(to!char(curc));
        curc = getchar ();
    }
    while (32 < curc);
    return res.data;
}

void CF143B()
{
    int n = ni(), d = ni(), l = ni();
    int[] ans = new int[n - 1];
    for (int i = 0; i < n - 1; ++i)
    {
        ans[i] = max(1, min(l, d + 1));
        d = ans[i] - d;
    }
    if ((d < 1) | (d > l)) printf("-1");
    else
    {
        for (int i = 0; i < n - 1; ++i) printf("%d ", ans[i]);
        printf("%d", d);
    }
}

void main()
{
    CF143B();
}


Nash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the $$$n\times n$$$ board. Rows and columns of this board are numbered from $$$1$$$ to $$$n$$$. The cell on the intersection of the $$$r$$$-th row and $$$c$$$-th column is denoted by $$$(r, c)$$$.Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following $$$5$$$ characters  — $$$U$$$, $$$D$$$, $$$L$$$, $$$R$$$ or $$$X$$$  — instructions for the player. Suppose that the current cell is $$$(r, c)$$$. If the character is $$$R$$$, the player should move to the right cell $$$(r, c+1)$$$, for $$$L$$$ the player should move to the left cell $$$(r, c-1)$$$, for $$$U$$$ the player should move to the top cell $$$(r-1, c)$$$, for $$$D$$$ the player should move to the bottom cell $$$(r+1, c)$$$. Finally, if the character in the cell is $$$X$$$, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the $$$n^2$$$ cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell $$$(r, c)$$$ she wrote:   a pair ($$$x$$$,$$$y$$$), meaning if a player had started at $$$(r, c)$$$, he would end up at cell ($$$x$$$,$$$y$$$).  or a pair ($$$-1$$$,$$$-1$$$), meaning if a player had started at $$$(r, c)$$$, he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.

The first line of the input contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^{3}$$$)  — the side of the board. The $$$i$$$-th of the next $$$n$$$ lines of the input contains $$$2n$$$ integers $$$x_1, y_1, x_2, y_2, \dots, x_n, y_n$$$, where $$$(x_j, y_j)$$$ ($$$1 \leq x_j \leq n, 1 \leq y_j \leq n$$$, or $$$(x_j,y_j)=(-1,-1)$$$) is the pair written by Alice for the cell $$$(i, j)$$$.

If there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID.  Otherwise, in the first line print VALID. In the $$$i$$$-th of the next $$$n$$$ lines, print the string of $$$n$$$ characters, corresponding to the characters in the $$$i$$$-th row of the suitable board you found. Each character of a string can either be $$$U$$$, $$$D$$$, $$$L$$$, $$$R$$$ or $$$X$$$. If there exist several different boards that satisfy the provided information, you can find any of them.

NoteFor the sample test 1 :The given grid in output is a valid one.   If the player starts at $$$(1,1)$$$, he doesn't move any further following $$$X$$$ and stops there.  If the player starts at $$$(1,2)$$$, he moves to left following $$$L$$$ and stops at $$$(1,1)$$$.  If the player starts at $$$(2,1)$$$, he moves to right following $$$R$$$ and stops at $$$(2,2)$$$.  If the player starts at $$$(2,2)$$$, he doesn't move any further following $$$X$$$ and stops there. The simulation can be seen below :   For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center $$$(2,2)$$$, keeps moving in an infinitely long cycle and never stops. Had he started at $$$(2,2)$$$, he wouldn't have moved further following instruction $$$X$$$ .The simulation can be seen below :

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T cells){ return cells.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    int n = scan!int;
    Cell[][] cells = new Cell[][](n);
    foreach(i; 0 .. n) foreach(j; 0 .. n){
        cells[i] ~= new Cell(i, j, scan!int - 1, scan!int - 1);
    }

    foreach(i; 0 .. n - 1) foreach(j; 0 .. n){
        cells[i][j].cells ~= cells[i + 1][j];
        cells[i + 1][j].cells ~= cells[i][j];
    }
    foreach(i; 0 .. n) foreach(j; 0 .. n - 1){
        cells[i][j].cells ~= cells[i][j + 1];
        cells[i][j + 1].cells ~= cells[i][j];
    }

    auto cellq = new Queue!Cell;
    foreach(i; 0 .. n) foreach(j; 0 .. n){
        Cell cell = cells[i][j];
        if(cell.x == i && cell.y == j){
            cell.ans = 'X';
            cellq.enq(cell);
        }
    }

    if(DEBUG) foreach(cellu; cells) cellu.map!(c => c.ans).array.writeln;
    if(DEBUG) "".writeln;

    if(DEBUG) "-----".writeln;

    while(cellq.length > 0){
        if(DEBUG) cellq.length.writeln;
        Cell cell = cellq.deq;
        foreach(ce; cell.cells){
            if(ce.ans != ' ') continue;
            if(ce.x == cell.x && ce.y == cell.y){
                if(ce.i < cell.i) ce.ans = 'D';
                if(ce.i > cell.i) ce.ans = 'U';
                if(ce.j < cell.j) ce.ans = 'R';
                if(ce.j > cell.j) ce.ans = 'L';
                cellq.enq(ce);
            }
            if(DEBUG) foreach(cellu; cells) cellu.map!(c => c.ans).array.writeln;
            if(DEBUG) "".writeln;
        }
    }

    if(DEBUG) "-----".writeln;

    foreach(i; 0 .. n) foreach(j; 0 .. n){
        Cell cell = cells[i][j];
        if(cell.x >= 0 && cell.ans == ' '){
            "INVALID".writeln;
            return;
        }
    }

    foreach(i; 0 .. n) foreach(j; 0 .. n){
        Cell cell = cells[i][j];
        if(cell.x < 0){
            foreach(ce; cell.cells){
                if(ce.x < 0){
                    if(ce.i < cell.i) cell.ans = 'U';
                    if(ce.i > cell.i) cell.ans = 'D';
                    if(ce.j < cell.j) cell.ans = 'L';
                    if(ce.j > cell.j) cell.ans = 'R';
                    break;
                }
            }
            if(cell.ans == ' '){
                "INVALID".writeln;
                return;
            }
        }
    }

    "VALID".writeln;
    foreach(cellu; cells) cellu.map!(c => c.ans).array.writeln;
}

class Cell{
    int i, j;
    int x, y;
    char ans = ' ';
    Cell[] cells;
    this(int i, int j, int x, int y){
        this.i = i, this.j = j;
        this.x = x, this.y = y;
    }
}
class Queue(T){
	private T[] xs;
	private uint i, j; // i : 次に読み出す位置　j: 次に書き込む位置
	this(){	}
	this(T[] xs){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){
		while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1;
		xs[j ++] = x;
	}
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(){ return new Queue!T; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T cells){ return cells.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    int n = scan!int;
    Cell[][] cells = new Cell[][](n);
    foreach(i; 0 .. n) foreach(j; 0 .. n){
        cells[i] ~= new Cell(i, j, scan!int - 1, scan!int - 1);
    }

    foreach(i; 0 .. n - 1) foreach(j; 0 .. n){
        cells[i][j].cells ~= cells[i + 1][j];
        cells[i + 1][j].cells ~= cells[i][j];
    }
    foreach(i; 0 .. n) foreach(j; 0 .. n - 1){
        cells[i][j].cells ~= cells[i][j + 1];
        cells[i][j + 1].cells ~= cells[i][j];
    }

    auto cellq = new Queue!Cell;
    foreach(i; 0 .. n) foreach(j; 0 .. n){
        Cell cell = cells[i][j];
        if(cell.x == i && cell.y == j) cell.ans = 'X';
        cellq.enq(cell);
    }

    while(cellq.length > 0){
        Cell cell = cellq.deq;
        foreach(ce; cell.cells){
            if(ce.ans != ' ') continue;
            if(ce.x == cell.x && ce.y == cell.y){
                if(ce.i < cell.i) ce.ans = 'D';
                if(ce.i > cell.i) ce.ans = 'U';
                if(ce.j < cell.j) ce.ans = 'R';
                if(ce.j > cell.j) ce.ans = 'L';
                cellq.enq(ce);
            }
        }
    }

    foreach(i; 0 .. n) foreach(j; 0 .. n){
        Cell cell = cells[i][j];
        if(cell.x >= 0 && cell.ans == ' '){
            "INVALID".writeln;
            return;
        }
    }

    foreach(i; 0 .. n) foreach(j; 0 .. n){
        Cell cell = cells[i][j];
        if(cell.x < 0){
            foreach(ce; cell.cells){
                if(ce.x < 0){
                    if(ce.i < cell.i) cell.ans = 'U';
                    if(ce.i > cell.i) cell.ans = 'D';
                    if(ce.j < cell.j) cell.ans = 'L';
                    if(ce.j > cell.j) cell.ans = 'R';
                    break;
                }
            }
            if(cell.ans == ' '){
                "INVALID".writeln;
                return;
            }
        }
    }

    "VALID".writeln;
    foreach(cellu; cells) cellu.map!(c => c.ans).array.writeln;
}

class Cell{
    int i, j;
    int x, y;
    char ans = ' ';
    Cell[] cells;
    this(int i, int j, int x, int y){
        this.i = i, this.j = j;
        this.x = x, this.y = y;
    }
}
class Queue(T){
	private T[] xs;
	private uint i, j; // i : 次に読み出す位置　j: 次に書き込む位置
	this(){	}
	this(T[] xs){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){
		while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1;
		xs[j ++] = x;
	}
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(){ return new Queue!T; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}


Polycarp bought a new expensive painting and decided to show it to his $$$n$$$ friends. He hung it in his room. $$$n$$$ of his friends entered and exited there one by one. At one moment there was no more than one person in the room. In other words, the first friend entered and left first, then the second, and so on.It is known that at the beginning (before visiting friends) a picture hung in the room. At the end (after the $$$n$$$-th friend) it turned out that it disappeared. At what exact moment it disappeared — there is no information.Polycarp asked his friends one by one. He asked each one if there was a picture when he entered the room. Each friend answered one of three:  no (response encoded with 0);  yes (response encoded as 1);  can't remember (response is encoded with ?). Everyone except the thief either doesn't remember or told the truth. The thief can say anything (any of the three options).Polycarp cannot understand who the thief is. He asks you to find out the number of those who can be considered a thief according to the answers.

The first number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The following is a description of test cases. The first line of each test case contains one string $$$s$$$ (length does not exceed $$$2 \cdot 10^5$$$) — a description of the friends' answers, where $$$s_i$$$ indicates the answer of the $$$i$$$-th friend. Each character in the string is either 0 or 1 or ?. The given regularity is described in the actual situation. In particular, on the basis of answers, at least one friend can be suspected of stealing a painting. It is guaranteed that the sum of string lengths over the entire input data set does not exceed $$$2 \cdot 10^5$$$.

Output one positive (strictly more zero) number – the number of people who could steal the picture based on the data shown.

NoteIn the first case, the answer is $$$1$$$ since we had exactly $$$1$$$ friend.The second case is similar to the first.In the third case, the suspects are the third and fourth friends (we count from one). It can be shown that no one else could be the thief.In the fourth case, we know absolutely nothing, so we suspect everyone.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = '1' ~ readln.strip ~ '0';
		auto n = s.length;
		auto p = s.countUntil ('0');
		auto q = n - 1 - s.retro.countUntil ('1');
		int res = n - 2;
		foreach (i; 1..n - 1)
		{
			res -= (p < i || q > i);
		}
		writeln (res);
	}
}

// cheese-cracker [2022-05-05]

void solve(){
    auto word = scan!(dchar[]);
    int last1 = -1;
    int first0 = -1;
    for(int i = 0; i < word.length; ++i){
       if(word[i] == '1'){
           last1 = i;
       }else if(word[i] == '0' && first0 == -1){
           first0 = i;
       }
    }
    if(last1 == -1 && first0 == -1){
        writeln(word.length.to!int);
    }else if(last1 == -1){
        writeln(first0 + 1);
    }else if(first0 == -1){
        writeln(word.length.to!int - last1);
    }else if(last1 < first0){
        writeln(first0 - last1 + 1);
    }else{
        long cnt0 = 0;
        for(int i = 0; i < last1; ++i){
            cnt0 += (word[i] == '0');
        }
        long cnt1 = 0;
        for(int i = first0+1; i < word.length; ++i){
            cnt1 += (word[i] == '1');
        }
        if(cnt1 > cnt0 || cnt0 < cnt1){
            writeln(1);
        }else{
            writeln(last1 - first0 + 1);
        }
    }
}

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

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


DZY loves chessboard, and he enjoys playing with it.He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.You task is to find any suitable placement of chessmen on the given chessboard.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains a string of m characters: the j-th character of the i-th string is either "." or "-". A "." means that the corresponding cell (in the i-th row and the j-th column) is good, while a "-" means it is bad.

Output must contain n lines, each line must contain a string of m characters. The j-th character of the i-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell. If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.

NoteIn the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are.

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    char[][] F = new char[][N];
    foreach (i; 0 .. N) {
        F[i] = cast(char[])readln.chomp;
    }

    char flip(char x) {
        if (x == 'B') return 'W';
        if (x == 'W') return 'B';
        assert(0);
    }

    const dy = [1, 0, -1, 0],
          dx = [0, 1, 0, -1];
    void dfs(int y, int x, char c) {
        F[y][x] = c;
        foreach (i; 0 .. 4) {
            int ny = y + dy[i],
                nx = x + dx[i];
            if (ny < 0 || ny >= N) continue;
            if (nx < 0 || nx >= M) continue;
            if (F[ny][nx] == '.') {
                dfs(ny, nx, flip(c));
            }
        }
    }

    for (int y = 0; y < N; y++) {
        for (int x = 0; x < M; x++) {
            if (F[y][x] == '.') {
                dfs(y, x, 'B');
            }
        }
    }
    foreach (ref L; F) {
        writeln(L);
    }
}

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

void main() {

	byte n, m;

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

	bool k = (m & 1) ? 0 : 1;

	char c;
	bool flag = 0;
	foreach (i; 0 .. n) {
		foreach (j; 0 .. m) {
			scanf(" %c", &c);
			if (c == '-')
				write('-');
			else if (flag)
				putchar('W');
			else
				putchar('B');
			flag ^= 1;
		}
		flag ^= k;
		putchar('\n');
	}
}

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

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

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

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

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

int M, N;
string[] A;

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

		foreach (x; 0 .. M) {
			foreach (y; 0 .. N) {
				write((A[x][y] == '-') ? '-' : ((x + y) % 2 == 0) ? 'B' : 'W');
			}
			writeln;
		}

	}
	} catch (EOFException) {}
}

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    char[][] F = new char[][N];
    foreach (i; 0 .. N) {
        F[i] = cast(char[])readln.chomp;
    }

    char flip(char x) {
        if (x == 'B') return 'W';
        if (x == 'W') return 'B';
        assert(0);
    }

    bool C(char x) {
        return x == 'W' || x == 'B';
    }

    for (int y = 0; y < N; y++) {
        for (int x = 0; x < M; x++) {
            if (F[y][x] == '-') continue;
            if (y - 1 >= 0 && C(F[y - 1][x])) {
                F[y][x] = flip(F[y - 1][x]);
            } else if (x - 1 >= 0 && C(F[y][x - 1])) {
                F[y][x] = flip(F[y][x - 1]);
            } else {
                F[y][x] = 'B';
            }
        }
    }
    foreach (ref L; F) {
        writeln(L);
    }
}

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

char[102][102] a;

void main() {

	byte n, m;

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

	char c;
	foreach (i; 1 .. n + 1)
		foreach (j; 1 .. m + 1) {
			scanf(" %c", &c);
			if (c == '-')
				a[i][j] = '-';
			else
				a[i][j] = 'W';
		}

	foreach (i; 1 .. n + 1) {
		foreach (j; 1 .. m + 1) {
			if (a[i][j] == '-') {
				write('-');
				continue;
			}
			if ((i != 1 && j != 1) && a[i][j] == 'W' && a[i - 1][j] != 'B' && a[i][j + 1] != 'B' && a[i + 1][j] != 'B' && a[i][j - 1] != 'B') {
				a[i][j] = 'B';
				write('B');
			}
			else
				write('W');
		}
		putchar('\n');
	}
}

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

char[102][102] a;

void main() {

	byte n, m;

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

	char c;
	foreach (i; 1 .. n + 1)
		foreach (j; 1 .. m + 1) {
			scanf(" %c", &c);
			if (c == '-')
				a[i][j] = '-';
			else
				a[i][j] = 'W';
		}

	foreach (i; 1 .. n + 1) {
		foreach (j; 1 .. m + 1) {
			if (a[i][j] == '-') {
				write('-');
				continue;
			}
			if (i == 1 && j == 0) {
				write('W');
				continue;
			}
			if ( a[i][j] == 'W' && a[i - 1][j] != 'B' && a[i][j + 1] != 'B' && a[i + 1][j] != 'B' && a[i][j - 1] != 'B') {
				a[i][j] = 'B';
				write('B');
			}
			else
				write('W');
		}
		putchar('\n');
	}
}

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

char[102][102] a;

void main() {

	byte n, m;

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

	char c;
	foreach (i; 1 .. n + 1)
		foreach (j; 1 .. m + 1) {
			scanf(" %c", &c);
			if (c == '-')
				a[i][j] = '-';
			else
				a[i][j] = 'W';
		}

	foreach (i; 1 .. n + 1) {
		foreach (j; 1 .. m + 1) {
			if (a[i][j] == '-') {
				write('-');
				continue;
			}
			if (a[i][j] == 'W' && a[i - 1][j] != 'B' && a[i][j + 1] != 'B' && a[i + 1][j] != 'B' && a[i][j - 1] != 'B') {
				a[i][j] = 'B';
				write('B');
			}
			else
				write('W');
		}
		putchar('\n');
	}
}

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

char[102][102] a;

void main() {

	byte n, m;

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

	char c;
	foreach (i; 1 .. n + 1)
		foreach (j; 1 .. m + 1) {
			scanf(" %c", &c);
			if (c == '-')
				a[i][j] = '-';
			else
				a[i][j] = 'W';
		}

	foreach (i; 1 .. n + 1) {
		foreach (j; 1 .. m + 1) {
			if (a[i][j] == '-') {
				write('-');
				continue;
			}
			if (i == 1 && j == 1) {
				write('W');
				continue;
			}
			if ( a[i][j] == 'W' && a[i - 1][j] != 'B' && a[i][j + 1] != 'B' && a[i + 1][j] != 'B' && a[i][j - 1] != 'B') {
				a[i][j] = 'B';
				write('B');
			}
			else
				write('W');
		}
		putchar('\n');
	}
}

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

void main() {

	byte n, m;

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

	char c;
	bool flag;
	foreach (i; 1 .. n + 1) {
		foreach (j; 1 .. m + 1) {
			scanf(" %c", &c);
			if (c == '-')
				write('-');
			else if (flag)
				putchar('W');
			else
				putchar('B');
			flag ^= 1;
		}
		flag ^= 1;
		putchar('\n');
	}
}

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

char[100][100] a;

void main() {

	byte n, m;

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

	char c;
	foreach (i; 0 .. n)
		foreach (j; 0 .. m) {
			scanf(" %c", &c);
			if (c == '-')
				a[i][j] = '-';
			else
				a[i][j] = 'W';
		}

	foreach (i; 0 .. n) {
		foreach (j; 0 .. m)
			if (a[i][j] == '-')
				write('-');
			else if (a[i][j] == 'W') {
				if (j + 1 <= m - 1 && i + 1 <= n - 1 && a[i][j + 1] == 'W' && a[i + 1][j] == 'W' ||
					i - 1 >= 0 && j - 1 >= 0 && a[i - 1][j] == 'W' && a[i][j - 1] == 'W') {
					write('B');
					a[i][j] = 'B';
				}
				else
					write('W');
			}
		putchar('\n');
	}
}


Petya has recently learned data structure named "Binary heap".The heap he is now operating with allows the following operations:   put the given number into the heap;  get the value of the minimum element in the heap;  extract the minimum element from the heap; Thus, at any moment of time the heap contains several integers (possibly none), some of them might be equal.In order to better learn this data structure Petya took an empty heap and applied some operations above to it. Also, he carefully wrote down all the operations and their results to his event log, following the format:   insert x — put the element with value x in the heap;  getMin x — the value of the minimum element contained in the heap was equal to x;  removeMin — the minimum element was extracted from the heap (only one instance, if there were many). All the operations were correct, i.e. there was at least one element in the heap each time getMin or removeMin operations were applied.While Petya was away for a lunch, his little brother Vova came to the room, took away some of the pages from Petya's log and used them to make paper boats.Now Vova is worried, if he made Petya's sequence of operations inconsistent. For example, if one apply operations one-by-one in the order they are written in the event log, results of getMin operations might differ from the results recorded by Petya, and some of getMin or removeMin operations may be incorrect, as the heap is empty at the moment they are applied.Now Vova wants to add some new operation records to the event log in order to make the resulting sequence of operations correct. That is, the result of each getMin operation is equal to the result in the record, and the heap is non-empty when getMin ad removeMin are applied. Vova wants to complete this as fast as possible, as the Petya may get back at any moment. He asks you to add the least possible number of operation records to the current log. Note that arbitrary number of operations may be added at the beginning, between any two other operations, or at the end of the log.

The first line of the input contains the only integer n (1 ≤ n ≤ 100 000) — the number of the records left in Petya's journal. Each of the following n lines describe the records in the current log in the order they are applied. Format described in the statement is used. All numbers in the input are integers not exceeding 109 by their absolute value.

The first line of the output should contain a single integer m — the minimum possible number of records in the modified sequence of operations. Next m lines should contain the corrected sequence of records following the format of the input (described in the statement), one per line and in the order they are applied. All the numbers in the output should be integers not exceeding 109 by their absolute value. Note that the input sequence of operations must be the subsequence of the output sequence. It's guaranteed that there exists the correct answer consisting of no more than 1 000 000 operations.

6
insert 1
insert 1
removeMin
removeMin
insert 2
getMin 2

NoteIn the first sample, after number 3 is inserted into the heap, the minimum number is 3. To make the result of the first getMin equal to 4 one should firstly remove number 3 from the heap and then add number 4 into the heap.In the second sample case number 1 is inserted two times, so should be similarly removed twice.

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

struct _node{
    int x,s=0;
    _node* l=null,r=null;
}
alias node=_node*;
node root=null;
node merge(node l,node r){
    if(!l||!r) return l?l:r;
    if(l.x>r.x)
        swap(l,r);
    l.r=merge(l.r,r);
    if(!l.l)
        swap(l.l,l.r);
    else{
        if(l.l.s<l.r.s)
            swap(l.l,l.r);
        l.s=l.r.s+1;
    }
    return l;
}

void main(){
    int n=readln.chomp.to!int;
    string s;
    int v;
    string[] r;
    void add(){
        r~="insert "~v.to!string;
    }
    while(n--){
        auto line=readln.splitter.array;
        s=line[0].strip;
        if(s=="removeMin"){
            if(!root)
                r~="insert 1";
            else
                root=merge(root.l,root.r);
            r~=s;
        }
        else if(s=="getMin"){
            v=line[1].to!int;
            while(root && root.x<v){
                r~="removeMin";
                root=merge(root.l,root.r);
            }
            if(!root || root.x>v){
                add();
                root=merge(root,new _node(v));
            }
            r~=s~" "~v.to!string;
        }
        else{
            v=line[1].to!int;
            root=merge(root,new _node(v));
            add();
        }
    }
    writeln(r.length);
    foreach(ref x;r)
        writeln(x);
}

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

void main(){
    BinaryHeap!(Array!int,"a>b") h;
    int n=readln.chomp.to!int;
    string s;
    int v;
    string[] r;
    void add(){
        r~="insert "~v.to!string;
    }
    while(n--){
        auto line=readln.splitter.array;
        s=line[0].strip;
        if(s=="removeMin"){
            if(h.empty)
                r~="insert 1";
            r~=s;
        }
        else if(s=="getMin"){
            v=line[1].to!int;
            if(!h.empty){
                if(v<h.front)
                    add();
                else{
                    while(!h.empty && v>h.front){
                        r~="removeMin";
                        h.removeFront;
                    }
                    if(h.empty || h.front>v)
                        add();
                }
            }else{
                add();
                h.insert(v);
            }
            r~=s~v.to!string;
        }
        else{
            v=line[1].to!int;
            h.insert(v);
            r~=s~v.to!string;
        }
    }
}

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

void main(){
    BinaryHeap!(Array!int,"a>b") h;
    int n=readln.chomp.to!int;
    string s;
    int v;
    while(n--){
        auto line=readln.splitter
                        .array;
        s=line[0].strip;
        if(s=="removeMin"){
            if(h.empty)
                writeln("insert 1");
            writeln(s);
        }
        else if(s=="getMin"){
            v=line[1].to!int;
            if(!h.empty){
                if(v<h.front){
                    writefln!"insert %d"(v);
                }
                else{
                    while(!h.empty && v>h.front){
                        writeln("removeMin");
                        h.removeFront;
                    }
                    if(h.empty || h.front>v){
                        writefln!"insert %d"(v);
                    }
                }
            }else{
                writeln("insert ",v);
                h.insert(v);
            }
            writefln!"%s %d"(s,v);
        }
        else{
            v=line[1].to!int;
            h.insert(v);
            writefln!"%s %d"(s,v);
        }
    }
}

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

void main(){
    BinaryHeap!(Array!int,"a>b") h;
    int n=readln.chomp.to!int;
    string s;
    int v;
    string[] r;
    void add(){
        r~="insert "~v.to!string;
    }
    while(n--){
        auto line=readln.splitter.array;
        s=line[0].strip;
        if(s=="removeMin"){
            if(h.empty)
                r~="insert 1";
            r~=s;
        }
        else if(s=="getMin"){
            v=line[1].to!int;
            if(!h.empty){
                if(v<h.front)
                    add();
                else{
                    while(!h.empty && v>h.front){
                        r~="removeMin";
                        h.removeFront;
                    }
                    if(h.empty || h.front>v)
                        add();
                }
            }else{
                add();
                h.insert(v);
            }
            r~=s~" "~v.to!string;
        }
        else{
            v=line[1].to!int;
            h.insert(v);
            add();
        }
    }
    writeln(r.length);
    foreach(ref x;r)
        writeln(x);
}


While performing complex market analysis William encountered the following problem:For a given array $$$a$$$ of size $$$n$$$ and a natural number $$$e$$$, calculate the number of pairs of natural numbers $$$(i, k)$$$ which satisfy the following conditions:   $$$1 \le i, k$$$  $$$i + e \cdot k \le n$$$.  Product $$$a_i \cdot a_{i + e} \cdot a_{i + 2 \cdot e} \cdot \ldots \cdot a_{i + k \cdot e} $$$ is a prime number. A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.

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 two integers $$$n$$$ and $$$e$$$ $$$(1 \le e \le n \le 2 \cdot 10^5)$$$, the number of items in the array and number $$$e$$$, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^6)$$$, the contents of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output the answer in the following format: Output one line containing the number of pairs of numbers $$$(i, k)$$$ which satisfy the conditions.

NoteIn the first example test case two pairs satisfy the conditions:   $$$i = 2, k = 1$$$, for which the product is: $$$a_{2} \cdot a_{5} = 2$$$ which is a prime number.  $$$i = 3, k = 1$$$, for which the product is: $$$a_{3} \cdot a_{6} = 19$$$ which is a prime number. In the second example test case there are no pairs that satisfy the conditions.In the third example test case four pairs satisfy the conditions:   $$$i = 1, k = 1$$$, for which the product is: $$$a_{1} \cdot a_{4} = 2$$$ which is a prime number.  $$$i = 1, k = 2$$$, for which the product is: $$$a_{1} \cdot a_{4} \cdot a_{7} = 2$$$ which is a prime number.  $$$i = 3, k = 1$$$, for which the product is: $$$a_{3} \cdot a_{6} = 2$$$ which is a prime number.  $$$i = 6, k = 1$$$, for which the product is: $$$a_{6} \cdot a_{9} = 2$$$ which is a prime number. In the fourth example test case there are no pairs that satisfy the conditions.In the fifth example test case five pairs satisfy the conditions:   $$$i = 1, k = 1$$$, for which the product is: $$$a_{1} \cdot a_{2} = 2$$$ which is a prime number.  $$$i = 1, k = 2$$$, for which the product is: $$$a_{1} \cdot a_{2} \cdot a_{3} = 2$$$ which is a prime number.  $$$i = 1, k = 3$$$, for which the product is: $$$a_{1} \cdot a_{2} \cdot a_{3} \cdot a_{4} = 2$$$ which is a prime number.  $$$i = 2, k = 1$$$, for which the product is: $$$a_{2} \cdot a_{3} = 2$$$ which is a prime number.  $$$i = 2, k = 2$$$, for which the product is: $$$a_{2} \cdot a_{3} \cdot a_{4} = 2$$$ which is a prime number. In the sixth example test case there are no pairs that satisfy the conditions.

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

immutable int limit = 10 ^^ 6 + 3;

void main ()
{
	auto s = new bool [limit];
	s[2..$] = true;
	for (int d = 2; d * d < limit; d++)
	{
		if (s[d])
		{
			for (int e = d; e * d < limit; e++)
			{
				s[e * d] = false;
			}
		}
	}

	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, e;
		readf !(" %s %s") (n, e);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		long res = 0;
		int primes = 0;
		foreach (start; 0..e)
		{
			int lo = 0;
			int hi = 0;
			foreach (c; a.drop (start).stride (e))
			{
				if (c == 1)
				{
					hi += 1;
					res += lo;
				}
				else if (s[c])
				{
					lo = hi + 1;
					hi = 0;
					res += lo;
					primes += 1;
				}
				else
				{
					lo = 0;
					hi = 0;
				}
			}
		}
		writeln (res - primes);
	}
}

immutable multi = true;

immutable int maxAi = 1_000_000;
bool[maxAi+1] isPrime = true;

static this()
{
  isPrime[0] = isPrime[1] = false;
  foreach(n; 2 .. maxAi+1)
    {
      if (isPrime[n])
	{
	  for(int m = 2*n;
	      m <= maxAi;
	      m += n) isPrime[m] = false;
	}
    }
}

void solve(int tc)
{
  auto n = readInt!int;
  auto e = readInt!int;
  debug writeln("solving case ", e, " ", n);
  auto a = ma(n, readInt!int);
  auto cnt1 = new int[](n);
  foreach_reverse(i; 0 .. n)
    {
      if (i + e < n)
	{
	  if (a[i] == 1)
	    {
	      cnt1[i] = 1 + cnt1[i + e];
	    }
	  else
	    {
	      cnt1[i] = 0;
	    }
	}
      else
	{
	  cnt1[i] = int(a[i] == 1);
	}
    }
  debug writeln(cnt1);
  long ans = 0;
  foreach_reverse(i; 0 .. n)
    {
      if (isPrime[a[i]])
	{
	  ans += i + e < n? cnt1[i + e] : 0;
	}
      else if (a[i] == 1)
	{
	  auto nxt = i + e * cnt1[i];
	  debug writeln("for ", i, " next is ", nxt);
	  if (nxt < n)
	    {
	      auto aNxt = a[nxt];
	      if (isPrime[aNxt])
		{
		  ans += 1 + (nxt + e < n? cnt1[nxt + e] : 0);
		}
	    }
	}
    }
  ans.writeln;
}

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

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

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

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

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

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

// From: https://rosettacode.org/wiki/Sieve_of_Eratosthenes#D

/// Extensible Sieve of Eratosthenes.
struct Prime {
    uint[] a = [2];
    private void grow() pure nothrow @safe {
        immutable p0 = a[$ - 1] + 1;
        auto b = new bool[p0];

        foreach (immutable di; a) {
            immutable uint i0 = p0 / di * di;
            uint i = (i0 < p0) ? i0 + di - p0 : i0 - p0;
            for (; i < b.length; i += di)
                b[i] = true;
        }
        foreach (immutable uint i, immutable bi; b)
            if (!b[i])
                a ~= p0 + i;
    }
    uint opCall(in uint n) pure nothrow @safe {
        while (n >= a.length)
            grow;
        return a[n];
    }
}

int get_ones_l(int[] a, int i, int e, int[] ones_l)
{
  if (ones_l[i] != -1)
    return ones_l[i];
  if (i - e < 0 || a[i - e] != 1) {
    ones_l[i] = 0;
  } else {
    ones_l[i] = 1 + get_ones_l(a, i - e, e, ones_l);
  }
  return ones_l[i];
}

int get_ones_r(int[] a, int i, int e, int[] ones_r)
{
  if (ones_r[i] != -1)
    return ones_r[i];
  if (i + e >= a.length || a[i + e] != 1) {
    ones_r[i] = 0;
  } else {
    ones_r[i] = 1 + get_ones_r(a, i + e, e, ones_r);
  }
  return ones_r[i];
}

void main()
{
  Prime prime;
  bool[int] primes;
  foreach (prime_num ; int.max.iota.map!prime.until!q{a > 1000001})
    primes[prime_num] = true;

  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, e;
    readf!" %d %d "(n, e);
    auto a = readln.splitter.map!(to!int).array;
    foreach (ref x ; a) {
      if (x == 1)
        continue;
      if (x in primes)
        x = 2;
      else
        x = 0;
    }

    auto ones_l = new int[](n);
    auto ones_r = new int[](n);
    ones_l[] = -1;
    ones_r[] = -1;

    long ans;
    foreach (i ; 0 .. n) {
      if (a[i] != 2)
        continue;
      long l = get_ones_l(a, i, e, ones_l);
      long r = get_ones_r(a, i, e, ones_r);
      if (l != 0 || r != 0) {
        ans += (l + 1) * (r + 1) - 1;
      }
    }
    writeln(ans);
  }
}

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

immutable int limit = 10 ^^ 6 + 3;

void main ()
{
	auto s = new bool [limit];
	s[2..$] = true;
	for (int d = 2; d * d < limit; d++)
	{
		if (s[d])
		{
			for (int e = d; e * d < limit; e += d)
			{
				s[e * d] = false;
			}
		}
	}

	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, e;
		readf !(" %s %s") (n, e);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		long res = 0;
		int primes = 0;
		foreach (start; 0..e)
		{
			int lo = 0;
			int hi = 0;
			foreach (c; a.drop (start).stride (e))
			{
				if (c == 1)
				{
					hi += 1;
					res += lo;
				}
				else if (s[c])
				{
					lo = hi + 1;
					hi = 0;
					res += lo;
					primes += 1;
				}
				else
				{
					lo = 0;
					hi = 0;
				}
			}
		}
		writeln (res - primes);
	}
}


There are $$$n$$$ trees in a park, numbered from $$$1$$$ to $$$n$$$. The initial height of the $$$i$$$-th tree is $$$h_i$$$.You want to water these trees, so they all grow to the same height.The watering process goes as follows. You start watering trees at day $$$1$$$. During the $$$j$$$-th day you can:   Choose a tree and water it. If the day is odd (e.g. $$$1, 3, 5, 7, \dots$$$), then the height of the tree increases by $$$1$$$. If the day is even (e.g. $$$2, 4, 6, 8, \dots$$$), then the height of the tree increases by $$$2$$$.  Or skip a day without watering any tree. Note that you can't water more than one tree in a day. Your task is to determine the minimum number of days required to water the trees so they grow to the same height.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of trees. The second line of the test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).

For each test case, print one integer — the minimum number of days required to water the trees, so they grow to the same height.

NoteConsider the first test case of the example. The initial state of the trees is $$$[1, 2, 4]$$$.  During the first day, let's water the first tree, so the sequence of heights becomes $$$[2, 2, 4]$$$;  during the second day, let's water the second tree, so the sequence of heights becomes $$$[2, 4, 4]$$$;  let's skip the third day;  during the fourth day, let's water the first tree, so the sequence of heights becomes $$$[4, 4, 4]$$$. Thus, the answer is $$$4$$$.

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

T read(T)() {
    return readln.chomp.to!T;
}
T[] readarray(T)() {
    return readln.chomp.split(" ").map!(to!T).array;
}

enum long INFLL = 1L<<56;

void solve() {
    int N = read!int;
    auto H = readarray!long;
    auto Hmax = H.reduce!max;

    bool C(long x, long hmax) {
        int k = 0;
        auto HH = H.dup;
        for (int i = 0; i < N; i++) {
            if (H[i] % 2 == hmax % 2) {
                HH[i] = H[i];
            } else {
                k++;
                HH[i] = H[i] + 1;
            }
        }
        if ( (x + 1) / 2 < k ) return false;
        long r = 0;
        for (int i = 0; i < N; i++) {
            r += hmax - HH[i];
        }
        return r <= 2 * (x / 2) + (x + 1) / 2 - k;
    }

    long try_h(long hmax) {
        long lb = 0, ub = INFLL;
        if (C(lb, hmax)) {
            ub = lb;
        } else {
            while (lb + 1 < ub) {
                long mid = (lb + ub) / 2;
                (C(mid, hmax) ? ub : lb) = mid;
            }
        }
        return ub;
    }

    auto ans = min(try_h(Hmax), try_h(Hmax + 1));
    writeln(ans);
}

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

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

T read(T)() {
    return readln.chomp.to!T;
}
T[] readarray(T)() {
    return readln.chomp.split(" ").map!(to!T).array;
}

enum long INFLL = 1L<<56;

void solve() {
    int N = read!int;
    auto H = readarray!long;
    auto Hmax = H.reduce!max;

    bool C(long x) {
        int k = 0;
        auto HH = H.dup;
        for (int i = 0; i < N; i++) {
            if (H[i] % 2 == Hmax % 2) {
                HH[i] = H[i];
            } else {
                k++;
                HH[i] = H[i] + 1;
            }
        }
        if ( (x + 1) / 2 < k ) return false;
        long r = 0;
        for (int i = 0; i < N; i++) {
            r += Hmax - HH[i];
        }
        return r <= 2 * (x / 2) + (x + 1) / 2 - k;
    }

    long lb = 0, ub = INFLL;
    if (C(lb)) {
        ub = lb;
    } else {
        while (lb + 1 < ub) {
            long mid = (lb + ub) / 2;
            (C(mid) ? ub : lb) = mid;
        }
    }
    writeln(ub);
}

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


Alina has discovered a weird language, which contains only $$$4$$$ words: $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string.Alina has found one such sentence $$$s$$$ and she is curious: is it possible that it consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$?In other words, determine, if it's possible to concatenate these $$$a+b+c+d$$$ words in some order so that the resulting string is $$$s$$$. Each of the $$$a+b+c+d$$$ words must be used exactly once in the concatenation, but you can choose the order in which they are concatenated.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0\le a,b,c,d\le 2\cdot 10^5$$$) — the number of times that words $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$ respectively must be used in the sentence. The second line contains the string $$$s$$$ ($$$s$$$ consists only of the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$, $$$1\le |s| \le 2\cdot 10^5$$$, $$$|s|=a+b+2c+2d$$$)  — the sentence. Notice that the condition $$$|s|=a+b+2c+2d$$$ (here $$$|s|$$$ denotes the length of the string $$$s$$$) is equivalent to the fact that $$$s$$$ is as long as the concatenation of the $$$a+b+c+d$$$ words. The sum of the lengths of $$$s$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.

For each test case output $$$\texttt{YES}$$$ if it is possible that the sentence $$$s$$$ consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$, and $$$\texttt{NO}$$$ otherwise. You can output each letter in any case.

8
1 0 0 0
B
0 0 1 0
AB
1 1 0 1
ABAB
1 0 1 1
ABAAB
1 1 2 2
BAABBABBAA
1 1 2 3
ABABABBAABAB
2 3 5 4
AABAABBABAAABABBABBBABB
1 3 3 10
BBABABABABBBABABABABABABAABABA

NoteIn the first test case, the sentence $$$s$$$ is $$$\texttt{B}$$$. Clearly, it can't consist of a single word $$$\texttt{A}$$$, so the answer is $$$\texttt{NO}$$$.In the second test case, the sentence $$$s$$$ is $$$\texttt{AB}$$$, and it's possible that it consists of a single word $$$\texttt{AB}$$$, so the answer is $$$\texttt{YES}$$$.In the third test case, the sentence $$$s$$$ is $$$\texttt{ABAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{B} = \texttt{ABAB}$$$.In the fourth test case, the sentence $$$s$$$ is $$$\texttt{ABAAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{AB}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{AB} = \texttt{ABAAB}$$$. In the fifth test case, the sentence $$$s$$$ is $$$\texttt{BAABBABBAA}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, two words $$$\texttt{AB}$$$, and two words $$$\texttt{BA}$$$, as $$$\texttt{BA} + \texttt{AB} + \texttt{B} + \texttt{AB} + \texttt{BA} + \texttt{A}= \texttt{BAABBABBAA}$$$.

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

bool solve (int [] x, string s)
{
	auto a = x[0];
	auto b = x[1];
	auto ab = x[2];
	auto ba = x[3];
	auto n = s.length.to !(int);

	auto ra = s.count ("A");
	auto rb = s.count ("B");
	if (ra != a + ab + ba || rb != b + ab + ba)
	{
		return false;
	}

	alias Record = Tuple !(int, q{a}, int, q{b}, char, q{start});
	Record [] r;
	int ca = 0;
	int cb = 0;
	char start;
	foreach (i; 0..n)
	{
		if (ca == 0 && cb == 0)
		{
			start = s[i];
		}
		if (s[i] == 'A')
		{
			ca += 1;
		}
		else
		{
			cb += 1;
		}
		if (i + 1 == n || s[i] == s[i + 1])
		{
			r ~= Record (ca, cb, start);
			ca = 0;
			cb = 0;
		}
	}
	r.schwartzSort !(t => t.a + t.b);
	reverse (r);

	int wildcard = 0;
	foreach (ref t; r)
	{
		if (t.a != t.b)
		{
			wildcard += min (t.a, t.b);
		}
	}

	int pab = 0;
	int pba = 0;
	foreach (ref t; r)
	{
		if (t.a == t.b)
		{
			if (t.start == 'A')
			{
				pab += t.a;
			}
			else
			{
				pba += t.b;
			}
		}
	}

	foreach (ref t; r)
	{
		if (t.a == t.b)
		{
			if (t.start == 'A')
			{
				if (pba + wildcard < ba)
				{
					int cur = t.b - 1;
					pab -= 1;
					while (pba + wildcard < ba && cur > 0)
					{
						cur -= 1;
						pab -= 1;
						pba += 1;
					}
				}
			}
			else
			{
				if (pab + wildcard < ab)
				{
					int cur = t.a - 1;
					pba -= 1;
					while (pab + wildcard < ab && cur > 0)
					{
						cur -= 1;
						pba -= 1;
						pab += 1;
					}
				}
			}
		}
	}

	if (pab + wildcard >= ab && pba + wildcard >= ba &&
	    pab + pba + wildcard >= ab + ba)
	{
		return true;
	}
	return false;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto x = readln.splitter.map !(to !(int)).array;
		auto s = readln.strip;
		writeln (solve (x, s) ? "YES" : "NO");
	}
}

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 solve(int A, int B, int C, int D, string S) {
  debug {
    writeln("  ", [A, B, C, D], " ", S);
  }
  const N = cast(int)(S.length);
  const cntA = cast(int)(S.count('A'));
  const cntB = cast(int)(S.count('B'));
  if (cntA != A + C + D) return 1;
  if (cntB != B + C + D) return 2;

  int odd;
  int[][2] fss;
  for (int i = 0, j; i < N; i = j) {
    for (j = i; j < N && ((S[i] == S[j]) == ((i & 1) == (j & 1))); ++j) {}
    debug {
      writeln("    ", S[i .. j]);
    }
    if ((j - i) % 2 != 0) {
      odd += (j - i) / 2;
    } else {
      fss[S[i] - 'A'] ~= (j - i) / 2;
    }
  }
  foreach (h; 0 .. 2) {
    fss[h].sort;
  }
  debug {
    writeln("    odd = ", odd);
    writeln("    fss = ", fss);
  }

  int[2] cs = [C, D];
  foreach (h; 0 .. 2) {
    foreach (ref f; fss[h]) {
      const t = min(f, cs[h]);
      f -= t;
      cs[h] -= t;
    }
  }
  debug {
    writeln("    ", fss, " ", cs);
  }
  foreach (h; 0 .. 2) {
    foreach (ref f; fss[h ^ 1]) if (f >= 1) {
      const t = min(f - 1, cs[h]);
      cs[h] -= t;
    }
  }
  if (cs[0] + cs[1] > odd) {
    return 3;
  }

  return 0;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const A = readInt;
        const B = readInt;
        const C = readInt;
        const D = readInt;
        const S = readToken;

        const ans = solve(A, B, C, D, S);
        writeln((ans == 0) ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}


Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him.

The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds.

Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan.    All the pi's should be mutually different.  All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1).  If there are several solutions, output any.

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

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

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

	for (int case_i = 1; case_i <= n_Cases; case_i++) {
                int n = cin.readInt;
                int i = 1;
                int j = n;
                int count = 0;
                while (1) {
                        if (count % 2) {
                                write(j, " ");
                                j--;
                        } else {
                                write(i, " ");
                                i++;
                        }
                        count++;
                        if (count == n) break;
                }
	}
}


Ilya plays a card game by the following rules.A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of cards Ilya has. Each of the next n lines contains two non-negative space-separated integers — ai and bi (0 ≤ ai, bi ≤ 104) — the numbers, written at the top and the bottom of the i-th card correspondingly.

Print the single number — the maximum number of points you can score in one round by the described rules.

NoteIn the first sample none of two cards brings extra moves, so you should play the one that will bring more points.In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards.

module cf_155B;

import std.stdio;
import std.algorithm;

struct Card {
    int topValue, bottomValue;

    int opCmp(ref const Card card) const {
        if (topValue == card.topValue && bottomValue == card.bottomValue) {
            return 0;
        }
        if (bottomValue > card.bottomValue || bottomValue == card.bottomValue &&
            topValue > card.topValue) {
            return -1;
        }
        return 1;
    }
}

void main() {
    int n;
    Card[] cards;

    readf("%d", &n);
    cards = new Card[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d %d", &cards[i].topValue, &cards[i].bottomValue);
    }

    sort(cards);

    int counter = 1, curCard = 0, points = 0;
    while (counter > 0 && curCard < n) {
        points += cards[curCard].topValue;
        counter += cards[curCard++].bottomValue - 1;
    }

    writeln(points);
}


It is the hard version of the problem. The only difference is that in this version $$$3 \le k \le n$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, such that:  $$$a_1 + a_2 + \ldots + a_k = n$$$  $$$LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \ldots, a_k$$$.We can show that for given constraints the answer always exists.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^4)$$$  — the number of test cases. The only line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \le n \le 10^9$$$, $$$3 \le k \le n$$$). It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, for which all conditions are satisfied.

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

string FMT_F = "%.10f";

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

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

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

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

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

		n -= k - 3;
		if (n % 2)
		{
			auto x = n - 1;
			ans[ti] = [1, x/2, x/2];
		}
		else if ((n/2) % 2)
		{
			auto x = n - 2;
			ans[ti] = [2, x/2, x/2];
		}
		else
		{
			ans[ti] = [n/2, n/4, n/4];
		}
		foreach (i; 0..k-3)
		{
			ans[ti] ~= 1;
		}
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}


Mitya has a rooted tree with $$$n$$$ vertices indexed from $$$1$$$ to $$$n$$$, where the root has index $$$1$$$. Each vertex $$$v$$$ initially had an integer number $$$a_v \ge 0$$$ written on it. For every vertex $$$v$$$ Mitya has computed $$$s_v$$$: the sum of all values written on the vertices on the path from vertex $$$v$$$ to the root, as well as $$$h_v$$$ — the depth of vertex $$$v$$$, which denotes the number of vertices on the path from vertex $$$v$$$ to the root. Clearly, $$$s_1=a_1$$$ and $$$h_1=1$$$.Then Mitya erased all numbers $$$a_v$$$, and by accident he also erased all values $$$s_v$$$ for vertices with even depth (vertices with even $$$h_v$$$). Your task is to restore the values $$$a_v$$$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $$$a_v$$$ for all vertices in the tree.

The first line contains one integer $$$n$$$ — the number of vertices in the tree ($$$2 \le n \le 10^5$$$). The following line contains integers $$$p_2$$$, $$$p_3$$$, ... $$$p_n$$$, where $$$p_i$$$ stands for the parent of vertex with index $$$i$$$ in the tree ($$$1 \le p_i < i$$$). The last line contains integer values $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$-1 \le s_v \le 10^9$$$), where erased values are replaced by $$$-1$$$.

Output one integer — the minimum total sum of all values $$$a_v$$$ in the original tree, or $$$-1$$$ if such tree does not exist.

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;

immutable long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto P = readln.split.map!(to!int).array;
    auto S = readln.split.map!(to!long).array;
    auto X = new long[](N);
    auto G = new int[][](N);
    foreach (i; 0..N-1) {
        G[P[i]-1] ~= i+1;
        G[i+1] ~= P[i]-1;
    }

    bool ok = true;
    long ans = 0;

    long dfs(int n, int p) {
        long ret = S[n];
        if (ret == -1) ret = INF;
        foreach (m; G[n]) {
            if (m == p) continue;
            auto v = dfs(m, n);
            if (v < S[n]) ok = false;
            ret = min(ret, v);
        }
        X[n] = ret;
        return ret;
    }

    void dfs2(int n, int p, long s) {
        if (X[n] == INF) return;
        long a = X[n] - s;
        ans += a;
        foreach (m; G[n]) {
            if (m == p) continue;
            dfs2(m, n, X[n]);
        }
    }

    dfs(0, -1);

    if (!ok) {
        writeln(-1);
        return;
    }

    dfs2(0, -1, 0);

    ans.writeln;
}

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

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[0]; tokens.popFront; return token; }
int readInt() { return readToken().to!int; }
long readLong() { return readToken().to!long; }
real readReal() { return readToken().to!real; }

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

int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = cast(int)(as.length); for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a < val)); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a <= val)); }

int N;
int[] P;
long[] S;

long solve() {
  auto h = new int[N];
  h[0] = 1;
  foreach (u; 1 .. N) {
    h[u] = h[P[u]] + 1;
  }
  debug {
    writefln("h = %s", h);
  }
  foreach (u; 0 .. N) {
    if ((S[u] == -1) != (h[u] % 2 == 0)) {
      debug {
        writeln("incorrectly erased");
      }
      return -1;
    }
  }

  auto graph = new int[][N];
  foreach (u; 1 .. N) {
    graph[P[u]] ~= u;
  }

  auto a = new long[N];
  a[0] = S[0];
  foreach (u; 1 .. N) {
    if (S[u] == -1) {
      if (graph[u].empty) {
        a[u] = 0;
      } else {
        a[u] = graph[u].map!(v => S[v]).minElement - S[P[u]];
      }
    } else {
      a[u] = S[u] - S[P[P[u]]] - a[P[u]];
    }
    if (a[u] < 0) {
      debug {
        writeln("negative value needed");
      }
      return -1;
    }
  }
  debug {
    writefln("a = %s", a);
  }
  return a.sum;
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      P = new int[N];
      S = new long[N];
      foreach (u; 1 .. N) {
        P[u] = readInt() - 1;
      }
      foreach (u; 0 .. N) {
        S[u] = readInt();
      }
      const ans = solve();
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:  Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.  Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≤ i ≤ n).  Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.

The first line contains integers n, m (1 ≤ n, m ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≤ ti ≤ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≤ vi ≤ n, 1 ≤ xi ≤ 109). If ti = 2, then it is followed by integer yi (1 ≤ yi ≤ 104). And if ti = 3, then it is followed by integer qi (1 ≤ qi ≤ n).

For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.

import std.stdio;

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

    long[100_001] arr;
    long runtot = 0;
    int n, m;
    readf(" %d %d\n", &n, &m);
    foreach (i; 1 .. n + 1) {
        readf(" %d", &arr[i]);
    }
    foreach (i; 0 .. m) {
        int q, a, b; readf(" %d", &q);
        switch (q) {
            case 1:
                readf(" %d %d\n", &a, &b);
                arr[a] = b - runtot;
                break;
            case 2:
                readf(" %d\n", &a);
                runtot += a;
                break;
            case 3:
                readf(" %d\n", &a);
                writeln(arr[a] + runtot);
                break;
            default:
                assert(0);
        }
    }

    return 0;
}

import std.stdio;

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

    long[100_001] arr;
    long runtot = 0;
    int n, m;
    readf(" %s %s\n", &n, &m);
    foreach (i; 1 .. n + 1) {
        readf(" %s", &arr[i]);
    }
    foreach (i; 0 .. m) {
        int q, a, b; readf(" %s", &q);
        switch (q) {
            case 1:
                readf(" %s %s\n", &a, &b);
                arr[a] = b - runtot;
                break;
            case 2:
                readf(" %s\n", &a);
                runtot += a;
                break;
            case 3:
                readf(" %s\n", &a);
                writeln(arr[a] + runtot);
                break;
            default:
                assert(0);
        }
    }

    return 0;
}