Not so long ago, Vlad came up with an interesting function: $$$f_a(x)=\left\lfloor\frac{x}{a}\right\rfloor + x \bmod a$$$, where $$$\left\lfloor\frac{x}{a}\right\rfloor$$$ is $$$\frac{x}{a}$$$, rounded down, $$$x \bmod a$$$ — the remainder of the integer division of $$$x$$$ by $$$a$$$.For example, with $$$a=3$$$ and $$$x=11$$$, the value $$$f_3(11) = \left\lfloor\frac{11}{3}\right\rfloor + 11 \bmod 3 = 3 + 2 = 5$$$.The number $$$a$$$ is fixed and known to Vlad. Help Vlad find the maximum value of $$$f_a(x)$$$ if $$$x$$$ can take any integer value from $$$l$$$ to $$$r$$$ inclusive ($$$l \le x \le r$$$).

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. This is followed by $$$t$$$ lines, each of which contains three integers $$$l_i$$$, $$$r_i$$$ and $$$a_i$$$ ($$$1 \le l_i \le r_i \le 10^9, 1 \le a_i \le 10^9$$$) — the left and right boundaries of the segment and the fixed value of $$$a$$$.

For each test case, output one number on a separate line — the maximum value of the function on a given segment for a given $$$a$$$.

NoteIn the first sample:  $$$f_3(1) = \left\lfloor\frac{1}{3}\right\rfloor + 1 \bmod 3 = 0 + 1 = 1$$$,  $$$f_3(2) = \left\lfloor\frac{2}{3}\right\rfloor + 2 \bmod 3 = 0 + 2 = 2$$$,  $$$f_3(3) = \left\lfloor\frac{3}{3}\right\rfloor + 3 \bmod 3 = 1 + 0 = 1$$$,  $$$f_3(4) = \left\lfloor\frac{4}{3}\right\rfloor + 4 \bmod 3 = 1 + 1 = 2$$$ As an answer, obviously, $$$f_3(2)$$$ and $$$f_3(4)$$$ are suitable.

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

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

while( $testcase -- > 0 ){
  my ($l,$r,$a) = map { $_ - 0 } split(/\s+/,<STDIN>);
  my $v1 = $r / $a;
  my $mx = -1;
  if( $v1 > 0 ){
    my $x = $r - ($r % $a) - 1;
    $mx = ( $x / $a ) + ( $x % $a ) if $x >= $l ;
  }
  my $v2 = $v1 + ($r % $a);
  $mx = $v2 if $v2 > $mx;
  print "$mx\n";
}

exit(0);

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

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

while( $testcase -- > 0 ){
  my ($l,$r,$a) = map { $_ - 0 } split(/\s+/,<STDIN>);
  my $v1 = $r / $a;
  my $mx = -1;
  if( $v1 > 0 ){
    my $x = $l - ($l % $a) - 1;
    $mx = ( $x / $a ) + ( $x % $a ) if $x >= $l ;
  }
  my $v2 = $v1 + ($r % $a);
  $mx = $v2 if $v2 > $mx;
  print "$mx\n";
}

exit(0);


Polycarp had an array $$$a$$$ of $$$3$$$ positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $$$b$$$ of $$$7$$$ integers.For example, if $$$a = \{1, 4, 3\}$$$, then Polycarp wrote out $$$1$$$, $$$4$$$, $$$3$$$, $$$1 + 4 = 5$$$, $$$1 + 3 = 4$$$, $$$4 + 3 = 7$$$, $$$1 + 4 + 3 = 8$$$. After sorting, he got an array $$$b = \{1, 3, 4, 4, 5, 7, 8\}.$$$Unfortunately, Polycarp lost the array $$$a$$$. He only has the array $$$b$$$ left. Help him to restore the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line which contains $$$7$$$ integers $$$b_1, b_2, \dots, b_7$$$ ($$$1 \le b_i \le 10^9$$$; $$$b_i \le b_{i+1}$$$).  Additional constraint on the input: there exists at least one array $$$a$$$ which yields this array $$$b$$$ as described in the statement.

For each test case, print $$$3$$$ integers — $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$. If there can be several answers, print any of them.

NoteThe subsequence of the array $$$a$$$ is a sequence that can be obtained from $$$a$$$ by removing zero or more of its elements.Two subsequences are considered different if index sets of elements included in them are different. That is, the values of the elements don't matter in the comparison of subsequences. In particular, any array of length $$$3$$$ has exactly $$$7$$$ different non-empty subsequences.

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

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

while( $testcase -- > 0 ){
  my @A = map { $_ - 0 } split(/\s+/,<STDIN>);
  $A[2] = $A[6] - $A[0] - $A[1];
  print ( join(' ',@A[0..2]) . "\n" );
}

exit(0);


Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula , where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≤ x ≤ m.

The first line contains integer n (1 ≤ n ≤ 105) — the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 ≤ ai ≤ 104) — elements of array a. The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 — the binary representation of number m. Number m equals .

Print a single integer — the maximum value of function f(x) for all .

NoteIn the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.


In an ICPC contest, balloons are distributed as follows:   Whenever a team solves a problem, that team gets a balloon.  The first team to solve a problem gets an additional balloon.  A contest has 26 problems, labelled $$$\textsf{A}$$$, $$$\textsf{B}$$$, $$$\textsf{C}$$$, ..., $$$\textsf{Z}$$$. You are given the order of solved problems in the contest, denoted as a string $$$s$$$, where the $$$i$$$-th character indicates that the problem $$$s_i$$$ has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of testcases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the string. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of uppercase English letters, denoting the order of solved problems.

For each test case, output a single integer — the total number of balloons that the teams received.

6

3

ABA

1

A

3

ORZ

5

BAAAA

4

BKPT

10

CODEFORCES

NoteIn the first test case, $$$5$$$ balloons are given out:   Problem $$$\textsf{A}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.  Problem $$$\textsf{B}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{B}$$$.  Problem $$$\textsf{A}$$$ is solved. That team receives only $$$1$$$ balloon, because they solved the problem. Note that they don't get an additional balloon because they are not the first team to solve problem $$$\textsf{A}$$$.  The total number of balloons given out is $$$2+2+1=5$$$.In the second test case, there is only one problem solved. The team who solved it receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my %h;

	map $h{ $_ } ++, m/./g;

	print 0 + ( length ) + keys %h;
	}


A big football championship will occur soon! $$$n$$$ teams will compete in it, and each pair of teams will play exactly one game against each other.There are two possible outcomes of a game:  the game may result in a tie, then both teams get $$$1$$$ point;  one team might win in a game, then the winning team gets $$$3$$$ points and the losing team gets $$$0$$$ points. The score of a team is the number of points it gained during all games that it played.You are interested in a hypothetical situation when all teams get the same score at the end of the championship. A simple example of that situation is when all games result in ties, but you want to minimize the number of ties as well.Your task is to describe a situation (choose the result of each game) so that all teams get the same score, and the number of ties is the minimum possible.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case is described by one line containing one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of teams.

For each test case, print $$$\frac{n(n - 1)}{2}$$$ integers describing the results of the games in the following order: the first integer should correspond to the match between team $$$1$$$ and team $$$2$$$, the second — between team $$$1$$$ and team $$$3$$$, then $$$1$$$ and $$$4$$$, ..., $$$1$$$ and $$$n$$$, $$$2$$$ and $$$3$$$, $$$2$$$ and $$$4$$$, ..., $$$2$$$ and $$$n$$$, and so on, until the game between the team $$$n - 1$$$ and the team $$$n$$$. The integer corresponding to the game between the team $$$x$$$ and the team $$$y$$$ should be $$$1$$$ if $$$x$$$ wins, $$$-1$$$ if $$$y$$$ wins, or $$$0$$$ if the game results in a tie. All teams should get the same score, and the number of ties should be the minimum possible. If there are multiple optimal answers, print any of them. It can be shown that there always exists a way to make all teams have the same score.

NoteIn the first test case of the example, both teams get $$$1$$$ point since the game between them is a tie.In the second test case of the example, team $$$1$$$ defeats team $$$2$$$ (team $$$1$$$ gets $$$3$$$ points), team $$$1$$$ loses to team $$$3$$$ (team $$$3$$$ gets $$$3$$$ points), and team $$$2$$$ wins against team $$$3$$$ (team $$$2$$$ gets $$$3$$$ points).


Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $$$q$$$ questions about this song. Each question is about a subsegment of the song starting from the $$$l$$$-th letter to the $$$r$$$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $$$k$$$ times, where $$$k$$$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is $$$10$$$. Vasya is interested about the length of the resulting string.Help Petya find the length of each string obtained by Vasya.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1\leq n\leq 100\,000$$$, $$$1\leq q \leq 100\,000$$$) — the length of the song and the number of questions.  The second line contains one string $$$s$$$ — the song, consisting of $$$n$$$ lowercase letters of English letters. Vasya's questions are contained in the next $$$q$$$ lines. Each line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) — the bounds of the question.

Print $$$q$$$ lines: for each question print the length of the string obtained by Vasya.

NoteIn the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to $$$4$$$. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is $$$7$$$. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length $$$11$$$.


A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.

Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.

#!/usr/bin/perl
use 5.010;

sub Solve {
    my $ret = 0;
    my $inc = 1;
    while (($idx, $val) = each(@_)) {
        $idx == $val && $ret++;
        $idx != $val && $_[$val] == $idx && ($inc = 2);
    }
    return $ret == @_? $ret : $ret + $inc;
}

while (<>) {
    @line = split /\s+/, <>;
    say Solve(@line);
}

my $num = <>;
chomp $num;
my @perm = split ' ', <>;
my %perm = map { $_, $perm[$_] } 0..$num-1;
$count = 0;
my $ext = 0;
for (0..$num-1) {
    if ($perm{$_} == $_) {
        $count++;
    } elsif (!$ext && $perm{$perm{$_}} == $_) {
        $ext = 2;
    }
}
$ext = 1 unless $ext == 2 || $count == $num;
$count += $ext;
print $count;


Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $$$0$$$ or $$$1$$$. For example, $$$1\,010\,111$$$ is a binary decimal, while $$$10\,201$$$ and $$$787\,788$$$ are not.Given a number $$$n$$$, you are asked to represent $$$n$$$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$), denoting the number to be represented.

For each test case, output the smallest number of binary decimals required to represent $$$n$$$ as a sum.

NoteIn the first test case, $$$121$$$ can be represented as $$$121 = 110 + 11$$$ or $$$121 = 111 + 10$$$.In the second test case, $$$5$$$ can be represented as $$$5 = 1 + 1 + 1 + 1 + 1$$$.In the third test case, $$$1\,000\,000\,000$$$ is a binary decimal itself, thus the answer is $$$1$$$.

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

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

while( $test_case -- > 0 ){
  my ($n) = map { $_ - 0 } split(/\s+/,<STDIN>);
  my @a = split(//,( '' . $n ));
  my $mx = 1;
  for(my $i=0;$i<=$#a;$i++){
    $mx = $a[$i] - 0 if $a[$i] - 0 > $mx;
  }
  print "$mx\n";
}

exit(0);

<>;
chomp, print +(sort split'')[-1] . $/ for <>

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

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

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

  my $cnt = 0;
  while( $n > 0 ){
    my $ns = '' . $n;
    my $ov = undef;
    my $top = substr($ns,0,1) - 0;
    my $ms = $top;
    for(my $i=1;$i<length($ns);$i++){
      if( $ov ){
        $ms .= $top;
      } else {
        my $j = substr($ns,$i,1) - 0;
        if( $j == $top ){
          $ms .= $top;
        } else {
          $ms .= ( $j > $top ? $top : '0' );
          $ov = 1;
        }
      }
    }
    $n -= ( $ms - 0 );
    $cnt += $top;
  }
  print "$cnt\n";

}

exit(0);


A rectangle with its opposite corners in $$$(0, 0)$$$ and $$$(w, h)$$$ and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that:   exactly two of them belong to the same side of a rectangle;  the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$w$$$ and $$$h$$$ ($$$3 \le w, h \le 10^6$$$) — the coordinates of the corner of a rectangle. The next two lines contain the description of the points on two horizontal sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$x_1 < x_2 < \dots < x_k$$$ ($$$0 < x_i < w$$$) — the $$$x$$$ coordinates of the points in the ascending order. The $$$y$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$h$$$. The next two lines contain the description of the points on two vertical sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$y_1 < y_2 < \dots < y_k$$$ ($$$0 < y_i < h$$$) — the $$$y$$$ coordinates of the points in the ascending order. The $$$x$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$w$$$. The total number of points on all sides in all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side.


Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house.

Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.

use strict;
use warnings;

$\ = "\n";

sub dist {
    my ($x, $y, $n) = @_;
    ($y - $x + $n) % $n;
}

my ($n, $m) = split ' ', <>;
my @tasks = split ' ', <>;
my $pos = 1;
my $time = 0;

for my $task (@tasks) {
    $time += dist($pos, $task, $n);
    $pos = $task;
}

print $time;

($n, $m) = split ' ', <>;
@arr = split ' ', <>;
$total = 0;
$last = 1;
for (@arr) {
    if ($_ >= $last) {
        $total += $_ - $last;
        $last = $_;
    } else {
        $total += $n - ($last - $_);
        $last = $_;
    }
}
print $total;

#!/usr/bin/perl

use strict;
use warnings;

use constant POS_START=>1;  # 開始位置

main();

## main()
# メイン処理
sub main {
    # 標準入力の取得
    my $line1 = <>;
    my $line2 = <>;
    chomp($line1);
    chomp($line2);

    # 標準入力の解析
    my ($n, $m) = split(/ /, $line1);
    my (@a) = split(/ /, $line2);
    if ($m != $#a+1) {
        print "illeagal arguments\n";
        exit -1;
    }

    my $pos = POS_START;
    my $cnt_round = 0;
    foreach(@a) {
        if ($_ > $n || $_ < 1) {
            print "illeagal arguments\n";
            exit -1;
        }
        if ($pos > $_) { $cnt_round++; }
        $pos = $_;
    }

    my $time_total = $cnt_round * $n + $pos - POS_START;
    print "$time_total\n";
}

#!/usr/bin/perl

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

@_=split/ /,<>;
unshift @_,1;
for $i(1..@_-1){
    $_[$i]>=$_[$i-1] ? ($sum+=$_[$i]-$_[$i-1]) : ($sum+= $`+$_[$i]-$_[$i-1]);
    }
print $sum;

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
}


We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7.The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.

The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.

Print the minimum number of steps modulo 109 + 7.

NoteThe first example: "ab"  →  "bba".The second example: "aab"  →  "abba"  →  "bbaba"  →  "bbbbaa".

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $MOD = 1e9 + 7;

while(<>){
	chomp;
	my $c;
	my $ans = 0;
	my $B = 0;

	while( $c = chop ){

		if( $c eq 'b' ){
			$B ++;
			}
		else{
			map { $_ %= $MOD } $ans += $B, $B <<= 1;
			}
		}

	print $ans;
	}


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times:  if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  ...  remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.

The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.

Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).

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

my ($n, $k, $str);
my $asdf = <STDIN>; chomp($asdf); $asdf =~ /(\d+) (\d+)/; ($n, $k) = ($1, $2);
$str = <STDIN>; chomp($str);

my @chars = reverse split(//, $str);
my @pos;
for ('a'..'z') {
    $pos[ord($_)-ord('a')] = [];
}
while (my ($i, $ch) = each @chars) {
    push(@{$pos[ord($ch)-ord('a')]}, $n-1-$i);
}
@chars = reverse @chars;
for (1..$k) {
    for ('a'..'z') {
        my $idx = ord($_)-ord('a');
        if (scalar @{$pos[$idx]} > 0) {
            my $pos = pop @{$pos[$idx]};
            $chars[$pos] = '';
            last;
        }
    }
}

print join('', @chars), "\n";


Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.

The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font:

Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes).

$_ = <STDIN>;
chomp;

if ( $_=~m/[BCDEFGJKLNPQRSZ]/ ){
    print "NO";
}else{
    if ( $_ eq (reverse $_)){
        print "YES";
    }else{
        print "NO";
    }
}

$_=<>; chomp;
$r=reverse$_;
print /[^AHIOMT-Y]/ || $r ne $_? NO:YES

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

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

if ($line1 =~ m/[BCDEFGJKLNPQRSZ]/)
{
  say "NO";
  exit;
}
elsif ($line1 eq reverse($line1))
{
  say "YES";
  exit;
}
else
{
  say "NO";
  exit;
}

use strict;
use POSIX;

chomp (my $s = <>);
my @s = split '', $s;
print "NO" and exit if $s=~ m/[BCDEFGJKLNPQRSZ]/;
my $f=0;
a:for(0..$#s/2)
{
if ($s[$_] ne $s[$#s - $_])
{
$f = 2;
last a;

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

$st=<>;
chomp($st);
$rv=reverse $st;
($rv ne $st || $st=~/[^AHIOMT-Y]/ )? print "NO":print "YES";

use integer;

while(<>){

	chomp;
	$f=0;

	# A H I O U V W T Y X M
	# <>

	$le = length;
	@_=qw(A H I O U V W T Y X M);
#	print "@_\n";

	/[^AHIOUVWTYXM]/ and $f=1;

	@a=split//;
#	print 0+@a,"\n";

	if (!$f)
	{
		for $i(0..(@a/2)){

			$a[$i] eq $a[@a-$i-1] or $f=2;

		}

	}
#	print "$f\n";
	print $f? "NO\n":"YES\n";

	}

$_ = <STDIN>;
chomp;

if ( $_=~m/[BCDEFGJKLMNPQRSZ]/ ){
    print "NO";
}else{
    if ( $_ eq (reverse $_)){
        print "YES";
    }else{
        print "NO";
    }
}

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

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

if ($line1 =~ m/[BCDEFGJKLNPQRSZ]/)
{
  say "No";
  exit;
}
elsif ($line1 eq reverse($line1))
{
  say "Yes";
  exit;
}
else
{
  say "No";
  exit;
}

use strict;
use POSIX;

chomp (my $s = <>);
my @s = split '', $s;
print "NO" and exit if $s=~ m/[BCDEFGJKLNPQRS]/;
my $f=0;
a:for(0..$#s/2)
{
if ($s[$_] ne $s[$#s - $_])
{
$f = 2;
last a;

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

$st=<>;
chomp($st);
$rv=reverse $st;
($rv eq $st)? print "YES":print "NO";

$st=<>;
chomp($st);
$rv=reverse $st;
($rt eq $st && length($rt)!=1)? print "YES":print "NO";

$st=<>;
chomp($st);
$rv=reverse $st;
($rv eq $st&& length($rv)!=1)? print "YES":print "NO";

$st=<>;
chomp($st);
$rv=reverse $st;
($rv eq $st && length($rv)!=1)? print "YES":print "NO";

$st=<>;
chomp($st);
$rt=reverse $st;
($rt eq $st && length($rt)!=1)? print "YES":print "NO";

$st=<>;
chomp($st);
$rv=reverse $st;
($rv ne $st || $st=~/[^AHITOMY]/ )? print "NO":print "YES";


The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.

The first line of input will contain an integer n (1 ≤ n ≤ 105), the number of events. The next line will contain n space-separated integers. If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.

Print a single integer, the number of crimes which will go untreated.

NoteLets consider the second example:  Firstly one person is hired.  Then crime appears, the last hired person will investigate this crime.  One more person is hired.  One more crime appears, the last hired person will investigate this crime.  Crime appears. There is no free policeman at the time, so this crime will go untreated.  One more person is hired.  One more person is hired.  One more person is hired. The answer is one, as one crime (on step 5) will go untreated.

my $n = <>;
chomp($n);
my $in = <>;
chomp($in);
my @A = split ' ', $in;
my ($sum, $ans) = (0, 0);
for (my $i = 0; $i < $n; ++$i) {
    $sum += $A[$i];
    $ans = $sum if $ans > $sum;
}
print abs $ans;

use strict;
<>;
my (@a) = split (' ',<>);
my $cop=0;
my $ans = 0;
for my $event (@a)
{
    if($event > 0)
    {
        $cop += $event;
    }
    else
    {
        $ans++ if $cop == 0;
        $cop-- if $cop > 0;
    }
}
print $ans;

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

chomp($n = <>);
($ans, $tot) = (0, 0);
foreach (split / /, <>) {
	$tot += $_;
	$tot<0 and ++$ans and $tot=0;
}
say $ans;

<>;
my @events = split ' ', <>;
my $free = 0;
my $missed = 0;

for my $event (@events) {
    $free += $event;
    while ($free < 0) {
        $missed++;
        $free++;
    }
}

print $missed, "\n";


Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.

The single line contains three integers k, d and t (1 ≤ k, d, t ≤ 1018).

Print a single number, the total time of cooking in minutes. The relative or absolute error must not exceed 10 - 9. Namely, let's assume that your answer is x and the answer of the jury is y. The checker program will consider your answer correct if .

NoteIn the first example, the chicken will be cooked for 3 minutes on the turned on stove, after this it will be cooked for . Then the chicken will be cooked for one minute on a turned off stove, it will be cooked for . Thus, after four minutes the chicken will be cooked for . Before the fifth minute Julia will turn on the stove and after 2.5 minutes the chicken will be ready .In the second example, when the stove is turned off, Julia will immediately turn it on, so the stove will always be turned on and the chicken will be cooked in 20 minutes.

#!/usr/bin/perl

use warnings;
use strict;
use bignum;

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

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

	while( $k > $d ){
		if( $k % $d == 0 ){ $d = $k; last; }
		my $i = int $k / $d;
		$d = ( $i + 1 ) * $d;
		}

	$debug and print "[$k|$d]";

	my $c = $k + 0.5 * ( $d - $k );

	print do {

		if( $k == $d ){
			$t;
			}
		else{
			my $i = int $t / $c;
			my $r = $t - $i * $c;

			$debug and print " <$i|$r>";

			$i * $d +
				do {
					if( $r <= $k ){
						$r;
						}
					else{
						$k + 2 * ( $r - $k );
						}
				};
			}
		};

	}


There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.

Print the minimum number of operations required to change balance in each bank to zero.

NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer:   transfer 1 from the first bank to the second bank;  transfer 3 from the second bank to the third;  transfer 6 from the third bank to the fourth.


You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones. You can do the following operation:  choose two indices $$$1 \le i , j \le n$$$, $$$i \ne j$$$,  add $$$a_{i}$$$ to $$$a_{j}$$$,  remove $$$a_{i}$$$ from $$$a$$$. Note that elements of $$$a$$$ can become bigger than $$$1$$$ after performing some operations. Also note that $$$n$$$ becomes $$$1$$$ less after the operation.What is the minimum number of operations needed to make $$$a$$$ non-decreasing, i. e. that each element is not less than the previous element?

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 an integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the size of array $$$a$$$. Next line contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$. It's guaranteed that sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer, minimum number of operations needed to make $$$a$$$ non-decreasing.

NoteIn the first test case, $$$a$$$ is already non-decreasing, so you don't need to do any operations and the answer is $$$0$$$.In the second test case, you can perform an operation for $$$i = 1$$$ and $$$j = 5$$$, so $$$a$$$ will be equal to $$$[0, 0, 1, 2]$$$ and it becomes non-decreasing.In the third test case, you can perform an operation for $$$i = 2$$$ and $$$j = 1$$$, so $$$a$$$ will be equal to $$$[1]$$$ and it becomes non-decreasing.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my $i = 0;

	OUTER:
	while( @_ ){
		while( $_[ 0 ] == 0 ){
			shift @_;
			next OUTER;
			}
		while( $_[ @_ - 1 ] == 1 ){
			pop @_;
			next OUTER;
			}

		$i ++;
		shift @_;
		pop @_;
		}

	print $i;
	}


Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type.

The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.

NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.Optimal sequence of actions in the second sample case:   In the first day Anastasia collects 8 pebbles of the third type.  In the second day she collects 8 pebbles of the fourth type.  In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.  In the fourth day she collects 7 pebbles of the fifth type.  In the fifth day she collects 1 pebble of the second type.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	@_ = split ' ', <>;

	my $sum = 0;

	$sum += (int $_ / $k) + !!($_ % $k) for @_;

	print int( $sum / 2 ) + $sum % 2;

	}


A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes).A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string.The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ.

The first line contains integer n (1 ≤ n ≤ 105) — the number of strings in the set. Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct. The total length of the strings doesn't exceed 105.

Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print "NO" (without quotes) if there are no good strings.

NoteOne can show that in the first sample only two good strings with minimum length exist: "cfmailru" and "mailrucf". The first string is lexicographically minimum.


You are given a table $$$a$$$ of size $$$n \times m$$$. We will consider the table rows numbered from top to bottom from $$$1$$$ to $$$n$$$, and the columns numbered from left to right from $$$1$$$ to $$$m$$$. We will denote a cell that is in the $$$i$$$-th row and in the $$$j$$$-th column as $$$(i, j)$$$. In the cell $$$(i, j)$$$ there is written a number $$$(i - 1) \cdot m + j$$$, that is $$$a_{ij} = (i - 1) \cdot m + j$$$.A turtle initially stands in the cell $$$(1, 1)$$$ and it wants to come to the cell $$$(n, m)$$$. From the cell $$$(i, j)$$$ it can in one step go to one of the cells $$$(i + 1, j)$$$ or $$$(i, j + 1)$$$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path.  For example, with $$$n = 2$$$ and $$$m = 3$$$ the table will look as shown above. The turtle can take the following path: $$$(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3)$$$. The cost of such way is equal to $$$a_{11} + a_{12} + a_{13} + a_{23} = 12$$$. On the other hand, the paths $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 1)$$$ and $$$(1, 1) \rightarrow (1, 3)$$$ are incorrect, because in the first path the turtle can't make a step $$$(2, 2) \rightarrow (2, 1)$$$, and in the second path it can't make a step $$$(1, 1) \rightarrow (1, 3)$$$.You are asked to tell the turtle a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. Please note that the cells $$$(1, 1)$$$ and $$$(n, m)$$$ are a part of the way.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of test cases follows. A single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^4$$$) — the number of rows and columns of the table $$$a$$$ respectively.

For each test case output a single integer — a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$.

NoteIn the first test case the only possible path consists of a single cell $$$(1, 1)$$$.The path with the minimal cost in the second test case is shown in the statement.In the fourth and the fifth test cases there is only one path from $$$(1, 1)$$$ to $$$(n, m)$$$. Both paths visit every cell in the table.


Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...The string $$$s$$$ he found is a binary string of length $$$n$$$ (i. e. string consists only of 0-s and 1-s).In one move he can choose two consecutive characters $$$s_i$$$ and $$$s_{i+1}$$$, and if $$$s_i$$$ is 1 and $$$s_{i + 1}$$$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $$$s$$$ as clean as possible. He thinks for two different strings $$$x$$$ and $$$y$$$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.Now you should answer $$$t$$$ test cases: for the $$$i$$$-th test case, print the cleanest possible string that Lee can get by doing some number of moves.Small reminder: if we have two strings $$$x$$$ and $$$y$$$ of the same length then $$$x$$$ is lexicographically smaller than $$$y$$$ if there is a position $$$i$$$ such that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$,..., $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$.

The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  Next $$$2t$$$ lines contain test cases — one per two lines. The first line of each test case contains the integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The second line contains the binary string $$$s$$$. The string $$$s$$$ is a string of length $$$n$$$ which consists only of zeroes and ones. It's guaranteed that sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.

Print $$$t$$$ answers — one per test case. The answer to the $$$i$$$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero).

NoteIn the first test case, Lee can't perform any moves.In the second test case, Lee should erase $$$s_2$$$.In the third test case, Lee can make moves, for example, in the following order: 11001101 $$$\rightarrow$$$ 1100101 $$$\rightarrow$$$ 110101 $$$\rightarrow$$$ 10101 $$$\rightarrow$$$ 1101 $$$\rightarrow$$$ 101 $$$\rightarrow$$$ 01.

#!/usr/bin/env perl

use strict;
use warnings;

my $t = int <>;
for (1 .. $t) {
    my $n = int <>;
    my $s = <>;
    chomp $s;

    $s = reverse $s;
    while ($s =~ s/0+1/0/) {}
    $s = reverse $s;
    print qq($s\n);
}


Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to:   dr(n) = S(n), if S(n) < 10;  dr(n) = dr( S(n) ), if S(n) ≥ 10. For example, dr(4098)  =  dr(21)  =  3.Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n)  =  S( S( S( S(n) ) ) ) (n ≤ 101000).Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist.

The first line contains two integers k and d (1 ≤ k ≤ 1000; 0 ≤ d ≤ 9).

In a single line print either any number that meets the requirements (without the leading zeroes) or "No solution" (without the quotes), if the corresponding number does not exist. The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes.

NoteFor the first test sample dr(5881)  =  dr(22)  =  4.For the second test sample dr(36172)  =  dr(19)  =  dr(10)  =  1.


Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.You are a new applicant for his company. Boboniu will test you with the following chess question:Consider a $$$n\times m$$$ grid (rows are numbered from $$$1$$$ to $$$n$$$, and columns are numbered from $$$1$$$ to $$$m$$$). You have a chess piece, and it stands at some cell $$$(S_x,S_y)$$$ which is not on the border (i.e. $$$2 \le S_x \le n-1$$$ and $$$2 \le S_y \le m-1$$$).From the cell $$$(x,y)$$$, you can move your chess piece to $$$(x,y')$$$ ($$$1\le y'\le m, y' \neq y$$$) or $$$(x',y)$$$ ($$$1\le x'\le n, x'\neq x$$$). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.Your goal is to visit each cell exactly once. Can you find a solution?Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.

The only line of the input contains four integers $$$n$$$, $$$m$$$, $$$S_x$$$ and $$$S_y$$$ ($$$3\le n,m\le 100$$$, $$$2 \le S_x \le n-1$$$, $$$2 \le S_y \le m-1$$$) — the number of rows, the number of columns, and the initial position of your chess piece, respectively.

You should print $$$n\cdot m$$$ lines. The $$$i$$$-th line should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i \leq n$$$, $$$1 \leq y_i \leq m$$$), denoting the $$$i$$$-th cell that you visited. You should print exactly $$$nm$$$ pairs $$$(x_i, y_i)$$$, they should cover all possible pairs $$$(x_i, y_i)$$$, such that $$$1 \leq x_i \leq n$$$, $$$1 \leq y_i \leq m$$$. We can show that under these constraints there always exists a solution. If there are multiple answers, print any.


You are given a positive integer $$$n$$$. Your task is to find any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \le a, b, c \le 10^9$$$) for which $$$(a\oplus b)+(b\oplus c)+(a\oplus c)=n$$$, or determine that there are no such integers.Here $$$a \oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$. For example, $$$2 \oplus 4 = 6$$$ and $$$3 \oplus 1=2$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, print any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \le a, b, c \le 10^9$$$) for which $$$(a\oplus b)+(b\oplus c)+(a\oplus c)=n$$$. If no such integers exist, print $$$-1$$$.

NoteIn the first test case, $$$a=3$$$, $$$b=3$$$, $$$c=1$$$, so $$$(3 \oplus 3)+(3 \oplus 1) + (3 \oplus 1)=0+2+2=4$$$.In the second test case, there are no solutions.In the third test case, $$$(2 \oplus 4)+(4 \oplus 6) + (2 \oplus 6)=6+2+4=12$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;

	if( $_ % 2 == 1 ){
		print -1;
		next;
		}

	$_ >>= 1;

	print join ' ', $_ + 1, $_ + 1, 1;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

while(<>){
	chomp;

	if( $_ % 2 == 1 ){
		print -1;
		next;
		}

	$_ >>= 1;

	print join ' ', $_, $_ - 1, 1;
	}


Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!

The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi,  ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively.

If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line.

NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris.

use strict;
use warnings;

use Data::Dumper;

my $n = <>;
chomp $n;

die ('wrong n..') unless $n >= 1;

my %player_wins;
$player_wins{Mishka} = 0;
$player_wins{Chris} = 0;

for (my $i=0; $i<$n; $i++) {
    my $in = <>;
    chomp $in;
    my ($m , $c) = split(' ', $in);

    if ($m > $c) {
        $player_wins{Mishka}++;
    } elsif($c > $m) {
        $player_wins{Chris}++;
    }
}

if ($player_wins{Mishka} > $player_wins{Chris}) {
    print 'Mishka';
} elsif($player_wins{Chris} > $player_wins{Mishka}) {
    print 'Chris';
} else {
    print 'Friendship is magic!^^';
}

#!/usr/bin/env perl

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

# send argument as array, not reference, to function requiring list

# 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 $a = "Mishka";
my $b = "Chris";
my $c = "Friendship is magic!^^";

my $n = read_token;

my $balance = 0;

for (1..$n) {
    my $p = read_token;
    my $q = read_token;
    $balance++ if $p > $q;
    $balance-- if $p < $q;
}

say $a if $balance > 0;
say $b if $balance < 0;
say $c if $balance == 0;

# cf703a
my $n=<>;
my $s;
foreach (<>) {
  my ($m,$c)=split(' ',$_);
  if($m>$c) {++$s;}
  elsif($m<$c) {--$s;}
}

print $s>0 ? 'Mishka' : $s<0 ? 'Chris' : 'Friendship is magic!^^';

use strict;
use warnings;

use Data::Dumper;

my $n = <>;
chomp $n;

die ('wrong n..') unless $n >= 1;

my %player_wins;
$player_wins{Mishka} = 0;
$player_wins{Chris} = 0;

for (my $i=0; $i<$n; $i++) {
    my $in = <>;
    chomp $in;
    my ($m , $c) = split(' ', $in);

    if ($m > $c) {
        $player_wins{Mishka}++;
    } else {
        $player_wins{Chris}++;
    }
}

if ($player_wins{Mishka} > $player_wins{Chris}) {
    print 'Mishka';
} elsif($player_wins{Chris} > $player_wins{Mishka}) {
    print 'Chris';
} else {
    print 'Friendship is magic!^^';
}

use strict;
use warnings;

my $n = <>;
chomp $n;

die ('wrong n..') unless $n >= 1;

my %player_wins;
$player_wins{Mishka} = 0;
$player_wins{Chris} = 0;
$player_wins{draw} = 0;

for (my $i=0; $i<$n; $i++) {
    my $in = <>;
    chomp $in;
    my ($m , $c) = split(' ', $in);

    if ($m == $c) {
        $player_wins{draw}++;
    } elsif ($m > $c) {
        $player_wins{Mishka}++;
    } else {
        $player_wins{Chris}++;
    }
}

my $max = 'draw';

    if ($player_wins{Mishka} > $player_wins{$max}) {
        $max = 'Mishka';
    }
    if ($player_wins{Chris} > $player_wins{$max}) {
        $max = 'Chris';
    }
    if ($player_wins{Chris} == $player_wins{Mishka}) {
        $max = 'draw';
    }
print $max;

use strict;
use warnings;

my $n = <>;
chomp $n;

die ('wrong n..') unless $n >= 1;

my %player_wins;
$player_wins{Mishka} = 0;
$player_wins{Chris} = 0;
$player_wins{draw} = 0;

for (my $i=0; $i<$n; $i++) {
    my $in = <>;
    chomp $in;
    my ($m , $c) = split(' ', $in);

    if ($m == $c) {
        $player_wins{draw}++;
    } elsif ($m > $c) {
        $player_wins{Mishka}++;
    } else {
        $player_wins{Chris}++;
    }
}

my $max = 'draw';

    if ($player_wins{Mishka} > $player_wins{$max}) {
        $max = 'Mishka';
    }
    if ($player_wins{Chris} > $player_wins{$max}) {
        $max = 'Chris';
    }
    if ($player_wins{Chris} == $player_wins{Mishka}) {
        $max = 'draw';
    }
my $out = ($max eq 'draw') ? 'Friendship is magic!^^' : $max;

print $out;

use strict;
use warnings;

use Data::Dumper;

# rows 10
# per row: 2x2
# find to seats next to each other...

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

die('wrong number or rows') unless $n >=0 && $n <= 100;

# store input as array with length n * 2
# loop array, find first seat with OO.
# found: change 00 to ++
# exit and print result

my @buss;
my @left;
my @right;
for (0..$n-1) {
    my $in = <>;
    chomp($in);
    my @seats = split('\|', $in);
#    print Dumper \@seats;
    push @left, $seats[0];
    push @right, $seats[1];
}
@buss = (@left, @right);

for (@buss) {
    if ($_ eq 'OO') {
        print "YES\n";
        $_ = '++';
        print_bus(\@buss, $n);
        exit;
    }
}
print "NO\n";

sub print_bus {
    my ($buss, $n) = @_;

    for (my $i=0; $i<$n; $i++) {
        my $row = $buss->[$i] . '|' . $buss->[$n + $i];
        print $row . "\n";
    }
}

use strict;
use warnings;

my $n = <>;
chomp $n;

die ('wrong n..') unless $n >= 1;

my %player_wins;
for (my $i=0; $i<$n; $i++) {
    my $in = <>;
    chomp $in;
    my ($m , $c) = split(' ', $in);

    if ($m == $c) {
        $player_wins{draw}++;
    } elsif ($m > $c) {
        $player_wins{Mishka}++;
    } else {
        $player_wins{Chris}++;
    }
}

my @sorted = sort { $player_wins{$b} <=> $player_wins{$a} } keys %player_wins;
my $winner = shift @sorted;

my $out = ($winner eq 'draw') ? 'Friendship is magic!^^' : $winner;

print $out;


There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.

The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105).

Output a single integer — the optimal number of visible kangaroos.

my $num = <>;
chomp $num;

my @kangaroo;
for (1..$num) {
    my $size = <>;
    chomp $size;
    push @kangaroo, $size;
}
@kangaroo = sort {$a<=>$b} @kangaroo;

my $count = $num;
my $low = int($num/2) - 1;
my $high = $num - 1;
while ($low>=0) {
    if (2 * $kangaroo[$low] <= $kangaroo[$high]) {
        $count--;
        $high--;
    }
    $low--;
}

print $count;

my $num = <>;
chomp $num;

my @kangaroo;
for (1..$num) {
    my $size = <>;
    chomp $size;
    push @kangaroo, $size;
}
@kangaroo = sort {$b<=>$a} @kangaroo;

my $small_i = 0;
if (2 * $kangaroo[-1] <= $kangaroo[0]){
    $small_i++ while 2 * $kangaroo[$small_i] > $kangaroo[0];

    my $big_i = $small_i-1;
    while ($big_i >= 0 && $small_i <= $#kangaroo) {
        for my $i($small_i..$#kangaroo) {
            if ($kangaroo[$big_i] >= $kangaroo[$i] * 2) {
                splice @kangaroo, $i, 1;
                last;
            }
        }
        $big_i--;
    }
}
print scalar @kangaroo;


Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.

The first line of the input contains two integers n and a (1 ≤ n ≤ 100 000,  - 1 000 000 ≤ a ≤ 1 000 000) — the number of checkpoints and Vasya's starting position respectively. The second line contains n integers x1, x2, ..., xn ( - 1 000 000 ≤ xi ≤ 1 000 000) — coordinates of the checkpoints.

Print one integer — the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.

NoteIn the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point  - 10.


You are given an array $$$a$$$ of $$$2n$$$ distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its $$$2$$$ neighbours.More formally, find an array $$$b$$$, such that: $$$b$$$ is a permutation of $$$a$$$.For every $$$i$$$ from $$$1$$$ to $$$2n$$$, $$$b_i \neq \frac{b_{i-1}+b_{i+1}}{2}$$$, where $$$b_0 = b_{2n}$$$ and $$$b_{2n+1} = b_1$$$. It can be proved that under the constraints of this problem, such array $$$b$$$ always exists.

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$ — the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(1 \leq n \leq 25)$$$. The second line of each testcase contains $$$2n$$$ integers $$$a_1, a_2, \ldots, a_{2n}$$$ $$$(1 \leq a_i \leq 10^9)$$$ — elements of the array. Note that there is no limit to the sum of $$$n$$$ over all testcases.

For each testcase, you should output $$$2n$$$ integers, $$$b_1, b_2, \ldots b_{2n}$$$, for which the conditions from the statement are satisfied.


Polycarp has guessed three positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$.You have to guess three numbers $$$a$$$, $$$b$$$ and $$$c$$$ using given numbers. Print three guessed integers in any order.Pay attention that some given numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (it is also possible that $$$a=b=c$$$).

The only line of the input contains four positive integers $$$x_1, x_2, x_3, x_4$$$ ($$$2 \le x_i \le 10^9$$$) — numbers written on a board in random order. It is guaranteed that the answer exists for the given number $$$x_1, x_2, x_3, x_4$$$.

Print such positive integers $$$a$$$, $$$b$$$ and $$$c$$$ that four numbers written on a board are values $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$ written in some order. Print $$$a$$$, $$$b$$$ and $$$c$$$ in any order. If there are several answers, you can print any. It is guaranteed that the answer exists.

my $line = <STDIN>;
chomp $line;
my @numbers = split ' ', $line;

my $max = 0;
my $idx = 0;
for (@numbers) {
    $max = $idx if $_ > $numbers[$max];
    $idx++;
}

my @output;
$idx = 0;
for (@numbers) {
    if ($idx != $max) {
        push @output, $numbers[$max] - $_;
    }
    $idx++;
}

print join(' ', @output) . "\n";

#!/usr/bin/env perl

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

# essential
my @tokens = ();

my @sums = split q{ }, read_line();

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

my $abc = pop @sums;

my $answer = '';

$answer .= $sums[0] + $sums[1] - $abc;
$answer .= ' ';
$answer .= $sums[1] + $sums[2] - $abc;
$answer .= ' ';
$answer .= $sums[2] + $sums[0] - $abc;

say $answer;

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

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

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

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

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

my $line = <STDIN>;
chomp $line;
my @numbers = split ' ', $line;

my $max = -1;
my $idx = 0;
for (@numbers) {
    $max = $idx if $_ > $numbers[max];
    $idx++;
}

my @output;
$idx = 0;
for (@numbers) {
    if ($idx != $max) {
        push @output, $numbers[$max] - $_;
    }
    $idx++;
}

print join(' ', @output) . "\n";

#!/usr/bin/env perl

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

# essential
my @tokens = ();

my @sums = split q{ }, read_line();

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

say @sums;

my $abc = pop @sums;

my $answer = '';

$answer .= $sums[0] + $sums[1] - $abc;
$answer .= ' ';
$answer .= $sums[1] + $sums[2] - $abc;
$answer .= ' ';
$answer .= $sums[2] + $sums[0] - $abc;

say $answer;

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

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

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

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

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

#!/usr/bin/env perl

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

# essential
my @tokens = ();

my @sums = split q{ }, read_line();

@sums = sort @sums;

my $abc = pop @sums;

my $answer = '';

$answer .= $sums[0] + $sums[1] - $abc;
$answer .= ' ';
$answer .= $sums[1] + $sums[2] - $abc;
$answer .= ' ';
$answer .= $sums[2] + $sums[0] - $abc;

say $answer;

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

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

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

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

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


In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.

The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles. The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).

Print a single number — the sought number of days.

NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.


New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is wi.As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.  He lifts all the books above book x.  He pushes book x out of the stack.  He puts down the lifted books without changing their order.  After reading book x, he puts book x on the top of the stack.  He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer bj (1 ≤ bj ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?

The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books. The second line contains n space-separated integers w1, w2, ..., wn (1 ≤ wi ≤ 100) — the weight of each book. The third line contains m space separated integers b1, b2, ..., bm (1 ≤ bj ≤ n) — the order of books that he would read. Note that he can read the same book more than once.

Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.

NoteHere's a picture depicting the example. Each vertical column presents the stacked books.

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

chomp (my ($n, $m) = split /\s+/, <STDIN>);
chomp (my (@w) = split /\s+/, <STDIN>);
chomp (my (@b) = split /\s+/, <STDIN>);

my @order;
my %seen;
foreach (@b) {
  push @order, $_ if not exists $seen{$_};
  $seen{$_}++;
}

my @arr;
foreach (@order) {
  push @arr, $w[$_ - 1];
}

# printf "@arr\n";
my $sum = 0;
my $x;

sub findIdx {
  for (my $i = 0; $i < @order; $i++) {
    return $i if ($order[$i] == $_[0])
  }
}

foreach (@b) {
  $x = &findIdx($_);
  $sum += &sum(@arr[0 .. ($x - 1)]) if ($x > 0);
  unshift @arr, splice @arr, $x, 1;
  unshift @order, splice @order, $x, 1;
}

printf "$sum\n";

use warnings; use strict;
my ($n, $m) = split ' ', scalar<>;
$n += 0; $m+= 0;
my @a = split ' ', scalar <>; $_ += 0 foreach @a;
my @b = split ' ', scalar <>; $_ -= 1 foreach @b;
my @c = (0) x $n;
my @after = (0) x $n;
$after[$_] = [(0) x $n] foreach (0 .. ($n-1));
my $res = 0;
foreach my $b (@b){
    $res += $c[$b];
    #print @{$after[$_]}, "\n" foreach (0 .. ($n-1));
    #print join ' ', @c;
    #print " $res\n";
    foreach (0 .. ($n-1)){
        $c[$_] += $a[$b] unless $after[$b][$_];
        }
    foreach (0 .. ($n-1)){
        $after[$b][$_] = 1;
        $after[$_][$b] = 0;
        }
    $c[$b] = 0;
    }
print "$res\n";


You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.Let instability of the array be the following value: $$$\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$$$.You have to remove exactly one element from this array to minimize instability of the resulting $$$(n-1)$$$-elements array. Your task is to calculate the minimum possible instability.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — elements of the array $$$a$$$.

Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $$$a$$$.

NoteIn the first example you can remove $$$7$$$ then instability of the remaining array will be $$$3 - 1 = 2$$$.In the second example you can remove either $$$1$$$ or $$$100000$$$ then instability of the remaining array will be $$$100000 - 100000 = 0$$$ and $$$1 - 1 = 0$$$ correspondingly.


You are given an array $$$a_{1}, a_{2}, \ldots, a_{n}$$$. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct.In other words, at most one time you can choose two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) and delete integers $$$a_l, a_{l+1}, \ldots, a_r$$$ from the array. Remaining elements should be pairwise distinct. Find the minimum size of the subsegment you need to remove to make all remaining elements distinct.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of elements in the given array. The next line contains $$$n$$$ spaced integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$1 \le a_{i} \le 10^{9}$$$) — the elements of the array.

Print a single integer — the minimum size of the subsegment you need to remove to make all elements of the array pairwise distinct. If no subsegment needs to be removed, print $$$0$$$.

NoteIn the first example all the elements are already distinct, therefore no subsegment needs to be removed.In the second example you can remove the subsegment from index $$$2$$$ to $$$3$$$.In the third example you can remove the subsegments from index $$$1$$$ to $$$2$$$, or from index $$$2$$$ to $$$3$$$, or from index $$$3$$$ to $$$4$$$.

#!/usr/bin/env perl

use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

chomp (my $n = <STDIN>);

my @array;
push @array, split (q{ }, <STDIN>);

my $answer = "INF";

for my $i (0..$n-1) {
    my %count;
    my $prefix_exists = FALSE;
    for my $j (0..$i-1) {
        my $number = $array[$j];
        my $c = ++$count{$number};
        if ( $c == 2 ) {
            $prefix_exists = TRUE;
            last;
        }
    }

    my $suffix_index = $n;

    for my $j (reverse $i..$n-1) {
        my $number = $array[$j];
        my $c = ++$count{$number};
        if ( $c == 1 ) {
            $suffix_index = $j;
        }
        else {
            last;
        }
    }

    if ( !$prefix_exists ) {
        $answer = min($answer, $suffix_index-$i);
    }
}

say $answer;

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

#!/usr/bin/env perl

use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

chomp (my $n = <STDIN>);

my @array = (0);
push @array, split (q{ }, <STDIN>);

my $l = 0;
my $r = 0;
my %count;

my $answer = "INF";

for my $i (1..$n) {
    my $prefix_exists = FALSE;
    for my $j (1..$i) {
        my $number = $array[$j];
        my $c = ++$count{$number};
        if ( $c == 2 ) {
            $prefix_exists = TRUE;
            last;
        }
    }

    my $suffix_index = $n;

    for my $j (reverse $i..$n) {
        my $number = $array[$j];
        my $c = ++$count{$number};
        if ( $c == 1 ) {
            $suffix_index = $j;
        }
        else {
            last;
        }
    }

    if ( !$prefix_exists ) {
        $answer = min($answer, $suffix_index-$i-1);
    }

    %count = ();
}

say ($answer < 0 ? 0 : $answer);

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

#!/usr/bin/env perl

use strict;
use warnings;
use feature qw/ say /;
use constant TRUE => 1;
use constant FALSE => 0;

chomp (my $n = <STDIN>);

my @array = (0);
push @array, split (q{ }, <STDIN>);

my $l = 0;
my $r = 0;
my %count;

my $answer = "INF";

for my $i (1..$n) {
    my $prefix_exists = FALSE;
    for my $j (1..$i) {
        my $number = $array[$j];
        my $c = ++$count{$number};
        if ( $c == 2 ) {
            $prefix_exists = TRUE;
            last;
        }
    }

    my $suffix_index = $n+1;

    for my $j (reverse $i..$n) {
        my $number = $array[$j];
        my $c = ++$count{$number};
        if ( $c == 1 ) {
            $suffix_index = $j;
        }
        else {
            last;
        }
    }

    if ( !$prefix_exists ) {
        $answer = min($answer, $suffix_index-$i-1);
    }

    %count = ();
}

say ($answer < 0 ? 0 : $answer);

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

#!/usr/bin/env perl

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

chomp (my $n = <STDIN>);

my @array = (0);
push @array, split (q{ }, <STDIN>);

my $l = 0;
my $r = 0;
my %count;

my $answer = 0;

for (1..$n) {
    my $number = $array[$_];
    my $c = ++$count{$number};
    if ( $c >= 2 ) {
        $l = $_;
        last;
    }
}

if ( $l != 0 ) {
    for ( reverse $l+1 .. $n ) {
        my $number = $array[$_];
        my $c = ++$count{$number};
        if ( $c >= 2 ) {
            $r = $_;
            $answer = $r-$l+1;
            last;
        }
    }
}

say $answer;


There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.

The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i.

Print the maximum number of teams of three people the coach can form.

NoteIn the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.In the second example he can't make a single team.In the third example the coach can form three teams. For example, he can do this in the following way:  The first group (of two people) and the seventh group (of one person),  The second group (of two people) and the sixth group (of one person),  The third group (of two people) and the fourth group (of one person).


In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 or i + 1 > n, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.

Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.

NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field.

$,=" ";
my $n=<>;
my $str=<>;
chomp($str);
while(1)
{
  last if index($str,'><')<0;
  $str =~ s/>+<+//g;
}

print length($str) , "\n";

$,=" ";
my $n=<>;
my $str=<>;
chomp($str);
while(1)
{
  last if index($str,'><')<0;
  $str =~ s/><//g;
}

print length($str) , "\n";


In BerSoft $$$n$$$ programmers work, the programmer $$$i$$$ is characterized by a skill $$$r_i$$$.A programmer $$$a$$$ can be a mentor of a programmer $$$b$$$ if and only if the skill of the programmer $$$a$$$ is strictly greater than the skill of the programmer $$$b$$$ $$$(r_a > r_b)$$$ and programmers $$$a$$$ and $$$b$$$ are not in a quarrel.You are given the skills of each programmers and a list of $$$k$$$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $$$i$$$, find the number of programmers, for which the programmer $$$i$$$ can be a mentor.

The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$$$ — total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $$$r_1, r_2, \dots, r_n$$$ $$$(1 \le r_i \le 10^{9})$$$, where $$$r_i$$$ equals to the skill of the $$$i$$$-th programmer. Each of the following $$$k$$$ lines contains two distinct integers $$$x$$$, $$$y$$$ $$$(1 \le x, y \le n$$$, $$$x \ne y)$$$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $$$x$$$ is in a quarrel with $$$y$$$ then $$$y$$$ is in a quarrel with $$$x$$$. Guaranteed, that for each pair $$$(x, y)$$$ there are no other pairs $$$(x, y)$$$ and $$$(y, x)$$$ in the input.

Print $$$n$$$ integers, the $$$i$$$-th number should be equal to the number of programmers, for which the $$$i$$$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.

NoteIn the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.

# author : Gabriel Hofer
use strict;
use warnings;
use constant NL => qq/\n/;
sub max { $_ [ 0 ] > $_ [ 1 ] ? $_ [ 0 ] : $_ [ 1 ] }
my %quarrel = ();
my ( $n, $k ) = split qq / /, <STDIN>;
my @skill = split qq/ /, <STDIN>;
my @skill_sorted = sort { $a <=> $b } @skill;

my %h = ();
AA: for ( 1 .. $k  ) {
    my ( $five, $six ) = split qq/ /, <STDIN>;
    if ( $skill [ $five - 1 ] > $skill [ $six - 1 ] ) {
        $quarrel { $five } = 0 if not exists $quarrel { $five };
        $quarrel { $five } += 1;
        next AA
    } elsif ( $skill [ $five - 1 ] < $skill [ $six - 1 ] ) {
        $quarrel { $six } = 0 if not exists $quarrel { $six };
        $quarrel { $six } += 1;
        next AA
    }
}

AB: for my $j ( 1 .. ($#skill + 1) ) {
    (not (my $left = 0)) and (my $right = $#skill + 1) and (my $mid);
    AC: while ( $left < $right ) {
        $mid = int ( ( $left + $right ) / 2 );
        if ( $skill_sorted [ $mid ] < ($skill [ $j - 1 ]) ) { ($left = $mid + 1) and next AC }
        else { ($right = $mid) and next AC }
    }
    $mid = int ( ( $left + $right ) / 2 );
    if ( exists $quarrel { $j } ) { print max ( 0, $mid - $quarrel { $j } ) }
    else { print $mid }
    print qq/ /;
}
print NL;

#!/usr/bin/perl

use warnings;
use strict;

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

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

	my @sA = sort { $a <=> $b } @A;
	my @B;

	my $prev = $sA[ 0 ];
	my %h;

	for my $i ( 0 .. @sA - 1 ){
		next if $sA[ $i ] == $prev;
		$h{ $sA[ $i ] } = $i;
		$prev = $sA[ $i ];
		}

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

	for( 1 .. $k ){
		my( $u, $v ) = split ' ', <>;
		$debug and print "$u|$v||$A[ $u - 1 ]|$A[ $v - 1 ]";
		next if $A[ $u - 1 ] == $A[ $v - 1 ];
		$B[ $A[ $u - 1 ] > $A[ $v - 1 ] ? $u - 1 : $v - 1 ] --;
		}

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

	print join ' ', map { ( $h{ $_ } || 0 ) + shift @B } @A;

	$debug and print '-' x 15;
	}

# author : Gabriel Hofer
use strict;
use warnings;
use constant NL => qq/\n/;
sub max { $_ [ 0 ] > $_ [ 1 ] ? $_ [ 0 ] : $_ [ 1 ] }
my %quarrel = ();
my ( $n, $k ) = split qq / /, <STDIN>;
my @skill = split qq/ /, <STDIN>;
my @skill_sorted = sort { $a <=> $b } @skill;

my %h = ();
AA: for ( 1 .. $k  ) {
    my ( $five, $six ) = ( <STDIN> =~ m /(\d+)\s(\d+)/ );
    my $nine;
    if ( $skill [ $five - 1 ] > $skill [ $six - 1 ] ) { $nine = $five }
    else { $nine = $six }
    $quarrel { $nine } = 0 if not exists $quarrel { $nine };
    $quarrel { $nine } += 1;
}

AA: for my $j ( 1 .. ($#skill + 1) ) {
    (not (my $left = 0)) and (my $right = $#skill + 1) and (my $mid);
    AB: while ( $left < $right ) {
        $mid = int ( ( $left + $right ) / 2 );
        if ( $skill_sorted [ $mid ] < ($skill [ $j - 1 ]) ) { ($left = $mid + 1) and next AB }
        else { ($right = $mid) and next AB }
    }
    $mid = int ( ( $left + $right ) / 2 );
    if ( exists $quarrel { $j } ) { print $mid - $quarrel { $j } }
    else { print $mid }
    print qq/ /;
}
print NL;

# author : Gabriel Hofer
use strict;
use warnings;
use constant NL => qq/\n/;
sub max { $_ [ 0 ] > $_ [ 1 ] ? $_ [ 0 ] : $_ [ 1 ] }
my %quarrel = ();
my ( $n, $k ) = split qq / /, <STDIN>;
my @skill = split qq/ /, <STDIN>;
my @skill_sorted = sort { $a <=> $b } @skill;

my %h = ();
AA: for ( 1 .. $k  ) {
    my ( $five, $six ) = ( <STDIN> =~ m /(\d+)\s(\d+)/ );
    my $nine;
    if ( $skill [ $five - 1 ] > $skill [ $six - 1 ] ) { $nine = $five }
    else { $nine = $six }
    $quarrel { $nine } = 0 if not exists $quarrel { $nine };
    $quarrel { $nine } += 1;
}

AA: for my $j ( 1 .. ($#skill + 1) ) {
    (not (my $left = 0)) and (my $right = $#skill + 1) and (my $mid);
    AB: while ( $left < $right ) {
        $mid = int ( ( $left + $right ) / 2 );
        if ( $skill_sorted [ $mid ] < ($skill [ $j - 1 ]) ) { ($left = $mid + 1) and next AB }
        else { ($right = $mid) and next AB }
    }
    $mid = int ( ( $left + $right ) / 2 );
    if ( exists $quarrel { $j } ) { print max ( 0, $mid - $quarrel { $j } ) }
    else { print $mid }
    print qq/ /;
}
print NL;

#!/usr/bin/perl

use warnings;
use strict;

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

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

	my @sA = sort { $a <=> $b } @A;
	my @B;

	my $prev = $sA[ 0 ];
	my %h;

	for my $i ( 0 .. @sA - 1 ){
		next if $sA[ $i ] == $prev;
		$h{ $sA[ $i ] } = $i;
		$prev = $sA[ $i ];
		}

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

	for( 1 .. $k ){
		my( $u, $v ) = split ' ', <>;
		$debug and print "$u|$v||$A[ $u - 1 ]|$A[ $v - 1 ]";
		$B[ $A[ $u - 1 ] > $A[ $v - 1 ] ? $u - 1 : $v - 1 ] --;
		}

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

	print join ' ', map { ( $h{ $_ } || 0 ) + shift @B } @A;

	$debug and print '-' x 15;
	}


Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.

The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.

Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.

NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and  for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.

#
# Hello World Program in Perl
#
use strict;

my $count = <>;
my (%hf, %hs);
my %pair;
my %all;
for(1..$count)
{
    my ($a, $b) = split /\s/, <>;

    $hf{$a}++;
    $hs{$b}++;

    if($a == $b)
    {
        $pair{$a}++;
    }
    else
    {
        $all{"[$a][$b]"}++;
    }
}
my $ans = 0;

my @toDel;
for(keys(%hf))
{
    $ans += f($hf{$_});

}

for(keys(%hs))
{
    $ans += f($hs{$_});

}

for(keys(%pair))
{
    $ans -=f($pair{$_});
}

for(keys(%all))
{
    $ans-=f($all{$_});
}

print $ans;

sub f($)
{
    my $ans = 0;
    for(1..$_[0]-1)
    {
        $ans += $_;
    }
    return $ans;
}


This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format:  $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$  $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).

After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).

NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.