def solve(s)
  if s.split('').uniq.size == 1
    -1
  else
    s.split('').sort.join
  end
end

gets.strip.to_i.times do
  puts solve(gets.strip)
end

n = gets.to_i
n.times do
  s = gets.chomp
  idx = nil
  flag = false
  s.length.times do |i|
    if s[i] != s[0]
      flag = true
      idx = i
    end
  end
  if flag && s == s.reverse
    t = s[0]
    s[0] = s[idx]
    s[idx] = t
  end
  puts flag ? s : -1
end

gets;puts$<.map{|e|e=e.chomp.chars.sort*'';e[0]<e[-1] ? e : -1}

n = gets.strip.to_i
results = []
n.times do
    x = gets.strip
    res = -1
    if x.chars.uniq.length > 1
        x_chars = x.chars
        if x_chars == x.chars.reverse
            while true do
                x_chars.shuffle!
                if x_chars != x_chars.reverse
                    res = x_chars.join
                    break
                end
            end
        else
            res = x_chars.join
        end
    end
    results << res
end

n.times do |x|
    puts results[x]
end

gets;puts$<.map{|e|e.chomp!;f=e.chars.sort*'';f<e ? f : -1}

n = gets.strip.to_i
results = []
n.times do
    x = gets.strip
    res = -1
    if x.chars.uniq.length > 1
        x_chars = x.chars
        if x_chars == x.chars.reverse
            while true do
                x_chars.shuffle!
                if x_chars != x.chars.reverse
                    res = x_chars.join
                    break
                end
            end
        else
            res = x_chars.join
        end
    end
    results << res
end

n.times do |x|
    puts results[x]
end


n, x1, y1, x2, y2 = gets.split(' ').map(&:to_i)

fs = []
for i in 0...n
  fx, fy = gets.split(' ').map(&:to_i)
  fs << [fx, fy]
end

ds = []
for j in 0...n
  fx, fy = fs[j]
  d1 = (fx-x1)**2+(fy-y1)**2
  d2 = (fx-x2)**2+(fy-y2)**2
  ds << [d1, d2]
end
ds << [0,0]

min = Float::INFINITY
for dv in ds
    d1 = dv[0]
    d2 = 0
    for dw in ds
        if dw[0] > d1
            d2 = [dw[1], d2].max
        end
    end

    min = [min, d1+d2].min
end

puts min

n, x1, y1, x2, y2 = gets.chomp.split(" ").map(&:to_i)
dist = []

n.times do
  fx, fy = gets.chomp.split(" ").map(&:to_i)
  d1 = (x1 - fx)**2 + (y1 - fy)**2
  d2 = (x2 - fx)**2 + (y2 - fy)**2
  dist << [d1, d2]
end
dist << [0,0]

res = Float::INFINITY
dist.each do |i|
  r1 = i[0]
  r2 = 0
  dist.each do |j|
    if j[0] > r1 then
      r2 = [r2, j[1]].max
    end
  end
  res = [res, r1 + r2].min
end

puts res

n, x1, y1, x2, y2 = gets.split(' ').map(&:to_i)
md1 = md2 = 0
for i in 0...n
  fx, fy = gets.split(' ').map(&:to_i)
  d1 = (fx-x1)**2+(fy-y1)**2
  d2 = (fx-x2)**2+(fy-y2)**2
  if d1-md1 < d2-md2
    # closer to r1
    md1 = [md1, d1].max
  else
    # closer to r2
    md2 = [md2, d2].max
  end
end

puts md1 + md2

n, x1, y1, x2, y2 = gets.split(' ').map(&:to_i)

fs = []
for i in 0...n
  fx, fy = gets.split(' ').map(&:to_i)
  fs << [fx, fy]
end

min = Float::INFINITY

md1 = md2 = 0
for j in 0...n
  fx, fy = fs[j]
  d1 = (fx-x1)**2+(fy-y1)**2
  d2 = (fx-x2)**2+(fy-y2)**2
  if d1-md1 < d2-md2
    # closer to r1
    md1 = [md1, d1].max
  else
    # closer to r2
    md2 = [md2, d2].max
  end
end
min = [min, md1 + md2].min

md1 = md2 = 0
for j in 1..n
  fx, fy = fs[n-j]
  d1 = (fx-x1)**2+(fy-y1)**2
  d2 = (fx-x2)**2+(fy-y2)**2
  if d1-md1 < d2-md2
    # closer to r1
    md1 = [md1, d1].max
  else
    # closer to r2
    md2 = [md2, d2].max
  end
end
min = [min, md1 + md2].min

puts min

n, x1, y1, x2, y2 = gets.chomp.split(" ").map(&:to_i)
dist = []

n.times do
  fx, fy = gets.chomp.split(" ").map(&:to_i)
  d1 = (x1 - fx)**2 + (y1 - fy)**2
  d2 = (x2 - fx)**2 + (y2 - fy)**2
  dist << [d1, d2]
end

res = 10**15
dist.each do |i|
  r1 = i[0]
  r2 = 0
  dist.each do |j|
    if j[0] > r1 then
      r2 = [r2, j[1]].max
    end
  end
  res = [res, r1 + r2].min
end
puts res

n, x1, y1, x2, y2 = gets.chomp.split(" ").map(&:to_i)
dist = []

n.times do
  fx, fy = gets.chomp.split(" ").map(&:to_i)
  d1 = (x1 - fx)**2 + (y1 - fy)**2
  d2 = (x2 - fx)**2 + (y2 - fy)**2
  dist << [d1, d2]
end

res = 10**8
dist.each do |i|
  r1 = i[0]
  r2 = 0
  dist.each do |j|
    if j[0] > r1 then
      r2 = [r2, j[1]].max
    end
  end
  res = [res, r1 + r2].min
end
puts res


# TEMPLATE BEGIN
def read_vector
    gets.chomp.split(/\s+/)
end
def read_vector_int
    read_vector.map(&:to_i)
end
# TEMPLATE END

$mod = 1_000_000_007
$maxn = 1010

def mypow(a, b)
    res = 1
    while b > 0
        res = res * a % $mod if b % 2 == 1
        a = a * a % $mod
        b /= 2
    end
    res
end

def ceshka(a, b)
    $fuck[a] * $rfuck[b] * $rfuck[a-b] % $mod
end

$fuck, $rfuck = [1], [1]
(1..$maxn).each.map do |i|
    $fuck.push $fuck[i-1] * i % $mod
    $rfuck.push mypow($fuck[i], $mod - 2)
end

k = read_vector_int.first
a = k.times.map{ read_vector_int.first }

res, sum = 1, 0
k.times do |i|
    sum += a[i]
    res = res * ceshka(sum - 1, a[i] - 1) % $mod
end
puts res

k = gets().chomp().to_i

n = gets().chomp().to_i
count = 1
mod = 1000000007
(k-1).times {
        c = gets().chomp().to_i
        p=c-1
        t1=1
        t2=1
        for i in(1..p)
                t1 *= n+i
                #t1 %= mod
                t2 *= i
                #t2 %= mod
        end

        count *= t1/t2
        count %= mod
        n+=c
}

puts count

k = gets().chomp().to_i

n = gets().chomp().to_i
count = 1
mod = 1000000007
(k-1).times {
        c = gets().chomp().to_i
        p=c-1
        t1=1
        t2=1
        for i in(1..p)
                t1 *= n+i
                t1 %= mod
                t2 *= i
                t2 %= mod
        end

        count *= t1/t2
        n+=c
}

puts count


n = gets.chomp.to_i
n.times {
    arrNum = gets.chomp.to_i
    userstr = gets.chomp
    arr = userstr.split().map(&:to_i).sort
    result = arr.each_cons(2).map {|a,b| b-a}
    p result.min
}

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).sort
	puts a.each_cons(2).map { _2 - _1 }.min
end

gets.strip.to_i.times do |t|
  _ = gets.strip.to_i
  vals = gets.strip.split(' ').map(&:to_i).sort
  mn = vals[1] - vals[0]
  a = vals[0]
  b = vals[1]
  vals.each_with_index do |e, i|
    next if i.zero?
    if vals[i] - vals[i - 1] < mn
      mn = vals[i] - vals[i-1]
      a = vals[i-1]
      b = vals[i]
    end
  end
  puts (a - b).abs
end

t = gets.chomp.to_i
t.times do |testcase|
  n = gets.chomp.to_i
  arr = gets.split.map(&:to_i)
  arr = arr.sort ; min_val = 1000000
  (arr.size-1).times do |i|
    min_val = [min_val , arr[i+1]-arr[i]].min
  end
  puts min_val
end

t = gets.to_i

1.upto t do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  a.sort!
  diff = a[1] - a[0]
  1.upto a.length-1 do |i|
    diff = [diff, a[i]-a[i-1]].min
  end
  puts diff
end

gets.to_i.times {
    gets
    puts gets.split.map(&:to_i).sort.each_cons(2).map{|x,y|y-x}.min
}

gets.to_i.times {
  gets
  data = gets.split.map { |v| v.to_i }.sort_by {|v| v}

  m = data[1] - data[0]
  for i in 2...data.size
    d = data[i] - data[i-1]
    if d < m
      m = d
    end
  end

  puts m
}

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i).sort
  diff = 1001
  arr.each_with_index { |el, i|
    next if i.zero?
    diff = [diff, arr[i] - arr[i - 1]].min
  }
  puts diff

end

gets.strip.to_i.times do
  solve
end

t = gets.to_i
t.times do
  n = gets.to_i
  s = gets.split.map(&:to_i).sort
  min_diff = s[-1] - s[0]
  for i in 0...(n - 1) do
    diff = s[i + 1] - s[i]
    if diff < min_diff
      min_diff = diff
    end
  end
  puts min_diff
end

gets.to_i.times do
  gets
  a = gets.split(' ').map(&:to_i).sort

  result = 1_000_000
  while a.size > 1
    x = a.shift

    result = [a.first - x, result].min
  end

  puts result
end


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

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

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

puts std

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

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

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

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

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

min = arr.join.to_i
min_arr = arr

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

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

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

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

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

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

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

puts min_arr.join

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

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

puts min_arr.join

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

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

puts min_arr.join

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

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

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

puts min_arr.join

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

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

puts std

n=gets.to_i
str=gets.to_s

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

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


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

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

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

  sequence.length - sequence.index(current_light)
end

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

  times.compact.max
end

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

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

##### code for tests:

number_of_cases = gets.chomp.to_i

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  puts result.max
  t -= 1
end

t = gets.chomp.to_i

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


#!/usr/bin/env ruby

test_no = Integer(gets)

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

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

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

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

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

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

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

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

	end

end

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

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

#!/usr/bin/env ruby

test_no = Integer(gets)

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

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

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

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

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

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

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

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

	end

end


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

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

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

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

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

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

puts maxi

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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


# require 'pry'

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

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

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

# coding: utf-8

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

    puts bads
}

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

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

def solve
end

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

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

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

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

# coding: utf-8

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

    puts bads
}

# coding: utf-8

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

    puts bads
}


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

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

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

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

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

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

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

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

p ans
puts $map

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

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

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

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

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

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

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

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

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

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

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

  min_groups = groups - l
  min = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@n, @m = n, m

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

lakes = []

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

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

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

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

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

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

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

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

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

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

@n, @m = n, m

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

lakes = []

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

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

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

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

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

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

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

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

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

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

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

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

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

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

min_groups = groups - l
min = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

min_groups = groups - l
min = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

min_groups = groups - l
min = 0

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

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

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


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

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

puts b

a = gets.strip

ok = false

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

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

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

Solve.new.solve

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

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

#!/usr/bin/ruby

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

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

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

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

run if $0 == __FILE__

s=gets.chomp

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

s[-1]=''
puts s

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

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

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

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

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

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

# coding: utf-8

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

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

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

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

s=gets.chomp

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

puts s.chop

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

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

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

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

#!/usr/bin/ruby1.9

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

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

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

s=gets

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

s[-1]=''
puts

a = gets.strip

ok = false

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


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

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

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


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

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

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


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

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

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


$__cur_readed = []
$__cur_index = 0

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

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

t = rs.to_i

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

$__cur_readed = []
$__cur_index = 0

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

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

def ri()
	return rs1.to_i
end

t = ri

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

$__cur_readed = []
$__cur_index = 0

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

t = ri.to_i

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

p m

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

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

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

puts (n-dem)

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

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

puts n - set.keys.length

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

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

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

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

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

puts ans

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

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

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

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

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

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

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

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

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

puts n - m.uniq.size

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

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

ret = 0

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

puts ret

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

ret = 0

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

puts ret

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

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

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

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

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

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

p m

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

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

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

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

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

puts ans

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

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

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

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

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

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

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

puts n - set.keys.length

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

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


# coding: utf-8

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

q = readline.to_i

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

  k = l.size

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

  puts ans
end

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

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

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

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

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

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

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

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

  puts ans
end


n,m=gets.split.map &:to_i

# s=?a+gets.chomp+?a
s=?a
s<<gets.chomp
s<<?a

#groups=s.scan(/\.+/).size
#dots=s.count ?.
dots=groups=0
b=[]
for i in 1..n+1
    if s[i]==?.
        dots+=1
        b[i]=true
    else
        groups+=1 if s[i-1]==?.
    end
end

res=[]
queries=$<.read.split
m.times{|i|
    x=queries[2*i].to_i
    c=queries[2*i+1]
    if b[x] and c!=?.
        dots-=1
        if !b[x-1] and !b[x+1]
            groups-=1
        elsif b[x-1] and b[x+1]
            groups+=1
        end
        b[x]=false
    elsif !b[x] and c==?.
        dots+=1
        if !b[x-1] and !b[x+1]
            groups+=1
        elsif b[x-1] and b[x+1]
            groups-=1
        end
        b[x]=true
    end
    res<<dots-groups
}
puts res

n,q = gets.chomp.split.map{|x| x.to_i}

str = gets.chomp
prev = str[0]
total = 0
(1..n-1).each do |i|
	curr = str[i]
	if prev == curr and prev == '.'
		total+=1
	end
	prev = curr
end

q.times do
	i,c = gets.chomp.split
	i = (i.to_i)-1

	if c == '.'
		if str[i] != '.'
				if i > 0 and i < n-1

				total+=1 if str[i-1] == '.'
				total+=1 if str[i+1] == '.'
				elsif i==0 and i+1<n  and str[i+1] == '.'
				total+=1
				elsif i==n-1 and i-1>=0 and str[i-1] == '.'
				total+=1
				end
		end
	else
		if str[i] == '.'
			if i > 0 and i < n-1
				total-=1 if str[i-1] == '.'
				total-=1 if str[i+1] == '.'
			elsif i==0 and i+1<n  and str[i+1] == '.'
				total-=1
			elsif i==n-1 and i-1>=0 and str[i-1] == '.'
				total-=1
			end
		end

	end
	str[i] = c
	puts total
end

#!/usr/bin/ruby

def solution(n, m, s, narr, carr)
  count = 0
  prev_char = nil
  s.each_char do |char|
    count+=1 if char == '.' && prev_char == '.'
    prev_char = char
  end
  m.times do |t|
    i = narr[t]
    char = carr[t]
    if (char == '.') ^ (s[i] == '.')
      if char == '.'
        count+=1 if i > 0 && s[i-1] == '.'
        count+=1 if i+1 < n && s[i+1] == '.'
      else
        count-=1 if i > 0 && s[i-1] == '.'
        count-=1 if i+1 < n && s[i+1] == '.'
      end
      s[i] = char
    end
    puts count
  end
end

n, m = gets.split(' ').map{|s|s.to_i}
s = gets
narr = []
carr = []
m.times{
  i, c = gets.split(' ')
  narr.push i.to_i - 1
  carr.push c
}
solution n, m, s, narr, carr

# solution 10, 3, '.b..bz....', [0, 2, 8], %w(h c f)
# solution 4, 4, '.cc.', [1, 2, 1, 0], %w(. . a a)
# solution 4,3
# solution 3,2
# solution 3,1
# solution 3,3
# solution 2,1
# solution 2,2
#
# #
# # solution 4, [75, 150, 75, 50]
# # solution 3, [100, 150, 250]

n,m=gets.split.map &:to_i

s=?a+gets.chomp+?a
groups=s.scan(/\.+/).size
dots=s.count ?.
b=s.bytes.map{|c|c<90}

res=[]
queries=$<.read.split
m.times{|i|
    x=queries[2*i].to_i
    c=queries[2*i+1]
    if b[x] and c!=?.
        dots-=1
        if !b[x-1] and !b[x+1]
            groups-=1
        elsif b[x-1] and b[x+1]
            groups+=1
        end
        b[x]=false
    elsif !b[x] and c==?.
        dots+=1
        if !b[x-1] and !b[x+1]
            groups+=1
        elsif b[x-1] and b[x+1]
            groups-=1
        end
        b[x]=true
    end
    res<<dots-groups
}
puts res

#!/usr/bin/ruby

n, m = gets.split
N = n.to_i
M = m.to_i

str = gets.chomp

dot_amount = str.count(".")

seg_amount = 0
i = 0
while i < N do
  if str[i] == "."
    j = i + 1
    while j < N && str[j] == "." do
      j = j + 1
    end
    seg_amount += 1
    i = j + 1
  else
    i += 1
  end
end
#puts dot_amount, seg_amount

for k in 0...M do
  pos, chr = gets.chomp.split
  pos = pos.to_i - 1
  left_dot = pos != 0 && str[pos-1] == "."
  right_dot = pos != N - 1 && str[pos+1] == "."
  #puts "left #{left_dot}, right #{right_dot}, str #{str}, pos #{pos}, str.. #{str[pos+1]}"

  if chr == "." and str[pos] != "."
    if left_dot and right_dot
      seg_amount -= 1
    elsif (not left_dot) and (not right_dot)
      seg_amount += 1
    end
    dot_amount += 1
  elsif chr != "." and str[pos] == "."
    if left_dot and right_dot
      seg_amount += 1
    elsif (not left_dot) and (not right_dot)
      seg_amount -= 1
    end
    dot_amount -= 1
  end
  #puts "pos #{pos} str #{str} chr #{chr}"
  str[pos] = chr

  puts dot_amount - seg_amount
end

#!/usr/bin/ruby

n, m = gets.split
N = n.to_i
M = m.to_i

str = gets.chomp

dot_amount = str.count(".")

seg_amount = 0
i = 0
while i < N do
  j = i
  while j < N && str[j] == "." do
    j = j + 1
  end
  if j != i
    seg_amount += 1
  end

  i = j + 1
end
#puts dot_amount, seg_amount

for k in 0...M do
  pos, chr = gets.chomp.split
  pos = pos.to_i - 1
  left_dot = pos != 0 && str[pos-1] == "."
  right_dot = pos != N - 1 && str[pos+1] == "."
  #puts "left #{left_dot}, right #{right_dot}, str #{str}, pos #{pos}, str.. #{str[pos+1]}"

  if chr == "." and str[pos] != "."
    if left_dot and right_dot
      seg_amount -= 1
    elsif (not left_dot) and (not right_dot)
      seg_amount += 1
    end
    dot_amount += 1
  elsif chr != "." and str[pos] == "."
    if left_dot and right_dot
      seg_amount += 1
    elsif (not left_dot) and (not right_dot)
      seg_amount -= 1
    end
    dot_amount -= 1
  end
  #puts "pos #{pos} str #{str} chr #{chr}"
  str[pos] = chr

  puts dot_amount - seg_amount
end

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
s = []
s = gets.chomp.split("")
query = []
for i in 0...m
    input = gets.chomp.split
    query[i] = []
    query[i][0] = Integer(input[0])
    query[i][1] = input[1]
end
dot_amount = 0
for i in 0...n
    if s[i] == "."
        dot_amount += 1
    end
end
record = {}
i = 0
while i < n do
    if s[i] == "."
        j = i + 1
        while j < n && s[j] == "." do
            j += 1
        end
        record[i] = [i, j - 1]
        i = j + 1
    else
        i += 1
    end
end
seg_amount = record.size
for i in 0...m
    index = query[i][0] - 1
    content = query[i][1]
    left = index != 0 && s[index - 1] == "."
    right = index != n - 1 && s[index + 1] == "."
    if s[index]!= "."
        if content != "."
            puts dot_amount - seg_amount
        else
            dot_amount += 1
            if left && right
                seg_amount -= 1
                puts dot_amount - seg_amount
            elsif left && !right
                puts dot_amount - seg_amount
            elsif !left && right
                puts dot_amount - seg_amount
            else
                seg_amount += 1
                puts dot_amount - seg_amount
            end
        end
    else
        if content == "."
            puts dot_amount - seg_amount
        else
            dot_amount -= 1
            if left && right
                seg_amount += 1
                puts dot_amount - seg_amount
            elsif left && !right
                puts dot_amount - seg_amount
            elsif !left && right
                puts dot_amount - seg_amount
            else
                seg_amount -= 1
                puts dot_amount - seg_amount
            end
        end
    end
    s[index] = content
end

n,q = gets.chomp.split.map{|x| x.to_i}

str = gets.chomp
prev = str[0]
total = 0
(1..n-1).each do |i|
	curr = str[i]
	if prev == curr and prev == '.'
		total+=1
	end
	prev = curr
end

q.times do
	i,c = gets.chomp.split
	i = (i.to_i)-1

	if c == '.'
		if str[i] != '.'
				if i > 0 and i < n-1

				total+=1 if str[i-1] == '.'
				total+=1 if str[i+1] == '.'
				elsif i==0 and i+1<n  and str[i+1] == '.'
				total+=1
				elsif i==n-1 and str[i-1] == '.'
				total+=1
				end
		end
	else
		if str[i] == '.'
			if i > 0 and i < n-1
				total-=1 if str[i-1] == '.'
				total-=1 if str[i+1] == '.'
			elsif i==0 and i+1<n  and str[i+1] == '.'
				total-=1
			elsif i==n-1 and str[i-1] == '.'
				total-=1
			end
		end

	end
	str[i] = c
	puts total
end

n,m=gets.split.map &:to_i
s=gets

groups=s.scan(/\.+/).size
dots=n-groups

m.times{
    x,c=gets.split
    x=x.to_i-1
    if s[x]==?. and c!=?.
        dots-=1
        if n>1 and (x==0 and s[x+1]!=?.) or (x==n-1 and s[x-1]!=?.)
            groups-=1
        elsif n>2 and (0<x and x<n-1 and s[x-1]==?. and s[x+1]==?.)
            groups+=1
        end
    elsif s[x]!=?. and c==?.
        dots+=1
        if n>1 and (x==0 and s[x+1]!=?.) or (x==n-1 and s[x-1]!=?.)
            groups+=1
        elsif n>2 and (0<x and x<n-1 and s[x-1]==?. and s[x+1]==?.)
            groups-=1
        end
    end
    s[x]=c
    puts dots-groups
}

n,m=gets.split.map &:to_i
s=gets

groups=s.scan(/\.+/).size
dots=s.count ?.

m.times{
    x,c=gets.split
    x=x.to_i-1
    if s[x]==?. and c!=?.
        dots-=1
        if n>1 and (x==0 and s[x+1]!=?.) or (x==n-1 and s[x-1]!=?.)
            groups-=1
        elsif n>2 and (0<x and x<n-1 and s[x-1]==?. and s[x+1]==?.)
            groups+=1
        end
    elsif s[x]!=?. and c==?.
        dots+=1
        if n>1 and (x==0 and s[x+1]!=?.) or (x==n-1 and s[x-1]!=?.)
            groups+=1
        elsif n>2 and (0<x and x<n-1 and s[x-1]==?. and s[x+1]==?.)
            groups-=1
        end
    end
    s[x]=c
    puts dots-groups
}


x, y, a, b = gets.split.map(&:to_i)
outcomes = []
a.upto(x) do |i|
    b.upto(y) do |j|
        outcomes << [i, j] if i > j
    end
end
puts outcomes.size
outcomes.sort.each do |outcome|
    puts outcome.join(" ")
end

x,y,a,b = gets.split.map{|i| i.to_i}

n = 0
ish = []
while a <= x do
    v = b
    while v <= y do
        if a > v then
            n += 1
            ish << a.to_s + " " + v.to_s
        end
        v += 1
    end
    a += 1
end

puts n
n.times do |i|
    puts ish[i]
end

ans=Array.new
x,y,a,b=gets.split.map(&:to_i)
for i in a.to_i..x.to_i do
k=[y.to_i,i].min
	for j in b.to_i..k
		ans<< [i,j] if i!=j
	end
end
ans.size!=0?(puts ans.size;ans.each{|el|puts el.join(" ")}):(puts 0)

x, y, a, b = gets.split.map(&:to_i)
res = Array.new
for i in [a, b+1].max..x
  for j in b..y
    break if j >= i
    res << [i, j]
  end
end
puts res.count
for i in res
  puts "#{i[0]} #{i[1]}"
end

x, y, a, b = gets.split(' ').collect!{ |i| i.to_i}
n = 0
a.upto(x) do |i|
	b.upto(y) do |j|
		if i>j
			n += 1
		end
	end
end

puts n

a.upto(x) do |i|
	b.upto(y) do |j|
		if i>j
                        puts "#{i} #{j}"
		end
	end
end

x,y,a,b=gets.chomp.split().map(&:to_i)
if a<=b
	a=b+1
end
count=0
i=a
while i<=x
	if i<=y
		min=i-1
	else
		min=y
	end
	count+=min-b+1
	i+=1
end
puts count
while a<=x
	if a<=y
		min=a-1
	else
		min=y
	end
	i=b
	while i<=min
		puts a.to_s+' '+i.to_s
		i+=1
	end
	a+=1

end

x,y,a,b = gets.split.map(&:to_i)
s = %w()
(a..x).each { |i| (b..y).each { |j| s.push [i, j] if i > j } }
puts s.size
s.each { |f| puts f*' ' }

#CF Round 149. Div II Prob. A - Heads or Tails
arr = gets.chomp.split(/ /)
a, res = [], []
arr.each {|i| a << i.to_i}
(a[2]..a[0]).each { |i|
    (a[3]..[a[1], i - 1].min).each { |j|
        res << (i.to_s + " " + j.to_s)
    }
}
puts res.size
res.each {|i| puts i}

#CF Round 149. Div II Prob. A - Heads or Tails
a = gets.chomp.split(/ /).map(&:to_i)
res = []
(a[2]..a[0]).each { |i|
    (a[3]..[a[1], i - 1].min).each { |j|
        res << (i.to_s + " " + j.to_s)
    }
}
puts res.size
res.each {|i| puts i}

x,y,a,b = gets.split.map(&:to_i)
ans = []
if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a).upto(x) do |i|
        (b).upto([(i-1),y].min) do |j|
            ans << "#{i} #{j}"
        end
    end
end
puts ans.length
ans.each { |i| puts i }

x, y, a, b = gets.split.collect{|i| i.to_i}
cnt = 0
for i in a..x
    for j in b...(i<y+1 ? i : y+1)
        cnt += 1
    end
end
puts cnt
for i in a..x
    for j in b...(i<y+1 ? i : y+1)
        print i, " ", j, "\n"
    end
end

x, y, a, b = gets.split.map { |x| x.to_i }
s = a > b ? a : b + 1
t = y + 1
ps = []
for i in s..x
  for j in b...[i, t].min
    ps << [i, j]
  end
end
puts ps.size
ps.each { |p| puts p * ' ' }

ans=Array.new
x,y,a,b=gets.split.map(&:to_i)
for i in a.to_i..x.to_i do
	for j in [b.to_i,a.to_i].max..[y.to_i,i].min
		ans<< [i,j] if i!=j
	end
end
ans.size!=0?(ans.each{|el|puts el.join(" ")}):(puts 0)

ans=Array.new
x,y,a,b=gets.split.map(&:to_i)
for i in a.to_i..x.to_i do
	for j in [b.to_i,a.to_i].max..[y.to_i,i].min
		ans<< [i,j] if i!=j
	end
end
ans.size!=0?(puts ans.size;ans.each{|el|puts el.join(" ")}):(puts 0)

x, y, a, b = gets.split(' ').collect!{ |i| i.to_i}
n = 0
x.downto(a) do |i|
	y.downto(b) do |j|
		if i>j
			n += 1
		end
	end
end

puts n

x.downto(a) do |i|
	y.downto(b) do |j|
		if i>j
                        puts "#{i} #{j}"
		end
	end
end

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

if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a+1).upto(x) do |i|
        (b).upto(i-1) do |j|
            print i,' ',j; puts
        end
    end
end

x,y,a,b = gets.split.map(&:to_i)
ans = []
if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a+1).upto(x) do |i|
        (b).upto([(i-1),b].min) do |j|
            ans << "#{i} #{j}"
        end
    end
end
puts ans.length
ans.each { |i| puts i }

x,y,a,b = gets.split.map(&:to_i)
ans = []
if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a+1).upto(x) do |i|
        (b).upto(i-1) do |j|
            ans << "#{i} #{j}"
        end
    end
end
puts ans.length
ans.each { |i| puts i }

x,y,a,b = gets.split.map(&:to_i)
ans = []
if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a+1).upto(x) do |i|
        (b).upto(i-1) do |j|
            ans << "#{i} #{j}"
        end
    end
end

ans.each { |i| puts i }

x,y,a,b = gets.split.map(&:to_i)
ans = []
if x <= b
    puts 0
    exit
else
    a = [a,b].max
    (a+1).upto(x) do |i|
        (b).upto([(i-1),y].min) do |j|
            ans << "#{i} #{j}"
        end
    end
end
puts ans.length
ans.each { |i| puts i }

x, y, a, b = gets.split.collect{|i| i.to_i}
cnt = 0
for i in b..y
    for j in i+1..x
        cnt += 1
    end
end
puts cnt
for i in b..y
    for j in i+1..x
        print j, " ", i, "\n"
    end
end


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

hs = Hash.new()
(0...n).each do |i|
  hs[ps[i]] = i
end

ans = n - 1
cnt = 1
for i in 2..n
  if hs[i - 1] < hs[i]
    cnt += 1
  else
    cnt = 1
  end
  ans = [ans, n - cnt].min
end

puts ans

#Good luk for the Contest 606, Problem: c
n = gets.strip.to_i
ar = gets.strip.split.map(&:to_i)

pos = Array.new(n, 0)
0.upto(n-1).each do |i|
	pos[ar[i]-1]  = i
end

res = 1
tmp = 1
1.upto(n-1).each do |i|
	if pos[i] > pos[i-1]
		tmp += 1
	else
		res = tmp if tmp >res
		tmp = 1
	end
end
res = tmp if tmp > res
puts n-res

n = gets.to_i
ps = gets.chomp.split.map(&:to_i)
d = Array.new(n, 0)
ps.each {|p| d[p - 1] = p == 1 ?  1 : d[p - 2] + 1 }
puts (n - d.max)

#Good luk for the Contest 606, Problem: c
n = gets.strip.to_i
ar = gets.strip.split.map(&:to_i)

pos = Array.new(n, 0)
0.upto(n-1).each do |i|
	pos[ar[i]-1]  = i
end

res = 1
tmp = 1
1.upto(n-1).each do |i|
	if pos[i] > pos[i-1]
		tmp += 1
	else
		res = tmp if tmp >res
		tmp = 1
	end
end
puts n-res

#Good luk for the Contest 606, Problem: c
n = gets.strip.to_i
ar = gets.strip.split.map(&:to_i)

pos = Array.new(n, 0)
0.upto(n-1).each do |i|
	pos[ar[i]-1]  = i
end

res = 0
tmp = 1
1.upto(n-1).each do |i|
	if pos[i] > pos[i-1]
		tmp += 1
	else
		res = tmp if tmp >res
		tmp = 1
	end
end
puts n-res


n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|i| i < y}
g = kk.count{|i| i >= y}
add_g = [0, (n + 1) / 2 - g].max
if l > n / 2 || kk.inject(:+).to_i + add_g * y + (n - k - add_g) > x
  puts -1
else
  ans = []
  add_g.times{ans << y}
  (n - k - add_g).times{ans << 1}
  puts ans.join(" ")
end

n,k,p,x,y=gets.chomp.split(' ').map(&:to_i)
ak=gets.chomp.split(' ').map(&:to_i)
one=0
two=0
sum=0
for i in ak do
	sum+=i
	if i<y
		one+=1
	else
		two+=1
	end
end

won=n/2-one
if won>(n-k)
	won=n-k
end
m=n-k-won
sum=x-sum
if won+y*m>sum ||won<0
	puts "-1"
else
	won.times do
		print "1 "
	end
	m.times do
		print y.to_s+' '
	end
end
puts

n,k,p,x,y=gets.chomp.split(' ').map(&:to_i)
ak=gets.chomp.split(' ').map(&:to_i).sort
ch=0
sum=0
for i in ak do
	sum+=i
end
ak.each_with_index { |i,j|
	if i>=y
		ch=j
		break
	end
}
left=n/2-ch
right=n-k-left

#puts "left = "+left.to_s
#puts "right = "+right.to_s
#puts "p = "+p.to_s
#puts "y = "+y.to_s
#puts "x = "+x.to_s
#puts "sum = "+sum.to_s
#puts "sum+left+right*y = "+ (sum+left+right*y).to_s

if(left<0)
	puts "-1"
elsif(p<y && right>0)
	puts "-1"
elsif(right<0)
	right=0;
	left=n-k-right;
elsif sum+left+right*y<=x
	left.times do
		print "1 "
	end
	right.times do
		print y.to_s+' '
	end
	puts
else
	puts "-1"
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|x| x < y}
g = k - l

if l > n / 2 || (n / 2 - l) * 1 + [(n - n / 2 - g), 0].max * y + kk.inject(:+).to_i > x
  puts -1
else
  ans = []
  (n - k).times do
    if kk[(kk.size - 1) / 2].to_i >= y
      kk << 1
      ans << 1
    else
      kk << y
      ans << y
    end
    kk.sort!
  end
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|x| x < y}
g = k - l
if l > n / 2 || (n / 2 - l) * 1 + (n - n / 2 - g) * y + kk.inject(:+).to_i > x
  puts -1
else
  ans = []
  (n - k).times do
    if kk[(kk.size - 1) / 2].to_i >= y
      kk << 1
      ans << 1
    else
      kk << y
      ans << y
    end
    kk.sort!
  end
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|x| x < y}
g = k - l
if l > n / 2 || g > n / 2 || (n / 2 - l) * 1 + (n / 2 - g) * y + kk.inject(:+).to_i > x
  puts -1
else
  ans = []
  (n - k).times do
    if kk[(kk.size - 1) / 2].to_i >= y
      kk << 1
      ans << 1
    else
      kk << 4
      ans << 4
    end
    kk.sort!
  end
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|i| i < y}
g = kk.count{|i| i >= y}
add_g = [0, (n + 1) / 2 - g].max
if l > n / 2 || kk.inject(:+).to_i + add_g * y + (n - k - add_g) > x
  puts -1
else
  ans = []
  (n - k).times do
    if kk[kk.size / 2] < y
      kk << y
      ans << y
    elsif kk.size < n
      kk << 1
      ans << 1
    end
  end
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|x| x < y}
g = k - l
if l > n / 2 || g > n / 2 || (n / 2 - l) * 1 + (n - n / 2 - g) * y + kk.inject(:+).to_i > x
  puts -1
else
  ans = []
  (n - k).times do
    if kk[(kk.size - 1) / 2].to_i >= y
      kk << 1
      ans << 1
    else
      kk << y
      ans << y
    end
    kk.sort!
  end
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
ans = []
if k > 0
  kk = gets.split.map(&:to_i)
else
  kk = [y]
  ans << y
end
l = kk.count{|x| x < y}
g = kk.count{|x| x > y}
p_n = x - kk.inject(:+)
if l > n / 2 || g > n / 2 || (n / 2 - l) * 1 + (n / 2 - g) * y > p_n
  puts -1
else
  (n / 2 - l).times{ans << 1}
  (n / 2 - g).times{ans << y}
  puts ans.join(" ")
end

n, k, p, x, y = gets.split.map(&:to_i)
kk = gets.split.map(&:to_i).sort
l = kk.count{|x| x < y}
g = kk.count{|x| x > y}
p_n = x - kk.inject(:+)
if l > n / 2 || g > n / 2 || (n / 2 - l) * 1 + (n / 2 - g) * y > p_n
  puts -1
else
  ans = []
  (n / 2 - l).times{ans << 1}
  (n / 2 - g).times{ans << y}
  puts ans.join(" ")
end


str = gets.chomp
last = -1
ans = 0
(3...str.size).step(1) { |i|
  last = i-3 if str[i-3..i] == 'bear'
  ans += last + 1
}
puts ans

s=gets.chomp
l=s.size
p=0
r=0
while (q=s.index('bear',p))
  r+=(l-q-3)*(q-p+1)
  p=q+1
end
p r

s, r, x = gets.chomp, 0, -1

(s.length - 3).times do |i|
    x = i if s[i..i+3] == 'bear'
    r += x + 1
end

p r

#f = File.open('test1.txt', 'r')
f = STDIN
s = f.gets.chomp
res = 0
length = s.length
length.times do |i|
  j = s.index 'bear', i
  next unless j
  j += 3
  res += length - j
end
puts res

str = gets.chomp

def eq_bear?(str)
	str[(0..3)] == "bear"
end

sum = 0
last = -1
(0...str.length).each do |i|
	if eq_bear? str[(i..(i + 3))]
		sum += (i - last) * (str.length - (i + 3))
		last = i
	end
end

puts sum

s, r = gets.chomp, 0
n = s.length
x = 1

s.each_char.with_index do |c, i|
    if (i < n-3) && s[i] + s[i+1] + s[i+2] + s[i+3] == 'bear'

        r += (i+x) * (n - i - 3)
        x = 0 if x == 1
    end
end

p r


class String
  def rbs?
    b = 0
    self.each_char { |c|
      b += 1 if c == '('
      b -= 1 if c == ')'
      return false if b < 0
    }
    b == 0
  end
end

gets.to_i.times do
  s = gets.strip

  solution_found = false
  8.times do |m|
    a = '()'[(m >> 0) & 1]
    b = '()'[(m >> 1) & 1]
    c = '()'[(m >> 2) & 1]
    t = s.gsub('A', a).gsub('B', b).gsub('C', c)
    solution_found = true if t.rbs?
  end

  puts(solution_found ? "YES" : "NO")
end

def solve
  a = string
  n = a.size
  (1 << 3).times do |bits|
    paren = 0
    xa = 1 - bits[0] * 2
    xb = 1 - bits[1] * 2
    xc = 1 - bits[2] * 2
    valid = true
    a.each_char do |c|
      case c
      when ?A
        paren += xa
      when ?B
        paren += xb
      when ?C
        paren += xc
      end
      if paren < 0
        valid = false
        break
      end
    end
    valid &&= (paren == 0)
    if valid
      puts "YES"
      return
    end
  end
  puts "NO"
end

def main
  t = int
  t.times do
    solve
  end
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(No Yes)
INF = 10**9

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def rep(n, &b); Array.new(n, &b) end
def yes; puts YESNO[1] end
def no; puts YESNO[0] end
def yesno t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * mod_inv(y, mod) % mod end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main

def good(s)
  cur = 0
  s.each_char do |c|
    cur += c == '(' ? 1 : -1
    return false if cur < 0
  end
  cur == 0
end
gets.to_i.times do
  s = gets.chomp
  ok = false
  (0...8).each do |msk|
    cur = s.dup
    (0...s.size).each do |i|
      if msk >> (s[i].ord - 'A'.ord) & 1 != 0
        cur[i] = '('
      else
        cur[i] = ')'
      end
    end
    ok |= good cur
  end
  puts ok ? "YES" : "NO"
end

def good(s)
  cur = 0
  s.each_char do |c|
    cur += c == '(' ? 1 : -1
    return false if cur < 0
  end
  cur == 0
end
gets.to_i.times do
  s = gets.chomp
  ok = false
  (0..7).each do |msk|
    cur = s
    (0...s.size).each do |i|
      if (msk >> (s[i].ord - 'A'.ord)) & 1 != 0
        cur[i] = '('
      else
        cur[i] = ')'
      end
      ok |= good cur
    end
  end
  puts ok ? "YES" : "NO"
end

def good(s)
  cur = 0
  s.each_char do |c|
    cur += c == '(' ? 1 : -1
    return false if cur < 0
  end
  cur == 0
end
gets.to_i.times do
  s = gets.chomp
  ok = false
  (0..7).each do |msk|
    cur = s
    (0...s.size).each do |i|
      if msk >> (s[i].ord - 'A'.ord) & 1 != 0
        cur[i] = '('
      else
        cur[i] = ')'
      end
      ok |= good cur
    end
  end
  puts ok ? "YES" : "NO"
end

def good(s)
  cur = 0
  s.each_char do |c|
    cur += c == '(' ? 1 : -1
    return false if cur < 0
  end
  cur == 0
end
gets.to_i.times do
  s = gets.chomp
  ok = false
  (1..7).each do |msk|
    cur = s
    (0...s.size).each do |i|
      if msk >> (s[i].ord - 'A'.ord) & 1 != 0
        cur[i] = '('
      else
        cur[i] = ')'
      end
      ok |= good cur
    end
  end
  puts ok ? "YES" : "NO"
end


n = STDIN.gets.to_i
scores = {}
(0...n).each do |it|
	name, score = STDIN.gets.split ' '
	score = score.to_i
	if scores.has_key? name
		scores[name] = [scores[name], score].max
	else
		scores[name] = score
	end
end

p scores.size
scores.keys.each do |i|
	score = scores[i]
	not_worse = 0
	better = 0
        scores.values.each do |j|
        	if j <= score
        		not_worse += 1
		else
			better += 1
		end
        end
        category = ""
        if better > 0.5 * scores.size
        	category = "noob"
	elsif better > 0.2 * scores.size
		category = "random"
	elsif better > 0.1 * scores.size
		category = "average"
	elsif better > 0.01 * scores.size
		category = "hardcore"
	else
		category = "pro"
	end
	puts "#{i} #{category}"
end

result = Hash.new
result.default = 0
n = gets.to_i
n.times do
  a,b = gets.split
  b = b.to_i
  result[a] = [result[a],b].max
end
array = result.sort
m=array.length
puts m
m.times do |i|
  cnt=0
  tmp=array[i][1]
  m.times{|j|
    cnt+=1 if tmp<array[j][1]
  }
  print array[i][0]
  per=100.0-cnt*100.0/m
  if per>=99.0
    puts " pro"
  elsif per>=90.0
    puts " hardcore"
  elsif per>=80.0
    puts " average"
  elsif per>=50.0
    puts " random"
  else
    puts " noob"
  end
end

def classify(percent)
  return "noob" if percent > 50.0
  return "random" if percent > 20.0
  return "average" if percent > 10.0
  return "hardcore" if percent > 1.0
  return "pro"
end

n = gets.chomp.to_i
h = Hash.new()
for i in 0..n-1
  nm, pt = gets.chomp.split(/ /)
  pt = pt.to_i
  if h.key?(nm)
    if h[nm] < pt
      h[nm] = pt
    end
  else
    h[nm] = pt
  end
end

a = h.to_a
n = a.length
a.sort!{|a1, a2|
  a2[1] <=> a1[1]
}
ret = []
wkper = 0
prev = 0
for i in 0..n-1
  if prev > a[i][1]
    wkper = (i / n.to_f) * 100
  end
  ret << [a[i][0], classify(wkper)]
  prev = a[i][1]
end
ret.sort!{|r1, r2|
  r1[0] <=> r2[0]
}
puts n
ret.each{|rr|
  puts rr.join(" ")
}

result = Hash.new
result.default = 0
n = gets.to_i
n.times do
  a,b = gets.split
  b = b.to_i
  result[a] = [result[a],b].max
end

array = result.sort
m=array.length
puts m
m.times{|i|
  cnt=0
  tmp=array[i][1]
  m.times{|j|
    cnt+=1 if tmp<array[j][1]
  }
  print array[i][0]
  per=100.0-cnt*100.0/m
  if per>=99.0
    puts " pro"
  elsif per>=90.0
    puts " hardcore"
  elsif per>=80.0
    puts " average"
  elsif per>=50.0
    puts " random"
  else
    puts " noob"
  end
}

result = Hash.new
result.default = 0
n = gets.to_i
n.times do
  a,b = gets.split
  b = b.to_i
  result[a] = [result[a],b].max
end

array = result.sort
m=array.length
m.times{|i|
  cnt=0
  tmp=array[i][1]
  m.times{|j|
    cnt+=1 if tmp<array[j][1]
  }
  print array[i][0]
  per=100.0-cnt*100.0/m
  if per>99.0
    puts " pro"
  elsif per>90.0
    puts " hardcore"
  elsif per>80.0
    puts " average"
  elsif per>50.0
    puts " random"
  else
    puts " noob"
  end
}


k = gets.to_i
n = gets.chomp.chars.map(&:to_i).sort
s = n.map(&:to_i).reduce(0, :+)
d = 0
n.each{|x|
  break if s>=k
  d += 1
  s += 9 - x
}
p d

k = gets.to_i
n = gets.chomp.split('').map(&:to_i).sort
sum = n.inject(:+)
ans = 0
idx = 0
while sum < k
    sum += 9 - n[idx]
    idx += 1
    ans += 1
end
puts ans

k=gets.to_i
n=gets.chomp.chars.sort.map &:to_i
x=n.inject :+
res=0
while x<k
    x+=9-n[res]
    res+=1
end
puts res

k=gets.to_i
n=gets.chars.sort.map &:to_i
x=n.inject :+
res=0
while x<k
    x+=9-n[res]
    res+=1
end
puts res

k=gets.to_i
n=gets
x=n.chars.map(&:to_i).inject(:+)
puts (x<k ? 1 : 0)


h, l = STDIN.read.split("\n")

l.each_char do |c|
  next if c == ' '
  i = h.index c
  (print :NO; exit) if i.nil?
  h[i] = ''
end

print :YES

str=gets
str2=gets

symbols=str2.scan(/(\w)/)
r=true
symbols.each{|i|
	if str=~/#{i}/
		str=str.sub(/#{i}/,"")
#		print "Found ",i,"\nstr=",str,"\n"
	else
#		print "Not found ",i,"\nstr=",str,"\n"
		r=false
		break
	end
}
if r then print "YES"
else print "NO"
end

a=[*gets.chars]
puts gets.scan(/\S/).all?{|b|(c=a.index b)&&a.delete_at(c)}?:YES:"NO"

#=================================
require 'prime'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

txt=gets.strip.gsub(/[^a-zA-Z]/,'')
msg=gets.strip.gsub(/[^a-zA-Z]/,'')

ans=true
msg.each_char{|c|
	(ans=false and break) if !(txt.count(c)>=msg.count(c))
}

puts ans ? :YES : :NO

def main()
	s1=gets.chomp.to_s
	s2=gets.chomp.to_s
	charavail=[]
	for i in 0...(s1.length)
		if s1[i].chr!=" "
		charavail << s1[i].chr
		end
	end
	f=true
	for i in 0...(s2.length)
		if s2[i].chr!=" "
			if charavail.include?(s2[i].chr)
				ind=charavail.index(s2[i].chr)
				charavail.delete_at(ind)
			else
				f=false
				break;
			end
		end
	end
	if f
		puts "YES"
	else
		puts "NO"
	end
end
main()

s1 = gets.chomp!.gsub(" ","")
s2 = gets.chomp!.gsub(" ","")

s2.each_char { |c|
  index = s1.index(c)
  if index == nil
    puts "NO"
    exit
  else
    s1[index..index] = ""
  end
}

puts "YES"

s1, s2 = gets.chomp, gets.chomp

s1 = s1.scan(/./).reject{ |x| x =~ /\s+/ }
s2 = s2.scan(/./).reject{ |x| x =~ /\s+/ }

res = true
s2.each do |char|
  i = s1.index(char)
  if i
    s1.delete_at(i)
  else
    res = false
    break
  end
end

puts res ? "YES" : "NO"

require 'set'

YES, NO = "YES", "NO"

def get_table(test)
  result = Hash.new(0)
  test.gsub(/\s+/, '').each_char { |char| result[char] += 1 }
  result
end

header, text = get_table(gets), get_table(gets)

ok = true

text.each_key do |letter|
  if text[letter] > header[letter]
    ok = false
    break
  end
end

puts ok ? YES : NO

str=gets
str2=gets
#str="Instead of dogging Your footsteps it disappears but you dont notice anything"
#str2="where is your dog"

symbols=str2.scan(/(\w)/)
r=true
symbols.each{|i|
	if str=~/#{i}/
		str=str.sub(/#{i}/,"")
	else
		r=false
		break
	end
}
if r then p "YES"
else print "NO"
end

#=================================
require 'prime'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

txt=gets.strip
msg=gets.strip

ans=true
msg.each_char{|c|
	(ans=false and break) if !(msg.count(c)>=txt.count(c))
}

puts ans ? :YES : :NO

s1 = gets.chomp!.gsub(" ","")
s2 = gets.chomp!.gsub(" ","")

s2.each_char { |c|
  if s1.index(c) == nil
    puts "NO"
    exit
  end
}

puts "YES"


t = gets.to_i
ans = []
t.times do
  n,m = gets.chomp.split(" ").map(&:to_i)
  k = gets.chomp.split(" ").map(&:to_i).sort!.reverse!
  c = gets.chomp.split(" ").map(&:to_i)
  sum = 0
  index = 0
  n.times do |i|
    if c[k[i]-1] > c[index]
      sum += c[index]
      index += 1
    else
      sum += c[k[i]-1]
    end
  end
  ans << sum
end
puts ans

t= gets.chomp.to_i
while t > 0
 n, m   = gets.chomp.split(' ')
 n = n.to_i
 m = m.to_i
 k = gets.chomp.split(' ').map(&:to_i)
 c = gets.chomp.split(' ').map(&:to_i)
 k = k.sort.reverse()
 last_used_gift = 0
 cost = 0
 k.each do |ks|
  if(c[ks-1] > c[last_used_gift] && last_used_gift < m)
  	cost = cost + c[last_used_gift]
  	last_used_gift = last_used_gift + 1
  else
  	cost = cost + c[ks-1]
  end
 end
 puts cost
 t = t - 1
end


a=gets.chomp.to_i
b=gets.chomp.split(" ")
0.upto(a-1) {|i| b[i]=b[i].to_i}
b.sort!
if a%2==0
0.upto (a/2-1) do |i|
printf "#{b[i]} #{b[a/2+i]} "
end
else
0.upto (a/2) do |i|
if i!=a/2
printf "#{b[i]} #{b[a/2+1+i]} "
else
printf "#{b[i]}"
end
end
end

n = gets.to_i
a = gets.split(" ").map(&:to_i).sort
i = 0
j = n-1

b = []
while true do
  b << a[i]
  i += 1
  break if i > j
  b << a[j]
  j -= 1
  break if i > j
end

valid = true
n.times do |i|
  if (i+1).even?
    valid = false if b[i] < b[i-1]
  elsif (i+1).odd? && i > 0
    valid = false if b[i] > b[i-1]
  end
end

puts valid ? b.join(" ") : "Impossible"

n = gets.to_i
a = gets.split.map(&:to_i)
for i in 0..n-1
    if (i+1)%2==0 then printf "%d ", a.max; a.delete_at a.index(a.max);
    else printf "%d ", a.min; a.delete_at a.index(a.min); end
end

n = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
res = []
for i in 0..n[0] - 1 do
  if i == 0 or (i + 1) % 2 != 0
    res[i] = arr.min
  else
    res[i] = arr.max
  end
  arr.delete_at(arr.index(res[i]) || arr.length)
end
puts res.join(' ')

#!/usr/bin/env ruby

n = gets.to_i
inp = gets.split.map(&:to_i)
for i in 0..n-1
  if (i+1) % 2 == 0 then printf "%d ", inp.max; inp.delete_at inp.index(inp.max)
  else printf "%d ", inp.min; inp.delete_at inp.index(inp.min) end
end
puts

n = readline.to_i
arr = readline.split(' ').collect(&:to_i).sort
arr[0..(n / 2)].zip(arr[(n / 2 + 1)..-1]).flatten.compact.each_with_index do |num, ind|
  print " " if ind != 0
  print num
end
puts ""

gets
a = gets.split.map(&:to_i)
a.sort!
b = []
a.size.times do |i|
  if i.even?
    b << a.shift
  else
    b << a.pop
  end
end
puts b.join ' '

n=gets.to_i
a=gets.split(' ')
for i in 0..a.size-1
	a[i]=a[i].to_i
end
a=a.sort
l=0
r=a.size-1
ans=""
while l<=r
	ans+=" #{a[l]}"
	ans+=" #{a[r]}" if l<r
	l+=1
	r-=1
end
puts ans.strip

gets # ignore
sorted = gets.split(" ").map(&:to_i).sort
lo, hi = 0, sorted.length - 1

ret = []
while lo < hi
  ret << sorted[lo]
  ret << sorted[hi]

  lo += 1
  hi -= 1
end
ret << sorted[hi] if lo == hi

puts ret.join(" ")

gets # ignore
arr = gets.split(" ").map(&:to_i)

if arr.length <= 1
  puts arr.join(" ")
  exit
end

len = arr.length
do_swap = len % 2 != 0

sorted = arr.sort

lo = 0
hi = len/2

ret = []
(0...(len/2)).each do
  ret << sorted[lo]
  ret << sorted[hi]

  lo += 1
  hi += 1
end

if do_swap
  tmp = ret[-1]
  ret[-1] = sorted[hi]
  ret << tmp
end

puts ret.join(" ")

n = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
res = []
for i in 0..n[0] - 1 do
  if i == 0 or (i + 1) % 2 != 0
    res[i] = arr.min
  else
    res[i] = arr.max
  end
  arr.delete_at(i)
end
puts res.join(' ')

n = readline.to_i
arr = readline.split(' ').collect(&:to_i).sort
puts arr
arr[0..(n / 2)].zip(arr[(n / 2 + 1)..-1]).flatten.compact.each_with_index do |num, ind|
  print " " if ind != 0
  print num
end
puts ""

gets # ignore
arr = gets.split(" ").map(&:to_i)
if arr.length <= 1
  puts "Impossible"
  exit 0
end

len = arr.length
do_swap = len % 2 != 0

sorted = arr.sort

lo = 0
hi = len/2

ret = []
(0...(len/2)).each do
  ret << sorted[lo]
  ret << sorted[hi]

  lo += 1
  hi += 1
end

if do_swap
  tmp = ret[-1]
  ret[-1] = arr[hi]
  ret << tmp
end

puts ret.join(" ")

gets # ignore
arr = gets.split(" ").map(&:to_i)

if arr.length <= 1
  puts arr.join(" ")
  exit
end

len = arr.length
do_swap = len % 2 != 0

sorted = arr.sort

lo = 0
hi = len/2

ret = []
(0...(len/2)).each do
  ret << sorted[lo]
  ret << sorted[hi]

  lo += 1
  hi += 1
end

if do_swap
  tmp = ret[-1]
  ret[-1] = arr[hi]
  ret << tmp
end

puts ret.join(" ")

gets # ignore
sorted = gets.split(" ").map(&:to_i).sort
lo, hi = 0, sorted.length - 1

ret = []
while lo < hi
  ret << sorted[lo]
  ret << sorted[hi]

  lo += 1
  hi -= 1
end
ret << sorted[hi]

puts ret.join(" ")