A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?

The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.

NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.

chomp (my @n = split /\s+/, <STDIN>);
chomp (my @str = split /\s*/, <STDIN>);

my %wt;
foreach ('a' .. 'z') {
  $wt{$_} = shift @n;
}

sub calc {
  my $s = 0;
  $s += $wt{$_} foreach (@_);
  return $s;
}

my %pos;
my @sum;
my $c = 0;

foreach my $x (0 .. $#str) {
  $sum[$x] = $wt{$str[$x]};
  $sum[$x] += $sum[$x - 1] if ($x > 0);
  push @{$pos{$str[$x]}}, $x;
}

# printf "@sum\n";
foreach my $l ('a' .. 'z') {
  my %map = ();
  foreach (@{$pos{$l}}) {
    # printf "Char: $l Pos: $_ Sum to p-1: $sum[$_ - 1] Sum to p: $sum[$_]\n";
    $c += $map{$sum[$_ - 1]} if exists $map{$sum[$_ - 1]};
    $map{$sum[$_]}++;
  }
}

printf "$c\n";

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

chomp (my @n = split /\s+/, <STDIN>);
chomp (my @str = split /\s*/, <STDIN>);

my %wt;
foreach ('a' .. 'z') {
  $wt{$_} = shift @n;
}

sub calc {
  my $s = 0;
  $s += $wt{$_} foreach (@_);
  return $s;
}

my %pos;
my @sum;
my $c = 0;

foreach my $x (0 .. $#str) {
  $sum[$x] = $wt{$str[$x]};
  $sum[$x] += $sum[$x - 1] if ($x > 0);
  push @{$pos{$str[$x]}}, $x;
}

printf "@sum\n";
foreach my $l ('a' .. 'z') {
  my %map = ();
  foreach (@{$pos{$l}}) {
    printf "Char: $l Pos: $_ Sum to p-1: $sum[$_ - 1] Sum to p: $sum[$_]\n";
    $c += $map{$sum[$_ - 1]} if exists $map{$sum[$_ - 1]};
    $map{$sum[$_]}++;
  }
}

printf "$c\n";

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

chomp (my @n = split /\s+/, <STDIN>);
chomp (my @str = split /\s*/, <STDIN>);

my %wt;
foreach ('a' .. 'z') {
  $wt{$_} = shift @n;
}

sub calc {
  my $s = 0;
  $s += $wt{$_} foreach (@_);
  return $s;
}

foreach my $x (0 .. $#str - 1) {
  foreach my $y ($x + 1 .. $#str) {
    printf "%s\n", join "", @str[$x .. $y] if (
      ($str[$x] eq $str[$y]) &&
      (&calc(@str[$x+1 .. $y-1]) == 0)
    );
  }
}


Kolya is going to make fresh orange juice. He has n oranges of sizes a1, a2, ..., an. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than d. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?

The first line of the input contains three integers n, b and d (1 ≤ n ≤ 100 000, 1 ≤ b ≤ d ≤ 1 000 000) — the number of oranges, the maximum size of the orange that fits in the juicer and the value d, which determines the condition when the waste section should be emptied. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1 000 000) — sizes of the oranges listed in the order Kolya is going to try to put them in the juicer.

Print one integer — the number of times Kolya will have to empty the waste section.

NoteIn the first sample, Kolya will squeeze the juice from two oranges and empty the waste section afterwards.In the second sample, the orange won't fit in the juicer so Kolya will have no juice at all.


You are living on an infinite plane with the Cartesian coordinate system on it. In one move you can go to any of the four adjacent points (left, right, up, down).More formally, if you are standing at the point $$$(x, y)$$$, you can:   go left, and move to $$$(x - 1, y)$$$, or  go right, and move to $$$(x + 1, y)$$$, or  go up, and move to $$$(x, y + 1)$$$, or  go down, and move to $$$(x, y - 1)$$$. There are $$$n$$$ boxes on this plane. The $$$i$$$-th box has coordinates $$$(x_i,y_i)$$$. It is guaranteed that the boxes are either on the $$$x$$$-axis or the $$$y$$$-axis. That is, either $$$x_i=0$$$ or $$$y_i=0$$$.You can collect a box if you and the box are at the same point. Find the minimum number of moves you have to perform to collect all of these boxes if you have to start and finish at the point $$$(0,0)$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of boxes. The $$$i$$$-th line of the following $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-100 \le x_i, y_i \le 100$$$) — the coordinate of the $$$i$$$-th box. It is guaranteed that either $$$x_i=0$$$ or $$$y_i=0$$$. Do note that the sum of $$$n$$$ over all test cases is not bounded.

For each test case output a single integer — the minimum number of moves required.

NoteIn the first test case, a possible sequence of moves that uses the minimum number of moves required is shown below.  $$$$$$(0,0) \to (1,0) \to (1,1) \to (1, 2) \to (0,2) \to (-1,2) \to (-1,1) \to (-1,0) \to (-1,-1) \to (-1,-2) \to (0,-2) \to (0,-1) \to (0,0)$$$$$$ In the second test case, a possible sequence of moves that uses the minimum number of moves required is shown below.  $$$$$$(0,0) \to (0,1) \to (0,2) \to (-1, 2) \to (-2,2) \to (-3,2) \to (-3,1) \to (-3,0) \to (-3,-1) \to (-2,-1) \to (-1,-1) \to (0,-1) \to (0,0)$$$$$$ In the third test case, we can collect all boxes without making any moves.


You are given an integer $$$n$$$.Let's define $$$s(n)$$$ as the string "BAN" concatenated $$$n$$$ times. For example, $$$s(1)$$$ = "BAN", $$$s(3)$$$ = "BANBANBAN". Note that the length of the string $$$s(n)$$$ is equal to $$$3n$$$.Consider $$$s(n)$$$. You can perform the following operation on $$$s(n)$$$ any number of times (possibly zero): Select any two distinct indices $$$i$$$ and $$$j$$$ $$$(1 \leq i, j \leq 3n, i \ne j)$$$. Then, swap $$$s(n)_i$$$ and $$$s(n)_j$$$. You want the string "BAN" to not appear in $$$s(n)$$$ as a subsequence. What's the smallest number of operations you have to do to achieve this? Also, find one such shortest sequence of operations.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 100)$$$  — the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 100)$$$.

For each test case, in the first line output $$$m$$$ ($$$0 \le m \le 10^5$$$) — the minimum number of operations required. It's guaranteed that the objective is always achievable in at most $$$10^5$$$ operations under the constraints of the problem.  Then, output $$$m$$$ lines. The $$$k$$$-th of these lines should contain two integers $$$i_k$$$, $$$j_k$$$ $$$(1\leq i_k, j_k \leq 3n, i_k \ne j_k)$$$ denoting that you want to swap characters at indices $$$i_k$$$ and $$$j_k$$$ at the $$$k$$$-th operation.  After all $$$m$$$ operations, "BAN" must not appear in $$$s(n)$$$ as a subsequence.  If there are multiple possible answers, output any.

NoteIn the first testcase, $$$s(1) = $$$ "BAN", we can swap $$$s(1)_1$$$ and $$$s(1)_2$$$, converting $$$s(1)$$$ to "ABN", which does not contain "BAN" as a subsequence.In the second testcase, $$$s(2) = $$$ "BANBAN", we can swap $$$s(2)_2$$$ and $$$s(2)_6$$$, converting $$$s(2)$$$ to "BNNBAA", which does not contain "BAN" as a subsequence.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	my $A = "BAN" x $_;

	my $B = "N" x $_ . "A" x $_;
	$B =~ s/(..)/B$1/g;

	my @S;
	my @F;

	for my $i ( 0 .. $_ * 3 - 1 ){
		if( "A" eq substr $A, $i, 1 and "N" eq substr $B, $i, 1 ){
			push @S, $i + 1;
			}
		if( "N" eq substr $A, $i, 1 and "A" eq substr $B, $i, 1 ){
			push @F, $i + 1;
			}
		}

	@_ = ();

	while( @S ){
		push @_, join ' ', shift @S, shift @F;
		}

	print for 0 + @_, @_;
	}


PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?

The first input line contains two integers n and m (1 ≤ n, m ≤ 103) — number of words PolandBall and EnemyBall know, respectively. Then n strings follow, one per line — words familiar to PolandBall. Then m strings follow, one per line — words familiar to EnemyBall. Note that one Ball cannot know a word more than once (strings are unique), but some words can be known by both players. Each word is non-empty and consists of no more than 500 lowercase English alphabet letters.

In a single line of print the answer — "YES" if PolandBall wins and "NO" otherwise. Both Balls play optimally.

2 2
kremowka
wadowicka
kremowka
wiedenska

NoteIn the first example PolandBall knows much more words and wins effortlessly.In the second example if PolandBall says kremowka first, then EnemyBall cannot use that word anymore. EnemyBall can only say wiedenska. PolandBall says wadowicka and wins.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my @n = map ~~<>, 1 .. $n;
	chomp @n;
	my %n = map { $_, undef } @n;

	my @m = map ~~<>, 1 .. $m;
	chomp @m;
	my %m = map { $_, undef } @m;

	my $i = 0;

	for (@m){
		exists $n{$_} or next;
		$i ++;
		if( $i % 2 ){
			delete $m{$_}
			}
		else {
			delete $n{$_}
			}
		}

	print qw(NO YES)[ (~~ keys %n) > (~~ keys %m) ];
	}


After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher gave them 3 strings and asked them to concatenate them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation.Unfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked.Now the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers.Shapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said:   As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin.  As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include "-", ";" and "_". These characters are my own invention of course! And I call them Signs.  The length of all initial strings was less than or equal to 100 and the lengths of my students' answers are less than or equal to 600  My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes.  Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN  You should indicate for any of my students if his answer was right or wrong. Do this by writing "WA" for Wrong answer or "ACC" for a correct answer.  I should remind you that none of the strings (initial strings or answers) are empty.  Finally, do these as soon as possible. You have less than 2 hours to complete this.

The first three lines contain a string each. These are the initial strings. They consists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). All the initial strings have length from 1 to 100, inclusively. In the fourth line there is a single integer n (0 ≤ n ≤ 1000), the number of students. Next n lines contain a student's answer each. It is guaranteed that the answer meets what the teacher said. Each answer iconsists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). Length is from 1 to 600, inclusively.

For each student write in a different line. Print "WA" if his answer is wrong or "ACC" if his answer is OK.

Iran_
Persian;
W_o;n;d;e;r;f;u;l;
7
WonderfulPersianIran
wonderful_PersIAN_IRAN;;_
WONDERFUL___IRAN__PERSIAN__;;
Ira__Persiann__Wonderful
Wonder;;fulPersian___;I;r;a;n;
__________IranPersianWonderful__________
PersianIran_is_Wonderful

Shapur;;
is___
a_genius
3
Shapur__a_is___geniUs
is___shapur___a__Genius;
Shapur;;is;;a;;geni;;us;;


Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.

The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.

Print single integer — the maximum number of Pokemons Bash can take.

Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.

my $poke_nr = <>;
my %pokemons;
my @numbers = split(" ", <>);
my $biggest_poke = 0;
my $max_poke = 0;
my $current_max = 0;
foreach(@numbers)
{
	if(exists($pokemons{$_}))
	{
		$pokemons{$_} = $pokemons{$_} + 1;
	}
	else
	{
		$pokemons{$_} = 1;
		if($_ > $biggest_poke)
		{
			$biggest_poke = $_;
		}
	}
}
foreach my $i(2 .. $biggest_poke)
{
	$current_max = 0;
	for(my $j = $i; $j <= $biggest_poke; $j += $i)
	{
		if(exists($pokemons{$j}))
		{
			$current_max += $pokemons{$j};
		}
	}
	if($current_max > $max_poke)
	{
		$max_poke = $current_max;
	}
}
if($max_poke > 0)
{
	print $max_poke;
}
else
{
	if(exists($pokemons{1}))
	{
		print 1;
	}
	else
	{
		print 0;
	}

}

my $poke_nr = <>;
my %pokemons;
my @numbers = split(" ", <>);
my $biggest_poke = 0;
my $max_poke = 0;
my $current_max = 0;
foreach(@numbers)
{
	if(exists($pokemons{$_}))
	{
		$pokemons{$_} = $pokemons{$_} + 1;
	}
	else
	{
		$pokemons{$_} = 1;
		if($_ > $biggest_poke)
		{
			$biggest_poke = $_;
		}
	}
}
foreach my $i(1 .. $biggest_poke)
{
	$current_max = 0;
	for(my $j = $i; $j <= $biggest_poke; $j += $i)
	{
		if(exists($pokemons{$j}))
		{
			$current_max += $pokemons{$j};
		}
	}
	if($current_max > $max_poke)
	{
		$max_poke = $current_max;
	}
}
print $max_poke;

my $poke_nr = <>;
my %pokemons;
my @numbers = split(" ", <>);
my $biggest_poke = 0;
my $max_poke = 0;
my $current_max = 0;
foreach(@numbers)
{
	if(exists($pokemons{$_}))
	{
		$pokemons{$_} = $pokemons{$_} + 1;
	}
	else
	{
		$pokemons{$_} = 1;
		if($_ > $biggest_poke)
		{
			$biggest_poke = $_;
		}
	}
}
foreach my $i(2 .. $biggest_poke)
{
	$current_max = 0;
	for(my $j = $i; $j <= $biggest_poke; $j += $i)
	{
		if(exists($pokemons{$j}))
		{
			$current_max += $pokemons{$j};
		}
	}
	if($current_max > $max_poke)
	{
		$max_poke = $current_max;
	}
}
print $max_poke;


The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:  ti = 1, if the i-th child is good at programming,  ti = 2, if the i-th child is good at maths,  ti = 3, if the i-th child is good at PE Each child happens to be good at exactly one of these three subjects.The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?

The first line contains integer n (1 ≤ n ≤ 5000) — the number of children in the school. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 3), where ti describes the skill of the i-th child.

In the first line output integer w — the largest possible number of teams.  Then print w lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to n in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them. If no teams can be compiled, print the only line with value w equal to 0.

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

sub min{
    return (sort {$a <=> $b} @_)[0];
}
sub len{
    return scalar @{$_[0]};
}

my $n = <>;
my @list = split ' ',<>;
my @arr;
push @arr,[] for 0..3;
for my $i(0..$n-1){
    my $val = $list[$i];
    push @{$arr[$val]}, $i+1;
}
my $min = min(len($arr[1]), len($arr[2]), len($arr[3]));
print $min, "\n";
for my $i(0..$min-1){
    print "$arr[1][$i] $arr[2][$i] $arr[3][$i]\n";
}

<>;
$_=<>;
s/\s//g;
while(/1/g){push @a, pos}
while(/2/g){push @b, pos}
while(/3/g){push @c, pos}
$min = (sort {$a <=> $b} (0+@a, 0+@b, 0+@c) )[0];
print $min, $/;
while($min--){
	printf "%d %d %d\n", shift @a, shift @b, shift @c
	}

use strict;
use warnings;

<>;
my @kids = split ' ', <>;
my @teams;
my %kinds;

for my $i (0..$#kids) {
    push @{$kinds{$kids[$i]}}, $i + 1;
}

OUTER: for (;;) {
    my @line;
    for (1..3) {
        my $m = shift @{$kinds{$_}};
        last OUTER unless defined $m;
        push @line, $m;
    }
    push @teams, \@line;
}

$\ = "\n";
$, = ' ';

print scalar @teams;
print @$_ for @teams;

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

<>;
my @students = split(' ', <>);
my @pro; my @ma; my @pre;
my $idx;
for my $el(@students){
	++$idx;
	if($el == 1){push (@pro, $idx);}
	elsif($el == 2){push (@ma, $idx);}
	else{push (@pre, $idx);}
}

$idx = $#pro;	if($#ma < $idx){$idx = $#ma;} if($#pre < $idx){$idx = $#pre;} $idx ++;
print "$idx\n";
while($#pro >= 0 && $#ma >= 0 && $#pre >= 0){
	print ((pop @pro), " ", (pop @ma), " ", (pop @pre), "\n");
}

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

<>;
my @students = split(' ', <>);
my @pro; my @ma; my @pre;
my $idx;
for my $el(@students){
	++$idx;
	if($el == 1){push (@pro, $idx);}
	elsif($el == 2){push (@ma, $idx);}
	else{push (@pre, $idx);}
}

while($#pro >= 0 && $#ma >= 0 && $#pre >= 0){
	print ((pop @pro), " ", (pop @ma), " ", (pop @pre), "\n");
}

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

<>;
my @students = split(' ', <>);
my @pro; my @ma; my @pre;
my $idx;
for my $el(@students){
	++$idx;
	if($el == 1){push (@pro, $idx);}
	elsif($el == 2){push (@ma, $idx);}
	else{push (@pre, $idx);}
}
$idx = scalar @pro; $idx < scalar @ma ? $idx : $idx = scalar @ma;  $idx < scalar @pre ? $idx : $idx = scalar @pre;
print "$idx\n";
while($#pro >= 0 && $#ma >= 0 && $#pre >= 0){
	print ((pop @pro), " ", (pop @ma), " ", (pop @pre), "\n");
}

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

<>;
my @students = split(' ', <>);
my @pro; my @ma; my @pre;
my $idx;
for my $el(@students){
	++$idx;
	if($el == 1){push (@pro, $idx);}
	elsif($el == 2){push (@ma, $idx);}
	else{push (@pre, $idx);}
}
$idx = $#pro; $idx < $#ma ? $idx : $idx = $#ma;  $idx < $#pre ? $idx : $idx = $#pre; $idx++;
print "$idx\n";
while($#pro >= 0 && $#ma >= 0 && $#pre >= 0){
	print ((pop @pro), " ", (pop @ma), " ", (pop @pre), "\n");
}


A tree is a connected undirected graph consisting of n vertices and n  -  1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:  The tree had exactly n vertices.  The tree had diameter d. In other words, d was the biggest distance between two vertices.  Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".

The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.

If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.

NoteBelow you can see trees printed to the output in the first sample and the third sample.


Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.

The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$ — the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).

For each test case print a single integer $$$d$$$ — the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.

NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	print $_[ 0 ];
	}


And where the are the phone numbers?You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.It's guaranteed that the answer exists.Note that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is {a, b, d}.String p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q or there exists i, such that pi < qi and for all j < i it is satisfied that pj = qj. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa is not lexicographically smaller than ab and a is not lexicographically smaller than a.

The first line of input contains two space separated integers n and k (1 ≤ n, k ≤ 100 000) — the length of s and the required length of t. The second line of input contains the string s consisting of n lowercase English letters.

Output the string t conforming to the requirements above. It's guaranteed that the answer exists.

NoteIn the first example the list of strings t of length 3, such that the set of letters of t is a subset of letters of s is as follows: aaa, aab, aac, aba, abb, abc, aca, acb, .... Among them, those are lexicographically greater than abc: aca, acb, .... Out of those the lexicographically smallest is aca.

#!/usr/bin/perl

use warnings;
use strict;

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

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

	$_ = <>, chomp;
	@_ = split //;

	my %h;

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

	my @az = sort keys %h;

	my( $min, $max ) = @az[ 0, -1 ];

	my $az = join '', @az;

	$debug and print "[$min]";

	if( $k > $n ){
		$debug and print '>';
		print $_ . $min x ( $k - $n );
		}
	else{
		for my $i ( reverse 0 .. $k - 1 ){
			if( $_[ $i ] ne $max ){
				print @_[ 0 .. $i - 1 ],
					( grep $_ gt $_[ $i ], @az )[ 0 ],
					( $min ) x ( $k - $i - 1 );
				last;
				}
			}
		}
	}

#!/usr/bin/perl

use warnings;
use strict;

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

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

	$_ = <>, chomp;

	my %h;

	map $h{ $_ } ++, split //;

	my @az = sort keys %h;

	my( $min, $max ) = @az[ 0, -1 ];

	$debug and print "[$min|$max]";

	my $pos = -1;

	/
		(?= (.)(.) )
		(?{
			$1 lt $2 and $pos = pos;
		})
		(*FAIL)
	/x;

	my $next = 0;
	my $ans = '';

	if( $k > $n ){
		$debug and print '>';
		print $_ . $az[ 0 ] x ( $k - $n );
		}
	else{
		for my $lett ( reverse( ( split // )[ 0 .. $k - 1 ] ) ){
			$debug and print $lett;
			$next and do {
				$ans .= $lett;
				next;
				};

			if( $lett eq $max ){
				$ans .= $min;
				}
			else{
				$ans .= $max;
				$next = 1;
				}
			}
		print scalar reverse $ans;
		}
	}


In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.

The first line contains the integer n (1 ≤ n ≤ 100) — the number of citizens in the kingdom. The second line contains n integers a1, a2, ..., an, where ai (0 ≤ ai ≤ 106) — the welfare of the i-th citizen.

In the only line print the integer S — the minimum number of burles which are had to spend.

NoteIn the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.In the second example it is enough to give one burle to the third citizen. In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles.

use 5.016;
use strict;
use warnings;

sub max {
  my $max = shift;
  local $_;

  for (@_) {
    $max = $_ if $_ > $max;
  }
  $max;
}

sub sum {
  local $_;
  my $sum = 0;
  $sum += $_ for @_;
  $sum;
}

<>;
my @welfare = split ' ', <>;
my $max = max(@welfare);

say sum map { $max - $_ } @welfare;

#!/usr/bin/env perl

use strict;
use warnings;
use feature qw/ say /;

# send argument as array, not reference, to function requiring list

# essential
my @tokens = ();

sub ceil {
    my $n = shift;
    my $in = int($n);
    return $n if $in == $n;
    return $in + 1;
}

sub read_line {
    chomp (my $line = <STDIN>);
    return $line;
}

sub read_token {
    @tokens = split q{ }, read_line() if @tokens == 0;
    return shift @tokens;
}

sub min {
    my @numbers = @_;
    my $min = shift @numbers;
    for ( @numbers ) {
        $min = $min<$_ ? $min : $_;
    }
    return $min;
}

sub max {
    my @numbers = @_;
    my $max = shift @numbers;
    for ( @numbers ) {
        $max = $max > $_ ? $max : $_;
    }
    return $max;
}

sub sum {
    my @numbers = @_;
    my $sum = 0;
    for (@numbers) {
        $sum += $_;
    }
    return $sum;
}

# solve

my $n = read_token;

my @welfares = split q{ }, read_line;

my $max = max(@welfares);

my $answer = 0;

for (@welfares) {
    $answer += $max - $_;
}

say $answer;


Let's call an array $$$a_1, a_2, \dots, a_m$$$ of nonnegative integer numbers good if $$$a_1 + a_2 + \dots + a_m = 2\cdot(a_1 \oplus a_2 \oplus \dots \oplus a_m)$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.For example, array $$$[1, 2, 3, 6]$$$ is good, as $$$1 + 2 + 3 + 6 = 12 = 2\cdot 6 = 2\cdot (1\oplus 2 \oplus 3 \oplus 6)$$$. At the same time, array $$$[1, 2, 1, 3]$$$ isn't good, as $$$1 + 2 + 1 + 3 = 7 \neq 2\cdot 1 = 2\cdot(1\oplus 2 \oplus 1 \oplus 3)$$$.You are given an array of length $$$n$$$: $$$a_1, a_2, \dots, a_n$$$. Append at most $$$3$$$ elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don't have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n \le 10^5)$$$ — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0\le a_i \le 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output two lines. In the first line, output a single integer $$$s$$$ ($$$0\le s\le 3$$$) — the number of elements you want to append. In the second line, output $$$s$$$ integers $$$b_1, \dots, b_s$$$ ($$$0\le b_i \le 10^{18}$$$) — the elements you want to append to the array. If there are different solutions, you are allowed to output any of them.

NoteIn the first test case of the example, the sum of all numbers is $$$12$$$, and their $$$\oplus$$$ is $$$6$$$, so the condition is already satisfied.In the second test case of the example, after adding $$$4, 4$$$, the array becomes $$$[8, 4, 4]$$$. The sum of numbers in it is $$$16$$$, $$$\oplus$$$ of numbers in it is $$$8$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

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

	@_ = split ' ', <>;

	$debug and print "[@_]";

	my $sum = 0;

	$sum += $_ for @_;

	my $xor = 0;

	$xor ^= $_ for @_;

	$debug and print "sum:[$sum]";
	$debug and print "xor:[$xor]";

	my $Bsum = sprintf "%0b", $sum;
	my $Bxor = sprintf "%0b", $xor;

	$debug and print "Bsum:[$Bsum]";
	$debug and print "Bxor:[$Bxor]";

	my @ans;

	push @ans, $xor;

	$sum += $xor;
	$xor ^= $xor;

	$Bsum = sprintf "%0b", $sum;
	$Bxor = sprintf "%0b", $xor;

	$debug and print "Bsum:[$Bsum]";
	$debug and print "Bxor:[$Bxor]";

	push @ans, $sum;

	print for ~~ @ans, "@ans";
	}


Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:  Include a person to the chat ('Add' command).  Remove a person from the chat ('Remove' command).  Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.

Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:   +<name> for 'Add' command.  -<name> for 'Remove' command.  <sender_name>:<message_text> for 'Send' command.  <name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line. It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc. All names are case-sensitive.

Print a single number — answer to the problem.

+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate

+Mike
-Mike
+Mike
Mike:Hi   I am here
-Mike
+Kate
-Kate

#!/usr/bin/perl

main();

sub main {
    my %hash = ();
    my $line;
    my $ans = 0;
    while ($line = <>) {
        if ($line =~ /^\+/) {
            $line =~ s/^\+//;
            $hash{$line} = 1;
            next;
        }
        if ($line =~ /^-/) {
            $line =~ s/^-//;
            delete $hash{$line};
            next;
        }
        my $cnt = keys (%hash);
        $line =~ s/^[\S]+://g;
        $line =~ s/[^\w ]+//g;
        $ans += length ($line) * $cnt;
    }
    print ("$ans\n");
}

#!/usr/bin/perl

my @users;
my $total = 0;
my $len;

while (<>) {
    chomp $_;
    if (/\+/) {
	$_ =~ s/\+//;
	push @users, $_;
    } elsif (/\-/) {
	$_ =~ s/\-//;
	for my $i (0 .. $#users){
	    if ($users[$i] eq $_) {
		splice(@users, $i, 1, ());
	    }
	}
    } else {
	$_ =~ s/([\w]*:)//;
	$total += (scalar @users) * (length $_);
    }
}

print $total

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

my %ch;my $snd;my $traf=0;my $com;my $msg;my $come;
for(1..100){
    $come=<STDIN>;
    chomp($come);
    if($come eq ""){ last;}
    if($come=~/\A[\+]/){$com=$come=~s/[\+]//r; $ch{$com}=1;}
    elsif($come=~/\A[\-]/){$com=$come=~s/[\-]//r; $ch{$com}=0;}
    elsif($come=~/:/){
	($snd,$msg)=split/:/,$come;chomp($msg);
	foreach(keys %ch){ if($ch{$_}==1){$traf+=length($msg);}}
    }
}
print $traf."\n";


Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:   The product of all numbers in the first set is less than zero ( < 0).  The product of all numbers in the second set is greater than zero ( > 0).  The product of all numbers in the third set is equal to zero.  Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.

The first line of the input contains integer n (3 ≤ n ≤ 100). The second line contains n space-separated distinct integers a1, a2, ..., an (|ai| ≤ 103) — the array elements.

In the first line print integer n1 (n1 > 0) — the number of elements in the first set. Then print n1 numbers — the elements that got to the first set. In the next line print integer n2 (n2 > 0) — the number of elements in the second set. Then print n2 numbers — the elements that got to the second set. In the next line print integer n3 (n3 > 0) — the number of elements in the third set. Then print n3 numbers — the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.

#!/usr/bin/perl

use strict;
use warnings;

chomp(my $n = <>);
chomp($_ = <>);
my @a = split;
my @pos  = grep { $_ > 0 } @a;
my @neg  = grep { $_ < 0 } @a;
my @zero = grep { $_ == 0 } @a;

my @set1 = ();
my @set2 = ();
my @set3 = ();

if (@pos) {
    push @set1, shift @neg;
    push @set2, shift @pos;
    push @set3, @pos;
    push @set3, @neg;
    push @set3, @zero;
} else {
    push @set1, shift @neg;
    push @set2, shift @neg;
    push @set2, shift @neg;
    push @set3, @pos;
    push @set3, @neg;
    push @set3, @zero;
}

unshift @set1, scalar @set1;
unshift @set2, scalar @set2;
unshift @set3, scalar @set3;
print "@set1\n@set2\n@set3\n";

#!/usr/bin/perl
#

while ($eil=<>) {

$num = <>;
@num = split/ /,$num;
chomp @num;

$i=0;
@a1 = @a2 = @a3 = ();
foreach (@num){
    if ($_==0) {push @a3, $_}
    elsif ($_<0 and $i==0) {push @a1, $_; $i++}
    else {push @a2, $_}
    }
print "@num\n";
print "1 @a1\n";
print scalar @a2, " @a2\n";
print scalar @a3, " @a3\n";

}

#!/usr/bin/perl
#

while ($eil=<>) {

$num = <>;
@num = split/ /,$num;
chomp @num;

$i=0;
@a1 = @a2 = @a3 = ();
foreach (@num){
    if ($_==0) {push @a3, $_}
    elsif ($_<0 and $i==0) {push @a1, $_; $i++}
    else {push @a2, $_}
    }
# print "@num\n";
print "1 @a1\n";
print scalar @a2, " @a2\n";
print scalar @a3, " @a3\n";

}


Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:  Walk up or down one unit on a tree.  Eat a nut on the top of the current tree.  Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h > hi + 1. Compute the minimal time (in seconds) required to eat all nuts.

The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.

Print a single integer — the minimal time required to eat all nuts in seconds.


You are given an array of $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$. Your task is to calculate the number of arrays of $$$n$$$ positive integers $$$b_1, b_2, \ldots, b_n$$$ such that:   $$$1 \le b_i \le a_i$$$ for every $$$i$$$ ($$$1 \le i \le n$$$), and  $$$b_i \neq b_{i+1}$$$ for every $$$i$$$ ($$$1 \le i \le n - 1$$$). The number of such arrays can be very large, so print it modulo $$$998\,244\,353$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print the answer modulo $$$998\,244\,353$$$ in a single line.

NoteIn the first test case possible arrays are $$$[1, 2, 1]$$$ and $$$[2, 1, 2]$$$.In the second test case possible arrays are $$$[1, 2]$$$, $$$[1, 3]$$$, $$$[2, 1]$$$ and $$$[2, 3]$$$.


There are $$$n$$$ participants in a competition, participant $$$i$$$ having a strength of $$$s_i$$$. Every participant wonders how much of an advantage they have over the other best participant. In other words, each participant $$$i$$$ wants to know the difference between $$$s_i$$$ and $$$s_j$$$, where $$$j$$$ is the strongest participant in the competition, not counting $$$i$$$ (a difference can be negative).So, they ask you for your help! For each $$$i$$$ ($$$1 \leq i \leq n$$$) output the difference between $$$s_i$$$ and the maximum strength of any participant other than participant $$$i$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 2\cdot10^5$$$) — the length of the array. The following line contains $$$n$$$ space-separated positive integers $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$1 \leq s_i \leq 10^9$$$) — the strengths of the participants. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, output $$$n$$$ space-separated integers. For each $$$i$$$ ($$$1 \leq i \leq n$$$) output the difference between $$$s_i$$$ and the maximum strength of any other participant.

NoteFor the first test case: The first participant has a strength of $$$4$$$ and the largest strength of a participant different from the first one is $$$7$$$, so the answer for the first participant is $$$4 - 7 = -3$$$.  The second participant has a strength of $$$7$$$ and the largest strength of a participant different from the second one is $$$5$$$, so the answer for the second participant is $$$7 - 5 = 2$$$. The third participant has a strength of $$$3$$$ and the largest strength of a participant different from the third one is $$$7$$$, so the answer for the third participant is $$$3 - 7 = -4$$$. The fourth participant has a strength of $$$5$$$ and the largest strength of a participant different from the fourth one is $$$7$$$, so the answer for the fourth participant is $$$5 - 7 = -2$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my( $max, $smax ) = sort { $b <=> $a } @_;

	$_ -= $max for @_;

	$_ ||= $max - $smax for @_;

	print "@_";
	}


Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.

The first line contains three integers h1, a1, c1 (1 ≤ h1, a1 ≤ 100, 2 ≤ c1 ≤ 100) — Vova's health, Vova's attack power and the healing power of a potion. The second line contains two integers h2, a2 (1 ≤ h2 ≤ 100, 1 ≤ a2 < c1) — the Modcrab's health and his attack power.

In the first line print one integer n denoting the minimum number of phases required to win the battle. Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab. The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action. If there are multiple optimal solutions, print any of them.

NoteIn the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $h1, $a1, $c ) = split;
	my( $h2, $a2 ) = split ' ', <>;

	my @moves;

	while( 1 ){
		if( $h1 - $a2 > 0 || $a1 >= $h2 ){
			push @moves, 'STRIKE';
			$h2 -= $a1;
			$h2 <= 0 and last;
			}
		else{
			push @moves, 'HEAL';
			$h1 += $c;
			}
		$h1 -= $a2;
		}

	print ~~ @moves;
	print for @moves;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $h1, $a1, $c ) = split;
	my( $h2, $a2 ) = split ' ', <>;

	my @moves;

	while( 1 ){
		if( $h1 - $a2 > 0 ){
			push @moves, 'STRIKE';
			$h2 -= $a1;
			$h2 <= 0 and last;
			}
		else{
			push @moves, 'HEAL';
			$h1 += $c;
			}
		$h1 -= $a2;
		}

	print ~~ @moves;
	print for @moves;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $h1, $a1, $c ) = split;
	my( $h2, $a2 ) = split ' ', <>;

	my @moves;

	while( 1 ){
		if( $h1 - $a2 > 0 ){
			push @moves, 'STRIKE';
			$h2 -= $a1;
			$h2 <= 0 and last;
			$h1 -= $a2;
			}
		else{
			push @moves, 'HEAL';
			$h1 += $c;
			}
		}

	print ~~ @moves;
	print for @moves;
	}


Tired of boring office work, Denis decided to open a fast food restaurant.On the first day he made $$$a$$$ portions of dumplings, $$$b$$$ portions of cranberry juice and $$$c$$$ pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:  every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);  each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;  all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?

The first line contains an integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases to solve. Each of the remaining $$$t$$$ lines contains integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \leq a, b, c \leq 10$$$) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.

For each test case print a single integer — the maximum number of visitors Denis can feed.

NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.


Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri, and its elements are a[li], a[li + 1], ..., a[ri].Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible. You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.The mex of a set S is a minimum possible non-negative integer that is not in S.

The first line contains two integers n and m (1 ≤ n, m ≤ 105). The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), that describe the subarray a[li], a[li + 1], ..., a[ri].

In the first line print single integer — the maximum possible minimum mex. In the second line print n integers — the array a. All the elements in a should be between 0 and 109. It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 109. If there are multiple solutions, print any of them.

NoteThe first example: the mex of the subarray (1, 3) is equal to 3, the mex of the subarray (2, 5) is equal to 3, the mex of the subarray (4, 5) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona is equal to 2.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){

	my( $n, $m ) = split;

	my $min = (sort {$a <=> $b} map { 0 - eval join '-', split ' ', <> } 1 .. $m )[ 0 ];

	print 1 + $min;
	print join " ", ( (0 .. $min) x (1 + $n / ( $min || 1 ) ) )[ 0 .. $n - 1 ];

	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){

	my( $n, $m ) = split;

	my $min = (sort {$a <=> $b} map { 0 - eval join '-', split ' ', <> } 1 .. $m )[ 0 ];

	print 1 + $min;
	print do { local $, = " "; ( (0 .. $min) x (1 + $n / $min) )[ 0 .. $n - 1 ] };

	}


You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).You've got some number of pairs (ai, bi). How many operations will be performed for each of them?

The first line contains the number of pairs n (1  ≤  n  ≤  1000). Then follow n lines, each line contains a pair of positive integers ai, bi (1  ≤  ai,  bi  ≤  109).

Print the sought number of operations for each pair on a single line.

for(1..<>){
	($a, $b) = split(' ', <>);
	$sum = 0;
	until($a == 0 or $b == 0){
	$sum += int($a / $b) and $a %= $b and next if $a >= $b and $b != 0;
	$sum += int($b / $a) and $b %= $a and next if $b >= $a and $a != 0	;}
	print "$sum\n";
		}


You are given an array consisting of $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. Initially $$$a_x = 1$$$, all other elements are equal to $$$0$$$.You have to perform $$$m$$$ operations. During the $$$i$$$-th operation, you choose two indices $$$c$$$ and $$$d$$$ such that $$$l_i \le c, d \le r_i$$$, and swap $$$a_c$$$ and $$$a_d$$$.Calculate the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the description of $$$t$$$ testcases follow. The first line of each test case contains three integers $$$n$$$, $$$x$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 100$$$; $$$1 \le x \le n$$$). Each of next $$$m$$$ lines contains the descriptions of the operations; the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).

For each test case print one integer — the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

NoteIn the first test case, it is possible to achieve $$$a_k = 1$$$ for every $$$k$$$. To do so, you may use the following operations:  swap $$$a_k$$$ and $$$a_4$$$;  swap $$$a_2$$$ and $$$a_2$$$;  swap $$$a_5$$$ and $$$a_5$$$. In the second test case, only $$$k = 1$$$ and $$$k = 2$$$ are possible answers. To achieve $$$a_1 = 1$$$, you have to swap $$$a_1$$$ and $$$a_1$$$ during the second operation. To achieve $$$a_2 = 1$$$, you have to swap $$$a_1$$$ and $$$a_2$$$ during the second operation.


Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

First line of the input contains a single integer n (1 ≤ n ≤ 2·105), the length of the string that Andreid has. The second line contains the string of length n consisting only from zeros and ones.

Output the minimum length of the string that may remain after applying the described operations several times.

NoteIn the first sample test it is possible to change the string like the following: .In the second sample test it is possible to change the string like the following: .In the third sample test it is possible to change the string like the following: .

my $n = int<>;
my @arr = split //, <>;
my @stack = ();
my $ans = $n;
push @stack, shift @arr;
for (2..$n) {
    push @stack, shift @arr;
    if (scalar @stack > 1 && $stack[-1] != $stack[-2]) {
        pop @stack;
        pop @stack;
    }
}
print scalar @stack;

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

my ($n, $line, $on, $zn) = (<>, <>, 0, 0);
chomp $line;
$_>0 and ++$on or ++$zn foreach (split //, $line);
say abs($zn-$on);

use 5.016;
use strict;
use warnings;

sub abs {
  my ($x) = @_;
  $x < 0 ? -$x : $x;
}

<>;
chomp (my $bits = <>);

my $zero = $bits =~ tr/0//d;
my $one = $bits =~ tr/1//d;
say abs($one - $zero);

use strict;
use warnings;
#!/usr/bin/perl
#$, = " ";

$a = <>;
$a = <>;
chomp($a);
my ($zero, $one) = (0,0);
foreach my $i (0..length($a)-1) {
	$zero += (substr($a,$i,1)=='0');
	$one += (substr($a,$i,1)=='1');
}
print abs($zero-$one);


Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k + 1). When the player have made such a move, its energy increases by hk - hk + 1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers h1, h2, ..., hn (1  ≤  hi  ≤  105) representing the heights of the pylons.

Print a single number representing the minimum number of dollars paid by Caisa.

NoteIn the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon.

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

chomp($n = <>);
$ans = 0;
$ans=$_>$ans ? $_:$ans foreach (split / /, <>);
say $ans;


You are given two polynomials:  P(x) = a0·xn + a1·xn - 1 + ... + an - 1·x + an and  Q(x) = b0·xm + b1·xm - 1 + ... + bm - 1·x + bm.  Calculate limit .

The first line contains two space-separated integers n and m (0 ≤ n, m ≤ 100) — degrees of polynomials P(x) and Q(x) correspondingly. The second line contains n + 1 space-separated integers — the factors of polynomial P(x): a0, a1, ..., an - 1, an ( - 100 ≤ ai ≤ 100, a0 ≠ 0). The third line contains m + 1 space-separated integers — the factors of polynomial Q(x): b0, b1, ..., bm - 1, bm ( - 100 ≤ bi ≤ 100, b0 ≠ 0).

If the limit equals  + ∞, print "Infinity" (without quotes). If the limit equals  - ∞, print "-Infinity" (without the quotes). If the value of the limit equals zero, print "0/1" (without the quotes). Otherwise, print an irreducible fraction — the value of limit , in the format "p/q" (without the quotes), where p is the — numerator, q (q > 0) is the denominator of the fraction.

NoteLet's consider all samples:           You can learn more about the definition and properties of limits if you follow the link: http://en.wikipedia.org/wiki/Limit_of_a_function


PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the following process n times, starting from the vertex 1: Assume you've ended last operation in vertex x (consider x = 1 if it is the first operation). Draw a new segment from vertex x to k-th next vertex in clockwise direction. This is a vertex x + k or x + k - n depending on which of these is a valid index of polygon's vertex.Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.

There are only two numbers in the input: n and k (5 ≤ n ≤ 106, 2 ≤ k ≤ n - 2, gcd(n, k) = 1).

You should print n values separated by spaces. The i-th value should represent number of polygon's sections after drawing first i lines.

NoteThe greatest common divisor (gcd) of two integers a and b is the largest positive integer that divides both a and b without a remainder.For the first sample testcase, you should output "2 3 5 8 11". Pictures below correspond to situations after drawing lines.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $n, $k ) = split;
	$k = ( sort { $a <=> $b } $n - $k, $k )[ 0 ];

	my $L = 0;
	my $sect = 1;
	my $plus = 1;
	my @sect;

	for my $i (1 .. $n){
		$L += $k;
		if( $L > $n ){
			$plus ++;
			push @sect, $sect += $plus;
			$plus ++;
			$L %= $n;
			}
		else{
			push @sect, $sect += $plus;
			}

		}

	print "@sect";
	}


There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.

The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.

If there is no way to assigns seats to parliamentarians in a proper way print -1. Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.

NoteIn the first sample there are many other possible solutions. For example, 3 20 1and 2 13 0The following assignment 3 21 0is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.


ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal —  and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?

The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0.

Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output  - 1 instead. If there are multiple solutions, you may print any of them.

NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square.


Another Codeforces Round has just finished! It has gathered $$$n$$$ participants, and according to the results, the expected rating change of participant $$$i$$$ is $$$a_i$$$. These rating changes are perfectly balanced — their sum is equal to $$$0$$$.Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.There are two conditions though:   For each participant $$$i$$$, their modified rating change $$$b_i$$$ must be integer, and as close to $$$\frac{a_i}{2}$$$ as possible. It means that either $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$ or $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. In particular, if $$$a_i$$$ is even, $$$b_i = \frac{a_i}{2}$$$. Here $$$\lfloor x \rfloor$$$ denotes rounding down to the largest integer not greater than $$$x$$$, and $$$\lceil x \rceil$$$ denotes rounding up to the smallest integer not smaller than $$$x$$$.  The modified rating changes must be perfectly balanced — their sum must be equal to $$$0$$$. Can you help with that?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 13\,845$$$), denoting the number of participants. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$-336 \le a_i \le 1164$$$), denoting the rating change of the $$$i$$$-th participant. The sum of all $$$a_i$$$ is equal to $$$0$$$.

Output $$$n$$$ integers $$$b_i$$$, each denoting the modified rating change of the $$$i$$$-th participant in order of input. For any $$$i$$$, it must be true that either $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$ or $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. The sum of all $$$b_i$$$ must be equal to $$$0$$$. If there are multiple solutions, print any. We can show that a solution exists for any valid input.

NoteIn the first example, $$$b_1 = 5$$$, $$$b_2 = -3$$$ and $$$b_3 = -2$$$ is another correct solution.In the second example there are $$$6$$$ possible solutions, one of them is shown in the example output.

#!/usr/bin/perl

use warnings;
use strict;
use integer;

$\ = $/;

my $debug = 0;

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

	@_ = map ~~<>, 1 .. $_;
	chomp @_;

	$debug and print for @_;

	my $negative = grep { /-/ and $_ % 2 } @_;
	my $positive = grep { !/-/ and $_ % 2 } @_;

	my $diff = $positive - $negative;

	$debug and print "diff: [$diff]";

	if( $diff > 0 ){
		for( @_ ){
			if( !/-/ and $_ % 2 and $diff > 0 ){
				$_ /= 2;
				$_ ++;
				$diff -= 2;
				}
			else{
				$_ /= 2;
				}
			}
		}
	elsif( $diff <= 0 ){
		for( @_ ){
			if( /-/ and $_ % 2 and $diff < 0 ){
				$_ /= 2;
				$_ --;
				$diff += 2;
				}
			else{
				$_ /= 2;
				}
			}
		}

	my $sum = 0;
	$sum += $_ for @_;

	$debug and print "sum: [$sum]";

	print for @_;
	}


Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!".Not all students are equally sociable. About each student you know the value ai — the maximum number of messages which the i-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that:  the student i sends no more than ai messages (for all i from 1 to n);  all students knew the news about the credit (initially only Polycarp knew it);  the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from 1 to n, and Polycarp always has the number 1.In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above.

The first line contains the positive integer n (2 ≤ n ≤ 100) — the number of students.  The second line contains the sequence a1, a2, ..., an (0 ≤ ai ≤ 100), where ai equals to the maximum number of messages which can the i-th student agree to send. Consider that Polycarp always has the number 1.

Print -1 to the first line if it is impossible to inform all students about credit.  Otherwise, in the first line print the integer k — the number of messages which will be sent. In each of the next k lines print two distinct integers f and t, meaning that the student number f sent the message with news to the student number t. All messages should be printed in chronological order. It means that the student, who is sending the message, must already know this news. It is assumed that students can receive repeated messages with news of the credit.  If there are several answers, it is acceptable to print any of them.

NoteIn the first test Polycarp (the student number 1) can send the message to the student number 2, who after that can send the message to students number 3 and 4. Thus, all students knew about the credit.

use strict;
use warnings;

sub next_student_id
{
	my $students_ref = shift;

	my ($id, $msg_cnt, $left_cnt);
	for (my $i = 0; $i < @{ $students_ref }; $i++) {
		next if $students_ref->[$i]->{notified};

		if (not $id or $msg_cnt < $students_ref->[$i]->{msg_cnt}) {
			$msg_cnt = $students_ref->[$i]->{msg_cnt};
			$id = $i;
		}

		$left_cnt++;
	}

	return ($id, $left_cnt);
}

sub send_notifications
{
	my ($sender_id, $students_ref) = @_;

	$students_ref->[$sender_id]->{notified} = 1;

	my ($sent_cnt, $sequence) = (0, "");
	while ($students_ref->[$sender_id]->{msg_cnt} != 0) {
		my ($receiver_id, $left_cnt) = next_student_id($students_ref);
		return ($sent_cnt, $sequence, 1) unless defined $receiver_id;

		$students_ref->[$sender_id]->{msg_cnt}--;
		$left_cnt--;

		$sequence .= sprintf "%u %u\n", $sender_id+1, $receiver_id+1;
		$sent_cnt++;

		my ($new_sent_cnt, $new_sequence, $stop) = send_notifications($receiver_id, $students_ref);
		$sent_cnt += $new_sent_cnt;
		$sequence .= $new_sequence;

		return ($sent_cnt, $sequence, 1)
			if $stop or $left_cnt == 0;
	}

	return ($sent_cnt, $sequence);
}

my $n = <> + 0;
my @students = map { { msg_cnt => $_ } } split /\s+/, <>;

my ($msg_cnt, $sequence, $done) = send_notifications(0, \@students);
if (not $done) {
	print "-1\n";
} else {
	print "$msg_cnt\n$sequence";
}

use strict;
use warnings;

sub next_student_id
{
	my $students_ref = shift;

	my ($id, $msg_cnt);
	for (my $i = 0; $i < @{ $students_ref }; $i++) {
		next if $students_ref->[$i]->{notified};

		if (not $id or $msg_cnt < $students_ref->[$i]->{msg_cnt}) {
			$msg_cnt = $students_ref->[$i]->{msg_cnt};
			$id = $i;
		}
	}

	return $id;
}

sub send_notifications
{
	my ($sender_id, $students_ref) = @_;

	my ($sent_cnt, $sequence) = (0, "");
	while ($students_ref->[$sender_id]->{msg_cnt} != 0) {
		my $receiver_id = next_student_id($students_ref);
		return ($sent_cnt, $sequence, 1) unless defined $receiver_id;

		$students_ref->[$receiver_id]->{notified} = 1;
		$students_ref->[$sender_id]->{msg_cnt}--;
		$sequence .= sprintf "%u %u\n", $sender_id+1, $receiver_id+1;
		$sent_cnt++;

		my ($new_sent_cnt, $new_sequence, $stop) = send_notifications($receiver_id, $students_ref);
		$sent_cnt += $new_sent_cnt;
		$sequence .= $new_sequence;

		return ($sent_cnt, $sequence, 1) if $stop;
	}

	return ($sent_cnt, $sequence);
}

my $n = <> + 0;
my @students = map { { msg_cnt => $_ } } split /\s+/, <>;

$students[0]->{notified} = 1; # policarp

my ($msg_cnt, $sequence, $done) = send_notifications(0, \@students);
if (not $done) {
	print "-1\n";
} else {
	print "$msg_cnt\n$sequence";
}


Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $$$l$$$ centimeters after haircut, where $$$l$$$ is her favorite number. Suppose, that the Alice's head is a straight line on which $$$n$$$ hairlines grow. Let's number them from $$$1$$$ to $$$n$$$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $$$l$$$, given that all hairlines on that segment had length strictly greater than $$$l$$$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types:  $$$0$$$ — Alice asks how much time the haircut would take if she would go to the hairdresser now.  $$$1$$$ $$$p$$$ $$$d$$$ — $$$p$$$-th hairline grows by $$$d$$$ centimeters. Note, that in the request $$$0$$$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$l$$$ ($$$1 \le n, m \le 100\,000$$$, $$$1 \le l \le 10^9$$$) — the number of hairlines, the number of requests and the favorite number of Alice. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — the initial lengths of all hairlines of Alice. Each of the following $$$m$$$ lines contains a request in the format described in the statement. The request description starts with an integer $$$t_i$$$. If $$$t_i = 0$$$, then you need to find the time the haircut would take. Otherwise, $$$t_i = 1$$$ and in this moment one hairline grows. The rest of the line than contains two more integers: $$$p_i$$$ and $$$d_i$$$ ($$$1 \le p_i \le n$$$, $$$1 \le d_i \le 10^9$$$) — the number of the hairline and the length it grows by.

For each query of type $$$0$$$ print the time the haircut would take.

NoteConsider the first example:  Initially lengths of hairlines are equal to $$$1, 2, 3, 4$$$ and only $$$4$$$-th hairline is longer $$$l=3$$$, and hairdresser can cut it in $$$1$$$ second.  Then Alice's second hairline grows, the lengths of hairlines are now equal to $$$1, 5, 3, 4$$$  Now haircut takes two seonds: two swings are required: for the $$$4$$$-th hairline and for the $$$2$$$-nd.  Then Alice's first hairline grows, the lengths of hairlines are now equal to $$$4, 5, 3, 4$$$  The haircut still takes two seconds: with one swing hairdresser can cut $$$4$$$-th hairline and with one more swing cut the segment from $$$1$$$-st to $$$2$$$-nd hairline.  Then Alice's third hairline grows, the lengths of hairlines are now equal to $$$4, 5, 4, 4$$$  Now haircut takes only one second: with one swing it is possible to cut the segment from $$$1$$$-st hairline to the $$$4$$$-th.

use strict;
use warnings;

my $input = <STDIN>;
my ($n, $m, $l) = map {$_+0} split / /, $input;
$input = <STDIN>;
my @hairs = map {$_+0} split / /, $input;
my @res = ();
my $counter = 0;
my $r = 0;
for my $i (0 .. $m - 1) {
    $input = <STDIN>;
    my @req = map {$_+0} (split(/ /, $input));
    if (scalar @req == 1 && $req[0] == 0) {
        unless (@res) {
            $r = f(\@hairs, $n, $l);
        }
        push @res, $r;
    } elsif (scalar @req == 3 && $req[0] == 1) {
        my $j = $req[1] - 1;
        my $d = $hairs[$j] + $req[2];
        if (scalar @res > 0 && $hairs[$j] <= $l && $d > $l) {
            if ($j == 0 && $n > 1 && $hairs[1] <= $l) {
                $r++;
            } elsif ($j == $n-1 && $n > 1 && $hairs[$n-2] <= $l) {
                $r++;
            } elsif ($j != $n-1 && $j != 0 && $hairs[$j-1] <= $l && $hairs[$j+1] <= $l) {
                $r++;
            } elsif ($j != $n-1 && $j != 0 && $hairs[$j-1] > $l && $hairs[$j+1] > $l) {
                $r--;
            } elsif ($n == 1) {
                $r++;
            }
        }
        $hairs[$req[1]-1] = $d;
    }
}

my $j = scalar @res;
for my $i (0..$j-1) {
    print $res[$i];
    print "\n" if $i != $j-1;
}

sub f {
    my $hairs = shift;
    my $n = shift;
    my $l = shift;
    my $counter = 0;
    my $flag = 0;
    for my $i (0..$n-1) {
        if ($hairs->[$i] > $l) {
            $flag = 1;
        } else {
            $counter++ if $flag == 1;
            $flag = 0;
        }
    }
    $counter++ if ($flag == 1);
    return $counter;
}

use strict;
use warnings;

my $input = <STDIN>;
my ($n, $m, $l) = map {$_+0} split / /, $input;
$input = <STDIN>;
my @hairs = map {$_+0} split / /, $input;
my @res = ();
for my $i (0 .. $m - 1) {
    $input = <STDIN>;
    my @req = map {$_+0} (split(/ /, $input));
    if (scalar @req == 1 && $req[0] == 0) {
        push @res, f(\@hairs, $n, $l);
    } elsif (scalar @req == 3 && $req[0] == 1) {
        $hairs[$req[1]-1] += $hairs[$req[2]];
    }
}

my $j = scalar @res;
for my $i (0..$j-1) {
    print $res[$i];
    print "\n" if $i != $j-1;
}

sub f {
    my $hairs = shift;
    my $n = shift;
    my $l = shift;
    my $counter = 0;
    my $flag = 0;
    for my $i (0..$n-1) {
        if ($hairs->[$i] > $l) {
            $flag = 1;
        } else {
            $counter++ if $flag == 1;
            $flag = 0;
        }
    }
    $counter++ if ($flag == 1);
    return $counter;
}

use strict;
use warnings;

my $input = <STDIN>;
my ($n, $m, $l) = map {$_+0} split / /, $input;
$input = <STDIN>;
my @hairs = map {$_+0} split / /, $input;
my @res = ();
my $counter = 0;
my $r = 0;
for my $i (0 .. $m - 1) {
    $input = <STDIN>;
    my @req = map {$_+0} (split(/ /, $input));
    if (scalar @req == 1 && $req[0] == 0) {
        unless (@res) {
            $r = f(\@hairs, $n, $l);
        }
        push @res, $r;
    } elsif (scalar @req == 3 && $req[0] == 1) {
        my $j = $req[1] - 1;
        my $d = $hairs[$j] + $req[2];
        if (scalar @res > 0 && $hairs[$j] <= $l && $d > $l) {
            if ($j == 0 && $n > 1 && $hairs[$j+1] <= $l) {
                $r++;
            } elsif ($j == $n-1 && $n > 1 && $hairs[$j-1] <= $l) {
                $r++;
            } elsif ($j != $n-1 && $j != 0 && $hairs[$j-1] <= $l && $hairs[$j+1] <= $l) {
                $r++;
            } elsif ($j != $n-1 && $j != 0 && $hairs[$j-1] > $l && $hairs[$j+1] > $l) {
                $r--;
            }
        }
        $hairs[$req[1]-1] = $d;
    }
}

my $j = scalar @res;
for my $i (0..$j-1) {
    print $res[$i];
    print "\n" if $i != $j-1;
}

sub f {
    my $hairs = shift;
    my $n = shift;
    my $l = shift;
    my $counter = 0;
    my $flag = 0;
    for my $i (0..$n-1) {
        if ($hairs->[$i] > $l) {
            $flag = 1;
        } else {
            $counter++ if $flag == 1;
            $flag = 0;
        }
    }
    $counter++ if ($flag == 1);
    return $counter;
}

use strict;
use warnings;

my $input = <STDIN>;
my ($n, $m, $l) = map {$_+0} split / /, $input;
$input = <STDIN>;
my @hairs = map {$_+0} split / /, $input;
my @res = ();
for my $i (0 .. $m - 1) {
    $input = <STDIN>;
    my @req = map {$_+0} (split(/ /, $input));
    if (scalar @req == 1) {
        push @res, f(\@hairs, $n, $l);
    } else {
        $hairs[$req[1]-1] += $hairs[$req[2]];
    }
}

my $j = scalar @res;
for my $i (0..$j-1) {
    print $res[$i];
    print "\n" if $i != $j-1;
}

sub f {
    my $hairs = shift;
    my $n = shift;
    my $l = shift;
    my $counter = 0;
    my $flag = 0;
    for my $i (0..$n-1) {
        if ($hairs->[$i] > $l) {
            $flag = 1;
        } else {
            $counter++ if $flag == 1;
            $flag = 0;
        }
    }
    $counter++ if ($flag == 1);
    return $counter;
}


Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.  The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square . Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads.    To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square  has ai lights.Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.

The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and . All numbers ai are positive integers, not exceeding 100.

Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.

NotePicture for the sample test. Green color denotes the additional street lights.

use strict;
use warnings;
use List::Util qw(first max maxstr min minstr reduce shuffle sum);;
our $ans = 0;
my $n = <>;

my @elm = split / /,<>;
unshift @elm ,"www";
reet(@elm);
print $ans;
sub reet
{
    my @a = @_;
    my $i = $#a;
    if ($i <= 1)
    {
        return;
    }
    my @b = @a[0..($#a - 1)/2];
    while ($i > $#a/2)
    {
        #print "$i : ",$a[$i]," ";
        $b[($i - 1)/2] += max($a[$i], $a[$i - 1]);
        $ans += abs($a[$i] - $a[$i - 1]);
        $i -= 2;
    }

    reet(@b);
}

 #!perl

 $\ ="\n";

 sub count
 {
    my $link = shift;
    my @a = @{$link};

    if($#a == 1)
    {
        return @a;
    }
    else
    {
        my $first = shift @a;
        my $second = shift @a;

        my $p = ($#a + 1)/2 - 1;
        my @branch_1 = @a[0..$p];
        my @branch_2 = @a[($p + 1)..$#a];

        for my $i (@branch_1)
        {
            $i += $first;
        }

        for my $j (@branch_2)
        {
            $j += $second;
        }

        return (count(\@branch_1), count(\@branch_2));
    }
 }

 sub  find_answer
 {
    my $link = shift;
    my @a = @{$link};
    my $m = shift;

    if($#a == 1)
    {
        my $left = $m - @a[0];
        my $right = $m - @a[1];

        return $left > $right ? $left : $right;
    }
    else
    {
        my $first = shift @a;
        my $second = shift @a;

        my $p = ($#a + 1)/2 - 1;
        my @branch_1 = @a[0..$p];
        my @branch_2 = @a[($p + 1)..$#a];

        my $left = find_answer(\@branch_1, $m) - $first;
        my $right = find_answer(\@branch_2, $m) - $second;

        return $left + $right;
    }
 }

 $n = <>;
 @lamps = split / /, <>;

 @paths = count(\@lamps);

 $max = 0;
 for my $item (@paths)
 {
    $max = $item if $max < $item;
 }

 print find_answer(\@lamps, $max);


Polycarp and his friends want to visit a new restaurant. The restaurant has $$$n$$$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $$$1$$$ to $$$n$$$ in the order from left to right. The state of the restaurant is described by a string of length $$$n$$$ which contains characters "1" (the table is occupied) and "0" (the table is empty).Restaurant rules prohibit people to sit at a distance of $$$k$$$ or less from each other. That is, if a person sits at the table number $$$i$$$, then all tables with numbers from $$$i-k$$$ to $$$i+k$$$ (except for the $$$i$$$-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than $$$k$$$.For example, if $$$n=8$$$ and $$$k=2$$$, then:  strings "10010001", "10000010", "00000000", "00100000" satisfy the rules of the restaurant;  strings "10100100", "10011001", "11111111" do not satisfy to the rules of the restaurant, since each of them has a pair of "1" with a distance less than or equal to $$$k=2$$$. In particular, if the state of the restaurant is described by a string without "1" or a string with one "1", then the requirement of the restaurant is satisfied.You are given a binary string $$$s$$$ that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string $$$s$$$.Find the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of "0" that can be replaced by "1" such that the requirement will still be satisfied?For example, if $$$n=6$$$, $$$k=1$$$, $$$s=$$$ "100010", then the answer to the problem will be $$$1$$$, since only the table at position $$$3$$$ can be occupied such that the rules are still satisfied.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — the number of tables in the restaurant and the minimum allowed distance between two people. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ consisting of "0" and "1" — a description of the free and occupied tables in the restaurant. The given string satisfy to the rules of the restaurant — the difference between indices of any two "1" is more than $$$k$$$. The sum of $$$n$$$ for all test cases in one test does not exceed $$$2\cdot 10^5$$$.

For each test case output one integer — the number of tables that you can occupy so as not to violate the rules of the restaurant. If additional tables cannot be taken, then, obviously, you need to output $$$0$$$.

NoteThe first test case is explained in the statement.In the second test case, the answer is $$$2$$$, since you can choose the first and the sixth table.In the third test case, you cannot take any free table without violating the rules of the restaurant.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

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

	my( $n, $k ) = split;
	$_ = <>, chomp;

	my @k = partition( $k );

	my $k_re = join '', map { "0{0,$_}" } @k;

	$debug and print "k_re:[$k_re]";

	s/1 \K ( $k_re ) / "1" x length $1 /gex;

	$_ = reverse;

	s/1 \K ( $k_re ) / "1" x length $1 /gex;

	$_ = reverse;

	$debug and print "[$_]";

	my @free_rows = grep $_, map length, split /1+/, $_;

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

	my $ans = 0;

	for my $i ( @free_rows ){
		while( $i >= $k + 1 ){
			$ans ++;
			$i -= $k + 1;
			}
		$i and $ans ++;
		}

	print $ans;
	}

sub partition {
	my $i = shift;

	my @arr;
	my $max = 1e4;

	while( $i > $max ){
		push @arr, $max;
		$i -= $max;
		}

	$i > 0 and push @arr, $i;

	@arr;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

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

	my( $n, $k ) = split;
	$_ = <>, chomp;

	my @k = partition( $k );

	my $k_re = join '|', map { "0{0,$_}" } @k;

	$debug and print "k_re:[$k_re]";

	s/1 \K ( $k_re ) / "1" x length $1 /gex;

	$_ = reverse;

	s/1 \K ( $k_re ) / "1" x length $1 /gex;

	$_ = reverse;

	$debug and print "[$_]";

	my @free_rows = grep $_, map length, split /1+/, $_;

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

	my $ans = 0;

	for my $i ( @free_rows ){
		while( $i >= $k + 1 ){
			$ans ++;
			$i -= $k + 1;
			}
		$i and $ans ++;
		}

	print $ans;
	}

sub partition {
	my $i = shift;

	my @arr;
	my $max = 1e4;

	while( $i > $max ){
		push @arr, $max;
		$i -= $max;
		}

	$i > 0 and push @arr, $i;

	@arr;
	}


You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces.  Space can be represented as the $$$XY$$$ plane. You are starting at point $$$(0, 0)$$$, and Planetforces is located in point $$$(p_x, p_y)$$$.The piloting system of your spaceship follows its list of orders which can be represented as a string $$$s$$$. The system reads $$$s$$$ from left to right. Suppose you are at point $$$(x, y)$$$ and current order is $$$s_i$$$:   if $$$s_i = \text{U}$$$, you move to $$$(x, y + 1)$$$;  if $$$s_i = \text{D}$$$, you move to $$$(x, y - 1)$$$;  if $$$s_i = \text{R}$$$, you move to $$$(x + 1, y)$$$;  if $$$s_i = \text{L}$$$, you move to $$$(x - 1, y)$$$. Since string $$$s$$$ could be corrupted, there is a possibility that you won't reach Planetforces in the end. Fortunately, you can delete some orders from $$$s$$$ but you can't change their positions.Can you delete several orders (possibly, zero) from $$$s$$$ in such a way, that you'll reach Planetforces after the system processes all orders?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line in each test case contains two integers $$$p_x$$$ and $$$p_y$$$ ($$$-10^5 \le p_x, p_y \le 10^5$$$; $$$(p_x, p_y) \neq (0, 0)$$$) — the coordinates of Planetforces $$$(p_x, p_y)$$$. The second line contains the string $$$s$$$ ($$$1 \le |s| \le 10^5$$$: $$$|s|$$$ is the length of string $$$s$$$) — the list of orders. It is guaranteed that the sum of $$$|s|$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" if you can delete several orders (possibly, zero) from $$$s$$$ in such a way, that you'll reach Planetforces. Otherwise, print "NO". You can print each letter in any case (upper or lower).

6
10 5
RRRRRRRRRRUUUUU
1 1
UDDDRLLL
-3 -5
LDLDLDDDR
1 2
LLLLUU
3 -2
RDULRLLDR
-1 6
RUDURUUUUR

NoteIn the first case, you don't need to modify $$$s$$$, since the given $$$s$$$ will bring you to Planetforces.In the second case, you can delete orders $$$s_2$$$, $$$s_3$$$, $$$s_4$$$, $$$s_6$$$, $$$s_7$$$ and $$$s_8$$$, so $$$s$$$ becomes equal to "UR".In the third test case, you have to delete order $$$s_9$$$, otherwise, you won't finish in the position of Planetforces.


n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.

The first line contains two integers: n and k (2 ≤ n ≤ 500, 2 ≤ k ≤ 1012) — the number of people and the number of wins. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.

Output a single integer — power of the winner.

NoteGames in the second sample:3 plays with 1. 3 wins. 1 goes to the end of the line.3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $n, $k ) = split;
	@_ = split ' ', <>;
	my $pre = $_[ 0 ];
	my $ok = 0;
	my $cnt = 0;

	for my $i ( 1 .. @_ - 1 ){
		my $new = $_[ $i ] > $pre ? $_[ $i ] : $pre;
		if( $pre == $new ){
			$cnt ++;
			}
		else{
			$cnt = 1;
			}
		$cnt == $k and do {
			$ok = 1;
			last;
			};
	#	print "  pre: $pre, new: $new";
		$pre = $new;
		}

	print $pre;
	}


Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?

The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for.

Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above.

10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020

sinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja

NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

#!/usr/bin/env perl

use strict;
use warnings;
use feature qw/ say /;

# essential
my @tokens = ();

sub read_line {
    chomp (my $line = <STDIN>);
    return $line;
}

sub read_token {
    @tokens = split q{ }, read_line() if @tokens == 0;
    return shift @tokens;
}

sub min {
    my @numbers = @_;
    my $min = shift @numbers;
    for ( @numbers ) {
        $min = $min<$_ ? $min : $_;
    }
    return $min;
}

sub max {
    my @numbers = @_;
    my $max = shift @numbers;
    for ( @numbers ) {
        $max = $max > $_ ? $max : $_;
    }
    return $max;
}

sub sum {
    my @numbers = @_;
    my $sum = 0;
    for (@numbers) {
        $sum += $_;
    }
    return $sum;
}

# solve

read_token;
read_token;

my @a = split q{ }, read_line;
my @b = split q{ }, read_line;
my $length_of_a = @a;
my $length_of_b = @b;

my $q = read_line;

for (1..$q) {
    my $year = read_line;
    my $mod_of_a = $year % $length_of_a;
    my $mod_of_b = $year % $length_of_b;
    say "$a[$mod_of_a-1]$b[$mod_of_b-1]";
}


Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.  The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of disks on the combination lock. The second line contains a string of n digits — the original state of the disks. The third line contains a string of n digits — Scrooge McDuck's combination that opens the lock.

Print a single integer — the minimum number of moves Scrooge McDuck needs to open the lock.

NoteIn the sample he needs 13 moves:  1 disk:   2 disk:   3 disk:   4 disk:   5 disk:

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

sub abs {
	$a = shift;
	return $a>0 ? $a:-$a;
};

sub min {
	($a, $b) = (shift, shift);
	return $a<$b ? $a:$b;
};

chomp($len = <>);
chomp($l1 = <>);
chomp($l2 = <>);
$ans = 0;
foreach (0..$len-1) {
	($a, $b) = (substr($l1, $_, 1), substr($l2, $_, 1));
	$tmp = abs($a-$b);
	$ans += min($tmp, 10-$tmp);
}
say $ans;

#!perl

<>;
my @start_state = split //, <>;
my @combination = split //, <>;

my $answer = 0;
for my $i (0..$#start_state - 1)
{
    (my $x1, my $x2) = @start_state[$i] < @combination[$i] ? (@start_state[$i], @combination[$i]) : (@combination[$i], @start_state[$i]);
    my $a = $x2 - $x1;
    my $b = 9 - $x2 + $x1 + 1;
    $answer += $a < $b ? $a : $b;
}

print $answer, "\n";

#!/usr/bin/perl
use strict;
use warnings;
my $n = <>;
chomp $n;
my $na = <>;
chomp $na;
my $nb = <>;
chomp $nb;

my $res = 0;

my @a = split(//, $na);
my @b = split(//, $nb);

for (my $i = 0; $i < $n; $i++) {
    my ($m, $M);
    my $c1 = abs($a[$i] - $b[$i]);
    my $c2 = 10 - $c1;
    if ($c1 < $c2) {
        $res += $c1;
    } else {
        $res += $c2;
    }
}

print "$res\n";

#!/usr/bin/perl
use strict;
use warnings;
sub min{
    return $_[0] < $_[1] ? $_[0] : $_[1];
}
my $n = <>;
my @src = split '',<>;
my @dest = split '',<>;
my $res = 0;
foreach my $i(0 .. $n-1){
    my $d = abs($src[$i] - $dest[$i]);
    $res += min($d, 10 - $d);
}
print $res;


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z".

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$.

Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$.

NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda".

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	@_ = map ord, split //;

	my $j = @_ - 1;

	for my $i ( 0 .. @_ - 2 ){
		$_[ $i ] > $_[ $i + 1 ] and do { $j = $i; last; };
		}

	substr $_, $j, 1, '';

	print;
	}