Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:   +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.   -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.  ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.

The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.

For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.

NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.   1 and 241.  361.  101 and 361.  361.  4000.

#use strict;
#use warnings;

use Data::Dumper;
$,=" ";
my $N=<>;
chomp($N);
my %data;

while($N--)
{
my ($op,$s)=split / /,<>;
chomp($op,$s);
if($op eq '+')
{
  my $p;
  for my $i (0..length($s)-1)
  {
    $p.=substr($s,$i,1)%2;
  }
  #print $p , "\n";
  $data{$p}++;
}
if($op eq '-')
{
  my $p;
  for my $i (0..length($s)-1)
  {
    $p.=substr($s,$i,1)%2;
  }
  #print $p , "\n";
  $data{$p}--;
}
if($op eq '?')
{
  $s=~ s/^0+//g;
  my $count=0;
  my $t=length($s);
  $count+=$data{$s};
  for($t..17)
  {
    $s="0".$s;
    $count+=$data{$s};
  }
  print $count . "\n";
}
}


It is the easy version of the problem. The only difference is that in this version $$$k = 3$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, such that:  $$$a_1 + a_2 + \ldots + a_k = n$$$  $$$LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \ldots, a_k$$$.We can show that for given constraints the answer always exists.

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

For each test case print $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, for which all conditions are satisfied.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

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

	$debug and print $n;

	if( $n % 6 == 0 ){
		print join ' ', ( $n / 3 ) x 3;
		}
	elsif( $n % 2 == 1 ){
		print join ' ', 1, ( ( $n - 1 ) / 2 ) x 2;
		}
	else{
		my $times = 0;
		while( $n % 2 == 0 and $n > 2 ){
			$n /= 2;
			$times ++;
			}
		print join ' ', map $_ * 2 ** $times, 1, ( ( $n - 1 ) / 2 ) x 2;
		}
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	print join ' ', 1, 1, $n - 2;
	}


A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled: An example of such a bar can be seen on the picture.  For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.

We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).

Print n numbers. The i-th of them should be equal to ai.


A camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means that the corresponding column is black.You think that this photo can contain a zebra. In this case the whole photo should consist of several (possibly, only one) alternating black and white stripes of equal width. For example, the photo [0, 0, 0, 1, 1, 1, 0, 0, 0] can be a photo of zebra, while the photo [0, 0, 0, 1, 1, 1, 1] can not, because the width of the black stripe is 3, while the width of the white stripe is 4. Can the given photo be a photo of zebra or not?

The first line contains a single integer n (1 ≤ n ≤ 100 000) — the width of the photo. The second line contains a sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 1) — the description of the photo. If ai is zero, the i-th column is all black. If ai is one, then the i-th column is all white.

If the photo can be a photo of zebra, print "YES" (without quotes). Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteThe first two examples are described in the statements.In the third example all pixels are white, so the photo can be a photo of zebra.In the fourth example the width of the first stripe is equal to three (white color), the width of the second stripe is equal to three (black), and the width of the third stripe is equal to two (white). Thus, not all stripes have equal length, so this photo is not a photo of zebra.

$n = <STDIN>;
@bits = split / /, <STDIN>;

$first = @bits[0];
$mb_len = 1;
$mb_len_done = 0;

for ($curr = 1; $curr < $n; $curr++) {
	if (@bits[$curr] != @bits[$curr-1]) {
		$mb_len_done = 1;
	}
	if (!$mb_len_done) {
		$mb_len += 1;
	}
}

if ($mb_len == $n) {
	print "Yes";
	exit();
}

$result = 1; # true
$curr_color = $first;
$last = 0;

for ($i = 0; $i < $n;) {
	$last = 0;
	for ($j = 0; $j < $mb_len && $i < $n; $j++) {
		$last += 1;
		if ($curr_color != @bits[$i]) {
			$result = 0;
		}
		$i += 1;
	}
	$curr_color = ($curr_color + 1) % 2;
}

if ($result && $last == $mb_len) {
	print "Yes";
} else {
	print "No";
}

#!/usr/bin/env perl

use strict;
use warnings;
no warnings 'uninitialized';

my $N = <>+0;
my $line = <>;
chomp $line;
$line =~ s/ +//g;
$line =~ s/01/0#1/g;
$line =~ s/10/1#0/g;

#print $line, "\n";

my @A = split '#', $line;

my $M = scalar(@A);
for (my $i = 1; $i < $M; ++$i) {
   if (length($A[$i]) != length($A[0])) {
      print "NO\n";
      exit(0);
   }
}

print "YES\n";

$n=<STDIN>;
$_ = <STDIN>; @a=split;
$prvval=-1;
$cur=0;
$curv=$a[0];
$isok=1;
foreach $x (@a)
{
    if($curv!=$x) {
        if($prvval!=-1){
            if($cur!=$prvval) {
                $isok = 0;
            }
        }
        $prvval = $cur;
        $cur = 0;
        $curv = $x;

    }
    $cur=$cur+1;
}

if($prvval!=-1){
    if($cur!=$prvval) {
        $isok = 0;
    }
}

if($isok==1){
    print "YES";
}
else
{
    print "NO";
}


You are given a deck of $$$n$$$ cards numbered from $$$1$$$ to $$$n$$$ (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.   Choose $$$2 \le k \le n$$$ and split the deck in $$$k$$$ nonempty contiguous parts $$$D_1, D_2,\dots, D_k$$$ ($$$D_1$$$ contains the first $$$|D_1|$$$ cards of the deck, $$$D_2$$$ contains the following $$$|D_2|$$$ cards and so on). Then reverse the order of the parts, transforming the deck into $$$D_k, D_{k-1}, \dots, D_2, D_1$$$ (so, the first $$$|D_k|$$$ cards of the new deck are $$$D_k$$$, the following $$$|D_{k-1}|$$$ cards are $$$D_{k-1}$$$ and so on). The internal order of each packet of cards $$$D_i$$$ is unchanged by the operation. You have to obtain a sorted deck (i.e., a deck where the first card is $$$1$$$, the second is $$$2$$$ and so on) performing at most $$$n$$$ operations. It can be proven that it is always possible to sort the deck performing at most $$$n$$$ operations.Examples of operation: The following are three examples of valid operations (on three decks with different sizes).   If the deck is [3 6 2 1 4 5 7] (so $$$3$$$ is the first card and $$$7$$$ is the last card), we may apply the operation with $$$k=4$$$ and $$$D_1=$$$[3 6], $$$D_2=$$$[2 1 4], $$$D_3=$$$[5], $$$D_4=$$$[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].  If the deck is [3 1 2], we may apply the operation with $$$k=3$$$ and $$$D_1=$$$[3], $$$D_2=$$$[1], $$$D_3=$$$[2]. Doing so, the deck becomes [2 1 3].  If the deck is [5 1 2 4 3 6], we may apply the operation with $$$k=2$$$ and $$$D_1=$$$[5 1], $$$D_2=$$$[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].

The first line of the input contains one integer $$$n$$$ ($$$1\le n\le 52$$$)  — the number of cards in the deck. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$  — the cards in the deck. The first card is $$$c_1$$$, the second is $$$c_2$$$ and so on. It is guaranteed that for all $$$i=1,\dots,n$$$ there is exactly one $$$j\in\{1,\dots,n\}$$$ such that $$$c_j = i$$$.

On the first line, print the number $$$q$$$ of operations you perform (it must hold $$$0\le q\le n$$$). Then, print $$$q$$$ lines, each describing one operation. To describe an operation, print on a single line the number $$$k$$$ of parts you are going to split the deck in, followed by the size of the $$$k$$$ parts: $$$|D_1|, |D_2|, \dots , |D_k|$$$.  It must hold $$$2\le k\le n$$$, and $$$|D_i|\ge 1$$$ for all $$$i=1,\dots,k$$$, and $$$|D_1|+|D_2|+\cdots + |D_k| = n$$$. It can be proven that it is always possible to sort the deck performing at most $$$n$$$ operations. If there are several ways to sort the deck you can output any of them.

NoteExplanation of the first testcase: Initially the deck is [3 1 2 4].   The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].  The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].  Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].   The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6].


There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and:  Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$.  Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.

For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).

NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.


One day n friends met at a party, they hadn't seen each other for a long time and so they decided to make a group photo together. Simply speaking, the process of taking photos can be described as follows. On the photo, each photographed friend occupies a rectangle of pixels: the i-th of them occupies the rectangle of width wi pixels and height hi pixels. On the group photo everybody stands in a line, thus the minimum pixel size of the photo including all the photographed friends, is W × H, where W is the total sum of all widths and H is the maximum height of all the photographed friends.As is usually the case, the friends made n photos — the j-th (1 ≤ j ≤ n) photo had everybody except for the j-th friend as he was the photographer.Print the minimum size of each made photo in pixels.

The first line contains integer n (2 ≤ n ≤ 200 000) — the number of friends.  Then n lines follow: the i-th line contains information about the i-th friend. The line contains a pair of integers wi, hi (1 ≤ wi ≤ 10, 1 ≤ hi ≤ 1000) — the width and height in pixels of the corresponding rectangle.

Print n space-separated numbers b1, b2, ..., bn, where bi — the total number of pixels on the minimum photo containing all friends expect for the i-th one.


The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.Koa the Koala is at the beach!The beach consists (from left to right) of a shore, $$$n+1$$$ meters of sea and an island at $$$n+1$$$ meters from the shore.She measured the depth of the sea at $$$1, 2, \dots, n$$$ meters from the shore and saved them in array $$$d$$$. $$$d_i$$$ denotes the depth of the sea at $$$i$$$ meters from the shore for $$$1 \le i \le n$$$.Like any beach this one has tide, the intensity of the tide is measured by parameter $$$k$$$ and affects all depths from the beginning at time $$$t=0$$$ in the following way:  For a total of $$$k$$$ seconds, each second, tide increases all depths by $$$1$$$.  Then, for a total of $$$k$$$ seconds, each second, tide decreases all depths by $$$1$$$.  This process repeats again and again (ie. depths increase for $$$k$$$ seconds then decrease for $$$k$$$ seconds and so on ...).Formally, let's define $$$0$$$-indexed array $$$p = [0, 1, 2, \ldots, k - 2, k - 1, k, k - 1, k - 2, \ldots, 2, 1]$$$ of length $$$2k$$$. At time $$$t$$$ ($$$0 \le t$$$) depth at $$$i$$$ meters from the shore equals $$$d_i + p[t \bmod 2k]$$$ ($$$t \bmod 2k$$$ denotes the remainder of the division of $$$t$$$ by $$$2k$$$). Note that the changes occur instantaneously after each second, see the notes for better understanding. At time $$$t=0$$$ Koa is standing at the shore and wants to get to the island. Suppose that at some time $$$t$$$ ($$$0 \le t$$$) she is at $$$x$$$ ($$$0 \le x \le n$$$) meters from the shore:  In one second Koa can swim $$$1$$$ meter further from the shore ($$$x$$$ changes to $$$x+1$$$) or not swim at all ($$$x$$$ stays the same), in both cases $$$t$$$ changes to $$$t+1$$$.  As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed $$$l$$$ at integer points of time (or she will drown). More formally, if Koa is at $$$x$$$ ($$$1 \le x \le n$$$) meters from the shore at the moment $$$t$$$ (for some integer $$$t\ge 0$$$), the depth of the sea at this point  — $$$d_x + p[t \bmod 2k]$$$  — can't exceed $$$l$$$. In other words, $$$d_x + p[t \bmod 2k] \le l$$$ must hold always.  Once Koa reaches the island at $$$n+1$$$ meters from the shore, she stops and can rest.Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there). Koa wants to know whether she can go from the shore to the island. Help her!

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$)  — the number of test cases. Description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$k$$$ and $$$l$$$ ($$$1 \le n \le 3 \cdot 10^5; 1 \le k \le 10^9; 1 \le l \le 10^9$$$) — the number of meters of sea Koa measured and parameters $$$k$$$ and $$$l$$$. The second line of each test case contains $$$n$$$ integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \le d_i \le 10^9$$$)  — the depths of each meter of sea Koa measured. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case: Print Yes if Koa can get from the shore to the island, and No otherwise. You may print each letter in any case (upper or lower).

NoteIn the following $$$s$$$ denotes the shore, $$$i$$$ denotes the island, $$$x$$$ denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at $$$1, 2, \dots, n$$$ meters from the shore.In test case $$$1$$$ we have $$$n = 2, k = 1, l = 1, p = [ 0, 1 ]$$$.Koa wants to go from shore (at $$$x = 0$$$) to the island (at $$$x = 3$$$). Let's describe a possible solution:  Initially at $$$t = 0$$$ the beach looks like this: $$$[\underline{s}, 1, 0, i]$$$.  At $$$t = 0$$$ if Koa would decide to swim to $$$x = 1$$$, beach would look like: $$$[s, \underline{2}, 1, i]$$$ at $$$t = 1$$$, since $$$2 > 1$$$ she would drown. So Koa waits $$$1$$$ second instead and beach looks like $$$[\underline{s}, 2, 1, i]$$$ at $$$t = 1$$$.  At $$$t = 1$$$ Koa swims to $$$x = 1$$$, beach looks like $$$[s, \underline{1}, 0, i]$$$ at $$$t = 2$$$. Koa doesn't drown because $$$1 \le 1$$$.  At $$$t = 2$$$ Koa swims to $$$x = 2$$$, beach looks like $$$[s, 2, \underline{1}, i]$$$ at $$$t = 3$$$. Koa doesn't drown because $$$1 \le 1$$$.  At $$$t = 3$$$ Koa swims to $$$x = 3$$$, beach looks like $$$[s, 1, 0, \underline{i}]$$$ at $$$t = 4$$$.  At $$$t = 4$$$ Koa is at $$$x = 3$$$ and she made it! We can show that in test case $$$2$$$ Koa can't get to the island.

#!/usr/bin/perl

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

my $bg = 10000000000;

my $n;
my $k;
my $l;
my @d;

for( my $t_loop=0; $t_loop<$t; $t_loop++ ){

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

  #print ( join(":",@d) . "\n");

  my $i;
  for( $i=0; $i<$n; $i++){
    last if( $d[$i] > 0 );
  }
  if( $i<$n ){
    print "No\n"; next;
  }

  my $pr = -1;
  my $no = undef;
  for( $i=0; $i<$n; $i++){
    if( $d[$i] + $k <= 0 ){
      #print "d i =$d[$i] , k=$k\n";
      if( &sim($pr,$i) ){
        $no = 1;
        last;
      }
      $pr = $i;
    }
  }
  my $res = 'Yes';
  $res = 'No' if ( $no or &sim($pr,$n) );
  print "$res\n";
}

exit(0);

sub dd {
  my $idx = shift;
  return -$bg if $idx < 0 or $idx >= $n;
  return $d[$idx];
}

sub sim {
  my $i1 = shift;
  my $i2 = shift;
  #print "i1=$i1 , i2=$i2\n";

  return undef if ( $i2 == $i1 + 1 );

  my $dir = -1;
  my $i = $i1;
  my $adp = $k;

  while($i < $i2 - 1){
    $i++;
    my $cdp = - &dd($i);
    if( $dir == -1 ){
      $adp = &min( $cdp , $adp - 1 );
      $dir = 1 if $adp == 0;
    } else {
      $adp += 1;
      if( $adp > $k or $adp > $cdp ){
        return 1;
      }
    }
  }

  return undef;
}

sub min {
  my $x = shift; my $y = shift;
  return ( $x < $y ? $x : $y );
}


You are given three positive (i.e. strictly greater than zero) integers $$$x$$$, $$$y$$$ and $$$z$$$.Your task is to find positive integers $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$x = \max(a, b)$$$, $$$y = \max(a, c)$$$ and $$$z = \max(b, c)$$$, or determine that it is impossible to find such $$$a$$$, $$$b$$$ and $$$c$$$.You have to answer $$$t$$$ independent test cases. Print required $$$a$$$, $$$b$$$ and $$$c$$$ in any (arbitrary) order.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$, and $$$z$$$ ($$$1 \le x, y, z \le 10^9$$$).

For each test case, print the answer:   "NO" in the only line of the output if a solution doesn't exist;  or "YES" in the first line and any valid triple of positive integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^9$$$) in the second line. You can print $$$a$$$, $$$b$$$ and $$$c$$$ in any order.

#!/usr/bin/perl

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

for( my $t_loop=0; $t_loop<$t; $t_loop++ ){

  my @x = map { $_ - 0 } split(/\s+/,<STDIN>);
  $#x = 2;
  my @sx = sort { $b <=> $a } @x;

  if( $sx[0] != $sx[1] ){
    print "NO\n";
    next;
  }

  my $a = $sx[0];
  my $b = $sx[2];
  print "YES\n";
  print "$a $b $b\n";

}

exit(0);

chomp(my $t = <STDIN>);
print $t;
foreach (1..$t)
{
    my @a = split /\s+/, <STDIN>;
    my @x = sort { $b <=> $a } @a;
    if ($x[0] != $x[1])
    {
        print "NO\n";
    }
    else
    {
        my ($a, $b) = ($x[0], $x[2]);
        print "YES\n$a $b $b\n";
    }
}


The only difference between easy and hard versions are constraints on $$$n$$$ and $$$k$$$.You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $$$k$$$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $$$0$$$).Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.You (suddenly!) have the ability to see the future. You know that during the day you will receive $$$n$$$ messages, the $$$i$$$-th message will be received from the friend with ID $$$id_i$$$ ($$$1 \le id_i \le 10^9$$$).If you receive a message from $$$id_i$$$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.Otherwise (i.e. if there is no conversation with $$$id_i$$$ on the screen):  Firstly, if the number of conversations displayed on the screen is $$$k$$$, the last conversation (which has the position $$$k$$$) is removed from the screen.  Now the number of conversations on the screen is guaranteed to be less than $$$k$$$ and the conversation with the friend $$$id_i$$$ is not displayed on the screen.  The conversation with the friend $$$id_i$$$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $$$n$$$ messages.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 200)$$$ — the number of messages and the number of conversations your smartphone can show. The second line of the input contains $$$n$$$ integers $$$id_1, id_2, \dots, id_n$$$ ($$$1 \le id_i \le 10^9$$$), where $$$id_i$$$ is the ID of the friend which sends you the $$$i$$$-th message.

In the first line of the output print one integer $$$m$$$ ($$$1 \le m \le min(n, k)$$$) — the number of conversations shown after receiving all $$$n$$$ messages. In the second line print $$$m$$$ integers $$$ids_1, ids_2, \dots, ids_m$$$, where $$$ids_i$$$ should be equal to the ID of the friend corresponding to the conversation displayed on the position $$$i$$$ after receiving all $$$n$$$ messages.

NoteIn the first example the list of conversations will change in the following way (in order from the first to last message):  $$$[]$$$;  $$$[1]$$$;  $$$[2, 1]$$$;  $$$[3, 2]$$$;  $$$[3, 2]$$$;  $$$[1, 3]$$$;  $$$[1, 3]$$$;  $$$[2, 1]$$$. In the second example the list of conversations will change in the following way:  $$$[]$$$;  $$$[2]$$$;  $$$[3, 2]$$$;  $$$[3, 2]$$$;  $$$[1, 3, 2]$$$;  and then the list will not change till the end.

#!/usr/bin/env perl

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

chomp (my $line = <STDIN>);

my ($n, $k) = split q{ }, $line;

my @inputs = split q{ }, <STDIN>;

my $set = {};
my @answer = ();

for my $input ( @inputs ) {
    if ( defined $set->{$input} ) {
        next;
    }
    else {
        if ( @answer == $k ) {
            my $id = shift @answer;
            delete $set->{$id};
        }
        push @answer, $input;
        $set->{$input} = 1;
    }
}

say scalar @answer;
@answer = reverse @answer;
say "@answer";

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	@_ = split ' ', <>;

	my %h;
	my @q;

	for( @_ ){
		next if exists $h{ $_ };

		if( $k == @q ){
			my $del = shift @q;
			delete $h{ $del };
			}

		push @q, $_;
		$h{ $_ } = 1;
		}

	print ~~ @q;
	print join ' ', reverse @q;
	}

#!/usr/bin/env perl

my ($messages, $limit) = split /\s/, <>;
my @IDs   = split /\s/, <>;
my @shown = ();

for my $id (@IDs) {
    unless (grep { $_ == $id } @shown ) {
        pop @shown unless @shown < $limit;
        unshift @shown, $id;
    }
}

$\ = "\n";
print scalar @shown;
print join(" ", @shown);


There are $$$n$$$ rectangles in a row. You can either turn each rectangle by $$$90$$$ degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of rectangles. Each of the next $$$n$$$ lines contains two integers $$$w_i$$$ and $$$h_i$$$ ($$$1 \leq w_i, h_i \leq 10^9$$$) — the width and the height of the $$$i$$$-th rectangle.

Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].In the second test, there is no way the second rectangle will be not higher than the first one.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my $max = ~0;
	my $f = 0;

	for( 1 .. $_ ){
		my( $A, $B ) = sort { $b <=> $a } split ' ', <>;
		if( $A > $max ){ $A = $B; }
		if( $A > $max ){ $f ++; }
		$max = $A;
		}

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


You are given a permutation $$$a$$$ of size $$$n$$$ and you should perform $$$n$$$ operations on it. In the $$$i$$$-th operation, you can choose a non-empty suffix of $$$a$$$ and increase all of its elements by $$$i$$$. How can we perform the operations to minimize the number of inversions in the final array?Note that you can perform operations on the same suffix any number of times you want.A permutation of size $$$n$$$ is an array of size $$$n$$$ such that each integer from $$$1$$$ to $$$n$$$ occurs exactly once in this array. A suffix is several consecutive elements of an array that include the last element of the array. An inversion in an array $$$a$$$ is a pair of indices $$$(i, j)$$$ such that $$$i > j$$$ and $$$a_{i} < a_{j}$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of the array. The second line contains $$$n$$$ distinct integers $$$a_{1}, a_{2}, \dots, a_{n}$$$ ($$$1 \le a_i \le n$$$), the initial permutation $$$a$$$. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print $$$n$$$ integers $$$x_{1}, x_{2}, \ldots, x_{n}$$$ ($$$1 \le x_{i} \le n$$$ for each $$$1 \le i \le n$$$) indicating that the $$$i$$$-th operation must be applied to the suffix starting at index $$$x_{i}$$$. If there are multiple answers, print any of them.

NoteIn the first test case one of the optimal solutions is to increase the whole array on each operation (that is, choose the suffix starting at index $$$1$$$). The final array $$$[11, 12, 13, 14]$$$ contains $$$0$$$ inversions.In the second test case, $$$a$$$ will be equal to $$$[2, 4, 3, 5, 6]$$$, $$$[2, 4, 3, 7, 8]$$$, $$$[2, 4, 6, 10, 11]$$$, $$$[2, 8, 10, 14, 15]$$$ and $$$[7, 13, 15, 19, 20]$$$ after the first, second, third, fourth, and fifth operations, respectively. So the final array $$$a$$$ has zero inversions.


Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is negative, then the company suffered losses on the i-th day.Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the n days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (ai < 0), he loses his temper and his wrath is terrible.Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.Write a program that, given sequence ai, will print the minimum number of folders.

The first line contains integer n (1 ≤ n ≤ 100), n is the number of days. The second line contains a sequence of integers a1, a2, ..., an (|ai| ≤ 100), where ai means the company profit on the i-th day. It is possible that the company has no days with the negative ai.

Print an integer k — the required minimum number of folders. In the second line print a sequence of integers b1, b2, ..., bk, where bj is the number of day reports in the j-th folder. If there are multiple ways to sort the reports into k days, print any of them.

NoteHere goes a way to sort the reports from the first sample into three folders:  1 2 3 -4 -5 | -6 5 -5 | -6 -7 6 In the second sample you can put all five reports in one folder.

use strict;
use warnings;
<>;
my $s = <>;
chomp $s;
my @a = map int, split /\s/, $s;
my ($i, $c, $n) = (0, 0, 0);
my @answer = ();
for (@a) {
    if ($_ < 0) {
	if ($c == 2) {
	    push @answer, $i;
	    $n++;
	    $c = 1;
	    $i = 1;
	} else {
	    $c++;
	    $i++;
	}
    } else {
	$i++;
    }
}
push @answer, $i;
$n++;
print "$n\n@answer";


You are given a string $$$s$$$. You have to determine whether it is possible to build the string $$$s$$$ out of strings aa, aaa, bb and/or bbb by concatenating them. You can use the strings aa, aaa, bb and/or bbb any number of times and in any order.For example:  aaaabbb can be built as aa $$$+$$$ aa $$$+$$$ bbb;  bbaaaaabbb can be built as bb $$$+$$$ aaa $$$+$$$ aa $$$+$$$ bbb;  aaaaaa can be built as aa $$$+$$$ aa $$$+$$$ aa;  abab cannot be built from aa, aaa, bb and/or bbb.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 50$$$), consisting of characters a and/or b.

For each test case, print YES if it is possible to build the string $$$s$$$. Otherwise, print NO. You may print each letter in any case (for example, YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

8

aaaabbb

bbaaaaabbb

aaaaaa

abab

a

b

aaaab

bbaaa

NoteThe first four test cases of the example are described in the statement.

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

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

while( $testcase -- > 0 ){

  ( my $s = <STDIN> ) =~ s/[\x00-\x20]+$//ios;
  my $l = length($s);
  my $cn = 0;
  my $pr = '';
  my $res = 'YES';
  for(my $i=0;$i<$l;$i++){
    my $c1 = substr($s,$i,1);
    if( $pr ne $c1 ){
      if( $pr ne '' and $cn <= 1 ){
        $res = 'NO';
        last;
      }
      $cn = 1;
    } else {
      $cn++;
    }
    $pr = $c1;
  }
  $res = 'NO' if $res eq 'YES' and $cn <= 1;
  print "$res\n";
}

exit(0);

sub max {
  my $r = undef;
  foreach my $e (@_){  $r = $e if !defined($r) or $e > $r;  }
  return $r;
}
sub min {
  my $r = undef;
  foreach my $e (@_){  $r = $e if !defined($r) or $e < $r;  }
  return $r;
}
sub sum {
  my $r = 0;
  foreach my $e (@_){ $r += $e; }
  return $r;
}
sub ruisum {   # my @rui = (0); &ruisum(\@rui,\@array);
  my $r = shift; my $ar = shift;
  $#{$r} = 1+$#{$ar}; $r->[0] = 0; my $rr = 0;
  for(my $i=0;$i<=$#ar;$i++){
    $rr += $ar->[$i];
    $r->[1+$i] = $rr;
  }
}


You are given a string $$$s$$$, consisting only of characters '0' and '1'.You have to choose a contiguous substring of $$$s$$$ and remove all occurrences of the character, which is a strict minority in it, from the substring.That is, if the amount of '0's in the substring is strictly smaller than the amount of '1's, remove all occurrences of '0' from the substring. If the amount of '1's is strictly smaller than the amount of '0's, remove all occurrences of '1'. If the amounts are the same, do nothing.You have to apply the operation exactly once. What is the maximum amount of characters that can be removed?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The only line of each testcase contains a non-empty string $$$s$$$, consisting only of characters '0' and '1'. The length of $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the maximum amount of characters that can be removed after applying the operation exactly once.

NoteIn the first testcase, you can choose substrings "0", "1" or "01". In "0" the amount of '0' is $$$1$$$, the amount of '1' is $$$0$$$. '1' is a strict minority, thus all occurrences of it are removed from the substring. However, since there were $$$0$$$ of them, nothing changes. Same for "1". And in "01" neither of '0' or '1' is a strict minority. Thus, nothing changes. So there is no way to remove any characters.In the second testcase, you can choose substring "10101010101". It contains $$$5$$$ characters '0' and $$$6$$$ characters '1'. '0' is a strict minority. Thus, you can remove all its occurrences. There exist other substrings that produce the same answer.In the third testcase, you can choose substring "011000100". It contains $$$6$$$ characters '0' and $$$3$$$ characters '1'. '1' is a strict minority. Thus, you can remove all its occurrences.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;

	my $zero = () = m/0/g;
	my $one  = () = m/1/g;

	if( $zero > $one ){
		print 0 + $one;
		}
	elsif( $zero < $one ){
		print 0 + $zero;
		}
	else{
		print $zero - 1;
		}
	}


You are given an array $$$a$$$ of size $$$n$$$. Each element in this array is an integer between $$$1$$$ and $$$10^9$$$.You can perform several operations to this array. During an operation, you can replace an element in the array with any integer between $$$1$$$ and $$$10^9$$$. Output the minimum number of operations needed such that the resulting array doesn't contain any local maximums, and the resulting array after the operations.An element $$$a_i$$$ is a local maximum if it is strictly larger than both of its neighbors (that is, $$$a_i > a_{i - 1}$$$ and $$$a_i > a_{i + 1}$$$). Since $$$a_1$$$ and $$$a_n$$$ have only one neighbor each, they will never be a local maximum.

Each test contains multiple test cases. The first line will contain a single integer $$$t$$$ $$$(1 \leq t \leq 10000)$$$ — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ $$$(2 \leq n \leq 2 \cdot 10^5)$$$ — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots ,a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$, the elements of array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, first output a line containing a single integer $$$m$$$ — minimum number of operations required. Then ouput a line consist of $$$n$$$ integers — the resulting array after the operations. Note that this array should differ in exactly $$$m$$$ elements from the initial array. If there are multiple answers, print any.

NoteIn the first example, the array contains no local maximum, so we don't need to perform operations.In the second example, we can change $$$a_2$$$ to $$$3$$$, then the array don't have local maximums.


There are $$$n$$$ emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The $$$i$$$-th emote increases the opponent's happiness by $$$a_i$$$ units (we all know that emotes in this game are used to make opponents happy).You have time to use some emotes only $$$m$$$ times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than $$$k$$$ times in a row (otherwise the opponent will think that you're trolling him).Note that two emotes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that $$$a_i = a_j$$$ are considered different.You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.

The first line of the input contains three integers $$$n, m$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le m \le 2 \cdot 10^9$$$) — the number of emotes, the number of times you can use emotes and the maximum number of times you may use the same emote in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is value of the happiness of the $$$i$$$-th emote.

Print one integer — the maximum opponent's happiness if you use emotes in a way satisfying the problem statement.

NoteIn the first example you may use emotes in the following sequence: $$$4, 4, 5, 4, 4, 5, 4, 4, 5$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my( $max, $smax) = ( sort { $b <=> $a } @_ )[ 0, 1 ];

	my $int = int $m / ( $k + 1 );
	$m -= $int * ( $k + 1 );

	print $int * ( $k * $max + $smax ) + $m * $max;
	}


Vasya has a multiset $$$s$$$ consisting of $$$n$$$ integer numbers. Vasya calls some number $$$x$$$ nice if it appears in the multiset exactly once. For example, multiset $$$\{1, 1, 2, 3, 3, 3, 4\}$$$ contains nice numbers $$$2$$$ and $$$4$$$.Vasya wants to split multiset $$$s$$$ into two multisets $$$a$$$ and $$$b$$$ (one of which may be empty) in such a way that the quantity of nice numbers in multiset $$$a$$$ would be the same as the quantity of nice numbers in multiset $$$b$$$ (the quantity of numbers to appear exactly once in multiset $$$a$$$ and the quantity of numbers to appear exactly once in multiset $$$b$$$).

The first line contains a single integer $$$n~(2 \le n \le 100)$$$. The second line contains $$$n$$$ integers $$$s_1, s_2, \dots s_n~(1 \le s_i \le 100)$$$ — the multiset $$$s$$$.

If there exists no split of $$$s$$$ to satisfy the given requirements, then print "NO" in the first line. Otherwise print "YES" in the first line. The second line should contain a string, consisting of $$$n$$$ characters. $$$i$$$-th character should be equal to 'A' if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$a$$$ and 'B' if if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$b$$$. Elements are numbered from $$$1$$$ to $$$n$$$ in the order they are given in the input. If there exist multiple solutions, then print any of them.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my %h;

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

	my %ones;
	my %twos;
	my %mores;

	for( keys %h ){
		if( $h{ $_ } == 1 ){
			$ones{ $_ } = 1;
			}
		elsif( $h{ $_ } == 2 ){
			$twos{ $_ } = 1;
			}
		else{
			$mores{ $_ } = 1;
			}
		}

	my %convert;

	for( keys %twos ){
		$convert{ $_ } = 'A';
		}

	for( keys %mores ){
		$convert{ $_ } = 'A';
		}

	if( ( keys %ones ) % 2 == 1 and 0 == keys %mores ){
		print "NO";
		}
	else{
		if( ( keys %ones ) % 2 == 1 ){
			my $to_split = ( sort { $a <=> $b } keys %mores )[ 0 ];

			for( @_ ){
				$_ == $to_split and do { $_ = 0 ; last; };
				}
			$ones{ 0 } = 1;
			}

		my @ones = ( sort { $a <=> $b } keys %ones );

		for my $i ( 0 .. @ones - 1 ){
			$convert{ $ones[ $i ] } = $i % 2 ? 'A' : 'B';
			}

		my $ans = '';

		for( @_ ){
			$ans .= $convert{ $_ };
			}

		print "YES";
		print $ans;
		}

	}


A permutation is a sequence of $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ are permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ are not.Polycarp was presented with a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. However, when Polycarp came home, he noticed that in his pocket, the permutation $$$p$$$ had turned into an array $$$q$$$ according to the following rule:   $$$q_i = \max(p_1, p_2, \ldots, p_i)$$$. Now Polycarp wondered what lexicographically minimal and lexicographically maximal permutations could be presented to him.An array $$$a$$$ of length $$$n$$$ is lexicographically smaller than an array $$$b$$$ of length $$$n$$$ if there is an index $$$i$$$ ($$$1 \le i \le n$$$) such that the first $$$i-1$$$ elements of arrays $$$a$$$ and $$$b$$$ are the same, and the $$$i$$$-th element of the array $$$a$$$ is less than the $$$i$$$-th element of the array $$$b$$$. For example, the array $$$a=[1, 3, 2, 3]$$$ is lexicographically smaller than the array $$$b=[1, 3, 4, 2]$$$.For example, if $$$n=7$$$ and $$$p=[3, 2, 4, 1, 7, 5, 6]$$$, then $$$q=[3, 3, 4, 4, 7, 7, 7]$$$ and the following permutations could have been as $$$p$$$ initially:   $$$[3, 1, 4, 2, 7, 5, 6]$$$ (lexicographically minimal permutation);  $$$[3, 1, 4, 2, 7, 6, 5]$$$;  $$$[3, 2, 4, 1, 7, 5, 6]$$$;  $$$[3, 2, 4, 1, 7, 6, 5]$$$ (lexicographically maximum permutation). For a given array $$$q$$$, find the lexicographically minimal and lexicographically maximal permutations that could have been originally presented to Polycarp.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$q_1, q_2, \ldots, q_n$$$ ($$$1 \le q_i \le n$$$). It is guaranteed that the array $$$q$$$ was obtained by applying the rule from the statement to some permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output two lines:    on the first line output $$$n$$$ integers — lexicographically minimal permutation that could have been originally presented to Polycarp;  on the second line print $$$n$$$ integers — lexicographically maximal permutation that could have been originally presented to Polycarp;

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	@_ = split ' ', <>;

	$debug and print "[@_]";

	my %maxes;

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

	my %cycle;

	exists $maxes{ $_ } or $cycle{ $_ } ++ for 1 .. @_;

	my @cycle = sort { $a <=> $b } keys %cycle;

	$debug and print "[@cycle]";

	my @copy_cycle = @cycle;

	my @lex_min;

	my %used;

	for( @_ ){
		if( exists $used{ $_ } ){
			push @lex_min, shift @copy_cycle;
			}
		else{
			push @lex_min, $_;
			$used{ $_ } ++;
			}
		}

	print "@lex_min";

	my @r_cycle = reverse @cycle;

	my @lex_max;

	%used = ();

	for( @_ ){
		$debug and print "  [$_][@r_cycle]";

		if( exists $used{ $_ } ){
			while( 1 ){
				my $cand = shift @r_cycle;
				if( $cand > $_ ){
					push @r_cycle, $cand;
					}
				else{
					push @lex_max, $cand;
					last;
					}
				}
			}
		else{
			push @lex_max, $_;
			$used{ $_ } ++;

			my $c = @r_cycle;

			next if @r_cycle < 2;

			while( $r_cycle[ 0 ] < $r_cycle[ -1 ] and $r_cycle[ -1 ] < $_ ){
				unshift @r_cycle, pop @r_cycle;
				last if $c -- < 0;
				}
			}
		}

	print "@lex_max";
	}

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	@_ = split ' ', <>;

	$debug and print "[@_]";

	my %maxes;

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

	my %cycle;

	exists $maxes{ $_ } or $cycle{ $_ } ++ for 1 .. @_;

	my @cycle = sort { $a <=> $b } keys %cycle;

	$debug and print "[@cycle]";

	my @copy_cycle = @cycle;

	my @lex_min;

	my %used;

	for( @_ ){
		if( exists $used{ $_ } ){
			push @lex_min, shift @copy_cycle;
			}
		else{
			push @lex_min, $_;
			$used{ $_ } ++;
			}
		}

	print "@lex_min";

	my @r_cycle = reverse @cycle;

	my @lex_max;

	%used = ();

	my $prev_max = 1;
	my @r_array;

	for( @_ ){
		if( exists $used{ $_ } ){
			my $cand;
			while( 1 ){
				$cand = shift @r_array;
				if( exists $maxes{ $cand } ){
					next;
					}
				last;
				}
			push @lex_max, $cand;
			}
		else{
			push @r_array, reverse $prev_max .. $_;
			$prev_max = $_;
			push @lex_max, $_;
			$used{ $_ } ++;
			}
		}

	print "@lex_max";
	}

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	@_ = split ' ', <>;

	$debug and print "[@_]";

	my %maxes;

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

	my %cycle;

	exists $maxes{ $_ } or $cycle{ $_ } ++ for 1 .. @_;

	my @cycle = sort { $a <=> $b } keys %cycle;

	$debug and print "[@cycle]";

	my @copy_cycle = @cycle;

	my @lex_min;

	my %used;

	for( @_ ){
		if( exists $used{ $_ } ){
			push @lex_min, shift @copy_cycle;
			}
		else{
			push @lex_min, $_;
			$used{ $_ } ++;
			}
		}

	print "@lex_min";

	my @r_cycle = reverse @cycle;

	my @lex_max;

	%used = ();

	for( @_ ){
		if( exists $used{ $_ } ){
			while( 1 ){
				my $cand = shift @r_cycle;
				if( $cand > $_ ){
					push @r_cycle, $cand;
					}
				else{
					push @lex_max, $cand;
					last;
					}
				}
			}
		else{
			push @lex_max, $_;
			$used{ $_ } ++;
			}
		}

	print "@lex_max";
	}


To celebrate your birthday you have prepared a festive table! Now you want to seat as many guests as possible.The table can be represented as a rectangle with height $$$h$$$ and width $$$w$$$, divided into $$$h \times w$$$ cells. Let $$$(i, j)$$$ denote the cell in the $$$i$$$-th row and the $$$j$$$-th column of the rectangle ($$$1 \le i \le h$$$; $$$1 \le j \le w$$$).Into each cell of the table you can either put a plate or keep it empty.As each guest has to be seated next to their plate, you can only put plates on the edge of the table — into the first or the last row of the rectangle, or into the first or the last column. Formally, for each cell $$$(i, j)$$$ you put a plate into, at least one of the following conditions must be satisfied: $$$i = 1$$$, $$$i = h$$$, $$$j = 1$$$, $$$j = w$$$.To make the guests comfortable, no two plates must be put into cells that have a common side or corner. In other words, if cell $$$(i, j)$$$ contains a plate, you can't put plates into cells $$$(i - 1, j)$$$, $$$(i, j - 1)$$$, $$$(i + 1, j)$$$, $$$(i, j + 1)$$$, $$$(i - 1, j - 1)$$$, $$$(i - 1, j + 1)$$$, $$$(i + 1, j - 1)$$$, $$$(i + 1, j + 1)$$$.Put as many plates on the table as possible without violating the rules above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each of the following $$$t$$$ lines describes one test case and contains two integers $$$h$$$ and $$$w$$$ ($$$3 \le h, w \le 20$$$) — the height and the width of the table.

For each test case, print $$$h$$$ lines containing $$$w$$$ characters each. Character $$$j$$$ in line $$$i$$$ must be equal to $$$1$$$ if you are putting a plate into cell $$$(i, j)$$$, and $$$0$$$ otherwise. If there are multiple answers, print any. All plates must be put on the edge of the table. No two plates can be put into cells that have a common side or corner. The number of plates put on the table under these conditions must be as large as possible. You are allowed to print additional empty lines.

NoteFor the first test case, example output contains the only way to put $$$6$$$ plates on the table.For the second test case, there are many ways to put $$$4$$$ plates on the table, example output contains one of them.Putting more than $$$6$$$ plates in the first test case or more than $$$4$$$ plates in the second test case is impossible.


Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Roma's got n positive integers. He wonders, how many of those integers have not more than k lucky digits? Help him, write the program that solves the problem.

The first line contains two integers n, k (1 ≤ n, k ≤ 100). The second line contains n integers ai (1 ≤ ai ≤ 109) — the numbers that Roma has.  The numbers in the lines are separated by single spaces.

In a single line print a single integer — the answer to the problem.

NoteIn the first sample all numbers contain at most four lucky digits, so the answer is 3.In the second sample number 447 doesn't fit in, as it contains more than two lucky digits. All other numbers are fine, so the answer is 2.

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

my ($n, $k) = map int, split '\D', <>;
my @numbers = map int, split '\D', <>;

my $answer = 0;

for (@numbers) {
    if ($_ =~ tr/[47]/L/ <= $k) {
	$answer++;
    }
}

print "$answer\n";

#!/usr/bin/perl

$ans = 0;

@str1 = split(' ', <STDIN>);

$n = @str1[0];
$k = @str1[1];

@str2 = split(' ', <STDIN>);

for my $now (@str2) {
    $counter = 0;
    while($now > 0) {
        $digit = $now % 10;
        if($digit == 4 || $digit == 7) {
            $counter += 1;
        }
        $now /= 10;
    }
    if($counter <= $k) {
        $ans += 1;
    }
}

print $ans;


While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s.  He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k messages in his own bag, each was a palindrome string and all those strings had the same length.He asked you to help him and tell him if he has worn his own back-bag. Check if the given string s is a concatenation of k palindromes of the same length.

The first line of input contains string s containing lowercase English letters (1 ≤ |s| ≤ 1000). The second line contains integer k (1 ≤ k ≤ 1000).

Print "YES"(without quotes) if he has worn his own back-bag or "NO"(without quotes) otherwise.

NotePalindrome is a string reading the same forward and backward.In the second sample, the faxes in his back-bag can be "saddas" and "tavvat".

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

chomp($line = <>);
$len = length $line;
@a = split //, $line;
chomp($k = <>);
$len%$k>0 and say "NO" and exit;
$l = $len / $k;
for ($b=0,$e=$l; $b<$len; $b=$e,$e+=$l) {
	for ($i=$b,$j=$e-1; $i<$j; ++$i,--$j) {
		$a[$i] ne $a[$j] and say "NO" and exit;
	}
}
say "YES";

chomp($s = <>);
chomp($k = <>);
($i, $mark) = (0, 1);
$len = length $s;
$mark = 0 if $len % $k != 0;
while ($mark == 1 && $i < $len) {
	$su = substr($s, $i, $len / $k);
	$mark = 0 unless ($su eq reverse $su);
	$i += $len / $k;
}
print qw(NO YES)[$mark == 1];

chomp($s = <>);
chomp($k = <>);
$i = 0;
$mark = 1;
$len = length $s;
$mark = 0 if $len % $k != 0;
while ($mark == 1 && $i < $len)
{
	$su = substr($s, $i, $len / $k);
	$mark = 0 unless ($su eq reverse $su);
	$i += $len / $k;
}
$mark == 1 ? print "YES" : print "NO";
print "\n";

use integer;
while(<>){
	chomp;
	$n = <>;
	$m = (length) / $n;
	$re = '.' x $m;
	$rq = qr/$re/;
	$i = $j = 0;
	while(/$rq/g){
		$i ++;
		$j += $& eq reverse $&;
		}
	print qw(NO YES)[$i == $n && $j == $n && $m * $n == length]
	}

chomp($s = <>);
chomp($k = <>);
$i = 0;
$mark = 1;
$len = length $s;
$mark = 0 if $len % $k != 0;
while ($mark == 1 && $i < length $s)
{
	$su = substr($s, 0, (length $s) / $k);
	$mark = 0 unless ($su eq reverse $su);
	$i += length $s / $k;
}
$mark == 1 ? print "YES" : print "NO";
print "\n";

chomp($s = <>);
chomp($k = <>);
$i = 0;
$mark = 1;
while ($i < length $s)
{
	$su = substr($s, 0, (length $s) / $k);
	$mark = 0 unless ($su eq reverse $su);
	$i += length $s / $k;
}
$mark == 1 ? print "YES" : print "NO";
print "\n";


Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,  - 2, 1, 3,  - 4. Suppose the mother suggested subarrays (1,  - 2), (3,  - 4), (1, 3), (1,  - 2, 1, 3). Then if the girl chooses the third and the fourth subarrays then:   the first flower adds 1·1 = 1 to the girl's happiness, because he is in one of chosen subarrays,  the second flower adds ( - 2)·1 =  - 2, because he is in one of chosen subarrays,  the third flower adds 1·2 = 2, because he is in two of chosen subarrays,  the fourth flower adds 3·2 = 6, because he is in two of chosen subarrays,  the fifth flower adds ( - 4)·0 = 0, because he is in no chosen subarrays. Thus, in total 1 + ( - 2) + 2 + 6 + 0 = 7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moods — n integers a1, a2, ..., an ( - 100 ≤ ai ≤ 100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1 ≤ li ≤ ri ≤ n) denoting the subarray a[li], a[li + 1], ..., a[ri]. Each subarray can encounter more than once.

Print single integer — the maximum possible value added to the Alyona's happiness.

NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.

use strict;
use warnings;

my ($n,$m)=split / /,<>;
chomp($n,$m);
my @d=split / /,<>;
chomp(@d);
my @sums;
my $ans=0;
while($m--)
{
  my ($s,$e)=split / /,<>;
  chomp($s,$e);
  push(@sums,sum($s,$e,\@d));
}

for my $val (@sums)
{
  $ans=max_($ans,$ans+$val);
}

print $ans . "\n";

sub sum{
  my $si=shift;
  my $ei=shift;
  my $arr=shift;
  my $aa=0;
  for(my $i=$si-1;$i<$ei;$i++)
  {
    $aa+=$arr->[$i];
  }
  return $aa;
}

sub min_{
	return $_[0] > $_[1] ? $_[1] : $_[0];
}

sub max_{
	return $_[1] > $_[0] ? $_[1] : $_[0];
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){

	my( $n, $m ) = split;

	@_ = split ' ', <>;

	print 0 + eval join '+', grep !/-/, map {
			0 + eval join '+', map "($_)",
			@_[ eval join '..', map $_ - 1, split ' ', <> ]
		} 1 .. $m;

	}


Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half.  English alphabet You are given a string s. Check if the string is "s-palindrome".

The only line contains the string s (1 ≤ |s| ≤ 1000) which consists of only English letters.

Print "TAK" if the string s is "s-palindrome" and "NIE" otherwise.

chomp,
(substr $_, substr $_, 0, (length) / 2,
(substr $_, 0, (length) / 2) =~ y/bdpq/dbqp/r),
( (length) % 2 and (substr $_, (length) / 2, 1) =~ /[bdpq]/ and $_ = 'a' ),
print qw(NIE TAK)[ !/[^ovwxAHIMOT-Ybdpq]/ * ($_ eq reverse) ]
for <>

chomp, print qw(NIE TAK)[ !/[^ovwxAHIMOT-Y]/ * ($_ eq reverse) ] for <>

chomp,
(substr $_, substr $_, 0, (length) / 2,
(substr $_, 0, (length) / 2) =~ y/bdpq/dbqp/r),
print qw(NIE TAK)[ !/[^ovwxAHIMOT-Ybdpq]/ * ($_ eq reverse) ] for <>

chomp,
(substr $_, substr $_, 0, (length) / 2,
(substr $_, 0, (length) / 2) =~ y/bdpq/dbqp/r),
( (length) % 2 and (substr $_, 0, (length) / 2 + 1) =~ /[bdpq]/ and $_ = 'a' ),
print qw(NIE TAK)[ !/[^ovwxAHIMOT-Ybdpq]/ * ($_ eq reverse) ]
for <>


Alyona has recently bought a miniature fridge that can be represented as a matrix with $$$h$$$ rows and $$$2$$$ columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part.  An example of a fridge with $$$h = 7$$$ and two shelves. The shelves are shown in black. The picture corresponds to the first example. Alyona has $$$n$$$ bottles of milk that she wants to put in the fridge. The $$$i$$$-th bottle is $$$a_i$$$ cells tall and $$$1$$$ cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can not put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.Alyona is interested in the largest integer $$$k$$$ such that she can put bottles $$$1$$$, $$$2$$$, ..., $$$k$$$ in the fridge at the same time. Find this largest $$$k$$$.

The first line contains two integers $$$n$$$ and $$$h$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le h \le 10^9$$$) — the number of bottles and the height of the fridge. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le h$$$) — the heights of the bottles.

Print the single integer $$$k$$$ — the maximum integer such that Alyona can put the bottles $$$1$$$, $$$2$$$, ..., $$$k$$$ in the fridge at the same time. If Alyona can put all bottles in the fridge, print $$$n$$$. It is easy to see that Alyona can always put at least one bottle in the fridge.

NoteOne of optimal locations in the first example is shown on the picture in the statement.One of optimal locations in the second example is shown on the picture below.  One of optimal locations in the third example is shown on the picture below.


Little Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers S that has the following properties:  for all x  the following inequality holds l ≤ x ≤ r;  1 ≤ |S| ≤ k;  lets denote the i-th element of the set S as si; value  must be as small as possible. Help Victor find the described set.

The first line contains three space-separated integers l, r, k (1 ≤ l ≤ r ≤ 1012; 1 ≤ k ≤ min(106, r - l + 1)).

Print the minimum possible value of f(S). Then print the cardinality of set |S|. Then print the elements of the set in any order. If there are multiple optimal sets, you can print any of them.

NoteOperation  represents the operation of bitwise exclusive OR. In other words, it is the XOR operation.


Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.  Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.

The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.

On the single line of the output print the number of groups of magnets.

NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.

#!/usr/bin/perl

use 5.012;
use warnings;

chomp(my $n = <>);
my $last;
my $groups = 1;
while ($n--) {
	use integer;
	chomp(my $m = <>);
	my $first = $m / 10;
	$groups++ if defined $last && $last eq $first;
	$last = $m % 10;
}
print $groups;

#!/usr/bin/perl

$n = <> + 0;
$groups = 1;
$previous = <>;

for ($i = 0; $i < ($n-1); $i++) {
    $magnet = <>;
    if ($magnet ne $previous) {
        $groups++;
    }

    $previous = $magnet;
}

print "$groups\n";

chomp($n=<>);
my $pre = "";
while (<>) {
	chomp;
	++$cnt if $_ != $pre;
	$pre = $_;
}
print "$cnt\n";

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

chomp($t = <>);
my $ans = 0;
while (<>) {
	chomp;
	$_ ne $s and $ans++;
	$s = $_;
}
say $ans;

#!/usr/bin/perl -w

use strict;

my $n = <>;
my $cur = '00';
my $g = 0;

for (1..$n) {
    my $s = <>;
    if ($s ne $cur) {
        $g++;
        $cur = $s;
    }
}

print $g, "\n";

#!/usr/bin/perl

#  Copyright 2013 Anton Leontiev <bunder@t-25.ru>
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are
#  met:
#
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above
#    copyright notice, this list of conditions and the following disclaimer
#    in the documentation and/or other materials provided with the
#    distribution.
#  * Neither the name of the  nor the names of its
#    contributors may be used to endorse or promote products derived from
#    this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

use v5.12;
use warnings;
use English qw(-no_match_vars);

$OUTPUT_FIELD_SEPARATOR = " ";

my $num = <>;
my $last = '';
my $islands;

map { $islands++, $last = $_ if $last ne $_ } <>;

say $islands;

#!/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 $latest_token = read_token;

my $answer = 1;

for (1..$n-1) {
    my $token = read_token;
    if ($latest_token ne $token) {
        $answer++;
        $latest_token = $token;
    }
}

say $answer;

$n = <>;
while ($n--) {
  $now = <>;
  $groups += $now != $last;
  $last = $now;
}
print "$groups\n";

#!/usr/bin/perl

use strict;
chomp(my $tc = <>);

my $ans = 1;
chomp(my $now = <>);
my $temp = $now;

for( my $i = 1; $i<$tc ;$i++){
	chomp($now = <>);
	if($now != $temp){
		$ans++;
	}
	$temp = $now
}
print $ans;

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

my $last = 'x';
my $number = 0;

my $n = <>;
foreach (1..$n)
{
    my $piece = <>;
    chomp $piece;
    if ($last eq 'x')
    {
        $number++;
    }
    elsif ($last eq substr($piece, 0, 1))
    {
        $number++;
    }
    $last = substr($piece, -1);
}

print $number;

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

$t=<>;
while (<>){
	$t!=$_ and $c++;
	$t=$_;
	}
print $c+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
}

my $num = <>;
chomp $num;
my $count = 1;
my $magnet = <>;
for (2..$num) {
    $next = <>;
    if (!($magnet eq $next)) {
        $count++;
        $magnet = $next;
    }
}
print $count;

chomp($n=<>);
my $pre = "";
while (<>) {
	chomp;
	$cnt++ if $_ == $pre;
	$pre = $_;
}
print "$cnt\n";

#!/usr/bin/perl

use strict;
chomp(my $tc = <>);

my $ans = 1;
chomp(my $now = <>);
my @arr = split("", $now);
my $temp = $arr[1];

for( my $i = 1; $i<$tc ;$i++){
	chomp(my $now = <>);
	@arr = split("", $now);
	if($arr[0] == $temp){
		$ans++;
	}
	else{
		$temp = $arr[1];
	}
}
print $ans;

#!/usr/bin/perl

use strict;
chomp(my $tc = <>);

my $ans = 1;
chomp(my $now = <>);
my $temp = $now;

for( my $i = 1; $i<$tc ;$i++){
	chomp(my $now = <>);
	if($now == $temp){
		$ans++;
	}
	else{
		$temp = $now;
	}
}
print $ans;


Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≤ ti ≤ 10). Of course, one number can be assigned to any number of customers."Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1,  - 1, 1,  - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.Of course, a client can't form a couple with him/herself.

The first line of the input data contains an integer n (1 ≤ n ≤ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 ≤ ti ≤ 10), ti — is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.

Print the number of couples of customs with opposite t. The opposite number for x is number  - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

NoteIn the first sample the couples of opposite clients are: (1,2), (1,5) и (3,4).In the second sample any couple of clients is opposite.

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

<>;
$_=<>;
s/-?\d+/$_[$&+10]++/eg;
for (1..10){
	$ats += $_[10-$_]*$_[10+$_]
	}
$ats += $_[10]*($_[10]-1)/2;
print $ats;

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

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

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

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

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

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

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

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

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

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

#!/usr/bin/perl

$PI=3.14159265358979323846;
$MOD=1000000007;

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

<>;
$_=<>;
$_[20]=0;
s/-?\d+/$_[$&]++/eg;
for (1..10){
	$ats += $_[-$_]*$_[$_]
	}
$ats += $_[0]*($_[0]-1)/2;
print $ats;

#***********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
}


You are given an array $$$a$$$ of $$$n$$$ elements. You can apply the following operation to it any number of times:  Select some subarray from $$$a$$$ of even size $$$2k$$$ that begins at position $$$l$$$ ($$$1\le l \le l+2\cdot{k}-1\le n$$$, $$$k \ge 1$$$) and for each $$$i$$$ between $$$0$$$ and $$$k-1$$$ (inclusive), assign the value $$$a_{l+k+i}$$$ to $$$a_{l+i}$$$. For example, if $$$a = [2, 1, 3, 4, 5, 3]$$$, then choose $$$l = 1$$$ and $$$k = 2$$$, applying this operation the array will become $$$a = [3, 4, 3, 4, 5, 3]$$$.Find the minimum number of operations (possibly zero) needed to make all the elements of the array equal.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array. The second line of each test case consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case — the minimum number of operations needed to make equal all the elements of the array with the given operation.

NoteIn the first test, all elements are equal, therefore no operations are needed.In the second test, you can apply one operation with $$$k=1$$$ and $$$l=1$$$, set $$$a_1 := a_2$$$, and the array becomes $$$[1, 1]$$$ with $$$1$$$ operation.In the third test, you can apply one operation with $$$k=1$$$ and $$$l=4$$$, set $$$a_4 := a_5$$$, and the array becomes $$$[4, 4, 4, 4, 4]$$$.In the fourth test, you can apply one operation with $$$k=1$$$ and $$$l=3$$$, set $$$a_3 := a_4$$$, and the array becomes $$$[4, 2, 3, 3]$$$, then you can apply another operation with $$$k=2$$$ and $$$l=1$$$, set $$$a_1 := a_3$$$, $$$a_2 := a_4$$$, and the array becomes $$$[3, 3, 3, 3]$$$.In the fifth test, there is only one element, therefore no operations are needed.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	@_ = reverse @_;

	my $first = shift @_;

	my $len = 1;

	my $ans = 0;

	while( @_ ){
		if( $_[ 0 ] == $first ){
			shift @_;
			$len ++;
			}
		else{
			$ans ++;
			for my $j ( 1 .. $len ){
				last if not @_;
				shift @_;
				$len ++;
				}
			}
		}

	print $ans;
	}


Vanya is doing his maths homework. He has an expression of form , where x1, x2, ..., xn are digits from 1 to 9, and sign  represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.

The first line contains expression s (1 ≤ |s| ≤ 5001, |s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs  +  and  * .  The number of signs  *  doesn't exceed 15.

In the first line print the maximum possible value of an expression.

NoteNote to the first sample test. 3 + 5 * (7 + 8) * 4 = 303.Note to the second sample test. (2 + 3) * 5 = 25.Note to the third sample test. (3 * 4) * 5 = 60 (also many other variants are valid, for instance, (3) * 4 * 5 = 60).

$_ = <>; # readline
s/(^|\*)\K/ $pre_match = $`, ($post_match = $') =~ s!(?=\*)|$! $hash{eval "$pre_match($`)$'"} = "$pre_match($`)$'", '' !ge, '' /ge;

use bigint;
print eval $hash{ (sort {$b <=> $a} keys %hash)[0] }


You are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters.Your task is to add spaces to the text by the following rules:  if there is no punctuation mark between two words, then they should be separated by exactly one space  there should be no spaces before each punctuation mark  there should be exactly one space after each punctuation mark It is guaranteed that there is at least one word between any two punctuation marks. The text begins and ends with a Latin letter.

The input data contains of a single non-empty line — the text whose length is no more than 10000 characters.

Print the text, edited according to the rules. In this problem you should follow the output format very strictly. For example, extra space at the end of the output line is considered as wrong answer. Note that a newline character at the end of the line doesn't matter.

galileo galilei was an   italian physicist  ,mathematician,astronomer

galileo galilei was an italian physicist, mathematician, astronomer

#!/usr/bin/env perl
package Codeforces::Task::_;
use v5.10;
use strict;
use warnings;

sub min{my($a,$b)=@_;if($a<$b){return$a;}else{return$b;}}
sub max{my($a,$b)=@_;if($a>$b){return$a;}else{return$b;}}
sub out{foreach my$c(@_){print"$c ";}print("\n");}

sub solve {
    my $s = <>;
    $s =~ s/( )+/ /g;
    $s =~ s/ ?([\.,!\?]) ?/$1 /g;
    say $s;
}

sub main {
    my $t = 1;
#    $t = int(<>);
    while ($t--) {
        solve();
    }
    return 0;
}

exit(main(@ARGV));

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

my $str = <>;

# Clear text
$str =~ s/\s+/ /g;
$str =~ s/\s*([?,.!])\s*/$1 /g;

print $str;

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

my $str = <>;

# Clear text
$str =~ s/\s+/ /g;
$str =~ s/\s([.,!?:;])/$1/g;
$str =~ s/([.,!?:;])/$1 /g;

print $str, "\n";

#!/usr/bin/perl -w
# Почему не работает-то?
while (<STDIN>)
{
    s/\s+/ /g;
    s/\s*([?,.!])\s*/$1 /g;

    print $_, "\n";
}

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

my $str = <>;

# Clear text
$str =~ s/\s+/ /g;
$str =~ s/\s([.,!?:;])/$1/g;
$str =~ s/([.,!?:;])/$1 /g;
$str =~ s/\s+/ /g;

print $str, "\n";

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

my $str = <>;

# Clear text
$str =~ s/\s+/ /g;
$str =~ s/\s*([?,.!])\s*/$1 /g;

print $str, "\n";


New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $$$h$$$ hours and $$$m$$$ minutes, where $$$0 \le hh < 24$$$ and $$$0 \le mm < 60$$$. We use 24-hour time format!Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows $$$0$$$ hours and $$$0$$$ minutes.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1439$$$) — the number of test cases. The following $$$t$$$ lines describe test cases. The $$$i$$$-th line contains the time as two integers $$$h$$$ and $$$m$$$ ($$$0 \le h < 24$$$, $$$0 \le m < 60$$$). It is guaranteed that this time is not a midnight, i.e. the following two conditions can't be met at the same time: $$$h=0$$$ and $$$m=0$$$. It is guaranteed that both $$$h$$$ and $$$m$$$ are given without leading zeros.

For each test case, print the answer on it — the number of minutes before the New Year.

#!/usr/bin/env perl
package Codeforces::Task::A;
use v5.10;
use strict;
use warnings;

sub min {
    my ($a, $b) = @_;
    if ($a < $b) {
		return $a;
	} else {
        return $b;
    }
}
sub max {
    my ($a, $b) = @_;
    if ($a > $b) {
        return $a;
    } else {
        return $b;
    }
}

sub solve {
    my ($h, $m) = map(int, split(" ", <>));
    print 24 * 60 - $m - 60 * $h, "\n";
}

sub main {
    my $t = 1;
    $t = int(<>);
    while ($t--) {
        solve();
    }
    return 0;
}

exit(main(@ARGV));

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	my( $h, $min ) = split;

	print 24 * 60 - ( $h * 60 + $min );
	}


Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3 × 5 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3 × 5 table is 15 + 8 + 3 = 26.

The first line of the input contains a single integer x (1 ≤ x ≤ 1018) — the number of squares inside the tables Spongebob is interested in.

First print a single integer k — the number of tables with exactly x distinct squares inside. Then print k pairs of integers describing the tables. Print the pairs in the order of increasing n, and in case of equality — in the order of increasing m.

NoteIn a 1 × 2 table there are 2 1 × 1 squares. So, 2 distinct squares in total.  In a 2 × 3 table there are 6 1 × 1 squares and 2 2 × 2 squares. That is equal to 8 squares in total.


Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit ≠ ermit).Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):   Clerihew (aabb);  Alternating (abab);  Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.

The first line contains two integers n and k (1 ≤ n ≤ 2500, 1 ≤ k ≤ 5) — the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.

Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.

2 1
day
may
sun
fun
test
hill
fest
thrill

NoteIn the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".


A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordinary sorting problem, but we can make it more interesting by adding nondeterministic element. There are n people, each person will use either his/her first name or last name as a handle. Can the lexicographical order of the handles be exactly equal to the given permutation p?More formally, if we denote the handle of the i-th person as hi, then the following condition must hold: .

The first line contains an integer n (1 ≤ n ≤ 105) — the number of people. The next n lines each contains two strings. The i-th line contains strings fi and si (1 ≤ |fi|, |si| ≤ 50) — the first name and last name of the i-th person. Each string consists only of lowercase English letters. All of the given 2n strings will be distinct. The next line contains n distinct integers: p1, p2, ..., pn (1 ≤ pi ≤ n).

If it is possible, output "YES", otherwise output "NO".

3
gennady korotkevich
petr mitrichev
gaoyuan chen
1 2 3

3
gennady korotkevich
petr mitrichev
gaoyuan chen
3 1 2

2
galileo galilei
nicolaus copernicus
2 1

10
rean schwarzer
fei claussell
alisa reinford
eliot craig
laura arseid
jusis albarea
machias regnitz
sara valestin
emma millstein
gaius worzel
1 2 3 4 5 6 7 8 9 10

10
rean schwarzer
fei claussell
alisa reinford
eliot craig
laura arseid
jusis albarea
machias regnitz
sara valestin
emma millstein
gaius worzel
2 4 9 6 5 7 1 3 8 10

NoteIn example 1 and 2, we have 3 people: tourist, Petr and me (cgy4ever). You can see that whatever handle is chosen, I must be the first, then tourist and Petr must be the last.In example 3, if Copernicus uses "copernicus" as his handle, everything will be alright.

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

chomp (my $n = <>);

my @names = (q/junk/);
while (<>) {
    chomp;
    push @names, $_;
}
my @order = split /\s+/, pop @names;

my $rsp = q/YES/;

my @h;
my $lH = '-';
foreach (@order) {
    @h = sort {$a cmp $b} split /\s+/, $names[$_];
    if ($lH lt $h[0]) {
        $lH = $h[0]; next;
    } elsif ($lH lt $h[1]) {
        $lH = $h[1]; next;
    } else {
        $rsp = q/NO/; last;
    }
}

printf "$rsp\n";


A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each row. Laurenty lives in the very last house of the second row. The only shop in town is placed in the first house of the first row.The first and second rows are separated with the main avenue of the city. The adjacent houses of one row are separated by streets.Each crosswalk of a street or an avenue has some traffic lights. In order to cross the street, you need to press a button on the traffic light, wait for a while for the green light and cross the street. Different traffic lights can have different waiting time.The traffic light on the crosswalk from the j-th house of the i-th row to the (j + 1)-th house of the same row has waiting time equal to aij (1 ≤ i ≤ 2, 1 ≤ j ≤ n - 1). For the traffic light on the crossing from the j-th house of one row to the j-th house of another row the waiting time equals bj (1 ≤ j ≤ n). The city doesn't have any other crossings.The boy wants to get to the store, buy the products and go back. The main avenue of the city is wide enough, so the boy wants to cross it exactly once on the way to the store and exactly once on the way back home. The boy would get bored if he had to walk the same way again, so he wants the way home to be different from the way to the store in at least one crossing.    Figure to the first sample. Help Laurenty determine the minimum total time he needs to wait at the crossroads.

The first line of the input contains integer n (2 ≤ n ≤ 50) — the number of houses in each row.  Each of the next two lines contains n - 1 space-separated integer — values aij (1 ≤ aij ≤ 100).  The last line contains n space-separated integers bj (1 ≤ bj ≤ 100).

Print a single integer — the least total time Laurenty needs to wait at the crossroads, given that he crosses the avenue only once both on his way to the store and on his way back home.

NoteThe first sample is shown on the figure above. In the second sample, Laurenty's path can look as follows:   Laurenty crosses the avenue, the waiting time is 3;  Laurenty uses the second crossing in the first row, the waiting time is 2;  Laurenty uses the first crossing in the first row, the waiting time is 1;  Laurenty uses the first crossing in the first row, the waiting time is 1;  Laurenty crosses the avenue, the waiting time is 1;  Laurenty uses the second crossing in the second row, the waiting time is 3.  In total we get that the answer equals 11.In the last sample Laurenty visits all the crossings, so the answer is 4.


Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $$$(0, 0)$$$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $$$OX$$$ or $$$OY$$$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.Alexey wants to make a polyline in such a way that its end is as far as possible from $$$(0, 0)$$$. Please help him to grow the tree this way.Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of sticks Alexey got as a present. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) — the lengths of the sticks.

Print one integer — the square of the largest possible distance from $$$(0, 0)$$$ to the tree end.

NoteThe following pictures show optimal trees for example tests. The squared distance in the first example equals $$$5 \cdot 5 + 1 \cdot 1 = 26$$$, and in the second example $$$4 \cdot 4 + 2 \cdot 2 = 20$$$.


You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:  Swap i-th and j-th rows of the matrix;  Swap i-th and j-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.

The first line contains an integer n (2 ≤ n ≤ 1000) — the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 ≤ xk, yk ≤ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one. It is guaranteed that all positions are distinct.

Print the description of your actions. These actions should transform the matrix to the described special form. In the first line you should print a non-negative integer m (m ≤ 105) — the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 ≤ t ≤ 2, 1 ≤ i, j ≤ n, i ≠ j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively. Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.


A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.

The first line contains number n (1 ≤ n ≤ 105). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.

Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.

#!/usr/bin/perl

main();

sub main {
    my $n = int <>;
    my %hash = ();
    for(1..$n) {
        my $name = <>;
        $name =~ s/[\W]//;
        my $add = "";
        if (exists $hash{$name}) {
            $add = $hash{$name};
            print("$name$add\n");
            $hash{$name} = $add + 1;
        } else {
            print("OK\n");
            $hash{$name} = 1;
        }
    }
}

chomp($count = <STDIN>);
for ($i = 0; $i < $count; ++$i)
{
    chomp($newName = <STDIN>);
    push @names, $newName;
}
foreach (@names)
{
    if ( ! exists $logins{$_} )
    {
        $logins{$_}++;
        print "OK\n";
    }
    else
    {
        print "$_$logins{$_}\n";
        $logins{$_}++;
    }
}

my %hash;
for my $i(1..int<>) {
    chomp($_ = <>);
    if (not exists $hash{$_}) {
        print "OK\n";
        $hash{$_} = 1;
        next;
    }
    print $_ . $hash{$_} . "\n";
    $hash{$_}++;
}

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

chomp($n = <>);
foreach (1 .. $n) {
	chomp($line = <>);
	defined $tb{$line} and say $line,$tb{$line} or say "OK";
	++$tb{$line};
}

my $n = <>;
my %names;

for (1..$n) {
    my $name = <>;
    chomp $name;
    if (exists $names{$name}) {
        print $name, $names{$name}++, "\n";
    } else {
        $names{$name} = 1;
        print "OK\n";
    }
}

#!perl

for (1..<STDIN>) {
	chomp ($name = <STDIN>);
	if (!defined($names{$name})) {
		print "OK\n";
		$names{$name} = 0;
	} else {
		print $name, ++$names{$name}, "\n";
	}
}

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

my $n=<STDIN>;
my %list;my $p=0;
my @output;
for my $i(0..$n-1){
    my $name=<STDIN>;
    chomp($name);
    if(!defined($list{$name})){
	$list{$name}=$name;
	$output[$i]="OK\n";
    }
    else{
	$p=$list{$name}=~s/[a-z]+/0/r+1;
	$list{$name}=$name.$p;
	$output[$i]=$list{$name}."\n";
    }
}
print @output;

#!/usr/bin/perl

$n=<STDIN>;
$n=int($n);

%db=();

for($i=0;$i<$n;$i++) {
	$name=<STDIN>;
	chomp($name);
	if($db{$name}) {
		$name2=$name . $db{$name};
		$db{$name}=$db{$name}+1;
		print "$name2\n";
	} else {
		$db{$name}=1;
		print "OK\n";
	}
}

chomp($n = <STDIN>);

%dic = {};
@userlist = [];
pop @userlist;

for( $i = 0; $i < $n; $i++){
    chomp($name = <STDIN>);
    if (exists $dic{$name}) {
        #$dic{$name} = $dic{$name} + 1;
        $dic{$name}++;
        $string = $name.$dic{$name};
        push @userlist , ($string);
    }
    else
    {
        $dic{$name} = 0;
        push @userlist, "OK";
    }
}

foreach $name(@userlist){
	print "$name\n";
}

$len = <STDIN>;
$hashMap;

for my $val (1 .. $len) {
	$input = <STDIN>;
	$input =~ s/\s//g;

	if ($hashMap->{$input}) {
		print $input.$hashMap->{$input}."\n";
		++$hashMap->{$input};
	} else {
		$hashMap->{$input} = 1;
		print "OK\n";
	}
}

#!perl

for (1..<STDIN>) {
	chomp ($name = <STDIN>);
	if (!defined($names{$name})) {
		print "OK";
		$names{$name} = 0;
	} else {
		print $name, ++$names{$name}, "\n";
	}
}

#!perl

for (1..<STDIN>) {
	chomp ($name = <STDIN>);
	if (!defined($names{$name})) {
		print "OK";
		$names{$name} = 0;
	} else {
		print $name, ++$names{$name};
	}
}

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

my $n=<STDIN>;
my %list;
my @output;
for my $i(0..$n-1){
    my $name=<STDIN>;
    chomp($name);
    if(!defined($list{$name})){
	$list{$name}=$name;
	$output[$i]="OK\n";
    }
    else{
	my $p=$name=~s/\w+/0/r;
	$list{$name}=$name.($p+1);
	$output[$i]=$list{$name}."\n";
    }
}
print @output;