Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.

The first line of the input contains one integer, n (1 ≤ n ≤ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive.

Print the maximum possible even sum that can be obtained if we use some of the given integers.

NoteIn the first sample, we can simply take all three integers for a total sum of 6.In the second sample Wet Shark should take any four out of five integers 999 999 999.

#!/usr/bin/perl

while (<>) {
    my @nums = split(/ /, <>);
    my @odds;
    my $sum = 0;

    $_ & 1 ? push @odds, $_ : ($sum += $_) for @nums;

    if (@odds & 1) {
        @odds = sort {$a <=> $b} @odds;
        $sum += $_ for @odds[1..$#odds];
    } else {
        $sum += $_ for @odds;
    }

    print "$sum";
}

#!/usr/bin/perl

while (<>) {
    my @nums = split(/ /, <>);
    my @odds;
    my $sum = 0;

    $_ & 1 ? push @odds, $_ : ($sum += $_) for @nums;

    if (@odds & 1) {
        @odds = sort {$a <=> $b} @odds;
        $sum += $_ for @odds[-$#odds..-1];
    } else {
        $sum += $_ for @odds;
    }

    print "$sum";
}

#!/usr/bin/perl

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

my @nums = split(/ /, $line);
my @odds;
my $sum = 0;

$_ & 1 ? push @odds, $_ : ($sum += $_) for @nums;

if (@odds % 2 == 0) {
    $sum += $_ for @odds;
} else {
    @odds = sort {$a <=> $b} @odds;
    shift @odds;
    $sum += $_ for @odds;
}

print "$sum";

#!/usr/bin/perl

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

my @nums = split(/ /, $line);

my @odds;
my $sum = 0;
for (@nums) {
    if ($_ % 2 == 0) {
        $sum += $_;
    } else {
        push @odds, $_;
    }
}

if (@odds % 2 == 0) {
    for (@odds) {
        $sum += $_;
    }
} else {
    @odds = sort {$a <=> $b} @odds;
    shift @odds;
    for (@odds) {
        $sum += $_;
    }
}

print "$sum";

#!/usr/bin/perl

while (<>) {
    my @nums = split(/ /, <>);
    my @odds;
    my $sum = 0;

    $_ & 1 ? push @odds, $_ : ($sum += $_) for @nums;

    if (@odds & 1) {
        @odds = sort {$a <=> $b} @odds;
        shift @odds;
    }
    $sum += $_ for @odds;

    print "$sum";
}

#!/usr/bin/perl

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

my @nums = split(/ /, $line);

my (@evens, @odds);

for (@nums) {
    if ($_ % 2 == 0) {
        push @evens, $_;
    } else {
        push @odds, $_;
    }
}

my $sum = 0;

for (@evens) {
    $sum += $_;
}

if (@odds % 2 == 0) {
    for (@odds) {
        $sum += $_;
    }
} else {
    @odds = reverse sort @odds;
    for (@odds[-$#odds..-1]) {
        $sum += $_;
    }
}

print "$sum";

#!/usr/bin/perl

while (<>) {
    my @nums = split(/ /, <>);
    my @odds;
    my $sum = 0;

    $_ & 1 ? push @odds, $_ : ($sum += $_) for @nums;

    if (@odds & 1) {
        @odds = sort @odds;
        $sum += $_ for @odds[1..$#odds];
    } else {
        $sum += $_ for @odds;
    }

    print "$sum";
}

#!/usr/bin/perl

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

my @nums = split(/ /, $line);

my (@evens, @odds);

for (@nums) {
    if ($_ % 2 == 0) {
        push @evens, $_;
    } else {
        push @odds, $_;
    }
}

my $sum = 0;

for (@evens) {
    $sum += $_;
}

if (@odds % 2 == 0) {
    for (@odds) {
        $sum += $_;
    }
} else {
    @odds = sort @odds;
    for (@odds[-$#odds..-1]) {
        $sum += $_;
    }
}

print "$sum";


You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.The following definition of a regular bracket sequence is well-known, so you can be familiar with it.Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.Determine the least number of replaces to make the string s RBS.

The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.

If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s.


The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to figure out whether the document has malfunctioned. Specifically, he is given a string of length $$$n$$$ whose characters are all either T or M, and he wants to figure out if it is possible to partition it into some number of disjoint subsequences, all of which are equal to TMT. That is, each character of the string should belong to exactly one of the subsequences.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) characters.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$)  — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$3 \le n < 10^5$$$), the number of characters in the string entered in the document. It is guaranteed that $$$n$$$ is divisible by $$$3$$$. The second line of each test case contains a string of length $$$n$$$ consisting of only the characters T and M. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single line containing YES if the described partition exists, and a single line containing NO otherwise.

5
3
TMT
3
MTT
6
TMTMTT
6
TMTTTT
6
TTMMTT

NoteIn the first test case, the string itself is already a sequence equal to TMT.In the third test case, we may partition the string into the subsequences TMTMTT. Both the bolded and the non-bolded subsequences are equal to TMT.


The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dn - 1 is the distance between the n - 1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.

The first line contains integer n (3 ≤ n ≤ 100) — the number of stations on the circle line. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 100) — the distances between pairs of neighboring stations. The third line contains two integers s and t (1 ≤ s, t ≤ n) — the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces.

Print a single number — the length of the shortest path between stations number s and t.

NoteIn the first sample the length of path 1 → 2 → 3 equals 5, the length of path 1 → 4 → 3 equals 13.In the second sample the length of path 4 → 1 is 100, the length of path 4 → 3 → 2 → 1 is 15.In the third sample the length of path 3 → 1 is 1, the length of path 3 → 2 → 1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.

#!usr/bin/perl
#use warnings;
#use strict;
#use autodie;
#use diagnostics;
use utf8;
use 5.010;
use 5.012;
use 5.014;
my($n,$ss,@arr,$s,$t,$count,$max);
chomp($n=<STDIN>);
chomp($ss=<STDIN>);
@arr=split / /,$ss;
chomp($ss=<STDIN>);
($s,$t)=split / /,$ss;
$count=$s;
$max=999999999;
$ss=0;
while($count ne $t)
{
    $ss+=$arr[$count-1];
    $count=0 if $count eq $n;
    $count++;
}
$max=$ss if $max > $ss;
($ss,$count)=(0,$s);
while($count ne $t)
{
    $count=$n+1 if $count eq 1;
    $count--;
    $ss+=$arr[$count-1];
}
$max=$ss if $max > $ss;
say $max;

#!/usr/bin/perl -w
use strict;
use warnings;
use List::Util qw{sum min};

my $n = int <>;
my @d = map int, split /\D/, <>;
my ($s, $t) = map int, split /\D/, <>;
if ($s > $t) {
    my $tmp = $t;
    $t = $s;
    $s = $tmp;
}
my $s1 = 0;
for ($s-1 .. $t-2) {
    $s1 += $d[$_];
}
my $s2 = (sum @d) - $s1;
print min ($s1, $s2);

my $num = <>;
chomp $num;
my @dist = grep /\w/, split ' ', <>;
my ($s, $t) = sort {$a <=> $b} split ' ', <>;

my $r = 0;
$r += $dist[$_-1] for $s..$t-1;
my $total;
$total += $dist[$_-1] for 1..$num;
my $l = $total - $r;
print $r < $l ? $r : $l;


A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show.The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions:  Is it true that y is strictly larger than number x?  Is it true that y is strictly smaller than number x?  Is it true that y is larger than or equal to number x?  Is it true that y is smaller than or equal to number x? On each question the host answers truthfully, "yes" or "no".Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 10000) — the number of questions (and answers). Next n lines each contain one question and one answer to it. The format of each line is like that: "sign x answer", where the sign is:   ">" (for the first type queries),  "<" (for the second type queries),  ">=" (for the third type queries),  "<=" (for the fourth type queries).  All values of x are integer and meet the inequation  - 109 ≤ x ≤ 109. The answer is an English letter "Y" (for "yes") or "N" (for "no"). Consequtive elements in lines are separated by a single space.

Print any of such integers y, that the answers to all the queries are correct. The printed number y must meet the inequation  - 2·109 ≤ y ≤ 2·109. If there are many answers, print any of them. If such value doesn't exist, print word "Impossible" (without the quotes).

#!/perl -w

use strict ;

chomp ( my $n = <STDIN> );
my($gmax,$gmin) = (2*10**9,-2*10**9) ;
while($n-- ){
    my($symbol,$guess,$answer) = split /\s+/s , <STDIN> ;
    if($answer eq 'N'){
        my $temp = $symbol ;
        $symbol = '<'  if $temp eq '>=' ;
        $symbol = '<=' if $temp eq '>'  ;
        $symbol = '>'  if $temp eq '<=' ;
        $symbol = '>=' if $temp eq '<' ;
    }

    $gmin = ($guess > $gmin)? $guess : $gmin  if $symbol eq '>=' ;
    $gmin = ($guess + 1 > $gmin)? $guess +1 : $gmin  if $symbol eq '>' ;
    $gmax = ($guess < $gmax)? $guess : $gmax  if $symbol eq '<=' ;
    $gmax = ($guess - 1 < $gmax)? $guess -1 : $gmax  if $symbol eq '<' ;
}

if($gmax < $gmin){
    print "Impossible\n" ;
}else{
    print "$gmin\n";
}


Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.

The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.

Print a single number — the number of distinct letters in Anton's set.

my $str = <>;
$str =~ s/{([^{}]*)}\n/$1/;
my %hash = map { $_, 1 } split ", ", $str;
print scalar keys %hash;

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

my %st;
chomp($line = <>);
$st{$_}++ foreach(split ", ", substr $line, 1, length($line)-2);
say scalar(keys %st);

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

my $s = <>;
chomp $s;

$s = substr(substr($s, 0, -1), 1);

my %set;

foreach my $letter (split(', ', $s))
{
    $set{$letter} = 1;
}

my $result = keys %set;

print $result

#!/usr/bin/env perl

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

my $line = <>;

$line =~ s/[^a-z]//g;

my %seen;
foreach my $c (split(//, $line))
{
   $seen{$c} = 1
}

print scalar(keys %seen), "\n"

my $s = <>;
$s = substr ($s, 1, (length $s) - 3);
%k = ();
grep { $k{$_} = $_ } split ", ", $s;
print scalar (keys %k);

#! usr/bin/perl

use warnings;
use strict;

my $line = readline();

my $count = {};

while ($line =~ m/(\w),/g) {
    $count->{$1} = 1;
#   print $1 . "\n";
}
if ($line =~ m/(\w)\}/g) {
    $count->{$1} = 1;
}

my @keys = keys %$count;

my $size = @keys;

print $size . "\n";

my $str = <>;
my $reg = "{([^{}]*)}\n";
$str =~ s/$reg/$1/;
my %hash = map { $_, 1 } split ", ", $str;
print scalar keys %hash;


There is a robot on a coordinate plane. Initially, the robot is located at the point $$$(0, 0)$$$. Its path is described as a string $$$s$$$ of length $$$n$$$ consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move:   'L' (left): means that the robot moves from the point $$$(x, y)$$$ to the point $$$(x - 1, y)$$$;  'R' (right): means that the robot moves from the point $$$(x, y)$$$ to the point $$$(x + 1, y)$$$;  'U' (up): means that the robot moves from the point $$$(x, y)$$$ to the point $$$(x, y + 1)$$$;  'D' (down): means that the robot moves from the point $$$(x, y)$$$ to the point $$$(x, y - 1)$$$. The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point $$$(x_e, y_e)$$$, then after optimization (i.e. removing some single substring from $$$s$$$) the robot also ends its path at the point $$$(x_e, y_e)$$$.This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string $$$s$$$).Recall that the substring of $$$s$$$ is such string that can be obtained from $$$s$$$ by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The next $$$2t$$$ lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the robot's path. The second line of the test case contains one string $$$s$$$ consisting of $$$n$$$ characters 'L', 'R', 'U', 'D' — the robot's path. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers $$$l$$$ and $$$r$$$ such that $$$1 \le l \le r \le n$$$ — endpoints of the substring you remove. The value $$$r-l+1$$$ should be minimum possible. If there are several answers, print any of them.


Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches. The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.

Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.

NoteIn the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.


Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling.  It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.

For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.

NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).


Given a positive integer $$$k$$$, two arrays are called $$$k$$$-similar if:  they are strictly increasing;  they have the same length;  all their elements are positive integers between $$$1$$$ and $$$k$$$ (inclusive);  they differ in exactly one position. You are given an integer $$$k$$$, a strictly increasing array $$$a$$$ and $$$q$$$ queries. For each query, you are given two integers $$$l_i \leq r_i$$$. Your task is to find how many arrays $$$b$$$ exist, such that $$$b$$$ is $$$k$$$-similar to array $$$[a_{l_i},a_{l_i+1}\ldots,a_{r_i}]$$$.

The first line contains three integers $$$n$$$, $$$q$$$ and $$$k$$$ ($$$1\leq n, q \leq 10^5$$$, $$$n\leq k \leq 10^9$$$) — the length of array $$$a$$$, the number of queries and number $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots,a_n$$$ ($$$1 \leq a_i \leq k$$$). This array is strictly increasing  — $$$a_1 < a_2 < \ldots < a_n$$$. Each of the following $$$q$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ ($$$1 \leq l_i \leq r_i \leq n$$$).

Print $$$q$$$ lines. The $$$i$$$-th of them should contain the answer to the $$$i$$$-th query.

NoteIn the first example:In the first query there are $$$4$$$ arrays that are $$$5$$$-similar to $$$[2,4]$$$: $$$[1,4],[3,4],[2,3],[2,5]$$$.In the second query there are $$$3$$$ arrays that are $$$5$$$-similar to $$$[4,5]$$$: $$$[1,5],[2,5],[3,5]$$$.


Phoenix is playing with a new puzzle, which consists of $$$n$$$ identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below.    A puzzle piece The goal of the puzzle is to create a square using the $$$n$$$ pieces. He is allowed to rotate and move the pieces around, but none of them can overlap and all $$$n$$$ pieces must be used (of course, the square shouldn't contain any holes as well). Can he do it?

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the number of puzzle pieces.

For each test case, if Phoenix can create a square with the $$$n$$$ puzzle pieces, print YES. Otherwise, print NO.

NoteFor $$$n=2$$$, Phoenix can create a square like this:    For $$$n=4$$$, Phoenix can create a square like this:    For $$$n=6$$$, it is impossible for Phoenix to create a square.


Polycarp has come up with a new game to play with you. He calls it "A missing bigram".A bigram of a word is a sequence of two adjacent letters in it.For example, word "abbaaba" contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba".The game goes as follows. First, Polycarp comes up with a word, consisting only of lowercase letters 'a' and 'b'. Then, he writes down all its bigrams on a whiteboard in the same order as they appear in the word. After that, he wipes one of them off the whiteboard.Finally, Polycarp invites you to guess what the word that he has come up with was.Your goal is to find any word such that it's possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with.The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the length of the word Polycarp has come up with. The second line of each testcase contains $$$n-2$$$ bigrams of that word, separated by a single space. Each bigram consists of two letters, each of them is either 'a' or 'b'. Additional constraint on the input: there exists at least one string such that it is possible to write down all its bigrams, except one, so that the resulting sequence is the same as the sequence in the input. In other words, the answer exists.

For each testcase print a word, consisting of $$$n$$$ letters, each of them should be either 'a' or 'b'. It should be possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with. The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.

4
7
ab bb ba aa ba
7
ab ba aa ab ba
3
aa
5
bb ab bb

NoteThe first two testcases from the example are produced from the word "abbaaba". As listed in the statement, it contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba".In the first testcase, the $$$5$$$-th bigram is removed. In the second testcase, the $$$2$$$-nd bigram is removed. However, that sequence could also have been produced from the word "abaabaa". It contains bigrams "ab", "ba", "aa", "ab", "ba" and "aa". The missing bigram is the $$$6$$$-th one.In the third testcase, all of "baa", "aab" and "aaa" are valid answers.

#!/usr/bin/perl

use warnings;
use strict;

<>;

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

	s/(.)\K \1//g;

	print m/ / ? s/ //r : s/^/a/r;
	}


Carol is currently curling.She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100.She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.

The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.

Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if  for all coordinates.

NoteThe final positions of the disks will look as follows:  In particular, note the position of the last disk.

my $n, $r;
my $f = <STDIN>;
chomp ( $f );
($n, $r) = split m/ /, $f;
$f = <STDIN>;
chomp ( $f );
my @disks = split m/ /, $f;

my @placed = ();
my $elem;
my $found;
my @yy = ();
my $val;
my $height;

my $j = 0;
my $max;
while ( @disks > 0 ) {

    $elem = shift @disks;
    $found = 0;

    $max = 0;
    for ( my $i = 0; $i < @placed; $i += 1 ) {

	if ( abs ( $elem - $placed[ $i ][ 0 ] ) <= (2 * $r) ) { # if there's a collision
	    $found = 1;

	    $height = sqrt (abs( ((2 * $r) ** 2) - (abs ( $elem - $placed[ $i ][ 0 ] ) ** 2)));
	    $val = $placed[ $i ][ 1 ] + $height;
	    if ( $val > $max ) {
		$max = $val;}
	}
    }

    if ( $found == 1 ) {
	unshift @placed, [ $elem, $max, $j ];
    }

    if ( $found == 0 ) {	# if there's no collision
	unshift @placed, [ $elem, $r, $j ];
    }

    @placed = sort { ${ $a }[ 1 ] <=> ${ $b }[ 1 ] } @placed;
    @placed = reverse @placed;

    $j += 1;
}

my @answer = sort { ${ $a }[ 2 ] <=> ${ $b }[ 2 ] } @placed;

for ( my $i = 0; $i < @answer; $i += 1 ) {
    print $answer[ $i ][ 1 ];
    print " ";}
print "\n";

use 5.016;
use strict;
use warnings;

my (undef, $r) = split ' ', <>;
my @x = split ' ', <>;

my %y;
my @y;

for my $x (@x) {
  my $max = $r;
  while (my ($x2, $y2s) = each %y) {
    for my $y2 (@$y2s) {
      if (abs($x2 - $x) <= 2 * $r) {
        # collision

        # dx^2 + dy^2 = (2r)^2
        my $dy = sqrt(4 * $r**2 - ($x2 - $x)**2);
        my $y = $y2 + $dy;

        $max = $y if $y > $max;
      }
    }
  }

  push @y, $max;
  push @{$y{$x}}, $max;
}

say join ' ', @y;

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $n, $r ) = split;
	my( $x1, @x ) = split ' ', <>;

	my %y;
	$y{ $x1 } = $r;
	my @y;
	push @y, $r;

	my $sqr = ( $r * 2 ) ** 2;

	for my $x ( @x ){

		my $Y = 0;

		for my $xkey ( keys %y ){

			my $B = $sqr - ( $x - $xkey ) ** 2;
			next if $B < 0;

			my $y = $y{ $xkey } + sqrt( $B );

			if( $y >= $Y ){
				$Y = $y;
				}

			}

		$Y ||= $r;
		$y{ $x } = $Y;
		push @y, $Y;
		}

	print "@y";
	}

my $n, $r;
my $f = <STDIN>;
chomp ( $f );
($n, $r) = split m/ /, $f;
$f = <STDIN>;
chomp ( $f );
my @disks = split m/ /, $f;

my @placed = ();
my $elem;
my $found;
my @yy = ();
my $val;
my $height;

my $j = 0;
while ( @disks > 0 ) {

    $elem = shift @disks;
    $found = 0;

    for ( my $i = 0; not $found and $i < @placed; $i += 1 ) {
	if ( abs ( $elem - $placed[ $i ][ 0 ] ) <= (2 * $r) ) { # if there's a collision
	    $found = 1;

	    $height = sqrt (abs( ((2 * $r) ** 2) - (abs ( $elem - $placed[ $i ][ 0 ] ) ** 2)));
	    $val = $placed[ $i ][ 1 ] + $height;
	    unshift @placed, [ $elem, $val, $j ];
	}
    }

    if ( $found == 0 ) {	# if there's no collision
	unshift @placed, [ $elem, $r, $j ];
    }

    @placed = sort { ${ $a }[ 1 ] <=> ${ $b }[ 1 ] } @placed;
    @placed = reverse @placed;
    $j += 1;
}

my @answer = sort { ${ $a }[ 2 ] <=> ${ $b }[ 2 ] } @placed;

for ( my $i = 0; $i < @answer; $i += 1 ) {
    print $answer[ $i ][ 1 ];
    print " ";}
print "\n";

my $n, $r;
my $f = <STDIN>;
chomp ( $f );
($n, $r) = split m/ /, $f;
$f = <STDIN>;
chomp ( $f );
my @disks = split m/ /, $f;

my @placed = ();
my $elem;
my $found;
my @yy = ();
my $val;
my $height;

while ( @disks > 0 ) {

    $elem = shift @disks;
    $found = 0;

    for ( my $i = 0; not $found and $i < @placed; $i += 1 ) {
	if ( abs ( $elem - $placed[ $i ][ 0 ] ) <= (2 * $r) ) { # if there's a collision
	    $found = 1;

	    $height = sqrt (abs( ((2 * $r) ** 2) - (abs ( $elem - $placed[ $i ][ 0 ] ) ** 2)));
	    $val = $placed[ $i ][ 1 ] + $height;
	    unshift @placed, [ $elem, $val ];
	}
    }

    if ( $found == 0 ) {	# if there's no collision
	unshift @placed, [ $elem, $r ];
    }
}

my @answer = reverse @placed;

for ( my $i = 0; $i < @answer; $i += 1 ) {
    print $answer[ $i ][ 1 ];
    print " "; }
print "\n";


Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number , in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a0a1...an equals to .Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.Given two numbers written in golden system notation, determine which of them has larger decimal value.

Input consists of two lines — one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.

Print ">" if the first number is larger, "<" if it is smaller and "=" if they are equal.

NoteIn the first example first number equals to , while second number is approximately 1.6180339882 + 1.618033988 + 1 ≈ 5.236, which is clearly a bigger number.In the second example numbers are equal. Each of them is  ≈ 2.618.


The process of mammoth's genome decoding in Berland comes to its end!One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.

The first line contains the integer n (4 ≤ n ≤ 255) — the length of the genome. The second line contains the string s of length n — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.

If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).

NoteIn the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.In the third and the fourth examples it is impossible to decode the genom.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my %h;

	map { $h{$_}++ } grep /\w/, split //;

	my $L = length;
	my $q = $L / 4;

	print do {
		if ($L % 4 or $q < (sort {$b <=> $a} values %h)[0] ){
			'==='
			}
		else{
			for my $lett (split //, 'ACTG'){
				for my $times ( 1 .. $q - $h{$lett} ){
					s/\?/$lett/
					}
				}
			$_
			}
		};

	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

while(not eof){
	my( $Ax, $Ay, $Bx, $By, $Cx, $Cy ) =
		map { split } ~~<>, ~~<>, ~~<>;

	my( $Dx, $Dy, $Ex, $Ey, $Fx, $Fy );

	$Dx = ($Ax + $Bx) / 2;
	$Dy = ($Ay + $By) / 2;

	$Ex = ($Cx + $Bx) / 2;
	$Ey = ($Cy + $By) / 2;

	$Fx = ($Ax + $Cx) / 2;
	$Fy = ($Ay + $Cy) / 2;

	$debug and print "[$Dx, $Dy, $Ex, $Ey, $Fx, $Fy]";

	my( $AEx, $AEy, $CDx, $CDy, $BFx, $BFy );
	my $diff;

	$diff = $Ex - $Ax;
	$AEx = $Ex + $diff;

	$diff = $Ey - $Ay;
	$AEy = $Ey + $diff;

	$diff = $Dx - $Cx;
	$CDx = $Dx + $diff;

	$diff = $Dy - $Cy;
	$CDy = $Dy + $diff;

	$diff = $Fx - $Bx;
	$BFx = $Fx + $diff;

	$diff = $Fy - $By;
	$BFy = $Fy + $diff;

	print 3;
	print for "$AEx $AEy", "$CDx $CDy", "$BFx $BFy";

	}


Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $$$1$$$. Each person is looking through the circle's center at the opposite person.    A sample of a circle of $$$6$$$ persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $$$c$$$? If, for the specified $$$a$$$, $$$b$$$, and $$$c$$$, no such circle exists, output -1.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a,b,c \le 10^8$$$).

For each test case output in a separate line a single integer $$$d$$$ — the number of the person being looked at by the person with the number $$$c$$$ in a circle such that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$. If there are multiple solutions, print any of them. Output $$$-1$$$ if there's no circle meeting the given conditions.

NoteIn the first test case, there's a desired circle of $$$8$$$ people. The person with the number $$$6$$$ will look at the person with the number $$$2$$$ and the person with the number $$$8$$$ will look at the person with the number $$$4$$$.In the second test case, there's no circle meeting the conditions. If the person with the number $$$2$$$ is looking at the person with the number $$$3$$$, the circle consists of $$$2$$$ people because these persons are neighbors. But, in this case, they must have the numbers $$$1$$$ and $$$2$$$, but it doesn't meet the problem's conditions.In the third test case, the only circle with the persons with the numbers $$$2$$$ and $$$4$$$ looking at each other consists of $$$4$$$ people. Therefore, the person with the number $$$10$$$ doesn't occur in the circle.


Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?You can assume that initially Vanya had infinitely many cards with each integer number from  - x to x.

The first line contains two integers: n (1 ≤ n ≤ 1000) — the number of found cards and x (1 ≤ x ≤ 1000) — the maximum absolute value of the number on a card. The second line contains n space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.

Print a single number — the answer to the problem.

NoteIn the first sample, Vanya needs to find a single card with number -2.In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value.

my ($n, $x) = split / /, <>;
my @arr = split / /, <>;
my $sum;
$sum += $_ for(@arr);
print int((abs($sum)+$x - 1) / $x);

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

($n, $x) = split / /, <>;
$tot+=$_ foreach (split / /, <>);
say ((abs($tot) + $x-1)/$x);

use integer;

while(<>){

	($n,$x)=split/ /;
	$_=<>;
	$sum=0;
	s/-?\d+/$sum+=$&/ge;
#	print "$sum\n";

	$sum=abs $sum;
#	print "$sum\n";
	$answer=$sum/$x + ($sum%$x? 1:0) ;

	print "$answer\n";

	}


Connect the countless points with lines, till we reach the faraway yonder.There are n points on a coordinate plane, the i-th of which being (i, yi).Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes through at least one point in the set.

The first line of input contains a positive integer n (3 ≤ n ≤ 1 000) — the number of points. The second line contains n space-separated integers y1, y2, ..., yn ( - 109 ≤ yi ≤ 109) — the vertical coordinates of each point.

Output "Yes" (without quotes) if it's possible to fulfill the requirements, and "No" otherwise. You can print each letter in any case (upper or lower).

NoteIn the first example, there are five points: (1, 7), (2, 5), (3, 8), (4, 6) and (5, 9). It's possible to draw a line that passes through points 1, 3, 5, and another one that passes through points 2, 4 and is parallel to the first one.In the second example, while it's possible to draw two lines that cover all points, they cannot be made parallel.In the third example, it's impossible to satisfy both requirements at the same time.

#!/usr/bin/perl

use warnings;
use strict;

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

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

	my @cand;
	push @cand, $A[1] - $A[0], $A[2] - $A[1], ($A[2] - $A[0]) / 2;
	$debug and print "cand:[@cand]";

	my $ok = 0;

	for my $cand ( @cand ){

		my $jump;
		my $f = 0;

		for( my $i = 0; $i < @A - 1; $i ++ ){
			my $diff = $A[ $i+1 ] - $A[ $i ];

			if( $diff != $cand ){
				if( not defined $jump ){
					$jump = $diff - $cand;
					}
				elsif( -$jump == $diff - $cand ){
					$jump *= -1;
					#OK
					}
				else{
					$f ++;
					last;
					}
				}
			}

		if( $f == 0 and defined $jump ){
			$ok = 1;
			last;
			}
		}

	print $ok ? "YES" : "NO";

	}


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ are permutations, and $$$[1, 1]$$$, $$$[0, 1]$$$, $$$[2, 2, 1, 4]$$$ are not.There was a permutation $$$p[1 \dots n]$$$. It was merged with itself. In other words, let's take two instances of $$$p$$$ and insert elements of the second $$$p$$$ into the first maintaining relative order of elements. The result is a sequence of the length $$$2n$$$.For example, if $$$p=[3, 1, 2]$$$ some possible results are: $$$[3, 1, 2, 3, 1, 2]$$$, $$$[3, 3, 1, 1, 2, 2]$$$, $$$[3, 1, 3, 1, 2, 2]$$$. The following sequences are not possible results of a merging: $$$[1, 3, 2, 1, 2, 3$$$], [$$$3, 1, 2, 3, 2, 1]$$$, $$$[3, 3, 1, 2, 2, 1]$$$.For example, if $$$p=[2, 1]$$$ the possible results are: $$$[2, 2, 1, 1]$$$, $$$[2, 1, 2, 1]$$$. The following sequences are not possible results of a merging: $$$[1, 1, 2, 2$$$], [$$$2, 1, 1, 2]$$$, $$$[1, 2, 2, 1]$$$.Your task is to restore the permutation $$$p$$$ by the given resulting sequence $$$a$$$. It is guaranteed that the answer exists and is unique.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 400$$$) — 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 length of permutation. The second line of the test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the array $$$a$$$ represents the result of merging of some permutation $$$p$$$ with the same permutation $$$p$$$.

For each test case, print the answer: $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$), representing the initial permutation. It is guaranteed that the answer exists and is unique.

#!/usr/bin/perl

my $test_count = <STDIN>;
chomp $test_count;
my @final_results;

for ($i = 0; $i < $test_count; ++$i) {
  my $seq_length = <STDIN>;
  chomp($seq_length);
  my $line = <STDIN>;
  chomp($line);
  my @elements = split(/ /,$line);
  my %seen;
  my @result;
  foreach (@elements) {
    unless ($seen{$_}) {
      $seen{$_} = true;
      push(@result,$_);
    }
  }
  push(@final_results,join(' ',@result));
}

print join("\n", @final_results)."\n";


You are given an integer $$$n$$$ and an array $$$a_1, a_2, \ldots, a_n$$$. You should reorder the elements of the array $$$a$$$ in such way that the sum of $$$\textbf{MEX}$$$ on prefixes ($$$i$$$-th prefix is $$$a_1, a_2, \ldots, a_i$$$) is maximized.Formally, you should find an array $$$b_1, b_2, \ldots, b_n$$$, such that the sets of elements of arrays $$$a$$$ and $$$b$$$ are equal (it is equivalent to array $$$b$$$ can be found as an array $$$a$$$ with some reordering of its elements) and $$$\sum\limits_{i=1}^{n} \textbf{MEX}(b_1, b_2, \ldots, b_i)$$$ is maximized.$$$\textbf{MEX}$$$ of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set.For example, $$$\textbf{MEX}(\{1, 2, 3\}) = 0$$$, $$$\textbf{MEX}(\{0, 1, 2, 4, 5\}) = 3$$$.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$  — the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \le n \le 100)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(0 \le a_i \le 100)$$$.

For each test case print an array $$$b_1, b_2, \ldots, b_n$$$  — the optimal reordering of $$$a_1, a_2, \ldots, a_n$$$, so the sum of $$$\textbf{MEX}$$$ on its prefixes is maximized. If there exist multiple optimal answers you can find any.


You are given a square grid with $$$n$$$ rows and $$$n$$$ columns. Each cell contains either $$$0$$$ or $$$1$$$. In an operation, you can select a cell of the grid and flip it (from $$$0 \to 1$$$ or $$$1 \to 0$$$). Find the minimum number of operations you need to obtain a square that remains the same when rotated $$$0^{\circ}$$$, $$$90^{\circ}$$$, $$$180^{\circ}$$$ and $$$270^{\circ}$$$.The picture below shows an example of all rotations of a grid.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the size of the grid. Then $$$n$$$ lines follow, each with $$$n$$$ characters $$$a_{i,j}$$$ ($$$0 \leq a_{i,j} \leq 1$$$) — the number written in each cell.

For each test case output a single integer  — the minimum number of operations needed to make the square look the same rotated $$$0^{\circ}$$$, $$$90^{\circ}$$$, $$$180^{\circ}$$$ and $$$270^{\circ}$$$.

NoteIn the first test case, we can perform one operations to make the grid $$$\begin{matrix}0 & 1 & 0\\ 1 & 1 & \color{red}{1}\\ 0 & 1 & 0\end{matrix}$$$. Now, all rotations of the square are the same.In the second test case, all rotations of the square are already the same, so we don't need any flips.


Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.

A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.

On a single line print the answer to the problem. If such number does not exist, then you should print -1.

NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.

#!/usr/bin/perl

use strict;
use warnings;

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

my @nums = split(/\s/, $line);
my $data = +{};
for my $num (@nums) {
    $data->{$num}++;
}

if (!$data->{0}) {
    print "-1";
    exit;
}

my $sum = get_sum($data);

my $rest = $sum % 3;
my $cnt = 0;
while ($rest != 0 && $cnt < 2) {
    func($data, $rest);
    $rest = get_sum($data) % 3;
    $cnt++;
}

if ($rest == 0) {
    my $ans = '';
    for (my $i=9; $i >= 0; $i--) {
        if ($data->{$i}) {
             $ans .= $i x $data->{$i};
        }
    }

    if (substr($ans, 0, 1) eq '0') {
        print 0;
    }
    else {
        print $ans;
    }
}
else {
    print "-1";
}

sub get_sum {
    $data = shift;
    my $sum = 0;
    for my $key (keys(%{$data})) {
        if ($data->{$key}) {
            $sum += $key * $data->{$key};
        }
    }

    return $sum;
}

sub func {
    my ($data, $rest) = @_;
    if ($rest == 1) {
        for my $i (1, 4, 7) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
        for my $i (2, 5, 8) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
    }
    if ($rest == 2) {
        for my $i (2, 5, 8) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
        for my $i (1, 4, 7) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
    }
}

#!/usr/bin/perl

use strict;
use warnings;

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

my @nums = split(/\s/, $line);
my $data = +{};
for my $num (@nums) {
    $data->{$num}++;
}

if (!$data->{0}) {
    print "-1";
    exit;
}

my $sum = get_sum($data);

my $rest = $sum % 3;
my $cnt = 0;
while ($rest != 0 && $cnt < 2) {
    func($data, $rest);
    $rest = get_sum($data) % 3;
    $cnt++;
}

if ($rest == 0) {
    for (my $i=9; $i >= 0; $i--) {
        if ($data->{$i}) {
            print $i x $data->{$i};
        }
    }
}
else {
    print "-1";
}

sub get_sum {
    $data = shift;
        for my $key (keys(%{$data})) {
            if ($data->{$key}) {
                $sum += $key * $data->{$key};
            }
        }
}

sub func {
    my ($data, $rest) = @_;
    if ($rest == 1) {
        for my $i (1, 4, 7) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
        for my $i (2, 5, 8) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
    }
    if ($rest == 2) {
        for my $i (2, 5, 8) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
        for my $i (1, 4, 7) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
    }
}

#!/usr/bin/perl

use strict;
use warnings;

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

my @nums = split(/\s/, $line);
my $data = +{};
for my $num (@nums) {
    $data->{$num}++;
}

if (!$data->{0}) {
    print "-1";
    exit;
}

my $sum = get_sum($data);

my $rest = $sum % 3;
my $cnt = 0;
while ($rest != 0 && $cnt < 2) {
    func($data, $rest);
    $rest = get_sum($data) % 3;
    $cnt++;
}

if ($rest == 0) {
    my $ans = '';
    for (my $i=9; $i >= 0; $i--) {
        if ($data->{$i}) {
             $ans .= $i x $data->{$i};
        }
    }

    print int($ans);
}
else {
    print "-1";
}

sub get_sum {
    $data = shift;
    my $sum = 0;
    for my $key (keys(%{$data})) {
        if ($data->{$key}) {
            $sum += $key * $data->{$key};
        }
    }

    return $sum;
}

sub func {
    my ($data, $rest) = @_;
    if ($rest == 1) {
        for my $i (1, 4, 7) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
        for my $i (2, 5, 8) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
    }
    if ($rest == 2) {
        for my $i (2, 5, 8) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
        for my $i (1, 4, 7) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
    }
}

#!/usr/bin/perl

use strict;
use warnings;

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

my @nums = split(/\s/, $line);
my $data = +{};
for my $num (@nums) {
    $data->{$num}++;
}

if (!$data->{0}) {
    print "-1";
    exit;
}

my $sum = get_sum($data);

my $rest = $sum % 3;
my $cnt = 0;
while ($rest != 0 && $cnt < 2) {
    func($data, $rest);
    $rest = get_sum($data) % 3;
    $cnt++;
}

if ($rest == 0) {
    for (my $i=9; $i >= 0; $i--) {
        if ($data->{$i}) {
            print $i x $data->{$i};
        }
    }
}
else {
    print "-1";
}

sub get_sum {
    $data = shift;
    my $sum = 0;
    for my $key (keys(%{$data})) {
        if ($data->{$key}) {
            $sum += $key * $data->{$key};
        }
    }

    return $sum;
}

sub func {
    my ($data, $rest) = @_;
    if ($rest == 1) {
        for my $i (1, 4, 7) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
        for my $i (2, 5, 8) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
    }
    if ($rest == 2) {
        for my $i (2, 5, 8) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
        for my $i (1, 4, 7) {
            if ($data->{$i}) {
                $data->{$i}--;
                return;
            }
        }
    }
}


Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n1 settle in the first city and then some subset of size n2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth ai among all its residents divided by the number of them (n1 or n2 depending on the city). The division should be done in real numbers without any rounding.Please, help authorities find the optimal way to pick residents for two cities.

The first line of the input contains three integers n, n1 and n2 (1 ≤ n, n1, n2 ≤ 100 000, n1 + n2 ≤ n) — the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), the i-th of them is equal to the wealth of the i-th candidate.

Print one real value — the maximum possible sum of arithmetic means of wealth of cities' residents. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second.In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (a3 + a4) / 2 + a2 = (3 + 2) / 2 + 4 = 6.5


Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:Consider an $$$n$$$ by $$$n$$$ chessboard. Its rows are numbered from $$$1$$$ to $$$n$$$ from the top to the bottom. Its columns are numbered from $$$1$$$ to $$$n$$$ from the left to the right. A cell on an intersection of $$$x$$$-th row and $$$y$$$-th column is denoted $$$(x, y)$$$. The main diagonal of the chessboard is cells $$$(x, x)$$$ for all $$$1 \le x \le n$$$.A permutation of $$$\{1, 2, 3, \dots, n\}$$$ is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly $$$1+2+ \ldots +n$$$ such cells) into $$$n$$$ connected regions satisfying the following constraints:  Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell.  The $$$x$$$-th region should contain cell on the main diagonal with number $$$x$$$ for all $$$1\le x\le n$$$.  The number of cells that belong to the $$$x$$$-th region should be equal to $$$x$$$ for all $$$1\le x\le n$$$.  Each cell under and on the main diagonal should belong to exactly one region.

The first line contains a single integer $$$n$$$ ($$$1\le n \le 500$$$) denoting the size of the chessboard. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$. $$$p_i$$$ is the number written on cell $$$(i, i)$$$. It is guaranteed that each integer from $$$\{1, \ldots, n\}$$$ appears exactly once in $$$p_1$$$, ..., $$$p_n$$$.

If no solution exists, output $$$-1$$$. Otherwise, output $$$n$$$ lines. The $$$i$$$-th line should contain $$$i$$$ numbers. The $$$j$$$-th number on the $$$i$$$-th line should be $$$x$$$ if cell $$$(i, j)$$$ belongs to the the region with $$$x$$$ cells.

NoteThe solutions to the examples are illustrated in the following pictures:


Recently, Norge found a string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $$$s$$$. Yes, all $$$\frac{n (n + 1)}{2}$$$ of them!A substring of $$$s$$$ is a non-empty string $$$x = s[a \ldots b] = s_{a} s_{a + 1} \ldots s_{b}$$$ ($$$1 \leq a \leq b \leq n$$$). For example, "auto" and "ton" are substrings of "automaton".Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $$$k$$$ Latin letters $$$c_1, c_2, \ldots, c_k$$$ out of $$$26$$$.After that, Norge became interested in how many substrings of the string $$$s$$$ he could still type using his broken keyboard. Help him to find this number.

The first line contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq k \leq 26$$$) — the length of the string $$$s$$$ and the number of Latin letters still available on the keyboard. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains $$$k$$$ space-separated distinct lowercase Latin letters $$$c_1, c_2, \ldots, c_k$$$ — the letters still available on the keyboard.

Print a single number — the number of substrings of $$$s$$$ that can be typed using only available letters $$$c_1, c_2, \ldots, c_k$$$.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	print eval join '+', 0, map $_ * ( $_ + 1 ) / 2, map length, split /[^$ok]/, $_;
	}


Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya.

The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≤ n ≤ 90) — the number of fouls.  Each of the following n lines contains information about a foul in the following form:    first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs;  then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player;  then goes the player's number m (1 ≤ m ≤ 99);  then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given.  The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute.

For each event when a player received his first red card in a chronological order print a string containing the following information:   The name of the team to which the player belongs;  the player's number in his team;  the minute when he received the card.  If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards).


'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have n questions, m of them are auction questions and n - m of them are regular questions. Each question has a price. The price of the i-th question is ai points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100; m ≤ min(n, 30)) — the total number of questions and the number of auction questions, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the prices of the questions. The third line contains m distinct integers bi (1 ≤ bi ≤ n) — the numbers of auction questions. Assume that the questions are numbered from 1 to n.

In the single line, print the answer to the problem — the maximum points the R2 company can get if it plays optimally well. It is guaranteed that the answer fits into the integer 64-bit signed type.


The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.

The first line contains four space-separated integers x0, y0, x1, y1 (1 ≤ x0, y0, x1, y1 ≤ 109), denoting the initial and the final positions of the king. The second line contains a single integer n (1 ≤ n ≤ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≤ ri, ai, bi ≤ 109, ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily. It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.

If there is no path between the initial and final position along allowed cells, print -1. Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one.


You are given $$$n$$$ of integers $$$a_1, a_2, \ldots, a_n$$$. Process $$$q$$$ queries of two types: query of the form "0 $$$x_j$$$": add the value $$$x_j$$$ to all even elements of the array $$$a$$$, query of the form "1 $$$x_j$$$": add the value $$$x_j$$$ to all odd elements of the array $$$a$$$.Note that when processing the query, we look specifically at the odd/even value of $$$a_i$$$, not its index.After processing each query, print the sum of the elements of the array $$$a$$$.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

The first line of the input contains an integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n$$$, $$$q \leq 10^5$$$) — the length of array $$$a$$$ and the number of queries. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. The following $$$q$$$ lines contain queries as two integers $$$type_j$$$ and $$$x_j$$$ $$$(0 \leq type_j \leq 1$$$, $$$1 \leq x_j \leq 10^4$$$). It is guaranteed that the sum of values $$$n$$$ over all test cases in a test does not exceed $$$10^5$$$. Similarly, the sum of values $$$q$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print $$$q$$$ numbers: the sum of the elements of the array $$$a$$$ after processing a query.

#!/usr/bin/perl

use warnings;
use strict;

my $debug = 0;

$\ = $/;

<>;

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

	my( $n, $q ) = split;
	@_ = split ' ', <>;
	$debug and print "[@_]";

	my $sum = 0;
	$sum += $_ for @_;

	my $LYG = grep $_ % 2 == 0, @_;
	my $NELYG = @_ - $LYG;
	$debug and print "LYG[$LYG], NELYG:[$NELYG]";

	for my $qq ( 1 .. $q ){
		my( $t, $x ) = split ' ', <>;

		if( $t == 0 ){
			$sum += $LYG * $x;
			if( $x % 2 == 1 ){
				$LYG = 0;
				$NELYG = @_;
				}
			}
		if( $t == 1 ){
			$sum += $NELYG * $x;
			if( $x % 2 == 1 ){
				$LYG = @_;
				$NELYG = 0;
				}
			}
		print $sum;
		}
	}


Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1·p2·...·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value.

The first line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of primes in factorization of n.  The second line contains m primes numbers pi (2 ≤ pi ≤ 200 000).

Print one integer — the product of all divisors of n modulo 109 + 7.

NoteIn the first sample n = 2·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1·2·3·6 = 36.In the second sample 2·3·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1·2·3·4·6·12 = 1728.


President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.

The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.

Print the only number — the amount of President's deputies.

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

my ($n, $m, $color) = (split / /, <>);
chomp $color;
my ($ps, $ns) = ('', '');
my @s;
for (1..$n) {
    my $rs = <>;
    chomp $rs;
    if ($rs =~ /$color/) {
	push @s, $rs;
    } elsif (@s) {
	$ns = $rs;
	last;
    } else {
	$ps = $rs;
    }
}

my %tables;
# left and right tables
for (@s) {
    if (/([^$color])$color/) {
	$tables{$1} = 1 if $1 ne '.';
    }
    if (/$color([^$color])/) {
	$tables{$1} = 1 if $1 ne '.';
    }
}

# tables in previous row
if ($ps ne '') {
    my @ps = split //, $ps;
    my @fs = split //, $s[0];
    for (0..$#ps) {
	if ($fs[$_] eq $color and $ps[$_] ne '.') {
	    $tables{$ps[$_]} = 1;
	}
    }
}
# tables in next row
if ($ns ne '') {
    my @ns = split //, $ns;
    my @ls = split //, $s[$#s];
    for (0..$#ns) {
	if ($ls[$_] eq $color and $ns[$_] ne '.') {
	    $tables{$ns[$_]} = 1;
	}
    }
}
# all tables

my $sum = keys %tables;
print "$sum\n";

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

my ($n, $m, $color) = (split / /, <>);
chomp $color;
my ($ps, $s, $ns) = ('', '', '');
for (1..$n) {
    $s = <>;
    chomp $s;
    if ($s =~ /$color/) {
	$ns = <> if $_ < $n;
	chomp $ns;
	last;
    } else {
	$ps = $s;
    }
}

my %tables;
# left table
if ($s =~ /([^$color])$color/) {
    $tables{$1} = 1 if $1 ne '.';
}
# right table
if ($s =~ /$color([^$color])/) {
    $tables{$1} = 1 if $1 ne '.';
}

# tables in previous row
if ($ps ne '') {
    my @ps = split //, $ps;
    my @s = split //, $s;
    for (0..$#ps) {
	if ($s[$_] eq $color and $ps[$_] ne '.') {
	    $tables{$ps[$_]} = 1;
	}
    }
}
# tables in next row
if ($ns ne '') {
    my @ns = split //, $ns;
    my @s = split //, $s;
    for (0..$#ns) {
	if ($s[$_] eq $color and $ns[$_] ne '.') {
	    $tables{$ns[$_]} = 1;
	}
    }
}
# all tables

my $sum = keys %tables;
print "$sum\n";

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

my ($n, $m, $color) = (split / /, <>);
chomp $color;
my ($ps, $ns) = ('', '');
my @s;
for (1..$n) {
    my $rs = <>;
    chomp $rs;
    if ($rs =~ /$color/) {
	push @s, $rs;
    } elsif (@s) {
	$ns = $rs;
	last;
    } else {
	$ps = $rs;
    }
}

my %tables;
# left and right tables
for (@s) {
    if (/([^$color])$color/) {
	$tables{$1} = 1 if $1 ne '.';
    }
    if (/$color(^$color])/) {
	$tables{$1} = 1 if $1 ne '.';
    }
}

# tables in previous row
if ($ps ne '') {
    my @ps = split //, $ps;
    my @fs = split //, $s[0];
    for (0..$#ps) {
	if ($fs[$_] eq $color and $ps[$_] ne '.') {
	    $tables{$ps[$_]} = 1;
	}
    }
}
# tables in next row
if ($ns ne '') {
    my @ns = split //, $ns;
    my @ls = split //, $s[$#s];
    for (0..$#ns) {
	if ($ls[$_] eq $color and $ns[$_] ne '.') {
	    $tables{$ns[$_]} = 1;
	}
    }
}
# all tables

my $sum = keys %tables;
print "$sum\n";


You are given an array of integers $$$a_1,a_2,\ldots,a_n$$$. Find the maximum possible value of $$$a_ia_ja_ka_la_t$$$ among all five indices $$$(i, j, k, l, t)$$$ ($$$i<j<k<l<t$$$).

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t\le 2 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$5\le n\le 10^5$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$-3\times 10^3\le a_i\le 3\times 10^3$$$) — given array. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print one integer — the answer to the problem.

NoteIn the first test case, choosing $$$a_1,a_2,a_3,a_4,a_5$$$ is a best choice: $$$(-1)\cdot (-2) \cdot (-3)\cdot (-4)\cdot (-5)=-120$$$.In the second test case, choosing $$$a_1,a_2,a_3,a_5,a_6$$$ is a best choice: $$$(-1)\cdot (-2) \cdot (-3)\cdot 2\cdot (-1)=12$$$.In the third test case, choosing $$$a_1,a_2,a_3,a_4,a_5$$$ is a best choice: $$$(-1)\cdot 0\cdot 0\cdot 0\cdot (-1)=0$$$.In the fourth test case, choosing $$$a_1,a_2,a_3,a_4,a_6$$$ is a best choice: $$$(-9)\cdot (-7) \cdot (-5)\cdot (-3)\cdot 1=945$$$.


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You want to distribute these $$$n$$$ integers into two groups $$$s_1$$$ and $$$s_2$$$ (groups can be empty) so that the following conditions are satisfied:  For each $$$i$$$ $$$(1 \leq i \leq n)$$$, $$$a_i$$$ goes into exactly one group. The value $$$|sum(s_1)| - |sum(s_2)|$$$ is the maximum possible among all such ways to distribute the integers.Here $$$sum(s_1)$$$ denotes the sum of the numbers in the group $$$s_1$$$, and $$$sum(s_2)$$$ denotes the sum of the numbers in the group $$$s_2$$$.Determine the maximum possible value of $$$|sum(s_1)| - |sum(s_2)|$$$.

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. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2 \ldots a_n$$$ $$$(-10^9 \leq a_i \leq 10^9)$$$  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, output a single integer  — the maximum possible value of $$$|sum(s_1)| - |sum(s_2)|$$$.

<>; print abs eval <> =~ s/\s/+/gr . 0, $/ while <>


You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.

The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.

Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).

NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .

use 5.016;
use strict;
use warnings;

<>;
my ($k, $m) = split ' ', <>;
my @x = split ' ', <>;
my @y = split ' ', <>;

my $x = $x[$k - 1];
my $y = $y[-$m];

say $x < $y ? 'YES' : 'NO';


Michael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple.The prison can be represented as a rectangle $$$a\times b$$$ which is divided into $$$ab$$$ cells, each representing a prison cell, common sides being the walls between cells, and sides on the perimeter being the walls leading to freedom. Before sentencing, Michael can ask his friends among the prison employees to make (very well hidden) holes in some of the walls (including walls between cells and the outermost walls). Michael wants to be able to get out of the prison after this, no matter which cell he is placed in. However, he also wants to break as few walls as possible.Your task is to find out the smallest number of walls to be broken so that there is a path to the outside from every cell after this.

The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 100$$$) — the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1\leq a, b\leq 100$$$), representing a corresponding test case.

For each test case print the single integer on a separate line — the answer to the problem.

NoteSome possible escape plans for the example test cases are shown below. Broken walls are shown in gray, not broken walls are shown in black.


Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of n Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, so each person agrees to swap places with the person right behind him for just 1 dollar. More formally, if person a stands just behind person b, then person a can pay person b 1 dollar, then a and b get swapped. Of course, if person a has zero dollars, he can not swap places with person b.Residents of Berland are strange people. In particular, they get upset when there is someone with a strictly smaller sum of money in the line in front of them.Can you help the residents of Berland form such order in the line so that they were all happy? A happy resident is the one who stands first in the line or the one in front of who another resident stands with not less number of dollars. Note that the people of Berland are people of honor and they agree to swap places only in the manner described above.

The first line contains integer n (1 ≤ n ≤ 200 000) — the number of residents who stand in the line. The second line contains n space-separated integers ai (0 ≤ ai ≤ 109), where ai is the number of Berland dollars of a man standing on the i-th position in the line. The positions are numbered starting from the end of the line.

If it is impossible to make all the residents happy, print ":(" without the quotes. Otherwise, print in the single line n space-separated integers, the i-th of them must be equal to the number of money of the person on position i in the new line. If there are multiple answers, print any of them.

NoteIn the first sample two residents should swap places, after that the first resident has 10 dollars and he is at the head of the line and the second resident will have 9 coins and he will be at the end of the line. In the second sample it is impossible to achieve the desired result.In the third sample the first person can swap with the second one, then they will have the following numbers of dollars: 4 11 3, then the second person (in the new line) swaps with the third one, and the resulting numbers of dollars will equal to: 4 4 10. In this line everybody will be happy.

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

<>;
my @array = split(' ', <>);
my $inc;

for my $el(@array){
	$el += $inc ++;
}

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

$inc = -1;
for my $el(@array){
	if($el == $inc){
		print ":(";
		exit;
	}
	$inc = $el;
}

$inc = 0;
for my $el(@array){
	$el -= $inc ++;
}
print "@array";


Consider a tunnel on a one-way road. During a particular day, $$$n$$$ cars numbered from $$$1$$$ to $$$n$$$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.Traffic regulations prohibit overtaking inside the tunnel. If car $$$i$$$ overtakes any other car $$$j$$$ inside the tunnel, car $$$i$$$ must be fined. However, each car can be fined at most once.Formally, let's say that car $$$i$$$ definitely overtook car $$$j$$$ if car $$$i$$$ entered the tunnel later than car $$$j$$$ and exited the tunnel earlier than car $$$j$$$. Then, car $$$i$$$ must be fined if and only if it definitely overtook at least one other car.Find the number of cars that must be fined.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$), denoting the number of cars. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), denoting the ids of cars in order of entering the tunnel. All $$$a_i$$$ are pairwise distinct. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$), denoting the ids of cars in order of exiting the tunnel. All $$$b_i$$$ are pairwise distinct.

NoteThe first example is depicted below:Car $$$2$$$ definitely overtook car $$$5$$$, while car $$$4$$$ definitely overtook cars $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. Cars $$$2$$$ and $$$4$$$ must be fined.In the second example car $$$5$$$ was definitely overtaken by all other cars.In the third example no car must be fined.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

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

	my @A = split ' ', <>;
	my @B = split ' ', <>;

	$debug and print "\@A: [@A]";
	$debug and print "\@B: [@B]";

	my %h;

	my $i = 0;

	map $h{ $_ } = ++ $i, @A;

	$_ = $h{ $_ } for @A;
	$_ = $h{ $_ } for @B;

	$debug and print "\@A: [@A]";
	$debug and print "\@B: [@B]";

	my $cnt = 0;

	@B = reverse @B;

	my $min = $B[ 0 ];

	for( @B ){
		if( $_ > $min ){
			$cnt ++;
			}
		if( $_ < $min ){
			$min = $_;
			}
		}

	print $cnt;
	}


Alice and Bob are playing a game. They are given an array $$$A$$$ of length $$$N$$$. The array consists of integers. They are building a sequence together. In the beginning, the sequence is empty. In one turn a player can remove a number from the left or right side of the array and append it to the sequence. The rule is that the sequence they are building must be strictly increasing. The winner is the player that makes the last move. Alice is playing first. Given the starting array, under the assumption that they both play optimally, who wins the game?

The first line contains one integer $$$N$$$ ($$$1 \leq N \leq 2*10^5$$$) - the length of the array $$$A$$$. The second line contains $$$N$$$ integers $$$A_1$$$, $$$A_2$$$,...,$$$A_N$$$ ($$$0 \leq A_i \leq 10^9$$$)

The first and only line of output consists of one string, the name of the winner. If Alice won, print "Alice", otherwise, print "Bob".

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my @A;

	my @B = @_;

	my $prev = shift @_;
	push @A, $prev;

	for( @_ ){
		if( $_ == $prev ){
			next;
			}
		else{
			push @A, $_;
			}
		$prev = $_;
		}

	@A = @B;

	my $c = 0;

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

		$c ++;
		}

	my $d = 0;

	@A = reverse @A;

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

		$d ++;
		}

	if( $c % 2 == 0 or $d % 2 == 0 ){
		print 'Alice';
		}
	else{
		print 'Bob';
		}
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my @A;

	my $prev = shift @_;
	push @A, $prev;

	for( @_ ){
		if( $_ == $prev ){
		#	next;
			}
		else{
			push @A, $_;
			}
		$prev = $_;
		}

	my $c = 0;

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

		$c ++;
		}

	my $d = 0;

	@A = reverse @A;

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

		$d ++;
		}

	if( $c % 2 == 0 or $d % 2 == 0 ){
		print 'Alice';
		}
	else{
		print 'Bob';
		}
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my @A;

	my $prev = shift @_;
	push @A, $prev;

	for( @_ ){
		if( $_ == $prev ){
			next;
			}
		else{
			push @A, $_;
			}
		$prev = $_;
		}

	my $c = 0;

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

		$c ++;
		}

	my $d = 0;

	@A = reverse @A;

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

		$d ++;
		}

	if( $c % 2 == 0 or $d % 2 == 0 ){
		print 'Alice';
		}
	else{
		print 'Bob';
		}
	}


You are given $$$n$$$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String $$$a$$$ is a substring of string $$$b$$$ if it is possible to choose several consecutive letters in $$$b$$$ in such a way that they form $$$a$$$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of strings. The next $$$n$$$ lines contain the given strings. The number of letters in each string is from $$$1$$$ to $$$100$$$, inclusive. Each string consists of lowercase English letters. Some strings might be equal.

If it is impossible to reorder $$$n$$$ given strings in required order, print "NO" (without quotes). Otherwise print "YES" (without quotes) and $$$n$$$ given strings in required order.

NoteIn the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba".

#!/usr/bin/perl

$input_line = <STDIN>;
chop($input_line);
$n=$input_line;
@s=();
for ($counter = 0; $counter <$n; $counter++){
	$input_line = <STDIN>;
	chop($input_line);
	$s[$counter] = $input_line;
}
$counter = $n;
while ($counter > 0){
	$i = 1;
	while ($i < $counter){
		if (length($s[$i])< length($s[$i-1])){($s[$i],$s[$i-1]) = ($s[$i-1], $s[$i])}
		$i++;
	}
	$counter--;
}
$check = 1;
for ($i = 1; $i <$n; $i++){
	if ($s[$i] !~ /${s[$i-1]}/){$check = 0}
}
if ($check == 0){print ("NO\n");}
else{
	print("YES\n");
	for ($i = 0; $i <$n; $i++){
		print ("$s[$i]\n");}
}

use warnings;
use strict;
chomp ( my $n = <STDIN> );
my @a = ();
my $s;
for ( 1 .. $n ) {
    $s = <STDIN>;
    chomp ( $s );
    push @a, $s;
}
$, = qq/\n/, $\ = qq/\n/;
@a = sort { $a =~ m/$b/ ? 1 : -1 } @a;
for my $i ( 1 .. $#a ) { if ( not $a[$i] =~ m/$a[$i-1]/ ) { print "NO\n"; exit; }}
print "YES";
print @a;

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	@_ = sort { length $a <=> length $b } @_;

	my $f = 0;

	for my $i ( 0 .. @_ - 2 ){
		$_[ $i + 1 ] =~ $_[ $i ] or $f ++;
		}

	next if $f and print "NO";

	print for "YES", @_;
	}

use warnings;
use strict;
chomp ( my $n = <STDIN> );
my @a = ();
my $s;
for ( 1 .. $n ) {
    $s = <STDIN>;
    chomp ( $s );
    push @a, $s;
}
$, = qq/\n/, $\ = qq/\n/;
@a = sort { $a =~ m/$b/ ? 1 : -1 } @a;
for my $i ( 1 .. $#a ) { if ( not $a[$i] =~ m/$a[$i-1]/ ) { print "NO\n"; exit; }}
print @a;

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	@_ = sort { length $a <=> length $b } @_;

	my $f = 0;

	for my $i ( 0 .. @_ - 2 ){
		$_[ $i + 1 ] =~ $_[ $i ] or $f ++;
		}

	next if $f and print "NO";

	print for @_;
	}


You are given an array a with n elements. Each element of a is either 0 or 1.Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).

The first line contains two integers n and k (1 ≤ n ≤ 3·105, 0 ≤ k ≤ n) — the number of elements in a and the parameter k. The second line contains n integers ai (0 ≤ ai ≤ 1) — the elements of a.

On the first line print a non-negative integer z — the maximal value of f(a) after no more than k changes of zeroes to ones. On the second line print n integers aj — the elements of the array a after the changes. If there are multiple answers, you can print any one of them.

my $f;
chomp ( $f = <STDIN> );
my ($n, $k) = split m/ /, $f;
chomp ( $f = <STDIN> );
my @arr = split m/ /, $f;

my @dp = ();
my $prev = 0;
my $is_one = 0;

# pointers a and b
my $ptr_a = 0;
my $ptr_b = 0;

# number of changed elements right now
my $changed = 0;
# maximum length of contiguous ones
my $max_len = 0;
my $index_of_max = 0;
while ( $ptr_b < @arr ) {
    if ( $arr[ $ptr_b ] == 0 ) {
	if ( $changed < $k ) {
	    $changed += 1;
	    $ptr_b += 1;
	    if ( ($ptr_b - $ptr_a) > $max_len ) {
		$max_len = $ptr_b - $ptr_a;
		$index_of_max = $ptr_a;
	    }
	}
	else {
	    while ( $arr[ $ptr_a ] == 1 ) {
		$ptr_a += 1;
	    }
	    if ( $arr[ $ptr_a ] == 0 ) {
		$changed -= 1;
		$ptr_a += 1;
	    }
	}
    }
    else {
	$ptr_b += 1;
	if ( ($ptr_b - $ptr_a) > $max_len ) {
	    $max_len = $ptr_b - $ptr_a;
	    $index_of_max = $ptr_a;
	}
    }
}

print $max_len;
print "\n";

for ( my $i = $index_of_max ; $i < ($index_of_max + $max_len); $i += 1 ) {
    $arr[ $i ] = 1;
}

for (@arr) {
    print "$_ ";}
print "\n";


You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:  the Power Gem of purple color,  the Time Gem of green color,  the Space Gem of blue color,  the Soul Gem of orange color,  the Reality Gem of red color,  the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.

In the first line of input there is one integer $$$n$$$ ($$$0 \le n \le 6$$$) — the number of Gems in Infinity Gauntlet. In next $$$n$$$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.

In the first line output one integer $$$m$$$ ($$$0 \le m \le 6$$$) — the number of absent Gems. Then in $$$m$$$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.

NoteIn the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.In the second sample Thanos doesn't have any Gems, so he needs all six.

use warnings;
use strict;
use integer;
use constant NL => qq/\n/;
$\ = qq/\n/, $, = qq/\n/;
chomp ( my $n = <STDIN> );
my %gems = (
    'purple' => 'Power',
    'green' => 'Time',
    'blue' => 'Space',
    'orange' => 'Soul',
    'red' => 'Reality',
    'yellow' => 'Mind'
);
for my $val ( 1 .. $n ) {
    chomp ( my $str = <STDIN> );
    delete $gems { $str };
}
print scalar values %gems;
print values %gems;

#!/usr/bin/perl -l
use warnings;
use strict;
chomp(my $n=<STDIN>);
my %mapp=('purple'=>'Power','green'=>'Time','blue'=>'Space','orange'=>'Soul','red'=>'Reality','yellow'=>'Mind');
for(my $i=0;$i<$n;$i++)
{
	chomp(my $s=<STDIN>);
        delete $mapp{$s};
}
my $ss=keys %mapp;
print $ss;
foreach my $value(values %mapp)
{
	print $value;
}

#!/usr/bin/perl -l
use warnings;
use strict;
chomp(my $n=<STDIN>);
my %mapp=('purple'=>'Power','green'=>'Time','blue'=>'Space','orange'=>'Soul','red'=>'Reality','yellow'=>'Mind');
for(my $i=0;$i<$n;$i++)
{
	chomp(my $s=<STDIN>);
        delete $mapp{$s};
}
foreach my $value(values %mapp)
{
	print $value;
}


Hr0d1y has $$$q$$$ queries on a binary string $$$s$$$ of length $$$n$$$. A binary string is a string containing only characters '0' and '1'.A query is described by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \leq l_i \lt r_i \leq n)$$$. For each query, he has to determine whether there exists a good subsequence in $$$s$$$ that is equal to the substring $$$s[l_i\ldots r_i]$$$.   A substring $$$s[i\ldots j]$$$ of a string $$$s$$$ is the string formed by characters $$$s_i s_{i+1} \ldots s_j$$$. String $$$a$$$ is said to be a subsequence of string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some characters without changing the order of the remaining characters. A subsequence is said to be good if it is not contiguous and has length $$$\ge 2$$$. For example, if $$$s$$$ is "1100110", then the subsequences $$$s_1s_2s_4$$$ ("1100110") and $$$s_1s_5s_7$$$ ("1100110") are good, while $$$s_1s_2s_3$$$ ("1100110") is not good. Can you help Hr0d1y answer each query?

The first line of the input contains a single integer $$$t$$$ ($$$1\leq t \leq 100$$$) — the number of test cases. The description of each test case is as follows. The first line contains two integers $$$n$$$ ($$$2 \leq n \leq 100$$$) and $$$q$$$ ($$$1\leq q \leq 100$$$) — the length of the string and the number of queries.  The second line contains the string $$$s$$$. The $$$i$$$-th of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \leq l_i \lt r_i \leq n$$$).

For each test case, output $$$q$$$ lines. The $$$i$$$-th line of the output of each test case should contain "YES" if there exists a good subsequence equal to the substring $$$s[l_i...r_i]$$$, and "NO" otherwise. You may print each letter in any case (upper or lower).

NoteIn the first test case,   $$$s[2\ldots 4] = $$$ "010". In this case $$$s_1s_3s_5$$$ ("001000") and $$$s_2s_3s_6$$$ ("001000") are good suitable subsequences, while $$$s_2s_3s_4$$$ ("001000") is not good.  $$$s[1\ldots 3] = $$$ "001". No suitable good subsequence exists.  $$$s[3\ldots 5] = $$$ "100". Here $$$s_3s_5s_6$$$ ("001000") is a suitable good subsequence.


Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $$$(x_1,y_1)$$$ to the point $$$(x_2,y_2)$$$.He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly $$$1$$$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $$$1$$$ unit.   For example, if the box is at the point $$$(1,2)$$$ and Wabbit is standing at the point $$$(2,2)$$$, he can pull the box right by $$$1$$$ unit, with the box ending up at the point $$$(2,2)$$$ and Wabbit ending at the point $$$(3,2)$$$.Also, Wabbit can move $$$1$$$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $$$1$$$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes $$$1$$$ second to travel $$$1$$$ unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$. Note that the point where Wabbit ends up at does not matter.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$: the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains four space-separated integers $$$x_1, y_1, x_2, y_2$$$ $$$(1 \leq x_1, y_1, x_2, y_2 \leq 10^9)$$$, describing the next test case.

For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$.

NoteIn the first test case, the starting and the ending points of the box are $$$(1,2)$$$ and $$$(2,2)$$$ respectively. This is the same as the picture in the statement. Wabbit needs only $$$1$$$ second to move as shown in the picture in the statement.In the second test case, Wabbit can start at the point $$$(2,1)$$$. He pulls the box to $$$(2,1)$$$ while moving to $$$(3,1)$$$. He then moves to $$$(3,2)$$$ and then to $$$(2,2)$$$ without pulling the box. Then, he pulls the box to $$$(2,2)$$$ while moving to $$$(2,3)$$$. It takes $$$4$$$ seconds.


You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!   Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$, $$$1 \le x \le 10^9$$$) — the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $$$n$$$ lines of each query contain the descriptions of types of blows you can deal. The $$$i$$$-th line contains two integers $$$d_i$$$ and $$$h_i$$$ ($$$1 \le d_i, h_i \le 10^9$$$) — the description of the $$$i$$$-th blow.

For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich.  If Zmei Gorynuch cannot be defeated print $$$-1$$$.

NoteIn the first query you can deal the first blow (after that the number of heads changes to $$$10 - 6 + 3 = 7$$$), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

my $debug = 0;

<>;

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

	my( $n, $x ) = split;

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

	my $strongest = ( sort { $b <=> $a } @_ )[ 0 ];

	my $best = ( sort { eval( $b =~ s/ /-/r) <=> eval( $a =~ s/ /-/r ) } @_ )[ 0 ];

	my $minus = eval( $best =~ s/ /-/r);

	$debug and print "n: $n, x: $x, strongest: $strongest, best: $best, minus: $minus";

	my $turns = 1;

	$x -= $strongest;

	if( $x <= 0 ){
		print $turns;
		next;
		}

	if( $minus <= 0 ){
		print -1;
		next;
		}

	$debug and print "x: $x";

	$turns += int( $x / $minus ) + !! ( $x % $minus );

	print $turns;
	}


Berland crossword is a puzzle that is solved on a square grid with $$$n$$$ rows and $$$n$$$ columns. Initially all the cells are white.To solve the puzzle one has to color some cells on the border of the grid black in such a way that:   exactly $$$U$$$ cells in the top row are black;  exactly $$$R$$$ cells in the rightmost column are black;  exactly $$$D$$$ cells in the bottom row are black;  exactly $$$L$$$ cells in the leftmost column are black. Note that you can color zero cells black and leave every cell white.Your task is to check if there exists a solution to the given puzzle.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains $$$5$$$ integers $$$n, U, R, D, L$$$ ($$$2 \le n \le 100$$$; $$$0 \le U, R, D, L \le n$$$).

For each testcase print "YES" if the solution exists and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteHere are possible solutions to testcases $$$1$$$, $$$2$$$ and $$$4$$$: