For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $$$n$$$ days of summer. On the $$$i$$$-th day, $$$a_i$$$ millimeters of rain will fall. All values $$$a_i$$$ are distinct.The mayor knows that citizens will watch the weather $$$x$$$ days before the celebration and $$$y$$$ days after. Because of that, he says that a day $$$d$$$ is not-so-rainy if $$$a_d$$$ is smaller than rain amounts at each of $$$x$$$ days before day $$$d$$$ and and each of $$$y$$$ days after day $$$d$$$. In other words, $$$a_d < a_j$$$ should hold for all $$$d - x \le j < d$$$ and $$$d < j \le d + y$$$. Citizens only watch the weather during summer, so we only consider such $$$j$$$ that $$$1 \le j \le n$$$.Help mayor find the earliest not-so-rainy day of summer.

The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le x, y \le 7$$$) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after. The second line contains $$$n$$$ distinct integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ denotes the rain amount on the $$$i$$$-th day.

Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.

NoteIn the first example days $$$3$$$ and $$$8$$$ are not-so-rainy. The $$$3$$$-rd day is earlier.In the second example day $$$3$$$ is not not-so-rainy, because $$$3 + y = 6$$$ and $$$a_3 > a_6$$$. Thus, day $$$8$$$ is the answer. Note that $$$8 + y = 11$$$, but we don't consider day $$$11$$$, because it is not summer.

#! /usr/bin/perl
use strict;
my $row = <STDIN>;
chomp($row);
my @inputs_p = split(' ',$row);
my $l = $inputs_p[0];
my $x = $inputs_p[1];
my $y = $inputs_p[2];
my $data = <STDIN>;
chomp($data);
my @data = split(' ',$data);
sub test {
    my @array = @{$_[0]};
    my $size = scalar @array;
    my $value = $_[1];
    my $flag = 0;
    my $index = 0;
    while($index < $size){
        if($array[$index] < $value ) {$flag = 1; last;}
        $index++;
    }
    return $flag;
}
sub max {
    return $_[1] > $_[0] ?  $_[1] : $_[0];
}
sub min {
    return $_[1] > $_[0] ?  $_[0] : $_[1];
}
my $index = 0;
OUTER:while(  $index < $l-1 ){

    if ($x == 0 && $y == 0 ){ last OUTER;}
    elsif($x == 0){

        while($index < $l-$y-1){
            my @split_data_pos= @data[$index+1..$index+$y];
        if(  test(\@split_data_pos,$data[$index]) == 0 ) { last OUTER;};
            $index++;
        }
        while(($index >= $l-1-$y) && ($index < $l)){
            my @split_data_pos= @data[$index+1..$l-1];
            if(  test(\@split_data_pos,$data[$index]) == 0 ) { last OUTER;};
            $index++;

        }
    }
    elsif($y == 0){

        while($index < $x){
        my $pre_ind = max($index-1,0);
        my @split_data_pre= @data[0..$pre_ind];
            if(  test(\@split_data_pre,$data[$index]) == 0 ) { last OUTER;};
            $index++;
        }
        while(($index >= $x) && ($index < $l)){
            my @split_data_pos= @data[$index-$x..$index-1];
            if(  test(\@split_data_pos,$data[$index]) == 0 ) { last OUTER;};
            $index++;

        }
    }
    else {

        while( ($index < $x ) && ($index+$y < $l))
            {

            my $pre_ind = max($index-1,0);
            my @split_data_pre= @data[0..$pre_ind];
            my @split_data_pos= @data[$index+1..$index+$y];
            if($index == 0){
                if(test(\@split_data_pos,$data[$index]) == 0 ) {last OUTER;}
            }

            if( ( test(\@split_data_pre,$data[$index]) == 0 ) && ( test(\@split_data_pos,$data[$index]) == 0 )) { last OUTER;}
            $index++;

            }

        while( ($index < $l-1-$y) && ($index >= $x)  ){

            my @split_data_pre= @data[$index-$x..$index-1];
            my @split_data_pos= @data[$index+1..$index+$y];
            if( ( test(\@split_data_pre,$data[$index]) == 0 ) && ( test(\@split_data_pos,$data[$index]) == 0 )) {last OUTER;}
            $index++;

            }
        while( ($index >= $l-1-$y) && ($index < $l-1) ){

            my @split_data_pre= @data[$index-$x..$index-1];
            my @split_data_pos= @data[$index+1..$l-1];
            if((test(\@split_data_pre,$data[$index]) == 0 )&& (test(\@split_data_pos,$data[$index]) == 0) ) {last OUTER;}
            if($index == $l-1) {

                if(test(\@split_data_pre,$data[$index]) == 0)  {last OUTER;}
            }
            $index++;

            }
    }
}
print($index+1);

#! /usr/bin/perl
use strict;
my $row = <STDIN>;
chomp($row);
my @inputs_p = split(' ',$row);
my $l = $inputs_p[0];
my $x = $inputs_p[1];
my $y = $inputs_p[2];
my $data = <STDIN>;
chomp($data);
my @data = split(' ',$data);
sub test {
    my @array = @{$_[0]};
    my $size = scalar @array;
    my $value = $_[1];
    my $flag = 0;
    my $index = 0;
    while($index < $size){
        if($array[$index] < $value ) {$flag = 1; last;}
        $index++;
    }
    return $flag;
}
my $index = $x;
my $flag = 0;
while( $flag != 1 && $index < $l){
    while( $index < $l-1-$y && $flag != 1){
        my @split_data_pre= @data[$index-$x..$index-1];
        my @split_data_pos= @data[$index+1..$index+$y];
    if( ( test(\@split_data_pre,$data[$index]) == 0 ) && ( test(\@split_data_pos,$data[$index]) == 0 )) {$flag = 1;}
    $index++;
    }
    while( $index >= $l-1-$y && $index < $l && $flag != 1)
    {
        my @split_data_pre= @data[$index-$x..$index-1];
        my @split_data_pos= @data[$index+1..$l-1];
        if((test(\@split_data_pre,$data[$index]) == 0 )&& (test(\@split_data_pos,$data[$index]) == 0) ) {$flag = 1;}
        $index++;

    }
}
print($index);

#! /usr/bin/perl
use strict;
my $row = <STDIN>;
chomp($row);
my @inputs_p = split(' ',$row);
my $l = $inputs_p[0];
my $x = $inputs_p[1];
my $y = $inputs_p[2];
my $data = <STDIN>;
chomp($data);
my @data = split(' ',$data);
sub test {
    my @array = @{$_[0]};
    my $size = scalar @array;
    my $value = $_[1];
    my $flag = 0;
    my $index = 0;
    while($index < $size){
        if($array[$index] < $value ) {$flag = 1; last;}
        $index++;
    }
    return $flag;
}
sub max {
    return $_[1] > $_[0] ?  $_[1] : $_[0];
}
sub min {
    return $_[1] > $_[0] ?  $_[0] : $_[1];
}
my $index = 0;

OUTER:while(  $index < $l-1 ){
    if ($x == 0 && $y == 0 ){ last OUTER;}
    elsif($x == 0){
        while($index < $l-$y-1){
            my @split_data_pos= @data[$index+1..$index+$y];
        if(  test(\@split_data_pos,$data[$index]) == 0 ) { last OUTER;};
            $index++;
        }
        while(($index >= $l-1-$y) && ($index < $l)){
            my @split_data_pos= @data[$index+1..$l-1];
            if(  test(\@split_data_pos,$data[$index]) == 0 ) { last OUTER;};
            $index++;

        }
    }
    elsif($y == 0){
        while($index < $x){
        my $pre_ind = max($index-1,0);
        my @split_data_pre= @data[0..$pre_ind];
            if(  test(\@split_data_pre,$data[$index]) == 0 ) { last OUTER;};
            $index++;
        }
        while(($index >= $x) && ($index < $l)){
            my @split_data_pos= @data[$index-$x..$index-1];
            if(  test(\@split_data_pos,$data[$index]) == 0 ) { last OUTER;};
            $index++;

        }
    }
    else {
        while( ($index < $x ) )
            {
            my $pre_ind = max($index-1,0);
            my @split_data_pre= @data[0..$pre_ind];
            my @split_data_pos= @data[$index+1..$index+$y];

            if( ( test(\@split_data_pre,$data[$index]) == 0 ) && ( test(\@split_data_pos,$data[$index]) == 0 )) { last OUTER;}
            $index++;

            }

        while( ($index < $l-1-$y) && ($index >= $x)  ){
            my @split_data_pre= @data[$index-$x..$index-1];
            my @split_data_pos= @data[$index+1..$index+$y];
            if( ( test(\@split_data_pre,$data[$index]) == 0 ) && ( test(\@split_data_pos,$data[$index]) == 0 )) { last OUTER;}
            $index++;

            }
        while( ($index >= $l-1-$y) && ($index < $l) ){
            my @split_data_pre= @data[$index-$x..$index-1];
            my @split_data_pos= @data[$index+1..$l-1];
            if((test(\@split_data_pre,$data[$index]) == 0 )&& (test(\@split_data_pos,$data[$index]) == 0) ) {last OUTER;}
            $index++;

            }
    }
}
print(min($index+1,$l));

#! /usr/bin/perl
use strict;
my $row = <STDIN>;
chomp($row);
my @inputs_p = split(' ',$row);
my $l = $inputs_p[0];
my $x = $inputs_p[1];
my $y = $inputs_p[2];
my $data = <STDIN>;
chomp($data);
my @data = split(' ',$data);
sub test {
    my @array = @{$_[0]};
    my $size = scalar @array;
    my $value = $_[1];
    my $flag = 0;
    my $index = 0;
    while($index < $size){
        if($array[$index] < $value ) {$flag = 1; last;}
        $index++;
    }
    return $flag;
}
sub max {
    return $_[1] > $_[0] ?  $_[1] : $_[0];
}
sub min {
    return $_[1] > $_[0] ?  $_[0] : $_[1];
}
my $index = max($x-1,0);

OUTER:while(  $index < $l-1 ){
    while( ($index <= $x-1 ) )
    {
        my $pre_ind = max($index-1,0);
        my $pos_ind = min($index+$y,$index+1);
        my @split_data_pre= @data[0..$pre_ind];
        my @split_data_pos= @data[$index+1..$index+$y];
    if( ( test(\@split_data_pre,$data[$index]) == 0 ) && ( test(\@split_data_pos,$data[$index]) == 0 )) { last OUTER;}
   $index++;

    }

    while( ($index < $l-1-$y) && ($index > $x-1)  ){
       my $pre_ind = max($index-1,$index-$x);
        my $pos_ind = min($index+$y,$index+1);
        my @split_data_pre= @data[$index-$x..$pre_ind];
        my @split_data_pos= @data[$index+1..$index+$y];
    if( ( test(\@split_data_pre,$data[$index]) == 0 ) && ( test(\@split_data_pos,$data[$index]) == 0 )) { last OUTER;}
   $index++;

    }
    while( ($index >= $l-1-$y) && ($index < $l) )
    {
        my $pre_ind = max($index-1,$index-$x);
        my @split_data_pre= @data[$index-$x..$pre_ind];
        my @split_data_pos= @data[$index+1..$l-1];
        if((test(\@split_data_pre,$data[$index]) == 0 )&& (test(\@split_data_pos,$data[$index]) == 0) ) {last OUTER;}
        $index++;

    }
}
print($index+1);


You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my $max = 0;
	my @acc;
	my @ans;

	for my $i ( 0 .. @_ - 1 ){

		if( $_[ $i ] > $max ){
			unshift @ans, @acc;
			@acc = ();
			$max = $_[ $i ];
			}
		else{
			;
			}

		push @acc, $_[ $i ];
		}

	print "@ans";
	}


Allen and Bessie are playing a simple number game. They both know a function $$$f: \{0, 1\}^n \to \mathbb{R}$$$, i. e. the function takes $$$n$$$ binary arguments and returns a real value. At the start of the game, the variables $$$x_1, x_2, \dots, x_n$$$ are all set to $$$-1$$$. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an $$$i$$$ such that $$$x_i = -1$$$ and either setting $$$x_i \to 0$$$ or $$$x_i \to 1$$$.After $$$n$$$ rounds all variables are set, and the game value resolves to $$$f(x_1, x_2, \dots, x_n)$$$. Allen wants to maximize the game value, and Bessie wants to minimize it.Your goal is to help Allen and Bessie find the expected game value! They will play $$$r+1$$$ times though, so between each game, exactly one value of $$$f$$$ changes. In other words, between rounds $$$i$$$ and $$$i+1$$$ for $$$1 \le i \le r$$$, $$$f(z_1, \dots, z_n) \to g_i$$$ for some $$$(z_1, \dots, z_n) \in \{0, 1\}^n$$$. You are to find the expected game value in the beginning and after each change.

The first line contains two integers $$$n$$$ and $$$r$$$ ($$$1 \le n \le 18$$$, $$$0 \le r \le 2^{18}$$$). The next line contains $$$2^n$$$ integers $$$c_0, c_1, \dots, c_{2^n-1}$$$ ($$$0 \le c_i \le 10^9$$$), denoting the initial values of $$$f$$$. More specifically, $$$f(x_0, x_1, \dots, x_{n-1}) = c_x$$$, if $$$x = \overline{x_{n-1} \ldots x_0}$$$ in binary. Each of the next $$$r$$$ lines contains two integers $$$z$$$ and $$$g$$$ ($$$0 \le z \le 2^n - 1$$$, $$$0 \le g \le 10^9$$$). If $$$z = \overline{z_{n-1} \dots z_0}$$$ in binary, then this means to set $$$f(z_0, \dots, z_{n-1}) \to g$$$.

Print $$$r+1$$$ lines, the $$$i$$$-th of which denotes the value of the game $$$f$$$ during the $$$i$$$-th round. Your answer must have absolute or relative error within $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

NoteConsider the second test case. If Allen goes first, he will set $$$x_1 \to 1$$$, so the final value will be $$$3$$$. If Bessie goes first, then she will set $$$x_1 \to 0$$$ so the final value will be $$$2$$$. Thus the answer is $$$2.5$$$.In the third test case, the game value will always be $$$1$$$ regardless of Allen and Bessie's play.


In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.Farmer John wants to book a set of k + 1 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j - i|. Help Farmer John protect his cows by calculating this minimum possible distance.

The first line of the input contains two integers n and k (1 ≤ k < n ≤ 100 000) — the number of rooms in the hotel and the number of cows travelling with Farmer John. The second line contains a string of length n describing the rooms. The i-th character of the string will be '0' if the i-th room is free, and '1' if the i-th room is occupied. It is guaranteed that at least k + 1 characters of this string are '0', so there exists at least one possible choice of k + 1 rooms for Farmer John and his cows to stay in.

Print the minimum possible distance between Farmer John's room and his farthest cow.

NoteIn the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms.In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2.In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1.

use strict;

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

sub min ($$) {
  return ($_[0] < $_[1]) ? $_[0] : $_[1];
}
sub max ($$) {
  return ($_[0] > $_[1]) ? $_[0] : $_[1];
}

sub getNextFreeRoom ($) {
  my $i = $_[0] + 1;

  while (($i < $n) && $m[$i]) {
    $i++;
  }

  return $i;
}

sub findFirstHit {
  my ($x, $y);

  $y = $x = &getNextFreeRoom(-1);
  for (my $i = 0; $i < $k; $i++) {
    $y = &getNextFreeRoom ($y)
  }

  return ($x, $y);
}

sub adjustOwner ($$$$) {
  my ($x, $y, $z, $res) = @_;

  my $nextZ = &getNextFreeRoom($z);

  while (max($z - $x, $y - $z) > max($nextZ - $x, $y - $nextZ)) {
    $z = $nextZ;
    $nextZ = &getNextFreeRoom($z);
  }

  $res = min ($res, max ($z - $x, $y - $z));
  return ($z, $res);
}

my ($x, $y) = &findFirstHit;
my ($z, $res) = &adjustOwner ($x, $y, $x, 10 ** 9);

while ($y < $n) {
  ($z, $res) = &adjustOwner ($x, $y, $z, $res);
  $x = &getNextFreeRoom ($x);
  $y = &getNextFreeRoom ($y);
}

print "$res";

use strict;

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

sub min ($$) {
  return ($_[0] < $_[1]) ? $_[0] : $_[1];
}
sub max ($$) {
  return ($_[0] > $_[1]) ? $_[0] : $_[1];
}

sub getNextFreeRoom ($) {
  my $i = $_[0] + 1;

  while (($i < $n) && $m[$i]) {
    $i++;
  }

  return $i;
}

sub findFirstHit {
  my ($x, $y);

  $y = $x = &getNextFreeRoom(-1);
  for (my $i = 0; $i < $k; $i++) {
    $y = &getNextFreeRoom ($y)
  }

  return ($x, $y);
}

sub adjustOwner ($$$$) {
  my ($x, $y, $z, $res) = @_;

  my $nextZ = &getNextFreeRoom($z);

  while (max($z - $x, $y - $z) > max($nextZ - $x, $y - $nextZ)) {
    $z = $nextZ;
  }

  $res = min ($res, max ($z - $x, $y - $z));
  return ($z, $res);
}

my ($x, $y) = &findFirstHit;
my ($z, $res) = &adjustOwner ($x, $y, $x, 10 ** 9);

while ($y < $n) {
  ($z, $res) = &adjustOwner ($x, $y, $z, $res);
  $x = &getNextFreeRoom ($x);
  $y = &getNextFreeRoom ($y);
}

print "$res";


Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!Your task is to write a program which calculates two things:  The maximum beauty difference of flowers that Pashmak can give to Parmida.  The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.

The first line of the input contains n (2 ≤ n ≤ 2·105). In the next line there are n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ 109).

The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.

NoteIn the third sample the maximum beauty difference is 2 and there are 4 ways to do this:  choosing the first and the second flowers;  choosing the first and the fifth flowers;  choosing the fourth and the second flowers;  choosing the fourth and the fifth flowers.

#!/perl -w

use strict ;

chomp( my $n = <STDIN> );

my @beauty = split /\s+/ , <STDIN>;

my $maxbeauti = 0 ;
my $minbeauti = 10E9 + 1;
my $maxcount  = 0 ;
my $mincount  = 0 ;

foreach( @beauty ){
    if ( $_ >= $maxbeauti ){
        $maxbeauti = $_ ;
    }
    if ( $_ <= $minbeauti ){
        $minbeauti = $_ ;
    }
}
if( $minbeauti != $maxbeauti ){
    foreach( @beauty ){
        if ( $_ == $maxbeauti ){
            $maxcount ++ ;
        }
        if ( $_ == $minbeauti ){
            $mincount ++ ;
        }
    }
    print $maxbeauti - $minbeauti , " " , $mincount * $maxcount ;
}else{
    print "0" , " " , $n*($n - 1)/2 ;
}

use 5.016;
use strict;
use warnings;

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

my $count_min = 0;
for my $x (@x) {
  if ($x > $min) {
    last;
  } else {
    $count_min++;
  }
}

my $count_max = 0;
for my $x (reverse @x) {
  if ($x < $max) {
    last;
  } else {
    $count_max++;
  }
}

my $ways = $max_diff == 0 ? $count_min * ($count_min - 1) / 2
                          : $count_min * $count_max;

say "$max_diff $ways";

#!/perl -w

use strict ;

chomp( my $n = <STDIN> );

my @beauty = split /\s+/ , <STDIN>;

my $maxbeauti = 0 ;
my $minbeauti = 10E9 + 1;
my $maxcount  = 0 ;
my $mincount  = 0 ;

foreach( @beauty ){
    if ( $_ >= $maxbeauti ){
        $maxbeauti = $_ ;
    }
    if ( $_ <= $minbeauti ){
        $minbeauti = $_ ;
    }
}

foreach( @beauty ){
    if ( $_ == $maxbeauti ){
        $maxcount ++ ;
    }
    if ( $_ == $minbeauti ){
        $mincount ++ ;
    }
}

print $maxbeauti-$minbeauti , " " , $mincount * $maxcount ;

# Perl
chomp($n = <>);
@a = sort split / /, <>;
foreach (@a) {
	$a++ if $_==$a[0] or last;
}
foreach (reverse @a) {
	$b++ if $_==$a[-1] or last;
}
print $a[-1]-$a[0], ' ', $a*$b, "\n";

use 5.016;
use strict;
use warnings;

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

my $count_min = 0;
for my $x (@x) {
  if ($x > $min) {
    last;
  } else {
    $count_min++;
  }
}

my $count_max = 0;
for my $x (reverse @x) {
  if ($x < $max) {
    last;
  } else {
    $count_max++;
  }
}

my $ways = $count_min * $count_max;

say "$max_diff $ways";

<>;
@_=split/ /,<>;
$_>$max and $max=$_ for @_;
$min=$max;
$_<$max and $max=$_ for @_;
$min==$_ and $MIN++ for @_;
$max==$_ and $MAX++ for @_;
$max-$min and $f=$MIN*$MAX;
print $max-$min, " ", 0+$f;


Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.

The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.

If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes). Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct. If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair. Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.


A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).  Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of dice in the tower. The second line contains an integer x (1 ≤ x ≤ 6) — the number Bob sees at the top of the tower. Next n lines contain two space-separated integers each: the i-th line contains numbers ai, bi (1 ≤ ai, bi ≤ 6; ai ≠ bi) — the numbers Bob sees on the two sidelong faces of the i-th dice in the tower. Consider the dice in the tower indexed from top to bottom from 1 to n. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input.

Print "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes).

chomp($totalDice = <STDIN>);
chomp($topFace = <STDIN>);
$bottomFace = 7 - $topFace;
@diceFaces = ( 1, 2, 3, 4, 5, 6);
@topBottomFaces = ( $topFace, $bottomFace);
my %diceFaces=map{$_ =>1} @diceFaces;
my %topBottomFaces=map{$_=>1} @topBottomFaces;
my @remFaces=grep(!defined $topBottomFaces{$_}, @diceFaces);
while (<STDIN>) { # assigns each line in turn to $_
    #print "Just read in this line: $_";
    $currentLine = $_;
    if($currentLine =~ /([1-6]) ([1-6])/) {
        $leftFace = $1;
        $rightFace = $2;
        if ( grep { $_ eq $leftFace } @remFaces ) {
        }
        else {
            print "NO";
            exit 0;
        }
        if ( grep { $_ eq $rightFace } @remFaces ) {
        }
        else {
            print "NO";
            exit 0;
        }
    }
    $totalDice--;
}
if ( $totalDice == 0) {
    print "YES";
}
else {
    print "NO";
}

#!/usr/bin/perl

use strict;
use warnings;

my $n=<>;
my $up=<>;
my @current=split(' ',<>);
my $last=7-$up;
my $can=1;
foreach my $count(1..$n-1){
	@current=split(' ',<>);
	if($last==$current[0] || $last==7-$current[0] || $last==$current[1] || $last==7-$current[1]){
		$can=0;
	}
}
if($can==1){
	print"YES\n";
}else{
	print"NO\n";
}

chomp($totalDice = <STDIN>);
$topFace = <STDIN>;
$bottomFace = 7 - $topFace;
@diceFaces = ( 1, 2, 3, 4, 5, 6);
@topBottomFaces = ( $topFace, $bottomFace);
@diff{ @diceFaces } = { @diceFaces };
delete @diff{ @topBottomFaces };
@remFaces = (keys %diff);
while (<STDIN>) { # assigns each line in turn to $_
	#print "Just read in this line: $_";
	$currentLine = $_;
	if($currentLine =~ /([1-6]) ([1-6])/) {
		$leftFace = $1;
		$rightFace = $2;
		if ( grep { $_ eq $leftFace } @remFaces ) {
		}
		else {
			print "NO";
			exit 0;
		}
		if ( grep { $_ eq $leftFace } @remFaces ) {
		}
		else {
			print "NO";
			exit 0;
		}
	}
	$totalDice--;
}
if ( $totalDice == 0) {
	print "YES";
}
else {
	print "NO";
}

chomp($totalDice = <STDIN>);
$topFace = <STDIN>;
$bottomFace = 7 - $topFace;
@diceFaces = ( 1, 2, 3, 4, 5, 6);
@topBottomFaces = ( $topFace, $bottomFace);
@diff{ @diceFaces } = { @diceFaces };
delete @diff{ @topBottomFaces };
@remFaces = (keys %diff);
while (<STDIN>) { # assigns each line in turn to $_
    $currentLine = $_;
    if($currentLine =~ /([1-6]) ([1-6])/) {
        $leftFace = $1;
        $rightFace = $2;
        if ( grep { $_ eq $leftFace } @remFaces ) {
        }
        else {
            print "NO";
            exit 0;
        }
        if ( grep { $_ eq $rightFace } @remFaces ) {
        }
        else {
            print "NO";
            exit 0;
        }
    }
    $totalDice--;
}
if ( $totalDice == 0) {
    print "YES";
}
else {
    print "NO";
}


Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly ai calories on touching the i-th strip.You've got a string s, describing the process of the game and numbers a1, a2, a3, a4. Calculate how many calories Jury needs to destroy all the squares?

The first line contains four space-separated integers a1, a2, a3, a4 (0 ≤ a1, a2, a3, a4 ≤ 104). The second line contains string s (1 ≤ |s| ≤ 105), where the і-th character of the string equals "1", if on the i-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip.

Print a single integer — the total number of calories that Jury wastes.

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

@a = (0, split / /, <>);
chomp($line = <>);
$tb{int($_)}++ foreach (split //, $line);
$ans+=$a[$_] * $tb{$_} foreach(keys %tb);
say $ans;

#!/usr/bin/perl

my @cal = split / /, <>;
my $s = <>;
chomp $s;

print eval join '+', map { $cal[$_ - 1] } (split //, $s);

use strict;
#open STDIN, '<input.txt';
#open STDOUT, '>output.txt';
my @a = split(' ', <>);
my @b = split(//, <>);
my $ans = 0;
sub kek{
  my ($a, $b) = @_;
for(my $i = 0; $i < $#b; $i++){
  print $a[$b[$i] - 1], ' ';
  $ans += $a[$b[$i] - 1];
}
print $ans;
}
kek(\@a, \@b);


Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:  either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before);  or the girl in the dancing pair must dance for the first time. Help Fox Ciel to make a schedule that they can dance as many songs as possible.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of boys and girls in the dancing room.

In the first line print k — the number of songs during which they can dance. Then in the following k lines, print the indexes of boys and girls dancing during songs chronologically. You can assume that the boys are indexed from 1 to n, and the girls are indexed from 1 to m.

NoteIn test case 1, there are 2 boys and 1 girl. We can have 2 dances: the 1st boy and 1st girl (during the first song), the 2nd boy and 1st girl (during the second song).And in test case 2, we have 2 boys with 2 girls, the answer is 3.


A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square.For a given string $$$s$$$ determine if it is square.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) —the number of test cases. This is followed by $$$t$$$ lines, each containing a description of one test case. The given strings consist only of lowercase Latin letters and have lengths between $$$1$$$ and $$$100$$$ inclusive.

For each test case, output on a separate line:   YES if the string in the corresponding test case is square,  NO otherwise.  You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

10
a
aa
aaa
aaaa
abab
abcabc
abacaba
xxyy
xyyx
xyxy

#!/usr/bin/perl

my ($tcase) = split(/\s+/o,<STDIN>);

while( $tcase -- > 0 ){
  ( my $s = <STDIN> ) =~ s/[\x00-\x20]+$//ios;
  if( length($s) % 2 == 1 ){
    print "No\n"; next;
  }
  if( substr($s,0,length($s)/2) eq substr($s,length($s)/2,length($s)/2) ){
    print "Yes\n";
  } else {
    print "No\n";
  }
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	print m/^(.+)\1$/ ? "YES" : "NO";

	}

#!/usr/bin/perl

my ($tcase) = split(/\s+/o,<STDIN>);

while( $tcase -- > 0 ){
  ( my $s = <STDIN> ) =~ s/[\x00-\x20]+$//ios;
  if( length($s) % 2 == 1 ){
    print "No\n"; next;
  }
  print ( substr($s,0,length($s)/2) . "\n" );
}

#!/usr/bin/perl

my ($tcase) = split(/\s+/o,<STDIN>);

while( $tcase -- > 0 ){
  ( my $s = <STDIN> ) =~ s/[\x00-\x20]+$//ios;
  my %x = ();
  for(my $i=0;$i<length($s);$i++){
    for(my $j=$i;$j<length($s);$j++){
      my $ss = substr($s,$i,$j-$i+1);
      $x{$ss}++;
    }
  }
  my $res = 'No';
	foreach my $k (keys %x){
    $res = 'Yes' if $x{$k}-0 > 1;
	}
  print "$res\n";
}


After lessons Nastya decided to read a book. The book contains $$$n$$$ chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number $$$k$$$ as the first page which was not read (i.e. she read all pages from the $$$1$$$-st to the $$$(k-1)$$$-th).The next day Nastya's friend Igor came and asked her, how many chapters remain to be read by Nastya? Nastya is too busy now, so she asks you to compute the number of chapters she has not completely read yet (i.e. the number of chapters she has not started to read or has finished reading somewhere in the middle).

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of chapters in the book. There are $$$n$$$ lines then. The $$$i$$$-th of these lines contains two integers $$$l_i$$$, $$$r_i$$$ separated by space ($$$l_1 = 1$$$, $$$l_i \leq r_i$$$) — numbers of the first and the last pages of the $$$i$$$-th chapter. It's guaranteed that $$$l_{i+1} = r_i + 1$$$ for all $$$1 \leq i \leq n-1$$$, and also that every chapter contains at most $$$100$$$ pages. The $$$(n+2)$$$-th line contains a single integer $$$k$$$ ($$$1 \leq k \leq r_n$$$) — the index of the marked page.

Print a single integer — the number of chapters which has not been completely read so far.

NoteIn the first example the book contains $$$11$$$ pages and $$$3$$$ chapters — $$$[1;3]$$$, $$$[4;7]$$$ and $$$[8;11]$$$. Nastya marked the $$$2$$$-nd page, so she finished in the middle of the $$$1$$$-st chapter. So, all chapters has not been read so far, so the answer is $$$3$$$.The book in the second example contains $$$12$$$ pages and $$$3$$$ chapters too, but Nastya finished reading in the middle of the $$$2$$$-nd chapter, so that the answer is $$$2$$$.

#!/usr/bin/perl -wl
use strict;

while(<>) {
    @_ = reverse map { my @k = split ' ', <>; $k[1] } 1..$_;
    chomp(my $k = <>);
    1 while scalar(@_) > 0 and eval $k.'-'.pop @_ > 0;
    print scalar(@_) + 1;
}

#!/usr/bin/perl -wl

use strict;

while( <> ){
    $_ = join ',', map { '-' x ( 1 + eval join '-', reverse split ' ', <> ) } 1 .. $_;
    s/-*\K-/;/g;
    y/,//d;
    chomp( my $k = <> );
    substr $_, 0, $k - 1, '';
    print scalar( () = /;/g );
    }


You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.You have to determine the length of the longest balanced substring of s.

The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.

If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.

NoteIn the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.In the second example it's impossible to find a non-empty balanced substring.


At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.

Print a single integer — the number of places in queue she can move forward.

NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is   change places for pupils with numbers $$$1$$$ and $$$3$$$.  change places for pupils with numbers $$$3$$$ and $$$2$$$.  change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.


The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law:  For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;  For each station i there exists exactly one station j such that pj = i. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!

The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.

Print one number — the maximum possible value of convenience.

NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).In the second example the mayor can change p2 to 4 and p3 to 5.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my %h;
	my $i = 0;
	map { $h{ ++ $i } = $_ } @_;
	my @c;

	for my $key ( 1 .. @_ ){
		next if not exists $h{ $key };
		my $new = $key;
		my $c = 0;
		while( exists $h{ $new } ){
			$c ++;
			my $old = $new;
			$new = $h{ $old };
			delete $h{ $old };
			}
		push @c, $c;
		}

	@c = ( sort { $a <=> $b } @c );

	if( @c >= 2 ){
		push @c, ( pop @c ) + ( pop @c );
		}

	my $sum = 0;
	map { $sum += $_ ** 2 } @c;

	print $sum;
	}


Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.

The first line of the input contains two integers n and t (1 ≤ n ≤ 200 000, 1 ≤ t ≤ 109) — the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.

Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.

NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all.


There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

The first line contains single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of  keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$ — the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.

Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist.

#!/usr/bin/perl

use warnings;
use strict;

use Data::Dumper;

my $keyboards = <>;
my $numbers = <>;

my @splitted = split(" ", $numbers);

my $min;
my $max;
foreach my $one (@splitted) {
	if (! defined $min || $min > $one) {
	      $min = $one;
	}
	if (! defined $max || $one > $max) {
		$max = $one;
	}
}

my $result = $max - $min + 1 - $keyboards;

print "$result\n";

use v5.10;

chomp($n = <STDIN>);
chomp($piano = <STDIN>);
@pianoList = split / /, $piano;
@pianoList = sort {$a<=>$b} @pianoList;
say $pianoList[$#pianoList] - $pianoList[0] - $n + 1;


Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.For simplicity, let us assume that Volodya's text can be represented as a single string.

Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.

Print exactly one number — the number of powerful substrings of the given string. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal".

#!/usr/bin/perl
chomp ($_ = <>);
$i = 0;
$res = 0;
for ($i = 0; $i < length ($_) - 4; $i++) {
    $block = substr $_, $i, 5;

    if ($block eq "heavy") {
        $h++;
        $i += 4;
    } elsif ($block eq "metal") {
        $res += $h;
        $i += 4;
    }
}

print $res;

#!/usr/bin/perl

while (<>) {
    chomp;
    $i=$j=0;
    s/heavy/H/g;
    s/metal/M/g;
    s/[a-z]//g;
    @m=split//;
    foreach (@m){
        /H/ and $i++;
        /M/ and $j+=$i;
        }
    print "$j\n";
}

#!/usr/bin/perl -pi
for ($i = 0; $i < length ($_); $i++) {
    $block = substr $_, $i, 5;

    if ($block eq "heavy") {
        $h++;
        $i += 4;
    } elsif ($block eq "metal") {
        $res += $h;
        $i += 4;
    }
}
$_ = $res;

#!/usr/bin/perl

while (<>) {
    chomp;
    s/heavy/H/g;
    s/metal/M/g;
    s/[a-z]//g;
    @m=split//;
    foreach (@m){
        /H/ and $i++;
        /M/ and $j+=$i;
        }
    print "$j\n";
    $i=$j=0;
}


Boboniu likes bit operations. He wants to play a game with you.Boboniu gives you two sequences of non-negative integers $$$a_1,a_2,\ldots,a_n$$$ and $$$b_1,b_2,\ldots,b_m$$$.For each $$$i$$$ ($$$1\le i\le n$$$), you're asked to choose a $$$j$$$ ($$$1\le j\le m$$$) and let $$$c_i=a_i\& b_j$$$, where $$$\&$$$ denotes the bitwise AND operation. Note that you can pick the same $$$j$$$ for different $$$i$$$'s.Find the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$, where $$$|$$$ denotes the bitwise OR operation.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 200$$$). The next line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i < 2^9$$$). The next line contains $$$m$$$ integers $$$b_1,b_2,\ldots,b_m$$$ ($$$0\le b_i < 2^9$$$).

Print one integer: the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$.


You are given two arrays $$$a$$$ and $$$b$$$ of $$$n$$$ positive integers each. You can apply the following operation to them any number of times:  Select an index $$$i$$$ ($$$1\leq i\leq n$$$) and swap $$$a_i$$$ with $$$b_i$$$ (i. e. $$$a_i$$$ becomes $$$b_i$$$ and vice versa). Find the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times (possibly zero).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\le n\le 100$$$) — the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 10\,000$$$) where $$$b_i$$$ is the $$$i$$$-th element of the array $$$b$$$.

For each test case, print a single integer, the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times.

NoteIn the first test, you can apply the operations at indices $$$2$$$ and $$$6$$$, then $$$a = [1, 4, 6, 5, 1, 5]$$$ and $$$b = [3, 2, 3, 2, 2, 2]$$$, $$$\max(1, 4, 6, 5, 1, 5) \cdot \max(3, 2, 3, 2, 2, 2) = 6 \cdot 3 = 18$$$.In the second test, no matter how you apply the operations, $$$a = [3, 3, 3]$$$ and $$$b = [3, 3, 3]$$$ will always hold, so the answer is $$$\max(3, 3, 3) \cdot \max(3, 3, 3) = 3 \cdot 3 = 9$$$.In the third test, you can apply the operation at index $$$1$$$, then $$$a = [2, 2]$$$, $$$b = [1, 1]$$$, so the answer is $$$\max(2, 2) \cdot \max(1, 1) = 2 \cdot 1 = 2$$$.


Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.

The single line contains two integers, n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000).

Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value. If there are multiple suitable tables, you are allowed to print any of them.

NoteIn the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

$_=$'.(" 0"x($`-1));

for $i(1..$`){
s/\n//;
	$j++ and print "\n";
print;
	s/^\d+ //;
	$_.=" ".$&;
	chop;
	}

#***********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+) /;

$_=$'.(" 0"x($`-1));
s/\n//;

for $i(1..$`){
	print;
	print "\n";
	s/^\d+ //;
	$_.=" ".$&;
	chop;
	}

#***********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+) /;

$_=$'.(" 0"x($`-1));
# print;

for $i(1..$`){
	$j++ and print "\n";
	print;
	s/^\d+ //;
	$_.=" ".$&;
	chop;
	}

#***********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+) /;

$_=$'.(" 0"x($`-1));

for $i(1..$`){
	print;
	print "\n";
	s/^\d+ //;
	$_.=" ".$&;
	chop;
	}

#***********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
}


Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back w tokens then he'll get  dollars. Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has n numbers x1, x2, ..., xn. Number xi is the number of tokens given to each worker on the i-th day. Help him calculate for each of n days the number of tokens he can save.

The first line of input contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The second line of input contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 109).

Output n space-separated integers. The i-th of them is the number of tokens Mashmokh can save on the i-th day.


Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: An 'L' indicates he should move one unit left.  An 'R' indicates he should move one unit right.  A 'U' indicates he should move one unit up.  A 'D' indicates he should move one unit down.But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in s with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.

The first and only line contains the string s (1 ≤ |s| ≤ 100 000) — the instructions Memory is given.

If there is a string satisfying the conditions, output a single integer — the minimum number of edits required. In case it's not possible to change the sequence in such a way that it will bring Memory to to the origin, output -1.

NoteIn the first sample test, Memory is told to walk right, then right, then up. It is easy to see that it is impossible to edit these instructions to form a valid walk.In the second sample test, Memory is told to walk up, then down, then up, then right. One possible solution is to change s to "LDUR". This string uses 1 edit, which is the minimum possible. It also ends at the origin.

$,=" ";
my $s=<>;
chomp($s);
my %counts;
for(0..length($s)-1)
{
$counts{substr($s,$_,1)}++;
}
my $diff=0;

$diff = abs($counts{"R"}-$counts{"L"}) + abs($counts{"D"}-$counts{"U"});
if($diff%2==0)
{
  $diff/=2;
  print $diff . "\n";
}
else
{
  print "-1\n";
}


You are given a string $$$s$$$, consisting only of characters '0' or '1'. Let $$$|s|$$$ be the length of $$$s$$$.You are asked to choose some integer $$$k$$$ ($$$k > 0$$$) and find a sequence $$$a$$$ of length $$$k$$$ such that:   $$$1 \le a_1 < a_2 < \dots < a_k \le |s|$$$;  $$$a_{i-1} + 1 < a_i$$$ for all $$$i$$$ from $$$2$$$ to $$$k$$$. The characters at positions $$$a_1, a_2, \dots, a_k$$$ are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence $$$a$$$ should not be adjacent.Let the resulting string be $$$s'$$$. $$$s'$$$ is called sorted if for all $$$i$$$ from $$$2$$$ to $$$|s'|$$$ $$$s'_{i-1} \le s'_i$$$.Does there exist such a sequence $$$a$$$ that the resulting string $$$s'$$$ is sorted?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$s$$$ ($$$2 \le |s| \le 100$$$). Each character is either '0' or '1'.

For each testcase print "YES" if there exists a sequence $$$a$$$ such that removing the characters at positions $$$a_1, a_2, \dots, a_k$$$ and concatenating the parts without changing the order produces a sorted string. Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first testcase you can choose a sequence $$$a=[1,3,6,9]$$$. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.In the second and the third testcases the sequences are already sorted.In the fourth testcase you can choose a sequence $$$a=[3]$$$. $$$s'=$$$ "11", which is sorted.In the fifth testcase there is no way to choose a sequence $$$a$$$ such that $$$s'$$$ is sorted.


Consider an array $$$a$$$ of $$$n$$$ positive integers.You may perform the following operation:   select two indices $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$), then  decrease all elements $$$a_l, a_{l + 1}, \dots, a_r$$$ by $$$1$$$. Let's call $$$f(a)$$$ the minimum number of operations needed to change array $$$a$$$ into an array of $$$n$$$ zeros.Determine if for all permutations$$$^\dagger$$$ $$$b$$$ of $$$a$$$, $$$f(a) \leq f(b)$$$ is true. $$$^\dagger$$$ An array $$$b$$$ is a permutation of an array $$$a$$$ if $$$b$$$ consists of the elements of $$$a$$$ in arbitrary order. For example, $$$[4,2,3,4]$$$ is a permutation of $$$[3,2,4,4]$$$ while $$$[1,2,2]$$$ is not a permutation of $$$[1,2,3]$$$.

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

For each test case, print "YES" (without quotes) if for all permutations $$$b$$$ of $$$a$$$, $$$f(a) \leq f(b)$$$ is true, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we can change all elements to $$$0$$$ in $$$5$$$ operations. It can be shown that no permutation of $$$[2, 3, 5, 4]$$$ requires less than $$$5$$$ operations to change all elements to $$$0$$$.In the third test case, we need $$$5$$$ operations to change all elements to $$$0$$$, while $$$[2, 3, 3, 1]$$$ only needs $$$3$$$ operations.


A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?

Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106.

Output the maximum possible length of a regular bracket sequence.


You have a string $$$s$$$ consisting of lowercase Latin alphabet letters. You can color some letters in colors from $$$1$$$ to $$$k$$$. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.Then you can swap any two symbols painted in the same color as many times as you want. After that, $$$k$$$ strings will be created, $$$i$$$-th of them will contain all the characters colored in the color $$$i$$$, written in the order of their sequence in the string $$$s$$$.Your task is to color the characters of the string so that all the resulting $$$k$$$ strings are palindromes, and the length of the shortest of these $$$k$$$ strings is as large as possible.Read the note for the first test case of the example if you need a clarification.Recall that a string is a palindrome if it reads the same way both from left to right and from right to left. For example, the strings abacaba, cccc, z and dxd are palindromes, but the strings abab and aaabaa — are not.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input data sets in the test.  The descriptions of the input data sets follow. The first line of the description of each input data set contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the length of the string and the number of colors in which its letters can be painted. The second line of the description of each input data set contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase letters of the Latin alphabet. It is guaranteed that the sum of n over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each set of input data, output a single integer  — the maximum length of the shortest palindrome string that can be obtained.

10

8 2

bxyaxzay

6 3

aaaaaa

6 1

abcdef

6 6

abcdef

3 2

dxd

11 2

abcabcabcac

6 6

sipkic

7 2

eatoohd

3 1

llw

6 2

bfvfbv

Note In the first test case, $$$s$$$="bxyaxzay", $$$k=2$$$. We use indices in the string from $$$1$$$ to $$$8$$$. The following coloring will work: $$$\mathtt{\mathbf{\color{red}{b}\color{blue}{xy}\color{red}{a}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$ (the letter z remained uncolored). After painting:  swap two red characters (with the indices $$$1$$$ and $$$4$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$;  swap two blue characters (with the indices $$$5$$$ and $$$8$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{y}z\color{red}{a}\color{blue}{x}}}$$$. Now, for each of the two colors we write out the corresponding characters from left to right, we get two strings $$$\mathtt{\mathbf{\color{red}{aba}}}$$$ and $$$\mathtt{\mathbf{\color{blue}{xyyx}}}$$$. Both of them are palindromes, the length of the shortest is $$$3$$$. It can be shown that the greatest length of the shortest palindrome cannot be achieved. In the second set of input data, the following coloring is suitable: $$$[1, 1, 2, 2, 3, 3]$$$. There is no need to swap characters. Both received strings are equal to aa, they are palindromes and their length is $$$2$$$. In the third set of input data, you can color any character and take it into a string. In the fourth set of input data, you can color the $$$i$$$th character in the color $$$i$$$. In the fifth set of input data can be colored in each of the colors of one character. In the sixth set of input data, the following coloring is suitable: $$$[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0]$$$. Rearrange the characters so as to get the palindromes abcba and acbca.

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	my( $n, $k ) = split;

	$debug and print "[$n, $k]";

	my %h;

	$h{ $_ } ++ for <> =~ /./g;

	$debug and print join ' ', map { $_ x $h{ $_ } } sort keys %h;

	my $ans = 0;

	while( 1 ){

		$debug and print join ' ', "[$ans]", map { $_ x $h{ $_ } } sort keys %h;

		my $pairs = 0;
		for my $key ( sort keys %h ){
			$pairs += ( $h{ $key } >> 1 );
			}

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

		if( $pairs >= $k ){
			$ans += 2;

			my $kk = $k;

			for my $key ( sort keys %h ){
				my $has = ( $h{ $key } >> 1 );

				$debug and print "key:[$key], has:[$has]";

				if( $has >= $kk ){
					$h{ $key } -= $kk * 2;
					$kk = 0;
					}
				else{
					$kk -= $has;
					$h{ $key } -= $has * 2;
					}
				}
			}
		else{
			last;
			}
		}

	my $left = 0;
	for my $key ( sort keys %h ){
		$left += $h{ $key };
		}

	if( $left >= $k ){
		$ans ++;
		}

	print $ans;
	}


Masha meets a new friend and learns his phone number — $$$s$$$. She wants to remember it as soon as possible. The phone number — is a string of length $$$m$$$ that consists of digits from $$$0$$$ to $$$9$$$. The phone number may start with 0.Masha already knows $$$n$$$ phone numbers (all numbers have the same length $$$m$$$). It will be easier for her to remember a new number if the $$$s$$$ is represented as segments of numbers she already knows. Each such segment must be of length at least $$$2$$$, otherwise there will be too many segments and Masha will get confused.For example, Masha needs to remember the number: $$$s = $$$ '12345678' and she already knows $$$n = 4$$$ numbers: '12340219', '20215601', '56782022', '12300678'. You can represent $$$s$$$ as a $$$3$$$ segment: '1234' of number one, '56' of number two, and '78' of number three. There are other ways to represent $$$s$$$.Masha asks you for help, she asks you to break the string $$$s$$$ into segments of length $$$2$$$ or more of the numbers she already knows. If there are several possible answers, print any of them.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases. Before each test case there is a blank line. Then there is a line containing integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^3$$$) —the number of phone numbers that Masha knows and the number of digits in each phone number. Then follow $$$n$$$ line, $$$i$$$-th of which describes the $$$i$$$-th number that Masha knows. The next line contains the phone number of her new friend $$$s$$$. Among the given $$$n+1$$$ phones, there may be duplicates (identical phones). It is guaranteed that the sum of $$$n \cdot m$$$ ($$$n$$$ multiplied by $$$m$$$) values over all input test cases does not exceed $$$10^6$$$.

You need to print the answers to $$$t$$$ test cases. The first line of the answer should contain one number $$$k$$$, corresponding to the number of segments into which you split the phone number $$$s$$$. Print -1 if you cannot get such a split. If the answer is yes, then follow $$$k$$$ lines containing triples of numbers $$$l, r, i$$$. Such triplets mean that the next $$$r-l+1$$$ digits of number $$$s$$$ are equal to a segment (substring) with boundaries $$$[l, r]$$$ of the phone under number $$$i$$$. Both the phones and the digits in them are numbered from $$$1$$$. Note that $$$r-l+1 \ge 2$$$ for all $$$k$$$ lines.

NoteThe example from the statement.In the second case, it is impossible to represent by segments of known numbers of length 2 or more.In the third case, you can get the segments '12' and '21' from the first phone number.


Consider a table of size $$$n \times m$$$, initially fully white. Rows are numbered $$$1$$$ through $$$n$$$ from top to bottom, columns $$$1$$$ through $$$m$$$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 115$$$) — the number of rows and the number of columns in the table. The $$$i$$$-th of the next $$$n$$$ lines contains a string of $$$m$$$ characters $$$s_{i1} s_{i2} \ldots s_{im}$$$ ($$$s_{ij}$$$ is 'W' for white cells and 'B' for black cells), describing the $$$i$$$-th row of the table.

Output two integers $$$r$$$ and $$$c$$$ ($$$1 \le r \le n$$$, $$$1 \le c \le m$$$) separated by a space — the row and column numbers of the center of the black square.


Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.

The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000).

On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1.

NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana".

#!/bin/perl -w
use strict;
use warnings;
use List::Util qw[reduce max];
use POSIX;

my $s = <>;
chomp $s;
my $n = int <>;
my %letters;
for (split //, $s) {
    if (defined $letters{$_}) {
	$letters{$_}++;
    } else {
	$letters{$_} = 1;
    }
}

if (keys %letters > $n) {
    print -1;
    exit;
} else {
    my $string = '';
    my %used;
    my %left = %letters;
    while (keys %letters < $n) {
	my $k = reduce {
	    $left{$a} > $left{$b} ? $a : $b
	} keys %letters;
	$string .= $k;
	if (defined $used{$k}) {
	    $used{$k}++;
	} else {
	    $used{$k} = 1;
	}
	$left{$k} = ceil ($letters{$k} / (1 + $used{$k}));
	$n--;
    }
    my $stickers = max values %left;
    map { $string .= $_ } keys %left;
    print "$stickers\n$string\n";
}

#!/bin/perl -w
use strict;
use warnings;
use List::Util qw[reduce max];

my $s = <>;
chomp $s;
my $n = int <>;
my %letters;
for (split //, $s) {
    if (defined $letters{$_}) {
	$letters{$_}++;
    } else {
	$letters{$_} = 1;
    }
}

if (keys %letters > $n) {
    print -1;
    exit;
} else {
    my $string = '';
    while (keys %letters < $n) {
	my $k = reduce {
	    $letters{$a} > $letters{$b} ? $a : $b
	} keys %letters;
	$string .= $k;
	$letters{$k} = $letters{$k} >> 1 + $letters{$k} % 2;
	$n--;
    }
    my $stickers = max values %letters;
    map { $string .= $_ } keys %letters;
    print "$stickers\n$string\n";
}

#!/bin/perl -w
use strict;
use warnings;
use List::Util qw[reduce max];

my $s = <>;
chomp $s;
my $n = int <>;
my %letters;
for (split //, $s) {
    if (defined $letters{$_}) {
	$letters{$_}++;
    } else {
	$letters{$_} = 1;
    }
}

if (keys %letters > $n) {
    print -1;
    exit;
} else {
    my $string = '';
    while (keys %letters < $n) {
	my $k = reduce {
	    $letters{$a} > $letters{$b} ? $a : $b
	} keys %letters;
	$string .= $k;
	$letters{$k} =  $letters{$k} % 2 + $letters{$k} >> 1;
	$n--;
    }
    my $stickers = max values %letters;
    map { $string .= $_ } keys %letters;
    print "$stickers\n$string\n";
}


Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:  on both diagonals of the square paper all letters are the same;  all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.

The first line contains integer n (3 ≤ n < 300; n is odd). Each of the next n lines contains n small English letters — the description of Valera's paper.

Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.

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

chomp($n = <>);
push @a, [split //, <>] foreach (0 .. $n-1);
$ch = $a[0][0];
$a[$_][$_] ne $ch and say "NO" and exit foreach(0 .. $n-1);
$a[$_][$n-1-$_] ne $ch and say "NO" and exit foreach(0 .. $n-1);
$a[1][0] eq $ch and say "NO" and exit;
$ch = $a[1][0];
foreach $i (0 .. $n-1) {
	foreach $j (0 .. $n-1) {
		($j==$i || $j==$n-1-$i) and next;
		$a[$i][$j] ne $ch and say "NO" and exit;
	}
}
say "YES";

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

chomp($n = <>);
push @a, [split //, <>] foreach (0 .. $n-1);
$ch = $a[0][0];
$a[$_][$_] ne $ch and say "NO" and exit foreach(0 .. $n-1);
$a[$_][$n-1-$_] ne $ch and say "NO" and exit foreach(0 .. $n-1);
$ch = $a[1][0];
foreach $i (0 .. $n-1) {
	foreach $j (0 .. $n-1) {
		($j==$i || $j==$n-1-$i) and next;
		$a[$i][$j] ne $ch and say "NO" and exit;
	}
}
say "YES";


There is a chessboard of size $$$n$$$ by $$$n$$$. The square in the $$$i$$$-th row from top and $$$j$$$-th column from the left is labelled $$$(i,j)$$$.Currently, Gregor has some pawns in the $$$n$$$-th row. There are also enemy pawns in the $$$1$$$-st row. On one turn, Gregor moves one of his pawns. A pawn can move one square up (from $$$(i,j)$$$ to $$$(i-1,j)$$$) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from $$$(i,j)$$$ to either $$$(i-1,j-1)$$$ or $$$(i-1,j+1)$$$) if and only if there is an enemy pawn in that square. The enemy pawn is also removed.Gregor wants to know what is the maximum number of his pawns that can reach row $$$1$$$?Note that only Gregor takes turns in this game, and the enemy pawns never move. Also, when Gregor's pawn reaches row $$$1$$$, it is stuck and cannot make any further moves.

The first line of the input contains one integer $$$t$$$ ($$$1\le t\le 2\cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot{10}^{5}$$$) — the size of the chessboard. The second line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to an enemy pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. The third line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to a Gregor's pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. It is guaranteed that the sum of $$$n$$$ across all test cases is less than $$$2\cdot{10}^{5}$$$.

For each test case, print one integer: the maximum number of Gregor's pawns which can reach the $$$1$$$-st row.

NoteIn the first example, Gregor can simply advance all $$$3$$$ of his pawns forward. Thus, the answer is $$$3$$$.In the second example, Gregor can guarantee that all $$$4$$$ of his pawns reach the enemy row, by following the colored paths as demonstrated in the diagram below. Remember, only Gregor takes turns in this "game"!  In the third example, Gregor's only pawn is stuck behind the enemy pawn, and cannot reach the end.In the fourth example, Gregor has no pawns, so the answer is clearly $$$0$$$.


Phoenix has collected $$$n$$$ pieces of gold, and he wants to weigh them together so he can feel rich. The $$$i$$$-th piece of gold has weight $$$w_i$$$. All weights are distinct. He will put his $$$n$$$ pieces of gold on a weight scale, one piece at a time. The scale has an unusual defect: if the total weight on it is exactly $$$x$$$, it will explode. Can he put all $$$n$$$ gold pieces onto the scale in some order, without the scale exploding during the process? If so, help him find some possible order. Formally, rearrange the array $$$w$$$ so that for each $$$i$$$ $$$(1 \le i \le n)$$$, $$$\sum\limits_{j = 1}^{i}w_j \ne x$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$; $$$1 \le x \le 10^4$$$) — the number of gold pieces that Phoenix has and the weight to avoid, respectively.  The second line of each test case contains $$$n$$$ space-separated integers $$$(1 \le w_i \le 100)$$$ — the weights of the gold pieces. It is guaranteed that the weights are pairwise distinct.

For each test case, if Phoenix cannot place all $$$n$$$ pieces without the scale exploding, print NO. Otherwise, print YES followed by the rearranged array $$$w$$$. If there are multiple solutions, print any.

NoteIn the first test case, Phoenix puts the gold piece with weight $$$3$$$ on the scale first, then the piece with weight $$$2$$$, and finally the piece with weight $$$1$$$. The total weight on the scale is $$$3$$$, then $$$5$$$, then $$$6$$$. The scale does not explode because the total weight on the scale is never $$$2$$$.In the second test case, the total weight on the scale is $$$8$$$, $$$9$$$, $$$11$$$, $$$14$$$, then $$$18$$$. It is never $$$3$$$.In the third test case, Phoenix must put the gold piece with weight $$$5$$$ on the scale, and the scale will always explode.


Martian scientists explore Ganymede, one of Jupiter's numerous moons. Recently, they have found ruins of an ancient civilization. The scientists brought to Mars some tablets with writings in a language unknown to science.They found out that the inhabitants of Ganymede used an alphabet consisting of two letters, and each word was exactly $$$\ell$$$ letters long. So, the scientists decided to write each word of this language as an integer from $$$0$$$ to $$$2^{\ell} - 1$$$ inclusively. The first letter of the alphabet corresponds to zero bit in this integer, and the second letter corresponds to one bit.The same word may have various forms in this language. Then, you need to restore the initial form. The process of doing it is described below.Denote the distance between two words as the amount of positions, in which these words differ. For example, the distance between $$$1001_2$$$ and $$$1100_2$$$ (in binary) is equal to two, as these words have different letters in the second and the fourth positions, counting from left to right. Further, denote the distance between words $$$x$$$ and $$$y$$$ as $$$d(x, y)$$$.Let the word have $$$n$$$ forms, the $$$i$$$-th of which is described with an integer $$$x_i$$$. All the $$$x_i$$$ are not necessarily different, as two various forms of the word can be written the same. Consider some word $$$y$$$. Then, closeness of the word $$$y$$$ is equal to the sum of distances to each of the word forms, i. e. the sum $$$d(x_i, y)$$$ over all $$$1 \le i \le n$$$.The initial form is the word $$$y$$$ with minimal possible nearness.You need to help the scientists and write the program which finds the initial form of the word given all its known forms. Note that the initial form is not necessarily equal to any of the $$$n$$$ given forms.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following are descriptions of the test cases. The first line contains two integers $$$n$$$ and $$$\ell$$$ ($$$1 \le n \le 100$$$, $$$1 \le \ell \le 30$$$) — the amount of word forms, and the number of letters in one word. The second line contains $$$n$$$ integers $$$x_i$$$ ($$$0 \le x_i \le 2^\ell - 1$$$) — word forms. The integers are not necessarily different.

For each test, print a single integer, the initial form of the word, i. e. such $$$y$$$ ($$$0 \le y \le 2^\ell - 1$$$) that the sum $$$d(x_i, y)$$$ over all $$$1 \le i \le n$$$ is minimal possible. Note that $$$y$$$ can differ from all the integers $$$x_i$$$. If there are multiple ways to restore the initial form, print any.

NoteIn the first test case, the words can be written as $$$x_1 = 10010_2$$$, $$$x_2 = 01001_2$$$ and $$$x_3 = 10101_2$$$ in binary. Let $$$y = 10001_2$$$. Then, $$$d(x_1, y) = 2$$$ (the difference is in the fourth and the fifth positions), $$$d(x_2, y) = 2$$$ (the difference is in the first and the second positions), $$$d(x_3, y) = 1$$$ (the difference is in the third position). So, the closeness is $$$2 + 2 + 1 = 5$$$. It can be shown that you cannot achieve smaller closeness.In the second test case, all the forms are equal to $$$18$$$ ($$$10010_2$$$ in binary), so the initial form is also $$$18$$$. It's easy to see that closeness is equal to zero in this case.

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

my $W = 31;

<>;

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

	my( $n, $l ) = split;
	@_ = split ' ', <>;

	$debug and print "[$n, $l]";
	$debug and print "[@_]";

	map { $_ = sprintf "%0${W}b", $_ } @_;

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

	my $ans;

	for my $i ( 0 .. $W - 1 ){
		my %h;

		for my $j ( 0 .. @_ - 1 ){
			$h{ substr $_[ $j ], $i, 1 } ++;
			}

		$ans .= ( sort { $h{ $b } <=> $h{ $a } } keys %h )[ 0 ];
		}

	print eval "0b$ans";
	}


After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?

The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group.

Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.

NoteIn the first test we can sort the children into four cars like this:  the third group (consisting of four children),  the fourth group (consisting of three children),  the fifth group (consisting of three children),  the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars.

my $n   = <>;
my @arr = split " ", <>;
my $l   = scalar @arr - 1;
my $ans = 0;
@arr = sort @arr;
while (scalar @arr > 1) {
    # if ($arr[-1] >= 4) {
    #     $ans += int(($arr[-1] + 3) / 4);
    #     pop @arr;
    # }
    # else {
        if ($arr[-1] + $arr[0] <= 4) {
            push @arr, shift(@arr) + pop @arr;
        }
        else {
            $ans += int(($arr[-1] +3) / 4);
            pop @arr;
        }
    # }
}
$ans+= int(($arr[0]+3)/4) if scalar @arr;
print $ans . "\n";

my $n   = <>;
my @arr = split " ", <>;
my $l   = scalar @arr - 1;
my $ans = 0;
@arr = sort @arr;
while (scalar @arr > 1) {
    if ($arr[-1] >= 4) {
        $ans += int(($arr[-1] + 3) / 4);
        # print "+ $arr[-1]\n";
        pop @arr;
    }
    else {
        if ($arr[-1] + $arr[0] <= 4) {
            # print "- $arr[-1] $arr[0]\n";
            push @arr, shift(@arr) + pop @arr;
        }
        else {
            $ans += int(($arr[-1] +3) / 4);
            # print "* $arr[-1]\n";
            pop @arr;
        }
    }
    # print scalar @arr . "\n";
}
$ans+= int(($arr[0]+3)/4) if scalar @arr;
print $ans . "\n";

#!/usr/bin/perl
# 158 B

use warnings;
use strict;
use POSIX;

my $n = <STDIN>;
my @groups = split(" ", <STDIN>);
my ($one, $two, $three, $four);
my $ret = 0;

foreach(@groups){
    if($_==1){
        $one++;
    }elsif($_==2){
        $two++;
    }elsif($_==3){
        $three++;
    }else{
        $four++;
    }
}

# groups of 4
$ret += $four;
$four= 0;

# groups of 3
if($three<=$one){
    $ret += $three;
    $one -= $three;
    $three=0;
} else {
    $ret += $one;
    $three -= $one;
    $ret += $three;
    $three = 0;
    $one = 0;
}

# groups of 2
my $div = floor($two/2);
my $rem = $two % 2;

$ret += $div;
$two = $rem; #at this point $two will be 0 or 1

if($two == 1){
    $one -= 2;
    $ret++;
}

$ret += ceil($one/4);
print $ret;

use strict;
use warnings;

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

die('n to big') unless $n >= 1 && $n <= 100000;

my $line = <>;
chomp($line);
my @in = split(' ', $line);

my $result = 0;

# calculate how many groups of each size in stop one. so for example:
# 1 2 4 3 3 goes into
# 1: 1
# 2: 1
# 3: 2
# 4: 1

#remove 4 from equation since its a corner case
#possible compbis per number:
# 3: only go with 1...
# 2: can go with 2 and 1
# 1: can go with 3, 2, 1
#we see higher number is more restrictive. therefor lest start to solve backwards
# try to generalisation:
# x: 4-x.... test. 3: 4-3=1 OK. 2: 4-2=2 OK. 1

my %groups;
for (@in) {
    die('1-4...') unless $_ >= 1 && $_ <= 4;
    $groups{$_}++;
}
my $taxies = 0;

while (grep { $_ >= 1 } values %groups) {
    if ($groups{4}) {
        $groups{4}--;
        $taxies++;
    } elsif($groups{3}) {
        $groups{3}--;
        if ($groups{1}) {
            $groups{1}--;
        }
        $taxies++;
    } elsif ($groups{2}) {
        $groups{2}--;
        if ($groups{2}) {
            $groups{2}--;
        } elsif ($groups{1} >= 2) {
            $groups{1} -=2;
        } elsif ($groups{1} >= 1) {
            $groups{1}--;
        }
        $taxies++;
    } elsif ($groups{1}) {
        $groups{1}--;
        if ($groups{1} >= 3) {
            $groups{1} -= 3;
        } elsif($groups{1} >= 2) {
            $groups{1} -= 2;
        } elsif($groups{1} >= 1) {
            $groups{1}--;
        }
        $taxies++;
    } else {
        die('invalid input error...');
    }

}

print $taxies;

$DEBUG = 0;
chomp($n = <STDIN>);
chomp($line = <STDIN>);

%g = {};
map { $g{$_} = 0; } 1..4;
foreach(split /\s/, $line) {
	$g{$_}++;
}
$taxis = $g{4};
print "$taxis groups of 4\n" if $DEBUG;
if($g{3} <= $g{1}) {
	print $g{3}." groups of 3+1\n" if $DEBUG;
	$taxis += $g{3};
	$g{1} -= $g{3};
	$g{3} = 0;
} else {
	$taxis += $g{1};
	print $g{1}." groups of 3+1\n" if $DEBUG;
	$g{3} -= $g{1};
	$g{1} = 0;
}
if($g{3} > 0) { $taxis += $g{3}; print $g{3}." groups of 3\n" if $DEBUG; }
while($g{2} > 1) {
	$taxis++;
	$g{2} -= 2;
	print "A group of 2+2\n" if $DEBUG;
}
if($g{2}>0) {
	$taxis++;
	$g{1} -= 2;
	print "A group of 2+1+1, ".$g{1}." singles left\n" if $DEBUG;
}
while($g{1}>0) {
	$taxis++;
	$g{1} -= 4;
	print "A group of 4 singles\n" if $DEBUG;
}
print "$taxis\n";

$\="\n";
$n=<STDIN>;

$/=" ";
my $cabs=0;
my @passGroups=(0,0,0,0,0);

for ($i=1;$i<$n;$i++){
    $passGroups[<STDIN>]+=1;
}
$/="\n";
$passGroups[<STDIN>]+=1;
#print "\n", @passGroups;

#print "1) ".$cubs;

#print "        passGroups[1]= $passGroups[1]";
#print "        passGroups[2]= $passGroups[2]";
#print "        passGroups[3]= $passGroups[3]";
#print "        passGroups[4]= $passGroups[4]";

$cubs+=$passGroups[4];
#print "12) ".$cubs;
#print "        passGroups[1]= $passGroups[1]";
#print "        passGroups[2]= $passGroups[2]";
#print "        passGroups[3]= $passGroups[3]";
#print "        passGroups[4]= $passGroups[4]";

if ($passGroups[1]<=$passGroups[3]){
    $cubs+=$passGroups[3];
    $passGroups[1]=0;
}

if ($passGroups[1]>$passGroups[3]){
    $passGroups[1]-=$passGroups[3];
    $cubs+=$passGroups[3];
}

if ($passGroups[2]%2!=0){
    $cubs+=1;
    $passGroups[2]-=1;
    if ($passGroups[1]>1){
        $passGroups[1]-=2;
    }
    if ($passGroups[1]==1){
        $passGroups[1]-=1;
    }

}
    $cubs+=$passGroups[2]/2;
if ($passGroups[1]%4!=0){
    $cubs+=int($passGroups[1]/4) +1;
}else{
    $cubs+=int($passGroups[1]/4);
}

print $cubs;

$\="\n";
$n=<STDIN>;
my $cabs=0;
my @passGroups=(0,0,0,0,0);

@passs=split(" ",<STDIN>);

foreach $i (@passs){
    $passGroups[$i]+=1;
    #print $i;
}

$cubs+=$passGroups[4];

if ($passGroups[1]<=$passGroups[3]){
    $cubs+=$passGroups[3];
    $passGroups[1]=0;
}

if ($passGroups[1]>$passGroups[3]){
    $passGroups[1]-=$passGroups[3];
    $cubs+=$passGroups[3];
}

if ($passGroups[2]%2!=0){
    $cubs+=1;
    $passGroups[2]-=1;
    if ($passGroups[1]>1){
        $passGroups[1]-=2;
    }
    if ($passGroups[1]==1){
        $passGroups[1]-=1;
    }

}
    $cubs+=$passGroups[2]/2;
if ($passGroups[1]%4!=0){
    $cubs+=int($passGroups[1]/4) +1;
}else{
    $cubs+=int($passGroups[1]/4);
}

print $cubs;

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

sub ceil { my $j = $_[0]; my $i = int $j; $i < $j ? $i + 1 : $i }

my ($taxi, $one, $two, $three) = (0, 0, 0, 0); <STDIN>;
foreach (split ' ', <STDIN>)
{ if ($_ == 1) { if ($three) { --$three } else { ++$one; next } }
  elsif ($_ == 2) { if ($two) { --$two } else { ++$two; next } }
  elsif ($_ == 3) { if ($one) { --$one } else { ++$three; next } }
  ++$taxi }
if ($two) { $one -= $one > 1 ? 2 : $one; ++$taxi }
printf "%d\n", $taxi + $three + ceil $one / 4

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

sub ceil { my $j = $_[0]; my $i = int $j; $i < $j ? $i + 1 : $i }

sub input
{ <STDIN>; $_ = <STDIN>; s/\s//g; my ($n, $m, @a) = length;
  foreach my $i (1..4)
  { s/$i+//g; $m = length; push @a, $n - $m; $n = $m }
  @a }

my ($one, $two, $three, $four) = input;
$one -= $one < $three ? $one : $three;
if ($two % 2) { $one -= $one < 2 ? $one : 2; ++$two }
printf "%d\n", $two / 2 + $three + $four + ceil $one / 4

#!/usr/bin/perl

use 5.012;
use warnings;
use integer;

chomp(my $i = <>);
chomp(my $line = <>);
my $g = ($line =~ s/ //gr);
my $cnt = ($g =~ tr/4/4/);
my $threes = ($g =~ tr/3/3/);
my $twos = ($g =~ tr/2/2/);
my $ones = ($g =~ tr/1/1/);
$cnt += $threes;
$ones -= $threes;
$cnt += $ones if $ones > 0;
$cnt += $twos / 2;
$cnt++ if $twos % 2;
print $cnt;

#!/usr/bin/perl

use 5.012;
use warnings;
use integer;

chomp(my $i = <>);
chomp(my $line = <>);
my $g = ($line =~ s/ //gr);
my $cnt = ($g =~ tr/4/4/);
my $threes = ($g =~ tr/3/3/);
my $twos = ($g =~ tr/2/2/);
my $ones = ($g =~ tr/1/1/);
$cnt += $threes;
$ones -= $threes;
$ones = 0 if $ones < 0;
$cnt += $twos / 2;
$cnt++ if $twos % 2;
$cnt += $ones / 4;
$cnt++ if $ones % 4;
print $cnt;

use strict;
use warnings;

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

die('n to big') unless $n >= 1 && $n <= 10000;

my $line = <>;
chomp($line);
my @in = split(' ', $line);

my $result = 0;

# calculate how many groups of each size in stop one. so for example:
# 1 2 4 3 3 goes into
# 1: 1
# 2: 1
# 3: 2
# 4: 1

#remove 4 from equation since its a corner case
#possible compbis per number:
# 3: only go with 1...
# 2: can go with 2 and 1
# 1: can go with 3, 2, 1
#we see higher number is more restrictive. therefor lest start to solve backwards
# try to generalisation:
# x: 4-x.... test. 3: 4-3=1 OK. 2: 4-2=2 OK. 1

my %groups;
for (@in) {
    die('1-4...') unless $_ >= 1 && $_ <= 4;
    $groups{$_}++;
}
# I want to loop: 4 3 3 2 1

for (my $i = 4; $i >= 1; $i--) {
    while ($groups{$i} >= 1) {
        my $taxi_occupany = $i;
        $groups{$i}--; #remove self from groups
        my $max_friend_group = 4 - $taxi_occupany;;

        for (my $j = $max_friend_group; $j >= 1; $j--) {
            if ($groups{$j} > 0) {
                $groups{$j}--;
                $taxi_occupany += $j;
            }
            last if $taxi_occupany >= 4;
        }
        $result++;
    }
}

print $result;

$\="\n";
$n=<STDIN>;

$/=" ";
my $cabs=0;
my @passGroups=(0,0,0,0,0);

for ($i=1;$i<$n;$i++){
    $passGroups[<STDIN>]+=1;
}
$/="\n";
$passGroups[<STDIN>]+=1;

$cubs+=$passGroups[4];

if ($passGroups[1]<=$passGroups[3]){
    $cubs+=$passGroups[3];
    $passGroups[1]=0;
}

if ($passGroups[1]>$passGroups[3]){
    $passGroups[1]-=$passGroups[3];
    $cubs+=$passGroups[3];
}

if ($passGroups[2]%2!=0){
    $cubs+=1;
    $passGroups[2]-=1;
    if ($passGroups[1]>1){
        $passGroups[1]-=2;
    }
}

    $cubs+=$passGroups[2]/2;

if ($passGroups[1]%4!=0){
    $cubs+=int($passGroups[1]/4) +1;
}else{
    $cubs+=int($passGroups[1]/4);
}

print $cubs;


Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.

The first line contains two integers n and m (1 ≤ n ≤ 100; 0 ≤ m ≤ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ ci ≤ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x).

Print a single integer — the minimum sum of debts in the optimal rearrangement.

NoteIn the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10.In the second sample, there are no debts.In the third sample, you can annul all the debts.

my $nm = <STDIN>;
chomp ($nm);
my @data = split (" ", $nm);
my $n = shift (@data);
my $m = pop (@data);
if ($m < 2) {
    print $m;
    exit;
}
my $i = 0;
my $j = 0;
my $s = 0;
my $x = 0;
my @result;
while ($i != $m ) {
    my $input = <STDIN>;
    chomp ($input);
    my @temp = split (" ", $input);
    my $p = shift (@temp);
    push (@poor, $p);
    my $r = shift (@temp);
    push (@rich, $r);
    my $t = shift (@temp);
    push (@total, $t);
    $result[$i] = 0;
    $i++;
}
for (my $i = 0; $i < $n; $i++) {
    for (my $j = 0; $j <$m; $j++) {
        if ($poor[$j] == $i+1) {
            $result[$i] = $result[$i] - $total[$j];
        }
        if ($rich[$j] == $i+1) {
            $result[$i] = $result[$i] + $total[$j];
        }
    }
}
for (my $i = 0; $i < $n; $i++) {
    if ($result[$i] >= 0) {
    $x = $x + $result[$i];
    }
}
print $x;

my $nm = <STDIN>;
chomp ($nm);
my @data = split (" ", $nm);
my $n = shift (@data);
my $m = pop (@data);
if ($m < 2) {
    print $m;
    exit;}

my $i = 0;
my $x = 0;

while ($i != $m ) {
    my $input = <STDIN>;
    chomp ($input);
    my @temp = split (" ", $input);
    my $p = shift (@temp);
    push (@poor, $p);
    my $r = shift (@temp);
    push (@rich, $r);
    my $t = shift (@temp);
    push (@total, $t);
    $x = $x + $t;
    $i++;
}
$i = 0;
$j = 0;
while ($i != $m) {
    while ($j != $m) {
        if ($poor[$i] == $rich[$j]) {
            if ($total[$i] > $total[$j]) {
                $x = $x - $total[$j];
            } else {
                $x = $x - $total[$i];
            }
        }
        $j++;
    }
    $j = 0;
    $i++;
}
print $x;

my $nm = <STDIN>;
chomp ($nm);
my @data = split (" ", $nm);
my $n = shift (@data);
my $m = pop (@data);
if ($m < 2) {
    print $m;
    exit;}

my $i = 0;
my $x = 0;

while ($i != $m ) {
    my $input = <STDIN>;
    chomp ($input);
    my @temp = split (" ", $input);
    my $p = shift (@temp);
    push (@poor, $p);
    my $r = shift (@temp);
    push (@rich, $r);
    my $t = shift (@temp);
    push (@total, $t);
    $x = $x + $t;
    $i++;
}
$i = 0;
$j = 0;
while ($i != $m) {
    while ($j != $m) {
        if ($poor[$i] != $poor[($i-1)]) {
            if ($poor[$i] == $rich[$j]) {
                if ($total[$i] > $total[$j]) {
                    $x = $x - $total[$j];
                } else {
                    $x = $x - $total[$i];
                }
            }
        }
        $j++;
    }
    $j = 0;
    $i++;
}
print $x;