Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.

The single line contains an integer n (1 ≤ n ≤ 106) — the sum of digits of the required lucky number.

Print on the single line the result — the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.

# http://codeforces.com/problemset/problem/109/A

# read n
my $n = <STDIN>;		#
chomp ( $n );			#

my $a, $b;
$a = $b = -1;
my %ha;
my $found = 0;
# calculate all possible values of a
$b = 0;
while ( $n >= (7 * $b) ) {
    if ( ($n - (7 * $b)) % 4 == 0 ) {
	$found = 1;
	$a = ($n - (7 * $b)) / 4;
	$ha{ $a } = $b;}
    $b += 1;}

# find minimum sum of any pair
my $min = 100000000;
my @k = keys %ha;
for (@k) {
    if ( $_ + $ha{ $_ } < $min ) {
	$min = $_ + $ha{ $_ };}}

# find pairs with sum equal to minimum
# and store them in @sel
my @filter_one;
@filter_one = grep { ($_ + $ha{ $_ }) == $min } @k;

# find pair with minimum $b
$min = 100000000;
for (@filter_one) {
    if ( $ha{ $_ } < $min ) {
	$min = $ha{ $_ };
	$a = $_;
	$b = $ha{ $_ };}}

# print answer
if ( not $found ) { print "-1\n"; }
else { print (("4" x $a ) . ("7" x $b) . "\n"); }

# http://codeforces.com/problemset/problem/109/A

# read n
my $n = <STDIN>;		#
chomp ( $n );			#

my $a, $b;
$a = $b = -1;
my %ha;
my $found = 0;
# calculate all possible values of a
$b = 0;
while ( $n > (7 * $b) ) {
    if ( ($n - (7 * $b)) % 4 == 0 ) {
	$found = 1;
	$a = ($n - (7 * $b)) / 4;
	$ha{ $a } = $b;}
    $b += 1;}

# find minimum sum of any pair
my $min = 100000000;
my @k = keys %ha;
for (@k) {
    if ( $_ + $ha{ $_ } < $min ) {
	$min = $_ + $ha{ $_ };}}

# find pairs with sum equal to minimum
# and store them in @sel
my @filter_one;
@filter_one = grep { ($_ + $ha{ $_ }) == $min } @k;

# find pair with minimum $b
$min = 100000000;
for (@filter_one) {
    if ( $ha{ $_ } < $min ) {
	$min = $ha{ $_ };
	$a = $_;
	$b = $ha{ $_ };}}

# print answer
if ( not $found ) { print "-1\n"; }
else { print (("4" x $a ) . ("7" x $b) . "\n"); }


$$$n$$$ students are taking an exam. The highest possible score at this exam is $$$m$$$. Let $$$a_{i}$$$ be the score of the $$$i$$$-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied:   All scores are integers  $$$0 \leq a_{i} \leq m$$$  The average score of the class doesn't change. You are student $$$1$$$ and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 200$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^{3}$$$, $$$1 \leq m \leq 10^{5}$$$)  — the number of students and the highest possible score respectively. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 0 \leq a_{i} \leq m$$$)  — scores of the students.

For each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._

NoteIn the first case, $$$a = [1,2,3,4] $$$, with average of $$$2.5$$$. You can change array $$$a$$$ to $$$[10,0,0,0]$$$. Average remains $$$2.5$$$, and all conditions are satisfied.In the second case, $$$0 \leq a_{i} \leq 5$$$. You can change $$$a$$$ to $$$[5,1,1,3]$$$. You cannot increase $$$a_{1}$$$ further as it will violate condition $$$0\le a_i\le m$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	@_ = split ' ', <>;

	my $sum = eval join '+', @_;

	print $sum > $m ? $m : $sum;
	}


You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during $$$n$$$ consecutive days. During the $$$i$$$-th day you have to write exactly $$$a_i$$$ names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $$$m$$$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $$$1$$$ to $$$n$$$.

The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ means the number of names you will write in the notebook during the $$$i$$$-th day.

Print exactly $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$, where $$$t_i$$$ is the number of times you will turn the page during the $$$i$$$-th day.

NoteIn the first example pages of the Death Note will look like this $$$[1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]$$$. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.

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

my ($n,$m)=split/ /,<STDIN>;
my @a=split/ /,<STDIN>;chomp($m,$a[-1]);
my $i=0;my $su=0;my @out;
for(0..$n-1){
    $su+=$a[$_];
    if($su>=$m){$i=$su/$m;$su%=$m;}
    push @out,"$i ";
    $i=0;
}
print "@out\n";


Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm:  Root the tree at node 1.  Count the number of nodes at an even depth. Let it be evenCnt.  Count the number of nodes at an odd depth. Let it be oddCnt.  The answer is the minimum between evenCnt and oddCnt. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.

The only line contains an integer n (2 ≤ n ≤ 105), the number of nodes in the desired trees.

The output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output "-1" (without quotes) for that section only. If the answer for a section exists, it should contain n - 1 lines, each containing 2 space-separated integers u and v (1 ≤ u, v ≤ n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict. If there are multiple answers, you can print any of them.

NoteIn the first sample, there is only 1 tree with 2 nodes (node 1 connected to node 2). The algorithm will produce a correct answer in it so we printed  - 1 in the first section, but notice that we printed this tree in the second section.In the second sample:In the first tree, the algorithm will find an answer with 4 nodes, while there exists an answer with 3 nodes like this:  In the second tree, the algorithm will find an answer with 3 nodes which is correct:


You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.

The first line contains two integers, n and m (1 ≤ n ≤ 3000, 1 ≤ m ≤ 3000) — the number of words in the professor's lecture and the number of words in each of these languages. The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once. The next line contains n space-separated strings c1, c2, ..., cn — the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1, a2, ... am}. All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.

Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.

4 3
codeforces codesecrof
contest round
letter message
codeforces contest letter contest

5 3
joll wuqrd
euzf un
hbnyiyc rsoqqveh
hbnyiyc joll joll euzf joll

codeforces round letter round
hbnyiyc joll joll un joll

use strict;
use warnings;

my ( $n, $m ) = split ( " ", <> );
my %map;
while ( $m-- ){
	my ( $a, $b ) = split ( " ", <> );
	$map{$a} = $b;
}

print join ( " ", map ( ( length $_ <= length $map{$_} ? $_ : $map{$_} ), split ( " ", <> ) ) )."\n";

$\ = $/;
while (<>){
	($n, $m)=split;
	undef %h;
	for $i (1..$m){
		($first, $second) = split " ", <>;
		$value = length $second < length $first ? $second : $first;
		$h{$first} = $value;
		}
	$, = $";
#	print keys %h;
#	print values %h;

	$_ = <>;
	s/(\w+)/$h{$1}/eg;

	print
	}


You are given a string $$$s$$$ consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.You have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of queries. Each of the next $$$t$$$ lines contains one string. The $$$i$$$-th line contains a string $$$s_i$$$ consisting only of lowercase Latin letter. It is guaranteed that the length of $$$s_i$$$ is from $$$1$$$ to $$$1000$$$ (inclusive).

Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: -1 if it is impossible to obtain a good string by rearranging the letters of $$$s_i$$$ and any good string which can be obtained from the given one (by rearranging the letters) otherwise.

NoteIn the first query we cannot rearrange letters to obtain a good string.Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".In the third query we can do nothing to obtain a good string.

#!/usr/bin/perl

use strict;
use warnings;
use integer;

<>;

while (<>) {
	chomp;
	if (is_homo($_)) {
		print "-1\n";
	} else {
		my @chars = split //;
		print sort @chars;
		print "\n";
	}
}

sub is_homo {
	my $string = shift;
	my @chars = split //, $string;
	my $is_homo = 1;

	if (@chars > 0) {
		my $prev = $chars[0];
		for (my $i = 1; $i < @chars; $i++) {
			$is_homo = $is_homo && $chars[$i] eq $prev;
			$prev = $chars[$i];
		}
	}
	return $is_homo;
}

sub is_palindrome {
	my $string = shift;
	my @chars = split //, $string;
	my $radius = @chars / 2;

	my $is_palindrome = 1;
	for (my $i = 0; $i < $radius; $i++) {
		$is_palindrome = $is_palindrome && $chars[$i] eq $chars[$#chars - $i];
	}
	return $is_palindrome;
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;

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

	print /^(.)\1*$/ ? -1 : $_;
	}


The stardate is 1983, and Princess Heidi is getting better at detecting the Death Stars. This time, two Rebel spies have yet again given Heidi two maps with the possible locations of the Death Star. Since she got rid of all double agents last time, she knows that both maps are correct, and indeed show the map of the solar system that contains the Death Star. However, this time the Empire has hidden the Death Star very well, and Heidi needs to find a place that appears on both maps in order to detect the Death Star.The first map is an N × M grid, each cell of which shows some type of cosmic object that is present in the corresponding quadrant of space. The second map is an M × N grid. Heidi needs to align those two maps in such a way that they overlap over some M × M section in which all cosmic objects are identical. Help Heidi by identifying where such an M × M section lies within both maps.

The first line of the input contains two space-separated integers N and M (1 ≤ N ≤ 2000, 1 ≤ M ≤ 200, M ≤ N). The next N lines each contain M lower-case Latin characters (a-z), denoting the first map. Different characters correspond to different cosmic object types. The next M lines each contain N characters, describing the second map in the same format.

The only line of the output should contain two space-separated integers i and j, denoting that the section of size M × M in the first map that starts at the i-th row is equal to the section of the second map that starts at the j-th column. Rows and columns are numbered starting from 1. If there are several possible ways to align the maps, Heidi will be satisfied with any of those. It is guaranteed that a solution exists.

10 5
somer
andom
noise
mayth
eforc
ebewi
thyou
hctwo
again
noise
somermayth
andomeforc
noiseebewi
againthyou
noisehctwo

NoteThe 5-by-5 grid for the first test case looks like this: maytheforcebewithyouhctwo


Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich. Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers $$$a$$$ and $$$b$$$ ($$$a < b$$$). After that, the student can apply any of the following operations any number of times:   $$$a := a + 1$$$ (increase $$$a$$$ by $$$1$$$),  $$$b := b + 1$$$ (increase $$$b$$$ by $$$1$$$),  $$$a := a \ | \ b$$$ (replace $$$a$$$ with the bitwise OR of $$$a$$$ and $$$b$$$). To get full marks on the test, the student has to tell the teacher the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.Igor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make $$$a$$$ equal to $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The only line for each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a < b \le 10^6$$$). It is guaranteed that the sum of $$$b$$$ over all test cases does not exceed $$$10^6$$$.

For each test case print one integer — the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.

NoteIn the first test case, it is optimal to apply the third operation.In the second test case, it is optimal to apply the first operation three times.In the third test case, it is optimal to apply the second operation and then the third operation.

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	my( $A, $B ) = split;

	$debug and print "$A $B";

	$_ = sprintf "%021b", $_ for $A, $B;

	my $len;
	my $c = 0;

	OUTER:
	while( 1 ){
		while( $A =~ m/^0/ and $B =~ m/^0/ ){
			$A =~ s/.//;
			$B =~ s/.//;
			next OUTER;
			}

		while( $A =~ m/^1/ and $B =~ m/^1/ ){
			$A =~ s/.//;
			$B =~ s/.//;
			next OUTER;
			}

		while( $A =~ m/^0/ and $B =~ m/^1/ ){

			$len = length $A;
			$c ++;

			$A =~ s/.//;
			$B =~ s/.//;

			next OUTER;
			}

		last;
		}

	$debug and print $A;
	$debug and print $B;

	my $copy_B = $B;

	$_ = eval "0b$_" for $A, $B;

	$debug and print "$A $B";

	print +( sort { $a <=> $b }
		1 + $A - $B,
		( $c > 1 || $copy_B =~ m/1/ ? 1 : 0 ) + 0 - $A + ( 1 << ( $len - 1 ) )
		)[ 0 ];
	}

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	my( $A, $B ) = split;

	$debug and print "$A $B";

	$_ = sprintf "%021b", $_ for $A, $B;

	my $len;
	my $c = 0;

	OUTER:
	while( 1 ){
		while( $A =~ m/^0/ and $B =~ m/^0/ ){
			$A =~ s/.//;
			$B =~ s/.//;
			next OUTER;
			}

		while( $A =~ m/^1/ and $B =~ m/^1/ ){
			$A =~ s/.//;
			$B =~ s/.//;
			next OUTER;
			}

		while( $A =~ m/^0/ and $B =~ m/^1/ ){

			$len = length $A;
			$c ++;

			$A =~ s/.//;
			$B =~ s/.//;

			next OUTER;
			}

		last;
		}

	$debug and print $A;
	$debug and print $B;

	$_ = eval "0b$_" for $A, $B;

	$debug and print "$A $B";

	print +( sort { $a <=> $b }
		1 + $A - $B,
		( $c > 1 ? 1 : 0 ) + 0 - $A + ( 1 << ( $len - 1 ) )
		)[ 0 ];
	}

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	my( $A, $B ) = split;

	$debug and print "$A $B";

	$_ = sprintf "%021b", $_ for $A, $B;

	my $len;
	my $c = 0;

	OUTER:
	while( 1 ){
		while( $A =~ m/^0/ and $B =~ m/^0/ ){
			$A =~ s/.//;
			$B =~ s/.//;
			next OUTER;
			}

		while( $A =~ m/^1/ and $B =~ m/^1/ ){
			$A =~ s/.//;
			$B =~ s/.//;
			next OUTER;
			}

		while( $A =~ m/^0/ and $B =~ m/^1/ ){

			$len = length $A;
			$c ++;

			$A =~ s/.//;
			$B =~ s/.//;

			next OUTER;
			}

		last;
		}

	$debug and print $A;
	$debug and print $B;

	$_ = eval "0b$_" for $A, $B;

	$debug and print "$A $B";

	print +( sort { $a <=> $b }
		1 + $A - $B,
		( $c > 1 ? 1 : 0 ) + $B - $A + ( 1 << ( $len - 1 ) )
		)[ 0 ];
	}


There are $$$n$$$ athletes in front of you. Athletes are numbered from $$$1$$$ to $$$n$$$ from left to right. You know the strength of each athlete — the athlete number $$$i$$$ has the strength $$$s_i$$$.You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $$$A$$$ and $$$B$$$ so that the value $$$|\max(A) - \min(B)|$$$ is as small as possible, where $$$\max(A)$$$ is the maximum strength of an athlete from team $$$A$$$, and $$$\min(B)$$$ is the minimum strength of an athlete from team $$$B$$$.For example, if $$$n=5$$$ and the strength of the athletes is $$$s=[3, 1, 2, 6, 4]$$$, then one of the possible split into teams is:   first team: $$$A = [1, 2, 4]$$$,  second team: $$$B = [3, 6]$$$. In this case, the value $$$|\max(A) - \min(B)|$$$ will be equal to $$$|4-3|=1$$$. This example illustrates one of the ways of optimal split into two teams.Print the minimum value $$$|\max(A) - \min(B)|$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case consists of two lines.  The first line contains positive integer $$$n$$$ ($$$2 \le n \le 50$$$) — number of athletes.  The second line contains $$$n$$$ positive integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 1000$$$), where $$$s_i$$$ — is the strength of the $$$i$$$-th athlete. Please note that $$$s$$$ values may not be distinct.

For each test case print one integer — the minimum value of $$$|\max(A) - \min(B)|$$$ with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams.

NoteThe first test case was explained in the statement. In the second test case, one of the optimal splits is $$$A=[2, 1]$$$, $$$B=[3, 2, 4, 3]$$$, so the answer is $$$|2-2|=0$$$.

$t=readline STDIN;
chomp $t;
 while ($t) {
     $n= readline STDIN; chomp $n;
     @line=split / /, readline STDIN; chomp @line;

    my $min;
    while($l=shift @line) {
     foreach $k (@line) {
        $min=abs($k-$l) if abs($k-$l)<$min or !defined $min;
        last if !$min;
     }
     last if !min;
    }

    print $min;
    print "\n";
    $t--;
 }

$t=readline STDIN;
chomp $t;
 while ($t) {
     $n= readline STDIN; chomp $n;
     @line=split / /, readline STDIN; chomp @line;

    my $min;
    while($l=shift @line) {
     foreach $k (@line) {
        $min=abs($k-$l) if abs($k-$l)<$min or !defined $min;
        last if !$min;
     }
    }

    print $min;
    print "\n";
    $t--;
 }


You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display. The second line contains n digits — the initial state of the display.

Print a single line containing n digits — the desired state of the display containing the smallest possible number.

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

my @res;
foreach my $i (0 .. 9) {
  $res[$i] = [map {(++$_) % 10} @arr];
}

sub isMin {
  foreach (0 .. (@arr - 1)) {
    return 1 if (${$_[0]}[$_] < $arr[$_]);
    return 0 if (${$_[0]}[$_] > $arr[$_]);
  }
  return 0;
}

foreach my $i (0 .. 9) {
  foreach (1 .. @arr) {
    push @{$res[$i]}, shift @{$res[$i]};
    if (&isMin ($res[$i])) {
      @arr = @{$res[$i]};
    }
  }
}

printf "%s\n", join "", @arr;


You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $$$n$$$ seconds and at the $$$i$$$-th second the color $$$s_i$$$ is on.That way, the order of the colors is described by a string. For example, if $$$s=$$$"rggry", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on.More formally, you are given a string $$$s_1, s_2, \ldots, s_n$$$ of length $$$n$$$. At the first second the color $$$s_1$$$ is on, at the second — $$$s_2$$$, ..., at the $$$n$$$-th second the color $$$s_n$$$ is on, at the $$$n + 1$$$-st second the color $$$s_1$$$ is on and so on.You need to cross the road and that can only be done when the green color is on. You know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road.You can assume that you cross the road immediately. For example, with $$$s=$$$"rggry" and the current color r there are two options: either the green color will be on after $$$1$$$ second, or after $$$3$$$. That way, the answer is equal to $$$3$$$ — that is the number of seconds that we are guaranteed to cross the road, if the current color is r.

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. Then the description of the test cases follows. The first line of each test case contains an integer $$$n$$$ and a symbol $$$c$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$c$$$ is one of allowed traffic light colors r, y or g)— the length of the string $$$s$$$ and the current color of the traffic light.  The second line of each test case contains a string $$$s$$$ of the length $$$n$$$, consisting of the letters r, y and g. It is guaranteed that the symbol g is in the string $$$s$$$ and the symbol $$$c$$$ is in the string $$$s$$$.  It is guaranteed, that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case output the minimal number of second in which you are guaranteed to cross the road.

6

5 r

rggry

1 g

g

3 r

rrg

5 y

yrrgy

7 r

rgrgyrg

9 y

rrrgyyygy

NoteThe first test case is explained in the statement.In the second test case the green color is on so you can cross the road immediately. In the third test case, if the red color was on at the second second, then we would wait for the green color for one second, and if the red light was on at the first second, then we would wait for the green light for two seconds.In the fourth test case the longest we would wait for the green color is if we wait for it starting from the fifth second.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	my( $n, $c ) = split;
	$_ = <>, chomp;
	$_ x= 2;

	if( $c eq 'g' ){
		print 0;
		next;
		}

	print -1 + ( sort { $b <=> $a } map length, m/$c.*?g/g )[ 0 ];
	}


Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $$$n$$$ last days: $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the price of berPhone on the day $$$i$$$.Polycarp considers the price on the day $$$i$$$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $$$n=6$$$ and $$$a=[3, 9, 4, 6, 7, 5]$$$, then the number of days with a bad price is $$$3$$$ — these are days $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) and $$$5$$$ ($$$a_5=7$$$).Print the number of days with a bad price.You have to answer $$$t$$$ independent data sets.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of sets of input data in the test. Input data sets must be processed independently, one after another. Each input data set consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of days. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the price on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ over all data sets in the test does not exceed $$$150000$$$.

Print $$$t$$$ integers, the $$$j$$$-th of which should be equal to the number of days with a bad price in the $$$j$$$-th input data set.

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

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

# start

chomp (my $t = <STDIN>);

for (1..$t) {
    chomp (my $n = <STDIN>);
    chomp (my $line = <STDIN>);
    my @prices = split q{ }, $line;
    my $i = 1;
    my @prices_and_order
        = map { [$i++,$_] } @prices;

    @prices_and_order
        = sort { $a->[1] <=> $b->[1] } @prices_and_order;

    my $pao = shift @prices_and_order;
    my $max = $pao->[0];
    my $answer = 0;
    for ( @prices_and_order ) {
        if ( $pao->[1] == $_->[1] ) {
            if ( $_->[0] > $max ) {
                $max = $_->[0];
            }
            else {
                $answer++;
            }
        }
        else {
            if ( $max > $_->[0] ) {
                $answer++;
            }
            else {
                $max = $_->[0];
            }
        }
        $pao = $_;
    }
    say $answer;
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

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

	@_ = split ' ', <>;

	$debug and print "\@_: @_";

	@_ = reverse @_;

	my @min;

	$min[ 0 ] = $_[ 0 ];

	my $min = $min[ 0 ];

	for my $i ( 1 .. @_ - 1 ){
		$min > $_[ $i ] and $min = $_[ $i ];
		$min[ $i ] = $min;
		}

	@min = reverse @min;
	@_ = reverse @_;

	$debug and print "\@min: @min";

	my $cnt = 0;

	for my $i ( 0 .. @_ - 1 ){
		$cnt += $_[ $i ] > $min[ $i ];
		}

	print $cnt;
	}

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

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

# start

chomp (my $t = <STDIN>);

for (1..$t) {
    chomp (my $n = <STDIN>);
    chomp (my $line = <STDIN>);
    my @prices = split q{ }, $line;
    my $i = 1;
    my @prices_and_order
        = map { [$i++,$_] } @prices;

    @prices_and_order
        = sort { $a->[1] <=> $b->[1] } @prices_and_order;

    my $pao = shift @prices_and_order;
    my $max = $pao->[0];
    my $answer = 0;
    for ( @prices_and_order ) {
        if ( $pao->[1] == $_->[1] ) {
        }
        else {
            if ( $max > $_->[0] ) {
                $answer++;
            }
            else {
                $max = $_->[0];
            }
        }
        $pao = $_;
    }
    say $answer;
}

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

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

# start

chomp (my $t = <STDIN>);

for (1..$t) {
    chomp (my $n = <STDIN>);
    chomp (my $line = <STDIN>);
    my @prices = split q{ }, $line;
    my $i = 1;
    my @prices_and_order
        = map { [$i++,$_] } @prices;

    @prices_and_order
        = sort { $a->[1] <=> $b->[1] } @prices_and_order;

    my $pao = shift @prices_and_order;
    my $max = $pao->[0];
    my $answer = 0;
    for ( @prices_and_order ) {
        if ( $pao->[1] == $_->[1] ) {
            $max = $_->[0];
        }
        else {
            if ( $max > $_->[0] ) {
                $answer++;
            }
            else {
                $max = $_->[0];
            }
        }
        $pao = $_;
    }
    say $answer;
}


The map of Berland is a rectangle of the size n × m, which consists of cells of size 1 × 1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k.

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 0 ≤ k ≤ 50) — the sizes of the map and the number of lakes which should be left on the map. The next n lines contain m characters each — the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land). It is guaranteed that the map contain at least k lakes.

In the first line print the minimum number of cells which should be transformed from water to land.  In the next n lines print m symbols — the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them.  It is guaranteed that the answer exists on the given data.

NoteIn the first example there are only two lakes — the first consists of the cells (2, 2) and (2, 3), the second consists of the cell (4, 3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean.


The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.

The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.

In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem.

NoteIn the first sample the best strategy is to delete the second digit. That results in number 112 = 310.In the second sample the best strategy is to delete the third or fourth digits — that results in number 110102 = 2610.

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

my $n = <>;
if ($n =~ /0/) {
    $n =~ s/0//;
} else {
    $n =~ s/1//;
}
print $n;

#!/bin/bash/perl
$input=<>;
@inputProcessor=split(" ",$input);
$input=$inputProcessor[0];
@elements=split("",$input);
$f=0;
for($i=0;$i<@elements;++$i){
	if($f==0 && $i==(@elements-1)){
		#do nothing
	}
	else{
		if($elements[$i] eq 0 && $f==0){
			#then trim it and dont print
			#also signal the flag
			$f=1;
		}
		else{
			print $elements[$i];
		}
	}
}

#!/bin/bash/perl
$input=<>;
@inputProcessor=split(" ",$input);
$input=$inputProcessor[0];
$input=$input+0;
@elements=split("",$input);
$f=0;
for($i=0;$i<@elements;++$i){
	if($f==0 && $i==(@elements-1)){
		#do nothing
	}
	else{
		if($elements[$i]==0 && $f==0){
			#then trim it and dont print
			#also signal the flag
			$f=1;
		}
		else{
			print $elements[$i];
		}
	}
}


Sam is a kindergartener, and there are $$$n$$$ children in his group. He decided to create a team with some of his children to play "brawl:go 2".Sam has $$$n$$$ power-ups, the $$$i$$$-th has type $$$a_i$$$. A child's strength is equal to the number of different types among power-ups he has.For a team of size $$$k$$$, Sam will distribute all $$$n$$$ power-ups to $$$k$$$ children in such a way that each of the $$$k$$$ children receives at least one power-up, and each power-up is given to someone.For each integer $$$k$$$ from $$$1$$$ to $$$n$$$, find the minimum sum of strengths of a team of $$$k$$$ children Sam can get.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$).  The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — types of Sam's power-ups. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For every test case print $$$n$$$ integers. The $$$k$$$-th integer should be equal to the minimum sum of strengths of children in the team of size $$$k$$$ that Sam can get.


A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.For example:   If x = 6 and the crossword is 111011, then its encoding is an array {3, 2};  If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1};  If x = 5 and the crossword is 11111, then its encoding is an array {5};  If x = 5 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!

The first line contains two integer numbers n and x (1 ≤ n ≤ 100000, 1 ≤ x ≤ 109) — the number of elements in the encoding and the length of the crossword Mishka picked. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 10000) — the encoding.

Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my $sum = unpack '%32i' . @_, pack 'i' . @_, @_;

	print $sum + @_ - 1 == $x ? "YES" : "NO";
	}


Pak Chanek has a prime number$$$^\dagger$$$ $$$n$$$. Find a prime number $$$m$$$ such that $$$n + m$$$ is not prime.$$$^\dagger$$$ A prime number is a number with exactly $$$2$$$ factors. The first few prime numbers are $$$2,3,5,7,11,13,\ldots$$$. In particular, $$$1$$$ is not a prime number.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The only line of each test case contains a prime number $$$n$$$ ($$$2 \leq n \leq 10^5$$$).

For each test case, output a line containing a prime number $$$m$$$ ($$$2 \leq m \leq 10^5$$$) such that $$$n + m$$$ is not prime. It can be proven that under the constraints of the problem, such $$$m$$$ always exists. If there are multiple solutions, you can output any of them.

NoteIn the first test case, $$$m = 2$$$, which is prime, and $$$n + m = 7 + 2 = 9$$$, which is not prime.In the second test case, $$$m = 7$$$, which is prime, and $$$n + m = 2 + 7 = 9$$$, which is not prime.In the third test case, $$$m = 47837$$$, which is prime, and $$$n + m = 75619 + 47837 = 123456$$$, which is not prime.


You have an array $$$a$$$ of length $$$n$$$. You can exactly once select an integer $$$len$$$ between $$$1$$$ and $$$n - 1$$$ inclusively, and then sort in non-decreasing order the prefix of the array of length $$$len$$$ and the suffix of the array of length $$$n - len$$$ independently.For example, if the array is $$$a = [3, 1, 4, 5, 2]$$$, and you choose $$$len = 2$$$, then after that the array will be equal to $$$[1, 3, 2, 4, 5]$$$.Could it be that after performing this operation, the array will not be sorted in non-decreasing order?

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^4$$$) — the length of the array. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case of input data, output "YES" (without quotes), if the array may be not sorted in non-decreasing order, output "NO" (without quotes) otherwise. You can output each letter in any case (uppercase or lowercase).

NoteIn the first test case, it's possible to select $$$len = 1$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[2, 1, 2]$$$.In the second test case, it's possible to select $$$len = 3$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[1, 2, 3, 1]$$$.In the third test case, the array will be sorted in non-decreasing order for every possible $$$len$$$.


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

#!/usr/bin/perl

use strict;
use warnings;

my $num=<>;
my @str=split(' ',<>);
my @used;
foreach my $count(1..$num){
	$used[$count]=0;
}
my $total=$num;
foreach my $count(0..$#str){
	if($str[$count]>0 && $str[$count]<=$num && $used[$str[$count]]==0){
		$total--;
		$used[$str[$count]]=1;
	}
}
print $total;


Rahul and Tina are looking forward to starting their new year at college. As they enter their new classroom, they observe the seats of students are arranged in a $$$n \times m$$$ grid. The seat in row $$$r$$$ and column $$$c$$$ is denoted by $$$(r, c)$$$, and the distance between two seats $$$(a,b)$$$ and $$$(c,d)$$$ is $$$|a-c| + |b-d|$$$. As the class president, Tina has access to exactly $$$k$$$ buckets of pink paint. The following process occurs.   First, Tina chooses exactly $$$k$$$ seats in the classroom to paint with pink paint. One bucket of paint can paint exactly one seat.  After Tina has painted $$$k$$$ seats in the previous step, Rahul chooses where he sits. He will not choose a seat that has been painted pink due to his hatred of the colour pink.  After Rahul has chosen his seat, Tina chooses a seat for herself. She can choose any of the seats, painted or not, other than the one chosen by Rahul. Rahul wants to choose a seat such that he sits as close to Tina as possible. However, Tina wants to sit as far away from Rahul as possible due to some complicated relationship history that we couldn't fit into the statement!Now, Rahul wonders for $$$k = 0, 1, \dots, n \cdot m - 1$$$, if Tina has $$$k$$$ buckets of paint, how close can Rahul sit to Tina, if both Rahul and Tina are aware of each other's intentions and they both act as strategically as possible? Please help satisfy Rahul's curiosity!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \cdot m \leq 10^5$$$) — the number of rows and columns of seats in the classroom. The sum of $$$n \cdot m$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, output $$$n \cdot m$$$ ordered integers — the distance between Rahul and Tina if both of them act optimally for every $$$k \in [0, n \cdot m - 1]$$$.

NoteOne possible sequence of choices for the first testcase where Tina has $$$k=3$$$ buckets of paints is as follows.Tina paints the seats at positions $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ with pink paint. Rahul chooses the seat at $$$(3, 1)$$$ after which Tina chooses to sit at $$$(1, 3)$$$. Therefore, the distance between Tina and Rahul is $$$|3-1| + |1-3| = 4$$$, and we can prove that this is indeed the minimum possible distance under the given constraints. There may be other choices of seats which lead to the same answer as well.For $$$k=0$$$ in the first test case, Rahul can decide to sit at $$$(2, 2)$$$ and Tina can decide to sit at $$$(4, 3)$$$ so the distance between them would be $$$|2 - 4| + |2 - 3| = 3$$$.Below are pictorial representations of the $$$k=3$$$ and $$$k=0$$$ cases for the first test case.  A possible seating arrangement for $$$k=3$$$.  A possible seating arrangement for $$$k=0$$$.


Polycarp is reading a book consisting of $$$n$$$ pages numbered from $$$1$$$ to $$$n$$$. Every time he finishes the page with the number divisible by $$$m$$$, he writes down the last digit of this page number. For example, if $$$n=15$$$ and $$$m=5$$$, pages divisible by $$$m$$$ are $$$5, 10, 15$$$. Their last digits are $$$5, 0, 5$$$ correspondingly, their sum is $$$10$$$.Your task is to calculate the sum of all digits Polycarp has written down.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The following $$$q$$$ lines contain queries, one per line. Each query is given as two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^{16}$$$) — the number of pages in the book and required divisor, respectively.

For each query print the answer for it — the sum of digits written down by Polycarp.

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

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

# start

chomp (my $q = <STDIN>);

for (1..$q) {
    chomp (my $line = <STDIN>);
    my ($n, $m) = split q{ }, $line;

    my @ar;
    my $p = 0;
    for (1..10) {
        $ar[$_-1] = ($m*$_)%10;
        $p += $ar[$_-1];
    }

    my $d = int($n/($m*10));
    my $answer = $d*$p;

    my $i = $d*$m*10+$m;
    while ( $i<=$n ) {
        $answer += $i%10;
        $i+=$m;
    }
    say $answer;
}

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

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

# start

chomp (my $q = <STDIN>);

for (1..$q) {
    chomp (my $line = <STDIN>);
    my ($n, $m) = split q{ }, $line;
    my $lom = $m % 10;

    if ( $lom == 0 ) {
        say 0;
        next;
    }
    if ( $n < $m ) {
        say 0;
        next;
    }

    my $ld = $lom;
    my $i = 1;
    my $sum = $ld;
    my @sums = (0, $sum);
    while ($ld != 0) {
        $ld += $lom;
        $ld %= 10;
        $sum += $ld;
        push @sums, $sum;
        $i++;
    }

    my $div = int($n/$m);

    my $mo = int($div/$i);

    my $answer = $mo*$sums[$i];

    my $mod = $div % $i;
    $answer += $sums[$mod];
    say $answer;
}

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

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

# start

chomp (my $q = <STDIN>);

for (1..$q) {
    chomp (my $line = <STDIN>);
    my ($n, $m) = split q{ }, $line;
    my $lom = $m % 10;

    say "0", next if $lom == 0;
    say "0", next if $n < $m;

    my $ld = $lom;
    my $i = 1;
    my $sum = $ld;
    my @sums = (0, $lom);
    while ($ld != 0) {
        $ld += $lom;
        $ld %= 10;
        $sum += $ld;
        push @sums, $sum;
        $i++;
    }

    my $div = int($n/$m);

    my $mo = int($div/$i);

    my $answer = $mo*$sum;

    my $mod = $div % $i;
    $answer += $sums[$mod];
    say $answer;
}

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

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

# start

chomp (my $q = <STDIN>);

for (1..$q) {
    chomp (my $line = <STDIN>);
    my ($n, $m) = split q{ }, $line;
    my $lom = $m % 10;

    if ( $lom == 0 ) {
        say 0;
        next;
    }
    if ( $n < $m ) {
        say 0;
        next;
    }

    my $ld = $lom;
    my $i = 1;
    my $sum = $ld;
    my @sums = (0, $lom);
    while ($ld != 0) {
        $ld += $lom;
        $ld %= 10;
        $sum += $ld;
        push @sums, $sum;
        $i++;
    }

    my $div = int($n/$m);

    my $mo = int($div/$i);

    my $answer = $mo*$sum;

    my $mod = $div % $i;
    $answer += $sums[$mod];
    say $answer;
}

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

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

# start

chomp (my $q = <STDIN>);

for (1..$q) {
    chomp (my $line = <STDIN>);
    my ($n, $m) = split q{ }, $line;
    my $lom = $m % 10;

    if ( $lom == 0 ) {
        say 0;
        next;
    }
    if ( $n < $m ) {
        say 0;
        next;
    }

    my $ld = $lom;
    my $i = 1;
    my $sum = $ld;
    my @sums = (0, $sum);
    while ($i < 10) {
        $ld += $lom;
        $ld %= 10;
        $sum += $ld;
        push @sums, $sum;
        $i++;
    }

    my $answer = 0;

    $answer += $sums[10]*int(int($n/$m)/10);
    $answer += $sums[int(int($n/$m)%10)];
    say $answer;
}


Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).Help Daniel to process all queries.

The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries. The second line contains string s, consisting of n lowercase English letters and period signs. The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.

Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.

NoteNote to the first sample test (replaced periods are enclosed in square brackets).The original string is ".b..bz....". after the first query f(hb..bz....) = 4    ("hb[..]bz...."  →  "hb.bz[..].."  →  "hb.bz[..]."  →  "hb.bz[..]"  →  "hb.bz.") after the second query f(hbс.bz....) = 3    ("hbс.bz[..].."  →  "hbс.bz[..]."  →  "hbс.bz[..]"  →  "hbс.bz.") after the third query f(hbс.bz..f.) = 1    ("hbс.bz[..]f."  →  "hbс.bz.f.")Note to the second sample test.The original string is ".cc.". after the first query: f(..c.) = 1    ("[..]c."  →  ".c.") after the second query: f(....) = 3    ("[..].."  →  "[..]."  →  "[..]"  →  ".") after the third query: f(.a..) = 1    (".a[..]"  →  ".a.") after the fourth query: f(aa..) = 1    ("aa[..]"  →  "aa.")


Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.

The single line contains four integers x, y, a, b (1 ≤ a ≤ x ≤ 100, 1 ≤ b ≤ y ≤ 100). The numbers on the line are separated by a space.

In the first line print integer n — the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers ci, di — the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (ci, di) in the strictly increasing order. Let us remind you that the pair of numbers (p1, q1) is less than the pair of numbers (p2, q2), if p1 < p2, or p1 = p2 and also q1 < q2.


An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.  The second line contains n integers pi (1 ≤ pi ≤ n, pi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.

Print a single integer — the minimum number of actions needed to sort the railway cars.

NoteIn the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.


Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows.  The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 10^9$$$) which location must be found.

For each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \ge 1$$$) separated by spaces — the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.


You are given a picture consisting of $$$n$$$ rows and $$$m$$$ columns. Rows are numbered from $$$1$$$ to $$$n$$$ from the top to the bottom, columns are numbered from $$$1$$$ to $$$m$$$ from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers $$$x$$$ and $$$y$$$, where $$$1 \le x \le n$$$ and $$$1 \le y \le m$$$, such that all cells in row $$$x$$$ and all cells in column $$$y$$$ are painted black.For examples, each of these pictures contain crosses:  The fourth picture contains 4 crosses: at $$$(1, 3)$$$, $$$(1, 5)$$$, $$$(3, 3)$$$ and $$$(3, 5)$$$.Following images don't contain crosses:  You have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black.What is the minimum number of minutes you have to spend so the resulting picture contains at least one cross?You are also asked to answer multiple independent queries.

The first line contains an integer $$$q$$$ ($$$1 \le q \le 5 \cdot 10^4$$$) — the number of queries. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^4$$$, $$$n \cdot m \le 4 \cdot 10^5$$$) — the number of rows and the number of columns in the picture. Each of the next $$$n$$$ lines contains $$$m$$$ characters — '.' if the cell is painted white and '*' if the cell is painted black. It is guaranteed that $$$\sum n \le 5 \cdot 10^4$$$ and $$$\sum n \cdot m \le 4 \cdot 10^5$$$.

Print $$$q$$$ lines, the $$$i$$$-th line should contain a single integer — the answer to the $$$i$$$-th query, which is the minimum number of minutes you have to spend so the resulting picture contains at least one cross.

NoteThe example contains all the pictures from above in the same order.The first 5 pictures already contain a cross, thus you don't have to paint anything.You can paint $$$(1, 3)$$$, $$$(3, 1)$$$, $$$(5, 3)$$$ and $$$(3, 5)$$$ on the $$$6$$$-th picture to get a cross in $$$(3, 3)$$$. That'll take you $$$4$$$ minutes.You can paint $$$(1, 2)$$$ on the $$$7$$$-th picture to get a cross in $$$(4, 2)$$$.You can paint $$$(2, 2)$$$ on the $$$8$$$-th picture to get a cross in $$$(2, 2)$$$. You can, for example, paint $$$(1, 3)$$$, $$$(3, 1)$$$ and $$$(3, 3)$$$ to get a cross in $$$(3, 3)$$$ but that will take you $$$3$$$ minutes instead of $$$1$$$.There are 9 possible crosses you can get in minimum time on the $$$9$$$-th picture. One of them is in $$$(1, 1)$$$: paint $$$(1, 2)$$$ and $$$(2, 1)$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

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

	my( $n, $m ) = split;

	@_ = map { chomp; [ split '' ] } map ~~<>, 1 .. $n;

	$debug and print "@{ $_ }" for @_;

	my @hor;

	for( @_ ){
		my $cnt = 0;

		for my $j ( 0 .. @{ $_ } - 1 ){
			if( $_->[ $j ] eq '*' ){
				$cnt ++;
				}
			}

		push @hor, $cnt;
		}

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

	my @ver;

	for my $j ( 0 .. @{ $_[ 0 ] } - 1 ){
		my $cnt = 0;

		for my $i ( 0 .. @_ - 1 ){
			if( $_[ $i ][ $j ] eq '*' ){
				$cnt ++;
				}
			}

		push @ver, $cnt;
		}

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

	my @cand;

	for my $i ( 0 .. @_ - 1 ){
		for my $j ( 0 .. @{ $_[ 0 ] } - 1 ){
			my $is_star = $_[ $i ][ $j ] eq '*' ? 1 : 0;
			my $cand = $n + $m - 1 - ( $hor[ $i ] + $ver[ $j ] - 1 * $is_star );
			push @cand, $cand;
			}
		$debug and print "[@cand]";
		}

	print +( sort { $a <=> $b } @cand )[ 0 ];
	}


Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.Vova has already wrote k tests and got marks a1, ..., ak. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.

The first line contains 5 space-separated integers: n, k, p, x and y (1 ≤ n ≤ 999, n is odd, 0 ≤ k < n, 1 ≤ p ≤ 1000, n ≤ x ≤ n·p, 1 ≤ y ≤ p). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games. The second line contains k space-separated integers: a1, ..., ak (1 ≤ ai ≤ p) — the marks that Vova got for the tests he has already written.

If Vova cannot achieve the desired result, print "-1". Otherwise, print n - k space-separated integers — the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.

NoteThe median of sequence a1, ..., an where n is odd (in this problem n is always odd) is the element staying on (n + 1) / 2 position in the sorted list of ai.In the first sample the sum of marks equals 3 + 5 + 4 + 4 + 1 = 17, what doesn't exceed 18, that means that Vova won't be disturbed by his classmates. And the median point of the sequence {1, 3, 4, 4, 5} equals to 4, that isn't less than 4, so his mom lets him play computer games.Please note that you do not have to maximize the sum of marks or the median mark. Any of the answers: "4 2", "2 4", "5 1", "1 5", "4 1", "1 4" for the first test is correct.In the second sample Vova got three '5' marks, so even if he gets two '1' marks, the sum of marks will be 17, that is more than the required value of 16. So, the answer to this test is "-1".


The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r.Help the bear cope with the given problem.

The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters.

Print a single number — the answer to the problem.

#!/bin/perl

chomp(my $str = <>);
my $str_len = length $str;
my $start = 0;
my $ans = 0;
while ((my $idx = index($str, 'bear', $start)) != -1) {
    my ($f, $s) = ($idx - $start, $str_len - $idx - 4);
    $ans += $f + $s + 1 + $f * $s;
    $start = $idx + 1;
}
print $ans . "\n";

while(<>){
	chomp;
	$a=0;
	while (s/^(.*?)bear/ear/){
		$a+=(1+length $1)*(1+length $');
		}
	print $a
	}


You are given a sorted array $$$a_1, a_2, \dots, a_n$$$ (for each index $$$i > 1$$$ condition $$$a_i \ge a_{i-1}$$$ holds) and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$max(i)$$$ be equal to the maximum in the $$$i$$$-th subarray, and $$$min(i)$$$ be equal to the minimum in the $$$i$$$-th subarray. The cost of division is equal to $$$\sum\limits_{i=1}^{k} (max(i) - min(i))$$$. For example, if $$$a = [2, 4, 5, 5, 8, 11, 19]$$$ and we divide it into $$$3$$$ subarrays in the following way: $$$[2, 4], [5, 5], [8, 11, 19]$$$, then the cost of division is equal to $$$(4 - 2) + (5 - 5) + (19 - 8) = 13$$$.Calculate the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 1 \le a_i \le 10^9$$$, $$$a_i \ge a_{i-1}$$$).

Print the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays.

NoteIn the first test we can divide array $$$a$$$ in the following way: $$$[4, 8, 15, 16], [23], [42]$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	@_ = split ' ', <>;

	my @diffs;

	for my $i ( 0 .. @_ - 2 ){
		push @diffs, $_[ $i + 1 ] - $_[ $i ];
		}

	my @diffs_max = ( sort { $b <=> $a } @diffs )[ 0 .. $k - 2 ];

	my $sum = 0 + eval join '+', @diffs_max;

	print $_[ @_ - 1 ] - $_[ 0 ] - $sum;
	}


Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:  on this day the gym is closed and the contest is not carried out;  on this day the gym is closed and the contest is carried out;  on this day the gym is open and the contest is not carried out;  on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 3) separated by space, where:    ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;  ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;  ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;  ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.

Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:   to do sport on any two consecutive days,  to write the contest on any two consecutive days.

NoteIn the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.


You are given a string $$$a$$$, consisting of $$$n$$$ characters, $$$n$$$ is even. For each $$$i$$$ from $$$1$$$ to $$$n$$$ $$$a_i$$$ is one of 'A', 'B' or 'C'.A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You want to find a string $$$b$$$ that consists of $$$n$$$ characters such that:   $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.Your task is to determine if such a string $$$b$$$ exists.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$a$$$. $$$a$$$ consists only of uppercase letters 'A', 'B' and 'C'. Let $$$n$$$ be the length of $$$a$$$. It is guaranteed that $$$n$$$ is even and $$$2 \le n \le 50$$$.

For each testcase print "YES" if there exists such a string $$$b$$$ that:    $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$.  Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first testcase one of the possible strings $$$b$$$ is "(())()".In the second testcase one of the possible strings $$$b$$$ is "()()".

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;

	/./;
	my $open = $&;

	s/$open/(/g;

	/[ABC]$/ or do {
		print 'NO';
		next;
		};

	my $close = $&;

	s/$close/)/g;

	my $A = s/[ABC]/(/gr;
	my $B = s/[ABC]/)/gr;

	1 while $A =~ s/[(][)]//g;
	1 while $B =~ s/[(][)]//g;

	if( ! $A or ! $B ){
		print "YES";
		}
	else{
		print "NO";
		}
	}


Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has n records in total.In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category:   "noob" — if more than 50% of players have better results;  "random" — if his result is not worse than the result that 50% of players have, but more than 20% of players have better results;  "average" — if his result is not worse than the result that 80% of players have, but more than 10% of players have better results;  "hardcore" — if his result is not worse than the result that 90% of players have, but more than 1% of players have better results;  "pro" — if his result is not worse than the result that 99% of players have.  When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that 50% of players have, and the second one is not worse than the result that 100% of players have.Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.

The first line contains the only integer number n (1 ≤ n ≤ 1000) — a number of records with the players' results. Each of the next n lines contains a player's name and the amount of points, obtained by the player for the round, separated with a space. The name contains not less than 1 and no more than 10 characters. The name consists of lowercase Latin letters only. It is guaranteed that any two different players have different names. The amount of points, obtained by the player for the round, is a non-negative integer number and does not exceed 1000.

Print on the first line the number m — the number of players, who participated in one round at least. Each one of the next m lines should contain a player name and a category he belongs to, separated with space. Category can be one of the following: "noob", "random", "average", "hardcore" or "pro" (without quotes). The name of each player should be printed only once. Player names with respective categories can be printed in an arbitrary order.

5
vasya 100
vasya 200
artem 100
kolya 200
igor 250

4
artem noob
igor pro
kolya random
vasya random

NoteIn the first example the best result, obtained by artem is not worse than the result that 25% of players have (his own result), so he belongs to category "noob". vasya and kolya have best results not worse than the results that 75% players have (both of them and artem), so they belong to category "random". igor has best result not worse than the result that 100% of players have (all other players and himself), so he belongs to category "pro".In the second example both players have the same amount of points, so they have results not worse than 100% players have, so they belong to category "pro".

#!/usr/bin/perl

use strict;
use warnings;

my $lines = <STDIN>;
$lines =~ s/[\r\n]*$//;

my %scores = ();
for(my $i = 0; $i < $lines; $i++){
	my $s = <STDIN>;
	my @arr = split /[ \r\n]+/, $s;
	$scores{$arr[0]} = 0 unless exists $scores{$arr[0]};
	$scores{$arr[0]} = $arr[1]-0 if $scores{$arr[0]} < $arr[1];
}
my $users = keys %scores;
print "$users\n";
foreach my $user (sort keys %scores){
	my $worse   = grep {$scores{$_} <= $scores{$user}} keys %scores;
	if($worse * 100 >= $users * 99){
		print "$user pro\n";
	}elsif($worse * 100 >= $users * 90){
			print "$user hardcore\n";
	}elsif($worse * 100 >= $users * 80){
			print "$user average\n";
	}elsif($worse * 100 >= $users * 50){
			print "$user random\n";
	}else{
		print "$user noob\n";
	}
}

#!/usr/bin/perl

my $lines = <STDIN>;
$lines =~ s/[\r\n]*$//;

my %scores = ();
for(my $i = 0; $i < $lines; $i++){
	my $s = <STDIN>;
	my @arr = split /[ \r\n]+/, $s;
	$scores{$arr[0]} = 0 unless exists $scores{$arr[0]};
	$scores{$arr[0]} = $arr[1]-0 if $scores{$arr[0]} < $arr[1];
}
my $users = keys %scores;
print "$users\n";
foreach my $user (sort keys %scores){
	my $worse = grep {$scores{$_} <= $scores{$user}} keys %scores;
	if($worse * 100 > $users * 99){
		print "$user pro\n";
	}elsif($worse * 100 > $users * 90){
		print "$user hardcore\n";
	}elsif($worse * 100 > $users * 80){
		print "$user average\n";
	}elsif($worse * 100 > $users * 50){
		print "$user random\n";
	}else{
		print "$user noob\n";
	}
}


Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.

The first line contains integer k (1 ≤ k ≤ 109). The second line contains integer n (1 ≤ n < 10100000). There are no leading zeros in n. It's guaranteed that this situation is possible.

Print the minimum number of digits in which the initial number and n can differ.

NoteIn the first example, the initial number could be 12.In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.


Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.

If Vasya can write the given anonymous letter, print YES, otherwise print NO

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

#!/bin/bash/perl
$input=<>;
@reference = split(" ",$input);
$input=<>;
@tofind=split(" ",$input);
#for($x=0;$x<@tofind;++$x){print length($tofind[$x])."\n";}
%hash;
for($var='a';$var ne 'aa';++$var){
    $hash{$var}=0;
}
for($var='A';$var ne 'AA';++$var){
    $hash{$var}=0;
}
#fill the hash
for($i=0;$i<@reference;++$i){
    @temp=split("",$reference[$i]);
    for($j=0;$j<@temp;++$j){
        ++$hash{$temp[$j]};
    }
}

#start checking the hash
$notfound=1;
for($i=0;$i<@tofind && $notfound==1;++$i){
    @temp=split("",$tofind[$i]);
    for($j=0;$j<@temp;++$j){
        if($hash{$temp[$j]}<=0){
            $notfound=0;
            $j=@temp;
        }
        else{
            $hash{$temp[$j]}--;
        }
    }
}

if($notfound==0){
    print "NO";
}
else{
    print "YES";
}

#!/bin/bash/perl
$input=<>;
@reference = split(" ",$input);
$input=<>;
@tofind=split(" ",$input);
#for($x=0;$x<@tofind;++$x){print length($tofind[$x])."\n";}
$tofindnums=@tofind;
$havenums=@reference;
$found=0;
$inflag;

for($i=0;$i<@tofind;++$i){
    $wordlen=length($tofind[$i]);
    $inflag=1;

    for($j=0;$j<@reference && $inflag;++$j){

        if(length($reference[$j])>= $wordlen){

            for($k=0;$k<=length($reference[$j])-$wordlen;++$k){
                $sub = substr($reference[$j],$k,$wordlen);
                #print "sub found is $sub \n";
                if($sub eq $tofind[$i]){
                    #increase found enrty
                    ++$found;
                    #now replenish this with new character
                    @temp=split("",$reference[$j]);
                    for($s=$k;$s<$k+$wordlen;++$s){
                        $temp[$s]='-';
                    }
                    $tempnew;
                    for($s=0;$s<@temp;++$s){
                        if($temp[$s] ne '-')
                        {$tempnew=$tempnew.$temp[$s];}
                    }
                    $reference[$j]=$tempnew;

                    #propogate out of array
                    $k=length($reference[$j]);
                    #mark outer array bbreaker
                    $inflag=0;
                }
            }
        }
    }
}

if($found==$tofindnums){
    print "YES";
}
else{
    #print "found value is $found\n expected value $tofindnums\n";
    print "NO";
}

#!/bin/bash/perl
$input=<>;
@reference = split(" ",$input);
$input=<>;
@tofind=split(" ",$input);
#for($x=0;$x<@tofind;++$x){print length($tofind[$x])."\n";}
%hash;
for($var='a';$var ne 'aa';++$var){
    $hash{$var}=0;
}
for($var='A';$var ne 'AA';++$var){
    $hash{$var}=0;
}
#fill the hash
for($i=0;$i<@reference;++$i){
    @temp=split("",$reference[$i]);
    for($j=0;$j<@temp;++$j){
        ++$hash{$temp[$j]};
    }
}
#start checking the hash
$notfound=1;
for($i=0;$i<@tofind && $notfound==1;++$i){
    @temp=split("",$tofind[$$i]);
    for($j=0;$j<@temp;++$j){
        if($hash{$temp[$j]}<=0){
            $notfound=0;
            $j=@temp;
        }
    }
}

if($notfound==0){
    print "NO";
}
else{
    print "YES";
}

#!/bin/bash/perl
$input=<>;
@reference = split(" ",$input);
$input=<>;
@tofind=split(" ",$input);
#for($x=0;$x<@tofind;++$x){print length($tofind[$x])."\n";}
%hash;
for($var='a';$var ne 'aa';++$var){
    $hash{$var}=0;
}
for($var='A';$var ne 'AA';++$var){
    $hash{$var}=0;
}
#fill the hash
for($i=0;$i<@reference;++$i){
    @temp=split("",$reference[$i]);
    for($j=0;$j<@temp;++$j){
        ++$hash{$temp[$j]};
    }
}
#start checking the hash
$notfound=1;
for($i=0;$i<@tofind && $notfound==1;++$i){
    @temp=split("",$tofind[$$i]);
    for($j=0;$j<@temp;++$j){
        if($hash{$temp[$j]}<=0){
            $notfound=0;
            $j=@temp;
        }
        else{
            $hash{$temp[$j]}--;
        }
    }
}

if($notfound==0){
    print "NO";
}
else{
    print "YES";
}


This is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1.Paul and Mary have a favorite string $$$s$$$ which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a string wonderful if the following conditions are met:  each letter of the string is either painted in exactly one color (red or green) or isn't painted;  each two letters which are painted in the same color are different;  the number of letters painted in red is equal to the number of letters painted in green;  the number of painted letters of this coloring is maximum among all colorings of the string which meet the first three conditions. E. g. consider a string $$$s$$$ equal to "kzaaa". One of the wonderful colorings of the string is shown in the figure.    The example of a wonderful coloring of the string "kzaaa". Paul and Mary want to learn by themselves how to find a wonderful coloring of the string. But they are very young, so they need a hint. Help them find $$$k$$$ — the number of red (or green, these numbers are equal) letters in a wonderful coloring.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one non-empty string $$$s$$$ which consists of lowercase letters of the Latin alphabet. The number of characters in the string doesn't exceed $$$50$$$.

For each test case, output a separate line containing one non-negative integer $$$k$$$ — the number of letters which will be painted in red in a wonderful coloring.

NoteThe first test case contains the string from the statement. One of the wonderful colorings is shown in the figure. There's no wonderful coloring containing $$$3$$$ or more red letters because the total number of painted symbols will exceed the string's length.The string from the second test case can be painted as follows. Let's paint the first occurrence of each of the letters "c", "o", "e" in red and the second ones in green. Let's paint the letters "d", "f" in red and "r", "s" in green. So every letter will be painted in red or green, hence the answer better than $$$5$$$ doesn't exist.The third test case contains the string of distinct letters, so you can paint any set of characters in red, as long as the size of this set doesn't exceed half of the size of the string and is the maximum possible.The fourth test case contains a single letter which cannot be painted in red because there will be no letter able to be painted in green.The fifth test case contains a string of identical letters, so there's no way to paint more than one letter in red.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;

	my %h;

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

	my $ans = 0;

	for my $key ( sort keys %h ){
		if( $h{ $key } > 1 ){
			$ans += 2;
			}
		else{
			$ans ++;
			}
		}

	print $ans >> 1;
	}


A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:  ai ≥ ai - 1 for all even i,  ai ≤ ai - 1 for all odd i > 1. For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.Can you make the array z-sorted?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array a. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

If it's possible to make the array a z-sorted print n space separated integers ai — the elements after z-sort. Otherwise print the only word "Impossible".

#
my $n = <STDIN>;
chomp ( $n );

my $f = <STDIN>;
chomp ( $f );

my @arr = split m/ /, $f;
my @arr_two = (sort { $a <=> $b } @arr);

my @ans;
my $i = 0;
my $temp;
while ( @arr_two > 0 ) {

    if ( $i % 2 == 0 ) {
	push @ans, (shift @arr_two);}
    else {
	push @ans, (pop @arr_two);}
    $i += 1;
}

print (join " ", @ans);
print "\n";

# never impossible

<>;
@_ = sort {$a <=> $b} split ' ', <>;
push @ans, shift @_, pop @_ while @_;
print "@ans"

my $n = <STDIN>;
chomp ( $n );
my @arr;
my $f = <STDIN>;
chomp ( $f );
@arr = split m/ /, $f;

my @arr_two = sort @arr;
my @one, @two;

my $i;
while ( @arr_two > 0 ) {

    if ( ($i+1) % 2 == 0 ) {
	push @one, (shift @arr_two);
    }
    else {
	push @two, (shift @arr_two);
    }

    $i += 1;
}

my @two_two = reverse @two;

my @ans = ();
$i = 0;
while ( @two_two > 0 or @one ) {

    if ( ($i + 1) % 2 == 0 ) {
	push @ans, (shift @one);}
    else {
	push @ans, (shift @two_two);}
    $i += 1;
}

print (join " ", @ans);
print "\n";

#
my $n = <STDIN>;
chomp ( $n );

my $f = <STDIN>;
chomp ( $f );

my @arr = split m/ /, $f;
my @arr_two = sort @arr;

my @ans;
my $i = 0;
while ( @arr_two > 0 ) {

    if ( $i % 2 == 0 ) {
	push @ans, (shift @arr_two);}
    else {
	push @ans, (pop @arr_two);}
    $i += 1;
}

print (join " ", @ans);
print "\n";

# never impossible

#
my $n = <STDIN>;
chomp ( $n );
my @arr;
my $f = <STDIN>;
chomp ( $f );
@arr = split m/ /, $f;

my @arr_two = sort @arr;
my @one, @two;

my $i;
while ( @arr_two > 0 ) {

    if ( ($i+1) % 2 == 0 ) {
	push @one, (shift @arr_two);
    }
    else {
	push @two, (shift @arr_two);
    }

    $i += 1;
}

my @two_two = reverse @one;

my @ans = ();
$i = 0;
while ( @two_two > 0 or @two ) {

    if ( ($i + 1) % 2 == 0 ) {
	push @ans, (shift @two_two);}
    else {
	push @ans, (shift @two);}
    $i += 1;
}

print (join " ", @ans);
print "\n";

<>;
@_ = sort {$a <=> $b} split ' ', <>;
push @ans, pop @_, shift @_ while @_;
print "@ans"


You are given an array $$$a$$$ of length $$$n$$$ consisting of integers. You can apply the following operation, consisting of several steps, on the array $$$a$$$ zero or more times:   you select two different numbers in the array $$$a_i$$$ and $$$a_j$$$;  you remove $$$i$$$-th and $$$j$$$-th elements from the array. For example, if $$$n=6$$$ and $$$a=[1, 6, 1, 1, 4, 4]$$$, then you can perform the following sequence of operations:   select $$$i=1, j=5$$$. The array $$$a$$$ becomes equal to $$$[6, 1, 1, 4]$$$;  select $$$i=1, j=2$$$. The array $$$a$$$ becomes equal to $$$[1, 4]$$$. What can be the minimum size of the array after applying some sequence of operations to it?

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

For each test case, output the minimum possible size of the array after applying some sequence of operations to it.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my %h;

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

	my( $max ) = sort { $b <=> $a } values %h;

	$max -= ( @_ - $max );

	print $max < 0 ? 0 : $max;
	}


Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k) and sign all laws with numbers lying in the segments [a; a + k - 1] and [b; b + k - 1] (borders are included).As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.

The first line contains two integers n and k (2 ≤ n ≤ 2·105, 0 < 2k ≤ n) — the number of laws accepted by the parliament and the length of one segment in the law list, correspondingly. The next line contains n integers x1, x2, ..., xn — the absurdity of each law (1 ≤ xi ≤ 109).

Print two integers a, b — the beginning of segments that mr. Boosch should choose. That means that the president signs laws with numbers from segments [a; a + k - 1] and [b; b + k - 1]. If there are multiple solutions, print the one with the minimum number a. If there still are multiple solutions, print the one with the minimum b.

NoteIn the first sample mr. Boosch signs laws with numbers from segments [1;2] and [4;5]. The total absurdity of the signed laws equals 3 + 6 + 1 + 6 = 16.In the second sample mr. Boosch signs laws with numbers from segments [1;2] and [3;4]. The total absurdity of the signed laws equals 1 + 1 + 1 + 1 = 4.

# betaveros's polyglot adventures
use strict;
use warnings;

my ($nLaws, $seglen) = split(' ', <STDIN>);
my @absurdities = split(' ', <STDIN>);

my @cumsums = (0);

my $tempsum = 0;
foreach (@absurdities) {
	$tempsum += $_;
	push @cumsums, $tempsum;
}

my @segments = ();
my @maxsums = ();
my @maxis = ();

my $maxsum = 0;
my $maxi = 0;
foreach my $i (0 .. (scalar @absurdities) - $seglen) {
	my $segsum = $cumsums[$i + $seglen] - $cumsums[$i];
	push @segments, $segsum;
	if ($segsum > $maxsum) {
		$maxi = $i;
		$maxsum = $segsum;
	}
	push @maxsums, $maxsum;
	push @maxis, $maxi;
}

my $maxsign = 0;
my $maxsi1 = 0;
my $maxsi2 = 0;
foreach my $i ($seglen .. (scalar @absurdities) - $seglen) {
	my $signsum = $maxsums[$i - $seglen] + $segments[$i];
	if ($signsum > $maxsign) {
		$maxsign = $signsum;
		$maxsi1 = $maxis[$i - $seglen];
		$maxsi2 = $i;
	}
}
print ($maxsi1 + 1, " ", $maxsi2 + 1);


Two players play a game.Initially there are $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $$$n - 1$$$ turns are made. The first player makes the first move, then players alternate turns.The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.You want to know what number will be left on the board after $$$n - 1$$$ turns if both players make optimal moves.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of numbers on the board. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$).

Print one number that will be left on the board.

NoteIn the first sample, the first player erases $$$3$$$ and the second erases $$$1$$$. $$$2$$$ is left on the board.In the second sample, $$$2$$$ is left on the board regardless of the actions of the players.

use warnings;
use strict;
use constant NL => qq/\n/;
use integer;

<STDIN>;
my @arr = sort { $a <=> $b } ( split qq/ /, <STDIN> );
my $i = 0;
while ( @arr > 1 ) {
    pop @arr if ($i % 2 == 0);
    shift @arr if ($i % 2 == 1);
    $i += 1;
}
print $arr [ 0 ];
print NL;

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	print $_[ ( @_ - 1 ) / 2 ];
	}

use warnings;
use strict;
use constant NL => qq/\n/;

<STDIN>;
my @arr = sort ( split qq/ /, <STDIN> );
print $arr [ int ( $#arr / 2) ];
print NL;

use warnings;
use strict;
use constant NL => qq/\n/;

<STDIN>;
my @arr = sort ( split qq/ /, <STDIN> );
my $i = 0;
while ( @arr > 1 ) {
    pop @arr if $i % 2 == 0;
    shift @arr if $i % 2 == 1;
    $i += 1;
}
print $arr [ 0 ];
print NL;


As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.Let's consider a set of functions of the following form:  Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.

The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.

Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.

#!/usr/bin/perl

use 5.006;
use strict;
use warnings;

my %hash;

sub gcd {
  my $a = abs (shift);
  my $b = abs (shift);
  while ($b > 0) {
    $b ^= $a ^= $b ^= $a %= $b;
  }
  return $a;
}

my $n = <>;
for(1..$n) {
  my $line = <>;
  my @arr = split(/ /, $line);
  my $k = $arr[0];
  my $b = $arr[1];
  next if (0 == $k);
  my $g = gcd($k, $b);
  $k /= $g;
  $b /= $g;
  if ($k < 0) {
    $k = -$k;
    $b = -$b;
  }
  $hash{($k, $b)} = 1;
}
print "".keys( %hash )."\n";

#!/usr/bin/perl

use 5.006;
use strict;
use warnings;

my %hash;

sub gcd {
  my $a = shift;
  my $b = shift;
  return $b ? gcd($b, $a % $b) : $a;
}

my $n = <>;
for(1..$n) {
  my $line = <>;
  my @arr = split(/ /, $line);
  my $k = $arr[0];
  my $b = $arr[1];
  next if (0 == $k);
  $hash{10000000 * $b / $k} = 1;
}
print "".keys( %hash )."\n";

#!/usr/bin/perl

use 5.006;
use strict;
use warnings;

my %hash;

sub gcd {
  my $a = shift;
  my $b = shift;
  return $b ? gcd($b, $a % $b) : $a;
}

my $n = <>;
for(1..$n) {
  my $line = <>;
  my @arr = split(/ /, $line);
  my $k = $arr[0];
  my $b = $arr[1];
  next if (0 == $k);
  my $g = gcd($b, $k);
  $b /= $g;
  $k /= $g;
  $hash{$b}++;
}
print "".keys( %hash )."\n";

#!/usr/bin/perl

use 5.006;
use strict;
use warnings;

my %hash;

sub gcd {
  my $a = shift;
  my $b = shift;
  while ($b > 0) {
    $b ^= $a ^= $b ^= $a %= $b;
  }
  return $a;
}

my $n = <>;
for(1..$n) {
  my $line = <>;
  my @arr = split(/ /, $line);
  my $k = $arr[0];
  my $b = $arr[1];
  next if (0 == $k);
  my $g = gcd($k, $b);

  $hash{($k / $g, $b / $g)} = 1;
}
print "".keys( %hash )."\n";

#!/usr/bin/perl

use 5.006;
use strict;
use warnings;

my %hash;

sub gcd {
  my $a = shift;
  my $b = shift;
  while ($b > 0) {
    $b ^= $a ^= $b ^= $a %= $b;
  }
  return $a;
}

my $n = <>;
for(1..$n) {
  my $line = <>;
  my @arr = split(/ /, $line);
  my $k = $arr[0];
  my $b = $arr[1];
  next if (0 == $k);
  my $g = gcd($k, $b);
  $k /= $g;
  $b /= $g;
  if ($k < 0) {
    $k = -$k;
    $b = -$b;
  }
  $hash{($k, $b)} = 1;
}
print "".keys( %hash )."\n";

#!/usr/bin/perl

use 5.006;
use strict;
use warnings;

my %hash;

sub gcd {
  my $a = shift;
  my $b = shift;
  return $b ? gcd($b, $a % $b) : $a;
}

my $n = <>;
for(1..$n) {
  my $line = <>;
  my @arr = split(/ /, $line);
  my $k = $arr[0];
  my $b = $arr[1];
  next if (0 == $k);
  my $g = gcd($b, $k);
  $b /= $g;
  $k /= $g;
  $hash{1000 * $b / $k} = 1;
}
print "".keys( %hash )."\n";

#!/usr/bin/perl

use 5.006;
use strict;
use warnings;

my %hash;

sub gcd {
  my $a = shift;
  my $b = shift;
  return $b ? gcd($b, $a % $b) : $a;
}

my $n = <>;
for(1..$n) {
  my $line = <>;
  my @arr = split(/ /, $line);
  my $k = $arr[0];
  my $b = $arr[1];
  next if (0 == $k);
  $hash{$b / $k} = 1;
}
print "".keys( %hash )."\n";

#!/usr/bin/perl

use 5.006;
use strict;
use warnings;

my %hash;

sub gcd {
  my $a = shift;
  my $b = shift;
  return $b ? gcd($b, $a % $b) : $a;
}

my $n = <>;
for(1..$n) {
  my $line = <>;
  my @arr = split(/ /, $line);
  my $k = $arr[0];
  my $b = $arr[1];
  next if (0 == $k);
  $hash{1000000000 * $b / $k} = 1;
}
print "".keys( %hash )."\n";