Thanos sort is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort?*Infinity Gauntlet required.

The first line of input contains a single number $$$n$$$ ($$$1 \le n \le 16$$$) — the size of the array. $$$n$$$ is guaranteed to be a power of 2. The second line of input contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \le a_i \le 100$$$) — the elements of the array.

Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order.

NoteIn the first example the array is already sorted, so no finger snaps are required.In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array.In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction.


Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his string — each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2·ai ≤ |s|.You face the following task: determine what Pasha's string will look like after m days.

The first line of the input contains Pasha's string s of length from 2 to 2·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≤ m ≤ 105) —  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≤ ai; 2·ai ≤ |s|) — the position from which Pasha started transforming the string on the i-th day.

In the first line of the output print what Pasha's string s will look like after m days.


You are given a sequence $$$b_1, b_2, \ldots, b_n$$$. Find the lexicographically minimal permutation $$$a_1, a_2, \ldots, a_{2n}$$$ such that $$$b_i = \min(a_{2i-1}, a_{2i})$$$, or determine that it is impossible.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). The first line of each test case consists of one integer $$$n$$$ — the number of elements in the sequence $$$b$$$ ($$$1 \le n \le 100$$$). The second line of each test case consists of $$$n$$$ different integers $$$b_1, \ldots, b_n$$$ — elements of the sequence $$$b$$$ ($$$1 \le b_i \le 2n$$$). It is guaranteed that the sum of $$$n$$$ by all test cases doesn't exceed $$$100$$$.

For each test case, if there is no appropriate permutation, print one number $$$-1$$$. Otherwise, print $$$2n$$$ integers $$$a_1, \ldots, a_{2n}$$$ — required lexicographically minimal permutation of numbers from $$$1$$$ to $$$2n$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

while(<>){
	$debug and print '-' x 15;

	@_ = split ' ', <>;

	$debug and print "[@_]";

	my %exists = map { $_ => 1 } @_;
	my %not_exists = map { $_ => 1 } grep { not $exists{ $_ } } 1 .. @_ * 2;

	my @not_exists = sort { $a <=> $b } keys %not_exists;

	$debug and print "not_exists:[@not_exists]";

	for my $i ( @not_exists ){
		for my $j ( @_ ){
			next if $j =~ /_/;

			if( $j < $i ){
				$j .= "_" . $i;
				last;
				}
			}
		}

	$debug and print join ' ', @_;

	if( grep !/_/, @_ ){
		print -1;
		}
	else{
		print +( join '_', @_ ) =~ y/_/ /r;
		}
	}


Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?

First line of input contains an integer n (2 ≤ n ≤ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109) — the bids of players.

Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.

NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.


Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.

The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers.

Print the number of operations needed to destroy all towers.

NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.    After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.


Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point $$$T$$$, which coordinates to be found out.Bob travelled around the world and collected clues of the treasure location at $$$n$$$ obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?As everyone knows, the world is a two-dimensional plane. The $$$i$$$-th obelisk is at integer coordinates $$$(x_i, y_i)$$$. The $$$j$$$-th clue consists of $$$2$$$ integers $$$(a_j, b_j)$$$ and belongs to the obelisk $$$p_j$$$, where $$$p$$$ is some (unknown) permutation on $$$n$$$ elements. It means that the treasure is located at $$$T=(x_{p_j} + a_j, y_{p_j} + b_j)$$$. This point $$$T$$$ is the same for all clues.In other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.Your task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.Note that you don't need to find the permutation. Permutations are used only in order to explain the problem.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the number of obelisks, that is also equal to the number of clues. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^6 \leq x_i, y_i \leq 10^6$$$) — the coordinates of the $$$i$$$-th obelisk. All coordinates are distinct, that is $$$x_i \neq x_j$$$ or $$$y_i \neq y_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \neq j$$$.  Each of the next $$$n$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$ ($$$-2 \cdot 10^6 \leq a_i, b_i \leq 2 \cdot 10^6$$$) — the direction of the $$$i$$$-th clue. All coordinates are distinct, that is $$$a_i \neq a_j$$$ or $$$b_i \neq b_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \neq j$$$.  It is guaranteed that there exists a permutation $$$p$$$, such that for all $$$i,j$$$ it holds $$$\left(x_{p_i} + a_i, y_{p_i} + b_i\right) = \left(x_{p_j} + a_j, y_{p_j} + b_j\right)$$$.

Output a single line containing two integers $$$T_x, T_y$$$ — the coordinates of the treasure. If there are multiple answers, you may print any of them.

NoteAs $$$n = 2$$$, we can consider all permutations on two elements. If $$$p = [1, 2]$$$, then the obelisk $$$(2, 5)$$$ holds the clue $$$(7, -2)$$$, which means that the treasure is hidden at $$$(9, 3)$$$. The second obelisk $$$(-6, 4)$$$ would give the clue $$$(-1,-3)$$$ and the treasure at $$$(-7, 1)$$$. However, both obelisks must give the same location, hence this is clearly not the correct permutation.If the hidden permutation is $$$[2, 1]$$$, then the first clue belongs to the second obelisk and the second clue belongs to the first obelisk. Hence $$$(-6, 4) + (7, -2) = (2,5) + (-1,-3) = (1, 2)$$$, so $$$T = (1,2)$$$ is the location of the treasure.  In the second sample, the hidden permutation is $$$[2, 3, 4, 1]$$$.


Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all d days.Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.

The first line of input contains three space-separated integers n, k, d (1 ≤ n, d ≤ 1000; 1 ≤ k ≤ 109).

If there is no valid arrangement just print -1. Otherwise print d lines, in each of them print n integers. The j-th integer of the i-th line shows which bus the j-th student has to take on the i-th day. You can assume that the buses are numbered from 1 to k.

NoteNote that two students become close friends only if they share a bus each day. But the bus they share can differ from day to day.


Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $$$26$$$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $$$s$$$ appeared on the screen. When Polycarp presses a button with character $$$c$$$, one of the following events happened:  if the button was working correctly, a character $$$c$$$ appeared at the end of the string Polycarp was typing;  if the button was malfunctioning, two characters $$$c$$$ appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $$$\rightarrow$$$ abb $$$\rightarrow$$$ abba $$$\rightarrow$$$ abbac $$$\rightarrow$$$ abbaca $$$\rightarrow$$$ abbacabb $$$\rightarrow$$$ abbacabba.You are given a string $$$s$$$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then the test cases follow. Each test case is represented by one line containing a string $$$s$$$ consisting of no less than $$$1$$$ and no more than $$$500$$$ lowercase Latin letters.

For each test case, print one line containing a string $$$res$$$. The string $$$res$$$ should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, $$$res$$$ should be empty.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;

	s/(.)\1//g;

	$_ = join '', sort split '';

	s/(.)\1+/$1/g;

	print;
	}


You have a string $$$s$$$ of length $$$n$$$ consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the last one, nothing happens). If you choose a character <, the character that comes right before it is deleted (if the character you chose was the first one, nothing happens).For example, if we choose character > in string > > < >, the string will become to > > >. And if we choose character < in string > <, the string will become to <.The string is good if there is a sequence of operations such that after performing it only one character will remain in the string. For example, the strings >, > > are good. Before applying the operations, you may remove any number of characters from the given string (possibly none, possibly up to $$$n - 1$$$, but not the whole string). You need to calculate the minimum number of characters to be deleted from string $$$s$$$ so that it becomes good.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of test cases. Each test case is represented by two lines. The first line of $$$i$$$-th test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) – the length of string $$$s$$$. The second line of $$$i$$$-th test case contains string $$$s$$$, consisting of only characters > and <.

For each test case print one line. For $$$i$$$-th test case print the minimum number of characters to be deleted from string $$$s$$$ so that it becomes good.

NoteIn the first test case we can delete any character in string <>.In the second test case we don't need to delete any characters. The string > < < is good, because we can perform the following sequence of operations: > < < $$$\rightarrow$$$ < < $$$\rightarrow$$$ <.


A sequence of square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" — are regular, at the same time "][", "[[]" and "[[]]][" — are irregular. Draw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height — use symbols '+', '-' and '|'. For example, the sequence "[[][]][]" should be represented as: +-        -++- -+    |+- -++- -+||   |||   ||   |||   ||+- -++- -+||   |+-        -++- -+Each bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above.Brackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height. The enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image.Study carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique.

The first line contains an even integer n (2 ≤ n ≤ 100) — the length of the sequence of brackets. The second line contains the sequence of brackets — these are n symbols "[" and "]". It is guaranteed that the given sequence of brackets is regular.

Print the drawn bracket sequence in the format which is given in the condition. Don't print extra (unnecessary) spaces.

use strict;
use warnings;

my $n = 0 + <>;
my $seq = <>;

my ($depth, $max_depth) = (0, 0);
for (my $i = 0; $i < $n; $i++) {
	if (substr($seq, $i, 1) eq '[') {
		$depth++;

		if ($depth > $max_depth) {
			$max_depth = $depth;
		}
	} else {
		$depth--;
	}
}

my $top_level_lines_cnt = $max_depth*2 - 1;

my @image = map { '' } (1 .. $max_depth);
for (my $i = 0; $i < $n; $i++) {
	if (substr($seq, $i, 1) eq '[') {
		my $new_level = $i > 0 && substr($seq, $i-1, 1) eq '[';
		print_main_bracket_part($depth++, $new_level);
	} else {
		my $prev_was_open = substr($seq, $i-1, 1) eq '[';
		my $end_level = $i < $n-1 && substr($seq, $i+1, 1) eq ']';
		$depth--;

		# spaces
		if ($prev_was_open) {
			print_additional_bracket_part($depth);

			for (my $j = 0; $j < $top_level_lines_cnt+2; $j++) {
				$image[$j] .= ' ';
			}

			print_additional_bracket_part($depth);
		}

		print_main_bracket_part($depth, $end_level);
	}
}

foreach my $line (@image) {
	print "$line\n";
}

sub print_main_bracket_part
{
	my ($depth, $need_minus) = @_;

	my $lines_cnt = ($max_depth - $depth)*2 - 1;
	my $space_cnt = $depth != 0 ? (($top_level_lines_cnt + 2) - ($lines_cnt + 2 + 2)) / 2 : 0;
	my $j = 0;

	# spaces
	for (my $k = 0; $k < $space_cnt; $k++) { $image[$j++] .= ' '; }

	# -
	if ($depth != 0) {
		$image[$j++] .= $need_minus ? '-' : ' ';
	}

	# +
	$image[$j++] .= '+';

	# |
	for (my $k = 0; $k < $lines_cnt; $k++) { $image[$j++] .= '|'; }

	# +
	$image[$j++] .= '+';

	# -
	if ($depth != 0) {
		$image[$j++] .= $need_minus ? '-' : ' ';
	}

	# spaces
	for (my $k = 0; $k < $space_cnt; $k++) { $image[$j++] .= ' '; }
}

sub print_additional_bracket_part
{
	my $lines_cnt = ($max_depth - $depth)*2 - 1;
	my $space_cnt = $depth != 0 ? (($top_level_lines_cnt + 2) - ($lines_cnt + 2 + 2)) / 2 : 0;
	my $j = 0;

	# spaces
	for (my $k = 0; $k < $space_cnt; $k++) { $image[$j++] .= ' '; }

	# -
	if ($depth != 0) {
		$image[$j++] .= ' ';
	}

	# +
	$image[$j++] .= '-';

	# |
	for (my $k = 0; $k < $lines_cnt; $k++) { $image[$j++] .= ' '; }

	# +
	$image[$j++] .= '-';

	# -
	if ($depth != 0) {
		$image[$j++] .= ' ';
	}

	# spaces
	for (my $k = 0; $k < $space_cnt; $k++) { $image[$j++] .= ' '; }
}


One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of lines in the description. Then follow n lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.

Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.

#!/usr/bin/perl -w
use strict;

my %goals = ();
for (1..<>) {
	$goals{<>}++;
}
my ($winner) = sort {$goals{$b}<=>$goals{$a}} keys %goals;
print $winner;


Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and x - p vertices where 1 ≤ p < x is chosen by the player. The player who cannot make a move loses the game (and his life!).Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of tests Peter is about to make. The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), i-th of them stands for the number of vertices in the cycle added before the i-th test.

Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.

NoteIn the first sample test:In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses.In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins.In the second sample test:Having cycles of size 1 is like not having them (because no one can make a move on them). In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3.  If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses.  If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins. So, either way first player loses.


New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.

The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.

If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".

NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.

my ($n, $t) = split " ", <>;
my @arr = split " ", <>;
unshift @arr, 0;
my $pos = 1;
$pos += $arr[$pos] while ($pos < $t);
print ($pos == $t ? "YES\n" : "NO\n");

#!/usr/bin/perl
# your code goes here
use v5.10;

our $flag = 0;
our ($n, $t) = split / /, <>;
our @adj = ([()]) x $n+1;
our @visit = (0) x $n+1;

sub dfs {
	my $u = shift;

	# say $u;
	$visit[$u] = 1;
	$u==$t and return 1;
	foreach my $v (@{$adj[$u]}) {
		$visit[$v]==0 and dfs($v) and return 1;
	}
	return 0;
}

my $i = 1;
foreach (split / /, <>) {
	push @{$adj[$i]}, $_+$i;
	++$i;
}

dfs(1) and say "YES" or say "NO";

#!/usr/bin/perl
# your code goes here
use v5.10;

our $flag = 0;
our ($n, $t) = split / /, <>;
our @adj = ([]) x $n+1;
our @visit = (0) x $n+1;

sub dfs {
	my $u = shift;

	# say $u;
	$visit[$u] = 1;
	$u==$t and return 1;
	foreach my $v (@{$adj[$u]}) {
		$visit[$v]==0 and dfs($v) and return 1;
	}
	return 0;
}

my $i = 1;
foreach (split / /, <>) {
	push @{$adj[$i]}, $_+$i;
	++$i;
}

dfs(1) and say "YES" or say "NO";

use Data::Dumper;
my ($n, $t) = split ' ', <>;
my @indices = split ' ', <>;
my @a = ();
push @a, 0 for (1 .. $n);

$a[0] = 1;

for my $i (0 .. $n - 2) {
    my $j = shift @indices;
    $a[$i + $j] = 1 if $a[$i];
}

print $a[$t - 1] == 1 ? "YES\n" : "NO\n";

my ($n, $t) = split ' ', scalar <>;
my @a = split ' ', scalar <>;
my @used = (0) x scalar @a;
my $i;
for($i=0; $i<$t-1; $i += $a[$i]){}
print (($i == $t-1) ? "YES\n" : "NO\n");

my ($n, $t) = split " ", <>;
my @arr = split " ", <>;
my $pos = 1;
$pos += $arr[$pos] while ($pos < $t);
print ($pos == $t ? "YES\n" : "NO\n");

my ($n, $t) = split " ", <>;
my @arr = split " ", <>;
my @mark = (0) x $n+1;
$mark[1] = 1;
for (my $pos = 1; $pos != $t; $pos++) {
    $pos += int $arr[$pos];
    if ($pos >= $n-1 || $mark[$pos]) {
        print "NO\n";
        exit;
    }
    $mark[$pos] = 1;
}
print "YES\n";

use Data::Dumper;
my ($n, $t) = split ' ', <>;
my @indices = split ' ', <>;
my @a = ();
push @a, 0 for (1 .. $n);

for my $i (0 .. $n - 2) {
    my $j = shift @indices;
    $a[$i + $j] = 1 if $a[$i];
}

print $a[$t - 1] == 1 ? "YES\n" : "NO\n";


Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.

The first line contains an integer n (1 ≤ n ≤ 5·105) — the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≤ xi ≤ 1023.

Output an integer k (0 ≤ k ≤ 5) — the length of your program. Next k lines must contain commands in the same format as in the input.

NoteYou can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation.Second sample:Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Initially all elements of $$$a$$$ are either $$$0$$$ or $$$1$$$. You need to process $$$q$$$ queries of two kinds:  1 x : Assign to $$$a_x$$$ the value $$$1 - a_x$$$.  2 k : Print the $$$k$$$-th largest value of the array. As a reminder, $$$k$$$-th largest value of the array $$$b$$$ is defined as following: Sort the array in the non-increasing order, return $$$k$$$-th element from it. For example, the second largest element in array $$$[0, 1, 0, 1]$$$ is $$$1$$$, as after sorting in non-increasing order it becomes $$$[1, 1, 0, 0]$$$, and the second element in this array is equal to $$$1$$$.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the length of the given array and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, a_3, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$) — elements of the initial array. Each of the following $$$q$$$ lines contains two integers. The first integer is $$$t$$$ ($$$1 \le t \le 2$$$) — the type of query.   If $$$t = 1$$$ the second integer is $$$x$$$ ($$$1 \le x \le n$$$) — the position of the modified number. You have to assign to $$$a_x$$$ the value $$$1 - a_x$$$. If $$$t = 2$$$ the second integer is $$$k$$$ ($$$1 \le k \le n$$$) — you need to print the $$$k$$$-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying $$$t = 2$$$).

For each query of the second type, print a single integer — the answer to the query.

NoteInitially $$$a = [1, 1, 0, 1, 0]$$$.The first operation is printing the third largest value, which is $$$1$$$.The second operation is assigning $$$a_2$$$ the value $$$0$$$, $$$a$$$ becomes $$$[1, 0, 0, 1, 0]$$$.The third operation is printing the third largest value, it is $$$0$$$.The fourth operation is printing the first largest value, it is $$$1$$$.The last operation is printing the fifth largest value, it is $$$0$$$.


One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·m from left to right, then the j-th flat of the i-th floor has windows 2·j - 1 and 2·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of floors in the house and the number of flats on each floor respectively. Next n lines describe the floors from top to bottom and contain 2·m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.

Print a single integer — the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.

NoteIn the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off.


There are $$$n + 1$$$ cities, numbered from $$$0$$$ to $$$n$$$. $$$n$$$ roads connect these cities, the $$$i$$$-th road connects cities $$$i - 1$$$ and $$$i$$$ ($$$i \in [1, n]$$$).Each road has a direction. The directions are given by a string of $$$n$$$ characters such that each character is either L or R. If the $$$i$$$-th character is L, it means that the $$$i$$$-th road initially goes from the city $$$i$$$ to the city $$$i - 1$$$; otherwise it goes from the city $$$i - 1$$$ to the city $$$i$$$.A traveler would like to visit as many cities of this country as possible. Initially, they will choose some city to start their journey from. Each day, the traveler must go from the city where they currently are to a neighboring city using one of the roads, and they can go along a road only if it is directed in the same direction they are going; i. e., if a road is directed from city $$$i$$$ to the city $$$i + 1$$$, it is possible to travel from $$$i$$$ to $$$i + 1$$$, but not from $$$i + 1$$$ to $$$i$$$. After the traveler moves to a neighboring city, all roads change their directions to the opposite ones. If the traveler cannot go from their current city to a neighboring city, their journey ends; it is also possible to end the journey whenever the traveler wants to.The goal of the traveler is to visit as many different cities as possible (they can visit a city multiple times, but only the first visit is counted). For each city $$$i$$$, calculate the maximum number of different cities the traveler can visit during exactly one journey if they start in the city $$$i$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$). The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters, each character is either L or R. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print $$$n + 1$$$ integers. The $$$i$$$-th integer should be equal to the maximum number of different cities the traveler can visit during one journey if this journey starts in the $$$i$$$-th city.

#!/usr/bin/perl

use warnings;

$\ = $/;

<>;

while(<>){
	$_ = <>, chomp;

	@A = ( 1 ) x ( 1 + length );

	&add_forward_cities;
	&add_forward_cities;

	print "@A";
	}

sub add_forward_cities {
	$_ = reverse;
	y/RL/LR/;
	@A = reverse @A;

	$length = 0;

	/
		(?=R)
		(?{ $length > 0 and $length -= 2 })
		(?(?{ $length <= 0 })
			(?: (?:RL)*+ ){0,10}+
			R?+
			(?{ $length = length $& })
			)
		(?{
			$A[ $-[ 0 ] ] += $length
			})
		(*F)
		/x;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

while(<>){
	$debug and print '-' x 15;
	$_ = <>, chomp;

	$debug and print "\$_:[$_]";

	my @A = ( 1 ) x ( 1 + length );

	fill_array_with_counts_of_forward_nodes(
		$_, \@A
		);

	$debug and print "\@A:[@A]";

	$_ = reverse;
	$_ =~ y/RL/LR/;
	@A = reverse @A;

	fill_array_with_counts_of_forward_nodes(
		$_, \@A
		);

	@A = reverse @A;

	$debug and print "\@A:[@A]";

	print "@A";
	}

sub fill_array_with_counts_of_forward_nodes {
	my( $line, $ref_array ) = @_;

	my $len = 0;

	$line =~ /
		(?{
			$debug and print ">[$-[0]][$`][$&][$'][@{ $ref_array }][$len]";
			})
		(?=R)
		(?{ $len > 0 and $len -= 2; })
		(?(?{ $len <= 0; })
			(?: (?:RL)*+ ){0,10}+
			R?+
			(?{ $len = length $&; })
			)
		(?{
			$debug and print "[$-[ 0 ]], len:[$len]";
			${ $ref_array }[ $-[ 0 ] ] += $len;
			})
		(*FAIL)
		/x;
	}


Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition:  These k dots are different: if i ≠ j then di is different from dj.  k is at least 4.  All dots belong to the same color.  For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.

The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.

Output "Yes" if there exists a cycle, and "No" otherwise.

7 6
AAAAAB
ABBBAB
ABAAAB
ABABBB
ABAAAB
ABBBAB
AAAAAB

NoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).

use strict;
#use warnings;
<>;
my @matrix;
push @matrix, [];
for(<>)
{
	chomp;
	push @matrix, [0,split(//,$_ ),0];
}
push @matrix, [];

for my $x (1..$#matrix-1)
{
	for my $y (1..$#{$matrix[$x]}-1)
	{
		if($matrix[$x][$y])
		{
			my $toDel = [[]];
			func($x,$y,0,$toDel);
			Del($toDel);
		}
	}
}
print "No";
sub Del
{
	my $toDel = shift;
	for my $x (0..$#matrix)
	{
		for my $y (0..$#{$matrix[$x]})
		{
			$matrix[$x][$y] = 0 if($toDel->[$x][$y]);

		}
	}
}
sub func
{
	my ($x,$y, $dir,$path) = @_;

	if(!defined $path->[$x][$y])
	{
		my $color = $matrix[$x][$y];
		$path->[$x][$y] = 1;
		checkWin($x,$y,$dir,$path);
		if($dir ne 'r' and $color eq $matrix[$x-1][$y])
		{
			func($x-1, $y, 'l', $path);
		}
		if($dir ne 'l' and $color eq $matrix[$x+1][$y])
		{
			func($x+1, $y, 'r', $path);
		}
		if($dir ne 'd' and $color eq $matrix[$x][$y+1])
		{
			func($x, $y+1, 'u', $path);
		}
		if($dir ne 'u' and $color eq $matrix[$x][$y-1])
		{
			func($x, $y-1, 'd', $path);
		}
	}
}
sub checkWin
{
	my ($x,$y, $dir,$path) = @_;
	if($matrix[$x][$y] eq $matrix[$x+1][$y] and $path->[$x+1][$y] and $dir ne 'l' ){ print "Yes" and exit 0;}
	if($matrix[$x][$y] eq $matrix[$x-1][$y] and $path->[$x-1][$y] and  $dir ne 'r' ){ print "Yes" and exit 0;}
	if($matrix[$x][$y] eq $matrix[$x][$y+1] and $path->[$x][$y+1] and $dir ne 'd' ){ print "Yes" and exit 0;}
	if($matrix[$x][$y] eq $matrix[$x][$y-1] and $path->[$x][$y-1] and $dir ne 'u' ){ print "Yes" and exit 0;}
	return 0;
}


Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≤ i ≤ n). Help Polycarpus determine the length of the city phone code.

The first line of the input contains an integer n (2 ≤ n ≤ 3·104) — the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn — the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different.

Print the number of digits in the city phone code.

NoteA prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209".In the first sample the city phone code is string "00".In the second sample the city phone code is an empty string.In the third sample the city phone code is string "770123456789".

#!/usr/bin/perl
chomp($n = <STDIN>);
$nums;
for ($i = 0; $i < $n; $i++)
{
    chomp($num = <STDIN>);
    push(@nums, $num);
    #print $num . "\n";
}

$numlen = length $nums[0];
#$res = 0;
for ($i = $numlen - 1; $i >= 0; $i--)
{
    #print $i . "\n";
    #print $nums[$i] . "\n";
    $head = substr($nums[0], 0, $i + 1);
    #print $head . "\n";
    $isok = 1;
    for ($j = 1; $j < $n; $j++)
    {
        #print "tmp: " . substr($nums[j], 0, $i + 1) . "\n";
        if (substr($nums[$j], 0, $i + 1) ne $head)
        {
            $isok = 0;
            last;
        }
    }

    if ($isok)
    {
        print $i + 1;
        exit;
    }
    elsif (!$isok && $i == 0)
    {
        print 0;
        exit;
    }
}

my $n = <STDIN>;
my @a;
for (my $i = 0; $i < $n; $i++) {
    my $q = <STDIN>;
    push(@a, $q);
}

my $l = length $a[0];
my $ans = 0;

for (my $i = $l; $i > 0; $i--) {
    my $substr = substr $a[0], 0, $i;
    my $flag = 1;
    for my $t (@a) {
        if (!($t =~ /^$substr/)) {
            $flag = 0;
            last;
        }
    }
    if ($flag) {
        $ans = $i;
        last;
    }
}

print "$ans\n";

#!/usr/bin/perl
use strict;
use warnings;

######z1

my $count = <STDIN>;
my $pref = <STDIN>;
my $len = length($pref);
foreach (my $i=1;$i<$count;$i++) {
    my $num = <STDIN>;
    while ($pref ne substr($num, 0, $len)) {
        $len--;
        $pref = substr($pref, 0, $len);
    }
}
print $len."\n";
1;

#!/usr/bin/perl
use strict;
use warnings;

my @phones;
my $n;
sub isvalid{
    my $start = shift;
    my $len = shift;
    my $cmp = substr $phones[0], $start, $len-$start;
    for my $i(1..$n-1){
        return 0 if $cmp ne substr $phones[$i], $start, $len-$start;
    }
    return 1;
}
#==================================

$n = <>;
for(1..$n){
    chomp (my $val = <>);
    push @phones, $val;
}

my ($low, $high) = (0,40000);
while($low < $high){
    my $mid = int(($low + $high + 1) / 2);
    if(isvalid($low, $mid)){$low = $mid;}
    else {$high = $mid-1;}
}
print $low;

#!/usr/bin/perl
use strict;
use warnings;

my @phones;
my $n;
$n = <>;
for(1..$n){
    my @val = (<> =~ /\w/g);
    push @phones, \@val;
}
for my $j(0..40000){
    my $char = $phones[0][$j];
    for my $i(0..$n-1){
        if($char ne $phones[$i][$j]){
            print $j;
            exit 0;
        }
    }
}

my @input;
while(<>) {chomp; push(@input, $_);}
my @list = map{ {}; } (1..20);
shift(@input);
my ($l, $c, $i);
my $regexp = qr//o;
for $l (@input) {
	$i = 0;
  foreach $c (split($regexp, $l)) {
    $list[$i++]{$c} = 1;
  }
}
$i = 0;
$i++ while( scalar(keys(%{$list[$i]}) == 1 ) );
print $i;

@_=<>;
shift @_;
chomp @_;
$a = shift @_;
for $j(1..length $_[0]){
    $i=0;
    for (@_){
        $a eq $_ or $i=1;
        chop;
        }
    chop $a;
    $i or last
    }
print 1 - $i + length $a

#!/usr/bin/perl
chomp($n = <STDIN>);
$nums;
for ($i = 0; $i < $n; $i++)
{
    chomp($num = <STDIN>);
    push(@nums, $num);
    #print $num . "\n";
}

$numlen = length $nums[0];
#$res = 0;
for ($i = $numlen - 1; $i >= 0; $i--)
{
    #print $i . "\n";
    #print $nums[$i] . "\n";
    $head = substr($nums[0], 0, $i + 1);
    #print $head . "\n";
    #$isok = 1;
    for ($j = 1; $j < $n; $j++)
    {
        #print "tmp: " . substr($nums[j], 0, $i + 1) . "\n";
        if (substr($nums[$j], 0, $i + 1) ne $head)
        {
            last;
        }

        if ($j == $n - 1)
        {
            print $i + 1;
            exit;
        }
    }
}


Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.

The only line contains odd integer n (1 ≤ n ≤ 49).

Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.


Recently, the students of School 179 have developed a unique algorithm, which takes in a binary string $$$s$$$ as input. However, they soon found out that if some substring $$$t$$$ of $$$s$$$ is a palindrome of length greater than 1, the algorithm will work incorrectly. Can the students somehow reorder the characters of $$$s$$$ so that the algorithm will work correctly on the string?A binary string is a string where each character is either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.A palindrome is a string that reads the same backwards as forwards.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the string $$$s$$$. The second line of each test case contains the string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.

For each test case, print YES (case-insensitive) if it is possible to reorder the characters of $$$s$$$ so that there are no substrings that are a palindrome of length greater than 1, or NO (case-insensitive) otherwise.

NoteIn the first three test cases, the given strings do not contain palindromes of length greater than 1, so the answers are YES.In the last test case, it is impossible to reorder the characters so that the string does not contain palindromes of length greater than 1, so the answer is NO.

for (1..<>) {
      chomp(my $n = <>);
      chomp(my $in = <>);
      my @a = split //, $in;
      scalar(@a) == 1 and print "YES\n" and next;
      scalar(@a) > 2 and print "NO\n" and next;
      my $a = shift @a;
      my $b = shift @a;
      $a != $b and print "YES\n";
      $a == $b and print "NO\n";
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	$_ = <>, chomp;

	print m/^(1|0|10|01)$/ ? 'YES' : 'NO';
	}


You have a permutation: an array $$$a = [a_1, a_2, \ldots, a_n]$$$ of distinct integers from $$$1$$$ to $$$n$$$. The length of the permutation $$$n$$$ is odd.Consider the following algorithm of sorting the permutation in increasing order.A helper procedure of the algorithm, $$$f(i)$$$, takes a single argument $$$i$$$ ($$$1 \le i \le n-1$$$) and does the following. If $$$a_i > a_{i+1}$$$, the values of $$$a_i$$$ and $$$a_{i+1}$$$ are exchanged. Otherwise, the permutation doesn't change.The algorithm consists of iterations, numbered with consecutive integers starting with $$$1$$$. On the $$$i$$$-th iteration, the algorithm does the following:   if $$$i$$$ is odd, call $$$f(1), f(3), \ldots, f(n - 2)$$$;  if $$$i$$$ is even, call $$$f(2), f(4), \ldots, f(n - 1)$$$. It can be proven that after a finite number of iterations the permutation will be sorted in increasing order.After how many iterations will this happen for the first time?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 999$$$; $$$n$$$ is odd) — the length of the permutation. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the permutation itself.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$999$$$.

For each test case print the number of iterations after which the permutation will become sorted in increasing order for the first time. If the given permutation is already sorted, print $$$0$$$.

NoteIn the first test case, the permutation will be changing as follows:   after the $$$1$$$-st iteration: $$$[2, 3, 1]$$$;  after the $$$2$$$-nd iteration: $$$[2, 1, 3]$$$;  after the $$$3$$$-rd iteration: $$$[1, 2, 3]$$$. In the second test case, the permutation will be changing as follows:   after the $$$1$$$-st iteration: $$$[4, 5, 1, 7, 2, 3, 6]$$$;  after the $$$2$$$-nd iteration: $$$[4, 1, 5, 2, 7, 3, 6]$$$;  after the $$$3$$$-rd iteration: $$$[1, 4, 2, 5, 3, 7, 6]$$$;  after the $$$4$$$-th iteration: $$$[1, 2, 4, 3, 5, 6, 7]$$$;  after the $$$5$$$-th iteration: $$$[1, 2, 3, 4, 5, 6, 7]$$$. In the third test case, the permutation is already sorted and the answer is $$$0$$$.


There are $$$n$$$ piles of sand where the $$$i$$$-th pile has $$$a_i$$$ blocks of sand. The $$$i$$$-th pile is called too tall if $$$1 < i < n$$$ and $$$a_i > a_{i-1} + a_{i+1}$$$. That is, a pile is too tall if it has more sand than its two neighbours combined. (Note that piles on the ends of the array cannot be too tall.)You are given an integer $$$k$$$. An operation consists of picking $$$k$$$ consecutive piles of sand and adding one unit of sand to them all. Formally, pick $$$1 \leq l,r \leq n$$$ such that $$$r-l+1=k$$$. Then for all $$$l \leq i \leq r$$$, update $$$a_i \gets a_i+1$$$.What is the maximum number of piles that can simultaneously be too tall after some (possibly zero) operations?

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq k \leq n$$$) — the number of piles of sand and the size of the operation, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of the piles. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the maximum number of piles that are simultaneously too tall after some (possibly zero) operations.

NoteIn the first test case, we can perform the following three operations:   Add one unit of sand to piles $$$1$$$ and $$$2$$$: $$$[\color{red}{3}, \color{red}{10}, 2, 4, 1]$$$.  Add one unit of sand to piles $$$4$$$ and $$$5$$$: $$$[3, 10, 2, \color{red}{5}, \color{red}{2}]$$$.  Add one unit of sand to piles $$$3$$$ and $$$4$$$: $$$[3, 10, \color{red}{3}, \color{red}{6}, 2]$$$.  Now piles $$$2$$$ and $$$4$$$ are too tall, so in this case the answer is $$$2$$$. It can be shown that it is impossible to make more than $$$2$$$ piles too tall.In the second test case, any operation will increase all piles by $$$1$$$ unit, so the number of too tall piles will always be $$$0$$$.In the third test case, we can increase any pile by $$$1$$$ unit of sand. It can be shown that the maximum number of too tall piles is $$$1$$$.


After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique.For a given sentence, the cipher is processed as:   Convert all letters of the sentence to lowercase.  Reverse each of the words of the sentence individually.  Remove all the spaces in the sentence. For example, when this cipher is applied to the sentenceKira is childish and he hates losingthe resulting string isariksihsidlihcdnaehsetahgnisolNow Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times.

The first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t. The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000.

Print one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those.

30
ariksihsidlihcdnaehsetahgnisol
10
Kira
hates
is
he
losing
death
childish
L
and
Note

12
iherehtolleh
5
HI
Ho
there
HeLLo
hello

Kira is childish and he hates losing
HI there HeLLo

NoteIn sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them.

chomp( (undef, $_, undef, @words) = <> );

%restore_case = map { lc, $_ } @words;

$list = join '|', map { scalar reverse lc } @words;

m/^ (?: ($list | $ | (?{ pop @submatches }) (?!) ) (?{ push @submatches, $^N }) )+ $/x;

pop @submatches;

print join ' ', map { $restore_case{ scalar reverse } } @submatches

# Eily+

chomp( (undef, $_, undef, @words) = <> );

%restore_case = map { lc reverse, $_ } @words;

$list = join '|', keys %restore_case;

m/^ (?: ($list | $ | (?{ pop @submatches }) (?!) ) (?{ push @submatches, $^N }) )+ $ (?{ pop @submatches })/x;

print join ' ', map { $restore_case{ $_ } } @submatches

$\ = $/;

while(<>){
	$_ = <>, chomp;
	@w = @ww = @ans = @ANS = ();

	for (1 .. <>){
		push @w, scalar <>;
		}
	chomp @w;

	%h = map { (scalar reverse lc) => 1 } @w;
	%H = map { lc, $_ } @w;

	$re = join '|', keys %h;

	/^(?:($re)(?{push @ww, $^N}))+$/;

	for $st (@ww){
		s/^$st/ (push @ans, scalar reverse $&) , ''/e;
		}

	for (@ans){
		push @ANS, $H{ $_ };
		}

	print "@ANS";
	}

chomp( (undef, $_, undef, @words) = <> );

%restore_case = map { lc, $_ } @words;

$list = join '|', map { scalar reverse lc } sort { length $a <=> length $b } @words;

m/^ (?: ($list) (?{ unshift @sub_matches, $^N }) )+ $/x;

for $sub_match (@sub_matches){
	s/$sub_match$// and unshift @ans, $restore_case{ reverse $& }
	}

print "[$_]" if $_;
print "@ans"

chomp( (undef, $_, undef, @words) = <> );

%restore_case = map { lc, $_ } @words;

$list = join '|', map { scalar reverse lc } @words;

m/^ (?: ($list) (?{ unshift @sub_matches, $^N }) )+ $/x;

for $sub_match (@sub_matches){
	s/$sub_match$// and unshift @ans, $restore_case{ reverse $& }
	}

print "[$_]" if $_;
print "@ans"

chomp( (undef, $_, undef, @words) = <> );

%restore_case = map { lc, $_ } @words;

$list = join '|', map { scalar reverse lc } @words;

m/^ (?: ($list) (?{ push @sub_matches, $^N }) )+ $/x;

for $sub_match (reverse @sub_matches){
	s/$sub_match$// and unshift @ans, $restore_case{ reverse $& }
	}

print "@ans"

chomp( (undef, $_, undef, @words) = <> );

%restore_case = map { lc, $_ } @words;

$list = join '|', map { scalar reverse lc } @words;

m/^ (?: ($list) (?{ push @sub_matches, $^N }) )+ $/x;

for $sub_match (@sub_matches){
	s/^$sub_match// and push @ans, $restore_case{ reverse $& }
	}

print "@ans";


You are given a positive decimal number x.Your task is to convert it to the "simple exponential notation".Let x = a·10b, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.

The only line contains the positive decimal number x. The length of the line will not exceed 106. Note that you are given too large number, so you can't use standard built-in data types "float", "double" and other.

Print the only line — the "simple exponential notation" of the given number x.


A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.

The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai < bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.

If the required division into teams doesn't exist, print number -1. Otherwise, print  lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team.  If there are multiple answers, you are allowed to print any of them.

#!/usr/bin/perl

use strict;
use warnings;

chomp($_ = <>);
my ($n, $m) = split;
my @e = ();
push @e, [] for (1 .. $n);
for (1 .. $m) {
    chomp($_ = <>);
    my ($u, $v) = split;
    push @{$e[$u - 1]}, $v - 1;
    push @{$e[$v - 1]}, $u - 1;
}

my @one = ();
my @used = (0) x $n;
for my $i (0 .. $n - 1) {
    unless (@{$e[$i]}) {
        $used[$i] = 1;
        push @one, $i;
    }
}

my @res = ();
my $fail = 0;
for my $i (0 .. $n - 1) {
    next if $used[$i];

    my @cur = ($i);
    my @q = ($i);
    $used[$i] = 1;
    while (@q) {
        my $t = shift @q;
        for my $j (@{$e[$t]}) {
            if (!$used[$j]) {
                $used[$j] = 1;
                push @q, $j;
                push @cur, $j;
            }
        }
    }
    if (@cur > 3 || (@cur == 2 && !@one)) {
        $fail = 1;
        last;
    } elsif (@cur == 2) {
        push @cur, shift @one;
    }
    push @res, [@cur];
}
unless ($fail) {
    while (@one) {
        push @res, [@one[0, 1, 2]];
        @one = @one[3 .. $#one];
    }
}
if ($fail) {
    print "-1\n";
} else {
    for (@res) {
        map { ++$_ } @$_;
        print "@$_\n";
    }
}


Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.

The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.

The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.

NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.


An integer array $$$a_1, a_2, \ldots, a_n$$$ is being transformed into an array of lowercase English letters using the following prodecure:While there is at least one number in the array:   Choose any number $$$x$$$ from the array $$$a$$$, and any letter of the English alphabet $$$y$$$.  Replace all occurrences of number $$$x$$$ with the letter $$$y$$$. For example, if we initially had an array $$$a = [2, 3, 2, 4, 1]$$$, then we could transform it the following way:  Choose the number $$$2$$$ and the letter c. After that $$$a = [c, 3, c, 4, 1]$$$.  Choose the number $$$3$$$ and the letter a. After that $$$a = [c, a, c, 4, 1]$$$.  Choose the number $$$4$$$ and the letter t. After that $$$a = [c, a, c, t, 1]$$$.  Choose the number $$$1$$$ and the letter a. After that $$$a = [c, a, c, t, a]$$$. After the transformation all letters are united into a string, in our example we get the string "cacta".Having the array $$$a$$$ and the string $$$s$$$ determine if the string $$$s$$$ could be got from the array $$$a$$$ after the described transformation?

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^3$$$) — the number of test cases. Then the description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the array $$$a$$$ and the string $$$s$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 50$$$) — the elements of the array $$$a$$$. The third line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of lowercase English letters.

For each test case, output "YES", if we can get the string $$$s$$$ from the array $$$a$$$, and "NO" otherwise. You can output each letter in any case.

NoteThe first test case corresponds to the sample described in the statement.In the second test case we can choose the number $$$50$$$ and the letter a.In the third test case we can choose the number $$$11$$$ and the letter a, after that $$$a = [a, 22]$$$. Then we choose the number $$$22$$$ and the letter b and get $$$a = [a, b]$$$.In the fifth test case we can change all numbers one by one to the letter a.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	@_ = split ' ', <>;
	$_ = <>, chomp;

	my %h;
	my $f = 0;

	while( @_ ){
		my $i = pop @_;
		my $j = chop;

		if( exists $h{ $i } ){
			if( $h{ $i } ne $j ){
				$f = 1;
				last;
				}
			}
		else{
			$h{ $i } = $j;
			}
		}

	print $f ? 'NO' : 'YES';
	}


Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

$\ = $/;

<>;
$c = 0;
$max = 0;
while(<>){
	chomp;
	($n, $m) = split;
	$n eq '+' and ++ $h{$m} and ++ $c; # and $c > $max and $max = $c;
	$n eq '-' and do {
		$h{$m} // $max ++;
		defined $h{$m} and $c --;
		$h{$m} and delete $h{$m};
	};
	$c > $max and $max = $c;
#	print $_,' ',$max;
#	print qw(NO YES)[]
	}
print $max;


Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility).  Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world). Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2n possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.

The first line of input contains two integers n and m (1 ≤ n, m ≤ 104) — number of universes and number of groups respectively. The next m lines contain the information about the groups. i-th of them first contains an integer k (number of times someone joined i-th group, k > 0) followed by k integers vi, 1, vi, 2, ..., vi, k. If vi, j is negative, it means that Rick from universe number  - vi, j has joined this group and otherwise it means that Morty from universe number vi, j has joined it. Sum of k for all groups does not exceed 104.

In a single line print the answer to Summer's question. Print "YES" if she should cancel the event and "NO" otherwise.

NoteIn the first sample testcase, 1st group only contains the Rick from universe number 3, so in case he's a traitor, then all members of this group are traitors and so Summer should cancel the event.


You want to perform the combo on your opponent in one popular fighting game. The combo is the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $$$s$$$. I.e. if $$$s=$$$"abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend $$$m$$$ wrong tries to perform the combo and during the $$$i$$$-th try you will make a mistake right after $$$p_i$$$-th button ($$$1 \le p_i < n$$$) (i.e. you will press first $$$p_i$$$ buttons right and start performing the combo from the beginning). It is guaranteed that during the $$$m+1$$$-th try you press all buttons right and finally perform the combo.I.e. if $$$s=$$$"abca", $$$m=2$$$ and $$$p = [1, 3]$$$ then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$) — the length of $$$s$$$ and the number of tries correspondingly. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of each test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i < n$$$) — the number of characters pressed right during the $$$i$$$-th try. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ both does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$). It is guaranteed that the answer for each letter does not exceed $$$2 \cdot 10^9$$$.

For each test case, print the answer — $$$26$$$ integers: the number of times you press the button 'a', the number of times you press the button 'b', $$$\dots$$$, the number of times you press the button 'z'.

3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4

NoteThe first test case is described in the problem statement. Wrong tries are "a", "abc" and the final try is "abca". The number of times you press 'a' is $$$4$$$, 'b' is $$$2$$$ and 'c' is $$$2$$$.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is $$$9$$$, 'd' is $$$4$$$, 'e' is $$$5$$$, 'f' is $$$3$$$, 'o' is $$$9$$$, 'r' is $$$3$$$ and 's' is $$$1$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

while(<>){
	$debug and print '-' x 15;

	my( $n, $m ) = split;

	my $str = <>;
	chomp $str;

	my @p = split ' ', <>;

	push @p, $n;

	my @A = ( 0 ) x $n;

	for( @p ){
		$A[ $_ - 1 ] ++;
		}

	$debug and print "A:[@A]";

	my $add = 0;

	for my $i ( reverse 0 .. @A - 1 ){
		$A[ $i ] += $add;
		$add = $A[ $i ];
		}

	$debug and print "A:[@A]";

	my %h;

	while( @A ){
		$str =~ /./g;
		$h{ $& } += shift @A;
		}

	print join ' ', map { $h{ $_ } // 0 } 'a' .. 'z';
	}


Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that:  he pointed at the person with index (bi + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y);  if j ≥ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice;  the turn went to person number (bi + 1) mod n. The person who was pointed on the last turn did not make any actions.The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.You can assume that in any scenario, there is enough juice for everybody.

The first line contains a single integer n (4 ≤ n ≤ 2000) — the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns.

Print a single integer — the number of glasses of juice Vasya could have drunk if he had played optimally well.

NoteIn both samples Vasya has got two turns — 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different.

#!/usr/bin/perl
use strict;
use warnings;

my $n = <>;
chomp $n;

my $moves_s = <>;
chomp $moves_s;
my @moves = split(//, $moves_s);

my $res = 0;

for (my $i = 0; $i <= $#moves; $i += $n) {
  if ($i >= 4) {
    if ($moves[$i-3] eq $moves[$i-2]
      && $moves[$i-2] eq $moves[$i-1]) {
      $res++;
    }
  }
}

print "$res\n";


There is a binary string $$$a$$$ of length $$$n$$$. In one operation, you can select any prefix of $$$a$$$ with an equal number of $$$0$$$ and $$$1$$$ symbols. Then all symbols in the prefix are inverted: each $$$0$$$ becomes $$$1$$$ and each $$$1$$$ becomes $$$0$$$.For example, suppose $$$a=0111010000$$$.   In the first operation, we can select the prefix of length $$$8$$$ since it has four $$$0$$$'s and four $$$1$$$'s: $$$[01110100]00\to [10001011]00$$$.  In the second operation, we can select the prefix of length $$$2$$$ since it has one $$$0$$$ and one $$$1$$$: $$$[10]00101100\to [01]00101100$$$.  It is illegal to select the prefix of length $$$4$$$ for the third operation, because it has three $$$0$$$'s and one $$$1$$$. Can you transform the string $$$a$$$ into the string $$$b$$$ using some finite number of operations (possibly, none)?

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 3\cdot 10^5$$$) — the length of the strings $$$a$$$ and $$$b$$$. The following two lines contain strings $$$a$$$ and $$$b$$$ of length $$$n$$$, consisting of symbols $$$0$$$ and $$$1$$$. The sum of $$$n$$$ across all test cases does not exceed $$$3\cdot 10^5$$$.

For each test case, output "YES" if it is possible to transform $$$a$$$ into $$$b$$$, or "NO" if it is impossible. You can print each letter in any case (upper or lower).

NoteThe first test case is shown in the statement.In the second test case, we transform $$$a$$$ into $$$b$$$ by using zero operations.In the third test case, there is no legal operation, so it is impossible to transform $$$a$$$ into $$$b$$$.In the fourth test case, here is one such transformation:   Select the length $$$2$$$ prefix to get $$$100101010101$$$.  Select the length $$$12$$$ prefix to get $$$011010101010$$$.  Select the length $$$8$$$ prefix to get $$$100101011010$$$.  Select the length $$$4$$$ prefix to get $$$011001011010$$$.  Select the length $$$6$$$ prefix to get $$$100110011010$$$. In the fifth test case, the only legal operation is to transform $$$a$$$ into $$$111000$$$. From there, the only legal operation is to return to the string we started with, so we cannot transform $$$a$$$ into $$$b$$$.


You are playing a variation of game 2048. Initially you have a multiset $$$s$$$ of $$$n$$$ integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from $$$s$$$, remove them from $$$s$$$ and insert the number equal to their sum into $$$s$$$.For example, if $$$s = \{1, 2, 1, 1, 4, 2, 2\}$$$ and you choose integers $$$2$$$ and $$$2$$$, then the multiset becomes $$$\{1, 1, 1, 4, 4, 2\}$$$.You win if the number $$$2048$$$ belongs to your multiset. For example, if $$$s = \{1024, 512, 512, 4\}$$$ you can win as follows: choose $$$512$$$ and $$$512$$$, your multiset turns into $$$\{1024, 1024, 4\}$$$. Then choose $$$1024$$$ and $$$1024$$$, your multiset turns into $$$\{2048, 4\}$$$ and you win.You have to determine if you can win this game.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) – the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in multiset. The second line of each query contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 2^{29}$$$) — the description of the multiset. It is guaranteed that all elements of the multiset are powers of two.

For each query print YES if it is possible to obtain the number $$$2048$$$ in your multiset, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first query you can win as follows: choose $$$512$$$ and $$$512$$$, and $$$s$$$ turns into $$$\{1024, 64, 1024\}$$$. Then choose $$$1024$$$ and $$$1024$$$, and $$$s$$$ turns into $$$\{2048, 64\}$$$ and you win.In the second query $$$s$$$ contains $$$2048$$$ initially.

#!/usr/bin/perl -w
use strict;
use warnings;

my $n = <STDIN>; chomp $n;
my $rB = [];
for my $j ( 1 .. $n ) {
   my $a = <STDIN>; chomp $a;
   my $str = <STDIN>; my @r = split(/\s+/, $str);
   pop @r unless ( $#r+1 eq $a );
   $rB->[$j] = \@r;
}
for my $j ( 1 .. $n ) {
    my @q = sort { $a <=> $b } @{ $rB->[$j] };
    my $change = 1; my $flag = 0;
    while ( $change eq 1 ) {
     @q = sort { $a <=> $b } @q;
     $change = 0;
     $flag = 1 if ( $q[$#q] eq "2048" );
     if ( $flag eq 0 ) {
     for my $t ( 0 .. $#q - 1 ) {
        if ( $q[$t] eq "2048" ) {
            $flag = 1; last;
        }
        if ( $q[$t] eq $q[$t+1] ) {
            $change = 1;
            $q[$t] = 2*$q[$t];
            for my $p ( $t + 1 .. $#q - 1 ) {
               $q[$p] = $q[$p+1];
            }
            pop @q;
            if ( $q[$t] eq "2048" ) {
                $flag = 1; last;
            }
            last;
        }
     }
     }
     last if ( $flag eq 1 );
    }
    if ( $flag eq 1 ) { print "YES\n";
    } else { print "NO\n"; }
}

my $n = <STDIN>; chomp $n;
my $rB = [];
for my $j ( 1 .. $n ) {
   my $a = <STDIN>; chomp $a;
   my $str = <STDIN>; my @r = split(/\s+/, $str);
   pop @r unless ( $#r+1 eq $a );
   $rB->[$j] = \@r;
}
for my $j ( 1 .. $n ) {
    my @q = sort { $a <=> $b } @{ $rB->[$j] };
    my $change = 1; my $flag = 0;
    while ( $change eq 1 ) {
     $change = 0;
     $flag = 1 if ( $q[$#q] eq "2048" );
     if ( $flag eq 0 ) {
     for my $t ( 0 .. $#q - 1 ) {
        if ( $q[$t] eq "2048" ) {
            $flag = 1; last;
        }
        if ( $q[$t] eq $q[$t+1] ) {
            $change = 1;
            $q[$t] = 2*$q[$t];
            for my $p ( $t + 1 .. $#q - 1 ) {
               $q[$p] = $q[$p+1];
            }
            pop @q;
            if ( $q[$t] eq "2048" ) {
                $flag = 1; last;
            }
            last;
        }
     }
     }
     last if ( $flag eq 1 );
    }
    if ( $flag eq 1 ) { print "YES\n";
    } else { print "NO\n"; }
}

#!/usr/bin/perl -w
use strict;
use warnings;

my $n = <STDIN>; chomp $n;
my $rB = [];
for my $j ( 1 .. $n ) {
   my $a = <STDIN>; chomp $a;
   my $str = <STDIN>; my @r = split(/\s+/, $str);
   pop @r unless ( $#r+1 eq $a );
   $rB->[$j] = \@r;
}
for my $j ( 1 .. $n ) {
    my @q = sort { $a <=> $b } @{ $rB->[$j] };
    my $change = 1; my $flag = 0;
    while ( $change eq 1 ) {
     $change = 0;
     $flag = 1 if ( $q[$#q] eq "2048" );
     for my $t ( 0 .. $#q - 1 ) {
        if ( $q[$t] eq "2048" ) {
            $flag = 1; last;
        }
        if ( $q[$t] eq $q[$t+1] ) {
            $change = 1;
            $q[$t] = 2*$q[$t];
            for my $p ( $t + 1 .. $#q - 1 ) {
               $q[$p] = $q[$p+1];
            }
            pop @q;
            if ( $q[$t] eq "2048" ) {
                $flag = 1; last;
            }
            last;
        }
     }
     last if ( $flag eq 1 );
    }
    if ( $flag eq 1 ) { print "YES\n";
    } else { print "NO\n"; }
}

#!/usr/bin/perl -w
use strict;
use warnings;

my $n = <STDIN>; chomp $n;
my $rA = []; my $rB = [];
for my $j ( 1 .. $n ) {
   $rA->[$j] = <STDIN>;
   my $str = <STDIN>; my @r = split(/\s+/, $str);
   $rB->[$j] = \@r;
}
for my $j ( 1 .. $n ) {
    my @q = sort { $a <=> $b } @{ $rB->[$j] };
    my $change = 1; my $flag = 0;
    while ( $change eq 1 ) {
     $change = 0;
     $flag = 1 if ( $q[$#q] eq "2048" );
     for my $t ( 0 .. $#q - 1 ) {
        if ( $q[$t] eq "2048" ) {
            $flag = 1; last;
        }
        if ( $q[$t] eq $q[$t+1] ) {
            $change = 1;
            $q[$t] = 2*$q[$t];
            for my $p ( $t + 1 .. $#q - 1 ) {
               $q[$p] = $q[$p+1];
            }
            pop @q;
            if ( $q[$t] eq "2048" ) {
                $flag = 1; last;
            }
            last;
        }
     }
     last if ( $flag eq 1 );
    }
    if ( $flag eq 1 ) { print "YES\n";
    } else { print "NO\n"; }
}


Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.  You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.

For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO".

5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*

NoteThe graph from the first three test cases is shown below:  In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.


You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:   Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$;  Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$;  Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$).

Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it.

use strict;
use warnings;

use Data::Dumper;

sub main {

    my $in= *STDIN;
    my $q= <$in>; chomp($q);

    OUT: for (my $i = 0; $i < $q; $i++) {
        my $t= <$in>; chomp($t); #this..

        if($t == 1) {
            print "0\n";
            next;
        }

        my $c= 0;
        my $s= 0;
        while($t != 1) {
            if(($t%2)==0) {
                $t= ($t/2);
            } elsif (($t%3)==0) {
                $t= ((2*$t)/3);
            } elsif (($t%5)==0) {
                $t= ((4*$t)/5);
            } else {
                print "-1\n";
                $s= 1;
                last;
            }
            $c++;
        }

        print "$c\n" unless($s);

    }

}

main() unless caller();


Прошло много лет, и на вечеринке снова встретились n друзей. С момента последней встречи техника шагнула далеко вперёд, появились фотоаппараты с автоспуском, и теперь не требуется, чтобы один из друзей стоял с фотоаппаратом, и, тем самым, оказывался не запечатлённым на снимке.Упрощенно процесс фотографирования можно описать следующим образом. На фотографии каждый из друзей занимает прямоугольник из пикселей: в стоячем положении i-й из них занимает прямоугольник ширины wi пикселей и высоты hi пикселей. Но также, при фотографировании каждый человек может лечь, и тогда он будет занимать прямоугольник ширины hi пикселей и высоты wi пикселей.Общая фотография будет иметь размеры W × H, где W — суммарная ширина всех прямоугольников-людей, а H — максимальная из высот. Друзья хотят определить, какую минимальную площадь может иметь общая фотография. Помогите им в этом.

В первой строке следует целое число n (1 ≤ n ≤ 1000) — количество друзей. В последующих n строках следуют по два целых числа wi, hi (1 ≤ wi, hi ≤ 1000), обозначающие размеры прямоугольника, соответствующего i-му из друзей.

Выведите единственное целое число, равное минимальной возможной площади фотографии, вмещающей всех друзей.

#!perl

$n = <>;

$max_h = 0;
for(my $i = 0; $i < $n; $i++)
{
	(my $w, my $h) = split / /, <>;
	chomp $w;
	chomp $h;
	($w, $h) = $w >= $h ? ($w, $h) : ($h, $w);

	$max_h = $h if $max_h < $h ;

	push @ws, $w;
	push @hs, $h;
}

push @b, $max_h;
foreach my $item (@ws)
{
	push @b, $item if $item >= $max_h;
}

foreach my $item (@b)
{
	my $sum = 0;
	for(my $i = 0; $i < $n; $i ++)
	{
		$sum += @ws[$i] > $item ? @ws[$i] : @hs[$i];
	}

	push @s, $sum*$item;
}

$mins = 10**10;
foreach my $item (@s)
{
	$mins = $item if  $mins > $item;
}

print  $mins, "\n";

#!perl

$n = <>;

$max_h = 0;
for(my $i = 0; $i < $n; $i++)
{
    (my $w, my $h) = split / /, <>;
    chomp $w;
    chomp $h;
    ($w, $h) = $w >= $h ? ($w, $h) : ($h, $w);

    $max_h = $h if $max_h < $h ;

    push @a, ($w, $h);
}

@sorted_a = sort { $a <=> $b} @a;
@b = @sorted_a[$n..$#sorted_a];
push @b, $max_h;

foreach my $item (@b)
{
    my $sum = 0;
    for(my $i = 0; $i <= $#a; $i += 2)
    {
        $sum += @a[$i] > $item ? @a[$i] : @a[$i + 1];
    }

    print $sum, " ", $item, "\n";
    push @s, $sum*$item;
}

$mins = 10**10;
foreach my $item (@s)
{
    $mins = $item if  $mins > $item;
}

print  $mins, "\n";

#!perl

$n = <>;

$max_h = 0;
for(my $i = 0; $i < $n; $i++)
{
    (my $w, my $h) = split / /, <>;
    chomp $w;
    chomp $h;
    ($w, $h) = $w >= $h ? ($w, $h) : ($h, $w);

    $max_h = $h if $max_h < $h ;

    push @a, ($w, $h);
}

@sorted_a = sort { $a <=> $b} @a;
@b = @sorted_a[$n..$#sorted_a];
push @b, $max_h;

foreach my $item (@b)
{
    my $sum = 0;
    for(my $i = 0; $i <= $#a; $i += 2)
    {
        $sum += @a[$i] > $item ? @a[$i] : @a[$i + 1];
    }

    push @s, $sum*$item;
}

$mins = 10**10;
foreach my $item (@s)
{
    $mins = $item if  $mins > $item;
}

print  $mins, "\n";


Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once. Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.

The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house. The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.

Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.

NoteIn the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6. In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.


Let's call the string beautiful if it does not contain a substring of length at least $$$2$$$, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not.Let's define cost of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first $$$3$$$ letters of the Latin alphabet (in lowercase).You are given a string $$$s$$$ of length $$$n$$$, each character of the string is one of the first $$$3$$$ letters of the Latin alphabet (in lowercase).You have to answer $$$m$$$ queries — calculate the cost of the substring of the string $$$s$$$ from $$$l_i$$$-th to $$$r_i$$$-th position, inclusive.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$ and the number of queries. The second line contains the string $$$s$$$, it consists of $$$n$$$ characters, each character one of the first $$$3$$$ Latin letters. The following $$$m$$$ lines contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — parameters of the $$$i$$$-th query.

For each query, print a single integer — the cost of the substring of the string $$$s$$$ from $$$l_i$$$-th to $$$r_i$$$-th position, inclusive.

NoteConsider the queries of the example test.  in the first query, the substring is baa, which can be changed to bac in one operation;  in the second query, the substring is baacb, which can be changed to cbacb in two operations;  in the third query, the substring is cb, which can be left unchanged;  in the fourth query, the substring is aa, which can be changed to ba in one operation.


Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.

The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items.

Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.

NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one.


Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead.The first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help.Consider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move. Help Anton and write the program that for the given position determines whether the white king is in check.Remainder, on how do chess pieces move:   Bishop moves any number of cells diagonally, but it can't "leap" over the occupied cells.  Rook moves any number of cells horizontally or vertically, but it also can't "leap" over the occupied cells.  Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't "leap".

The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of black pieces. The second line contains two integers x0 and y0 ( - 109 ≤ x0, y0 ≤ 109) — coordinates of the white king. Then follow n lines, each of them contains a character and two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — type of the i-th piece and its position. Character 'B' stands for the bishop, 'R' for the rook and 'Q' for the queen. It's guaranteed that no two pieces occupy the same position.

The only line of the output should contains "YES" (without quotes) if the white king is in check and "NO" (without quotes) otherwise.

NotePicture for the first sample:    White king is in check, because the black bishop can reach the cell with the white king in one move. The answer is "YES".Picture for the second sample:    Here bishop can't reach the cell with the white king, because his path is blocked by the rook, and the bishop cant "leap" over it. Rook can't reach the white king, because it can't move diagonally. Hence, the king is not in check and the answer is "NO".

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $X, $Y ) = split ' ', <>;

	my $check = 0;

	my @top = (~0) x 5;
	my @bot = (-~0) x 5;
	my @topF;
	my @botF;

	for (1 .. $_){
		my( $fig, $x, $y ) = split ' ', <>;

		my $D = $x == $X ? 1 :
			$y == $Y ? 2 :
			$x + $y == $X + $Y ? 3 :
			$x - $X == $y - $Y ? 4 : 0;

		$D or next;
		my $M = $X;
		$D == 1 and do { $x = $y ; $M = $Y };

		if( $x > $M and $x < $top[$D]){
			$top[$D] = $x;
			$topF[$D] = $fig;
			}
		if( $x < $M and $x > $bot[$D]){
			$bot[$D] = $x;
			$botF[$D] = $fig;
			}
		}

	$check += grep /[QR]/, grep defined, @topF[1,2], @botF[1,2];
	$check += grep /[QB]/, grep defined, @topF[3,4], @botF[3,4];

	print $check ? "YES" : "NO";
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $X, $Y ) = split ' ', <>;

	my( @X, @Y, @a8h1, @a1h8 );

	for (1 .. $_){
		my( $fig, $x, $y ) = split ' ', <>;

		if( $x == $X ){
			push @X, [$fig, $x, $y];
			}
		if( $y == $Y ){
			push @Y, [$fig, $x, $y];
			}
		if( $x + $y == $X + $Y ){
			push @a8h1, [$fig, $x, $y];
			}
		if( $x - $X == $y - $Y ){
			push @a1h8, [$fig, $x, $y];
			}
		}

	my $check = 0;

	my $top = ~0;
	my $bottom = -~0;
	my $topFig;
	my $bottomFig;

	for( @X ){
		if( $_->[2] > $Y and $_->[2] < $top){
			$top = $_->[2];
			$topFig = $_->[0];
			}
		if( $_->[2] < $Y and $_->[2] > $bottom){
			$bottom = $_->[2];
			$bottomFig = $_->[0];
			}
		}

	$check += grep /[QR]/, grep defined, $topFig, $bottomFig;

#	print "check X: $check";

	my $top = ~0;
	my $bottom = -~0;
	my $topFig;
	my $bottomFig;

	for( @Y ){
		if( $_->[1] > $X and $_->[1] < $top){
			$top = $_->[1];
			$topFig = $_->[0];
			}
		if( $_->[1] < $X and $_->[1] > $bottom){
			$bottom = $_->[1];
			$bottomFig = $_->[0];
			}
		}

	$check += grep /[QR]/, grep defined, $topFig, $bottomFig;

#	print "check Y: $check";

	my $top = ~0;
	my $bottom = -~0;
	my $topFig;
	my $bottomFig;

	for( @a8h1 ){
		if( $_->[1] > $X and $_->[1] < $top){
			$top = $_->[1];
			$topFig = $_->[0];
			}
		if( $_->[1] < $X and $_->[1] > $bottom){
			$bottom = $_->[1];
			$bottomFig = $_->[0];
			}
		}

	$check += grep /[QB]/, grep defined, $topFig, $bottomFig;

#	print "check a8h1: $check";

	my $top = ~0;
	my $bottom = -~0;
	my $topFig;
	my $bottomFig;

	for( @a1h8 ){
		if( $_->[1] > $X and $_->[1] < $top){
			$top = $_->[1];
			$topFig = $_->[0];
			}
		if( $_->[1] < $X and $_->[1] > $bottom){
			$bottom = $_->[1];
			$bottomFig = $_->[0];
			}
		}

	$check += grep /[QB]/, grep defined, $topFig, $bottomFig;

#	print "check a1h8: $check";

	print $check ? "YES" : "NO";
}