You are given two positive integers $$$a$$$ and $$$b$$$.In one move, you can change $$$a$$$ in the following way:  Choose any positive odd integer $$$x$$$ ($$$x > 0$$$) and replace $$$a$$$ with $$$a+x$$$;  choose any positive even integer $$$y$$$ ($$$y > 0$$$) and replace $$$a$$$ with $$$a-y$$$. You can perform as many such operations as you want. You can choose the same numbers $$$x$$$ and $$$y$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is given as two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case, print the answer — the minimum number of moves required to obtain $$$b$$$ from $$$a$$$ if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.

NoteIn the first test case, you can just add $$$1$$$.In the second test case, you don't need to do anything.In the third test case, you can add $$$1$$$ two times.In the fourth test case, you can subtract $$$4$$$ and add $$$1$$$.In the fifth test case, you can just subtract $$$6$$$.

#!/usr/bin/env perl

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

use Carp;

# essential
my @tokens = ();

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

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

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

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

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

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

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

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

    $$ref = !$$ref;
}

sub odd {
    my $num = shift;
    return $num % 2 == 1;
}

sub even {
    my $num = shift;
    return $num % 2 == 0;
}

# solution

my $n = read_token;

for (1..$n) {
    my ($a, $b) = split q{ }, read_line;
    if ($a == $b) {
        say 0;
        next;
    }
    if ($a > $b) {
        if (even($a - $b)) {
            say 1;
        }
        else {
            say 2;
        }
    }
    else {
        if (odd($b - $a)) {
            say 1;
        }
        else {
            say 2;
        }
    }
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	if( $A == $B ){
		print 0;
		}

	elsif( $A % 2 == 0 and $B % 2 == 1 and $A < $B ){
		print 1;
		}
	elsif( $A % 2 == 0 and $B % 2 == 0 and $A < $B ){
		print 2;
		}
	elsif( $A % 2 == 1 and $B % 2 == 1 and $A < $B ){
		print 2;
		}
	elsif( $A % 2 == 1 and $B % 2 == 0 and $A < $B ){
		print 1;
		}

	elsif( $A % 2 == 0 and $B % 2 == 1 and $A > $B ){
		print 2;
		}
	elsif( $A % 2 == 0 and $B % 2 == 0 and $A > $B ){
		print 1;
		}
	elsif( $A % 2 == 1 and $B % 2 == 1 and $A > $B ){
		print 1;
		}
	elsif( $A % 2 == 1 and $B % 2 == 0 and $A > $B ){
		print 2;
		}

	}


Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties:  the upper half of matrix c (rows with numbers from 1 to x) exactly matches b;  the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?

The first line contains two integers, n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains m integers — the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≤ aij ≤ 1) — the i-th row of the matrix a.

In the single line, print the answer to the problem — the minimum number of rows of matrix b.

NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001


Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e.  or  (or both).Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the prize graph, respectively. Each of the next m lines contains a pair of integers ui and vi (1  ≤  ui,  vi  ≤  n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges.

If it's impossible to split the graph between Pari and Arya as they expect, print "-1" (without quotes). If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers — the indices of vertices. Note that because of m ≥ 1, vertex cover cannot be empty.

NoteIn the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish).In the second sample, there is no way to satisfy both Pari and Arya.

use feature 'state';
use experimental qw(autoderef postderef);

sub input { $_ = <>; chomp; split }
($n, $m) = input;
for (1..$n) {
	$conn[$_] = [];
	$mark[$_] = 0;
}
for (1..$m) {
	($a, $b) = input;
	push $conn[$a], $b;
	push $conn[$b], $a;
}

sub find_start {
	state $i;
	for ($i++; $i <= $n; $i++) {
		if ($mark[$i] == 0 && $conn[$i]->@* > 0) {
			return $i;
		}
	}
	undef;
}

while ($start = find_start) {
	@queue = ($start);
	$mark[$start] = 1;
        while (@queue) {
        	$a = shift @queue;
        	$mark_a = $mark[$a];
        	$mark_b = ($mark_a == 1? 2: 1);
        	for $b ($conn[$a]->@*) {
        		if ($mark[$b] == 0) {
        			$mark[$b] = $mark_b;
        			push @queue, $b;
        		} elsif ($mark[$b] != $mark_b) {
        			print -1;
        			exit;
        		}
        	}
        }
}

for (1..$n) {
	push @A, $_ if $mark[$_] == 1;
	push @B, $_ if $mark[$_] == 2;
}
print 0 + @A, "\n@A\n";
print 0 + @B, "\n@B\n";

use experimental qw(autoderef postderef);

sub input { $_ = <>; chomp; split }
($n, $m) = input;
for (1..$n) {
	$conn[$_] = [];
	$mark[$_] = 0;
}
for (1..$m) {
	($a, $b) = input;
	push $conn[$a], $b;
	push $conn[$b], $a;
}
@queue = ($a);
$mark[$a] = 1;

while (@queue) {
	$a = shift @queue;
	$mark_a = $mark[$a];
	$mark_b = ($mark_a == 1? 2: 1);
	for $b ($conn[$a]->@*) {
		if ($mark[$b] == 0) {
			$mark[$b] = $mark_b;
			push @queue, $b;
		} elsif ($mark[$b] != $mark_b) {
			print -1;
			exit;
		}
	}
}

for (1..$n) {
	push @A, $_ if $mark[$_] == 1;
	push @B, $_ if $mark[$_] == 2;
}
sub number { $a <=> $b }
@A = sort number @A;
@B = sort number @B;
print 0 + @A, "\n@A\n";
print 0 + @B, "\n@B\n";

use feature 'state';
use experimental qw(autoderef postderef);

sub input { $_ = <>; chomp; split }
($n, $m) = input;
for (1..$n) {
	$conn[$_] = [];
	$mark[$_] = 0;
}
for (1..$m) {
	($a, $b) = input;
	push $conn[$a], $b;
	push $conn[$b], $a;
}

sub find_start {
	state $i;
	for ($i++; $i <= $n; $i++) {
		if ($mark[$_] == 0 && $conn[$_]->@* > 0) {
			return $_;
		}
	}
	undef;
}

while ($start = find_start) {
	@queue = ($start);
	$mark[$start] = 1;
        while (@queue) {
        	$a = shift @queue;
        	$mark_a = $mark[$a];
        	$mark_b = ($mark_a == 1? 2: 1);
        	for $b ($conn[$a]->@*) {
        		if ($mark[$b] == 0) {
        			$mark[$b] = $mark_b;
        			push @queue, $b;
        		} elsif ($mark[$b] != $mark_b) {
        			print -1;
        			exit;
        		}
        	}
        }
}

for (1..$n) {
	push @A, $_ if $mark[$_] == 1;
	push @B, $_ if $mark[$_] == 2;
}
print 0 + @A, "\n@A\n";
print 0 + @B, "\n@B\n";


There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i < n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.

The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.

Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl.  Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.

NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.

#!/usr/bin/perl
use strict;
use warnings;
open(INPUT, "< input.txt");
open(OUTPUT, "> output.txt");
my ($n, $m) = map int, split /\D/, <INPUT>;
if ($n > $m) {
    for my $i (1..$m) {
	print OUTPUT "BG";
    }
    for my $i (1..$n-$m) {
	print OUTPUT "B";
    }
} else {
    for my $i (1..$n) {
	print OUTPUT "GB";
    }
    for my $i (1..$m-$n) {
	print OUTPUT "G";
    }
}


The grasshopper is located on the numeric axis at the point with coordinate $$$x_0$$$.Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $$$x$$$ with a distance $$$d$$$ to the left moves the grasshopper to a point with a coordinate $$$x - d$$$, while jumping to the right moves him to a point with a coordinate $$$x + d$$$.The grasshopper is very fond of positive integers, so for each integer $$$i$$$ starting with $$$1$$$ the following holds: exactly $$$i$$$ minutes after the start he makes a jump with a distance of exactly $$$i$$$. So, in the first minutes he jumps by $$$1$$$, then by $$$2$$$, and so on.The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.For example, if after $$$18$$$ consecutive jumps he arrives at the point with a coordinate $$$7$$$, he will jump by a distance of $$$19$$$ to the right, since $$$7$$$ is an odd number, and will end up at a point $$$7 + 19 = 26$$$. Since $$$26$$$ is an even number, the next jump the grasshopper will make to the left by a distance of $$$20$$$, and it will move him to the point $$$26 - 20 = 6$$$.Find exactly which point the grasshopper will be at after exactly $$$n$$$ jumps.

The first line of input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$x_0$$$ ($$$-10^{14} \leq x_0 \leq 10^{14}$$$) and $$$n$$$ ($$$0 \leq n \leq 10^{14}$$$) — the coordinate of the grasshopper's initial position and the number of jumps.

Print exactly $$$t$$$ lines. On the $$$i$$$-th line print one integer — the answer to the $$$i$$$-th test case — the coordinate of the point the grasshopper will be at after making $$$n$$$ jumps from the point $$$x_0$$$.

NoteThe first two test cases in the example correspond to the first two jumps from the point $$$x_0 = 0$$$. Since $$$0$$$ is an even number, the first jump of length $$$1$$$ is made to the left, and the grasshopper ends up at the point $$$0 - 1 = -1$$$.Then, since $$$-1$$$ is an odd number, a jump of length $$$2$$$ is made to the right, bringing the grasshopper to the point with coordinate $$$-1 + 2 = 1$$$.

use POSIX;
my $line;
my @input1; my @input2;
my $key1 = 0; my $key2 = 0; my $key3 = 0; my $key4 = 0;
my $s = 0; my $c; my $result; my $i; my %h;

$line = <STDIN>;
chomp($line);
@input1 = split(' ', $line);

#$line = <STDIN>;
#chomp($line);
#@input2 = split(' ', $line);

my $line2;
for(1..@input1[0]) {
        $line = <STDIN>;
        chomp($line);
        @input2 = split(' ', $line);
        $s = @input2[1] % 4;
        if (@input2[0] % 2) {
                if ($s == 0) { print $input2[0], "\n"; }
                if ($s == 1) { print $input2[0] + $input2[1], "\n"; }
                if ($s == 2) { print $input2[0] -  1, "\n";}
                if ($s == 3) { print $input2[0] - (@input2[1] + 1), "\n"; }
        } else {
                if ($s == 0) { print $input2[0], "\n"; }
                if ($s == 1) { print $input2[0] - $input2[1], "\n"; }
                if ($s == 2) { print $input2[0] + 1, "\n"; }
                if ($s == 3) { print $input2[1] + @input2[0] + 1, "\n";}
        }
}


Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task.The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array   $$$[1, 1, 1]$$$ is $$$1$$$;  $$$[5, 7]$$$ is $$$2$$$, as it could be split into blocks $$$[5]$$$ and $$$[7]$$$;  $$$[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$$$ is 3, as it could be split into blocks $$$[1]$$$, $$$[7, 7, 7, 7, 7, 7, 7]$$$, and $$$[9, 9, 9, 9, 9, 9, 9, 9, 9]$$$. You are given an array $$$a$$$ of length $$$n$$$. There are $$$m$$$ queries of two integers $$$i$$$, $$$x$$$. A query $$$i$$$, $$$x$$$ means that from now on the $$$i$$$-th element of the array $$$a$$$ is equal to $$$x$$$.After each query print the sum of awesomeness values among all subsegments of array $$$a$$$. In other words, after each query you need to calculate $$$$$$\sum\limits_{l = 1}^n \sum\limits_{r = l}^n g(l, r),$$$$$$ where $$$g(l, r)$$$ is the awesomeness of the array $$$b = [a_l, a_{l + 1}, \ldots, a_r]$$$.

In the first line you are given with two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. In the next $$$m$$$ lines you are given the descriptions of queries. Each line contains two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq x \leq 10^9$$$).

Print the answer to each query on a new line.


According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.  However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.Write a program that models the behavior of Ankh-Morpork residents.

The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks. The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

NoteIn the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.

use strict;
use warnings;

use feature qw/say/;
{
    my $n = <>;
    chomp $n;
    my %has;
    my $temp_heap = $n;
    my @values;
    {
        local $/ = ' ';
        for (my $i=1;$i<=$n;$i++){
            if ($i == $n){
                $/ = "\n";
            }
            my $str = <>;
            chomp $str;
            $has{$str} = 1;

            while (defined $has{$temp_heap} ){
                print $temp_heap . " ";
                $temp_heap--;
            }
            print "\n";
        }
    }
}

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

#open (my $F1, "<", "a") or die "a: $!";
#my $num=0;
my %Q=();
my $num = <>;
chomp($num);
my $line2 = <>;
chomp($line2);
my @snacks = split (" ", $line2);
my $len = scalar @snacks;
if ($num != $len ) { print "Error: $num != $len\n";exit(1);}
#print "num=$num\n";
#print "snacks:@snacks\n";
#close($F1);
##############################################
my $wait_for = $num;
for (my $i=0;$i < $num;$i++) {
   if ($wait_for == $snacks[$i] ) {
      print "$wait_for";
      $wait_for--;
      #while (my $ele = pop (@Q)) {
      while ($Q{$wait_for}) {
         #if ($wait_for == $ele) {
            print " $wait_for";
            $wait_for--;

      }
      print "\n";
   } else {
      print "\n";
      $Q{$snacks[$i]} = 1;
      #push (@Q,$snacks[$i]);
   }
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

while(<>){
	chomp;

	@_ = (-1, 1 .. $_);

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

	my $last = $_;

	for my $i ( @A ){

		$_[ $i ] = 0;

		my @out;

		while( $_[ $last ] == 0 ){
			push @out, $last --
			}

		print "@out";
		}

	$debug and print '-' x 10;
	}

use strict;
use warnings;

use feature qw/say/;
{
    my $n = <>;
    chomp $n;

    my $temp_heap = $n+1;
    my @values;
    {
        local $/ = ' ';
        for (my $i=1;$i<=$n;$i++){
            if ($i == $n){
                $/ = "\n";
            }
            my $str = <>;
            chomp $str;
            push @values, $str;
            @values = reverse sort @values;
            while (defined $values[0] && $values[0]+1 == $temp_heap ){
                my $new_heap = shift @values;
                print $new_heap . " ";
                $temp_heap = $new_heap;
            }
            print "\n";
        }
    }
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

while(<>){
	chomp;

	@_ = (-1, 1 .. $_);

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

	my $c = $_;
	my $last = $_;

	for my $i ( reverse 1 .. @_ - 1 ){
		my $num = shift @A;
		$_[ $num ] = 0;
		if( $num >= $i ){ $c-- }
		$debug and print "  $c";
		if( $num != $i and $_[ $i ] == 0 ){ $c-- }
		$debug and print "    $c";
		if( $c < $i ){
			print join ' ', reverse $c + 1 .. $last;
			$last = $c;
			}
		else{
			print ''
			}
		}

	$debug and print '-' x 10;
	}


A number is called 2050-number if it is $$$2050$$$, $$$20500$$$, ..., ($$$2050 \cdot 10^k$$$ for integer $$$k \ge 0$$$).Given a number $$$n$$$, you are asked to represent $$$n$$$ as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.

The first line contains a single integer $$$T$$$ ($$$1\le T\leq 1\,000$$$) denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^{18}$$$) denoting the number to be represented.

For each test case, output the minimum number of 2050-numbers in one line.  If $$$n$$$ cannot be represented as the sum of 2050-numbers, output $$$-1$$$ instead.


Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj = xi.Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.

The first input line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of markers and the number of caps, correspondingly.  Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1 ≤ xi, yi ≤ 1000) — the i-th marker's color and diameter, correspondingly. Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1 ≤ aj, bj ≤ 1000) — the color and diameter of the j-th cap, correspondingly.

Print two space-separated integers u, v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.

NoteIn the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed — the first and the third markers.

#!/usr/bin/perl

my ($n,$m) = split /\s+/, <STDIN>, -1;

my %pens;
my %caps;

for (my $i = 0; $i < $n; $i++) {
    my ($color,$dia) = split /\s+/, <STDIN>, -1;
    $pens{$dia + 0}{$color + 0}++;
    $pens_nc{$dia + 0}++;
}

for (my $i = 0; $i < $m; $i++) {
    my ($color,$dia) = split /\s+/, <STDIN>, -1;
    $caps{$dia + 0}{$color + 0}++;
    $caps_nc{$dia + 0}++;
}

my $beauty = 0;
foreach my $dia (keys %pens) {
    my $mpens = $pens{$dia};
    foreach my $color (keys %$mpens) {
	my $npens = $mpens->{$color};
	if (!$npens) { next; }
	my $ncups = $caps{$dia}{$color};
	if (!$ncups) { next; }

	my $min = ($npens < $ncups) ? $npens : $ncups;

	$beauty += $min;
	$caps{$dia}{$color} -= $min;
	$mpens->{$color} -= $min;
	$caps_nc{$dia} -= $min;
	$pens_nc{$dia} -= $min;
    }
}

my $ok = 0;
foreach my $dia (keys %pens_nc) {
    my $npens = $pens_nc{$dia};
    if (!$npens) { next; }
    my $ncups = $caps_nc{$dia};
    if (!$ncups) { next; }

    my $min = ($npens < $ncups) ? $npens : $ncups;
    $ok += $min;
}

print $ok + $beauty . " " . $beauty . "\n";


The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.Satisfy Arkady's curiosity and tell him the final version of the name.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the length of the initial name and the number of designers hired, respectively. The second line consists of n lowercase English letters and represents the original name of the corporation. Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters xi and yi.

11 6
abacabadaba
a b
b c
a d
e g
f a
b b

NoteIn the second sample the name of the corporation consecutively changes as follows:

#!/usr/bin/perl

($n, $m) = split /\s/, <>;

$name = <>;
chomp $name;

@name_letters = split //, $name;

for my $i (0..$#name_letters)
{
    $h{@name_letters[$i]} = [] if ! exists   $h{@name_letters[$i]};

    push @{$h{@name_letters[$i]}}, $i;
}

for (1..$m)
{
    my $xy = <>;
    chomp $xy;
    (my $x, my $y) = split /\s/, $xy;

    if($x ne $y)
    {
    if(exists $h{$x} and exists $h{$y})
        {
        my $ar_ref = $h{$x};
            $h{$x} = $h{$y};
            $h{$y} = $ar_ref;
    }
        elsif(exists $h{$x})
        {
        my $ar_ref = $h{$x};
            delete  $h{$x};
            $h{$y} = $ar_ref;
        }
        elsif(exists $h{$y})
        {
        my $ar_ref = $h{$y};
            delete  $h{$y};
            $h{$x} = $ar_ref;
        }
    }
}

for my $letter (keys %h)
{
    for my $i (@{$h{$letter}})
    {
    @name_letters[$i] = $letter;
    }
}

$name = join '', @name_letters;

print $name, "\n";


In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.For example, for n = 4 the sum is equal to  - 1 - 2 + 3 - 4 =  - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.Calculate the answer for t values of n.

The first line of the input contains a single integer t (1 ≤ t ≤ 100) — the number of values of n to be processed. Each of next t lines contains a single integer n (1 ≤ n ≤ 109).

Print the requested sum for each of t integers n given in the input.

NoteThe answer for the first sample is explained in the statement.

#!/usr/bin/perl

use 5.010;
use strict;
use warnings;
use bignum;

my $count=<>;
my $sum;
my $temp;

for (my $i=0;$i<$count;$i+=1)
{
	$temp=1;
	my $number=<>;
	$sum = (1 + $number) * ($number / 2);

	while ($temp <= $number)
	{
		$sum = $sum - ($temp * 2);
		$temp = $temp * 2;
	}
	print $sum ;
	print "\n" ;
}

#!/usr/bin/perl -w
use bigint;

sub doit {
    my $n = $_[0];
    my $next_power_of_two = 1;
    while ($next_power_of_two <= $n) {
        $next_power_of_two *= 2;
    }
    $n * ($n + 1) / 2 - 2 * ($next_power_of_two - 1);
}

my $t = <>;
for (1..$t) {
    my $n = <>;
    print doit($n), "\n";
}

use strict;
use warnings;

my $case = <STDIN>;

for my $i(0..$case - 1){
	my $num = <STDIN>;
	my $sum = 0;
	my $exp = 0;

	$sum = ($num * ($num + 1)) >> 1;
	for my $j(0..$num - 1){
		if($num < (1 << $j)){
			$exp = $j;
			last;
		}
	}

	$sum -= (2 * ((1 << $exp) - 1));

	if($num == 1){
		print "-1\n";
	}elsif($num == 2){
		print "-3\n";
	}else{
		print $sum, "\n";
	}
}

#!/usr/bin/perl

use 5.010;
use strict;
use warnings;

my $count=<>;
my $sum;
my $temp;

for (my $i=0;$i<$count;$i+=1)
{
	$temp=1;
	my $number=<>;
	$sum = (1 + $number) * ($number / 2);

	while ($temp <= $number)
	{
		$sum = $sum - ($temp * 2);
		$temp = $temp * 2;
	}
	print $sum ;
	print "\n" ;
}

use strict;
use warnings;

my $case = <STDIN>;

for my $i(0..$case){
	my $num = <STDIN>;
	my $sum = 0;
	my $exp = 0;

	$sum = ($num * ($num + 1)) >> 1;
	for my $j(0..$num - 1){
		if($num < (1 << $j)){
			$exp = $j;
			last;
		}
	}

	$sum -= (2 * ((1 << $exp) - 1));

	if($num == 1){
		print "-1\n";
	}elsif($num == 2){
		print "-3\n";
	}else{
		print $sum, "\n";
	}
}

use strict;
use warnings;

my $case = <STDIN>;

for my $i(0..$case){
	my $num = <STDIN>;
	my $sum = 0;
	my $exp = 0;

	$sum = ($num * ($num + 1)) >> 1;
	for my $j(0..$num){
		if($num < (1 << $j)){
			$exp = $j;
			last;
		}
	}

	$sum -= (2 * ((1 << $exp) - 1));

	if($num == 1){
		print "-1\n";
	}elsif($num == 2){
		print "-3\n";
	}else{
		print $sum, "\n";
	}
}


You are given an array $$$a[0 \dots n-1]$$$ of $$$n$$$ integers. This array is called a "valley" if there exists exactly one subarray $$$a[l \dots r]$$$ such that:  $$$0 \le l \le r \le n-1$$$,  $$$a_l = a_{l+1} = a_{l+2} = \dots = a_r$$$,  $$$l = 0$$$ or $$$a_{l-1} > a_{l}$$$,  $$$r = n-1$$$ or $$$a_r < a_{r+1}$$$. Here are three examples:  The first image shows the array [$$$3, 2, 2, 1, 2, 2, 3$$$], it is a valley because only subarray with indices $$$l=r=3$$$ satisfies the condition.The second image shows the array [$$$1, 1, 1, 2, 3, 3, 4, 5, 6, 6, 6$$$], it is a valley because only subarray with indices $$$l=0, r=2$$$ satisfies the codition.The third image shows the array [$$$1, 2, 3, 4, 3, 2, 1$$$], it is not a valley because two subarrays $$$l=r=0$$$ and $$$l=r=6$$$ that satisfy the condition.You are asked whether the given array is a valley or not.Note that we consider the array to be indexed from $$$0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases is smaller than $$$2\cdot10^5$$$.

For each test case, output "YES" (without quotes) if the array is a valley, and "NO" (without quotes) otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteThe first three test cases are explained in the statement.


Two people are playing a game with a string $$$s$$$, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses.Your task is to determine which player will win if both play optimally.

The only line contains the string $$$s$$$, consisting of lowercase latin letters ($$$1 \leq |s| \leq 100\,000$$$), where $$$|s|$$$ means the length of a string $$$s$$$.

If the first player wins, print "Yes". If the second player wins, print "No".

NoteIn the first example the first player is unable to make a turn, so he loses.In the second example first player turns the string into "q", then second player is unable to move, so he loses.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

while(<>){
	chomp;

	my $del = 0;

	@_ = ();

	for( split // ){
		push @_, $_;
		if( @_ > 1 and $_[ -2 ] eq $_[ -1 ] ){
			pop @_ for 1 .. 2;
			$del ++;
			}
	}

	print $del % 2 ? "Yes" : "No";
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

while(<>){
	chomp;

	my $del = 0;

	@_ = ();

	for( split // ){
		if( @_ > 0 and $_ eq $_[ -1 ] ){
			pop @_;
			$del ++;
			}
		else{
			push @_, $_;
			}
	}

	print $del % 2 ? "Yes" : "No";
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	chomp;

	my $del = 0;

	my $pos = pos;

	( pos ) = $pos < 0 ? 0 : $pos while s/\G.*?\K(.)\1(?{ $del ++; $pos = ( pos ) - 3; })//x;

	print $del % 2 ? "Yes" : "No";
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	chomp;

	my $del = 0;

	my $pos = pos;

	( pos ) = $pos while s/\G.*?\K(.)\1(?{ $del ++; $pos = ( pos ) - 3; })//x;

	print $del % 2 ? "Yes" : "No";
	}


Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns. Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street?

The first line contains two integers n, l (1 ≤ n ≤ 1000, 1 ≤ l ≤ 109) — the number of lanterns and the length of the street respectively.  The next line contains n integers ai (0 ≤ ai ≤ l). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street.

Print the minimum light radius d, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.

NoteConsider the second sample. At d = 2 the first lantern will light the segment [0, 4] of the street, and the second lantern will light segment [3, 5]. Thus, the whole street will be lit.

#!/usr/bin/perl
use v5.10;
# use List::Util qw(first max maxstr min minstr reduce shuffle sum);

sub max {
    my ($x, $y) = (shift, shift);
    return $x>$y ? $x:$y;
}

($n, $l) = split / /, <>;
@a = sort {$a <=> $b} split / /, <>;
$ans = max ($a[0]*2, ($l-$a[-1])*2);
$ans = max $ans,$a[$_]-$a[$_-1] foreach (1..$n-1);
say $ans/2;

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

my $n; my $l;
my @num;
sub valid{
    my $d = shift;
    my $last = 0;
    for my $i(0..$n-1){
        return 0 if $num[$i]-$d > $last;
        $last = $last > $num[$i] + $d ? $last : $num[$i] + $d;
    }
    return $last >= $l;
}

($n,$l) = split ' ',<>;
@num = split ' ',<>;
@num = sort {$a <=> $b} @num;
my ($start,$len) = (0,$l+1);
while($len > 1e-11){
    $len /= 2.0;
    my $mid = $start + $len;
    $start = $mid if(!valid($mid)) ;
}

printf "%0.11f\n",$start;

#!/usr/bin/perl
use v5.10;
#use List::Util qw(first max maxstr min minstr reduce shuffle sum);

sub max {
    my ($x, $y) = (shift, shift);
    return $x>$y ? $x:$y;
}

($n, $l) = split / /, <>;
@a = sort {$a <=> $b} split / /, <>;
$ans = max ($a[0]*2, (l-$a[-1])*2);
$ans = max ($ans,$a[$_]-$a[$_-1]) foreach (1..$n-1);
say $ans/2;

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

my $n; my $l;
my @num;
sub valid{
    my $d = shift;
    my $last = 0;
    for my $i(0..$n-1){
        return 0 if $num[$i]-$d > $last;
        $last = $last > $num[$i] + $d ? $last : $num[$i] + $d;
    }
    return $last >= $l;
}

($n,$l) = split ' ',<>;
@num = split ' ',<>;
@num = sort {$a <=> $b} @num;
my ($low,$high) = (0,$l+1);
while($high - $low > 1e-8){
    my $mid = ($low + $high) / 2;
    if(valid($mid)){
        $high = $mid;
    }
    else{
        $low = $mid;
    }
}

printf "%0.11   f\n",$low;


The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.The site of the University has already conducted a voting that estimated each sculpture's characteristic of ti — the degree of the sculpture's attractiveness. The values of ti can be positive, negative or zero.When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that:   the remaining sculptures form a regular polygon (the number of vertices should be between 3 and n),  the sum of the ti values of the remaining sculptures is maximized. Help the Vice Rector to analyze the criticism — find the maximum value of ti sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.

The first input line contains an integer n (3 ≤ n ≤ 20000) — the initial number of sculptures. The second line contains a sequence of integers t1, t2, ..., tn, ti — the degree of the i-th sculpture's attractiveness ( - 1000 ≤ ti ≤ 1000). The numbers on the line are separated by spaces.

Print the required maximum sum of the sculptures' attractiveness.

NoteIn the first sample it is best to leave every second sculpture, that is, leave sculptures with attractivenesses: 2, 4, 5 и 3.

#!perl
sub sum{
	my $step = shift;
	my $start = shift;
	my $s = 0;
	for(my $i = $start; $i <= $#_; $i += $step){
		$s += $_[$i];
	}
	$s;
}
my $n = <STDIN>;
if ($n <= 2) {
	die "wrong input\n";
}
my @possible;
$m = sqrt($n);
for (my $i = 2; $i <= $m; $i++) {
	if (0 == $n % $i) {
		$d = int $n / $i;
		push @possible, $i if $d >= 3;
		push @possible, $d if $i >= 3;
	}
}

my @statues = map {int $_} grep {/^-?\d+$/} split / +/, <STDIN>;
@statues = @statues[0..($n-1)];
my $max = sum 1, 0, @statues;
for my $k(@possible){
	for (0..($k-1)) {
		my $s = sum $k, $_, @statues;
		$max = $s if ($s > $max);
	}
}
print $max."\n";

#!/usr/bin/perl
# Codeforces Practice - 26 May 2012
use strict;
use warnings;
use Math::Complex;

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

my @tis = split(" ",<STDIN>);

my $tSum =0;
$tSum += $_ for @tis; #summing up the array

if($n<6) {
    print $tSum;
}

else {
    my @sums = ($tSum);
    my $count;

    #................ Calculate factors of $n

    my @factors;

    for(2..sqrt $n){
        if($n % $_ == 0){
            my $div = $n/$_;
            push(@factors,$_);
            unless($div == $_){
                push(@factors,$div);
    }}}

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

    #................ Finished calculating factors of $n

    foreach my $factor (@factors){
        next if ($n / $factor < 3);
        my @factSums = ();
        my $count = 0;
        foreach my $t (@tis){
            @factSums[$count++ % $factor] += $t;
        }
        @sums = (@sums,@factSums);
    }

    my $max = $sums[0];
$_ > $max and $max = $_
    for @sums;

print $max;
}

#!/usr/bin/perl -w

use strict;
use List::Util qw(sum max);

my $n = <>;
my @t = split ' ', <>;

my @foos = ();

for my $m (1 .. $n / 3) {
    next unless $n % $m == 0;
    for my $i (0 .. $m - 1) {
        my @foo = map { $t[$i + $m * $_] } (0 .. $n / $m - 1);
        push @foos, sum @foo;
    }
}

print max @foos;

sub game($$){
    my $r=($_[0]-1)/$_[1];
    while($r>=1){
        if ($r == 1){
            return 1;
        }
        $r/=$_[1];
    }
    return 0;
}
$\=$/;
my $max=0;
$n=<STDIN>;
my $maxn=0;
@sculptures=(0,split(" ",<STDIN>));

$pointSTOP=$n/3;

for ($index=1;$index<$n+1;$index++){

    $max+=$sculptures[$index];

}
#print "pointSTOP=".$pointSTOP."   n=".$n."\n";
for ($delims=2;(($delims<=$pointSTOP));$delims++){
    if (($n%$delims==0)){
#       print "delims="."$delims";

        for ($index=1;(($index<=$delims));$index++){
            #if (game($index,$delims)==0){
                #print "        index="."$index";
                $maxn=0;
                for ($subindex=$index-1;$subindex<$index+$n-1;($subindex+=$delims)){
                #   print "         subindex=".$subindex."    delims=".$delims."    sculpturerank=".$sculptures[$subindex%($n)+1];
                    $maxn+=$sculptures[$subindex%($n)+1];
                #   print "         maxn=".$maxn;
                }
                #print "        max=".$max."  maxn=".$maxn;
                if ($max<$maxn){
                $max=$maxn;
                }
            #}
        }
    }

}

print $max;

my ($n) = split(/\s/, <STDIN>);

my @t = split(/\s/, <STDIN>);

sub calc {
    my (@a) = @_;
    my $sum = 0;
    for my $e (@a) {
        $sum += $e;
    }
    if (scalar @a % 2 == 0 && scalar @a > 4) {
        my @b;
        my @c;
        for (my $i = 0; $i < scalar @a; $i++) {
            if ($i % 2 == 0) {
                push(@b, $a[$i]);
            } else {
                push(@c, $a[$i]);
            }
        }
        my $odd_sum = calc(@b);
        my $even_sum = calc(@c);
        $sum = $odd_sum if ($odd_sum > $sum);
        $sum = $even_sum if ($even_sum > $sum);
    }
    return $sum;
}

print calc(@t);

#!/usr/bin/perl
# Codeforces Practice - 26 May 2012
use strict;
use warnings;

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

my @tis = split(" ",<STDIN>);
my $tSum =0;
$tSum += $_ for @tis;
if($n%2==1 || $n<6) {print $tSum;}
else {
my ($sum1,$sum2) = (0,0);
my $toggle = 0;
foreach my $t (@tis) {
    if($toggle){
        $sum1 += $t;
    } else {
        $sum2 += $t;
    }
    $toggle = not $toggle;
}
if($sum1 >= $tSum && $sum1 >= $sum2){print $sum1;}
elsif($sum2 >= $tSum && $sum2 >= $sum1){print $sum2;}
else {print $tSum;}
}

#!/usr/bin/perl
# Codeforces Practice - 26 May 2012
use strict;
use warnings;

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

my @tis = split(" ",<STDIN>);
my $tSum =0;
$tSum += $_ for @tis;
if($n%2==1) {print $tSum;}
else {
my ($sum1,$sum2) = (0,0);
my $toggle = 0;
foreach my $t (@tis) {
    if($toggle){
        $sum1 += $t;
    } else {
        $sum2 += $t;
    }
    $toggle = not $toggle;
}
if($sum1 >= $tSum && $sum1 >= $sum2){print $sum1;}
elsif($sum2 >= $tSum && $sum2 >= $sum1){print $sum2;}
else {print $tSum;}
}

#!/usr/bin/perl -w

use strict;
use List::Util qw(sum max);

my $n = <>;
my @t = split ' ', <>;

my @foos = ();

for my $m (1 .. $n) {
    next unless $n % $m == 0;
    for my $i (0 .. $m - 1) {
        my @foo = map { $t[$i + $m * $_] } (0 .. $n / $m - 1);
        push @foos, sum @foo;
    }
}

print max @foos;

sub game($$){
    my $r=($_[0]-1)/$_[1];
    while($r>=1){
        if ($r == 1){
            return 1;
        }
        $r/=$_[1];
    }
    return 0;
}
$\=$/;
my $max=0;
$n=<STDIN>;
my $maxn=0;
@sculptures=(0,split(" ",<STDIN>));

$pointSTOP=$n/3;

for ($index=1;$index<$n+1;$index++){

    $max+=$sculptures[$index];

}
#print "pointSTOP=".$pointSTOP."   n=".$n."\n";
for ($delims=2;(($delims<$pointSTOP));$delims++){
    if (($n%$delims==0)){
#       print "delims="."$delims";

        for ($index=1;(($index<=$delims));$index++){
            #if (game($index,$delims)==0){
                #print "        index="."$index";
                $maxn=0;
                for ($subindex=$index-1;$subindex<$index+$n-1;($subindex+=$delims)){
                #   print "         subindex=".$subindex."    delims=".$delims."    sculpturerank=".$sculptures[$subindex%($n)+1];
                    $maxn+=$sculptures[$subindex%($n)+1];
                #   print "         maxn=".$maxn;
                }
                #print "        max=".$max."  maxn=".$maxn;
                if ($max<$maxn){
                $max=$maxn;
                }
            #}
        }
    }

}

print $max;

sub game($$){
    my $r=($_[0]-1)/$_[1];
    while($r>=1){
        if ($r == 1){
            return 1;
        }
        $r/=$_[1];
    }
    return 0;
}
$\=$/;
my $max=0;
$n=<STDIN>;
my $maxn=0;
@sculptures=(0,split(" ",<STDIN>));

$pointSTOP=$n/3+1;

for ($index=1;$index<$n+1;$index++){

    $max+=$sculptures[$index];

}
#print "pointSTOP=".$pointSTOP."   n=".$n."\n";
for ($delims=2;(($delims<$pointSTOP));$delims++){
    if (($n%$delims==0)){
        #print "delims="."$delims";

        for ($index=1;(($index<=$delims));$index++){
            #if (game($index,$delims)==0){
            #   print "     index="."$index";
                $maxn=0;
                for ($subindex=$index-1;$subindex<$index+$n-1;($subindex+=$delims)){
                    #print "            subindex=".$subindex."    delims=".$delims."    sculpturerank=".$sculptures[$subindex%($n)+1];
                    $maxn+=$sculptures[$subindex%($n)+1];
                    #print "            maxn=".$maxn;
                }
                #print "        max=".$max."  maxn=".$maxn;
                if ($max<$maxn){
                $max=$maxn;
                }
            #}
        }
    }

}

print $max;

use strict;

my ($n) = split(/\s/, <STDIN>);

my @t = split(/\s/, <STDIN>);

sub calc {
    my (@a) = @_;
    my $sum = 0;
    for my $e (@a) {
        $sum += $e;
    }
    if (scalar @a % 2 == 0) {
        my @b;
        my @c;
        for (my $i = 0; $i < scalar @a; $i++) {
            if ($i % 2 == 0) {
                push(@b, $a[$i]);
            } else {
                push(@c, $a[$i]);
            }
        }
        my $sum_even = calc(@b);
        my $sum_odd = calc(@c);
        $sum = $sum_even if ($sum < $sum_even);
        $sum = $sum_odd if ($sum < $sum_odd);
    }
    return $sum;
}

print calc(@t) . "\n";

my ($n) = split(/\s/, <STDIN>);

my @t = split(/\s/, <STDIN>);

my @res = ();

sub calc {
    my (@a) = @_;
    my $sum = 0;
    for my $e (@a) {
        $sum += $e;
    }
    push (@res, $sum);
    if (scalar @a % 2 == 0) {
        my @b;
        my @c;
        for (my $i = 0; $i < scalar @a; $i++) {
            if ($i % 2 == 0) {
                push(@b, $a[$i]);
            } else {
                push(@c, $a[$i]);
            }
        }
        calc(@b);
        calc(@c);
    }
}

calc(@t);

my $max = $res[0];
for $e (@res) {
    $max = $e if ($max < $e);
}

print $max;


You are given a string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not.Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one).It is guaranteed that there is at least two different characters in $$$s$$$.Note that you can remove the whole string and it is correct. Also note that you should remove at least one character.Since the answer can be rather large (not very large though) print it modulo $$$998244353$$$.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in $$$s$$$.

Print one integer — the number of ways modulo $$$998244353$$$ to remove exactly one substring from $$$s$$$ in such way that all remaining characters are equal.

NoteLet $$$s[l; r]$$$ be the substring of $$$s$$$ from the position $$$l$$$ to the position $$$r$$$ inclusive.Then in the first example you can remove the following substrings:   $$$s[1; 2]$$$;  $$$s[1; 3]$$$;  $$$s[1; 4]$$$;  $$$s[2; 2]$$$;  $$$s[2; 3]$$$;  $$$s[2; 4]$$$. In the second example you can remove the following substrings:   $$$s[1; 4]$$$;  $$$s[1; 5]$$$;  $$$s[1; 6]$$$;  $$$s[1; 7]$$$;  $$$s[2; 7]$$$;  $$$s[3; 7]$$$. In the third example you can remove the following substrings:   $$$s[1; 1]$$$;  $$$s[1; 2]$$$;  $$$s[2; 2]$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;
my $MOD = 998244353;

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

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

    /./;
    my $first = $&;
	/.$/;
	my $last = $&;

	my $L = 0;
	my $R = 0;

	while( s/^$first+// ){
        $L += length $&;
        }

	$_ = reverse;

	while( s/^$last+// ){
        $R += length $&;
        }

    $debug and print " L:$L, R:$R";

    print do {
    	if( $R == 0 ){
            $len * ( $len + 1 ) / 2 % $MOD;
            }
    	elsif( $first eq $last ){
            ( $L + 1 ) * ( $R + 1 ) % $MOD;
            }
        else{
            $L + $R + 1;
            }
        };
    }

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;
my $MOD = 998244353;

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

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

    /./;
    my $first = $&;
	/.$/;
	my $last = $&;

	my $L = 0;
	my $R = 0;

	while( s/^$first+// ){
        $L += length $&;
        }

	$_ = reverse;

	while( s/^$last+// ){
        $R += length $&;
        }

    $debug and print " L:$L, R:$R";

    print do {
    	if( $R == 0 ){
            $len * ( $len + 1 ) / 2 % $MOD;
            }
    	elsif( $first eq $last ){
            ( $L + $R ) * ( $L + $R + 1 ) / 2 % $MOD;
            }
        else{
            $L + $R + 1;
            }
        };
    }


Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.Now Petya is on the first stair of the staircase, consisting of n stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number n without touching a dirty stair once.One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.

The first line contains two integers n and m (1 ≤ n ≤ 109, 0 ≤ m ≤ 3000) — the number of stairs in the staircase and the number of dirty stairs, correspondingly. The second line contains m different space-separated integers d1, d2, ..., dm (1 ≤ di ≤ n) — the numbers of the dirty stairs (in an arbitrary order).

Print "YES" if Petya can reach stair number n, stepping only on the clean stairs. Otherwise print "NO".

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

@_=split/ /,<>;
@_=sort num @_;

for $i(0..@_-3){
	if ($_[$i]==$_[$i+1]-1 and $_[$i+1]==$_[$i+2]-1){ $F++ ;last}
	}

for (@_){$_==1 || $_==$` and $F++}

print $F? "NO":"YES";
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
}


Wilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai, ai + 1, ... , an or subtract 1 from all elements ai, ai + 1, ..., an. His goal is to end up with the array b1, b2, ..., bn. Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the array ai. Initially ai = 0 for every position i, so this array is not given in the input. The second line of the input contains n integers b1, b2, ..., bn ( - 109 ≤ bi ≤ 109).

Print the minimum number of steps that Wilbur needs to make in order to achieve ai = bi for all i.

NoteIn the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1.

#!/usr/bin/perl

$n = <STDIN>;
@b = split ' ', <STDIN>;
$ans = 0;
$delta = 0;
foreach (@b) {
    $ans += abs $_ - $delta;
    $delta += $_ - $delta;
}
print $ans, "\n";


You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value.

For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

#!/usr/bin/env perl

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

my @tokens = ();

my $q = read_token();

for (1..$q) {
    my $a = read_token();
    my $b = read_token();
    my $n = read_token();
    my $s = read_token();

    my $m = $a*$n;
    if ( $m > $s ) {
        if ( $s % $n <= $b ) {
            say "YES";
        }
        else {
            say "NO";
        }
    }
    elsif ( $m == $s ) {
        say "YES";
    }
    else {
        if ( $s - $m <= $b ) {
            say "YES";
        }
        else {
            say "NO";
        }
    }
}

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


Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.For example:  the following words have typos: "hellno", "hackcerrs" and "backtothefutttture";  the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo". When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.

The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.

Print the given word without any changes if there are no typos. If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them.


Alice and Bob play the following game. Alice has a set $$$S$$$ of disjoint ranges of integers, initially containing only one range $$$[1, n]$$$. In one turn, Alice picks a range $$$[l, r]$$$ from the set $$$S$$$ and asks Bob to pick a number in the range. Bob chooses a number $$$d$$$ ($$$l \le d \le r$$$). Then Alice removes $$$[l, r]$$$ from $$$S$$$ and puts into the set $$$S$$$ the range $$$[l, d - 1]$$$ (if $$$l \le d - 1$$$) and the range $$$[d + 1, r]$$$ (if $$$d + 1 \le r$$$). The game ends when the set $$$S$$$ is empty. We can show that the number of turns in each game is exactly $$$n$$$.After playing the game, Alice remembers all the ranges $$$[l, r]$$$ she picked from the set $$$S$$$, but Bob does not remember any of the numbers that he picked. But Bob is smart, and he knows he can find out his numbers $$$d$$$ from Alice's ranges, and so he asks you for help with your programming skill.Given the list of ranges that Alice has picked ($$$[l, r]$$$), for each range, help Bob find the number $$$d$$$ that Bob has picked.We can show that there is always a unique way for Bob to choose his number for a list of valid ranges picked by Alice.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$). Each of the next $$$n$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$), denoting the range $$$[l, r]$$$ that Alice picked at some point. Note that the ranges are given in no particular order. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$, and the ranges for each test case are from a valid game.

For each test case print $$$n$$$ lines. Each line should contain three integers $$$l$$$, $$$r$$$, and $$$d$$$, denoting that for Alice's range $$$[l, r]$$$ Bob picked the number $$$d$$$. You can print the lines in any order. We can show that the answer is unique. It is not required to print a new line after each test case. The new lines in the output of the example are for readability only.

NoteIn the first test case, there is only 1 range $$$[1, 1]$$$. There was only one range $$$[1, 1]$$$ for Alice to pick, and there was only one number $$$1$$$ for Bob to pick.In the second test case, $$$n = 3$$$. Initially, the set contains only one range $$$[1, 3]$$$.   Alice picked the range $$$[1, 3]$$$. Bob picked the number $$$1$$$. Then Alice put the range $$$[2, 3]$$$ back to the set, which after this turn is the only range in the set.  Alice picked the range $$$[2, 3]$$$. Bob picked the number $$$3$$$. Then Alice put the range $$$[2, 2]$$$ back to the set.  Alice picked the range $$$[2, 2]$$$. Bob picked the number $$$2$$$. The game ended. In the fourth test case, the game was played with $$$n = 5$$$. Initially, the set contains only one range $$$[1, 5]$$$. The game's turn is described in the following table.  Game turnAlice's picked rangeBob's picked numberThe range set afterBefore the game start$$$ \{ [1, 5] \} $$$1$$$[1, 5]$$$$$$3$$$$$$ \{ [1, 2], [4, 5] \}$$$2$$$[1, 2]$$$$$$1$$$$$$ \{ [2, 2], [4, 5] \} $$$3$$$[4, 5]$$$$$$5$$$$$$ \{ [2, 2], [4, 4] \} $$$4$$$[2, 2]$$$$$$2$$$$$$ \{ [4, 4] \} $$$5$$$[4, 4]$$$$$$4$$$$$$ \{ \} $$$ (empty set)


Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.

The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.

For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.

NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	my( $c, $sum ) = split;

	my $min = int $sum / $c;
	my $rem = $sum % $c;

	print $min ** 2 * ( $c - $rem ) + ( $min + 1 ) ** 2 * $rem;
	}


Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.

In first line there is one integer n (1 ≤ n ≤ 2·105) — number of cafes indices written by Vlad. In second line, n numbers a1, a2, ..., an (0 ≤ ai ≤ 2·105) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.

Print one integer — index of the cafe that Vlad hasn't visited for as long as possible.

NoteIn first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer. In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my %h;
	my $last;

	for( reverse split ' ', <> ){
		not exists $h{ $_ } and $last = $_;
		$h{ $_ } ++;
		}

	print $last;
	}

<>;

$h{ $_ } ++ or $L = $_ for reverse split ' ', <>;

print $L


There is an infinite set generated as follows:  $$$1$$$ is in this set.  If $$$x$$$ is in this set, $$$x \cdot a$$$ and $$$x+b$$$ both are in this set. For example, when $$$a=3$$$ and $$$b=6$$$, the five smallest elements of the set are:  $$$1$$$,  $$$3$$$ ($$$1$$$ is in this set, so $$$1\cdot a=3$$$ is in this set),  $$$7$$$ ($$$1$$$ is in this set, so $$$1+b=7$$$ is in this set),  $$$9$$$ ($$$3$$$ is in this set, so $$$3\cdot a=9$$$ is in this set),  $$$13$$$ ($$$7$$$ is in this set, so $$$7+b=13$$$ is in this set). Given positive integers $$$a$$$, $$$b$$$, $$$n$$$, determine if $$$n$$$ is in this set.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 10^5$$$) — the number of test cases. The description of the test cases follows. The only line describing each test case contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$1\leq n,a,b\leq 10^9$$$) separated by a single space.

For each test case, print "Yes" if $$$n$$$ is in this set, and "No" otherwise. You can print each letter in any case.

NoteIn the first test case, $$$24$$$ is generated as follows:  $$$1$$$ is in this set, so $$$3$$$ and $$$6$$$ are in this set;  $$$3$$$ is in this set, so $$$9$$$ and $$$8$$$ are in this set;  $$$8$$$ is in this set, so $$$24$$$ and $$$13$$$ are in this set. Thus we can see $$$24$$$ is in this set.The five smallest elements of the set in the second test case is described in statements. We can see that $$$10$$$ isn't among them.

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

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

while( $test_case -- > 0 ){
  my ($n,$a,$b) = map { $_ - 0 } split(/\s+/,<STDIN>);
  my $res = 'No';
  if( $a == 1 ){
    if( $n >= 1 and ( $n - 1 ) % $b == 0 ){
      $res = 'Yes';
    }
    print "$res\n";
    next;
  }

  my $st = 1;
  while( $n >= $st ){
    if( ( $n - $st ) % $b == 0 ){
      $res = 'Yes';
      last;
    }
    $st *= $a;
  }
  print "$res\n";
}

exit(0);


Zane the wizard is going to perform a magic show shuffling the cups.There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.The problematic bone is initially at the position x = 1. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions x = ui and x = vi. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at x = 4 and the one at x = 6, they will not be at the position x = 5 at any moment during the operation.  Zane’s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.

The first line contains three integers n, m, and k (2 ≤ n ≤ 106, 1 ≤ m ≤ n, 1 ≤ k ≤ 3·105) — the number of cups, the number of holes on the table, and the number of swapping operations, respectively. The second line contains m distinct integers h1, h2, ..., hm (1 ≤ hi ≤ n) — the positions along the x-axis where there is a hole on the table. Each of the next k lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the positions of the cups to be swapped.

Print one integer — the final position along the x-axis of the bone.

NoteIn the first sample, after the operations, the bone becomes at x = 2, x = 5, x = 7, and x = 1, respectively.In the second sample, after the first operation, the bone becomes at x = 2, and falls into the hole onto the ground.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $n, $m, $k ) = split;
	my @A = 0 .. 1e6;
	map { $A[ $_ ] = -1 } split ' ', <>;

	my $x = 1;

	for (1 .. $k){

		my( $u, $v ) = split ' ', <>;

		if( $A[ $x ] == -1 ){
			next;
			}

		$x == $u and $x = $v and next;
		$x == $v and $x = $u and next;
		}

	print $x;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $n, $m, $k ) = split;
	my @A = 0 .. 1e6;
	map { $A[ $_ ] = -1 } split ' ', <>;

	my $x = 1;

	for (1 .. $k){

		my( $u, $v ) = split ' ', <>;

		if( $A[ $x ] == -1 ){
			last;
			}

		$x == $u and $x = $v and next;
		$x == $v and $x = $u and next;
		}

	print $x;
	}


You are given an array of $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$.You have to create an array of $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$ such that:   The array $$$b$$$ is a rearrangement of the array $$$a$$$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets $$$\{a_1,a_2,\dots,a_n\}$$$ and $$$\{b_1,b_2,\dots,b_n\}$$$ are equal.For example, if $$$a=[1,-1,0,1]$$$, then $$$b=[-1,1,1,0]$$$ and $$$b=[0,1,-1,1]$$$ are rearrangements of $$$a$$$, but $$$b=[1,-1,-1,0]$$$ and $$$b=[1,0,2,-3]$$$ are not rearrangements of $$$a$$$.  For all $$$k=1,2,\dots,n$$$ the sum of the first $$$k$$$ elements of $$$b$$$ is nonzero. Formally, for all $$$k=1,2,\dots,n$$$, it must hold $$$$$$b_1+b_2+\cdots+b_k\not=0\,.$$$$$$ If an array $$$b_1,b_2,\dots, b_n$$$ with the required properties does not exist, you have to print NO.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t \le 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each testcase contains one integer $$$n$$$ ($$$1\le n\le 50$$$)  — the length of the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\dots, a_n$$$ ($$$-50\le a_i\le 50$$$)  — the elements of $$$a$$$.

For each testcase, if there is not an array $$$b_1,b_2,\dots,b_n$$$ with the required properties, print a single line with the word NO. Otherwise print a line with the word YES, followed by a line with the $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$.  If there is more than one array $$$b_1,b_2,\dots,b_n$$$ satisfying the required properties, you can print any of them.

NoteExplanation of the first testcase: An array with the desired properties is $$$b=[1,-2,3,-4]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$-1$$$.  The sum of the first three elements of $$$b$$$ is $$$2$$$.  The sum of the first four elements of $$$b$$$ is $$$-2$$$. Explanation of the second testcase: Since all values in $$$a$$$ are $$$0$$$, any rearrangement $$$b$$$ of $$$a$$$ will have all elements equal to $$$0$$$ and therefore it clearly cannot satisfy the second property described in the statement (for example because $$$b_1=0$$$). Hence in this case the answer is NO.Explanation of the third testcase: An array with the desired properties is $$$b=[1, 1, -1, 1, -1]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$2$$$.  The sum of the first three elements of $$$b$$$ is $$$1$$$.  The sum of the first four elements of $$$b$$$ is $$$2$$$.  The sum of the first five elements of $$$b$$$ is $$$1$$$. Explanation of the fourth testcase: An array with the desired properties is $$$b=[-40,13,40,0,-9,-31]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$-40$$$.  The sum of the first two elements of $$$b$$$ is $$$-27$$$.  The sum of the first three elements of $$$b$$$ is $$$13$$$.  The sum of the first four elements of $$$b$$$ is $$$13$$$.  The sum of the first five elements of $$$b$$$ is $$$4$$$.  The sum of the first six elements of $$$b$$$ is $$$-27$$$.


Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time (in seconds).Let's suppose that Valera will set v seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most v seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, a seconds, an inequality 2a ≤ v holds.As a result, Valera decided to set v seconds TL, that the following conditions are met:  v is a positive integer;  all correct solutions pass the system testing;  at least one correct solution passes the system testing with some "extra" time;  all wrong solutions do not pass the system testing;  value v is minimum among all TLs, for which points 1, 2, 3, 4 hold. Help Valera and find the most suitable TL or else state that such TL doesn't exist.

The first line contains two integers n, m (1 ≤ n, m ≤ 100). The second line contains n space-separated positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the running time of each of the n correct solutions in seconds. The third line contains m space-separated positive integers b1, b2, ..., bm (1 ≤ bi ≤ 100) — the running time of each of m wrong solutions in seconds.

If there is a valid TL value, print it. Otherwise, print -1.

use strict;

my ($n, $m, @pass, @fail);

($n,$m) = split / /, <>;
@pass = split / /, <>;
@fail = split / /, <>;
chomp(@pass), chomp(@fail);

@pass = sort {$a <=> $b} @pass;
@fail = sort {$a <=> $b} @fail;

(print "-1") and exit if (($pass[-1] >= $fail[0]) || (2 * $pass[0] >= $fail[0]));

print ((2 * $pass[0] > $pass[-1]) ? 2 * $pass[0] : $pass[-1]);

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';

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

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

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

my @right = split(' ', <>);
my @wrong = split(' ', <>);

my $v = min(@right) * 2;

my $possible = 1;

foreach my $time (@wrong)
{
    if ($time <= $v)
    {
        $possible = 0;
        last;
    }
}

$possible = 0 if max(@right) >= min(@wrong);

if ($possible)
{
    if (max(@right) == min(@right)) {
        print min(min(@wrong) - 1, $v)
    } else {
        print min(min(@wrong) - 1, max(@right, $v))
    }
}
else
{
    print -1;
}

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

@a=split/ /,<>;
@b=split/ /,<>;

$ib=min(@b);
$ia=min(@a);
$aa=max(@a);

$TL=max($ia*2,$aa);
print $TL<$ib?$TL:-1;
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
}

use strict;

my ($n, $m, @pass, @fail);

($n,$m) = split / /, <>;
@pass = split / /, <>;
@fail = split / /, <>;
chomp(@pass), chomp(@fail);

@pass = sort @pass;
@fail = sort @fail;

(print "-1") and exit if (($pass[-1] >= $fail[0]) || (2 * $pass[0] >= $fail[0]));

print ((2 * $pass[0] > $pass[-1]) ? 2 * $pass[0] : $pass[-1]);

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';

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

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

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

my @right = split(' ', <>);
my @wrong = split(' ', <>);

my $v = min(@right) * 2;

my $possible = 1;

foreach my $time (@wrong)
{
    if ($time <= $v)
    {
        $possible = 0;
        last;
    }
}

if ($possible)
{
    if (max(@right) == min(@right)) {
        print min(min(@wrong) - 1, $v)
    } else {
        print min(min(@wrong) - 1, max(@right))
    }
}
else
{
    print -1;
}

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';

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

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

my @right = split(' ', <>);
my @wrong = split(' ', <>);

my $v = min(@right) * 2;

my $possible = 1;

foreach my $time (@wrong)
{
    if ($time <= $v)
    {
        $possible = 0;
        last;
    }
}

if ($possible)
{
    print min(@wrong) - 1;
}
else
{
    print -1;
}

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';

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

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

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

my @right = split(' ', <>);
my @wrong = split(' ', <>);

my $v = min(@right) * 2;

my $possible = 1;

foreach my $time (@wrong)
{
    if ($time <= $v)
    {
        $possible = 0;
        last;
    }
}

$possible = 0 if max(@right) >= max(@wrong);

if ($possible)
{
    if (max(@right) == min(@right)) {
        print min(min(@wrong) - 1, $v)
    } else {
        print min(min(@wrong) - 1, max(@right, $v))
    }
}
else
{
    print -1;
}

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';

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

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

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

my @right = split(' ', <>);
my @wrong = split(' ', <>);

my $v = min(@right) * 2;

my $possible = 1;

foreach my $time (@wrong)
{
    if ($time <= $v)
    {
        $possible = 0;
        last;
    }
}

if ($possible)
{
    if (max(@right) == max(@wrong)) {
        print min(min(@wrong) - 1, $v)
    } else {
        print min(min(@wrong) - 1, max(@right))
    }
}
else
{
    print -1;
}

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';

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

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

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

my @right = split(' ', <>);
my @wrong = split(' ', <>);

my $v = min(@right) * 2;

my $possible = 1;

foreach my $time (@wrong)
{
    if ($time <= $v)
    {
        $possible = 0;
        last;
    }
}

if ($possible)
{
    print min(min(@wrong) - 1, $v)
}
else
{
    print -1;
}

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';

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

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

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

my @right = split(' ', <>);
my @wrong = split(' ', <>);

my $v = min(@right) * 2;

my $possible = 1;

foreach my $time (@wrong)
{
    if ($time <= $v)
    {
        $possible = 0;
        last;
    }
}

if ($possible)
{
    if (max(@right) == min(@right)) {
        print min(min(@wrong) - 1, $v)
    } else {
        print min(min(@wrong) - 1, max(@right, $v))
    }
}
else
{
    print -1;
}


Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.  Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.

Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).

NoteIn the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite.


Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately. Valera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe. Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.

The first line contains a single integer n (1 ≤ n ≤ 105), that is the number of cafe visitors. Each of the following n lines has two space-separated integers hi and mi (0 ≤ hi ≤ 23; 0 ≤ mi ≤ 59), representing the time when the i-th person comes into the cafe.  Note that the time is given in the chronological order. All time is given within one 24-hour period.

Print a single integer — the minimum number of cashes, needed to serve all clients next day.

NoteIn the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.In the second sample all visitors will come in different times, so it will be enough one cash.

#!/usr/bin/perl -w

use List::Util qw(max);
use strict;

my %times = ();
chomp(my $n = <>);
for (1 .. $n) {
	chomp($_ = <>);
	++$times{$_};
}
my $res = max values %times;
print "$res\n";

use List::Util 'max';for(<>){++$_{$_}}print max values%_

use strict;
use warnings;

my $n = <STDIN>;
my %h = ();
for (1 .. $n) {
  $_ = <STDIN>;
  ++$h{$_};
}
my $m = 0;
for (values %h) {
  $m = $_ if $_ > $m;
}
print "$m\n";

#!perl -n
use List::Util 'max';
INIT{$_=<>}++$_{$_};END{print max values%_}

#!perl -n
use List::Util 'max';
BEGIN{$_='1'}++$_{$_};END{print max values%_}

#!perl -n
use List::Util 'max';
END{print max values%_}++$_{$_}

use strict;
use warnings;
use List::Util 'max';

my $n = <STDIN>;
my %h = ();
for (1 .. $n) {
  $_ = <STDIN>;
  ++$h{$_};
}
my $m = 0;
for (values %h) {
  $m = $_ if $_ > $m;
}
print "$m\n";

my %hash;
my $n = int<>;
my $max = 0;
$hash{<>}++ for(1..$n);
for(values %hash) {
    $max = $_ if ($_ > $max);
}
print $max;

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

@c = (0) x 1440;
chomp($n = <>);
while (<>) {
	chomp;
	($h, $m) = split / /;
	++$c[$h*60+$m];
}
$ans = 0;
$ans=$ans>$_ ? $ans:$_ foreach (@c);
say $ans;

#! /usr/bin/perl -wl
#------------------------------------------------
# Author:    vj
# Created:   Thu Oct 25 21:02:27 IST 2012
# File Name: a.pl
# USAGE:
#       a.pl
#
#
#------------------------------------------------
use List::Util qw(first max maxstr min minstr reduce shuffle sum);
chomp (my $n = <STDIN>);
my %times;
my $buf;
while ($n--) {
  chomp ($buf = <STDIN>);
  $times{$buf}++;
}
print &max(values %times);

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw(max min);

chomp(my $n = <STDIN>);
my %cnt;
for (my $i = 0; $i < $n; $i++) {
    chomp(my $customer = <STDIN>);
    if (exists($cnt{$customer})) {
        $cnt{$customer} += 1;
    } else {
        $cnt{$customer} = 1;
    }
}

print max values %cnt;

#!usr/bin/perl
#use warnings;
#use strict;
#use autodie;
#use diagnostics;
use utf8;
use 5.010;
use 5.012;
use 5.014;
my($line,$n,$max,$count,$prev,$ans);
$count=0;
$max=1;
$ans=1;
chomp($n=<STDIN>);
while($count ne $n)
{
    chomp($line=<STDIN>);
    if($count eq 0)
    {
        $prev=$line;
        $count++;
        next;
    }
    $count++;
    if($prev eq $line)
    {
        $ans++;
    }
    else
    {
        if($max<$ans)
        {
            $max=$ans;
        }
        $ans=1;
    }
    $prev=$line;
}
if($max<$ans){$max=$ans;}
say $max;

#!/usr/bin/perl -w
use strict;
use warnings;
use List::Util qw(max);

my $n = int <STDIN>;
my %hash;
for (1 .. $n) {
    my ($h, $m) = map int, split /\D/, <STDIN>;
    $m += $h*60;
    if ($hash{$m}) {
	$hash{$m}++;
    } else {
	$hash{$m} = 1;
    }
}
print max values %hash;

my $num = <>;
chomp $num;
my %count;
for (1..$num) {
    my $time = <>;
    chomp $time;
    $count{$time}++;
}
my @temp = sort {$count{$b}<=>$count{$a}} keys %count;
my $time = shift @temp;
print $count{$time};

my $n = int<>;
my @temp;
my @arr;
for (1..$n) {
    @temp = split / /, <>;
    push @arr, $temp[0] * 100 + $temp[1];
}
@arr = sort @arr;
my ($max, $ans) = (0, 0);
for (1..$n - 1) {
    if (int$arr[$_] == int$arr[$_ - 1]) {
        $ans++;
    }
    else {
        $max = $ans if ($ans > $max);
        $ans = 0;
    }
}
print $max + 1;

#!/usr/bin/perl -w

use strict;

my $n = <>;
my ($ch, $cm) = (0, 0);
my $mc = 0;
my $cash = 1;
for (1..$n) {
    my ($h, $m) = split ' ', <>;
    if ($h == $ch && $m == $cm) {
        $cash++;
    } else {
        $cash = 1;
    }
    $ch = $h;
    $cm = $m;
    $mc = $cash > $mc ? $cash : $mc;
}

print $mc, "\n";

#!usr/bin/perl
#use warnings;
#use strict;
#use autodie;
#use diagnostics;
use utf8;
use 5.010;
use 5.012;
use 5.014;
my($line,$n,$max,$count,$prev,$ans);
$count=0;
$max=1;
$ans=1;
chomp($n=<STDIN>);
while($count ne $n)
{
    chomp($line=<STDIN>);
    if($count eq 0)
    {
        $prev=$line;
        $count++;
        next;
    }
    $count++;
    if($prev eq $line)
    {
        $ans++;
    }
    else
    {
        if($max<$ans)
        {
            $max=$ans;
        }
        $ans=1;
    }
    $prev=$line;
}
say $max;


Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that si isn't equal to ti. As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t.It's time for Susie to go to bed, help her find such string p or state that it is impossible.

The first line contains string s of length n.  The second line contains string t of length n. The length of string n is within range from 1 to 105. It is guaranteed that both strings contain only digits zero and one.

Print a string of length n, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line "impossible" (without the quotes). If there are multiple possible answers, print any of them.

NoteIn the first sample different answers are possible, namely — 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101.

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

chomp($a = <>);
chomp($b = <>);
$len = length $a;
@a = split //, $a;
@b = split //, $b;
$c = 0;
$a[$_] ne $b[$_] and ++$c foreach (0 .. $len-1);
$c%2>0 and say "impossible" and exit;
for ($i=0,$j=0,$c>>=1; $i<$len; ++$i) {
	if ($a[$i] eq $b[$i]) {
		push @ans, $a[$i];
	} else {
		$j < $c and push @ans, $a[$i] or push @ans, $b[$i];
		++$j;
	}
}
say join '', @ans;

chomp (($_, $b) = <>);
for $j (1 .. length){
	$e .= chop $b ne ($a = chop) ?
		(++ $i % 2 ? $a : 1 - $a)
	:
		0
	}
print $i % 2 ? 'impossible' : scalar reverse $e

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

chomp($a = <>);
chomp($b = <>);
$len = length $a;
@a = split //, $a;
@b = split //, $b;
$c = 0;
$a[$_] ne $b[$_] and ++$c foreach (0 .. $len-1);
$c%2>0 and say "impossible" and exit;
for ($i=0,$j=0; $i<$len; ++$i) {
	if ($a[$_] eq $b[$_]) {
		push @ans, $a[$_];
	} else {
		$j < $c and push @ans, $a[$_] or push @ans, $b[$_];
		++$j;
	}
}
say join '', @ans;

chomp (($_, $b) = <>);
for $j (1 .. length){
	$e .= chop $b ne (chop) ?
		++ $i % 2
	:
		0
	}
print $i % 2 ? 'impossible' : scalar reverse $e

chomp (($_, $b) = <>);
for $j (1 .. length){
	$e .= chop $b ne (chop) ?
		++ $i % 2
	:
		0
	}
print $i % 2 ? 'Impossible' : scalar reverse $e


You are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where ai, j = 1 if the i-th switch turns on the j-th lamp and ai, j = 0 if the i-th switch is not connected to the j-th lamp.Initially all m lamps are turned off.Switches change state only from "off" to "on". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards.It is guaranteed that if you push all n switches then all m lamps will be turned on.Your think that you have too many switches and you would like to ignore one of them. Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other n - 1 switches then all the m lamps will be turned on.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 2000) — the number of the switches and the number of the lamps. The following n lines contain m characters each. The character ai, j is equal to '1' if the i-th switch turns on the j-th lamp and '0' otherwise. It is guaranteed that if you press all n switches all m lamps will be turned on.

Print "YES" if there is a switch that if you will ignore it and press all the other n - 1 switches then all m lamps will be turned on. Print "NO" if there is no such switch.

use warnings;
use strict;
use integer;
$\ = qq/\n/, $, = qq/ /;
my ( $n, $m ) = split qq/ /, <STDIN>;
my %batman = ();
my $redundant = ();
my @arr = ();
# initialize batman
$batman { $_ } = 0 for ( 0 .. $n );
for ( 1 .. $n ) {
    my $str = <STDIN>;
    my @characters = split qq//, $str;
    push @arr, $str;
    for my $ii ( 0 .. $#characters ) {
        $batman { $ii } += 1 if $characters [ $ii ] eq q/1/;
    }
}
for my $jj ( @arr ) {
    $redundant = 1;
    my @characters = split q//, $jj;
    for my $hh ( 0 .. $#characters ) {
        if ( $characters [ $hh ] eq q/1/ ) {
            if ( $batman { $hh } == 1 ) { $redundant = 0 }
        }
    }
    if ( $redundant ) {
        print qq/YES/;
        exit
    }
}
print qq/NO/;

use warnings;
use strict;
use integer;
$\ = qq/\n/, $, = qq/ /;
my ( $n, $m ) = split qq/ /, <STDIN>;
my %batman = ();
for ( 1 .. $n ) {
    my $str = <STDIN>;
    my $redundant = 1;
    for ( my $ii = 0; $ii < length $str; $ii += 1 ) {
        if ( substr ( $str, $ii, 1 ) eq q/1/ ) {
            if ( not exists $batman { $ii } ) {
                $redundant = 0;
                $batman { $ii } = 1;
            }
        }
    }
    if ( $redundant ) {
        print qq/YES/;
        exit
    }
}
print qq/NO/;


When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.

The first line contains a single integer $$$n$$$ ($$$1 \leqslant n \leqslant 10^5$$$) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'. It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit $$$0$$$ or "one" which corresponds to the digit $$$1$$$.

Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.

NoteIn the first example, the correct initial ordering is "zero".In the second example, the correct initial ordering is "oneonezero".

#!/usr/bin/env perl

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

# essential
my @tokens = ();

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

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

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

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

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

sub remainder {
    my ($dividend, $divisor) = @_;
}

# solve

my $length = read_token;
my $input = read_line;

my @chars = split q{}, $input;

my @bins = ();

for (@chars) {
    push @bins, 0 if $_ eq 'z';
    push @bins, 1 if $_ eq 'n';
}

@bins = reverse sort @bins;

say "@bins";

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my %h;

	/
		.
		(?{ $h{ $& } ++ })
		(*F)
		/x;

	my @ans;

	while( not grep !$_, @h{ split //, 'one' } ){
		push @ans, 1;
		map { $_ -- } @h{ split //, 'one' };
		}

	while( not grep !$_, @h{ split //, 'zero' } ){
		push @ans, 0;
		map { $_ -- } @h{ split //, 'zero' };
		}

	print join ' ', @ans;
	}


There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes.

The first line contains five integers n, A, B, C and T (1 ≤ n, A, B, C, T ≤ 1000). The second string contains n integers ti (1 ≤ ti ≤ T).

Output one integer  — the answer to the problem.

NoteIn the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n·A = 20 in total.In the second sample the messages can be read at any integer moment.In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4·3) + (5 - 3·3) + (5 - 2·3) + (5 - 1·3) + 5 =  - 5 points. This is 35 in total.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	@_ = split ' ', <>;

	my $sum = 0;

	for( @_ ){
		if( $B > $C ){
			$sum += $A;
			}
		else{
			$sum += $A + ( $T - $_ ) * ( $C - $B );
			}
		}

	print $sum;
	}