Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this angle. As you spend lots of time "glued to the screen", your vision is impaired. So you have to write a program that will pass the check for you.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of mannequins. Next n lines contain two space-separated integers each: xi, yi (|xi|, |yi| ≤ 1000) — the coordinates of the i-th mannequin. It is guaranteed that the origin of the coordinates has no mannequin. It is guaranteed that no two mannequins are located in the same point on the plane.

Print a single real number — the value of the sought angle in degrees. The answer will be considered valid if the relative or absolute error doesn't exceed 10 - 6.

NoteSolution for the first sample test is shown below:   Solution for the second sample test is shown below:   Solution for the third sample test is shown below:   Solution for the fourth sample test is shown below:

#!/usr/bin/perl -w

use strict;
use List::Util qw(max);
use constant PI => atan2 0, -1;
use constant EPS => 1e-8;

chomp(my $n = <>);
my @p = ();
for (1 .. $n) {
    chomp($_ = <>);
    my ($x, $y) = split;
    push @p, atan2 $y, $x;
}
@p = sort { $a <=> $b } @p;
push @p, $p[0];

my $res = 0.0;
for my $i (1 .. $n) {
    my $diff = $p[$i] - $p[$i - 1];
    $diff += 2 * PI if $diff < - EPS;
    $res = max($res, $diff);
}
$res = 2 * PI if $res < EPS;
$res = 360.0 - $res * 180.0 / PI;
print "$res\n";

#!/usr/bin/perl -w

use strict;
use List::Util qw(max);
use constant PI => atan2 0, -1;
use constant EPS => 1e-8;

chomp(my $n = <>);
my @p = ();
for (1 .. $n) {
    chomp($_ = <>);
    my ($x, $y) = split;
    my $a = atan2 $y, $x;
    push @p, [$x, $y, $a];
}
@p = sort { $$a[2] <=> $$b[2] } @p;
push @p, $p[0];

my $res = 0.0;
for my $i (1 .. $n) {
    my $diff = $p[$i][2] - $p[$i - 1][2];
    $diff += 2 * PI if $diff < EPS;
    $res = max($res, $diff);
}
$res = 360.0 - $res * 180.0 / PI;
print "$res\n";

#!/usr/bin/perl -w

use strict;
use List::Util qw(max);
use constant PI => atan2 0, -1;
use constant EPS => 1e-8;

chomp(my $n = <>);
my @p = ();
for (1 .. $n) {
    chomp($_ = <>);
    my ($x, $y) = split;
    my $a = atan2 $y, $x;
    push @p, [$x, $y, $a];
}
@p = sort { $$a[2] <=> $$b[2] } @p;
push @p, $p[0];

my $res = 0.0;
for my $i (1 .. $n) {
    my $diff = $p[$i][2] - $p[$i - 1][2];
    $diff += 2 * PI if $diff < - EPS;
    $res = max($res, $diff);
}
$res = 360.0 - $res * 180.0 / PI;
print "$res\n";


As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task.

The first line contains two space-separated positive integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000) — the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 104) — the towers' initial heights.

In the first line print two space-separated non-negative integers s and m (m ≤ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i ≠ j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them.

NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6.


Ridbit starts with an integer $$$n$$$.In one move, he can perform one of the following operations:   divide $$$n$$$ by one of its proper divisors, or  subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. A proper divisor is a divisor of a number, excluding itself. For example, $$$1$$$, $$$2$$$, $$$4$$$, $$$5$$$, and $$$10$$$ are proper divisors of $$$20$$$, but $$$20$$$ itself is not.What is the minimum number of moves Ridbit is required to make to reduce $$$n$$$ to $$$1$$$?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^9$$$).

For each test case, output the minimum number of moves required to reduce $$$n$$$ to $$$1$$$.

NoteFor the test cases in the example, $$$n$$$ may be reduced to $$$1$$$ using the following operations in sequence$$$1$$$$$$2 \xrightarrow{} 1$$$$$$3 \xrightarrow{} 2 \xrightarrow{} 1$$$$$$4 \xrightarrow{} 2 \xrightarrow{} 1$$$$$$6 \xrightarrow{} 2 \xrightarrow{} 1$$$$$$9 \xrightarrow{} 3 \xrightarrow{} 2\xrightarrow{} 1$$$


Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a × b.After n - 1 steps there is only one number left. Can you make this number equal to 24?

The first line contains a single integer n (1 ≤ n ≤ 105).

If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes). If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces. If there are multiple valid answers, you may print any of them.


There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m — the smallest number of points you should add on the line to make the distances between all neighboring points equal.

The first line contains a single integer n (3 ≤ n ≤ 100 000) — the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≤ xi ≤ 109) — the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.

Print a single integer m — the smallest number of points you should add on the line to make the distances between all neighboring points equal.

NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.


Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!

The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.

Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.

welcome to the
Codeforces
Beta
Round 5

and
good luck

#!/bin/perl -w
use strict;
use warnings;
use List::Util qw{max};
use integer;

my @s;
my ($i,$l) = (0,0);
while ($s[$i] = <>) {
    chomp $s[$i++];
}
delete $s[$#s];
my $len = max map length, @s;
print '*' x ($len + 2), "\n";
for (@s) {
    print '*';
    my $s = $len - length $_;
    if ($s % 2) {
	print ' ' x ($s / 2 + $l), $_, ' ' x ($s / 2 + 1 - $l);
	$l = 1 - $l;
    } else {
	print ' ' x ($s / 2), $_, ' ' x ($s / 2);
    }
    print "*\n";
}
print '*' x ($len + 2), "\n";

#!/bin/perl -w
use strict;
use warnings;
use List::Util qw{max};
use integer;

my @s;
my ($i,$l) = (0,1);
while ($s[$i] = <>) {
    chomp $s[$i++];
}
delete $s[$#s];
my $len = max map length, @s;
print '*' x ($len + 2), "\n";
for (@s) {
    print '*';
    my $s = $len - length $_;
    if ($s % 2) {
	print ' ' x ($s / 2 + $l), $_, ' ' x ($s / 2 + 1 - $l);
	$l = 1 - $l;
    } else {
	print ' ' x ($s / 2), $_, ' ' x ($s / 2);
    }
    print "*\n";
}
print '*' x ($len + 2), "\n";


Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change.

The first line contains two space-separated integers n, s (1 ≤ n, s ≤ 100). The i-th of the next n lines contains two integers xi, yi (1 ≤ xi ≤ 100; 0 ≤ yi < 100), where xi represents the number of dollars and yi the number of cents needed in order to buy the i-th type of sugar.

Print a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.

NoteIn the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change.

#!perl

($n, $mony) = split / /, <>;

$mony1 = $mony - 1;
$flag = 0;
$maxResult = 0;

foreach my $i (1..$n)
{
    ($dolars, $cents) = split / /, <>;

    if(($dolars <= $mony1) or ($dolars == $mony and $cents == 0))
    {
        $result = 100 - $cents;
        $maxResult = $result if $result > $maxResult and $result < 100;

        $flag = 1;
    }
}

$\ = "\n";

if($flag == 1)
{
    print $maxResult;
}
else
{
    print -1;
}


Mihai plans to watch a movie. He only likes palindromic movies, so he wants to skip some (possibly zero) scenes to make the remaining parts of the movie palindromic.You are given a list $$$s$$$ of $$$n$$$ non-empty strings of length at most $$$3$$$, representing the scenes of Mihai's movie.A subsequence of $$$s$$$ is called awesome if it is non-empty and the concatenation of the strings in the subsequence, in order, is a palindrome.Can you help Mihai check if there is at least one awesome subsequence of $$$s$$$?A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.A sequence $$$a$$$ is a non-empty subsequence of a non-empty sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero, but not all) elements.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of scenes in the movie. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single non-empty string $$$s_i$$$ of length at most $$$3$$$, consisting of lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" if there is an awesome subsequence of $$$s$$$, or "NO" otherwise (case insensitive).

6

5

zx

ab

cc

zx

ba

2

ab

bad

4

co

def

orc

es

3

a

b

c

3

ab

cd

cba

2

ab

ab

NoteIn the first test case, an awesome subsequence of $$$s$$$ is $$$[ab, cc, ba]$$$

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	$_ = join '', map ~~<>, 1 .. $_;

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

	if( 0
		|| m/\b\w\b/
		|| m/\b(\w)\1\b/
		|| m/\b(\w)\w\1\b/
		){
		print 'YES';
		next;
		}

	my %h3;

	map $h3{ $_ } ++, m/\w\w\w/g;

	for my $key ( sort keys %h3 ){
		if( exists $h3{ scalar reverse $key } ){
			print 'YES';
			next MAIN;
			}
		}

	my %h2;
	my %h2L;
	my %h2R;

	m/\b\w\w\b(?{ push @{ $h2{ $& } }, $-[0] })(*FAIL)/gx;

	$debug and print "$_-->[@{ $h2{ $_ } }]" for sort keys %h2;

	m/\w(\w\w)(?{ $h2L{ scalar reverse $1 }   = $-[0] })(*FAIL)/gx;
	m!(\w\w)\w(?{ $h2R{ scalar reverse $1 } //= $-[0] })(*FAIL)!gx;

	$debug and print "L:$_-->$h2L{ $_ }" for sort keys %h2L;
	$debug and print "R:$_-->$h2R{ $_ }" for sort keys %h2R;

	for my $key ( sort keys %h2 ){

		if( exists $h2{ scalar reverse $key } ){
			print 'YES';
			next MAIN;
			}

		for my $i ( 0 .. @{ $h2{ $key } } - 1 ){

			if( exists $h2L{ $key } and $h2{ $key }[ $i ] < $h2L{ $key } ){
				print 'YES';
				next MAIN;
				}

			if( exists $h2R{ $key } and $h2{ $key }[ $i ] > $h2R{ $key } ){
				print 'YES';
				next MAIN;
				}

			}
		}

	print 'NO';
	}

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	$_ = join '', map ~~<>, 1 .. $_;

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

	if( 0
		|| m/\b\w\b/
		|| m/\b(\w)\1\b/
		|| m/\b(\w)\w\1\b/
		){
		print 'YES';
		next;
		}

	my %h3;

	map $h3{ $& } ++, m/\w\w\w/g;

	for my $key ( sort keys %h3 ){
		if( exists $h3{ scalar reverse $key } ){
			print 'YES';
			next MAIN;
			}
		}

	my %h2;
	my %h2L;
	my %h2R;

	m/\b\w\w\b(?{ push @{ $h2{ $& } }, $-[0] })(*FAIL)/gx;

	$debug and print "$_-->[@{ $h2{ $_ } }]" for sort keys %h2;

	m/\w(\w\w)(?{ $h2L{ scalar reverse $1 }   = $-[0] })(*FAIL)/gx;
	m!(\w\w)\w(?{ $h2R{ scalar reverse $1 } //= $-[0] })(*FAIL)!gx;

	$debug and print "L:$_-->$h2L{ $_ }" for sort keys %h2L;
	$debug and print "R:$_-->$h2R{ $_ }" for sort keys %h2R;

	for my $key ( sort keys %h2 ){

		if( exists $h2{ scalar reverse $key } ){
			print 'YES';
			next MAIN;
			}

		for my $i ( 0 .. @{ $h2{ $key } } - 1 ){

			if( exists $h2L{ $key } and $h2{ $key }[ $i ] < $h2L{ $key } ){
				print 'YES';
				next MAIN;
				}

			if( exists $h2R{ $key } and $h2{ $key }[ $i ] > $h2R{ $key } ){
				print 'YES';
				next MAIN;
				}

			}
		}

	print 'NO';
	}

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	$_ = join '', map ~~<>, 1 .. $_;

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

	if( 0
		|| m/\b\w\b/
		|| m/\b(\w)\1\b/
		|| m/\b(\w)\w\1\b/
		){
		print 'YES';
		next;
		}

	my %h3;

	map $h3{ $& } ++, m/\w\w\w/g;

	for my $key ( sort keys %h3 ){
		if( exists $h3{ scalar reverse $key } ){
			print 'YES';
			next MAIN;
			}
		}

	my %h2;
	my %h2L;
	my %h2R;

	m/\b\w\w\b(?{ push @{ $h2{ $& } }, $-[0] })(*FAIL)/gx;

	$debug and print "$_-->[@{ $h2{ $_ } }]" for sort keys %h2;

	m/\w(\w\w)(?{ $h2L{ scalar reverse $1 }   = $-[0] })(*FAIL)/gx;
	m!(\w\w)\w(?{ $h2R{ scalar reverse $1 } //= $-[0] })(*FAIL)!gx;

	$debug and print "L:$_-->$h2L{ $_ }" for sort keys %h2L;
	$debug and print "R:$_-->$h2R{ $_ }" for sort keys %h2R;

	for my $key ( sort keys %h2 ){
		for my $i ( 0 .. @{ $h2{ $key } } - 1 ){

			if( exists $h2L{ $key } and $h2{ $key }[ $i ] < $h2L{ $key } ){
				print 'YES';
				next MAIN;
				}

			if( exists $h2R{ $key } and $h2{ $key }[ $i ] > $h2R{ $key } ){
				print 'YES';
				next MAIN;
				}

			}
		}

	print 'NO';
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

MAIN:
while(<>){
	$_ = join '', map ~~<>, 1 .. $_;

	my %h;

	map $h{ $& } ++, m/\w\w\w/g;

	for my $key ( sort keys %h ){
		if( exists $h{ scalar reverse $key } ){
			print 'YES';
			next MAIN;
			}
		}

	my $_b;

	print qw( NO YES )[ 0 + (
		0
		|| m/\b\w\b/
		|| m/\b(\w)\1\b/
		|| m/\b(\w)\w\1\b/
		|| m/   \b(\w)(\w)
				( \b )?
				.*
				( \b )?
				\2\1\b
				(??{ '-' x ( ( defined $3 ) * ( defined $4 ) ) })
				/sx
		) ];
	}

#!/usr/bin/perl

# WA

use warnings;
use strict;

$\ = $/;

<>;

MAIN:
while(<>){
	$_ = join '', map ~~<>, 1 .. $_;

	my %h;

	map $h{ $& } ++, m/\w\w\w/g;

	for my $key ( sort keys %h ){
		if( exists $h{ scalar reverse $key } ){
			print 'YES';
			next MAIN;
			}
		}

	print qw( NO YES )[ 0 + (
		0
		|| m/\b\w\b/
		|| m/\b(\w)\1\b/
		|| m/\b(\w)\w\1\b/
		|| m/\b(\w)(\w)(.*+)?(.*+)?.*\2\1\b/s
		) ];
	}

#!/usr/bin/perl

# WA

use warnings;
use strict;

$\ = $/;

<>;

MAIN:
while(<>){
	$_ = join '', map ~~<>, 1 .. $_;

	my %h;

	map $h{ $& } ++, m/\w\w\w/g;

	for my $key ( sort keys %h ){
		if( exists $h{ scalar reverse $key } ){
			print 'YES';
			next MAIN;
			}
		}

	print qw( NO YES )[ 0 + (
		0
		|| m/\b\w\b/
		|| m/\b(\w)\1\b/
		|| m/\b(\w)\w\1\b/
		|| m/\b(\w)(\w)(??{ ".*$2$1\\b" })/s
		) ];
	}

#!/usr/bin/perl

# WA

use warnings;
use strict;

$\ = $/;

<>;

MAIN:
while(<>){
	$_ = join '', map ~~<>, 1 .. $_;

	my %h;

	map $h{ $& } ++, m/\w\w\w/g;

	for my $key ( sort keys %h ){
		if( exists $h{ scalar reverse $key } ){
			print 'YES';
			next MAIN;
			}
		}

	print qw( NO YES )[ 0 + (
		0
		|| m/\b\w\b/
		|| m/\b(\w)\1\b/
		|| m/\b(\w)\w\1\b/
		|| m/\b(\w)(\w).*.*\2\1\b/s
		) ];
	}

#!/usr/bin/perl

# WA

use warnings;
use strict;

$\ = $/;

<>;

MAIN:
while(<>){
	$_ = join '', map ~~<>, 1 .. $_;

	my %h;

	map $h{ $& } ++, m/\w\w\w/g;

	for my $key ( sort keys %h ){
		if( exists $h{ scalar reverse $key } ){
			print 'YES';
			next MAIN;
			}
		}

	print qw( NO YES )[ 0 + (
		0
		|| m/\b\w\b/
		|| m/\b(\w)\1\b/
		|| m/\b(\w)\w\1\b/
		|| m/\b(\w)(\w).*\2\1\b/s
		) ];
	}


Polycarp wrote on the board a string $$$s$$$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.After that, he erased some letters from the string $$$s$$$, and he rewrote the remaining letters in any order. As a result, he got some new string $$$t$$$. You have to find it with some additional information.Suppose that the string $$$t$$$ has length $$$m$$$ and the characters are numbered from left to right from $$$1$$$ to $$$m$$$. You are given a sequence of $$$m$$$ integers: $$$b_1, b_2, \ldots, b_m$$$, where $$$b_i$$$ is the sum of the distances $$$|i-j|$$$ from the index $$$i$$$ to all such indices $$$j$$$ that $$$t_j > t_i$$$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $$$b_i$$$, Polycarp finds all such indices $$$j$$$ that the index $$$j$$$ contains a letter that is later in the alphabet than $$$t_i$$$ and sums all the values $$$|i-j|$$$.For example, if $$$t$$$ = "abzb", then:  since $$$t_1$$$='a', all other indices contain letters which are later in the alphabet, that is: $$$b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$$$;  since $$$t_2$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_2=|2-3|=1$$$;  since $$$t_3$$$='z', then there are no indexes $$$j$$$ such that $$$t_j>t_i$$$, thus $$$b_3=0$$$;  since $$$t_4$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_4=|4-3|=1$$$. Thus, if $$$t$$$ = "abzb", then $$$b=[6,1,0,1]$$$.Given the string $$$s$$$ and the array $$$b$$$, find any possible string $$$t$$$ for which the following two requirements are fulfilled simultaneously:  $$$t$$$ is obtained from $$$s$$$ by erasing some letters (possibly zero) and then writing the rest in any order;  the array, constructed from the string $$$t$$$ according to the rules above, equals to the array $$$b$$$ specified in the input data.

The first line contains an integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. Each test case consists of three lines:   the first line contains string $$$s$$$, which has a length from $$$1$$$ to $$$50$$$ and consists of lowercase English letters;  the second line contains positive integer $$$m$$$ ($$$1 \le m \le |s|$$$), where $$$|s|$$$ is the length of the string $$$s$$$, and $$$m$$$ is the length of the array $$$b$$$;  the third line contains the integers $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_i \le 1225$$$).  It is guaranteed that in each test case an answer exists.

Output $$$q$$$ lines: the $$$k$$$-th of them should contain the answer (string $$$t$$$) to the $$$k$$$-th test case. It is guaranteed that an answer to each test case exists. If there are several answers, output any.

NoteIn the first test case, such strings $$$t$$$ are suitable: "aac', "aab".In the second test case, such trings $$$t$$$ are suitable: "a", "b", "c".In the third test case, only the string $$$t$$$ equals to "aba" is suitable, but the character 'b' can be from the second or third position.

#!/usr/bin/perl

## + https://www.perlmonks.org/?node_id=11118153

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

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

	chomp;
	my $character_bank = join '', reverse sort split //;

	<>;
	@_ = split ' ', <>;

	my @idx;
	my @groups;

	while( @idx != @_ ){

		my @idx_new;

		OUTER:
		for my $i ( 0 .. @_ - 1 ){
			my $sum = 0;
			for my $j ( @idx ){
				next OUTER if $i == $j;
				$sum += abs( $i - $j );
				}

			$_[ $i ] == $sum and push @idx_new, $i;
			}

		push @idx, @idx_new;
		push @groups, 0 + @idx_new;
		}

	$debug and print "idx:[@idx]";
	$debug and print "groups:[@groups]";

	my $re = join '', map { "(?=(.)) (\\g{-2}{$_}) \\g{-2}* .*? " } @groups;

	$debug and print "re:[$re]";
	$debug and print "[[$character_bank]]";

	$character_bank =~ /
		$re
		/x or print "FAIL!";

	my @chars_seq = ( $character_bank =~ /$re/x )[ map 2 * $_ + 1, 0 .. @groups - 1 ];

	$debug and print "[[@chars_seq]]";

	my $chars_seq = join '', @chars_seq;

	my @ans;

	for my $c ( split //, $chars_seq ){
		$ans[ shift @idx ] = $c;
		}

	print @ans;
	}

#!/usr/bin/perl

## + https://www.perlmonks.org/?node_id=11118153

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;
	$_ = join '', reverse sort split //;

	<>;
	@_ = split ' ', <>;

	my @idx;
	my @groups;

	while( @idx != @_ ){

		my @idx_new;

		OUTER:
		for my $i ( 0 .. @_ - 1 ){
			my $sum = 0;
			for my $j ( @idx ){
				next OUTER if $i == $j;
				$sum += abs( $i - $j );
				}

			$_[ $i ] == $sum and push @idx_new, $i;
			}

		push @idx, @idx_new;
		push @groups, 0 + @idx_new;
		}

	my $re = join '', map { "(?=(.)) (\\g{-2}{$_}) \\g{-2}* .*? " } @groups;

	my @ans;
	@ans[ @idx ] = map { split '' } ( /$re/x )[ map 2 * $_ + 1, 0 .. @groups - 1 ];

	print @ans;
	}

#!/usr/bin/perl

## + https://www.perlmonks.org/?node_id=11118153

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;
	$_ = join '', reverse sort split //;

	<>;
	@_ = split ' ', <>;

	my @idx;
	my @groups;

	while( @idx != @_ ){

		my @idx_new;

		OUTER:
		for my $i ( 0 .. @_ - 1 ){
			my $sum = 0;
			for my $j ( @idx ){
				next OUTER if $i == $j;
				$sum += abs( $i - $j );
				}

			$_[ $i ] == $sum and push @idx_new, $i;
			}

		push @idx, @idx_new;
		push @groups, 0 + @idx_new;
		}

	my $re = join '', map { "(?=(.)) (\\g{-2}{$_}) \\g{-2}* .*? " } @groups;

	my @ans;
	@ans[ @idx ] = map { split '' } ( /$re/x )[ map 2 * $_ + 1, 0 .. @groups - 1 ];

	print "@ans";
	}


A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.

The first line of the input data contains numbers n and m (1 ≤ n, m ≤ 50), n — amount of lines, and m — amount of columns on Bob's sheet. The following n lines contain m characters each. Character «.» stands for a non-shaded square on the sheet, and «*» — for a shaded square. It is guaranteed that Bob has shaded at least one square.

Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better.

use strict;
#use warnings;
use 5.010;

my ($n, $m) = split " ", <>;
my @board;

my ($min_i, $max_i, $min_j, $max_j) = ($n, 0, $m, 0);

sub min {
    return @_[0] < @_[1] ? @_[0] : @_[1];
}

sub max {
    return @_[0] < @_[1] ? @_[1] : @_[0];
}

for my $i (0..$n) {
    push @board, [split //, <>];
}

#for my $i (0..$n) {
    #for my $j (0..$m) {
        #print $board[$i][$j];
    #}
    #print "\n";
#}

for my $i (0..$n) {
    for my $j (0..$m) {
        if($board[$i][$j] eq '*') {
            $min_i = min $min_i, $i;
            $max_i = max $max_i, $i;

            $min_j = min $min_j, $j;
            $max_j = max $max_j, $j;
        }
    }
}

#print "$min_i, $max_i, $min_j, $max_j\n";

for my $i ($min_i..$max_i) {
    for my $j ($min_j..$max_j) {
        print $board[$i][$j];
    }
    print "\n";
}


Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction  as a sum of three distinct positive fractions in form .Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that . Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.If there is no such answer, print -1.

The single line contains single integer n (1 ≤ n ≤ 104).

If the answer exists, print 3 distinct numbers x, y and z (1 ≤ x, y, z ≤ 109, x ≠ y, x ≠ z, y ≠ z). Otherwise print -1. If there are multiple answers, print any of them.


Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed $$$n$$$ cans in a row on a table. Cans are numbered from left to right from $$$1$$$ to $$$n$$$. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down.Vasya knows that the durability of the $$$i$$$-th can is $$$a_i$$$. It means that if Vasya has already knocked $$$x$$$ cans down and is now about to start shooting the $$$i$$$-th one, he will need $$$(a_i \cdot x + 1)$$$ shots to knock it down. You can assume that if Vasya starts shooting the $$$i$$$-th can, he will be shooting it until he knocks it down.Your task is to choose such an order of shooting so that the number of shots required to knock each of the $$$n$$$ given cans down exactly once is minimum possible.

The first line of the input contains one integer $$$n$$$ $$$(2 \le n \le 1\,000)$$$ — the number of cans. The second line of the input contains the sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1\,000)$$$, where $$$a_i$$$ is the durability of the $$$i$$$-th can.

In the first line print the minimum number of shots required to knock each of the $$$n$$$ given cans down exactly once. In the second line print the sequence consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them.

NoteIn the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots $$$20 \cdot 1 + 1 = 21$$$ times. After that only second can remains. To knock it down Vasya shoots $$$10 \cdot 2 + 1 = 21$$$ times. So the total number of shots is $$$1 + 21 + 21 = 43$$$.In the second example the order of shooting does not matter because all cans have the same durability.


Let there be an array $$$b_1, b_2, \ldots, b_k$$$. Let there be a partition of this array into segments $$$[l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c]$$$, where $$$l_1 = 1$$$, $$$r_c = k$$$, and for any $$$2 \leq i \leq c$$$ holds that $$$r_{i-1} + 1 = l_i$$$. In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as $$$$$$c + \sum_{i = 1}^{c} \operatorname{mex}(\{b_{l_i}, b_{l_i + 1}, \ldots, b_{r_i}\}),$$$$$$ where $$$\operatorname{mex}$$$ of a set of numbers $$$S$$$ is the smallest non-negative integer that does not occur in the set $$$S$$$. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array $$$b_1, b_2, \ldots, b_k$$$ as the maximum possible cost over all partitions of this array.You are given an array $$$a$$$ of size $$$n$$$. Find the sum of values of all its subsegments.An array $$$x$$$ is a subsegment of an array $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 30$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the second test case:   The best partition for the subsegment $$$[2, 0, 1]$$$: $$$[2], [0, 1]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0, 1\}) = 2 + 0 + 2 = 4$$$.  The best partition for the subsegment $$$[2, 0]$$$: $$$[2], [0]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0\}) = 2 + 0 + 1 = 3$$$  The best partition for the subsegment $$$[2]$$$: $$$[2]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{2\}) = 1 + 0 = 1$$$.  The best partition for the subsegment $$$[0, 1]$$$: $$$[0, 1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0, 1\}) = 1 + 2 = 3$$$.  The best partition for the subsegment $$$[0]$$$: $$$[0]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0\}) = 1 + 1 = 2$$$.  The best partition for the subsegment $$$[1]$$$: $$$[1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{1\}) = 1 + 0 = 1$$$. The sum of values over all subsegments equals to $$$4 + 3 + 1 + 3 + 2 + 1 = 14$$$.

#!/usr/bin/perl
use Data::Dumper;
use integer;   ### important!
my $mod = 10 ** 9 + 7;
# my $mod = 998244353;

my ($tcase) = map { $_ - 0 } split(/\s+/,<STDIN>);
while( $tcase -- > 0 ){
  my ($n) = map { $_ - 0 } split(/\s+/,<STDIN>);
  my @A = map { $_ - 0 } split(/\s+/,<STDIN>);
  my $res = 0;
  for(my $i=0;$i<$n;$i++){
    for(my $j=$i;$j<$n;$j++){
      my $cz = $j-$i+1;
      for(my $k=$i;$k<=$j;$k++){
        $cz++ if $A[$k] == 0;
      }
      $res += $cz;
    }
  }
  print "$res\n";

}

exit(0);

sub max {
  my $r = undef;
  foreach my $e (@_){  $r = $e if !defined($r) or $e > $r;  }
  return $r;
}
sub min {
  my $r = undef;
  foreach my $e (@_){  $r = $e if !defined($r) or $e < $r;  }
  return $r;
}
sub sum {
  my $r = 0;
  foreach my $e (@_){ $r += $e; }
  return $r;
}
sub ruisum {   # my @rui = (0); &ruisum(\@rui,\@array);
  my $r = shift; my $ar = shift;
  $#{$r} = 1+$#{$ar}; $r->[0] = 0; my $rr = 0;
  for(my $i=0;$i<=$#ar;$i++){
    $rr += $ar->[$i];
    $r->[1+$i] = $rr;
  }
}


You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.

For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.

NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.


Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.Two matrices $$$A$$$ and $$$B$$$ are given, each of them has size $$$n \times m$$$. Nastya can perform the following operation to matrix $$$A$$$ unlimited number of times:   take any square square submatrix of $$$A$$$ and transpose it (i.e. the element of the submatrix which was in the $$$i$$$-th row and $$$j$$$-th column of the submatrix will be in the $$$j$$$-th row and $$$i$$$-th column after transposing, and the transposed submatrix itself will keep its place in the matrix $$$A$$$). Nastya's task is to check whether it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$.    Example of the operation As it may require a lot of operations, you are asked to answer this question for Nastya.A square submatrix of matrix $$$M$$$ is a matrix which consist of all elements which comes from one of the rows with indeces $$$x, x+1, \dots, x+k-1$$$ of matrix $$$M$$$ and comes from one of the columns with indeces $$$y, y+1, \dots, y+k-1$$$ of matrix $$$M$$$. $$$k$$$ is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).

The first line contains two integers $$$n$$$ and $$$m$$$ separated by space ($$$1 \leq n, m \leq 500$$$) — the numbers of rows and columns in $$$A$$$ and $$$B$$$ respectively. Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$1 \leq A_{ij} \leq 10^{9}$$$). Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$1 \leq B_{ij} \leq 10^{9}$$$).

Print "YES" (without quotes) if it is possible to transform $$$A$$$ to $$$B$$$ and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).

NoteConsider the third example. The matrix $$$A$$$ initially looks as follows.$$$$$$ \begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{bmatrix} $$$$$$Then we choose the whole matrix as transposed submatrix and it becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 8\\ 3 & 6 & 9 \end{bmatrix} $$$$$$Then we transpose the submatrix with corners in cells $$$(2, 2)$$$ and $$$(3, 3)$$$. $$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & \textbf{5} & \textbf{8}\\ 3 & \textbf{6} & \textbf{9} \end{bmatrix} $$$$$$So matrix becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 6\\ 3 & 8 & 9 \end{bmatrix} $$$$$$and it is $$$B$$$.


In the capital city of Berland, Bertown, demonstrations are against the recent election of the King of Berland. Berland opposition, led by Mr. Ovalny, believes that the elections were not fair enough and wants to organize a demonstration at one of the squares.Bertown has n squares, numbered from 1 to n, they are numbered in the order of increasing distance between them and the city center. That is, square number 1 is central, and square number n is the farthest from the center. Naturally, the opposition wants to hold a meeting as close to the city center as possible (that is, they want an square with the minimum number).There are exactly k (k < n) days left before the demonstration. Now all squares are free. But the Bertown city administration never sleeps, and the approval of an application for the demonstration threatens to become a very complex process. The process of approval lasts several days, but every day the following procedure takes place:  The opposition shall apply to hold a demonstration at a free square (the one which isn't used by the administration).  The administration tries to move the demonstration to the worst free square left. To do this, the administration organizes some long-term activities on the square, which is specified in the application of opposition. In other words, the administration starts using the square and it is no longer free. Then the administration proposes to move the opposition demonstration to the worst free square. If the opposition has applied for the worst free square then request is accepted and administration doesn't spend money. If the administration does not have enough money to organize an event on the square in question, the opposition's application is accepted. If administration doesn't have enough money to organize activity, then rest of administration's money spends and application is accepted  If the application is not accepted, then the opposition can agree to the administration's proposal (that is, take the worst free square), or withdraw the current application and submit another one the next day. If there are no more days left before the meeting, the opposition has no choice but to agree to the proposal of City Hall. If application is accepted opposition can reject it. It means than opposition still can submit more applications later, but square remains free. In order to organize an event on the square i, the administration needs to spend ai bourles. Because of the crisis the administration has only b bourles to confront the opposition. What is the best square that the opposition can take, if the administration will keep trying to occupy the square in question each time? Note that the administration's actions always depend only on the actions of the opposition.

The first line contains two integers n and k — the number of squares and days left before the meeting, correspondingly (1 ≤ k < n ≤ 105). The second line contains a single integer b — the number of bourles the administration has (1 ≤ b ≤ 1018). The third line contains n space-separated integers ai — the sum of money, needed to organise an event on square i (1 ≤ ai ≤ 109). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print a single number — the minimum number of the square where the opposition can organize the demonstration.

NoteIn the first sample the opposition can act like this. On day one it applies for square 3. The administration has to organize an event there and end up with 3 bourles. If on the second day the opposition applies for square 2, the administration won't have the money to intervene.In the second sample the opposition has only the chance for the last square. If its first move occupies one of the first four squares, the administration is left with at least 4 bourles, which means that next day it can use its next move to move the opposition from any square to the last one.In the third sample administration has a lot of money, so opposition can occupy only last square.


Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.The camera's memory is d megabytes. Valera's camera can take photos of high and low quality. One low quality photo takes a megabytes of memory, one high quality photo take b megabytes of memory. For unknown reasons, each client asks him to make several low quality photos and several high quality photos. More formally, the i-th client asks to make xi low quality photos and yi high quality photos.Valera wants to serve as many clients per day as possible, provided that they will be pleased with his work. To please the i-th client, Valera needs to give him everything he wants, that is, to make xi low quality photos and yi high quality photos. To make one low quality photo, the camera must have at least a megabytes of free memory space. Similarly, to make one high quality photo, the camera must have at least b megabytes of free memory space. Initially the camera's memory is empty. Valera also does not delete photos from the camera so that the camera's memory gradually fills up.Calculate the maximum number of clients Valera can successfully serve and print the numbers of these clients.

The first line contains two integers n and d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) — the number of clients and the camera memory size, correspondingly. The second line contains two integers a and b (1 ≤ a ≤ b ≤ 104) — the size of one low quality photo and of one high quality photo, correspondingly.  Next n lines describe the clients. The i-th line contains two integers xi and yi (0 ≤ xi, yi ≤ 105) — the number of low quality photos and high quality photos the i-th client wants, correspondingly.  All numbers on all lines are separated by single spaces.

On the first line print the answer to the problem — the maximum number of clients that Valera can successfully serve. Print on the second line the numbers of the client in any order. All numbers must be distinct. If there are multiple answers, print any of them. The clients are numbered starting with 1 in the order in which they are defined in the input data.

#!perl
use strict;
use warnings;

main();

sub main {
    my ( $n, $d ) = map int, split /\D/, <>;
    my ( $aa, $bb ) = map int, split /\D/, <>;
    my %clients;
    for my $i ( 1 .. $n ) {
        my ( $x, $y ) = map int, split /\D/, <>;
        $clients{$i} = $x * $aa + $y * $bb;
    }
    my @nclients = sort { $clients{$a} <=> $clients{$b} } keys %clients;
    my @accepted;
    while ( @nclients ) {
        my $client = shift @nclients;
        if ( $clients{$client} <= $d ) {
            $d -= $clients{$client};
            push @accepted, $client;
        } else {
            last;
        }
    }
    my $len = @accepted;
    print "$len\n@accepted";
}

__END__


The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints.

aeren
ari
arousal
around
ari
monogon
monogamy
monthly
kevinvu
kuroni
kurioni
korone
anton
loves
adhoc
problems

NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are:  Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$  Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$  Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$  Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$


A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is $$$6$$$ because all its substrings are palindromes, and the palindromic count of the string "abc" is $$$3$$$ because only its substrings of length $$$1$$$ are palindromes.You are given a string $$$s$$$. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the length of string $$$s$$$. The second line contains string $$$s$$$ that consists of exactly $$$n$$$ lowercase characters of Latin alphabet.

Print string $$$t$$$, which consists of the same set of characters (and each characters appears exactly the same number of times) as string $$$s$$$. Moreover, $$$t$$$ should have the maximum possible value of palindromic count among all such strings strings. If there are multiple such strings, print any of them.

NoteIn the first example, string "ololo" has $$$9$$$ palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.In the second example, the palindromic count of string "abccbaghghghgdfd" is $$$29$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	print join '', sort split //;
	}


The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.

The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.

Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship.

6
Jack captain
Alice woman
Charlie man
Teddy rat
Bob child
Julia woman


You are given two integers $$$a$$$ and $$$b$$$. You may perform any number of operations on them (possibly zero).During each operation you should choose any positive integer $$$x$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$ or $$$a := a - 2x$$$, $$$b := b - x$$$. Note that you may choose different values of $$$x$$$ in different operations.Is it possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously?Your program should answer $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow, each test case is represented by one line containing two integers $$$a$$$ and $$$b$$$ for this test case ($$$0 \le a, b \le 10^9$$$).

For each test case print the answer to it — YES if it is possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first test case of the example two operations can be used to make both $$$a$$$ and $$$b$$$ equal to zero:  choose $$$x = 4$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$. Then $$$a = 6 - 4 = 2$$$, $$$b = 9 - 8 = 1$$$;  choose $$$x = 1$$$ and set $$$a := a - 2x$$$, $$$b := b - x$$$. Then $$$a = 2 - 2 = 0$$$, $$$b = 1 - 1 = 0$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	my( $A, $B ) = sort { $a <=> $b } split;

	if( ( $A + $B ) % 3 == 0 and $A * 2 >= $B ){
		print "YES";
		}
	else{
		print "NO";
		}
	}


You are given two even integers $$$n$$$ and $$$m$$$. Your task is to find any binary matrix $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns where every cell $$$(i,j)$$$ has exactly two neighbours with a different value than $$$a_{i,j}$$$.Two cells in the matrix are considered neighbours if and only if they share a side. More formally, the neighbours of cell $$$(x,y)$$$ are: $$$(x-1,y)$$$, $$$(x,y+1)$$$, $$$(x+1,y)$$$ and $$$(x,y-1)$$$.It can be proven that under the given constraints, an answer always exists.

Each test contains multiple test cases. The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains two even integers $$$n$$$ and $$$m$$$ ($$$2 \le n,m \le 50$$$) — the height and width of the binary matrix, respectively.

For each test case, print $$$n$$$ lines, each of which contains $$$m$$$ numbers, equal to $$$0$$$ or $$$1$$$ — any binary matrix which satisfies the constraints described in the statement. It can be proven that under the given constraints, an answer always exists.

NoteWhite means $$$0$$$, black means $$$1$$$. The binary matrix from the first test caseThe binary matrix from the second test caseThe binary matrix from the third test case


After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3».The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each player has an army. Army of the i-th player can be described by non-negative integer xi. Consider binary representation of xi: if the j-th bit of number xi equal to one, then the army of the i-th player has soldiers of the j-th type. Fedor is the (m + 1)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.

The first line contains three integers n, m, k (1 ≤ k ≤ n ≤ 20; 1 ≤ m ≤ 1000). The i-th of the next (m + 1) lines contains a single integer xi (1 ≤ xi ≤ 2n - 1), that describes the i-th player's army. We remind you that Fedor is the (m + 1)-th player.

Print a single integer — the number of Fedor's potential friends.

use strict;
use warnings;

sub dec2bin {
    my $str = unpack("B32", pack("N", shift));
    $str =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
    return $str;
}

my @arr;
my ($n, $m, $k) = split / /, <>;
my ($count, $ans) = (0, 0);
for my $i(0..$m) {
    chomp($_ = <>);
    push @arr, $_;
}
for my $i(0..$m-1) {
    # $count = unpack("%32b*", $arr[$i] ^ $arr[-1]) - 2;
    $count = dec2bin(int$arr[$i] ^ int$arr[-1]) =~ tr/1/1/;
    # print unpack("%32b*", 4);
    # print $arr[$i] . " " . $arr[-1] . " " . $count . " " . dec2bin(int$arr[$i] ^ int$arr[-1]) ."\n";
    $ans++ if ($count <= $k);
}
print $ans . "\n";

sub dec2bin {
    my $str = unpack("B32", pack("N", shift));
    $str =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
    return $str;
}

my @arr;
my ($n, $m, $k) = split / /, <>;
my ($count, $ans) = (0, 0);
for my $i(0..$m) {
    chomp($_ = <>);
    push @arr, $_;
}
for my $i(0..$m-1) {
    $count = dec2bin(int$arr[$i] ^ int$arr[-1]) =~ tr/1/1/;
    $ans++ if ($count <= $k);
}
print $ans . "\n";

#!/perl -w

use strict ;

my($n,$m,$k) = split /\s+/s , <STDIN> ;

my @soldiertype = (0) ;
my $num = 1 ;
while($num <= $m+1 ){
    chomp ( $soldiertype[$num] = <STDIN> );
    $num++ ;
}

my $friend = 0 ;
foreach(1..($m)){
    my $cmp_soldier = $soldiertype[$m+1] ;
    my $diff = 0 ;
    while ( $cmp_soldier || $soldiertype[$_] ){
        if ( ( $soldiertype[$_] & 1 ) ^ ( $cmp_soldier & 1 )  ){
            $diff ++ ;
        }
        $cmp_soldier = $cmp_soldier >> 1 ;
        $soldiertype[$_] = $soldiertype[$_] >> 1 ;
    }
    $friend++ if ( $diff <= $k ) ;
}

print $friend, "\n" ;

#!/usr/bin/perl
use v5.10;

sub getBits {
	my ($x, $ret) = (shift, 0);
	# say "x = $x";
	while ($x) {
		$ret += ($x & 1);
		$x >>= 1;
	}
	# say "ret = $ret";
	return $ret;
}

($n, $m, $k) = split / /, <>;
push @a, int(<>) foreach (0..$m);
getBits($_ ^ $a[$m])<=$k and ++$ans foreach (@a);
say $ans-1;

use 5.016;
use strict;
use warnings;

sub popcount {
  my ($n) = @_;

  my $c = 0;
  while ($n) {
    $c++;
    $n = $n & ($n - 1);
  }
  $c;
}

sub hamming_distance {
  my ($x, $y) = @_;

  popcount((0+$x) ^ (0+$y));
}

my ($n, $m, $k) = split ' ', <>;

my @players;
for (1..$m) {
  push @players, scalar <>;
}
my $fedor = <>;

say scalar grep { hamming_distance($fedor, $_) <= $k } @players;


Polycarp found a rectangular table consisting of $$$n$$$ rows and $$$m$$$ columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns":   cells are numbered starting from one;  cells are numbered from left to right by columns, and inside each column from top to bottom;  number of each cell is an integer one greater than in the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, the table will be numbered as follows:$$$$$$ \begin{matrix} 1 & 4 & 7 & 10 & 13 \\ 2 & 5 & 8 & 11 & 14 \\ 3 & 6 & 9 & 12 & 15 \\ \end{matrix} $$$$$$However, Polycarp considers such numbering inconvenient. He likes the numbering "by rows":   cells are numbered starting from one;  cells are numbered from top to bottom by rows, and inside each row from left to right;  number of each cell is an integer one greater than the number of the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, then Polycarp likes the following table numbering: $$$$$$ \begin{matrix} 1 & 2 & 3 & 4 & 5 \\ 6 & 7 & 8 & 9 & 10 \\ 11 & 12 & 13 & 14 & 15 \\ \end{matrix} $$$$$$Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering "by rows", if in the numbering "by columns" the cell has the number $$$x$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single line containing three integers $$$n$$$, $$$m$$$, $$$x$$$ ($$$1 \le n, m \le 10^6$$$, $$$1 \le x \le n \cdot m$$$), where $$$n$$$ and $$$m$$$ are the number of rows and columns in the table, and $$$x$$$ is the cell number. Note that the numbers in some test cases do not fit into the $$$32$$$-bit integer type, so you must use at least the $$$64$$$-bit integer type of your programming language.

For each test case, output the cell number in the numbering "by rows".

use bigint;
<STDIN>;
while (<>)
{
    chomp;
    my ($n, $m, $x) = split;
    $x--;
    my ($r, $c) = ($x % $n, int($x / $n));
    my $res = $r * $m + $c + 1;
    print "$res\n";
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	$x --;

	my $int = int $x / $n;
	my $mod = $x % $n;

	print 1 + $int + $mod * $m;
	}

use bigint;
<STDIN>;
while (<>)
{
    chomp;
    my ($n, $m, $x) = split;
    $x--;
    my ($r, $c) = ($x % $n, $x / $n);
    my $res = $r * $m + $c + 1;
    print "$res\n";
}

use bigint;
<STDIN>;
while (<>)
{
    my ($n, $mm, $x) = split / /, chomp;
    $x--;
    my ($r, $c) = ($x % $n, $x / $n);
    my $res = $r * $mm + $c + 1;
    print "$res\n";
}

use bigint;
<STDIN>;
while (<>)
{
    my ($n, $m, $x) = split / /, chomp;
    $x--;
    my ($r, $c) = ($x % $n, $x / $n);
    my $res = $r * $m + $c + 1;
    print "$res";
}


Theofanis has a string $$$s_1 s_2 \dots s_n$$$ and a character $$$c$$$. He wants to make all characters of the string equal to $$$c$$$ using the minimum number of operations.In one operation he can choose a number $$$x$$$ ($$$1 \le x \le n$$$) and for every position $$$i$$$, where $$$i$$$ is not divisible by $$$x$$$, replace $$$s_i$$$ with $$$c$$$. Find the minimum number of operations required to make all the characters equal to $$$c$$$ and the $$$x$$$-s that he should use in his operations.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains the integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$) and a lowercase Latin letter $$$c$$$ — the length of the string $$$s$$$ and the character the resulting string should consist of. The second line of each test case contains a string $$$s$$$ of lowercase Latin letters — the initial string. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, firstly print one integer $$$m$$$ — the minimum number of operations required to make all the characters equal to $$$c$$$. Next, print $$$m$$$ integers $$$x_1, x_2, \dots, x_m$$$ ($$$1 \le x_j \le n$$$) — the $$$x$$$-s that should be used in the order they are given. It can be proved that under given constraints, an answer always exists. If there are multiple answers, print any.

NoteLet's describe what happens in the third test case:   $$$x_1 = 2$$$: we choose all positions that are not divisible by $$$2$$$ and replace them, i. e. bzyx $$$\rightarrow$$$ bzbx;  $$$x_2 = 3$$$: we choose all positions that are not divisible by $$$3$$$ and replace them, i. e. bzbx $$$\rightarrow$$$ bbbb.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

while(<>){
	$debug and print '-' x 15;
	my( $n, $c ) = split;

	$_ = <>, chomp;

	my $rindex = rindex $_, $c;

	$rindex < 1 and $rindex = 1;

	$debug and print "[$n][$c][$_][$rindex]";

	if( ! m/[^$c]/ ){
		print 0;
		}
	else{
		for my $i ( 0 .. $n - 1 ){
			next if ( $i + 1 ) % ( $rindex + 1 ) == 0;
			substr $_, $i, 1, $c;
			}

		$debug and print " [$_]";

		my $rindex2 = rindex $_, $c;

		if( ! m/[^$c]/ ){
			print 1;
			print $rindex + 1;
			}
		else{
			print 2;
			print join ' ', $rindex + 1, $rindex2 + 1;
			}
		}
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	$_ = <>, chomp;

	if( m/[^$c]/ ){
		if( m/[^$c]\B/ and m/[^$c]$/ ){
			print 2;
			print join ' ', $n - 1, $n;
			}
		else{
			print 1;
			if( m/[^$c]$/ ){
				print $n - 1;
				}
			else{
				print $n;
				}
			}
		}
	else{
		print 0;
		}
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	$_ = <>, chomp;

	if( m/[^$c]/ ){
		if( m/[^$c]\b/ and m/[^$c]$/ ){
			print 2;
			print join ' ', $n - 1, $n;
			}
		else{
			print 1;
			if( m/[^$c]$/ ){
				print $n - 1;
				}
			else{
				print $n;
				}
			}
		}
	else{
		print 0;
		}
	}


You are given three integers $$$a$$$, $$$b$$$, and $$$c$$$. Determine if one of them is the sum of the other two.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 9261$$$) — the number of test cases. The description of each test case consists of three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$0 \leq a, b, c \leq 20$$$).

For each test case, output "YES" if one of the numbers is the sum of the other two, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case, $$$1 + 3 = 4$$$.In the second test case, none of the numbers is the sum of the other two.In the third test case, $$$9 + 11 = 20$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	@_ = sort { $a <=> $b } split;

	if( $_[ 0 ] + $_[ 1 ] == $_[ 2 ] ){
		print 'YES';
		}
	else{
		print 'NO';
		}
	}


Alperen has two strings, $$$s$$$ and $$$t$$$ which are both initially equal to "a". He will perform $$$q$$$ operations of two types on the given strings:  $$$1 \;\; k \;\; x$$$ — Append the string $$$x$$$ exactly $$$k$$$ times at the end of string $$$s$$$. In other words, $$$s := s + \underbrace{x + \dots + x}_{k \text{ times}}$$$.  $$$2 \;\; k \;\; x$$$ — Append the string $$$x$$$ exactly $$$k$$$ times at the end of string $$$t$$$. In other words, $$$t := t + \underbrace{x + \dots + x}_{k \text{ times}}$$$. After each operation, determine if it is possible to rearrange the characters of $$$s$$$ and $$$t$$$ such that $$$s$$$ is lexicographically smaller$$$^{\dagger}$$$ than $$$t$$$.Note that the strings change after performing each operation and don't go back to their initial states.$$$^{\dagger}$$$ Simply speaking, the lexicographical order is the order in which words are listed in a dictionary. A formal definition is as follows: string $$$p$$$ is lexicographically smaller than string $$$q$$$ if there exists a position $$$i$$$ such that $$$p_i < q_i$$$, and for all $$$j < i$$$, $$$p_j = q_j$$$. If no such $$$i$$$ exists, then $$$p$$$ is lexicographically smaller than $$$q$$$ if the length of $$$p$$$ is less than the length of $$$q$$$. For example, $$$\texttt{abdc} < \texttt{abe}$$$ and $$$\texttt{abc} < \texttt{abcd}$$$, where we write $$$p < q$$$ if $$$p$$$ is lexicographically smaller than $$$q$$$.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$q$$$ $$$(1 \leq q \leq 10^5)$$$ — the number of operations Alperen will perform. Then $$$q$$$ lines follow, each containing two positive integers $$$d$$$ and $$$k$$$ ($$$1 \leq d \leq 2$$$; $$$1 \leq k \leq 10^5$$$) and a non-empty string $$$x$$$ consisting of lowercase English letters — the type of the operation, the number of times we will append string $$$x$$$ and the string we need to append respectively. It is guaranteed that the sum of $$$q$$$ over all test cases doesn't exceed $$$10^5$$$ and that the sum of lengths of all strings $$$x$$$ in the input doesn't exceed $$$5 \cdot 10^5$$$.

For each operation, output "YES", if it is possible to arrange the elements in both strings in such a way that $$$s$$$ is lexicographically smaller than $$$t$$$ and "NO" otherwise.

3

5

2 1 aa

1 2 a

2 3 a

1 2 b

2 3 abca

2

1 5 mihai

2 2 buiucani

3

1 5 b

2 3 a

2 4 paiu

NoteIn the first test case, the strings are initially $$$s = $$$ "a" and $$$t = $$$ "a". After the first operation the string $$$t$$$ becomes "aaa". Since "a" is already lexicographically smaller than "aaa", the answer for this operation should be "YES".After the second operation string $$$s$$$ becomes "aaa", and since $$$t$$$ is also equal to "aaa", we can't arrange $$$s$$$ in any way such that it is lexicographically smaller than $$$t$$$, so the answer is "NO".After the third operation string $$$t$$$ becomes "aaaaaa" and $$$s$$$ is already lexicographically smaller than it so the answer is "YES".After the fourth operation $$$s$$$ becomes "aaabb" and there is no way to make it lexicographically smaller than "aaaaaa" so the answer is "NO".After the fifth operation the string $$$t$$$ becomes "aaaaaaabcaabcaabca", and we can rearrange the strings to: "bbaaa" and "caaaaaabcaabcaabaa" so that $$$s$$$ is lexicographically smaller than $$$t$$$, so we should answer "YES".


Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:  He looks through all the coins from left to right;  If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.  Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.

The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.

Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.

NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.

use strict;
our ($n, $m, @l, @r);

sub calc {
	my $p = shift;
	my ($left, $right) = ($l[$p - 1], $r[$p + 1]);
	if (!$left and !$right) {
		$l[$p] = $r[$p] = $p;
	} elsif ($left and $right) {
		$r[$left] = $right;
		$l[$right] = $left;
	} elsif ($left) {
		$l[$p] = $left;
		$r[$left] = $p;
	} elsif ($right) {
		$r[$p] = $right;
		$l[$right] = $p;
	}
	my $empty = ($l[$n] == undef);
	my $last = ($empty? 0: $n - $l[$n] + 1);
	++$m - $last + 1;
}

$n = <>;
print "1 ";
print calc($_), " " for split " ", <>;


Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x = 0 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing.What is the maximum number of apples he can collect?

The first line contains one number n (1 ≤ n ≤ 100), the number of apple trees in Lala Land. The following n lines contains two integers each xi, ai ( - 105 ≤ xi ≤ 105, xi ≠ 0, 1 ≤ ai ≤ 105), representing the position of the i-th tree and number of apples on it. It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0.

Output the maximum number of apples Amr can collect.

NoteIn the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples.In the second sample test the optimal solution is to go left to x =  - 1, collect apples from there, then the direction will be reversed, Amr has to go to x = 1, collect apples from there, then the direction will be reversed and Amr goes to the final tree x =  - 2.In the third sample test the optimal solution is to go right to x = 1, collect apples from there, then the direction will be reversed and Amr will not be able to collect anymore apples because there are no apple trees to his left.

#!/usr/bin/perl

use strict;
use warnings;

my $n = <>;
chomp $n;

my (@neg, @pos);

for (1..$n) {
  my $line = <>;
  chomp $line;
  my ($p, $apples) = split(/ /, $line);
  if ($p < 0) {
    $p *= -1;
    push(@neg, "$p:$apples");
  } else {
    push(@pos, "$p:$apples");
  }
}

@neg = sort {
  my @agh = split(/:/, $a);
  my @bgh = split(/:/, $b);
  my $na = $agh[0];
  my $nb = $bgh[0];
  $na <=> $nb
} @neg;

@pos = sort {
  my @agh = split(/:/, $a);
  my @bgh = split(/:/, $b);
  my $na = $agh[0];
  my $nb = $bgh[0];
  $na <=> $nb
} @pos;

map { my @tmp = split(/:/, $_); $_ = $tmp[1] } @pos;
map { my @tmp = split(/:/, $_); $_ = $tmp[1] } @neg;

my @origpos = @pos;
my @origneg = @neg;
my $res = 0;
my $tmp = 0;
while (scalar(@pos) > 0) {
  $tmp += shift @pos;
  if (scalar(@neg) > 0) {
    $tmp += shift @neg;
  } else {
    last;
  }
}
if ($tmp > $res) {
  $res = $tmp;
}
@pos = @origpos;
@neg = @origneg;
$tmp = 0;
while (scalar(@neg) > 0) {
  $tmp += shift @neg;
  if (scalar(@pos) > 0) {
    $tmp += shift @pos;
  } else {
    last;
  }
}
if ($tmp > $res) {
  $res = $tmp;
}
print "$res\n";

	<>, %h = map split, <>;

	++ ( /-/ ? $d : $u ) for keys %h;

	@d = sort {$b <=> $a} grep  /-/, keys %h;
	@u = sort {$a <=> $b} grep !/-/, keys %h;

	$sum += $h{shift @d} + $h{shift @u} while @d && @u;

	print $sum += 0 + $h{ 0 + "@d@u" }

$\ = $/;

while($n = <>){
	undef @h;
	for (1 .. $n){
		push @h, split " ", <>;
		}
	%h = @h;

	$u = $d = 0;
	/-/ ? $d++ : $u++ for keys %h;
	$min = $d > $u ? $u : $d;
	@d = sort sort {$b <=> $a} grep  /-/, keys %h;
	@u = sort sort {$a <=> $b} grep !/-/, keys %h;

	$sum = 0;
	for (1 .. $min){
		$dd = shift @d;
		$uu = shift @u;
		$sum += $h{$dd};
		$sum += $h{$uu};
		}

	$iu = $id = 0;
	@d and $id = shift @d;
	@u and $iu = shift @u;

	$max = $h{$iu} > $h{$id} ? $h{$iu} : $h{$id};

	$sum += $max;
	print $sum;
	}

	<>, %h = map split, <>;

	++ ( /-/ ? $d : $u ) for keys %h;

	@d = sort {$b <=> $a} grep  /-/, keys %h;
	@u = sort {$a <=> $b} grep !/-/, keys %h;

	$sum += $h{shift @d} + $h{shift @u} while @d && @u;

	print $sum += 0 + $h{+"@d@u0"}

	<>, %h = map split, <>;

	++ ( /-/ ? $d : $u ) for keys %h;

	@d = sort {$b <=> $a} grep  /-/, keys %h;
	@u = sort {$a <=> $b} grep !/-/, keys %h;

	$sum += $h{shift @d} + $h{shift @u} while @d && @u;

	print $sum += (@d, @u, 0)[0]


Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value ai.Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative integer power of k. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment.Help her to do so in finding the total number of such segments.

The first line of input contains two integers, n and k, the number of chemicals and the number, such that the total affection value is a non-negative power of this number k. (1 ≤ n ≤ 105, 1 ≤ |k| ≤ 10). Next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — affection values of chemicals.

Output a single integer — the number of valid segments.

NoteDo keep in mind that k0 = 1.In the first sample, Molly can get following different affection values:  2: segments [1, 1], [2, 2], [3, 3], [4, 4]; 4: segments [1, 2], [2, 3], [3, 4]; 6: segments [1, 3], [2, 4]; 8: segments [1, 4]. Out of these, 2, 4 and 8 are powers of k = 2. Therefore, the answer is 8.In the second sample, Molly can choose segments [1, 2], [3, 3], [3, 4].


Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.

The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.

Print the sequence of operations that will rearrange the animals by non-decreasing height. The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed. The number of operations should not exceed 20 000. If the animals are arranged correctly from the start, you are allowed to output nothing.

NoteNote that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: b: 2 c: 3, 10 d: 4, 8 e: 6 f: 7 z: 1, 5, 9 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.

The single line contains a positive integer n (1 ≤ n ≤ 105) — the length of the sought string.

Print on the single line the lexicographically minimal lucky string whose length equals n.

NoteThe lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

#    <>=~/ /;
#    <>=~/ (\d+) /;
#    <>=~/ (\d+) (\d+) /;

chomp ($i=<>);
$_="abcd"x($i/4+1);
for $j(1..4-$i%4){chop}
print ;

#***********SUBS************

sub num {$a <=> $b}
sub num_rev {$b <=> $a}
sub rev {$b cmp $a}

sub p{print}
sub n{print "\n"}
sub pn{p,n}
sub pn_mas {pn for @_}

# Transpose "charbox"
sub transpose{
    $i=@m=@_;
    chomp @m;
    while ($i--){
        $t[$i]=~s/$/chop/e for @m
    }
return @t
}

# Transpose "value sets"
sub transpose_space{
    my @t;
    for (@_){
        my $j=0;
        s/\d+/($t[$j++].="$& ")?$&:$&/eg;
        }
    chop @t;
return @t
}

sub div{
    my ($n, $k)=@_;
return ($n - $n % $k) / $k
}

sub uniq{
    my @m=sort @_;
    push @u, my $i=shift @m;
    for (@m){
        $i eq $_ or push @u, $_;
        $i=$_;
        }
return @u
}

sub max{
    my $max=shift;
    $max<$_ and $max=$_ for @_;
return $max
}

sub min{
    my $min=shift;
    $min>$_ and $min=$_ for @_;
return $min
}

# count (kas_ieskoma, masyvas)
sub count{
    my $i=0;
    $_ eq $_[0] and $i++ for @_;
return --$i
}

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

#    <>=~/ /;
#    <>=~/ (\d+) /;
#    <>=~/ (\d+) (\d+) /;

$_="abcd"x25e3;
chomp ($i=<>);
print substr($_,0,$i);

#***********SUBS************

sub num {$a <=> $b}
sub num_rev {$b <=> $a}
sub rev {$b cmp $a}

sub p{print}
sub n{print "\n"}
sub pn{p,n}
sub pn_mas {pn for @_}

# Transpose "charbox"
sub transpose{
    $i=@m=@_;
    chomp @m;
    while ($i--){
        $t[$i]=~s/$/chop/e for @m
    }
return @t
}

# Transpose "value sets"
sub transpose_space{
    my @t;
    for (@_){
        my $j=0;
        s/\d+/($t[$j++].="$& ")?$&:$&/eg;
        }
    chop @t;
return @t
}

sub div{
    my ($n, $k)=@_;
return ($n - $n % $k) / $k
}

sub uniq{
    my @m=sort @_;
    push @u, my $i=shift @m;
    for (@m){
        $i eq $_ or push @u, $_;
        $i=$_;
        }
return @u
}

sub max{
    my $max=shift;
    $max<$_ and $max=$_ for @_;
return $max
}

sub min{
    my $min=shift;
    $min>$_ and $min=$_ for @_;
return $min
}

# count (kas_ieskoma, masyvas)
sub count{
    my $i=0;
    $_ eq $_[0] and $i++ for @_;
return --$i
}

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

#    <>=~/ /;
#    <>=~/ (\d+) /;
#    <>=~/ (\d+) (\d+) /;

for $i(0..<>-1){s/$/$i%4==0?("a"):($i%4==1?("b"):($i%4==2?("c"):("d")))/e}
print;

#***********SUBS************

sub num {$a <=> $b}
sub num_rev {$b <=> $a}
sub rev {$b cmp $a}

sub p{print}
sub n{print "\n"}
sub pn{p,n}
sub pn_mas {pn for @_}

# Transpose "charbox"
sub transpose{
    $i=@m=@_;
    chomp @m;
    while ($i--){
        $t[$i]=~s/$/chop/e for @m
    }
return @t
}

# Transpose "value sets"
sub transpose_space{
    my @t;
    for (@_){
        my $j=0;
        s/\d+/($t[$j++].="$& ")?$&:$&/eg;
        }
    chop @t;
return @t
}

sub div{
    my ($n, $k)=@_;
return ($n - $n % $k) / $k
}

sub uniq{
    my @m=sort @_;
    push @u, my $i=shift @m;
    for (@m){
        $i eq $_ or push @u, $_;
        $i=$_;
        }
return @u
}

sub max{
    my $max=shift;
    $max<$_ and $max=$_ for @_;
return $max
}

sub min{
    my $min=shift;
    $min>$_ and $min=$_ for @_;
return $min
}

# count (kas_ieskoma, masyvas)
sub count{
    my $i=0;
    $_ eq $_[0] and $i++ for @_;
return --$i
}

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

#    <>=~/ /;
#    <>=~/ (\d+) /;
#    <>=~/ (\d+) (\d+) /;

$_="abcd"x25e3;
$i=<>;
s/.{$i}//;
print "$&\n";

#***********SUBS************

sub num {$a <=> $b}
sub num_rev {$b <=> $a}
sub rev {$b cmp $a}

sub p{print}
sub n{print "\n"}
sub pn{p,n}
sub pn_mas {pn for @_}

# Transpose "charbox"
sub transpose{
    $i=@m=@_;
    chomp @m;
    while ($i--){
        $t[$i]=~s/$/chop/e for @m
    }
return @t
}

# Transpose "value sets"
sub transpose_space{
    my @t;
    for (@_){
        my $j=0;
        s/\d+/($t[$j++].="$& ")?$&:$&/eg;
        }
    chop @t;
return @t
}

sub div{
    my ($n, $k)=@_;
return ($n - $n % $k) / $k
}

sub uniq{
    my @m=sort @_;
    push @u, my $i=shift @m;
    for (@m){
        $i eq $_ or push @u, $_;
        $i=$_;
        }
return @u
}

sub max{
    my $max=shift;
    $max<$_ and $max=$_ for @_;
return $max
}

sub min{
    my $min=shift;
    $min>$_ and $min=$_ for @_;
return $min
}

# count (kas_ieskoma, masyvas)
sub count{
    my $i=0;
    $_ eq $_[0] and $i++ for @_;
return --$i
}


Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

$_=<>;
$a=<>;
$b=<>;
chomp($a,$b,$_);
$a1=join '',reverse split'',$a;
$b1=join '',reverse split'',$b;
print "both" and exit if /$a.*$b/ and /$b1.*$a1/;
print "forward" and exit if /$a.*$b/;
print "backward" and exit if /$b1.*$a1/;
print "fantasy";

$_=<>;
$a=<>;
$b=<>;
chomp($a,$b);
$a1 = reverse $a;
$b1 = reverse $b;
print "both" and exit if /$a.*$b/ and /$b1.*$a1/;
print "forward" and exit if /$a.*$b/;
print "backward" and exit if /$b1.*$a1/;
print "fantasy";

$ch=<>;
chomp$ch;
$str1=<>;
chomp$str1;
$str2=<>;
chomp$str2;
$ok1=0,$ok2=0;
if($ch=~m/$str1.*$str2/){
$ok1=1;
}
if(reverse($ch)=~m/$str1.*$str2/){
$ok2=1;
}
if($ok2+$ok1==2){
print "both";
}
elsif($ok1){
print"forward";
}
elsif($ok2){
print"backward"
}
else{
print "fantasy";
}

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

my $s = <>;
chomp $s;
my $s1 = <>;
chomp $s1;
my $s2 = <>;
chomp $s2;
my $fb = 0;

$fb += 1 if ($s =~ m/$s1.*$s2/);
$s = reverse $s;
$fb += 2 if ($s =~ m/$s1.*$s2/);
if ($fb == 3) {
    print "both\n";
} elsif ($fb == 2) {
    print "backward\n";
} elsif ($fb == 1) {
    print "forward\n";
} else {
    print "fantasy\n";
}

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

my $flags=<STDIN>;chomp($flags);my $one=<STDIN>;chomp($one);my $two=<STDIN>;chomp($two);
my $sgalf=reverse $flags;
if($flags=~/\A.*?$one.*?$two/&&$sgalf=~/\A.*?$one.*?$two/){print "both\n";}
elsif($flags=~/\A.*?$one.*?$two/){print "forward\n";}
elsif($sgalf=~/\A.*?$one.*?$two/){print "backward\n";}
else{print "fantasy\n";}

$_=<>;
$a=<>;
$b=<>;
chomp($a,$b,$_);
print "both" and exit if /$a.*$b/ and /$b.*$a/;
print "forward" and exit if /$a.*$b/;
print "backward" and exit if /$b.*$a/;
print "fantasy";

$_=<>;
$a=<>;
$b=<>;
chomp($a,$b);
print "both" and exit if /$a.*$b/ and /$b.*$a/;
print "forward" and exit if /$a.*$b/;
print "backward" and exit if /$b.*$a/;
print "fantasy";

$ch=<>;
chomp$ch;
$str1=<>;
chomp$str1;
$str2=<>;
chomp$str2;
$ok1=0,$ok2=0;
if($ch=~m/$str1.*$str2/){
$ok1=1;
}
if($ch=~m/$str2.*$str1/){
$ok2=1;
}
if($ok2+$ok1==2){
print "both";
}
elsif($ok1){
print"forward";
}
elsif($ok2){
print"backward"
}
else{
print "fantasy";
}

$ch=<>;
chomp$ch;
$str1=<>;
chomp$str1;
$str2=<>;
chomp$str2;
$ok1=0,$ok2=0;
if($ch=~m/$str1.*$str2/){
$ok1=1;
}
if(reverse($ch)=~m/$str2.*$str1/){
$ok2=1;
}
if($ok2+$ok1==2){
print "both";
}
elsif($ok1){
print"forward";
}
elsif($ok2){
print"backward"
}
else{
print "fantasy";
}

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

my $flags=<STDIN>;chomp($flags);my $one=<STDIN>;chomp($one);my $two=<STDIN>;chomp($two);
if($flags!~/$one/||$flags!~/$two/){print "fantasy\n";}
else{
    my $sgalf=reverse $flags;
    my $fone=$flags=~s/\A.*?$one//r;my $ftwo=$sgalf=~s/\A.*?$one//r;
    if($fone=~/$two/&&$ftwo=~/$two/){print "both\n";}
    elsif($fone!~/$two/&&$ftwo!~/$two/){print "fantasy\n";}
    else{
	my $ans=($fone=~/$two/)?"forward\n":"backward\n";
	print $ans;
    }
}

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

my $flags=<STDIN>;chomp($flags);my $one=<STDIN>;chomp($one);my $two=<STDIN>;chomp($two);
my $fone=$flags=~s/\A.*$one//r;my $ftwo=$flags=~s/$fone//r;
if($flags!~/$one/||$flags!~/$two/){print "fantasy\n";}
else{
    if($fone=~/$two/&&$ftwo=~/$two/) {print "both\n";}
    else{
	if($fone!~/$two/&&$ftwo!~/$two/){print "fantasy\n";}
	else{
	    if($fone=~/$two/){print "forward\n";}
	    else{ print "backward\n";}
	}
    }
}

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

my $flags=<STDIN>;chomp($flags);my $one=<STDIN>;chomp($one);my $two=<STDIN>;chomp($two);
my $fone=$flags=~s/\A.*$one//r;my $ftwo=$flags=~s/$fone//r;
if($fone=~/$two/&&$ftwo=~/$two/) {print "both\n";}
else{
    if($fone!~/$two/&&$ftwo!~/$two/){print "fantasy\n";}
    else{
	if($fone=~/$two/){print "forward\n";}
	else{ print "backward\n";}
    }
}

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

my $flags=<STDIN>;chomp($flags);my $one=<STDIN>;chomp($one);my $two=<STDIN>;chomp($two);
my $fone=$flags=~s/\A.*?$one//r;my $ftwo=$flags=~s/$fone//r;
if($flags!~/$one/||$flags!~/$two/){print "fantasy\n";}
else{
    if($fone=~/$two/&&$ftwo=~/$two/) {print "both\n";}
    else{
	if($fone!~/$two/&&$ftwo!~/$two/){print "fantasy\n";}
	else{
	    if($fone=~/$two/){print "forward\n";}
	    else{ print "backward\n";}
	}
    }
}


Polycarp found under the Christmas tree an array $$$a$$$ of $$$n$$$ elements and instructions for playing with it:   At first, choose index $$$i$$$ ($$$1 \leq i \leq n$$$) — starting position in the array. Put the chip at the index $$$i$$$ (on the value $$$a_i$$$).  While $$$i \leq n$$$, add $$$a_i$$$ to your score and move the chip $$$a_i$$$ positions to the right (i.e. replace $$$i$$$ with $$$i + a_i$$$).  If $$$i > n$$$, then Polycarp ends the game. For example, if $$$n = 5$$$ and $$$a = [7, 3, 1, 2, 3]$$$, then the following game options are possible:   Polycarp chooses $$$i = 1$$$. Game process: $$$i = 1 \overset{+7}{\longrightarrow} 8$$$. The score of the game is: $$$a_1 = 7$$$.  Polycarp chooses $$$i = 2$$$. Game process: $$$i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_2 + a_5 = 6$$$.  Polycarp chooses $$$i = 3$$$. Game process: $$$i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_3 + a_4 = 3$$$.  Polycarp chooses $$$i = 4$$$. Game process: $$$i = 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_4 = 2$$$.  Polycarp chooses $$$i = 5$$$. Game process: $$$i = 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_5 = 3$$$. Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output on a separate line one number — the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from $$$1$$$ to $$$n$$$ in such a way as to maximize his result.

NoteThe first test case is explained in the statement.In the second test case, the maximum score can be achieved by choosing $$$i = 1$$$.In the third test case, the maximum score can be achieved by choosing $$$i = 2$$$.In the fourth test case, the maximum score can be achieved by choosing $$$i = 1$$$.


You are given $$$n$$$ strings $$$s_1, s_2, \dots, s_n$$$ of length at most $$$\mathbf{8}$$$. For each string $$$s_i$$$, determine if there exist two strings $$$s_j$$$ and $$$s_k$$$ such that $$$s_i = s_j + s_k$$$. That is, $$$s_i$$$ is the concatenation of $$$s_j$$$ and $$$s_k$$$. Note that $$$j$$$ can be equal to $$$k$$$.Recall that the concatenation of strings $$$s$$$ and $$$t$$$ is $$$s + t = s_1 s_2 \dots s_p t_1 t_2 \dots t_q$$$, where $$$p$$$ and $$$q$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. For example, concatenation of "code" and "forces" is "codeforces".

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of strings. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains non-empty string $$$s_i$$$ of length at most $$$\mathbf{8}$$$, consisting of lowercase English letters. Among the given $$$n$$$ strings, there may be equal (duplicates). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, output a binary string of length $$$n$$$. The $$$i$$$-th bit should be $$$\texttt{1}$$$ if there exist two strings $$$s_j$$$ and $$$s_k$$$ where $$$s_i = s_j + s_k$$$, and $$$\texttt{0}$$$ otherwise. Note that $$$j$$$ can be equal to $$$k$$$.

3

5

abab

ab

abc

abacb

c

3

x

xx

xxx

8

codeforc

es

codes

cod

forc

forces

e

code

NoteIn the first test case, we have the following:   $$$s_1 = s_2 + s_2$$$, since $$$\texttt{abab} = \texttt{ab} + \texttt{ab}$$$. Remember that $$$j$$$ can be equal to $$$k$$$.  $$$s_2$$$ is not the concatenation of any two strings in the list.  $$$s_3 = s_2 + s_5$$$, since $$$\texttt{abc} = \texttt{ab} + \texttt{c}$$$.  $$$s_4$$$ is not the concatenation of any two strings in the list.  $$$s_5$$$ is not the concatenation of any two strings in the list.  Since only $$$s_1$$$ and $$$s_3$$$ satisfy the conditions, only the first and third bits in the answer should be $$$\texttt{1}$$$, so the answer is $$$\texttt{10100}$$$.

#!/usr/bin/perl

use warnings;
use strict;
no warnings 'uninitialized';

$\ = $/;

<>;

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

	my %h;

	map $h{ $_ } = 1, @_;

	my $ANS;

	for( @_ ){
		my $ans = 0;
		while( /\B/g ){
			$ans ||= $h{ $` } * $h{ $' };
			}
		$ANS .= $ans;
		}

	print $ANS;
	}


In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.

The first line contains single integer n (1 ≤ n ≤ 2·105) — the length of the string.

Print the string that satisfies all the constraints. If there are multiple answers, print any of them.

NoteA palindrome is a sequence of characters which reads the same backward and forward.

print substr 'aabb' x ($_ / 4 + 1), 0, $_ for <>


Two pirates Polycarpus and Vasily play a very interesting game. They have n chests with coins, the chests are numbered with integers from 1 to n. Chest number i has ai coins. Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer x (2·x + 1 ≤ n) and take a coin from each chest with numbers x, 2·x, 2·x + 1. It may turn out that some chest has no coins, in this case the player doesn't take a coin from this chest. The game finishes when all chests get emptied.Polycarpus isn't a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily's moves.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of chests with coins. The second line contains a sequence of space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 1000), where ai is the number of coins in the chest number i at the beginning of the game.

Print a single integer — the minimum number of moves needed to finish the game. If no sequence of turns leads to finishing the game, print -1.

NoteIn the first test case there isn't a single move that can be made. That's why the players won't be able to empty the chests.In the second sample there is only one possible move x = 1. This move should be repeated at least 3 times to empty the third chest.

#!/usr/bin/perl -w

use strict;

use List::Util qw(max);

sub gao {
    my ($n, @a) = @_;
    return -1 if $n == 1 || $n % 2 == 0;
    my $ret = 0;
    for (my $i = $n; $i > 1; $i -= 2) {
        my $tmp = max(0, $a[$i], $a[$i - 1]);
        $ret += $tmp;
        $a[int($i / 2)] -= $tmp;
    }
    return $ret + max(0, $a[1]);
}

chomp(my $n = <>);
chomp($_ = <>);
my @a = (0, split);
my $res = &gao($n, @a);
print $res, "\n";