You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x < n$$$ and $$$1 \le y < m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.

If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.

n, m = gets.split.map(&:to_i)
aa = []
not_zero = false
n.times do|_x|
   arr = gets.split
   aa << arr
   unless not_zero
     not_zero=true if arr.include?("1")
   end
end

unless not_zero
  puts 0
  exit
end

changed = Array.new(n,"0").map{Array.new(m,"0")}
ans = []

0.upto(n-1-1) do |i|
  0.upto(m-1-1) do |j|
    if aa[i][j]=="1" && aa[i][j+1]=="1" && aa[i+1][j]=="1" && aa[i+1][j+1]=="1"
      ans << "#{i+1} #{j+1}"
      changed[i][j]="1"
      changed[i][j+1]="1"
      changed[i+1][j]="1"
      changed[i+1][j+1]="1"
    end
    #d
    #puts changed.to_s
  end

  unless aa[i] == changed[i]
    # できない
    puts -1
    exit
  end
  if i==n-2 && aa[n-1] != changed[n-1]
    # できない
    puts -1
    exit
  end
end

puts("#{ans.size}\n" + ans.join("\n"))

n,m = gets.split.map(&:to_i)
grid = []
n.times do
  grid << gets.split.map(&:to_i)
end
target = Array.new(n){[0]*m}
ans = []
(n-1).times do |i|
  (m-1).times do |j|
    if grid[i][j] == 1 && grid[i+1][j] == 1 && grid[i][j+1] == 1 && grid[i+1][j+1] == 1
      2.times do |x|
        2.times do |y|
          target[i+x][j+y] = 1
        end
      end
      ans << [i+1,j+1]
    end
  end
end
flg = true
n.times do |i|
  m.times do |j|
    flg = false if grid[i][j] != target[i][j]
  end
end
if flg
  p ans.length
  ans.each do |a|
    puts a.join(" ")
  end
else
  p -1
end

# http://codeforces.com/contest/1207/problem/B

def board
  nm = get_each gets.chomp
  n, m = nm[0], nm[1]
  a = Array.new
  color = Array.new(n) { Array.new(m, 0)}

  n.times do
    row = get_each(gets.chomp)
    a << row
  end

  paint = Array.new

  0.upto(n-2) do |r|
    0.upto(m-2) do |c|
      if 4 == (a[r][c] + a[r+1][c] + a[r][c+1] + a[r+1][c+1])
        coloring(color, r, c)
        paint << [r, c]
      end
    end
  end

  if !array_match(a, color)
    puts -1
    return
  elsif paint.empty?
    puts 0
    return
  end

  puts paint.count
  0.upto(paint.size-1) do |i|
    print "#{paint[i][0]+1} #{paint[i][1]+1}\n"
  end
end

def array_match(arr1, arr2)
  0.upto(arr1.size-1) do |r|
    0.upto(arr1[0].size-1) do |c|
      return false unless arr1[r][c] == arr2[r][c]
    end
  end
  true
end

def coloring(color, r, c)
  color[r][c], color[r+1][c], color[r][c+1], color[r+1][c+1] = 1, 1, 1, 1
end

def get_each(str)
  arr = Array.new
  num = 0
  str.each_char do |e|
    if e == ' '
      arr << num
      num = 0
    else
      num = num * 10 + e.to_i
    end
  end
  arr << num #unless num.zero?
  arr
end

board

def board
  nm = get_each gets.chomp
  n, m = nm[0], nm[1]
  a = Array.new
  color = Array.new(n) { Array.new(m, 0)}

  n.times do
    row = get_each(gets.chomp)
    a << row
  end

  paint = Array.new

  0.upto(n-2) do |r|
    0.upto(m-2) do |c|
      if 4 == (a[r][c] + a[r+1][c] + a[r][c+1] + a[r+1][c+1])
        coloring(color, r, c)
        paint << [r, c]
      end
    end
  end

  if !array_match(a, color)
    puts -1
    return
  elsif paint.empty?
    puts 0
    return
  end

  puts paint.count
  0.upto(paint.size-1) do |i|
    print "#{paint[i][0]} #{paint[i][1]}\n"
  end
end

def array_match(arr1, arr2)
  0.upto(arr1.size-1) do |r|
    0.upto(arr1[0].size-1) do |c|
      return false unless arr1[r][c] == arr2[r][c]
    end
  end
  true
end

def coloring(color, r, c)
  color[r][c], color[r+1][c], color[r][c+1], color[r+1][c+1] = 1, 1, 1, 1
end

def get_each(str)
  arr = Array.new
  num = 0
  str.each_char do |e|
    if e == ' '
      arr << num
      num = 0
    else
      num = num * 10 + e.to_i
    end
  end
  arr << num #unless num.zero?
  arr
end

board

$visited = nil
$color = nil

def board
  nm = get_each gets.chomp
  n = nm[0]
  m = nm[1]
  a = Array.new
  $color = Array.new(n) { Array.new(m, 0)}
  $visited = Array.new(n) { Array.new(m, 0) }

  n.times do
    row = get_each(gets.chomp)
    a << row
  end
  coord = start_coord(a, n, m)
  if coord.empty?
    puts 0
    return
  end
  result = collect_result(coord, a)
  if result == -1 || !color_match(a)
    puts -1
    return
  end
  puts result.count
  0.upto(result.size-1) do |i|
    print "#{result[i][0]} #{result[i][1]}\n"
  end
end

def color_match(arr)
  0.upto(arr.size-1) do |r|
    0.upto(arr[0].size-1) do |c|
      return false unless $color[r][c] == arr[r][c]
    end
  end
  true
end

def start_coord(arr, n, m)
  0.upto(n-1) do |r|
    0.upto(m-1) do |c|
      return [r,c] if arr[r][c] == 1
    end
  end
  []
end

def collect_result(coord, a)
  result = Array.new
  q = Array.new
  r, c = coord
  q << [coord]
  i = 4
  until q.empty? do
    point = q.shift.flatten.flatten
    r, c = point[0], point[1]
    coloring(r, c)
    $visited[r][c] = 1
    result << [r+1, c+1]
    ways = way_to_go(a, r, c)
    until ways.empty? do # max 4
      var = ways.shift
      next_r = r + var[0]
      next_c = c + var[1]
      q << [next_r, next_c] if $visited[next_r][next_c].zero?
    end
    i -= 1
    break if i.zero?
  end
  result
end

def coloring(r, c)
  $color[r][c], $color[r+1][c], $color[r][c+1], $color[r+1][c+1] = 1, 1, 1, 1
end

def way_to_go(arr, r, c)
  ways = Array.new
  if (r+1) < arr.size && $visited[r+1][c].zero? && block_check(arr, r+1, c)
    ways << [1,0]
  elsif (r-1) >= 0 && $visited[r-1][c].zero? && block_check(arr, r-1, c)
    ways << [-1,0]
  elsif (c+1) < arr[0].size && $visited[r][c+1].zero? && block_check(arr, r, c+1)
    ways << [0,1]
  elsif (c-1) >= 0 && $visited[r][c-1].zero? && block_check(arr, r, c-1)
    ways << [0,-1]
  end
  ways
end

def block_check(arr, r, c)
  return false unless r >= 0 && (r+1) < arr.size && c >= 0 && (c+1) < arr[0].size
  unless 4 == ($color[r][c] + $color[r+1][c] + $color[r][c+1] + $color[r+1][c+1])
    return 4 == (arr[r][c] + arr[r+1][c] + arr[r][c+1] + arr[r+1][c+1])
  end
  false
end

def get_each(str)
  arr = Array.new
  num = 0
  str.each_char do |e|
    if e == ' '
      arr << num
      num = 0
    else
      num = num * 10 + e.to_i
    end
  end
  arr << num #unless num.zero?
  arr
end

board

$visited = nil
$color = nil

def board
  nm = get_each gets.chomp
  n = nm[0]
  m = nm[1]
  a = Array.new
  $color = Array.new(n) { Array.new(m, 0)}
  $visited = Array.new(n) { Array.new(m, 0) }

  n.times do
    row = get_each(gets.chomp)
    a << row
  end
  coord = start_coord(a, n, m)
  if coord.empty?
    puts 0
    return
  end
  result = collect_result(coord, a)
  if result == -1 || !color_match(a)
    puts -1
    return
  end
  puts result.count
  0.upto(result.size-1) do |i|
    print "#{result[i][0]} #{result[i][1]}\n"
  end
end

def color_match(arr)
  0.upto(arr.size-1) do |r|
    0.upto(arr[0].size-1) do |c|
      return false unless $color[r][c] == arr[r][c]
    end
  end
  true
end

def start_coord(arr, n, m)
  0.upto(n-1) do |r|
    0.upto(m-1) do |c|
      return [r,c] if arr[r][c] == 1
    end
  end
  []
end

def collect_result(coord, a)
  result = Array.new
  q = Array.new
  r, c = coord
  q << [coord]
  until q.empty? do
    point = q.shift.flatten.flatten
    r, c = point[0], point[1]
    coloring(r, c)
    $visited[r][c] = 1
    result << [r+1, c+1]
    ways = way_to_go(a, r, c)
    until ways.empty? do # max 4
      var = ways.shift
      next_r = r + var[0]
      next_c = c + var[1]
      q << [next_r, next_c] if $visited[next_r][next_c].zero?
    end
  end
  result
end

def coloring(r, c)
  $color[r][c], $color[r+1][c], $color[r][c+1], $color[r+1][c+1] = 1, 1, 1, 1
end

def way_to_go(arr, r, c)
  ways = Array.new
  if (r+1) < arr.size && $visited[r+1][c].zero? && block_check(arr, r+1, c)
    ways << [1,0]
  elsif (r-1) >= 0 && $visited[r-1][c].zero? && block_check(arr, r-1, c)
    ways << [-1,0]
  elsif (c+1) < arr[0].size && $visited[r][c+1].zero? && block_check(arr, r, c+1)
    ways << [0,1]
  elsif (c-1) >= 0 && $visited[r][c-1].zero? && block_check(arr, r, c-1)
    ways << [0,-1]
  end
  ways
end

def block_check(arr, r, c)
  return false unless r >= 0 && (r+1) < arr.size && c >= 0 && (c+1) < arr[0].size
  unless 4 == ($color[r][c] + $color[r+1][c] + $color[r][c+1] + $color[r+1][c+1])
    return 4 == (arr[r][c] + arr[r+1][c] + arr[r][c+1] + arr[r+1][c+1])
  end
  false
end

def get_each(str)
  arr = Array.new
  num = 0
  str.each_char do |e|
    if e == ' '
      arr << num
      num = 0
    else
      num = num * 10 + e.to_i
    end
  end
  arr << num #unless num.zero?
  arr
end

board

$visited = nil
$color = nil

def board
  nm = get_each gets.chomp
  n = nm[0]
  m = nm[1]
  a = Array.new
  $color = Array.new(n) { Array.new(m, 0)}
  $visited = Array.new(n) { Array.new(m, 0) }

  n.times do
    row = get_each(gets.chomp)
    a << row
  end
  coord = start_coord(a, n, m)
  if coord.empty?
    puts 0
    return
  end
  result = collect_result(coord, a)
  if result == -1 || !color_match(a)
    puts -1
    return
  end
  puts result.count
  0.upto(result.size-1) do |i|
    print "#{result[i][0]} #{result[i][1]}\n"
  end
end

def color_match(arr)
  0.upto(arr.size-1) do |r|
    0.upto(arr[0].size-1) do |c|
      return false unless $color[r][c] == arr[r][c]
    end
  end
  true
end

def start_coord(arr, n, m)
  0.upto(n-1) do |r|
    0.upto(m-1) do |c|
      return [r,c] if arr[r][c] == 1
    end
  end
  []
end

def collect_result(coord, a)
  result = Array.new
  q = Array.new
  r, c = coord
  coloring(r, c)
  $visited[r][c] = 1
  q << [coord]
  i = 4
  until q.empty? do
    point = q.shift.flatten.flatten
    r, c = point[0], point[1]
    result << [r+1, c+1]
    ways = way_to_go(a, r, c)
    until ways.empty? do # max 4
      var = ways.shift
      next_r = r + var[0]
      next_c = c + var[1]
      q << [next_r, next_c] if $visited[next_r][next_c].zero?
      coloring(next_r, next_c)
      $visited[next_r][next_c] = 1
    end
    i -= 1
    break if i.zero?
  end
  result
end

def coloring(r, c)
  $color[r][c], $color[r+1][c], $color[r][c+1], $color[r+1][c+1] = 1, 1, 1, 1
end

def way_to_go(arr, r, c)
  ways = Array.new
  if (r+1) < arr.size && $visited[r+1][c].zero? && block_check(arr, r+1, c)
    ways << [1,0]
  elsif (r-1) >= 0 && $visited[r-1][c].zero? && block_check(arr, r-1, c)
    ways << [-1,0]
  elsif (c+1) < arr[0].size && $visited[r][c+1].zero? && block_check(arr, r, c+1)
    ways << [0,1]
  elsif (c-1) >= 0 && $visited[r][c-1].zero? && block_check(arr, r, c-1)
    ways << [0,-1]
  end
  ways
end

def block_check(arr, r, c)
  return false unless r >= 0 && (r+1) < arr.size && c >= 0 && (c+1) < arr[0].size
  unless 4 == ($color[r][c] + $color[r+1][c] + $color[r][c+1] + $color[r+1][c+1])
    return 4 == (arr[r][c] + arr[r+1][c] + arr[r][c+1] + arr[r+1][c+1])
  end
  false
end

def get_each(str)
  arr = Array.new
  num = 0
  str.each_char do |e|
    if e == ' '
      arr << num
      num = 0
    else
      num = num * 10 + e.to_i
    end
  end
  arr << num #unless num.zero?
  arr
end

board

n, m = gets.split.map(&:to_i)
aa = []
not_zero = false
n.times do|_x|
   arr = gets.split
   aa << arr
   unless not_zero
     not_zero=true if arr.include?("1")
   end
end

unless not_zero
  puts 0
  exit
end

changed = Array.new(n,"0").map{Array.new(m,"0")}
ans = []

0.upto(n-1-1) do |i|
  0.upto(m-1-1) do |j|
    if aa[i][j]=="1" && aa[i][j+1]=="1" && aa[i+1][j]=="1" && aa[i+1][j+1]=="1"
      ans << "#{i+1} #{j+1}"
      changed[i][j]="1"
      changed[i][j+1]="1"
      changed[i+1][j]="1"
      changed[i+1][j+1]="1"
    end
    #d
    #puts changed.to_s
  end

  unless aa[i] == changed[i]
    # できない
    puts -1
    exit
  end
end

puts("#{ans.size}\n" + ans.join("\n"))

n, m = gets.split.map(&:to_i)
aa = []
not_zero = false
n.times do|_x|
   arr = gets.split
   aa << arr
   unless not_zero
     not_zero=true if arr.include?("1")
   end
end

unless not_zero
  puts 0
  exit
end

changed = Array.new(n).map{Array.new(m)}
ans = []

0.upto(n-1-1) do |i|
  0.upto(m-1-1) do |j|
    if aa[i][j]=="1" && aa[i][j+1]=="1" && aa[i+1][j]=="1" && aa[i+1][j+1]=="1"
      ans << "#{i+1} #{j+1}"
      changed[i][j]=1
      changed[i+1][j]=1
      changed[i+1][j+1]=1
    elsif changed[i][j]==1
    else
      # できない
      puts -1
      exit
    end
    #d
    #puts changed.to_s
  end
end

puts("#{ans.size}\n" + ans.join("\n"))


Each day in Berland consists of $$$n$$$ hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence $$$a_1, a_2, \dots, a_n$$$ (each $$$a_i$$$ is either $$$0$$$ or $$$1$$$), where $$$a_i=0$$$ if Polycarp works during the $$$i$$$-th hour of the day and $$$a_i=1$$$ if Polycarp rests during the $$$i$$$-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.

The first line contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — number of hours per day. The second line contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i=0$$$ if the $$$i$$$-th hour in a day is working and $$$a_i=1$$$ if the $$$i$$$-th hour is resting. It is guaranteed that $$$a_i=0$$$ for at least one $$$i$$$.

Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.

NoteIn the first example, the maximal rest starts in last hour and goes to the first hour of the next day.In the second example, Polycarp has maximal rest from the $$$4$$$-th to the $$$5$$$-th hour.In the third example, Polycarp has maximal rest from the $$$3$$$-rd to the $$$5$$$-th hour.In the fourth example, Polycarp has no rest at all.

N = gets.to_i
s = gets.split.join
s += s
p s.scan(/1+/).map{ |s| s.size }.max || 0

n = gets.to_i
a = gets.split.map(&:to_i)
ans = 0
c = 0
a += a
(n*2).times do |i|
    if a[i] == 1
        c += 1
        ans = c if ans < c
    else
        c = 0
    end
end
puts [ans,n].min

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
a = gets.split.map(&:to_i) # "0" works "1" rests
doublea = a*2 # simulate it with 'mod' operator in other language (looping)
longest_rests = 0
rests = 0
doublea.each { |flag|
    if flag == 0 # works
        rests = 0
    else
        rests += 1

        if rests > longest_rests
            longest_rests = rests
        end
    end
}

puts longest_rests

gets
r=(gets*2).tr('
','').gsub(/1+/).map(&:size).max
p r==nil ?0:r

gets
r=(gets*2).tr('
','').split(?0).map(&:size).max
p r==nil ?0:r

quantidade=gets
numeros=gets
vetordenumeros=numeros.split
vetordenumeros=vetordenumeros+vetordenumeros
i=0
contador=0
for numero in vetordenumeros do
    if numero.to_i==1
        i+=1
    else
        if contador<i
            contador=i
        end
        i=0
    end
end
puts contador

N = gets.to_i
s = gets.split.join
s += s[0]
p s.scan(/1+/).map{ |s| s.size }.max || 0


A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).

The first and only line consists of a string $$$S$$$ ($$$ 1 \le |S| \le 5\,000 $$$). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.

Print "YES" or "NO", according to the condition.

NoteConsider first example: the number of 'c' is equal to the number of 'a'. Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct.Consider third example: the number of 'c' is equal to the number of 'b'.

s = gets.chomp
order = s =~ /\Aa+b+c+$/
cntC = s.count('c')
count = cntC == s.count('a') || cntC == s.count('b')
puts order && count ? 'YES' : 'NO'
puts order


Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks: The try operator. It opens a new try-catch-block.  The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.Let's suggest that as a result of using some throw operator the program created an exception of type a. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception".To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.Your task is: given a program in VPL, determine, what message will be displayed on the screen.

The first line contains a single integer: n (1 ≤ n ≤ 105) the number of lines in the program. Next n lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces. The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark. The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols. Length of any line in the input file does not exceed 50 symbols.

Print the message the screen will show after the given program is executed.

8
try
    try
        throw ( AE )
    catch ( BE, "BE in line 3")

    try
    catch(AE, "AE in line 5")
catch(AE,"AE somewhere")

8
try
    try
        throw ( AE )
    catch ( AE, "AE in line 3")

    try
    catch(BE, "BE in line 5")
catch(AE,"AE somewhere")

8
try
    try
        throw ( CE )
    catch ( BE, "BE in line 3")

    try
    catch(AE, "AE in line 5")
catch(AE,"AE somewhere")

AE somewhere
AE in line 3
Unhandled Exception

NoteIn the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE.In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere")In the third sample there is no blocks that can be activated by an exception of type CE.

#!/usr/bin/env ruby
# encoding: utf-8
n=gets.to_i

thlist = []
thid = []
trylist = []
flag=0

n.times do |id|
  str=gets.strip!
  next if flag == 1
  if /^try$/ =~ str
    trylist << id
  elsif /throw/ =~ str
    /(?<=\()\s*\w+\s*(?=\))/ =~ str
    thlist << $&.strip
    # puts thlist.last
    thid << id
  elsif /catch/ =~ str
    /(?<=\()\s*\w+\s*(?=,)/ =~ str
    if (pos=thlist.index($&.strip))!=nil && thid[pos] > trylist.last
      /(?<=\").+(?=\")/ =~ str
      puts $&
      flag=1
    end
    trylist.pop
  end
end

puts "Unhandled Exception" if flag == 0

#!/usr/bin/env ruby
# encoding: utf-8
n=gets.to_i

thlist = []
thid = []
trylist = []
flag=0

n.times do |id|
  str=gets.strip!
  next if flag == 1
  if /^try$/ =~ str
    trylist << id
  elsif /throw/ =~ str
    /(?<=\()\s*\w+\s*(?=\))/ =~ str
    thlist << $&.strip
    thid << id
  elsif /catch/ =~ str
    /(?<=\()\s*\w+\s*(?=,)/ =~ str
    if (pos=thlist.index($&.strip))!=nil && thid[pos] > trylist.last
      /(?<=\").+(?=\")/ =~ str
      puts $&
      flag=1
    end
    trylist.pop
  end
end

puts "Unhandled Exception" if flag == 0

#!/usr/bin/ruby -w

N = gets.strip.to_i
level = 0
ex = ''
ex_level = 0
dummy = 0

N.times do |i|
  line = gets
  next if not line
  line.strip!

  if line =~ /try$/
    level += 1
    dummy += 1 if ex != ''
    #puts "#{level}, #{dummy}, try, #{ex}"
  elsif line =~ /throw\s*\((.+?)\)/
    #puts "#{level}, #{dummy}, throw #{$1.strip}"
    ex = $1.strip
    ex_level = level
  elsif line =~ /catch\s*\((.+?)\s*,\s*"(.+?)"\s*\)/
    #puts "#{level}, #{dummy}, #{$2}"
    if dummy == 0 && level <= ex_level && ex == $1.strip
      puts $2
      exit
    end
    level -= 1
    dummy -= 1 if dummy > 0
  end
end

puts "Unhandled Exception"

#!/usr/bin/ruby -w

N = gets.strip.to_i
level = 0
ex = ''
ex_level = 0
dummy = 0

N.times do |i|
  line = gets
  next if not line
  line.strip!

  if line =~ /try$/
    level += 1
    dummy += 1 if ex != ''
    #puts "#{level}, #{dummy}, try, #{ex}"
  elsif line =~ /throw\s*\((.+?)\)/
    #puts "#{level}, throw #{$1.strip}"
    ex = $1.strip
    ex_level = level
  elsif line =~ /catch\s*\((.+?)\s*,\s*"(.+?)"\s*\)/
    #puts "#{level}, #{dummy}, #{$2}"
    if dummy == 0 && level <= ex_level && ex == $1.strip
      puts $2
      exit
    end
    level -= 1
    dummy -= 1 if dummy > 0
  end
end

puts "Unhandled Exception"

n = gets.to_i
a = []
for i in (1..n) do
  a[i]=gets
end

thr = /(\s*)throw(.*)/
thr_s = /\s*throw\s*\(\s*([a-zA-Z]+)/
try = /(\s*)try(\s*)/
cat = /(\s*)catch(.*)/
cat_s = /\s*catch\s*\(\s*([a-zA-Z]+).+"(.+)"/

for i in (1..n) do
  r = a[i]=~thr
  if r==0 then break end
end
isc = a[i].match(thr_s)[1]
c = 0
for k in (i+1..n) do
  r = a[k]=~try
  if r==0 then c+=1 end
  r = a[k]=~cat
  if r==0 then
    if c==0 then
      z=a[k].match(cat_s)
      if isc==z[1] then
        puts z[2]
        exit
      end
    else
      c-=1
    end
  end
end
puts 'Unhandled Exception'

#!/usr/bin/ruby

n = $stdin.gets.to_i
lines = []
n.times do
  s = $stdin.gets.chomp.strip
  if s == 'try' || s.start_with?('catch') || s.start_with?('throw')
    lines << s
  end
end

exn = {:level => -1, :type => nil}
level = 0
while not lines.empty?
  s = lines.shift
  case s
  when 'try'
    level += 1
  when /\Acatch\s*\(\s*([A-Za-z]+)\s*,\s*"([^"]+)"\s*\)\z/
    type = $1
    mes = $2
    if level == exn[:level] && type == exn[:type]
      puts mes
      exit 0
    end
    if level == exn[:level]
      exn[:level] -= 1
    end
    level -= 1
  when/\Athrow\s*\(\s*([A-Za-z]+)\s*\)\z/
    exn[:level] = level
    exn[:type] = $1
  end
end
puts 'Unhandled Exception'

#!/usr/bin/env ruby
n = gets.chomp.to_i
stack = []
exception = nil
n.times do |i|
    line = gets.chomp.strip
    next if line.empty?

    #puts line
    if line == "try"
        stack.push({type: "try", line: i})
        #puts "try"
    elsif line.start_with?("throw")
        exception = line.split(/\(|\)/).last.strip
        stack.push({type: :throw, exception: exception})
        #puts throw_type
    elsif line.start_with?("catch")
        catch_type = line.match(/\(\s*(\w+)/)[1].strip
        message = line.match(/,\s*("[^"]*")\s*\)/)[1]
        x = stack.last
        stack.pop
        if x[:type] == :throw
            stack.pop
            if x[:exception] == catch_type
                puts message[1...-1]
            else
                stack.push(x)
            end
        end
        #puts "#{catch_type} -> #{message}"
    end
end
unless stack.empty?
    puts "Unhandled Exception"
end

#!/usr/bin/env ruby
# encoding: utf-8
n=gets.to_i

thlist = []
thid = []
trylist = []
flag=0

n.times do |id|
  str=gets.strip!
  next if flag == 1
  if /try/ =~ str
    trylist << id
  elsif /throw/ =~ str
    /(?<=\()\s*\w+\s*(?=\))/ =~ str
    thlist << $&.strip
    thid << id
  elsif /catch/ =~ str
    /(?<=\()\s*\w+\s*(?=,)/ =~ str
    if (pos=thlist.index($&.strip))!=nil && thid[pos] > trylist.last
        /(?<=\").+(?=\")/ =~ str
      puts $&
      flag=1
    end
    trylist.pop
  end
end

puts "Unhandled Exception" if flag == 0

#!/usr/bin/ruby -w

N = gets.strip.to_i
level = 0
ex = ''
ex_level = 0
dummy = 0

N.times do |i|
  line = gets
  next if not line
  line.strip!

  if line =~ /try/
    level += 1
    dummy += 1 if ex != ''
    #puts "#{level}, #{dummy}, try, #{ex}"
  elsif line =~ /throw\s*\((.+?)\)/
    #puts "#{level}, throw #{$1.strip}"
    ex = $1.strip
    ex_level = level
  elsif line =~ /catch\s*\((.+?)\s*,\s*"(.+?)"\s*\)/
    #puts "#{level}, #{dummy}, #{$2}"
    if dummy == 0 && level <= ex_level && ex == $1.strip
      puts $2
      exit
    end
    level -= 1
    dummy -= 1 if dummy > 0
  end
end

puts "Unhandled Exception"

n = gets.to_i
a = []
for i in (1..n) do
  a[i]=gets
end

for i in (1..n) do
  if a[i]=~(/(\s*)throw(.*)/) then break end
end
isc = a[i].match(/\s*throw\s*\(\s*([a-zA-Z]+)/)[1]
c = 0
for k in (i+1..n) do
  if a[k]=~(/(\s*)try(\s*)/) then c+=1 end
  if a[k]=~(/(\s*)catch(.*)/) then
    if c==0 then
      z=a[k].match(/\s*catch\s*\(\s*([a-zA-Z]+).+"(.+)"/)
      if isc==z[1] then
        puts z[2]
        exit
      end
    else
      c-=1
    end
  end
end
puts 'Unhandled Exception'

#!/usr/bin/ruby

n = $stdin.gets.to_i
lines = []
n.times do
  s = $stdin.gets.chomp.strip
  if s == 'try' || s.start_with?('catch') || s.start_with?('throw')
    lines << s
  end
end

def parse(lines)
  s = lines.shift
  if s == 'try'
    bodies = []
    while not lines[0].start_with?('catch')
      bodies << parse(lines)
    end
    c = lines.shift
    m = c.match(/\Acatch\s*\(\s*([A-Za-z]+)\s*,\s*"([^"]+)"\s*\)\z/)
    {:catch => {:type => m[1], :mes => m[2], :bodies => bodies} }
  else
    m = s.match(/\Athrow\s*\(\s*([A-Za-z]+)\s*\)\z/)
    {:throw => m[1] }
  end
end

tree = parse lines

def solve(t)
  if c = t[:catch]
    exn = nil
    c[:bodies].each do |b|
      exn = solve b
      break if exn
    end
    if exn && exn == c[:type]
      puts c[:mes]
      exit 0
    end
    exn
  else
    t[:throw]
  end
end
solve tree
puts 'Unhandled Exception'

#!/usr/bin/ruby

n = $stdin.gets.to_i
lines = []
n.times do
  s = $stdin.gets.chomp.strip
  if s == 'try' || s.start_with?('catch') || s.start_with?('throw')
    lines << s
  end
end

def parse(lines)
  if not lines.empty?
    s = lines.shift
    if s == 'try'
      bodies = []
      while lines[0] !~ /\Acatch/
        bodies << parse(lines)
      end
      c = lines.shift
      m = c.match(/\Acatch\s*\(\s*([A-Za-z]+)\s*,\s*"([^"]+)"/)
      {:catch => {:type => m[1], :mes => m[2], :bodies => bodies} }
    else
      m = s.match(/\Athrow\s*\(\s*([A-Za-z]+)\s*\)/)
      {:throw => m[1] }
    end
  end
end

tree = parse lines

def solve(t)
  if c = t[:catch]
    exn = nil
    c[:bodies].each do |b|
      exn = solve b
      break if exn
    end
    if exn && exn == c[:type]
      puts c[:mes]
      exit 0
    end
    exn
  else
    t[:throw]
  end
end
solve tree
puts 'Unhandled Exception'

#!/usr/bin/ruby

n = $stdin.gets.to_i
lines = []
n.times do
  s = $stdin.gets.strip
  if s == 'try' || s.start_with?('catch') || s.start_with?('throw')
    lines << s
  end
end

tree = {}
def parse(lines)
  if not lines.empty?
    s = lines.shift
    if s == 'try'
      bodies = []
      while lines[0] !~ /\Acatch/
        bodies << parse(lines)
      end
      c = lines.shift
      m = c.match(/\Acatch\s*\(\s*([A-Za-z]+)\s*,\s*"([^"]+)"/)
      {:catch => {:type => m[1], :mes => m[2], :bodies => bodies} }
    else
      m = s.match(/\Athrow\s*\(\s*([A-Za-z]+)\s*\)/)
      {:throw => m[1] }
    end
  end
end

tree = parse lines

def solve(t)
  if c = t[:catch]
    exn = nil
    c[:bodies].each do |b|
      a = solve b
      if a
        exn = a
      end
    end
    if exn && exn == c[:type]
      puts c[:mes]
      exit 0
    end
    exn
  else
    t[:throw]
  end
end
solve tree
puts 'Unhandled Exception'


Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).For any integer $$$k$$$ and positive integer $$$n$$$, let $$$k\bmod n$$$ denote the remainder when $$$k$$$ is divided by $$$n$$$. More formally, $$$r=k\bmod n$$$ is the smallest non-negative integer such that $$$k-r$$$ is divisible by $$$n$$$. It always holds that $$$0\le k\bmod n\le n-1$$$. For example, $$$100\bmod 12=4$$$ and $$$(-1337)\bmod 3=1$$$.Then the shuffling works as follows. There is an array of $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$. Then for each integer $$$k$$$, the guest in room $$$k$$$ is moved to room number $$$k+a_{k\bmod n}$$$.After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$ ($$$-10^9\le a_i\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower).

NoteIn the first test case, every guest is shifted by $$$14$$$ rooms, so the assignment is still unique.In the second test case, even guests move to the right by $$$1$$$ room, and odd guests move to the left by $$$1$$$ room. We can show that the assignment is still unique.In the third test case, every fourth guest moves to the right by $$$1$$$ room, and the other guests move to the right by $$$5$$$ rooms. We can show that the assignment is still unique.In the fourth test case, guests $$$0$$$ and $$$1$$$ are both assigned to room $$$3$$$.In the fifth test case, guests $$$1$$$ and $$$2$$$ are both assigned to room $$$2$$$.

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

  puts((0...n).map do |i|
    (i + a[i]) % n
  end.uniq.size == n ? "YES" : "NO")
end


School holidays come in Berland. The holidays are going to continue for n days. The students of school №N are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are in charge of the daily watering of flowers in shifts according to the schedule. However when Marina Sergeyevna was making the schedule, she was so tired from work and so lost in dreams of the oncoming vacation that she perhaps made several mistakes. In fact, it is possible that according to the schedule, on some days during the holidays the flowers will not be watered or will be watered multiple times. Help Marina Sergeyevna to find a mistake.

The first input line contains two numbers n and m (1 ≤ n, m ≤ 100) — the number of days in Berland holidays and the number of people in charge of the watering respectively. The next m lines contain the description of the duty schedule. Each line contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), meaning that the i-th person in charge should water the flowers from the ai-th to the bi-th day inclusively, once a day. The duty shifts are described sequentially, i.e. bi ≤ ai + 1 for all i from 1 to n - 1 inclusively.

Print "OK" (without quotes), if the schedule does not contain mistakes. Otherwise you have to find the minimal number of a day when the flowers will not be watered or will be watered multiple times, and output two integers — the day number and the number of times the flowers will be watered that day.

NoteKeep in mind that in the second sample the mistake occurs not only on the second day, but also on the sixth day, when nobody waters the flowers. However, you have to print the second day, i.e. the day with the minimal number.

OK = "OK"

n, m = gets.split.map { |v| v.to_i }
t = Array.new(n, 0)

m.times do
  a, b = gets.split.map { |v| v.to_i - 1 }
  (a .. b).each { |index| t[index] += 1 }
end

incorrect_day = nil

t.each_index do |index|
  if t[index] != 1
    incorrect_day = index
    break
  end
end

if incorrect_day
  puts "#{incorrect_day + 1} #{t[incorrect_day]}"
else
  puts OK
end

n, m = gets.split.map { |v| v.to_i }
t = Array.new(n, 0)

m.times do
  a, b = gets.split.map { |v| v.to_i - 1 }
  (a .. b).each { |index| t[index] += 1 }
end

incorrect_day = t.find_index { |v| v != 1 }

if incorrect_day
  puts "#{incorrect_day + 1} #{t[incorrect_day]}"
else
  puts "OK"
end

n,m = gets.chomp.split(/ /).map!{|x| x.to_i}
cnt = 0
err = 0
prevnum = 0
for i in 0..m-1
	a = gets.chomp.split(/ /).map!{|x| x.to_i}
	if a[0] == prevnum
		if err == 1
			cnt += 1
		else
			cnt = 2
			err = 1
		end
		break if a[1] != a[0]
	else
		break if err == 1
		if a[0] > prevnum+1
			err = 2
			break
		end
	end
	prevnum = a[1]
end
if err == 2
	puts (prevnum+1).to_s + " 0"
elsif err == 1
	puts prevnum.to_s + " " + cnt.to_s
elsif n != prevnum
	puts (prevnum+1).to_s + " 0"
else
	puts "OK"
end

n,m = gets.chomp.split(/ /).map!{|x| x.to_i}
cnt = 0
err = 0
prevnum = 0
for i in 0..m-1
	a = gets.chomp.split(/ /).map!{|x| x.to_i}
	if a[0] == prevnum
		if err == 1
			cnt += 1
		else
			cnt = 2
			err = 1
		end
		break if a[1] != a[0]
	else
		break if err == 1
		if a[0] > prevnum+1
			err = 2
			break
		end
	end
	prevnum = a[1]
end
if err == 2
	puts (prevnum+1).to_s + " 0"
elsif err == 1
	puts prevnum.to_s + " " + cnt.to_s
else
	puts "OK"
end


Given an array $$$a=[a_1,a_2,\dots,a_n]$$$ of $$$n$$$ positive integers, you can do operations of two types on it:  Add $$$1$$$ to every element with an odd index. In other words change the array as follows: $$$a_1 := a_1 +1, a_3 := a_3 + 1, a_5 := a_5+1, \dots$$$.  Add $$$1$$$ to every element with an even index. In other words change the array as follows: $$$a_2 := a_2 +1, a_4 := a_4 + 1, a_6 := a_6+1, \dots$$$.Determine if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers. In other words, determine if you can make all elements of the array have the same parity after any number of operations.Note that you can do operations of both types any number of times (even none). Operations of different types can be performed a different number of times.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 50$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^3$$$) — the elements of the array. Note that after the performed operations the elements in the array can become greater than $$$10^3$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output "YES" if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteFor the first test case, we can increment the elements with an even index, obtaining the array $$$[1, 3, 1]$$$, which contains only odd numbers, so the answer is "YES".For the second test case, we can show that after performing any number of operations we won't be able to make all elements have the same parity, so the answer is "NO".For the third test case, all elements already have the same parity so the answer is "YES".For the fourth test case, we can perform one operation and increase all elements at odd positions by $$$1$$$, thus obtaining the array $$$[1001, 1, 1001, 1, 1001]$$$, and all elements become odd so the answer is "YES".

def all_odds?(arr)
  arr.each do |a|
    if a.even?
      return false
    end
  end
  return true
end

def all_evens?(arr)
arr.each do |a|
  if a.odd?
    return false
  end
end
return true
end

def odd_even_increments(arr, n)
  if all_odds?(arr) || all_evens?(arr)
    return true
  end
  i = 0
  while i < n
    if (i+1) % 2 != 0
      arr[i] += 1
    end
    i += 2
  end

  if all_evens?(arr) || all_odds?(arr)
    return true
  end
  i = 1

  while i < n
    if (i+1) % 2 == 0
      arr[i] += 1
    end
    i+=2
  end

  if all_odds?(arr) || all_odds?(arr)
    return true
  end

  return false
end

t = gets.chomp.to_i
inputs = []
(0..t-1).each do |i|
  n = gets.chomp.to_i
  arr = gets.chomp
  arr = arr.split(" ").map(&:to_i)
  inputs.push([arr, n])
end

inputs.each do |element|
  result = odd_even_increments(element[0], element[1])
  if result
    puts "YES"
  else
    puts "NO"
  end
end

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  as = xs.zip(0..).filter_map { |x, i| x % 2 if i % 2 == 0 }
  bs = xs.zip(0..).filter_map { |x, i| x % 2 if i % 2 == 1 }
  puts as.uniq.size == 1 && bs.uniq.size == 1 ? "YES" : "NO"
end

gets.to_i.times do
  gets
  a = gets.split.map(&:to_i)
  f = true
  a.each_with_index do |_q, i|
    f = false if i.even? && a[i] % 2 != a[0] % 2
    f = false if i.odd? && a[i] % 2 != a[1] % 2
  end
  if f
    puts :YES
  else
    puts :NO
  end
end

def all_odds?(arr)
  arr.each do |a|
    if a.even?
      return false
    end
  end
  return true
end

def all_evens?(arr)
arr.each do |a|
  if a.odd?
    return false
  end
end
return true
end

def odd_even_increments(arr, n)
  if all_odds?(arr) || all_evens?(arr)
    return true
  end
  i = 0
  while i < n
    if (i+1) % 2 != 0
      arr[i] += 1
    end
    i += 2
  end

  if all_evens?(arr) || all_odds?(arr)
    return true
  end
  i = 1

  while i < n
    if (i+1) % 2 == 0
      arr[i] += 1
    end
    i+=2
  end

  if all_odds?(arr) || all_odds?(arr)
    return true
  end

  return false
end

t = gets.chomp.to_i
inputs = []
(0..t-1).each do |i|
  n = gets.chomp.to_i
  arr = gets.chomp
  arr = arr.split(" ").map(&:to_i)
  inputs.push([arr, n])
end

inputs.each do |element|
  result = odd_even_increments(element[0], element[1])
  if result
    p "YES"
  else
    p "NO"
  end
end


Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters.   Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the i-th letter of her name should be 'O' (uppercase) if i is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to n. Fibonacci sequence is the sequence f where  f1 = 1,  f2 = 1,  fn = fn - 2 + fn - 1 (n > 2). As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.

The first and only line of input contains an integer n (1 ≤ n ≤ 1000).

Print Eleven's new name on the first and only line of output.

n = gets.to_i

name = String.new

name[0] = 'O'

unless n < 2
    name[1] = 'O'
end

a = 1
b = 2

for i in 2...n
    if (i+1) == a+b
        name[i] = 'O'
        a = i+1
        a,b=b,a
    else
        name[i] = 'o'
    end
end

puts name

n=gets.to_i
s='o'*n
a=b=1
while b<=n
	s[b-1]='O'
	a,b=b,a+b
end
puts s

def IsPerfect(x)
  Math.sqrt(x)%1==0
end

def Fibonnaci(n)
  IsPerfect(5*n*n + 4) || IsPerfect(5*n*n - 4)
end

n = gets.to_i
i = 1
res = ''
while i <= n
  res=Fibonnaci(i)? res+'O': res+'o'
  i+=1
end

puts res

def fib(n)
  return 1 if n == 1
  return 1 if n == 2
  fib(n-2) + fib(n-1)
end

fib_arr = []
(1..20).each do |i|
  fib_arr << fib(i)
end

fib_s = 'o' * 10000

fib_arr.each do |f|
  fib_s[f-1] = 'O'
end

n = gets.to_i

puts fib_s[0..n-1]

n = gets.to_i
f, s = 0, 1
fib = []
while s <= n
  fib << s
  f, s = s, f + s
end
n.times { |i| print fib.include?(i + 1) ? 'O' : 'o' }

def IsPerfect(x)
  Math.sqrt(x)%1==0
end

def Fibonnaci(n)
  IsPerfect(5*n*n + 4) || IsPerfect(5*n*n - 4)
end

n = gets.to_i
i = 0
res = ''
while i < n
  res=Fibonnaci(i)? res+'O': res+'o'
  i+=1
end

puts res

n = gets.to_i
res = 'OOOoO'
m = 2
while res.size<=n
  m.times do
    res+='o'
  end
  res+='O'
  m=m**2
end
puts res[0,n]

def fib(n)
  return 1 if n == 1
  return 1 if n == 2
  fib(n-2) + fib(n-1)
end

fib_arr = []
(1..13).each do |i|
  fib_arr << fib(i)
end

fib_s = 'o' * 300

fib_arr.each do |f|
  fib_s[f-1] = 'O'
end

n = gets.to_i

puts fib_s[0..n-1]

def fib(n)
  return 1 if n == 1
  return 1 if n == 2
  fib(n-2) + fib(n-1)
end

fib_arr = []
(1..13).each do |i|
  fib_arr << fib(i)
end

fib_s = 'o' * 10000

fib_arr.each do |f|
  fib_s[f-1] = 'O'
end

n = gets.to_i

puts fib_s[0..n-1]

n = gets.to_i
f, s = 0, 1
fib = []
n.times do
  fib << s
  f, s = s, f + s
end
n.times { |i| print fib.include?(i + 1) ? 'O' : 'o' }


This is an interactive problem!An arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element ($$$x_i - x_{i - 1}$$$, where $$$i \ge 2$$$) is constant — such difference is called a common difference of the sequence.That is, an arithmetic progression is a sequence of form $$$x_i = x_1 + (i - 1) d$$$, where $$$d$$$ is a common difference of the sequence.There is a secret list of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$.It is guaranteed that all elements $$$a_1, a_2, \ldots, a_n$$$ are between $$$0$$$ and $$$10^9$$$, inclusive.This list is special: if sorted in increasing order, it will form an arithmetic progression with positive common difference ($$$d > 0$$$). For example, the list $$$[14, 24, 9, 19]$$$ satisfies this requirement, after sorting it makes a list $$$[9, 14, 19, 24]$$$, which can be produced as $$$x_n = 9 + 5 \cdot (n - 1)$$$.Also you are also given a device, which has a quite discharged battery, thus you can only use it to perform at most $$$60$$$ queries of following two types: Given a value $$$i$$$ ($$$1 \le i \le n$$$), the device will show the value of the $$$a_i$$$. Given a value $$$x$$$ ($$$0 \le x \le 10^9$$$), the device will return $$$1$$$ if an element with a value strictly greater than $$$x$$$ exists, and it will return $$$0$$$ otherwise.Your can use this special device for at most $$$60$$$ queries. Could you please find out the smallest element and the common difference of the sequence? That is, values $$$x_1$$$ and $$$d$$$ in the definition of the arithmetic progression. Note that the array $$$a$$$ is not sorted.

NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The list in the example test is $$$[14, 24, 9, 19]$$$.

$stdout.sync = true
def r()
  gets.to_i
end
n = r()
l,r=0,10**9;
while l<=r
  m = (l+r)/2
  puts "> #{m}"
  if r()==0
    r = m - 1
  else
    l = m + 1
  end
end
a = [l]
r=0
30.times{
  puts "? #{rand(n)+1}"
  a<< r()
}
for i in a
  for j in a
    r = (i-j).abs.gcd(r)
  end
end
puts "! #{l-(n-1)*r} #{r}"


A PIN code is a string that consists of exactly $$$4$$$ digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.Polycarp has $$$n$$$ ($$$2 \le n \le 10$$$) bank cards, the PIN code of the $$$i$$$-th card is $$$p_i$$$.Polycarp has recently read a recommendation that it is better to set different PIN codes on different cards. Thus he wants to change the minimal number of digits in the PIN codes of his cards so that all $$$n$$$ codes would become different.Formally, in one step, Polycarp picks $$$i$$$-th card ($$$1 \le i \le n$$$), then in its PIN code $$$p_i$$$ selects one position (from $$$1$$$ to $$$4$$$), and changes the digit in this position to any other. He needs to change the minimum number of digits so that all PIN codes become different.Polycarp quickly solved this problem. Can you solve it?

The first line contains integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then test cases follow. The first line of each of $$$t$$$ test sets contains a single integer $$$n$$$ ($$$2 \le n \le 10$$$) — the number of Polycarp's bank cards. The next $$$n$$$ lines contain the PIN codes $$$p_1, p_2, \dots, p_n$$$ — one per line. The length of each of them is $$$4$$$. All PIN codes consist of digits only.

Print the answers to $$$t$$$ test sets. The answer to each set should consist of a $$$n + 1$$$ lines In the first line print $$$k$$$ — the least number of changes to make all PIN codes different. In the next $$$n$$$ lines output the changed PIN codes in the order corresponding to their appearance in the input. If there are several optimal answers, print any of them.

# https://codeforces.com/problemset/problem/1263/B

n = gets.to_i

n.times do
 count = gets.to_i
 cards = []
 digits = Array.new(10, false)

 count.times do |i|
  cards << card = gets.chomp.split('').map(&:to_i)
  digits[cards[i][0]] = true
 end

 moves = 0

 i = 0
 while i < count do
  j = i + 1

  while j < count do
   if cards[i] == cards[j]

    k = 0
    k += 1 while digits[k]

    cards[i][0] = k
    digits[k] = true
    moves += 1
    break
   end

   j += 1
  end
  i += 1
 end

 puts moves
 cards.each { |card| puts card.join('') }
end

# https://codeforces.com/problemset/problem/1263/B

n = gets.to_i

n.times do
 count = gets.to_i
 cards = []
 digits = Array.new(10, false)

 count.times do |i|
  cards << card = gets.chomp.split('').map(&:to_i)
  digits[cards[i][0]] = true
 end

 moves = 0
 table = {}

 i = 0
 while i < count do
  j = i + 1
  while j < count do
   table[[i, j]] = same = cards[i] == cards[j]

   if same
    k = 0
    while digits[k] do
     k += 1
    end
    cards[i][0] = k
    digits[k] = true
    moves += 1
    break
   end

   j += 1
  end
  i += 1
 end

 puts moves
 cards.each { |card| puts card.join('') }
end

# https://codeforces.com/problemset/problem/1263/B

n = gets.to_i

n.times do
 count = gets.to_i
 cards = []
 digits = []
 4.times { digits << Array.new(10, false) }

 count.times do |i|
  cards << card = gets.chomp.split('').map(&:to_i)
  4.times do |j|
   digits[j][cards[i][j]] = true
  end
 end

 moves = 0
 table = {}

 i = 0
 while i < count do
  j = i + 1
  while j < count do
   table[[i, j]] = same = cards[i] == cards[j]

   if same
    k = 0
    while digits[0][k] do
     k += 1
    end
    cards[i][0] = k
    digits[0][k] = true
    moves += 1
    break
   end

   j += 1
  end
  i += 1
 end

 puts moves
 cards.each { |card| puts card.join('') }
end

gets.strip.to_i.times do
  pins = []
  gets.strip.to_i.times do
    pins << gets.strip
  end
  steps = 0
  pins.each_with_index do |p, i|
    c = p.dup
    until !(pins.slice(0, i).concat(pins.slice(i + 1, pins.size))).include?(c)
      c = p.dup
      c[(0..3).to_a.shuffle.first] = ('0'..'9').to_a.shuffle.first
    end
    if c != p
      pins[i] = c
      steps += 1
    end
  end
  puts steps
  puts pins.join("\n")
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

t = inp[0]
t.times do
  h = {}
  n = inp[0]
  d = []
  mc = 0
  n.times{d<<gets.chomp}
  d.each do |s|
    unless h[s]
      h[s] = 1
      mc += 1
    end
  end
  ans = 0
  anst = []
  d.each do |s|
    if h[s] == 1
      anst.push(s)
      h[s] = true
    else
      (0..9).each do |dd|
        s[-1] = dd.to_s
        if(h[s])
          next
        else
          anst.push(s)
          h[s] = true
          break
        end
      end
    end
    next if h[s]
  end
  p n-mc
  puts anst
end

# https://codeforces.com/problemset/problem/1263/B

n = gets.to_i

n.times do
 count = gets.to_i
 cards = []
 digits = []
 4.times { digits << Array.new(10, false) }

 count.times do |i|
  cards << card = gets.chomp.split('').map(&:to_i)
  4.times do |j|
   digits[j][cards[i][j]] = true
  end
 end

 moves = 0
 table = {}

 i = 0
 while i < count do
  j = i + 1
  while j < count do
   table[[i, j]] = same = cards[i] == cards[j]

   if same
    k = 0
    while digits[0][k] do
     k += 1
    end
    cards[i][0] = k
    digits[0][k] = true
    moves += 1
    break
   end

   j += 1
  end
  i += 1
 end

 puts moves
 puts cards.inspect
end


Alicia has an array, $$$a_1, a_2, \ldots, a_n$$$, of non-negative integers. For each $$$1 \leq i \leq n$$$, she has found a non-negative integer $$$x_i = max(0, a_1, \ldots, a_{i-1})$$$. Note that for $$$i=1$$$, $$$x_i = 0$$$.For example, if Alicia had the array $$$a = \{0, 1, 2, 0, 3\}$$$, then $$$x = \{0, 0, 1, 2, 2\}$$$.Then, she calculated an array, $$$b_1, b_2, \ldots, b_n$$$: $$$b_i = a_i - x_i$$$.For example, if Alicia had the array $$$a = \{0, 1, 2, 0, 3\}$$$, $$$b = \{0-0, 1-0, 2-1, 0-2, 3-2\} = \{0, 1, 1, -2, 1\}$$$.Alicia gives you the values $$$b_1, b_2, \ldots, b_n$$$ and asks you to restore the values $$$a_1, a_2, \ldots, a_n$$$. Can you help her solve the problem?

The first line contains one integer $$$n$$$ ($$$3 \leq n \leq 200\,000$$$) – the number of elements in Alicia's array. The next line contains $$$n$$$ integers, $$$b_1, b_2, \ldots, b_n$$$ ($$$-10^9 \leq b_i \leq 10^9$$$). It is guaranteed that for the given array $$$b$$$ there is a solution $$$a_1, a_2, \ldots, a_n$$$, for all elements of which the following is true: $$$0 \leq a_i \leq 10^9$$$.

Print $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$), such that if you calculate $$$x$$$ according to the statement, $$$b_1$$$ will be equal to $$$a_1 - x_1$$$, $$$b_2$$$ will be equal to $$$a_2 - x_2$$$, ..., and $$$b_n$$$ will be equal to $$$a_n - x_n$$$. It is guaranteed that there exists at least one solution for the given tests. It can be shown that the solution is unique.

n = gets.chomp.to_i
arr = gets.split(" ").map!{|el| el.to_i}
result = []

current_max = arr[0]
result << arr[0]
1.upto(n-1) do |i|
  new_element = arr[i] + current_max
  result << new_element
  current_max = new_element if new_element > current_max
end

result.each do |x|
  print x.to_s + " "
end

N = gets.to_i
B = gets.split.map(&:to_i)

sum = 0
ans = []

B.each do |b|
  if b >= 0
    sum += b
    ans << sum
  else
    ans << sum + b
  end
end

puts ans.join(' ')

# coding: utf-8

# Maximums

n = gets.to_i
remax = 0
ax = []
gets.split.each { |i|
    i = i.to_i
    ax << remax + i
    if remax < (remax + i)
        remax = remax + i
    end
}

puts ax.join ' '

n = gets.to_i
b = gets.split.map(&:to_i)
x = [0]
a = []
n.times do |i|
  a[i] = b[i] + x[i]
  x[i + 1] = [x[i], a[i]].max
end
puts a.join(" ")

max = 0

gets
puts(gets.split(' ').map do |e|
  pmax = max
  max = [max, e.to_i + max].max
  e.to_i + pmax
end.join(' '))

n = gets.chomp.to_i
arr = gets.split(" ").map!{|el| el.to_i}
result = []

current_max = arr[0]
result << arr[0]
1.upto(n-1) do |i|
  new_element = arr[i] + current_max
  result << new_element
  current_max = new_element if new_element > current_max
end

p result

N = gets.to_i
B = gets.split.map(&:to_i)

sum = 0
ans = []

B.each do |b|
  sum += b
  ans << sum
end

puts ans.join(' ')


Santa has $$$n$$$ candies and he wants to gift them to $$$k$$$ kids. He wants to divide as many candies as possible between all $$$k$$$ kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.Suppose the kid who recieves the minimum number of candies has $$$a$$$ candies and the kid who recieves the maximum number of candies has $$$b$$$ candies. Then Santa will be satisfied, if the both conditions are met at the same time:  $$$b - a \le 1$$$ (it means $$$b = a$$$ or $$$b = a + 1$$$);  the number of kids who has $$$a+1$$$ candies (note that $$$a+1$$$ not necessarily equals $$$b$$$) does not exceed $$$\lfloor\frac{k}{2}\rfloor$$$ (less than or equal to $$$\lfloor\frac{k}{2}\rfloor$$$). $$$\lfloor\frac{k}{2}\rfloor$$$ is $$$k$$$ divided by $$$2$$$ and rounded down to the nearest integer. For example, if $$$k=5$$$ then $$$\lfloor\frac{k}{2}\rfloor=\lfloor\frac{5}{2}\rfloor=2$$$.Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The $$$i$$$-th test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^9$$$) — the number of candies and the number of kids.

For each test case print the answer on it — the maximum number of candies Santa can give to kids so that he will be satisfied.

NoteIn the first test case, Santa can give $$$3$$$ and $$$2$$$ candies to kids. There $$$a=2, b=3,a+1=3$$$.In the second test case, Santa can give $$$5, 5, 4$$$ and $$$4$$$ candies. There $$$a=4,b=5,a+1=5$$$. The answer cannot be greater because then the number of kids with $$$5$$$ candies will be $$$3$$$.In the third test case, Santa can distribute candies in the following way: $$$[1, 2, 2, 1, 1, 2, 1]$$$. There $$$a=1,b=2,a+1=2$$$. He cannot distribute two remaining candies in a way to be satisfied.In the fourth test case, Santa can distribute candies in the following way: $$$[3, 3]$$$. There $$$a=3, b=3, a+1=4$$$. Santa distributed all $$$6$$$ candies.

readline.to_i.times do
  n, k = readline.split.map(&:to_i)
  a = n/k
  print([n, a*k + k/2].min, "\n")
end

gets.to_i.times do
	a, b = gets.split.map(&:to_i)
	puts [a, a / b * b + b / 2].min
end

gets.strip.to_i.times do
  n, k = gets.strip.split(' ').map(&:to_i)
  per_k = ((n / k).to_i * k)
  if per_k.zero?
    puts [n, (k / 2).to_i].min
  else
    puts per_k + [(n % per_k), (k / 2).to_i].min
  end
end

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

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

q = inp[0]
d = []
ans = []
q.times{d<<inp}
q.times do |i|
  n,m = d[i]
  a = n/m
  ans.push([n,a*m+m/2].min)
end
puts ans

gets.strip.to_i.times {
    n, k = gets.strip.split(' ').map(&:to_i);
    x = ((n / k).floor * k)
    n -= x
    y = (k / 2).floor
    puts x + y if y <= n
    puts x + n if y > n
}

t=gets.to_i
t.times do
    n,k=gets.split.map(&:to_i)
    c1=(n/k)*k
    n-=c1
    c2=[n,k/2].min
    puts c1+c2
end

gets.strip.to_i.times do
  n, k = gets.strip.split(' ').map(&:to_i)
  per_k = ((n / k).to_i * k)
  if per_k.zero?
    puts n
  else
    puts per_k + [(n % per_k), (k / 2).to_i].min
  end
end

gets.strip.to_i.times {
    n, k = gets.strip.split(' ').map(&:to_i);
    x = (n / k).floor
    n -= (x * k)
    y = n - (n / 2).floor;
    puts y + (x * k)
}


Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the n drinks and mixed them. Then he wondered, how much orange juice the cocktail has.Find the volume fraction of orange juice in the final drink.

The first input line contains a single integer n (1 ≤ n ≤ 100) — the number of orange-containing drinks in Vasya's fridge. The second line contains n integers pi (0 ≤ pi ≤ 100) — the volume fraction of orange juice in the i-th drink, in percent. The numbers are separated by a space.

Print the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10  - 4.

NoteNote to the first sample: let's assume that Vasya takes x milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal  milliliters. The total cocktail's volume equals 3·x milliliters, so the volume fraction of the juice in the cocktail equals , that is, 66.(6) percent.

n = gets.to_i
sum = 0

a = []
a = gets.split.map &:to_i

(0...n).each do |i|
    sum += a[i]
end

puts 1.0 * sum / n

n, a = gets.to_i, gets.chomp.split.map {|x| x.to_i / 100.0 }
puts a.inject(:+) / n * 100.0

n = gets.to_i
k = gets.split.map{|e| e.to_f}
puts k.inject(0){|r,e| r+e}/n

k = gets.to_f
a = gets.split.map(&:to_i).reduce(:+)

puts a/k

n = gets.to_f
arr = gets.split.map &:to_f
total = 0
arr.each { |x| total += x / 100.0 }
printf "%.12f",100.0 * total / n

n = gets.to_i
sums = gets.split.map(&:to_f).inject(:+)
puts sums/n

n = gets.strip.to_i
p = gets.strip.split.map(&:to_i)
ans = 0
n.times do |i|
    ans += p[i] / 100.0
end
ans /= n
ans *= 100
puts "%.12f" % ans

n=gets.to_f
x=gets.split.map{|e| e.to_f}.inject(0){|sum,e| sum+e}
puts x/n

n = gets.to_i
p gets.split.map(&:to_i).inject(:+) / n.to_f

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

puts (arr.inject(0, :+))/n.to_f

n=gets.to_i
p=gets.chomp.split.collect{|a| a.to_i}
puts Float(p.reduce(:+))/(Float(p.size*100.0))*100.0

n = Integer(gets)
input = gets.chomp
nums = input.split
p = Array.new
for i in 0...n
    p[i] = Float(nums[i])
end
sum = 0
for i in 0...n
    if p[i] != 0
        sum += p[i] / 100
    end
end

puts sum / n * 100

number = gets.chomp.to_i
pi = gets.chomp
percentages = pi.split

x = 0
percentages.each do |orange|
	x += orange.to_i
end

print x/number.to_f

n=gets.to_i
per=gets.split.map(&:to_i)
count=0
per.each {|t| count+=t}
puts 1.0*count/n;

#puts "Enter number of juice bottle\n"
n = gets.to_i
t = 0
#puts "Enter percentage by one space\n"
s = gets.chomp.to_s.split(" ")
for i in 0...n do
    t += s[i].to_i
end
r = t/n.to_f
puts "%1.12f" % r

require "scanf"
ans = 0
n = gets.to_i
gets.split(" ").each {
    |i| ans += i.to_i
}
ans = ans * 1.0 / n;
printf("%.12f\n",ans)

n = gets.to_f

v = gets.split.map(&:to_i).reduce(:+)

puts v/n

n = gets.to_f
juice = gets.split(' ').take(n).map { |e| e.to_f }
total = 0
juice.each do |volume|
  total += volume
end
print total / n

n = gets.to_i
puts gets.split.map(&:to_f).inject(:+)/n

n = gets.to_i
sum = 0
gets.split(" ").each{|a|
sum+=a.to_f
}
puts sum.to_f/n

n = STDIN.gets
ps = STDIN.gets.split

n = n.to_i
s = 0
ps.each do |p|
  s += p.to_i
end

p s.to_f / n

gets
puts(gets.split(' ').map(&:to_i).instance_eval { reduce(&:+) / size.to_f })

# Codeforces Round #126
# Problem B -- Drinks
n = gets.to_i
puts gets.split.map(&:to_i).inject { |s, i| s + i } / n.to_f

n = gets.chomp.to_i
a = gets.chomp.split(" ")
sum = 0
while b = a.shift do
    sum += b.to_i
end
puts (sum+0.0)/n

n = gets.to_f
print "%.12f" % (gets.split.map(&:to_i).inject(&:+) / n)

def calc_proc(num_arr)
  numer = num_arr.inject(:+)
  denom = 100 * num_arr.size
  Float(100 * numer) / denom
end

if __FILE__ == $0
  #while line = gets
  #  puts line
  #end
  num_arr = []
  STDIN.each_with_index do |line, index|
    if index == 1
      num_arr = line.split.collect {|val| Integer(val) }
    end
  end
  #p num_arr
  STDOUT.puts calc_proc(num_arr)
end

n = gets.to_i
sum = gets.split.map { |x| x.to_i }.reduce(:+)

puts '%.6f' % (sum.to_f / n)

n = gets.to_i
sum = gets.split(' ').map(&:to_i).inject(:+)
puts Rational(sum,n).to_f

class Main
  #def get_problem_link
  #  problem_link = "https://codeforces.com/contest/200/problem/B"
  #  return problem_link
  #end

  #def get_submission_link
  #  submission_link = ''
  #  return submisson_link
  #end

  #begin
  #of codeforces interface
  def run_interface
    n = gets.to_i
    k = gets.split(' ').map(&:to_i)
    puts solution(n, k)
  end
  #end
  #of codeforces interface

  def solution(n, drinks_array)
      sum = 0
      drinks_array.each {|value|
        sum += value
      }
      return sum.fdiv(n).round(12)
  end

end

#then upload to codeforces uncomment this line:
Main.new.run_interface

# cook your code here

n = gets.to_i
s = 0

g = gets.chomp.split

for i in 0...n
    s = s + g[i].to_i
end

s = s/n.to_f

puts s

n = gets.to_i
a = gets.split.map(&:to_i)
sum = 0.0
a.each{|dj| sum+=dj}
puts sum/n

n = gets.to_i
p = gets.split(" ").map{|x| x.to_i}
s = p.inject(:+)
puts s.to_f/n

# codeforce#127(Div2.A)
n = gets.chomp.to_i
p = gets.chomp.split(" ").map{|e| e.to_i}
sum = p.inject{|i, sum| sum += i}

puts (sum.to_f / n.to_f)

require 'bigdecimal'

n = gets.to_i
p = gets.split(/\s/).map(&:to_i)

r = BigDecimal(p.sum.to_s) / n
puts r.to_f.round(8)


All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point.Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.For each city calculate two values mini and maxi, where mini is the minimum cost of sending a letter from the i-th city to some other city, and maxi is the the maximum cost of sending a letter from the i-th city to some other city

The first line of the input contains integer n (2 ≤ n ≤ 105) — the number of cities in Lineland. The second line contains the sequence of n distinct integers x1, x2, ..., xn ( - 109 ≤ xi ≤ 109), where xi is the x-coordinate of the i-th city. All the xi's are distinct and follow in ascending order.

Print n lines, the i-th line must contain two integers mini, maxi, separated by a space, where mini is the minimum cost of sending a letter from the i-th city, and maxi is the maximum cost of sending a letter from the i-th city.

# http://codeforces.com/contest/567/problem/A
n = gets.chomp.to_i
array = gets.chomp.split.map(&:to_i)

array.each.with_index do |num, idx|
  possibles = [].tap do |out|
    out << array[idx - 1] if idx != 0
    out << array[idx + 1] if idx != (n - 1)
    out << array[0] if idx != 0
    out << array[n - 1] if idx != (n - 1)
  end
  possibles.map! { |b| (b - num).abs }.sort!

  puts [possibles.first, possibles.last].join(' ')

end

n = gets.chomp.to_i;
arr = gets.chomp.split.map(&:to_i);
min = Array.new;
max = Array.new;
min[0] = arr[1] - arr[0];
max[0] = arr[-1] - arr[0];

(1..(n - 2)).each do |i|
   min[i] = [arr[i] - arr[i - 1], arr[i + 1] - arr[i]].min();
   max[i] = [arr[i] - arr[0], arr[-1] - arr[i]].max();
   # print min[i], max[i], arr[i], "\n";
 end
min.push(arr[-1] - arr[-2]);
max.push(arr[-1] - arr[0]);

(0..n-1).each do |i|
  puts "#{min[i]} #{max[i]}";
end

def calc (mas)
  pairs = []
  mas.each_index { |i| mas[i]= mas[i].to_i }
  mas.each_index { |i|
    dist=[i>0 ? mas[i]-mas[i-1] : 2**50, i+1<mas.size ? mas[i+1]-mas[i] : 2**50].min
    pairs[i] = [dist,[mas[i]-mas.first,mas.last-mas[i]].max]
  }
  pairs
end
gets
a = gets.split(" ")
b = calc(a)
b.each{|x| puts x.join(' ')}

# require 'pry'
def read_ints; gets.chomp.split.map(&:to_i) end
n = read_ints[0]
x = read_ints
puts (x[1]-x[0]).to_s+" "+(x[-1]-x[0]).to_s
(1..(n-2)).each do |i|
	puts [x[i]-x[i-1],x[i+1]-x[i]].min.to_s + " " + [x[i]-x[0],x[-1]-x[i]].max.to_s
end

puts (x[-1]-x[-2]).to_s+" "+(x[-1]-x[0]).to_s

n = gets.to_i
a = gets.split.map(&:to_i)
print a[1] - a[0],' ',a.last - a[0],"\n"
1.upto(n - 2) do |i|
	print [a[i] - a[i - 1] , a[i + 1] - a[i]].min,' ',[a.last - a[i], a[i] - a.first].max,"\n"
end
print a.last - a[ n - 2],' ',a.last - a.first

# coding: utf-8

# if __FILE__ == $0
# end

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

cities.each_with_index { |base, index|
    near, far = 2* (10**9), 0

    # near
    [index -1, index +1].each { |nidx|
        if nidx >= 0 && nidx < n
            dist = (cities[index] - cities[nidx]).abs
            if dist < near
                near = dist
            end
        end
    }

    # far
    [0, n-1].each { |fidx|
        if index != fidx
            dist = (cities[index] - cities[fidx]).abs
            if dist > far
                far = dist
            end
        end
    }

    puts "#{near} #{far}"
}

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

puts "#{xs[1]-xs[0]} #{xs[-1]-xs[0]}"

for i in 1..n-2
  if xs[i]-xs[i-1] < xs[i+1]-xs[i]
    print xs[i]-xs[i-1]
  else
    print xs[i+1]-xs[i]
  end
  print " "
  if   xs[i]-xs[0] < xs[-1]-xs[i]
    print xs[-1]-xs[i]
  else
    print xs[i]-xs[0]
  end
  print "\n"
end

puts "#{xs[-1]-xs[-2]} #{xs[-1]-xs[0]}"

n = gets.to_i
a = gets.split.map(&:to_i)
a = a.map{|x| x -= a[0]}
n.times do |i|
  mi = a[n - 1]
  mi = a[i] - a[i - 1] if i != 0
  mi = [mi, a[i + 1] - a[i]].min if i != n - 1
  mx = [a[i] - a[0], a[n - 1] - a[i]].max
  puts "#{mi} #{mx}"
end

n = gets.chomp
n = n.to_i

arr = gets.chomp.split(' ')

n.times do |x|
  arr[ x ] = arr[ x ].to_i
end

n.times do |ith|
  if ith == 0
    mx = ( arr[ 1 ] - arr[ 0 ]).abs
    mn = ( arr.last - arr[ 0 ] ).abs
    mx, mn = mn, mx if mx < mn
    print mn.to_s +  " "  + mx.to_s + "\n"
  elsif ith > 0 && ith < n - 1
    mn = [ ( arr[ ith ] - arr[ ith - 1 ] ).abs, (arr[ ith ] - arr[ ith + 1 ]).abs ].min
    mx = [ ( arr.last - arr[ ith ] ).abs, ( arr.first - arr[ith] ).abs ].max
    mx, mn = mn, mx if mx < mn
    print mn.to_s + " " + mx.to_s + "\n"
  else
    mn = ( arr[ ith ] - arr[ ith - 1 ] ).abs
    mx = ( arr.first - arr[ith] ).abs
    mx, mn = mn, mx if mx < mn
    print mn.to_s + " " + mx.to_s + "\n"
  end

end

cityNum = gets.chomp.to_i
city = gets.chomp.split(' ').map {|item| item.to_i}
result = []

city.each_with_index do |value, index|
	ans = []

	if index > 0
		left = city[index - 1]
	else
		left = -100000000001
	end

	if index < cityNum - 1
		right = city[index + 1]
	else
		right = 100000000001
	end

	mostLeft = city[0]
	mostRight = city[cityNum - 1]

=begin
	puts "cityNum : #{cityNum}"
	puts "index : #{index}"
	puts "left : #{left}"
	puts "right : #{right}"
	puts "mostLeft : #{mostLeft}"
	puts "mostRight : #{mostRight}"
=end

	if value - left > right - value
		ans << right - value
	else
		ans << value - left
	end

	if value - mostLeft > mostRight - value
		ans << value - mostLeft
	else
		ans << mostRight - value
	end

	result << ans
end

result.each do |value|
	value.each do |item|
		print "#{item} "
	end

	puts ''
end

n = gets.to_i
a = gets.split.map(&:to_i)
a = a.map{|x| x -= a[0]}
n.times do |i|
  mi = n
  mi = a[i] - a[i - 1] if i != 0
  mi = [mi, a[i + 1] - a[i]].min if i != n - 1
  mx = [a[i] - a[0], a[n - 1] - a[i]].max
  puts "#{mi} #{mx}"
end

cityNum = gets.chomp.to_i
city = gets.chomp.split(' ').map {|item| item.to_i}
result = []

city.each_with_index do |value, index|
	ans = []

	if index > 0
		left = city[index - 1]
	else
		left = -1000000001
	end

	if index < cityNum - 1
		right = city[index + 1]
	else
		right = 1000000001
	end

	mostLeft = city[0]
	mostRight = city[cityNum - 1]

=begin
	puts "cityNum : #{cityNum}"
	puts "index : #{index}"
	puts "left : #{left}"
	puts "right : #{right}"
	puts "mostLeft : #{mostLeft}"
	puts "mostRight : #{mostRight}"
=end

	if value - left > right - value
		ans << right - value
	else
		ans << value - left
	end

	if value - mostLeft > mostRight - value
		ans << value - mostLeft
	else
		ans << mostRight - value
	end

	result << ans
end

result.each do |value|
	value.each do |item|
		print "#{item} "
	end

	puts ''
end


During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows:   The cell with coordinates $$$(x, y)$$$ is at the intersection of $$$x$$$-th row and $$$y$$$-th column. Upper left cell $$$(1,1)$$$ contains an integer $$$1$$$.The developers of the SUM function don't sleep either. Because of the boredom, they teamed up with the developers of the RAND function, so they added the ability to calculate the sum on an arbitrary path from one cell to another, moving down or right. Formally, from the cell $$$(x,y)$$$ in one step you can move to the cell $$$(x+1, y)$$$ or $$$(x, y+1)$$$. After another Dinwows update, Levian started to study "Celex-2021" (because he wants to be an accountant!). After filling in the table with the GAZ-GIZ function, he asked you to calculate the quantity of possible different amounts on the path from a given cell $$$(x_1, y_1)$$$ to another given cell $$$(x_2, y_2$$$), if you can only move one cell down or right.Formally, consider all the paths from the cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ such that each next cell in the path is located either to the down or to the right of the previous one. Calculate the number of different sums of elements for all such paths.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 57179$$$) — the number of test cases. Each of the following $$$t$$$ lines contains four natural numbers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \le x_1 \le x_2 \le 10^9$$$, $$$1 \le y_1 \le y_2 \le 10^9$$$) — coordinates of the start and the end cells.

For each test case, in a separate line, print the number of possible different sums on the way from the start cell to the end cell.

NoteIn the first test case there are two possible sums: $$$1+2+5=8$$$ and $$$1+3+5=9$$$.

t = gets.to_i

1.upto t do
  x1, y1, x2, y2 = gets.split.map(&:to_i)
  puts ((x2 - x1) * (y2 - y1) + 1)
end


Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task.You are given two matrices $$$A$$$ and $$$B$$$ of size $$$n \times m$$$, each of which consists of $$$0$$$ and $$$1$$$ only. You can apply the following operation to the matrix $$$A$$$ arbitrary number of times: take any submatrix of the matrix $$$A$$$ that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain $$$0$$$, will be replaced by $$$1$$$, and all corners of the submatrix that contain $$$1$$$, will be replaced by $$$0$$$). You have to answer whether you can obtain the matrix $$$B$$$ from the matrix $$$A$$$.  An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow. Ramesses don't want to perform these operations by himself, so he asks you to answer this question.A submatrix of matrix $$$M$$$ is a matrix which consist of all elements which come from one of the rows with indices $$$x_1, x_1+1, \ldots, x_2$$$ of matrix $$$M$$$ and one of the columns with indices $$$y_1, y_1+1, \ldots, y_2$$$ of matrix $$$M$$$, where $$$x_1, x_2, y_1, y_2$$$ are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$, where the cell $$$(i,j)$$$ denotes the cell on the intersection of the $$$i$$$-th row and the $$$j$$$-th column.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 500$$$) — the number of rows and the number of columns in matrices $$$A$$$ and $$$B$$$. Each of the next $$$n$$$ lines contain $$$m$$$ integers: the $$$j$$$-th integer in the $$$i$$$-th line is the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$0 \leq A_{ij} \leq 1$$$).  Each of the next $$$n$$$ lines contain $$$m$$$ integers: the $$$j$$$-th integer in the $$$i$$$-th line is the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$0 \leq B_{ij} \leq 1$$$).

Print "Yes" (without quotes) if it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$ using the operations described above, and "No" (without quotes), if it is not possible. You can print each letter in any case (upper or lower).

NoteThe examples are explained below.  Example 1.   Example 2.   Example 3.

n,m = gets.split.map(&:to_i)
s = []
g = []
n.times do
  s << gets.split.map(&:to_i)
end
n.times do
  g << gets.split.map(&:to_i)
end
flg = true
cnt = 0
n.times do |i|
  m.times do |j|
    if s[i][j] != g[i][j]
      cnt += 1
    end
  end
  if cnt % 2 == 1
    flg = false
  end
end
cnt = 0
m.times do |j|
  n.times do |i|
    if s[i][j] != g[i][j]
      cnt += 1
    end
  end
  if cnt % 2 == 1
    flg = false
  end
end
puts flg ? "Yes" : "No"


You're given an array $$$a_1, \ldots, a_n$$$ of $$$n$$$ non-negative integers.Let's call it sharpened if and only if there exists an integer $$$1 \le k \le n$$$ such that $$$a_1 < a_2 < \ldots < a_k$$$ and $$$a_k > a_{k+1} > \ldots > a_n$$$. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:  The arrays $$$[4]$$$, $$$[0, 1]$$$, $$$[12, 10, 8]$$$ and $$$[3, 11, 15, 9, 7, 4]$$$ are sharpened;  The arrays $$$[2, 8, 2, 8, 6, 5]$$$, $$$[0, 1, 1, 0]$$$ and $$$[2, 5, 6, 9, 8, 8]$$$ are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any $$$i$$$ ($$$1 \le i \le n$$$) such that $$$a_i>0$$$ and assign $$$a_i := a_i - 1$$$.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 15\ 000$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$). The second line of each test case contains a sequence of $$$n$$$ non-negative integers $$$a_1, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.

NoteIn the first and the second test case of the first test, the given array is already sharpened.In the third test case of the first test, we can transform the array into $$$[3, 11, 15, 9, 7, 4]$$$ (decrease the first element $$$97$$$ times and decrease the last element $$$4$$$ times). It is sharpened because $$$3 < 11 < 15$$$ and $$$15 > 9 > 7 > 4$$$.In the fourth test case of the first test, it's impossible to make the given array sharpened.

num_tests = gets.chomp.to_i

def array_sharpening(arr)
  peak = false
  i = 0
  while i < arr.size
    if arr[i] < i && !peak
      return "No"
    elsif arr[i] < arr.size - i - 1
      return "No" if arr[i] < i
      peak = false
    elsif !peak
      peak = true
    end
    i += 1
  end
  peak ? "Yes" : "No"
end

i = 0
while i < num_tests
  n = gets.chomp
  arr = gets.chomp.split(" ").map(&:to_i)
  puts array_sharpening(arr)
  i += 1
end

T = gets.to_i

def checker(nums)
  success = true
  l = nums.size
  cur = 0
  mode = :increase

  l.times do |i|
    if mode == :increase
      if nums[i] < cur
        mode = :decrease
        cur = nums[i - 1]
      else
        cur += 1
      end
    end

    if mode == :decrease
      cur = [cur - 1, nums[i]].min

      if cur < 0
        success = false
      end
    end
  end

  success
end

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

  if checker(a) || checker(a.reverse)
    puts 'Yes'
  else
    puts 'No'
  end
end

t = gets.to_i
def check_odd(n, arr)
  flag = true
  [*0..(n/2)].each{|i|
    if arr[i]<i
      flag = false
      break
    end
  }
  [*(n/2)+1..n-1].each{|i|
    if arr[i]<(n-1-i)
      flag = false
      break
    end
  } if flag
  flag
end
def check_even(n, arr)
  flag = true
  [*0..(n/2)-1].each{|i|
    if arr[i]<i
      flag = false
      break
    end
  }
  [*(n/2)..n-1].each{|i|
    if arr[i]<(n-1-i)
      flag = false
      break
    end
  } if flag
  flag = false if arr[n/2-1]==n/2-1 && arr[n/2]==n/2-1
  flag
end
t.times{
  n = gets.to_i
  arr = gets.split.map(&:to_i)
  if n.odd?
    puts check_odd(n, arr) ? "Yes" : "No"
  else
    puts check_even(n, arr) ? "Yes" : "No"
  end
}

num_tests = gets.chomp.to_i

def array_sharpening(arr)
  peak = false
  i = 0
  while i < arr.size
    if arr[i] < i && !peak
      return "No"
    elsif arr[i] < arr.size - i - 1
      peak = false
    elsif !peak
      peak = true
    end
    i += 1
  end
  peak ? "Yes" : "No"
end

i = 0
while i < num_tests
  n = gets.chomp
  arr = gets.chomp.split(" ").map(&:to_i)
  puts array_sharpening(arr)
  i += 1
end


You have a list of numbers from $$$1$$$ to $$$n$$$ written from left to right on the blackboard.You perform an algorithm consisting of several steps (steps are $$$1$$$-indexed). On the $$$i$$$-th step you wipe the $$$i$$$-th number (considering only remaining numbers). You wipe the whole number (not one digit).  When there are less than $$$i$$$ numbers remaining, you stop your algorithm. Now you wonder: what is the value of the $$$x$$$-th remaining number after the algorithm is stopped?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The next $$$T$$$ lines contain queries — one per line. All queries are independent. Each line contains two space-separated integers $$$n$$$ and $$$x$$$ ($$$1 \le x < n \le 10^{9}$$$) — the length of the list and the position we wonder about. It's guaranteed that after the algorithm ends, the list will still contain at least $$$x$$$ numbers.

Print $$$T$$$ integers (one per query) — the values of the $$$x$$$-th number after performing the algorithm for the corresponding queries.

# https://codeforces.com/contest/1194/problem/A
t = gets.to_i

t.times do
  _, x = gets.split.map &:to_i
  puts x * 2
end

t = gets.to_i
t.times do
  n,x = gets.split.map(&:to_i)
  p x*2
end

n = gets
output = []

Array.new n.to_i do
  input = gets
  output << 2 * input.split(" ")[1].to_i
end

output.each do |e|
  puts e
end

gets.strip.to_i.times do
  n, x = gets.strip.split(' ').map(&:to_i)
  puts x * 2
end

t = gets.to_i
t.times do
  n, x = gets.split.map(&:to_i)
  puts x * 2
end

num = gets.to_i
num.times do
  puts gets.split(" ").last.to_i*2
end

t = gets.to_i
t.times do
  n, x = gets.split.map &:to_i
  puts 2*x
end

n=gets.to_i
for _ in 1..n
a=gets.split.map &:to_i
puts a[1]*2
end

num = gets.to_i
num.times do
  puts gets.split(" ").last.to_i
end


$$$n$$$ distinct integers $$$x_1,x_2,\ldots,x_n$$$ are written on the board. Nezzar can perform the following operation multiple times.  Select two integers $$$x,y$$$ (not necessarily distinct) on the board, and write down $$$2x-y$$$. Note that you don't remove selected numbers. Now, Nezzar wonders if it is possible to have his favorite number $$$k$$$ on the board after applying above operation multiple times.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases.  The first line of each test case contains two integers $$$n,k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$-10^{18} \le k \le 10^{18}$$$). The second line of each test case contains $$$n$$$ distinct integers $$$x_1,x_2,\ldots,x_n$$$ ($$$-10^{18} \le x_i \le 10^{18}$$$). It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" on a single line if it is possible to have $$$k$$$ on the board. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case, the number $$$1$$$ is already on the board.In the second test case, Nezzar could perform the following operations to write down $$$k=0$$$ on the board:   Select $$$x=3$$$ and $$$y=2$$$ and write down $$$4$$$ on the board.  Select $$$x=4$$$ and $$$y=7$$$ and write down $$$1$$$ on the board.  Select $$$x=1$$$ and $$$y=2$$$ and write down $$$0$$$ on the board. In the third test case, it is impossible to have the number $$$k = -1$$$ on the board.

gets.to_i.times do
  n,k=gets.split.map(&:to_i)
  x=gets.split.map(&:to_i).sort
  g=x[1]-x[0]
  (n-1).times do |i|
    g=g.gcd(x[i+1]-x[i])
  end
  if (x[0]-k)%g==0
    puts "YES"
  else
    puts "NO"
  end
end


Kawashiro Nitori is a girl who loves competitive programming.One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.Given a string $$$s$$$ and a parameter $$$k$$$, you need to check if there exist $$$k+1$$$ non-empty strings $$$a_1,a_2...,a_{k+1}$$$, such that $$$$$$s=a_1+a_2+\ldots +a_k+a_{k+1}+R(a_k)+R(a_{k-1})+\ldots+R(a_{1}).$$$$$$ Here $$$+$$$ represents concatenation. We define $$$R(x)$$$ as a reversed string $$$x$$$. For example $$$R(abcd) = dcba$$$. Note that in the formula above the part $$$R(a_{k+1})$$$ is intentionally skipped.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 100$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case description contains two integers $$$n$$$, $$$k$$$ ($$$1\le n\le 100$$$, $$$0\le k\le \lfloor \frac{n}{2} \rfloor$$$)  — the length of the string $$$s$$$ and the parameter $$$k$$$. The second line of each test case description contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase English letters.

For each test case, print "YES" (without quotes), if it is possible to find $$$a_1,a_2,\ldots,a_{k+1}$$$, and "NO" (without quotes) otherwise. You can print letters in any case (upper or lower).

7
5 1
qwqwq
2 1
ab
3 1
ioi
4 2
icpc
22 0
dokidokiliteratureclub
19 8
imteamshanghaialice
6 3
aaaaaa

NoteIn the first test case, one possible solution is $$$a_1=qw$$$ and $$$a_2=q$$$.In the third test case, one possible solution is $$$a_1=i$$$ and $$$a_2=o$$$.In the fifth test case, one possible solution is $$$a_1=dokidokiliteratureclub$$$.

def fn(s, k)
  if k == 0
    if s.empty?
    puts "NO"
    else
    puts "YES"
    end
    return
  end

  if s.length == 2 * k
    puts "NO"
    return
  end
  l=0; r=s.length-1

  while l < r
    if s[l] == s[r]
      l+=1
      r-=1
    else
      puts "NO"
      return
    end
    if l == k
      puts "YES"
      return
    end
  end

  puts "NO"
end

gets.to_i.times {
  l, k = gets.chomp!.split(' ').map &:to_i
  s = gets.chomp
  fn(s[0,l], k)
}


Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied:  If number x belongs to set A, then number a - x must also belong to set A.  If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible.

The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≤ pi ≤ 109).

If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print "NO" (without the quotes).

NoteIt's OK if all the numbers are in the same set, and the other one is empty.

def find(u)
    if u != $f[u]
        $f[u] = find($f[u])
    end
    return $f[u]
end

def merge(x, y)
    x = find(x)
    y = find(y)
    if x != y
        $f[x] = y
    end
end

n, a, b = gets.split
n = n.to_i
a = a.to_i
b = b.to_i
$f = Array.new(n, 0)
(1..n + 2).each do |i|
    $f[i] = i
end
h = Hash.new
s = gets.split
(1..n).each do |i|
    x = s[i - 1].to_i
    h.store(x, i)
end
h.each do |k, v|
    if h[a - k] != nil
        merge(v, h[a - k])
    else
        merge(v, n + 2)
    end
    if h[b - k] != nil
        merge(v, h[b - k])
    else
        merge(v, n + 1)
    end
end
if find(n + 1) == find(n + 2)
    puts "NO"
else
    puts "YES"
    (1..n).each do |i|
        if find(i) == find(n + 1)
            print "0 "
        else
            print "1 "
        end
    end
    puts ""
end


Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset Y from the remaining blocks, that the equality holds:  "Are you kidding me?", asks Chris.For example, consider a case where s = 8 and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: (1 - 1) + (4 - 1) + (5 - 1) = (8 - 3) + (8 - 6) = 7.  However, now Chris has exactly s = 106 blocks. Given the set X of blocks his teacher chooses, help Chris to find the required set Y!

The first line of input contains a single integer n (1 ≤ n ≤ 5·105), the number of blocks in the set X. The next line contains n distinct space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 106), the numbers of the blocks in X. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

In the first line of output print a single integer m (1 ≤ m ≤ 106 - n), the number of blocks in the set Y. In the next line output m distinct space-separated integers y1, y2, ..., ym (1 ≤ yi ≤ 106), such that the required equality holds. The sets X and Y should not intersect, i.e. xi ≠ yj for all i, j (1 ≤ i ≤ n; 1 ≤ j ≤ m). It is guaranteed that at least one solution always exists. If there are multiple solutions, output any of them.

require 'set'
N = 1000000
n = gets.to_i
#x = Set.new(gets.split.map(&:to_i))
x = gets.split.map(&:to_i).sort!
a = []
y = []
pairs = 0
for i in x
  a[i] = 1
end
for i in (1..N)
  if a[i] and a[N+1-i]
    pairs += 1 if i <= N/2
  elsif a[i]
    y << (N + 1 -i)
  end
end
for i in (1..N)
  break if pairs == 0
  unless a[i] or a[N+1-i]
    y << i << (N+1-i)
    pairs -= 1
  end
end
puts y.size
print y.join(' ')


You are given a string $$$s$$$ consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and has exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'. Note that each of the characters '?' is replaced independently from the others.A string $$$t$$$ of length $$$n$$$ is called a palindrome if the equality $$$t[i] = t[n-i+1]$$$ is true for all $$$i$$$ ($$$1 \le i \le n$$$).For example, if $$$s=$$$"01?????0", $$$a=4$$$ and $$$b=4$$$, then you can replace the characters '?' in the following ways:   "01011010";  "01100110". For the given string $$$s$$$ and the numbers $$$a$$$ and $$$b$$$, replace all the characters with '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and has exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 2 \cdot 10^5$$$, $$$a + b \ge 1$$$). The second line of each test case contains the string $$$s$$$ of length $$$a+b$$$, consisting of the characters '0', '1', and '?'. It is guaranteed that the sum of the string lengths of $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output:    "-1", if you can't replace all the characters '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and that it contains exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1';  the string that is obtained as a result of the replacement, otherwise.  If there are several suitable ways to replace characters, you can output any.

t = gets.to_s.to_i

def solve(a, b, s)
  sr = s.reverse

  c0 = 0
  c1 = 0

  s.each do |x|
    if x == "0"
      c0 += 1
    end
    if x == "1"
      c1 += 1
    end
  end

  return "-1" if c0 > a
  return "-1" if c1 > b

  a = a - c0
  b = b - c1

  # pass 1
  s.each_index do |i|
    return "-1" if s[i] != sr[i] && s[i] != "?" && sr[i] != "?"
    next if s[i] == sr[i] && s[i] != "?"
    next if s[i] == "?" && sr[i] == "?"
    if s[i] == "?" && sr[i] == "0"
      s[i] = "0"
      a -= 1
      return "-1" if a < 0
    end
    if s[i] == "?" && sr[i] == "1"
      s[i] = "1"
      b -= 1
      return "-1" if b < 0
    end
  end

  # special case
  if s.size % 2 == 1 && s[s.size / 2] == "?"
    if a % 2 == 1
      s[s.size / 2] = "0"
      a -= 1
    elsif b % 2 == 1
      s[s.size / 2] = "1"
      b -= 1
    else
      return "-1"
    end
  end

  # pass 2
  s.each_index do |i|
    break if i >= s.size / 2
    if s[i] == "?"
      if a >= 2
        s[i] = "0"
        s[s.size - i - 1] = "0"
        a -= 2
      elsif b >= 2
        s[i] = "1"
        s[s.size - i - 1] = "1"
        b -= 2
      else
        return "-1"
      end
    end
  end

  return s.join("")
end

1.upto(t) do |casenum|
  a, b = gets.to_s.split.map {|x| x.to_i }
  s = gets.to_s.strip.split("")
  printf("%s\n", solve(a, b, s))
end


Родители Васи хотят, чтобы он как можно лучше учился. Поэтому если он получает подряд три положительные оценки («четвёрки» или «пятёрки»), они дарят ему подарок. Соответственно, оценки «единица», «двойка» и «тройка» родители Васи считают плохими. Когда Вася получает подряд три хорошие оценки, ему сразу вручают подарок, но для того, чтобы получить ещё один подарок, ему вновь надо получить подряд ещё три хорошие оценки.Например, если Вася получит подряд пять «четвёрок» оценок, а потом «двойку», то ему дадут только один подарок, а вот если бы «четвёрок» было уже шесть, то подарков было бы два. За месяц Вася получил n оценок. Вам предстоит посчитать количество подарков, которые получил Вася. Оценки будут даны именно в том порядке, в котором Вася их получал.

В первой строке входных данных следует целое положительное число n (3 ≤ n ≤ 1000) — количество оценок, полученных Васей. Во второй строке входных данных следует последовательность из n чисел a1, a2, ..., an (1 ≤ ai ≤ 5) — оценки, полученные Васей. Оценки заданы в том порядке, в котором Вася их получил.

Выведите одно целое число — количество подарков, полученных Васей.

ПримечаниеВ первом примере Вася получит два подарка — за первые три положительные оценки и за следующую тройку положительных оценок соответственно.

#!/usr/bin/env ruby

n = gets.to_i
inp = gets.split.map(&:to_i)
ret = 0
pos = 0
for i in 0..n-1
  if inp[i] >= 4 then pos += 1
  else pos = 0 end
  if pos == 3 then ret += 1; pos = 0 end
end
puts ret

#!/usr/bin/env ruby

n = gets.to_i
inp = gets.split.map(&:to_i)
ret = 0
pos = 0
for i in 0..n-1
  if inp[i] >= 4 then pos += 1 end
  if pos == 3 then ret += 1; pos = 0 end
end
puts ret