if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

nmk = gets.chomp.split(" ").map(&:to_i)
n = nmk[0]
m = nmk[1]
k = nmk[2]

power = gets.chomp.split(" ").map(&:to_i)
schools = gets.chomp.split(" ").map(&:to_i)
chosen = gets.chomp.split(" ").map(&:to_i)

schoolsarr = []
m.times {schoolsarr.push []}

(0..n-1).each do |i|
	schoolsarr[schools[i]-1].push power[i]
end

(0..m-1).each do |i|
	schoolsarr[i].sort!
end

ans = 0

#p schoolsarr

chosen.each do |z|
	ind = z-1
#	p ind
#	p schools[ind]
	if (power[ind]!=schoolsarr[schools[ind]-1][-1])
		ans+=1
	end
end

puts ans

a = gets.rstrip.split.map(&:to_i)
n = a[0]
m = a[1]
k = a[2]

powers = gets.rstrip.split.map(&:to_i)
schools = gets.rstrip.split.map(&:to_i)
chosen = gets.rstrip.split.map(&:to_i)
count = 0
chosen.each do |chosen_one|
	school = schools[chosen_one - 1]
	max_power = 0
	schools.each_with_index do |student, i|
		next unless student == school
		max_power = powers[i] if max_power < powers[i]
	end
	count += 1 if powers[chosen_one - 1] < max_power
end

p count

n, m, k = gets.strip.split(" ").map(&:to_i)

powers  = gets.split(" ").map(&:to_i)
schools = gets.split(" ").map(&:to_i)
choosens = gets.split(" ").map(&:to_i)

made_up_cnt = 0
choosens.each do |student|
  schools.each_with_index do |school, index|
    if student-1 != index and schools[student-1] == school and powers[student-1] < powers[index]
      made_up_cnt += 1
      break
    end
  end
end

puts made_up_cnt

n, m, k = gets.strip.split(" ").map(&:to_i)

powers  = gets.split(" ").map(&:to_i)
schools = gets.split(" ").map(&:to_i)
choosens = gets.split(" ").map(&:to_i)

made_up_cnt = 0
choosens.each do |student|
  schools.each_with_index do |school, index|
    if schools[student-1] == school and powers[student-1] < powers[index]
      made_up_cnt += 1
    end
  end
end

puts made_up_cnt

n, m, k = gets.strip.split(" ").map(&:to_i)

powers  = gets.split(" ").map(&:to_i)
schools = gets.split(" ").map(&:to_i)
choosens = gets.split(" ").map(&:to_i)

made_up_cnt = 0
choosens.each do |student|
  schools.each_with_index do |school, index|
    if student-1 != index and schools[student-1] == school and powers[student-1] < powers[index]
      made_up_cnt += 1
    end
  end
end

puts made_up_cnt


#!/usr/bin/env ruby

class MeetingPlace
  attr_accessor :n, :x, :v, :zip, :result

  def get_data
    # fl=File.new "test0.txt"
    # @n,@x,@v = fl.readlines.map {|x| x.split.map(&:to_i)}
    @n, @x, @v = $stdin.readlines.map { |x| x.split.map(&:to_i) }
    @n = @n[0]
  end

  def output
    puts @result
  end

  def init
    @zip = @x.zip @v
    @x, @v = nil, nil
    @zip = @zip.sort { |a, b| a[0]<=>b[0] }
    @zipUp = @zip.each
    @zipDown = @zip.reverse_each
    @upper = @zipDown.next
    @lower =@zipUp.next
    @upperPrev = @upper
    @lowerPrev = @lower
    @direction = nil
    @result = (@upper[0] - @lower[0]).to_f / (@upper[1] + @lower[1])
    @lowerPtr = 0
    @upperPtr = @zip.length - 1
  end

  def getNext
    return false if @lowerPtr == @upperPtr
    if @upper[1] > @lower[1]
      @upper = @zipDown.next
      @direction = :down
      @upperPtr-=1
    else
      @lower = @zipUp.next
      @direction = :up
      @lowerPtr+=1
    end
    true
  end

  def get_result
    init
    while getNext
      if @direction == :down
        tmp = (@upper[0] - @lowerPrev[0]).to_f / (@upper[1] + @lowerPrev[1])
      else
        tmp = (@upperPrev[0] - @lower[0]).to_f / (@upperPrev[1] + @lower[1])
      end
      if tmp > @result
        @result = tmp
        if @upper[1] != @upperPrev[1]
          @upperPrev = @upper
        else
          @lowerPrev = @lower
        end
      end
    end
    @result = @result.round(6)
  end
end

if __FILE__ == $0
  mp = MeetingPlace.new
  mp.get_data
  mp.get_result
  mp.output
end

gets
xv = gets.split.map(&:to_f).zip(gets.split.map(&:to_f)).sort
aa, res = (bb = []), [0.0]
begin
  u = 2e9
  xv.each { |x, v|
    if u > v
      u = v
      bb << [x, v]
    end
  }
  break if !aa.equal?(bb)
  bb = []
  xv.reverse!
end while true
aa.each { |x, v|
  bb.each { |y, u|
    break if y <= x
    res << (y - x) / (u + v)
  }
}
p res.max

def read_ints
  gets.split.map(&:to_i)
end

n = gets.to_i
a = read_ints.zip(read_ints)

l = 0.0
r = 1e9
100.times do
  c = (l + r) / 2
  mx = a.map{|x, v| x - v * c}.max
  mi = a.map{|x, v| x + v * c}.min
  if mx > mi
    l = c
  else
    r = c
  end
end
p (l + r) / 2

#!/usr/bin/env ruby

class MeetingPlace
  attr_accessor :n, :x, :v, :zip, :result

  def get_data
    # fl=File.new "test0.txt"
    # @n,@x,@v = fl.readlines.map {|x| x.split.map(&:to_i)}
    @n, @x, @v = $stdin.readlines.map { |x| x.split.map(&:to_i) }
    @n = @n[0]
  end

  def output
    puts @result
  end

  def init
    @zip = @x.zip @v
    @x, @v = nil, nil
    @zip = @zip.sort { |a, b| a[0]<=>b[0] }
    @zipUp = @zip.each
    @zipDown = @zip.reverse_each
    @upper = @zipDown.next
    @lower =@zipUp.next
    @upperPrev = @upper
    @lowerPrev = @lower
    @result = (@upper[0] - @lower[0]).to_f / (@upper[1] + @lower[1])
  end

  def getNext
    return false if @upper[0] == @lower[0]
    if @upper[1] > @lower[1]
      @upper = @zipDown.next
    else
      @lower = @zipUp.next
    end
    true
  end

  def get_result
    init
    while getNext
      tmp = (@upper[0] - @lower[0]).to_f / (@upper[1] + @lower[1])
      @result = tmp if tmp > @result
    end
    @result = @result.round(6)
  end
end

if __FILE__ == $0
  mp = MeetingPlace.new
  mp.get_data
  mp.get_result
  mp.output
end


#!/usr/bin/env ruby
# encoding: utf-8
n = gets.to_i
a = gets.split.map(&:to_i)
g = Array.new(n) { [] }

(n-1).times do
    u, v = gets.split.map(&:to_i)
    u, v = u-1, v-1
    g[u] << v
    g[v] << u
end

def GCD(a, b)
    return b == 0 ? a : GCD(b, a%b)
end

dp = Array.new(n) { Array.new(2) { [] } }
dp[0] = [[a[0]], [0]]
par = [-1]*n

st = [0]
until st.empty?
    u = st.pop
    g[u].each do |v|
        next if v == par[u]
        par[v] = u
        st.push(v)
        dp[v][0] += dp[u][0].map{|x| GCD(x,a[v])}
        dp[v][1] += dp[u][0]
        dp[v][1] += dp[u][1].map{|x| GCD(x,a[v]) }
        2.times do |i|
            dp[v][i].uniq!
        end
    end
end

print a[0]
for u in 1...n do
    print " #{dp[u][1].max}"
end

n = gets.to_i
a = gets.split.map &:to_i
g = Array.new(n) { [] }

(n-1).times do
    u, v = gets.split.map &:to_i
    u, v = u-1, v-1
    g[u] << v
    g[v] << u
end

def GCD(a, b)
    return (b == 0) ? a : GCD(b, a%b)
end

dp = Array.new(n) { Array.new(2) { [] } }
dp[0] = [[a[0]], [0]]
par = [-1]*n

q = [0]
until q.empty?
    u = q.shift
    g[u].each do |v|
        next if v == par[u]
        par[v] = u
        q.unshift(v)
        dp[u][0].each do |x|
            dp[v][0] << GCD(x, a[v]);
            dp[v][1] << x
        end
        dp[u][1].each do |x|
            dp[v][1] << GCD(x, a[v])
        end
        for i in 0..1 do
            dp[v][i].uniq!
        end
    end
end

print a[0]
for u in 1...n do
    print " #{dp[u][1].max}"
end


n, r, avg = gets.split.map(&:to_i)
total = avg * n

arr = []
n.times do
   ai, bi = gets.split.map(&:to_i)
   total -= ai
   arr << [bi, ai]
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, r - item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

n, r, avg = gets.split.map(&:to_i)
total = avg * n

arr = []
n.times do
   ai, bi = gets.split.map(&:to_i)
   total -= ai
   if r > ai
       arr << [bi, r - ai]
   end
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

n, r, avg = gets.split.collect {|x| x.to_i}
total = avg * n

arr = []
n.times do
   ai, bi = gets.split.collect {|x| x.to_i}
   total -= ai
   arr.push [bi, ai]
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, r - item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

n, r, avg = gets.split(" ").collect {|x| x.to_i}
total = avg * n

arr = []
n.times do
   ai, bi = gets.split(" ").collect {|x| x.to_i}
   total -= ai
   arr.push [bi, ai]
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, r - item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

n, r, avg = gets.split.map(&:to_i)
total = avg * n

arr = []
n.times do
   ai, bi = gets.split.map(&:to_i)
   total -= ai
   arr.push [bi, ai]
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, r - item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

n, r, avg = gets.split(' ').map(&:to_i)
total = avg * n

arr = []
n.times do
   ai, bi = gets.split(' ').map(&:to_i)
   total -= ai
   arr.push [bi, ai]
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, r - item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

#! /usr/bin/env ruby
# coding: utf-8

n, r, avg = gets.chomp.split.map(&:to_i)
req = n * avg

s = []
n.times do
  tmp = gets.split.map(&:to_i)
  req -= tmp[0]
  unless r <= tmp[0]
    tmp[0] = r - tmp[0]
    s << tmp
  end
end

if req <= 0
  puts 0
  exit 0
end

s.sort_by! { |a| a[1] }

i = 0
essays = 0
while 0 < req and i < n
  a = s[i][0]
  essay = s[i][1]
  if req <= a
    essays += req * essay
    break
  end
  essays += a * essay
  i += 1
  req -= a
end

puts essays

#! /usr/bin/env ruby
# coding: utf-8

n, r, avg = gets.chomp.split.map(&:to_i)
req = n * avg

s = []
n.times do
  tmp = gets.split.map(&:to_i)
  req -= tmp[0]
  unless r <= tmp[0]
    #tmp[0] = r - tmp[0]
    s << tmp
  end
end

if req <= 0
  puts 0
  exit 0
end

s.sort_by! { |a| a[1] }

i = 0
essays = 0
while 0 < req and i < n
  grade = s[i][0]
  essay = s[i][1]
  a = (r - grade)
  if req <= a
    essays += req * essay
    break
  end
  essays += a * essay
  i += 1
  req -= a
end

puts essays

class Point
  def initialize(a,b)
    @a = a
    @b = b
  end
  def a
    @a
  end
  def b
    @b
  end
end

p= Array.new
n , r , avg = gets.split.map(&:to_i)
sum, ans, i= 0, 0, 0
n.times do
  x, y= gets.split.map(&:to_i)
  p<<Point.new(x,y)
  sum += x
end

p.sort_by!{|x| x.b}

  until sum>=avg*n
    sum += r-p[i].a
    ans += (r-p[i].a)*p[i].b
    i += 1
  end
  r=ans-(sum-avg*n)*p[i-1].b
  puts r>0?r:0

def read_ints; STDIN.gets.split.map(&:to_i); end

n, r, avg = read_ints
avg *= n
a = []
cur_avg = 0
n.times do
  a << read_ints
  cur_avg += a[-1][0]
end
ans = 0
a.sort_by!{|x| x[1]}
a.each do |x|
  break if cur_avg >= avg
  mn =[r - x[0], avg - cur_avg].min
    ans += mn * x[1]
    cur_avg += mn
end
puts ans

def read_ints; STDIN.gets.split.map(&:to_i); end

n, r, avg = read_ints
avg *= n
a = []
cur_avg = 0
n.times do
  a << read_ints
  cur_avg += a[-1][0]
end
if cur_avg >= avg
  puts 0
  exit 0
end
ans = 0
a.sort_by!{|x| x[1]}
a.each do |x|
  if r - x[0] >= avg - cur_avg
    ans += x[1] * (avg - cur_avg)
    break
  end
    ans += (r - x[0]) * x[1]
    cur_avg += (r - x[0])
end

puts ans

def read_ints; STDIN.gets.split.map(&:to_i); end

n, r, avg = read_ints
avg *= n
a = []
cur_avg = 0
n.times do
  a << read_ints
  cur_avg += a[-1][0]
end
if cur_avg >= avg
  puts 0
  exit 0
end
ans = 0
a.sort_by{|x| x[1]}.each do |x|
  if r - x[0] >= avg - cur_avg
    ans += x[1] * (avg - cur_avg)
    break
  end
    ans += (r - x[0]) * x[1]
    cur_avg += (r - x[0])
end

puts ans

#$stdin = File.open("input.txt")

n, r, avg = gets.split.map &:to_i
exams = gets(nil).split("\n").map { |line| line.split.map &:to_i }

need = avg * n
have = exams.transpose.first.inject(:+)

exams.sort! { |a, b| a.last <=> b.last }

essays = 0
while have < need
	a, b = exams.first

	up = [need - have, r - a].min

	have   += up
	essays += up * b

	exams.shift
end

puts essays

def read_ints; STDIN.gets.split.map(&:to_i); end
n, r, avg = read_ints
a = []
i = 0
curSum = 0
n.times do
  a << read_ints
  a[i].reverse!
  curSum+= a[i][1]
  i+=1
end
a.sort!
avgSum = avg*n
resEssays = 0
i=0
while(curSum<avgSum)
  j = [avgSum - curSum, r - a[i][1]]
  curEssays = j.min
  resEssays+= curEssays * a[i][0];
  curSum += curEssays
  i+=1
end
puts resEssays

class Stu
  attr_accessor:a
  attr_accessor:b
end

pa=Array.new
pb=Array.new

str=gets.to_s
pa=str.split
n=pa[0].to_i
r=pa[1].to_i
avg=pa[2].to_i
s=n*avg

for i in 0..n-1
  str=gets.to_s
  pa=str.split
  pb[i]=Stu.new
  s-=pa[0].to_i
  pb[i].a=r-pa[0].to_i
  pb[i].b=pa[1].to_i
end

if s<0
  s=0
end
pb=pb.sort_by{|x| x.b}
#p pb

k=0
for i in 0..n-1
  if pb[i].a>=s
    k+=pb[i].b*s
    break
  else
    s-=pb[i].a
    k+=pb[i].b*pb[i].a
  end
end

puts k

class Stu
  attr_accessor:a,:b
end

pa=Array.new
pb=Array.new

str=gets.to_s
pa=str.split
n=pa[0].to_i
r=pa[1].to_i
avg=pa[2].to_i
s=n*avg

for i in 0..n-1
  str=gets.to_s
  pa=str.split
  pb[i]=Stu.new
  s-=pa[0].to_i
  pb[i].a=r-pa[0].to_i
  pb[i].b=pa[1].to_i
end

if s<0
  s=0
end

pb.sort! {|x,y| x.b<=>y.b }
#p pb

k=0
for i in 0..n-1
  if pb[i].a>=s
    k+=pb[i].b*s
    break
  else
    s-=pb[i].a
    k+=pb[i].b*pb[i].a
  end
end

puts k

#! /usr/bin/env ruby
# coding: utf-8

n, r, avg = gets.chomp.split.map(&:to_i)
req = n * avg

s = []
n.times do
  tmp = gets.split.map(&:to_i)
  req -= tmp[0]
  unless r <= tmp[0]
    tmp[0] = r - tmp[0]
    s << tmp
  end
end

s.sort_by! { |a| a[1] }

essays = 0
s.each do |a|
  is_break = false
  a[0].times do |i|
    req -= 1
    essays += a[1]
    is_break = true and break if req <= 0
  end
  break if is_break
end

puts essays

#! /usr/bin/env ruby
# coding: utf-8

n, r, avg = gets.chomp.split.map(&:to_i)
req = n * avg

s = []
n.times do
  tmp = gets.split.map(&:to_i)
  req -= tmp[0]
  unless r <= tmp[0]
    tmp[0] = r - tmp[0]
    s << tmp
  end
end

if req <= 0
  puts 0
  exit 0
end

s.sort_by! { |a| a[1] }

essays = 0
s.each do |a|
  if 0 <= req - a[0]
    req -= a[0]
    essays += a[0] * a[1]
    break if req <= 0
    next
  end
  req -= 1
  essays += a[1]
  break if req <= 0
end

puts essays

def read_ints; STDIN.gets.split.map(&:to_i); end

n, r, avg = read_ints
avg *= n
a = []
cur_avg = 0
n.times do
  a << read_ints
  cur_avg += a[-1][0]
end
if cur_avg > avg
  puts 0
  exit 0
end
ans = 0
a.each do |x|
  if r - x[0] >= avg - cur_avg
    ans += x[1] * (avg - cur_avg)
    break
  end
    ans += (r - x[0]) * x[1]
    cur_avg += (r - x[0])
end

puts ans

n, r, avg = gets.split.map &:to_i
exams = gets(nil).split("\n").map { |line| line.split.map &:to_i }

need = avg * n
have = exams.transpose.first.inject(:+)

exams.sort! { |a, b| a.last <=> b.last }

essays = 0
while have < need
    a, b = exams.first

    up = [need - have, r - a].min

    have   += up
    essays += up * b

    exams.unshift
end

puts essays


#!/usr/bin/env ruby
phone_length, block_length = gets.split(' ').map(&:to_i)

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

possibilities_in_each_block = a.zip(b).map do |a_i, b_i|
  vsego_kratnix = (10**(block_length) - 1).div(a_i)

  #require 'byebug'
  #debugger
  kratnix_i_startujut_s_b_itogo = ((b_i+1)*(10**(block_length-1)) - 1).div(a_i) - (b_i*(10**(block_length-1)) - 1).div(a_i)

  nulevoi_element = 1

  nulevoi_element + vsego_kratnix - kratnix_i_startujut_s_b_itogo
end

big_modulo = 10**9 + 7

def fast_product_stupid(int_arr_product, big_modulo)
  total = 1
  int_arr_product.each do |num|
    total = (num*total).modulo(big_modulo)
  end
  total
end

puts fast_product_stupid(possibilities_in_each_block, big_modulo)

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

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

x = 10 ** k
xx = 10 ** k.pred
md = (10 ** 9) + 7

f = "%0" + k.to_s + "d"
ans = 1

a.size.times do |i|
    c = 0
    v = 0
    ai = a[i].to_i
    bi = b[i].to_i
    if a[i].size == k
        while v < x
            if (f % [v])[0] != b[i]
                c += 1
            end
            v += ai
        end
    else
        c = x.pred.div(ai).succ
        if bi == 0
            c -= xx.pred.div(ai).succ
        else
            c -= bi.succ.*(xx).pred.div(ai).succ - bi.*(xx).pred.div(ai).succ
        end
    end
    ans *= c
    ans %= md
end

puts ans.%(md)

n, k = gets.chomp.split.map(&:to_i)
as = gets.chomp.split.map(&:to_i)
bs = gets.chomp.split.map(&:to_i)
mod = (1E9 + 7).to_i

ans = 1
for i in 0...(n / k)
  ans = ans * ((10**k - 1) / as[i] + 1 - (bs[i] * 10**(k - 1) + 10**(k - 1) - 1) / as[i] + (bs[i] * 10**(k - 1) - 1) / as[i]) % mod
end

puts ans

#!/usr/bin/ruby

n, k = gets.strip().split(" ")
n = n.to_i
k = k.to_i
a = gets.strip().split(" ")
a = a.map(&:to_i)
b = gets.strip().split(" ")
b = b.map(&:to_i)
m = n / k;
ans = 1;
for i in 0..m - 1
    if b[i] == 0
        tmp = 10 ** (k - 1)
        mul = (tmp * 10 - 1) / a[i] - tmp / a[i] + 1
        if tmp % a[i] > 0
            mul -= 1
        end
    else
        tmp = 10 ** (k - 1)
        mul = (tmp * 10 - 1) / a[i] - tmp * (b[i] + 1) / a[i] + 1 + (tmp * b[i] - 1) / a[i] + 1
        if tmp * (b[i] + 1) % a[i] > 0
            mul -= 1
        end
    end
    ans = ans * mul
    ans %= 10 ** 9 + 7
end
print ans, "\n"

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

block = n / k

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

answer = 1

for i in 0..(block - 1)
  ans = (10**k - 1) / a[i] + 1

  degree =  10**(k - 1)
  ans -= ((b[i] + 1) * degree - 1) / a[i]
  ans += (b[i] * degree - 1) / a[i]

  answer *= ans
  answer %= 1000000007
end

puts answer

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

block = n / k

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

answer = 1

for i in 0..(block - 1)
  degree =  10**(k - 1)

  ans = (10**k - 1) / a[i] + 1

  ans -= ((b[i] + 1) * degree - 1) / a[i]
  ans += (b[i] * degree - 1) / a[i]

  answer *= ans
end

puts answer

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

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

x = 10 ** k
xx = 10 ** k.pred

f = "%0" + k.to_s + "d"
ans = 1

n.div(k).times do |i|
    c = 0
    v = 0
    ai = a[i].to_i
    bi = b[i].to_i
    if a[i].size == k
        while v < x
            if (f % v)[0] != b[i]
                c += 1
            end
            v += ai
        end
    else
        c = x.pred.div(ai).succ
        if bi == 0
            c -= xx.pred.div(ai).succ
        else
            c -= bi.*(xx).div(ai).succ - bi.pred.*(xx).div(ai).succ
        end
    end
    ans *= c
end

puts ans.%((10 ** 9) + 7)

#!/usr/bin/env ruby
phone_length, block_length = gets.split(' ').map(&:to_i)

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

possibilities_in_each_block = a.zip(b).map do |a_i, b_i|
  valid_parts_in_block = ('9'*block_length).to_i.div(a_i)
  next 1 if valid_parts_in_block == 0

  valid_parts_in_block.downto(1).take_while do |kratnoe|
    num = (kratnoe*a_i).to_s

    longest_kratnoe = num.length == block_length
    if (longest_kratnoe && num[0] == b_i)
      valid_parts_in_block -= 1
    end

    longest_kratnoe
  end

  next valid_parts_in_block+1 # zero
end

big_modulo = 10**9 + 7

def fast_product_stupid(int_arr_product, big_modulo)
  total = 1
  int_arr_product.each do |num|
    total = (num*total).modulo(big_modulo)
  end
  total
end

puts fast_product_stupid(possibilities_in_each_block, big_modulo)

n, k = gets.chomp.split.map(&:to_i)
as = gets.chomp.split.map(&:to_i)
bs = gets.chomp.split.map(&:to_i)
mod = (1E9 + 7).to_i
ans = 1
for i in 0...(n / k)
  ans = ans * (99 / as[i] - ((bs[i] * 10 + 9) / as[i]) + (bs[i] * 10 - 1) / as[i] + 1) % mod
end

puts ans

#!/usr/bin/ruby

n, k = gets.strip().split(" ")
n = n.to_i
k = k.to_i
a = gets.strip().split(" ")
a = a.map(&:to_i)
b = gets.strip().split(" ")
b = b.map(&:to_i)
m = n / k;
ans = 1;
for i in 0..m - 1
    if b[i] == 0
        tmp = 10 ** (k - 1)
        mul = (tmp * 10 - 1) / a[i] - tmp / a[i] + 1
        if tmp % a[i] > 0
            mul -= 1
        end
    else
        tmp = 10 ** (k - 1)
        mul = (tmp * 10 - 1) / a[i] - tmp * (b[i] + 1) / a[i] + 1 + (tmp * b[i] - 1) / a[i] + 1
        if tmp * (b[i] + 1) % a[i]
            mul -= 1
        end
    end
    ans = ans * mul
    ans %= 10 ** 9 + 7
end
print ans, "\n"


gets.to_i.times do
  a,v,l,r = gets.split.map(&:to_i)
  puts a/v-r/v+(l-1)/v
end

gets.to_i.times do
	n, v, l, r = gets.split.map(&:to_i)
	puts n / v - (r / v - l.pred / v)
end

def go
  l, v, s, e = read_ints

  count = 0
  # interval before train
  from = v
  to = s - 1
  count += ((to-from)/v) + 1 if from <= to

  # interval after train
  from = e + 1
  to = (l.to_f / v).floor * v
  count += ((to-from)/v) + 1 if from <= to

  puts count
end

def solution
  n = read_int
  n.times do
    go
  end
end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

def solve
  t = gets.strip.to_i
  t.times do
    d, v, l, r = gets.strip.split.map(&:to_i)
    puts (d / v) - ( (r / v) - (l / v) + (l % v == 0 ? 1 : 0))
  end
end

solve

# https://codeforces.com/problemset/problem/1066/A
def solution(d, v, l, r)
  return (d / v) - (r / v) + ((l - 1) / v)
end

n = gets.chomp.to_i
n.times do
  d, v, l, r = gets.chomp.split(" ").map(&:to_i)
  puts solution(d, v, l, r)
end

def lights(len, v)
	(len + v)/v - 1
end
n = gets.chomp
n.to_i.times do |i|
	line = gets.chomp
	len, v, l, r = line.split.map(&:to_i)
	res = lights(len, v)
	#puts res
	res = res - ( lights(r,v) - lights(l - 1,v) )
	puts res
end

n = gets.strip.to_i

out = []
n.times do
    arr = gets.strip.split(' ').map(&:to_i)
    start = arr[2] - 1

    start2 = arr[3] + 1
    end2 = arr[0]

    final = (start / arr[1]).floor + (end2 / arr[1]).floor - (start2 / arr[1]).floor
    if (start2 % arr[1] == 0 && end2 % arr[1] == 0)
        final += 1
    elsif (start2 % arr[1] == 0 && end2 % arr[1] != 0)
        final += 1
    end
    out << final
end

out.each do |o|
    puts o
end

n = gets.strip.to_i

out = []
n.times do
    arr = gets.strip.split(' ').map(&:to_i)
    start = arr[2] - 1

    start2 = arr[3] + 1
    end2 = arr[0]

    final = (start / arr[1]).floor + (end2 / arr[1]).floor - (start2 / arr[1]).floor
    if (start2 % arr[1] == 0 && end2 % arr[1] == 0)
        final += 1
    end
    out << final
end

out.each do |o|
    puts o
end

n = gets.strip.to_i

out = []
n.times do
    arr = gets.strip.split(' ').map(&:to_i)
    start = arr[2] - 1

    start2 = arr[3] + 1
    end2 = arr[0]

    final = (start / arr[1]).floor + (end2 / arr[1]).floor - (start2 / arr[1]).floor
    if (start2 % arr[1] == 0 || end2 % arr[1] == 0)
        final += 1
    end
    out << final
end

out.each do |o|
    puts o
end


Pointer = Struct.new(:value)

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  ass = n.times.map { gets.split.map(&:to_i) }
  go = ->(i, j, di, dj, map) {
    pointer = Pointer.new(0)
    while i < n && j < m && i >= 0 && j >= 0
      map[[i, j]] = pointer
      pointer.value += ass[i][j]
      i += di
      j += dj
    end
  }
  ltr, rtl = {}, {}
  0.upto(n - 1) { |i| go[i, 0, 1, 1, ltr] }
  0.upto(m - 1) { |j| go[0, j, 1, 1, ltr] }
  0.upto(n - 1) { |i| go[i, m - 1, 1, -1, rtl] }
  0.upto(m - 1) { |j| go[0, j, 1, -1, rtl] }
  answer = 0.upto(n - 1).map do |i|
    0.upto(m - 1).map do |j|
      ltr[[i, j]].value + rtl[[i, j]].value - ass[i][j]
    end.max
  end.max
  p answer
end

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  ass = n.times.map { gets.split.map(&:to_i) }
  answer = 0.upto(n - 1).map do |i|
    0.upto(m - 1).map do |j|
      sum = ass[i][j]
      [[-1, -1], [-1, 1], [1, -1], [1, 1]].map do |di, dj|
        ii, jj = i + di, j + dj
        while ii >= 0 && ii <= n - 1 && jj >= 0 && jj <= m - 1
          sum += ass[ii][jj]
          ii += di
          jj += dj
        end
      end
      sum
    end.max
  end.max
  p answer
end

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  diag = {}
  rdiag = {}

  as = Array.new(n) { gets.split.map(&:to_i) }

  n.times { |i|
    m.times { |j|
      di = j - i
      diag[di] ||= 0
      diag[di]  += as[i][j]

      rdi = m - 1 - j - i
      rdiag[rdi] ||= 0
      rdiag[rdi]  += as[i][j]
    }
  }

  ans = nil
  n.times { |i|
    m.times { |j|
      cur = diag[j - i] + rdiag[m - 1 - j - i] - as[i][j]
      ans = cur if !ans || cur > ans
    }
  }

  p ans
end

def solve
  h, w = gli
  b = []
  h.times { b << gli }
  ans = 0
  (0...h).each do |i|
    (0...w).each do |j|
      tmp = b[i][j]
      (1..i).each do |q|
        break if i - q < 0 || j - q < 0

        tmp += b[i - q][j - q]
      end
      (1..i).each do |q|
        break if i - q < 0 || j + q >= w

        tmp += b[i - q][j + q]
      end
      (i + 1...h).each do |q|
        break if j - (q - i) < 0

        tmp += b[q][j - (q - i)]
      end
      (i + 1...h).each do |q|
        break if j + (q - i) >= w

        tmp += b[q][j + (q - i)]
      end

      ans = [ans, tmp].max
    end
  end
  puts ans
end

MOD = 10**9 + 7
def gs = gets.chomp
def gi = gets.to_i
def gli = gets.split.map(&:to_i)
def cyesno(x) = x ? :Yes : :No
def uyesno(x) = x ? :YES : :NO

gets.to_i.times { solve }

main = -> {
  t = int
  t.times do
      n, m = ints
      a = rep(n) { ints }
      sum_x = Hash.new(0)
      sum_y = Hash.new(0)
      n.times do |i|
          m.times do |j|
              sum_x[i + j] += a[i][j]
              sum_y[i - j] += a[i][j]
          end
      end
      ans = 0
      n.times do |i|
          m.times do |j|
              ans = [ans, sum_x[i + j] + sum_y[i - j] - a[i][j]].max
          end
      end
      puts ans
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

require "set"
require "prime"

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 strings; gets.to_s.split 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 YesNo t; puts YesNo[t] 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 * y.mod_inv(mod) % mod end
  def mod_nCr(r, mod = MOD); x = y = 1; (1..r).each { |i| x = x * (self + 1 - i) % mod; y = y * i % mod }; x.mod_div(y, 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
  def compress(kinds = uniq.sort!); map { |x| kinds.bsearch_index { _1 >= x } }; 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[]


n=gets.to_i

ans=[]
n.times{|i|
	ans<<i+1
}

n.times{
	x=gets.split.map{|e| e.to_i}
	n.times{|i|
		ans[i]=0 if x[i]==2 || x[i]==3
	}
}
c=ans.count{|e| e!=0}
puts c
if c>0 then
puts ans.select{|e| e>0}*" "
end

n = gets.to_i
cars = 1.upto(n).select do |_|
  collisions = gets.split(' ').map(&:to_i)
  !collisions.include?(1) && !collisions.include?(3)
end

puts cars.length
puts cars.join(' ')

n = gets.to_i
ans = Array.new
n.times do |i|
    tmp = gets.split
    ans.push(i+1) if not tmp.include?("1") and not tmp.include?("3")
end
puts ans.size
puts ans.join(" ") unless ans.empty?

n = gets.chomp.to_i
ans = [*1..n]
ar = Array.new(n) { Array.new(n) }
for i in 0...n
  ar[i] = gets.split(" ").map{|i| i.to_i}
end
for i in 0...n
	for j in 0...n
		if ar[i][j] == 3
			ans.delete(i + 1)
			ans.delete(j + 1)
		elsif ar[i][j] == 1
			ans.delete(i + 1)
		elsif ar[i][j] == 2
			ans.delete(j + 1)
		end
	end
end
puts ans.size
puts ans.join(" ")

n, c, s = Integer(gets), 0, ""

(1..n).each do |i|
	x = gets.split(" ")
	unless x.include? "1" or x.include? "3"
		c += 1
		s += "#{i} "
	end
end

puts c
if c > 0
	puts s
end

n = gets.to_i
ans = []
(1..n).each do |i|
    row = gets.split.map &:to_i
    ans.push i if not row.include? 1 and not row.include? 3
end
puts ans.size
ans.each do |a|
    print a.to_s + ' '
end
puts

# http://codeforces.com/contest/545/problem/A
n = gets.chomp.to_i
matrix = [].tap do |arr|
  n.times { arr << gets.chomp.split.map(&:to_i) }
end

good_cars = []
matrix.transpose.each.with_index do |row, idx|
  good_cars << idx + 1 unless (row.include?(2) || row.include?(3))
end

puts good_cars.length
puts good_cars.join(" ") unless good_cars.empty?

arr = []
gets.to_i.times do
  arr << gets.split.map { |x| x.to_i }.to_a
end
indices = []
count = 0
arr.each do |i|
  if !i.include?(1) && !i.include?(3)
    count += 1
    indices << arr.index(i) + 1
  end
end
puts count
indices.each { |x| print x, " " }

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

# a.rb

def main()
    n = gets.to_i
    r = []
    n.times do |i|
        a = gets.chomp.split(" ").map{|s| next s.to_i }
        r << (i + 1) if !(a.index(1) || a.index(3))
    end
    puts r.size
    puts r * " " if r.size > 0
end

if __FILE__ == $0 then
    main()
end

n = gets.to_i
goodCars = []
amountOfGoodCar = 0
n.times do |i|
    crashes = gets.split(' ')
                  .map{|x| x.to_i}
                  .select{|x| x > 0 && x % 2 == 1}
    next if crashes.size > 0
    amountOfGoodCar += 1
    goodCars << i + 1
end

puts amountOfGoodCar
goodCars.each {|car| print "#{car} "}


ab = gets.split(' ')
initial1 = ab[0]
initial2 = ab[1]
n = gets.to_i()
puts "#{initial1} #{initial2}"
for i in 1..n do
  ab = gets.split(' ')
  if initial1 == ab[0]
    initial1 = ab[1]
  else
    initial2 = ab[1]
  end
  puts "#{initial1} #{initial2}"
end

#!/usr/bin/ruby
a,b=gets.split
puts [a,b]*' '
gets
$<.each{|e|
	x,y=e.split
	if a==x
		a=y
	elsif b==x
		b=y
	end
	puts [a,b]*' '
}

#在ruby里我都不需要关心字符串的长度了！
name=gets.chomp.split(" ")
a=name[0]
b=name[1]
n=gets.chomp.to_i
puts "#{a} #{b}"
n.times do
    name=gets.chomp.split(" ")
    x=name[0]
    y=name[1]
    if x==a
        puts "#{b} #{y}"
        a=y
    else
        puts "#{a} #{y}"
        b=y
    end
end

a = gets.split
puts a * ' '
gets.to_i.times{
	x, y = gets.split
	a[a.index(x)] = y
	puts a * ' '
}

p = gets.split
n = gets.to_i
ans = [p]
n.times do
  a, b = gets.split
  p = p - [a] + [b]
  ans << p
end
puts ans.map{|x| x.join(' ')}

x = gets.split
n = gets.to_i
ans = [[*x]]
n.times do
  a1, a2 = gets.split
  if x.delete(a1)
    x.push(a2)
  elsif x.delete(a2)
    x.push(a1)
  end
  ans << x.flatten
end
puts ans.map{|x| x.join(' ')}

l = gets.split
puts l * ' '
gets.to_i.times {
  a, b = gets.split
  l[(l[0] == a) ? 0 : 1] = b
  puts l * ' '
}

a, b = gets.split
print(a, ' ', b)
gets.to_i.times do
  c, d = gets.split
  if a == c
    a = d
  else
    b = d
  end
  print("\n", a, ' ', b)
end

#!/usr/bin/ruby
a,b=gets.split
gets
$<.each{|e|
	x,y=e.split
	if a==x
		a=y
	elsif b==x
		b=y
	end
}
puts [a,b]*' '


N,X,Y = gets.split.map &:to_i
A = gets.split.map &:to_i
if X > Y
  p N; exit
end

p (A.count{ |a| a <= X }+1)/2

n, x, y = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
if x > y
	puts n
else
	puts a.count { _1 <= x }.succ / 2
end

# Input
n, x, y = gets.split(" ").map { |e| e.to_i }
a = gets.split(" ").map { |e| e.to_i }

# total_moves = 10**100, and maximum_hp = 100 * 10**5 = 10**7 => If we are stronger then everything will be destroyed *evil laugh*

# Processing
d = x - y
one_hit = a.count { |n| n <= x }
case
when d > 0
  result = n
when d <= 0
  result = one_hit / 2 + one_hit % 2
end

# Output
puts result

n, x, y = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
if x > y
  puts n
  exit
end
if x == y
  puts (arr.select{|a| a <= x}.size / 2.0).ceil
  exit
end
if x < y
  puts (arr.select{|a| a <= x}.size / 2.0).ceil
  exit
end

# Input
n, k = gets.split(" ").map { |e| e.to_i }
a = gets.split(" ").map { |e| e }

# Processing
count = Hash.new(0)
current_color = Hash.new

a.each do |n|
  count[n] += 1
end

count.each do |n, amount|
  if amount > k
    puts "NO"
    #puts "#{n} amount > k"
    exit
  end
  current_color[n] = (current_color.length % k) + 1
end

c = Array.new(n) do |i|
  #puts current_color
  color = current_color[a[i]]
  current_color[a[i]] = current_color[a[i]] % k + 1
  color
end

# Output
puts "YES"
puts c.join(" ")

# Input
n, x, y = gets.split(" ").map { |e| e.to_i }
a = gets.split(" ").map { |e| e.to_i }

# total_moves = 10**100, and maximum_hp = 100 * 10**5 = 10**7 => If we are stronger then everything will be destroyed *evil laugh*

# Processing
d = x - y
one_hit = a.count { |n| n < x }
case
when d > 0
  result = n
when d <= 0
  result = one_hit / 2 + one_hit % 2
end

# Output
puts result


int,frac = gets.split('.')
if int[-1] == '9'
    puts "GOTO Vasilisa."
elsif frac[0].to_i < 5
    puts int
else
    puts int.to_i+1
end

ss = gets.chomp.split(/\./)
i = ss[0].to_i

s = ss[0]
ch = s[s.length-1]
if ch == "9" then
  puts "GOTO Vasilisa."
else
  rnd = ss[1][0].to_i
  if rnd < 5 then
    puts i
  else
    puts i+1
  end
end

n=gets
s=n.split('\n')[0].split('.')
s[0]=s[0].to_i

if s[0]%10 == 9 then
        puts "GOTO Vasilisa."
else
        if s[1].slice(0)>='5' then
                s[0]+=1
        end
        puts s[0]
end

num = gets
the_dot = num.index('.')
if num[the_dot-1] == '9'
	puts "GOTO Vasilisa."
else
	if num[the_dot+1].to_i >= 5
		puts ((num[0...the_dot].to_i)+1).to_s
	else
		puts num[0...the_dot]
	end
end

s = gets.chomp
t = s.index(".")
if s[t-1] == '9'
  puts "GOTO Vasilisa."
  exit
end
puts s[t+1] <= "4" ? s[0...t] : s[0...t].succ

a,b = gets.chomp.split('.')
if a.to_i % 10 == 9 then puts "GOTO Vasilisa."
else if b[0].to_i >= 5 then p a.to_i + 1
else p a.to_i end end

a,b=gets.split('.')

ch1, ch2 = a[-1,1], b[0,1]

if ch1!='9' && ch2<'5'
	puts a
elsif ch1!='9' && ch2>='5'
	puts a.to_i+1
else
	puts "GOTO Vasilisa."
end

def help_far_away_kingdom
  i, f = gets.split('.')

  if i[i.length-1] == '9'
    puts 'GOTO Vasilisa.'
  else
    if f.nil? or f[0].to_i < 5
      puts i.to_i
    else
      puts i.to_i+1
    end
  end
end
help_far_away_kingdom

int, frac = gets.split('.')
if int[-1] == '9'
    puts "GOTO Vasilisa."
elsif frac[0].to_i < 5
    puts int
else
    puts int.to_i+1
end

while !gets.nil?

integer, float = $_.split('.')

if integer[-1] == '9'
  puts "GOTO Vasilisa."
elsif float[0].to_i <= 4
  puts integer
else
  integer[-1] = integer[-1].succ
  puts integer
end

end

inp = gets.split('.')

int_part = inp[0]

if int_part.rindex('9') == int_part.size-1
  puts "GOTO Vasilisa."
elsif inp[1][0..0].to_i >= 5
  puts inp[0].to_i + 1
else
  puts inp[0]
end

i, f = gets.chomp.split(".")
if i[-1] == "9"
    puts "GOTO Vasilisa."
elsif f[0] < "5"
    puts i
else
    puts i.to_i+1
end

s = gets
case s
when /9\./
  puts 'GOTO Vasilisa.'
when /(\d+)\.[0-4]/
  puts $1.to_i
else
  puts s.to_i + 1
end

#!/usr/bin/ruby
s = $stdin.gets.strip.split(".")
int = s[0].to_i
flt = s[1][0].to_i
Blah = "GOTO Vasilisa."
if int % 10 == 9 then
  puts "#{Blah}"
else
  int += 1 if flt >= 5
  puts "#{int}"
end

x = gets.strip

if x =~ /9\./
	print :"GOTO Vasilisa."
else
	x =~ /(\d+)\.(\d)/
	print $2.to_i < 5 ? $1 : $1.to_i + 1
end

a,b = gets.chomp.split('.')
if a.to_i % 9 == 0 then puts "GOTO Vasilisa."
else if b[0].to_i >= 5 then p a.to_i + 1
else p a.to_i end end

def help_far_away_kingdom
  n = gets.strip
  r, ind = '', 0

  while ind < n.length
    if n[ind+1] == '.'
      if n[ind] == '9'
        puts 'GOTO Vasilisa.'
      else
        fraction = ("0.#{n[ind+2..-1]}").to_f
        if fraction < 0.5
          puts n[0..ind].to_i
        else
          puts n[0..ind].to_i + 1
        end
      end
      break
    end
    ind += 1
  end
  puts n if ind == n.length
end

help_far_away_kingdom

def help_far_away_kingdom
  n = gets.strip
  r, ind = '', 0

  while ind < n.length
    if n[ind+1] == '.'
      if n[ind] == '9'
        puts 'GOTO Vasilisa.'
      else
        fraction = ("0.#{n[ind+2..-1]}").to_f
        if fraction < 0.5
          puts n[0..ind].to_i
        else
          puts n[0..ind].to_i + 1
        end
      end
      break
    end
    ind += 1
  end
end

help_far_away_kingdom

while !gets.nil?

integer, float = $_.split('.')
if integer[-1] == '9'
  puts "GOTO Vasilisa."
elsif float[0].to_i < 4
  integer[-1] = integer[-1].succ
  puts integer
else
  puts integer
end

end

x = gets.strip
f = x.split('.')[1]
print f.count("9") == f.length ? :"GOTO Vasilisa." : x.to_f.round

x = gets.strip
l, r = x.split('.').map &:to_i

if l % 10 == 9
	print :"GOTO Vasilisa."
else
	l += 1 if r.to_s[0].to_i >= 5
	print l
end

x = gets.strip
print x[-1] == "9" ? :"GOTO Vasilisa." : x.to_f.round


def solve(cur_ram, arr1, arr2)
  merge_arr = []
  for index in 0..(arr1.length-1)
    merge_arr << [arr1[index], arr2[index]]
  end

  merge_arr.sort_by! {|x, y| x}

  # puts "merge_arr = #{merge_arr}"

  for index in 0..(merge_arr.length-1)
    break if merge_arr[index][0] > cur_ram
    cur_ram += merge_arr[index][1]
  end
  cur_ram
end

testcases = gets.chomp.to_i

for testcase in 1..testcases
  n, k = gets.chomp.split(" ").map(&:to_i)
  arr1 = gets.chomp.split(" ").map(&:to_i)
  arr2 = gets.chomp.split(" ").map(&:to_i)
  # puts "n, k, arr1, arr2 = #{[n, k, arr1, arr2]}"
  res = solve(k, arr1, arr2)
  puts res
end

t = gets.chomp.to_i

for i in (1..t)
    n, k = gets.chomp.split.map {|e| e.to_i}
    a = gets.chomp.split.map {|e| e.to_i}
    b = gets.chomp.split.map {|e| e.to_i}
    c = (a.zip b).sort
    for j in (0..n-1)
        if k >= c[j][0]
            k += c[j][1]
        end
    end
    puts k
end

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  abs = gets.split.map(&:to_i).zip(gets.split.map(&:to_i)).sort_by(&:first)
  abs.each do |a, b|
    break if k < a
    k += b
  end
  p k
end


n,*a=$<.read.split.map &:to_i;(n/2).times{|i|a[i],a[n-i-1]=a[n-i-1],a[i]if i.even?};puts a*' '

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

(0...(n / 2)).each do |i|
  next if i.odd?
  t = a[i]
  a[i] = a[n - i - 1]
  a[n - i - 1] = t
end

puts a.join(" ")

TEST_MODE = ARGV[0] == 't'

def evaluate(actual, expected); actual == expected ? "OK" : "**NG**"; end
def tests(); yield if TEST_MODE; end
def to_array(val); val.kind_of?(Array) ? val : [val]; end
def parse_int_array(str); str.split(" ").collect{|s| s.to_i}; end

def t(input, expected_output)
  input = to_array(input)
  expected_output = to_array(expected_output)
  output = []
  solve(input, output)
  puts "#{evaluate(output, expected_output)} : input=#{input.to_s}, expected=#{expected_output.to_s}, actual=#{output.to_s}"
end

def solve(input, output)
  arr = parse_int_array(input[1])
  (0..arr.size/2-1).step(2) {|i|
    temp = arr[i]
    arr[i] = arr[arr.size-i-1]
    arr[arr.size-i-1] = temp
  }
  output << arr.join(" ")
end

tests do
  # test cases
  t(["7","4 3 7 6 9 1 2"], "2 3 9 6 7 1 4")
  t(["8","6 1 4 2 5 6 9 2"], "2 1 6 2 5 4 9 6")
end

puts solve(STDIN.read.split("\n"), []) unless TEST_MODE

n=gets.to_i
s=gets.chomp.split
(s.size/2).times{|i|
	if i%2==0 then
		s[i],s[n-i-1]=s[n-i-1],s[i]
	end
}
puts s*" "

n = gets.to_i
a = gets.split.map(&:to_i)
c = n / 2 + (n.even? ? 0 : 1) - 1
ans = []
c.times do |i|
  if i % 2 == 0
    ans[i] = a[n - 1 - i]
    ans[n - 1 - i] = a[i]
  else
    ans[i] = a[i]
    ans[n - 1 - i] = a[n - 1 - i]
  end
end
a2 = a[c..(n - 1 - c)]
a2.reverse!  if c % 2 == 0
ans[c..(n - 1 - c)] = a2
puts ans.join(' ')

n = gets.to_i
a = gets.split.map(&:to_i)
(n / 2).times do |i|
  a[i], a[-1 - i] = a[-1 - i], a[i] if i % 2 == 0
end
puts a.join(' ')

n=gets.to_i
a=gets.split.map &:to_i
for i in 0 ... n / 2
  if i % 2 == 0
    tmp = a[i]
    a[i] = a[n - 1 - i]
    a[n - 1 - i] = tmp
  end
end
puts a*' '


MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

def main
  gi.times do
    n = gi
    d = 1
    s = 0
    c = 0
    while n > s
      s += d
      c += 1
      d += 2
    end
    puts c
  end
end

main

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i
  ans = 0
  curr_max = 1
  sum = 0
  while sum < n do
    ans += 1
    n -= curr_max
    curr_max += 2
  end

  ans += 1 if n > 0

  puts "#{ans}\n"
end


T=gets().to_i
line=gets().split(" ").map!{|x|x.to_i}
sum=(T*(T+1))/2
sb=line.inject(:+)
puts sum-sb

n=gets.to_i
mas=gets.split.map &:to_i
puts (n*(n+1)/2) - mas.inject(:+)


regs = [/(\w+) posted on (\w+)'s wall/,
        /(\w+) commented on (\w+)'s post/,
        /(\w+) likes (\w+)'s post/]

myname = gets.chomp
action = gets.to_i
player = {}
action.times do |i|
  tmp = gets
  if tmp =~ regs[0]
 #  p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 15
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 15
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  elsif tmp =~ regs[1]
#   p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 10
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 10
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  elsif tmp =~ regs[2]
#   p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 5
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 5
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  end
end
values = player.values
keys   = player.keys
while true do
    maxary = []
    max = values.max
    while true do
        maxpos = values.index(max)
        maxary << keys[maxpos].dup
        #p max,maxpos,maxary
        values.delete_at(maxpos)
        keys.delete_at(maxpos)
        break if values == []
        break if max > values.max
    end
    maxary.map{|item| item.extend Comparable}
    sorted = maxary
    sorted = maxary.sort if maxary.size > 1

    puts sorted
    break if values == []
end

my_name = STDIN.gets.strip
n = STDIN.gets.strip.to_i
actions = []
n.times do
  actions.push STDIN.gets.strip
end
persons = {}
regexps = [/(.*) posted on (.*)'s wall/,/(.*) commented on (.*)'s post/,/(.*) likes (.*)'s post/]
points = [15,10,5]
actions.each do |action|
  3.times do |i|
    if match = regexps[i].match(action)
      if match[1] == my_name || match[2] == my_name
        if persons[match[1]]
          persons[match[1]] += points[i]
        else
          persons[match[1]] = points[i]
        end
        if persons[match[2]]
          persons[match[2]] += points[i]
        else
          persons[match[2]] = points[i]
        end
      else
        if !persons[match[1]]
          persons[match[1]] = 0
        end
        if !persons[match[2]]
          persons[match[2]] = 0
        end
      end
    end
  end
end
persons.delete(my_name)
sorted = persons.to_a.sort_by{|x| [-x[1],x[0]]}
sorted.each do |person|
  puts person[0]
end

me = gets.chomp

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

(gets.to_i).times do
  line = gets.chomp.split
  x = line[0]
  y = nil
  points = 0
  if line[1] == "posted"
    points = 15
    y = line[3]
  elsif line[1] == "commented"
    points = 10
    y = line[3]
  elsif line[1] == "likes"
    points = 5
    y = line[2]
  end
  y = y[0..y.size - 3]
  if x == me
    map[y] += points
  elsif y == me
    map[x] += points
  else
    map[y] += 0
    map[x] += 0
  end
end

(map.sort {|a, b| if a[1] == b[1]
   a[0] <=> b[0] else b[1] <=> a[1] end }).each do |m|
    puts m[0]
end

my_name = gets.chomp
names = Hash.new(0)
gets.to_i.times do
  gets.chomp =~ /^(\w+) (posted on|commented on|likes) (\w+)'s (wall|post)$/
  n1, n2 = $1, $3
  other_name = if n1 == my_name
    n2
  elsif n2 == my_name
    n1
  end
  if other_name
    point = case $2
    when "posted on"
      15
    when "commented on"
      10
    else # "likes"
      5
    end
    names[other_name] += point
  else
    names[n1] += 0
    names[n2] += 0
  end
end

names.sort{|a,b| (b[1] <=> a[1]).nonzero? || a[0] <=> b[0] }.each{|n| puts n[0]}

h = Hash.new(0)
u = gets.chomp
gets.to_i.times do
	$_ = gets
	if /(\w+) posted on (\w+)'s wall/
		x, y, z = $1, $2, 15
	elsif /(\w+) commented on (\w+)'s post/
		x, y, z = $1, $2, 10
	elsif /(\w+) likes (\w+)'s post/
		x, y, z = $1, $2, 5
	else
		warn 555
	end
	if x == u
		h[y] += z
	elsif y == u
		h[x] += z
	else
		h[x] += 0
		h[y] += 0
	end
end
puts h.map{|k, v| [-v, k]}.sort.map{|a, b| b} * "\n"

MYNAME = gets.chomp
N = gets.to_i
persons = Hash.new(0)
N.times do
  str = gets.split(' ')
  add = 0
  x = str[0]
  y = str[3]
  if (str[1] == "posted")
    add = 15
  elsif (str[1] == "commented")
    add = 10
  else
    add = 5
    y = str[2]
  end
  y.gsub!("'s", "")
  if (x != MYNAME && y != MYNAME) # Priority factor according to me!
    add = 0 # but we have to print ALL persons
  end
  persons[x] += add
  persons[y] += add
end

result = persons.to_a.sort{|l, r|
  if (l[1] != r[1])
    r[1] <=> l[1]
  else
    l[0] <=> r[0]
  end
}

#p result

result.each {|e|
  puts e[0] if (e[0] != MYNAME)
}

name = gets.chomp
n = gets.to_i
priority = Hash.new(0)
n.times do
	v = gets.chomp.downcase
	arr = v.split(" ")
	a = arr[0]
	p = 0
	if arr[1].eql?("posted")
		p = 15
		b = arr[3]
	elsif arr[1].eql?("commented")
		p = 10
		b = arr[3]
	else
		p = 5
		b = arr[2]
	end
	b = b.sub("'s","")
	p = 0 unless (a.eql?(name) || b.eql?(name))
	priority[a] += p
	priority[b] += p
end

priority.keys.sort{|k1,k2| priority[k1] != priority[k2] ? -(priority[k1] <=> priority[k2]) : k1 <=> k2}.each do |k|
	puts k unless k.eql?(name)
end

regs = [/(\w+) posted on (\w+)'s wall/,
        /(\w+) commented on (\w+)'s post/,
        /(\w+) likes (\w+)'s post/]

myname = gets.chomp
action = gets.to_i
player = {}
action.times do |i|
  tmp = gets
  if tmp =~ regs[0]
 #  p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 15
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 15
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  elsif tmp =~ regs[1]
#   p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 10
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 10
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  elsif tmp =~ regs[2]
#   p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 5
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 5
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  end
end
values = player.values
keys   = player.keys

while true do
    while true do
        maxary = []
        max = values.max
        maxpos = values.index(values.max)
        maxary << keys[maxpos]
#       p max,maxpos,maxary
        values.delete_at(maxpos)
        keys.delete_at(maxpos)
        break if max > values.max.to_i
    end
    #maxary.sort_by!{|a,b| b <=> a} if maxary.size > 1
#   puts maxary
    break if values == []
end

MYNAME = gets.chomp
N = gets.to_i
persons = Hash.new(0)
N.times do
  str = gets.split(' ')
  add = 0
  x = str[0]
  y = str[3]
  if (str[1] == "posted")
    add = 15
  elsif (str[1] == "commented")
    add = 10
  else
    add = 5
    y = str[2]
  end
  y.gsub!("'s", "")
  persons[x] += add
  persons[y] += add
end

result = persons.to_a.sort{|l, r|
  if (l[1] != r[1])
    r[1] <=> l[1]
  else
    l[0] <=> r[0]
  end
}

#p result

result.each {|e|
  puts e[0] if (e[0] != MYNAME)
}

name = gets.chomp
n = gets.to_i
priority = Hash.new(0)
n.times do
	v = gets.chomp.downcase
	arr = v.split(" ")
	a = arr[0]
	p = 0
	if arr.include?("posted")
		p = 15
		b = arr[3]
	elsif arr.include?("commented")
		p = 10
		b = arr[3]
	else
		p = 5
		b = arr[2]
	end
	b = b.sub("'s","")
	p = 0 unless (a.eql?(name) || b.eql?(name))
	priority[a] += p
	priority[b] += p
end

priority.keys.sort{|k1,k2| priority[k1] != priority[k2] ? -(priority[k1] <=> priority[k2]) : k1 <=> k2}.each do |k|
	puts k unless k.eql?(name)
end

name = gets.chomp
n = gets.to_i
priority = Hash.new(0)
n.times do
	v = gets.chomp.downcase
	arr = v.split(" ")
	a = arr[0]
	p = 0
	if arr.include?("posted")
		p = 15
		b = arr[3]
	elsif arr.include?("commented")
		p = 10
		b = arr[3]
	else
		p = 5
		b = arr[2]
	end
	b = b.sub("'s","")
	p = 0 unless (a.include?(name) || b.include?(name))
	priority[a] += p
	priority[b] += p
end

priority.keys.sort{|k1,k2| priority[k1] != priority[k2] ? -(priority[k1] <=> priority[k2]) : k1 <=> k2}.each do |k|
	puts k unless k.eql?(name)
end

me = gets.chomp

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

(gets.to_i).times do
  line = gets.chomp.split
  x = line[0]
  y = nil
  points = 0
  if line[1] == "posted"
    points = 15
    y = line[3]
  elsif line[1] == "commented"
    points = 10
    y = line[3]
  elsif line[1] == "likes"
    points = 5
    y = line[2]
  end
  y = y[0..y.size - 3]
  map[x] += points
  map[y] += points
end

(map.sort {|a, b| if a[1] == b[1]
   a[0] <=> b[0] else b[1] <=> a[1] end }).each do |m|
  if m[0] != me
    puts m[0]
  end
end

my_name = gets.chomp
names = Hash.new(0)
gets.to_i.times do
  gets.chomp =~ /^(\w+) (posted on|commented on|likes|) (\w+)'s (wall|post)$/
  n1, n2 = $1, $3
  other_name = if n1 == my_name
    n2
  elsif n2 == my_name
    n1
  end
  if other_name
    point = case $2
    when "posted on"
      15
    when "commented on"
      10
    else # "likes"
      5
    end
    names[other_name] += 5
  else
    names[n1] += 0
    names[n2] += 0
  end
end

names.sort{|a,b| (b[1] <=> a[1]).nonzero? || a[0] <=> b[0] }.each{|n| puts n[0]}


times = gets.to_i

def resolve(binary_s)
  game_a = binary_s.split("0").map(&:size).sort{|a,b| b <=> a}
  game_a.delete(0)
  alice_points = 0
  game_a.each_with_index {|e,i| alice_points += e if i % 2 == 0}
  alice_points
end

(1..times).each do |i|
  s = gets.chomp
  puts resolve(s)
end

gets.to_i.times do
  puts gets.chomp.split(/0+/).map(&:length).sort{ |a, b| b <=> a }.select.each_with_index{|_, index| index.even?}.sum
end

t = gets.chomp.to_i
t.times do
    s = gets.chomp.split("")
    ookisa = s.size
    ans = 0
    count = 0
    arr = []
    (0..ookisa-1).each_with_index do |item,i|
        if item == "1" && s[i] == "1" && s[i-1] == "1" && i != 0
            count += 1
        elsif s[i] == "1"
            count += 1
        elsif s[i] == "0"
            arr << count
            count = 0
        end
        if ans <= count
            ans = count
            point = i
        end
    end
    arr << count
    arr = arr.sort
    arisa = 0
    bob = 0
    while true
        if arr != []
            arisa += arr.pop
        else
            break
        end
        if arr != []
            bob += arr.pop
        else
            break
        end
    end
    puts arisa
end

t = gets.chomp.to_i
t.times {
  str = gets.chomp
  index = -1
  (0...str.size).each do |ind|
    next if str[ind] == '0'

    index = ind
    break
  end

  list = []
  count = 1

  if index == -1
    puts '0'
    next
  end
  (index+1...str.size).each do |ind|
    if str[ind] == '1'
      count += 1
    else
      list << count if count != 0
      count = 0
    end
  end

  list << count if count != 0
  list.sort_by! {|ele| -1 * ele}

  ans = 0
  i = 0
  while ( i < list.size ) do
    ans += list[i]
    i += 2
  end
  puts ans
}

t = gets.to_i
ans = []
t.times do
  a = gets.chomp.split("").map(&:to_i)
  arr = []
  cnt = 0
  a.each do |v|
    if v == 1
      cnt += 1
    else
      if cnt > 0
        arr << cnt
        cnt = 0
      end
    end
  end
  if cnt > 0
    arr << cnt
  end
  arr = arr.sort.reverse
  len = arr.length
  value = 0
  len.times do |i|
    value += arr[i] if i%2 == 0
  end
  ans << value
end
ans.each do |x|
  puts x
end

gets.to_i.times do
  puts gets.split(/0+/).map(&:length).sort{ |a, b| b <=> a }.select.each_with_index{|_, index| index.even?}.sum
end

t = gets.chomp.to_i
t.times {
  str = gets.chomp
  index = -1
  (0...str.size).each do |ind|
    next if str[ind] == '0'

    index = ind
    break
  end

  list = []
  count = 1

  if index == -1
    puts '0'
    next
  end

  (index+1...str.size).each do |ind|
    if str[ind] == '1'
      count += 1
    else
      list << count if count != 0
      count = 0
    end
  end

  list << count if count != 0
  list.sort_by {|ele| -1 * ele}

  ans = 0
  i = 0
  while ( i < list.size ) do
    ans += list[i]
    i += 2
  end
  puts ans
}


at_exit do
  task_count = get_numbers_from_line[0]
  tasks = []
  task_count.times do
    t,c = get_numbers_from_line[0..1]
    tasks << {t: t, sms_count: c}
  end

  time = 0
  max_queue_length = 0
  task_in_queue_count = 0
  while true
    next_task = tasks.shift
    if next_task != nil
      dt = next_task[:t] - time
      task_in_queue_count = [0, task_in_queue_count - dt].max
      task_in_queue_count += next_task[:sms_count]
      max_queue_length = task_in_queue_count if task_in_queue_count > max_queue_length
      time += dt
    elsif task_in_queue_count != 0
      time += task_in_queue_count
      break
    else
      break
    end
  end

  puts [time, max_queue_length].join(' ')
end

def get_numbers_from_line
  gets.strip.split.map(&:to_i)
end

num_tasks = gets.to_i
tasks = Array.new
for i in 0...num_tasks
  tasks << gets.split.collect{ |n| n.to_i }
end
current_task = tasks.shift
t = current_task[0]
to_send = current_task[1]
max_queries = to_send
if tasks.length < 1
  puts (t+to_send).to_s + " " + max_queries.to_s
  exit
end
current_task = tasks.shift
while true
  t = t+1
  to_send -= 1 if to_send > 0
  if t == current_task[0]
    to_send += current_task[1]
    if to_send > max_queries
      max_queries = to_send
    end
    if tasks.length < 1
      break
    end
    current_task = tasks.shift
  end
end
puts (t+to_send).to_s + " " + max_queries.to_s

class A
  def initialize
    n = $stdin.gets.chomp.to_i
    queue_size = 0
    b_time = 0
    next_time = 0
    max_size = 0

    n.times do
      time, task = $stdin.gets.chomp.split(' ').map(&:to_i)
      d_time = time - b_time

      queue_size = [0, queue_size-d_time].max

      b_time = time

      queue_size += task

      max_size = queue_size if max_size < queue_size
    end

    puts "#{b_time+queue_size} #{max_size}"
  end
end

a = A.new

n = gets.to_i

tc = n.times.map{ gets.split.map(&:to_i) }

t = 1
max = 0
prev = [0, 0]

tc.each do |i|
  t = (t < i[0] ? i[0] : t) + i[1]
  m = prev[1] + prev[0] - i[0]
  m = m > 0 ? m + i[1] : i[1]
  max = m if max < m
  prev = [i[0], m]
end

puts "#{t} #{max}"

n = gets.chomp.to_i

times = []
messages_count = []

max_queue = 1
queue = 0

ftime = true

r_queue = 0

n.times do |i|
  input = gets.chomp.split(" ")

  times << input[0].to_i
  messages_count << input[1].to_i

  if ftime == false
    queue = queue - (input[0].to_i - times[i-1])
  end

  if queue < 0
    queue = 0
  end

  queue += input[1].to_i

  if queue > max_queue
    max_queue = queue
  end

  r_queue = queue

  if ftime
    ftime = false
  end
end

time = times.last + r_queue

puts "#{time} #{max_queue}"

n = gets.chomp.to_i

times = []
messages_count = []

max_queue = 1
queue = 0

r_queue = 0

n.times do
  input = gets.chomp.split(" ")

  times << input[0].to_i
  messages_count << input[1].to_i

  queue += input[1].to_i

  r_queue = queue

  if queue > max_queue
    max_queue = queue
  end

  queue -= input[0].to_i
  if queue < 0
    queue = 0
  end
end

time = times.last + r_queue

puts "#{time} #{max_queue}"

n = gets.chomp.to_i

times = []
messages_count = []

max_queue = 1
queue = 0

n.times do
  input = gets.chomp.split(" ")
  times << input[0].to_i
  messages_count << input[1].to_i
  queue += input[1].to_i

  if queue > max_queue
    max_queue = queue
  end

  queue -= 1
end

time = times.first + messages_count.inject(:+)

puts "#{time} #{max_queue}"

n = gets.chomp.to_i

times = []
messages_count = []

max_queue = 1
queue = 0

r_queue = 0

n.times do |i|
  input = gets.chomp.split(" ")

  times << input[0].to_i
  messages_count << input[1].to_i

  queue += input[1].to_i

  r_queue = queue

  if queue > max_queue
    max_queue = queue
  end

  queue = queue - (input[0].to_i - times[i-1])

  if queue < 0
    queue = 0
  end
end

time = times.last + r_queue

time -= 1 if times.size != 1
max_queue -= 1 if times.size != 1

puts "#{time} #{max_queue}"


n=gets.to_i
a=gets.split.map(&:to_i)
l=[]
r=[]
h={}
(n+1).times do |i|
  h.delete_if do |k,v|
    if i==n||a[i]%k>0
      (v..i).each {|x|r[x]=i-1 if a[x]==k}
      true
    else
      false
    end
  end
  h[a[i]]||=i if a[i]
end

(n+1).times do |i|
  h.delete_if do |k,v|
    if i==n||a[n-1-i]%k>0
      ([n-1-i,0].max..v).each {|x|l[x]=n-i if a[x]==k}
      true
    else
      false
    end
  end
  h[a[n-1-i]]||=n-1-i if a[i]
end

b=n.times.map{|x|r[x]-l[x]}
m=b.max
c=n.times.map{|x| l[x]+1 if b[x]==m}.select{|x|x}.sort.uniq
puts "#{c.size} #{m}"
puts c.join(' ')

n = gets.to_i
a = gets.split.map(&:to_i)
ll = Array.new(n)
rr = Array.new(n)

i = 0
loop do
  r = i+1
  while r < n
    break if a[r] % a[i] != 0
    r += 1
  end
  rr[i] = r-1
  break if r == n
  i = r
end

i = n-1
loop do
  l = i-1
  while l >= 0
    break if a[l] % a[i] != 0
    l -= 1
  end
  i.downto(l+1) do |j|
    ll[j] = l+1
  end
  break if l < 0
  i = l
end

best = 0
n.times do |i|
  best = [best, rr[i]-ll[i]].max if rr[i]
end

ans = []
n.times do |i|
  if rr[i] and rr[i]-ll[i] == best
    ans << ll[i]+1
  end
end

puts "#{ans.size} #{best}"
puts ans.join(' ')
# p ll, rr

n=gets.to_i
a=gets.split.map(&:to_i)
def f a,n,d
  h={}
  b=[]
  (n+1).times do |i|
    j=d>0 ? n-i-1 : i
    h.delete_if do |k,v|
      if i==n||a[j]%k>0
        p=v>j ? j : v
        q=v>j ? v : j
        p=0 if p<0
        q=n-1 if q==n
        (p..q).each {|x|b[x]=j+d if a[x]==k}
        true
      else
        false
      end
    end
    h[a[j]]||=j
  end
  b
end
r=f(a,n,-1)
l=f(a,n,1)

b=n.times.map{|x|r[x]-l[x]}
m=b.max
c=n.times.map{|x| l[x]+1 if b[x]==m}.select{|x|x}.sort.uniq
puts "#{c.size} #{m}"
puts c.join(' ')

n=gets.to_i
a=gets.split.map(&:to_i)
l=[]
r=[]
h={}
n.times do |i|
  h.delete_if do |k,v|
    if a[i]%k>0
      (v..i).each {|x|r[x]=i-1 if a[x]==k}
      true
    else
      false
    end
  end
  h[a[i]]||=i
end

h.delete_if do |k,v|
    (v..n-1).each {|x|r[x]=n-1 if a[x]==k}
    true
end

n.times do |i|
  h.delete_if do |k,v|
    if a[n-1-i]%k>0
      (n-1-i..v).each {|x|l[x]=n-i if a[x]==k}
      true
    else
      false
    end
  end
  h[a[n-1-i]]||=n-1-i
end

h.delete_if do |k,v|
  (0..v).each {|x|l[x]=0 if a[x]==k}
  true
end

b=n.times.map{|x|r[x]-l[x]}
m=b.max
c=n.times.map{|x| l[x]+1 if b[x]==m}.select{|x|x}.sort.uniq
puts "#{c.size} #{m}"
puts c.join(' ')

n=gets.to_i
a=gets.split.map(&:to_i)
l=[]
r=[]
h={}
n.times do |i|
  h.delete_if do |k,v|
    if a[i]%k>0
      (v..i).each {|x|r[x]=i-1 if a[x]==k}
      true
    else
      false
    end
  end
  h[a[i]]||=i
end

h.delete_if do |k,v|
    (v..n-1).each {|x|r[x]=n-1 if a[x]==k}
    true
end

n.times do |i|
  h.delete_if do |k,v|
    if a[n-1-i]%k>0
      (n-1-i..v).each {|x|l[x]=n-i if a[x]==k}
      true
    else
      false
    end
  end
  h[a[n-1-i]]||=n-1-i
end

h.delete_if do |k,v|
  (0..v).each {|x|l[x]=0 if a[x]==k}
  true
end

b=n.times.map{|x|r[x]-l[x]}
m=b.max
puts "#{b.count(m)} #{m}"
n.times.map{|x| print "#{l[x]+1} " if b[x]==m}

n=gets.to_i
a=gets.split.map(&:to_i)
def f a,n,d
  h={}
  b=[]
  (n+1).times do |i|
    j=d>0 ? n-i-1 : i
    h.delete_if do |k,v|
      if i==n||a[j]%k>0
        ([[v,j].min,0].max..[[v,j].max,n-1].min).each {|x|b[x]=j+d if a[x]==k}
        true
      else
        false
      end
    end
    h[a[j]]||=j
  end
  b
end
r=f(a,n,1)
l=f(a,n,-1)

b=n.times.map{|x|r[x]-l[x]}
m=b.max
c=n.times.map{|x| l[x]+1 if b[x]==m}.select{|x|x}.sort.uniq
puts "#{c.size} #{m}"
puts c.join(' ')

n=gets.to_i
a=gets.split.map(&:to_i)
l=[]
r=[]
h={}
n.times do |i|
  h.delete_if do |k,v|
    if a[i]%k>0
      (v..i).each {|x|r[x]=i-1 if a[x]==k}
      true
    else
      false
    end
  end
  h[a[i]]||=i
end

h.delete_if do |k,v|
    (v..n-1).each {|x|r[x]=n-1 if a[x]==k}
    true
end

n.times do |i|
  h.delete_if do |k,v|
    if a[n-1-i]%k>0
      (n-1-i..v).each {|x|l[x]=n-i if a[x]==k}
      true
    else
      false
    end
  end
  h[a[n-1-i]]||=n-1-i
end

h.delete_if do |k,v|
  (0..v).each {|x|l[x]=0 if a[x]==k}
  true
end

b=n.times.map{|x|r[x]-l[x]}
m=b.max
puts "#{b.count(m)} #{m}"
puts n.times.map{|x| l[x]+1 if b[x]==m}.select{|x|x}.sort.uniq


n = gets.to_i
max_stars = (n - 1) / 2
counter = 0
n.times do |iteration|
  counter = (iteration - max_stars).abs
  puts "*" * counter + "D" * (n - 2 * counter).abs + "*" * counter
end

n = gets.to_i

n.times do |i|
  aaa = n - (n/2 - i).abs * 2
  bbb = (n-aaa)/2
  puts "*" * bbb + "D" * aaa + "*" * bbb
end

n=gets.to_i

n2=n/2
arr=[]
n2.times{|i|
	s=i-n2
	d=1
	str=""
	n.times{
		if 0<=s then
			str<<"D"
		else
			str<<"*"
		end
		s=s+d
		if s==i then
			d=-1
		end
	}
	arr<<str
	puts str
}
puts "D"*n
arr.reverse.each{|e|
	puts e
}

n = gets.to_i
max = n / 2
str = []
for i in 0...max + 1
    rep = max - i
    str[i] = '*' * rep + 'D' * (n - 2 * rep) + '*' * rep
end
puts str + str[0...max].reverse

n = gets.to_i
max = n / 2
str = []
for i in 0..max
    rep = max - i
    str[i] = '*' * rep + 'D' * (n - 2 * rep) + '*' * rep
end
puts str + str[0...max].reverse

def f(n, io)
  h = n / 2
  n.times.each do |i|
    a = (h - i).abs
    d = n - 2*a
    s = '*'*a + 'D'*d + '*'*a
    io.puts s
  end
end

f(STDIN.gets.strip.to_i, STDOUT)

d = gets.chomp
n = Integer(d)
q = n / 2
t = 0
for i in 1..n
    if i > q
        t = n - i + 1
    else
        t = i
    end
    r = q - t + 1
    r.times do
        print "*"
    end
    (t * 2 - 1).times do
        print "D"
    end
    r.times do
        print "*"
    end
    puts ""
end

n = gets.to_i
a = Array.new(n)
i = Array.new(n / 2, "*")
j = ["D"]
for k in 0...n / 2 do
  a[k] = a[n - 1 - k] = (i + j + i).join
  i.pop
  2.times do
    j.push "D"
  end
end

a[n / 2] = Array.new(n, "D").join
puts a

n = gets.to_i
n.times do |i|
  nasterisks, nds = (n/2 - i).abs
  nds = n - nasterisks*2
  nasterisks.times { print '*' }
  nds.times { print 'D' }
  nasterisks.times { print '*' }
  puts
end

n=gets.to_i

diamond=Array.new(n){Array.new(n) {'*'}}
for i in 0..(n/2) do
    for j in (n/2-i)..(n/2+i) do
        diamond[i][j]='D'
        diamond[n-i-1][j]='D'
    end
end

for i in 0...n do
    for j in 0...n do
        print diamond[i][j]
    end
    puts ''
end

n = gets.to_i

str = ""

i = 1
while i < n
  stars = (n - i) / 2

  str += ('*' * stars)
  str += ('D' * i)
  str += ('*' * stars)
  str += "\n"

  i += 2
end

str += ('D' * n) + "\n"

i -= 2
while i > 0
  stars = (n - i) / 2

  str += ('*' * stars)
  str += ('D' * i)
  str += ('*' * stars)
  str += "\n"

  i -= 2
end

puts str

size = gets.chomp.to_i

(1..(size/2 + 1)).each do |i|
	dn = (2 * i - 1)
	print "*" * ((size - dn) / 2)
	print "D" * dn
	print "*" * ((size - dn) / 2)
	puts ""
end

((size/2 + 2)..size).each do |j|
	i = size - j + 1
	dn = (2 * i - 1)
	print "*" * ((size - dn) / 2)
	print "D" * dn
	print "*" * ((size - dn) / 2)
	puts ""
end

n = gets.chomp.to_i
start = (n / 2) + 1
dNum = 0

(0...n).each do |row|
	if row <= n / 2
		dNum = 2 * (row + 1) - 1
		start -= 1
	else
		dNum = (-2 * row + (2 * n - 1))
		start += 1 if row > n / 2
	end

	(0...n).each do |col|
		if col >= start && dNum > 0
			print 'D'
			dNum -= 1
		else
			print '*'
		end
	end

	puts ''
end

class Crystal
  def initialize(size)
    @size = size
  end

  def draw_diamond
    @size.times do |i|
      if i <= @size / 2
        cut_size = @size / 2 - i
      else
        cut_size = i - @size / 2
      end
      puts(("*" * cut_size ) +
          ("D" * (@size - cut_size * 2)) +
          ("*" * cut_size ))
    end
  end
end

Crystal.new(gets.to_i).draw_diamond

#!/usr/bin/env ruby

n = gets.to_i

arr = []
(n/2).times do |r|
  l = ("D" * (r+1)).rjust((n+1)/2, "*")
  arr << l + l.reverse[1..-1]
end

puts arr
puts "D" * n
puts arr.reverse

n = gets.to_i

i = 1
while i<=n
    t = (n-i)/2
    for j in 1..t
        print "*"
    end
    for j in 1..i
        print "D"
    end
    for j in 1..t
        print "*"
    end
    puts ""
    i+=2
end
i = n-2
while i>=1
    t = (n-i)/2
    for j in 1..t
        print "*"
    end
    for j in 1..i
        print "D"
    end
    for j in 1..t
        print "*"
    end
    puts ""
    i-=2
end

class A

  def run
    n = $stdin.gets.to_i
    (1..n).each do |i|
      pad = (n - 2 * i + 1).abs / 2
      fill = n - pad * 2
      puts '*' * pad + 'D' * fill + '*' * pad
    end
  end

end

A.new.run if __FILE__ == $0

n = gets.to_i
(0...n).each do |i|
  a = (n / 2 - i).abs
  b = n - a * 2
  puts '*' * a + 'D' * b + '*' * a
end

n = gets.to_i

size = 1

while size <= n
  ((n - size) / 2).times do print '*' end
  size.times do print 'D' end
  ((n - size) / 2).times do print '*' end
  puts ''
  size += 2
end

size -= 2

while size != 1
  size -= 2
  ((n - size) / 2).times do print '*' end
  size.times do print 'D' end
  ((n - size) / 2).times do print '*' end
  puts ''
end

n = gets.to_i
max_stars = (n / 3.0).ceil
counter = 0
n.times do |iteration|
  counter = (iteration - max_stars).abs
  puts "*" * counter + "D" * (n - 2 * counter).abs + "*" * counter
end


#require "prime"
#input of int(split by space)
def get_i()
    return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
    return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
    return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
    return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
    return bool ? y : n
end
#output grid(two dimensional array)
def puts_grid(grid,join_char="")
    grid.each do|line|
        puts line.join(join_char)
    end
end

Dirxy4=[[1,0],[-1,0],[0,1],[0,-1]]
Dirxy8=[[1,0],[1,-1],[1,1],[0,-1],[0,1],[-1,0],[-1,-1],[-1,1]]

INF=Float::INFINITY

#MOD=998_244_353
MOD=10**9+7

T=gets.to_i
T.times do
    n=gets.to_i
    s=get_i
    f=get_i
    ans=[]
    prev=-1
    n.times do |i|
        ans<<f[i]-[s[i],prev].max
        prev=f[i]
    end
    puts ans.join(" ")
end

t = gets.to_i

t.times do
  n = gets.to_i
  s = gets.split.map(&:to_i)
  f = gets.split.map(&:to_i)

  ans = []
  prev = s[0]
  now = f[0]
  1.upto(n-1) do |i|
    if now <= s[i]
      ans << now - prev
      now = f[i]
      prev = s[i]
    else
      ans << now - prev
      prev = now
      now = f[i]
    end
  end
  ans << now - prev
  puts ans.join(" ")
end


n = gets.to_i
s = gets.strip
a = s.split(/[.?!] ?/)
if a.any? {|x| x.size > n}
  puts "Impossible"
else
  puts s.scan(/.{,#{n-1}}[.?!] ?/).size
end

def min2(x, y)
    if x < y then return x
    else return y
    end
end

def min3(x, y, z)
    if x < y then
        if z < x then return z
        else return x
        end
    else
        if z < y then return z
        else return y
        end
    end
end

def min(x, y, z)
    if x && y && z then return min3(x,y,z)
    elsif x && y then return min2(x,y)
    elsif x && z then return min2(x,z)
    elsif y && z then return min2(y,z)
    elsif x then return x
    elsif y then return y
    else return z
    end
end

n = gets.to_i
s = gets.chomp
s = s.gsub("..", ".").gsub("!!", "!").gsub("??", "?")
result = ""
k = []
dot = s.index(".")
ask = s.index("?")
exp = s.index("!")
k[0] = min(dot, ask, exp)
i = 0
while k[i] && k[i] != s.size-1 do
    i += 1
    dot = s.index(".", k[i-1] + 1)
    ask = s.index("?", k[i-1] + 1)
    exp = s.index("!", k[i-1] + 1)
    k[i] = min(dot, ask, exp)
end
k = k.compact
k = k.sort
str = []
str[0] = s[0..k[0]]
if str[0].size > n
    then result = "Impossible"
else
    i = 1
    while i < k.size do
        str[i] = s[k[i-1]+1..k[i]]
        if str[i].start_with? " " then
            str[i] = str[i][1..-1]
        end
        if str[i].size > n then
            result = "Impossible"
        end
        i += 1
    end
end
if result != "Impossible" then
    if s.size < n then
        result = 1
    else
        result = 0
        i = 0
        while i < k.size do
            sum = str[i].size
            while i + 1 < k.size && sum + str[i+1].size + 1 <= n do
                i += 1
                sum += str[i].size + 1
            end
            i += 1
            result += 1
        end
    end
end
puts "#{result}"

n = gets.to_i
s = gets.scan(/.*?[\.?!]/).map{|_| _.strip.size}
x, y = 0, 0
s.each do |_|
	if _ > n
		puts :Impossible
		exit
	elsif x == 0
		x = _
	else
		x += 1 + _
		if x > n
			x = _
			y += 1
		end
	end
end
if x > 0
	y += 1
end
p y

n = gets.to_i
s = gets.strip
a = s.split(/[.?!] ?/)
if a.any?{|x|x.size > n}
  puts "Impossible"
else
  p s.scan(/.{,#{n-1}}[.?!] ?/).size
end

msgSize, txt=gets.to_i, [gets]
while txt.last.size>msgSize
  if (idx=txt.last[0, msgSize].rindex(/[?.!]/))==nil
    print "Impossible"
    exit
  else
    txt<<txt.last[idx+2...txt.last.size]
  end
end
print txt.keep_if{|v|v!=""}.size

N = gets.to_i
str = gets.chomp

count = 1
current = -1

sentences = str.split(/[.?!]/).map{|e| e.gsub(/^ /, '')}

#p sentences
s = ""
sentences.each {|e|
#  print current

  e += "."
  if e.size > N
    puts "Impossible"
    exit
  end
  current += e.size + 1
  s += " " + e
#  p [e, current]
  if current > N
#    p e
    count += 1
    current = e.size # check! 10 ab ab. ab. abcd abcd.
    s = e
  end
}
puts count

n = gets.to_i
s = gets.strip
if s.split(/[.?!] ?/).any? { |t| t.size >= n }
  puts :Impossible
else
  puts s.scan(/.{,#{n - 1}}[.?!] ?/).size
end

n = STDIN.gets.to_i
text = STDIN.gets.strip
sentences = text.split(/[?|.|!]/)
if !!sentences.find{|s| s.strip.length+1 > n}
  puts "Impossible"
  exit
end
left = n
count = 1
while sentence = sentences.shift
  len = sentence.length + 1
  if left >= len
    #puts sentence
    left -= len
  else
    #puts "new #{sentence}"
    count += 1
    left = n - (sentence.strip.length + 1)
  end
end
puts count

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+\s?/
count = 0
total_size = 0
str = ""
loop do
  if text.sub!(regexp, '').nil? || (str = $&).strip.size > max_size
    puts "Impossible"
    exit
  end
  if total_size + str.size <= max_size
    total_size += str.size
  else
    if total_size + str.strip.size <= max_size
      total_size = 0
      count += 1
    else
      total_size = str.size
      count += 1
    end
  end

  if text == ""
    puts count + 1
    exit
  end
end

def min2(x, y)
    if x < y then return x
    else return y
    end
end

def min3(x, y, z)
    if x < y then
        if z < x then return z
        else return x
        end
    else
        if z < y then return z
        else return y
        end
    end
end

def min(x, y, z)
    if x && y && z then return min3(x,y,z)
    elsif x && y then return min2(x,y)
    elsif x && z then return min2(x,z)
    elsif y && z then return min2(y,z)
    elsif x then return x
    elsif y then return y
    else return z
    end
end

n = gets.to_i
s = gets.chomp
s = s.gsub("..", ".").gsub("!!", "!").gsub("??", "?")
result = ""
k = []
dot = s.index(".")
ask = s.index("?")
exp = s.index("!")
k[0] = min(dot, ask, exp)
i = 0
while k[i] && k[i] != s.size-1 do
    i += 1
    dot = s.index(".", k[i-1] + 1)
    ask = s.index("?", k[i-1] + 1)
    exp = s.index("!", k[i-1] + 1)
    k[i] = min(dot, ask, exp)
end
k = k.compact
k = k.sort
str = []
str[0] = s[0..k[0]]
if str[0].size > n
    then result = "Impossible"
else
    i = 1
    while i < k.size do
        str[i] = s[k[i-1]+1..k[i]]
        if str[i].start_with? " " then
            str[i] = str[i][1..-1]
        end
        if str[i].size > n then
            result = "Impossible"
        end
        i += 1
    end
end
if result != "Impossible" then
    if s.size < n then
        result = 1
    else
        result = 0
        i = 0
        while i < k.size do
            sum = str[i].size
            while i + 1 < k.size && sum + str[i+1].size + 1 < n do
                i += 1
                sum += str[i].size + 1
            end
            i += 1
            result += 1
        end
    end
end
puts "#{result}"

def min2(x, y)
    if x < y then return x
    else return y
    end
end

def min3(x, y, z)
    if x < y then
        if z < x then return z
        else return x
        end
    else
        if z < y then return z
        else return y
        end
    end
end

def min(x, y, z)
    if x && y && z then return min3(x,y,z)
    elsif x && y then return min2(x,y)
    elsif x && z then return min2(x,z)
    elsif y && z then return min2(y,z)
    elsif x then return x
    elsif y then return y
    else return z
    end
end

n = gets.to_i
s = gets.chomp
result = ""
k = []
dot = s.index(".")
ask = s.index("?")
exp = s.index("!")
k[0] = min(dot, ask, exp)
st = s[k[0]+1..-1]
i = 0
while k[i] && k[i] != s.size-1 do
    i += 1
    if st.include? "." then
        k[i] = st.index(".") + k[i-1] + 1
    elsif st.include? "?" then
        k[i] = st.index("?") + k[i-1] + 1
    else
        k[i] = st.index("!")
        if k[i] then
            k[i] += k[i-1] + 1
        end
    end
    if k[i] then
        st = s[k[i]+1..-1]
    end
end
k = k.compact
k = k.sort
str = []
str[0] = s[0..k[0]]
if str[0].size > n
    then result = "Impossible"
else
    i = 1
    while i < k.size do
        str[i] = s[k[i-1]+1..k[i]]
        if str[i].start_with? " " then
            str[i] = str[i][1..-1]
        end
        if str[i].size > n then
            result = "Impossible"
        end
        i += 1
    end
end
if result != "Impossible" then
    if s.size < n then
        result = 1
    else
        result = 0
        i = 0
        while i < k.size do
            sum = k[i]
            while i + 1 < k.size && sum + k[i+1] + 1 < n do
                i += 1
                sum += k[i] + 1
            end
            i += 1
            result += 1
        end
    end
end
puts "#{result}"

def min2(x, y)
    if x < y then return x
    else return y
    end
end

def min3(x, y, z)
    if x < y then
        if z < x then return z
        else return x
        end
    else
        if z < y then return z
        else return y
        end
    end
end

def min(x, y, z)
    if x && y && z then return min3(x,y,z)
    elsif x && y then return min2(x,y)
    elsif x && z then return min2(x,z)
    elsif y && z then return min2(y,z)
    elsif x then return x
    elsif y then return y
    else return z
    end
end

n = gets.to_i
s = gets.chomp
s = s.gsub("..", ".").gsub("!!", "!").gsub("??", "?")
result = ""
k = []
dot = s.index(".")
ask = s.index("?")
exp = s.index("!")
k[0] = min(dot, ask, exp)
i = 0
while k[i] && k[i] != s.size-1 do
    i += 1
    dot = s.index(".", k[i-1] + 1)
    ask = s.index("?", k[i-1] + 1)
    exp = s.index("!", k[i-1] + 1)
    k[i] = min(dot, ask, exp)
end
k = k.compact
k = k.sort
str = []
str[0] = s[0..k[0]]
if str[0].size > n
    then result = "Impossible"
else
    i = 1
    while i < k.size do
        str[i] = s[k[i-1]+1..k[i]]
        if str[i].start_with? " " then
            str[i] = str[i][1..-1]
        end
        if str[i].size > n then
            result = "Impossible"
        end
        i += 1
    end
end
if result != "Impossible" then
    if s.size < n then
        result = 1
    else
        result = 0
        i = 0
        while i < k.size do
            sum = str[i].size
            while i + 1 < k.size && sum + str[i+1].size + 1 <= n do
                i += 1
                sum += str[i].size + 1
            end
            i += 1
            result += 1
        end
    end
end
p k
p str
puts "#{result}"

msgSize, txt=gets.to_i, [gets]
while txt.last.size>msgSize
  if (idx=txt.last[0, msgSize].rindex(/[?.!]/))==nil
    print "Impossible"
    exit
  else
    txt<<txt.last[idx+2...txt.last.size]
  end
end
print txt.size

N = gets.to_i
str = gets.chomp

count = 1
current = 0

sentences = str.split(/[.?!]/).map{|e| e.gsub(/^ /, '')}

#p sentences
s = ""
sentences.each {|e|
  e += "."
  if e.size > N
    puts "Impossible"
    exit
  end
  current += e.size + 1
  s += " " + e
  if current - 1 > N
#    p e
    count += 1
    current = e.size # check! 10 ab ab. ab. abcd abcd.
    s = e
  end
}
puts count

n = STDIN.gets.to_i
text = STDIN.gets.strip
sentences = text.split(/[?|.|!]/)
if !!sentences.find{|s| s.length+1 > n}
  puts "Impossible"
  exit
end
left = n
count = 1
while sentence = sentences.shift
  len = sentence.length + 1
  if left > len
    left -= len
  else
    count += 1
    left = n - (sentence.strip.length + 1)
  end
end
puts count

n = STDIN.gets.to_i
text = STDIN.gets.strip
sentences = text.split(/[?|.|!]/)
if !!sentences.find{|s| s.length+1 > n}
  puts "Impossible"
  exit
end
left = n
count = 1
while sentence = sentences.shift
  len = sentence.length + 1
  if left >= len
    puts sentence
    left -= len
  else
    puts "new #{sentence}"
    count += 1
    left = n - (sentence.strip.length + 1)
  end
end
puts count

n = STDIN.gets.to_i
text = STDIN.gets.strip
sentences = text.split(/[?|.|!]/)
if !!sentences.find{|s| s.length+1 > n}
  puts "Impossible"
  exit
end
left = n
count = 1
while sentence = sentences.shift
  len = sentence.length + 1
  if left >= len
    #puts sentence
    left -= len
  else
    #puts "new #{sentence}"
    count += 1
    left = n - (sentence.strip.length + 1)
  end
end
puts count

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /\s?[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+(?=\s?)/
count = 0
total_size = 0
loop do
  text.strip!
  size = 0
  if text.sub!(regexp){|s| size = s.size; nil}.nil? || size > max_size
    puts "Impossible"
    exit
  end
  if total_size + size <= max_size
    total_size += size
  else
    count += 1
    total_size = size
  end

  if text == ""
    puts count + 1
    exit
  end
end

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]\s?/
count = 0
loop do
  size = 0
  res = text.sub!(regexp){|s| size = s.size; nil}
  if res.nil? || size > max_size
    puts "Impossible"
    exit
  end
  count += 1
  if text == ""
    puts count
    exit
  end
end

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /\s?[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+(?=\s?)/
count = 0
total_size = 0
loop do
  size = 0
  if text.sub!(regexp){|s| size = s.size; nil}.nil? || size > max_size
    puts "Impossible"
    exit
  end
  if total_size + size <= max_size
    total_size += size
  else
    count += 1
    total_size = size
  end

  if text == ""
    puts count + 1
    exit
  end
end

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+\s?/
count = 0
total_size = 0
loop do
  size = 0
  if text.sub!(regexp){|s| size = s.size; nil}.nil? || size > max_size
    puts "Impossible"
    exit
  end
  if total_size + size < max_size
    total_size += size
  else
    count += 1
    total_size = size
  end

  if text == ""
    puts count + 1
    exit
  end
end

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+(?=\s?)/
count = 0
total_size = 0
loop do
  size = 0
  if text.sub!(regexp){|s| size = s.size; nil}.nil? || size > max_size
    puts "Impossible"
    exit
  end
  if total_size + size <= max_size
    total_size += size
  else
    count += 1
    total_size = size
  end

  if text == ""
    puts count + 1
    exit
  end
end

#!/usr/bin/env ruby

max_size = gets.to_i
text = gets.chomp

regexp = /[a-zA-Z]+(\s[a-zA-Z]+)*[.?!]+\s?/
count = 0
total_size = 0
loop do
  size = 0
  if text.sub!(regexp){|s| size = s.size; nil}.nil? || size > max_size
    puts "Impossible"
    exit
  end
  if total_size + size <= max_size
    total_size += size
  else
    count += 1
    total_size = size
  end

  if text == ""
    puts count + 1
    exit
  end
end

n = gets.to_i
text = gets.chomp
x = n
ret = 0
impossible = false
text.split(/[\!\.\?]/).each do |sentence|
  if sentence.size + 1 > n
    impossible = true
    break
  end
  ret += 1
end

if impossible
  puts "Impossible"
else
  puts ret
end


n,m,c = gets.split.map{|e| e.to_i}
a = gets.split.map{|e| e.to_i}
b = gets.split.map{|e| e.to_i}
ch = []
ch[0]=0
r = []
n-=1
m-=1
for i in 0..m
  ch[i+1]=(ch[i]+b[i]).modulo(c)
end

for i in 0..n
  z = [m+1, i+1].min
  k = [0, m-n+i].max
  r[i] = (a[i]+ch[z]-ch[k]).modulo(c)
end
puts r.join(' ')

n,m,c = gets.split.map{|e| e.to_i}
a = gets.split.map{|e| e.to_i}
b = gets.split.map{|e| e.to_i}
ch = []
ch[0] = b[0]
r = []
n-=1
m-=1
for i in 1..m
  ch[i]=(ch[i-1]+b[i]).modulo(c)
end

r[0]=(a[0]+b[0]).modulo(c)
r[n]=(a[n]+b[m]).modulo(c)
for i in 1..n-1
  if i>=m && n-i>=m
    r[i] = (a[i]+ch[m]).modulo(c)
    next
  end
  if i<n-i
    r[i] = (a[i]+ch[i]).modulo(c)
  else
    r[i] = (a[i]+ch[m]-ch[n-i-1]).modulo(c)
  end
end
puts r.join(' ')


input = gets.chomp
input_array = input.split(' ').map(&:to_i)

sasha = input_array[0]
masha = input_array[1]
price = input_array[2]

sasha_coconut, sasha_mod = sasha.divmod(price)
masha_coconut, masha_mod = masha.divmod(price)

max = sasha_coconut + masha_coconut

if sasha_mod > masha_mod
  swap = price - sasha_mod
  sasha += swap
  masha -= swap
else
  swap = price - masha_mod
  masha += swap
  sasha -= swap
end

max_temp = (sasha / price) + (masha / price)
max_temp = 0 if max_temp.eql?(nil)

if max_temp > max
  puts "#{max_temp} #{swap}"
else
  puts "#{max} 0"
end

x,y,z = gets.split.map(&:to_i)
a = (x+y)/z
b = x%z+y%z >= z ? [z-x%z,z-y%z].min : 0
puts "#{a} #{b}"

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

a = (x/z) + (y/z)
am = x % z
bm = y % z
aa = (am + bm)/z
if aa > 0
  b = [z-am, z-bm].min
else
  b = 0
end
a += aa
puts "#{a} #{b}"

x,y,z = gets.split.map(&:to_i)
if x/z+y/z < (x+y)/z
    puts "#{(x+y)/z} #{z-[x%z,y%z].max}"
else
    puts "#{x/z+y/z} 0"
end

def prog()
  str = gets
  x,y,z = str.split(" ").map(&:to_i)
  calc(x,y,z)
end

def calc(x,y,z)
  min = 0
  num = 0
  if (x%z + y%z >= z)
    max = (x%z > y%z) ? (x%z) : (y%z)
    min = z - max
    num = 1
  end
  puts "#{x/z + y/z + num} #{min}"
end

prog()

# frozen_string_literal: true

class ChungaChanga
  def initialize(sasha_chizhics, masha_chizhics, coconut_price)
    @sasha_chizhics = sasha_chizhics
    @masha_chizhics = masha_chizhics
    @coconut_price  = coconut_price
  end

  def calculate
    sasha_coconuts, remaining_sasha_chizhics = @sasha_chizhics.divmod(@coconut_price)
    masha_coconuts, remaining_masha_chizhics = @masha_chizhics.divmod(@coconut_price)

    if (remaining_sasha_chizhics + remaining_masha_chizhics) < @coconut_price
      [sasha_coconuts + masha_coconuts, 0]
    else
      bigger_remaining = [remaining_sasha_chizhics, remaining_masha_chizhics].max
      [sasha_coconuts + masha_coconuts + 1, @coconut_price - bigger_remaining]
    end
  end
end

input = gets.chomp.split(' ').map(&:to_i)
result = ChungaChanga.new(*input).calculate
puts result.join(' ')

input = gets.chomp
input_array = input.split(' ').map(&:to_i)

sasha = input_array[0]
masha = input_array[1]
price = input_array[2]

sasha_coconut, sasha_mod = sasha.divmod(price)
masha_coconut, masha_mod = masha.divmod(price)

if sasha_mod.eql?(0) || masha_mod.eql?(0)
  max = sasha_coconut + masha_coconut
  puts "#{max} 0"
else
  if sasha_mod > masha_mod
    swap = price - sasha_mod
    sasha += swap
    masha -= swap
  else
    swap = price - masha_mod
    masha += swap
    sasha -= swap
  end
  max = (sasha / price) + (masha / price)
  puts "#{max} #{swap}"
end

input = gets.chomp
input_array = input.split(' ').map(&:to_i)

sasha = input_array[0]
masha = input_array[1]
price = input_array[2]

sasha_coconut, sasha_mod = sasha.divmod(price)
masha_coconut, masha_mod = masha.divmod(price)

if sasha_mod.eql?(0) && masha_mod.eql?(0)
  max = sasha_coconut + masha_coconut
  puts "#{max} 0"
else
  if sasha_mod > masha_mod
    swap = price - sasha_mod
    sasha += swap
    masha -= swap
  else
    swap = price - masha_mod
    masha += swap
    sasha -= swap
  end
  max = (sasha / price) + (masha / price)
  puts "#{max} #{swap}"
end

input = gets.chomp
input_array = input.split(' ').map(&:to_i)

sasha = input_array[0]
masha = input_array[1]
price = input_array[2]

max = (sasha / price) + (masha / price)

# Choose big number
big_number = [sasha, masha].max
small_number = [sasha, masha].min

mod = big_number % price
swap = price - mod

big_number += swap
small_number -= swap

max_temp = (big_number / price) + (small_number / price)
if max_temp > max
  puts "#{max_temp} #{swap}"
else
  puts "#{max} 0"
end

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

a = (x/z) + (y/z)
am = x % z
bm = y % z
aa = (am + bm)/z
if aa > 0
  b = [am % z, bm%z].min
else
  b = 0
end
a += aa
puts "#{a} #{b}"

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

a = (x + y) / z
b = [x%z, y%z].min
puts "#{a} #{b}"

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

a = (x/z) + (y/z)
am = x % z
bm = y % z
aa = (am + bm)/z
if aa > 0
  b = (am+bm)%z
else
  b = 0
end
a += aa
puts "#{a} #{b}"

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

a = (x + y) / z
if (x+y) >= z
  b = [x%z, y%z].min
else
  b = 0
end
puts "#{a} #{b}"

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

a = (x + y) / z
b = [x, y].min % z
puts "#{a} #{b}"

def prog()
  str = gets
  x,y,z = str.split(" ").map(&:to_i)
  calc(x,y,z)
end

def calc(x,y,z)
  min = 0
  num = 0
  if (x%z + y%z >= z)
    min = (x%z > y%z) ? (y%z) : (x%z)
    num = (x%z + y%z)/z
  end
  puts "#{x/z + y/z + min} #{num}"
end

prog()

def prog()
  str = gets
  x,y,z = str.split(" ").map(&:to_i)
  calc(x,y,z)
end

def calc(x,y,z)
  min = 0
  num = 0
  if (x%z + y%z >= z)
    min = (x%z > y%z) ? (y%z) : (x%z)
    num = (x%z + y%z)/z
  end
  puts "#{x/z + y/z + num} #{min}"
end

prog()

x, y, z = gets.split(' ').map(&:to_i)
puts "#{(x + y) / z} #{[x % z, y % z].min}"


  n, q = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)
  b = [ 0 ] * n
  sum = a.inject(:+)
  all_t = -1
  all_x = 0
  q.times do |t|
    qq = gets.split.map(&:to_i)
    if qq[0] == 1 then
      _, i, x = qq
      if b[i-1] > all_t then
        c = a[i-1]
      else
        c = all_x
      end
      sum +=  x - c
      a[i-1] = x
      b[i-1] = t
    else
      _, x = qq
      all_t = t
      all_x = x
      sum = x * n
    end
    puts sum
  end

n,q=gets.split.map(&:to_i)
arr=gets.split.map(&:to_i)
sum=arr.sum
hash=Hash.new(0)
cur_mod=1
q.times do
    mod, *arg=gets.split.map(&:to_i)
    if mod==2
        cur_mod=2
        hash=Hash.new(arg[0])
        puts sum= n*arg[0]
    elsif cur_mod==1
        sum+=arg[1]-arr[arg[0]-1]
        arr[arg[0]-1]=arg[1]
        puts sum
    else
        sum+=arg[1]-hash[arg[0]]
        hash[arg[0]]=arg[1]
        puts sum
    end
end

n,q=gets.split.map(&:to_i)
arr=gets.split.map(&:to_i)
sum=arr.sum
hash=Hash.new(0)
cur_mod=1
q.times do
    mod, *arg=gets.split.map(&:to_i)
    if mod==2
        cur_mod=2
        hash=Hash.new(arg[0])
        puts sum= n*arg[0]
    elsif cur_mod==1
        sum+=arg[1]-arr[arg[0]-1]
        puts sum
    else
        sum+=arg[1]-hash[arg[0]]
        hash[arg[0]]=arg[1]
        puts sum
    end
end


n=gets.to_i
x=gets.split
h=Hash.new(0)

ans=0
c1=0
x.each{|e|
		if h.key?(e) then
			h.delete(e)
			c1-=1
		else
			h[e]=1
			c1+=1
		end
		ans=[ans,c1].max
}
puts ans

gets
b, c, maxc  = Hash.new, 0, 0
for a in gets.chomp.split.map{|x| Integer(x)}
  if b.include?(a) then
     b[a], c = true, c-1 if not b[a]
  else
    b[a], c = false, c+1
  end
  maxc = [c, maxc].max
end
puts maxc

#其实这些简单问题刚好适合ruby解决，让我可以掌握ruby的基本语法！
#就模拟整个过程，得到那个最大数就可以！
n=gets.chomp.to_i
exist=Array.new(100001)
socks=gets.chomp.split(" ")
table=0
count=0
for i in 0..2*n
    if exist[socks[i].to_i]
        exist[socks[i].to_i]=0
        count=count-1 if table > 0
    else
        exist[socks[i].to_i]=1
        count=count+1
    end
    if count>table
        table=count
    end
end
puts table

require 'set'
n=gets.chomp.to_i
#table=Array.new
table = Set.new
socks=gets.chomp.split(" ")
max=0
count=0
#超时了，ruby里不提供类似red black的插入？
for i in 0..2*n
    if table.include?(socks[i])
        table.delete(socks[i])
        count=count-1 if count > 0
    else
        table.add(socks[i])
        count=count+1
    end
    if count>max
        max=count
    end
end
puts max

gets
v, res = Hash.new(nil), []
gets.split.each { |s|
  if v[s]
    v.delete(s)
  else
    v[s] = true
    res.push(v.length)
  end
}
p res.max

#!/usr/bin/ruby
gets;t={};r=0;gets.split.each{|e|
	if t.has_key?(e)
		t.delete(e)
	else
		t[e]=1
		r=[r,t.size].max
	end
};p r

n = gets.strip.to_i
s = gets.strip.split.map(&:to_i)
track = Array.new((2 * n) + 1, false)
ans = count = 0
(2 * n).times do |i|
    curr = s[i]
    if track[curr]
        ans = [ans, count].max
        count -= 1
    else
        track[curr] = true
        count += 1
    end
end
puts ans

n = gets.to_i
a = gets.split.map(&:to_i)
vis = Array.new(n + 1)
cnt = 0
mx = 0
a.each do |x|
  cnt -= 2 if vis[x]
  vis[x] = true
  cnt += 1
  mx = [cnt, mx].max
end
p mx

n = gets.strip.to_i
s = gets.strip.split.map(&:to_i)
track = {}
ans = 0
n.times do |i|
    curr = s[i]
    track[curr] = 0 if !track[curr]
    track[curr] += 1
    ans += 1 if track[curr] < 2
end
puts ans


gets.to_i.times do

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

a_min = a.min
a.map! { |ai| ai - a_min }
a.delete_if { |ai| ai == 0 }

if a.empty?
  puts -1
else
  puts a.inject(0, :gcd)
end

end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	a = a.sort
	res = 0; tmp = a[0]
	a.map! {|ai| ai - tmp}
	a.map! {|x| res = res.gcd(x)}
	puts res != 0? res:-1
end


t=gets.to_i
(1).upto(t) do
  n=gets.to_i
  freq=Array.new(n+1,0)
  a=gets.split(' ').map(&:to_i)
  x=0
  y=0
  a.each do |e|
    freq[e]+=1
    y=[y,freq[e]].max
    x+=1 if freq[e]==1
  end
  if(y>x)
    puts x
  elsif y==x
    puts x-1
  else
    puts y
  end
end

t = gets.chomp.to_i

(1..t).each{
    n = gets.chomp.to_i
    a = gets.chomp.split.map{|x| x.to_i}
    count = Hash.new 0
    a.each{|x|
        count[x] += 1;
    }

    max_diff = count.keys.size
    max_same = count.values.max

    if max_same == max_diff then
        puts (max_same - 1)
    else
        puts [max_same, max_diff].min
    end
}

1.upto(gets.to_i) do
  gets
  h = Hash.new { 0 }
  gets.split(' ').map(&:to_i).each { |x| h[x] += 1 }

  u = h.keys.size
  m = h.max_by(&:last).last

  puts [[u-1, m].min, [u, m-1].min].max
end

t=gets.to_i
(1).upto(t) do
  n=gets.to_i
  freq=Array.new(n+1,0)
  a=gets.split(' ').map(&:to_i)
  x=0
  y=0
  a.each do |e|
    freq[e]+=1
    y=[y,freq[e]].max
    x+=1 if freq[e]==1
  end
  puts [y,x-1].min
end


UF=Hash.new{|_,k|k}
def u a,b;UF[f a]=UF[f b]end
def f c;c==UF[c]?c:UF[c]=f(UF[c])end

n=gets.to_i
a=gets.split.map(&:to_i)
m=(1..n).map{gets.chomp.chars.map{|c|c>?0}}
r=0...n
r.each{|i|r.each{|j|
  u(i,j) if m[i][j]
}}
group=r.map{|i|f i}
g=a.group_by.with_index{|i,j|group[j]}
g.values.map(&:sort!)
puts r.map{|i|g[group[i]].shift}*" "

class DSU
	def initialize n
		@p = Array.new(n) { |i, v| v = i }
	end
	def find x
		return x if @p[x] == x
		@p[x] = find @p[x]
	end
	def merge a, b
		@p[find(a)] = find(b)
	end
	def query? a, b
		find(a) == find(b)
	end
end

n = gets.to_i
dsu = DSU.new n
p = gets.split.map { |x| x.to_i - 1 }
n.times do |i|
	s = gets.chomp
	n.times do |j|
		if s[j] == '1' and !dsu.query?(i, j)
			dsu.merge i, j
		end
	end
end

ans = Array.new n
n.times do |i|
	if dsu.find(i) == i
		a = []
		b = []
		n.times do |j|
			if dsu.find(j) == i
				a << j
				b << p[j]
			end
		end
		b.sort!
		a.size.times do |j|
			ans[a[j]] = b[j] + 1
		end
	end
end
puts ans.join ' '

n = gets.to_i
ps = gets.split.map(&:to_i)
aij = []
n.times do |i|
  aij[i] = gets.split("").map(&:to_i)
end

ret = Array.new(n)
gs = []
gn = []
gi = 0
ni = 0
flags = Array.new(n){ |x| false }
while ni
  gs[gi] = []
  gn[gi] = []
  target = [ni]
  flags[ni] = true
  until target.size == 0 do
    x = target.pop
    gs[gi] << x
    gn[gi] << ps[x]
    aij[x].each_with_index do |y,j|
      if y==1 && !flags[j]
        target << j
        flags[j] = true
      end
    end
  end
  gs[gi].sort!
  gn[gi].sort!
  gs[gi].each_with_index do |x,i|
    ret[x] = gn[gi][i]
  end
  STDERR.puts "#{ni} #{ret.join(" ")}"
  ni = flags.index{ |x| x==false }
  gi += 1
end
puts ret.join(" ")

n = gets.to_i
ps = gets.split.map(&:to_i)
aij = []
n.times do |i|
  aij[i] = gets.split("").map(&:to_i)
end

ret = Array.new(n)
gs = []
gn = []
gi = 0
ni = 0
flags = Array.new(n){ |x| false }
while ni < n
  gs[gi] = []
  gn[gi] = []
  target = [ni]
  flags[ni] = true
  ni += 1
  until target.size == 0 do
    x = target.pop
    gs[gi] << x
    gn[gi] << ps[x]
    aij[x].each_with_index do |y,j|
      if y==1 && !flags[j]
        target << j
        flags[j] = true
      end
    end
  end
  gs[gi].sort!
  gn[gi].sort!
  gs[gi].each_with_index do |x,i|
    ret[x] = gn[gi][i]
  end
  break if ni == n
  (ni...n).each do |x|
    ni = x
    break unless flags[x]
  end
  gi += 1
end
puts ret.join(" ")

n = gets.to_i
ps = gets.split.map(&:to_i)
aij = []
n.times do |i|
  aij[i] = gets.split("").map(&:to_i)
end

ret = Array.new(n)
gs = []
gn = []
gi = 0
ni = 0
flags = Array.new(n){ |x| false }
while ni < n
  gs[gi] = []
  gn[gi] = []
  target = [ni]
  flags[ni] = true
  ni += 1
  #break if ni == n
  until target.size == 0 do
    x = target.pop
    gs[gi] << x
    gn[gi] << ps[x]
    aij[x].each_with_index do |y,j|
      if y==1 && !flags[j]
        target << j
        flags[j] = true
      end
    end
  end
  gs[gi].sort!
  gn[gi].sort!
  gs[gi].each_with_index do |x,i|
    ret[x] = gn[gi][i]
  end
  (ni...n).each do |x|
    ni = x
    break unless flags[x]
  end
  gi += 1
end
puts ret.join(" ")

n = gets.to_i
ps = gets.split.map(&:to_i)
aij = []
n.times do |i|
  aij[i] = gets.split("").map(&:to_i)
end

ret = Array.new(n)
gs = []
gn = []
gi = 0
ni = 0
flags = Array.new(n){ |x| false }
while ni < n
  gs[gi] = []
  gn[gi] = []
  target = [ni]
  flags[ni] = true
  ni += 1
  break if ni == n
  until target.size == 0 do
    x = target.pop
    gs[gi] << x
    gn[gi] << ps[x]
    aij[x].each_with_index do |y,j|
      if y==1 && !flags[j]
        target << j
        flags[j] = true
      end
    end
  end
  gs[gi].sort!
  gn[gi].sort!
  gs[gi].each_with_index do |x,i|
    ret[x] = gn[gi][i]
  end
  (ni...n).each do |x|
    ni = x
    break unless flags[x]
  end
  gi += 1
end
puts ret.join(" ")