Monocarp is playing a computer game once again. He is a wizard apprentice, who only knows a single spell. Luckily, this spell can damage the monsters.The level he's currently on contains $$$n$$$ monsters. The $$$i$$$-th of them appears $$$k_i$$$ seconds after the start of the level and has $$$h_i$$$ health points. As an additional constraint, $$$h_i \le k_i$$$ for all $$$1 \le i \le n$$$. All $$$k_i$$$ are different.Monocarp can cast the spell at moments which are positive integer amounts of second after the start of the level: $$$1, 2, 3, \dots$$$ The damage of the spell is calculated as follows. If he didn't cast the spell at the previous second, the damage is $$$1$$$. Otherwise, let the damage at the previous second be $$$x$$$. Then he can choose the damage to be either $$$x + 1$$$ or $$$1$$$. A spell uses mana: casting a spell with damage $$$x$$$ uses $$$x$$$ mana. Mana doesn't regenerate.To kill the $$$i$$$-th monster, Monocarp has to cast a spell with damage at least $$$h_i$$$ at the exact moment the monster appears, which is $$$k_i$$$.Note that Monocarp can cast the spell even when there is no monster at the current second.The mana amount required to cast the spells is the sum of mana usages for all cast spells. Calculate the least amount of mana required for Monocarp to kill all monsters.It can be shown that it's always possible to kill all monsters under the constraints of the problem.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of monsters in the level. The second line of the testcase contains $$$n$$$ integers $$$k_1 < k_2 < \dots < k_n$$$ ($$$1 \le k_i \le 10^9$$$) — the number of second from the start the $$$i$$$-th monster appears at. All $$$k_i$$$ are different, $$$k_i$$$ are provided in the increasing order. The third line of the testcase contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le k_i \le 10^9$$$) — the health of the $$$i$$$-th monster. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^4$$$.

For each testcase, print a single integer — the least amount of mana required for Monocarp to kill all monsters.

NoteIn the first testcase of the example, Monocarp can cast spells $$$3, 4, 5$$$ and $$$6$$$ seconds from the start with damages $$$1, 2, 3$$$ and $$$4$$$, respectively. The damage dealt at $$$6$$$ seconds is $$$4$$$, which is indeed greater than or equal to the health of the monster that appears.In the second testcase of the example, Monocarp can cast spells $$$3, 4$$$ and $$$5$$$ seconds from the start with damages $$$1, 2$$$ and $$$3$$$, respectively.In the third testcase of the example, Monocarp can cast spells $$$4, 5, 7, 8$$$ and $$$9$$$ seconds from the start with damages $$$1, 2, 1, 1$$$ and $$$2$$$, respectively.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

<>;

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

	my @k = split ' ', <>;
	my @h = split ' ', <>;

	my $sum = 0;

	while( @k ){
		my $k = pop @k;
		my $h = pop @h;

		if( @k ){
			if( $k[ -1 ] + $h > $k ){
				my $k2 = pop @k;
				my $h2 = pop @h;

				push @k, $k;
				push @h, $h2 + $k - $k2 > $h ? $h2 + $k - $k2 : $h;
				}
			else{
				$sum += $h * ( $h + 1 ) / 2;
				}
			}
		else{
			$sum += $h * ( $h + 1 ) / 2;
			}
		}

	print $sum;
	}


Polycarp has n dice d1, d2, ..., dn. The i-th dice shows numbers from 1 to di. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d1, d2, ..., dn. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is A = 11, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.

The first line contains two integers n, A (1 ≤ n ≤ 2·105, n ≤ A ≤ s) — the number of dice and the sum of shown values where s = d1 + d2 + ... + dn. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 106), where di is the maximum value that the i-th dice can show.

Print n integers b1, b2, ..., bn, where bi is the number of values for which it is guaranteed that the i-th dice couldn't show them.

NoteIn the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3.


Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!

The first line of the input contains three space-separated integers l, r and k (1 ≤ l ≤ r ≤ 1018, 2 ≤ k ≤ 109).

Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).

NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.


The robot is placed in the top left corner of a grid, consisting of $$$n$$$ rows and $$$m$$$ columns, in a cell $$$(1, 1)$$$.In one step, it can move into a cell, adjacent by a side to the current one:   $$$(x, y) \rightarrow (x, y + 1)$$$;  $$$(x, y) \rightarrow (x + 1, y)$$$;  $$$(x, y) \rightarrow (x, y - 1)$$$;  $$$(x, y) \rightarrow (x - 1, y)$$$. The robot can't move outside the grid.The cell $$$(s_x, s_y)$$$ contains a deadly laser. If the robot comes into some cell that has distance less than or equal to $$$d$$$ to the laser, it gets evaporated. The distance between two cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$.Print the smallest number of steps that the robot can take to reach the cell $$$(n, m)$$$ without getting evaporated or moving outside the grid. If it's not possible to reach the cell $$$(n, m)$$$, print -1.The laser is neither in the starting cell, nor in the ending cell. The starting cell always has distance greater than $$$d$$$ to the laser.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The only line of each testcase contains five integers $$$n, m, s_x, s_y, d$$$ ($$$2 \le n, m \le 1000$$$; $$$1 \le s_x \le n$$$; $$$1 \le s_y \le m$$$; $$$0 \le d \le n + m$$$) — the size of the grid, the cell that contains the laser and the evaporating distance of the laser. The laser is neither in the starting cell, nor in the ending cell ($$$(s_x, s_y) \neq (1, 1)$$$ and $$$(s_x, s_y) \neq (n, m)$$$). The starting cell $$$(1, 1)$$$ always has distance greater than $$$d$$$ to the laser ($$$|s_x - 1| + |s_y - 1| > d$$$).

For each testcase, print a single integer. If it's possible to reach the cell $$$(n, m)$$$ from $$$(1, 1)$$$ without getting evaporated or moving outside the grid, then print the smallest amount of steps it can take the robot to reach it. Otherwise, print -1.


The hero is addicted to glory, and is fighting against a monster. The hero has $$$n$$$ skills. The $$$i$$$-th skill is of type $$$a_i$$$ (either fire or frost) and has initial damage $$$b_i$$$. The hero can perform all of the $$$n$$$ skills in any order (with each skill performed exactly once). When performing each skill, the hero can play a magic as follows:   If the current skill immediately follows another skill of a different type, then its damage is doubled.  In other words,   If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$c$$$ damage;  If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type frost, then it will deal $$$2c$$$ damage;  If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$2c$$$ damage;  If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type frost , then it will deal $$$c$$$ damage. Your task is to find the maximum damage the hero can deal.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$), indicating the number of skills.  The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 1$$$), where $$$a_i$$$ indicates the type of the $$$i$$$-th skill. Specifically, the $$$i$$$-th skill is of type fire if $$$a_i = 0$$$, and of type frost if $$$a_i = 1$$$.  The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$), where $$$b_i$$$ indicates the initial damage of the $$$i$$$-th skill.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output the maximum damage the hero can deal.

NoteIn the first test case, we can order the skills by $$$[3, 1, 4, 2]$$$, and the total damage is $$$100 + 2 \times 1 + 2 \times 1000 + 10 = 2112$$$.In the second test case, we can order the skills by $$$[1, 4, 2, 5, 3, 6]$$$, and the total damage is $$$3 + 2 \times 6 + 2 \times 4 + 2 \times 7 + 2 \times 5 + 2 \times 8 = 63$$$.In the third test case, we can order the skills by $$$[1, 2, 3]$$$, and the total damage is $$$1000000000 + 1000000000 + 1000000000 = 3000000000$$$.In the fourth test case, there is only one skill with initial damage $$$1$$$, so the total damage is $$$1$$$.

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

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

while( $testcase -- > 0 ){

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

  my @sa0 = (); my @sb0 = ();
  for(my $i=0;$i<$n;$i++){
    if( $A[$i] == 0 ){
      push(@sa0,$B[$i]);
    } else {
      push(@sb0,$B[$i]);
    }
  }

  my @sa = sort { $b <=> $a } @sa0;
  my @sb = sort { $b <=> $a } @sb0;

  my @sa2 = (@sa);
  my @sb2 = (@sb);

  my $r1 =0;
  if( @sa ){
    $r1 = pop @sa;
    my $sw = 1;
    while( @sa or @sb ){
      if( @sa and @sb ){
        my $v;
        if( $sw == 1 ){
          $v = shift @sb;
        } else {
          $v = shift @sa;
        }
        $sw ^= 1;
        $r1 += 2 * $v;
      } elsif( @sa ){
        my $v = shift @sa;
        $v *= ( $sw == 0 ? 2 : 1);
        $r1 += $v;
        $sw = -1;
      } elsif( @sb ){
        my $v = shift @sb;
        $v *= ( $sw == 1 ? 2 : 1);
        $r1 += $v;
        $sw = -1;
      }
    }
  }

  my $r2 = 0;
  if( @sb2 ){
    $r2 = pop @sb2;
    my $sw = 0;
    while( @sa2 or @sb2 ){
      if( @sa2 and @sb2 ){
        my $v;
        if( $sw == 1 ){
          $v = shift @sb2;
        } else {
          $v = shift @sa2;
        }
        $sw ^= 1;
        $r2 += 2 * $v;
      } elsif( @sa2 ){
        my $v = shift @sa2;
        $v *= ( $sw == 0 ? 2 : 1);
        $r2 += $v;
        $sw = -1;
      } elsif( @sb2 ){
        my $v = shift @sb2;
        $v *= ( $sw == 1 ? 2 : 1);
        $r2 += $v;
        $sw = -1;
      }
    }
  }
  print ( ( &max($r1,$r2) ) . "\n" );
}

exit(0);

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


You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.

Print minimal r so that each city will be covered by cellular network.


The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $$$h$$$ hours and each hour lasts $$$m$$$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $$$0$$$ to $$$h-1$$$ and minutes are numbered from $$$0$$$ to $$$m-1$$$.  That's how the digits are displayed on the clock. Please note that digit $$$1$$$ is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).The image of the clocks in the mirror is reflected against a vertical axis.  The reflection is not a valid time.The reflection is a valid time with $$$h=24$$$, $$$m = 60$$$. However, for example, if $$$h=10$$$, $$$m=60$$$, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $$$s$$$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.It can be shown that with any $$$h$$$, $$$m$$$, $$$s$$$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.You are asked to solve the problem for several test cases.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. The next $$$2 \cdot T$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers $$$h$$$, $$$m$$$ ($$$1 \le h, m \le 100$$$). The second line contains the start time $$$s$$$ in the described format HH:MM.

For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct.

NoteIn the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct.


Theater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.A position is good if two conditions hold:   there is no actor in the cell the spotlight is placed to;  there is at least one actor in the direction the spotlight projects. Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the plan. The next n lines contain m integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.

Print one integer — the number of good positions for placing the spotlight.

NoteIn the first example the following positions are good:  the (1, 1) cell and right direction;  the (1, 1) cell and down direction;  the (1, 3) cell and left direction;  the (1, 3) cell and down direction;  the (1, 4) cell and left direction;  the (2, 2) cell and left direction;  the (2, 2) cell and up direction;  the (2, 2) and right direction;  the (2, 4) cell and left direction. Therefore, there are 9 good positions in this example.

use integer;

$,=" ";
my ($n,$m)=split / /,<>;
chomp($n,$m);
my @GRID;
my $count_=0;
my $before=0;
my $after=0;
my $c=0;
my $kki=0;
$n--;
$m--;
my @t1=(0..$n);
my @t2=(0..$m);
while(<>)
{
  $before=0;
  $after=0;
  $c=0;
  chomp;
  s/ //g;
  push @GRID,$_;
  if(/1/)
  {
    for my $j (@t2)
    {
      if(!substr($GRID[$kki],$j,1)){
        $c++;
        $count_++ if($before);
      }elsif(substr($GRID[$kki],$j,1))
      {
        if($before)
        {
          $count_+=$c;
          $c=0;
        }
        else
        {
          $before=1;
          $count_+=$c;
        }
        $c=0;
      }
    }
  }
  $kki++;
}

for my $i (@t2)
{
  $before=undef;
  $after=undef;
  $c=undef;
  for my $j (@t1)
  {
    if(!substr($GRID[$j],$i,1)){
      $c++;
      $count_++ if($before);
    }elsif(substr($GRID[$j],$i,1))
    {
      if($before)
      {
        $count_+=$c;
        $c=0;
      }
      else
      {
        $before=1;
        $count_+=$c;
      }
      $c=0;
    }
  }
}

print $count_ . "\n";


Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.Petya can ask questions like: "Is the unknown number divisible by number y?".The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers yi, he should ask the questions about.

A single line contains number n (1 ≤ n ≤ 103).

Print the length of the sequence of questions k (0 ≤ k ≤ n), followed by k numbers — the questions yi (1 ≤ yi ≤ n). If there are several correct sequences of questions of the minimum length, you are allowed to print any of them.

NoteThe sequence from the answer to the first sample test is actually correct.If the unknown number is not divisible by one of the sequence numbers, it is equal to 1.If the unknown number is divisible by 4, it is 4.If the unknown number is divisible by 3, then the unknown number is 3.Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter.


When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read.

The first line contains two integers n and t (1 ≤ n ≤ 105; 1 ≤ t ≤ 109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.

Print a single integer — the maximum number of books Valera can read.


There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight ai.For example, if weights are [1, 2, 2, 2, 1, 2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are:  the first monster can't eat the second monster because a1 = 1 is not greater than a2 = 2;  the second monster can't eat the third monster because a2 = 2 is not greater than a3 = 2;  the second monster can't eat the fifth monster because they are not neighbors;  the second monster can eat the first monster, the queue will be transformed to [3, 2, 2, 1, 2]. After some time, someone said a good joke and all monsters recovered. At that moment there were k (k ≤ n) monsters in the queue, the j-th of which had weight bj. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last.You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other.

The first line contains single integer n (1 ≤ n ≤ 500) — the number of monsters in the initial queue. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial weights of the monsters. The third line contains single integer k (1 ≤ k ≤ n) — the number of monsters in the queue after the joke.  The fourth line contains k integers b1, b2, ..., bk (1 ≤ bj ≤ 5·108) — the weights of the monsters after the joke.  Monsters are listed in the order from the beginning of the queue to the end.

In case if no actions could lead to the final queue, print "NO" (without quotes) in the only line.  Otherwise print "YES" (without quotes) in the first line. In the next n - k lines print actions in the chronological order. In each line print x — the index number of the monster in the current queue which eats and, separated by space, the symbol 'L' if the monster which stays the x-th in the queue eats the monster in front of him, or 'R' if the monster which stays the x-th in the queue eats the monster behind him. After each eating the queue is enumerated again.  When one monster eats another the queue decreases. If there are several answers, print any of them.

NoteIn the first example, initially there were n = 6 monsters, their weights are [1, 2, 2, 2, 1, 2] (in order of queue from the first monster to the last monster). The final queue should be [5, 5]. The following sequence of eatings leads to the final queue:  the second monster eats the monster to the left (i.e. the first monster), queue becomes [3, 2, 2, 1, 2];  the first monster (note, it was the second on the previous step) eats the monster to the right (i.e. the second monster), queue becomes [5, 2, 1, 2];  the fourth monster eats the mosnter to the left (i.e. the third monster), queue becomes [5, 2, 3];  the finally, the third monster eats the monster to the left (i.e. the second monster), queue becomes [5, 5]. Note that for each step the output contains numbers of the monsters in their current order in the queue.


n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.What is the maximum amount of people that could stay at the party in the end?

The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).

For each test output in a separate line one number — the maximum amount of people that could stay in the end.


Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2 ,3,...,   10" will be corrected to "1, 2, 3, ..., 10".In this task you are given a string s, which is composed by a concatination of terms, each of which may be:   a positive integer of an arbitrary length (leading zeroes are not allowed),  a "comma" symbol (","),  a "space" symbol (" "),  "three dots" ("...", that is, exactly three points written one after another, also known as suspension points). Polycarp wants to add and remove spaces in the string s to ensure the following:   each comma is followed by exactly one space (if the comma is the last character in the string, this rule does not apply to it),  each "three dots" term is preceded by exactly one space (if the dots are at the beginning of the string, this rule does not apply to the term),  if two consecutive numbers were separated by spaces only (one or more), then exactly one of them should be left,  there should not be other spaces. Automate Polycarp's work and write a program that will process the given string s.

The input data contains a single string s. Its length is from 1 to 255 characters. The string s does not begin and end with a space. Its content matches the description given above.

Print the string s after it is processed. Your program's output should be exactly the same as the expected answer. It is permissible to end output line with a line-break character, and without it.


At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.

Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.

NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.


This problem is same as the previous one, but has larger constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the $$$n$$$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $$$i$$$-th day has a ribbon with color $$$u_i$$$. Shiro wants to know the largest number $$$x$$$, such that if we consider the streak of the first $$$x$$$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $$$x - 1$$$ will have the same number of occurrences.For example, consider the following sequence of $$$u_i$$$: $$$[2, 2, 1, 1, 5, 4, 4, 5]$$$. Then $$$x = 7$$$ makes a streak, since if we remove the leftmost $$$u_i = 5$$$, each ribbon color will appear exactly twice in the prefix of $$$x - 1$$$ days. Note that $$$x = 8$$$ doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the total number of days. The second line contains $$$n$$$ integers $$$u_1, u_2, \ldots, u_n$$$ ($$$1 \leq u_i \leq 10^5$$$) — the colors of the ribbons the cats wear.

Print a single integer $$$x$$$ — the largest possible streak of days.

NoteIn the first example, we can choose the longest streak of $$$13$$$ days, since upon removing the last day out of the streak, all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$ will have the same number of occurrences of $$$3$$$. Note that the streak can also be $$$10$$$ days (by removing the $$$10$$$-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first $$$6$$$ days, we can remove the third day from this streak then all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ will occur exactly once.


You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest".A palindrome is a string that reads the same forward or backward.The length of string B should be at most 104. It is guaranteed that there always exists such string.You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104.

First line contains a string A (1 ≤ |A| ≤ 103) consisting of lowercase Latin letters, where |A| is a length of A.

Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. If there are many possible B, print any of them.

NoteIn the first example, "aba" is a subsequence of "aba" which is a palindrome.In the second example, "ab" is a subsequence of "aabaa" which is a palindrome.

use strict;
use warnings;
use 5.010;

my $str = <>;
chop $str;
my $rev = reverse $str;
$str .= $rev;
say $str;

$a = <STDIN>;
chomp $a;
print($a);
print(scalar reverse $a);

use strict;
use warnings;
use 5.010;

my $str = <>;
my $rev = reverse $str;
$str .= $rev;
say $str;
#


Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?

The first line contains the only integer n (0 ≤ n ≤ 10100000). It is guaranteed that n doesn't contain any leading zeroes.

Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.

NoteIn the first sample the number already is one-digit — Herald can't cast a spell.The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit.

#!/usr/bin/perl -w

chomp ($num = <>);
@arr = unpack('(A1)*', $num);
$count = 0;
while (@arr > 1) {
	$count++;
	$num = 0;
	for $i (0..@arr-1) {
		$num += $arr[$i];
	}
	@arr = unpack('(A1)*', $num);
}
print $count;


Initially Ildar has an empty array. He performs $$$n$$$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset $$$[0, 2, 3]$$$ is $$$1$$$, while the mex of the multiset $$$[1, 2, 1]$$$ is $$$0$$$.More formally, on the step $$$m$$$, when Ildar already has an array $$$a_1, a_2, \ldots, a_{m-1}$$$, he chooses some subset of indices $$$1 \leq i_1 < i_2 < \ldots < i_k < m$$$ (possibly, empty), where $$$0 \leq k < m$$$, and appends the $$$mex(a_{i_1}, a_{i_2}, \ldots a_{i_k})$$$ to the end of the array.After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $$$a_1, a_2, \ldots, a_n$$$ the minimum step $$$t$$$ such that he has definitely made a mistake on at least one of the steps $$$1, 2, \ldots, t$$$, or determine that he could have obtained this array without mistakes.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the number of steps Ildar made. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array Ildar obtained.

If Ildar could have chosen the subsets on each step in such a way that the resulting array is $$$a_1, a_2, \ldots, a_n$$$, print $$$-1$$$. Otherwise print a single integer $$$t$$$ — the smallest index of a step such that a mistake was made on at least one step among steps $$$1, 2, \ldots, t$$$.

NoteIn the first example it is possible that Ildar made no mistakes. Here is the process he could have followed.  $$$1$$$-st step. The initial array is empty. He can choose an empty subset and obtain $$$0$$$, because the mex of an empty set is $$$0$$$. Appending this value to the end he gets the array $$$[0]$$$.  $$$2$$$-nd step. The current array is $$$[0]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1]$$$.  $$$3$$$-rd step. The current array is $$$[0,1]$$$. He can choose a subset $$$[0,1]$$$ and obtain an integer $$$2$$$, because $$$mex(0,1) = 2$$$. Appending this value to the end he gets the array $$$[0,1,2]$$$.  $$$4$$$-th step. The current array is $$$[0,1,2]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1,2,1]$$$. Thus, he can get the array without mistakes, so the answer is $$$-1$$$.In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from $$$0$$$.In the third example he could have obtained $$$[0, 1, 2]$$$ without mistakes, but $$$239$$$ is definitely wrong.

use strict;
use warnings;

my $input = <STDIN>;
my $n = 0+$input;
$input = <STDIN>;
my @arr = map {$_+0} split / /, $input;
my $max_mex = 0;
my $answer = -1;
my $e;
for my $i (0.. scalar @arr - 1) {
    $e = $arr[$i];
    if ($e > $max_mex) {
        $answer = $i+1;
        last;
    } else {
        $max_mex = $e + 1 if $max_mex == $e;
    }
}
print($answer);

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my $max = -1;
	my $ans = -1;

	for my $i ( 0 .. @_ - 1 ){
		if( $_[ $i ] > $max + 1 ){
			$ans = $i + 1;
			last;
			}
		$max < $_[ $i ] and $max = $_[ $i ];
		}

	print $ans;
	}


There is a $$$n \times m$$$ grid. You are standing at cell $$$(1, 1)$$$ and your goal is to finish at cell $$$(n, m)$$$.You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell $$$(x, y)$$$. You can:   move right to the cell $$$(x, y + 1)$$$ — it costs $$$x$$$ burles;  move down to the cell $$$(x + 1, y)$$$ — it costs $$$y$$$ burles. Can you reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first and only line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n, m \le 100$$$; $$$0 \le k \le 10^4$$$) — the sizes of grid and the exact amount of money you need to spend.

For each test case, if you can reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles, print YES. Otherwise, print NO. 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).

NoteIn the first test case, you are already in the final cell, so you spend $$$0$$$ burles.In the second, third and fourth test cases, there are two paths from $$$(1, 1)$$$ to $$$(2, 2)$$$: $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(1, 2)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ or $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$. Both costs $$$1 + 2 = 3$$$ burles, so it's the only amount of money you can spend.In the fifth test case, there is the only way from $$$(1, 1)$$$ to $$$(1, 4)$$$ and it costs $$$1 + 1 + 1 = 3$$$ burles.

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

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

while( $test_case -- > 0 ){
  my ($n,$m,$k) = map { $_ - 0 } split(/\s+/,<STDIN>);
  if( ( $n - 1 ) + $n * ( $m - 1 ) == $k ){
    print "YES\n";
  } else {
    print "NO\n";
  }
}

exit(0);


Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.

The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).

Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1).In the second sample you need 6 moves to build permutation (1, 3, 2).


Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second.The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.

The first line of the input contains a single integer l (1 ≤ l ≤ 1 000) — the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≤ p, q ≤ 500) — the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively.

Print a single real number — the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4.  Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .

NoteIn the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor.


Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second.Scrooge signed exactly k papers throughout his life and all those signatures look the same.Find the total time Scrooge wasted signing the papers.

The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 1000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai — integers xi and yi, separated by a space. All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.

Print one real number — the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10 - 6.

#!/usr/bin/perl

use Math::Complex;

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

$ats=1*$'/50;

($x, $y)=split/ /,<>;

for (2..$`){
    <>=~/ /;
    $sum += sqrt (($x-$`)**2 + ($y-$')**2);
    $x=$`; $y=$';
    }
print $sum*$ats;

#-----------SUBs-------------#

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

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

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

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

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

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

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

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

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

$PI=3.14159265358979323846;
$MOD=1000000007;


You are given two integers $$$l$$$ and $$$r$$$, where $$$l < r$$$. We will add $$$1$$$ to $$$l$$$ until the result is equal to $$$r$$$. Thus, there will be exactly $$$r-l$$$ additions performed. For each such addition, let's look at the number of digits that will be changed after it.For example:   if $$$l=909$$$, then adding one will result in $$$910$$$ and $$$2$$$ digits will be changed;  if you add one to $$$l=9$$$, the result will be $$$10$$$ and $$$2$$$ digits will also be changed;  if you add one to $$$l=489999$$$, the result will be $$$490000$$$ and $$$5$$$ digits will be changed. Changed digits always form a suffix of the result written in the decimal system.Output the total number of changed digits, if you want to get $$$r$$$ from $$$l$$$, adding $$$1$$$ each time.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by two integers $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le 10^9$$$).

For each test case, calculate the total number of changed digits if you want to get $$$r$$$ from $$$l$$$, adding one each time.

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

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

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

  my $r = &f($r) - &f($l);
  print "$r\n";

}

exit(0);

sub f {
  my $x = shift;
  my $r = 0;
  while( $x > 0 ){
    $r += $x;
    $x /= 10;
  }
  return $r;
}


Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$.    An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d < n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.

Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).

NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	for( 1 .. <> ){
		my( $x, $y ) = sort { $a <=> $b } split ' ', <>;
		print "NO" and next if $x + $y < $d;
		print "NO" and next if $x + $y > $n + $n - $d;
		print "NO" and next if $y - $x > $d;
		print "NO" and next if $y - $x < -$d;

		print "YES";
		}

	}


You are given $$$n$$$ rectangles, each of height $$$1$$$. Each rectangle's width is a power of $$$2$$$ (i. e. it can be represented as $$$2^x$$$ for some non-negative integer $$$x$$$). You are also given a two-dimensional box of width $$$W$$$. Note that $$$W$$$ may or may not be a power of $$$2$$$. Moreover, $$$W$$$ is at least as large as the width of the largest rectangle.You have to find the smallest height of this box, such that it is able to fit all the given rectangles. It is allowed to have some empty space left in this box after fitting all the rectangles.You cannot rotate the given rectangles to make them fit into the box. Moreover, any two distinct rectangles must not overlap, i. e., any two distinct rectangles must have zero intersection area.See notes for visual explanation of sample input.

The first line of input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^3$$$) — the number of test cases. Each test case consists of two lines. For each test case:  the first line contains two integers $$$n$$$ ($$$1 \le n \le 10^5$$$) and $$$W$$$ ($$$1 \le W \le 10^9$$$); the second line contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^6$$$), where $$$w_i$$$ is the width of the $$$i$$$-th rectangle. Each $$$w_i$$$ is a power of $$$2$$$; additionally, $$$\max\limits_{i=1}^{n} w_i \le W$$$.  The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

Output $$$t$$$ integers. The $$$i$$$-th integer should be equal to the answer to the $$$i$$$-th test case — the smallest height of the box.

NoteFor the first test case in the sample input, the following figure shows one way to fit the given five rectangles into the 2D box with minimum height:  In the figure above, the number inside each rectangle is its width. The width of the 2D box is $$$16$$$ (indicated with arrow below). The minimum height required for the 2D box in this case is $$$2$$$ (indicated on the left).In the second test case, you can have a minimum height of three by keeping two blocks (one each of widths eight and two) on each of the three levels.

#!/usr/bin/perl

# TLE 5;
# greedy, fill

use warnings;
use strict;

$\ = $/;

my @widths = map 2 ** $_, 0 .. 19;

<>;

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

	@_ = split ' ', <>;

	my %h;

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

	my $height = 0;

	while( keys %h ){
		$height ++;
		my $ww = $w;

		for my $i ( sort { $b <=> $a } keys %h ){
	#%	for my $i ( reverse @widths ){
			next if not exists $h{ $i };
			if( $ww - $i >= 0 ){
				$ww -= $i;
				$h{ $i } --;
				$h{ $i } == 0 and delete $h{ $i };
				redo;
				}
			}
		}

	print $height;
	}


The Queen of England has n trees growing in a row in her garden. At that, the i-th (1 ≤ i ≤ n) tree from the left has height ai meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all i (1 ≤ i < n), ai + 1 - ai = k, where k is the number the Queen chose.Unfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes?

The first line contains two space-separated integers: n, k (1 ≤ n, k ≤ 1000). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the heights of the trees in the row.

In the first line print a single integer p — the minimum number of minutes the gardener needs. In the next p lines print the description of his actions.  If the gardener needs to increase the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, then print in the corresponding line "+ j x". If the gardener needs to decrease the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, print on the corresponding line "- j x". If there are multiple ways to make a row of trees beautiful in the minimum number of actions, you are allowed to print any of them.

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

my ($n, $k) = split /\s/, <>;
my @w = split /\s/, <>;

my $min = 1001;
my $min_i;
for my $i (0..$n-1){
	my $err = 0;
	my $lmin = 0;
	for my $j (0..$n-1){
		if ( $w[$i] + ($j-$i)*$k <= 0 ) {
			$err = 1;
			last;
		}

		if($w[$i] + ($j-$i)*$k != $w[$j]){
			$lmin++;
		}
	}
	if(!$err && $lmin < $min){
		$min = $lmin;
		$min_i = $i;
	}
}

print "$min\n";
for my $j (0..$n-1){
	my $delta = $w[$min_i]+($j-$min_i)*$k - $w[$j];
	if($delta != 0){
		my $sign = ($delta > 0) ? '+' : '-';
		$delta = abs($delta);
		my $pos = $j+1;
		print "$sign $pos $delta\n";
	}
}

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

my ($n, $k) = split /\s/, <>;
my @w = split /\s/, <>;

my $min = 1001;
my $min_i;
for my $i (0..$n-1){
	my $lmin = 0;
	for my $j (0..$n-1){
		if($w[$j]-$w[$i] != ($j-$i)*$k){
			$lmin++;
		}
	}
	if($lmin < $min){
		$min = $lmin;
		$min_i = $i;
	}
}

print "$min\n";
for my $j (0..$n-1){
	my $delta = $w[$min_i]+($j-$min_i)*$k - $w[$j];
	if($delta != 0){
		my $sign = ($delta > 0) ? '+' : '-';
		$delta = abs($delta);
		my $pos = $j+1;
		print "$sign $pos $delta\n";
	}
}


Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$. Bob lives near the station with number $$$1$$$, while Alice lives near the station with number $$$s$$$. The metro line has two tracks. Trains on the first track go from the station $$$1$$$ to the station $$$n$$$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$2 \le s \le n \le 1000$$$) — the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station $$$1$$$. Next lines describe information about closed and open stations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$). If $$$a_i = 1$$$, then the $$$i$$$-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$b_i = 0$$$ or $$$b_i = 1$$$). If $$$b_i = 1$$$, then the $$$i$$$-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.

Print "YES" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and "NO" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).

NoteIn the first example, all stations are opened, so Bob can simply travel to the station with number $$$3$$$.In the second example, Bob should travel to the station $$$5$$$ first, switch to the second track and travel to the station $$$4$$$ then.In the third example, Bob simply can't enter the train going in the direction of Alice's home.

use strict;
use warnings;

my $input = <STDIN>;
my ($n, $m) = map {$_+0} split / /, $input;
$input = <STDIN>;
my @a1 = map {$_+0} split / /, $input;
$input = <STDIN>;
my @a2 = map {$_+0} split / /, $input;
my %hash = ($m => 1);
my %hash2 = ();
my @a = ($m);
my $oo;
while(@a) {
    $m = $a[0];
    my $ok = ff($m, \%hash, $n, \@a1, \@a2, 1);
    if ($ok == 1) {
        print "YES";
        $oo=1;
        last;
    }
    $hash2{$m} = 1;
    @a = grep {not defined $hash2{$_}} keys %hash;
}
print "NO" unless $oo;

sub ff {
    my ($station, $h, $n, $a1, $a2, $m) = @_;
    my $ok = 0;
    if ($station < $n && $a2->[$station-1]) {
        for (($station + 1) .. $n) {
            if ($a2->[$_-1]) {
                return 1 if $_ == $m;
                $ok = -1 unless defined $h->{$_};
                $h->{$_} = 1;
            }
        }
    }
    if ($station > 1) {
        for (1..$station - 1) {
            if ($a1->[$_-1] && $a1->[$station-1]) {
                return 1 if $_ == $m;
                $ok = -1 unless defined $h->{$_};
                $h->{$_} = 1;
            }
        }
    }
}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my @A = split ' ', <> =~ s/1/2/rg;
	my @B = split ' ', <>;

	if( $A[ 0 ] == 0 ){
		print "NO";
		next;
		}

	$_ += shift @B for @A;

	$_ = reverse join '', @A;

	s/3\K(1+)/ 2 x length $1 /ge;

	$_ = reverse;

	print 1 < ( substr $_, $s - 1, 1 ) ? "YES" : "NO";
	}


Polycarp likes to play with numbers. He takes some integer number $$$x$$$, writes it down on the board, and then performs with it $$$n - 1$$$ operations of the two kinds:   divide the number $$$x$$$ by $$$3$$$ ($$$x$$$ must be divisible by $$$3$$$);  multiply the number $$$x$$$ by $$$2$$$. After each operation, Polycarp writes down the result on the board and replaces $$$x$$$ by the result. So there will be $$$n$$$ numbers on the board after all.You are given a sequence of length $$$n$$$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.

The first line of the input contatins an integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the number of the elements in the sequence. The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 3 \cdot 10^{18}$$$) — rearranged (reordered) sequence that Polycarp can wrote down on the board.

Print $$$n$$$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists.

NoteIn the first example the given sequence can be rearranged in the following way: $$$[9, 3, 6, 12, 4, 8]$$$. It can match possible Polycarp's game which started with $$$x = 9$$$.


The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.A Bitlandish string is a string made only of characters "0" and "1".BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p = x xor y, q = x or y. Then he replaces one of the two taken characters by p and the other one by q.The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.

The first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths. It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 106.

Print "YES" if a can be transformed into b, otherwise print "NO". Please do not print the quotes.

chomp ($str1 = <STDIN>);
chomp ($str2 = <STDIN>);
if (length($str1) == length($str2)) {
	printf "YES\n" if ($str1 =~ /1/ && $str2 =~ /1/);
	printf "YES\n" if ($str1 !~ /1/ && $str2 !~ /1/);
	printf "NO\n"  if ($str1 !~ /1/ && $str2 =~ /1/);
	printf "NO\n"  if ($str1 =~ /1/ && $str2 !~ /1/);
} else {
	printf "NO\n";
}


You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.

The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.

Print the minimum non-zero element before each operation in a new line.

NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

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

	my %h;

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

	@_ = sort { $a <=> $b } keys %h;

	my $prev = 0;
	my @ans;

	for my $i ( 1 .. $k ){
		my $A = shift @_ // $prev;
		push @ans, $A - $prev;
		$prev = $A;
		}

	print join "\n", @ans;
	}


Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options.You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.

The first line contains three integers a, b and c (0 ≤ a, b, c ≤ 105)  — the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively. The next line contains one integer m (0 ≤ m ≤ 3·105)  — the number of mouses in the price list. The next m lines each describe another mouse. The i-th line contains first integer vali (1 ≤ vali ≤ 109)  — the cost of the i-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.

Output two integers separated by space — the number of equipped computers and the total cost of the mouses you will buy.

NoteIn the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports.

use v5.20;
use warnings;

sub compare {
	return $a <=> $b;
}

my ($a,$b,$c) = split(' ',<>);
my $m = int <>;

my (@A,@B);

for (1..$m) {
	my ($val,$type) = split(' ',<>);
	if ($type eq "USB") {
		push @A,$val;
    }
	else {
		push @B,$val;
	}
}

@A = sort compare @A;
@B = sort compare @B;

my $cost = 0;
my $comp = 0;

while ($a and scalar @A) {
	$comp += 1;
	$cost += shift @A;
	$a -= 1;
}

while ($b and scalar @B) {
	$comp += 1;
	$cost += shift @B;
	$b -= 1;
}

my @C = sort compare (@A,@B);

while ($c and scalar @C) {
	$comp += 1;
	$cost += shift @C;
	$c -= 1;
}

say "$comp $cost";

use v5.20;

my $input = <>;
my ($usb_comp, $ps2_comp, $both_comp) = split(/ /, $input);

my $m = <>;
my @usb, my @ps2;
for (my $i = 0; $i < $m; $i = $i + 1) {
	$input = <>;
	chomp $input;
	my ($number, $type) = split(/ /, $input);

	if ($type eq "USB") {
		push(@usb, $number);
	} else {
		push(@ps2, $number);
	}
}

my $price = 0;
my $matched = 0;
# Match as many only-usb computers to usb mouses.
@usb = sort {$a <=> $b} @usb;
my $i = 0;
while ($i < scalar @usb and $usb_comp > 0) {
	$price = $price + $usb[$i];
	$i++;
	$matched++;
	$usb_comp--;
}

# Match as many only-ps2 computers to usb mouses.
@ps2 = sort {$a <=> $b} @ps2;
my $j = 0;
while ($j < scalar @ps2 and $ps2_comp > 0) {
	$price = $price + $ps2[$j];
	$j++;
	$matched++;
	$ps2_comp--;
}

# Match the computers having both ports to cheapest mouses.
while (($j < scalar @ps2 or $i < scalar @usb) and $both_comp > 0) {
	if ($i >= scalar @usb or ($j < scalar @ps2 and $ps2[$j] < $usb[$i])) {
		$price = $price + $ps2[$j];
		$j++;
	} else {
		$price = $price + $usb[$i];
		$i++;
	}
	$matched++;
	$both_comp--;
}

print "$matched $price"

#use v5.24;
use warnings;
my @usb,@ps2,@merged,$nrcump=0,$costtot=0;

my $line=<stdin>;
chomp($line);
my ($usbonly,$ps2only,$both)=split(/ /,$line);
$line=<stdin>;
chomp($line);
my ($n)=split(/ /,$line);
for (my $i=1;$i<=$n;$i++){
	$line=<stdin>;
	chomp($line);
	my ($cost,$tip)=split(/ /,$line);
	if ($tip eq "USB") {push @usb, $cost;}
	else {push @ps2, $cost;}
}
@usb=sort {$a<=>$b} @usb;
@ps2=sort {$a<=>$b} @ps2;
while ($usbonly>0 && scalar @usb>0){
	$usbonly--;
	$nrcump++;
	$costtot=$costtot+shift @usb;
}
while ($ps2only>0 && scalar @ps2>0){
	$ps2only--;
	$nrcump++;
	$costtot=$costtot+shift @ps2;
}
foreach my $var (@usb) {push @merged, $var;}
foreach my $var (@ps2) {push @merged, $var;}
@merged=sort {$a<=>$b} @merged;
while ($both>0 && scalar @merged>0){
	$both--;
	$nrcump++;
	$costtot=$costtot+shift @merged;
}
print $nrcump.' '.$costtot;
<stdin>;
exit(0);

use v5.20.1;
use warnings;

=pod
my $filename = "date.in";
open(my $fh, '<:encoding(UTF-8)', $filename)
	or die "Could not open the file";
=cut

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

my($a, $b, $c) = split(' ', $line);

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

my $m = $line;

my @usb;
my @ps;
my $model;
my $price = 0;

for(my $i = 0; $i < $m; $i++){

	$line = <STDIN>;
	($price, $model) = split(' ', $line);
	if($model eq "USB"){

		push @usb, $price;

	}elsif($model eq "PS/2"){

		push @ps, $price;

	}

}

my @usbSorted = sort {$::a <=> $::b} @usb;
my @psSorted = sort {$::a <=> $::b} @ps;

@usb = @usbSorted;
@ps = @psSorted;

my $ui = 0;
my $pi = 0;
my $cost = 0;
my $mice = 0;

while($ui < @usb && $a > 0){

	$cost += $usb[$ui];
	#say $usb[$ui], "\n";
	$ui++;
	$mice++;
	$a--;

}

while($pi < @ps && $b > 0){

	$cost += $ps[$pi];
	#say $ps[$pi], "\n";
	$pi++;
	$b--;
	$mice++;

}

while($ui < @usb && $pi < @ps && $c > 0){

	if($usb[$ui] < $ps[$pi]){

		$cost += $usb[$ui];
		#say $usb[$ui], "\n";
		$c--;
		$ui++;
		$mice++;

	}else{

		$cost += $ps[$pi];
		#say $ps[$pi], "\n";
		$pi++;
		$c--;
		$mice++;

	}

}

while($ui < @usb && $c > 0){

	$cost += $usb[$ui];
	#say $usb[$ui], "\n";
	$ui++;
	$c--;
	$mice++;

}

while($pi < @ps && $c > 0){

	$cost += $ps[$pi];
	#say $ps[$pi], "\n";
	$pi++;
	$c--;
	$mice++;

}

say $mice, " ", $cost, "\n";

sub input { $_ = <>; chomp; wantarray? split: $_ }

sub less_first { sort { $a <=> $b } @_ }

sub buy {
	my ($c, $aref) = @_;
	while ($c--) {
		last unless @$aref;
		$R++, $V += shift @$aref;
	}
}

$R = $V = 0; @c = input; $m = input;
for (1..$m) {
	($v, $t) = input;
	if ($t eq "USB") {
		push @v0, $v;
	} else {
		push @v1, $v;
	}
}

@v0 = less_first @v0;
@v1 = less_first @v1;

buy $c[0], \@v0;
buy $c[1], \@v1;
@v2 = less_first @v0, @v1;
buy $c[2], \@v2;

print $R, " ", $V;

use warnings;
use v5.20;

my @array;
my $total = 0;
my $count = 0;

my $input = <STDIN>;
chomp $input;
my($A, $B, $C) = split(' ', $input);

$input = <STDIN>;
chomp $input;
my $m = int($input);

for(my $i = 0; $i < $m; $i += 1){
    $input = <STDIN>;
    chomp $input;
    my($value, $name) = split(' ', $input);
    $value = int($value);
    push @array, {id => $value, type => $name};
}

for my $item ( sort { $a->{id} <=> $b->{id} } @array ) {
    if($item->{type} eq "USB"){
        if($A > 0){
            $total = $total + $item->{id};
            $count += 1;
            $A -= 1;
        }
        elsif($C > 0){
            $total = $total + $item->{id};
            $count += 1;
            $C -= 1;
        }
    }
    else{
        if($B > 0){
            $total = $total + $item->{id};
            $count += 1;
            $B -= 1;
        }
        elsif($C > 0){
            $total = $total + $item->{id};
            $count += 1;
            $C -= 1;
        }
    }
}
print("$count $total\n");

use strict;
use warnings;

my ($usb_nr, $ps_nr, $both_nr) = split(" ", <>);
my $nr_prices = <>;
my @prices_usb = ();
my @prices_ps = ();
my $current_price = 0;
my $current_type = "";
my $equipped_usb = 0;
my $equipped_ps = 0;
my $equipped_both = 0;
my $cost = 0;
my $bought = 0;
foreach(1 .. $nr_prices)
{
	($current_price, $current_type) = split(" ", <>);
	if($current_type eq "USB")
	{
		push(@prices_usb, $current_price);
	}
	else
	{
		push(@prices_ps, $current_price);
	}
}
@prices_usb = sort {$a <=> $b} @prices_usb;
@prices_ps = sort {$a <=> $b} @prices_ps;
#print "Prices USB: @prices_usb \n";
#print "Prices PS/2: @prices_ps \n";
$bought = 0;
foreach(0 .. scalar $usb_nr-1)
{
	if($_ < scalar @prices_usb)
	{
		#print "Equipped USB PC with $prices_usb[$_]\n";
		$equipped_usb += 1;
		$cost += $prices_usb[$_];
		$bought += 1;
	}
}
splice @prices_usb, 0, $bought;
$bought = 0;
foreach(0 .. $ps_nr-1)
{
	if($_ < scalar @prices_ps)
	{
		#print "Equipped PS/2 PC with $prices_ps[$_]\n";
		$equipped_ps += 1;
		$cost += $prices_ps[$_];
		$bought += 1;
	}
}
splice @prices_ps, 0, $bought;
my $pos_usb = 0;
my $pos_ps = 0;
while($pos_usb < scalar @prices_usb and $pos_ps < scalar @prices_ps and $equipped_both < $both_nr)
{
	if($prices_usb[$pos_usb] <= $prices_ps[$pos_ps])
	{
		#print "Equipped PC with both with USB: $prices_usb[$pos_usb]\n";
		$equipped_both += 1;
		$cost += $prices_usb[$pos_usb];
		$pos_usb += 1;
	}
	else
	{
		#print "Equipped PC with both with PS/2: $prices_ps[$pos_ps]\n";
		$equipped_both += 1;
		$cost += $prices_ps[$pos_ps];
		$pos_ps += 1;
	}
}
while($pos_usb < scalar @prices_usb and $equipped_both < $both_nr)
{
	#print "Equipped PC with both with USB: $prices_usb[$pos_usb]\n";
	$equipped_both += 1;
	$cost += $prices_usb[$pos_usb];
	$pos_usb += 1;
}
while($pos_ps < scalar @prices_ps and $equipped_both < $both_nr)
{
	#print "Equipped PC with both with PS/2: $prices_ps[$pos_ps]\n";
	$equipped_both += 1;
	$cost += $prices_ps[$pos_ps];
	$pos_ps += 1;
}
print $equipped_usb + $equipped_ps + $equipped_both, " ", $cost;

use warnings;
use utf8;
use feature "say";

my $line = <>;
chomp($line);
my ($usb, $ps2, $mix) = split(' ', $line);
my $pcNr = <>;
chomp($pcNr);
my (@usb, @ps2);
while ($pcNr > 0) {
  $line = <>;
  chomp($line);
  my($price, $type) = split(' ', $line);
  if ($type eq "USB") {
    push ( @usb, $price );
  } else {
    push ( @ps2, $price);
  }
  --$pcNr;
}
@usb = sort ( { $a <=> $b } @usb );
@ps2 = sort ( { $a <=> $b } @ps2 );

my $price = 0;
my ( $iU, $iP );

for ( $iU = 0; $usb > 0 && $iU < scalar(@usb); ++$iU, --$usb) {
        $price += $usb[$iU];
        ++$pcNr;
}

for ( $iP = 0; $ps2 > 0 && $iP < scalar(@ps2); ++$iP, --$ps2) {
        $price += $ps2[$iP];
        ++$pcNr;
}

for (; ($iU < scalar(@usb) || $iP < scalar( @ps2 )) && $mix > 0; ) {
        if ( $iU < scalar(@usb) && $iP < scalar(@ps2) && $usb[$iU] <= $ps2[$iP] || $iP >= scalar(@ps2)) {
                $price += $usb[$iU];
                ++$pcNr;
                --$mix;
                ++$iU;
        } elsif ($iP < scalar(@ps2) && $iU < scalar(@usb) && $usb[$iU] > $ps2[$iP] || $iU >= scalar(@usb)) {
                $price += $ps2[$iP];
                ++$pcNr;
                --$mix;
                ++$iP;
        }
}

say $pcNr." ".$price;

    use warnings;
    use utf8;
    use feature "say";

    my $line = <>;
    chomp($line);
    my ($usb, $ps2, $mix) = split(' ', $line);
    my $pcNr = <>;
    chomp($pcNr);
    my (@usb, @ps2);
    while ($pcNr > 0) {
      $line = <>;
      chomp($line);
      my($price, $type) = split(' ', $line);
      if ($type eq "USB") {
        push ( @usb, $price );
      } else {
        push ( @ps2, $price);
      }
      --$pcNr;
    }
    @usb = sort ( { $a <=> $b } @usb );
    @ps2 = sort ( { $a <=> $b } @ps2 );

    my $price = 0;

    for ( ; $usb > 0 && scalar(@usb); --$usb) {
            $price += shift @usb;
            ++$pcNr;
    }

    for ( ; $ps2 > 0 && scalar(@ps2); --$ps2) {
            $price += shift @ps2;
            ++$pcNr;
    }

    my @c = sort( { $a <=> $b } @usb, @ps2 );

	for ( ;scalar( @c ) && $mix > 0; --$mix) {
		$price += shift @c;
		++$pcNr;
	}

    say $pcNr." ".$price;

use v5.20;
use warnings;

sub compare {
	return $a <=> $b;
}

my ($a,$b,$c) = split(' ',<>);
my $m = int <>;

my (@A,@B);

for (1..$m) {
	my ($val,$type) = split(' ',<>);
	if ($type eq "USB") {
		push @A,$val;
    }
	else {
		push @B,$val;
	}
}

@A = sort compare @A;
@B = sort compare @B;

my $cost = 0;
my $comp = 0;

while ($a and @A) {
	$comp += 1;
	$cost += shift @A;
	$a -= 1;
}

while ($b and @B) {
	$comp += 1;
	$cost += shift @B;
	$b -= 1;
}

my @C = sort compare (@A,@B);

while ($c and @C) {
	$comp += 1;
	$cost += shift @B;
	$c -= 1;
}

say "$comp $cost";

use v5.20;

my $input = <>;
my ($usb_comp, $ps2_comp, $both_comp) = split(/ /, $input);

my $m = <>;
my @usb, my @ps2;
for (my $i = 0; $i < $m; $i = $i + 1) {
	$input = <>;
	chomp $input;
	my ($number, $type) = split(/ /, $input);

	if ($type eq "USB") {
		push(@usb, $number);
	} else {
		say $type;
		push(@ps2, $number);
	}
}

my $price = 0;
my $matched = 0;
# Match as many only-usb computers to usb mouses.
@usb = sort {$a <=> $b} @usb;
my $i = 0;
while ($i < scalar @usb and $usb_comp > 0) {
	say 1;
	$price = $price + $usb[$i];
	$i++;
	$matched++;
	$usb_comp--;
}

# Match as many only-ps2 computers to usb mouses.
@ps2 = sort {$a <=> $b} @ps2;
my $j = 0;
while ($j < scalar @ps2 and $ps2_comp > 0) {
	say 2;
	$price = $price + $ps2[$j];
	$j++;
	$matched++;
	$ps2_comp--;
}

# Match the computers having both ports to cheapest mouses.
while (($j < scalar @ps2 or $i < scalar @usb) and $both_comp > 0) {
	say 3;
	if ($i >= scalar @usb or ($j < scalar @ps2 and $ps2[$j] < $usb[$i])) {
		$price = $price + $ps2[$j];
		$j++;
	} else {
		$price = $price + $usb[$i];
		$i++;
	}
	$matched++;
	$both_comp--;
}

print "$matched $price"

#use v5.24;
use warnings;
my @usb,@ps2,@merged,$nrcump=0,$costtot=0;

my $line=<stdin>;
chomp($line);
my ($usbonly,$ps2only,$both)=split(/ /,$line);
$line=<stdin>;
chomp($line);
my ($n)=split(/ /,$line);
for (my $i=1;$i<=$n;$i++){
	$line=<stdin>;
	chomp($line);
	my ($cost,$tip)=split(/ /,$line);
	if ($tip eq "USB") {push @usb, $cost;}
	else {push @ps2, $cost;}
}
@usb=sort {$a<=>$b} @usb;
@ps2=sort {$a<=>$b} @ps2;
while ($usbonly>0 && scalar @usb>0){
	$usbonly--;
	$nrcump++;
	$costtot=$costtot+shift @usb;
}
while ($ps2only>0 && scalar @ps2>0){
	$ps2only--;
	$nrcump++;
	$costtot=$costtot+shift @ps2;
}
foreach my $var (@usb) {push @merged, $var;}
foreach my $var (@ps2) {push @merged, $var;}
while ($both>0 && scalar @merged>0){
	$both--;
	$nrcump++;
	$costtot=$costtot+shift @merged;
}
print $nrcump.' '.$costtot;
<stdin>;
exit(0);

use v5.20.1;
use warnings;

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

my($a, $b, $c) = split(' ', $line);

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

my $m = $line;

my @usb = ();
my @ps = ();
my $model = "";
my $price = 0;

for(my $i = 0; $i < $m; $i++){

	$line = <STDIN>;
	($price, $model) = split(' ', $line);
	if($model eq "USB"){

		push @usb, $price;

	}elsif($model eq "PS/2"){

		push @ps, $price;

	}

}

@usb = sort @usb;
@ps = sort @ps;

my $ui = 0;
my $pi = 0;
my $cost = 0;
my $mice = 0;

while($ui < @usb && $a > 0){

	$cost += $usb[$ui];
	$ui++;
	$mice++;
	$a--;

}

while($pi < @ps && $b > 0){

	$cost += $ps[$pi];
	$pi++;
	$b--;
	$mice++;

}

while($ui < @usb && $pi < @ps && $c > 0){

	if($usb[$ui] < $ps[$pi]){

		$cost += $usb[$ui];
		$c--;
		$ui++;
		$mice++;

	}else{

		$cost += $ps[$pi];
		$pi++;
		$c--;
		$mice++;

	}

}

while($ui < @usb && $c > 0){

	$cost += $usb[$ui];
	$ui++;
	$c--;
	$mice++;

}

while($pi < @ps && $c > 0){

	$cost += $ps[$pi];
	$pi++;
	$c--;
	$mice++;

}

print $mice, " ", $cost, "\n";

sub input { $_ = <>; chomp; wantarray? split: $_ }

sub less_first { sort { $a <=> $b } @_ }

sub buy {
	my ($c, $aref) = @_;
	while ($c--) {
		last unless @$aref;
		$R++, $V += shift @$aref;
	}
}

@c = input; $m = input;
for (1..$m) {
	($v, $t) = input;
	if ($t eq "USB") {
		push @v0, $v;
	} else {
		push @v1, $v;
	}
}

@v0 = less_first @v0;
@v1 = less_first @v1;

buy $c[0], \@v0;
buy $c[1], \@v1;
@v2 = less_first @v0, @v1;
buy $c[2], \@v2;

print $R, " ", $V;

use utf8;
use feature "say";

my $line = <>;
chomp($line);
my ($usb, $ps2, $mix) = split(' ', $line);
my $pcNr = <>;
chomp($pcNr);
my (@usb, @ps2);
while ($pcNr > 0) {
  $line = <>;
  chomp($line);
  my($price, $type) = split(' ', $line);
  if ($type eq "USB") {
    push ( @usb, $price );
  } else {
    push ( @ps2, $price);
  }
  --$pcNr;
}

@usb = sort ( { $a <=> $b } @usb );
@ps2 = sort ( { $a <=> $b } @ps2 );
my $price = 0;
my ( $iU, $iP );

for ( $iU = 0; $iU < scalar ( @usb ) && $usb > 0; ++$iU, --$usb ) {
   $price += $usb[$iU];
   ++$pcNr;
}
for ( $iP = 0; $iP < scalar ( @ps2 ) && $ps2 > 0; ++$iP, --$ps2 ) {
   $price += $ps2[$iP];
   ++$pcNr;
}

for ( ; ( $iU < scalar( @usb ) || $iP < scalar ( @ps2 ) ) && $mix > 0; --$mix ) {
   if ( ({ $usb[$iU] <=> $ps2[$iP] } < 1) || $iP >= scalar ( @ps2 ) ) {
      $price += $usb[$iU];
      ++$pcNr;
      ++$iU;
   } else {
      $price += $ps2[$iP];
      ++$pcNr;
      ++$iP;
   }
}

say $pcNr." ".$price;

use warnings;
use utf8;
use feature "say";

my $line = <>;
chomp($line);
my ($usb, $ps2, $mix) = split(' ', $line);
my $pcNr = <>;
chomp($pcNr);
my (@usb, @ps2);
while ($pcNr > 0) {
  $line = <>;
  chomp($line);
  my($price, $type) = split(' ', $line);
  if ($type eq "USB") {
    push ( @usb, $price );
  } else {
    push ( @ps2, $price);
  }
  --$pcNr;
}
@usb = sort ( { $a <=> $b } @usb );
@ps2 = sort ( { $a <=> $b } @ps2 );

my $price = 0;
my ( $iU, $iP );
for ( $iU = 0; $iU < scalar ( @usb ) && $usb > 0; ++$iU, --$usb ) {
   $price += $usb[$iU];
   say $usb[$iU];
   ++$pcNr;
}
for ( $iP = 0; $iP < scalar ( @ps2 ) && $ps2 > 0; ++$iP, --$ps2 ) {
   $price += $ps2[$iP];
   say $ps2[$iP];
   ++$pcNr;
}
for ( ; ( $iU < scalar( @usb ) || $iP < scalar ( @ps2 ) ) && $mix > 0; --$mix ) {
   if ( $usb[$iU] <= $ps2[$iP]) {
      $price += $usb[$iU];
      ++$pcNr;
      ++$iU;
   } else {
      $price += $ps2[$iP];
      ++$pcNr;
      ++$iP;
   }
}

say $pcNr." ".$price;


Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i > 1 the respective term satisfies the condition bi = bi - 1·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≤ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.

The first line of input contains four integers b1, q, l, m (-109 ≤ b1, q ≤ 109, 1 ≤ l ≤ 109, 1 ≤ m ≤ 105) — the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≤ ai ≤ 109) — numbers that will never be written on the board.

Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.

NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $b, $q, $l, $m ) = split;
	my %h = map { $_ => 1 } split ' ', <>;

	my @ans;

	my $maxl = abs $l;
	my $minl = - $maxl;

	my $c = 0;

	while( $minl <= $b and $b <= $maxl ){
		$h{ $b } or push @ans, $b;
		$b *= $q;
		$c ++ > 2e4 and last;
		}

	print @ans >= 1e4 ? "inf" : 0 + @ans;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $b, $q, $l, $m ) = split;
	my %h = map { $_ => 1 } split ' ', <>;

	my @ans;

	my $maxl = abs $l;
	my $minl = - $maxl;

	my $inf;

	if( $b == 0 ){
		$inf = $h{ 0 } ? 0 : "inf";
		}
	elsif( $q == 0 ){
		$inf = $h{ 0 } ? 0 : "inf";
		$inf or $inf += ($minl <= $b and $b <= $maxl and not $h{ $b });
		}

	if( not defined $inf and $minl <= $b and $b <= $maxl and $q =~ /^-?1$/ ){
		if( $q == 1 ){ $inf = $h{ $b } ? 0 : "inf" }
		elsif( $q == -1 ){ $inf = ($h{ $b } * $h{ 0 - $b }) ? 0 : "inf" }
		}
	elsif( not defined $inf and not( $minl <= $b and $b <= $maxl) and $q =~ /^-?1$/ ){
		$inf = 0;
		}

	while( not defined $inf and $minl <= $b and $b <= $maxl ){
		$h{ $b } or push @ans, $b;
		$b *= $q;
		}

	print defined $inf ? $inf : 0 + @ans;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $b, $q, $l, $m ) = split;
	my %h = map { $_ => 1 } split ' ', <>;

	my @ans;

	my $maxl = abs $l;
	my $minl = - $maxl;

	my $c = 0;

	while( $minl <= $b and $b <= $maxl ){
		$h{ $b } or push @ans, $b;
		$b *= $q;
		$c ++ > 1e4 and last;
		}

	print @ans >= 1e4 ? "inf" : 0 + @ans;
	}

#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

while(<>){
	my( $b, $q, $l, $m ) = split;
	my %h = map { $_ => 1 } split ' ', <>;

	my @ans;

	my $maxl = abs $l;
	my $minl = - $maxl;

	my $inf;
	$b == 0 || $q == 0 and $inf = "inf";

	if( not defined $inf and $minl <= $b and $b <= $maxl and $q == 1 ){
		$inf = $h{ $b } ? 0 : "inf";
		}
	elsif( not defined $inf and not( $minl <= $b and $b <= $maxl) and $q == 1 ){
		$inf = 0;
		}

	while( not defined $inf and $minl <= $b and $b <= $maxl ){
		$h{ $b } or push @ans, $b;
		$b *= $q;
		}

	print defined $inf ? $inf : 0 + @ans;
	}


Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $$$a$$$ sticks and $$$b$$$ diamonds?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^9$$$) — the number of sticks and the number of diamonds, respectively.

For each test case print one integer — the maximum number of emeralds Polycarp can earn.

NoteIn the first test case Polycarp can earn two emeralds as follows: craft one sword and one shovel.In the second test case Polycarp does not have any diamonds, so he cannot craft anything.


Recently Petya walked in the forest and found a magic stick.Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:   If the chosen number $$$a$$$ is even, then the spell will turn it into $$$\frac{3a}{2}$$$;  If the chosen number $$$a$$$ is greater than one, then the spell will turn it into $$$a-1$$$. Note that if the number is even and greater than one, then Petya can choose which spell to apply.Petya now has only one number $$$x$$$. He wants to know if his favorite number $$$y$$$ can be obtained from $$$x$$$ using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave $$$x$$$ as it is.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^9$$$) — the current number and the number that Petya wants to get.

For the $$$i$$$-th test case print the answer on it — YES if Petya can get the number $$$y$$$ from the number $$$x$$$ using known spells, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

#!/usr/bin/env perl

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

# essential
my @tokens = ();

my $t = read_token();

for ( 1..$t ) {
    my $line = read_line();
    my ($x, $y) = split q{ }, $line;
    my $answer;
    if ( $x == 1 ) {
        if ( $y == 1 ) {
            $answer = "yes";
        }
        else {
            $answer = "no";
        }
    }
    elsif ( $x <= 3 && $y > 3 ) {
        $answer = "no";
    }
    else {
        $answer = "yes";
    }
    say $answer;
}

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

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

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

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

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

#!/usr/bin/env perl

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

# essential
my @tokens = ();

my $t = read_token();

for ( 1..$t ) {
    my $line = read_line();
    my ($x, $y) = split q{ }, $line;
    my $answer;
    if ( $x == 1 ) {
        $answer = "no";
    }
    elsif ( $x == 2 && $y > 3 ) {
        $answer = "no";
    }
    else {
        $answer = "yes";
    }
    say $answer;
}

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

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

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

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

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


InteractionThis is an interactive problem. You need to read participants' queries from standard input and print your responses to standard output. You don't know the number of queries upfront, so you'll need to process them as you get them; you'll know you're done once you reach the end of the file.In each query, you will be asked the question, written in one line. You have to answer it correctly, patiently and without any display of emotions. Your response is case-insensitive.Please make sure to use the stream flushing operation after each response in order not to leave part of your output in some buffer.ExampleInput
Is it rated?
Is it rated?
Is it rated?
Output
NO
NO
NO

#!/usr/bin/perl

$|=1;
while(<STDIN>){
  print "NO\n";
}


In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.

The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.

In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.

NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.

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

chomp (my %arr = map {$_ => 1} split /\s+/, <STDIN>);

my @ans;
for (my $i = 1; $i <= 10 ** 9; $i++) {
  next if exists $arr{$i};
  if ($m >= $i) {
    $m -= $i;
    push @ans, $i;
  } else {
    last;
  }
}

printf "%s\n", scalar @ans;
printf "@ans\n";

my @n = split(/ /, <STDIN>);
my $m = $n[1];
my @A = sort {$a <=> $b} split(/ /, <STDIN>);
my $j = 0, $t = 1;
my @ans;
while(1) {
    while($A[$j] == $t) {
        $j++;
        $t++;
    }
    if($m >= $t) {
        $m -= $t;
        push @ans, $t;
        $t++;
    } else {
        print scalar @ans."\n";
        foreach $x (@ans) { print "$x "; }
        exit 0;
    }
}