William has array of $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. He can perform the following sequence of operations any number of times:   Pick any two items from array $$$a_i$$$ and $$$a_j$$$, where $$$a_i$$$ must be a multiple of $$$2$$$  $$$a_i = \frac{a_i}{2}$$$  $$$a_j = a_j \cdot 2$$$ Help William find the maximal sum of array elements, which he can get by performing the sequence of operations described above.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 15)$$$, the number of elements in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i < 16)$$$, the contents of William's array.

For each test case output the maximal sum of array elements after performing an optimal sequence of operations.

NoteIn the first example test case the optimal sequence would be:   Pick $$$i = 2$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_2 = \frac{4}{2} = 2$$$ and $$$a_1 = 6 \cdot 2 = 12$$$, making the array look as: [12, 2, 2].  Pick $$$i = 2$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_2 = \frac{2}{2} = 1$$$ and $$$a_1 = 12 \cdot 2 = 24$$$, making the array look as: [24, 1, 2].  Pick $$$i = 3$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_3 = \frac{2}{2} = 1$$$ and $$$a_1 = 24 \cdot 2 = 48$$$, making the array look as: [48, 1, 1]. The final answer $$$48 + 1 + 1 = 50$$$.In the third example test case there is no way to change the sum of elements, so the answer is $$$10$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my @A;

	my @copy = @_;

	my @remain;

	for my $i ( @copy ){
		my $two = 0;
		while( $i % 2 == 0 ){
			$i /= 2;
			$two ++;
			}

		push @A, $two;
		push @remain, $i;
		}

	my $sum_twos = 0;

	$sum_twos += $_ for @A;

	my $pow_twos = 2 ** $sum_twos;

	my $sum_remain = 0;

	$sum_remain += $_ for @remain;

	my @cand;

	for my $i ( 0 .. @_ - 1 ){
		push @cand, $sum_remain - $remain[ $i ] + $remain[ $i ] * $pow_twos;
		}

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


Polycarp has a string $$$s$$$. Polycarp performs the following actions until the string $$$s$$$ is empty ($$$t$$$ is initially an empty string):  he adds to the right to the string $$$t$$$ the string $$$s$$$, i.e. he does $$$t = t + s$$$, where $$$t + s$$$ is a concatenation of the strings $$$t$$$ and $$$s$$$;  he selects an arbitrary letter of $$$s$$$ and removes from $$$s$$$ all its occurrences (the selected letter must occur in the string $$$s$$$ at the moment of performing this action). Polycarp performs this sequence of actions strictly in this order.Note that after Polycarp finishes the actions, the string $$$s$$$ will be empty and the string $$$t$$$ will be equal to some value (that is undefined and depends on the order of removing).E.g. consider $$$s$$$="abacaba" so the actions may be performed as follows:  $$$t$$$="abacaba", the letter 'b' is selected, then $$$s$$$="aacaa";  $$$t$$$="abacabaaacaa", the letter 'a' is selected, then $$$s$$$="c";  $$$t$$$="abacabaaacaac", the letter 'c' is selected, then $$$s$$$="" (the empty string). You need to restore the initial value of the string $$$s$$$ using only the final value of $$$t$$$ and find the order of removing letters from $$$s$$$.

The first line contains one integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Then $$$T$$$ test cases follow. Each test case contains one string $$$t$$$ consisting of lowercase letters of the Latin alphabet. The length of $$$t$$$ doesn't exceed $$$5 \cdot 10^5$$$. The sum of lengths of all strings $$$t$$$ in the test cases doesn't exceed $$$5 \cdot 10^5$$$.

For each test case output in a separate line:   $$$-1$$$, if the answer doesn't exist;  two strings separated by spaces. The first one must contain a possible initial value of $$$s$$$. The second one must contain a sequence of letters — it's in what order one needs to remove letters from $$$s$$$ to make the string $$$t$$$. E.g. if the string "bac" is outputted, then, first, all occurrences of the letter 'b' were deleted, then all occurrences of 'a', and then, finally, all occurrences of 'c'. If there are multiple solutions, print any one.

7
abacabaaacaac
nowyouknowthat
polycarppoycarppoyarppyarppyrpprppp
isi
everywherevrywhrvryhrvrhrvhv
haaha
qweqeewew

abacaba bac
-1
polycarp lcoayrp
is si
everywhere ewyrhv
-1
-1

NoteThe first test case is considered in the statement.

#!/usr/bin/perl
use Data::Dumper;
use integer;   ### important!

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

while( $tcase -- > 0 ){
  my $t = <STDIN>;
  $t =~ s/[\x00-\x20]+$//ios;

  my @seq = ();
  my %lc = ();
  for(my $i=length($t)-1;$i>=0;$i--){
    my $c1 = substr($t,$i,1);
    unshift(@seq,$c1) if $lc{$c1} - 0 == 0;
    $lc{$c1}++;
  }
  my $er = undef;
  my $initl = 0;
  for(my $i=0;$i<=$#seq;$i++){
    if( $lc{$seq[$i]} % (1+$i) != 0 ){
      $er=1; last;
    }
    $lc{$seq[$i]} /= (1+$i);
    $initl += $lc{$seq[$i]};
  }
  if( $er ){ print "-1\n"; next; }
  my $st = substr($t,0,$initl);
  my $s = $st;
  my $ch = $t;
  for(my $i=0;$i<=$#seq;$i++){
    if( substr($ch,0,length($s)) ne $s ){
      $er = 1; last;
    }
    substr($ch,0,length($s)) = '';
    $s =~ s/$seq[$i]//ig;
  }
  if( $er || ( $ch ne '' and $s eq '' ) ){ print "-1\n"; next; }
  print ( $st . " " . join('',@seq) . "\n" );
}

exit(0);


The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of boys. The second line contains sequence a1, a2, ..., an (1 ≤ ai ≤ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≤ m ≤ 100) — the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≤ bj ≤ 100), where bj is the j-th girl's dancing skill.

Print a single number — the required maximum possible number of pairs.

use 5.016;
use strict;
use warnings;

<>;
my @boys = sort { $a <=> $b } split ' ', <>;
<>;
my @girls = sort { $a <=> $b } split ' ', <>;

my $c = 0;

while (@boys && @girls) {
  if (abs($boys[0] - $girls[0]) <= 1) {
    shift @boys;
    shift @girls;
    $c++;
  } elsif ($boys[0] < $girls[0]) {
    shift @boys;
  } else {
    shift @girls;
  }
}

say $c;


Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur.Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word "Bulbasaur" (without quotes) and sticks it on his wall. Bash is very particular about case — the first letter of "Bulbasaur" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word "Bulbasaur" from the newspaper.Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?Note: uppercase and lowercase letters are considered different.

Input contains a single line containing a string s (1  ≤  |s|  ≤  105) — the text on the front page of the newspaper without spaces and punctuation marks. |s| is the length of the string s. The string s contains lowercase and uppercase English letters, i.e. .

Output a single integer, the answer to the problem.

NoteIn the first case, you could pick: Bulbbasaur.In the second case, there is no way to pick even a single Bulbasaur.In the third case, you can rearrange the string to BulbasaurBulbasauraddrgndgddgargndbb to get two words "Bulbasaur".

use warnings;

sub min {
	my $ans = $_[0];

	foreach my $i (@_) {
		if ($ans > $i) {
			$ans = $i;
		}
	}

	return $ans;
}

my @fr = (0) x 128;

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

for (my $i = 0; $i < length $text; ++$i) {
	++$fr[ord(substr($text, $i, 1))];
#	print substr($text, $i, 1);
}

printf("%d", min($fr[ord('B')], $fr[ord 'a']/2, $fr[ord 'b'], $fr[ord 's'], $fr[ord 'l'], $fr[ord 'r'], $fr[ord 'u']/2));

use warnings;

use v5.20;

my @frecv;
my @word = ('B','u','l','b','a','s','a','u','r');
my $solution = 1000000;

my $input = <STDIN>;
chomp $input;
my @chars = split("", $input);

for(my $i = 0; $i < length $input; $i += 1){
    my $c = ord($chars[$i]);
    $frecv[$c]++;
}

for(my $i = 0; $i < 9; $i += 1){
    my $c = $word[$i];
    my $poz = ord($word[$i]);
    unless(defined $frecv[$poz]) {
        $solution = 0;
        last;
    }
    if($c eq 'a' || $c eq 'u'){
        if(int($frecv[$poz] / 2) < $solution){
            $solution = int($frecv[$poz] / 2);
        }
    }
    elsif($frecv[$poz] < $solution){
        $solution = $frecv[$poz];
    }

}
print("$solution\n");

# Find out how many Bulbasaurs we can catch
# Solution:
use strict;
use warnings;
my $newspaper = <>;
my %letter;
my $bulbies = 0;
foreach(split//,$newspaper)
{
	if(exists($letter{$_}))
	{
		$letter{$_} += 1;
		if($bulbies < $letter{$_})
		{
			$bulbies = $letter{$_};
		}
	}
	else
	{
		$letter{$_} = 1;
		if($bulbies == 0)
		{
			$bulbies = 1;
		}
	}
}
if(exists($letter{"a"}))
{
	$letter{"a"} = int($letter{"a"}/2);
}
if(exists($letter{"u"}))
{
	$letter{"u"} = int($letter{"u"}/2);
}
foreach(split//,"Bulbasr")
{
	if(exists($letter{$_}))
	{
		if($bulbies > $letter{$_})
		{
			$bulbies = $letter{$_}
		}
	}
	else
	{
		$bulbies = 0;
	}
}
print int($bulbies);

use feature "say";

$text = <>;
@matches;
@target = ( "B", "u", "l", "b", "a", "s", "r" );
for ($i = 0; $i < scalar ( @target ); ++$i) {
	$matches[$i] = () = $text =~ /$target[$i]/g;
}
$matches[1] /= 2;
$matches[4] /= 2;
@matches = sort( { $a <=> $b } @matches );
say int $matches[0];

#!/usr/bin/perl

use strict;
use warnings;

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

my %validLetters = ('B' => 0, 'u' => 0, 'l' => 0, 'b' => 0, 'a' => 0, 's' => 0, 'r' => 0);
for (my $i = 0; $i < length($string); $i++) {
  my $char = substr($string, $i, 1);
  if (exists($validLetters{$char})) {
    $validLetters{$char} += 1;
  }
}

my $count = 0;

my $possible = 1;
while ($possible) {
  foreach my $key (keys(%validLetters)) {
    if ($key eq 'a' || $key eq 'u') {
      if ($validLetters{$key} < 2) {
        $possible = 0;
      } else {
        $validLetters{$key} -= 2;
      }
    } else {
      if ($validLetters{$key} < 1) {
        $possible = 0;
      } else {
        $validLetters{$key} -= 1;
      }
    }
  }

  if ($possible) {
    $count++;
  }
}

print $count, "\n";

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	chomp;
	my %h;

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

	my @occ;

	push @occ, 2 * $h{ $_ } for split //, 'Blbsr';
	push @occ, $h{ $_ } for split //, 'au';

	my $min = ( sort { $a <=> $b } @occ )[ 0 ];
	print int $min / 2;

	}

use v5.20;
use warnings;

sub min {
	my $ret = $_[0];
	foreach my $it (@_) {
		if ($ret > $it) {
			$ret = $it;
		}
	}
	return $ret;
}

my @fr = (0) x 300;

$_ = <>;

foreach my $it (split '') {
	$fr[ord $it] += 1;
}

say min($fr[ord 'B'],int ($fr[ord 'a']/2),$fr[ord 'b'],$fr[ord 's'],$fr[ord 'l'],$fr[ord 'r'],int ($fr[ord 'u']/2));

use v5.20;

sub minn {
	my ($a, $b) = @_;
	if ($a < $b) {
		return $a;
	}
	return $b;
}

my $target = "uaBlbsr";
my %ap = map { $_ => 0 } (0..length($target));

my $text = <>;
for (my $i = 0; $i < length $text; $i++) {
	my $ind = index($target, substr($text, $i, 1));
	if ($ind != -1) {
		$ap{$ind}++;
	}
}

my $mn = int(minn($ap{0} / 2, $ap{1} / 2));
for (my $i = 2; $i < length $target; $i++) {
	$mn = minn($mn, $ap{$i});
}

say $mn;

#use v5.24;
use warnings;
my %fr;

my $line=<stdin>;
chomp($line);
my @word=split(//,$line);
for (my $i=ord("A");$i<=ord("z");$i++){
	$fr{chr($i)}=0;
}
foreach my $lit (@word){
	$fr{$lit}++;
}
$fr{"u"}=int $fr{"u"}/2;
$fr{"a"}=int $fr{"a"}/2;
my @key=("B","u","l","b","a","s","a","u","r");
my $min=100006;
foreach my $lit (@key){
	if ($min>$fr{$lit}) {$min=$fr{$lit}};
}
print $min;
<stdin>;
exit(0);

#Bulbasaur

use v5.20.1;
use warnings;

=pod
my $filename = "date.in";
open(my $fh, '<:encoding(UTF-8)', $filename)
	or die "Could not open the file";
=cut

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

my @input = split('', $line);

my %letters = (

	'B' => 0,
	'u' => 0,
	'l' => 0,
	'b' => 0,
	'a' => 0,
	's' => 0,
	'r' => 0,

);

for(my $i = 0; $i < @input; $i++){

	if( index("Bulbasr", $input[$i]) != -1 ){

		$letters{$input[$i]}++;

	}

}

my $mini = 100002;

while(my ($key, $value) = each(%letters)){

	if( ($key eq 'a' || $key eq 'u') && int($value/2) < $mini ){

		$mini = int($value/2);

	}elsif($key ne 'a' && $key ne 'u' && $value < $mini){

		$mini = $value;

	}

}

say $mini;

$w = "Bulbbasaur";
$h{$_} = 0 for split //, $w;
while ( sysread(STDIN, $c, 1) ) {
	$n = () = $w =~ /$c/g;
	if ($n) {
		$h{$c} += 1/$n;
	}
}
@ans = sort {$a <=> $b} values %h;
$ans = $ans[0] || 0;
print $ans;

while ( sysread(STDIN, $c, 1) ) {
	$n = () = "Bulbasaur" =~ /$c/g;
	if ($n) {
		$h{$c} += 1/$n;
	}
}
@ans = sort {$a <=> $b} values %h;
$ans = $ans[0] || 0;
print $ans;

# Find the biggest subarray with GCD higher than 1
# Solution: http://codeforces.com/problemset/submission/757/55701579
my $poke_nr = <>;
my %pokemons;
my @numbers = split(" ", <>);
my $biggest_poke = 0;
my $max_poke = 0;
my $current_max = 0;
foreach(@numbers)
{
	if(exists($pokemons{$_}))
	{
		$pokemons{$_} = $pokemons{$_} + 1;
	}
	else
	{
		$pokemons{$_} = 1;
		if($_ > $biggest_poke)
		{
			$biggest_poke = $_;
		}
	}
}
foreach my $i(2 .. $biggest_poke)
{
	$current_max = 0;
	for(my $j = $i; $j <= $biggest_poke; $j += $i)
	{
		if(exists($pokemons{$j}))
		{
			$current_max += $pokemons{$j};
		}
	}
	if($current_max > $max_poke)
	{
		$max_poke = $current_max;
	}
}
if($max_poke > 0)
{
	print $max_poke;
}
else
{
	if(exists($pokemons{1}))
	{
		print 1;
	}
	else
	{
		print 0;
	}

}

# Find out how many Bulbasaurs we can catch
# Solution:
use strict;
use warnings;
my $newspaper = <>;
my %letter;
my $bulbies = 0;
foreach(split//,$newspaper)
{
	if(exists($letter{$_}))
	{
		$letter{$_} = $letter{$_} + 1;
		if($bulbies < $letter{$_})
		{
			$bulbies = $letter{$_};
		}
	}
	else
	{
		$letter{$_} = 1;
		if($bulbies == 0)
		{
			$bulbies = 1;
		}
	}
}
foreach(split//,"Bulbasr")
{
	if(exists($letter{$_}))
	{
		if($_ eq "a" or $_ eq "b"){
			if($bulbies > $letter{$_} / 2)
			{
				$bulbies = $letter{$_} / 2;
			}
		}
		else
		{
			if($bulbies > $letter{$_})
			{
				$bulbies = $letter{$_}
			}
		}
	}
	else
	{
		$bulbies = 0;
	}
}
print $bulbies;

$,=" ";

my %c;
map {$c{$_}++ }split //, "Bulbasaur";
my %d;

my $w=<>;
chomp($w);
map {$d{$_}++ }split //, $w;
for my $t (keys %c)
{
$d{$t}=int($d{$t}/$c{$t});
}

print min(values %d) , "\n";

sub min
{
my $ans=shift;
while(@_)
{
my $temp=shift;
$ans=$temp if($ans>$temp);
}
return $ans;
}

$_ = <>;
$B = 'Bulbasaur' x 2e1;
$i += $c eq 'B' while ($c = chop $B) && s/$c//;
print 0 + $i

$B = 'Bulbasaur' x 2e4;
$i += $c eq 'B' while ($c = chop $B) && s/$c//;
print 0 + $i

use v5.20;
my $buffer = <>;
chomp( $buffer );
my @arr = split //, $buffer;
my @fv = ();
for( my $i = 0 ; $i < length $buffer ; $i++ ) {
	$fv [$arr[ $i ]] ++;
}
my $ans = @fv[ ord('B') ];
$ans = $ans <= $fv[ ord('u') ] / 2 ? $ans : $fv[ ord('u') ] / 2;
$ans = $ans <= $fv[ ord('l') ] ? $ans : $fv[ ord('l') ];
$ans = $ans <= $fv[ ord('b') ] ? $ans : $fv[ ord('b') ];
$ans = $ans <= $fv[ ord('a') ] / 2 ? $ans : $fv[ ord('a') ] / 2;
$ans = $ans <= $fv[ ord('s') ] ? $ans : $fv[ ord('s') ];
$ans = $ans <= $fv[ ord('r') ] ? $ans : $fv[ ord('r') ];
say int($ans);

use v5.20;
use warnings;

sub min {
	my $ret = shift @_;
	foreach my $it (@_) {
		if ($ret > $it) {
			$ret = $it;
		}
	}
	return $ret;
}

my @fr = (0) x 300;

$_ = <>;

foreach my $it (split '') {
	$fr[ord $it] += 1;
}

say min($fr[ord 'B'],int ($fr[ord 'a']/2),$fr[ord 'b'],$fr[ord 's'],$fr[ord 'l'],$fr[ord 'r'],int ($fr[ord 'u']));

use v5.20;

sub minn {
	my ($a, $b) = @_;
	if ($a < $b) {
		return $a;
	}
	return $b;
}

my $target = "uaBlbsr";
my %ap = map { $_ => 0 } (0..length($target));

my $text = <>;
for (my $i = 0; $i < length $text; $i++) {
	my $ind = index($target, substr($text, $i, 1));
	if ($ind != -1) {
		$ap{$ind}++;
	}
}

my $mn = minn($ap{0} / 2, $ap{1} / 2);
for (my $i = 2; $i < length $target; $i++) {
	$mn = minn($mn, $ap{$i});
}

say $mn;

#use v5.24;
use warnings;
my %fr;

my $line=<stdin>;
chomp($line);
my @word=split(//,$line);
for (my $i=ord("A");$i<=ord("z");$i++){
	$fr{chr($i)}=0;
}
foreach my $lit (@word){
	$fr{$lit}++;
}
my @key=("B","u","l","b","a","s","a","u","r");
my $min=100006;
foreach my $lit (@key){
	if ($min>$fr{$lit}) {$min=$fr{$lit}};
}
print $min;
<stdin>;
exit(0);

#Bulbasaur

use v5.20.1;
use warnings;

=pod
my $filename = "date.in";
open(my $fh, '<:encoding(UTF-8)', $filename)
	or die "Could not open the file";
=cut

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

my @input = split('', $line);

my %letters = (

	'B' => 0,
	'u' => 0,
	'l' => 0,
	'b' => 0,
	'a' => 0,
	's' => 0,
	'r' => 0,

);

for(my $i = 0; $i < @input; $i++){

	if( index("Bulbasr", $input[$i]) != -1 ){

		$letters{$input[$i]}++;

	}

}

my $mini = 100002;

while(my ($key, $value) = each(%letters)){

	if( ($key eq 'a' || $key eq 'u') && $value/2 < $mini ){

		$mini = $value/2;

	}elsif($key ne 'a' && $key ne 'u' && $value < $mini){

		$mini = $value;

	}

}

say $mini;


Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.

The first line contains integer n (1 ≤ n ≤ 100) — the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the coins' values. All numbers are separated with spaces.

In the single line print the single number — the minimum needed number of coins.

NoteIn the first sample you will have to take 2 coins (you and your twin have sums equal to 6, 0 correspondingly). If you take 1 coin, you get sums 3, 3. If you take 0 coins, you get sums 0, 6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.In the second sample one coin isn't enough for us, too. You can pick coins with values 1, 2 or 2, 2. In any case, the minimum number of coins equals 2.

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

chomp($n = <>);
@a = sort { $b<=>$a } split / /, <>;
$tot += $_ foreach (@a);
$ans = 0;
$tmp = 0;
foreach (@a) {
	$tmp += $_;
	++$ans;
	$tmp>$tot-$tmp and last;
}
say $ans;

#!/usr/bin/perl

use 5.012;
use warnings;

my $n = <>;
chomp(my $s = <>);
my @c = split / /, $s;
@c = sort { $b <=> $a } @c;

sub sum {
	my $ref = shift;
	my $sum;
	$sum += $_ for @$ref;
	return $sum;
}

my $cnt = 0;
my $sum = 0;
while ($sum <= sum \@c) {
	$sum += shift @c;
	$cnt++;
	last unless @c;
}
print $cnt;

my $n = <>;
my @arr = reverse sort { $a <=> $b } split " ", <>;
my ($mid, $ans, $sum) = (0, 0, 0);
$mid += $_ foreach(@arr);
$mid = int($mid / 2);

foreach(@arr) {
    $sum += $_;
    $ans++;
    last if ($sum > $mid);
}
print "$ans\n";

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

#print $c;

@c=split ' ',$c;

#print @c;

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

foreach (@c)
{
    $sum+=$_;
}
$mid=$sum/2;

#print $mid;
#print @c;
$myC=1;

foreach(@c)
{
    $me+=$_;
    if ($me>$mid)
    {
        print $myC;
        exit;
    }
    $myC++;
}

#!/usr/bin/perl
# Codeforces Practice - 160A Twins
use warnings;
use strict;

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

my @coins = split(" ",<STDIN>);
my $sum = 0;
$sum += $_ for @coins;

@coins = sort {$b<=>$a} @coins;

my $sum2 = 0;
for(my $i = 1; @coins > 0; $i++){
    my $temp = shift @coins;
    $sum2 += $temp;
    $sum -= $temp;
    if($sum2>$sum){
        print $i;
        last;
    }
}

#!/usr/bin/perl -w

use strict;

my $n = <>;
my @x = sort { $a <=> $b } split ' ', <>;
my $s = 0;
$s += $_ for @x;
my $t = 0;
$t += pop @x while $t * 2 <= $s;
print $n - @x, "\n";

chomp($n = <STDIN>);
chomp($l = <STDIN>);

@coins = split /\s+/, $l;
@coins = sort { $b <=> $a } @coins;

$total = 0;
map { $total += $_; } @coins;
$taken_sum = 0;
$taken = 0;
while($taken_sum <= ($total - $taken_sum)) {
	$taken_sum += shift @coins;
	$taken++;
#	print "after taking $taken coins we have ".$taken_sum." and there's ".($total-$taken_sum)." left\n";
}

print "$taken\n";

use strict;
use warnings;

my $n = <>;
my @a = sort {$b <=> $a} split ' ', <>;
my $sum = 0;
for (@a) {
    $sum += $_;
}

my $res = 0;
my $curr = 0;

for (@a) {
    $res++;
    $curr += $_;
    last if (2*$curr > $sum);
}

print "$res\n";

<STDIN>;
@num = sort { $b <=> $a } split(/ +/, <STDIN>);

$s = $sum = $count = 0;
foreach(@num) { $sum += $_ }

foreach(@num)
{
	$s += $_;
	++$count;
	last if ($s > $sum / 2);
}

print $count;

#!/bin/perl

$n = <STDIN>;

$inpt = <STDIN>;
chomp $inpt;

@nums = split / +/, $inpt;
@nums = sort {$b <=> $a} @nums;

$s = 0;

for($i=0;$i<@nums;$i++)
{

  $s += @nums[$i];

}

$s /= 2;

$s2 = 0;
$it = 0;

while( $s2 <= $s )
{

  $s2 += @nums[$it];
  $it++;

}

print $it;

sub TakeInput
{
    $n = <STDIN>;
    $values = <STDIN>;
    @values = split(" ",$values);
    return @values;
}

sub sortArray
{
    @Array = @_;
    $l = @Array;
    for($i=0;$i<$l;$i++)
    {
        for($j=0;$j<($l-$i);$j++)
        {
            if(@Array[$j+1]>@Array[$j])
            {

                $tmp = @Array[$j];
                @Array[$j] = @Array[$j+1];
                @Array[$j+1] = $tmp;
            }
        }
    }
    return @Array;
}
sub sum
{
    my @Array = @_;
    my $l = @Array;
    $sm = 0;
    for($i=0;$i<$l;$i++)
    {

        $sm = $sm+@Array[$i];

    }
    return $sm;
}

@values = TakeInput();
@sorted = sortArray(@values);
$l = @sorted;
$flag = 0;
while($flag==0)
{

    for($counter=0;$counter<$l-1;$counter++)
    {

        @list1 = @sorted[0..$counter];
        @list2 = @sorted[$counter+1..$l-1];
        $s1 = sum(@list1);
        $s2 = sum(@list2);
        if($s1>$s2)
        {
            $v =  scalar @list1;
            print $v;
            $flag = 1;
            last;
        }

    }

    if($flag == 0)
    {
        print scalar @sorted;
        $flag = 1;
    }
}

my $num = <>;
my $coin = <>;
chomp $coin;
my @coin = sort {$b<=>$a} split / /, $coin;
my $sum=0;
$sum += $_ foreach @coin;
my $count;
my $val=0;
until ($val > $sum/2) {
    $count++;
    $val += shift @coin;
}
print $count;

#!/usr/bin/perl

use 5.012;
use warnings;

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

$s =~ /((.)\1)/;
say $2;

my $n = <>;
my @arr = reverse sort split " ", <>;
my ($mid, $ans, $sum) = (0, 0, 0);
$mid += $_ foreach(@arr);
$mid = int($mid / 2);

foreach(@arr) {
    $sum += $_;
    $ans++;
    last if ($sum > $mid);
}
print $ans . "\n";

#!/usr/bin/perl
# Codeforces Practice - 160A Twins
use warnings;
use strict;

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

my @coins = split(" ",<STDIN>);
my $sum = 0;
$sum += $_ for @coins;

@coins = sort {$b<=>$a} @coins;

print "@coins\n";

my $sum2 = 0;
for(my $i = 1; @coins > 0; $i++){
    my $temp = shift @coins;
    $sum2 += $temp;
    $sum -= $temp;
    if($sum2>$sum){
        print $i;
        last;
    }
}

#!/usr/bin/perl -w

use strict;

my $n = <>;
my @x = sort split ' ', <>;
my $s = 0;
$s += $_ for @x;
my $t = 0;
$t += pop @x while $t * 2 <= $s;
print $n - @x, "\n";

chomp($n = <STDIN>);
chomp($l = <STDIN>);

@coins = split /\s+/, $l;
sort { $b <=> $a } @coins;

$total = 0;
map { $total += $_; } @coins;
$taken_sum = 0;
$taken = 0;
while($taken_sum <= ($total - $taken_sum)) {
	$taken_sum += shift @coins;
	$taken++;
}

print "$taken\n";

use strict;
use warnings;

my $n = <>;
my @a = split ' ', <>;
my $sum = 0;
for (@a) {
    $sum += $_;
}

my $res = 0;
my $curr = 0;

for (@a) {
    last if (2*$curr > $sum);
    $res++;
    $curr += $_;
}

print "$res\n";

use strict;
use warnings;

my $n = <>;
my @a = reverse sort split ' ', <>;
my $sum = 0;
for (@a) {
    $sum += $_;
}

my $res = 0;
my $curr = 0;

for (@a) {
    last if (2*$curr > $sum);
    $res++;
    $curr += $_;
}

print "$res\n";

<STDIN>;
@num = reverse sort split(/ +/, <STDIN>);
$s = $sum = $count = 0;
foreach(@num) { $sum += $_ }

foreach(@num)
{
    $s += $_;
    ++$count;
    if ($s < $sum / 2) { last; }
}

print STDOUT $count;

<STDIN>;
@num = reverse sort split(/ +/, <STDIN>);
$s = $sum = $count = 0;
foreach(@num) { $sum += $_ }

foreach(@num)
{
    $s += $_;
    ++$count;
    if ($s > $sum / 2) { last; }
}

print STDOUT $count;

sub TakeInput
{
    $n = <STDIN>;
    $values = <STDIN>;
    @values = split(" ",$values);
    return @values;
}

sub sortArray
{
    @Array = @_;
    $l = @Array;
    for($i=0;$i<$l;$i++)
    {
        for($j=0;$j<($l-$i);$j++)
        {
            if(@Array[$j+1]>@Array[$j])
            {

                $tmp = @Array[$j];
                @Array[$j] = @Array[$j+1];
                @Array[$j+1] = $tmp;
            }
        }
    }
    return @Array;
}
sub sum
{
    @Array = @_;
    my $l = @Array;
    $sum = 0;
    for($i=0;$i<$l;$i++)
    {
        $sum = $sum+@Array[i];
    }
    return $sum;
}
@values = TakeInput();
@sorted = sortArray(@values);
$l = @sorted;
$flag = 0;
while($flag==0)
{

    for($counter=0;$counter<$l-1;$counter++)
    {

        @list1 = @sorted[0..$counter];
        @list2 = @sorted[$counter+1..$l-1];
        $s1 = sum(@list1);
        $s2 = sum(@list2);
        if($s1>$s2)
        {
            print scalar @list1;
            $flag = 1;
        }

    }

    if($flag == 0)
    {
        print scalar @sorted;
        $flag = 1;
    }
}

sub TakeInput
{
    $n = <STDIN>;
    $values = <STDIN>;
    @values = split(" ",$values);
    return @values;
}

sub sortArray
{
    @Array = @_;
    $l = @Array;
    for($i=0;$i<$l;$i++)
    {
        for($j=0;$j<($l-$i);$j++)
        {
            if(@Array[$j+1]>@Array[$j])
            {

                $tmp = @Array[$j];
                @Array[$j] = @Array[$j+1];
                @Array[$j+1] = $tmp;
            }
        }
    }
    return @Array;
}
sub sum
{
    @Array = @_;
    my $l = @Array;
    $sum = 0;
    for($i=0;$i<$l;$i++)
    {
        $sum = $sum+@Array[i];
    }
    return $sum;
}
@values = TakeInput();
@sorted = sortArray(@values);
$l = @sorted;
$flag = 0;
while($flag==0)
{

    for($counter=0;$counter<$l-1;$counter++)
    {

        @list1 = @sorted[0..$counter];
        @list2 = @sorted[$counter+1..$l-1];
        $s1 = sum(@list1);
        $s2 = sum(@list2);
        if($s1>$s2)
        {

            $v =  scalar @list1;
            print $v + 1;
            $flag = 1;
            last;
        }

    }

    if($flag == 0)
    {
        print scalar @sorted;
        $flag = 1;
    }
}

my $num = <>;
my $coin = <>;
chomp $coin;
my @coin = reverse sort split / /, $coin;
my $sum;
$sum += $_ foreach @coin;
my $count;
my $val=0;
until ($val > $sum/2) {
    $count++;
    $val += shift @coin;
}
print $count;


Pashmak has fallen in love with an attractive girl called Parmida since one year ago...Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.

The first line contains four space-separated x1, y1, x2, y2 ( - 100 ≤ x1, y1, x2, y2 ≤ 100) integers, where x1 and y1 are coordinates of the first tree and x2 and y2 are coordinates of the second tree. It's guaranteed that the given points are distinct.

If there is no solution to the problem, print -1. Otherwise print four space-separated integers x3, y3, x4, y4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them.  Note that x3, y3, x4, y4 must be in the range ( - 1000 ≤ x3, y3, x4, y4 ≤ 1000).


You're given an array $$$b$$$ of length $$$n$$$. Let's define another array $$$a$$$, also of length $$$n$$$, for which $$$a_i = 2^{b_i}$$$ ($$$1 \leq i \leq n$$$). Valerii says that every two non-intersecting subarrays of $$$a$$$ have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers $$$l_1,r_1,l_2,r_2$$$ that satisfy the following conditions:   $$$1 \leq l_1 \leq r_1 \lt l_2 \leq r_2 \leq n$$$;  $$$a_{l_1}+a_{l_1+1}+\ldots+a_{r_1-1}+a_{r_1} = a_{l_2}+a_{l_2+1}+\ldots+a_{r_2-1}+a_{r_2}$$$. If such four integers exist, you will prove Valerii wrong. Do they exist?An array $$$c$$$ is a subarray of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of every test case contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$). The second line of every test case contains $$$n$$$ integers $$$b_1,b_2,\ldots,b_n$$$ ($$$0 \le b_i \le 10^9$$$).

For every test case, if there exist two non-intersecting subarrays in $$$a$$$ that have the same sum, output YES on a separate line. Otherwise, output NO on a separate line.  Also, note that each letter can be in any case.

NoteIn the first case, $$$a = [16,8,1,2,4,1]$$$. Choosing $$$l_1 = 1$$$, $$$r_1 = 1$$$, $$$l_2 = 2$$$ and $$$r_2 = 6$$$ works because $$$16 = (8+1+2+4+1)$$$.In the second case, you can verify that there is no way to select to such subarrays.


Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:  there wouldn't be a pair of any side-adjacent cards with zeroes in a row;  there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.

The first line contains two integers: n (1 ≤ n ≤ 106) — the number of cards containing number 0; m (1 ≤ m ≤ 106) — the number of cards containing number 1.

In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.


ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?

NoteNote that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.O+|+XXO|XXOX|OOXX|OXOO|OOOO|XX

$sum = "";
foreach $s (<STDIN>) {
  if ($s =~ /\|/) {
    $sum = $sum . $s;
  }
}
if ($sum =~ /OO/) {
  print "YES\n";
  $sum =~ s/OO/\+\+/;
  print $sum;
} else {
  print "NO\n";
}

use warnings;
#use FileHandle;

#my $in = FileHandle->new("input.txt", "r");
#my $out = FileHandle->new("output.txt", "w");

sub solve {
	my $in = shift;
	my $out = shift;
	my $n = <$in>;
	my ($str, $str1, $str2, $yes);
	my @mas;
	$yes = 0;

	for my $i (0..$n - 1){
		$str = <$in>;
		$str1 = substr($str, 0, 2);
		if (($yes == 0) and ($str1 eq 'OO')){
			$yes = 1;
			$str1 = '++';
		}
		$str2 = substr($str, 3, 2);
		if (($yes == 0) and ($str2 eq 'OO')){
			$yes = 1;
			$str2 = '++';
		}

		push(@mas, $str1 . '|' . $str2 . "\n");
	}

	if ($yes == 1){
		print $out "YES\n";
	} else {
		print $out "NO\n";
		return 1;
	}

	for (@mas){
		print $out $_;
	}
	return 1;
}

solve(STDIN, STDOUT);

1;

use 5.020;
use warnings;
<>;
undef $/;
$_ = <>;
if (s/OO/++/) {
  say 'YES';
  say;
}
else { say 'NO' }

my $n = <>;
my @pairs;
for (1..$n) {
    my $line = <>;
    chomp $line;
    push @pairs, [split /\|/, $line];
}
my $ok = 0;

OUTER: for my $pair (@pairs) {
    for my $seats (@$pair) {
        if ($seats eq 'OO') {
            $seats = '++';
            $ok = 1;
            last OUTER;
        }
    }
}

if (!$ok) {
    print "NO\n";
    exit;
}

print "YES\n";
$, = "\n";
$\ = "\n";
print map { join "|", @$_ } @pairs;

use strict;
use warnings;

use Data::Dumper;

my $in = <>;
chomp $in;

my $n = $in;
die('invalid size') unless $n>=1 and $n<=1000;
my $bus = [];
foreach my $row (0..$in-1) {
  $in = <>;
  chomp $in;
  push(@$bus, $in);
}

my $can_sit_together = find_seats($bus);
if ($can_sit_together) {
  print "YES\n";
  print_bus($bus);
} else {
  print "NO\n";
}

sub find_seats {
  my $bus = shift;
  foreach my $bus_row (@$bus) {
    my @row = split(//, $bus_row);
    if ($row[0] eq 'O' and $row[1] eq 'O') {
      $row[0] = $row[1] = '+';
      $bus_row = join('', @row);
      return 1;
    } elsif ($row[3] eq 'O' and $row[4] eq 'O') {
      $row[3] = $row[4] = '+';
      $bus_row = join('', @row);
      return 1;
    }
  }
  return 0;
}

sub print_bus {
  my $bus = shift;
  foreach my $row (@$bus) {
    print "$row\n";
  }
}

#!/usr/bin/env perl

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

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

# essential
my @tokens = ();

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

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

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

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

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

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

# solve

my $n = read_token;

my $answer = 'NO';

my $lines = [];

for (1..$n) {
    my $line = read_line;
    my ($left, $right) = split q/\|/, $line;
    $left = '++', $answer = 'YES' if $answer eq 'NO' and $left eq 'OO';
    $right = '++', $answer = 'YES' if $answer eq 'NO' and $right eq 'OO';
    push @$lines, join q{|}, ($left, $right);
}

say $answer;

exit(0) if $answer eq 'NO';

for (@$lines) {
    say $_;
}

#!/usr/bin/env perl

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

use Carp;

# essential
my @tokens = ();

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

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

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

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

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

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

sub ref_ref_scalar {
    my $ref = shift;
    return 1 if ref($ref) eq 'SCALAR';
}

sub toggle {
    my $ref = shift;
    croak '$ref does not reference to scalar' if !ref_ref_scalar($ref);

    $$ref = !$$ref;
}

# solve

my $n = read_token;

my $answer = 0;

my $lines = [];

for (1..$n) {
    my $line = read_line;
    my ($left, $right) = split q/\|/, $line;
    $left = '++', toggle(\$answer) if !$answer and $left eq 'OO';
    $right = '++', toggle(\$answer) if !$answer and $right eq 'OO';
    push @$lines, join q{|}, ($left, $right);
}

say 'NO' and exit(0) if !$answer;

say 'YES';
for (@$lines) {
    say $_;
}

use strict;
# cf711a # solution courtesy 20253198 rsFalse
<>;
$/='';
$_ = <>;
print s/OO/++/ ? "YES\n$_" : "NO";

use strict;

# cf711a
=item

A. Bus to Udayland
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.

ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?
Input

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of rows of seats in the bus.

Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.

Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.
Output

If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output).

If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line.

If there are multiple solutions, you may print any of them.
Examples
Input

6
OO|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX

Output

YES
++|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX

Input

4
XO|OX
XO|XX
OX|OX
XX|OX

Output

NO

Input

5
XX|XX
XX|XX
XO|OX
XO|OO
OX|XO
Output
YES
XX|XX
XX|XX
XO|OX
XO|++
OX|XO
Note
Note that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.
O+|+X
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
=cut

my $n=<>;
my @ls=<>;

my @rs;
my $qFound=0;
foreach my $l (@ls) {
  chomp $l;
  my @vs=split('',$l);
  if((!$qFound) && ($vs[0] eq 'O') && ($vs[1] eq 'O')) {
    $vs[0]=$vs[1]='+';
    $qFound=1;
  }
  if((!$qFound) && ($vs[3] eq 'O') && ($vs[4] eq 'O')) {
    $vs[3]=$vs[4]='+';
    $qFound=1;
  }
  push @rs,join('',@vs);
}
if($qFound) {
  print "YES\n";
  foreach my $r (@rs) {
    print $r,"\n";
  }
} else {
  print "NO\n";
}

use strict;
use warnings;

use Data::Dumper;

# rows 10
# per row: 2x2
# find to seats next to each other...

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

die('wrong number or rows') unless $n >=0 && $n <= 100;

# store input as array with length n * 2
# loop array, find first seat with OO.
# found: change 00 to ++
# exit and print result

my @buss;
my @left;
my @right;
for (0..$n-1) {
    my $in = <>;
    chomp($in);
    my @seats = split('\|', $in);
#    print Dumper \@seats;
    push @left, $seats[0];
    push @right, $seats[1];
}
@buss = (@left, @right);

for (@buss) {
    if ($_ eq 'OO') {
        print "YES\n";
        print_bus(\@buss, $n);
        exit;
    }
}
print "NO\n";

sub print_bus {
    my ($buss, $n) = @_;

    for (my $i=0; $i<$n; $i++) {
        my $row = $buss->[$i] . '|' . $buss->[$n + $i];
        print $row . "\n";
    }
}

use 5.020;
use warnings;
undef $/;
$_ = <>;
if (s/OO/++/) {
  say 'YES';
  say;
}
else { say 'NO' }

use strict;

# cf711a
=item

A. Bus to Udayland
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.

ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?
Input

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of rows of seats in the bus.

Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.

Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.
Output

If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output).

If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line.

If there are multiple solutions, you may print any of them.
Examples
Input

6
OO|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX

Output

YES
++|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX

Input

4
XO|OX
XO|XX
OX|OX
XX|OX

Output

NO

Input

5
XX|XX
XX|XX
XO|OX
XO|OO
OX|XO
Output
YES
XX|XX
XX|XX
XO|OX
XO|++
OX|XO
Note
Note that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.
O+|+X
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
=cut

my $n=<>;
my @ls=<>;

my @rs;
my $qFound=0;
foreach my $l (@ls) {
  chomp $l;
  my @vs=split('',$l);
  if((!$qFound) && ($vs[0] eq 'O') && ($vs[1] eq 'O')) {
    $vs[0]=$vs[1]='+';
    $qFound=1;
  }
  if((!$qFound) && ($vs[3] eq 'O') && ($vs[4] eq 'O')) {
    $vs[3]=$vs[4]='+';
    $qFound=1;
  }
  push @rs,join('',@vs);
}
print ($qFound ? "YES" : "NO");
print "\n";
foreach my $r (@rs) {
  print $r,"\n";
}

use strict;

# cf711a
=item

A. Bus to Udayland
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.

ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?
Input

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of rows of seats in the bus.

Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.

Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.
Output

If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output).

If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line.

If there are multiple solutions, you may print any of them.
Examples
Input

6
OO|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX

Output

YES
++|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX

Input

4
XO|OX
XO|XX
OX|OX
XX|OX

Output

NO

Input

5
XX|XX
XX|XX
XO|OX
XO|OO
OX|XO
Output
YES
XX|XX
XX|XX
XO|OX
XO|++
OX|XO
Note
Note that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.
O+|+X
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
=cut

my $n=<>;
my @ls=<>;

my @rs;
my $qFound=0;
foreach my $l (@ls) {
  chomp $l;
  my @vs=split('',$l);
  if((!$qFound) && ($vs[0] eq 'O') && ($vs[1] eq 'O')) {
    $vs[0]=$vs[1]='X';
    $qFound=1;
  }
  if((!$qFound) && ($vs[3] eq 'O') && ($vs[4] eq 'O')) {
    $vs[3]=$vs[4]='X';
    $qFound=1;
  }
  push @rs,join('',@vs);
}
print ($qFound ? "YES" : "NO");
print "\n";
foreach my $r (@rs) {
  print $r,"\n";
}


You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of points on the line. The second line contains n integers xi ( - 109 ≤ xi ≤ 109) — the coordinates of the given n points.

Print the only integer x — the position of the optimal point on the line. If there are several optimal points print the position of the leftmost one. It is guaranteed that the answer is always the integer.


A sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Given two integers $$$n$$$ and $$$k$$$, construct a permutation $$$a$$$ of numbers from $$$1$$$ to $$$n$$$ which has exactly $$$k$$$ peaks. An index $$$i$$$ of an array $$$a$$$ of size $$$n$$$ is said to be a peak if $$$1 < i < n$$$ and $$$a_i \gt a_{i-1}$$$ and $$$a_i \gt a_{i+1}$$$. If such permutation is not possible, then print $$$-1$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ lines follow, each containing two space-separated integers $$$n$$$ ($$$1 \leq n \leq 100$$$) and $$$k$$$ ($$$0 \leq k \leq n$$$) — the length of an array and the required number of peaks.

Output $$$t$$$ lines. For each test case, if there is no permutation with given length and number of peaks, then print $$$-1$$$. Otherwise print a line containing $$$n$$$ space-separated integers which forms a permutation of numbers from $$$1$$$ to $$$n$$$ and contains exactly $$$k$$$ peaks.  If there are multiple answers, print any.

NoteIn the second test case of the example, we have array $$$a = [2,4,1,5,3]$$$. Here, indices $$$i=2$$$ and $$$i=4$$$ are the peaks of the array. This is because $$$(a_{2} \gt a_{1} $$$, $$$a_{2} \gt a_{3})$$$ and $$$(a_{4} \gt a_{3}$$$, $$$a_{4} \gt a_{5})$$$.


Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.

The first line contains the single integer n (1 ≤ n ≤ 1000) — the number of contests where the coder participated. The next line contains n space-separated non-negative integer numbers — they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.

Print the single number — the number of amazing performances the coder has had during his whole history of participating in the contests.

NoteIn the first sample the performances number 2 and 3 are amazing.In the second sample the performances number 2, 4, 9 and 10 are amazing.

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

chomp(my $n = <STDIN>);
my @scores = split / /,<STDIN>;

my $min = $scores[0];
my $max = $scores[0];
my $count = 0;
foreach my $score (@scores) {
    if($score > $max){
        $max = $score;
        $count++;
    } elsif($score <$min){
        $min = $score;
        $count++;
    }
}
print $count;

#!/usr/bin/perl -w

use strict;

<>;
my @a = split ' ', <>;
my $max = shift @a;
my $min = $max;
my $amaze = 0;

for (@a) {
    if ($_ > $max) {
        $amaze++;
        $max = $_;
    } elsif ($_ < $min) {
        $amaze++;
        $min = $_;
    }
}

print $amaze, "\n";

$n=<>;
@array=split(' ',<>);
$maxi=$array[0];
$mini=$array[0];
$score=0;
for($i=1;$i<$n;$i++){
if($array[$i]>$maxi){
$maxi=$array[$i];
$score++;
}
elsif($array[$i]<$mini){
$mini=$array[$i];
$score++;
}
}
print $score;

#!perl

$n = <>;
@arr = split /\D/, <>;
$result = 0;
$min = $max = $arr[0];
for $i (1..$n-1) {
	if ($arr[$i] > $max) {
		$max = $arr[$i];
		$result++;
	} elsif ($arr[$i] < $min) {
		$min = $arr[$i];
		$result++;
	}
}
print $result;

$line = <>;
$line = <>;
chomp $line;
my $max, $min;
$ans = 0;
foreach my $num (split(/ /, $line)) {
    if (!defined($max)) {
        $max = $num;
        $min = $num;
    }
    if ($num > $max) {
        $ans++;
        $max = $num;
    }
    if ($num < $min) {
        $ans++;
        $min = $num;
    }
}
print "$ans\n";

<>;
my @score = grep /\w/, split ' ', <>;
my $count = 0;
my ($max, $min) = (0, 0);
foreach (1..$#score) {
    if ($score[$_] > $score[$max]) {
        $count++;
        $max = $_;
    } elsif ($score[$_] < $score[$min]) {
        $count++;
        $min = $_;
    }
}
print $count;

#!perl

$n = <>;
@arr = <>;
$result = 0;
$max = $min = $arr[0];
for $i (1..$n-1) {
	if ($arr[$i] > $max) {
		$max = $arr[$i];
		$result++;
	} elsif ($arr[$i] < $min) {
		$min = $arr[$i];
		$result++;
	}
}
print $result;

<>;
my @score = grep /\w/, split ' ', <>;
my $count;
my ($max, $min) = (0, 0);
foreach (1..$#score) {
    if ($score[$_] > $score[$max]) {
        $count++;
        $max = $_;
    } elsif ($score[$_] < $score[$min]) {
        $count++;
        $min = $_;
    }
}
print $count;


Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage.The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation).Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once.

The first line contains n and k (1 ≤ k ≤ n ≤ 105) — the number of online-courses and the number of main courses of Polycarp's specialty.  The second line contains k distinct integers from 1 to n — numbers of main online-courses of Polycarp's specialty.  Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≤ ti ≤ n - 1) — the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n — numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself.  It is guaranteed that the sum of all values ti doesn't exceed 105.

Print -1, if there is no the way to get a specialty.  Otherwise, in the first line print the integer m — the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers — numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them.

NoteIn the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.

use strict;
use warnings;

my ($n, $k) = map { 0 + $_ } split /\s+/, <>;
my @main_courses = map { 0 + $_ } split /\s+/, <>;

my @course_deps;
for (my $i = 0; $i < $n; $i++) {
	push @course_deps, [map { 0 + $_ } split /\s+/, <>];
	shift @{ $course_deps[$i] };
}

my %checked_deps;

my @seq; eval { resolve_deps(\@main_courses, \@seq) };
if ($@) {
	print "-1\n"
} else {
	print scalar @seq, "\n";
	print "@seq\n";
}

sub resolve_deps
{
	my ($deps_ref, $seq_ref) = @_;

	for (my $i = 0; $i < @{ $deps_ref }; $i++) {
		my $d = $deps_ref->[$i];

		if (not $checked_deps{$d}) {
			$checked_deps{$d} = 'inprogress';

			resolve_deps($course_deps[$d - 1], $seq_ref);
			push @{ $seq_ref }, $d;

			$checked_deps{$d} = 'resolved';
		}

		next if $checked_deps{$d} eq 'resolved';

		die "cycle detected for course $d\n"
			if $checked_deps{$d} eq 'inprogress'
	}
}


Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.There is a cursor pointing at some symbol of the string. Suppose that cursor is at position i (1 ≤ i ≤ n, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position i - 1 if i > 1 or to the end of the string (i. e. position n) otherwise. The same holds when he presses the right arrow key (if i = n, the cursor appears at the beginning of the string).When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.Initially, the text cursor is at position p. Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?

The first line contains two space-separated integers n (1 ≤ n ≤ 105) and p (1 ≤ p ≤ n), the length of Nam's string and the initial position of the text cursor. The next line contains n lowercase characters of Nam's string.

Print the minimum number of presses needed to change string into a palindrome.

NoteA string is a palindrome if it reads the same forward or reversed.In the sample test, initial Nam's string is:  (cursor position is shown bold).In optimal solution, Nam may do 6 following steps:The result, , is now a palindrome.


This is an interactive problem. In the output section below you will see the information about flushing the output.Bear Limak thinks of some hidden number — an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.Integer x > 1 is called prime if it has exactly two distinct divisors, 1 and x. If integer x > 1 is not prime, it's called composite.You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2, 100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.When you are done asking queries, print "prime" or "composite" and terminate your program.You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2, 100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).

After each query you should read one string from the input. It will be "yes" if the printed integer is a divisor of the hidden number, and "no" otherwise.

Up to 20 times you can ask a query — print an integer from interval [2, 100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input. In any moment you can print the answer "prime" or "composite" (without the quotes). After that, flush the output and terminate your program. To flush you can use (just after printing an integer and end-of-line):    fflush(stdout) in C++;  System.out.flush() in Java;  stdout.flush() in Python;  flush(output) in Pascal;  See the documentation for other languages.  Hacking. To hack someone, as the input you should print the hidden number — one integer from the interval [2, 100]. Of course, his/her solution won't be able to read the hidden number from the input.

NoteThe hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.59 is a divisor of the hidden number. In the interval [2, 100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries).

$|=1; ($p,@p)=qw(2 3 5 7);
while (@p) {
	print "$p\n";
	$a=<>; chomp($a);
	if ($a eq "yes") {
		if (++$c==2) {
			print "composite\n";
			exit;
		}
		$p*=$p;
	} else {
		$p=shift(@p);
	}
}
print "prime\n";


Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.

The first line contains an integer n (1 ≤ n ≤ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.

Print "YES" or "NO" (without the quotes) depending on the answer to the problem.


You are given an array of positive integers $$$a_1, a_2, \ldots, a_n$$$.Make the product of all the numbers in the array (that is, $$$a_1 \cdot a_2 \cdot \ldots \cdot a_n$$$) divisible by $$$2^n$$$.You can perform the following operation as many times as you like:  select an arbitrary index $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the value $$$a_i$$$ with $$$a_i=a_i \cdot i$$$. You cannot apply the operation repeatedly to a single index. In other words, all selected values of $$$i$$$ must be different.Find the smallest number of operations you need to perform to make the product of all the elements in the array divisible by $$$2^n$$$. Note that such a set of operations does not always exist.

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

For each test case, print the least number of operations to make the product of all numbers in the array divisible by $$$2^n$$$. If the answer does not exist, print -1.

NoteIn the first test case, the product of all elements is initially $$$2$$$, so no operations needed.In the second test case, the product of elements initially equals $$$6$$$. We can apply the operation for $$$i = 2$$$, and then $$$a_2$$$ becomes $$$2\cdot2=4$$$, and the product of numbers becomes $$$3\cdot4=12$$$, and this product of numbers is divided by $$$2^n=2^2=4$$$. In the fourth test case, even if we apply all possible operations, we still cannot make the product of numbers divisible by $$$2^n$$$  — it will be $$$(13\cdot1)\cdot(17\cdot2)\cdot(1\cdot3)\cdot(1\cdot4)=5304$$$, which does not divide by $$$2^n=2^4=16$$$.In the fifth test case, we can apply operations for $$$i = 2$$$ and $$$i = 4$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my $twos = 0;

	for( @_ ){
		$_ /= 2, ++ $twos while $_ % 2 == 0;
		}

	my @idxs = 1 .. @_;

	for( @idxs ){
		my $cnt = 0;
		$_ /= 2, ++ $cnt while $_ % 2 == 0;
		$_ = $cnt;
		}

	@idxs = sort { $b <=> $a } grep $_, @idxs;

	my $ops = 0;

	while( $twos < @_ and @idxs ){
		$twos += shift @idxs;
		$ops ++;
		}

	print $twos >= @_ ? $ops : -1;
	}


One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have n people standing on the first floor, the i-th person wants to go to the fi-th floor. Unfortunately, there is only one elevator and its capacity equal to k (that is at most k people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs |a - b| seconds to move from the a-th floor to the b-th floor (we don't count the time the people need to get on and off the elevator).What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor?

The first line contains two integers n and k (1 ≤ n, k ≤ 2000) — the number of people and the maximal capacity of the elevator. The next line contains n integers: f1, f2, ..., fn (2 ≤ fi ≤ 2000), where fi denotes the target floor of the i-th person.

Output a single integer — the minimal time needed to achieve the goal.

NoteIn first sample, an optimal solution is:   The elevator takes up person #1 and person #2.  It goes to the 2nd floor.  Both people go out of the elevator.  The elevator goes back to the 1st floor.  Then the elevator takes up person #3.  And it goes to the 2nd floor.  It picks up person #2.  Then it goes to the 3rd floor.  Person #2 goes out.  Then it goes to the 4th floor, where person #3 goes out.  The elevator goes back to the 1st floor.

use List::Util qw(first max maxstr min minstr reduce shuffle sum);
chomp (my ($n, $k) = split /\s+/, <>);
chomp (my @targets = sort {$b <=> $a} split /\s+/, <>);

my $cnt = 0;
while (scalar @targets) {
    $cnt += ((&max(splice(@targets, 0, $k))) - 1) << 1;
}
printf "$cnt\n";

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

my ($n, $k) = split ' ', <>;
my @arr = sort { $a <=> $b } split (' ', <>);
my ($res, $idx) = (0,$n-1);

while($idx >= 0){
    $res += 2*($arr[$idx]-1);
    $idx -= $k;
}
print $res;

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

my ($n, $k) = split ' ', <>;
my @arr = sort { $b <=> $a } split (' ', <>);
my ($res, $idx) = (0,0);

while($idx < $n){
    $res += 2*($arr[$idx]-1);
    $idx += $k;
}
print $res;

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

my ($n, $k) = split ' ', <>;
my @arr = sort { $b <=> $a } split (' ', <>);
my ($res, $idx) = (0,$n-1);
while($idx >= 0){
    $res += 2*($arr[$idx]-1);
    $idx -= $k;
}
print $res;


Tanya has $$$n$$$ candies numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th candy has the weight $$$a_i$$$.She plans to eat exactly $$$n-1$$$ candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.Your task is to find the number of such candies $$$i$$$ (let's call these candies good) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one.For example, $$$n=4$$$ and weights are $$$[1, 4, 3, 3]$$$. Consider all possible cases to give a candy to dad:  Tanya gives the $$$1$$$-st candy to dad ($$$a_1=1$$$), the remaining candies are $$$[4, 3, 3]$$$. She will eat $$$a_2=4$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$4+3=7$$$ and in even days she will eat $$$3$$$. Since $$$7 \ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $$$2$$$-nd candy to dad ($$$a_2=4$$$), the remaining candies are $$$[1, 3, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$3$$$. Since $$$4 \ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $$$3$$$-rd candy to dad ($$$a_3=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good).  Tanya gives the $$$4$$$-th candy to dad ($$$a_4=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_3=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good). In total there $$$2$$$ cases which should counted (these candies are good), so the answer is $$$2$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the weight of the $$$i$$$-th candy.

Print one integer — the number of such candies $$$i$$$ (good candies) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days.

NoteIn the first example indices of good candies are $$$[1, 2]$$$.In the second example indices of good candies are $$$[2, 3]$$$.In the third example indices of good candies are $$$[4, 5, 9]$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

while(<>){
	$debug and print "-" x 20;

	@_ = split ' ', <>;
	$debug and print "[@_]";

	my @A = ( 0, 0 );

	my $i = 0;
	map { $A[ $i ++ % 2 ] += $_ } @_;

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

	my @B = ( 0, 0 );

	my $cnt = 0;

	$i = 0;
	for( @_ ){
		$debug and print "-" x 10;
		$debug and print "$_";

		$A[ $i ] -= $_;
		$debug and print "b:[@B]";
		$debug and print "a:[@A]";

		if( $B[ 0 ] + $A[ 1 ] == $B[ 1 ] + $A[ 0 ] ){
			$cnt ++;
			$debug and print "here:$_"
			}

		$B[ $i ] += $_;

		$i ++;
		$i %= 2;
		}

	$debug and print "cnt:";
	print $cnt;
	}


You are given a set of $$$n$$$ ($$$n$$$ is always a power of $$$2$$$) elements containing all integers $$$0, 1, 2, \ldots, n-1$$$ exactly once.Find $$$\frac{n}{2}$$$ pairs of elements such that:  Each element in the set is in exactly one pair.  The sum over all pairs of the bitwise AND of its elements must be exactly equal to $$$k$$$. Formally, if $$$a_i$$$ and $$$b_i$$$ are the elements of the $$$i$$$-th pair, then the following must hold: $$$$$$\sum_{i=1}^{n/2}{a_i \& b_i} = k,$$$$$$ where $$$\&$$$ denotes the bitwise AND operation. If there are many solutions, print any of them, if there is no solution, print $$$-1$$$ instead.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 400$$$) — the number of test cases. Description of the test cases follows. Each test case consists of a single line with two integers $$$n$$$ and $$$k$$$ ($$$4 \leq n \leq 2^{16}$$$, $$$n$$$ is a power of $$$2$$$, $$$0 \leq k \leq n-1$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2^{16}$$$. All test cases in each individual input will be pairwise different.

For each test case, if there is no solution, print a single line with the integer $$$-1$$$. Otherwise, print $$$\frac{n}{2}$$$ lines, the $$$i$$$-th of them must contain $$$a_i$$$ and $$$b_i$$$, the elements in the $$$i$$$-th pair.  If there are many solutions, print any of them. Print the pairs and the elements in the pairs in any order.

NoteIn the first test, $$$(0\&3)+(1\&2) = 0$$$.In the second test, $$$(0\&2)+(1\&3) = 1$$$.In the third test, $$$(0\&1)+(2\&3) = 2$$$.In the fourth test, there is no solution.


Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times. Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.

The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.  The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.

In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.  In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.


Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t - 1 gestures (if the icon is on the screen t), and then make another gesture — press the icon of the required application exactly once to launch it.After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.

The first line of the input contains three numbers n, m, k (1 ≤ n, m, k ≤ 105) — the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen. The next line contains n integers, permutation a1, a2, ..., an — the initial order of icons from left to right in the menu (from the first to the last one), ai —  is the id of the application, whose icon goes i-th in the menu. Each integer from 1 to n occurs exactly once among ai. The third line contains m integers b1, b2, ..., bm(1 ≤ bi ≤ n) — the ids of the launched applications in the planned order. One application may be launched multiple times.

Print a single number — the number of gestures that Anya needs to make to launch all the applications in the desired order.

NoteIn the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1, 2, 3, the second screen contains icons 4, 5, 6, the third screen contains icons 7, 8. After application 7 is launched, we get the new arrangement of the icons — (123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture.In total, Anya makes 7 gestures.

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

my %pos;
$pos{$arr[$_ - 1]} = $_ foreach (1 .. @arr);

sub gotoScreen {
  return int ($_[0] / $k);
}

sub updatePos {
  my $num = $_[0];
  my $loc = $pos{$num};
  return if ($loc == 1);

  my ($b, $a) = ($arr[$loc - 1], $arr[$loc - 2]) = ($arr[$loc - 2], $arr[$loc - 1]);
  ($pos{$a}, $pos{$b}) = ($pos{$b}, $pos{$a});
}

my $sum = 0;
foreach (@b) {
  # print "@arr";
  # print "$_ $pos{$_}" foreach keys %pos;
  $sum += &gotoScreen($pos{$_} - 1);
  $sum++; # Open
  &updatePos($_);
  # print "$sum";
}

printf "$sum\n";


Vova has won $$$n$$$ trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of trophies. The second line contains $$$n$$$ characters, each of them is either G or S. If the $$$i$$$-th character is G, then the $$$i$$$-th trophy is a golden one, otherwise it's a silver trophy.

Print the maximum possible length of a subsegment of golden trophies, if Vova is allowed to do at most one swap.

NoteIn the first example Vova has to swap trophies with indices $$$4$$$ and $$$10$$$. Thus he will obtain the sequence "GGGGGGGSGS", the length of the longest subsegment of golden trophies is $$$7$$$. In the second example Vova can make no swaps at all. The length of the longest subsegment of golden trophies in the sequence is $$$4$$$. In the third example Vova cannot do anything to make the length of the longest subsegment of golden trophies in the sequence greater than $$$0$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

while(<>){
	$debug and print '-' x 15;
	$_ = <>, chomp;

	my $cG = () = /G/g;

	s/SS\KS+//g;
	y/S/,/;
	s/G+/ ' ' . length $& /ge;
	1 while s/ (\d+) (\d+)/ ' ' . ( $1 + $2 ) /e;
	s/ //g;

	$debug and print;

	my @cand = ( 0 );

	/
		\b(\d+)
		,
		(?=(\d+)\b)
		(?{ push @cand, 1 + $1 + $2 })
		(*F)
	/x;

	push @cand, 1 + ( sort { $b <=> $a } split ',+' )[ 0 ];

	@cand = map { $_ > $cG ? $cG : $_ } @cand;

	$debug and print "[@cand]";

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

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

while(<>){
	$debug and print '-' x 15;
	$_ = <>, chomp;

	my $cG = () = /G/g;

	s/SS\KS+//g;
	s/G+/ ' ' . length $& /ge;
	1 while s/ (\d+) (\d+)/ ' ' . ( $1 + $2 ) /e;
	s/ //g;
	y/S/,/;

	$debug and print;

	my @cand = ( 0 );

	/
		\b(\d+)
		,
		(?=(\d+)\b)
		(?{ push @cand, 1 + $1 + $2 })
		(*F)
	/x;

	push @cand, +( sort { $b <=> $a } split ',+' )[ 0 ];

	@cand = map { $_ > $cG ? $cG : $_ } @cand;

	$debug and print "[@cand]";

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


Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $$$M$$$ with $$$n$$$ rows and $$$n$$$ columns such that $$$M_{ij}=a_i \cdot a_j$$$ where $$$a_1, \dots, a_n$$$ is some sequence of positive integers.Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $$$a_1, \dots, a_n$$$. Help Sasha restore the array!

The first line contains a single integer $$$n$$$ ($$$3 \leqslant n \leqslant 10^3$$$), the size of the table.  The next $$$n$$$ lines contain $$$n$$$ integers each. The $$$j$$$-th number of the $$$i$$$-th line contains the number $$$M_{ij}$$$ ($$$1 \leq M_{ij} \leq 10^9$$$). The table has zeroes on the main diagonal, that is, $$$M_{ii}=0$$$.

In a single line print $$$n$$$ integers, the original array $$$a_1, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that an answer exists. If there are multiple answers, print any.


You came to the exhibition and one exhibit has drawn your attention. It consists of $$$n$$$ stacks of blocks, where the $$$i$$$-th stack consists of $$$a_i$$$ blocks resting on the surface.The height of the exhibit is equal to $$$m$$$. Consequently, the number of blocks in each stack is less than or equal to $$$m$$$.There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks. Find the maximum number of blocks you can remove such that the views for both the cameras would not change.Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$1 \le m \le 10^9$$$) — the number of stacks and the height of the exhibit. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the number of blocks in each stack from left to right.

Print exactly one integer — the maximum number of blocks that can be removed.

NoteThe following pictures illustrate the first example and its possible solution.Blue cells indicate removed blocks. There are $$$10$$$ blue cells, so the answer is $$$10$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

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

	$debug and print '-' x 15;

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

	my $used = 0;
	my $top = 0;

	for( @_ ){
		if( $_ > $top ){
			$top ++;
			}
		else{
			;
			}

		$debug and print " $_ $top";
		}

	$used = $n + $_[ @_ - 1 ] - $top;

	my $sum = 0;

	$sum += $_ for @_;

	print $sum - $used;
	}


Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them — those with biggest ti.Your task is to handle queries of two types:  "1 id" — Friend id becomes online. It's guaranteed that he wasn't online before.  "2 id" — Check whether friend id is displayed by the system. Print "YES" or "NO" in a separate line. Are you able to help Limak and answer all queries of the second type?

The first line contains three integers n, k and q (1 ≤ n, q ≤ 150 000, 1 ≤ k ≤ min(6, n)) — the number of friends, the maximum number of displayed online friends and the number of queries, respectively. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 109) where ti describes how good is Limak's relation with the i-th friend. The i-th of the following q lines contains two integers typei and idi (1 ≤ typei ≤ 2, 1 ≤ idi ≤ n) — the i-th query. If typei = 1 then a friend idi becomes online. If typei = 2 then you should check whether a friend idi is displayed. It's guaranteed that no two queries of the first type will have the same idi becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (typei = 2) so the output won't be empty.

For each query of the second type print one line with the answer — "YES" (without quotes) if the given friend is displayed and "NO" (without quotes) otherwise.

NoteIn the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries:  "1 3" — Friend 3 becomes online.  "2 4" — We should check if friend 4 is displayed. He isn't even online and thus we print "NO".  "2 3" — We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print "YES".  "1 1" — Friend 1 becomes online. The system now displays both friend 1 and friend 3.  "1 2" — Friend 2 becomes online. There are 3 friends online now but we were given k = 2 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (t1 < t2, t3) so friend 1 won't be displayed  "2 1" — Print "NO".  "2 2" — Print "YES".  "2 3" — Print "YES".


Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros.

A single input line contains a single integer n (1 ≤ n ≤ 105).

Print a single integer — the answer to the problem without leading zeroes, or "-1" (without the quotes), if the number that meet the problem condition does not exist.


Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.

The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 106). Each character in s will be either "l" or "r".

Output n lines — on the i-th line you should print the i-th stone's number from the left.

NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1.

chomp ($s = <STDIN>);
@s = split /\s*/, $s;
(@l, @r) = ();
$i = 1;
foreach (@s) {
	if (/^l$/i) {unshift @r, $i} else {push @l, $i}
	$i++;
}
printf "%s\n", join "\n", @l, @r;


You've got a list of program warning logs. Each record of a log stream is a string in this format:  "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format.The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description).Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m.

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 10000). The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program.  It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·106 (in particular, this means that the length of some line does not exceed 5·106 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty.

If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) — the first moment of time when the number of warnings for the last n seconds got no less than m.


For a given array $$$a$$$ consisting of $$$n$$$ integers and a given integer $$$m$$$ find if it is possible to reorder elements of the array $$$a$$$ in such a way that $$$\sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}}$$$ equals $$$m$$$? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, $$$\frac{5}{2}=2.5$$$.

The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 100$$$). The test cases follow, each in two lines. The first line of a test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le 10^6$$$). The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$) — the elements of the array.

For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.

NoteIn the first test case one of the reorders could be $$$[1, 2, 5]$$$. The sum is equal to $$$(\frac{1}{1} + \frac{2}{2} + \frac{5}{3}) + (\frac{2}{2} + \frac{5}{3}) + (\frac{5}{3}) = 8$$$. The brackets denote the inner sum $$$\sum_{j=i}^{n}{\frac{a_j}{j}}$$$, while the summation of brackets corresponds to the sum over $$$i$$$.


Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland. Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.

Print m lines. On the i-th line print the team of the i-th region — the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.

5 2
Ivanov 1 763
Andreev 2 800
Petrov 1 595
Sidorov 1 790
Semenov 2 503

5 2
Ivanov 1 800
Andreev 2 763
Petrov 1 800
Sidorov 1 800
Semenov 2 503

NoteIn the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.


You are given a permutation of length $$$n$$$. Recall that the permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2, 3, 1, 5, 4]$$$ is a permutation, but $$$[1, 2, 2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1, 3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).You can perform at most $$$n-1$$$ operations with the given permutation (it is possible that you don't perform any operations at all). The $$$i$$$-th operation allows you to swap elements of the given permutation on positions $$$i$$$ and $$$i+1$$$. Each operation can be performed at most once. The operations can be performed in arbitrary order.Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.You can see the definition of the lexicographical order in the notes section.You have to answer $$$q$$$ independent test cases.For example, let's consider the permutation $$$[5, 4, 1, 3, 2]$$$. The minimum possible permutation we can obtain is $$$[1, 5, 2, 4, 3]$$$ and we can do it in the following way:  perform the second operation (swap the second and the third elements) and obtain the permutation $$$[5, 1, 4, 3, 2]$$$;  perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation $$$[5, 1, 4, 2, 3]$$$;  perform the third operation (swap the third and the fourth elements) and obtain the permutation $$$[5, 1, 2, 4, 3]$$$.  perform the first operation (swap the first and the second elements) and obtain the permutation $$$[1, 5, 2, 4, 3]$$$; Another example is $$$[1, 2, 4, 3]$$$. The minimum possible permutation we can obtain is $$$[1, 2, 3, 4]$$$ by performing the third operation (swap the third and the fourth elements).

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of test cases. Then $$$q$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation.

For each test case, print the answer on it — the lexicograhically minimum possible permutation obtained by performing some of the given operations in some order.

NoteRecall that the permutation $$$p$$$ of length $$$n$$$ is lexicographically less than the permutation $$$q$$$ of length $$$n$$$ if there is such index $$$i \le n$$$ that for all $$$j$$$ from $$$1$$$ to $$$i - 1$$$ the condition $$$p_j = q_j$$$ is satisfied, and $$$p_i < q_i$$$. For example:  $$$p = [1, 3, 5, 2, 4]$$$ is less than $$$q = [1, 3, 5, 4, 2]$$$ (such $$$i=4$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$),  $$$p = [1, 2]$$$ is less than $$$q = [2, 1]$$$ (such $$$i=1$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$).

#!/usr/bin/env perl

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

my @tokens = ();
my $q = read_token();

for (1..$q) {
    my $n = read_token();
    my @chances = (1)x($n+1);
    my @orders;
    for ( 1..$n ) {
        push @orders, $_;
    }
    my $line = read_line();
    my @arr = (0);
    push @arr, split q{ }, $line;

    while ( @orders ) {
        my $order = shift @orders;
        my $i = find_idex(\@arr, $order, $n);
        $i--;

        while ( $i > 0 ) {
            if ( $chances[$i] && $arr[$i] > $arr[$i+1] ) {
                @arr[$i,$i+1] = @arr[$i+1,$i];
                $chances[$i] = 0;
                $i--;
            }
            else { last; }
        }
    }
    shift @arr;
    say "@arr";

}

sub find_idex {
    my ($arr, $value, $n) = @_;
    my $i = 0;
    for ( 1..$n ) {
        if ( $$arr[$_] == $value ) {
            $i = $_;
            last;
        }
    }
    return $i;
}

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

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


You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.

The only line contains a string $$$s$$$ consisting of zeroes and ones ($$$1 \le |s| \le 1000$$$). Zero describes vertical tile, one describes horizontal tile.

Output $$$|s|$$$ lines — for each tile you should output two positive integers $$$r,c$$$, not exceeding $$$4$$$, representing numbers of smallest row and column intersecting with it. If there exist multiple solutions, print any of them.

NoteFollowing image illustrates the example after placing all three tiles:    Then the first row is deleted: