Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters.

In a single line print the answer to the problem — the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them.

NoteConsider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.


Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.

The first line contains two integer n and m (1 ≤ n, m ≤ 100). The second line contains integer b (0 ≤ b ≤ n), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1, x2, ..., xb (0 ≤ xi < n), denoting the list of indices of happy boys. The third line conatins integer g (0 ≤ g ≤ m), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1, y2, ... , yg (0 ≤ yj < m), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.

If Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No".

NoteBy  we define the remainder of integer division of i by k.In first sample case:   On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day.  On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day.  On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day.  On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy.  On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.

use strict;

use List::Util qw(first max maxstr min minstr reduce shuffle sum);

my ($n, $m) = split / /, <>;
my $b;
my @bs;
$#bs = $n-1;

my @i = split / /, <>;
$b = shift @i;
for(@i)
{
    $bs[$_] = 1;
}
my @gs;
$#gs = $m-1;
@i = split / /, <>;

my $g = shift @i;
for(@i)
{
    $gs[$_] = 1;
}
if($b == 0 and $g == 0){ print "No";exit 0; }

my $nod = nod($m, $n);

my @t; $#t = $nod-1;

for (0..max ($n, $m))
{
    $t[$_ % $nod] = $bs[$_ % $n] || $gs[$_ % $m] || $t[$_ % $nod];
}
my $flag = 1;
for(@t)
{
    $flag *= $_;
}

print "Yes" if ($flag);
print "No" unless ($flag);

sub nod
 {
 return  $_[0] != 0  ?  nod ( ( $_[1] % $_[0] ), $_[0] )  :  $_[1];
 };

sub gcf {
  my ($x, $y) = @_;
  ($x, $y) = ($y, $x % $y) while $y;
  return $x;
}

sub lcm {
  return($_[0] * $_[1] / gcf($_[0], $_[1]));
}

chomp (my ($n, $m) = split /\s+/, <>);
my @boys  = (0) x $n;
my @girls = (0) x $m;
chomp (my @hb = split /\s+/, <>);
chomp (my @hg = split /\s+/, <>);

my $hcnt = 0;
$hcnt += shift @hb;
$hcnt += shift @hg;

$boys[$_]   = 1 foreach (@hb);
$girls[$_]  = 1 foreach (@hg);

my $prevhcnt;
my ($i, $j);

repeat:

$prevhcnt = $hcnt;
($i, $j) = (0, 0);
foreach my $x (0 .. &lcm($n, $m) - 1) {
  $i++;
  $j++;
  $i = ($n > $i) ? $i : 0;
  $j = ($m > $j) ? $j : 0;
  if ($boys[$i] ^ $girls[$j]) {
    $boys[$i] = 1;
    $girls[$j] = 1;
    $hcnt++;
  }
}
# printf "@boys\n@girls\n$hcnt\n$prevhcnt\n";
goto repeat if ($hcnt > $prevhcnt);

if ($hcnt == ($m + $n)) {
  printf "YES\n";
} else {
  printf "NO\n";
}

chomp (my ($n, $m) = split /\s+/, <>);
my @boys  = (0) x $n;
my @girls = (0) x $m;
chomp (my @hb = split /\s+/, <>);
chomp (my @hg = split /\s+/, <>);

my $hcnt = 0;
$hcnt += shift @hb;
$hcnt += shift @hg;

$boys[$_]   = 1 foreach (@hb);
$girls[$_]  = 1 foreach (@hg);

my $prevhcnt;

$n--;
$m--;

repeat:
$prevhcnt = $hcnt;
foreach my $i (0 .. $n) {
  foreach my $j (0 .. $m) {
    if ($boys[$i] ^ $girls[$j]) {
      $girls[$j] = 1;
      $boys[$i] = 1;
      $hcnt++;
    }
  }
}
# printf "@boys\n@girls\n$hcnt\n$prevhcnt\n";
goto repeat if ($hcnt > $prevhcnt);

if ($hcnt == ($m + $n + 2)) {
  printf "YES\n";
} else {
  printf "NO\n";
}

sub gcf {
  my ($x, $y) = @_;
  ($x, $y) = ($y, $x % $y) while $y;
  return $x;
}

sub lcm {
  return($_[0] * $_[1] / gcf($_[0], $_[1]));
}

chomp (my ($n, $m) = split /\s+/, <>);
my @boys  = (0) x $n;
my @girls = (0) x $m;
chomp (my @hb = split /\s+/, <>);
chomp (my @hg = split /\s+/, <>);

my $hcnt = 0;
$hcnt += shift @hb;
$hcnt += shift @hg;

$boys[$_]   = 1 foreach (@hb);
$girls[$_]  = 1 foreach (@hg);

my $prevhcnt;
my ($i, $j);

repeat:

$prevhcnt = $hcnt;
($i, $j) = (0, 0);
foreach my $x (0 .. &lcm($n, $m) - 1) {
  $i++;
  $j++;
  $i = ($n > $i) ? $i : 0;
  $j = ($m > $j) ? $j : 0;
  if ($boys[$i] ^ $girls[$j]) {
    $boys[$i] = 1;
    $girls[$j] = 1;
    $hcnt++;
  }
}
printf "@boys\n@girls\n$hcnt\n$prevhcnt\n";
goto repeat if ($hcnt > $prevhcnt);

if ($hcnt == ($m + $n + 2)) {
  printf "YES\n";
} else {
  printf "NO\n";
}


There are $$$n$$$ dormitories in Berland State University, they are numbered with integers from $$$1$$$ to $$$n$$$. Each dormitory consists of rooms, there are $$$a_i$$$ rooms in $$$i$$$-th dormitory. The rooms in $$$i$$$-th dormitory are numbered from $$$1$$$ to $$$a_i$$$.A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all $$$n$$$ dormitories is written on an envelope. In this case, assume that all the rooms are numbered from $$$1$$$ to $$$a_1 + a_2 + \dots + a_n$$$ and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.For example, in case $$$n=2$$$, $$$a_1=3$$$ and $$$a_2=5$$$ an envelope can have any integer from $$$1$$$ to $$$8$$$ written on it. If the number $$$7$$$ is written on an envelope, it means that the letter should be delivered to the room number $$$4$$$ of the second dormitory.For each of $$$m$$$ letters by the room number among all $$$n$$$ dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \le n, m \le 2 \cdot 10^{5})$$$ — the number of dormitories and the number of letters. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{10})$$$, where $$$a_i$$$ equals to the number of rooms in the $$$i$$$-th dormitory. The third line contains a sequence $$$b_1, b_2, \dots, b_m$$$ $$$(1 \le b_j \le a_1 + a_2 + \dots + a_n)$$$, where $$$b_j$$$ equals to the room number (among all rooms of all dormitories) for the $$$j$$$-th letter. All $$$b_j$$$ are given in increasing order.

Print $$$m$$$ lines. For each letter print two integers $$$f$$$ and $$$k$$$ — the dormitory number $$$f$$$ $$$(1 \le f \le n)$$$ and the room number $$$k$$$ in this dormitory $$$(1 \le k \le a_f)$$$ to deliver the letter.

NoteIn the first example letters should be delivered in the following order:  the first letter in room $$$1$$$ of the first dormitory  the second letter in room $$$9$$$ of the first dormitory  the third letter in room $$$2$$$ of the second dormitory  the fourth letter in room $$$13$$$ of the second dormitory  the fifth letter in room $$$1$$$ of the third dormitory  the sixth letter in room $$$12$$$ of the third dormitory

# author : Gabriel Hofer
use warnings;
use strict;
use constant NL => qq/\n/;

my ($n, $m) = ( <STDIN> =~ m /(\d+)\s(\d+)/ );
my @one = split qq/ /, <STDIN>;
my @two = split qq/ /, <STDIN>;
my @three = @one;
for ( my $i = 1; $i <= $#three; $i += 1 ) {
    $three [ $i ] += $three [ $i - 1 ] }

AA: for my $i ( @two ) {
    my ($left, $right, $mid);
    $left = 0;
    $right = $#three;
    AB: while ( $left < $right ) {
        $mid = int ( ( $left + $right ) / 2 );
        if ( $i < $three [ $mid ] ) { $right = $mid }
        elsif ( $i > $three [ $mid ] ) { $left = $mid + 1 }
        else { last AB }
    }
    $mid = int ( ( $left + $right ) / 2 );
    print ( $mid + 1, qq/ / );
    if ( $mid == 0 ) { print qq/$i/ }
    else { print ( $i - $three [ $mid - 1 ] ) }
    print NL;
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $n, $m ) = split;
	@_ = split ' ', <>;

	my $house = 1;
	my $accum = 0;

	for my $i ( split ' ', <> ){

		while( @_ and $_[ 0 ] + $accum < $i ){
			$house ++;
			$accum += $_[ 0 ];
			shift @_;
			}

		print $house . ' ' . ( $i - $accum );
		}

	}


A sequence of positive integers is called great for a positive integer $$$x$$$, if we can split it into pairs in such a way that in each pair the first number multiplied by $$$x$$$ is equal to the second number. More formally, a sequence $$$a$$$ of size $$$n$$$ is great for a positive integer $$$x$$$, if $$$n$$$ is even and there exists a permutation $$$p$$$ of size $$$n$$$, such that for each $$$i$$$ ($$$1 \le i \le \frac{n}{2}$$$) $$$a_{p_{2i-1}} \cdot x = a_{p_{2i}}$$$. Sam has a sequence $$$a$$$ and a positive integer $$$x$$$. Help him to make the sequence great: find the minimum possible number of positive integers that should be added to the sequence $$$a$$$ to make it great for the number $$$x$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20\,000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$x$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$2 \le x \le 10^6$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer — the minimum number of integers that can be added to the end of $$$a$$$ to make it a great sequence for the number $$$x$$$.

NoteIn the first test case, Sam got lucky and the sequence is already great for the number $$$4$$$ because you can divide it into such pairs: $$$(1, 4)$$$, $$$(4, 16)$$$. Thus we can add $$$0$$$ numbers.In the second test case, you can add numbers $$$1$$$ and $$$14$$$ to the sequence, then you can divide all $$$8$$$ integers into such pairs: $$$(1, 2)$$$, $$$(1, 2)$$$, $$$(2, 4)$$$, $$$(7, 14)$$$. It is impossible to add less than $$$2$$$ integers to fix the sequence.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	my( $n, $x ) = split;

	@_ = split ' ', <>;

	my %h;

	map $h{ $_ } ++, @_;

	for my $key ( sort { $b <=> $a } keys %h ){
		if( $key % $x == 0 and exists $h{ $key / $x } ){
			while( $h{ $key } > 0 and $h{ $key / $x } > 0 ){
				$h{ $key } --;
				$h{ $key / $x } --;
				}
			}
		}

	print 0 + eval join '+', values %h;
	}


William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.

NoteIn the first test case the following sequence of operations would satisfy the requirements:   swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements:   swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$  swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$  swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements:   swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$  swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$


Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.

The first line contains two space-separated integers n and m (1 ≤ m ≤ n ≤ 100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai ( - 1000 ≤ ai ≤ 1000) — prices of the TV sets.

Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.

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

sub min{
    return $_[0] < $_[1]? $_[0]:$_[1];
}
my $n;my $m;
($n, $m) = split(' ', <>);

my @arr = split(' ', <>);
@arr = sort {$a <=> $b}@arr;

my $res = 0;
for(my $i = 0; $i < min($n,$m); $i++){
    if($arr[$i] < 0){$res += -$arr[$i];}
    else {last;}
}
print $res;

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

sub min{
    return $_[0] < $_[1]? $_[0]:$_[1];
}
my $n;my $m;
($n, $m) = split(' ', <>);

my @arr = split(' ', <>);
@arr = sort @arr;

my $res = 0;
for(my $i = 0; $i < min($n,$m); $i++){
    if($arr[$i] < 0){$res += -$arr[$i];}
    else {last;}
}
print $res;


You are given an integer $$$n$$$. You have to change the minimum number of digits in it in such a way that the resulting number does not have any leading zeroes and is divisible by $$$7$$$.If there are multiple ways to do it, print any of them. If the given number is already divisible by $$$7$$$, leave it unchanged.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 990$$$) — the number of test cases. Then the test cases follow, each test case consists of one line containing one integer $$$n$$$ ($$$10 \le n \le 999$$$).

For each test case, print one integer without any leading zeroes — the result of your changes (i. e. the integer that is divisible by $$$7$$$ and can be obtained by changing the minimum possible number of digits in $$$n$$$). If there are multiple ways to apply changes, print any resulting number. If the given number is already divisible by $$$7$$$, just print it.

NoteIn the first test case of the example, $$$42$$$ is already divisible by $$$7$$$, so there's no need to change it.In the second test case of the example, there are multiple answers — $$$28$$$, $$$21$$$ or $$$63$$$.In the third test case of the example, other possible answers are $$$357$$$, $$$371$$$ and $$$378$$$. Note that you cannot print $$$077$$$ or $$$77$$$.


You are given an array $$$a$$$ of $$$n$$$ integers. Find the number of pairs $$$(i, j)$$$ ($$$1 \le i < j \le n$$$) where the sum of $$$a_i + a_j$$$ is greater than or equal to $$$l$$$ and less than or equal to $$$r$$$ (that is, $$$l \le a_i + a_j \le r$$$).For example, if $$$n = 3$$$, $$$a = [5, 1, 2]$$$, $$$l = 4$$$ and $$$r = 7$$$, then two pairs are suitable:   $$$i=1$$$ and $$$j=2$$$ ($$$4 \le 5 + 1 \le 7$$$);  $$$i=1$$$ and $$$j=3$$$ ($$$4 \le 5 + 2 \le 7$$$).

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n, l, r$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le l \le r \le 10^9$$$) — the length of the array and the limits on the sum in the pair. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ overall test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of index pairs $$$(i, j)$$$ ($$$i < j$$$), such that $$$l \le a_i + a_j \le r$$$.


Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that:   the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN",  or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of clubs in the league. Each of the next n lines contains two words — the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20.

It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them.

3
PLAYFOOTBALL MOSCOW
PLAYVOLLEYBALL SPB
GOGO TECHNOCUP

NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different.


Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.Recently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer $$$x$$$ as nearly prime if it can be represented as $$$p \cdot q$$$, where $$$1 < p < q$$$ and $$$p$$$ and $$$q$$$ are prime numbers. For example, integers $$$6$$$ and $$$10$$$ are nearly primes (since $$$2 \cdot 3 = 6$$$ and $$$2 \cdot 5 = 10$$$), but integers $$$1$$$, $$$3$$$, $$$4$$$, $$$16$$$, $$$17$$$ or $$$44$$$ are not.Captain Flint guessed an integer $$$n$$$ and asked you: can you represent it as the sum of $$$4$$$ different positive integers where at least $$$3$$$ of them should be nearly prime.Uncle Bogdan easily solved the task and joined the crew. Can you do the same?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first and only line of each test case contains the single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ — the number Flint guessed.

For each test case print:    YES and $$$4$$$ different positive integers such that at least $$$3$$$ of them are nearly prime and their sum is equal to $$$n$$$ (if there are multiple answers print any of them);  NO if there is no way to represent $$$n$$$ as the sum of $$$4$$$ different positive integers where at least $$$3$$$ of them are nearly prime.  YES NO

NoteIn the first and second test cases, it can be proven that there are no four different positive integers such that at least three of them are nearly prime.In the third test case, $$$n=31=2 \cdot 7 + 2 \cdot 5 + 2 \cdot 3 + 1$$$: integers $$$14$$$, $$$10$$$, $$$6$$$ are nearly prime.In the fourth test case, $$$n=36=5 + 2 \cdot 3 + 2 \cdot 5 + 3 \cdot 5$$$: integers $$$6$$$, $$$10$$$, $$$15$$$ are nearly prime.In the fifth test case, $$$n=44=2 \cdot 3 + 7 + 2 \cdot 5 + 3 \cdot 7$$$: integers $$$6$$$, $$$10$$$, $$$21$$$ are nearly prime.In the sixth test case, $$$n=100=2 + 2 \cdot 5 + 3 \cdot 11 + 5 \cdot 11$$$: integers $$$10$$$, $$$33$$$, $$$55$$$ are nearly prime.In the seventh test case, $$$n=258=2 \cdot 5 + 3 \cdot 7 + 13 \cdot 17 + 2 \cdot 3$$$: integers $$$10$$$, $$$21$$$, $$$221$$$, $$$6$$$ are nearly prime.

use strict;

my $try = <>;
while($try-- > 0)
{
    my $val = <>;
    if($val < 31){
        print "NO\n";
    } elsif($val == 36) {
        print "YES\n";
        printf("15 10 6 %d\n", $val-31);
    } elsif($val == 40 || $val == 44) {
        print "YES\n";
        printf("15 10 14 %d\n", $val-39);
    } else {
        print "YES\n";
        printf("6 10 14 %d\n", $val-30);
    }
}


Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class. Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each student’s laziness level is equal to their task’s difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task. The time a student needs to finish a task is equal to the product of their laziness level and the task’s difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.

The first line of input contains integer n (1 ≤ n ≤ 100 000) — the number of tasks. The next n lines contain exactly one integer number ai (1 ≤ ai ≤ 100 000) — both the difficulty of the initial task and the laziness of the i-th students.

Print the minimum total time to finish all tasks modulo 10 007.

NoteIn the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.

my $n=<STDIN>;
chomp($n);
my @NUM;
while($n--){
my $k=<STDIN>;
chomp($k);
push(@NUM,$k);
}
my @L1=sort {$a <=> $b } @NUM;
my @L2=sort {$b <=> $a } @NUM;
my $ans=0;
for(my $i=0;$i<scalar(@NUM);$i++){
$ans += $L1[$i]*$L2[$i];
$ans %= 10007;
}

print $ans . "\n";

my $n=<STDIN>;
chomp($n);
my @NUM;
while($n--){
my $k=<STDIN>;
chomp($k);
push(@NUM,$k);
}
my @L1=sort {$a <=> $b } @NUM;
my @L2=sort {$b <=> $n } @NUM;
my $ans=0;
for(my $i=0;$i<scalar(@NUM);$i++){
$ans += $L1[$i]*$L2[$i];
}
$ans %= 10007;
print $ans . "\n";

my $n=<STDIN>;
chomp($n);
my @NUM;
while($n--){
my $k=<STDIN>;
chomp($k);
push(@NUM,$k);
}
my @L1=sort {$a <=> $b } @NUM;
my @L2=sort {$b <=> $n } @NUM;
my $ans=0;
for(my $i=0;$i<scalar(@NUM);$i++){
$ans += $L1[$i]*$L2[$i];
}

print $ans . "\n";

my $n=<STDIN>;
chomp($n);
my @NUM;
while($n--){
my $k=<STDIN>;
chomp($k);
push(@NUM,$k);
}
my @L1=sort {$a <=> $b } @NUM;
my @L2=sort {$b <=> $n } @NUM;
my $ans=0;
for(my $i=0;$i<scalar(@NUM);$i++){
$ans += $L1[$i]*$L2[$i];
$ans %= 10007;
}

print $ans . "\n";


City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.Road repairs are planned for n2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.According to the schedule of road works tell in which days at least one road will be asphalted.

The first line contains integer n (1 ≤ n ≤ 50) — the number of vertical and horizontal roads in the city.  Next n2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers hi, vi (1 ≤ hi, vi ≤ n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the hi-th horizontal and vi-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct.

In the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1.

NoteIn the sample the brigade acts like that:  On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road;  On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been asphalted, but as the 1-st horizontal road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the third day the brigade of the workers come to the intersection of the 2-nd horizontal and the 1-st vertical road. The 2-nd horizontal road hasn't been asphalted but as the 1-st vertical road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the fourth day the brigade come to the intersection formed by the intersection of the 2-nd horizontal and 2-nd vertical road. As none of them has been asphalted, the workers asphalt the 2-nd vertical and the 2-nd horizontal road.


It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?

First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).  Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).

Output a single integer — the minimum day at which Borya can visit the last doctor.

NoteIn the first sample case, Borya can visit all doctors on days 2, 3 and 4.In the second sample case, Borya can visit all doctors on days 10 and 11.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;
my $debug = 0;

while(<>){
	@_ = map ~~<>, 1 .. $_;
	my $start = 0;

	for( @_ ){
		my( $s, $d ) = split;
		$start ++;

		my $n = ( $start - $s ) / $d;
		$debug and print '  ', $n;
		$start = $s + $d * ( $n =~ s/-.*/0/r =~ s/(\d+)\..*/ $1 + 1 /er );
		$debug and print '       ', $start;
		}

	print $start;
	}


Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of columns.  The next n lines contain the pairs of integers li and ri (1 ≤ li, ri ≤ 500) — the number of soldiers in the i-th column which start to march from the left or the right leg respectively.

Print single integer k — the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached. Consider that columns are numbered from 1 to n in the order they are given in the input data. If there are several answers, print any of them.

NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5 + 8 + 10 = 23, and from the right leg — 6 + 9 + 3 = 18. In this case the beauty of the parade will equal |23 - 18| = 5.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5 + 8 + 3 = 16, and who march from the right leg — 6 + 9 + 10 = 25. In this case the beauty equals |16 - 25| = 9.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9.


Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, "abc" $$$\cdot~2~=$$$ "abcabc", "a" $$$\cdot~5~=$$$ "aaaaa".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \cdot x = a$$$. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of test cases. Each test case consists of two lines, containing strings $$$s$$$ and $$$t$$$ ($$$1 \le |s|, |t| \le 20$$$). Each character in each of these strings is either 'a' or 'b'.

For each test case, print $$$LCM(s, t)$$$ if it exists; otherwise, print -1. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

NoteIn the first test case, "baba" = "baba" $$$\cdot~1~=$$$ "ba" $$$\cdot~2$$$.In the second test case, "aaaaaa" = "aa" $$$\cdot~3~=$$$ "aaa" $$$\cdot~2$$$.

#!/usr/bin/perl
my ($q) = map { $_ - 0 } split(/\s+/o,<STDIN>);
while( $q -- > 0 ){
  ( my $s = <STDIN> ) =~ s/\s+$//ios;
  ( my $t = <STDIN> ) =~ s/\s+$//ios;
  my $r = -1;
  for(my $i=1;$i<=20;$i++){
    last if substr($s,$i-1,1) ne substr($t,$i-1,1);
    last unless (length($s) % $i == 0) and (length($t) % $i == 0);
    my $sc = (length($s)/$i);
    my $tc = (length($t)/$i);
    if( $s eq ( substr($s,0,$i) x $sc ) and $t eq ( substr($t,0,$i) x $tc ) ){
      my $c = $sc * $tc / gcd($sc,$tc);
      $r = ( substr($s,0,$i) x $c ); last;
    }
  }
  print "$r\n";
}
exit(0);
sub gcd {   # gcd(a,b)
  my ($a,$b) = @_;
  ($a,$b) = ($b,$a) if $a<$b;
  my $r = $a % $b;
  while($r!=0){
    $a = $b;
    $b = $r;
    $r = $a % $b;
  }
  return $b;
}

#!/usr/bin/perl
my ($q) = map { $_ - 0 } split(/\s+/o,<STDIN>);
while( $q -- > 0 ){
  ( my $s = <STDIN> ) =~ s/\s+$//ios;
  ( my $t = <STDIN> ) =~ s/\s+$//ios;
  my $r = -1;
  for(my $i=1;$i<=20;$i++){
    last if substr($s,$i-1,1) ne substr($t,$i-1,1);
    last unless (length($s) % $i == 0) and (length($t) % $i == 0);
    if( $s eq ( substr($s,0,$i) x (length($s)/$i) ) and $t eq ( substr($t,0,$i) x (length($t)/$i) ) ){
      $r = substr($s,0,$i); last;
    }
  }
  print "$r\n";
}

#!/usr/bin/perl
my ($q) = map { $_ - 0 } split(/\s+/o,<STDIN>);
while( $q -- > 0 ){
  ( my $s = <STDIN> ) =~ s/\s+$//ios;
  ( my $t = <STDIN> ) =~ s/\s+$//ios;
  my $r = -1;
  for(my $i=1;$i<=20;$i++){
    last if substr($s,$i-1,1) ne substr($t,$i-1,1);
    last unless length($s) % $i == 0 and length($t) % $i == 0;
    if( $s eq ( substr($s,0,$i) x (length($s)/$i) ) and $t eq ( substr($t,0,$i) x (length($t)/$i) ) ){
      $r = substr($s,0,$i);
    }
  }
  print "$r\n";
}


Gildong recently learned how to find the longest increasing subsequence (LIS) in $$$O(n\log{n})$$$ time for a sequence of length $$$n$$$. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length $$$n-1$$$, consisting of characters '<' and '>' only. The $$$i$$$-th (1-indexed) character is the comparison result between the $$$i$$$-th element and the $$$i+1$$$-st element of the sequence. If the $$$i$$$-th character of the string is '<', then the $$$i$$$-th element of the sequence is less than the $$$i+1$$$-st element. If the $$$i$$$-th character of the string is '>', then the $$$i$$$-th element of the sequence is greater than the $$$i+1$$$-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is $$$n-1$$$. It is guaranteed that the sum of all $$$n$$$ in all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print two lines with $$$n$$$ integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between $$$1$$$ and $$$n$$$, inclusive, and should satisfy the comparison results. It can be shown that at least one answer always exists.

NoteIn the first case, $$$1$$$ $$$2$$$ $$$3$$$ is the only possible answer.In the second case, the shortest length of the LIS is $$$2$$$, and the longest length of the LIS is $$$3$$$. In the example of the maximum LIS sequence, $$$4$$$ '$$$3$$$' $$$1$$$ $$$7$$$ '$$$5$$$' $$$2$$$ '$$$6$$$' can be one of the possible LIS.

# open STDIN, "<input";
chomp($t=<>);
sub long {
	my ($n, $s)=@_;
	my @arr=();
	my ($hi, $lo)=($n,1);
	for (my $i=0; $i<length $s; ++$i) {
		if (substr($s, $i, 1) eq '<') {
			$arr[$i]=$lo++;
		}
		else {
			$arr[$i]=$hi--;
		}
	}
	$arr[$n-1]=$hi;
	return @arr;
}
sub short {
	my ($n, $s)=@_;
	$s.='>';
	my @arr=();
	my $hi=$n;
	my ($idx,$i)=(index($s, '>'), 1);
	my @arr=();
	$arr[0]=$hi-$idx;
	my $newhi = $arr[0]-1;
	while ($i<$n) {
		while ($i<=$idx and $i<$n) {
			$arr[$i]=$hi-($idx-$i);
			++$i;
		}
		while ($i<$n and substr($s,$i,1) eq '>') {
			$arr[$i]=$newhi--;
			++$i;
		}
		$hi=$newhi;
		$idx=index($s, '>', $i);
		$newhi=$hi-($idx-$i)-1;
	}
	return @arr;
}
while ($t--) {
	($n, $s)=split(' ',<>); chomp $n, $s;
	# print "$n $s\n";
	@longest = &long($n,$s);
	@shortest = &short($n,$s);
	print "@shortest\n@longest\n";
}


A flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets. Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.Determine the maximum possible number of large bouquets Vasya can make.

The first line contains a single positive integer n (1 ≤ n ≤ 105) — the number of initial bouquets. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the number of flowers in each of the initial bouquets.

Print the maximum number of large bouquets Vasya can make.

NoteIn the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme. In the second example it is not possible to form a single bouquet with odd number of flowers.In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11 + 4 + 10 = 25.

#!/usr/local/bin/perl

my @ttt = split(/\s+/, <>);
my @arr = split(/\s+/, <>);

$odd = 0;
$even = 0;

foreach $a (@arr) {

    $c = int($a) % 2;

    if ($c == 1) {
        $odd = $odd + 1;
    } else {
        $even = $even + 1;
    }

}

if ($odd <= $even)
{
    print($odd)
}
else
{
    print($even + int(($odd - $even) / 3 + 1e-12))
}

$_ = <STDIN>; my ($n) = split;
$_ = <STDIN>; my @A = split;

$odd = 0;
$even = 0;
for($i=0; $i < $n ; $i=$i+1){

	if( $A[$i] %2 == 0){
	    $even = $even+1;
	}else{
	    $odd = $odd+1;
	}
}

$mn = $odd;
if ($even < $mn) {
    $mn = $even;
}

$df = $odd - $mn;
$kk = $df / 3;
$qq = int($kk);
$ans = $mn + $qq;

print "$ans\n"

my $x = <STDIN>;
chomp $x;

my $line = <STDIN>;
chomp $line;

my @splits = split / /, $line;

my $odd = 0;
my $even = 0;
for my $split (@splits) {
    if (int($split) % 2 == 0) {
        $even += 1;
    } else {
        $odd += 1;
    }
}

my $pair;

if ($even < $odd) {
    $pair = $even;
} else {
    $pair = $odd;
}

$odd -= $pair;
$even -= $pair;

my $ans = $pair + int($odd / 3);

print $ans . "\n";

my $x = <STDIN>;
chomp $x;

my $line = <STDIN>;
chomp $line;

my @splits = split / /, $line;

my $odd = 0;
my $even = 0;
for my $split (@splits) {
    if (int($split) % 2 == 0) {
        $even += 1;
    } else {
        $odd += 1;
    }
}

if ($even < $odd) {
    print $even . "\n";
} else {
    print $odd . "\n";
}

my $x = <STDIN>;
chomp $x;

my $line = <STDIN>;
chomp $line;

my @splits = split /,/, $line;

my $odd = 0;
my $even = 0;
for my $split (@splits) {
    if (int($split) % 2 == 0) {
        $even += 1;
    } else {
        $odd += 1;
    }
}

if ($even < $odd) {
    print $even . "\n";
} else {
    print $odd . "\n";
}


You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).

The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.

Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.

NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA".

$_=<>;
print qw/NO YES/[ 0+(/AB.*BA/ or /BA.*AB/) ]

$_=<>;
if(/AB.*BA/ or /BA.*AB/) {
  print "YES";
} else {
  print "NO";
}

$_ = <>;
my $ans = "NO\n";
$ans = "YES" if (/AB.*BA/ || /BA.*AB/);
print $ans;

print qw(YES NO)[$_ = <> xor /AB.*BA/ || /BA.*AB/ ]

$a = <>;
if ($a =~ m[AB.*BA]||$a =~ m[BA.*AB])
{
    print "YES";
}
else
{
    print "NO";
}

$_ = <>;
if (/AB.*BA/ || /BA.*AB/) {
	print 'YES';
} else {
	print 'NO';
}

$_=<>;
print qw/NO YES/[ /AB.*BA/ or /BA.*AB/ ]


Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string $$$s = s_1 s_2 \dots s_n$$$ of length $$$n$$$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.In a move, a player must choose an index $$$i$$$ ($$$1 \leq i \leq n$$$) that has not been chosen before, and change $$$s_i$$$ to any other lowercase English letter $$$c$$$ that $$$c \neq s_i$$$.When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Description of the test cases follows. The only line of each test case contains a single string $$$s$$$ ($$$1 \leq |s| \leq 50$$$) consisting of lowercase English letters.

For each test case, print the final string in a single line.

NoteIn the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'.


The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 × 2 square, such that from the four letters of this square you can make word "face". You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.

The first line contains two space-separated integers, n and m (1 ≤ n, m ≤ 50) — the height and the width of the image, respectively. Next n lines define the image. Each line contains m lowercase Latin letters.

In the single line print the number of faces on the image.

NoteIn the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column:   In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.In the third sample two faces are shown:   In the fourth sample the image has no faces on it.


You are given a binary string $$$s$$$ (recall that a string is binary if each character is either $$$0$$$ or $$$1$$$).Let $$$f(t)$$$ be the decimal representation of integer $$$t$$$ written in binary form (possibly with leading zeroes). For example $$$f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$$$ and $$$f(000100) = 4$$$.The substring $$$s_{l}, s_{l+1}, \dots , s_{r}$$$ is good if $$$r - l + 1 = f(s_l \dots s_r)$$$.For example string $$$s = 1011$$$ has $$$5$$$ good substrings: $$$s_1 \dots s_1 = 1$$$, $$$s_3 \dots s_3 = 1$$$, $$$s_4 \dots s_4 = 1$$$, $$$s_1 \dots s_2 = 10$$$ and $$$s_2 \dots s_4 = 011$$$. Your task is to calculate the number of good substrings of string $$$s$$$.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. The only line of each query contains string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$), consisting of only digits $$$0$$$ and $$$1$$$. It is guaranteed that $$$\sum\limits_{i=1}^{t} |s_i| \le 2 \cdot 10^5$$$.

For each query print one integer — the number of good substrings of string $$$s$$$.


A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you:  choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively),  swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously?

The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones.

Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case.

NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	@_ = map ~~<>, 1 .. $_;
	chomp @_;

	my $odd = grep { ( length ) % 2 } @_;

	if( $odd ){
		print ~~ @_;
		}
	else{
		my $ones = () = "@_" =~ /1/g;
		if( $ones % 2 ){
			print @_ - 1;
			}
		else{
			print ~~ @_;
			}
		}
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	@_ = map ~~<>, 1 .. $_;
	chomp @_;

	my( $odd ) = grep { ( length ) % 2 } @_;

	if( $odd ){
		print ~~ @_;
		}
	else{
		my $ones = () = "@_" =~ /1/g;
		if( $ones % 2 ){
			print @_ - 1;
			}
		else{
			print ~~ @_;
			}
		}
	}


Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by $$$2$$$ but the number itself is not divisible by $$$2$$$. For example, $$$13$$$, $$$1227$$$, $$$185217$$$ are ebne numbers, while $$$12$$$, $$$2$$$, $$$177013$$$, $$$265918$$$ are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer $$$s$$$, consisting of $$$n$$$ digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between $$$0$$$ (do not delete any digits at all) and $$$n-1$$$.For example, if you are given $$$s=$$$222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 $$$\rightarrow$$$ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to $$$70$$$ and is divisible by $$$2$$$, but number itself is not divisible by $$$2$$$: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 3000$$$)  — the number of digits in the original number. The second line of each test case contains a non-negative integer number $$$s$$$, consisting of $$$n$$$ digits. It is guaranteed that $$$s$$$ does not contain leading zeros and the sum of $$$n$$$ over all test cases does not exceed $$$3000$$$.

For each test case given in the input print the answer in the following format:  If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.

NoteIn the first test case of the example, $$$1227$$$ is already an ebne number (as $$$1 + 2 + 2 + 7 = 12$$$, $$$12$$$ is divisible by $$$2$$$, while in the same time, $$$1227$$$ is not divisible by $$$2$$$) so we don't need to delete any digits. Answers such as $$$127$$$ and $$$17$$$ will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, $$$1$$$ digit such as $$$17703$$$, $$$77013$$$ or $$$17013$$$. Answers such as $$$1701$$$ or $$$770$$$ will not be accepted as they are not ebne numbers. Answer $$$013$$$ will not be accepted as it contains leading zeroes.Explanation: $$$1 + 7 + 7 + 0 + 3 = 18$$$. As $$$18$$$ is divisible by $$$2$$$ while $$$17703$$$ is not divisible by $$$2$$$, we can see that $$$17703$$$ is an ebne number. Same with $$$77013$$$ and $$$17013$$$; $$$1 + 7 + 0 + 1 = 9$$$. Because $$$9$$$ is not divisible by $$$2$$$, $$$1701$$$ is not an ebne number; $$$7 + 7 + 0 = 14$$$. This time, $$$14$$$ is divisible by $$$2$$$ but $$$770$$$ is also divisible by $$$2$$$, therefore, $$$770$$$ is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 $$$\rightarrow$$$ 22237320442418521717191 (delete the last digit).


You play your favourite game yet another time. You chose the character you didn't play before. It has $$$str$$$ points of strength and $$$int$$$ points of intelligence. Also, at start, the character has $$$exp$$$ free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by $$$1$$$ or raise intelligence by $$$1$$$).Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$T$$$ lines contain descriptions of queries — one per line. This line contains three integers $$$str$$$, $$$int$$$ and $$$exp$$$ ($$$1 \le str, int \le 10^8$$$, $$$0 \le exp \le 10^8$$$) — the initial strength and intelligence of the character and the number of free points, respectively.

Print $$$T$$$ integers — one per query. For each query print the number of different character builds you can create.

NoteIn the first query there are only three appropriate character builds: $$$(str = 7, int = 5)$$$, $$$(8, 4)$$$ and $$$(9, 3)$$$. All other builds are either too smart or don't use all free points.In the second query there is only one possible build: $$$(2, 1)$$$.In the third query there are two appropriate builds: $$$(7, 6)$$$, $$$(8, 5)$$$.In the fourth query all builds have too much brains.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	my( $str, $int, $exp ) = split;

	$str += $exp;

	print $str > $int ? +( sort { $a <=> $b } $exp + 1, $str - $int + 1 >> 1 )[ 0 ] : 0;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	my( $str, $int, $exp ) = split;

	$str += $exp;

	print +( $str - $int + 1 ) >> 1;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	my( $str, $int, $exp ) = split;

	$str += $exp;

	print $str > $int ? $str - $int + 1 >> 1 : 0;
	}


Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers.During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct.You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not.

The first line of the input contains integer n (1 ≤ n ≤ 100) — the number of the players. Then follow n lines, each line describes a player's card. The line that describes a card starts from integer mi (1 ≤ mi ≤ 100) that shows how many numbers the i-th player's card has. Then follows a sequence of integers ai, 1, ai, 2, ..., ai, mi (1 ≤ ai, k ≤ 100) — the numbers on the i-th player's card. The numbers in the lines are separated by single spaces. It is guaranteed that all the numbers on each card are distinct.

Print n lines, the i-th line must contain word "YES" (without the quotes), if the i-th player can win, and "NO" (without the quotes) otherwise.

my $n = <>;

# my @m = split " ", scalar <>;

my @A = map {my @tmp = split " "; shift (@tmp) == @tmp or die "???"; [@tmp];} <>;

# (scalar @A) == (scalar @m) or die ((scalar @A) . ' ' . (scalar @m));

my @B = map{
    my @tmp = ();
    $tmp[100] = undef;
    @tmp[@$_] = (1) x @$_;
    \@tmp;
    } @A;

foreach my $curr (@B){
    my $good = 2;
    foreach my $chk (@A){
        # continue if $_ == $curr;
        $good-- unless grep {not $_} @$curr[@$chk];
        }
    print $good > 0 ? "YES\n" : "NO\n";
    }
1;

$n = <>;
@A = map {@tmp = split " "; shift (@tmp) == @tmp or die "???"; [@tmp];} <>;

@B = map{
    @tmp = ();
    $tmp[100] = undef;
    @tmp[@$_] = (1) x @$_;
    \@tmp;
    } @A;

foreach $curr (@B){
    $good = 2;
    foreach $chk (@A){
        $good-- unless grep {not $_} @$curr[@$chk];
        }
    print $good > 0 ? "YES\n" : "NO\n";
    }


The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vector is 1 or  - 1 and any two vectors are orthogonal. Just as a reminder, two vectors in n-dimensional space are considered to be orthogonal if and only if their scalar product is equal to zero, that is: .Danil quickly managed to come up with the solution for this problem and the teacher noticed that the problem can be solved in a more general case for 2k vectors in 2k-dimensinoal space. When Danil came home, he quickly came up with the solution for this problem. Can you cope with it?

The only line of the input contains a single integer k (0 ≤ k ≤ 9).

Print 2k lines consisting of 2k characters each. The j-th character of the i-th line must be equal to ' * ' if the j-th coordinate of the i-th vector is equal to  - 1, and must be equal to ' + ' if it's equal to  + 1. It's guaranteed that the answer always exists. If there are many correct answers, print any.

NoteConsider all scalar products in example:  Vectors 1 and 2: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( + 1) + ( - 1)·( - 1) = 0  Vectors 1 and 3: ( + 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) + ( - 1)·( + 1) = 0  Vectors 1 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( - 1) + ( - 1)·( + 1) = 0  Vectors 2 and 3: ( + 1)·( + 1) + ( - 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) = 0  Vectors 2 and 4: ( + 1)·( + 1) + ( - 1)·( - 1) + ( + 1)·( - 1) + ( - 1)·( + 1) = 0  Vectors 3 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( + 1)·( - 1) + ( + 1)·( + 1) = 0

use feature ':all';

while(<>){
	@_ = ('+');
	/0/ and say "@_" and next;
	for $i (1 .. $_){
		@new = ();
		for $line (@_){
			@syms = split //, $line;
			$doubled = '';
			for $k (@syms){ $doubled .= $k . $k };
			$mixed = '';
			for $k (@syms){ $mixed .= $k . ($k eq '+' ? '*' : '+') };
			push @new, $doubled, $mixed;
			}
		@_ = @new;
		}
	say join "\n", @_;
	}


You are standing at the point $$$0$$$ on a coordinate line. Your goal is to reach the point $$$n$$$. In one minute, you can move by $$$2$$$ or by $$$3$$$ to the left or to the right (i. e., if your current coordinate is $$$x$$$, it can become $$$x-3$$$, $$$x-2$$$, $$$x+2$$$ or $$$x+3$$$). Note that the new coordinate can become negative.Your task is to find the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$.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$$$ lines describing the test cases follow. The $$$i$$$-th of these lines contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the goal of the $$$i$$$-th test case.

For each test case, print one integer — the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$ for the corresponding test case.


XXI Berland Annual Fair is coming really soon! Traditionally fair consists of $$$n$$$ booths, arranged in a circle. The booths are numbered $$$1$$$ through $$$n$$$ clockwise with $$$n$$$ being adjacent to $$$1$$$. The $$$i$$$-th booths sells some candies for the price of $$$a_i$$$ burles per item. Each booth has an unlimited supply of candies.Polycarp has decided to spend at most $$$T$$$ burles at the fair. However, he has some plan in mind for his path across the booths:  at first, he visits booth number $$$1$$$;  if he has enough burles to buy exactly one candy from the current booth, then he buys it immediately;  then he proceeds to the next booth in the clockwise order (regardless of if he bought a candy or not). Polycarp's money is finite, thus the process will end once he can no longer buy candy at any booth.Calculate the number of candies Polycarp will buy.

The first line contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le T \le 10^{18}$$$) — the number of booths at the fair and the initial amount of burles Polycarp has. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the price of the single candy at booth number $$$i$$$.

Print a single integer — the total number of candies Polycarp will buy.

NoteLet's consider the first example. Here are Polycarp's moves until he runs out of money:  Booth $$$1$$$, buys candy for $$$5$$$, $$$T = 33$$$;  Booth $$$2$$$, buys candy for $$$2$$$, $$$T = 31$$$;  Booth $$$3$$$, buys candy for $$$5$$$, $$$T = 26$$$;  Booth $$$1$$$, buys candy for $$$5$$$, $$$T = 21$$$;  Booth $$$2$$$, buys candy for $$$2$$$, $$$T = 19$$$;  Booth $$$3$$$, buys candy for $$$5$$$, $$$T = 14$$$;  Booth $$$1$$$, buys candy for $$$5$$$, $$$T = 9$$$;  Booth $$$2$$$, buys candy for $$$2$$$, $$$T = 7$$$;  Booth $$$3$$$, buys candy for $$$5$$$, $$$T = 2$$$;  Booth $$$1$$$, buys no candy, not enough money;  Booth $$$2$$$, buys candy for $$$2$$$, $$$T = 0$$$. No candy can be bought later. The total number of candies bought is $$$10$$$.In the second example he has $$$1$$$ burle left at the end of his path, no candy can be bought with this amount.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $n, $t ) = split;

	@_ = split ' ', <>;

	my $sum = 0;

	$sum += $_ for @_;

	my $cnt = 0;

	my $i = 0;

	while( @_ ){
		if( 0 < int $t / $sum ){
			$cnt += @_ * ( int $t / $sum );
			$t -= $sum * ( int $t / $sum );
			}
		my $this = shift @_;
		if( $this > $t ){
			$sum -= $this;
			next;
			}
		else{
			$t -= $this;
			$cnt ++;
			push @_, $this;
			next;
			}
		}

	print $cnt;
	}


It's a walking tour day in SIS.Winter, so $$$t$$$ groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":   "A" corresponds to an angry student  "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index $$$i$$$ in the string describing a group then they will throw a snowball at the student that corresponds to the character with index $$$i+1$$$ (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.

The first line contains a single integer $$$t$$$ — the number of groups of students ($$$1 \le t \le 100$$$). The following $$$2t$$$ lines contain descriptions of groups of students. The description of the group starts with an integer $$$k_i$$$ ($$$1 \le k_i \le 100$$$) — the number of students in the group, followed by a string $$$s_i$$$, consisting of $$$k_i$$$ letters "A" and "P", which describes the $$$i$$$-th group of students.

For every group output single integer — the last moment a student becomes angry.

NoteIn the first test, after $$$1$$$ minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is:   after $$$1$$$ minute — AAPAAPPAAPPP  after $$$2$$$ minutes — AAAAAAPAAAPP  after $$$3$$$ minutes — AAAAAAAAAAAP  after $$$4$$$ minutes all $$$12$$$ students are angry In the second group after $$$1$$$ minute, all students are angry.

#!/usr/bin/env perl
package Codeforces::Task::A;
use v5.10;
use strict;
use warnings;

#    int ans = 0, cur = -1e5;
#    for (char c : $s) {
#        if (c == 'A') {ans = max(ans, cur);cur = 0;}else {++cur;}
#    }
#    answer(max(ans,cur));

sub solve {
    my ($ans, $n) = (0, int(<>));
    my @s = split("", <>);
    my $p = $n - 1;
    for (my $i = $n - 1; $i > -1; $i--) {
        if ($s[$i] eq "A") {
            if ($ans < $p - $i)
                { $ans = $p - $i; }
            $p = $i - 1;
		}
	}
    print "$ans\n";
}

sub main {
    my $t = 1;
    $t = int(<>);
    while ($t--) {
        solve();
    }
    return 0;
}

exit(main());

#!/usr/bin/env perl
package Codeforces::Task::A;
use v5.10;
use strict;
use warnings;

sub solve {
    my ($ans, $n) = (0, int(<>));
    my @s = split("", <>);
    my $p = $n - 1;
    for (my $i = $n - 1; $i > -1; $i--) {
        if ($s[$i] eq "A") {
            if ($ans < $p - $i)
                { $ans = $p - $i; }
            $p = $i - 1;
		}
	}
    print "$ans\n";
}

sub main {
    my $t = 1;
    $t = int(<>);
    while ($t--) {
        solve();
    }
    return 0;
}

exit(main());

use strict;
use warnings;

use Data::Dumper;

sub main {

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

    while($q > 0) {
        $q--;
        my $s= <$in>;
        my $z= <$in>;
        my @l= split('', $z);

        my $i= -1;
        for my $stud (@l) {
            last if($stud eq 'A');
            if($i==-1) {
                $i= 0;
            } else {
                $i++;
            }
        }

        $i++;

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

        my $c= 0;
        my $max= 0;
        for(my $j=$i; $j < $#l; $j++) {
            if($l[$j] eq 'A') {
                $c= 0;
            } else {
                $c++;
                if($max < $c) {
                    $max = $c;
                }
            }

        }

        print "$max\n";

    }

}

main() unless caller();

#!/usr/bin/env perl
package Codeforces::Task::A;
use v5.10;
use strict;
use warnings;

sub solve {
    my ($ans, $n) = (0, int(<>));
    my @s = split("", <>);
    my $f = 0;
    for (my $i = $n - 1; $i > -1; $i--) {
		if ($s[$i] eq 'A') {
            $f = 1;
		    last;
		}
        $ans++;
	}
	$ans *= $f;
    print "$ans\n";
}

sub main {
    my $t = 1;
    $t = int(<>);
    while ($t--) {
        solve();
    }
    return 0;
}

exit(main());

#!/usr/bin/env perl
package Codeforces::Task::A;
use v5.10;
use strict;
use warnings;

sub solve {
    my ($ans, $n) = (0, int(<>));
    my @s = split("", <>);
    for (my $i = $n - 1; $i > -1; $i--) {
		if ($s[$i] eq 'A') {
		    last;
		}
        $ans++;
	}
    print "$ans\n";
}

sub main {
    my $t = 1;
    $t = int(<>);
    while ($t--) {
        solve();
    }
    return 0;
}

exit(main());

#!/usr/bin/env perl
package Codeforces::Task::A;
use v5.10;
use strict;
use warnings;

#    int ans = 0, cur = -1e5;
#    for (char c : $s) {
#        if (c == 'A') {ans = max(ans, cur);cur = 0;}else {++cur;}
#    }
#    answer(max(ans,cur));

sub solve {
    my ($ans, $n) = (0, int(<>));
    my @s = split("", <>);
    push(@s, "A");
    my $p = $n - 1;
    for (my $i = $n - 1; $i > -1; $i--) {
        if ($s[$i] eq "A") {
            if ($ans < $p - $i)
                { $ans = $p - $i; }
            $p = $i;
		}
	}
    print "$ans\n";
}

sub main {
    my $t = 1;
    $t = int(<>);
    while ($t--) {
        solve();
    }
    return 0;
}

exit(main());


Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.

The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.

In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.

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

my ($n, $k) = map int, split '\D', <>;
my $p = 0;
for my $i (1..$n) {
  my ($f, $t) = map int, split '\D', <>;
  my $np = ($k < $t)? $f - $t + $k: $f;
  if ( ($i == 1) || ($p < $np) ) {
    $p = $np;
  }
}
print $p;


There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?Formally, we assume that two words denote the same name, if using the replacements "u"  "oo" and "h"  "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.For example, the following pairs of words denote the same name:  "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper"  "kuuper" and "kuooper"  "kuuper".  "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun"  "khoon" and "kkkhoon"  "kkhoon"  "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name.

The first line contains integer number n (2 ≤ n ≤ 400) — number of the words in the list. The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.

Print the minimal number of groups where the words in each group denote the same name.

10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon

9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi

NoteThere are four groups of words in the first example. Words in each group denote same name:  "mihail", "mikhail"  "oolyana", "ulyana"  "kooooper", "koouper"  "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name:  "hariton", "kkkhariton", "khariton"  "hkariton"  "buoi", "boooi", "boui"  "bui"  "boi" In the third example the words are equal, so they denote the same name.


You are given the strings $$$a$$$ and $$$b$$$, consisting of lowercase Latin letters. You can do any number of the following operations in any order:   if $$$|a| > 0$$$ (the length of the string $$$a$$$ is greater than zero), delete the first character of the string $$$a$$$, that is, replace $$$a$$$ with $$$a_2 a_3 \ldots a_n$$$;  if $$$|a| > 0$$$, delete the last character of the string $$$a$$$, that is, replace $$$a$$$ with $$$a_1 a_2 \ldots a_{n-1}$$$;  if $$$|b| > 0$$$ (the length of the string $$$b$$$ is greater than zero), delete the first character of the string $$$b$$$, that is, replace $$$b$$$ with $$$b_2 b_3 \ldots b_n$$$;  if $$$|b| > 0$$$, delete the last character of the string $$$b$$$, that is, replace $$$b$$$ with $$$b_1 b_2 \ldots b_{n-1}$$$. Note that after each of the operations, the string $$$a$$$ or $$$b$$$ may become empty.For example, if $$$a=$$$"hello" and $$$b=$$$"icpc", then you can apply the following sequence of operations:   delete the first character of the string $$$a$$$ $$$\Rightarrow$$$ $$$a=$$$"ello" and $$$b=$$$"icpc";  delete the first character of the string $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$"ello" and $$$b=$$$"cpc";  delete the first character of the string $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$"ello" and $$$b=$$$"pc";  delete the last character of the string $$$a$$$ $$$\Rightarrow$$$ $$$a=$$$"ell" and $$$b=$$$"pc";  delete the last character of the string $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$"ell" and $$$b=$$$"p". For the given strings $$$a$$$ and $$$b$$$, find the minimum number of operations for which you can make the strings $$$a$$$ and $$$b$$$ equal. Note that empty strings are also equal.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains the string $$$a$$$ ($$$1 \le |a| \le 20$$$), consisting of lowercase Latin letters. The second line of each test case contains the string $$$b$$$ ($$$1 \le |b| \le 20$$$), consisting of lowercase Latin letters.

For each test case, output the minimum number of operations that can make the strings $$$a$$$ and $$$b$$$ equal.

5
a
a
abcd
bc
hello
codeforces
hello
helo
dhjakjsnasjhfksafasd
adjsnasjhfksvdafdser

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	$_ .= <>;

	my $max_len = 0;

	m/
		(.*) .*
		\n
		.* \1
		(?{
			$max_len < length $1 and $max_len = length $1;
			})
		(*FAIL)
		/x;

	print +( length ) - 2 - $max_len * 2;
	}


Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.

The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.

Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;
my $debug = 0;

while(<>){

	my %h;

	for my $i (2 .. $_){
		my( $u, $v ) = split ' ', <>;

		$h{ $u }{ v }{ $v } ++;
		$h{ $v }{ v }{ $u } ++;
		}

	my $i = 0;
	map { $i ++; $h{ $i }{ c } = $_ } split ' ', <>;

	my @sorted = grep { keys %{ $h{ $_ }{ v } } == 1 }
		sort { keys %{ $h{ $a }{ v } } <=> keys %{ $h{ $b }{ v } } } keys %h;
	$debug and print "@sorted";

	my $i;

	while( @sorted ){
		$i = shift @sorted;
		my( $key ) = keys %{ $h{ $i }{ v } };
		if( $h{ $i }{ c } != $h{ $key }{ c } ){
			next;
			}

		delete $h{ $key }{ v }{ $i };
		keys %{ $h{ $key }{ v } } == 1 and unshift @sorted, $key;
		delete $h{ $i }{ v };
		}

	$debug and print "keys: ", map { ~~ keys %{ $h{ $_ }{ v } } } keys %h;
	my @g = grep $_ > 1, map { ~~ keys %{ $h{ $_ }{ v } } } keys %h;
	$debug and print "[@sorted]";

	if( @g > 1 ){
		print "NO";
		}
	elsif( @g == 0 ){
		print "YES";
		print $i;
		}
	else{
		print "YES";
		my $j;
		for my $k (keys %h){
			keys %{ $h{ $k }{ v } } > 1 and $j = $k;
			}
		print $j;
		}
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;
my $debug = 0;

while(<>){

	my %h;

	for my $i (2 .. $_){
		my( $u, $v ) = split ' ', <>;

		$h{ $u }{ v }{ $v } ++;
		$h{ $v }{ v }{ $u } ++;
		}

	my $i = 0;
	map { $i ++; $h{ $i }{ c } = $_ } split ' ', <>;

	my @sorted = grep { keys %{ $h{ $_ }{ v } } == 1 }
		sort { keys %{ $h{ $a }{ v } } <=> keys %{ $h{ $b }{ v } } } keys %h;
	$debug and print "@sorted";

	while( @sorted ){
		my $i = shift @sorted;
		my( $key ) = keys %{ $h{ $i }{ v } };
		if( $h{ $i }{ c } != $h{ $key }{ c } ){
			next;
			}

		delete $h{ $key }{ v }{ $i };
		keys %{ $h{ $key }{ v } } == 1 and unshift @sorted, $key;
		delete $h{ $i }{ v };
		}

	$debug and print "keys: ", map { ~~ keys %{ $h{ $_ }{ v } } } keys %h;
	my @g = grep $_ > 1, map { ~~ keys %{ $h{ $_ }{ v } } } keys %h;
	$debug and print "[@sorted]";

	if( @g > 1 ){
		print "NO";
		}
	elsif( @g == 0 ){
		print "YES";
		print 1;
		}
	else{
		print "YES";
		my $j;
		for my $k (keys %h){
			keys %{ $h{ $k }{ v } } > 1 and $j = $k;
			}
		print $j;
		}
	}


Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li.You are given lengths of the claws. You need to find the total number of alive people after the bell rings.

The first line contains one integer n (1 ≤ n ≤ 106) — the number of guilty people. Second line contains n space-separated integers L1, L2, ..., Ln (0 ≤ Li ≤ 109), where Li is the length of the i-th person's claw.

Print one integer — the total number of alive people after the bell rings.

NoteIn first sample the last person kills everyone in front of him.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my $knife = 0;
	my $alive = 0;

	for my $i ( reverse 0 .. @_ - 1 ){
		$knife --;
		$knife < 0 and $alive ++;
		$_[ $i ] > $knife and $knife = $_[ $i ];
		}

	print $alive;
	}


There is a robot staying at $$$X=0$$$ on the $$$Ox$$$ axis. He has to walk to $$$X=n$$$. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.The $$$i$$$-th segment of the path (from $$$X=i-1$$$ to $$$X=i$$$) can be exposed to sunlight or not. The array $$$s$$$ denotes which segments are exposed to sunlight: if segment $$$i$$$ is exposed, then $$$s_i = 1$$$, otherwise $$$s_i = 0$$$.The robot has one battery of capacity $$$b$$$ and one accumulator of capacity $$$a$$$. For each segment, you should choose which type of energy storage robot will use to go to the next point (it can be either battery or accumulator). If the robot goes using the battery, the current charge of the battery is decreased by one (the robot can't use the battery if its charge is zero). And if the robot goes using the accumulator, the current charge of the accumulator is decreased by one (and the robot also can't use the accumulator if its charge is zero).If the current segment is exposed to sunlight and the robot goes through it using the battery, the charge of the accumulator increases by one (of course, its charge can't become higher than it's maximum capacity).If accumulator is used to pass some segment, its charge decreases by 1 no matter if the segment is exposed or not.You understand that it is not always possible to walk to $$$X=n$$$. You want your robot to go as far as possible. Find the maximum number of segments of distance the robot can pass if you control him optimally.

The first line of the input contains three integers $$$n, b, a$$$ ($$$1 \le n, b, a \le 2 \cdot 10^5$$$) — the robot's destination point, the battery capacity and the accumulator capacity, respectively. The second line of the input contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$0 \le s_i \le 1$$$), where $$$s_i$$$ is $$$1$$$ if the $$$i$$$-th segment of distance is exposed to sunlight, and $$$0$$$ otherwise.

Print one integer — the maximum number of segments the robot can pass if you control him optimally.

NoteIn the first example the robot can go through the first segment using the accumulator, and charge levels become $$$b=2$$$ and $$$a=0$$$. The second segment can be passed using the battery, and charge levels become $$$b=1$$$ and $$$a=1$$$. The third segment can be passed using the accumulator, and charge levels become $$$b=1$$$ and $$$a=0$$$. The fourth segment can be passed using the battery, and charge levels become $$$b=0$$$ and $$$a=1$$$. And the fifth segment can be passed using the accumulator.In the second example the robot can go through the maximum number of segments using battery two times and accumulator one time in any order.

#use v5.24;
use warnings;
my $line=<stdin>;
chomp($line);
my($n,$b,$amax)=split(/ /,$line);
$line=<stdin>;
chomp($line);
my @v=split(/ /,$line);
my $a=$amax,$i=0;
BUCLA: while (($b>0 || $a>0) && $i<$n){
#	print $b.' '.$a."\n";
	my $tip=$v[$i];
	if ($tip==0){
		if ($a>0) {$a--;}
		else {$b--;}
		$i++;
	}
	else{
		if ($a==0) {$b--;$a++;$i++;next BUCLA;}
		if ($b==0) {$a--;$i++;next BUCLA;}
		if ($a<$amax) {$b--;$a++;$i++;next BUCLA;}
		else {$a--;$i++;next BUCLA;}
	}
}
print $i;
#<stdin>;
exit(0);


Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows:  You have to write a program that allows you to determine what number will be in the cell with index x (1 ≤ x ≤ n) after Dima's algorithm finishes.

The first line contains two integers n and q (1 ≤ n ≤ 1018, 1 ≤ q ≤ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer. Next q lines contain integers xi (1 ≤ xi ≤ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes.

For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes.

NoteThe first example is shown in the picture.In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7].


There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one.  At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints.

The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists.

Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them.

NoteThe first test sample is the one in the picture.


Nastia has received an array of $$$n$$$ positive integers as a gift.She calls such an array $$$a$$$ good that for all $$$i$$$ ($$$2 \le i \le n$$$) takes place $$$gcd(a_{i - 1}, a_{i}) = 1$$$, where $$$gcd(u, v)$$$ denotes the greatest common divisor (GCD) of integers $$$u$$$ and $$$v$$$.You can perform the operation: select two different indices $$$i, j$$$ ($$$1 \le i, j \le n$$$, $$$i \neq j$$$) and two integers $$$x, y$$$ ($$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$. Then change $$$a_i$$$ to $$$x$$$ and $$$a_j$$$ to $$$y$$$.The girl asks you to make the array good using at most $$$n$$$ operations.It can be proven that this is always possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array. 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 array which Nastia has received as a gift. It's guaranteed that the sum of $$$n$$$ in one test doesn't exceed $$$2 \cdot 10^5$$$.

For each of $$$t$$$ test cases print a single integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of operations. You don't need to minimize this number. In each of the next $$$k$$$ lines print $$$4$$$ integers $$$i$$$, $$$j$$$, $$$x$$$, $$$y$$$ ($$$1 \le i \neq j \le n$$$, $$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$ — in this manner you replace $$$a_i$$$ with $$$x$$$ and $$$a_j$$$ with $$$y$$$. If there are multiple answers, print any.

NoteConsider the first test case.Initially $$$a = [9, 6, 3, 11, 15]$$$.In the first operation replace $$$a_1$$$ with $$$11$$$ and $$$a_5$$$ with $$$9$$$. It's valid, because $$$\min{(a_1, a_5)} = \min{(11, 9)} = 9$$$.After this $$$a = [11, 6, 3, 11, 9]$$$.In the second operation replace $$$a_2$$$ with $$$7$$$ and $$$a_5$$$ with $$$6$$$. It's valid, because $$$\min{(a_2, a_5)} = \min{(7, 6)} = 6$$$.After this $$$a = [11, 7, 3, 11, 6]$$$ — a good array.In the second test case, the initial array is already good.


This is an interactive problem.Alice and Bob are playing a game. There is $$$n\times n$$$ grid, initially empty. We refer to the cell in row $$$i$$$ and column $$$j$$$ by $$$(i, j)$$$ for $$$1\le i, j\le n$$$. There is an infinite supply of tokens that come in $$$3$$$ colors labelled $$$1$$$, $$$2$$$, and $$$3$$$.The game proceeds with turns as follows. Each turn begins with Alice naming one of the three colors, let's call it $$$a$$$. Then, Bob chooses a color $$$b\ne a$$$, chooses an empty cell, and places a token of color $$$b$$$ on that cell.We say that there is a conflict if there exist two adjacent cells containing tokens of the same color. Two cells are considered adjacent if they share a common edge.If at any moment there is a conflict, Alice wins. Otherwise, if $$$n^2$$$ turns are completed (so that the grid becomes full) without any conflicts, Bob wins.We have a proof that Bob has a winning strategy. Play the game as Bob and win.The interactor is adaptive. That is, Alice's color choices can depend on Bob's previous moves.

NoteThe final grid from the sample is pictured below. Bob wins because there are no two adjacent cells with tokens of the same color. $$$$$$\begin{matrix}2&3\\3&1\end{matrix}$$$$$$The sample is only given to demonstrate the input and output format. It is not guaranteed to represent an optimal strategy for Bob or the real behavior of the interactor.


You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:  Write parity(a) to the end of a. For example, .  Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.

The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.

Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.

NoteIn the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110


There are $$$n$$$ pillars aligned in a row and numbered from $$$1$$$ to $$$n$$$.Initially each pillar contains exactly one disk. The $$$i$$$-th pillar contains a disk having radius $$$a_i$$$.You can move these disks from one pillar to another. You can take a disk from pillar $$$i$$$ and place it on top of pillar $$$j$$$ if all these conditions are met:  there is no other pillar between pillars $$$i$$$ and $$$j$$$. Formally, it means that $$$|i - j| = 1$$$;  pillar $$$i$$$ contains exactly one disk;  either pillar $$$j$$$ contains no disks, or the topmost disk on pillar $$$j$$$ has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all $$$n$$$ disks on the same pillar simultaneously?

The first line contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of pillars. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_i$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the radius of the disk initially placed on the $$$i$$$-th pillar. All numbers $$$a_i$$$ are distinct.

Print YES if it is possible to place all the disks on the same pillar simultaneously, and NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

NoteIn the first case it is possible to place all disks on pillar $$$3$$$ using the following sequence of actions:  take the disk with radius $$$3$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$;  take the disk with radius $$$1$$$ from pillar $$$1$$$ and place it on top of pillar $$$2$$$;  take the disk with radius $$$2$$$ from pillar $$$4$$$ and place it on top of pillar $$$3$$$;  take the disk with radius $$$1$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my $max = ( sort { $b <=> $a } @_ )[ 0 ];

	my $idx;

	for my $i ( 0 .. @_ - 1 ){
		$max == $_[ $i ] and $idx = $i;
		}

	my @up;

	push @up, [ @_[ 0 .. $idx ] ];
	push @up, [ reverse @_[ $idx .. @_ - 1 ] ];

	my $ok = 1;

	for my $ref ( @up ){
		my @arr = @{ $ref };
		for my $i ( 0 .. @arr - 2 ){
			$ok &&= $arr[ $i ] < $arr[ $i + 1 ];
			}
		}

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