Email address in Berland is a string of the form A@B, where A and B are arbitrary strings consisting of small Latin letters. Bob is a system administrator in «Bersoft» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once.Suddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that.

The first line contains the list of addresses without separators. The length of this string is between 1 and 200, inclusive. The string consists only from small Latin letters and characters «@».

If there is no list of the valid (according to the Berland rules) email addresses such that after removing all commas it coincides with the given string, output No solution. In the other case, output the list. The same address can be written in this list more than once. If there are several solutions, output any of them.

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

while(<>){
	s/(@\w)(\w+@)/$1,$2/g while /@(\w)(\w+)@/;
	print /@\w?@/||/^@/||/\@$/||!/@/?"No solution\n":"$_";
	}

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

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

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

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

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

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

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

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

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

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

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

while(<>){
	s/(@\w)(\w+@)/$1,$2/g while /@(\w)(\w+)@/;
	print /@\w?@/||/^@/||/\@$/?"No solution\n":"$_";
	}

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

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

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

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

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

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

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

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

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

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


Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race.Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next race. It's guaranteed that given astronaut will have unique number of points before the race.

The first line contains two integer numbers $$$N$$$ ($$$1 \leq N \leq 200000$$$) representing number of F1 astronauts, and current position of astronaut $$$D$$$ ($$$1 \leq D \leq N$$$) you want to calculate best ranking for (no other competitor will have the same number of points before the race). The second line contains $$$N$$$ integer numbers $$$S_k$$$ ($$$0 \leq S_k \leq 10^8$$$, $$$k=1...N$$$), separated by a single space, representing current ranking of astronauts. Points are sorted in non-increasing order. The third line contains $$$N$$$ integer numbers $$$P_k$$$ ($$$0 \leq P_k \leq 10^8$$$, $$$k=1...N$$$), separated by a single space, representing point awards for the next race. Points are sorted in non-increasing order, so winner of the race gets the maximum number of points.

Output contains one integer number — the best possible ranking for astronaut after the race. If multiple astronauts have the same score after the race, they all share the best ranking.

NoteIf the third ranked astronaut wins the race, he will have 35 points. He cannot take the leading position, but he can overtake the second position if the second ranked astronaut finishes the race at the last position.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

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

	my @S = split ' ', <>;

	my @P = split ' ', <>;

	my $pts = $S[ $d - 1 ] + shift @P;
	$debug and print " pts: $pts";

	my $pos = 0;

	while( $S[ 0 ] + $P[ @P - 1 ] > $pts ){
		$debug and print "  $S[ 0 ] + $P[ @P - 1 ] > $pts";
		shift @S;
		shift @P;
		$debug and print "  [@S]";
		$debug and print "  [@P]";
		}

	for my $i ( $d - 0 .. $n - 1 ){
		pop @S;
		shift @P;
		$debug and print "   [@S]";
		$debug and print "   [@P]";
		}

	pop @S;

	$debug and print " [@S]";
	$debug and print " [@P]";

	while( @S ){
		if( $S[ 0 ] + $P[ @P - 1 ] <= $pts ){
			shift @S;
			pop @P;
			$pos ++;
			}
		else{
			shift @S;
			shift @P;
			}
		$debug and print "   [@S]";
		$debug and print "   [@P]";
		}

	print $d - $pos;

	$debug and print '-' x 10;
	}


A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).

The first line contains one integer $$$n$$$ ($$$13 \le n < 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.

If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.

NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

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

	chomp;
	my $n = $_;

	$_ = <>, chomp;
	$debug and print;

	my $del = $n - 11 >> 1;
	$debug and print $del;

	my $cnt = 0;

	s/8(??{ $cnt ++; $cnt > $del ? '(*F)' : '' })//g;

	$debug and print;

	$cnt = 0;

	s/[^8](??{ $cnt ++; $cnt > $del ? '(*F)' : '' })//g;

	$debug and print;

	print /^8/ ? 'YES' : 'NO';
	}


You are given an array $$$a_1, a_2, \dots, a_n$$$, consisting of $$$n$$$ integers. You are also given an integer value $$$x$$$.Let $$$f(k)$$$ be the maximum sum of a contiguous subarray of $$$a$$$ after applying the following operation: add $$$x$$$ to the elements on exactly $$$k$$$ distinct positions. An empty subarray should also be considered, it has sum $$$0$$$.Note that the subarray doesn't have to include all of the increased elements.Calculate the maximum value of $$$f(k)$$$ for all $$$k$$$ from $$$0$$$ to $$$n$$$ independently.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of testcases. The first line of the testcase contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 5000$$$; $$$0 \le x \le 10^5$$$) — the number of elements in the array and the value to add. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$). The sum of $$$n$$$ over all testcases doesn't exceed $$$5000$$$.

For each testcase, print $$$n + 1$$$ integers — the maximum value of $$$f(k)$$$ for all $$$k$$$ from $$$0$$$ to $$$n$$$ independently.

NoteIn the first testcase, it doesn't matter which elements you add $$$x$$$ to. The subarray with the maximum sum will always be the entire array. If you increase $$$k$$$ elements by $$$x$$$, $$$k \cdot x$$$ will be added to the sum.In the second testcase:   For $$$k = 0$$$, the empty subarray is the best option.  For $$$k = 1$$$, it's optimal to increase the element at position $$$3$$$. The best sum becomes $$$-1 + 5 = 4$$$ for a subarray $$$[3, 3]$$$.  For $$$k = 2$$$, it's optimal to increase the element at position $$$3$$$ and any other element. The best sum is still $$$4$$$ for a subarray $$$[3, 3]$$$.  For $$$k = 3$$$, you have to increase all elements. The best sum becomes $$$(-2 + 5) + (-7 + 5) + (-1 + 5) = 5$$$ for a subarray $$$[1, 3]$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	@_ = split ' ', <>;

	my @max;

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

	my @sums = @_;

	for my $i ( 1 .. $n - 1 ){
		shift @_;
		pop @sums;

		my $max = -~0;
		for my $j ( 0 .. @sums - 1 ){
			$sums[ $j ] += $_[ $j ];
			$sums[ $j ] > $max and $max = $sums[ $j ];
			}
		push @max, $max;
		}

	my @cum = @max;

	for my $i ( reverse 0 .. @cum - 2 ){
		$cum[ $i ] = $cum[ $i ] > $cum[ $i + 1 ] ?
			$cum[ $i ] : $cum[ $i + 1 ];
		}

#	print "@cum";

	unshift @cum, $cum[ 0 ];

	for my $i ( 1 .. @cum - 1 ){
		$cum[ $i ] += $x * $i;
		}

	$cum[ 0 ] < 0 and $cum[ 0 ] = 0;

#	print "@cum";

	for my $i ( 1 .. @cum - 1 ){
		$cum[ $i ] = $cum[ $i ] > $cum[ $i - 1 ] ?
			$cum[ $i ] : $cum[ $i - 1 ];
		}

	print "@cum";

#	my @ans;

#	my $max = 0;
#	$max < $_ and $max = $_ for @max;

#	push @ans, $max;

#	for my $i ( 1 .. $n ){
#		my $max = $ans[ @ans - 1 ];

#		for my $j ( $i - 1 .. $n - 1 ){
#			$max[ $j ] += $x;

#			$max < $max[ $j ] and $max = $max[ $j ];
#			}

#		push @ans, $max;
#		}

#	print "@ans";
	}


One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?

The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).

If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.


One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the left of the i-th box" ("To the left of i"), "Hidden to the right of the i-th box" ("To the right of i"). Such hints mean that there are no flakes in the i-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.

The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000) which represent the number of boxes and the number of hints correspondingly. Next m lines contain hints like "To the left of i" and "To the right of i", where i is integer (1 ≤ i ≤ n). The hints may coincide.

The answer should contain exactly one integer — the number of boxes that should necessarily be checked or "-1" if the hints are contradictory.

($n, $m) = split (" ", <STDIN>);

$M = "1" x $n;

for (<STDIN>) {
	/To the (left|right) of (\d+)/ or die;
	($direction, $pos) = ($1, $2);
	if ($direction eq "left") {
		$left = 1; $right = 0;
	} else {
		$left = 0; $right = 1;
	}
	$m = ($left x ($pos - 1))."0".($right x ($n - $pos));
	$M = $M & $m;
}

$count = $M =~ y/1//;
$count = -1 if $count == 0;
print $count;


Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $$$k$$$ such that Mr. Black can exit the house after opening the first $$$k$$$ doors.We have to note that Mr. Black opened each door at most once, and in the end all doors became open.

The first line contains integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of doors. The next line contains $$$n$$$ integers: the sequence in which Mr. Black opened the doors. The $$$i$$$-th of these integers is equal to $$$0$$$ in case the $$$i$$$-th opened door is located in the left exit, and it is equal to $$$1$$$ in case it is in the right exit. It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.

Print the smallest integer $$$k$$$ such that after Mr. Black opened the first $$$k$$$ doors, he was able to exit the house.

NoteIn the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.In the second example when the first two doors were opened, there was open closed door in each of the exit.With three doors opened Mr. Black was able to use the left exit.

use strict;
use warnings;

use Data::Dumper;

sub main {

    my $in = *STDIN;
    # open(my $in, '<:encoding(UTF-8)', *STDIN);
    # open(my $out, '>:encoding(UTF-8)', './out.txt');

    my $r= <$in>; chomp($r);
    my $n= $r;

    $r= <$in>;
    my @d= split(' ', $r);

    my $dl= 0;
    my $dr= 0;

    for my $door (@d) {
        ($door eq 1) ? $dr++ : $dl++;
    }

    my $lc= 0;
    my $rc= 0;
    my $c= 0;
    for my $door (@d) {
        ($door eq 1) ? $rc++ : $lc++;
        $c++;

        if($rc >= $dr || $lc >= $dl) {
            print $c;
            # print $out $c;
            return;
        }
    }

}

main() unless caller();

use strict;
#open STDIN, '<input.txt';
#open STDOUT, '>output.txt';
my $n = <>;
my @a = split(' ', <>);
my $buf1 = 0;
my $buf2 = 0;
sub solve{
  my ($a, $n) = @_;
for(my $i = 0; $i < $n; $i++){
  if($a[$i] == 0){
    $buf1++;
  }
  else{
    $buf2++;
  }
}
my $ans = 0;
my $i = 0;
while($buf1 > 0 && $buf2 > 0){
  if($a[$i] == 0){
    $buf1--;
    $ans++;
  }
  else{
    $buf2--;
    $ans++;
  }
  $i++;
}
print $ans;
}
solve(\@a, $n);

use strict;
#open STDIN, '<input.txt';
#open STDOUT, '>output.txt';
my $n = <>;
my @a = split(' ', <>);
my $buf1 = 0;
my $buf2 = 0;
for(my $i = 0; $i < $n; $i++){
  if($a[$i] == 0){
    $buf1++;
  }
  else{
    $buf2++;
  }
}
my $ans = 0;
my $i = 0;
while($buf1 > 0 && $buf2 > 0){
  if($a[$i] == 0){
    $buf1--;
    $ans++;
  }
  else{
    $buf2--;
    $ans++;
  }
  $i++;
}
print $ans;

use strict;
#open STDIN, '<input.txt';
#open STDOUT, '>output.txt';
my $n = <>;
my @a = split(' ', <>);
my %h;
for(my $i = 0; $i < $n; $i++){
  $h{$a[$i]}++;
}
my $ans = 0;
for(my $i = 0; $i < $n; $i++){
  $h{$a[$i]}--;
  $ans++;
  if($h{$a[$i]} == 0){
    print $ans;
    exit(0);
  }
}
print $ans;

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	y/ //d;

	my $len = length;

	$_ = reverse;

	print /^0++(?=1)|^1++(?=0)/ ? $len - length $& : 0;
	}

use strict;
use warnings;

use Data::Dumper;

sub main {

    open(my $in, '<:encoding(UTF-8)', './in.txt');
    # open(my $out, '>:encoding(UTF-8)', './out.txt');

    my $r= <$in>; chomp($r);
    my $n= $r;

    $r= <$in>;
    my @d= split(' ', $r);

    my $dl= 0;
    my $dr= 0;

    for my $door (@d) {
        ($door eq 1) ? $dr++ : $dl++;
    }

    my $lc= 0;
    my $rc= 0;
    my $c= 0;
    for my $door (@d) {
        ($door eq 1) ? $rc++ : $lc++;
        $c++;

        if($rc >= $dr || $lc >= $dl) {
            print $c;
            # print $out $c;
            return;
        }
    }

}

main() unless caller();

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	y/ //d;

	my $len = length;

	$_ = reverse;

	print /^(.)\1*+\B/ ? $len - length $& : 0;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	y/ //d;

	my $len = length;

	$_ = reverse;

	/(.)\1*/;

	print $len - length $&;
	}


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.


The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.

The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.

Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.

NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.

#!/usr/bin/perl -w

use strict;

chomp($_ = <>);
my ($n, $m) = split;
my %votes;
my ($v_max, $v_candidate) = (0,1);

for my $i (0..$m-1) {
    chomp($_ = <>);
    my @city_votes = split;
    my ($max, $candidate) = (0, 1);
    my $len = @city_votes;
    for my $j (0..$len-1) {
        if($max < $city_votes[$j]) {
            $max = $city_votes[$j];
            $candidate = $j + 1;
        }
    }

    $votes{$candidate} += 1;
    if($votes{$candidate} > $v_max) {
        $v_max = $votes{$candidate};
        $v_candidate = $candidate;
    }
    elsif($votes{$candidate} == $v_max && $v_candidate > $candidate) {
        $v_max = $votes{$candidate};
        $v_candidate = $candidate;
    }
}

print $v_candidate, "\n";

#!/usr/bin/perl -w

use strict;

chomp($_ = <>);
my ($n, $m) = split;
my %votes;
my ($v_max, $v_candidate) = (0, 0);

for my $i (0..$m) {
    chomp($_ = <>);
    my @city_votes = split;
    my ($max, $candidate) = (0, 0);
    my $len = length(@city_votes);
    for my $j (0..$len) {
        if($max < $city_votes[$j]) {
            $max = $city_votes[$j];
            $candidate = $j + 1;
        }
    }

    $votes{$candidate} += 1;
    if($votes{$candidate} > $v_max) {
        $v_max = $votes{$candidate};
        $v_candidate = $candidate;
    }
    elsif($votes{$candidate} == $v_max && $v_candidate > $candidate) {
        $v_max = $votes{$candidate};
        $v_candidate = $candidate;
    }
}

print $v_candidate, "\n";

#!/usr/bin/perl -w

use strict;

chomp($_ = <>);
my ($n, $m) = split;
my %votes;
my ($v_max, $v_candidate) = (0, 0);

for my $i (0..$m-1) {
    chomp($_ = <>);
    my @city_votes = split;
    my ($max, $candidate) = (0, 0);
    my $len = @city_votes;
    for my $j (0..$len-1) {
        if($max < $city_votes[$j]) {
            $max = $city_votes[$j];
            $candidate = $j + 1;
        }
    }

    $votes{$candidate} += 1;
    if($votes{$candidate} > $v_max) {
        $v_max = $votes{$candidate};
        $v_candidate = $candidate;
    }
    elsif($votes{$candidate} == $v_max && $v_candidate > $candidate) {
        $v_max = $votes{$candidate};
        $v_candidate = $candidate;
    }
}

print $v_candidate, "\n";

#!/usr/bin/perl -w

use strict;

chomp($_ = <>);
my ($n, $m) = split;
my %votes;
my ($v_max, $v_candidate) = (0, 0);

for my $i (0..$m-1) {
    chomp($_ = <>);
    my @city_votes = split;
    my ($max, $candidate) = (0, 0);
    my $len = length(@city_votes);
    for my $j (0..$len-1) {
        if($max < $city_votes[$j]) {
            $max = $city_votes[$j];
            $candidate = $j + 1;
        }
    }

    $votes{$candidate} += 1;
    if($votes{$candidate} > $v_max) {
        $v_max = $votes{$candidate};
        $v_candidate = $candidate;
    }
    elsif($votes{$candidate} == $v_max && $v_candidate > $candidate) {
        $v_max = $votes{$candidate};
        $v_candidate = $candidate;
    }
}

print $v_candidate, "\n";


At the store, the salespeople want to make all prices round. In this problem, a number that is a power of $$$10$$$ is called a round number. For example, the numbers $$$10^0 = 1$$$, $$$10^1 = 10$$$, $$$10^2 = 100$$$ are round numbers, but $$$20$$$, $$$110$$$ and $$$256$$$ are not round numbers. So, if an item is worth $$$m$$$ bourles (the value of the item is not greater than $$$10^9$$$), the sellers want to change its value to the nearest round number that is not greater than $$$m$$$. They ask you: by how many bourles should you decrease the value of the item to make it worth exactly $$$10^k$$$ bourles, where the value of $$$k$$$ — is the maximum possible ($$$k$$$ — any non-negative integer).For example, let the item have a value of $$$178$$$-bourles. Then the new price of the item will be $$$100$$$, and the answer will be $$$178-100=78$$$.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases . Each test case is a string containing a single integer $$$m$$$ ($$$1 \le m \le 10^9$$$) — the price of the item.

For each test case, output on a separate line a single integer $$$d$$$ ($$$0 \le d < m$$$) such that if you reduce the cost of the item by $$$d$$$ bourles, the cost of the item will be the maximal possible round number. More formally: $$$m - d = 10^k$$$, where $$$k$$$ — the maximum possible non-negative integer.


One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.

The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.

Output one integer — the number of different variants of group composition.

#!/usr/bin/env perl

use bigint;

sub factorial {
    my $n = shift;
    if ($n==0) {
        return 1;
    } else {
        return $n*factorial($n-1);
    }
}

sub subfactorial {
    my $n = shift;
    my $sub = shift;
    if ($n==$sub) {
        return 1;
    } else {
        return $n*subfactorial($n-1, $sub);
    }
}

$np = <STDIN>;
$subnp = subfactorial($np, $np-4);
$k = factorial(4);
$result = 0;
for ($i=5; $i <= 7; $i++)
{
	$subnp *= $np - $i+1;
	$k *= $i;
	$result += ($subnp / $k);
}
print "$result\n";


Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer — the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?

The first line contains integer n (1 ≤ n ≤ 100). The second line contains 2·n space-separated integers ai (10 ≤ ai ≤ 99), denoting the numbers on the cubes.

In the first line print a single number — the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2·n numbers bi (1 ≤ bi ≤ 2). The numbers mean: the i-th cube belongs to the bi-th heap in your division. If there are multiple optimal ways to split the cubes into the heaps, print any of them.

NoteIn the first test case Valera can put the first cube in the first heap, and second cube — in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.In the second test case Valera can obtain numbers 1313, 1345, 2413, 2445. Note, that if he put the first and the third cubes in the first heap, he can obtain only two numbers 1324 and 1345.

use strict;

use List::Util qw(sum min);

chomp(my $n = <>);
chomp($_ = <>);
my @a = split;

my %occurence = ();
++$occurence{$_} for @a;

my $sum = sum map { min $_, 2 } values %occurence;
my $x = int($sum / 2);
my $y = $sum - $x;

print $x * $y, "\n";

my %pos = ();
push @{$pos{$a[$_]}}, $_ for 0 .. $#a;

my @res = (0) x (2 * $n);
my @one = ();
my @rest = ();
my @h1 = ();
my @h2 = ();
while (my ($k, $v) = each %pos) {
    if (@$v == 1) {
        push @one, @$v;
    } else {
        push @h1, shift @$v;
        push @h2, shift @$v;
        push @rest, @$v;
    }
}
while (@one) {
    push @h1, shift @one;
    push @h2, shift @one if @one;
}
while (@rest) {
    if (@h1 < $n) {
        push @h1, shift @rest;
    } else {
        push @h2, shift @rest;
    }
}
$res[$_] = 1 for @h1;
$res[$_] = 2 for @h2;
print "@res\n";

use strict;

use List::Util qw(sum min);

chomp(my $n = <>);
chomp($_ = <>);
my @a = split;

my %occurence = ();
++$occurence{$_} for @a;

my $sum = sum map { min $_, 2 } values %occurence;
my $x = int($sum / 2);
my $y = $sum - $x;

print $x * $y, "\n";

my %pos = ();
push @{$pos{$a[$_]}}, $_ for 0 .. $#a;

my @res = (0) x (2 * $n);
my @one = ();
my @rest = ();
my @h1 = ();
my @h2 = ();
while (my ($k, $v) = each %occurence) {
    if (@{$pos{$k}} == 1) {
        push @one, @{$pos{$k}};
    } else {
        push @h1, shift @{$pos{$k}};
        push @h2, shift @{$pos{$k}};
        push @rest, @{$pos{$k}};
    }
}
while (@one) {
    push @h1, shift @one;
    push @h2, shift @one if @one;
}
for (@rest) {
    if (@h1 < $n) {
        push @h1, shift @rest;
    } else {
        push @h2, shift @rest;
    }
}
$res[$_] = 1 for @h1;
$res[$_] = 2 for @h2;
print "@res\n";

use strict;

use List::Util qw(sum min);

chomp(my $n = <>);
chomp($_ = <>);
my @a = split;

my %occurence = ();
++$occurence{$_} for @a;

my $sum = sum map { min $_, 2 } values %occurence;
my $x = int($sum / 2);
my $y = $sum - $x;

print $x * $y, "\n";

my %pos = ();
push @{$pos{$a[$_]}}, $_ for 0 .. $#a;

my @res = (0) x (2 * $n);
my @one = ();
my @rest = ();
while (my ($k, $v) = each %occurence) {
    if (@{$pos{$k}} == 1) {
        push @one, @{$pos{$k}};
    } else {
        $res[shift @{$pos{$k}}] = 1;
        $res[shift @{$pos{$k}}] = 2;
        push @rest, @{$pos{$k}};
        --$x;
        --$y;
    }
}
while (@one) {
    $res[shift @one] = 1;
    --$x;
    if (@one) {
        $res[shift @one] = 2;
        --$y;
    }
}
for (@rest) {
    if ($x > 0) {
        $res[shift @rest] = 1;
        --$x;
    } else {
        $res[shift @rest] = 2;
        --$y;
    }
}
print "@res\n";


Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.There were $$$n$$$ classes of that subject during the semester and on $$$i$$$-th class professor mentioned some non-negative integer $$$a_i$$$ to the students. It turned out, the exam was to tell the whole sequence back to the professor. Sounds easy enough for those who attended every class, doesn't it?Obviously Mishka didn't attend any classes. However, professor left some clues on the values of $$$a$$$ to help out students like Mishka:   $$$a$$$ was sorted in non-decreasing order ($$$a_1 \le a_2 \le \dots \le a_n$$$);  $$$n$$$ was even;  the following sequence $$$b$$$, consisting of $$$\frac n 2$$$ elements, was formed and given out to students: $$$b_i = a_i + a_{n - i + 1}$$$. Professor also mentioned that any sequence $$$a$$$, which produces sequence $$$b$$$ with the presented technique, will be acceptable.Help Mishka to pass that last exam. Restore any sorted sequence $$$a$$$ of non-negative integers, which produces sequence $$$b$$$ with the presented technique. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of sequence $$$a$$$. $$$n$$$ is always even. The second line contains $$$\frac n 2$$$ integers $$$b_1, b_2, \dots, b_{\frac n 2}$$$ ($$$0 \le b_i \le 10^{18}$$$) — sequence $$$b$$$, where $$$b_i = a_i + a_{n - i + 1}$$$. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.

Print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{18}$$$) in a single line. $$$a_1 \le a_2 \le \dots \le a_n$$$ should be satisfied. $$$b_i = a_i + a_{n - i + 1}$$$ should be satisfied for all valid $$$i$$$.

#!/usr/bin/perl

use strict;
use warnings;
use integer;

<>;

my $bline = <>;
chomp $bline;

my @bseq = split /\s+/, $bline;

my ($low, $up) = (0, shift @bseq);

my @from_front = ($low);
my @from_back = ($up);

foreach my $b (@bseq) {
	my $sum = $low + $up;
	my $err = abs($sum - $b);
	$low+= $err if $sum < $b;
	$up -= $err if $sum > $b;
	push @from_front, $low;
	push @from_back , $up ;
}

print "@from_front";
print " ";
my @revd = reverse @from_back;
print "@revd\n";

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my @L;
	my @R;

	my $max = shift @_;
	unshift @L, 0;
	unshift @R, $max;

	for( @_ ){
		my $sum = $L[ 0 ] + $R[ 0 ];
		if( $sum == $_ ){
			unshift @L, $L[ 0 ];
			unshift @R, $R[ 0 ];
			}
		elsif( $sum < $_ ){
			unshift @L, $_ - $R[ 0 ];
			unshift @R, $R[ 0 ];
			}
		elsif( $sum > $_ ){
			unshift @R, $_ - $L[ 0 ];
			unshift @L, $L[ 0 ];
			}
		}

	print join ' ', ( reverse @L ), @R;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my @L;
	my @R;

	my $max = shift @_;
	unshift @L, 0;
	unshift @R, $max;

	for( @_ ){
		my $sum = $L[ 0 ] + $R[ 0 ];
		if( $sum == $_ ){
			unshift @L, $L[ 0 ];
			unshift @R, $R[ 0 ];
			}
		elsif( $sum < $_ ){
			unshift @L, $_ - $R[ 0 ];
			unshift @R, $R[ 0 ];
			}
		elsif( $sum > $_ ){
			unshift @R, $_ - $L[ 0 ];
			unshift @L, $L[ 0 ];
			}
		}

	print join ' ', ( reverse @L ), @R;
	}


After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.

The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one.  The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1.

Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.

use strict;
use warnings;
use Data::Dumper;

my $rc = <>;
my $a;
my @rooms;
my @keys;
my %hk;
for (0 .. $rc - 2)
{

    read(STDIN, $keys[$_], 1);
    read(STDIN, $rooms[$_], 1);

    $keys[$_] = uc($keys[$_]);
    $rooms[$_] = uc($rooms[$_]);
    $hk{$rooms[$_]} = 0;
    $hk{$keys[$_]} = 0;

}
my $ans = 0;
for (0 .. $#rooms)
{
    $hk{$keys[$_]}++;
    if($hk{$rooms[$_]} <= 0)
    {
        $ans ++;
    }
    else
    {
        $hk{$rooms[$_]}--;
    }

}
print $ans;

use strict;
use warnings;
use Data::Dumper;

my $rc = <>;
my $a;
my @rooms;
my @keys;
for (0 .. $rc - 2)
{
    read(STDIN, $rooms[$_], 1);
    $rooms[$_] = uc($rooms[$_]);
    read(STDIN, $keys[$_], 1);
}
my %hk;
my $ans = 0;
for (0 .. ($rc) / 2 + 1)
{
    $hk{$keys[$_]}++;
    if(!defined($hk{$rooms[$_]}) or $hk{$rooms[$_]} <= 0)
    {
        $ans ++;
    }
    else
    {
        $hk{$rooms[$_]}--;
    }
}
print $ans;

use strict;
use warnings;
use Data::Dumper;

my $rc = <>;
my $a;
my @rooms;
my @keys;
my %hk;
for (0 .. $rc - 2)
{
    read(STDIN, $rooms[$_], 1);
    $rooms[$_] = uc($rooms[$_]);
    read(STDIN, $keys[$_], 1);
    $keys[$_] = uc($keys[$_]);
    $hk{$rooms[$_]} = 0;
    $hk{$keys[$_]} = 0;

}

my $ans = 0;
for (0 .. $#rooms)
{
    $hk{$keys[$_]}++;
    if($hk{$rooms[$_]} <= 0)
    {
        $ans ++;
    }
    else
    {
        $hk{$rooms[$_]}--;
    }

}
print $ans;

use strict;
use warnings;
use Data::Dumper;

my $rc = <>;
my $a;
my @rooms;
my @keys;
for (0 .. $rc - 2)
{
    read(STDIN, $rooms[$_], 1);
    $rooms[$_] = uc($rooms[$_]);
    read(STDIN, $keys[$_], 1);
}
my %hk;
my $ans = 0;
for (0 .. $#rooms)
{
    $hk{$keys[$_]}++;
    if(!defined($hk{$rooms[$_]}) or $hk{$rooms[$_]} <= 0)
    {
        $ans ++;
    }
    else
    {
        $hk{$rooms[$_]}--;
    }
}
print $ans;


Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so that all brothers got the same number of candies.

The single line contains a single integer n (n is even, 2 ≤ n ≤ 100) — the number of Gerald's brothers.

Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers — the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n2. You can print the numbers in the lines in any order.  It is guaranteed that the solution exists at the given limits.

NoteThe sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.

use strict;

my $n = <>;

my $counter = 1;
foreach my $i  (1..$n) {
	print $i.' ';

	my $number = $i;
	for my $j (1..$n - 1) {
		if ($number % $n == 0) {
			$counter = 1;
		}
		else {
			$counter = $n + 1;
		}
		$number = $counter + $number;
		print $number.' ';

		#my $counter = $n + 2 - $;
		#my $number = $i;

	}
	print "\n";
}

use strict;

my $n = 5;

my $counter = 1;
foreach my $i  (1..$n) {
	print $i.' ';

	my $number = $i;
	for my $j (1..$n - 1) {
		if ($number % $n == 0) {
			$counter = 1;
		}
		else {
			$counter = $n + 1;
		}
		$number = $counter + $number;
		print $number.' ';

		#my $counter = $n + 2 - $;
		#my $number = $i;

	}
	print "\n";
}


You are given two arrays of length $$$n$$$: $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_n$$$.You can perform the following operation any number of times:   Choose integer index $$$i$$$ ($$$1 \le i \le n$$$);  Swap $$$a_i$$$ and $$$b_i$$$. What is the minimum possible sum $$$|a_1 - a_2| + |a_2 - a_3| + \dots + |a_{n-1} - a_n|$$$ $$$+$$$ $$$|b_1 - b_2| + |b_2 - b_3| + \dots + |b_{n-1} - b_n|$$$ (in other words, $$$\sum\limits_{i=1}^{n - 1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$$$) you can achieve after performing several (possibly, zero) operations?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 4000$$$) — the number of test cases. Then, $$$t$$$ test cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$2 \le n \le 25$$$) — the length of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) — the array $$$b$$$.

For each test case, print one integer — the minimum possible sum $$$\sum\limits_{i=1}^{n-1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$$$.

NoteIn the first test case, we can, for example, swap $$$a_3$$$ with $$$b_3$$$ and $$$a_4$$$ with $$$b_4$$$. We'll get arrays $$$a = [3, 3, 3, 3]$$$ and $$$b = [10, 10, 10, 10]$$$ with sum $$$3 \cdot |3 - 3| + 3 \cdot |10 - 10| = 0$$$.In the second test case, arrays already have minimum sum (described above) equal to $$$|1 - 2| + \dots + |4 - 5| + |6 - 7| + \dots + |9 - 10|$$$ $$$= 4 + 4 = 8$$$.In the third test case, we can, for example, swap $$$a_5$$$ and $$$b_5$$$.

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

my ($testcase) = map { $_ - 0 } split(/\s+/,<STDIN>);

while( $testcase -- > 0 ){

  my ($n) = map { $_ - 0 } split(/\s+/,<STDIN>);
  my @A = map { $_ - 0 } split(/\s+/,<STDIN>);
  my @B = map { $_ - 0 } split(/\s+/,<STDIN>);

  my $res = 0;
  for(my $i=1;$i<$n;$i++){
    $res += &min( abs($A[$i-1] - $A[$i]) + abs($B[$i-1] - $B[$i] ) ,
                  abs($A[$i-1] - $B[$i]) + abs($B[$i-1] - $A[$i] ) );
  }
  print "$res\n";
}

exit(0);

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


Vasya is reading a e-book. The file of the book consists of $$$n$$$ pages, numbered from $$$1$$$ to $$$n$$$. The screen is currently displaying the contents of page $$$x$$$, and Vasya wants to read the page $$$y$$$. There are two buttons on the book which allow Vasya to scroll $$$d$$$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $$$10$$$ pages, and $$$d = 3$$$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.Help Vasya to calculate the minimum number of times he needs to press a button to move to page $$$y$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases. Each testcase is denoted by a line containing four integers $$$n$$$, $$$x$$$, $$$y$$$, $$$d$$$ ($$$1\le n, d \le 10^9$$$, $$$1 \le x, y \le n$$$) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively.

Print one line for each test. If Vasya can move from page $$$x$$$ to page $$$y$$$, print the minimum number of times he needs to press a button to do it. Otherwise print $$$-1$$$.

NoteIn the first test case the optimal sequence is: $$$4 \rightarrow 2 \rightarrow 1 \rightarrow 3 \rightarrow 5$$$.In the second test case it is possible to get to pages $$$1$$$ and $$$5$$$.In the third test case the optimal sequence is: $$$4 \rightarrow 7 \rightarrow 10 \rightarrow 13 \rightarrow 16 \rightarrow 19$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

while(<>){
	chomp;
	$debug and print '-' x 15;
	$debug and print "[$_]";
	my( $n, $x, $y, $d ) = split;

	my @cand;
	my $cand;

	$cand = abs( $x - $y );

	if( $cand % $d == 0 ){
		push @cand, $cand / $d;
		}

	$cand = $y - 1;

	if( $cand % $d == 0 ){
		my $add = ( $x - 1 ) / $d;
		$add =~ /\./ and $add += 1;
		$add = int $add;
		push @cand, $cand / $d + $add;
		}

	$cand = $n - $y;

	if( $cand % $d == 0 ){
		my $add = ( $n - $x ) / $d;
		$add =~ /\./ and $add += 1;
		$add = int $add;
		push @cand, $cand / $d +$add;
		}

	$debug and print "[@cand]";

	print !@cand ? -1 : (
		sort { $a <=> $b }
		@cand
		)[ 0 ]
	}


"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.With that begins the watch of Jon Snow. He is assigned the task to support the stewards.This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.Can you find how many stewards will Jon support?

First line consists of a single integer n (1 ≤ n ≤ 105) — the number of stewards with Jon Snow. Second line consists of n space separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) representing the values assigned to the stewards.

Output a single integer representing the number of stewards which Jon will feed.

NoteIn the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5.In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2.

#!/usr/bin/perl

my $num = <>;
chomp($num);
my $line2 = <>;
chomp($line2);
my @tokens = split (" ", $line2);
my @array = sort { $a <=> $b } @tokens;
my $min = $array[0];
my $max = $array[-1];
my $output = 0 ;
for (my $i=0;$i < $num;$i++) {
                #print "$tokens[$i] -- $min -- $max\n";
        if ($tokens[$i] > $min && $tokens[$i] < $max) {
                $output++;
        }
}
print "$output\n";

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){

	@_ = sort { $a <=> $b } split ' ', <>;
	my $min = $_[0];
	my $max = $_[-1];

	my $cnt = 0;

	$_ != $min and $_ != $max and $cnt ++ for @_;

	print $cnt;
	}

#!/usr/bin/perl

my $num = <>;
chomp($num);
my $line2 = <>;
chomp($line2);
my @tokens = split (" ", $line2);
my @array = sort { $a <=> $b } @tokens;
my $min = $array[0];
my $max = $array[-1];
my $output = 0 ;
for (my $i=1;$i < $num-1;$i++) {
                #print "$tokens[$i] -- $min -- $max\n";
        if ($tokens[$i] > $min && $tokens[$i] < $max) {
                $output++;
        }
}
print "$output\n";


Slava plays his favorite game "Peace Lightning". Now he is flying a bomber on a very specific map.Formally, map is a checkered field of size 1 × n, the cells of which are numbered from 1 to n, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies very high, but he can drop a bomb in any cell. All tanks in this cell will be damaged.If a tank takes damage for the first time, it instantly moves to one of the neighboring cells (a tank in the cell n can only move to the cell n - 1, a tank in the cell 1 can only move to the cell 2). If a tank takes damage for the second time, it's counted as destroyed and never moves again. The tanks move only when they are damaged for the first time, they do not move by themselves.Help Slava to destroy all tanks using as few bombs as possible.

The first line contains a single integer n (2 ≤ n ≤ 100 000) — the size of the map.

In the first line print m — the minimum number of bombs Slava needs to destroy all tanks. In the second line print m integers k1, k2, ..., km. The number ki means that the i-th bomb should be dropped at the cell ki. If there are multiple answers, you can print any of them.


You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!An array $$$a$$$ of length $$$n$$$ is called complete if all elements are positive and don't exceed $$$1000$$$, and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \leq x,y,z \leq n$$$), $$$a_{x}+a_{y} \neq a_{z}$$$ (not necessarily distinct).You are given one integer $$$n$$$. Please find any complete array of length $$$n$$$. It is guaranteed that under given constraints such array exists.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Description of the test cases follows. The only line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case, print a complete array on a single line. All elements have to be integers between $$$1$$$ and $$$1000$$$ and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \leq x,y,z \leq n$$$) (not necessarily distinct), $$$a_{x}+a_{y} \neq a_{z}$$$ must hold. If multiple solutions exist, you may print any.

NoteIt can be shown that the outputs above are valid for each test case. For example, $$$44+44 \neq 384$$$.Below are some examples of arrays that are NOT complete for the 1st test case:$$$[1,2,3,4,5]$$$ Notice that $$$a_{1}+a_{2} = a_{3}$$$.$$$[1,3000,1,300,1]$$$ Notice that $$$a_{2} = 3000 > 1000$$$.


The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.

The first line contains a single integer n (2 ≤ n ≤ 105) — the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, — array a. Note that the elements of the array are not necessarily distinct numbers.

In a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise.

NoteIn the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES".In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES".In the third sample we can't sort the array in more than one swap operation, so the answer is "NO".

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

sub main {
    my $n = int <STDIN>;
    my @arr = map int, split /\D/, <STDIN>;
    my @sorted_arr = sort { $a <=> $b } @arr;
    my $count = 0;
    for (0 .. $#arr) {
	if ($arr[$_] != $sorted_arr[$_]) {
	    $count++;
	}
    }
    if ($count <= 2) {
	print 'YES';
    } else {
	print 'NO';
    }
}

main();

__END__

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

sub badElems {
    my @a = @_;
    my @indexes;
    for my $i (1 .. $#a) {
	if ($a[$i] < $a[$i - 1]) {
	    push(@indexes, $i);
	}
    }
    return @indexes;
}

sub check {
    my ($i1, $i2, @a) = @_;
    ($a[$i1], $a[$i2]) = ($a[$i2], $a[$i1]);
return ( (($i1 == 0) || ($a[$i1-1] <= $a[$i1])) &&
	 ($a[$i1] <= $a[$i1+1]) &&
	 ($a[$i2-1] <= $a[$i2]) &&
	 (($i2 == $#a) || ($a[$i2] <= $a[$i2+1])));
}

sub findFirstToSwap {
    my ($i2, @a) = @_;
    my $i = $i2-1;
    my $ai = $a[$i];
    do {
	$i--;
    } while (($i > 0) && ($a[$i] = $ai));
    return $i;
}

sub isGood {
    my @a = @_;
    my @indexes = badElems(@a);
    if (! @indexes) {
	return 1;
    } elsif (@indexes > 2) {
	return 0;
    } else {
	if (@indexes == 1) {
	    unshift(@indexes, findFirstToSwap($indexes[0], @a));
	} else {
	    $indexes[0]--;
	}
	return check(@indexes, @a);
    }
}

sub main {
    my $n = int(<STDIN>);
    my @a = map(int, split(/\D/, <STDIN>));
    if (isGood(@a)) {
	print 'YES';
    } else {
	print 'NO';
    }
}

main();

__END__

4
2 2 2 1

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

sub badElems {
    my @a = @_;
    my @indexes;
    for my $i (1 .. $#a) {
	if ($a[$i] < $a[$i - 1]) {
	    push(@indexes, $i);
	}
    }
    return @indexes;
}

sub check {
    my ($i1, $i2, @a) = @_;
    ($a[$i1], $a[$i2]) = ($a[$i2], $a[$i1]);
return ( (($i1 == 0) || ($a[$i1-1] <= $a[$i1])) &&
	 ($a[$i1] <= $a[$i1+1]) &&
	 ($a[$i2-1] <= $a[$i2]) &&
	 (($i2 == $#a) || ($a[$i2] <= $a[$i2+1])));
}

sub isGood {
    my @a = @_;
    my @indexes = badElems(@a);
    if (! @indexes) {
	return 1;
    } elsif (@indexes > 2) {
	return 0;
    } else {
	if (@indexes == 1) {
	    unshift(@indexes, $indexes[0] - 1);
	} else {
	    $indexes[0]--;
	}
	return check(@indexes, @a);
    }
}

sub main {
    my $n = int(<STDIN>);
    my @a = map(int, split(/\D/, <STDIN>));
    if (isGood(@a)) {
	print 'YES';
    } else {
	print 'NO';
    }
}

main();

__END__


Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!

The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.

If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.


The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the i-th computer it was ai kilobits per second.There will be k participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least k of n computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 100) — the number of computers and the number of participants, respectively. In the second line you have a space-separated sequence consisting of n integers: a1, a2, ..., an (16 ≤ ai ≤ 32768); number ai denotes the maximum data transfer speed on the i-th computer.

Print a single integer — the maximum Internet speed value. It is guaranteed that the answer to the problem is always an integer.

NoteIn the first test case the organizers can cut the first computer's speed to 30 kilobits. Then two computers (the first and the third one) will have the same speed of 30 kilobits. They should be used as the participants' computers. This answer is optimal.

#Scott Heinrich - A01273823
use strict;
use warnings;
use 5.010;

my $line1 = <>;
chomp($line1);
my @nk = split(" ",$line1);
my $n = $nk[0]; #computers
my $k = $nk[1]; #participants

my $line2 = <>;
chomp($line2);
my @a = split(" ",$line2); #max data transfer speed on ith computer

my @sorted = sort{ $b <=> $a } @a;

#n is basically useless, use k for index

say $sorted[$k-1];

use strict;
use POSIX;
my ($n,$k)=split(' ',<>);
my @l = split (' ',<>);
@l = sort{$b<=>$a} @l;
print  $l[$k-1];

use strict;
use POSIX;
my ($n,$k)=split(' ',<>);
my @l = split (' ',<>);
@l = sort @l;

print $l[$k-1]


Valera has n counters numbered from 1 to n. Some of them are connected by wires, and each of the counters has a special button.Initially, all the counters contain number 0. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connected to it by a wire, increase by one.Valera and Ignat started having a dispute, the dispute is as follows. Ignat thought of a sequence of n integers a1, a2, ..., an. Valera should choose some set of distinct counters and press buttons on each of them exactly once (on other counters the buttons won't be pressed). If after that there is a counter with the number i, which has value ai, then Valera loses the dispute, otherwise he wins the dispute.Help Valera to determine on which counters he needs to press a button to win the dispute.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105), that denote the number of counters Valera has and the number of pairs of counters connected by wires. Each of the following m lines contains two space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that mean that counters with numbers ui and vi are connected by a wire. It is guaranteed that each pair of connected counters occurs exactly once in the input. The last line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 105), where ai is the value that Ignat choose for the i-th counter.

If Valera can't win the dispute print in the first line -1. Otherwise, print in the first line integer k (0 ≤ k ≤ n). In the second line print k distinct space-separated integers — the numbers of the counters, where Valera should push buttons to win the dispute, in arbitrary order. If there exists multiple answers, you are allowed to print any of them.


You are a coach of a group consisting of $$$n$$$ students. The $$$i$$$-th student has programming skill $$$a_i$$$. All students have distinct programming skills. You want to divide them into teams in such a way that:  No two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $$$1$$$);  the number of teams is the minimum possible. You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of students in the query. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$, all $$$a_i$$$ are distinct), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student.

For each query, print the answer on it — the minimum number of teams you can form if no two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than $$$1$$$)

NoteIn the first query of the example, there are $$$n=4$$$ students with the skills $$$a=[2, 10, 1, 20]$$$. There is only one restriction here: the $$$1$$$-st and the $$$3$$$-th students can't be in the same team (because of $$$|a_1 - a_3|=|2-1|=1$$$). It is possible to divide them into $$$2$$$ teams: for example, students $$$1$$$, $$$2$$$ and $$$4$$$ are in the first team and the student $$$3$$$ in the second team.In the second query of the example, there are $$$n=2$$$ students with the skills $$$a=[3, 6]$$$. It is possible to compose just a single team containing both students.


The only difference between the two versions is that this version asks the maximal possible answer.Homer likes arrays a lot. Today he is painting an array $$$a_1, a_2, \dots, a_n$$$ with two kinds of colors, white and black. A painting assignment for $$$a_1, a_2, \dots, a_n$$$ is described by an array $$$b_1, b_2, \dots, b_n$$$ that $$$b_i$$$ indicates the color of $$$a_i$$$ ($$$0$$$ for white and $$$1$$$ for black).According to a painting assignment $$$b_1, b_2, \dots, b_n$$$, the array $$$a$$$ is split into two new arrays $$$a^{(0)}$$$ and $$$a^{(1)}$$$, where $$$a^{(0)}$$$ is the sub-sequence of all white elements in $$$a$$$ and $$$a^{(1)}$$$ is the sub-sequence of all black elements in $$$a$$$. For example, if $$$a = [1,2,3,4,5,6]$$$ and $$$b = [0,1,0,1,0,0]$$$, then $$$a^{(0)} = [1,3,5,6]$$$ and $$$a^{(1)} = [2,4]$$$.The number of segments in an array $$$c_1, c_2, \dots, c_k$$$, denoted $$$\mathit{seg}(c)$$$, is the number of elements if we merge all adjacent elements with the same value in $$$c$$$. For example, the number of segments in $$$[1,1,2,2,3,3,3,2]$$$ is $$$4$$$, because the array will become $$$[1,2,3,2]$$$ after merging adjacent elements with the same value. Especially, the number of segments in an empty array is $$$0$$$.Homer wants to find a painting assignment $$$b$$$, according to which the number of segments in both $$$a^{(0)}$$$ and $$$a^{(1)}$$$, i.e. $$$\mathit{seg}(a^{(0)})+\mathit{seg}(a^{(1)})$$$, is as large as possible. Find this number.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$).

Output a single integer, indicating the maximal possible total number of segments.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	$_ = join ' ', @_;

	1 while s/
		(\b\d+\b)
		[ ]\b\1\b
		\K
		(?:[ ]\b\1\b)+
		/ ''
		/xeg;

	print 0 + split;
	}


After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you).  You are given an array $$$h_1, h_2, \dots, h_n$$$, where $$$h_i$$$ is the height of the $$$i$$$-th mountain, and $$$k$$$ — the number of boulders you have.You will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is $$$h_i$$$):   if $$$h_i \ge h_{i + 1}$$$, the boulder will roll to the next mountain;  if $$$h_i < h_{i + 1}$$$, the boulder will stop rolling and increase the mountain height by $$$1$$$ ($$$h_i = h_i + 1$$$);  if the boulder reaches the last mountain it will fall to the waste collection system and disappear. You want to find the position of the $$$k$$$-th boulder or determine that it will fall into the waste collection system.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line in each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$; $$$1 \le k \le 10^9$$$) — the number of mountains and the number of boulders. The second line contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 100$$$) — the height of the mountains. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case, print $$$-1$$$ if the $$$k$$$-th boulder will fall into the collection system. Otherwise, print the position of the $$$k$$$-th boulder.

NoteLet's simulate the first case:  The first boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ it rolls to $$$i = 2$$$ and stops there because $$$h_2 < h_3$$$.  The new heights are $$$[4,2,2,3]$$$.  The second boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ the boulder rolls to $$$i = 2$$$; since $$$h_2 \ge h_3$$$ the boulder rolls to $$$i = 3$$$ and stops there because $$$h_3 < h_4$$$.  The new heights are $$$[4,2,3,3]$$$.  The third boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ it rolls to $$$i = 2$$$ and stops there because $$$h_2 < h_3$$$.  The new heights are $$$[4,3,3,3]$$$. The positions where each boulder stopped are the following: $$$[2,3,2]$$$.In the second case, all $$$7$$$ boulders will stop right at the first mountain rising its height from $$$1$$$ to $$$8$$$.The third case is similar to the first one but now you'll throw $$$5$$$ boulders. The first three will roll in the same way as in the first test case. After that, mountain heights will be equal to $$$[4, 3, 3, 3]$$$, that's why the other two boulders will fall into the collection system.In the fourth case, the first and only boulders will fall straight into the collection system.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my $fail = 0;
	my $pos = 0;

	while( $k -- ){
		my $ok = 0;

		for my $i ( 0 .. @_ - 2 ){
			if( $_[ $i ] < $_[ $i + 1 ] ){
				$_[ $i ] ++;
				$pos = $i + 1;
				$ok = 1;
				last;
				}
			}

		$ok or $fail = 1;
		last if $fail;
		}

	print $fail ? -1 : $pos;
	}


The mobile application store has a new game called "Subway Roller".The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column.

Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 ≤ t ≤ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) — the number of sets. Then follows the description of t sets of the input data.  The first line of the description of each set contains two integers n, k (2 ≤ n ≤ 100, 1 ≤ k ≤ 26) — the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.

For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.

NoteIn the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel.Note that in this problem the challenges are restricted to tests that contain only one testset.

$\ = $/;

@regexes = split /^$/m, join '', <DATA>;

while ($t = <>){

	for (1 .. $t){

		($length, undef) = split ' ' , <>;

		@_[ 0 .. 2 ] = map scalar <>, 0 .. 2;  # main array

		$i = -1;
		$i ++, /^s/ and $s = $i for @_;
		@test_lines = ($s);

		s/.// for @_;
		s/$/....../ for @_;

		$fail = 0;

		for $i (0 .. $length / 3){

			$_3x3 = join '', map { s/...//; $& } @_;

			$new_test_lines = '';
			for $k (@test_lines){

				$k == 0 and $_3x3 =~ /$regexes[0]/x and $new_test_lines .= 0;
				$k == 0 and $_3x3 =~ /$regexes[1]/x and $new_test_lines .= 1;

				$k == 1 and $_3x3 =~ /$regexes[2]/x and $new_test_lines .= 0;
				$k == 1 and $_3x3 =~ /$regexes[3]/x and $new_test_lines .= 1;
				$k == 1 and $_3x3 =~ /$regexes[4]/x and $new_test_lines .= 2;

				$k == 2 and $_3x3 =~ /$regexes[5]/x and $new_test_lines .= 1;
				$k == 2 and $_3x3 =~ /$regexes[6]/x and $new_test_lines .= 2;

				}
			$new_test_lines = join '', sort split //, $new_test_lines;
			$new_test_lines =~ y///cs;  # sqeeze
			@test_lines = split //, $new_test_lines;
			@test_lines or $fail = 1 and last;

			}

		print qw(YES NO)[ $fail ];
		}

	}

__DATA__
 \. \. \.
  .  .  .
  .  .  .

 \.  .  .
 \. \. \.
  .  .  .

 \. \. \.
 \.  .  .
  .  .  .

  .  .  .
 \. \. \.
  .  .  .

  .  .  .
 \.  .  .
 \. \. \.

  .  .  .
 \. \. \.
 \.  .  .

  .  .  .
  .  .  .
 \. \. \.


Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:  If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.  Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.

The first line of the input contains integers n, h and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ h ≤ 109) — the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1 ≤ ai ≤ h) — the heights of the pieces.

Print a single integer — the number of seconds required to smash all the potatoes following the process described in the problem statement.

NoteConsider the first sample.   First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.  Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.  Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.  Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.  During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2·5 = 10 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.

$\ = $/;
while(<>){
	($n, $h, $k) = split;
	@_ = split ' ', <>;
	$sec = 0;
	$stack = 0;
	while( @_ or $stack ){
		while( @_ and $stack + $_[0] <= $h ){
			$stack += shift @_;
			}

		int( $stack / $k ) or do { $stack = 0; $sec ++ };
		$sec += int( $stack / $k );
		$stack %= $k;
		}
	print 0 + $sec
}

$\ = $/;
while(<>){
	($n, $h, $k) = split;
	@_ = split ' ', <>;
	$sec = 0;
	$stack = 0;
	while( @_ ){
		while( @_ and $stack + $_[0] <= $h ){
			$stack += shift @_;
			}

		$stack -= $k;
		$stack < 0 and $stack = 0;
		$sec ++;
		}
	print ++ $sec
}


Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.

The first line contains two integers: x (1 ≤ x ≤ 4000) — the round Sereja is taking part in today, and k (0 ≤ k < 4000) — the number of rounds he took part in. Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 num2 num1" (where num2 is the identifier of this Div2 round, num1 is the identifier of the Div1 round). It is guaranteed that num1 - num2 = 1. If Sereja took part in a usual Div2 round, then the corresponding line looks like: "2 num" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.

Print in a single line two integers — the minimum and the maximum number of rounds that Sereja could have missed.

NoteIn the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual Div2 round and the round with identifier 6 will be synchronous with the Div1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual Div2 rounds.


The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:  If x = 1, exit the function.  Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.

A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation.

In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists.

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

sub main () {
	my $n = int <STDIN>;
	print "$n";
	for ( 1 .. $n - 1 ) {
		print " $_";
	}
	print "\n";
	exit 0;
}

main();

__END__


Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers ti (1 ≤ ti ≤ 109), separated by spaces.

Print a single number — the maximum number of not disappointed people in the queue.

NoteValue 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.


Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.

First string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust. Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 105). Each of next n lines contains three integer numbers xi, yi and ri ( - 500 ≤ xi, yi ≤ 500, 0 ≤ ri ≤ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri — radius of i-th peace of sausage.

Output the number of pieces of sausage that lay on the crust.

NoteBelow is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.

#!/usr/bin/perl
$line = <STDIN>;
@radios = split(/\s+/, $line);
$r = $radios[0];
$d = $radios[1];
my $N= <STDIN> - 1;
$dat = $N;
@distan=();
@rad=();
while ($dat >= 0){
	$ent = <STDIN>;
	@datos = split(/\s+/, $ent);
	$Tempd = sqrt(($datos[0] * $datos[0])+($datos[1] * $datos[1]));
	push (@distan, $Tempd);
	push (@rad, $datos[2]);
	$dat = $dat-1;
#	print "@distan\n";
#	print "@rad\n";
}
$c=0;
while ($N >= 0){
#	print $distan[$N]."\n";
#	print $rad[$N]."\n";
	if ((($distan[$N] + $rad[$N]) <= $r) && (($distan[$N]-$rad[$N]) >= $r - $d)) {
		$c = $c + 1;
	}
	$N = $N-1;
}
print $c."\n";

my $numberlines = <STDIN>;
my $numeros;
@arrayradios = split(/\s+/, $numberlines);
$R = $arrayradios[0];
$r = $arrayradios[1];
my $contador=0;
@arraydistancias=();
@radiosp=();
my $N= <STDIN>;
$l = $N-1;
for($i=$l;$l>=0;$l--)
{
	$numeros = <STDIN>;
	@arraynumeros = split(/\s+/, $numeros);
	$disteucl = sqrt(($arraynumeros[0] **2)+($arraynumeros[1] **2));
	push (@arraydistancias, $disteucl);
	push (@radiosp, $arraynumeros[2]);
}
for($i=$N-1;$N>=0;$N--)
{
	if ((($arraydistancias[$N] + $radiosp[$N]) <= $R) && (($arraydistancias[$N]-$radiosp[$N]) >= $R - $r)) {
		$contador = $contador+ 1;
	}
}

print $contador;

#!/usr/bin/perl
$line = <STDIN>;
@radios = split(/\s+/, $line);
$R = $radios[0];
$r = $radios[1];
my $N= <STDIN> - 1;
$dat = $N;
@distan=();
@rad=();
while ($dat >= 0){
	$ent = <STDIN>;
	@datos = split(/\s+/, $ent);
	$Tempd = sqrt(($datos[0] * $datos[0])+($datos[1] * $datos[1]));
	push (@distan, $Tempd);
	push (@rad, $datos[2]);
	$dat = $dat-1;
#	print "@distan\n";
#	print "@rad\n";
}
$c=0;
while ($N >= 0){
#	print $distan[$N]."\n";
#	print $rad[$N]."\n";
	if ((($distan[$N] + $rad[$N]) <= $R) && (($distan[$N]-$rad[$N]) >= $r)) {
		$c = $c + 1;
	}
	$N = $N-1;
}
print $c."\n";

use strict;
use warnings;
use Data::Dumper;

my $m;
my $i;
my $j;
my $valor;
my @m1;
my @m2;
my $contador=0;
my $outside;
my $main;

print "Ingrese R:";
my $R = <STDIN>;
chomp $R;
print "R es '$R'\n";

print "Ingrese r:";
my $r = <STDIN>;
chomp $r;
print "r es '$r'\n";

print "ingrese los puntos:";
$m=<STDIN>;
chop($m);

for($i=0;$i<$m;$i++)
{
   for($j=0;$j<3;$j++)
   {$valor=<STDIN>;
   	chop($valor);
   	$m1[$i][$j]=$valor;
   }
}
for($i=0;$i<$m;$i++)
{
	for($j=0;$j<=3;$j++)
	{
		$m2[$i][$j]=sqrt($m1[$i][$j]**2+$m1[$i][$j+1]**2);
	}
	print "\n";
}

for($i=0;$i<$m;$i++)
{
   for($j=0;$j<1;$j++)
   {
   	if($m2[$i][$j]+$r<=$R)
   	{
   		$contador=$contador+1;
   	}
   }
   print "\n";
}
print $contador;

use strict;
use warnings;
use Data::Dumper;

my $m;
my $i;
my $j;
my $valor;
my @m1;
my @m2;
my $contador=0;
my $outside;
my $main;

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

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

$m=<STDIN>;
chop($m);

for($i=0;$i<$m;$i++)
{
   for($j=0;$j<3;$j++)
   {$valor=<STDIN>;
   	chop($valor);
   	$m1[$i][$j]=$valor;
   }
}
for($i=0;$i<$m;$i++)
{
	for($j=0;$j<=3;$j++)
	{
		$m2[$i][$j]=sqrt($m1[$i][$j]**2+$m1[$i][$j+1]**2);
	}
}
for($i=0;$i<$m;$i++)
{
   for($j=0;$j<1;$j++)
   {
   	if($m2[$i][$j]+$r<=$R)
   	{
   		$contador=$contador+1;
   	}
   }
}
print $contador;


Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $$$s = s_1 s_2 \dots s_{n}$$$ of length $$$n$$$ where each letter is either R, S or P.While initializing, the bot is choosing a starting index $$$pos$$$ ($$$1 \le pos \le n$$$), and then it can play any number of rounds. In the first round, he chooses "Rock", "Scissors" or "Paper" based on the value of $$$s_{pos}$$$:   if $$$s_{pos}$$$ is equal to R the bot chooses "Rock";  if $$$s_{pos}$$$ is equal to S the bot chooses "Scissors";  if $$$s_{pos}$$$ is equal to P the bot chooses "Paper"; In the second round, the bot's choice is based on the value of $$$s_{pos + 1}$$$. In the third round — on $$$s_{pos + 2}$$$ and so on. After $$$s_n$$$ the bot returns to $$$s_1$$$ and continues his game.You plan to play $$$n$$$ rounds and you've already figured out the string $$$s$$$ but still don't know what is the starting index $$$pos$$$. But since the bot's tactic is so boring, you've decided to find $$$n$$$ choices to each round to maximize the average number of wins.In other words, let's suggest your choices are $$$c_1 c_2 \dots c_n$$$ and if the bot starts from index $$$pos$$$ then you'll win in $$$win(pos)$$$ rounds. Find $$$c_1 c_2 \dots c_n$$$ such that $$$\frac{win(1) + win(2) + \dots + win(n)}{n}$$$ is maximum possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first and only line of each test case contains string $$$s = s_1 s_2 \dots s_{n}$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$s_i \in \{\text{R}, \text{S}, \text{P}\}$$$) — the string of the bot. It's guaranteed that the total length of all strings in one test doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print $$$n$$$ choices $$$c_1 c_2 \dots c_n$$$ to maximize the average number of wins. Print them in the same manner as the string $$$s$$$. If there are multiple optimal answers, print any of them.

NoteIn the first test case, the bot (wherever it starts) will always choose "Rock", so we can always choose "Paper". So, in any case, we will win all $$$n = 4$$$ rounds, so the average is also equal to $$$4$$$.In the second test case:   if bot will start from $$$pos = 1$$$, then $$$(s_1, c_1)$$$ is draw, $$$(s_2, c_2)$$$ is draw and $$$(s_3, c_3)$$$ is draw, so $$$win(1) = 0$$$;  if bot will start from $$$pos = 2$$$, then $$$(s_2, c_1)$$$ is win, $$$(s_3, c_2)$$$ is win and $$$(s_1, c_3)$$$ is win, so $$$win(2) = 3$$$;  if bot will start from $$$pos = 3$$$, then $$$(s_3, c_1)$$$ is lose, $$$(s_1, c_2)$$$ is lose and $$$(s_2, c_3)$$$ is lose, so $$$win(3) = 0$$$;  The average is equal to $$$\frac{0 + 3 + 0}{3} = 1$$$ and it can be proven that it's the maximum possible average.A picture from Wikipedia explaining "Rock paper scissors" game:


When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1.A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1.Find the length of the longest almost constant range.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000).

Print a single number — the maximum length of an almost constant range of the given sequence.

NoteIn the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4.In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].


A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $$$s$$$.For some non-empty substring$$$^\dagger$$$ $$$t$$$ of string $$$s$$$ containing $$$x$$$ characters 0 and $$$y$$$ characters 1, define its cost as:  $$$x \cdot y$$$, if $$$x > 0$$$ and $$$y > 0$$$;  $$$x^2$$$, if $$$x > 0$$$ and $$$y = 0$$$;  $$$y^2$$$, if $$$x = 0$$$ and $$$y > 0$$$. Given a binary string $$$s$$$ of length $$$n$$$, find the maximum cost across all its non-empty substrings.$$$^\dagger$$$ A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the maximum cost across all substrings.

NoteIn the first test case, we can take a substring $$$111$$$. It contains $$$3$$$ characters 1 and $$$0$$$ characters 0. So $$$a = 3$$$, $$$b = 0$$$ and its cost is $$$3^2 = 9$$$.In the second test case, we can take the whole string. It contains $$$4$$$ characters 1 and $$$3$$$ characters 0. So $$$a = 4$$$, $$$b = 3$$$ and its cost is $$$4 \cdot 3 = 12$$$.In the third test case, we can can take a substring $$$1111$$$ and its cost is $$$4^2 = 16$$$.In the fourth test case, we can take the whole string and cost is $$$4 \cdot 3 = 12$$$.In the fifth test case, we can take a substring $$$000$$$ and its cost is $$$3 \cdot 3 = 9$$$.In the sixth test case, we can only take the substring $$$0$$$ and its cost is $$$1 \cdot 1 = 1$$$.


Vasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi.Vasya wonders what the numbers ai could be like. Of all the possible options he likes the one sequence with the minimum possible last number an. Help Vasya restore the initial sequence.It is guaranteed that such a sequence always exists.

The first line contains a single integer number n (1 ≤ n ≤ 300). Next n lines contain integer numbers b1, ..., bn  — the required sums of digits. All bi belong to the range 1 ≤ bi ≤ 300.

Print n integer numbers, one per line — the correct option for numbers ai, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to bi.  If there are multiple sequences with least possible number an, print any of them. Print the numbers without leading zeroes.


Let's denote a $$$k$$$-step ladder as the following structure: exactly $$$k + 2$$$ wooden planks, of which  two planks of length at least $$$k+1$$$ — the base of the ladder;  $$$k$$$ planks of length at least $$$1$$$ — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders $$$1$$$ and $$$3$$$ are correct $$$2$$$-step ladders and ladder $$$2$$$ is a correct $$$1$$$-step ladder. On the first picture the lengths of planks are $$$[3, 3]$$$ for the base and $$$[1]$$$ for the step. On the second picture lengths are $$$[3, 3]$$$ for the base and $$$[2]$$$ for the step. On the third picture lengths are $$$[3, 4]$$$ for the base and $$$[2, 3]$$$ for the steps.   You have $$$n$$$ planks. The length of the $$$i$$$-th planks is $$$a_i$$$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.The question is: what is the maximum number $$$k$$$ such that you can choose some subset of the given planks and assemble a $$$k$$$-step ladder using them?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The queries are independent. Each query consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of planks you have. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the lengths of the corresponding planks. It's guaranteed that the total number of planks from all queries doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per query. The $$$i$$$-th integer is the maximum number $$$k$$$, such that you can choose some subset of the planks given in the $$$i$$$-th query and assemble a $$$k$$$-step ladder using them. Print $$$0$$$ if you can't make even $$$1$$$-step ladder from the given set of planks.

NoteExamples for the queries $$$1-3$$$ are shown at the image in the legend section.The Russian meme to express the quality of the ladders:

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my $length = $_[ 1 ];

	my $steps = @_ - 2;

	$steps >= $length and $steps = $length - 1;

	print $steps;
	}


Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.

The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish.

Print a single integer — the minimum number of times Valera will need to wash a plate/bowl.

NoteIn the first sample Valera will wash a bowl only on the third day, so the answer is one.In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once.In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl.

#!/usr/bin/perl
use bignum;

($n, $m, $k) = split(/\s/, <STDIN>);
($mCount, $kCount) = ($m, $k);
@a = split(/\s/, <STDIN>);
$answer = 0;

foreach $item (@a) {
  if( $item == 1 ) {
    if( $mCount > 0 ) {
      $mCount--;
    }
    else {
      $answer++;
    }
  }
  else {
    if( $kCount > 0 ) {
      $kCount--;
    }
    else {
      if( $mCount > 0 ) {
	$mCount--;
      }
      else {
	$answer++;
      }
    }
  }
}

print $answer, "\n";

#!/usr/bin/perl

($n, $m, $k) = split(/\s/, <STDIN>);
($mCount, $kCount) = ($m, $k);
@a = split(/\s/, <STDIN>);
$answer = 0;

foreach $item (@a) {
  if( $item == 1 ) {
    if( $mCount > 0 ) {
      $mCount--;
    }
    else {
      $answer++;
    }
  }
  else {
    if( $kCount > 0 ) {
      $kCount--;
    }
    else {
      if( $mCount > 0 ) {
	$mCount--;
      }
      else {
	$answer++;
      }
    }
  }
}

print $answer, "\n";

#!/usr/bin/perl

$input = <>;
($n, $m, $k)=split(/\s/, $input);
$input = <>;
@a = split(/\s/, $input);
$bowl = $m;
$plate = $k;
$total = @a;

foreach $i (@a){
    if($i == 1){
	if($bowl > 0){
	$bowl--;
	$total--;
    }
	else{
	    break;
	}

    }
    else{
	if($plate > 0 ){
	    $plate--;
	    $total--;
	}
	elsif($bowl > 0){
	    $bowl--;
	    $total--;
	}
	else{
	break;
    }

    }
}
print $total;


Berland shop sells $$$n$$$ kinds of juices. Each juice has its price $$$c_i$$$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of juices. Each of the next $$$n$$$ lines contains an integer $$$c_i$$$ $$$(1 \le c_i \le 100\,000)$$$ and a string $$$s_i$$$ — the price of the $$$i$$$-th juice and the vitamins it contains. String $$$s_i$$$ contains from $$$1$$$ to $$$3$$$ characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string $$$s_i$$$. The order of letters in strings $$$s_i$$$ is arbitrary.

Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.

NoteIn the first example Petya buys the first, the second and the fourth juice. He spends $$$5 + 6 + 4 = 15$$$ and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is $$$16$$$, which isn't optimal.In the second example Petya can't obtain all three vitamins, as no juice contains vitamin "C".