DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b denotes taking a remainder after division a by b.However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1.

The first line contains two integers, p and n (2 ≤ p, n ≤ 300). Then n lines follow. The i-th of them contains an integer xi (0 ≤ xi ≤ 109).

Output a single integer — the answer to the problem.

# get first line as a string
my $f = <STDIN>;
chomp ( $f );

my $p, $n;
($p, $n) = split m/ /, $f;

my %h;
my $collison = 0;

for ( my $i =0 ; $i < $n; $i += 1 ) {
    $f = <STDIN>;
    chomp ( $f );
    if ( exists $h{ $f % $p } ) {
	print (($i + 1) . "\n");		# print answer
	$i = $n; 		# exit the loop
	$collision = 1;
    }
    $h{ $f % $p } = 1;
}

if ( not $collision ) {
    print "-1\n"; }

# get first line as a string
my $f = <STDIN>;
chomp ( $f );

my $p, $n;
($p, $n) = split m/ /, $f;

my %h;
my $colliison = 0;

for ( my $i =0 ; $i < $n; $i += 1 ) {
    $f = <STDIN>;
    chomp ( $f );
    if ( exists $h{ $f % $p } ) {
	print (($i + 1) . "\n");		# print answer
	$i = $n; 		# exit the loop
	$collision = 1;
    }
    $h{ $f % $p } = 1;
}

if ( not $collision ) {
    print "-1\n"; }

use strict ;
use warnings ;

my @array = split(/ /,<STDIN>) ;

my $p = $array[0] ;
my $n = $array[1] ;

my @x ;

for(my $j = 0 ; $j < $n ; $j++){
	$x[$j] = <STDIN> ;
}

my %hash ;

for(my $i = 0 ; $i < $n ; $i++ ) {
	my $value = $x[$i] ;
	my $remainder = $value % $p ;

	if(exists $hash{$remainder}){
		print $i + 1 ;
		exit ;
	}else{
		$hash{$remainder} = 1 ;
	}
}

print -1 ;

chomp ($line = <>);
($p, $n) = split ' ', $line;
for(1..$n)
{
    chomp($x = <>);
    print "$_\n" and exit if $seen{$x % $p};
    $seen{$x % $p} = 1;
}
print "-1\n";

#!/usr/bin/perl

my $inp = <STDIN>;
my @ar = split(' ', $inp);

my $i;
my $h;
my $f = 0;
my $f_ans = -1;

for ($i = 1; $i <= $ar[1]; $i += 1) {
  my $tmp = <STDIN>;
  my $ans = $tmp % $ar[0];
  if ($h{$ans} == 2) {
    if ($f == 0) {
        $f = 1;
        $f_ans = $i;
    }
  } else {
    $h{$ans} = 2;
  }
}

print $f_ans;

# get first line as a string
my $f = <STDIN>;
chomp ( $f );

my $p, $n;
($p, $n) = split m/ /, $f;

print "two\n";

my %h;
my $colliison = 0;

for ( my $i =0 ; $i < $n; $i += 1 ) {
    $f = <STDIN>;
    chomp ( $f );
    if ( exists $h{ $f } ) {
	print "$i\n";		# print answer
	$i = $n; 		# exit the loop
	$collision = 1;
    }
    $h{ $f } = 1;
}

if ( not $collision ) {
    print "-1\n"; }

# get first line as a string
my $f = <STDIN>;
chomp ( $f );

my $p, $n;
($p, $n) = split m/ /, $f;

my %h;
my $colliison = 0;

for ( my $i =0 ; $i < $n; $i += 1 ) {
    $f = <STDIN>;
    chomp ( $f );
    if ( exists $h{ $f } ) {
	print "$i\n";		# print answer
	$i = $n; 		# exit the loop
	$collision = 1;
    }
    $h{ $f } = 1;
}

if ( not $collision ) {
    print "-1\n"; }

#!/usr/bin/perl

my $inp = <STDIN>;
my @ar = split(' ', $inp);

my $i;
my $h;
my $f = 0;
my $f_ans = -1;

for ($i = 1; $i <= $ar[1]; $i += 1) {
  my $tmp = <STDIN>;
  my $ans = $tmp % $ar[0];
  if ($h{$ans} == 2) {
    $f = 1;
    my $f_ans = $i;
  } else {
    $h{$ans} = 2;
  }
}

print $f_ans;

#!/usr/bin/perl

my $inp = <STDIN>;
my @ar = split(' ', $inp);

my $i;
my $h;
my $f = 0;
my $f_ans = -1;

for ($i = 1; $i <= $ar[1]; $i += 1) {
  my $tmp = <>;
  my $ans = $tmp % $ar[0];
  if ($h{$ans} == 2) {
    $f = 1;
    my $f_ans = $i;
  } else {
    $h{$ans} = 2;
  }
}

print $f_ans;


Two integer sequences existed initially — one of them was strictly increasing, and the other one — strictly decreasing.Strictly increasing sequence is a sequence of integers $$$[x_1 < x_2 < \dots < x_k]$$$. And strictly decreasing sequence is a sequence of integers $$$[y_1 > y_2 > \dots > y_l]$$$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.They were merged into one sequence $$$a$$$. After that sequence $$$a$$$ got shuffled. For example, some of the possible resulting sequences $$$a$$$ for an increasing sequence $$$[1, 3, 4]$$$ and a decreasing sequence $$$[10, 4, 2]$$$ are sequences $$$[1, 2, 3, 4, 4, 10]$$$ or $$$[4, 2, 1, 10, 4, 3]$$$.This shuffled sequence $$$a$$$ is given in the input.Your task is to find any two suitable initial sequences. One of them should be strictly increasing and the other one — strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ to increasing and decreasing sequences, print "NO".

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

If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ to increasing and decreasing sequences, print "NO" in the first line. Otherwise print "YES" in the first line and any two suitable sequences. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing. In the second line print $$$n_i$$$ — the number of elements in the strictly increasing sequence. $$$n_i$$$ can be zero, in this case the increasing sequence is empty. In the third line print $$$n_i$$$ integers $$$inc_1, inc_2, \dots, inc_{n_i}$$$ in the increasing order of its values ($$$inc_1 < inc_2 < \dots < inc_{n_i}$$$) — the strictly increasing sequence itself. You can keep this line empty if $$$n_i = 0$$$ (or just print the empty line). In the fourth line print $$$n_d$$$ — the number of elements in the strictly decreasing sequence. $$$n_d$$$ can be zero, in this case the decreasing sequence is empty. In the fifth line print $$$n_d$$$ integers $$$dec_1, dec_2, \dots, dec_{n_d}$$$ in the decreasing order of its values ($$$dec_1 > dec_2 > \dots > dec_{n_d}$$$) — the strictly decreasing sequence itself. You can keep this line empty if $$$n_d = 0$$$ (or just print the empty line). $$$n_i + n_d$$$ should be equal to $$$n$$$ and the union of printed sequences should be a permutation of the given sequence (in case of "YES" answer).

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my %h;

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

	if( grep $_ > 2, values %h ){
		print "NO";
		next;
		}

	print "YES";
	print 0 + keys %h;
	print join ' ', sort { $a <=> $b } keys %h;
	print 0 + grep { $h{ $_ } == 2 } keys %h;
	print join ' ', sort { $b <=> $a } grep { $h{ $_ } == 2 } keys %h;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my %h;

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

	if( grep $_ > 2, values %h ){
		print "NO";
		next;
		}

	print "YES";
	print 0 + keys %h;
	print join ' ', sort { $a <=> $b } keys %h;
	print 0 + grep { $h{ $_ } == 2 } keys %h;
	print join ' ', sort { $a <=> $b } grep { $h{ $_ } == 2 } keys %h;
	}


Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a1, a2, ..., ak.Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another n - k cities, and, of course, flour delivery should be paid — for every kilometer of path between storage and bakery Masha should pay 1 ruble.Formally, Masha will pay x roubles, if she will open the bakery in some city b (ai ≠ b for every 1 ≤ i ≤ k) and choose a storage in some city s (s = aj for some 1 ≤ j ≤ k) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 105, 0 ≤ k ≤ n) — the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then m lines follow. Each of them contains three integers u, v and l (1 ≤ u, v ≤ n, 1 ≤ l ≤ 109, u ≠ v) meaning that there is a road between cities u and v of length of l kilometers . If k > 0, then the last line of the input contains k distinct integers a1, a2, ..., ak (1 ≤ ai ≤ n) — the number of cities having flour storage located in. If k = 0 then this line is not presented in the input.

Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the n cities, print  - 1 in the only line.

NoteImage illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened.


A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.

The first input line contains two integers n and k (1 ≤ n ≤ 5·105; 2 ≤ k ≤ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.

Print a single integer — the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.


Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others — a group of b-s), but cccc is not since in each possible consequent partition letters in these two groups coincide.You're given a string s. Check whether it can be split into two non-empty subsequences such that the strings formed by these subsequences are adorable. Here a subsequence is an arbitrary set of indexes of the string.

The only line contains s (1 ≤ |s| ≤ 105) consisting of lowercase latin letters.

Print «Yes» if the string can be split according to the criteria above or «No» otherwise. Each letter can be printed in arbitrary case.

NoteIn sample case two zzcxx can be split into subsequences zc and zxx each of which is adorable.There's no suitable partition in sample case three.

#!/usr/bin/perl
use 5.010;

$s = <STDIN>;
chomp($s);

my %mp;

foreach $c ( split //, $s )
{
	$char = "".$c;

	#print $char."\n";
	if( exists $mp{$char} ){
		my $val = $mp{$char};
		$mp{$char} = $val + 1;
	}
	else{
		$mp{$char}= 1;

	}

}

my $count = keys %mp;
my @v = values %mp;
my $cnt = 0;
for $val (@v){
			if($val>1){
				$cnt++;
			}
}
#print $count;

if( $count == 2 ){
		say( ($cnt==2) ? "Yes" : "No" );
}
elsif( $count == 3 ) {
		say( ($cnt>=1) ? "Yes" : "No" );
}
elsif ( $count ==4 ) {
	say("Yes");
}
else{
	say ("No");
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	chomp;

	my %h;

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

	my @values = values %h;

	print do {
		if( 4 < keys %h ){
			'No';
			}
		elsif( 4 == keys %h ){
			'Yes';
			}
		elsif( 3 == keys %h ){
			( 3 < length ) ? 'Yes' : 'No';
			}
		elsif( 2 == keys %h ){
			do {
				if( $values[ 0 ] > 1 and $values[ 1 ] > 1 ){
					'Yes';
					}
				else{
					'No';
					}
				};
			}
		else{
			'No';
			}
		};
	}

#!/usr/bin/perl
use 5.010;

$s = <STDIN>;
chomp($s);

my %mp;

foreach $c ( split //, $s )
{
	$char = "".$c;

	#print $char."\n";
	if( exists $mp{$char} ){
		my $val = $mp{$char};
		$mp{$char} = $val + 1;
	}
	else{
		$mp{$char}= 1;

	}

}

my $count = keys %mp;
my @v = values %mp;
my $cnt = 0;
for $val (@v){
			if($val>1){
				$cnt++;
			}
}
print $count;

if( $count == 2 ){
		say( ($cnt==2) ? "Yes" : "No" );
}
elsif( $count == 3 ) {
		say( ($cnt>=1) ? "Yes" : "No" );
}
elsif ( $count ==4 ) {
	say("Yes");
}
else{
	say ("No");
}

#!/usr/bin/perl
use 5.010;

$s = <STDIN>;
chomp($s);

foreach $char ( split //, $s )
{
	$char = "".$char;
	if( exists $mp{$char} ){
		$mp[$char] = $mp[$char]+1;
	}
	else{
		$mp[$char] = 1;
	}
}

my $count = keys %mp;
my @v = values %mp;
my $cnt = 0;
for $val (@v){
			if($val>1){
				$cnt++;
			}
}

if( $count == 2 ){
		say( ($cnt==2) ? "Yes" : "No" );
}
elsif( $count == 3 ) {
		say( ($cnt>=1) ? "Yes" : "No" );
}
elsif ( $count ==4 ) {
	say("Yes");
}
else{
	say ("No");
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){

	}


Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.

The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000). The following line contains a binary string of length n representing Kevin's results on the USAICO.

Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.

NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score.

#use Time::HiRes qw(gettimeofday tv_interval);
#$t=[gettimeofday];

$fh=\*STDIN;
# open($fh,"<","t\\l")||die;

$n=<$fh>;
$s=<$fh>; chomp $s;

$inspect = 1;
$eq_len = 1;

sub z {
	if ($inspect = 1 && $eq_len > 1) {
    	$eq_count++;
    	if ($eq_len == 2 && $eq_count == 1) {
    		$add = 1;
    	}
    	elsif ($eq_len > 2 || $eq_count > 1) {
    		$add = 2;
    		$inspect = 0;
    	}
    	$eq_len = 1;
	}
}

for ($i=0; $i<length($s); $i++) {
	$ch = substr($s, $i, 1);
	# print "ch=$ch\n";
  	if ($prev ne $ch)  {
  		$prev = $ch;
  		$count++;
  		z();
  	} else {
  		$eq_len++;
  	}
}
z();

$count+=$add;
print $count;

# print tv_interval($t),"\n";

$inspect = 1;
$eq_len = 1;

sub z {
	if ($inspect = 1 && $eq_len > 0) {
    	$eq_count++;
    	if ($eq_len == 2 && $eq_count == 1) {
    		$add = 1;
    	}
    	elsif ($eq_len > 2 || $eq_count > 1) {
    		$add = 2;
    		$inspect = 0;
    	}
    	$eq_len = 1;
	}
}

$skip = 1;
while (($n = sysread(STDIN, $s, 1000)) > 0) {
	for ($i=0; $i<length($s); $i++) {
		$ch = substr($s, $i, 1);
		# print "ch=$ch\n";
		if ($skip == 1) {
			if ($ch eq chr(10)) {
				$skip = 0;
			}
		} else {
    		if ($prev ne $ch)  {
    			$prev = $ch;
    			$count++;
    			z();
    		} else {
    			$eq_len++;
    		}
		}
	}
}
z();

# print "count=$count\n";
# print "add=$add\n";
$count+=$add;
print $count;

#use Time::HiRes qw(gettimeofday tv_interval);
#$t=[gettimeofday];

$fh=\*STDIN;
# open($fh,"<","t\\l")||die;

$n=<$fh>;
$s=<$fh>; chomp $s;

$inspect = 1;
$eq_len = 1;

sub z {
	if ($inspect = 1 && $eq_len > 0) {
    	$eq_count++;
    	if ($eq_len == 2 && $eq_count == 1) {
    		$add = 1;
    	}
    	elsif ($eq_len > 2 || $eq_count > 1) {
    		$add = 2;
    		$inspect = 0;
    	}
    	$eq_len = 1;
	}
}

for ($i=0; $i<length($s); $i++) {
	$ch = substr($s, $i, 1);
	# print "ch=$ch\n";
  	if ($prev ne $ch)  {
  		$prev = $ch;
  		$count++;
  		z();
  	} else {
  		$eq_len++;
  	}
}
z();

$count+=$add;
print $count;

# print tv_interval($t),"\n";


Основой любой социальной сети является отношение дружбы между двумя пользователями в том или ином смысле. В одной известной социальной сети дружба симметрична, то есть если a является другом b, то b также является другом a. В этой же сети есть функция, которая демонстрирует множество людей, имеющих высокую вероятность быть знакомыми для пользователя. Эта функция работает следующим образом. Зафиксируем пользователя x. Пусть некоторый другой человек y, не являющийся другом x на текущий момент, является другом не менее, чем для k% друзей x. Тогда он является предполагаемым другом для x.У каждого человека в социальной сети есть свой уникальный идентификатор — это целое число от 1 до 109. Вам дан список пар пользователей, являющихся друзьями. Определите для каждого упомянутого пользователя множество его предполагаемых друзей.

В первой строке следуют два целых числа m и k (1 ≤ m ≤ 100, 0 ≤ k ≤ 100) — количество пар друзей и необходимый процент общих друзей для того, чтобы считаться предполагаемым другом. В последующих m строках записано по два числа ai, bi (1 ≤ ai, bi ≤ 109, ai ≠ bi), обозначающих идентификаторы пользователей, являющихся друзьями.  Гарантируется, что каждая пара людей фигурирует в списке не более одного раза.

Для всех упомянутых людей в порядке возрастания id выведите информацию о предполагаемых друзьях. Информация должна иметь вид "id:  k id1 id2 ... idk", где id — это id самого человека, k — количество его предполагаемых друзей, а id1, id2, ..., idk — идентификаторы его предполагаемых друзей в возрастающем порядке.

use strict;
use warnings;
use Data::Dumper;

our %users;
sub Friends($)
{
    return keys %{$users{$_[0]}};
}
my ($m, $k) = split /\s/, <>;

for(1..$m)
{
    my ($unit, $friend) =split /\s/, <>;
    chomp($unit);
    chomp($friend);
    $users{$unit}->{$friend} = 1;
    $users{$friend}->{$unit} = 1;
}

for my $curUnit (sort {$a<=>$b} keys %users)  #для каждого чувака
{
    my @curFriends = Friends($curUnit);  #для всех друзей чувака
    my %checker;
    for (keys %users)
    {
        $checker{$_} = 0;
    }

    for(@curFriends)
    {
        for(Friends($_))
        {
            $checker{$_}++;         #увеличиваем на 1 крутость того, кого нашли в друзьях друзей
        }
    }
    my @ans;
    for (@curFriends)
    {
        delete $checker{$_}; #удаляем уже_друзей - их не нужно в ответ

    }
    delete $checker{$curUnit}; #удаляем себя;

    for(sort {$a<=>$b} keys %checker)
    {
        if ($checker{$_} >= ($#curFriends+1) * $k / 100 )
        {
            push @ans, $_;   #заносим в ответ тех, кто достаточно крут
        }
    }
    printf "%i: %i ",$curUnit, $#ans+1;
    print "@ans";
    print "\n";
}


You are playing a computer game. To pass the current level, you have to kill a big horde of monsters. In this horde, there are $$$n$$$ monsters standing in the row, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th monster has $$$a_i$$$ health and a special "Death's Blessing" spell of strength $$$b_i$$$ attached to it.You are going to kill all of them one by one. It takes exactly $$$h$$$ seconds to kill a monster with health $$$h$$$.When the $$$i$$$-th monster dies, it casts its spell that increases the health of its neighbors by $$$b_i$$$ (the neighbors of the $$$j$$$-th monster in the row are the monsters on places $$$j - 1$$$ and $$$j + 1$$$. The first and the last monsters have only one neighbor each).After each monster is killed, the row shrinks, so its former neighbors become adjacent to each other (so if one of them dies, the other one is affected by its spell). For example, imagine a situation with $$$4$$$ monsters with health $$$a = [2, 6, 7, 3]$$$ and spells $$$b = [3, 6, 0, 5]$$$. One of the ways to get rid of the monsters is shown below:  $$$2$$$$$$6$$$$$$7$$$$$$3$$$$$$\xrightarrow{6\ s}$$$$$$8$$$$$$13$$$$$$3$$$$$$\xrightarrow{13\ s}$$$$$$8$$$$$$3$$$$$$\xrightarrow{8\ s}$$$$$$6$$$$$$\xrightarrow{6\ s}$$$$$$\{\}$$$$$$3$$$$$$6$$$$$$0$$$$$$5$$$$$$3$$$$$$0$$$$$$5$$$$$$3$$$$$$5$$$$$$5$$$ The first row represents the health of each monster, the second one — the power of the spells. As a result, we can kill all monsters in $$$6 + 13 + 8 + 6$$$ $$$=$$$ $$$33$$$ seconds. Note that it's only an example and may not be the fastest way to get rid of the monsters.What is the minimum time required to kill all monsters in the row?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of monsters in the row. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial health of corresponding monsters. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i \le 10^9$$$), where $$$b_i$$$ is the strength of the spell for the $$$i$$$-th monster. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the minimum possible total time to kill all monsters.

NoteIn the first test case, there is only one monster that will be killed in $$$10$$$ seconds.In the second test case, it's optimal to kill the first monster, the last monster and then the middle one. It will take $$$100 + 100 + (1 + 1 + 1)$$$ $$$=$$$ $$$203$$$ seconds.In the third test case, it's optimal to kill the first monster, then the third one, then the fourth one and finally the second one. It will take $$$2 + 7 + (3 + 0) + (3 + 6 + 5)$$$ $$$=$$$ $$$26$$$ seconds.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my $time = 0;

	$time += $_ for @A;

	while( @B > 1 ){
		if( $B[ 0 ] < $B[ @B - 1 ] ){
			$time += $B[ 0 ];
			shift @B;
			}
		else{
			$time += $B[ @B - 1 ];
			pop @B;
			}
		}
	print $time;
	}


Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.Now Petya wants to know for each friend i the number of a friend who has given him a gift.

The first line contains one integer n (1 ≤ n ≤ 100) — the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi — the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.

Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.

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

chomp($n=<>);
@ans = (0) x ($n+1);
$i = 1;
$ans[$_]=$i++ foreach(split / /, <>);
1+shift @ans and say join ' ', @ans;

#!/usr/bin/perl -w

use strict;

my %donor = ();
my $n = <>;
my @a = split ' ', <>;
$donor{$a[$_ - 1]} = $_ for 1..$n;
print join ' ', map { $donor{$_} } sort { $a <=> $b } keys %donor;
print "\n";

<STDIN>;
chomp($s = <STDIN>);
@arr = split(/ /, $s);

for($i = 0; $i <= $#arr; ++$i) {
    $result[$arr[$i] - 1] = $i + 1;
}
print "@result";

<stdin>; chomp($_=<stdin>);my @arr=split(" "); my $i = 0; my %hash = map {++$i => $_} @arr; %hash = reverse %hash; print "$hash{$_} " for (1..@arr-1); print "$hash{@arr}\n"

#!/usr/bin/env perl

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

# essential
my @tokens = ();

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

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

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

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

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

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

# solve

my $n = read_token;
my @numbers = split q{ }, read_line;

my @answer = ();

for (1..$n) {
    my $i = shift @numbers;
    $answer[$i] = $_;
}

shift @answer;

say "@answer";

my $num = <>;
chomp $num;
my $index = <>;
chomp $index;
my @index = split / /, $index;
my @new;
for $n(1..$num) {
    my $count=1;
    $count++ while ($n != $index[$count-1]);
    push @new, $count;
}
print join " ", @new;

#!/usr/bin/perl -w

use strict;

my %donor = ();
my $n = <>;
my @a = split ' ', <>;
$donor{$a[$_ - 1]} = $_ for 1..$n;
print join ' ', map { $donor{$_} } sort keys %donor;
print "\n";

<STDIN>;
chomp($s = <STDIN>);
@arr = split(/ /, $s);

for($i = 0; $i <= $#arr; ++$i) {
    $result[$arr[$i] - 1] = $i + 1;
}
print @result;


You are given two segments $$$[l_1; r_1]$$$ and $$$[l_2; r_2]$$$ on the $$$x$$$-axis. It is guaranteed that $$$l_1 < r_1$$$ and $$$l_2 < r_2$$$. Segments may intersect, overlap or even coincide with each other.    The example of two segments on the $$$x$$$-axis. Your problem is to find two integers $$$a$$$ and $$$b$$$ such that $$$l_1 \le a \le r_1$$$, $$$l_2 \le b \le r_2$$$ and $$$a \ne b$$$. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment $$$[l_1; r_1]$$$ and the second one belongs to the segment $$$[l_2; r_2]$$$.It is guaranteed that the answer exists. If there are multiple answers, you can print any of them.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Each of the next $$$q$$$ lines contains four integers $$$l_{1_i}, r_{1_i}, l_{2_i}$$$ and $$$r_{2_i}$$$ ($$$1 \le l_{1_i}, r_{1_i}, l_{2_i}, r_{2_i} \le 10^9, l_{1_i} < r_{1_i}, l_{2_i} < r_{2_i}$$$) — the ends of the segments in the $$$i$$$-th query.

Print $$$2q$$$ integers. For the $$$i$$$-th query print two integers $$$a_i$$$ and $$$b_i$$$ — such numbers that $$$l_{1_i} \le a_i \le r_{1_i}$$$, $$$l_{2_i} \le b_i \le r_{2_i}$$$ and $$$a_i \ne b_i$$$. Queries are numbered in order of the input. It is guaranteed that the answer exists. If there are multiple answers, you can print any.


A permutation — is a sequence of length $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all the numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ — permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ — no.Polycarp was recently gifted a permutation $$$a[1 \dots n]$$$ of length $$$n$$$. Polycarp likes trees more than permutations, so he wants to transform permutation $$$a$$$ into a rooted binary tree. He transforms an array of different integers into a tree as follows:   the maximum element of the array becomes the root of the tree;  all elements to the left of the maximum — form a left subtree (which is built according to the same rules but applied to the left part of the array), but if there are no elements to the left of the maximum, then the root has no left child;  all elements to the right of the maximum — form a right subtree (which is built according to the same rules but applied to the right side of the array), but if there are no elements to the right of the maximum, then the root has no right child. For example, if he builds a tree by permutation $$$a=[3, 5, 2, 1, 4]$$$, then the root will be the element $$$a_2=5$$$, and the left subtree will be the tree that will be built for the subarray $$$a[1 \dots 1] = [3]$$$, and the right one — for the subarray $$$a[3 \dots 5] = [2, 1, 4]$$$. As a result, the following tree will be built:     The tree corresponding to the permutation $$$a=[3, 5, 2, 1, 4]$$$. Another example: let the permutation be $$$a=[1, 3, 2, 7, 5, 6, 4]$$$. In this case, the tree looks like this:     The tree corresponding to the permutation $$$a=[1, 3, 2, 7, 5, 6, 4]$$$. Let us denote by $$$d_v$$$ the depth of the vertex $$$a_v$$$, that is, the number of edges on the path from the root to the vertex numbered $$$a_v$$$. Note that the root depth is zero. Given the permutation $$$a$$$, for each vertex, find the value of $$$d_v$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the permutation. This is followed by $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$ — permutation $$$a$$$.

For each test case, output $$$n$$$ values — $$$d_1, d_2, \ldots, d_n$$$.

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	my @A = split ' ', <>;

	$_ = join " ", @A;

	$debug and print;

	my @branches = $_;

	my $depth = -1;

	my %depth;

	while( @A > keys %depth ){
		$depth ++;
		$debug and print "depth:[$depth]", join ',', @branches;
		my @new_branches;

		for( @branches ){
			@_ = grep length, split;
			if( @_ < 1 ){
				push @new_branches, $_;
				next;
				}
			my $max = ( sort { $b <=> $a } @_ )[ 0 ];
			$depth{ $max } = $depth;
			push @new_branches, grep length, split m/ ?\b$max\b ?/;
			}
		@branches = grep length, @new_branches;
		}

	print join ' ', map { $depth{ $_ } } @A;
	}


In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.

The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).

Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.

NoteIn the first example the ranks will be raised in the following manner:1 2 2 3  →  2 2 3 4  →  2 3 4 4  →  3 4 4 4  →  4 4 4 4Thus totals to 4 training sessions that require 4 golden coins.


Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner: where  is equal to 1 if some ai = 1, otherwise it is equal to 0.Nam has a matrix A consisting of m rows and n columns. The rows are numbered from 1 to m, columns are numbered from 1 to n. Element at row i (1 ≤ i ≤ m) and column j (1 ≤ j ≤ n) is denoted as Aij. All elements of A are either 0 or 1. From matrix A, Nam creates another matrix B of the same size using formula:.(Bij is OR of all elements in row i and column j of matrix A)Nam gives you matrix B and challenges you to guess matrix A. Although Nam is smart, he could probably make a mistake while calculating matrix B, since size of A can be large.

The first line contains two integer m and n (1 ≤ m, n ≤ 100), number of rows and number of columns of matrices respectively. The next m lines each contain n integers separated by spaces describing rows of matrix B (each element of B is either 0 or 1).

In the first line, print "NO" if Nam has made a mistake when calculating B, otherwise print "YES". If the first line is "YES", then also print m rows consisting of n integers representing matrix A that can produce given matrix B. If there are several solutions print any one.


While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.

The first line contains string a, and the second line — string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.

If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.

NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(!eof){
	my( $A, $B ) = map { chomp; $_ } ~~<>, ~~<>;

	print do {
	if( length $A == length $B ){
		if( $A eq $B){
			-1
			}
		else{ length $A }
		}
	else{
		length $A > length $B ? length $A : length $B
		}
	}

	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(!eof){
	my( $A, $B ) = map { chomp; $_ } ~~<>, ~~<>;

	print do {
	if( length $A == length $B ){
		if( $A eq $B){
			-1
			}
		else{ $A }
		}
	else{
		length $A > length $B ? $A : $B
		}
	}

	}


Ashish has a binary string $$$s$$$ of length $$$n$$$ that he wants to sort in non-decreasing order.He can perform the following operation:   Choose a subsequence of any length such that its elements are in non-increasing order. Formally, choose any $$$k$$$ such that $$$1 \leq k \leq n$$$ and any sequence of $$$k$$$ indices $$$1 \le i_1 \lt i_2 \lt \ldots \lt i_k \le n$$$ such that $$$s_{i_1} \ge s_{i_2} \ge \ldots \ge s_{i_k}$$$.  Reverse this subsequence in-place. Formally, swap $$$s_{i_1}$$$ with $$$s_{i_k}$$$, swap $$$s_{i_2}$$$ with $$$s_{i_{k-1}}$$$, $$$\ldots$$$ and swap $$$s_{i_{\lfloor k/2 \rfloor}}$$$ with $$$s_{i_{\lceil k/2 \rceil + 1}}$$$ (Here $$$\lfloor x \rfloor$$$ denotes the largest integer not exceeding $$$x$$$, and $$$\lceil x \rceil$$$ denotes the smallest integer not less than $$$x$$$) Find the minimum number of operations required to sort the string in non-decreasing order. It can be proven that it is always possible to sort the given binary string in at most $$$n$$$ operations.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 1000)$$$  — the length of the binary string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ containing only $$$0$$$s and $$$1$$$s. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case output the following:   The minimum number of operations $$$m$$$ in the first line ($$$0 \le m \le n$$$).  Each of the following $$$m$$$ lines should be of the form: $$$k$$$ $$$i_1$$$ $$$i_2$$$ ... $$$i_{k}$$$, where $$$k$$$ is the length and $$$i_1 \lt i_2 \lt ... \lt i_{k}$$$ are the indices of the chosen subsequence. For them the conditions from the statement must hold.

NoteIn the first test case, the binary string is already sorted in non-decreasing order.In the second test case, we can perform the following operation:   $$$k = 4:$$$ choose the indices $$$\{1, 3, 4, 5\}$$$$$$\underline{1}$$$ $$$0$$$ $$$\underline{1}$$$ $$$\underline{0}$$$ $$$\underline{0}$$$ $$$\rightarrow $$$ $$$\underline{0}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{1}$$$ $$$\underline{1}$$$ In the third test case, we can perform the following operation:  $$$k = 3:$$$ choose the indices $$$\{3, 5, 6\}$$$$$$0$$$ $$$0$$$ $$$\underline{1}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{0}$$$ $$$\rightarrow $$$ $$$0$$$ $$$0$$$ $$$\underline{0}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{1}$$$


There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.

The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct.

Print two integer numbers — the minimal distance and the quantity of pairs with this distance.

NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance.

<>; $_ = <>;
sub order { sort {$a <=> $b} @_ };
for $a (order split) {
	push @d, $a - $p if defined $p;
	$p = $a;
}
@d = order @d;
$c++ while $d[0] == $d[$c];
print "$d[0] $c";


The Rebel fleet is on the run. It consists of m ships currently gathered around a single planet. Just a few seconds ago, the vastly more powerful Empire fleet has appeared in the same solar system, and the Rebels will need to escape into hyperspace. In order to spread the fleet, the captain of each ship has independently come up with the coordinate to which that ship will jump. In the obsolete navigation system used by the Rebels, this coordinate is given as the value of an arithmetic expression of the form .To plan the future of the resistance movement, Princess Heidi needs to know, for each ship, how many ships are going to end up at the same coordinate after the jump. You are her only hope!

The first line of the input contains a single integer m (1 ≤ m ≤ 200 000) – the number of ships. The next m lines describe one jump coordinate each, given as an arithmetic expression. An expression has the form (a+b)/c. Namely, it consists of: an opening parenthesis (, a positive integer a of up to two decimal digits, a plus sign +, a positive integer b of up to two decimal digits, a closing parenthesis ), a slash /, and a positive integer c of up to two decimal digits.

Print a single line consisting of m space-separated integers. The i-th integer should be equal to the number of ships whose coordinate is equal to that of the i-th ship (including the i-th ship itself).

NoteIn the sample testcase, the second and the third ship will both end up at the coordinate 3.Note that this problem has only two versions – easy and hard.


Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

#!/usr/bin/perl

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

my $line = <>;
chomp($line);
my @points = split(/\s/, $line);

$line = <>;
chomp($line);
my @prize = split(/\s/, $line);
my $min_prize = $prize[0];

my $point = 0;

my @ans = (0,0,0,0,0);
for (@points) {
    $point += $_;
    if ($point >= $min_prize) {
        get_prize();
    }
}

print join(" ", @ans), "\n";
print $point;

sub get_prize {
    for (my $i=4; $i>=0; $i--) {
        if ($point >= $prize[$i]) {
            my $tmp = int($point / $prize[$i]);
            $ans[$i] += $tmp;
            $point -= $prize[$i] * $tmp;
        }
    }
}


A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.

The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di < di + 1.

If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).

NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.

use integer;
$\ = $/;
while(<>){
($n, $m) = split;
undef $d1;
undef $h1;
$f = 0;
$max = 0;
for $i (1 .. $m){
($d2, $h2) = split " ", <>;
!defined $d1 ? do {$top = $h2 + $d2 - 1} : do {
$higher = ($h2 > $h1 ? $h2 : $h1);
$diff = ($d2 - $d1) - abs($h1 - $h2);
$diff < 0 and $f++;
$top = $higher + $diff / 2;
$higher > $max and $max = $higher;
};
$top > $max and $max = $top;
($d1, $h1) = ($d2, $h2);
}
$top = $h1 + ($n - $d1);
$top > $max and $max = $top;
print $f ? "IMPOSSIBLE" : $max;
}


Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.Let's call a positive number special if it can be written as a sum of different non-negative powers of $$$n$$$. For example, for $$$n = 4$$$ number $$$17$$$ is special, because it can be written as $$$4^0 + 4^2 = 1 + 16 = 17$$$, but $$$9$$$ is not.Theofanis asks you to help him find the $$$k$$$-th special number if they are sorted in increasing order. Since this number may be too large, output it modulo $$$10^9+7$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$).

For each test case, print one integer — the $$$k$$$-th special number in increasing order modulo $$$10^9+7$$$.

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

my $MOD = 1_000_000_000 + 7;

<>;

while(<>){
	$debug and print '-' x 15 ;
	my( $n, $k ) = split;

	$_ = reverse sprintf "%b", $k;

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

	my $result = 1;
	my $mult = 1;

	while( m/./g ){
		$& and $result += $mult;

		$result %= $MOD;

		$mult *= $n;

		$mult %= $MOD;
		}

	print $result % $MOD - 1;
	}

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

my $MOD = 1_000_000_000 + 7;

<>;

while(<>){
	$debug and print '-' x 15 ;
	my( $n, $k ) = split;

	$_ = reverse sprintf "%b", $k;

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

	my $result = 1;
	my $mult = 1;

	while( m/./g ){
		$& and $result += $mult;

		$result %= $MOD;

		$mult *= $n;
		}

	print $result % $MOD - 1;
	}

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

my $MOD = 1_000_000_000 + 7;

<>;

while(<>){
	$debug and print '-' x 15 ;
	my( $n, $k ) = split;

	$_ = reverse sprintf "%b", $k;

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

	my $result = 1;
	my $mult = 1;

	while( m/./g ){
		$& and $result += $mult;

		$result %= $MOD;

		$mult *= $n;
		}

	print +( $result - 1 ) % $MOD;
	}

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

my $MOD = 1_000_000_000 + 7;

<>;

while(<>){
	$debug and print '-' x 15 ;
	my( $n, $k ) = split;

	$_ = reverse sprintf "%b", $k;

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

	my $result = 1;
	my $mult = 1;

	while( m/./g ){
		$& and $result += $mult;

		$mult *= $n;
		}

	print +( $result - 1 ) % $MOD;
	}

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

my $MOD = 1_000_000_000 + 7;

<>;

while(<>){
	$debug and print '-' x 15 ;
	my( $n, $k ) = split;

	$_ = reverse sprintf "%b", $k;

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

	my $result = 1;
	my $mult = 1;

	while( m/./g ){
		$& and $result += $mult;

		$mult *= $n;
		}

	print $result % $MOD - 1;
	}


In Aramic language words can only represent objects.Words in Aramic have special properties:   A word is a root if it does not contain the same letter more than once.  A root and all its permutations represent the same object.  The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".  Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.

Output one integer — the number of different objects mentioned in the given ancient Aramic script.

NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".

use strict;
use warnings;
use diagnostics;

my $numOfWords = <STDIN>;
my $line = <STDIN>;
chomp $line;

my @words = split(/ /,$line);
my %objects;

foreach my $word (@words) {
	my @orgins = split(//,$word);
	my $object = get_orgin(@orgins);
	if (not exists ($objects{$object})) {
		$objects{$object} = 1;
	}
}

my @hash_keys = keys %objects;
print scalar (@hash_keys)."\n";

sub get_orgin {
	my %used;
	my @orgins = @_;
	foreach my $orgin (@orgins) {
		if (not exists($used{$orgin})) {
			$used{$orgin} = 1;
		}
	}
	return join ("", (sort (keys %used)));
}


Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.

The first line of the input contains two integers a and b ( - 100 ≤ a, b ≤ 100) — coordinates of Vasiliy's home. The second line contains a single integer n (1 ≤ n ≤ 1000) — the number of available Beru-taxi cars nearby.  The i-th of the following n lines contains three integers xi, yi and vi ( - 100 ≤ xi, yi ≤ 100, 1 ≤ vi ≤ 100) — the coordinates of the i-th car and its speed. It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives.

Print a single real value — the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You 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, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer.In the second sample, cars 2 and 3 will arrive simultaneously.


You are given a set of $$$n$$$ segments on the axis $$$Ox$$$, each segment has integer endpoints between $$$1$$$ and $$$m$$$ inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$) — coordinates of the left and of the right endpoints. Consider all integer points between $$$1$$$ and $$$m$$$ inclusive. Your task is to print all such points that don't belong to any segment. The point $$$x$$$ belongs to the segment $$$[l; r]$$$ if and only if $$$l \le x \le r$$$.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the number of segments and the upper bound for coordinates. The next $$$n$$$ lines contain two integers each $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$) — the endpoints of the $$$i$$$-th segment. Segments may intersect, overlap or even coincide with each other. Note, it is possible that $$$l_i=r_i$$$, i.e. a segment can degenerate to a point.

In the first line print one integer $$$k$$$ — the number of points that don't belong to any segment. In the second line print exactly $$$k$$$ integers in any order — the points that don't belong to any segment. All points you print should be distinct. If there are no such points at all, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.

NoteIn the first example the point $$$1$$$ belongs to the second segment, the point $$$2$$$ belongs to the first and the second segments and the point $$$5$$$ belongs to the third segment. The points $$$3$$$ and $$$4$$$ do not belong to any segment.In the second example all the points from $$$1$$$ to $$$7$$$ belong to the first segment.


This is an easier version of the problem. In this version, $$$n \le 2000$$$.There are $$$n$$$ distinct points in three-dimensional space numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th point has coordinates $$$(x_i, y_i, z_i)$$$. The number of points $$$n$$$ is even.You'd like to remove all $$$n$$$ points using a sequence of $$$\frac{n}{2}$$$ snaps. In one snap, you can remove any two points $$$a$$$ and $$$b$$$ that have not been removed yet and form a perfectly balanced pair. A pair of points $$$a$$$ and $$$b$$$ is perfectly balanced if no other point $$$c$$$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $$$a$$$ and $$$b$$$.Formally, point $$$c$$$ lies within the axis-aligned minimum bounding box of points $$$a$$$ and $$$b$$$ if and only if $$$\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$$$, $$$\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$$$, and $$$\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$$$. Note that the bounding box might be degenerate. Find a way to remove all points in $$$\frac{n}{2}$$$ snaps.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2000$$$; $$$n$$$ is even), denoting the number of points. Each of the next $$$n$$$ lines contains three integers $$$x_i$$$, $$$y_i$$$, $$$z_i$$$ ($$$-10^8 \le x_i, y_i, z_i \le 10^8$$$), denoting the coordinates of the $$$i$$$-th point. No two points coincide.

Output $$$\frac{n}{2}$$$ pairs of integers $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting the indices of points removed on snap $$$i$$$. Every integer between $$$1$$$ and $$$n$$$, inclusive, must appear in your output exactly once. We can show that it is always possible to remove all points. If there are many solutions, output any of them.

NoteIn the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on $$$z = 0$$$ plane). Note that order of removing matters: for example, points $$$5$$$ and $$$1$$$ don't form a perfectly balanced pair initially, but they do after point $$$3$$$ is removed.


A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a, b] covers segment [c, d], if they meet this condition a ≤ c ≤ d ≤ b.

The first line contains integer n (1 ≤ n ≤ 105) — the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ 109) — the borders of the i-th segment. It is guaranteed that no two segments coincide.

Print a single integer — the number of the segment that covers all other segments in the set. If there's no solution, print -1. The segments are numbered starting from 1 in the order in which they appear in the input.

#!/usr/bin/perl -w

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

chomp(my $n = <>);
my @l = ();
my @r = ();

for my $i (1 .. $n) {
    chomp($_ = <>);
    my ($left, $right) = split;
    push @l, $left;
    push @r, $right;
}

my $min_low = min @l;
my $max_high = max @r;
my $find = 0;

for my $i (0 .. $n - 1) {
    if ($l[$i] == $min_low && $r[$i] == $max_high) {
        print $i + 1, "\n";
        $find = 1;
        last;
    }
}
unless ($find) {
    print "-1\n";
}

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

<>;
while (<>=~/ /){
	push @i,$`;
	push @j,$'+0;
	}
$i=min(@i);
$j=max(@j);

for $k(0..@i-1){
	$i[$k]==$i && $j[$k]==$j and print ($k+ ++$p);
	}

$p or print -1;

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

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

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

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

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

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

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

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

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

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


Fox Ciel has a board with n rows and n columns. So, the board consists of n × n cells. Each cell contains either a symbol '.', or a symbol '#'.A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.Please, tell Ciel if she can draw the crosses in the described way.

The first line contains an integer n (3 ≤ n ≤ 100) — the size of the board. Each of the next n lines describes one row of the board. The i-th line describes the i-th row of the board and consists of n characters. Each character is either a symbol '.', or a symbol '#'.

Output a single line with "YES" if Ciel can draw the crosses in the described way. Otherwise output a single line with "NO".

NoteIn example 1, you can draw two crosses. The picture below shows what they look like.In example 2, the board contains 16 cells with '#', but each cross contains 5. Since 16 is not a multiple of 5, so it's impossible to cover all.


You are given a chess board with $$$n$$$ rows and $$$n$$$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.A knight is a chess piece that can attack a piece in cell ($$$x_2$$$, $$$y_2$$$) from the cell ($$$x_1$$$, $$$y_1$$$) if one of the following conditions is met:  $$$|x_1 - x_2| = 2$$$ and $$$|y_1 - y_2| = 1$$$, or  $$$|x_1 - x_2| = 1$$$ and $$$|y_1 - y_2| = 2$$$. Here are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them).  A duel of knights is a pair of knights of different colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible.

The first line contains one integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of rows (and columns) in the board.

Print $$$n$$$ lines with $$$n$$$ characters in each line. The $$$j$$$-th character in the $$$i$$$-th line should be W, if the cell ($$$i$$$, $$$j$$$) contains a white knight, or B, if it contains a black knight. The number of duels should be maximum possible. If there are multiple optimal answers, print any of them.

NoteIn the first example, there are $$$8$$$ duels:  the white knight in ($$$1$$$, $$$1$$$) attacks the black knight in ($$$3$$$, $$$2$$$);  the white knight in ($$$1$$$, $$$1$$$) attacks the black knight in ($$$2$$$, $$$3$$$);  the white knight in ($$$1$$$, $$$3$$$) attacks the black knight in ($$$3$$$, $$$2$$$);  the white knight in ($$$1$$$, $$$3$$$) attacks the black knight in ($$$2$$$, $$$1$$$);  the white knight in ($$$3$$$, $$$1$$$) attacks the black knight in ($$$1$$$, $$$2$$$);  the white knight in ($$$3$$$, $$$1$$$) attacks the black knight in ($$$2$$$, $$$3$$$);  the white knight in ($$$3$$$, $$$3$$$) attacks the black knight in ($$$1$$$, $$$2$$$);  the white knight in ($$$3$$$, $$$3$$$) attacks the black knight in ($$$2$$$, $$$1$$$).

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	$_ = 'WB' x $n;

	@_ = ();

	for my $i ( 1 .. $n ){
		push @_, substr $_, $i % 2, $n;
		}

	print for @_;
	}


Consider the array $$$a$$$ composed of all the integers in the range $$$[l, r]$$$. For example, if $$$l = 3$$$ and $$$r = 7$$$, then $$$a = [3, 4, 5, 6, 7]$$$.Given $$$l$$$, $$$r$$$, and $$$k$$$, is it possible for $$$\gcd(a)$$$ to be greater than $$$1$$$ after doing the following operation at most $$$k$$$ times?   Choose $$$2$$$ numbers from $$$a$$$.  Permanently remove one occurrence of each of them from the array.  Insert their product back into $$$a$$$. $$$\gcd(b)$$$ denotes the greatest common divisor (GCD) of the integers in $$$b$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The description of test cases follows. The input for each test case consists of a single line containing $$$3$$$ non-negative integers $$$l$$$, $$$r$$$, and $$$k$$$ ($$$1 \leq l \leq r \leq 10^9, \enspace 0 \leq k \leq r - l$$$).

For each test case, print "YES" if it is possible to have the GCD of the corresponding array greater than $$$1$$$ by performing at most $$$k$$$ operations, and "NO" otherwise (case insensitive).

NoteFor the first test case, $$$a = [1]$$$, so the answer is "NO", since the only element in the array is $$$1$$$.For the second test case the array is $$$a = [3, 4, 5]$$$ and we have $$$1$$$ operation. After the first operation the array can change to: $$$[3, 20]$$$, $$$[4, 15]$$$ or $$$[5, 12]$$$ all of which having their greatest common divisor equal to $$$1$$$ so the answer is "NO".For the third test case, $$$a = [13]$$$, so the answer is "YES", since the only element in the array is $$$13$$$.For the fourth test case, $$$a = [4]$$$, so the answer is "YES", since the only element in the array is $$$4$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	if( $l == $r and $l > 1 ){
		print 'YES';
		next;
		}

	$l % 2 or $l ++;
	$r % 2 or $r --;

	my $odds = ( $r - $l + 2 >> 1 );

	print $odds > $k ? 'NO' : 'YES';
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	if( $l == $r and $l > 1 ){
		print 'YES';
		next;
		}

	my $odds = ( $r - $l >> 1 ) + ( $l % 2 );

	print $odds > $k ? 'NO' : 'YES';
	}


Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1, m), then goes down 2 rows to (3, m), then goes left to (3, 1) and so on.Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').Consider sample tests in order to understand the snake pattern.

The only line contains two integers: n and m (3 ≤ n, m ≤ 50).  n is an odd number.

Output n lines. Each line should contain a string consisting of m characters. Do not output spaces.

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';
use v5.18;
use integer;

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

say('#' x $m);

my $left = 0;

foreach (1..(($n-1) / 2))
{
    if ($left) {
        say('#' . '.' x ($m - 1));
    }
    else
    {
        say('.' x ($m - 1) . '#');
    }
    $left = !$left;
    say '#' x $m;
}


There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points).

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points.

In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them.

NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property.


You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x).

The first line contains the single positive integer n (1 ≤ n ≤ 105) — the number of integers. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2.

NoteIn the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).In the second example all pairs of indexes (i, j) (where i < j) include in answer.


There is a square field of size $$$n \times n$$$ in which two cells are marked. These cells can be in the same row or column.You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes.For example, if $$$n=4$$$ and a rectangular field looks like this (there are asterisks in the marked cells):$$$$$$ \begin{matrix} . & . & * & . \\ . & . & . & . \\ * & . & . & . \\ . & . & . & . \\ \end{matrix} $$$$$$Then you can mark two more cells as follows$$$$$$ \begin{matrix} * & . & * & . \\ . & . & . & . \\ * & . & * & . \\ . & . & . & . \\ \end{matrix} $$$$$$If there are several possible solutions, then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 400$$$). Then $$$t$$$ test cases follow. The first row of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 400$$$) — the number of rows and columns in the table. The following $$$n$$$ lines each contain $$$n$$$ characters '.' or '*' denoting empty and marked cells, respectively. It is guaranteed that the sums of $$$n$$$ for all test cases do not exceed $$$400$$$. It is guaranteed that there are exactly two asterisks on the field. They can be in the same row/column. It is guaranteed that the solution exists.

For each test case, output $$$n$$$ rows of $$$n$$$ characters — a field with four asterisks marked corresponding to the statements. If there multiple correct answers, print any of them.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	@_ = map ~~<>, 1 .. $_;
	chomp @_;

	my( $two_stars ) = grep m/\*.*\*/, @_;

	if( defined $two_stars ){
		for( @_ ){
			$_ ne $two_stars and do {
				$_ = $two_stars;
				last;
				};
			}
		}
	else{
		my @lines = grep m/\*/, @_;

		if( $lines[ 0 ] eq $lines[ 1 ] ){
			m/\*/ and s/\./*/ for @_;
			}
		else{
			my @idx = map { index $_, '*' } @lines;
			for( @_ ){
				next if not m/\*/;
				substr $_, $idx[ 0 ], 1, '*';
				substr $_, $idx[ 1 ], 1, '*';
				}
			}
		}

	print for @_;
	}


One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size $$$1\times1$$$, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks. The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of grids of the games.  Each of the next $$$T$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$): the size of the side of the grid of the game.

For each grid of the game print the minimum number of turns required to build a chess coloring pattern out of blocks on it.

NoteFor $$$3\times3$$$ grid ponies can make two following moves:


The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example:  $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$,  $$$1$$$ is a good number: $$$1 = 3^0$$$,  $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$,  but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$),  $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid),  $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).

For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.


On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.Help the child to find out, what is the minimum total energy he should spend to remove all n parts.

The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi). Consider all the parts are numbered from 1 to n.

Output the minimum total energy the child should spend to remove all n parts of the toy.

NoteOne of the optimal sequence of actions in the first sample is:  First, remove part 3, cost of the action is 20.  Then, remove part 2, cost of the action is 10.  Next, remove part 4, cost of the action is 10.  At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.In the second sample, the child will spend 400 no matter in what order he will remove the parts.

use strict;
use warnings;

$_ = readline;chomp;my($n,$m) = split " ";
$_ = readline;chomp;my @v = split " ";

my $et = 0;

foreach (1..$m) {
    $_ = readline;chomp;my($a,$b) = split " ";
    $et += $v[$a - 1]>$v[$b - 1]?$v[$b - 1]:$v[$a - 1];
}

print "$et\n";


Little C loves number «3» very much. He loves all things about it.Now he has a positive integer $$$n$$$. He wants to split $$$n$$$ into $$$3$$$ positive integers $$$a,b,c$$$, such that $$$a+b+c=n$$$ and none of the $$$3$$$ integers is a multiple of $$$3$$$. Help him to find a solution.

A single line containing one integer $$$n$$$ ($$$3 \leq n \leq 10^9$$$) — the integer Little C has.

Print $$$3$$$ positive integers $$$a,b,c$$$ in a single line, such that $$$a+b+c=n$$$ and none of them is a multiple of $$$3$$$. It can be proved that there is at least one solution. If there are multiple solutions, print any of them.


Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.

The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.

In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.

5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov

3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123

#!/usr/bin/env perl
#===============================================================================
#         FILE: 2.pl
#       AUTHOR: Phoenix Ikki (liuxueyang.github.io), liuxueyang457@gmail.com
# ORGANIZATION: Hunan University
#      CREATED: 01/14/2015 11:18:24 AM
#===============================================================================

use strict;
use warnings;
use utf8;
use 5.012;

chomp(my $n = <STDIN>);

my %name;
while ( $n-- ) {
	chomp($_ = <STDIN>);
	my ($old, $new) = split(/ /);
	if ( exists($name{$old}) ) {
		my $origin = $name{$old};
		delete $name{$old};
		$name{$new} = $origin;
	}
	else {
		$name{$new} = $old;
	}
}
my $size = keys %name;
print "$size\n";
for my $key (keys %name) {
	print "$name{$key} $key\n";
}

$\ = $/;
<>;
undef %h;
while(<>){
	($n,$m)=split;
	defined $h{$n} ? ($h{$m} = $h{$n}, delete $h{$n}): ($h{$m} = $n);
	}
$, = $";
print scalar keys %h;
while (($k,$v) = each %h){
	print $v,$k
	}


You have an array $$$a_1, a_2, \dots, a_n$$$. All $$$a_i$$$ are positive integers.In one step you can choose three distinct indices $$$i$$$, $$$j$$$, and $$$k$$$ ($$$i \neq j$$$; $$$i \neq k$$$; $$$j \neq k$$$) and assign the sum of $$$a_j$$$ and $$$a_k$$$ to $$$a_i$$$, i. e. make $$$a_i = a_j + a_k$$$.Can you make all $$$a_i$$$ lower or equal to $$$d$$$ using the operation above any number of times (possibly, zero)?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$d$$$ ($$$3 \le n \le 100$$$; $$$1 \le d \le 100$$$) — the number of elements in the array $$$a$$$ and the value $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$) — the array $$$a$$$.

For each test case, print YES, if it's possible to make all elements $$$a_i$$$ less or equal than $$$d$$$ using the operation above. Otherwise, print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).

NoteIn the first test case, we can prove that we can't make all $$$a_i \le 3$$$.In the second test case, all $$$a_i$$$ are already less or equal than $$$d = 4$$$.In the third test case, we can, for example, choose $$$i = 5$$$, $$$j = 1$$$, $$$k = 2$$$ and make $$$a_5 = a_1 + a_2 = 2 + 1 = 3$$$. Array $$$a$$$ will become $$$[2, 1, 5, 3, 3]$$$.After that we can make $$$a_3 = a_5 + a_2 = 3 + 1 = 4$$$. Array will become $$$[2, 1, 4, 3, 3]$$$ and all elements are less or equal than $$$d = 4$$$.


Vasya has got $$$n$$$ books, numbered from $$$1$$$ to $$$n$$$, arranged in a stack. The topmost book has number $$$a_1$$$, the next one — $$$a_2$$$, and so on. The book at the bottom of the stack has number $$$a_n$$$. All numbers are distinct.Vasya wants to move all the books to his backpack in $$$n$$$ steps. During $$$i$$$-th step he wants to move the book number $$$b_i$$$ into his backpack. If the book with number $$$b_i$$$ is in the stack, he takes this book and all the books above the book $$$b_i$$$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $$$[1, 2, 3]$$$ (book $$$1$$$ is the topmost), and Vasya moves the books in the order $$$[2, 1, 3]$$$, then during the first step he will move two books ($$$1$$$ and $$$2$$$), during the second step he will do nothing (since book $$$1$$$ is already in the backpack), and during the third step — one book (the book number $$$3$$$). Note that $$$b_1, b_2, \dots, b_n$$$ are distinct.Help Vasya! Tell him the number of books he will put into his backpack during each step.

The first line contains one integer $$$n~(1 \le n \le 2 \cdot 10^5)$$$ — the number of books in the stack. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n~(1 \le a_i \le n)$$$ denoting the stack of books. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n~(1 \le b_i \le n)$$$ denoting the steps Vasya is going to perform. All numbers $$$a_1 \dots a_n$$$ are distinct, the same goes for $$$b_1 \dots b_n$$$.

Print $$$n$$$ integers. The $$$i$$$-th of them should be equal to the number of books Vasya moves to his backpack during the $$$i$$$-th step.

NoteThe first example is described in the statement.In the second example, during the first step Vasya will move the books $$$[3, 1, 4]$$$. After that only books $$$2$$$ and $$$5$$$ remain in the stack ($$$2$$$ is above $$$5$$$). During the second step Vasya will take the books $$$2$$$ and $$$5$$$. After that the stack becomes empty, so during next steps Vasya won't move any books.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my @c;

	my %h;

	OUTER:
	for( @n ){
		my $c = 0;
		$h{ $_ } and do { push @c, 0; next };

		while( @_ ){
			my $i = shift @_;
			$h{ $i } ++;
			$c ++;
			if( $i == $_ ){
				push @c, $c;
				next OUTER;
				}
			}
		push @c, 0;
		}

	print "@c";
	}


You are given a problemset consisting of $$$n$$$ problems. The difficulty of the $$$i$$$-th problem is $$$a_i$$$. It is guaranteed that all difficulties are distinct and are given in the increasing order.You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let $$$a_{i_1}, a_{i_2}, \dots, a_{i_p}$$$ be the difficulties of the selected problems in increasing order. Then for each $$$j$$$ from $$$1$$$ to $$$p-1$$$ $$$a_{i_{j + 1}} \le a_{i_j} \cdot 2$$$ should hold. It means that the contest consisting of only one problem is always valid.Among all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of problems in the problemset. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — difficulties of the problems. It is guaranteed that difficulties of the problems are distinct and are given in the increasing order.

Print a single integer — maximum number of problems in the contest satisfying the condition in the problem statement.

NoteDescription of the first example: there are $$$10$$$ valid contests consisting of $$$1$$$ problem, $$$10$$$ valid contests consisting of $$$2$$$ problems ($$$[1, 2], [5, 6], [5, 7], [5, 10], [6, 7], [6, 10], [7, 10], [21, 23], [21, 24], [23, 24]$$$), $$$5$$$ valid contests consisting of $$$3$$$ problems ($$$[5, 6, 7], [5, 6, 10], [5, 7, 10], [6, 7, 10], [21, 23, 24]$$$) and a single valid contest consisting of $$$4$$$ problems ($$$[5, 6, 7, 10]$$$).In the second example all the valid contests consist of $$$1$$$ problem.In the third example are two contests consisting of $$$3$$$ problems: $$$[4, 7, 12]$$$ and $$$[100, 150, 199]$$$.

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

my $n=<STDIN>;
my @p=split/ /,<STDIN>;chomp($n,$p[-1]);
my @l;my $z=0;
my $max=0;
if(scalar @p==1){print "1\n";}
else{
    push @l,$p[0];
    for my $i(1..$#p){
	if($p[$i]<=2*$p[$i-1]){
	    push @l,$p[$i];
	}
	else{
	    while($z<$i){
		shift @l;
		$z++;
	    }
	    push @l,$p[$i];
	}
	$max = scalar @l if($max<scalar @l);
    }
print scalar "$max\n";
}

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

my $n=<STDIN>;
my @p=split/ /,<STDIN>;chomp($n,$p[-1]);
my @l;my $z=0;
my $max=0;
push @l,$p[0];
for my $i(1..$#p){
    if($p[$i]<=2*$p[$i-1]){
	push @l,$p[$i];
    }
    else{
	$max = scalar @l if($max<scalar @l);
	while($z<$i){
	    shift @l;
	    $z++;
	}
	push @l,$p[$i];
    }
}
print scalar "$max\n";

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

my $n=<STDIN>;
my @p=split/ /,<STDIN>;chomp($n,$p[-1]);
my @l;my $z=0;
my $max=0;
if(scalar @p==1){print "1\n";}
else{
    push @l,$p[0];
    for my $i(1..$#p){
	if($p[$i]<=2*$p[$i-1]){
	    push @l,$p[$i];
	}
	else{
	    $max = scalar @l if($max<scalar @l);
	    while($z<$i){
		shift @l;
		$z++;
	    }
	    push @l,$p[$i];
	}
    }
print scalar "$max\n";
}


Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.

The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109).

Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them.

NoteSample 1. You can reverse the entire array to get [1, 2, 3], which is sorted.Sample 3. No segment can be reversed such that the array will be sorted.DefinitionsA segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r].If you have an array a of size n and you reverse its segment [l, r], the array will become:a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].


Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.

The first line contains integer n (1 ≤ n ≤ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card.

In a single line print the answer to the problem — the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1.

NoteIn the first test you can make only one number that is a multiple of 90 — 0.In the second test you can make number 5555555550, it is a multiple of 90.

chomp($n=<>);
foreach (split / /, <>) {
	$five++ if $_==5;
}
$zero = $n-$five;
print "-1\n" and exit if $zero==0;
print "0\n" and exit if $five<9;
print "5" x ($five-$five%9) . "0"x$zero . "\n";


The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good.Heidi knows that the lair can be represented as a rectangle on a lattice, with sides parallel to the axes. Each vertex of the polygon occupies an integer point on the lattice. For each cell of the lattice, Heidi can check the level of Zombie Contamination. This level is an integer between 0 and 4, equal to the number of corners of the cell that are inside or on the border of the rectangle.As a test, Heidi wants to check that her Zombie Contamination level checker works. Given the output of the checker, Heidi wants to know whether it could have been produced by a single non-zero area rectangular-shaped lair (with axis-parallel sides).

The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 50). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4. Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).

The first line of the output should contain Yes if there exists a single non-zero area rectangular lair with corners on the grid for which checking the levels of Zombie Contamination gives the results given in the input, and No otherwise.

NoteThe lair, if it exists, has to be rectangular (that is, have corners at some grid points with coordinates (x1, y1), (x1, y2), (x2, y1), (x2, y2)), has a non-zero area and be contained inside of the grid (that is, 0 ≤ x1 < x2 ≤ N, 0 ≤ y1 < y2 ≤ N), and result in the levels of Zombie Contamination as reported in the input.

sub fail { print 'No'; exit }
<>;
while ($_ = <>) {
	/^0+$/ or last;
}
/^(0*)([1][2]+[1])0*$/ or fail;
$offset = $1;
$width = length $2;
while ($_ = <>) {
	/^(0*)([2][4]+[2])0*$/ or last;
	fail unless $1 eq $offset and length $2 == $width;
	$height++;
}
fail unless $height > 0;
fail unless /^(0*)([1][2]+[1])0*$/ and $1 eq $offset and length $2 == $width;
for (<>) {
	/^0+$/ or fail;
}
print 'Yes';

sub fail { print 'No'; exit }
<>;
while ($_ = <>) {
	/^0+$/ or last;
}
/^(0*)([1][2]+[1])(0*)$/ or fail;
$offset = $1;
$width = length $2;
while ($_ = <>) {
	/^(0*)([2][4]+[2])/ or last;
	fail unless $1 eq $offset and length $2 == $width;
	$height++;
}
fail unless $height > 0;
fail unless /^(0*)([1][2]+[1])/ and $1 eq $offset and length $2 == $width;
for (<>) {
	/^0+$/ or fail;
}
print 'Yes';


Your favorite shop sells $$$n$$$ Kinder Surprise chocolate eggs. You know that exactly $$$s$$$ stickers and exactly $$$t$$$ toys are placed in $$$n$$$ eggs in total.Each Kinder Surprise can be one of three types:  it can contain a single sticker and no toy;  it can contain a single toy and no sticker;  it can contain both a single sticker and a single toy. But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$T$$$ lines contain three integers $$$n$$$, $$$s$$$ and $$$t$$$ each ($$$1 \le n \le 10^9$$$, $$$1 \le s, t \le n$$$, $$$s + t \ge n$$$) — the number of eggs, stickers and toys. All queries are independent.

Print $$$T$$$ integers (one number per query) — the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and one toy

NoteIn the first query, we have to take at least $$$6$$$ eggs because there are $$$5$$$ eggs with only toy inside and, in the worst case, we'll buy all of them.In the second query, all eggs have both a sticker and a toy inside, that's why it's enough to buy only one egg.In the third query, we have to buy both eggs: one with a sticker and one with a toy.

use strict;
use warnings;

use Data::Dumper;

sub main {

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

    my ($a, $s, $t, $n, @a, $st, $so, $to);
    for my $i (1..$q) {
        $a= <$in>; chomp($a);
        @a= split(' ', $a);

        $n= $a[0];
        $s= $a[1];
        $t= $a[2];

        $st= $s + $t - $n;

        if($st == $n) {
            print "1\n";
            next;
        }

        $so= $s - $st;
        $to= $t - $st;

        print(
            $so < $to
            ? ($to+1)
            : ($so+1)
        );

        print "\n";
    }

}

main() unless caller();