The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column).    The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.

Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.

4
1 1
L
1 2
L
3 3
RRDLUU
4 3
LUURRDDLLLUU

gets.to_i.times do
  n,m=gets.split.map(&:to_i)
  s=gets.chomp.chars
  l,r,u,d=0,0,0,0
  lr,ud=1,1
  i,j=0,0
  s.each do |t|
    if t=="L"
      j-=1
      if j<l
        if lr==m
          break
        end
        l-=1
        lr+=1
      end
    elsif t=="U"
      i-=1
      if i<u
        if ud==n
          break
        end
        u-=1
        ud+=1
      end
    elsif t=="R"
      j+=1
      if j>r
        if lr==m
          break
        end
        r+=1
        lr+=1
      end
    else
      i+=1
      if i>d
        if ud==n
          break
        end
        d+=1
        ud+=1
      end
    end
  end
  puts [-u+1,-l+1].join(" ")
end

gets.to_i.times do
  n,m=gets.split.map(&:to_i)
  s=gets.chomp.chars
  l,r,u,d=0,0,0,0
  lr,ud=1,1
  i,j=0,0
  s.each do |t|
    if t=="L"
      j-=1
      if j<l
        if lr==m
          break
        end
        l-=1
        lr+=1
      end
    elsif t=="U"
      i-=1
      if i<u
        if ud==m
          break
        end
        u-=1
        ud+=1
      end
    elsif t=="R"
      j+=1
      if j>r
        if lr==m
          break
        end
        r+=1
        lr+=1
      end
    else
      i+=1
      if i>d
        if ud==m
          break
        end
        d+=1
        ud+=1
      end
    end
  end
  puts [-u+1,-l+1].join(" ")
end


You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display. The second line contains n digits — the initial state of the display.

Print a single line containing n digits — the desired state of the display containing the smallest possible number.

n = gets.to_i
arr = gets.chomp.split('').map(&:to_i)

min = arr.join.to_i
min_arr = arr

(1..n).each do |i|
  temp_arr = arr.rotate i
  #p temp_arr
  diff = 10 - temp_arr.first
  temp_arr.map! {|x| (x+diff)%10}
  value = temp_arr.join.to_i
  if value < min
    min = value
    min_arr = temp_arr
  end
end
puts min_arr.join

n = STDIN.readline.to_i
x = STDIN.readline.strip
digits = x.split('')

rot = {}
10.times do |digit|
  rot[digit.to_s] = ((digit+1) % 10).to_s
end

numbers = []
10.times do
  n.times {|i| digits[i] = rot[digits[i]] }
  n.times do
    digits.rotate!
    numbers.push(digits.join)
  end
end
puts numbers.sort[0]

gets
a = gets.rstrip.chars.map(&:to_i)
puts (0..a.size-1).map{|i| (a + a)[i, a.size]}
    .map{|x| x.map{|y| (y + 10 - x[0]) % 10}}
    .map{|x| x.join('')}.min

pa=Array.new
pb=Array.new
n=gets.to_i
str=gets.to_s

std="9"
for i in 0..9
  min=10
  for j in 0..n-1
    pa[j] = (str[j].to_i + i) % 10
    if min > pa[j]
      min=pa[j]
      r=0
      pb[r]=j
    elsif min==pa[j]
      r+=1
      pb[r]=j
    end
  end

  stt="9"
  for t in 0..r
     stk = pa[pb[t],n-pb[t]].join + pa[0,pb[t]].join
#    for j in pb[t]..pb[t]+n-1
#      stk << pa[j%n].to_s
#    end
#puts stk
    if stt > stk
      stt=stk.clone
    end
  end
  if std > stt
    std=stt.clone
  end
end

puts std

# $f = File.open('input.txt', 'r')
$f = STDIN

def inc(s)
  s.length.times{ |i| s[i] = ((s[i].to_i + 1) % 10).to_s }
  s
end

def get_min(s)
  res = s.clone
  s.length.times do
    tmp = s.chars.rotate(-1).join
    res = [res, tmp].min
    s = tmp
  end
  res
end

while str = $f.gets
  n = str.chomp.to_i
  s = $f.gets.chomp
  res = s.clone
  10.times do
    res = [res, get_min(s)].min.clone
    inc(s)
  end
  puts res
end

def transform arr
  diff = 10 - arr.first
  arr = arr.map {|a| (a + diff)%10}
  arr
end

n = gets.to_i
arr = gets.chomp.split('').map(&:to_i)
min = Float::INFINITY
new_min_arr = arr
new_min = new_min_arr.join.to_i
while new_min < min
  min_arr = new_min_arr
  min = new_min
  min_index,max_index = min_arr.each_with_index.minmax.collect{|x| x[1]}
  max_rot_arr = transform min_arr.rotate(max_index)
  min_rot_arr = min_arr.rotate(min_index)
  max_rot_arr_val = max_rot_arr.join.to_i
  min_rot_arr_val = min_rot_arr.join.to_i
  # p max_rot_arr
  # p min_rot_arr
  if max_rot_arr_val < min_rot_arr_val
    new_min_arr = max_rot_arr
    new_min = max_rot_arr_val
  else
    new_min_arr = min_rot_arr
    new_min_arr = min_rot_arr_val
  end
  #p new_min_arr
end

puts min_arr.join

def transform arr
  diff = 10 - arr.first
  arr = arr.map {|a| (a + diff)%10}
  arr
end

n = gets.to_i
arr = gets.chomp.split('').map(&:to_i)
min = Float::INFINITY
new_min_arr = arr
new_min = new_min_arr.join.to_i
while new_min < min
  min_arr = new_min_arr
  min = new_min
  min_index,max_index = min_arr.each_with_index.minmax.collect{|x| x[1]}
  max_rot_arr = transform min_arr.rotate(max_index)
  min_rot_arr = min_arr.rotate(min_index)
  max_rot_arr_val = max_rot_arr.join.to_i
  min_rot_arr_val = min_rot_arr.join.to_i
  # p max_rot_arr
  # p min_rot_arr
  if max_rot_arr_val < min_rot_arr_val
    new_min_arr = max_rot_arr
    new_min = max_rot_arr_val
  else
    new_min_arr = min_rot_arr
    new_min = min_rot_arr_val
  end
  #p new_min_arr
end

puts min_arr.join

def transform arr
  diff = 10 - arr.first
  arr = arr.map {|a| (a + diff)%10}
  arr
end

n = gets.to_i
arr = gets.chomp.split('').map(&:to_i)
min = Float::INFINITY
new_min_arr = arr
new_min = new_min_arr.join.to_i
while new_min < min
  min_arr = new_min_arr
  min = new_min
  max_index,min_index = min_arr.each_with_index.minmax.collect{|x| x[1]}
  max_rot_arr = transform min_arr.rotate(max_index)
  min_rot_arr = min_arr.rotate(min_index)
  max_rot_arr_val = max_rot_arr.join.to_i
  min_rot_arr_val = min_rot_arr.join.to_i
  if max_rot_arr_val < min_rot_arr_val
    new_min_arr = max_rot_arr
    new_min = max_rot_arr_val
  else
    new_min_arr = min_rot_arr
    new_min_arr = min_rot_arr_val
  end
end

puts min_arr.join

def transform arr
  diff = 10 - arr.first
  arr = arr.map {|a| (a + diff)%10}
  arr
end

def rotate arr,mode
  final_value = arr.join.to_i
  final_arr = arr
  (1..arr.size).each do |i|
    temp_arr = arr.rotate(i)
    if mode == "max"
      if final_value < temp_arr.join.to_i
        final_value = temp_arr.join.to_i
        final_arr = temp_arr
      end
    else
      if final_value > temp_arr.join.to_i
        final_value = temp_arr.join.to_i
        final_arr = temp_arr
      end
    end
  end
  final_arr
end

n = gets.to_i
arr = gets.chomp.split('').map(&:to_i)
min = Float::INFINITY
new_min_arr = arr
new_min = new_min_arr.join.to_i
while new_min < min
  min_arr = new_min_arr
  min = new_min
  max_rot_arr = transform(rotate min_arr,"max")
  min_rot_arr = rotate min_arr,"min"
  max_rot_arr_val = max_rot_arr.join.to_i
  min_rot_arr_val = min_rot_arr.join.to_i
  # p max_rot_arr
  # p min_rot_arr
  if max_rot_arr_val < min_rot_arr_val
    new_min_arr = max_rot_arr
    new_min = max_rot_arr_val
  else
    new_min_arr = min_rot_arr
    new_min = min_rot_arr_val
  end
  #p new_min_arr
end

puts min_arr.join

pa=Array.new
std=String.new
n=gets.to_i
str=gets.to_s

std=str.clone
for i in 0..9
  stt=String.new
  min=0
  for j in 0..n-1
    pa[j]=(str[j].to_i+i)%10
    if pa[min]>pa[j]
      min=j
    end
  end
#  p pa
  for j in min..min+n-1
    stt << pa[j%n].to_s
  end
#  p stt
  if std > stt
    std=stt.clone
  end
end

puts std

n=gets.to_i
str=gets.to_s

min=0
for i in 0..n-1
  if str[min]>str[i]
    min=i
  end
end
k=str[min].to_i

for i in min..min+n-1
  print str[i%n].to_i-k
end
puts


You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $$$n$$$ seconds and at the $$$i$$$-th second the color $$$s_i$$$ is on.That way, the order of the colors is described by a string. For example, if $$$s=$$$"rggry", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on.More formally, you are given a string $$$s_1, s_2, \ldots, s_n$$$ of length $$$n$$$. At the first second the color $$$s_1$$$ is on, at the second — $$$s_2$$$, ..., at the $$$n$$$-th second the color $$$s_n$$$ is on, at the $$$n + 1$$$-st second the color $$$s_1$$$ is on and so on.You need to cross the road and that can only be done when the green color is on. You know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road.You can assume that you cross the road immediately. For example, with $$$s=$$$"rggry" and the current color r there are two options: either the green color will be on after $$$1$$$ second, or after $$$3$$$. That way, the answer is equal to $$$3$$$ — that is the number of seconds that we are guaranteed to cross the road, if the current color is r.

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. Then the description of the test cases follows. The first line of each test case contains an integer $$$n$$$ and a symbol $$$c$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$c$$$ is one of allowed traffic light colors r, y or g)— the length of the string $$$s$$$ and the current color of the traffic light.  The second line of each test case contains a string $$$s$$$ of the length $$$n$$$, consisting of the letters r, y and g. It is guaranteed that the symbol g is in the string $$$s$$$ and the symbol $$$c$$$ is in the string $$$s$$$.  It is guaranteed, that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case output the minimal number of second in which you are guaranteed to cross the road.

6

5 r

rggry

1 g

g

3 r

rrg

5 y

yrrgy

7 r

rgrgyrg

9 y

rrrgyyygy

NoteThe first test case is explained in the statement.In the second test case the green color is on so you can cross the road immediately. In the third test case, if the red color was on at the second second, then we would wait for the green color for one second, and if the red light was on at the first second, then we would wait for the green light for two seconds.In the fourth test case the longest we would wait for the green color is if we wait for it starting from the fifth second.

# wrap around the lights after the last green light
# Eg: rrrgyyygy becomes: yrrrgyyyg
def wrap_lights(light_string)
  array = light_string.chars
  last_index = array.rindex('g') + 1
  array.rotate!(last_index)
  array.join
end

# create sequences of lights other than green Eg: yrrrgyyyg becomes: [yrrr, yyy]
def light_sequences(light_string)
  light_string.split('g')
              .reject(&:empty?)
end

# find best time for current light in a sequence
# Eg: for light yellow in sequence yrrr it returns 4
def best_time(sequence, current_light)
  return nil if sequence.index(current_light).nil?

  sequence.length - sequence.index(current_light)
end

# finds the best time in an array of sequences
# Eg the sequences [yrrr, yyy] returns 4
# since yrrr has time 4 and yyy has time 3
def best_in_sequences(sequence_arr, current_light)
  times = sequence_arr.map { |sequence| best_time(sequence, current_light) }

  times.compact.max
end

# combines the above four methods
def best_from_string(light_string, current_light)
  return 0 if current_light == 'g'

  wrapped = wrap_lights(light_string)
  sequences = light_sequences(wrapped)
  best_in_sequences(sequences, current_light)
end

##### code for tests:

number_of_cases = gets.chomp.to_i

number_of_cases.times do
  current_light = gets.chomp.split[-1]
  light_string = gets.chomp
  puts best_from_string(light_string, current_light)
end

ts = gets.to_i
ts.times do
  c = gets.split[1]
  s = gets.chomp
  ans = (s + s).split("g").map{ |t| t.size - (t.index(c) || 10**9) }.max
  puts c == "g" ? 0 : ans
end


This problem is interactive.We decided to play a game with you and guess the number $$$x$$$ ($$$1 \le x < n$$$), where you know the number $$$n$$$.You can make queries like this: + c: this command assigns $$$x = x + c$$$ ($$$1 \le c < n$$$) and then returns you the value $$$\lfloor\frac{x}{n}\rfloor$$$ ($$$x$$$ divide by $$$n$$$ and round down).You win if you guess the current number with no more than $$$10$$$ queries.

NoteIn the first sample initially $$$x = 2$$$. After the first query $$$x = 3$$$, $$$\lfloor\frac{x}{n}\rfloor = 1$$$.In the second sample also initially $$$x = 2$$$. After the first query $$$x = 3$$$, $$$\lfloor\frac{x}{n}\rfloor = 0$$$. After the second query $$$x = 4$$$, $$$\lfloor\frac{x}{n}\rfloor = 0$$$. After the third query $$$x=5$$$, $$$\lfloor\frac{x}{n}\rfloor = 1$$$.

n = gets.to_i
l = 1; r = n
cur_div = 0

while l + 1 < r
  m = (l + r) / 2

  puts "+ #{n - m}"
  $stdout.flush

  new_div = gets.to_i
  if new_div > cur_div
    l = m
  else
    r = m
  end

  cur_div = new_div
  l = (l + n - m) % n
  r = (r + n - m) % n
  r = n if r == 0
end

puts "! #{cur_div * n + l}"


There are $$$n$$$ models in the shop numbered from $$$1$$$ to $$$n$$$, with sizes $$$s_1, s_2, \ldots, s_n$$$.Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices $$$i_j$$$ and $$$i_{j+1}$$$ (note that $$$i_j < i_{j+1}$$$, because Orac arranged them properly), $$$i_{j+1}$$$ is divisible by $$$i_j$$$ and $$$s_{i_j} < s_{i_{j+1}}$$$.For example, for $$$6$$$ models with sizes $$$\{3, 6, 7, 7, 7, 7\}$$$, he can buy models with indices $$$1$$$, $$$2$$$, and $$$6$$$, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful.Orac wants to know the maximum number of models that he can buy, and he may ask you these queries many times.

The first line contains one integer $$$t\ (1 \le t\le 100)$$$: the number of queries. Each query contains two lines. The first line contains one integer $$$n\ (1\le n\le 100\,000)$$$: the number of models in the shop, and the second line contains $$$n$$$ integers $$$s_1,\dots,s_n\ (1\le s_i\le 10^9)$$$: the sizes of models. It is guaranteed that the total sum of $$$n$$$ is at most $$$100\,000$$$.

Print $$$t$$$ lines, the $$$i$$$-th of them should contain the maximum number of models that Orac can buy for the $$$i$$$-th query.

NoteIn the first query, for example, Orac can buy models with indices $$$2$$$ and $$$4$$$, the arrangement will be beautiful because $$$4$$$ is divisible by $$$2$$$ and $$$6$$$ is more than $$$3$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than two models. In the second query, Orac can buy models with indices $$$1$$$, $$$3$$$, and $$$6$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than three models. In the third query, there are no beautiful arrangements with more than one model.

t = gets.chomp.to_i

t.times do
  t2 = gets.chomp.to_i
  arr = gets.chomp.split(' ').collect(&:to_i)
  dp = Array.new(t2, 1)
  ans = 0
  for i in 1..t2
    j = i + i
    while true
      break if j > t2
      dp[j-1] = [dp[j-1], dp[i-1] + 1].max if arr[j-1] > arr[i-1]
      j += i
    end
  end
  puts dp.max
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']
require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
nt = []
dt = []
n.times do
  nt <<inp[0]
  dt <<inp
end
n.times do |i|
  mem = na(nt[i],1)
  nt[i].times do |j|
    ind = -1
    pl = j+1
    li = nt[i]-pl
    while ind < li
      ind += pl
      mem[ind] = big(mem[ind],mem[j] + 1) if(dt[i][j] < dt[i][ind])
    end
    #p 878778
  end
  #p 787879
  p mem.max
end

t = gets.chomp.to_i
while t > 0
  n = gets.chomp.to_i
  arr = [1].concat(gets.chomp.split(' ').map { |x| x.to_i })

  result = Array.new(n+1, 1)
  i = 1
  while i <= n
    j = 2
    while i*j <= n
      result[i*j] = result[i] + 1 if arr[i*j] > arr[i] && result[i*j] <= result[i]
      j += 1
    end
    i += 1
  end

  puts result.max
  t -= 1
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']
require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
nt = []
dt = []
n.times do
  nt <<inp[0]
  dt <<inp
end
n.times do |i|
  mem = na(nt[i])
  nt[i].times do |j|
    ind = 0
    pl = j+1
    li = nt[i]-pl
    while ind < li
      ind += pl
      mem[ind] = mem[j] + 1 if(dt[i][j] < dt[i][ind])
    end
  end
  p [mem.max,1].max
end


Gildong is playing a video game called Block Adventure. In Block Adventure, there are $$$n$$$ columns of blocks in a row, and the columns are numbered from $$$1$$$ to $$$n$$$. All blocks have equal heights. The height of the $$$i$$$-th column is represented as $$$h_i$$$, which is the number of blocks stacked in the $$$i$$$-th column.Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the $$$1$$$-st column. The goal of the game is to move the character to the top of the $$$n$$$-th column.The character also has a bag that can hold infinitely many blocks. When the character is on the top of the $$$i$$$-th column, Gildong can take one of the following three actions as many times as he wants:   if there is at least one block on the column, remove one block from the top of the $$$i$$$-th column and put it in the bag;  if there is at least one block in the bag, take one block out of the bag and place it on the top of the $$$i$$$-th column;  if $$$i < n$$$ and $$$|h_i - h_{i+1}| \le k$$$, move the character to the top of the $$$i+1$$$-st column. $$$k$$$ is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column. In actions of the first two types the character remains in the $$$i$$$-th column, and the value $$$h_i$$$ changes.The character initially has $$$m$$$ blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le 10^6$$$, $$$0 \le k \le 10^6$$$) — the number of columns in the game, the number of blocks in the character's bag at the beginning, and the non-negative integer $$$k$$$ described in the statement. The second line of each test case contains $$$n$$$ integers. The $$$i$$$-th integer is $$$h_i$$$ ($$$0 \le h_i \le 10^6$$$), the initial height of the $$$i$$$-th column.

For each test case, print "YES" if it is possible to win the game. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first case, Gildong can take one block from the $$$1$$$-st column, move to the $$$2$$$-nd column, put the block on the $$$2$$$-nd column, then move to the $$$3$$$-rd column.In the second case, Gildong has to put the block in his bag on the $$$1$$$-st column to get to the $$$2$$$-nd column. But it is impossible to get to the $$$3$$$-rd column because $$$|h_2 - h_3| = 3 > k$$$ and there is no way to decrease the gap.In the fifth case, the character is already on the $$$n$$$-th column from the start so the game is won instantly.

T = gets.to_i
T.times do
	n, m, k = gets.split.map(&:to_i)
	arr = gets.split.map(&:to_i)
	if n == 1
		puts "YES"
		next
	end
	succ = true
	while arr.size > 1
		cur = arr.shift
		if arr[0] >= k
			floor = arr[0] - k
		else
			floor = 0
		end
		m += cur - floor
		if m < 0
			succ = false
			break
		end
	end
	if succ
		puts "YES"
	else
		puts "NO"
	end
end

#!/usr/bin/env ruby

test_no = Integer(gets)

tests = Array.new (test_no)
columns = Array.new (test_no)

test_no.times.each do |num|
	tests[num] = gets.chomp.split(" ").map(&:to_i)
	columns[num] = gets.chomp.split(" ").map(&:to_i)
end

tests.map!.with_index do |test, index|

	columns[index].map!.with_index do |col, colindex|

 		if (test[0] == colindex + 1)
			puts "YES"
			break
		end

		if col >= 1 && ((col - 1 - columns[index][colindex+1]).abs <= test[2] || (col > columns[index][colindex+1]))
			blocks_to_bag = [col, (col - columns[index][colindex+1] + test[2]).abs].min
			test[1] = test[1] + blocks_to_bag
			col = col - blocks_to_bag
		elsif test[1] >= 1 && col < columns[index][colindex+1] && (col - columns[index][colindex+1]).abs > test[2]
			blocks_from_bag = [columns[index][colindex+1] - col - test[2], test[1]].min
			columns[index][colindex] = col = col + blocks_from_bag

			tests[index][1] = test[1] = test[1] - blocks_from_bag
		end

		if (col - columns[index][colindex+1]).abs <= test[2]
			next
		else
			puts "NO"
			break
		end

	end

end

T = gets.to_i
T.times do
	n, m, k = gets.split.map(&:to_i)
	arr = gets.split.map(&:to_i)
	if n == 1
		puts "YES"
		next
	end
	succ = true
	while arr.size > 1
		cur = arr.shift
		if arr[0] - k > cur + m
			succ = false
		end
		floor = arr[0] - k
		if cur > floor
			m += cur - floor
		elsif cur < floor
			m -= floor - cur
		end
		if m < 0
			succ = false
		end
	end
	if succ
		puts "YES"
	else
		puts "NO"
	end
end

#!/usr/bin/env ruby

test_no = Integer(gets)

tests = Array.new (test_no)
columns = Array.new (test_no)

test_no.times.each do |num|
	tests[num] = gets.chomp.split(" ").map(&:to_i)
	columns[num] = gets.chomp.split(" ").map(&:to_i)
end

tests.map!.with_index do |test, index|

	columns[index].map!.with_index do |col, colindex|

 		if (test[0] == colindex + 1)
			puts "YES"
			break
		end

		if col >= 1 && ((col - 1 - columns[index][colindex+1]).abs <= test[2] || (col > columns[index][colindex+1]))
			blocks_to_bag = col - (test[2] - columns[index][colindex+1]).abs
			test[1] = test[1] + blocks_to_bag
			col = col - blocks_to_bag
		elsif test[1] >= 1 && col < columns[index][colindex+1] && (col - columns[index][colindex+1]).abs > test[2]
			blocks_from_bag = [columns[index][colindex+1] - col - test[2], test[1]].min
			columns[index][colindex] = col = col + blocks_from_bag

			tests[index][1] = test[1] = test[1] - blocks_from_bag
		end

		if (col - columns[index][colindex+1]).abs <= test[2]
			next
		else
			puts "NO"
			break
		end

	end

end


After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $$$n$$$. Let's call them $$$a$$$ and $$$b$$$.Note that a permutation of $$$n$$$ elements is a sequence of numbers $$$a_1, a_2, \ldots, a_n$$$, in which every number from $$$1$$$ to $$$n$$$ appears exactly once. The message can be decoded by an arrangement of sequence $$$a$$$ and $$$b$$$, such that the number of matching pairs of elements between them is maximum. A pair of elements $$$a_i$$$ and $$$b_j$$$ is said to match if:   $$$i = j$$$, that is, they are at the same index.  $$$a_i = b_j$$$ His two disciples are allowed to perform the following operation any number of times:   choose a number $$$k$$$ and cyclically shift one of the permutations to the left or right $$$k$$$ times. A single cyclic shift to the left on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$$$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$$$ simultaneously.Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.

The first line of the input contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ — the size of the arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le n)$$$ — the elements of the first permutation. The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le n)$$$ — the elements of the second permutation.

Print the maximum number of matching pairs of elements after performing the above operations some (possibly zero) times.

NoteFor the first case: $$$b$$$ can be shifted to the right by $$$k = 1$$$. The resulting permutations will be $$$\{1, 2, 3, 4, 5\}$$$ and $$$\{1, 2, 3, 4, 5\}$$$.For the second case: The operation is not required. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$1$$$.For the third case: $$$b$$$ can be shifted to the left by $$$k = 1$$$. The resulting permutations will be $$$\{1, 3, 2, 4\}$$$ and $$$\{2, 3, 1, 4\}$$$. Positions $$$2$$$ and $$$4$$$ have matching pairs of elements. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$2$$$.

def f(l1, l2, n)
	if l2 <= l1
		return l1 - l2
	end
	return n - l2 + l1
end

n = gets.to_i
line1 = gets.split(' ').collect { |elem| elem.to_i}
line2 = gets.split(' ').collect { |elem| elem.to_i}
#["", "22", "14", "18"].map(&:to_i)
idx_line1 = Array.new(n)
n.times do
	|idx|
	idx_line1[line1[idx]] = idx
end
m = {}
maxi = 0;
n.times do
	|idx|
	val = f(idx_line1[line2[idx]], idx, n)
	if m[val] == nil
		m[val] = 1
	else
		m[val] += 1
	end
	maxi = [maxi, m[val]].max
end

puts maxi

_ = gets
a = gets.strip.split(' ').map(&:to_i)
b = gets.strip.split(' ').map(&:to_i)

h = Hash.new(0)
b.each_with_index { |e, i| h[e] = i }

hash_shift = Hash.new(0)
a.each_with_index { |e, i|
  if i < h[e]
    hash_shift[e] = (a.size - h[e]) + i
  else
    hash_shift[e] = i - h[e]
  end
}

mx = -1
an = Hash.new(0)
hash_shift.each_value { |v| an[v] += 1; mx = [mx, an[v]].max }
puts mx

_ = gets
a = gets.strip.split(' ').map(&:to_i)
b = gets.strip.split(' ').map(&:to_i)

h = Hash.new(0)
b.each_with_index { |e, i| h[e] = i }

hash_right = Hash.new(0)
hash_left = Hash.new(0)
a.each_with_index { |e, i|
  if i < h[e]
    hash_right[e] = (a.size - h[e]) + i
    hash_left[e] = h[e] - i
  else
    hash_right[e] = i - h[e]
    hash_left[e] = (a.size - i) + h[e]
  end
}

hash_right_count = Hash.new(0)
hash_left_count = Hash.new(0)
mx = -1
hash_right.each { |k, v|
  m1 = hash_right_count[v] += 1
  m2 = hash_left_count[hash_left[k]] += 1
  mx = [mx, m1, m2].max
}
puts mx


On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.

The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.

Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.

NoteIn the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.


Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.  Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si = A + (i - 1) × B.For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence sl, sl + 1, ..., sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.

The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 106, 1 ≤ n ≤ 105). Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 106) for i-th query.

For each query, print its answer in a single line.

a, b, n = gets.split.map(&:to_i)

def find_r (a, b, l, t, m, s, e)
  return e if s == e || t * m >= (e - l + 1) * (a + b * (e + l - 2) / 2.0)
  mid = (e + s + 1) / 2
  if t * m >= (mid - l + 1) * (a + b * (mid + l - 2) / 2.0)
    find_r(a, b, l, t, m, mid, e)
  else
    find_r(a, b, l, t, m, s, mid - 1)
  end
end

n.times do
  l, t, m = gets.split.map(&:to_i)
  if t < a + b * (l - 1)
    puts -1
    next
  end
  puts find_r(a, b, l, t, m, l, (t + b - a) / b)
end

a, b, n = gets.split.map(&:to_i)

def find_r (a, b, l, t, m, s, e)
  return e if t * m >= (e - l + 1) * (a + b * (e + l - 2) / 2.0)
  return s - 1 if s == e;
  mid = (e + s) / 2;
  if t * m >= (mid - l + 1) * (a + b * (mid + l - 2) / 2.0)
    find_r(a, b, l, t, m, mid + 1, e)
  else
    find_r(a, b, l, t, m, s, mid)
  end
end

n.times do
  l, t, m = gets.split.map(&:to_i)
  if t < a + b * (l - 1)
    puts -1
    next
  end
  puts find_r(a, b, l, t, m, l, (t + b - a) / b)
end

a, b, n = gets.split.map(&:to_i)

def si(a, b, i)
  a + b * (i - 1)
end

n.times do
  l, t, m = gets.split.map(&:to_i)

  if t < si(a, b, l)
    puts -1
    next
  end

  rl = l
  rr = (t + b - a) / b

  while rl != rr
    mid = (rl + rr + 1) / 2
    if t * m >= (si(a, b, l) + si(a, b, mid)) * (mid - l + 1) / 2
      rl = mid
    else
      rr = mid - 1
    end
  end
  puts rr
end

a, b, n = gets.split.map &:to_i
n.times do
	l, t, m = gets.split.map &:to_i
	d = t*m; f = a+(l-1)*b; k = l; x = 1000001
	while(k < x) do
            mid  = k+(x-k+1)/2; q = a+(mid-1)*b; sum  = (f+q)*(mid-l+1)/2
	    (t >= q && d >= sum)? (k = mid) : (x = mid-1)
	end
	puts (k == l and t < f)? (-1) : (k)
end

a, b, n = gets.split.map(&:to_i)

def si(a, b, i)
  a + b * (i - 1)
end

n.times do
  l, t, m = gets.split.map(&:to_i)

  rl = l
  rr = (t + b - a) / b

  if t < si(a, b, l)
    puts -1
    next
  end

  while rl != rr
    if t * m >= (si(a, b, l) + si(a, b, rr)) * (rr - l + 1) / 2
      rl = (rl + rr + 1) / 2
    else
      rr = (rl + rr + 1) / 2
    end
  end
  puts rr
end

a, b, n = gets.split.map(&:to_i)

def find_r (a, b, l, t, m, s, e)
  return s if s == e
  if t * m >= (e - l + 1) * (a + b * (e + l - 2) / 2.0)
    find_r(a, b, l, t, m, (e + s) / 2 + 1, e)
  else
    find_r(a, b, l, t, m, s, (e + s) / 2)
  end
end

n.times do
  l, t, m = gets.split.map(&:to_i)
  if t < a + b * (l - 1)
    puts -1
    next
  end
  puts find_r(a, b, l, t, m, l, ((t + b - a) / b))
end


During a recent research Berland scientists found out that there were n cities in Ancient Berland, joined by two-way paths. Any two cities are joined by no more than one path. No path joins a city with itself. According to a well-known tradition, the road network was built so that it would be impossible to choose three cities from each of which one can get to any other one directly. That is, there was no cycle exactly as long as 3. Unfortunately, the road map has not been preserved till nowadays. Now the scientists are interested how much developed a country Ancient Berland was. Help them - find, what maximal number of roads could be in the country. You also have to restore any of the possible road maps.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of cities in Berland.

On the first line must be printed number m — the maximal number of roads in Berland. Then print m lines containing two numbers each — the numbers of cities that the given road joins. The cities are numbered with integers from 1 to n. If there are several variants of solving the problem, print any of them.

n = gets.to_i
p = n/2
puts p*(n-p)
for i in 1..p do
  for j in p+1..n do
    printf("%d %d\n", i, j)
  end
end

n = gets.chomp.to_i
ar = Array.new
for i in 1..n-1
	for j in i+1..n
		next if i + 2 == j
		next if (i % 2 == j % 2)
		ar.push([i,j])
	end
end
puts ar.length
ar.each{|x| puts x[0].to_s + " " + x[1].to_s }

n = gets.chomp.to_i
ar = Array.new
for i in 1..n-1
	for j in i+1..n
		next if i + 2 == j
		if n > 3
			next if (i == 2 && j == n) || (i == 1 && j == n-1)
		end
		next if i > 1 && (i % 2 == j % 2)
		ar.push([i,j])
	end
end
puts ar.length
ar.each{|x| puts x[0].to_s + " " + x[1].to_s }

n = gets.chomp.to_i
ar = Array.new
for i in 1..n-1
	for j in i+1..n
		next if i + 2 == j
		if n > 3
			next if (i == 2 && j == n) || (i == 1 && j == n-1)
		end
		ar.push([i,j])
	end
end
puts ar.length
ar.each{|x| puts x[0].to_s + " " + x[1].to_s }


Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $$$n$$$ last days: $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the price of berPhone on the day $$$i$$$.Polycarp considers the price on the day $$$i$$$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $$$n=6$$$ and $$$a=[3, 9, 4, 6, 7, 5]$$$, then the number of days with a bad price is $$$3$$$ — these are days $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) and $$$5$$$ ($$$a_5=7$$$).Print the number of days with a bad price.You have to answer $$$t$$$ independent data sets.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of sets of input data in the test. Input data sets must be processed independently, one after another. Each input data set consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of days. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the price on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ over all data sets in the test does not exceed $$$150000$$$.

Print $$$t$$$ integers, the $$$j$$$-th of which should be equal to the number of days with a bad price in the $$$j$$$-th input data set.

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	min = 10**9
	puts a.reverse.count { |i|
			res = min < i
			min = [min, i].min
			res
	     }
end

t = gets.to_i
t.times do
  n = gets.to_i
  arr = gets.split.map(&:to_i)
  min = nil
  count = 0
  arr.reverse_each do |x|
    min = x if min.nil? || x < min
    count += 1 if x > min
  end
  puts count
end

# coding: utf-8

# if __FILE__ == $0
# end
Price = Struct.new(:price, :day)
t = gets.to_i
t.times {
    n = gets.to_i
    a = []
    gets.split.each_with_index { |price, day_zero|
        a << Price.new(price.to_i, day_zero+1)
    }
    # non-descending order
    a.sort! { |e1, e2|
        if e1.price != e2.price
            e1.price - e2.price
        else
            e1.day - e2.day
        end
    }
    # 사용 가능한 factor: price-day (value-index)
    bads = 0
    pday = 0
    for i in a
        if pday <= i.day
            pday = i.day
        else
            bads += 1
        end
    end

    puts bads
}

t=gets.to_i
for j in 0...t do
    n=gets.to_i
    a=Array.new()
    for i in 0...n-1 do
        a.unshift(gets(sep=' ').to_i)
    end
    d=0
    a.unshift(gets.to_i)
    mn=a[0]
        for i in 1...n do
            if a[i]>mn then
                d+=1
            else
                mn=a[i]
            end
        end
            puts d
end

t=gets.to_i
for j in 0...t do
    n=gets.to_i
    a=Array.new(n-1)
    for i in 0...n-1 do
        a[i]=gets(sep=' ').to_i
    end
    d=0
    a.push(gets.to_i)
            mn=a.last
        for i in (0...n).reverse_each do
            if a[i]>mn then
                d+=1
            else
                mn=a[i]
            end
        end
            puts d
end

def solve
end

gets.strip.to_i.times do
  n = gets.strip.to_i
  days = gets.strip.split(' ').map(&:to_i)
  days.reverse!
  last = days[0]
  res = 0
  days.each do |d|
    if d > last
      res += 1
    end
    last = [last, d].min
  end
  puts res
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  suf_min = 1E100.to_i
  res = 0
  (0...n).reverse_each do |i|
    res += 1 if a[i] > suf_min
    suf_min = [suf_min, a[i]].min
  end
  puts res
end

# require 'pry'

t = gets.to_i
t.times do
  n = gets.to_i
  min = nil
  res = 0
  gets.split.map(&:to_i).reverse_each do |num|
    res += 1 if min && min < num
    min = num if min.nil? || num < min
  end
  puts res
end

tt = gets.to_i
tt.times do |t|
  nn = gets.to_i
  aa = gets.split.map(&:to_i)

  cnt = 0
  min = aa[-1]
  (nn-2).downto(0) do |n|
      if aa[n] > min
        cnt+=1
      else
        min = aa[n]
      end
  end
  puts cnt
end

# coding: utf-8

# if __FILE__ == $0
# end
Price = Struct.new(:price, :day)
t = gets.to_i
t.times {
    n = gets.to_i
    a = []
    gets.split.each_with_index { |price, day_zero|
        a << Price.new(price.to_i, day_zero)
    }
    # non-descending order
    a.sort! { |e1, e2|
        e1.price - e2.price
    }
    # 사용 가능한 factor: price-day (value-index)
    bads = 0
    pday = 0
    for i in a
        if pday <= i.day
            pday = i.day
        else
            bads += 1
        end
    end

    puts bads
}

# coding: utf-8

# if __FILE__ == $0
# end
Price = Struct.new(:price, :day)
t = gets.to_i
t.times {
    n = gets.to_i
    a = []
    gets.split.each_with_index { |price, day_zero|
        a << Price.new(price.to_i, day_zero+1)
    }
    # non-descending order
    a.sort! { |e1, e2|
        e1.price - e2.price
    }
    # 사용 가능한 factor: price-day (value-index)
    bads = 0
    pday = 0
    for i in a
        if pday < i.day
            pday = i.day
        else
            bads += 1
        end
    end

    puts bads
}


The map of Berland is a rectangle of the size n × m, which consists of cells of size 1 × 1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k.

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 0 ≤ k ≤ 50) — the sizes of the map and the number of lakes which should be left on the map. The next n lines contain m characters each — the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land). It is guaranteed that the map contain at least k lakes.

In the first line print the minimum number of cells which should be transformed from water to land.  In the next n lines print m symbols — the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them.  It is guaranteed that the answer exists on the given data.

NoteIn the first example there are only two lakes — the first consists of the cells (2, 2) and (2, 3), the second consists of the cell (4, 3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean.

n, m, k = gets.split.map(&:to_i)
@land = []
n.times do |i|
  @land[i] = gets.chomp.split('')
end
@n, @m = n, m

# def bfs(r, c)
#   return [] unless @land[r][c] == '.'
#   arr = [[r, c]]
#   @land[r][c] = '#'
#   [[1, 0], [-1, 0], [0, 1], [0, -1]].each do |ud, lr|
#     rr, cc = r + ud, c + lr
#     next if rr < 0 || rr >= @n || cc < 0 || cc >= @m
#     arr += bfs(rr,cc)
#   end
#   arr
# end

def bfs(r, c)
  return [] unless @land[r][c] == '.'
  arr = [[r, c]]
  @land[r][c] = '#'
  answer = []
  while !arr.empty? do
    r, c = arr.pop
    answer << [r, c]
    [[1, 0], [-1, 0], [0, 1], [0, -1]].each do |ud, lr|
      rr, cc = r + ud, c + lr
      next if rr < 0 || rr >= @n || cc < 0 || cc >= @m
      next unless @land[rr][cc] == '.'
      arr << [rr, cc]
      @land[rr][cc] = '#'
    end
  end
  answer
end

n.times { |r| [0, m - 1].each { |c| bfs(r, c) } }
m.times { |c| [0, n - 1].each { |r| bfs(r, c) } }

lakes = []
(1...(n-1)).each do |r|
  (1...(m-1)).each do |c|
    lake = bfs(r, c)
    next if lake.empty?
    lakes << lake
  end
end

lakes.sort_by!(&:size)
count = 0
lakes[0...(lakes.size - k)].each do |lake|
  lake.each { |r, c| @land[r][c] = '*'; count += 1 }
end
@land.each { |row| row.map! { |x| x == '#' ? '.' : x } }

puts count
@land.each do |row|
  puts row.join
end

vs = Array.new(55){Array.new(55, 0)}
rv = Array.new(55){Array.new(55, 0)}
l = Array.new(2502)
lx = Array.new(2502)
ly = Array.new(2502)
def ff(vs, rv, x, y)
	dx = [1, 0, -1, 0]
	dy = [0, 1, 0, -1]
	fx = Array.new(2502)
	fy = Array.new(2502)
	r = 1
	t = 2
	cnt = 0
	fx[r] = x
	fy[r] = y
	vs[x][y] = '*'
	rv[x][y] = 15
	while r != t
		x = fx[r]
		y = fy[r]
		r += 1
		cnt += 1
		for o in (0..3)
			nx = x + dx[o]
			ny = y + dy[o]
			if vs[nx][ny] == '.'
				vs[nx][ny] = '*'
				rv[nx][ny] = 15
				fx[t] = nx
				fy[t] = ny
				t += 1
			end
		end
	end
	return cnt
end
ipt = gets.split(' ')
n = ipt[0].to_i
m = ipt[1].to_i
k = ipt[2].to_i
for i in (1..n)
	ipt = 'Z'
	ipt += gets
	vs[i] = ipt
end
for i in (1..m)
	if vs[1][i] == '.'
		ff(vs, rv, 1, i)
	end
	if vs[n][i] == '.'
		ff(vs, rv, n, i)
	end
end
for i in (1..n)
	if vs[i][1] == '.'
		ff(vs, rv, i, 1)
	end
	if vs[i][m] == '.'
		ff(vs, rv, i, m)
	end
end
lcnt = 0
for i in (1..n)
	for j in (1..m)
		if vs[i][j] == '.'
			lcnt = lcnt + 1
			l[lcnt] = ff(vs, rv, i, j)
			lx[lcnt] = i
			ly[lcnt] = j
		end
	end
end
for i in (1..lcnt)
	for j in (i+1..lcnt)
		if l[i] < l[j]
			t = l[i]
			l[i] = l[j]
			l[j] = t
			t = lx[i]
			lx[i] = lx[j]
			lx[j] = t
			t = ly[i]
			ly[i] = ly[j]
			ly[j] = t
		end
	end
end
for i in (1..n)
	for j in (1..m)
		if rv[i][j] == 15
			vs[i][j] = '.'
		end
	end
end
sum = 0
for k in (k+1..lcnt)
	sum += ff(vs, rv, lx[k], ly[k])
end
puts sum
for i in (1..n)
	for j in (1..m)
		print vs[i][j]
	end
	print "\n"
end

$n, $m, k = gets.split.map(&:to_i)
$map = $n.times.map{gets.chomp}
$vis = Array.new($n){Array.new($m, false)}
$lake = []

def dfs(x, y)
  return if x >= $n || y >= $m || x < 0 || y < 0
  return if $vis[x][y]
  return if $map[x][y] == '*'
  $lake << [x, y]
  $vis[x][y] = true

  dfs(x + 1, y)
  dfs(x - 1, y)
  dfs(x, y + 1)
  dfs(x, y - 1)
end

def get_lake(x, y)
  $lake = []
  dfs(x, y)
  return $lake
end

lakes = []
$n.times do |i|
  $m.times do |j|
    next if $map[i][j] == '*'
    lakes << get_lake(i, j)
  end
end

def is_ocean?(lake)
  lake.any? do |x, y|
    x == $n - 1 || x == 0 || y == $m - 1 || y == 0
  end
end

lakes = lakes.reject{|x| is_ocean?(x)}.sort_by(&:size)
ans = 0
while lakes.size > k
  lake = lakes.shift
  ans += lake.size
  lake.each{|x, y| $map[x][y] = '*'}
end

p ans
puts $map

def dfs(s, visited, map, path, start)
  k, j = s
  visited[s] = true

  list = []
  list.push([k, j - 1]) if j - 1 >= 0
  list.push([k, j + 1]) if j + 1 < map[0].length
  list.push([k - 1, j]) if k - 1 >= 0
  list.push([k + 1, j]) if k + 1 < map.length

  for i, j in list
    if !visited[[i, j]] && map[i][j] == "."
      path[start] << [i, j]
      dfs([i, j], visited, map, path, start)
    end
  end
end

n, m, l = gets.chomp.split.map(&:to_i)
map = Hash.new { |hash, key| hash[key] = nil }

n.times do |i|
  map[i] = gets.chomp.split("")
end

if map.values.join == "." * (n * m)
  puts 0
  for i in 0..(n - 1)
    print *map[i]
    puts
  end
else
  visited = Hash.new { |hash, key| hash[key] = false }
  path = Hash.new { |hash, key| hash[key] = [] }

  for k, v in map
    for j in 0..(v.length - 1)
      if !visited[[k, j]] && v[j] == "."
        path[[k, j]] << [k, j]
        dfs([k, j], visited, map, path, [k, j])
      end
    end
  end

  result = Hash.new { |hash, key| hash[key] = [] }
  for k, v in path
    v.push(k)

    flag = true
    for i, j in v
      if i == 0 || i == n - 1 || j == 0 || j == m - 1
        break flag = false
      end
    end

    result[v] = v.length - 1 if flag
  end

  groups = result.keys.count
  sizes = result.sort_by { |_k, v| v }

  min_groups = groups - l
  min = 0

  index = []
  min_groups.times do |i|
    min += sizes[i][1]
    index << sizes[i][0]
  end

  puts min
  for v in index
    for i, j in v
      map[i][j] = "*"
    end
  end
  for i in 0..(n - 1)
    print *map[i]
    puts
  end
end

n, m, k = gets.split.map(&:to_i)
@land = []
n.times do |i|
  @land[i] = gets.chomp.split('')
end
@n, @m = n, m

def bfs(r, c)
  return unless @land[r][c] == '.'
  (arr = []) << [r, c]
  lake = []
  while !arr.empty?
    r, c = arr.shift
    lake << [r, c]
    @land[r][c] = '#'
    [[1, 0], [-1, 0], [0, 1], [0, -1]].each do |ud, lr|
      rr, cc = r + ud, c + lr
      next if rr < 0 || rr >= @n || cc < 0 || cc >= @m
      next unless @land[rr][cc] == '.'
      arr << [rr, cc]
    end
  end
  lake
end

n.times { |r| [0, m - 1].each { |c| bfs(r, c) } }
m.times { |c| [0, n - 1].each { |r| bfs(r, c) } }

lakes = []
(1...(n-1)).each do |r|
  (1...(m-1)).each do |c|
    lake = bfs(r, c)
    next if lake.nil? || lake.empty?
    lakes << lake
  end
end

lakes.sort! { |l| l.size }
count = 0
lakes[0...(lakes.size - k)].each do |lake|
  lake.each { |r, c| @land[r][c] = '*'; count += 1 }
end
@land.each { |row| row.map! { |x| x == '#' ? '.' : x } }

puts count
@land.each do |row|
  puts row.join
end

n, m, k = gets.split.map(&:to_i)
@land = []
n.times do |i|
  @land[i] = gets.chomp.split('')
end

@n, @m = n, m

def dfs(r, c)
  return [] if @land[r][c] == '*' || @land[r][c] == '#'
  raise if (r == 0 or r == @n - 1 or c == 0 or c == @m - 1) && @land[r][c] == '.'
  @land[r][c] = '#'
  [[r, c]] + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c - 1) + dfs(r, c + 1)
end

lakes = []

(1...(n-1)).each do |r|
  (1...(m-1)).each do |c|
    begin
      lake = dfs(r, c)
      next if lake.empty?
      lakes << lake
    rescue
      next
    end
  end
end

lakes = lakes.sort { |l| -l.size }
count = 0
(k...(lakes.size)).each do |i|
  lakes[i].each { |r, c| @land[r][c] = '*'; count += 1 }
end
@land.each { |row| row.map! { |c| c == '#' ? '.' : c } }

puts count
@land.each do |row|
  puts row.join
end

n, m, k = gets.split.map(&:to_i)
@land = []
n.times do |i|
  @land[i] = gets.chomp.split('')
end
@n, @m = n, m

def bfs(r, c)
  return [] unless @land[r][c] == '.'
  (arr = []) << [r, c]
  @land[r][c] = '#'
  [[1, 0], [-1, 0], [0, 1], [0, -1]].each do |ud, lr|
    rr, cc = r + ud, c + lr
    next if rr < 0 || rr >= @n || cc < 0 || cc >= @m
    arr += bfs(rr,cc)
  end
  arr
end

n.times { |r| [0, m - 1].each { |c| bfs(r, c) } }
m.times { |c| [0, n - 1].each { |r| bfs(r, c) } }

lakes = []
(1...(n-1)).each do |r|
  (1...(m-1)).each do |c|
    lake = bfs(r, c)
    next if lake.empty?
    lakes << lake
  end
end

lakes.sort! { |l| l.size }
count = 0
lakes[0...(lakes.size - k)].each do |lake|
  lake.each { |r, c| @land[r][c] = '*'; count += 1 }
end
@land.each { |row| row.map! { |x| x == '#' ? '.' : x } }

puts count
@land.each do |row|
  puts row.join
end

n, m, k = gets.split.map(&:to_i)
@land = []
n.times do |i|
  @land[i] = gets.chomp.split('')
end

@n, @m = n, m

def dfs(r, c)
  return [] if @land[r][c] == '*' || @land[r][c] == '#'
  return nil if (r == 0 or r == @n - 1 or c == 0 or c == @m - 1) && @land[r][c] == '.'
  @land[r][c] = '#'
  ans = [[r, c]]
  [[r + 1, c], [r - 1, c], [r, c - 1], [r, c + 1]].each do |rr, cc|
    d = dfs(rr, cc)
    if d.nil?
      ans.each { |r, c| @land[r][c] = '.' }
      return
    else
      ans += d
    end
  end
  ans
end

lakes = []

(1...(n-1)).each do |r|
  (1...(m-1)).each do |c|
    begin
      lake = dfs(r, c)
      next if lake.nil? || lake.empty?
      lake.each { |r, c|  }
      lakes << lake
    rescue
      next
    end
  end
end

lakes.sort! { |l| -l.size }
count = 0
(k...(lakes.size)).each do |i|
  lakes[i].each { |r, c| @land[r][c] = '*'; count += 1 }
end
@land.each { |row| row.map! { |c| c == '#' ? '.' : c } }

puts count
@land.each do |row|
  puts row.join
end

def dfs(s, visited, map, path, start)
  k, j = s
  visited[s] = true

  list = []
  list.push([k, j - 1]) if j - 1 >= 0 && map[k][j - 1] == "."
  list.push([k, j + 1]) if j + 1 < map[0].length && map[k][j + 1] == "."
  list.push([k - 1, j]) if k - 1 >= 0 && map[k - 1][j] == "."
  list.push([k + 1, j]) if k + 1 < map.length && map[k + 1][j] == "."

  for i, j in list
    if !visited[[i, j]]
      path[start] << [i, j]
      dfs([i, j], visited, map, path, start)
    end
  end
end

n, m, l = gets.chomp.split.map(&:to_i)
map = Hash.new { |hash, key| hash[key] = nil }

n.times do |i|
  map[i] = gets.chomp.split("")
end

visited = Hash.new { |hash, key| hash[key] = false }
path = Hash.new { |hash, key| hash[key] = [] }

for k, v in map
  for j in 0..(v.length - 1)
    if !visited[[k, j]] && v[j] == "."
      path[[k, j]] << [k, j]
      dfs([k, j], visited, map, path, [k, j])
    end
  end
end

result = Hash.new { |hash, key| hash[key] = [] }
for k, v in path
  v.push(k)

  flag = true
  for i, j in v
    if i == 0 || i == n - 1 || j == 0 || j == m - 1
      break flag = false
    end
  end

  result[k] = v.length - 1 if flag
end

groups = result.keys.count
sizes = result.sort_by { |_k, v| v }

min_groups = groups - l
min = 0

index = []
min_groups.times do |i|
  min += sizes[i][1]
  index << sizes[i][0]
end

for i, j in index
  map[i][j] = "*"
end

puts min
for i in 0..(n - 1)
  print *map[i]
  puts
end

def dfs(s, visited, map, path, start)
  k, j = s
  visited[s] = true

  list = []
  list.push([k, j - 1]) if j - 1 >= 0 && map[k][j - 1] == "."
  list.push([k, j + 1]) if j + 1 < map[0].length && map[k][j + 1] == "."
  list.push([k - 1, j]) if k - 1 >= 0 && map[k - 1][j] == "."
  list.push([k + 1, j]) if k + 1 < map.length && map[k + 1][j] == "."

  for i, j in list
    if !visited[[i, j]]
      path[start] << [i, j]
      dfs([i, j], visited, map, path, start)
    end
  end
end

n, m, l = gets.chomp.split.map(&:to_i)
map = Hash.new { |hash, key| hash[key] = nil }

n.times do |i|
  map[i] = gets.chomp.split("")
end

visited = Hash.new { |hash, key| hash[key] = false }
path = Hash.new { |hash, key| hash[key] = [] }

for k, v in map
  for j in 0..(v.length - 1)
    if !visited[[k, j]] && v[j] == "."
      path[[k, j]] << [k, j]
      dfs([k, j], visited, map, path, [k, j])
    end
  end
end

result = Hash.new { |hash, key| hash[key] = [] }
for k, v in path
  v.push(k)

  flag = true
  for i, j in v
    if i == 0 || i == n - 1 || j == 0 || j == m - 1
      break flag = false
    end
  end

  result[k] = v.length - 1 if flag
end

groups = result.keys.count
sizes = result.sort_by { |_k, v| v }

min_groups = groups - l
min = 0

index = []
min_groups.times do |i|
  min += sizes[i][1]
  index << sizes[i][0]
end
puts min

for i, j in index
  map[i][j] = "*"
end

for i in 0..(n - 1)
  print *map[i]
  puts
end

def dfs(s, map, visited, path, start)
  k, j = s
  visited[s] = true

  list = [[k, j - 1], [k, j + 1], [k - 1, j], [k + 1, j]]

  for i, j in list
    if !visited[[i, j]] && map[i][j] == "."
      path[start] += 1
      dfs([i, j], map, visited, path, start)
    end
  end
end

n, m, l = gets.chomp.split.map(&:to_i)

map = Hash.new { |hash, key| hash[key] = [] }
map_2 = Hash.new { |hash, key| hash[key] = [] }

n.times do |i|
  row = gets.chomp.split("")
  map[i] = row
  map_2[i] = row.dup
end

for i in 0..(n - 1)
  for j in 0..(m - 1)
    if (i == 0 || i == n - 1 || j == 0 || j == m - 1) && map[i][j] == "."
      map[i][j] = "*"
      map[i][j + 1] = "*" if j + 1 < m
      map[i][j - 1] = "*" if j - 1 >= 0
      map[i + 1][j] = "*" if i + 1 < n
      map[i - 1][j] = "*" if i - 1 >= 0
    end
  end
end

visited = Hash.new { |hash, key| hash[key] = false }
path = Hash.new { |hash, key| hash[key] = 0 }

for k, v in map
  for j in 0..(v.length - 1)
    if !visited[[k, j]] && v[j] == "."
      path[[k, j]] += 1
      dfs([k, j], map, visited, path, [k, j])
    end
  end
end

groups = path.keys.count
sizes = path.sort_by { |_k, v| v }

min_groups = groups - l
min = 0

index = []
min_groups.times do |i|
  min += sizes[i][1]
  index << sizes[i][0]
end

for i, j in index
  map_2[i][j] = "*"
end

puts min
for i in 0..(n - 1)
  print *map_2[i]
  puts
end


The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.

The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.

In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem.

NoteIn the first sample the best strategy is to delete the second digit. That results in number 112 = 310.In the second sample the best strategy is to delete the third or fourth digits — that results in number 110102 = 2610.

=begin
Dear online judge:
I've wasted time reading the problem and trying to figure out the solution
If you insist on the penalty system, please don't include the time of debugging
I hope my code compile and get accepted. KEE O.o
     ____________
    /         __ \
   /   __    |  | \
  /   |__|   |  |  \
 (           |__|   )
  \                /
   \      ___     /
    \____________/
=end

class Solve
  def solve()
    $str = gets.chomp
    $res = ""
    $found = 0
    for $i in 0..($str.size() - 1)
      if $found == 1 || $str[$i] != '0'
        $res<<$str[$i]
      else
        $found = 1
      end
    end
    if $found == 0
      $res.chop!
    end
    puts $res
  end
end

Solve.new.solve

str = gets.chomp
n = str.index("0")
if n then
    str = str[0...n] + str[n+1..-1]
else
    str = str[0...-1]
end
puts str

a = gets
a.sub!('1', '') unless a.sub!('0', '')
puts a

#!/usr/bin/ruby

s = gets
pos = s.index('0') || 0
puts s[0...pos] + s[pos+1..-1]

s = gets.strip
i = s.index("0"); i = 0 if i == nil
s[i] = ""
puts s

s = gets
p = s.index "0"
if p != nil
    s[p, s.size] = s[p+1, s.size];
else
    s[s.size - 2, 2] = s[s.size-1, 2]
end
puts s

def run
  ARGF.readlines.each do |line|
    line.chomp!
    i = line.index('0') || 0
    puts line[0, i] + line[i + 1, line.length - i - 1]
  end
end

run if $0 == __FILE__

s = gets.chomp
n = s.length
(0..n).each do |i|
	if i == n
		puts s[1..n-1]
	elsif s[i] == '0'
		print s[0..i-1]
		print s[i+1..n-1]
		break
	end
end

s=gets.chomp
n1=0
n2=0
if s.size>1 && s.index("0") then
	n1=s.sub("0","").to_i(2)
end
if s.size>1 && s.rindex("1") then
	n2=s.reverse.sub("1","").reverse.to_i(2)
end
puts [n1,n2].max.to_s(2)

binary = gets.strip.split('')
if binary.index('0')
  binary.delete_at binary.index('0')
else
  binary.delete_at 0
end
puts binary.join

# coding: utf-8

s = gets.chomp
pos_zero = s.index('0')

if pos_zero == nil
    puts s[0...-1]
else
    puts "#{s[0...pos_zero]}#{s[(pos_zero+1)..-1]}"
end

s = gets.strip
i = s.index("0")
n = s.length
if i.nil?
    puts s[1...n]
else
   puts (s[0...i] + s[(i + 1)...n])
end

str = gets.chomp
pos = str.index('0')
pos = -1 if pos == nil
str.slice!(pos)
str = '0' if str.length == 0
print str

s=gets.chomp

s.length.times { |i|
  if s[i]==?0
    s[i]=''
    puts s
    exit
  end
}

puts s.chop

s=gets.chomp

s.length.times { |i|
  if s[i]==?0
    s[i]=''
    puts s
    exit
  end
}

s[-1]=''
puts s

s=gets
s.sub!('1','') unless s.sub!('0','')
puts s

a = gets.chomp.chars.map(&:to_i)
if a.include?(0)
  a[a.find_index{|x| x == 0}] = nil
else
  a[0] = nil
end
puts a.join("")

a = gets.chomp
puts a.sub(a['0'] || '1', '')

a=gets
if !a.sub! /0/,'' then
	a.sub! /1/,''
end
puts a

s = gets.chomp
if s.count('0') == 0
	puts s.chop
else
	id = s.index '0'
	s[id] = ''
	puts s
end

=begin
sq = Array.new(3)
for i in 0..2
  sq[i] = gets.split.map(&:to_i)
end
sq[0][0] = sq[0][2]
sq[2][2] = sq[0][0] + sq[0][1] - sq[1][2]
sq[1][1] = sq[0][0] + sq[2][0] - sq[1][2]
for i in sq
  for j in i
    print j, " "
  end
  puts ""
end
=end

bit = gets.strip
i = bit.index "0"
if i == nil then i = 0 end
bit[i] = ""
print bit

#!/usr/bin/ruby1.9

line = STDIN.readline.strip
pos = line.index('0')
if pos == nil
	pos = line.length-1
end
puts line.slice(0, pos)+line.slice(pos+1, line.length-1)

s = gets.strip
i = s.index("0"); i = 0 if i == nil
puts s[0...i]+s[i+1..-1]

s = gets.chomp.split('').map(&:to_i).to_a
s.delete_at(s.index(0) == nil ? 0 : s.index(0))
puts s*''

n = gets.chomp.chars.to_a
if i = n.index("0")
  n.delete_at i
else
  n.delete_at 0
end
puts n.join

a = gets
b = ""
f = false
a.each_char do |c|
  b << c if f || c == '1'
  f = true if c == '0'
end
b.chop! unless f

puts b

a = gets.strip

ok = false

if a == '1' * a.size
	print '1' * (a.size-1)
else
	a.each_char do |c|
		if ok or c == '1'
			print c
		elsif c == '0'
			ok = true
		end
	end
end

s=gets

s.length.times { |i|
  if s[i]==?0
    s[i]=''
    puts s
    exit
  end
}

s[-1]=''
puts

a = gets.strip

ok = false

a.each_char do |c|
	if ok or c == '1'
		print c
	elsif c == '0'
		ok = true
	end
end


Sam is a kindergartener, and there are $$$n$$$ children in his group. He decided to create a team with some of his children to play "brawl:go 2".Sam has $$$n$$$ power-ups, the $$$i$$$-th has type $$$a_i$$$. A child's strength is equal to the number of different types among power-ups he has.For a team of size $$$k$$$, Sam will distribute all $$$n$$$ power-ups to $$$k$$$ children in such a way that each of the $$$k$$$ children receives at least one power-up, and each power-up is given to someone.For each integer $$$k$$$ from $$$1$$$ to $$$n$$$, find the minimum sum of strengths of a team of $$$k$$$ children Sam can get.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$).  The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — types of Sam's power-ups. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For every test case print $$$n$$$ integers. The $$$k$$$-th integer should be equal to the minimum sum of strengths of children in the team of size $$$k$$$ that Sam can get.

require 'set'
gets.to_i.times {
  n = gets.to_i
  s = Set.new
  gets.split.map!(&:to_i).each { s.add _1 }
  m = s.size
  (1..n).each { |k|
    print [m, k].max, ' '
  }
  puts
}


A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.For example:   If x = 6 and the crossword is 111011, then its encoding is an array {3, 2};  If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1};  If x = 5 and the crossword is 11111, then its encoding is an array {5};  If x = 5 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!

The first line contains two integer numbers n and x (1 ≤ n ≤ 100000, 1 ≤ x ≤ 109) — the number of elements in the encoding and the length of the crossword Mishka picked. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 10000) — the encoding.

Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.

n,m=gets.split.map{|e| e.to_i}
sum=gets.split.map{|e| e.to_i}.inject(0){|sum,e| sum+e}+n-1
if m==sum
	puts "YES"
else
	puts "NO"
end

n, x = gets.split.map &:to_i
puts gets.split.map(&:to_i).inject(:+)+n==x+1?:YES:'NO'

in_str = gets
n, x = in_str.split(' ')
n, x = n.to_i, x.to_i
in_str = gets
crossword_arr = in_str.split(' ').map { |element| element.to_i }
length = 0
crossword_arr.each do |elem|
  length += elem + 1
end
if length - 1 == x
  puts 'YES'
else
  puts 'NO'
end


Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 × 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.The morning has come. All n alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game:  First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal.  Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off. Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!

The first line of the input contains integer n (1 ≤ n ≤ 105) — the number of the alarm clocks. The next n lines describe the clocks: the i-th line contains two integers xi, yi — the coordinates of the i-th alarm clock (0 ≤ xi, yi ≤ 100). Note that a single point in the room can contain any number of alarm clocks and the alarm clocks can lie on the sides of the square that represents the room.

In a single line print a single integer — the minimum number of segments Inna will have to draw if she acts optimally.

NoteIn the first sample, Inna first chooses type "vertical segments", and then she makes segments with ends at : (0, 0), (0, 2); and, for example, (1, 0), (1, 1). If she paints horizontal segments, she will need at least 3 segments.In the third sample it is important to note that Inna doesn't have the right to change the type of the segments during the game. That's why she will need 3 horizontal or 3 vertical segments to end the game.

k,l,a,b=0,0,Array.new(101,0),Array.new(101,0)
gets.to_i.times do
	x,y=gets.chomp.split.map(&:to_i)
	if a[x]==0
		a[x]=1
		l+=1
	end
	if b[y]==0
		b[y]=1
		k+=1
	end
end
puts [k,l].min

a = Array.new(2) { [0] * 101 }
gets.to_i.times { x, y = gets.split.map &:to_i; a[0][x] += 1; a[1][y] += 1 }
p a.map { |e| e.count { |e| e > 0 } }.min

n = gets.to_i
x_arr = []
y_arr = []
n.times do
	x,y = gets.split(" ").map(&:to_i)
	x_arr << x
	y_arr << y
end
h = x_arr.uniq.count
v = y_arr.uniq.count
puts [h,v].min


Pak Chanek has a prime number$$$^\dagger$$$ $$$n$$$. Find a prime number $$$m$$$ such that $$$n + m$$$ is not prime.$$$^\dagger$$$ A prime number is a number with exactly $$$2$$$ factors. The first few prime numbers are $$$2,3,5,7,11,13,\ldots$$$. In particular, $$$1$$$ is not a prime number.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The only line of each test case contains a prime number $$$n$$$ ($$$2 \leq n \leq 10^5$$$).

For each test case, output a line containing a prime number $$$m$$$ ($$$2 \leq m \leq 10^5$$$) such that $$$n + m$$$ is not prime. It can be proven that under the constraints of the problem, such $$$m$$$ always exists. If there are multiple solutions, you can output any of them.

NoteIn the first test case, $$$m = 2$$$, which is prime, and $$$n + m = 7 + 2 = 9$$$, which is not prime.In the second test case, $$$m = 7$$$, which is prime, and $$$n + m = 2 + 7 = 9$$$, which is not prime.In the third test case, $$$m = 47837$$$, which is prime, and $$$n + m = 75619 + 47837 = 123456$$$, which is not prime.

for i in 1..gets.to_i
  puts gets.to_i
end

n=gets.to_i
n.times do
    t=gets.to_i
    puts 7
end

for i in 1..gets.to_i
  puts 2*gets.to_i
end


You have an array $$$a$$$ of length $$$n$$$. You can exactly once select an integer $$$len$$$ between $$$1$$$ and $$$n - 1$$$ inclusively, and then sort in non-decreasing order the prefix of the array of length $$$len$$$ and the suffix of the array of length $$$n - len$$$ independently.For example, if the array is $$$a = [3, 1, 4, 5, 2]$$$, and you choose $$$len = 2$$$, then after that the array will be equal to $$$[1, 3, 2, 4, 5]$$$.Could it be that after performing this operation, the array will not be sorted in non-decreasing order?

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^4$$$) — the length of the array. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case of input data, output "YES" (without quotes), if the array may be not sorted in non-decreasing order, output "NO" (without quotes) otherwise. You can output each letter in any case (uppercase or lowercase).

NoteIn the first test case, it's possible to select $$$len = 1$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[2, 1, 2]$$$.In the second test case, it's possible to select $$$len = 3$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[1, 2, 3, 1]$$$.In the third test case, the array will be sorted in non-decreasing order for every possible $$$len$$$.

$__cur_readed = []
$__cur_index = 0

def rs1()
	while $__cur_index >= $__cur_readed.length
		$__cur_readed = gets.split(" ")
		$__cur_index = 0
	end
	$__cur_index+=1
	return $__cur_readed[$__cur_index-1]
end

def rs2()
	cur = ""
	while true
		if STDIN.eof
			return cur
		end
		c = STDIN.readchar
		#puts "cur s is " + c
		if c != " " and c != "\n"
			cur += c
		else
			if cur != ""
				return cur
			end
		end
	end
end

def ri()
	return rs1.to_i
end

t = ri

for curt in (1..t)
	n = ri
	arr = Array.new(n) {|i| ri}
	puts arr == arr.sort ? "NO" : "YES"
end

$__cur_readed = []
$__cur_index = 0

def ri()
	while $__cur_index >= $__cur_readed.length
		$__cur_readed = gets.split(" ")
		$__cur_index = 0
	end
	$__cur_index+=1
	return $__cur_readed[$__cur_index-1]
end

def rs()
	cur = ""
	while true
		if STDIN.eof
			return cur
		end
		c = STDIN.readchar
		#puts "cur s is " + c
		if c != " " and c != "\n"
			cur += c
		else
			if cur != ""
				return cur
			end
		end
	end
end

t = rs.to_i

for curt in (1..t)
	n = rs.to_i
	arr = Array.new(n) {|i| rs.to_i}
	puts arr == arr.sort ? "NO" : "YES"
end

$__cur_readed = []
$__cur_index = 0

def ri()
	while $__cur_index >= $__cur_readed.length
		$__cur_readed = gets.split(" ")
		$__cur_index = 0
	end
	$__cur_index+=1
	return $__cur_readed[$__cur_index-1]
end

t = ri.to_i

for curt in (1..t)
	n = ri.to_i
	arr = Array.new(n) {|i| ri.to_i}
	puts arr == arr.sort ? "NO" : "YES"
end

gets.to_i.times {
  gets
  xs = gets.split.map(&:to_i)
  if xs == xs.sort
    puts "NO"
  else
    puts "YES"
  end
}


There are $$$n$$$ boxers, the weight of the $$$i$$$-th boxer is $$$a_i$$$. Each of them can change the weight by no more than $$$1$$$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique).Write a program that for given current values $$$a_i$$$ will find the maximum possible number of boxers in a team.It is possible that after some change the weight of some boxer is $$$150001$$$ (but no more).

The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of boxers. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le 150000$$$) is the weight of the $$$i$$$-th boxer.

Print a single integer — the maximum possible number of people in a team.

NoteIn the first example, boxers should not change their weights — you can just make a team out of all of them.In the second example, one boxer with a weight of $$$1$$$ can be increased by one (get the weight of $$$2$$$), one boxer with a weight of $$$4$$$ can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of $$$3$$$ and $$$5$$$, respectively). Thus, you can get a team consisting of boxers with weights of $$$5, 4, 3, 2, 1$$$.

n = gets.to_i
aa = gets.split.map(&:to_i).sort

if n==1
  puts 1
  exit
end

max = 1
idx = 1
prev_num = aa[0]

# 選出フラグ
prev= aa[0]>1 ? true : false
current= aa[0]>1 ? false : true
nex=false

while idx < n do
  target = aa[idx]
  idx+=1

  # フラグ移動
  if target == prev_num
  elsif target == prev_num+1
    prev = current
    current = nex
    nex = false
  elsif target == prev_num+2
    prev = nex
    current = false
    nex = false
  else
    prev = false
    current = false
    nex = false
  end
  #puts "target:#{target},#{prev},#{current},#{nex}"

  # 小さい方から埋めていく
  if !prev && target>1
    prev_num = target
    prev = true
    max+=1
  elsif !current
    prev_num = target
    current = true
    max+=1
  elsif !nex
    prev_num = target
    nex = true
    max+=1
  end
  #puts max
end
puts max

n = gets.to_i
aa = gets.split.map(&:to_i).sort

idx = 0
max = 0

while idx < n do
  if (max..(max+2)).cover?(aa[idx])
    max+=1
  elsif aa[idx] >= max+3
    break
  end
  idx+=1
end
puts max


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

require 'set'
n = gets.to_i
a = Set.new(gets.split(' ').map(&:to_i))
res = 0
n.times do |i|
  unless a.include?(i+1); res += 1; end;
end
p res

n = gets.to_i
a = gets.split(' ').map(&:to_i)
res = 0
n.times do |i|
  unless a.include?(i+1); res += 1; end;
end
p res

n = gets.to_i
a = gets.split(' ').map(&:to_i)
res = 0
n.times do |i|
  if a.index(i+1) == nil; res += 1; end;
end
p res

def solve n, list
    (1..n).to_a.select{|i| list.include?(i) == false}.length
end

n = STDIN.gets.chomp.to_i
list = STDIN.gets.chomp.split(' ').map{|ch| ch.to_i}
puts solve n, list

n = gets.to_i
p n - gets.split.map(&:to_i).grep(1..n).uniq.size

n=gets.to_i
a=gets.split.map(&:to_i)
cnt=Array.new(n+1,0)
a.each{|i|
        if i<=n then
                cnt[i]=1
        end
}
ans=n
1.upto(n+1){|i|
        if cnt[i]==1 then
                ans-=1
        end
}
p ans

n = gets.to_i
p n - gets.split(' ').map{|i| i.to_i}.delete_if{|i| i > n}.uniq.size

n = gets.to_i
puts n - gets.split(' ').map{|i| i.to_i}.delete_if{|i| i > n}.uniq.size

require 'set'
n = gets().to_i
s = Set.new(gets().split(' ').map(&:to_i))

ret = 0
for i in 1..n
  if not s.include?(i) then
    ret += 1
  end
end
puts ret

require 'set'
n = gets().to_i
s = Set.new(gets().split(' ').map(&:to_i))
puts (1..n).reduce(0){|a,b| a+((s.include? b)?0:1)}

n = STDIN.gets.chomp.to_i
ary = STDIN.gets.chomp.split(' ').map{|x| x.to_i }
ary = ary[0...n]
mistaken = ary.size - ary.uniq.size
mistaken += ary.uniq.select{|x| x > n }.size
mistaken += ary.uniq.select{|x| x < 1 }.size
p mistaken

n = gets.to_i
a = gets.split.map(&:to_i)
p n - ((1..n).to_a&a).uniq.size

n = gets.to_i
a = gets.split.map(&:to_i)
b = Array.new(n){0}
m = 0

a.each do |i|
  if i <= n && b[i-1] == 0
    b[i-1] = 1
  else
    m += 1
  end
end

p m

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
require 'prime'
#require 'mathn'
require 'matrix'
require 'set'
include Math
#=================================

n=gets.to_i
data=gets.split.map(&:to_i)

hs=Hash.new(0)
data.each{|v| hs[v]+=1}

ans=0
n.times{|i|
	i+=1

	if hs[i]==0
		ans+=1
	end
}

puts ans

i = gets.to_i
puts i - gets.chomp.split().uniq.count { |x| x.to_i <= i }

n = gets.to_i
ar = gets.split(' ').map(&:to_i)
ar2 = (1..n).to_a
puts (ar2-ar).count

def main()
	n=gets.chomp.to_i
	sta=gets.chomp.split(" ").map{|i| i.to_i}
	sta=sta.uniq
	change=0
	for i in 1..n
		if !sta.include?(i)
			change+=1
		end
	end
	puts change
end
main()

n,k=gets.to_i,gets.split.map(&:to_i);ch=0;n.times {|x| k.include?(x+1) ?0:ch+=1};puts ch

n = gets.to_i
s = gets
a = s.split
b = [ ]
0.upto(n-1) {
	|i|
	a[i] = a[i].to_i
	b[a[i]] = 1
}
s = 0
0.upto(n-1) {
	|i|
	s = s + 1 if b[i+1] != 1
}
puts s

puts(((1..gets.to_i).to_a - gets.split.map { |x| x.to_i }).size)

#!/usr/bin/env ruby
n = gets.to_i
count = [false] * 5001
gets.split.each { |x|
    count[x.to_i] = true
}
result = n
1.upto(n) { |x|
    result -= 1 if count[x]
}
puts result

n = gets.to_i
a = gets.chomp.split(" ").map{|i| i.to_i}
b = []
dem = 0

(1..n).each do |i|
    b[i] = 0
end

(0..n-1).each do |i|
    if b[a[i]] == 0
        b[a[i]] = 1
        dem +=1
    end
end

puts (n-dem)

require 'set'
n = gets.chomp.to_i
a = gets.chomp.split(" ").map {|e| e.to_i}

set = {}
a.each do |e|
  if (1 <= e && e <= n)
    set[e] = 1
  end
end

puts n - set.keys.length

n = gets.chomp.to_i
puts gets.chomp.split.map(&:to_i).reduce(Array(1..n)) { |s, x| s - [x] }.length

n = gets.to_i
a = gets.split(' ').map(&:to_i).sort
res = 0
n.times do |i|
  if a[i] != i+1; res += 1; end;
end
p res

n = gets.to_i
m = gets.chomp.split(" ").collect! {|i| i}

puts n - m.uniq.size

n = gets.to_i
puts n - gets.split(' ').map{|i| i.to_i}.delete_if{|i| i > n}.size

gets()
d = Hash.new(0)
gets().split(' ').map(&:to_i).each do |e|
  d[e] += 1
end

ret = 0

d.each do |k,v|
  ret += v - 1
end

puts ret

gets()
d = Hash.new(0)
gets().split(' ').map(&:to_i).each do |e|
  d[e] += 1
end

ret = 0

d.each do |k,v|
  ret += d[k] - 1
end

puts ret

n = STDIN.gets.chomp.to_i
ary = STDIN.gets.chomp.split(' ').map{|x| x.to_i }
ary = ary[0...n]
p ary.size - ary.uniq.size

n = STDIN.gets.chomp.to_i
ary = STDIN.gets.chomp.split(' ').map{|x| x.to_i }
ary = ary[0...n]
mistaken = ary.size - ary.uniq.size
mistaken += ary.select{|x| x > n }.size
mistaken += ary.select{|x| x < 1 }.size
p mistaken

n = STDIN.gets.chomp.to_i
ary = STDIN.gets.chomp.split(' ')
ary = ary[0...n]
p ary.size - ary.uniq.size

n = gets.to_i
a = gets.split.map(&:to_i)
puts n - a.uniq.size

n = gets.to_i
a = gets.split.map(&:to_i)
b = Array.new(n){0}
m = 0

a.each do |i|
  if i > n ||b[i-1] == 0
    b[i-1] = 1
  else
    m += 1
  end
end

p m

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
require 'prime'
#require 'mathn'
require 'matrix'
require 'set'
include Math
#=================================

n=gets.to_i
data=gets.split.map(&:to_i)

hs=Hash.new(0)
data.each{|v| hs[v]+=1}

ans=0
n.times{|i|
	i+=1

	if hs[i]>1
		ans+=hs[i]-1
	end
}

puts ans

def main()
	n=gets.chomp.to_i
	sta=gets.chomp.split(" ").map{|i| i.to_i}
	sta=sta.sort
	change=0
	for i in 1..n
		if sta[i-1]!=i
			change+=1
		end
	end
	puts change
end
main()

n,k=gets.to_i,gets.split.map(&:to_i);ch=0;n.times {|x| k.include?(x) ?0:ch+=1};puts ch

n,k=gets.to_i,gets.split.map(&:to_i);ch=0;k=k.sort;n.times {|x| k[x]==x+1 ?0:ch+=1};puts ch

n = gets.to_i
s = gets
a = s.split
0.upto(n-1) {
	|i|
	a[i] = a[i].to_i
}
a = a.sort
s = 0
i = 0
while i < n
	s = s + (a[i]-i-1).abs
	i = i + 1
end
puts s

n = gets.to_i
s = gets
a = s.split
0.upto(n-1) {
	|i|
	a[i] = a[i].to_i
}
a = a.sort
s = 0
i = 0
while i < n
	s = s + 1 if a[i] != i + 1
	i = i + 1
end
puts s

require 'set'
n = gets.chomp.to_i
a = gets.chomp.split(" ").map {|e| e.to_i}

set = {}
a.each do |e|
  set[e] = 1
end

puts n - set.keys.length

n = gets.chomp.to_i
puts gets.chomp.split.map(&:to_i).reduce(Array(1..n)) { |s, x| s - [x]}

n = gets.chomp.to_i
gets.chomp.split.map(&:to_i).reduce(Array(1..n)) { |s, x| s - [x]}


Sasha and Dima want to buy two $$$n$$$-tier cakes. Each cake should consist of $$$n$$$ different tiers: from the size of $$$1$$$ to the size of $$$n$$$. Tiers should go in order from the smallest to the biggest (from top to bottom).They live on the same street, there are $$$2 \cdot n$$$ houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the $$$i$$$-th house you can buy a tier of the size $$$a_i$$$ ($$$1 \le a_i \le n$$$).Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: $$$1$$$, then $$$2$$$, then $$$3$$$ and so on up to $$$n$$$.Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly $$$1$$$.

The first line of the input contains an integer number $$$n$$$ — the number of tiers in each cake ($$$1 \le n \le 10^5$$$). The second line contains $$$2 \cdot n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is equal to the size of the tier, which can be bought in the $$$i$$$-th house. Remember that in each house you can buy only one tier. It is guaranteed that every number from $$$1$$$ to $$$n$$$ occurs in $$$a$$$ exactly two times.

Print one number  — the minimum distance that the guys have to walk in total to buy both cakes. Guys can be near same house at the same time. They begin near the first (leftmost) house. Each of the guys should buy $$$n$$$ tiers in ascending order of their sizes.

NoteIn the first example, the possible optimal sequence of actions is:  Sasha buys a tier of size $$$1$$$ near the $$$1$$$-st house ($$$a_1=1$$$);  Dima goes to the house $$$2$$$;  Dima buys a tier of size $$$1$$$ near the $$$2$$$-nd house ($$$a_2=1$$$);  Sasha goes to the house $$$4$$$;  Sasha buys a tier of size $$$2$$$ near the $$$4$$$-th house ($$$a_4=2$$$);  Sasha goes to the house $$$5$$$;  Sasha buys a tier of size $$$3$$$ near the $$$5$$$-th house ($$$a_5=3$$$);  Dima goes to the house $$$3$$$;  Dima buys a tier of size $$$2$$$ near the $$$3$$$-rd house ($$$a_3=2$$$);  Dima goes to the house $$$6$$$;  Dima buys a tier of size $$$3$$$ near the $$$6$$$-th house ($$$a_6=3$$$). So, Sasha goes the distance $$$3+1=4$$$, and Dima goes the distance $$$1+1+3=5$$$. In total, they cover a distance of $$$4+5=9$$$. You can make sure that with any other sequence of actions they will walk no less distance.

n = gets.to_i
a = gets.split.map(&:to_i)

map = {}
a.each_with_index do |s, i|
  map[s] ||= []
  map[s] << i
end

posns = [0,0]
total_dist = 0
(1..n).each do |tier|
  destns = map[tier]
  dist = [
    (posns[0]-destns[0]).abs + (posns[1]-destns[1]).abs,
    (posns[0]-destns[1]).abs + (posns[1]-destns[0]).abs,
  ].min
  total_dist += dist
  posns = destns
end

p total_dist


Rahul and Tina are looking forward to starting their new year at college. As they enter their new classroom, they observe the seats of students are arranged in a $$$n \times m$$$ grid. The seat in row $$$r$$$ and column $$$c$$$ is denoted by $$$(r, c)$$$, and the distance between two seats $$$(a,b)$$$ and $$$(c,d)$$$ is $$$|a-c| + |b-d|$$$. As the class president, Tina has access to exactly $$$k$$$ buckets of pink paint. The following process occurs.   First, Tina chooses exactly $$$k$$$ seats in the classroom to paint with pink paint. One bucket of paint can paint exactly one seat.  After Tina has painted $$$k$$$ seats in the previous step, Rahul chooses where he sits. He will not choose a seat that has been painted pink due to his hatred of the colour pink.  After Rahul has chosen his seat, Tina chooses a seat for herself. She can choose any of the seats, painted or not, other than the one chosen by Rahul. Rahul wants to choose a seat such that he sits as close to Tina as possible. However, Tina wants to sit as far away from Rahul as possible due to some complicated relationship history that we couldn't fit into the statement!Now, Rahul wonders for $$$k = 0, 1, \dots, n \cdot m - 1$$$, if Tina has $$$k$$$ buckets of paint, how close can Rahul sit to Tina, if both Rahul and Tina are aware of each other's intentions and they both act as strategically as possible? Please help satisfy Rahul's curiosity!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \cdot m \leq 10^5$$$) — the number of rows and columns of seats in the classroom. The sum of $$$n \cdot m$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, output $$$n \cdot m$$$ ordered integers — the distance between Rahul and Tina if both of them act optimally for every $$$k \in [0, n \cdot m - 1]$$$.

NoteOne possible sequence of choices for the first testcase where Tina has $$$k=3$$$ buckets of paints is as follows.Tina paints the seats at positions $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ with pink paint. Rahul chooses the seat at $$$(3, 1)$$$ after which Tina chooses to sit at $$$(1, 3)$$$. Therefore, the distance between Tina and Rahul is $$$|3-1| + |1-3| = 4$$$, and we can prove that this is indeed the minimum possible distance under the given constraints. There may be other choices of seats which lead to the same answer as well.For $$$k=0$$$ in the first test case, Rahul can decide to sit at $$$(2, 2)$$$ and Tina can decide to sit at $$$(4, 3)$$$ so the distance between them would be $$$|2 - 4| + |2 - 3| = 3$$$.Below are pictorial representations of the $$$k=3$$$ and $$$k=0$$$ cases for the first test case.  A possible seating arrangement for $$$k=3$$$.  A possible seating arrangement for $$$k=0$$$.

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  corners = [[1, 1], [1, m], [n, 1], [n, m]]
  puts(1.upto(n).flat_map do |i|
    1.upto(m).map do |j|
      corners.map { |ii, jj| (ii - i).abs + (jj - j).abs }.max
    end
  end.sort.join(" "))
end


Polycarp is reading a book consisting of $$$n$$$ pages numbered from $$$1$$$ to $$$n$$$. Every time he finishes the page with the number divisible by $$$m$$$, he writes down the last digit of this page number. For example, if $$$n=15$$$ and $$$m=5$$$, pages divisible by $$$m$$$ are $$$5, 10, 15$$$. Their last digits are $$$5, 0, 5$$$ correspondingly, their sum is $$$10$$$.Your task is to calculate the sum of all digits Polycarp has written down.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The following $$$q$$$ lines contain queries, one per line. Each query is given as two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^{16}$$$) — the number of pages in the book and required divisor, respectively.

For each query print the answer for it — the sum of digits written down by Polycarp.

q = readline.to_i

q.times do
  n, m = readline.split.map(&:to_i)
  ans = 0
  l = []
  c = m
  until l.include?(c % 10)
    l << c % 10
    c += m
  end

  k = l.size

  l.each_with_index do |v, i|
    ans += (n / (m * k)) * v
    n % (m * k) >= (i + 1) * m && ans += v
  end

  puts ans
end

def calc(b, range)
	range.sum { |i| b * i % 10 }
end

gets.to_i.times do
	a, b = gets.split.map(&:to_i)
	puts calc(b, 0...10) * (a / b / 10) + calc(b, 0..a / b % 10)
end

# coding: utf-8

q = gets.to_i
q.times {
    n, m = gets.split.map(&:to_i)
    sum = 0
    i = 1
    ten_round = []
    for i in 1..10
        x = m*i
        ten_round << x%10
    end
    # n = q*m + r
    q = n / (m*10)
    r = n % (m*10)
    sum = ten_round.reduce(:+) * q
    # take care of 'r'
    for i in 1..10
        x = m*i
        if x <= r
            sum += ten_round[i-1]
        else
            break
        end
    end
    puts sum
}

gets.strip.to_i.times do
  n, m = gets.strip.split(' ').map(&:to_i)
  divs = (1..10).to_a.map { |i| (i * m) }
  last = (1..10).to_a.map { |i| (i * m) % 10 }

  res1 = (last.inject(:+) * (n / divs[-1]))
  res2 = divs.select { |d| d <= (n % divs[-1]) }.map { |x| x % 10 }.inject(:+)
  puts (res1 || 0) + (res2 || 0)
end

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  cnt = n / m
  d = []
  (0..9).each do |i|
    d << (((i + 1) * m) % 10)
  end
  sum = 0
  (0...cnt % 10).each do |i|
    sum += d[i]
  end
  sum2 = 0
  (0..9).each do |i|
    sum2 += d[i]
  end
  sum += cnt / 10 * sum2
  puts sum
end

qq = gets.to_i
nm =
  qq.times.map do |q|
    gets.split.map(&:to_i)
  end
nm.each do |nn,mm|
  ans = 0
  # 10倍でループする
  num10 = 0
  1.upto(9) do |n|
    num10 += (mm*n) % 10
  end

  div = nn / (mm*10)
  ans += div * num10

  mod = nn % (mm*10)
  a = mm
  while a <= mod do
    ans += a%10
    a+=mm
  end

  puts ans
end