Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya!Sonya is an owl and she sleeps during the day and stay awake from minute l1 to minute r1 inclusive. Also, during the minute k she prinks and is unavailable for Filya.Filya works a lot and he plans to visit Sonya from minute l2 to minute r2 inclusive.Calculate the number of minutes they will be able to spend together.

NoteIn the first sample, they will be together during minutes 9 and 10.In the second sample, they will be together from minute 50 to minute 74 and from minute 76 to minute 100.

use strict;
use warnings;

use Data::Dumper;
$,=" ";
my ($l1,$r1,$l2,$r2,$k)=split / /,<>;
chomp($l1,$r1,$l2,$r2,$k);
my $ans=min($r1,$r2)-max($l1,$l2)+1;
if(max($l1,$l2) <= $k and $k <=min($r1,$r2))
{
  $ans--;
}
if($ans>=0)
{
  print $ans . "\n";
}
else
{
  print "0\n";
}

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

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

# cf714a
use strict;
=item
A. Meeting of Old Friends
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Today an outstanding event is going to happen in the forest
— hedgehog Filya will come to his old fried Sonya!

Sonya is an owl and she sleeps during the day and stay awake from minute
l1 to minute r1 inclusive. Also, during the minute k she prinks
and is unavailable for Filya.

Filya works a lot and he plans to visit Sonya from minute
l2 to minute r2 inclusive.

Calculate the number of minutes they will be able to spend together.
Input

The only line of the input contains integers l1, r1, l2, r2
and k (1 ≤ l1, r1, l2, r2, k ≤ 1018, l1 ≤ r1, l2 ≤ r2),
providing the segments of time for Sonya and Filya and the moment of
time when Sonya prinks.

Output

Print one integer — the number of minutes Sonya and Filya will be able to spend together.
Examples
Input

1 10 9 20 1

Output

2

Input

1 100 50 200 75

Output

50

Note

In the first sample, they will be together during minutes 9 and 10.

In the second sample, they will be together from minute 50 to minute 74 and from minute 76 to minute 100.
=cut
use bigint;

my ($l1,$r1,$l2,$r2,$k)=map {$_+0} split(' ',<>);
my $a=$l1<=$l2 ? $l2 : $l1;
my $b=$r1<=$r2 ? $r1 : $r2;
my $r=$b-$a>=0?$b-$a+1:0;
my $s=(($a<=$k)&&($k<=$b))?1:0;
print $r-$s,"\n";

# cf714a
use strict;
=item
A. Meeting of Old Friends
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Today an outstanding event is going to happen in the forest
— hedgehog Filya will come to his old fried Sonya!

Sonya is an owl and she sleeps during the day and stay awake from minute
l1 to minute r1 inclusive. Also, during the minute k she prinks
and is unavailable for Filya.

Filya works a lot and he plans to visit Sonya from minute
l2 to minute r2 inclusive.

Calculate the number of minutes they will be able to spend together.
Input

The only line of the input contains integers l1, r1, l2, r2
and k (1 ≤ l1, r1, l2, r2, k ≤ 1018, l1 ≤ r1, l2 ≤ r2),
providing the segments of time for Sonya and Filya and the moment of
time when Sonya prinks.

Output

Print one integer — the number of minutes Sonya and Filya will be able to spend together.
Examples
Input

1 10 9 20 1

Output

2

Input

1 100 50 200 75

Output

50

Note

In the first sample, they will be together during minutes 9 and 10.

In the second sample, they will be together from minute 50 to minute 74 and from minute 76 to minute 100.
=cut

my ($l1,$r1,$l2,$r2,$k)=split(' ',<>);
my $a=$l1<=$l2 ? $l2 : $l1;
my $b=$r1<=$r2 ? $r1 : $r2;
print $b-$a+1-($a<=$k&&$k<=$b),"\n";

# cf714a
use strict;
=item
A. Meeting of Old Friends
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Today an outstanding event is going to happen in the forest
— hedgehog Filya will come to his old fried Sonya!

Sonya is an owl and she sleeps during the day and stay awake from minute
l1 to minute r1 inclusive. Also, during the minute k she prinks
and is unavailable for Filya.

Filya works a lot and he plans to visit Sonya from minute
l2 to minute r2 inclusive.

Calculate the number of minutes they will be able to spend together.
Input

The only line of the input contains integers l1, r1, l2, r2
and k (1 ≤ l1, r1, l2, r2, k ≤ 1018, l1 ≤ r1, l2 ≤ r2),
providing the segments of time for Sonya and Filya and the moment of
time when Sonya prinks.

Output

Print one integer — the number of minutes Sonya and Filya will be able to spend together.
Examples
Input

1 10 9 20 1

Output

2

Input

1 100 50 200 75

Output

50

Note

In the first sample, they will be together during minutes 9 and 10.

In the second sample, they will be together from minute 50 to minute 74 and from minute 76 to minute 100.
=cut

my ($l1,$r1,$l2,$r2,$k)=split(' ',<>);

if($l1>$l2) {
  ($l1,$r1)=($l2,$r2);
}
# l1<=l2
if($r1<$l2) {
  print 0,"\n";
}
# l2<=r1
my $r=$r1-$l2+1; # inc
if(($l2<=$k) and ($k<=$r1)) {
  --$r;
}
print "$r\n";


"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many participants will advance to the next round.

The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 50) separated by a single space. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 100), where ai is the score earned by the participant who got the i-th place. The given sequence is non-increasing (that is, for all i from 1 to n - 1 the following condition is fulfilled: ai ≥ ai + 1).

Output the number of participants who advance to the next round.

NoteIn the first example the participant on the 5th place earned 7 points. As the participant on the 6th place also earned 7 points, there are 6 advancers.In the second example nobody got a positive score.

#
# Hello World Program in Perl
#
use strict;
my ($a, $b) = split /\s/, <>;

my @units = split /\s/, <>;
$b--;
$b++ while($b < $#units && $units[$b] == $units[$b+1]);
$b-- while($b >= 0 && $units[$b] == 0);
print $b+1;

#!/usr/bin/env perl

use strict;
use warnings;
use utf8;
use v5.20;

sub main {
    my %args = @_;

    my ($n, $k)  = split(/ /, readline(STDIN));
    my @points = split(/ /, readline(STDIN));

    my $pass_count = 0;
    my $pass_points = $points[$k-1];

    if ($pass_points > 0) {
        $pass_count = $k;

        foreach my $mark (@points[$k..$n-1]) {
            last if $mark < $pass_points;
            $pass_count += 1;
        }
    }
    else {
        foreach my $mark (@points[0..$k-1]) {
            last if $mark <= 0;
            $pass_count += 1;
        }
    }

    say $pass_count;

    return;
}

main();

exit;

#!/usr/bin/perl
# Codeforces Practice 158A - 25 May 2012

use warnings;
use strict;

my ($n,$k) = split(" ", <STDIN>);
my @scores = split(" ", <STDIN>);

my $kthScore = $scores[$k-1];
my $ret = 0;

for(0..$#scores){
    if($scores[$_]>=$kthScore && $scores[$_]!=0){
        $ret++;
    }
}

print $ret;

#!/usr/bin/perl
# Codeforces Practice 158A - 25 May 2012

use warnings;
use strict;

my ($n,$k) = split(" ", <STDIN>);
my @scores = split(" ", <STDIN>);

my $kthScore = $scores[$k-1];
my $ret = 0;

for(@scores){
    if($_>=$kthScore && $_!=0){
        $ret++;
    }
}

print $ret;

my($n, $k) = split(" ", <STDIN>);
my @a = split(" ", <STDIN>);
my $count = 0;
foreach my $i (@a) {
    if(($i >= $a[$k-1])&&($i > 0)) {
        $count++;
    }
}
print $count;

#!/usr/bin/perl
# your code goes here

chomp;
($n, $k) = split / /, <>;
chomp;
@a = split / /, <>;
$bound = $a[$k-1]>0 ? $a[$k-1]:1;
@a = sort { $a <=> $b } @a;
$ans = 0;
# print "bound = $bound";
# print $#a;
foreach (@a) {
	++$ans if $_ >= $bound;
	# print "$_ "
}
# print ;
print $ans;

use strict;
use warnings;

my $in1 = <>;
my ($n, $k) = split ' ', $in1;
my $in2 = <>;
my @a = split ' ', $in2;

# check a[0]=0 case...

#find k'th place score.
# find all a[i] bigger or equal to k'th place score

my $score_k = $a[$k-1];

my $winners = 0;
for (my $i=0; $i < $n; $i++) {
    if ($a[$i] >= $score_k && $a[$i] > 0) {
        $winners++;
    }
}

print $winners . "\n";

#!/usr/bin/perl

($n, $k) = split ' ', <STDIN>;
@a = split ' ', <STDIN>;

$ans = 0;
foreach  my $x (@a) {
	if ($x >= $a[$k - 1] && $x > 0){
		$ans++;
	}
}
print "$ans \n";

($n, $k) = split " ", <>;
@mas = split " ", <>;
@mas = sort {$b <=> $a} @mas;
$curr = @mas[$k-1];
if ($curr == 0)
{
	$ans = 0;
	foreach $index (0..$n-1)
	{
		if (@mas[$index] != 0)
		{
			$ans = $ans + 1;
		}
	}
	print $ans;
}
else
{
	$ans = $k;
	foreach $index ($k..$n-1)
	{
		# print "$index\n";
		if (@mas[$index] == $curr)
		{
			$ans = $ans + 1;
		}
	}
	print $ans;
}

($n, $k) = split " ", <>;
@mas = split " ", <>;
$curr = @mas[$k-1];
if ($curr == 0)
{
	$ans = 0;
	foreach $index (0..$n-1)
	{
		if (@mas[$index] != 0)
		{
			$ans = $ans + 1;
		}
	}
	print $ans;
}
else
{
	$ans = $k;
	foreach $index ($k..$n-1)
	{
		# print "$index\n";
		if (@mas[$index] == $curr)
		{
			$ans = $ans + 1;
		}
	}
	print $ans;
}

use strict;
use warnings;

my ($n, $k) = split ' ', <>;
my @a = split ' ', <>;
my $lim = $a[$k-1];
@a = grep { $_ >= $lim && $_ > 0 } @a;
print scalar @a, "\n";

#!/bin/perl
use strict;
use warnings;
my @a = ();
my $s = 0;
my ($n, $k) =  split " ", <>;

@a = split " ", <>;
foreach (@a) {
    if ($a[$k-1] <= $_) {
        $s = ($s+1) if ($_ > 0);
    } else {
        last;
    }
}
print "$s\n";

use strict;
use warnings;
use feature "say";

my $n;
my $k;

($n, $k) = split / +/, <STDIN>;

my @a = split / +/, <STDIN>;
my $ans = 0;

for (@a)
{
    if ($_ >= $a[$k - 1] && $_ > 0)
    {
        $ans++;
    }
}
say $ans;

#!/usr/bin/perl

use strict;
use warnings;

chomp( my $firstline = <STDIN> );
my ( $nummem, $lastmem ) = split / /, $firstline;

chomp( my $secondline = <STDIN> );
my @point = split / /, $secondline;

my $count = 0;

my $lastpoint = $point[ $lastmem - 1 ];

foreach my $p ( @point ) {
    if ( ( $p > 0 ) && ( $p >= $lastpoint ) ) {
        $count++;
    } else {
        last;
    }
}

print "$count\n";

use warnings;
use strict;

use feature ':5.10';

my ($n, $k) = split / /, <STDIN>;
my @a = split / /, <STDIN>, $n;

my $l = $a[$k - 1];

my $ans = 0;

for (@a){ $ans++ if ($_ >= $l and $_ > 0) };

say $ans;

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

my ($n, $k, @a) = (0, (split ' ', <STDIN>)[1], split ' ', <STDIN>);
$k = $a[$k - 1]; $k = 1 if $k < 1;
$_ >= $k and ++$n foreach @a;
print $n . "\n"

#!/usr/local/bin/perl

($n , $k) = split (/ / , <>);
@a = split (/ / , <>);

if ($a[0] == 0 || $k == 0){
    print "0\n";
    exit;
}
if ($a[$k-1] == 0){
    print binSearch(0 , $k -1)."\n";
    exit;
}
$count = $k;
while ($a[$count] == $a[$k-1] && $count<= $#a){
    $count++;

}
print $count."\n";

sub binSearch{
    use integer;
    my $begin = $_[0];
    my $end = $_[1];
    my $mid = $begin + ($end -$begin) / 2;

    if ($begin == $mid){
        return $begin+1;
    }

    if ($a[$mid] != 0){
        return binSearch($mid , $end);
    }
    return binSearch($begin , $mid);
}

#!/usr/bin/perl

use strict;

chomp(my $in = <>);
my @in1 = split(" ", $in);
my $k = $in1[1] -1;

chomp($in = <>);
my @in2 = split(" ", $in);

if($in2[$k] > 0){
	my $temp = $in2[$k];
	my $ans = $k;
	for my $i ($k+1..$#in2){
		if($in2[$i] == $temp){
			$ans++;
		}
	}
	print $ans+1;
}
else{
	my $ans = 0;
	for my $i (0..$k-1){
		if($in2[$i] > 0){
			$ans++;
		}
	}
	print $ans;
}

# for numeric sorting
sub numerically { $b <=> $a }

my $n, $k;
my $line;
my @arr, @sorted, @rev;
chomp ( $line = <STDIN> );
if ( $line =~ m/(.+) (.+)/ ) {
    $n = $1;
    $k = $2;}
chomp ( $line = <STDIN> );

@arr = split m/ /, $line;
@sorted = sort numerically @arr;
# @rev = reverse ( @sorted );

my $threshold = $sorted[ $k-1 ];
my $count = 0;
for (@sorted) {
    if ( $_ >= $threshold && $_ > 0 ) {
	$count += 1; }}
print "$count\n";

#!/usr/bin/env perl

use v5.012;
use warnings;

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

my $meh = grep { $_ > 0 } @scores[0..$k-1];
my $pass = grep { $_ > 0 && $_ == $scores[$k - 1] } @scores[$k..scalar @scores - 1];

print $meh + $pass;

use strict;
use warnings;

my @input = split(/ /,<STDIN>);
my $n = $input[0];
my $k = $input[1];
my @a = split(/ /,<STDIN>);
my $i;
my $count = 0;
for($i = 0 ; $i < @a ; $i++){
    if($a[$i] >= $a[$k-1] && $a[$i] > 0){
        $count++;
    }
}
print "$count\n";

my @a = split " ", <>;
my @b = split " ", <>;
my $cnt = 0;
foreach (@b)
{
    last unless $_ >= $b[$a[1]-1] and $_ > 0;
    ++$cnt;
}
print $cnt;

#!perl
my($n, $k) = split / /, <STDIN>;
if (!$n) {
	print(0, "\n");
	exit;
}
if ($k > $n) {
	die "wrong input: n < k\n";
}
my @points = grep {length $_ > 0} split / /, <STDIN>;
@points = map {int $_} grep {/^-?\d+$/} @points;
if ($#points + 1 != $n){
	die "wrong input: incorrect count\n";
}
@points = sort {$b <=> $a} grep {$_ > 0} @points;
my $count = $#points + 1;
my $min = $points[$k-1];
if ($k > $count) {
	print($count, "\n");
	exit;
}
my $out = $k;
for (my $i = $k; $i < $count && $points[$i] == $min; $i++) {
	$out++;
}
print $out, "\n";

use strict;
use warnings;

my $temp_line;
my @first_line;
my @second_line;
my $a_score_index; # advance_score_index

$temp_line = <>;
@first_line = split(" ", $temp_line);

$temp_line = <>;
@second_line = split(" ", $temp_line);

$a_score_index = $first_line[1] - 1; # kth place to index

while ($a_score_index < @second_line
        && $second_line[$a_score_index + 1] == $second_line[$a_score_index]) {
    $a_score_index++;
}

# do not take 0 score into account
while ($a_score_index > -1) {
    if (0 != $second_line[$a_score_index]) {
        last;
    }
    $a_score_index--;
}

print $a_score_index + 1;

#
# Hello World Program in Perl
#
use strict;
my ($a, $b) = split /\s/, <>;

my @units = split /\s/, <>;

$b++ while($b < $#units && $units[$b] == $units[$b+1]);
$b-- while($b >= 0 && $units[$b] == 0);
print $b+1;

#!/usr/bin/env perl

use strict;
use warnings;
use utf8;
use v5.20;

sub main {
    my %args = @_;

    my ($n, $k)  = split(/ /, readline(STDIN));
    my @points = split(/ /, readline(STDIN));

    my $pass_count = 0;
    my $pass_points = $points[$k-1];

    if ($pass_points > 0) {
        $pass_count = $k;

        foreach my $mark (@points[$k..$n-1]) {
            last if $mark < $pass_points;
            $pass_count += 1;
        }
    }
    else {
        foreach my $mark (@points[0, $k-1]) {
            last if $mark <= 0;
            $pass_count += 1;
        }
    }

    say $pass_count;

    return;
}

main();

exit;

#!/usr/bin/perl
# Codeforces Practice 158A - 25 May 2012

use warnings;
use strict;

my ($n,$k) = split(" ", <STDIN>);
my @scores = split(" ", <STDIN>);

if($scores[$k-1]!=0)
{
    my $kthScore = $scores[$k-1];
    my $ret = $k;
    for($k..$#scores){
        if($scores[$_]==$kthScore){
            $ret++;
        }
        last if($scores[$_]!=$kthScore);
    }
    print $ret;
}
else
{
    print 0;
}

#!/usr/bin/perl
# Codeforces Practice 158A - 25 May 2012

use warnings;
use strict;

my ($n,$k) = split(" ", <STDIN>);
my @scores = split(" ", <STDIN>);

if($k!=0)
{
    my $kthScore = $scores[$k-1];
    my $ret = $k;
    for($k..$#scores){
        if($scores[$_]==$kthScore){
            $ret++;
        }
        last if($scores[$_]!=$kthScore);
    }
    print $ret;
}
else
{
    print 0;
}

#!/usr/bin/perl
# Codeforces Practice 158A - 25 May 2012

use warnings;
use strict;

my ($n,$k) = split(" ", <STDIN>);
my @scores = split(" ", <STDIN>);

my $kthScore = $scores[$k-1];
my $ret = 0;
for(0..$#scores){
    if($scores[$_]>=$kthScore && $scores[$_]!=0){
        $ret++;
    }
    last if($scores[$_]!=$kthScore);
}
print $ret;

#!/usr/bin/perl
# your code goes here

chomp;
($n, $k) = split / /, <>;
chomp;
@a = sort split / /, <>;
$bound = $a[$k-1];
foreach (@a) {
	++$ans if $_ >= $bound;
}
print $ans;

#!/usr/bin/perl
# your code goes here

chomp;
($n, $k) = split / /, <>;
chomp;
@a = sort split / /, <>;
$bound = $a[$k-1]>0 ? $a[$k-1]:1;
$ans = 0;
foreach (@a) {
	++$ans if $_ >= $bound;
}
print $ans;

#!/usr/bin/perl

($n, $k) = split ' ', <STDIN>;
@a = split ' ', <STDIN>;
sort @a;
$ans = 0;
foreach  my $x  (@a) {
	if ($x >= $a[$n - $k] && $x > 0){
		$ans++;
	}
}
print "$ans \n";

#!/usr/bin/perl

($n, $k) = split ' ', <STDIN>;
@a = split ' ', <STDIN>;

$ans = 0;
foreach  my $x  (sort @a) {
	if ($x >= $a[$n - $k] && $x > 0){
		$ans++;
	}
}
print "$ans \n";

($n, $k) = split " ", <>;
@mas = split " ", <>;
@mas = reverse sort @mas;
$curr = @mas[$k-1];
if ($curr == 0)
{
	$ans = 0;
	foreach $index (0..$n-1)
	{
		if (@mas[$index] != 0)
		{
			$ans = $ans + 1;
		}
	}
	print $ans;
}
else
{
	$ans = $k;
	foreach $index ($k..$n-1)
	{
		if (@mas[$index] == $curr)
		{
			$ans = $ans + 1;
		}
	}
	print $ans;
}

($n, $k) = split " ", <>;
@mas = split " ", <>;
@mas = sort @mas;
$curr = @mas[$k-1];
if ($curr == 0)
{
	$ans = 0;
	foreach $index (0..$n-1)
	{
		if (@mas[$index] != 0)
		{
			$ans = $ans + 1;
		}
	}
	print $ans;
}
else
{
	$ans = $k;
	foreach $index ($k..$n-1)
	{
		if (@mas[$index] == $curr)
		{
			$ans = $ans + 1;
		}
	}
	print $ans;
}

$\=$/;

($n,$k)=split(" ",<STDIN>);
@members=split(" ",<STDIN>);

my $j=-1;

1 while (($members[++$j]>=$members[$k])&&(($members[$j]>0)));

print $j;

#!/bin/perl
use strict;
use warnings;
my @a = ();
my $a = '';
my $s = 0;
my ($n, $k) =  split " ", <>;
chomp ($a = <>);
foreach (1..$n) { @a = $a =~ /\d/sg; }
foreach (@a) {
    if ($k < $_) { $s = ($s+1); } else { last; }
}
print "$s";

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

my @a = ();
my $a = '';
my $s = 0;
my ($n, $k) =  split " ", <>;
chomp ($a = <>);
foreach (1..$n) { @a = $a =~ /\d+/sg; }
foreach (@a) {
    if ($k < $_) { $s = ($s+1); } else { last; }
}
print "$s";

use strict;
use warnings;
use feature "say";

my $n;
my $k;

($n, $k) = split / +/, <STDIN>;

my @a = split / +/, <STDIN>;
my $ans = 0;

for (@a)
{
    if ($_ >= $a[$k] && $_ > 0)
    {
        $ans++;
    }
}
say $ans;

#!/usr/bin/perl

use strict;
use warnings;

my $n = <>;

my @cmd;
push @cmd, <> for ($n);

my $curdir = "/";
my @dirstack = ();

sub pwd() { print $curdir, "\n"; }

sub cd($) {
    my @path = split '/', shift;

    foreach my $dir (@path)
    {
        pop @dirstack if ($dir eq "..");
        push @dirstack, $dir if ($dir ne "..");
    }

    $curdir = (join "/", @dirstack) . "/";
    $curdir = "/$curdir" if ((substr $curdir,0,1) ne "/");
}

foreach (@cmd)
{
    my ($cmd, $arg) = split /\s/, $_;

    cd ($arg) if ($cmd eq "cd");
    pwd() if ($cmd eq "pwd");
}

use warnings;
use strict;

use feature ':5.10';

my ($n, $k) = split / /, <STDIN>;
my @a = split / /, <STDIN>, $n;

my $l = $a[$k];

my $ans = 0;

for (@a){ $ans++ if ($_ >= $l and $_ > 0) };

say $ans;

#!/usr/local/bin/perl

($n , $k) = split (/ / , <>);
@a = split (/ / , <>);
if (!$a[0]){
    print "0\n";
    exit;
}
if (!$a[$k-1]){
    print binSearch(0 , $k -1)."\n";
    exit;
}
$count = $k;
while ($a[$count] == $a[$k-1] && $count<= $#a){
    $count++;

}
print $count."\n";

sub binSearch{
    use integer;
    my $begin = $_[0];
    my $end = $_[1];
    my $mid = $begin + ($end -$begin) / 2;

    if ($begin == $mid){
        return $begin+1;
    }

    if ($a[$mid]){
        return binSearch($mid , $end);
    }
    return binSearch($begin , $mid);
}

#!/usr/bin/perl

use strict;

chomp(my $in = <>);
my @in1 = split(" ", $in);
my $k = $in1[1];

chomp($in = <>);
my @in2 = split(" ", $in);

if($in2[$k] > 0){
	my $temp = $in2[$k];
	my $ans = $k;
	for my $i ($k+1..$#in2){
		if($in2[$i] == $temp){
			$ans++;
		}
	}
	print $ans;
}
else{
	my $ans = 0;
	for my $i (0..$k-1){
		if($in2[$i] > 0){
			$ans++;
		}
	}
	print $ans;
}

# for numeric sorting
sub numerically { $b <=> $a }

my $n, $k;
my $line;
my @arr, @sorted, @rev;
chomp ( $line = <STDIN> );
if ( $line =~ m/(.+) (.+)/ ) {
    $n = $1;
    $k = $2;}
chomp ( $line = <STDIN> );

@arr = split m/ /, $line;
@sorted = sort ( @arr );
@rev = reverse ( @sorted );

my $threshold = $rev[ $k-1 ];
my $count = 0;
for (@rev) {
    if ( $threshold >= $_ && $_ > 0 ) {
	$count += 1; }}

print "$count\n";

my $n, $k;
my $line;
my @arr, @sorted;
chomp ( $line = <STDIN> );
if ( $line =~ m/(.+) (.+)/ ) {
    $n = $1;
    $k = $2;}
chomp ( $line = <STDIN> );
@arr = split m/ /, $line;
@sorted = sort ( @arr );
my $threshold = $sorted[ $k-1 ];
my $count = 0;
for (@sorted) {
    if ( $_ >= $threshold && $_ > 0 ) {
	$count += 1; }}
print "$count\n";

#!/usr/bin/env perl

use v5.012;
use warnings;

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

my $len = scalar @scores;
my $meh = grep { $_ > 0 } @scores[0..$k-1];
my $pass = grep { $_ > 0 && $_ == $scores[$k] } @scores[$k..scalar @scores - 1];

print $meh + $pass;

use strict;
use warnings;

my @input = split(/ /,<STDIN>);
my $n = $input[0];
my $k = $input[1];
my @a = split(/ /,<STDIN>);
my $i = $k;
my $count = 0;
if($a[$k-1] == 0){
    print $count."\n";
}else{
    $count = $k;
    while($i < @a and $a[$i] ==$a[$k-1] ){
        $count++;
        $i++;
    };
    print $count."\n";
}

use strict;
use warnings;

my $temp_line;
my @first_line;
my @second_line;
my $a_score_index; # advance_score_index

$temp_line = <>;
@first_line = split(" ", $temp_line);

$temp_line = <>;
@second_line = split(" ", $temp_line);

$a_score_index = $first_line[1] - 1; # kth place to index

while ($a_score_index < @second_line
        && $second_line[$a_score_index + 1] == $second_line[$a_score_index]) {
    $a_score_index++;
}

print $a_score_index + 1;

use strict;
use warnings;

my @input_line = <STDIN>;
my $as_index = $input_line[1]; # index of score that will advance
print $as_index;
@input_line = <STDIN>;

# find the index where last score equal to k is
while ( $input_line[$as_index] != $input_line[$as_index + 1] ) {
        $as_index++;
}

# do not count the input parameters on first row
print $as_index - 2;

use strict;
use warnings;

my @input_lines;

# read input
while (<>) {
        my $line = $_;
        chomp $line;
        push @input_lines;
}

while (@input_lines) {
        print(pop @input_lines);
        print "\n";
}

#test

use strict;
use warnings;

my $as_index = $ARGV[1]; # index of score that will advance

# find the index where last score equal to k is
while ( $ARGV [$as_index] != $ARGV[$as_index + 1] ) {
        $as_index++;
}

# do not count the input parameters on first row
print $as_index - 2;

use strict;
use warnings;

my @input_lines;

while (<>) {
        my $line = $_;
        chomp $line;
        push @input_lines;
}

while (@input_lines) {
        print(pop @input_lines);
        print "\n";
}

use strict;
use warnings;

my @input_line = <STDIN>;
my $as_index = $input_line[1]; # index of score that will advance
@input_line = <STDIN>;

# find the index where last score equal to k is
while ( $input_line[$as_index] != $input_line[$as_index + 1] ) {
        $as_index++;
}

# do not count the input parameters on first row
print $as_index - 2;

use strict;
use warnings;

my @input_line = <STDIN>;
my $as_index = $input_line[0]; # index of score that will advance
print $as_index;
@input_line = <STDIN>;

# find the index where last score equal to k is
while ( $input_line[$as_index] != $input_line[$as_index + 1] ) {
        $as_index++;
}

# do not count the input parameters on first row
print $as_index - 2;

use strict;
use warnings;

my $temp_line;
my @first_line;
my @second_line;
my $a_score_index; # advance_score_index

$temp_line = <>;
@first_line = split(" ", $temp_line);

$temp_line = <>;
@second_line = split(" ", $temp_line);

$a_score_index = $first_line[1] - 1; # kth place to index

while ($a_score_index < @second_line
        && $second_line[$a_score_index + 1] == $second_line[$a_score_index]) {
    $a_score_index++;
}

if (0 == $a_score_index) { # nobody got positive score
        print $a_score_index;
}
else {
        print $a_score_index + 1;
}

use strict;
use warnings;

my @input_lines;

# read input
while (<>) {
        my $line = $_;
        chomp $line;
        push @input_lines;
}

while (@input_lines) {
        print(pop @input_lines);
        print "\n";
}
# fdsjoi

use strict;
use warnings;

my $temp_line;
my @first_line;
my @second_line;
my $a_score_index; # advance_score_index

$temp_line = <>;
@first_line = split(" ", $temp_line);

$temp_line = <>;
@second_line = split(" ", $temp_line);

$a_score_index = $first_line[1] - 1; # kth place to index

while ($a_score_index < @second_line
        && $second_line[$a_score_index + 1] == $second_line[$a_score_index]) {
    $a_score_index++;
}

if (0 == $second_line[0]) { # nobody got positive score
        print $second_line[0];
}
else {
        print $a_score_index + 1;
}

use strict;
use warnings;

my $temp_line;
my @first_line;
my @second_line;
my $a_score_index; # advance_score_index

$temp_line = <>;
@first_line = split(" ", $temp_line);

$temp_line = <>;
@second_line = split(" ", $temp_line);

$a_score_index = $first_line[1] - 1; # kth place to index

while ($a_score_index < @second_line
        && $second_line[$a_score_index + 1] == $second_line[$a_score_index]) {
    print "first while";
    $a_score_index++;
}

# do not take 0 score into account
while ($a_score_index > -1) {
    if (0 != $second_line[$a_score_index]) {
        last;
    }
    $a_score_index--;
}

print $a_score_index + 1;


Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... + (i - 1) + i cubes.Vanya wants to know what is the maximum height of the pyramid that he can make using the given cubes.

The first line contains integer n (1 ≤ n ≤ 104) — the number of cubes given to Vanya.

Print the maximum possible height of the pyramid in the single line.

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

chomp($mx = <>);
my $tmp = 0;
my $tot = 0;
my $ans = 0;
while (true) {
	$tmp += ++$ans;
	$tot += $tmp;
	$tot>$mx and --$ans and last;
}
say $ans;

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

my $n = <>;
my $lvl = 1; my $num = 1;
while($num <= $n){
    $n -= $num;
    $lvl++;
    $num += $lvl;
}

print $lvl-1;


JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer $$$n$$$, you can perform the following operations zero or more times:  mul $$$x$$$: multiplies $$$n$$$ by $$$x$$$ (where $$$x$$$ is an arbitrary positive integer).  sqrt: replaces $$$n$$$ with $$$\sqrt{n}$$$ (to apply this operation, $$$\sqrt{n}$$$ must be an integer). You can perform these operations as many times as you like. What is the minimum value of $$$n$$$, that can be achieved and what is the minimum number of operations, to achieve that minimum value?Apparently, no one in the class knows the answer to this problem, maybe you can help them?

The only line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the initial number.

Print two integers: the minimum integer $$$n$$$ that can be achieved using the described operations and the minimum number of operations required.

NoteIn the first example, you can apply the operation mul $$$5$$$ to get $$$100$$$ and then sqrt to get $$$10$$$.In the second example, you can first apply sqrt to get $$$72$$$, then mul $$$18$$$ to get $$$1296$$$ and finally two more sqrt and you get $$$6$$$.Note, that even if the initial value of $$$n$$$ is less or equal $$$10^6$$$, it can still become greater than $$$10^6$$$ after applying one or more operations.

$_ = <>;

exit if $_ == 1 and print "1 0";

for $i ( 2 .. sqrt ){
	if( $_ % $i == 0 ){
		$h{ $i } ++;
		$_ /= $i;
		redo;
		}
	}

$h{ $_ } ++;
delete $h{ 1 };

$g{ $_ } ++ for values %h;

$max = ( sort { $b <=> $a } keys %g )[ 0 ];

$cnt += ( 1 < keys %g or ( sprintf "%b", $max ) !~ /^10*$/ );

$max > 1 and $cnt += length sprintf "%b", -- $max;

$min = eval join ' * ', keys %h;

print "$min $cnt"

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

while(<>){
	chomp;

	$debug and print '-' x 15;
	$debug and print;

	if( $_ == 1 ){
		print "1 0";
		next;
		}

	my %h;

	for my $i ( 2 .. sqrt ){
		if( $_ % $i == 0 ){
			$h{ $i } ++;
			$_ /= $i;
			redo;
			}
		}

	$h{ $_ } ++;
	delete $h{ 1 };

	$debug and print " $_ -> $h{ $_ }" for keys %h;

	$debug and print ' ', '-' x 10;

	my %g;

	$g{ $_ } ++ for values %h;

	$debug and print " $_ -> $g{ $_ }" for keys %g;

	my $cnt = 0;

	my $max = ( sort { $b <=> $a } keys %g )[ 0 ];

	if( 1 < keys %g ){
		$cnt ++;
		}
	elsif( ( sprintf "%b", $max ) !~ /^10*$/ ){
		$cnt ++;
		}

	$max --;

	$max > 0 and $cnt += length sprintf "%b", $max;

	my $min = eval join ' * ', keys %h;

	print $min, ' ', $cnt;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

while(<>){
	chomp;

	$debug and print '-' x 15;
	$debug and print;

	if( $_ == 1 ){
		print "1 0";
		next;
		}

	my %h;

	for my $i ( 2 .. sqrt ){
		if( $_ % $i == 0 ){
			$h{ $i } ++;
			$_ /= $i;
			redo;
			}
		}

	$h{ $_ } ++;
	delete $h{ 1 };

	$debug and print " $_ -> $h{ $_ }" for keys %h;

	my %g;

	$g{ $_ } ++ for values %h;

	my $cnt = 0;

	if( 1 < keys %g ){
		$cnt ++;
		}

	my $max = ( sort { $b <=> $a } keys %g )[ 0 ];

	$max --;

	$max > 0 and $cnt += length sprintf "%b", $max;

	my $min = eval join ' * ', keys %h;

	print $min, ' ', $cnt;
	}


You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic check.Web-developers of the company Q assume that a password is complex enough, if it meets all of the following conditions:  the password length is at least 5 characters;  the password contains at least one large English letter;  the password contains at least one small English letter;  the password contains at least one digit. You are given a password. Please implement the automatic check of its complexity for company Q.

The first line contains a non-empty sequence of characters (at most 100 characters). Each character is either a large English letter, or a small English letter, or a digit, or one of characters: "!", "?", ".", ",", "_".

If the password is complex enough, print message "Correct" (without the quotes), otherwise print message "Too weak" (without the quotes).

$_ = <STDIN>;
chomp;

if ( /\d/ && /[a-z]/ && /[A-Z]/ && (length >= 5) ){
    print "Correct";
}else{
    print "Too weak";
}

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

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

my $strength = 0;

if(length($password) > 4)
{
    if($password =~ /\d/ && $password =~ /[A-Z]/ && $password =~ /[a-z]/)
    {
      $strength = 1;
    }
}

if($strength)
{
  say "Correct";
}
else
{
  say "Too weak";
}

while (<>)
{
    if (/^.{5,}$/ and /\d/ and /[a-z]/ and /[A-Z]/)
    {
        print "Correct\n";
    }
    else
    {
        print "Too weak\n";
    }
}

while (<>){
my $input=($_);
chomp($input);
my $pwdlength=length($input);
if ($input =~ /[A-Z]/ and $input =~ /[a-z]/ and $input =~ /[0-9]/ and $pwdlength >= 5){
print "Correct";
}
else{
print "Too weak";
}
}


Let’s define a grid to be a set of tiles with 2 rows and 13 columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid: ABCDEFGHIJKLMNOPQRSTUVWXYZ We say that two tiles are adjacent if they share a side or a corner. In the example grid above, the tile with the letter 'A' is adjacent only to the tiles with letters 'B', 'N', and 'O'. A tile is not adjacent to itself.A sequence of tiles is called a path if each tile in the sequence is adjacent to the tile which follows it (except for the last tile in the sequence, which of course has no successor). In this example, "ABC" is a path, and so is "KXWIHIJK". "MAB" is not a path because 'M' is not adjacent to 'A'. A single tile can be used more than once by a path (though the tile cannot occupy two consecutive places in the path because no tile is adjacent to itself).You’re given a string s which consists of 27 upper-case English letters. Each English letter occurs at least once in s. Find a grid that contains a path whose tiles, viewed in the order that the path visits them, form the string s. If there’s no solution, print "Impossible" (without the quotes).

The only line of the input contains the string s, consisting of 27 upper-case English letters. Each English letter occurs at least once in s.

Output two lines, each consisting of 13 upper-case English characters, representing the rows of the grid. If there are multiple solutions, print any of them. If there is no solution print "Impossible".


Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.There are $$$n$$$ stages available. The rocket must contain exactly $$$k$$$ of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — $$$26$$$ tons.Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.

The first line of input contains two integers — $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) – the number of available stages and the number of stages to use in the rocket. The second line contains string $$$s$$$, which consists of exactly $$$n$$$ lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.

Print a single integer — the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.

NoteIn the first example, the following rockets satisfy the condition: "adx" (weight is $$$1+4+24=29$$$); "ady" (weight is $$$1+4+25=30$$$); "bdx" (weight is $$$2+4+24=30$$$); "bdy" (weight is $$$2+4+25=31$$$).Rocket "adx" has the minimal weight, so the answer is $$$29$$$.In the second example, target rocket is "belo". Its weight is $$$2+5+12+15=34$$$.In the third example, $$$n=k=2$$$, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.


Apart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside.Big Banban is hesitating over the amount of money to give out. He considers loops to be lucky since it symbolizes unity and harmony.He would like to find a positive integer n not greater than 1018, such that there are exactly k loops in the decimal representation of n, or determine that such n does not exist.A loop is a planar area enclosed by lines in the digits' decimal representation written in Arabic numerals. For example, there is one loop in digit 4, two loops in 8 and no loops in 5. Refer to the figure below for all exact forms.

The first and only line contains an integer k (1 ≤ k ≤ 106) — the desired number of loops.

Output an integer — if no such n exists, output -1; otherwise output any such n. In the latter case, your output should be a positive decimal integer not exceeding 1018.


In some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take d minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven.Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get n cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.

The only line contains four integers n, t, k, d (1 ≤ n, t, k, d ≤ 1 000) — the number of cakes needed, the time needed for one oven to bake k cakes, the number of cakes baked at the same time, the time needed to build the second oven.

If it is reasonable to build the second oven, print "YES". Otherwise print "NO".

NoteIn the first example it is possible to get 8 cakes in 12 minutes using one oven. The second oven can be built in 5 minutes, so after 6 minutes the first oven bakes 4 cakes, the second oven bakes 4 more ovens after 11 minutes. Thus, it is reasonable to build the second oven. In the second example it doesn't matter whether we build the second oven or not, thus it takes 12 minutes to bake 8 cakes in both cases. Thus, it is unreasonable to build the second oven.In the third example the first oven bakes 11 cakes in 3 minutes, that is more than needed 10. It is unreasonable to build the second oven, because its building takes more time that baking the needed number of cakes using the only oven.

use warnings;
use strict;

my $line = <STDIN>;
chomp $line;
my ($req_cakes, $bake_time, $capacity, $time_to_build_oven) = split / /, $line;

# for positive numbers only
my $ceil = sub {
    my $val = shift;
    if (($val - int($val)) > 0) {
        return int($val) + 1;
    } else {
        return int($val);
    }
};

my $single_oven_time = $ceil->( $req_cakes / $capacity ) * $bake_time;
my $one_oven_cakes = $capacity * ($single_oven_time / $bake_time);

my $next_oven1 = $bake_time;
my $next_oven2 = $bake_time + $time_to_build_oven;

my $cakes = 0;
my $time = 0;
while($cakes < $req_cakes and $time < $single_oven_time) {
    # find out which oven finishes next
    $time = $next_oven1 < $next_oven2 ? $next_oven1 : $next_oven2;
    $cakes += $capacity;

    if ($next_oven1 < $next_oven2) {
        $next_oven1 += $bake_time;
    } else {
        $next_oven2 += $bake_time;
    }
}

#warn "1 oven: $one_oven_cakes after $single_oven_time;\n";
#warn "2 oven: $cakes after $time\n";
if ($time < $single_oven_time) {
    print "YES";
} else {
    print "NO";
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

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

	my $sec = $t + $d;

	my $N = 0;
	my $T = 0;

	while( $n > $N ){
		$N += $k;
		$T += $t;
		}

	$debug and print "$N|$T";

	print $sec < $T ? "YES" : "NO";

	}


Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string. String t is called a palindrome, if it reads the same from left to right and from right to left.For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strings "131" and "002010200", respectively, which are palindromes.You are given some integer number x. Check if it's a quasi-palindromic number.

The first line contains one integer number x (1 ≤ x ≤ 109). This number is given without any leading zeroes.

Print "YES" if number x is quasi-palindromic. Otherwise, print "NO" (without quotes).

print "Please Enter a Number: ";
my $num = <STDIN>;
chomp $num;
while ((substr $num, -1,1) == '0'){
	$num /= 10;
}
$len = length $num;
for (my $i = 1; $i <= $len; $i++){
	$a[$i] = substr $num, -$i,1;
}
$rev_num = join('', @a[1..$len]);

if ($num == $rev_num){
	print "YES";
}
else{
	print "NO";
}


Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.

The only line contains two integers n and k (1 ≤ n, k ≤ 109).

Print the smallest integer x > n, so it is divisible by the number k.

$input=<STDIN>;
chomp($input);
@input=split(/ /, $input);
$n=int(@input[0]);
$k=int(@input[1]);

$answer=int($n/$k)*$k;

if( $answer <= $n )
{
	$answer += $k;
}

print $answer."\n";


There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player.Your task is to write a program that can, given the number of coins each player has at the end of the game, determine the size b of the initial bet or find out that such outcome of the game cannot be obtained for any positive number of coins b in the initial bet.

The input consists of a single line containing five integers c1, c2, c3, c4 and c5 — the number of coins that the first, second, third, fourth and fifth players respectively have at the end of the game (0 ≤ c1, c2, c3, c4, c5 ≤ 100).

Print the only line containing a single positive integer b — the number of coins in the initial bet of each player. If there is no such value of b, then print the only value "-1" (quotes for clarity).

NoteIn the first sample the following sequence of operations is possible:  One coin is passed from the fourth player to the second player;  One coin is passed from the fourth player to the fifth player;  One coin is passed from the first player to the third player;  One coin is passed from the fourth player to the second player.

my @arr = split " ", <>;
my $sum = eval join "+", @arr;
print $sum % 5 == 0 && $sum > 0? $sum / 5 : -1;

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

$tot+=$_ foreach(split / /, <>);
$tot>0 and $tot%5==0 and say $tot/5 or say -1;

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

chomp (my @arr = split /\s+/, <>);
my $val = &sum (@arr);

if ((($val % 5) != 0) || ($val == 0)) {
    printf "-1\n";
} else {
    printf "%d\n", $val / 5;
}

my @arr = split /\s+/, <>;
my @sum = 0;
$sum += $_ foreach @arr;
if ($sum % 5 == 0 and $sum > 0) {
    print $sum / 5, "\n";
} else {
    print -1;
}

#!/usr/bin/perl
# your code here

chomp(my $string=<STDIN>);
my @array = split / /, $string;
my $answer = 0;
foreach(@array){
    $answer = $answer+$_;
}
if($answer !=0 ){
    if($answer%5 == 0){
        print $answer/5;
    }
    else{
        print "-1\n";
    }
}
else{
    print "-1\n";
}

use List::Util qw(sum);
my @arr = split " ", <>;
my $sum = sum (@arr);
print $sum % 5 == 0? $sum / 5 : -1;

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

chomp (my @arr = split /\s*/, <>);
my $val = &sum (@arr);

if (($val % 5) == 0) {
    printf "%d\n", $val / 5;
} else {
    printf "-1\n";
}

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

chomp (my @arr = split /\s+/, <>);
my $val = &sum (@arr);

if (($val % 5) == 0) {
    printf "%d\n", $val / 5;
} else {
    printf "-1\n";
}

#!/usr/bin/perl
# your code here

chomp(my $string=<STDIN>);
my @array = split / /, $string;
my $answer = 0;
foreach(@array){
    $answer = $answer+$_;
}

if($answer%5 == 0){
    print $answer/5;
}
else{
    print "-1";
}


A and B are preparing themselves for programming contests.To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.For each chess piece we know its weight:   the queen's weight is 9,  the rook's weight is 5,  the bishop's weight is 3,  the knight's weight is 3,  the pawn's weight is 1,  the king's weight isn't considered in evaluating position. The player's weight equals to the sum of weights of all his pieces on the board.As A doesn't like counting, he asked you to help him determine which player has the larger position weight.

The input contains eight lines, eight characters each — the board's description. The white pieces on the board are marked with uppercase letters, the black pieces are marked with lowercase letters. The white pieces are denoted as follows: the queen is represented is 'Q', the rook — as 'R', the bishop — as'B', the knight — as 'N', the pawn — as 'P', the king — as 'K'. The black pieces are denoted as 'q', 'r', 'b', 'n', 'p', 'k', respectively. An empty square of the board is marked as '.' (a dot).  It is not guaranteed that the given chess position can be achieved in a real game. Specifically, there can be an arbitrary (possibly zero) number pieces of each type, the king may be under attack and so on.

Print "White" (without quotes) if the weight of the position of the white pieces is more than the weight of the position of the black pieces, print "Black" if the weight of the black pieces is more than the weight of the white pieces and print "Draw" if the weights of the white and black pieces are equal.

rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR

NoteIn the first test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals 5.In the second test sample the weights of the positions of the black and the white pieces are equal to 39.In the third test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals to 16.

#!/usr/bin/env perl
use v5.10;use strict;use warnings;use Data::Dumper;
sub min{my($a,$b)=@_;return$a if($a<$b);return$b;}sub max{my($a,$b)=@_;return$a
if($a>$b);return$b;}sub out{foreach my$c(@_){print"$c ";}print("\n");}my$TESTAM=
1;sub input{my$r=<>;chomp$r;$r}

#$TESTAM = <STDIN>;
sub {
    my %w = (
        'q' => 9,
        'r' => 5,
        'b' => 3,
        'n' => 3,
        'p' => 1,
        'k' => 0,
        '.' => 0,
    );
    my ($white, $black) = (0, 0);
    foreach my $i (1..8) {
        foreach my $c (split("", input())) {
            $white += $w{lc($c)} if ($c eq uc($c));
            $black += $w{lc($c)} if ($c eq lc($c));
		}
	}

    if ($white == $black) {
        say "Draw";
	} elsif ($white < $black) {
		say "Black";
	} else {
        say "White";
	}
}->() while ($TESTAM--);

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

%tb = (
	q => 9,
	Q => 9,
	r => 5,
	R => 5,
	b => 3,
	B => 3,
	n => 3,
	N => 3,
	k => 0,
	K => 0,
	p => 1,
	P => 1,
	'.' => 0,
);
($white, $black) = (0, 0);
while (<>) {
	chomp;
	foreach (split //) {
		if ($_ ge 'a' && $_ le 'z') {
			$black += $tb{$_};
		} else {
			$white += $tb{$_};
		}
	}
}
if ($black > $white) {
	say "Black";
} elsif ($black < $white) {
	say "White";
} else {
	say "Draw";
}

use 5.016;
use strict;
use warnings;

sub count_black {
  local $_ = shift;
  tr/q//d * 9 + tr/r//d * 5 + tr/b//d * 3 + tr/n//d * 3 + tr/p//d;
}

sub count_white {
  local $_ = shift;
  tr/Q//d * 9 + tr/R//d * 5 + tr/B//d * 3 + tr/N//d * 3 + tr/P//d;
}

undef $/;
my $input = <>;

say qw(White Draw Black)[(count_black($input) <=> count_white($input)) + 1];

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

my %w = ('q' => 9, 'r'=> 5, 'b'=> 3, 'n'=> 3, 'p'=> 1, 'k'=> 0);
my ($black, $white) = (0,0);
while(<>){
    my @line = split '';
    foreach(@line){
        $black += $w{$_} if $_ =~ /[a-z]/;
        $white += $w{lc $_} if $_ =~ /[A-Z]/;
    }
}
if($black == $white){ print "Draw\n";}
else{ print $white > $black ? "White\n" : "Black\n";}

%h = qw(
q 9
r 5
n 3
b 3
p 1
);
print qw(Draw White Black)[0 <=> eval join '+', map 2 * $h{ $_ } - $h{ (lc) }, split '', join '', <>]

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

%tb = (
	q => 9,
	Q => 9,
	r => 5,
	R => 5,
	b => 3,
	B => 3,
	k => 3,
	K => 3,
	p => 1,
	P => 1,
	'.' => 0,
);
($white, $black) = (0, 0);
while (<>) {
	chomp;
	foreach (split //) {
		if ($_ ge 'a' && $_ le 'z') {
			$black += $tb{$_};
		} else {
			$white += $tb{$_};
		}
	}
}
if ($black > $white) {
	say "Black";
} elsif ($black < $white) {
	say "White";
} else {
	say "Draw";
}


Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to . Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.

The first and the single line of the input contains 6 space-separated integers a1, a2, a3, a4, a5 and a6 (1 ≤ ai ≤ 1000) — the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists.

Print a single integer — the number of triangles with the sides of one 1 centimeter, into which the hexagon is split.

NoteThis is what Gerald's hexagon looks like in the first sample:And that's what it looks like in the second sample:


Mislove had an array $$$a_1$$$, $$$a_2$$$, $$$\cdots$$$, $$$a_n$$$ of $$$n$$$ positive integers, but he has lost it. He only remembers the following facts about it: The number of different numbers in the array is not less than $$$l$$$ and is not greater than $$$r$$$; For each array's element $$$a_i$$$ either $$$a_i = 1$$$ or $$$a_i$$$ is even and there is a number $$$\dfrac{a_i}{2}$$$ in the array.For example, if $$$n=5$$$, $$$l=2$$$, $$$r=3$$$ then an array could be $$$[1,2,2,4,4]$$$ or $$$[1,1,1,1,2]$$$; but it couldn't be $$$[1,2,2,4,8]$$$ because this array contains $$$4$$$ different numbers; it couldn't be $$$[1,2,2,3,3]$$$ because $$$3$$$ is odd and isn't equal to $$$1$$$; and it couldn't be $$$[1,1,2,2,16]$$$ because there is a number $$$16$$$ in the array but there isn't a number $$$\frac{16}{2} = 8$$$.According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array.

The only input line contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$1 \leq n \leq 1\,000$$$, $$$1 \leq l \leq r \leq \min(n, 20)$$$) — an array's size, the minimal number and the maximal number of distinct elements in an array.

Output two numbers — the minimal and the maximal possible sums of all elements in an array.

NoteIn the first example, an array could be the one of the following: $$$[1,1,1,2]$$$, $$$[1,1,2,2]$$$ or $$$[1,2,2,2]$$$. In the first case the minimal sum is reached and in the last case the maximal sum is reached.In the second example, the minimal sum is reached at the array $$$[1,1,1,1,1]$$$, and the maximal one is reached at the array $$$[1,2,4,8,16]$$$.

use strict;
use warnings;

use Data::Dumper;

sub main {

    my $in= *STDIN;
    my $q= <$in>; chomp($q);

    my ($n, $l, $r)= split(' ', $q);

    my $v= 1;
    my $low_sum= 0;
    for (my $i = $l; $i > 0; $i--) {
        $low_sum += $v;
        $v *= 2;
    }
    $low_sum += ($n - $l);

    $v= 1;
    my $max_sum= 0;
    for (my $i = $r; $i > 0; $i--) {
        $max_sum += $v;
        $v *= 2;
    }

    $max_sum += (($n - $r) * ($v/2));

    print "$low_sum $max_sum";

}

main() unless caller();


Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale.Maxim often visits his neighbors, so apartment is good for him if it is available for sale and there is at least one already inhabited apartment adjacent to it. Maxim knows that there are exactly k already inhabited apartments, but he doesn't know their indices yet.Find out what could be the minimum possible and the maximum possible number of apartments that are good for Maxim.

The only line of the input contains two integers: n and k (1 ≤ n ≤ 109, 0 ≤ k ≤ n).

Print the minimum possible and the maximum possible number of apartments good for Maxim.

NoteIn the sample test, the number of good apartments could be minimum possible if, for example, apartments with indices 1, 2 and 3 were inhabited. In this case only apartment 4 is good. The maximum possible number could be, for example, if apartments with indices 1, 3 and 5 were inhabited. In this case all other apartments: 2, 4 and 6 are good.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	print do {
		if( $n == $k || $k == 0 ){
			"0 0";
			}
		else{
			my $x = $n - $k;
			my $min = ( sort { $a <=> $b } $x, $k * 2 )[ 0 ];
			"1 $min";
			}
		};
	}


Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."  The problem is: You are given a lucky number n. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.If we sort all lucky numbers in increasing order, what's the 1-based index of n? Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.

The first and only line of input contains a lucky number n (1 ≤ n ≤ 109).

Print the index of n among all lucky numbers.

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

chomp($line = <>);
$len = length $line;
$ans = 0;
foreach (split //, $line) {
	$ans <<= 1;
	$_ eq '7' and ++$ans;
}
$ans += 2**$len-1;
say $ans;

#	use integer;
#	use List::Util qw(max maxstr min minstr sum);
$\ = $/;

while(<>){
	chomp;
	y/47/12/;
	$n = 0;
	s/./ $n *= 2, $n += $&, '' /ge;
	print $n
	}


In the city of Ultima Thule job applicants are often offered an IQ test. The test is as follows: the person gets a piece of squared paper with a 4 × 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2 × 2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed. Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2 × 2 square, consisting of cells of the same color.

Four lines contain four characters each: the j-th character of the i-th line equals "." if the cell in the i-th row and the j-th column of the square is painted white, and "#", if the cell is black.

Print "YES" (without the quotes), if the test can be passed and "NO" (without the quotes) otherwise.

NoteIn the first test sample it is enough to repaint the first cell in the second row. After such repainting the required 2 × 2 square is on the intersection of the 1-st and 2-nd row with the 1-st and 2-nd column.


You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban — an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about them. Let's have a look at the Soroban's construction.  Soroban consists of some number of rods, each rod contains five beads. We will assume that the rods are horizontal lines. One bead on each rod (the leftmost one) is divided from the others by a bar (the reckoning bar). This single bead is called go-dama and four others are ichi-damas. Each rod is responsible for representing a single digit from 0 to 9. We can obtain the value of a digit by following simple algorithm:  Set the value of a digit equal to 0.  If the go-dama is shifted to the right, add 5.  Add the number of ichi-damas shifted to the left. Thus, the upper rod on the picture shows digit 0, the middle one shows digit 2 and the lower one shows 7. We will consider the top rod to represent the last decimal digit of a number, so the picture shows number 720.Write the program that prints the way Soroban shows the given number n.

The first line contains a single integer n (0 ≤ n < 109).

Print the description of the decimal digits of number n from the last one to the first one (as mentioned on the picture in the statement), one per line. Print the beads as large English letters 'O', rod pieces as character '-' and the reckoning bar as '|'. Print as many rods, as many digits are in the decimal representation of number n without leading zeroes. We can assume that number 0 has no leading zeroes.

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

(@_=reverse (split//,<>));
shift @_;

for (@_){

	$s=("O"x$_)."-".("O"x(9-$_));
	$s=~s/^OOOOO/-O|/;
	$s=~s/OOOOO$// and $s=~s/^/O-|/;
	print $s;
	n();
	}

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

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

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

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

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

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

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

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

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

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

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

(@_=reverse (split//,<>));
shift @_;

for (@_){

	$s=("O"x$_)."-".("O"x(8-$_));
	$s=~s/^OOOOO/-O|/;
	$s=~s/OOOOO$// and $s=~s/^/O-|/;
	print $s;
	n();
	}

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

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

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

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

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

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

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

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

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

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


Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom!Leha came up with a task for himself to relax a little. He chooses two integers A and B and then calculates the greatest common divisor of integers "A factorial" and "B factorial". Formally the hacker wants to find out GCD(A!, B!). It's well known that the factorial of an integer x is a product of all positive integers less than or equal to x. Thus x! = 1·2·3·...·(x - 1)·x. For example 4! = 1·2·3·4 = 24. Recall that GCD(x, y) is the largest positive integer q that divides (without a remainder) both x and y.Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?

The first and single line contains two integers A and B (1 ≤ A, B ≤ 109, min(A, B) ≤ 12).

Print a single integer denoting the greatest common divisor of integers A! and B!.

NoteConsider the sample.4! = 1·2·3·4 = 24. 3! = 1·2·3 = 6. The greatest common divisor of integers 24 and 6 is exactly 6.

#!/usr/bin/env perl

use strict;
use warnings;

my $input = <STDIN>;
chomp($input);
my ($aa, $bb) = split(' ', $input);

$aa = int($aa);
$bb = int($bb);

if ($aa < $bb) {
    print fac($aa);
}
else {
    print fac($bb);
}

sub fac {
    my ($n) = @_;
    my $f = 1;
    for my $i (1 .. $n) {
        $f *= $i;
    }
    return $f;
}

use strict;
my ($n, $m) = split(' ', <>);
sub fact{
  my ($n) = @_;
  if($n == 0){
    return 1;
  }
  else{
    return fact($n - 1) * $n;
  }
}
if($n > $m){
  print fact($m);
}
else{
  print fact($n);
}

print eval join ' * ', 1 .. ( sort { $a <=> $b } split ' ', <> )[ 0 ]

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $A, $B ) = split;

	my $min = ( sort { $a <=> $b } $A, $B )[ 0 ];

	print 1 * eval join ' * ', 1 .. $min;
	}

#!/usr/bin/env perl

use strict;
use warnings;

my $input = <STDIN>;
chomp($input);
my ($aa, $bb) = split(' ', $input);

$aa = int($aa);
$bb = int($bb);

if ($aa > $bb) {
    print fac($aa);
}
else {
    print fac($bb);
}

sub fac {
    my $n = @_;
    my $f = 1;
    for my $i (1 .. $n) {
        $f *= $i;
    }
}


Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues.On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on the clock were the same when read from both directions i.e. a palindrome.In his sleep, he started dreaming about such rare moments of the day when the time displayed on a digital clock is a palindrome. As soon as he woke up, he felt destined to write a program that finds the next such moment.However, he still hasn't mastered the skill of programming while sleeping, so your task is to help him.

The first and only line of the input starts with a string with the format "HH:MM" where "HH" is from "00" to "23" and "MM" is from "00" to "59". Both "HH" and "MM" have exactly two digits.

Print the palindromic time of day that comes soonest after the time given in the input. If the input time is palindromic, output the soonest palindromic time after the input time.

sub rev {
	my $in = shift;
	return join "", reverse split //, $in;
}

sub f {
	my $t = shift;

	($h, $m) = split /:/, $t;
	$h++ if $m >= $h && $m >= rev($h);
	while($h % 10 > 5) { $h++; }
	$h = 0 if $h > 23;
	$h = "0$h" if $h < 10 && length($h) == 1;
	return join ":", $h, rev($h);
}

chomp($line=<STDIN>);
print f($line)."\n";

sub rev {
	my $in = shift;
	return join "", reverse split //, $in;
}

sub f {
	my $t = shift;

	($h, $m) = split /:/, $t;
	$h++ if $m > $h && $m > rev($h);
	while($h % 10 > 5) { $h++; }
	$h = 0 if $h > 23;
	$h = "0$h" if $h < 10 && length($h) == 1;
	return join ":", $h, rev($h);
}

chomp($line=<STDIN>);
print f($line)."\n";

sub f {
	my $t = shift;

	($h, $m) = split /:/, $t;
	$h++ if $m > $h;
	while($h % 10 > 5) { $h++; }
	$h = 0 if $h > 23;
	$h = "0$h" if $h < 10;
	$m = join("", reverse(split //, $h));
	return join ":", $h, $m;
}

chomp($line=<STDIN>);
print f($line)."\n";

sub f {
	my $t = shift;

	($h, $m) = split /:/, $t;
	$h++ if $m > $h;
	$h = 0 if $h == 24;
	$h = "0$h" if $h < 10;
	$m = join("", reverse(split //, $h));
	return join ":", $h, $m;
}

chomp($line=<STDIN>);
print f($line)."\n";


Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:qwertyuiopasdfghjkl;zxcvbnm,./Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input).We have a sequence of characters he has typed and we want to find the original message.

First line of the input contains one letter describing direction of shifting ('L' or 'R' respectively for left or right). Second line contains a sequence of characters written by Mole. The size of this sequence will be no more than 100. Sequence contains only symbols that appear on Mole's keyboard. It doesn't contain spaces as there is no space on Mole's keyboard. It is guaranteed that even though Mole hands are moved, he is still pressing buttons on keyboard and not hitting outside it.

Print a line that contains the original message.

my $dir = <STDIN>;
chomp $dir;
my $str = <STDIN>;
chomp $str;

if ($dir eq 'R'){

    $str=~tr{qwertyuiopasdfghjkl;zxcvbnm,./}{/qwertyuiopasdfghjkl;zxcvbnm,./};

}else{

   $str=~tr{qwertyuiopasdfghjkl;zxcvbnm,./}{wertyuiopasdfghjkl;zxcvbnm,./};

}

print $str,"\n";

# author : Gabriel Hofer
use warnings;
use strict;
my $keyboard = q/qwertyuiopasdfghjkl;zxcvbnm,.\//;
if ( <STDIN> =~ m /L/ ) {
    chomp ( my $line = <STDIN> );
    for my $i ( split q//, $line ) {
        if ( $i eq '.' ) {
            $keyboard =~ m /\.(.)/;
            print qq /$1/;
        } else {
            $keyboard =~ m /$i(.)/;
            print qq /$1/;
        }
    }
} else {
    chomp ( my $line = <STDIN> );
    for my $i ( split q//, $line ) {
        if ( $i eq '.' ) {
            $keyboard =~ m /(.)\./;
            print qq/$1/;
        } else {
            $keyboard =~ m /(.)$i/;
            print qq/$1/;
        }}
}
print qq/\n/;

my $d = <>;
my $str = <>;
my @ch = split "", "qwertyuiopasdfghjkl;zxcvbnm,./";
my $sh = $d eq "R\n"? -1 : +1;
my %m = ();
foreach my $i (0 .. scalar @ch)
{
    $m{$ch[$i]} = $ch[$i + $sh];
}

print map { $m{$_} } split "", $str;

my @arr = ([split //,("qwertyuiop")],[split //,("asdfghjkl;")], [split //,"zxcvbnm,./"]);
chomp(my $ch  = <>);
$ch = $ch eq 'L' ? -1 : 1;
my @str = split //,<>;
pop @str;
my %key;
for my $i(0..2) {
    for my $j(0..9) {
        $key{$arr[$i][$j]} = $arr[$i][$j - $ch];
    }
}
print $key{$_} foreach(@str);

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

$delta = <> eq "R\n" ? -1:1;
@a = split //, "qwertyuiopasdfghjkl;zxcvbnm,./";
chomp($line = <>);
foreach $c(split //, $line) {
	foreach(0..$#a) {
		$a[$_] eq $c and print $a[$_+$delta] and last;
	}
}

my @arr = split /\s*/, "qwertyuiopasdfghjkl;zxcvbnm,./";

my (%l, %r);

for (my $i = 0; $i < @arr; $i++) {
    $l{$arr[$i]} = $arr[$i+1];
    $r{$arr[$i]} = $arr[$i-1];
}

chomp (my $k = <>);
chomp (my @in = split /\s*/, <>);
if ($k eq 'L') {
    printf "$l{$_}" foreach (@in);
} else {
    printf "$r{$_}" foreach (@in);
}
printf "\n";

use 5.016;
use strict;
use warnings;

sub left {
  $_[0] =~ tr{qwertyuioasdfghjklzxcvbnm,.}
             {wertyuiopsdfghjkl;xcvbnm,./}r;
}

sub right {
  $_[0] =~ tr{wertyuiopsdfghjkl;xcvbnm,./}
             {qwertyuioasdfghjklzxcvbnm,.}r;
}

my %dirs = (
  L => \&left,
  R => \&right,
);

chomp (my $dir = <>);
my $tr = $dirs{$dir};

my $msg = <>;
say $tr->($msg);

while($dirr=<>){

	$_="qwertyuiopasdfghjkl;zxcvbnm,./";

	for $i(split//,<>){
		$qi = quotemeta $i;
		($dirr =~ /R/ ? /(.)$qi/ : /$qi(.)/) and print $1
		}

	}

my $dir = <STDIN>;

if ($dir eq 'R'){

	print tr{wertyuiopasdfghjkl;zxcvbnm,./}{qwertyuiopasdfghjkl;zxcvbnm,.};

}else{

	print tr{qwertyuiopasdfghjkl;zxcvbnm,.}{wertyuiopasdfghjkl;zxcvbnm,./};

}

my $dir = <STDIN>;

$_ = <STDIN>;

if ($dir eq 'R'){

    print tr{wertyuiopasdfghjkl;zxcvbnm,./}{qwertyuiopasdfghjkl;zxcvbnm,.};

}else{

    print tr{qwertyuiopasdfghjkl;zxcvbnm,.}{wertyuiopasdfghjkl;zxcvbnm,./};

}

# author : Gabriel Hofer
use warnings;
use strict;
my $keyboard = q/qwertyuiopasdfghjkl;zxcvbnm,.\//;
if ( <STDIN> =~ m /L/ ) {
    chomp ( my $line = <STDIN> );
    for my $i ( split q//, $line ) {
       $keyboard =~ m /$i(.)/;
       print qq/$1/; }
} else {
    chomp ( my $line = <STDIN> );
    for my $i ( split q//, $line ) {
       $keyboard =~ m /(.)$i/;
       print qq/$1/; }
}
print qq/\n/;

my $d = <>;
my $str = <>;
my @ch = split "", "qwertyuiopasdfghjkl;zxcvbnm,./";
my $sh = $d eq "R"? 1 : -1;
my %m = ();
foreach my $i (0 .. scalar @ch)
{
    $m{$ch[$i]} = $ch[$i + $sh];
}

print map { $m{$_} } split "", $str;

my @arr = ([split //,("qwertyuiop")],[split //,("asdfghjkl;")], [split //,"zxcvbnm,./"]);
my $ch  = <> eq 'L' ? -1 : 1;
my @str = split //,<>;
pop @str;
my %key;
for my $i(0..2) {
    for my $j(0..9) {
        $key{$arr[$i][$j]} = $arr[$i][$j - $ch];
    }
}
print $key{$_} foreach(@str);

my @arr = split /\s*/, "qwertyuiopasdfghjkl;zxcvbnm,./";

my (%l, %r);

for (my $i = 0; $i < @arr; $i++) {
    $l{$arr[$i]} = $arr[$i-1];
    $r{$arr[$i]} = $arr[$i-1];
}

chomp (my $k = <>);
chomp (my @in = split /\s*/, <>);
if ($k eq 'L') {
    printf "$l{$_}" foreach (@in);
} else {
    printf "$r{$_}" foreach (@in);
}
printf "\n";


Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0 .Dr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?

The first line contains two integers n and x (1 ≤ n ≤ 100, 0 ≤ x ≤ 100) — the size of the set Dr. Evil owns, and the desired MEX. The second line contains n distinct non-negative integers not exceeding 100 that represent the set.

The only line should contain one integer — the minimal number of operations Dr. Evil should perform.

NoteFor the first test case Dr. Evil should add 1 and 2 to the set performing 2 operations.For the second test case Dr. Evil should erase 0 from the set. After that, the set becomes empty, so the MEX of it is 0.In the third test case the set is already evil.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my $op = $x;

	for ( @_ ){
		$_ == $x and do {
			$op ++;
			last;
			};
		$_ < $x and do {
			$op --;
			next;
			};
		}

	print $op;
	}


Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations:  multiply the current number by 2 (that is, replace the number x by 2·x);  append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1). You need to help Vasily to transform the number a into the number b using only the operations described above, or find that it is impossible.Note that in this task you are not required to minimize the number of operations. It suffices to find any way to transform a into b.

The first line contains two positive integers a and b (1 ≤ a < b ≤ 109) — the number which Vasily has and the number he wants to have.

If there is no way to get b from a, print "NO" (without quotes). Otherwise print three lines. On the first line print "YES" (without quotes). The second line should contain single integer k — the length of the transformation sequence. On the third line print the sequence of transformations x1, x2, ..., xk, where:   x1 should be equal to a,  xk should be equal to b,  xi should be obtained from xi - 1 using any of two described operations (1 < i ≤ k).  If there are multiple answers, print any of them.

$\ = $/;

while(<>){
	($n, $m) = split;
	while( $m ){
		unshift @m, $m;
		$m eq $n and last;
		$m < $n and ++ $f and last;
		$m =~ s/1$// and next;
		$m % 2 and ++ $f and last;
		$m /= 2;
		}

	print $f ? 'NO' :
		'YES' . "\n" . @m . "\n" . join ' ', @m;
	}


Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?Given an integer sequence a1, a2, ..., an of length n. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.A subsegment is a contiguous slice of the whole sequence. For example, {3, 4, 5} and {1} are subsegments of sequence {1, 2, 3, 4, 5, 6}, while {1, 2, 4} and {7} are not.

The first line of input contains a non-negative integer n (1 ≤ n ≤ 100) — the length of the sequence. The second line contains n space-separated non-negative integers a1, a2, ..., an (0 ≤ ai ≤ 100) — the elements of the sequence.

Output "Yes" if it's possible to fulfill the requirements, and "No" otherwise. You can output each letter in any case (upper or lower).

NoteIn the first example, divide the sequence into 1 subsegment: {1, 3, 5} and the requirements will be met.In the second example, divide the sequence into 3 subsegments: {1, 0, 1}, {5}, {1}.In the third example, one of the subsegments must start with 4 which is an even number, thus the requirements cannot be met.In the fourth example, the sequence can be divided into 2 subsegments: {3, 9, 9}, {3}, but this is not a valid solution because 2 is an even number.

use strict;
use warnings;
use utf8;
$| =1;

my $n = <>;
my $a = [map {$_&1} split " ",<>];

NO() if $a->[0]==0 or $a->[$#$a]==0;
OK() if $n & 1 == 1;

can_be_diveded($a, 0) ? OK() : NO();

sub OK {
    print "yes";
    exit(0);
}

sub NO {
    print "no";
    exit(0);
}

sub can_be_diveded {
    my $array = shift;
    my $even_lenght_bit = shift;
    my $retval = 0;
    my $last = $#$array;
    if (!$even_lenght_bit and !($last & 1) and ($array->[$last] & 1) ){
        $retval = 1;
    }

    for (my $i=0; ($i+1) < $last and $retval == 1 ; $i+=2){
        if ($array->[$i] & $array->[$i+1]){
            $retval = 1 if can_be_diveded([@$array[($i+1)..$last]], !$even_lenght_bit);
            last if $retval == 1;
        }
    }
    $retval;
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	if( @A % 2 and $A[0] % 2 and $A[-1] % 2 ){
		print "YES";
		}
	else{
		print "NO";
		}
	}

use strict;
use warnings;
use utf8;
$| =1;

my $n = <>;
my @a = map {$_&1} split " ",<>;

NO() if $a[0]==0 or $a[$#a]==0;
OK() if $n & 1 == 1;

my $blockNum = 0;
for (my $i=0;$i<($n-1) and $blockNum < 2;$i++){
    $blockNum++ if ($a[$i] & $a[$i+1]);
}
OK() if $blockNum > 1;
NO();

sub OK {
    print "yes";
    exit(0);
}

sub NO {
    print "no";
    exit(0);
}


Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than $$$a$$$ and screen height not greater than $$$b$$$. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is $$$w$$$, and the height of the screen is $$$h$$$, then the following condition should be met: $$$\frac{w}{h} = \frac{x}{y}$$$.There are many different TV sets in the shop. Monocarp is sure that for any pair of positive integers $$$w$$$ and $$$h$$$ there is a TV set with screen width $$$w$$$ and height $$$h$$$ in the shop.Monocarp isn't ready to choose the exact TV set he is going to buy. Firstly he wants to determine the optimal screen resolution. He has decided to try all possible variants of screen size. But he must count the number of pairs of positive integers $$$w$$$ and $$$h$$$, beforehand, such that $$$(w \le a)$$$, $$$(h \le b)$$$ and $$$(\frac{w}{h} = \frac{x}{y})$$$.In other words, Monocarp wants to determine the number of TV sets having aspect ratio $$$\frac{x}{y}$$$, screen width not exceeding $$$a$$$, and screen height not exceeding $$$b$$$. Two TV sets are considered different if they have different screen width or different screen height.

The first line contains four integers $$$a$$$, $$$b$$$, $$$x$$$, $$$y$$$ ($$$1 \le a, b, x, y \le 10^{18}$$$) — the constraints on the screen width and height, and on the aspect ratio.

Print one integer — the number of different variants to choose TV screen width and screen height so that they meet the aforementioned constraints.

NoteIn the first example, there are $$$3$$$ possible variants: $$$(5, 3)$$$, $$$(10, 6)$$$, $$$(15, 9)$$$.In the second example, there is no TV set meeting the constraints.In the third example, there is only one variant: $$$(3, 2)$$$.


When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked $$$n$$$ people about their opinions. Each person answered whether this problem is easy or hard.If at least one of these $$$n$$$ people has answered that the problem is hard, the coordinator decides to change the problem. For the given responses, check if the problem is easy enough.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of people who were asked to give their opinions. The second line contains $$$n$$$ integers, each integer is either $$$0$$$ or $$$1$$$. If $$$i$$$-th integer is $$$0$$$, then $$$i$$$-th person thinks that the problem is easy; if it is $$$1$$$, then $$$i$$$-th person thinks that the problem is hard.

Print one word: "EASY" if the problem is easy according to all responses, or "HARD" if there is at least one person who thinks the problem is hard.  You may print every letter in any register: "EASY", "easy", "EaSY" and "eAsY" all will be processed correctly.

NoteIn the first example the third person says it's a hard problem, so it should be replaced.In the second example the problem easy for the only person, so it doesn't have to be replaced.

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

my $n = <> + 0;
my $isEasy = 1;
my $line = <>;

my @numbers = split ' ', $line;

foreach my $number (@numbers) {
    if($number == 1) {
        $isEasy = 0;
    }
}

if($isEasy) {
    print "EASY\n";
} else {
    print "HARD\n";
}

use strict;
my $n = <>;
my @a = split(' ', <>);
for (my $i = 0; $i <= $#a; $i++){
  if($a[$i] == 1){
    print "HARD";
    exit(0);
  }
}
print "EASY";

#!/usr/bin/env perl

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

# essential
my @tokens = ();

my $n = read_token();
my $m = 0;

for ( 1..$n ) {
    $m = max($m, read_token());
}

if ( $m == 1 ) {
    say "hard";
}
else {
    say "easy";
}

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;
}

#!perl -w
use strict;
use warnings;

my ($i, $num, $str, $flag);
my (@arr_str, $len);

$num = <STDIN>;
chomp $num;

$str = <STDIN>;
chomp $str;

@arr_str = $str =~ /\d/g;
$len = @arr_str;

$flag = 0; # Если flag == 0, то задача легкая

for ($i  = 0; $i < $len; $i++) {
	if($arr_str[$i]) {
		$flag = 1;
		last;
	}
}

if($flag) {
	print "HARD";
}
else {
	print "EASY";}

exit 0;

#!/usr/bin/env perl

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

# essential
my @tokens = ();

my $n = read_token();
my $m = 0;

for ( 1..$n ) {
    $m = max($m, read_token());
}

if ( $m == 1 ) {
    say "hard";
}
else {
    say "easy";
}

say $n;

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;
}


The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t. As the king is not in habit of wasting his time, he wants to get from his current position s to square t in the least number of moves. Help him to do this.  In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).

The first line contains the chessboard coordinates of square s, the second line — of square t. Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h), the second one is a digit from 1 to 8.

In the first line print n — minimum number of the king's moves. Then in n lines print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD.  L, R, U, D stand respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them.


Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:  on Mondays, Thursdays and Sundays he eats fish food;  on Tuesdays and Saturdays he eats rabbit stew;  on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains:  $$$a$$$ daily rations of fish food;  $$$b$$$ daily rations of rabbit stew;  $$$c$$$ daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.

The first line of the input contains three positive integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 7\cdot10^8$$$) — the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly.

NoteIn the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday — rabbit stew and during Wednesday — chicken stake. So, after four days of the trip all food will be eaten.In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack.In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be $$$99$$$ portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip.

$\ = $/;

# Ans.: 4 7 3 39

my $debug = 0;

my $week_days = 'ABCACBA';

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

    my( $A, $B, $C ) = split;

    my $days = 0;

    for my $i ( reverse map 10 ** $_, 0 .. 9 ){
        while( $i * 3 <= $A && $i * 2 <= $B && $i * 2 <= $C ){
            $A -= $i * 3;
            $B -= $i * 2;
            $C -= $i * 2;
            $days += 7 * $i;
            }
        }

    my @additional_days;

    for my $start_day ( 0 .. 7 - 1 ){
        my $cycle = substr $week_days x 2, $start_day, 7;

        $cA = $A;
        $cB = $B;
        $cC = $C;
        my $additional_days = 0;

        while( $cycle ){
            $cycle =~ s/.//;
            my $L = $&;
            if( 0 ){ ; }
            elsif( $L eq 'A' ){
                $cA > 0 ? $cA -- : last;
                }
            elsif( $L eq 'B' ){
                $cB > 0 ? $cB -- : last;
                }
            elsif( $L eq 'C' ){
                $cC > 0 ? $cC -- : last;
                }
            $additional_days ++;
            }

        push @additional_days, $additional_days;
        }

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


Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (x + 1, y), (x - 1, y), (x, y + 1) or (x, y - 1). Unfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to (a, b) and continue travelling. Luckily, Drazil arrived to the position (a, b) successfully. Drazil said to Varda: "It took me exactly s steps to travel from my house to yours". But Varda is confused about his words, she is not sure that it is possible to get from (0, 0) to (a, b) in exactly s steps. Can you find out if it is possible for Varda?

You are given three integers a, b, and s ( - 109 ≤ a, b ≤ 109, 1 ≤ s ≤ 2·109) in a single line.

If you think Drazil made a mistake and it is impossible to take exactly s steps and get from his home to Varda's home, print "No" (without quotes). Otherwise, print "Yes".

NoteIn fourth sample case one possible route is: .

use strict;
use warnings;

my ($x, $y, $s) = split / /, <>;

if ($s < abs($x) + abs($y)){print "No"}
else
{
unless($s % 2 == ($x + $y) %2) {print "No" }
else {print "Yes";}
}

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

my ($x,$y,$s) = split ' ',<>;
my $sum = abs($x) + abs($y);
if($s < $sum){print "No\n";}
else{ print ( ($s-$sum)&1? "No\n" : "Yes\n" );}

use strict;
use warnings;

my $A = <STDIN>;
my ($a,$b,$s) = (split(" ", $A));

if( $s >= abs($a) + abs($b) and ($s - abs($a) - abs($b))%2 eq 0 ) {
	print "Yes";
	exit 0;
}

print "No";

use strict;
use warnings;

my ($x, $y, $s) = split / /, <>;

if ($s < $x + $y){print "No"}
else
{
unless($s % 2 == ($x + $y) %2) {print "No" }
else {print "Yes";}
}

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

my ($x,$y,$s) = split ' ',<>;
if($s < $x+$y){print "No\n";}
else{ print (($s-($x+$y))&1? "No\n" : "Yes\n");}

use strict;
use warnings;

my ($a,$b,$s);

$a = <STDIN>; $b = <STDIN>; $s = <STDIN>;
if( $s >= abs($a) + abs($b) and ($s - abs($a) - abs($b))%2 eq 0 ) {
	print "Yes";
}

print "No";


A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs  and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of schools.

Print single integer: the minimum cost of tickets needed to visit all schools.

NoteIn the first example we can buy a ticket between the schools that costs .

#!/usr/bin/perl
# POPITKA № 9998

my $a = <STDIN>;

while ($a > 0){
$result+= $a%2;
$a--;}

print $result-1;

my $n = <STDIN>;
$n-- if ($n % 2 == 0);
use integer;
print ($n/2);

#!/usr/bin/perl
#BOG PERLA NA SVYAZI

    my $a = <STDIN>;
    my $check = $a;

    while ($a > 0){
    $b = $a; $a--; $c = $a;
    $result+= ($b+$c)%(2+1);
    $a--;
    }

    if ($check%2 == 0){
    print $result;}
    else {
    print $result-1;}

#!/usr/bin/perl
#BOG PERLA NA SVYAZI

my $a = 31809;

while ($a > 0){
$result+= $a%2;
$a--;}

print $result-1;

#!/usr/bin/perl
#BOG PERLA NA SVYAZI

    my $a = <STDIN>;
    my $check = $a;

    while ($a >= 0){
    $b = $a; $a--; $c = $a;
    $result+= ($b+$c)%(2+1);
    $a--;
    }

    if ($check%2 == 0){
    print $result;}
    else {
    print $result-1;}


Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent.Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direction of increasing numbers (in this order entrance n should be followed by entrance 1). The negative value of b corresponds to moving |b| entrances in the order of decreasing numbers (in this order entrance 1 is followed by entrance n). If b = 0, then Vasya prefers to walk beside his entrance.    Illustration for n = 6, a = 2, b =  - 5. Help Vasya to determine the number of the entrance, near which he will be at the end of his walk.

The single line of the input contains three space-separated integers n, a and b (1 ≤ n ≤ 100, 1 ≤ a ≤ n,  - 100 ≤ b ≤ 100) — the number of entrances at Vasya's place, the number of his entrance and the length of his walk, respectively.

Print a single integer k (1 ≤ k ≤ n) — the number of the entrance where Vasya will be at the end of his walk.

NoteThe first example is illustrated by the picture in the statements.

print eval sprintf "1 + ( %d + %d - 1 ) %% %d", reverse split ' ', <>


You have two variables a and b. Consider the following sequence of actions performed with these variables: If a = 0 or b = 0, end the process. Otherwise, go to step 2; If a ≥ 2·b, then set the value of a to a - 2·b, and repeat step 1. Otherwise, go to step 3; If b ≥ 2·a, then set the value of b to b - 2·a, and repeat step 1. Otherwise, end the process.Initially the values of a and b are positive integers, and so the process will be finite.You have to determine the values of a and b after the process ends.

The only line of the input contains two integers n and m (1 ≤ n, m ≤ 1018). n is the initial value of variable a, and m is the initial value of variable b.

Print two integers — the values of a and b after the end of the process.

NoteExplanations to the samples: a = 12, b = 5  a = 2, b = 5  a = 2, b = 1  a = 0, b = 1; a = 31, b = 12  a = 7, b = 12.

#!/usr/bin/perl

use warnings;
use strict;
use bigint;

$\ = $/;

while(<>){
	my( $A, $B ) = map 0 + $_, split;

	while( 1 ){
		if( $A == 0 or $B == 0 ){
			last;
			}
		elsif( $A >= 2 * $B ){
			$A %= 2 * $B;
			}
		elsif( $B >= 2 * $A ){
			$B %= 2 * $A;
			}
		else{
			last;
			}
		}

	print "$A $B";
	}


Tattah's youngest brother, Tuftuf, is new to programming.Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava.Today, Tuftuf was introduced to Gava's unsigned integer datatypes. Gava has n unsigned integer datatypes of sizes (in bits) a1, a2, ... an. The i-th datatype have size ai bits, so it can represent every integer between 0 and 2ai - 1 inclusive. Tuftuf is thinking of learning a better programming language. If there exists an integer x, such that x fits in some type i (in ai bits) and x·x does not fit in some other type j (in aj bits) where ai < aj, then Tuftuf will stop using Gava.Your task is to determine Tuftuf's destiny.

The first line contains integer n (2 ≤ n ≤ 105) — the number of Gava's unsigned integer datatypes' sizes. The second line contains a single-space-separated list of n integers (1 ≤ ai ≤ 109) — sizes of datatypes in bits. Some datatypes may have equal sizes.

Print "YES" if Tuftuf will stop using Gava, and "NO" otherwise.

NoteIn the second example, x = 7 (1112) fits in 3 bits, but x2 = 49 (1100012) does not fit in 4 bits.

#!perl

$n = <STDIN>;
$str = <STDIN>;
@types = split /\D/, $str;
@types = sort {$a<=>$b} @types;
if ($n == 1) {
	print "NO";
} else {
	for ($i = 0; $i < $n-1; $i++) {
		if (($types[$i] != $types[$i+1]) && ($types[$i+1] / $types[$i] < 2)) {
			print "YES";
			goto end;
		}
	}
}
print "NO";
end:

#!perl

$n = <STDIN>;
$str = <STDIN>;
@types = split /\D/, $str;
@types = sort {$a<=>$b} @types;
if ($n == 1) {
	print "NO";
} else {
	for ($i = 1; $i < $n - 1; $i++) {
		if ($types[$i] / $types[$i-1] < 2) {
			print "YES";
			goto end;
		}
	}
}
print "NO";
end:

#!perl

$n = <STDIN>;
$str = <STDIN>;
@types = split /\D/, $str;
@types = sort {$a<=>$b} @types;
if ($n == 1) {
	print "NO";
} else {
	for ($i = 1; $i < $n - 1; $i++) {
		if ($types[$i] / $types[$i-1] < 2) {
			print "YES";
		} else {
			print "NO";
		}
	}
}

#!perl

$n = <STDIN>;
$str = <STDIN>;
@types = split /\D/, $str;
@types = sort {$a<=>$b} @types;
if ($n == 1) {
	print "NO";
} else {
	for ($i = 1; $i < $n - 1; $i++) {
		if (($types[$i] != $types[$i-1]) && ($types[$i] / $types[$i-1] < 2)) {
			print "YES";
			goto end;
		}
	}
}
print "NO";
end:


Recently Vasya found a golden ticket — a sequence which consists of $$$n$$$ digits $$$a_1a_2\dots a_n$$$. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket $$$350178$$$ is lucky since it can be divided into three segments $$$350$$$, $$$17$$$ and $$$8$$$: $$$3+5+0=1+7=8$$$. Note that each digit of sequence should belong to exactly one segment.Help Vasya! Tell him if the golden ticket he found is lucky or not.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of digits in the ticket. The second line contains $$$n$$$ digits $$$a_1 a_2 \dots a_n$$$ ($$$0 \le a_i \le 9$$$) — the golden ticket. Digits are printed without spaces.

If the golden ticket is lucky then print "YES", otherwise print "NO" (both case insensitive).

NoteIn the first example the ticket can be divided into $$$7$$$, $$$34$$$ and $$$52$$$: $$$7=3+4=5+2$$$.In the second example it is impossible to divide ticket into segments with equal sum.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my $sum = eval join ' + ', split //;

	my $ok = 0;

	for my $i ( 2 .. 100 ){
		my $d = $sum / $i;
		next if $d =~ /\./;

		my $s = 0;
		my $c = 0;

		while( /./g ){
			$s += $&;
			if( $s == $d ){
				$c ++;
				$s = 0;
				}
			}

		$i == $c and do {
			$ok = 1;
			last;
			};
		}

	print $ok ? "YES" : "NO";
	}


Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second — v0 + a pages, at third — v0 + 2a pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than v1 pages per day.Also, to refresh his memory, every day, starting from the second, Mister B had to reread last l pages he read on the previous day. Mister B finished the book when he read the last page for the first time.Help Mister B to calculate how many days he needed to finish the book.

First and only line contains five space-separated integers: c, v0, v1, a and l (1 ≤ c ≤ 1000, 0 ≤ l < v0 ≤ v1 ≤ 1000, 0 ≤ a ≤ 1000) — the length of the book in pages, the initial reading speed, the maximum reading speed, the acceleration in reading speed and the number of pages for rereading.

Print one integer — the number of days Mister B needed to finish the book.

NoteIn the first sample test the book contains 5 pages, so Mister B read it right at the first day.In the second sample test at first day Mister B read pages number 1 - 4, at second day — 4 - 11, at third day — 11 - 12 and finished the book.In third sample test every day Mister B read 1 page of the book, so he finished in 15 days.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $c, $v0, $v1, $a, $l ) = split;
	my $last = 0;
	my $d = 0;
	$v0 -= $a;

	while( 1 ){
		$d ++;
		$last -= $l;
		$last < 0 and $last = 0;
		$last += ($v0 += $a) > $v1 ? $v1 : $v0;
	#	print " :$last";
		$last >= $c and last;
		}

	print $d;
	}