Arkady is playing Battleship. The rules of this game aren't really important.There is a field of $$$n \times n$$$ cells. There should be exactly one $$$k$$$-decker on the field, i. e. a ship that is $$$k$$$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$) — the size of the field and the size of the ship. The next $$$n$$$ lines contain the field. Each line contains $$$n$$$ characters, each of which is either '#' (denotes a definitely empty cell) or '.' (denotes a cell that can belong to the ship).

Output two integers — the row and the column of a cell that belongs to the maximum possible number of different locations of the ship. If there are multiple answers, output any of them. In particular, if no ship can be placed on the field, you can output any cell.

NoteThe picture below shows the three possible locations of the ship that contain the cell $$$(3, 2)$$$ in the first sample.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;
my $debug = 0;

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

	my @A = map ~~<>, 1 .. $n;
	chomp @A;

	my @lengths;

	@_ = @A;

	for( @_ ){
		s!
			(\.{$k,})
		!
			my $len = length $1;
			'>' x ( $len % 2 + int $len / 2 ) .
			'<' x ( int $len / 2 )
		!gex;
		}

	$debug and print for @_;

	for my $i ( 0 .. @_ - 1 ){
		while( $_[ $i ] =~ /(>+)/g ){
			my $len = length $1;
			push @lengths, [ $len, $i + 1, pos $_[ $i ] ];
			}
		}

	$debug and print " @{ $_ }" for @lengths;

	@_ = ( '' ) x @A;

	for( @A ){
		my $i = 0;
		map { $_[ $i ++ ] .= $_ } split //;
		}

	for( @_ ){
		s!
			(\.{$k,})
		!
			my $len = length $1;
			'>' x ( $len % 2 + int $len / 2 ) .
			'<' x ( int $len / 2 )
		!gex;
		}

	$debug and print for @_;

	for my $i ( 0 .. @_ - 1 ){
		while( $_[ $i ] =~ /(>+)/g ){
			my $len = length $1;
			push @lengths, [ $len, pos $_[ $i ], $i + 1 ];
			}
		}

	$debug and print " @{ $_ }" for @lengths;

	print !@lengths ? "1 1" : join ' ', map { $_->[ 1 ], $_->[ 2 ] }
		( sort { $b->[ 0 ] <=> $a->[ 0 ] } @lengths )[ 0 ];

	$debug and print '-' x 15;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;
my $debug = 0;

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

	my @A = map ~~<>, 1 .. $n;
	chomp @A;

	my @lengths;

	@_ = @A;

	for( @_ ){
		s!
			(\.{$k,})
		!
			my $len = length $1;
			'>' x ( $len % 2 + int $len / 2 ) .
			'<' x ( int $len / 2 )
		!gex;
		}

	$debug and print for @_;

	for my $i ( 0 .. @_ - 1 ){
		while( $_[ $i ] =~ /(>+)/g ){
			my $len = length $1;
			push @lengths, [ $len, $i + 1, pos $_[ $i ] ];
			}
		}

	$debug and print " @{ $_ }" for @lengths;

	@_ = ( '' ) x @A;

	for( @A ){
		my $i = 0;
		map { $_[ $i ++ ] .= $_ } split //;
		}

	for( @_ ){
		s!
			(\.{$k,})
		!
			my $len = length $1;
			'>' x ( $len % 2 + int $len / 2 ) .
			'<' x ( int $len / 2 )
		!gex;
		}

	$debug and print for @_;

	for my $i ( 0 .. @_ - 1 ){
		while( $_[ $i ] =~ /(>+)/g ){
			my $len = length $1;
			push @lengths, [ $len, pos $_[ $i ], $i + 1 ];
			}
		}

	$debug and print " @{ $_ }" for @lengths;

	print join ' ', map { $_->[ 1 ], $_->[ 2 ] }
		( sort { $b->[ 0 ] <=> $a->[ 0 ] } @lengths )[ 0 ];

	$debug and print '-' x 15;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;
my $debug = 0;

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

	@_ = map { $_ = <>, chomp; [ map s/\./$k * 2/er, split // ] } 1 .. $n;

	$debug and print join ' ', map { sprintf "%2s", $_ } @{ $_ } for @_;

	$debug and print '-' x 5;

	for my $i ( 0 .. @_ - 1 ){
		my $cnt = $k;
		for my $j ( 0 .. @_ - 1 ){
			$_[ $i ][ $j ] =~ s/(-?\d+)/ $cnt --; $cnt < 0 and $cnt = 0;
				$1 - $cnt
				/e or do {
					$cnt = $k;
					};
			}
		}

	$debug and print join ' ', map { sprintf "%2s", $_ } @{ $_ } for @_;

	$debug and print '-' x 5;

	for my $i ( 0 .. @_ - 1 ){
		my $cnt = $k;
		for my $j ( reverse 0 .. @_ - 1 ){
			$_[ $i ][ $j ] =~ s/(-?\d+)/ $cnt --; $cnt < 0 and $cnt = 0;
				$1 - $cnt
				/e or do {
					$cnt = $k;
					};
			}
		}

	$debug and print join ' ', map { sprintf "%2s", $_ } @{ $_ } for @_;

	$debug and print '-' x 5;

	for my $i ( 0 .. @_ - 1 ){
		my $cnt = $k;
		for my $j ( 0 .. @_ - 1 ){
			$_[ $j ][ $i ] =~ s/(-?\d+)/ $cnt --; $cnt < 0 and $cnt = 0;
				$1 - $cnt
				/e or do {
					$cnt = $k;
					};
			}
		}

	$debug and print join ' ', map { sprintf "%2s", $_ } @{ $_ } for @_;

	$debug and print '-' x 5;

	for my $i ( 0 .. @_ - 1 ){
		my $cnt = $k;
		for my $j ( reverse 0 .. @_ - 1 ){
			$_[ $j ][ $i ] =~ s/(-?\d+)/ $cnt --; $cnt < 0 and $cnt = 0;
				$1 - $cnt
				/e or do {
					$cnt = $k;
					};
			}
		}

	$debug and print join ' ', map { sprintf "%2s", $_ } @{ $_ } for @_;

	my $max = 0;

	for my $i ( 0 .. @_ - 1 ){
		for my $j ( reverse 0 .. @_ - 1 ){
			next if $_[ $i ][ $j ] eq '#';
			$_[ $i ][ $j ] > $max and $max = $_[ $i ][ $j ];
			}
		}

	my $ans;

	for my $i ( 0 .. @_ - 1 ){
		for my $j ( reverse 0 .. @_ - 1 ){
			next if $_[ $i ][ $j ] eq '#';
			next if $_[ $i ][ $j ] eq '0';
			$_[ $i ][ $j ] == $max and do {
				$ans = join ' ', map $_ + 1, $i, $j;
				last;
				};
			}
		}

	print defined $ans ? $ans : "1 1";

	$debug and print '-' x 15;
	}


Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $$$n$$$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $$$d$$$ rubles, and one euro costs $$$e$$$ rubles.Recall that there exist the following dollar bills: $$$1$$$, $$$2$$$, $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, and the following euro bills — $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, $$$200$$$ (note that, in this problem we do not consider the $$$500$$$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.Help him — write a program that given integers $$$n$$$, $$$e$$$ and $$$d$$$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.

The first line of the input contains one integer $$$n$$$ ($$$1 \leq n \leq 10^8$$$) — the initial sum in rubles Andrew has.  The second line of the input contains one integer $$$d$$$ ($$$30 \leq d \leq 100$$$) — the price of one dollar in rubles.  The third line of the input contains integer $$$e$$$ ($$$30 \leq e \leq 100$$$) — the price of one euro in rubles.

Output one integer — the minimum number of rubles Andrew can have after buying dollar and euro bills optimally.

NoteIn the first example, we can buy just $$$1$$$ dollar because there is no $$$1$$$ euro bill.In the second example, optimal exchange is to buy $$$5$$$ euro and $$$1$$$ dollar.In the third example, optimal exchange is to buy $$$10$$$ dollars in one bill.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	chomp(
		my( $n, $d, $e ) = ( $_, ~~<>, ~~<> )
		);

	my $D = $d * 1;
	my $E = $e * 5;

	my @mods;

	for my $i ( 0 .. 1e6 ){
		my $nn = $n - $i * $E;
		last if $nn < 0;
		push @mods, $nn % $D;
		}

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


Polycarp has $$$3$$$ positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He can perform the following operation exactly once.  Choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$. Can Polycarp make it so that after performing the operation, the sequence of three numbers $$$a$$$, $$$b$$$, $$$c$$$ (in this order) forms an arithmetic progression? Note that you cannot change the order of $$$a$$$, $$$b$$$ and $$$c$$$.Formally, a sequence $$$x_1, x_2, \dots, x_n$$$ is called an arithmetic progression (AP) if there exists a number $$$d$$$ (called "common difference") such that $$$x_{i+1}=x_i+d$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$. In this problem, $$$n=3$$$.For example, the following sequences are AP: $$$[5, 10, 15]$$$, $$$[3, 2, 1]$$$, $$$[1, 1, 1]$$$, and $$$[13, 10, 7]$$$. The following sequences are not AP: $$$[1, 2, 4]$$$, $$$[0, 1, 0]$$$ and $$$[1, 3, 2]$$$.You need to answer $$$t$$$ independent test cases.

The first line contains the number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains $$$3$$$ integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a, b, c \le 10^8$$$).

For each test case print "YES" (without quotes) if Polycarp can choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$ to make $$$[a, b, c]$$$ be an arithmetic progression. Print "NO" (without quotes) otherwise. You can print YES and NO in any (upper or lower) case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer).

YES
YES
YES
YES
NO
YES
NO
YES
YES
NO
YES

NoteIn the first and second test cases, you can choose the number $$$m=4$$$ and multiply the second number ($$$b=5$$$) by $$$4$$$.In the first test case the resulting sequence will be $$$[10, 20, 30]$$$. This is an AP with a difference $$$d=10$$$.In the second test case the resulting sequence will be $$$[30, 20, 10]$$$. This is an AP with a difference $$$d=-10$$$.In the third test case, you can choose $$$m=1$$$ and multiply any number by $$$1$$$. The resulting sequence will be $$$[1, 2, 3]$$$. This is an AP with a difference $$$d=1$$$.In the fourth test case, you can choose $$$m=9$$$ and multiply the first number ($$$a=1$$$) by $$$9$$$. The resulting sequence will be $$$[9, 6, 3]$$$. This is an AP with a difference $$$d=-3$$$.In the fifth test case, it is impossible to make an AP.


You are given a binary array$$$^{\dagger}$$$ of length $$$n$$$. You are allowed to perform one operation on it at most once. In an operation, you can choose any element and flip it: turn a $$$0$$$ into a $$$1$$$ or vice-versa.What is the maximum number of inversions$$$^{\ddagger}$$$ the array can have after performing at most one operation?$$$^\dagger$$$ A binary array is an array that contains only zeroes and ones.$$$^\ddagger$$$ The number of inversions in an array is the number of pairs of indices $$$i,j$$$ such that $$$i<j$$$ and $$$a_i > a_j$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the array. The following line contains $$$n$$$ space-separated positive integers $$$a_1$$$, $$$a_2$$$,..., $$$a_n$$$ ($$$0 \leq a_i \leq 1$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, output a single integer  — the maximum number of inversions the array can have after performing at most one operation.

NoteFor the first test case, the inversions are initially formed by the pairs of indices ($$$1, 2$$$), ($$$1, 4$$$), ($$$3, 4$$$), being a total of $$$3$$$, which already is the maximum possible.For the second test case, the inversions are initially formed by the pairs of indices ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$), being a total of four. But, by flipping the first element, the array becomes $$${1, 1, 0, 0, 1, 0}$$$, which has the inversions formed by the pairs of indices ($$$1, 3$$$), ($$$1, 4$$$), ($$$1, 6$$$), ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$) which total to $$$7$$$ inversions which is the maximum possible.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my @cand;

	push @cand, count_inversions( @_ );

	my @A = @_;

	for my $i ( 0 .. @A - 1 ){
		if( $A[ $i ] == 0 ){
			$A[ $i ] = 1;
			last;
			}
		}

	push @cand, count_inversions( @A );

	@A = @_;

	for my $i ( reverse 0 .. @A - 1 ){
		if( $A[ $i ] == 1 ){
			$A[ $i ] = 0;
			last;
			}
		}

	push @cand, count_inversions( @A );

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

sub count_inversions {
	my $cz = grep !$_, @_;

	my $Z = 0;

	for my $i ( 0 .. @_ - 1 ){
		if( $_[ $i ] == 1 ){
			$Z += $cz;
			}
		else{
			$cz --;
			}
		}

	return $Z;
	}


Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.

The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children.

Print "Yes" if the tree is a spruce and "No" otherwise.

NoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example:

# returns 1 if the number of children is greater
# than or equal to three and returns 0 otherwise
# this subroutine also returns 1 if the node is a leaf
sub has_three_leaves {

    my ($mapp_ref, $curr) = @_;

    # count the number of leaves for each node
    my $leaves = 0;

    # return 1 if the node is a leaf
    if ( (scalar @{ $mapp_ref -> { $curr } }) == 0 ) {
	return 1;
    }

    # count number of children that are leaves
    for my $one_key (@{ $mapp_ref -> { $curr } }) {

	if ( (scalar @{ $mapp_ref -> { $one_key } }) == 0 ) {
	    $leaves += 1;
	    if ( $leaves >= 3 ) {
		return 1;
	    }
	}
    }

    return 0;
}

# returns 1 if the tree is sparse
# and returns 0 otherwise
sub is_sparse {

    my $mapp_ref = $_[0];

    for my $i (keys %{ $mapp_ref }) {

	if ( not &has_three_leaves ( $mapp_ref, $i ) ) {
	    # return 0 because we found a non-leaf node that has
	    # less than three children
	    return 0;
	}
    }
    # return 1 because every non-leaf node
    # that has at least three children
    return 1;
}

# read number of nodes n
my $n = <STDIN>;
chomp ( $n );

# my map
my %mapp;
# parent
my $p;

#
my @children = ();

# read edges of the tree
for my $i (2..$n) {
    $p = <STDIN>;
    chomp ( $p );

    $mapp { $i } = [ () ];

    if ( not exists $mapp { $p } ) {
	# inserts a reference to an empty array
	$mapp { $p } = [ () ];
    }

    push (@{ $mapp{ $p } }, $i);
}

# calculate answer
my $ans = &is_sparse ( \%mapp );

# print answer
if ( $ans ) {
    print "YES\n";
}
else {
    print "NO\n";
}


There are some beautiful girls in Arpa’s land as mentioned before.Once Arpa came up with an obvious problem:Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that , where  is bitwise xor operation (see notes for explanation).  Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.

First line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the array and the integer x. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the elements of the array.

Print a single integer: the answer to the problem.

NoteIn the first sample there is only one pair of i = 1 and j = 2.  so the answer is 1.In the second sample the only two pairs are i = 3, j = 4 (since ) and i = 1, j = 5 (since ).A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.

use strict;
use warnings;

my ($n,$x)=split / /,<>;
chomp($n,$x);

my @data=split / /,<>;
chomp(@data);
my %k;
for(my $i=0;$i<$n;$i++){
	push(@{$k{$data[$i]}},$i);
}
my $ans=0;

if($x==0){
for my $dd (keys %k){
	my $ff=scalar(@{$k{$dd}});
	$ans+=($ff)*($ff-1)/2;
}
print $ans . "\n";
}
else{
for my $dd (keys %k){
	my $t= int($x)^int($dd);
	if(defined $k{$t}){
		$ans+=scalar(@{$k{$dd}}) * scalar(@{$k{$t}});
	}
}
$ans/=2;
print $ans . "\n";
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

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

	@_ = split ' ', <>;

	my $j = 0;
	for my $i (0 .. 20){
		$j = $i;
		$x < 2 ** $i and last;
		}

	$debug and print "j: $j";

	my %h;

	$h{$_} ++ for @_;

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

	my $sum = 0;

	for (@_){
		$h{$_} --;

		my $rem = $_ % 2 ** $j;
		my $st = $_ - $rem;

		$debug and print "^: ", $rem ^ $x;

		$sum += $h{ $st + ($rem ^ $x) } || 0;

		}

	print $sum;

	}

use strict;
use warnings;

my ($n,$x)=split / /,<>;
chomp($n,$x);

my @data=split / /,<>;
chomp(@data);
my %k;
map {$k{$_}=1} @data;
my $ans=0;
for my $val (@data){
	my $t= int($x)^int($val);
	if(defined $k{$t}){
		$ans++;
	}
}
$ans/=2;
print $ans . "\n";

use strict;
use warnings;

my ($n,$x)=split / /,<>;
chomp($n,$x);

my @data=split / /,<>;
chomp(@data);
my %k;
for(my $i=0;$i<$n;$i++){
	push(@{$k{$data[$i]}},$i);
}
my $ans=0;

if($x==0){
for my $dd (keys %k){
	$ans+=2*scalar(@{$k{$dd}});
}
}
else{
for my $dd (keys %k){
	my $t= int($x)^int($dd);
	if(defined $k{$t}){
		$ans+=scalar(@{$k{$dd}}) * scalar(@{$k{$t}});
	}
}
}
$ans/=2;
print $ans . "\n";

use strict;
use warnings;

my ($n,$x)=split / /,<>;
chomp($n,$x);

my @data=split / /,<>;
chomp(@data);
my %k;
for(my $i=0;$i<$n;$i++){
	push(@{$k{$data[$i]}},$i);
}
my %indexes;

my $ans=0;
for my $dd (keys %k){
	my $t= int($x)^int($dd);
	if(defined $k{$t}){
		$ans+=scalar(@{$k{$dd}}) * scalar(@{$k{$t}});
	}
}
$ans/=2;
print $ans . "\n";


The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?

The first line contains integer n (1 ≤ n ≤ 105) — the number of people in the line. The next line contains n integers, each of them equals 25, 50 or 100 — the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.

Print "YES" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print "NO".

$n = <>;
$hundred = 0;
$fifty = 0;
$twentytwo = 0;
$ans = 'YES';
@queue = split ' ', <>;
foreach $a (@queue)
{
	if($a == 25)
	{
		$twentytwo++;
	}
	elsif($a == 50)
	{
		$fifty++;
		$twentytwo--;
	}
	else
	{
		if($fifty && $twentytwo)
		{
			$fifty--;
			$twentytwo--;
		}
		else
		{
			$twentytwo -= 3;
		}
		$hundred++;
	}
	if($twentytwo < 0 || $fifty < 0)
	{
		$ans = 'NO';
		last;
	}
}
print $ans;

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

sub Solve {
    my %change = ();
    foreach $p (@_) {
        given ($p) {
            when (25) {
                $change{25}++;
            }
            when (50) {
                $change{25} || return 0;
                $change{25}--, $change{50}++;
            }
            when (100) {
                $change{25} || return 0;
                $change{50} || $change{25} >= 3 || return 0;
                if ($change{50}) {
                    $change{50}--, $change{25}--, $change{100}++;
                } else {
                    $change{25} -= 3;
                    $change{100}++;
                }
            }
        }
    }
    return 1;
}

while (<>) {
    @queue = split /\s+/, <>;
    say &Solve(@queue)? 'YES' : 'NO';
}

<>;
my $change = 0;
for (split / /, <>) {
    if (int($_-=25) > $change) {
        $change = -1;
        last;
    }
    $change += 25;
}
print $change == -1 ? "NO\n" : "YES\n";

<>;
my $change = 0;
for (split / /, <>) {
    if (int$_ == 25) {
        $change += 25;
    }
    elsif (int($_ -= 25) <= $change) {
        $change += $_;
    }
    else {
        $change = -1;
        last;
    }
}
print $change == -1 ? "NO\n" : "YES\n";

<>;
my $change = 0;
my $ans = "YES\n";
for (split / /, <>) {
    $change += 25, next  if(int$_ == 25);
    $change -= $_, next  if($_-=25 <= $change);
    $ans = "NO\n";
    last;
}
print $ans;

$n = <>;
$hundred = 0;
$fifty = 0;
$twentytwo = 0;
$ans = 'YES';
@queue = split ' ', <>;
foreach $a (@queue)
{
	if($a == 25)
	{
		$twentytwo++;
	}
	elsif($a == 50)
	{
		$fifty++;
		$twentytwo--;
	}
	else
	{
		if($fifty && $twentytwo)
		{
			$fifty++;
			$twentytwo--;
		}
		else
		{
			$twentytwo -= 3;
		}
		$hundred++;
	}
	if($twentytwo < 0 || $fifty < 0)
	{
		$ans = 'NO';
		last;
	}
}
print $ans;


George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living in it and the room can accommodate qi people in total (pi ≤ qi). Your task is to count how many rooms has free place for both George and Alex.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of rooms. The i-th of the next n lines contains two integers pi and qi (0 ≤ pi ≤ qi ≤ 100) — the number of people who already live in the i-th room and the room's capacity.

Print a single integer — the number of rooms where George and Alex can move in.

my $a = <>;
my $cnt = 0;
foreach (0 .. $a)
{
    ($b, $c) = split " ", <>;
    ++$cnt unless $b + 2 > $c;
}
print $cnt;

#!/usr/bin/perl

use 5.012;
use warnings;

my $n = <>;
my $cnt = 0;
while ($n--) {
	my ($p, $q) = split / /, <>;
	$cnt++ if $q - $p >= 2;
}
print $cnt;

use strict;
my $t = <>;
my $cnt = 0;
while($t --) {

	chomp (my $line = <>) ;
	my ($a,$b) = split / /, $line;
	$cnt += $a + 2 <= $b;
}
print "$cnt\n";

#!/perl -w

use strict ;

chomp ( my $n = <STDIN> );

my $canlive = 0 ;
while ($n--){
    my($cu_people,$all_people) = split /\s+/s , <STDIN> ;
    $canlive++  if ( $all_people - $cu_people >= 2 ) ;

}

print $canlive,"\n" ;

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

chomp($n = <>);
my $ans = 0;
while ($n-- > 0) {
	($p, $q) = split / /, <>;
	$p+2<=$q and $ans++;
}
say $ans;

#!/usr/bin/perl -w

use strict;

my $n = <>;
my $c = 0;
for (1 .. $n) {
    my ($p, $q) = split ' ', <>;
    $c++ if $p + 2 <= $q;
}
print "$c\n";

use strict;
use warnings;

my $n = <>;
my $cnt = 0;
for (1..$n) {
    my ($a, $b) = split ' ', <>;
    $cnt++ if ($a < $b - 1);
}
print $cnt."\n";

<stdin>;$res = 0; while(<stdin>){chomp; my ($x, $n) = split(" "); $res += 1 if $x <= $n-2; } print "$res\n"

use strict;
my $t = <>;
my $cnt = 0;
while($t --) {

	chomp (my $line = <>) ;
	my ($a,$b) = split / /, $line;
	$cnt += $a < $b;
}
print "$cnt\n";


Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?

The first line contains the only integer n (1 ≤ n ≤ 100) — the number of cookie bags Anna and Maria have. The second line contains n integers ai (1 ≤ ai ≤ 100) — the number of cookies in the i-th bag.

Print in the only line the only number — the sought number of ways. If there are no such ways print 0.

NoteIn the first sample Olga should take the only bag so that the twins ended up with the even number of cookies.In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies — 5 + 3 = 8 ways in total.In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2 * 9 + 99 = 117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies.

#!perl
$_ = <STDIN>;
$scookies = <STDIN>;
@cookies = split(/\D/,$scookies);
$odd = $even = 0;
foreach $i (@cookies) {
	if ($i % 2) {
		$odd++;
	} else {
		$even++;
	}
}
$result = ($odd % 2)? $odd: $even;
print $result;

#!perl
$scookies = <STDIN>;
@cookies = split(/\D/,$scookies);
$odd = $even = 0;
foreach $i (@cookies) {
	if ($i % 2) {
		$odd++;
	} else {
		$even++;
	}
}
$result = ($odd % 2)? $odd: $even;
print $result;


Vasya plays the Geometry Horse.The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value. There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f  points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.

The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types. Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly. The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.  The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

Print the only number — the maximum number of points Vasya can get.

NoteIn the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.

#!/usr/bin/perl

use strict;
use warnings;
use bigint;

my $figures = <STDIN>;
my $total = 0;
my @figure = ();
foreach(1 .. $figures){
	$_ = <STDIN>;
	m/^(\d+) (\d+)/;
	push @figure, [$1, $2];
	$total += $1;
}
@figure = sort {$a->[1] <=> $b->[1]} @figure;

$_ = <STDIN>;
$_ = <STDIN>;
s/[\r\n]+$//;
my @factor = split / /, $_;
push @factor, $total + 100;

my $ret = 0;
my $f = 1;
my $d = 0;
my $p = shift @factor;
foreach(@figure){
	my $k = $_->[0];
	my $c = $_->[1];
	while($k){
		my $breakable = $p-$d < $k ? $p-$d : $k;
		$ret += $c * $f * $breakable;
		$k -= $breakable;
		$d += $breakable;
		if($p <= $d){
			$f++;
			$p = shift @factor;
		}
	}
}

print "$ret\n";


Mishka wants to buy some food in the nearby shop. Initially, he has $$$s$$$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number $$$1 \le x \le s$$$, buy food that costs exactly $$$x$$$ burles and obtain $$$\lfloor\frac{x}{10}\rfloor$$$ burles as a cashback (in other words, Mishka spends $$$x$$$ burles and obtains $$$\lfloor\frac{x}{10}\rfloor$$$ back). The operation $$$\lfloor\frac{a}{b}\rfloor$$$ means $$$a$$$ divided by $$$b$$$ rounded down.It is guaranteed that you can always buy some food that costs $$$x$$$ for any possible value of $$$x$$$.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has $$$s=19$$$ burles then the maximum number of burles he can spend is $$$21$$$. Firstly, he can spend $$$x=10$$$ burles, obtain $$$1$$$ burle as a cashback. Now he has $$$s=10$$$ burles, so can spend $$$x=10$$$ burles, obtain $$$1$$$ burle as a cashback and spend it too.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. The next $$$t$$$ lines describe test cases. Each test case is given on a separate line and consists of one integer $$$s$$$ ($$$1 \le s \le 10^9$$$) — the number of burles Mishka initially has.

For each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;

	my $sum = 0;

	while( /../ ){

		my $last = chop;

		$sum += $_ * 10;

		$_ += $last;
		}

	$sum += $_;

	print $sum;
	}


Consider the following process. You have a binary string (a string where each character is either 0 or 1) $$$w$$$ of length $$$n$$$ and an integer $$$x$$$. You build a new binary string $$$s$$$ consisting of $$$n$$$ characters. The $$$i$$$-th character of $$$s$$$ is chosen as follows:  if the character $$$w_{i-x}$$$ exists and is equal to 1, then $$$s_i$$$ is 1 (formally, if $$$i > x$$$ and $$$w_{i-x} = $$$ 1, then $$$s_i = $$$ 1);  if the character $$$w_{i+x}$$$ exists and is equal to 1, then $$$s_i$$$ is 1 (formally, if $$$i + x \le n$$$ and $$$w_{i+x} = $$$ 1, then $$$s_i = $$$ 1);  if both of the aforementioned conditions are false, then $$$s_i$$$ is 0. You are given the integer $$$x$$$ and the resulting string $$$s$$$. Reconstruct the original string $$$w$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains the resulting string $$$s$$$ ($$$2 \le |s| \le 10^5$$$, each character of $$$s$$$ is either 0 or 1). The second line contains one integer $$$x$$$ ($$$1 \le x \le |s| - 1$$$). The total length of all strings $$$s$$$ in the input does not exceed $$$10^5$$$.

For each test case, print the answer on a separate line as follows:   if no string $$$w$$$ can produce the string $$$s$$$ at the end of the process, print $$$-1$$$;  otherwise, print the binary string $$$w$$$ consisting of $$$|s|$$$ characters. If there are multiple answers, print any of them.


Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.


You are the gym teacher in the school.There are $$$n$$$ students in the row. And there are two rivalling students among them. The first one is in position $$$a$$$, the second in position $$$b$$$. Positions are numbered from $$$1$$$ to $$$n$$$ from left to right.Since they are rivals, you want to maximize the distance between them. If students are in positions $$$p$$$ and $$$s$$$ respectively, then distance between them is $$$|p - s|$$$. You can do the following operation at most $$$x$$$ times: choose two adjacent (neighbouring) students and swap them.Calculate the maximum distance between two rivalling students after at most $$$x$$$ swaps.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of each test case contains four integers $$$n$$$, $$$x$$$, $$$a$$$ and $$$b$$$ ($$$2 \le n \le 100$$$, $$$0 \le x \le 100$$$, $$$1 \le a, b \le n$$$, $$$a \neq b$$$) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

For each test case print one integer — the maximum distance between two rivaling students which you can obtain.

NoteIn the first test case you can swap students in positions $$$3$$$ and $$$4$$$. And then the distance between the rivals is equal to $$$|4 - 2| = 2$$$.In the second test case you don't have to swap students. In the third test case you can't swap students.

#!/usr/bin/env perl

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

# essential
my @tokens = ();

my $t = read_token();

for (1..$t) {
    my $line = read_line();
    my ($n, $x, $a, $b) = split q{ }, $line;
    ($a, $b) = ($b, $a) if $a > $b;
    my $answer;

    my $l = $a-1;
    my $r = $n-$b;
    if ( $x >= $l + $r ) {
        $answer = $n-1;
    }
    else {
        $answer = $b-$a+$x;
    }
    say $answer;
}

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


Aleksey has $$$n$$$ friends. He is also on a vacation right now, so he has $$$m$$$ days to play this new viral cooperative game! But since it's cooperative, Aleksey will need one teammate in each of these $$$m$$$ days.On each of these days some friends will be available for playing, and all others will not. On each day Aleksey must choose one of his available friends to offer him playing the game (and they, of course, always agree). However, if any of them happens to be chosen strictly more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times, then all other friends are offended. Of course, Aleksey doesn't want to offend anyone.Help him to choose teammates so that nobody is chosen strictly more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\leq n, m\leq 100\,000$$$) standing for the number of friends and the number of days to play, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains an integer $$$k_i$$$ ($$$1\leq k_i\leq n$$$), followed by $$$k_i$$$ distinct integers $$$f_{i1}$$$, ..., $$$f_{ik_i}$$$ ($$$1\leq f_{ij}\leq n$$$), separated by spaces — indices of available friends on the day $$$i$$$. It is guaranteed that the sums of $$$n$$$ and $$$m$$$ over all test cases do not exceed $$$100\,000$$$. It's guaranteed that the sum of all $$$k_i$$$ over all days of all test cases doesn't exceed $$$200\,000$$$.

Print an answer for each test case. If there is no way to achieve the goal, print "NO". Otherwise, in the first line print "YES", and in the second line print $$$m$$$ space separated integers $$$c_1$$$, ..., $$$c_m$$$. Each $$$c_i$$$ must denote the chosen friend on day $$$i$$$ (and therefore must be one of $$$f_{ij}$$$). No value must occur more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times. If there is more than one possible answer, print any of them.


Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that:   r ≥ 2;  for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds;  each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled:   no pair of tubes has common cells;  each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.

The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.

Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.

NotePicture for the first sample:   Picture for the second sample:


You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.In a more formal way, you have to find the quantity of tuples (a, b, x, y) such that 1 ≤ a ≤ b < x ≤ y ≤ |s| and substrings s[a... b], s[x... y] are palindromes.A palindrome is a string that can be read the same way from left to right and from right to left. For example, "abacaba", "z", "abba" are palindromes.A substring s[i... j] (1 ≤ i ≤ j ≤ |s|) of string s = s1s2... s|s| is a string sisi + 1... sj. For example, substring s[2...4] of string s = "abacaba" equals "bac".

The first line of input contains a non-empty string s which consists of lowercase letters ('a'...'z'), s contains at most 2000 characters.

Output a single number — the quantity of pairs of non-overlapping palindromic substrings of s. Please do not use the %lld format specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d format specifier.


Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.For each cell i you are given two values:   li — cell containing previous element for the element in the cell i;  ri — cell containing next element for the element in the cell i. If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.    Three lists are shown on the picture. For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.Any other action, other than joining the beginning of one list to the end of another, can not be performed.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located. Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list. It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.

Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.


You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).

The first line contains three positive integers n, p, q (1 ≤ p, q ≤ n ≤ 100). The second line contains the string s consists of lowercase and uppercase latin letters and digits.

If it's impossible to split the string s to the strings of length p and q print the only number "-1". Otherwise in the first line print integer k — the number of strings in partition of s. Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s — from left to right. If there are several solutions print any of them.

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

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

my @npq = split(" ",$input);
my $n = $npq[0];
my $p = $npq[1];
my $q = $npq[2];

for (my $var = 0; $var * $p <= $n ; $var++)
{
  if(($n - ($var* $p)) % $q == 0)
  {
      my $var2 = ($n - ($var * $p)) / $q;
      my $sub = 0;

      say $var + $var2;

      for (my $k = 0; $k < $var; $k++)
      {
        print substr($string, $sub, $p) . "\n";
        $sub = $sub + $p;
      }
      for (my $k = 0; $k < $var2; $k++)
      {
        print substr($string, $sub, $q) . "\n";
        $sub = $sub + $q;
      }

      exit;
  }
}

say "-1";

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

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

my @npq = split(" ",$input);
my $n = $npq[0];
my $p = $npq[1];
my $q = $npq[2];

for (my $var = 0; $var * $p <= $n ; $var++)
{
  if(($n - ($var* $p)) % $q == 0)
  {
      my $var2 = ($n - ($var * $p)) / $q;
      my $sub = 0;

      for (my $k = 0; $k < $var; $k++)
      {
        print substr($string, $sub, $p) . "\n";
        $sub = $sub + $p;
      }
      for (my $k = 0; $k < $var2; $k++)
      {
        print substr($string, $sub, $q) . "\n";
        $sub = $sub + $q;
      }

      exit;
  }
}

say "-1";


Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend it on reading.Help Luba to determine the minimum number of day when she finishes reading.It is guaranteed that the answer doesn't exceed n.Remember that there are 86400 seconds in a day.

The first line contains two integers n and t (1 ≤ n ≤ 100, 1 ≤ t ≤ 106) — the number of days and the time required to read the book. The second line contains n integers ai (0 ≤ ai ≤ 86400) — the time Luba has to spend on her work during i-th day.

Print the minimum day Luba can finish reading the book. It is guaranteed that answer doesn't exceed n.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $n, $t ) = split;
	@_ = map { 86400 - $_ } split ' ', <>;

	my $i = 0;

	for( @_ ){
		$i ++;
		$t -= $_;
		$t <= 0 and last;
		}

	print $i;
	}


Polycarp was gifted an array $$$a$$$ of length $$$n$$$. Polycarp considers an array beautiful if there exists a number $$$C$$$, such that each number in the array occurs either zero or $$$C$$$ times. Polycarp wants to remove some elements from the array $$$a$$$ to make it beautiful.For example, if $$$n=6$$$ and $$$a = [1, 3, 2, 1, 4, 2]$$$, then the following options are possible to make the array $$$a$$$ array beautiful:   Polycarp removes elements at positions $$$2$$$ and $$$5$$$, array $$$a$$$ becomes equal to $$$[1, 2, 1, 2]$$$;  Polycarp removes elements at positions $$$1$$$ and $$$6$$$, array $$$a$$$ becomes equal to $$$[3, 2, 1, 4]$$$;  Polycarp removes elements at positions $$$1, 2$$$ and $$$6$$$, array $$$a$$$ becomes equal to $$$[2, 1, 4]$$$; Help Polycarp determine the minimum number of elements to remove from the array $$$a$$$ to make it beautiful.

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

For each test case, output one integer — the minimum number of elements that Polycarp has to remove from the array $$$a$$$ to make it beautiful.

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	@_ = split ' ', <>;

	$debug and print "[@_]";

	my %h;

	map $h{ $_ } ++, @_;

	$debug and print "keys_h:", join ' ', sort keys %h;

	my %values;

	map $values{ $_ } ++, values %h;

	$debug and print "keys_values: $_ --> $values{ $_ }" for sort keys %values;

	my @cand;

	for my $value ( sort { $a <=> $b } keys %values ){
		$debug and print " value:[$value]";

		my $cnt = 0;

		for my $value2 ( sort { $a <=> $b } keys %values ){
			$debug and print "  value2:[$value2]";

			next if $value == $value2;

			if( $value2 < $value ){
				$cnt += $value2 * $values{ $value2 };
				}
			else{
				$cnt += ( $value2 - $value ) * $values{ $value2 };
				}

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

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

		push @cand, $cnt;
		}

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

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


You are given a system of pipes. It consists of two rows, each row consists of $$$n$$$ pipes. The top left pipe has the coordinates $$$(1, 1)$$$ and the bottom right — $$$(2, n)$$$.There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types:  Types of pipes You can turn each of the given pipes $$$90$$$ degrees clockwise or counterclockwise arbitrary (possibly, zero) number of times (so the types $$$1$$$ and $$$2$$$ can become each other and types $$$3, 4, 5, 6$$$ can become each other).You want to turn some pipes in a way that the water flow can start at $$$(1, 0)$$$ (to the left of the top left pipe), move to the pipe at $$$(1, 1)$$$, flow somehow by connected pipes to the pipe at $$$(2, n)$$$ and flow right to $$$(2, n + 1)$$$.Pipes are connected if they are adjacent in the system and their ends are connected. Here are examples of connected pipes:  Examples of connected pipes Let's describe the problem using some example:  The first example input And its solution is below:   The first example answer As you can see, the water flow is the poorly drawn blue line. To obtain the answer, we need to turn the pipe at $$$(1, 2)$$$ $$$90$$$ degrees clockwise, the pipe at $$$(2, 3)$$$ $$$90$$$ degrees, the pipe at $$$(1, 6)$$$ $$$90$$$ degrees, the pipe at $$$(1, 7)$$$ $$$180$$$ degrees and the pipe at $$$(2, 7)$$$ $$$180$$$ degrees. Then the flow of water can reach $$$(2, n + 1)$$$ from $$$(1, 0)$$$.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Then $$$q$$$ queries follow. Each query consists of exactly three lines. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of pipes in each row. The next two lines contain a description of the first and the second rows correspondingly. Each row description consists of $$$n$$$ digits from $$$1$$$ to $$$6$$$ without any whitespaces between them, each digit corresponds to the type of pipe in the corresponding cell. See the problem statement to understand which digits correspond to which types of pipes. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For the $$$i$$$-th query print the answer for it — "YES" (without quotes) if it is possible to turn some pipes in a way that the water flow can reach $$$(2, n + 1)$$$ from $$$(1, 0)$$$, and "NO" otherwise.

NoteThe first query from the example is described in the problem statement.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

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

	@_ = map ~~<>, 1 .. 2;
	chomp @_;

	$debug and print for @_;

	y/1-6/223/ for @_;

	$debug and print for @_;

	$_[ 1 ] = reverse $_[ 1 ];

	$_ = '';

	while( $_[ 0 ] =~ /./g ){
		$_ .= $& . chop $_[ 1 ];
		}

	$debug and print "[$_]";

	my $fail = 0;

	my $switch = 0;

	while( /(.)(.)/g ){
		if( $& == 33 ){
			$switch ++;
			$switch %= 2;
			}
		elsif( $switch == 0 and $& == 32 ){
			$fail = 1;
			}
		elsif( $switch == 1 and $& == 23 ){
			$fail = 1;
			}
		}

	print $fail || $switch == 0 ? "NO" : "YES";
	}


Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?

The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000).

Print the n-th even-length palindrome number.

NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001.

$n = <>; chomp $n;
print $n, scalar reverse $n;

#!/usr/bin/env perl

use strict;
use warnings;

my $thiswontwork = <>;
chomp $thiswontwork;
print $thiswontwork;
my $ff = reverse $thiswontwork;
print $ff;
print "\n";

$a = <>;
chomp($a);
print $a.reverse($a);


A ticket is a string consisting of six digits. A ticket is considered lucky if the sum of the first three digits is equal to the sum of the last three digits. Given a ticket, output if it is lucky or not. Note that a ticket can have leading zeroes.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of testcases. The description of each test consists of one line containing one string consisting of six digits.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. Output "YES" if the given ticket is lucky, and "NO" 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).

NoteIn the first test case, the sum of the first three digits is $$$2 + 1 + 3 = 6$$$ and the sum of the last three digits is $$$1 + 3 + 2 = 6$$$, they are equal so the answer is "YES".In the second test case, the sum of the first three digits is $$$9 + 7 + 3 = 19$$$ and the sum of the last three digits is $$$8 + 9 + 4 = 21$$$, they are not equal so the answer is "NO".In the third test case, the sum of the first three digits is $$$0 + 4 + 5 = 9$$$ and the sum of the last three digits is $$$2 + 0 + 7 = 9$$$, they are equal so the answer is "YES".

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

#print "yo\n";

my $n = <STDIN>;

my $i = 0;
while ($i < $n) {
    my $ticket = <STDIN>;
    chomp($ticket);

    my $left_part = substr($ticket, 0, 1) +
        substr($ticket, 1, 1) + substr($ticket, 2, 1);
    my $right_part = substr($ticket, 3, 1) +
        substr($ticket, 4, 1) + substr($ticket, 5, 1);
    if ($left_part == $right_part) {
        print STDOUT "YES\n";
    }
    else {
        print STDOUT "NO\n";
    }
    $i++;
}


Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous).If it is possible to partition the array, also give any possible way of valid partitioning.

The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109).

In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition.


You are given $$$n$$$ chips on a number line. The $$$i$$$-th chip is placed at the integer coordinate $$$x_i$$$. Some chips can have equal coordinates.You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:  Move the chip $$$i$$$ by $$$2$$$ to the left or $$$2$$$ to the right for free (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 2$$$ or with $$$x_i + 2$$$);  move the chip $$$i$$$ by $$$1$$$ to the left or $$$1$$$ to the right and pay one coin for this move (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 1$$$ or with $$$x_i + 1$$$). Note that it's allowed to move chips to any integer coordinate, including negative and zero.Your task is to find the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate (i.e. all $$$x_i$$$ should be equal after some sequence of moves).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of chips. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), where $$$x_i$$$ is the coordinate of the $$$i$$$-th chip.

Print one integer — the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate.

NoteIn the first example you need to move the first chip by $$$2$$$ to the right and the second chip by $$$1$$$ to the right or move the third chip by $$$2$$$ to the left and the second chip by $$$1$$$ to the left so the answer is $$$1$$$.In the second example you need to move two chips with coordinate $$$3$$$ by $$$1$$$ to the left so the answer is $$$2$$$.

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

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

# start

chomp (my $n = <STDIN>);

chomp (my $line = <STDIN>);

my @chips = split q{ }, $line;

my $odd = 0;
my $even = 0;
for (@chips) {
    $odd++ if $_ % 2 == 1;
    $even++ if $_ % 2 == 0;
}

say min($odd, $even);

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my %h;

	map $h{ $_ % 2 } ++, 0, 1, @_;

	print -1 + ( sort { $a <=> $b } values %h )[ 0 ];
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my %h;

	map $h{ $_ % 2 } ++, @_;

	print 0 + ( sort { $a <=> $b } values %h )[ 0 ];
	}


Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string $$$a$$$ consisting of lowercase English letters. The string $$$a$$$ has a length of $$$2$$$ or more characters. Then, from string $$$a$$$ he builds a new string $$$b$$$ and offers Alice the string $$$b$$$ so that she can guess the string $$$a$$$.Bob builds $$$b$$$ from $$$a$$$ as follows: he writes all the substrings of length $$$2$$$ of the string $$$a$$$ in the order from left to right, and then joins them in the same order into the string $$$b$$$.For example, if Bob came up with the string $$$a$$$="abac", then all the substrings of length $$$2$$$ of the string $$$a$$$ are: "ab", "ba", "ac". Therefore, the string $$$b$$$="abbaac".You are given the string $$$b$$$. Help Alice to guess the string $$$a$$$ that Bob came up with. It is guaranteed that $$$b$$$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.

The first line contains a single positive integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case consists of one line in which the string $$$b$$$ is written, consisting of lowercase English letters ($$$2 \le |b| \le 100$$$) — the string Bob came up with, where $$$|b|$$$ is the length of the string $$$b$$$. It is guaranteed that $$$b$$$ was built according to the algorithm given above.

Output $$$t$$$ answers to test cases. Each answer is the secret string $$$a$$$, consisting of lowercase English letters, that Bob came up with.

NoteThe first test case is explained in the statement.In the second test case, Bob came up with the string $$$a$$$="ac", the string $$$a$$$ has a length $$$2$$$, so the string $$$b$$$ is equal to the string $$$a$$$.In the third test case, Bob came up with the string $$$a$$$="bcdaf", substrings of length $$$2$$$ of string $$$a$$$ are: "bc", "cd", "da", "af", so the string $$$b$$$="bccddaaf".

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;

	print s/\B\w\K\w//gr;
	}


There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.

The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads.

Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;
my $sum;
my $depth;
my %h;

while(<>){
	%h = ();

	map {
		my( $u, $v ) = split ' ', <>;
		$h{ $u }{ $v } ++;
		$h{ $v }{ $u } ++;
		} 1 .. $_ - 1;

	$sum = 0;
	$depth = -1;
	go( 0, 1, 1 );

	$debug and print "-------ANS:";
	print $sum;

	}

	sub go {
		my( $prev, $try, $pbb ) = @_;
		$depth ++;
		$debug and print "$depth|@_|$sum";

		my @keys = grep { $_ != $prev } keys %{ $h{ $try } };

		if( ! @keys ){
			$sum += $pbb * $depth;
			$debug and print " sum: $sum";
			}

		for my $key ( @keys ){

			go( $try, $key, $pbb / @keys );

			}

		$depth --;
		}


Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position $$$x$$$, and the shorter rabbit is currently on position $$$y$$$ ($$$x \lt y$$$). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by $$$a$$$, and the shorter rabbit hops to the negative direction by $$$b$$$.  For example, let's say $$$x=0$$$, $$$y=10$$$, $$$a=2$$$, and $$$b=3$$$. At the $$$1$$$-st second, each rabbit will be at position $$$2$$$ and $$$7$$$. At the $$$2$$$-nd second, both rabbits will be at position $$$4$$$.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Each test case contains exactly one line. The line consists of four integers $$$x$$$, $$$y$$$, $$$a$$$, $$$b$$$ ($$$0 \le x \lt y \le 10^9$$$, $$$1 \le a,b \le 10^9$$$) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.

For each test case, print the single integer: number of seconds the two rabbits will take to be at the same position. If the two rabbits will never be at the same position simultaneously, print $$$-1$$$.

NoteThe first case is explained in the description.In the second case, each rabbit will be at position $$$3$$$ and $$$7$$$ respectively at the $$$1$$$-st second. But in the $$$2$$$-nd second they will be at $$$6$$$ and $$$4$$$ respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.

#!/usr/bin/env perl

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

use Carp;

# essential
my @tokens = ();

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

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

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

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

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

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

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

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

    $$ref = !$$ref;
}

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 ($x, $y, $a, $b) = split q{ }, read_line;

    my $gap = $y - $x;

    my $sum = sum($a, $b);

    if ($gap % $sum == 0) {
        say $gap / $sum;
    }
    else {
        say -1;
    }
}


A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.Determine if it is possible for the islanders to arrange the statues in the desired order.

The first line contains a single integer n (2 ≤ n ≤ 200 000) — the total number of islands. The second line contains n space-separated integers ai (0 ≤ ai ≤ n - 1) — the statue currently placed on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≤ bi ≤ n - 1) — the desired statues of the ith island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct.

Print "YES" (without quotes) if the rearrangement can be done in the existing network, and "NO" otherwise.

NoteIn the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3.In the second sample, the islanders can simply move statue 1 from island 1 to island 2.In the third sample, no sequence of movements results in the desired position.


Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.

The first line of the input contains n (1 ≤ n ≤ 200 000) — the number of bishops. Each of next n lines contains two space separated integers xi and yi (1 ≤ xi, yi ≤ 1000) — the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.

Output one integer — the number of pairs of bishops which attack each other.

NoteIn the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.

use strict;
use warnings;

while(<>) {
  my (%r,%l);
  for(1..$_) {
    my ($x,$y) = split " ", <>;
    $r{$x+$y}++;
    $l{$x-$y}++;
  }
  my $res = 0;
  $res += $_ * ($_-1)/2 foreach values %r;
  $res += $_ * ($_-1)/2 foreach values %l;
  print "$res\n";
}


You are given an array $$$a_1, a_2, \ldots, a_n$$$ of positive integers. A good pair is a pair of indices $$$(i, j)$$$ with $$$1 \leq i, j \leq n$$$ such that, for all $$$1 \leq k \leq n$$$, the following equality holds:$$$$$$ |a_i - a_k| + |a_k - a_j| = |a_i - a_j|, $$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Find a good pair. Note that $$$i$$$ can be equal to $$$j$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ for all test cases is at most $$$2 \cdot 10^5$$$.

For each test case, print a single line with two space-separated indices $$$i$$$ and $$$j$$$ which form a good pair of the array. The case $$$i=j$$$ is allowed. It can be shown that such a pair always exists. If there are multiple good pairs, print any of them.


Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked $$$n$$$ of them how much effort they needed to reach red."Oh, I just spent $$$x_i$$$ hours solving problems", said the $$$i$$$-th of them. Bob wants to train his math skills, so for each answer he wrote down the number of minutes ($$$60 \cdot x_i$$$), thanked the grandmasters and went home. Bob could write numbers with leading zeroes — for example, if some grandmaster answered that he had spent $$$2$$$ hours, Bob could write $$$000120$$$ instead of $$$120$$$.Alice wanted to tease Bob and so she took the numbers Bob wrote down, and for each of them she did one of the following independently:   rearranged its digits, or  wrote a random number. This way, Alice generated $$$n$$$ numbers, denoted $$$y_1$$$, ..., $$$y_n$$$.For each of the numbers, help Bob determine whether $$$y_i$$$ can be a permutation of a number divisible by $$$60$$$ (possibly with leading zeroes).

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 418$$$) — the number of grandmasters Bob asked. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains a single integer $$$y_i$$$ — the number that Alice wrote down. Each of these numbers has between $$$2$$$ and $$$100$$$ digits '0' through '9'. They can contain leading zeroes.

Output $$$n$$$ lines. For each $$$i$$$, output the following. If it is possible to rearrange the digits of $$$y_i$$$ such that the resulting number is divisible by $$$60$$$, output "red" (quotes for clarity). Otherwise, output "cyan".

NoteIn the first example, there is one rearrangement that yields a number divisible by $$$60$$$, and that is $$$360$$$.In the second example, there are two solutions. One is $$$060$$$ and the second is $$$600$$$.In the third example, there are $$$6$$$ possible rearrangments: $$$025$$$, $$$052$$$, $$$205$$$, $$$250$$$, $$$502$$$, $$$520$$$. None of these numbers is divisible by $$$60$$$.In the fourth example, there are $$$3$$$ rearrangements: $$$228$$$, $$$282$$$, $$$822$$$.In the fifth example, none of the $$$24$$$ rearrangements result in a number divisible by $$$60$$$.In the sixth example, note that $$$000\dots0$$$ is a valid solution.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;

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

	print s/0// && $sum % 3 == 0 && /[02468]/ ? 'red' : 'cyan';
	}


You are given n × m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that:  All cells in a set have the same color.  Every two cells in a set share row or column.

The first line of input contains integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns correspondingly. The next n lines of input contain descriptions of rows. There are m integers, separated by spaces, in each line. The number equals 0 if the corresponding cell is colored white and equals 1 if the corresponding cell is colored black.

Output single integer  — the number of non-empty sets from the problem description.

NoteIn the second example, there are six one-element sets. Additionally, there are two two-element sets, the first one consists of the first and the third cells of the first row, the second one consists of the first and the third cells of the second row. To sum up, there are 8 sets.


Let's define $$$S(x)$$$ to be the sum of digits of number $$$x$$$ written in decimal system. For example, $$$S(5) = 5$$$, $$$S(10) = 1$$$, $$$S(322) = 7$$$.We will call an integer $$$x$$$ interesting if $$$S(x + 1) < S(x)$$$. In each test you will be given one integer $$$n$$$. Your task is to calculate the number of integers $$$x$$$ such that $$$1 \le x \le n$$$ and $$$x$$$ is interesting.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) for the $$$i$$$-th test case.

Print $$$t$$$ integers, the $$$i$$$-th should be the answer for the $$$i$$$-th test case.

NoteThe first interesting number is equal to $$$9$$$.


You are given a positive integer $$$x$$$. Check whether the number $$$x$$$ is representable as the sum of the cubes of two positive integers.Formally, you need to check if there are two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b$$$) such that $$$a^3+b^3=x$$$.For example, if $$$x = 35$$$, then the numbers $$$a=2$$$ and $$$b=3$$$ are suitable ($$$2^3+3^3=8+27=35$$$). If $$$x=4$$$, then no pair of numbers $$$a$$$ and $$$b$$$ is suitable.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$x$$$ ($$$1 \le x \le 10^{12}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.

For each test case, output on a separate line:    "YES" if $$$x$$$ is representable as the sum of the cubes of two positive integers.  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

NoteThe number $$$1$$$ is not representable as the sum of two cubes.The number $$$2$$$ is represented as $$$1^3+1^3$$$.The number $$$4$$$ is not representable as the sum of two cubes.The number $$$34$$$ is not representable as the sum of two cubes.The number $$$35$$$ is represented as $$$2^3+3^3$$$.The number $$$16$$$ is represented as $$$2^3+2^3$$$.The number $$$703657519796$$$ is represented as $$$5779^3+7993^3$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my @cubes;
my %h;

for my $i ( 1 .. 1e4 ){
	push @cubes, $i ** 3;
	$h{ $cubes[ -1 ] } = 1;
	}

<>;

while(<>){
	chomp;

	my $find;

	for my $cube ( @cubes ){
		last if $cube > $_;

		$h{ $_ - $cube } and $find = 1 and last;
		}

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


Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?

You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph. The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n. The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.

8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN

#!/usb/bin/env perl

use strict;
use warnings;

package fox_and_minimal_path;

# B. Fox and Minimal path
# time limit per test1:  second
# memory limit per test: 256 megabytes
# input: standard input
# output: standard output
#
# Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
#
# Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
#
# Input
# The first line contains a single integer k (1 ≤ k ≤ 109).
#
# Output
# You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
#
# The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
#
# The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.

# --------------------------------------------------------------------------------

sub ternary_representation {
  my ( $num ) = @_;
  my @arr;
  my $divisor = 3;
  while ( $num > 0 ) {
    push @arr, $num % 3;
    $num = int $num / 3;
  }
  return @arr;
}

# --------------------------------------------------------------------------------

sub get_matrix {
  my ( $k ) = @_;

  my @arr = ternary_representation( $k );
  # my $n = int( log $k / log 3 ) + 1;
  my $n = scalar @arr;
  $n += 2;

  my $all_digits_are_either_0_or_1 = 1;
  for my $i ( @arr ) {
    if ( 2 == $i ) {
      $all_digits_are_either_0_or_1 = 0;
      last;
    }
  }
  my $matrix = [];
  # for my $i ( 0 .. $n - 1 ) {
  #   for my $j ( 0 .. $n - 1 ) {
  #     $matrix->[ $i ]->[ $j ] = 0;
  #   }
  # }

  my $next_index = 2;
  my @vertexes_to_be_connected;

  my $connect_new_vertexes = sub {
    my ( @new_vertexes ) = @_;
    for my $i ( @vertexes_to_be_connected ) {
      for my $j ( @new_vertexes ) {
        $matrix->[ $i ]->[ $j ] = $matrix->[ $j ]->[ $i ] = 1;
      }
    }
  };

  my $add_new_vertexes = sub {
    my ( $count ) = @_;
    my @new_vertexes = ( $next_index .. $next_index + $count - 1 );
    $connect_new_vertexes->( @new_vertexes );
    for my $i ( @vertexes_to_be_connected ) {
      for my $j ( @new_vertexes ) {
        $matrix->[ $i ]->[ $j ] = $matrix->[ $j ]->[ $i ] = 1;
      }
    }
    @vertexes_to_be_connected = @new_vertexes;
    $next_index += $count;
  };

  my $connect_final_vertex = sub {
    $connect_new_vertexes->( 1 );
  };

  for my $i ( 0 .. $#arr ) {
    next unless $arr[ $i ];
    @vertexes_to_be_connected = ( 0 );
    for my $j ( 0 .. $i - 1 ) {
      $add_new_vertexes->( 3 );
    }
    if ( ! $all_digits_are_either_0_or_1 ) {
      $add_new_vertexes->( $arr[ $i ] );
    }
    for my $j ( $i + 1 .. $#arr ) {
      $add_new_vertexes->( 1 );
    }
    $connect_final_vertex->();
  }

  if ( ! @arr ) {
    @vertexes_to_be_connected = ( 0 );
    $connect_final_vertex->();
  }

  return $matrix;
}

# --------------------------------------------------------------------------------

sub get_result {
  my ( $matrix ) = @_;

  my $result = scalar( @{ $matrix } ) . qq(\n);
  for my $i ( 0 .. $#{ $matrix } ) {
    for my $j ( 0 .. $#{ $matrix } ) {
      if ( $matrix->[ $i ]->[ $j ] ) {
        $result .= 'Y';
      }
      else {
        $result .= 'N';
      }
    }
    $result .= qq(\n) if $i != $#{ $matrix };
  }
  return $result;
}

# --------------------------------------------------------------------------------

sub main {
  my $k = int <>;
  print get_result( get_matrix( $k ) );
  return;
}

caller() or __PACKAGE__->main( @ARGV );

# --------------------------------------------------------------------------------


The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x0, y0) of a rectangular squared field of size x × y, after that a mine will be installed into one of the squares of the field. It is supposed to conduct exactly x·y tests, each time a mine is installed into a square that has never been used before. The starting cell of the robot always remains the same.After placing the objects on the field the robot will have to run a sequence of commands given by string s, consisting only of characters 'L', 'R', 'U', 'D'. These commands tell the robot to move one square to the left, to the right, up or down, or stay idle if moving in the given direction is impossible. As soon as the robot fulfills all the sequence of commands, it will blow up due to a bug in the code. But if at some moment of time the robot is at the same square with the mine, it will also blow up, but not due to a bug in the code.Moving to the left decreases coordinate y, and moving to the right increases it. Similarly, moving up decreases the x coordinate, and moving down increases it.The tests can go on for very long, so your task is to predict their results. For each k from 0 to length(s) your task is to find in how many tests the robot will run exactly k commands before it blows up.

The first line of the input contains four integers x, y, x0, y0 (1 ≤ x, y ≤ 500, 1 ≤ x0 ≤ x, 1 ≤ y0 ≤ y) — the sizes of the field and the starting coordinates of the robot. The coordinate axis X is directed downwards and axis Y is directed to the right. The second line contains a sequence of commands s, which should be fulfilled by the robot. It has length from 1 to 100 000 characters and only consists of characters 'L', 'R', 'U', 'D'.

Print the sequence consisting of (length(s) + 1) numbers. On the k-th position, starting with zero, print the number of tests where the robot will run exactly k commands before it blows up.

NoteIn the first sample, if we exclude the probable impact of the mines, the robot's route will look like that: .


You have array a1, a2, ..., an. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 ≤ i ≤ r).Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]).Your task is to find a good segment of the maximum length in array a. Note that a segment of length 1 or 2 is always good.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains integers: a1, a2, ..., an (0 ≤ ai ≤ 109).

Print the length of the longest good segment in array a.


Sayaka Saeki is a member of the student council, which has $$$n$$$ other members (excluding Sayaka). The $$$i$$$-th member has a height of $$$a_i$$$ millimeters.It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wants to arrange all the members in a line such that the amount of photogenic consecutive pairs of members is as large as possible.A pair of two consecutive members $$$u$$$ and $$$v$$$ on a line is considered photogenic if their average height is an integer, i.e. $$$\frac{a_u + a_v}{2}$$$ is an integer.Help Sayaka arrange the other members to maximize the number of photogenic consecutive pairs.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 500$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2000$$$)  — the number of other council members. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$)  — the heights of each of the other members in millimeters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.

For each test case, output on one line $$$n$$$ integers representing the heights of the other members in the order, which gives the largest number of photogenic consecutive pairs. If there are multiple such orders, output any of them.

NoteIn the first test case, there is one photogenic pair: $$$(1, 1)$$$ is photogenic, as $$$\frac{1+1}{2}=1$$$ is integer, while $$$(1, 2)$$$ isn't, as $$$\frac{1+2}{2}=1.5$$$ isn't integer.In the second test case, both pairs are photogenic.

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

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

while( $test_case -- > 0 ){
  my ($n) = map { $_ - 0 } split(/\s+/,<STDIN>);
  my @A = map { $_ - 0 } split(/\s+/,<STDIN>);
  my @od = (); my @ev = ();
  for(my $i=0;$i<$n;$i++){
    if( $A[$i] % 2 == 0 ){
      push(@ev,$A[$i]);
    } else {
      push(@od,$A[$i]);
    }
  }
  my @ot = (@od,@ev);
  print ( join(' ',@ot) . "\n" );
}

exit(0);

#!/usr/bin/perl
my ($n,$m) = map {$_ - 0} split(/\s+/o,<STDIN>);

my @tr = ();
$#tr = $n-1;
my @par = ();
$#par = $n-1;

for(my $i=0;$i<$n;$i++){
  $par[$i] = $i;
}

for(my $i=0;$i<$m;$i++){
  my ($x,$y,$z) = map {$_ - 0} split(/\s+/o,<STDIN>);
  unite($x-1,$y-1);
}

my %dum = ();
for(my $i=0;$i<$n;$i++){
  $dum{&root($i)} = 1;
}
my @d2 = keys %dum;
my $res = 1 + $#d2;
print "$res\n";

exit(0);

###

#!/usr/bin/perl
use Data::Dumper;
my ($n) = map {$_ - 0} split(/\s+/o,<STDIN>);

my $f = &factr($n);

my @facts = keys %$f;

my %f0 = ();

my %oki = ();

while(1){
  my $gosei = 1;
  foreach my $f1 (@facts){
    $gosei *= ( $f1 ** ( $f0{$f1} - 0 ) );
  }
  if( $gosei >= 3 ){
#    print "gosei = $gosei\n";
    my $syo = $n / $gosei;
    if( $syo <= $gosei - 2 ){
      my $g1 = $gosei - 1;
      $oki{$g1} = 1;
    }
  }
  my $cu = 0;
  my $carry = 1;
  while($carry > 0){
    $f0{$facts[$cu]} += 1;
    $carry = 0;
    if( $f0{$facts[$cu]} > $f->{$facts[$cu]} ){
      $f0{$facts[$cu]} = 0;
      $carry = 1;
      $cu++;
    }
    last if( $cu > $#facts );
  }
  last if $cu > $#facts;
}
my $res = 0;
foreach my $o1 (keys %oki){
  $res += ( $o1 - 0);
}
#print &Dumper(\%oki);
print "$res\n";
exit(0);

sub factr {
  my $v = shift;
  my %f = ();
  if( $v<4 ){
    $f{$v}++;
    return \%f;
  }
  for(my $i=1;$i*$i<=$v;$i+=2){
    my $ii = ($i == 1 ? 2 : $i);
    while($v % $ii == 0){
      $f{$ii}++;
      $v /= $ii;
    }
  }
  $f{$v}++ if $v>1;
  return \%f;
}

####  mod_int + nCr nPr set

#!/usr/bin/perl

my $mod = 10 ** 9 + 7;
# my $mod = 998244353;

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

&mk_fact($n+10);

### write here

exit(0);

sub mod_pow {     # ( x ** n ) % mod
  my ($x,$n) = @_;
  my $r = 1;
  while( $n ){
    $r = ( $r * $x ) % $mod if 1 & $n;
    $n >>= 1;
    $x = ( $x * $x ) % $mod;
  }
  return $r;
}

sub mk_fact {     # make {global} n-size variable  fact[]  factinv[]
  my $n_max = shift;
  our @fact    = (1); $#fact = $n_max;
  our @factinv = (1); $#factinv = $n_max;
  for(my $i=1;$i<=$n_max;$i++){
    $fact[$i] = ( $fact[$i-1] * $i ) % $mod;
    $factinv[$i] = &mod_pow($fact[$i],$mod-2);
  }
}

sub nCr {         # calc nCr % mod
  my $n = shift; my $r = shift;
  return (( $fact[$n] * ( ( $factinv[$r] * $factinv[$n-$r] ) % $mod ) ) % $mod);
}

sub nPr {         # calc nPr % mod
  my $n = shift; my $r = shift;
  return (( $fact[$n] * $factinv[$n-$r] ) % $mod );
}

#### union find set

#!/usr/bin/perl

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

#### write here

exit(0);

sub mk_uf {
  my $n = shift;
  our @uf = (); $#uf = $n - 1;
  for(my $i=0;$i<$n;$i++){
    $uf[$i] = $i;
  }
}

sub root {
  my $x = shift;
  while( $uf[$x] != $x ){  $x = $uf[$x] = $uf[$uf[$x]];  }
  return $x;
}

sub unite {
  my $x = &root(scalar(shift)); my $y = &root(scalar(shift));
  $uf[$y] = $x;
}


Permutation p is an ordered set of integers p1,   p2,   ...,   pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,   p2,   ...,   pn.Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.

The single line of the input contains two space-separated positive integers n, k (1 ≤ k < n ≤ 105).

Print n integers forming the permutation. If there are multiple answers, print any of them.

NoteBy |x| we denote the absolute value of number x.


Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.

The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise. Consider the secretaries indexed from 1 to n in some way.

Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.

NoteIn the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.In the second test sample the described situation is impossible as conferences aren't allowed.

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

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

my %calls;

my @data = split(' ', $n);

foreach (@data) {
	if ($_ != 0) {
		$calls{$_}++;
	}
}

my $total = 0;

foreach (values %calls) {
	if ($_ > 2) {
		print "-1\n";
		exit(0);
	} if ($_ == 2) {
		$total++;
	}
}

print "$total\n";

#!/usr/bin/perl
use strict;
my $samount = <STDIN>;
my $sessions = <STDIN>;
my @sessions = split( ' ', $sessions );
my $pairs = 0;
my $impossible = 0;
my %temp;
foreach ( @sessions )
{
	if ( $_ != 0 ) {
	    if ( $temp{ $_ } ) { $temp{ $_ } = $temp{ $_ } + 1 } else { $temp{ $_ } = 1 };
	    if ( $temp{ $_ } > 2 ) { $impossible = 1; }
	    elsif ( $temp{ $_ } == 2 ) { $pairs++; }
	}
}
print ($impossible ? '-1' : $pairs)."\n";