s = gets.to_i
a = 1
ans = 0
while a < s
    ans += 1
    a *= 100
end
puts ans


n = gets.strip.to_i
home = gets.strip
count_home = count_away = 0
n.times do
    departure, arrival = gets.strip.split("->")
    count_home += 1 if departure == home
    count_away += 1 if arrival == home
end
at_home = count_home == count_away
if at_home
    puts "home"
else
    puts "contest"
end


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

def check_if_sufficiant(x,y,z,a,b,c)
  a = a-x
  return 'No' if (a < 0)
  return 'No' if (a+b < y)
  return 'No' if (a+b+c-y < z)
  return 'Yes'
end

puts check_if_sufficiant(x,y,z,a,b,c)


def f(n)
	if n==1
		return X
	elsif n==2
		return X+[X,Y].min
	elsif n%2==0
		return f(n/2)+[Y,X*(n-n/2)].min
	else
		return X+[f(n+1),f(n-1)].min
	end
end
N,X,Y=gets.split.map(&:to_i)
p f(N)


nk = gets.chomp.split(" ")
n = nk[0].to_i
k = nk[1].to_i
arr = gets.chomp.split(" ").map(&:to_i)

hash = Hash.new(0)

uniqarr = arr.uniq
arr.each do |elem|
  hash[elem]+=1
end

max = hash.values.max
dishno = (max.to_f/k).ceil

count = 0

#every set of utensils is the same

hash.values.each do |z|
  count+= k*dishno-z
end

puts count


#!/usr/bin/ruby
# coding: utf-8
n, m = gets.split.map(&:to_i)
puts [n, m, (n + m) / 3].min


gets
b=0
c=0
gets.split.map{|e|
	e=e.to_i
	e>0? b+=e : c+=e}
p b-c


require 'prime'

a,b = gets.split.map(&:to_i)
if a != b
    g = (a-b).abs
else
    g = a
end
x = Prime.prime_division(g)
m = a.lcm(b)
ans = 0

$p = []

def div(c,d,i)
    if i == d.size
        $p << c
    else
        div(c,d,i+1)
        d[i][1].times do |j|
            div(c*(d[i][0]**(j+1)),d,i+1)
        end
    end
end

div(1,x,0)
$p.sort!
$p.each do |k|
    l = (k-a%k)%k
    if m > (a+l)*(b+l)/k
        m = (a+l)*(b+l)/k
        ans = l
    end
end
puts ans


f,i,t=gets.strip.split.map(&:to_i)
a=f.times.map{gets.strip}
p i.times.count{|x|f.times.count{|y|a[y][x] == 'Y'}>=t}
# kitten


n, k = gets.split.map(&:to_i)
ar = gets.split.map(&:to_i)
un = ar.uniq
if un.size < k
  puts "NO"
else
  puts"YES"
  un.map!{|i| ar.find_index(i)+1}
  puts un[0..(k-1)].join(" ")
end


a, b, w, x, c = gets.split.map &:to_i

go = Array.new(w + 1, -1)
val = []

while go[b] == -1
  b = go[b] = if b >= x then val << 1; b - x else val << 0; b + w - x end
end

if c <= a
  puts 0
else
  x, y, z, ans = 0, 0, 0, 1e100
  val.each { |v| x += v }

  c -= a
  val.each { |v|
    y += v
    z += 1
    if (c - y) % x == 0
      tmp = (c - y) / x * val.size + z
      ans = tmp if tmp < ans
    end
  }
  puts ans
end


n = gets.to_i
k = gets.to_i
a = gets.to_i
b = gets.to_i

s=0

unless k==1

     until n==0

         if n%k==0

             unless ((n-(n/k))*a) >= b
                  s=s+(n-(n/k))*a
                  n=n/k

             else
                  s=s+b
                  n=n/k
             end

         elsif n<k
             s=s+(n-1)*a
             n=1
             break

         else
             s=s+(n-(k*(n/k)))*a
             n=(n/k)*k
         end

     end

print s

else
     s=(n-1)*a
     print s
end


def factorial(n)
  if n == 0 then
    return 1
  else
    return n * factorial(n - 1)
  end
end

input = gets.strip
output = gets.strip
input_pluses = input.count("+") || 0
input_minuses = input.count("-") || 0
output_pluses = output.count("+") || 0
output_minuses = output.count("-") || 0
output_questions = output.count("?") || 0
if output_pluses > input_pluses || output_minuses > input_minuses then
  probability = 0
else
  diff_pluses = input_pluses - output_pluses
  diff_minuses = input_minuses - output_minuses
  combinations = factorial(output_questions)/(factorial(diff_pluses) * factorial(output_questions - diff_pluses))
  # puts combinations
  # puts 2**output_questions
  probability = combinations/2**output_questions.to_f

end
puts probability


f = ->n {
  n < 10 ? n : f[n.to_s.chars.map(&:to_i).sum]
}

p f[gets.to_i]


n, k = gets.strip.split(' ').map(&:to_i);
a = gets.strip.split(' ').map(&:to_i);
an = 0
k -= 1
(0...n).each { |e|
  ok1 = a[k + e] if k + e < n
  ok2 = a[k - e] if (k - e) >= 0
  if e == 0 && ok1 == 1
    an += 1
    next
  end
  next if ok1.nil? && ok2.nil?
  cnt = 0
  if !ok1.nil?
    next if ok1.zero?
    cnt += 1 if !ok1.zero?
  end
  if !ok2.nil?
    next if ok2.zero?
    cnt += 1 if !ok2.zero?
  end
  an += cnt
}
puts an


def almostP n
  res = 0
  primes = [2]
  for i in 3..(n/2)
    isP = true
    primes.each do |x|
      isP = false if i%x == 0
    end
    primes << i if isP
  end
  for i in 1..n
    np = 0
    primes.each do |x|
      np += 1 if i%x == 0
    end
    res += 1 if np == 2
  end
  return res
end
n = gets.to_i
puts almostP(n)


interesting_min_numbers = gets.to_i

increasing_order = gets.strip.split(' ').map(&:to_i)

def watch_minutes(increasing_order)
  start_time = 0

  increasing_order.each do |order|
    is_boring = order - start_time > 15
    return start_time + 15 if is_boring
    start_time = order
  end

  [start_time + 15, 90].min
end

puts watch_minutes(increasing_order)


k = gets.to_i
s = gets.chomp
z = s.count("0")
if z != (k-z)
  p 1
  puts s
else
  p 2
  puts "#{s[0]} #{s[1,k-1]}"
end


def solve(a)
  return a if a < 10
  l, r = a, a % 10
  while l >= 10
    l /= 10
  end
  ans = a / 10 + 9
  ans -= 1 if r < l
  return ans
end

l, r = gets.split.map { |i| i.to_i }
puts solve(r) - solve(l - 1)


#!/usr/bin/env ruby
class Integer
  def cnt
    res = 0
    t = self
    while t != 0
      res += 1 if t.odd?
      t >>= 1
    end
    res
  end
end
MAP = {}
MAP['R'] = 0; MAP['G'] = 1; MAP['B'] = 2; MAP['Y'] = 3; MAP['W'] = 4
_ = gets.to_i
all = gets.split.uniq.map { |x| MAP[x[0]] * 5 + x[1].to_i - 1 }
ans = 10
(1 << 5).times do |i|
  (1 << 5).times do |j|
    flag = true
    all.each do |x|
      all.each do |y|
        next if x == y
        a, b = x.divmod(5)
        c, d = y.divmod(5)
        next if a != c && (i & (1 << a) > 0 || i & (1 << c) > 0)
        next if b != d && (j & (1 << b) > 0 || j & (1 << d) > 0)
        flag = false
        break
      end
      break unless flag
    end
    next unless flag
    now = i.cnt + j.cnt
    ans = now < ans ? now : ans
  end
end
puts ans


n = gets.to_i
x = gets.split.map &:to_i
y = gets.split.map &:to_i
puts x.inject(0) { |s, x| s + x } >= y.inject(0) { |s, x| s + x } ? 'Yes' : 'No'


k = gets.to_i

d = Array.new(10) { [0] * 11 }
d[0][0] = 1
(0..8).each do |i|
  (0..10).each do |j|
    (0..9).each do |k|
      d[i + 1][j + k] += d[i][j] if j + k < 11
    end
  end
end

ans, s = 0, 10
9.downto(1) do |i|
  ans *= 10
  (0..9).each do |j|
    if d[i - 1][s - j] < k
      k -= d[i - 1][s - j]
    else
      s -= j
      ans += j
      break
    end
  end
end

p ans


def pow(x, y)
  md = 1000000007;
  if y == 0
    1
  else
    t = pow(x, y/2);
    t = (t * t) % md;
    if y % 2 == 1 then (x * t) % md else t end
  end
end

md = 1000000007;
n, k = gets.split.map(& :to_i)

if k == 1
  ans = pow(n - k, n- k)
else
  ans = ((pow(k, k - 2) * k)% md * pow(n - k, n - k)) % md
end

p ans


n, s, c = gets.split.map(&:to_i)
d = gets =~ /tail/ ? 1 : -1
gets.scan(/[01]/).each_with_index do |w, i|
 s = c if w == ?1
 d = 1 if c == 1
 d = -1 if c == n
 c += d
 s += d if s == c
 unless (1 .. n).include? s
  puts "Controller #{i + 1}"
  exit
 end
end
puts :Stowaway


require 'prime'
n = gets.to_i
p n == 1 ? 1 : n.prime_division.map{|x| x[0]}.inject(:*)


w,m,k=gets.split.map(&:to_i)
a=Math.log10(m).to_i+1
v=l=0
while a*k*(c=(b=10**a-1)-m+1)+v <=w do
  v+=a*k*c
  l+=c
  m=b+1
  a+=1
end
l+=(w-v)/(a*k)
p l


n, cw, cb = gets.split(' ').map(&:to_i)
arr = gets.split(' ').map(&:to_i)
answer = 0

1.upto(n) do |index|
  q = arr[index - 1]
  w = arr[n -index]

  if (q == 0 && w == 1) || (q == 1 && w == 0)
    answer = -1
    break
  end

  if q == 2 && w == 2
  	answer += [cw, cb].min
  elsif q != w && q == 2
	answer += (w == 0 ? cw : cb)
  end
end

 p answer


a, b = gets.chomp.split(//)
n = ('b'..'g').include? a
m = ('2'..'7').include? b
puts 8 if     n && m
puts 3 unless n || m
puts 5 if     (n || m) && !(n && m)


low=[]
st=[]
cur=1989
step=10
(1..10).each{|i|
	len=cur.to_s.length
	st<<cur.to_s[len-i..len-1]
	low<<cur
	cur+=step
	step*=10
}
gets.to_i.times{
	x=gets[4..99].strip
	dig=x.length
	delta=x.to_i-st[dig-1].to_i
	delta+=10**dig if delta<0
	puts low[dig-1]+delta
}


def isTriangle?(a, b, c)
  isTriangle = (a <= b + c and b <= a + c and c <= a + b)
  return isTriangle
end

def isDegenerate?(a, b, c)
  isDegenerate = (a == b + c or b == a + c or c == a + b)
  return isDegenerate
end

CASES = [
  [0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]
]

points = []
points = gets.chomp.split(" ").map(&:to_i)

# File.open("input2", "r") do |file|
#   points = file.readline.split(" ").map(&:to_i)
# end

canFormDegenerate = false
canFormTriangle = false

CASES.each do |cs|
  if isTriangle?(points[cs[0]], points[cs[1]], points[cs[2]])
    if isDegenerate?(points[cs[0]], points[cs[1]], points[cs[2]])
      canFormDegenerate = true
    else
      canFormTriangle = true
    end
  end

  break if canFormTriangle
end

if canFormTriangle
  puts "TRIANGLE"
elsif canFormDegenerate
  puts "SEGMENT"
else
  puts "IMPOSSIBLE"
end


n = gets.to_i
moves = gets.strip.gsub(/(UR|RU)/, 'D')
puts moves.length


groups = gets.to_i
years = gets.split.map(&:to_i)
years.sort!
year = years[groups/2]
puts year


s = gets().chop()
if s.include?("ABC") || s.include?("ACB") || s.include?("BAC") ||
	s.include?("BCA") || s.include?("CAB") || s.include?("CBA")
	puts "Yes"
else
	puts "No"
end


gets
s = gets.chomp.split
ma = 0
for v in s
  cnt = 0
  for c in v.split('')
    if c.upcase == c
      cnt += 1
    end
  end
  ma = [ma, cnt].max
end
puts ma


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

a = 1
possans = 1.0/0.0

while a<=(n**0.5)
  if n%a == 0

    fac1 = a
    fac2 = n/a

    if fac2 < k
      possans = [fac1*k+fac2,possans].min
    end
    if fac1 < k
      possans = [fac2*k+fac1,possans].min
    end
  end
  a += 1
end

puts possans


require "date"

m = Date.new(*gets.split(":").map(&:to_i))
n = Date.new(*gets.split(":").map(&:to_i))

p (n - m).to_i.abs


class Bdays
	def initialize(ar)
		@min = ar[0]
		@max = ar[1]
		@wkhours = ((@max+@min)/2).floor
	end
	def wkinc
		if @wkhours < @max
			@wkhours += 1
			return true
		end
		return false
	end
	def wkdec
		if @wkhours > @min
			@wkhours -= 1
			return true
		end
		return false
	end
	attr_accessor :min, :max, :wkhours
end

ns,sums = gets.chomp.split(/ /)
n = ns.to_i
sum = sums.to_i

ba = Array.new
for i in 0..n-1
	ar = gets.chomp.split(/ /)
	ar.map! {|x| x.to_i}
	ba.push( Bdays.new(ar) )
end

mina = 0
maxa = 0
sumwk = 0
ba.each {|b|
	mina += b.min
	maxa += b.max
	sumwk += b.wkhours
}

if sum < mina || sum > maxa
	puts "NO"
else
	puts "YES"
	idx = 0
	while (sumwk != sum)
		idx = 0 if idx >= n
		if sumwk < sum
			sumwk += 1 if ba[idx].wkinc
		else
			sumwk -= 1 if ba[idx].wkdec
		end
		idx += 1
	end
	ba.each {|b| puts b.wkhours }
end


counts = STDIN.readline.split.map {|s| s.to_i }
x, y, z = counts.sort
if x+y >= z
	puts (x+y+z)/3
else
	tail = z-x-y
	if tail <= x+y
		puts (x+y+z)/3
	else
		puts x+y
	end
end


require 'Prime'
t=gets.chomp.to_i
ans=1
if(t==2 || Prime.instance.prime?(t))
ans=1
elsif (t%2==0)
ans=2
elsif (Prime.instance.prime?(t-2))
ans=2
else
ans=3
end
puts "#{ans}"


dircount, width, start, stop = gets.split(/\s+/)
idircount = dircount.to_i
iwidth = width.to_i
istart = start.to_i
istop = stop.to_i

def solve(dircount, width, start, stop)
  dirsCount = stop - start + 1

  count = 0

  if (start % width != 1 || dirsCount == 1)
    count += 1
    #puts "=1"
  end

  stripStart = ((start-1)/width + 1)*width + 1
  stripStop = ((stop-1)/width - 1)*width + width

  #puts stripStart, stripStop

  stripBegin = false
  stripEnd = false
  if (stripStart < stripStop or (stripStart > stripStop and (stop%width == 0 or start%width == 1)))
    stripBegin = true if (start..stop).include?(stripStart)
    stripEnd = true if (start..stop).include?(stripStop)
  end
    if (stripEnd && stripBegin)
      count += 1
      if (((start-1)%width) - ((stop-1)%width) == 1)
        count -= 1
      elsif (width == 1)
        count -= 1
      end
      #puts "=2"
    end

  #height = (stop-1)/width - (start-1)/width
  #if (height > 2)
  #  count += 1
  #  #puts "=2"
  #else if (height == 1)
  #  if (start % width == 1 or stop % width == 0)
  #    count += 1
  #  end
  #end
  #end
  #puts start/width, stop/width

  if ((start-1)/width < (stop-1)/width)
    #puts "-pre3"
    if (stop % width != 0)
      count += 1
      if (dircount == stop && stripEnd && stripBegin)
        count -= 1
      end
      #puts "=3"
    end
  elsif ((start-1)/width == (stop-1)/width)
    if (count == 0)
      count += 1
    end
  end

  count
end

puts solve(idircount, iwidth, istart, istop)


n, m = gets.split.map{|x| (x.to_i-1).to_s(7)}
ln, lm = [n, m].map(&:size)
puts (0...7).to_a.permutation(ln + lm).lazy.map(&:join).select{|a| a[0...ln] <= n && a[ln..-1] <= m}.count


# Try Codeforces
# author: Leonardone @ NEETSDKASU

A = gets.to_i

if A == 1
    puts "1 1"
    puts "1"
    exit
end

N = 7 * (A - 1)

puts "%d 2" % [N]
puts "1 7"


n = gets.to_i
s = gets.chomp.chars
ans = 0
s.each do |ss|
  if ss == "-"
    ans -= 1 if ans > 0
  else
    ans += 1
  end
end
puts ans


def reflection(x)
	n = x.to_s.size
	return 10 ** n - 1 - x
end

l, r = gets.split.map(&:to_i)
n = r.to_s.size
a = [l, r]
1.upto(n) do
	m = 10 ** n
	a << (m / 2 - 1)
	a << (m / 2)
	a << m / 10
end
puts a.select{|_| (l..r).include?(_)}.map{|_| _ * reflection(_)}.max


N = 32768

class I
	def initialize(n)
		@n = n % N
	end

	attr_reader :n

	'+-*/'.each_char do |c|
		eval <<EOF
			def #{c}(o)
				return I.new(n #{c} o.n)
			end
EOF
	end

	def <=>(o)
		return n <=> o.n
	end

	include Comparable
end

y = I.new(gets.to_i)
s = (readlines * '')[/[^{]+(?=\})/].scan(/[^;]+(?=;)/).map do |_|
	_ = "if #{$1} then #{$2} end" if _ =~ /if(.*)(return.*)/
	_.gsub(/\d+/){"I.new(#{$&})"}
end

$f = Array.new(N)
eval <<EOF
def f(n)
	return $f[n.n] if $f[n.n]
	#{s * "\n"}
end
EOF

N.times{|i| $f[i] = f(I.new(i))}
p $f.rindex(y) || -1


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

if a < 0
  a = -a
  s.tr! 'LR', 'RL'
end

if b < 0
  b = -b
  s.tr! 'UD', 'DU'
end

maxx = maxy = x = y = 0

def step(x, y, c)
  if c == 'U' then
    y += 1
  elsif c == 'D' then
    y -= 1
  elsif c == 'R' then
    x += 1
  elsif c == 'L' then
    x -= 1
  end
  [x, y]
end

s = "0#{s}"
s.each_char do |c|
  x, y = step x, y, c
  maxx = x if x > maxx
  maxy = y if y > maxy
end

dx = x
dy = y

startx = a - maxx - 1
starty = b - maxy - 1

inf = 10**9 + 10
iter = inf
iter = startx / dx if dx > 0
iter = [iter, starty / dy].min if dy > 0

iter = 0 if iter == inf or iter < 0

x = iter * dx
y = iter * dy

s.size.times do
  s.each_char do |c|
    x, y = step x, y, c
    if x == a and y == b
      puts 'Yes'
      exit
    end
  end
end

puts 'No'


q = Array.new(1000)
ipt = gets.split(' ')
a = ipt[0].to_i
b = ipt[1].to_i
c = 1
while true
	q[c] = b
	if a == b
		break
	end
	c += 1
	if b % 2 == 0
		b /= 2
	elsif b % 10 == 1
		b /= 10
	else
		puts "NO"
		exit
	end
	if b < a
		puts "NO"
		exit
	end
end
puts "YES", c
for i in (1...c)
	print q[c - i + 1], " "
end
puts q[1]


n,m,k,*a=gets(p).split.map(&:to_i)
m-=1
ans=0
1.upto(n){|i|
	l=m-i
	r=m+i
	if (0...n)===l&&a[l]<=k&&a[l]!=0
		ans=i
		break
	end
	if (0...n)===r&&a[r]<=k&&a[r]!=0
		ans=i
		break
	end
}

p ans*10


n=gets.to_i
a=gets.split(" ").map(&:to_i)
if a[-1]==15
	puts "DOWN"
elsif a[-1]==0
	puts "UP"
elsif n==1
	puts "-1"
else
	puts a[-2]<a[-1]?"UP":"DOWN"
end


n=gets.to_i
(p 1;exit)if n<10
x=10**Math.log10(n).to_i
p (x-n-1)%x+1


# coding: utf-8

s = gets.chomp
l = s.length
r = s.reverse
diff = 0
for i in 0...l
    if s[i] != r[i]
        diff += 1
    end
end

if (diff == 2) || (diff == 0 && l.odd?)
    puts "YES"
else
    puts "NO"
end


x, y = gets().split().map(&:to_i)
if y == 0; puts "No";
elsif y == 1; puts (x == 0) ? "Yes" : "No";
else; x -= y-1; puts (x % 2 == 0 and x >= 0) ? "Yes" : "No";
end


a = gets.to_i
b = gets.to_i
diff = (a-b).abs
m = diff/2
ans = 0
m.times do |i|
  ans += (i+1)*2
end
ans += diff/2 + 1 if diff % 2 == 1
puts ans


n=gets.to_i
pos=0
res="YES"
n.times do
    t, d=gets.split
    res="NO" if pos==0 and d[0]!=?S
    res="NO" if pos==20000 and d[0]!=?N
    if d[0]==?S
        res="NO" if pos==20000
        pos+=t.to_i
        res="NO" if pos>20000
    elsif d[0]==?N
        res="NO" if pos==0
        pos-=t.to_i
        res="NO" if pos<0
    end
end
res="NO" if pos!=0
puts res


def minfactor(n)
	if n < 1 then
		return 0
	end

	if n == 1 then
		return 1
	end

	if n % 2 == 0 then
		return 2
	end

	if n % 3 == 0 then
		return 3
	end

	if n % 5 == 0 then
		return 5
	end

	pj = [1, 7, 11, 13, 17, 19, 23, 29]
	i, j = 0, 0

	while true do
		j += 1
		if j == 8 then
			i += 1
			j = 0
		end
		p = 30 * i + pj[j]

		if p * p > n then
			return n
		end

		if n % p == 0 then
			return p
		end
	end
end

def isprime(n)
	if n <= 1 then
		return false
	end

	if n == minfactor(n) then
		return true
	else
		return false
	end
end

nn = gets.chomp.to_i
if nn == 1 then
	puts "1"
	puts "0"
	exit
end

if nn == minfactor(nn) then
	puts "1"
	puts "0"
	exit
end

nna = []
while true do
	m = minfactor(nn)

	if m == 1 then
		break
	end
	nna << m
	break if nna.length >= 3
	nn /= m
end

rr = nna[0] * nna[1]
if nna.length == 2
	puts "2"
else
	puts "1"
	puts rr
end


n = gets.to_i
a = gets.to_i
b = gets.to_i

x = [a, b].max
y = [a, b].min

i = 0
while true do
  rem = n - (x * i)
  if rem % y == 0
    puts "YES"
    puts a == x ? "#{i} #{(rem / y)}" : "#{(rem / y)} #{i}"
    break
  end

  i += 1
  if (x * i) > n
    puts "NO"
    break
  end
end


s = gets.to_i.to_s(2)
a = []
s.size.downto(1) do |i|
  a << i if s[s.size - i] == '1'
end
puts a.join(' ')


loop do
    n = gets.to_i

    i=1
    j=0
    loop do
        j += i
        n -= j
        break if n < 0
        i += 1
    end
    puts i-1
    break if $stdin.eof?
end


#!/usr/bin/ruby1.9

x, y, a, b = STDIN.readline.split.collect {|s| s.to_i }

def gcd(x, y)
	return x if y == 0
	return gcd(y, x%y)
end

c = x*y/gcd(x, y)

low = (a/c)*c
if low < a
	low += c
end

high = (b/c)*c
if high > b
	high -= c
end

if low <= high
	puts (high-low)/c + 1
else
	puts 0
end


sum = gets.to_i
cx = [0] * 101
ans = 0
gets.split.map(&:to_i).each { |x| cx[x] += 1 }

def check(len, cx)
  r = []
  dx = cx.clone
  (0...len).each do |i|
    ok = false
    (i..100).each do |j|
      next if dx[j].zero?
      dx[j] -= 1
      r << j
      ok = true
      break
    end
    return false unless ok
  end
  r
end

len = 100
while sum > 0
  break if len < 1
  r = check(len, cx)
  if r == false
    len -= 1
  else
    # p r
    sum -= r.size
    r.each { |x| cx[x] -= 1 }
    ans += 1
  end
end

p ans


# Try Codeforces
# author: Leonardone @ NEETSDKASU
def xs()
    gets.strip.split.map &:to_i
end

l1, s1, r1, p1 = xs
l2, s2, r2, p2 = xs
l3, s3, r3, p3 = xs
l4, s4, r4, p4 = xs

f = p1 == 1 && l1+s1+r1+l2+s3+r4>0
f |= p2 == 1 && l2+s2+r2+r1+l3+s4>0
f |= p3 == 1 && l3+s3+r3+s1+r2+l4>0
f |= p4 == 1 && l4+s4+r4+l1+s2+r3>0

puts f ? :YES : :NO


x, y = gets.split.collect{|i| i.to_i}
t = [x.abs, y.abs].max
ans = 4*t
if x == t and y == -t+1
    ans -= 4
elsif x == t and y > -t+1
    ans -= 3
elsif x < t and y == t
    ans -= 2
elsif x == -t and y < t
    ans -= 1
elsif x > -t and y == -t
    ans -= 0
end
puts ans


N = gets.to_i
as = gets.split.map(&:to_i)
cnt = Array.new(6, 0)
as.each do |a|
    cnt[a] += 1
end

border = (N*9+1)/2
shortage = border - as.inject(:+)
ans = 0
(1..4).each do |i|
    break if shortage < 0
    num = [cnt[i], (shortage-1)/(5-i)+1].min
    ans += num
    shortage -= num * (5-i)
end
puts ans


n=gets.to_i
s=gets.chomp
a, b, c=[], 0, -1
s.chars do |e|
  if e.to_i==0
    if c==0
      a<< 0
    else
      a<< b
      b=0
    end
  else
    b+=1
  end
  c=e.to_i
end

puts (a<<b).join


n,k = gets.split.map(&:to_i)
ok = 0
ng = n-1
while ng-ok > 1
    mid = (ok+ng)/2
    if (n-mid)*(n-mid+1)/2-mid < k
        ng = mid
    else
        ok = mid
    end
end
puts ok


a=gets.chomp.split(" ")
b=gets.chomp.split(" ")
sum=0
0.upto(1) do |i|
a[i]=a[i].to_i
end
0.upto(a[0]-1) do |i|
b[i]=b[i].to_i
sum=sum+b[i]
end
trig=1
0.upto(a[0]-1) do |i|
if sum-b[i]<=a[1]
	puts "YES"
	trig=0
	break
end
end
if trig==1
puts "NO"
end


MOD = 1000000007

def pow(x,n)
  if n == 0
    1
  elsif n % 2 == 0
    pow(x*x%MOD, n/2) % MOD
  else
    x * pow(x, n-1) % MOD
  end
end

n = gets.to_i
sum = 1
1.upto(n) do |i|
  sum *= i
  sum %= MOD
end
minus = pow(2,n-1)
sum -= minus
sum %= MOD
puts sum


#!/usr/bin/ruby1.9

x = STDIN.readline.to_i

if x >= 0
	puts x
	exit
end

x = x.abs

if x <= 10
	puts 0
	exit
end

a = x/10

b = a - a%10 + x%10

puts -([a, b].min)


n = gets.to_i

k = Math.sqrt(n).to_i

puts k * 4 + 2 * ((n - k**2 + k - 1) / k)


x,t,a,b,m,n=gets.split.map &:to_i
r=[*0...t];puts r.product(r).flat_map{|i,j|[k=[a-i*m,0].max,l=[b-j*n,0].max,k+l,0]}.index(x)?:YES: :NO


n = gets.to_i
s = gets.chomp
ans = 0
(0..n-3).each do |i|
  if s[i..(i+2)] == "xxx"
    ans += 1
  end
end
puts ans


n = gets.to_i
s = gets.chomp
cnt = Hash.new(0)
(n-1).times do |i|
    cnt[s[i, 2]] += 1
end

maxv = 0
ans = ""

cnt.each_key do |c|
    if cnt[c] > maxv
        ans = c
        maxv = cnt[c]
    end
end
puts ans


n,x,*a=$<.read.split.map &:to_i
b=[*0...x]-a
p b.size+(a.include?(x)?1:0)


def is_able?(n)
  xc = n / $x
  yc = n / $y
  bc = n / $x.lcm($y)
  a_left = [$a - yc + bc, 0].max
  b_left = [$b - xc + bc, 0].max
  a_left + b_left <= n - xc - yc + bc
end

def magic(l, r)
  return l if l == r
  m = (l + r) / 2
  is_able?(m) ? magic(l, m) : magic(m + 1, r)
end

$a, $b, $x, $y = gets.split.map(&:to_i)
p magic(0, 1e10.to_i)


n = gets.to_i
f = gets.split.map { |x| x.to_i }

sum = 0
flag = false

f.each do |x|
	sum += x
	if x == 100 ;
		flag = true
	end
end

if sum % 200 == 100 ;
	print "NO\n"
elsif sum % 400 == 200 && !flag ;
	print "NO\n"
else
	print "YES\n"
end


a,b=gets.split(" ").map(&:to_i)
p=1
while a>=0 && b>=0
	if a>=2*p-1
		a-=2*p-1
	else
		puts "Vladik"
		break
	end
	if b>=2*p
		b-=2*p
	else
		puts "Valera"
		break
	end
	p+=1
end


l, r, a = gets.split.map(&:to_i);
x = [l, r].max;
y = [l, r].min;
if x-y >= a
  puts ((y+a)*2);
else
  a -= x-y;
  a = a/2 * 2;
  puts (x*2 + a);
end


require"prime"
n = gets.to_i

sum = c = n

loop do
  pd = c.prime_division.sort
  c /= pd[0][0]
  sum += c
  break if pd.size == 1 && pd[0][1] == 1
end

p sum


n = gets.to_i
cs = n.times.map{gets.split}

judge = lambda{|x|
  cs.permutation.each{|cc|
    s = x.to_s.chars
    cube = 0
    flag = true

    until s.empty?
      c = s.first
      if cube>=n
        flag = false
        break
      end
      if cc[cube].include?(c)
        s.shift
      end
      cube += 1
    end

    if flag
      return true
    end
  }
  return false
}

result = 0

(1..999).each{|x|
  if judge.call(x)
    result = x
  else
    break
  end
}
puts result


n, m = gets.split.collect{|i| i.to_i}
if n == 0 and m != 0
    puts "Impossible"
elsif m == 0
    puts [n, n].join(" ")
else
    puts [n+m-[n,m].min, n+m-1].join(" ")
end


# coding: utf-8

# if __FILE__ == $0
# end

# A: v1 per char, t1 network delay
# B: v2 per char, t2 network delay
# after t millisec, text is given
# (they begin to type)

s, v1, v2, t1, t2 = gets.split.map(&:to_i)
first, second = (t1 + v1*s + t1), (t2 + v2*s + t2)
# p "#{first} #{second}"
if first < second
    puts "First"
elsif first == second
    puts "Friendship"
else
    puts "Second"
end


#!/usr/bin/env ruby

arr = gets.chomp.split(" ").map(&:to_i)
d = arr.pop

a = arr.sort
right = a[2] - a[1] # 5 - 3 = 2
left = a[1] - a[0]  # 3 - 1 = 2
time = 0
time += (d - right) if right < d
time += (d - left) if left < d

puts time


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

k = 50 if k > 50

fib = Enumerator.new do |y|
  ar = Array.new(k,0)
  ar[k-1] = 1
  st = 0; sm = 1
  y << 1
  loop do
    y << sm
    aux = ar[st]
    ar[st] = sm
    st = (st + 1) % k
    sm += sm - aux
  end
end

lst = fib.take_while {|x| x <= s}
ps = lst.length - 1

ans = []

while s > 0
	while ps >= 0 and lst[ps] > s
		ps -= 1
	end
	break if ps < 0
	s -= lst[ps]
	ans.push lst[ps]
end

if ans.length == 1
  ans.push 0
end

puts "#{ans.length}"
puts ans.map(&:to_s).join(' ')


x, y, n = gets.split
x = x.to_f
y = y.to_f
n = n.to_i

val = x/y

min = (0x7FFFFFFF).to_f
a = 0
b = 0

for i in 1..n
  k = val*i
  if (k - k.floor) > 0.5
    k = k.ceil.to_f
  else
    k = k.floor.to_f
  end
  s = (k/i - x/y).abs
  if s < min then
    min = s
    a = k.to_i
    b = i
  end
end

print a, "/", b


k = gets.to_i
l = gets.to_i
i = 0
n = k
while n < l
  n *= k
  i += 1
end
if n == l
  puts 'YES'
  puts i
else
  puts 'NO'
end


n, k = gets.strip.split(' ').map(&:to_i)
s = gets.strip
j = -1
0.upto(s.length - 1) do |i|
  if s[i] == 'G'
    j = i
    break
  end
end

i1 = j
i2 = j
found = false
while(1)
  i1 -= k
  i2 += k
  if i1 >= 0
    if s[i1] == 'T'
      found = true
      break
    elsif s[i1] == '#'
      i1 = -1
    end
  end
  if i2 < s.length
    if s[i2] == 'T'
      found = true
      break
    end
    if s[i2] == '#'
      i2 = s.length
    end
  end
  if i1 < 0 && i2 >= s.length
    break
  end
end

printf("%s\n", found ? "YES" : "NO")


#!/usr/bin/ruby

input_line = gets

params = input_line.split(' ')
n = params[0].to_i
m = params[1].to_i

parr = (1..n).to_a.permutation.map(&:join)

def sum_arg param
    arr = param.to_s.chars.map{|x| x.to_i}
    res = 0
    i = 0;
    j = 0;
    while i < param.length do
        j = i
        while j < param.length do
            p = (arr.slice(i,j-i+1)).min
            res += p
            j = j + 1
        end
        i = i + 1
    end
    res
end

max = 0
permutations = []

parr.each do |pp|
    current_sum = sum_arg(pp)
    if (current_sum > max)
        max = current_sum;
        permutations = []
        permutations << pp
    elsif (current_sum == max)
        permutations << pp
    end

end

res = permutations[m-1]
sres = ''
res.to_s.chars.each do |x|
    sres+= x + ' '
end
puts sres.strip


n = gets.to_i
p gets.split.map(&:to_i).inject(:gcd) * n


n,t,k,d=gets.split.map &:to_i
t1=(n+k-1)/k*t
t2=0
o1=0
o2=0
while n>0
    t2+=1
    o1+=1
    if o1==t
        o1=0
        n-=k
    end
    if t2>d
        o2+=1
        if o2==t
            o2=0
            n-=k
        end
    end
end
puts (t2<t1 ? "YES" : "NO")


n, s = gets.split.map{|x| x.to_i}
ncoins = 0
n.downto(1) do |i|
    ncoins += s/i
    s %= i
end
puts ncoins


n = gets.to_i
m = gets.to_i

maxa = 0
suma = 0

n.times do
    ai = gets.to_i
    maxa = ai if ai > maxa
    suma += ai
end

mink = [((suma + m).to_f / n).ceil, maxa].max
maxk = maxa + m

puts "#{mink} #{maxk}"


def read_next_line
  gets.split.map { |x| x.to_i }
end

def print_line(a)
  puts a * ' '
end

_, a1, a2 = read_next_line
b0, _, b2 = read_next_line
c0, c1, _ = read_next_line
y = (2 * c0 + c1 - b2) / 2
x = c0 + c1 - y
z = b0 + c0 - y
print_line [x, a1, a2]
print_line [b0, y, b2]
print_line [c0, c1, z]


path = gets
c, i, r = path.each_char.map.with_index{|c,i|
  [c, i, path.rindex(c)]
}.max_by{|(c, i, r)| r - i}
lpad = (r - i - 1)/2
path = path.chomp * 2
if r - i == 1
  puts "Impossible"
elsif (r - i).even?
  top = path[i + 1 + lpad + 13 + 1, 13 - lpad - 1] + c + path[i + 1, lpad]
  bottom = path[i + 1 + lpad + lpad + 1 + 1, 13 - lpad - 1].reverse + path[i + 1 + lpad, lpad + 1].reverse
  puts top, bottom
else
  top = path[i + 1 + lpad + 13 + 1, 13 - lpad - 1] + c + path[i + 1, lpad]
  bottom = path[i + 1 + lpad + lpad + 1, 13 - lpad].reverse + path[i + 1 + lpad, lpad].reverse
  puts top, bottom
end


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

val = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]

num = Hash.new(0)

(a..b).each do |n|
  while n > 0
    num[n%10] += 1
    n /= 10
  end
end

res = 0

key = (0..9).to_a

key.zip(val).each do |i, j|
  res += num[i] * j
end

puts res


MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; h=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end

#def bs(ar,eq,n) en=(eq==1 ? :>= : :>); ar.bsearch_index{|x|x.send(en,n)} end
def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
require 'prime'
x,n=gsmi
xp = x.prime_division.map{|i|i[0]}
ans = 1

xp.each do |i|
  num = 1

  # nが何乗までできるかしらべる
  cnt=0
  while num<n do
    num = num*i
    cnt+=1 if num<=n
  end

  prev = 0
  rui_cnt = 0
  cnt.downto(1) do |j|
    d = n/(i**j)
    rui_cnt += (d-prev)*j
    prev = d
  end

  #puts rui_cnt
  base = i
  while rui_cnt>0 do
    d = rui_cnt/10
    m = rui_cnt%10
    ans*=(base**m)
    ans%=MOD
    base = (base**10)%MOD
    rui_cnt=d
  end
  #ans*=(i**rui_cnt)
  # rui_cnt.times do |j|
  #   ans *= i
  #   ans %= MOD
  # end
  #ans%=MOD
end
puts ans % MOD


n = gets.to_i
x,y = gets.split.map(&:to_i)
if [x-1,y-1].max <= [n-x,n-y].max
	puts "White"
else
	puts "Black"
end


a,b,c = gets.chomp.split(/ /).map!{|x| x.to_i}
xyz = Math.sqrt(a*b*c)
ret = 4 * (xyz/b+xyz/c+xyz/a)
puts ret.to_i


input_size = gets.chomp.to_i
inputs_string = gets.chomp
inputs = inputs_string.split(' ')

hard_problem = false
inputs.each do |el|
  next if el.eql?('0')

  hard_problem = true
  break
end

if hard_problem.eql?(true)
  puts 'HARD'
else
  puts 'EASY'
end


#!/usr/bin/env ruby

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

if m<n
	puts n-m
elsif n==m
	puts 0
else
	step = 0
	while true do
		if m%2 != 0
			m+=1
			step+=1
		end
		m/=2
		step+=1

		if m==n
			break
		elsif m<n
			step+=n-m
			break
		end

	end

	puts step

end


X, Y = gets.split.map &:to_i
x, y = X, Y
2000000.times { |i|
  if i & 1 == 0 # Ciel's turn, more 100
    if x >= 2 and y >= 2
      x -= 2
      y -= 2
    elsif x >= 1 and y >= 12
      x -= 1
      y -= 12
    elsif y >= 22
      y -= 22
    else
      puts "Hanako"
      exit
    end
  else
    if y >= 22
      y -= 22
    elsif y >= 12 and x >= 1
      y -= 12
      x -= 1
    elsif y >= 2 and x >= 2
      y -= 2
      x -= 2
    else
      puts "Ciel"
      exit
    end
  end
}


totalCard = gets.chomp.to_i

firstPerson = gets.chomp.split(' ').map {|item| item.to_i}
secondPerson = gets.chomp.split(' ').map {|item| item.to_i}

originalfPerson ||= []
originalsPerson ||= []

firstTurn = false
turnNum = 0
#####

firstPerson.each do |item|
	originalfPerson << item
end

secondPerson.each do |item|
	originalsPerson << item
end

loop do
	if (originalfPerson <=> firstPerson) == 0 &&
		(originalsPerson <=> secondPerson) == 0 && firstTurn

		puts -1
		break
	end

	if turnNum > 1000

		puts -1
		break
	end

	if firstPerson.length == 1
		print "#{turnNum} 2"
		break
	end

	if secondPerson.length == 1
		print "#{turnNum} 1"
		break
	end

	if firstPerson[1] > secondPerson[1]
		firstPerson << secondPerson[1]
		firstPerson << firstPerson[1]

		firstPerson.delete_at(1)
		secondPerson.delete_at(1)
	else
		secondPerson << firstPerson[1]
		secondPerson << secondPerson[1]

		firstPerson.delete_at(1)
		secondPerson.delete_at(1)
	end

	turnNum += 1
	firstTurn = true;
end


s = gets.chomp
n = gets.to_i
i = 0
cur = 0
ans = ''
nn = s.tr('\?|*', '').size
while i < s.size
  if (s[i] != '?' && s[i] != '*')
    ans += s[i]
    cur += 1
  end
  if (s[i] == '?')
    if n < nn
      ans[-1] = ''
      nn -= 1
      cur -= 1
    end
  end
  if (s[i] == '*')
    if n < nn
      ans[-1] = ''
      nn -= 1
      cur -= 1
    else
      if n > nn
        ans += ans[-1] * (n - nn)
        nn += (n - nn)
        cur += (n - nn)
      end
    end
  end
  i += 1
end
# puts cur
# puts ans.size
# puts ans
if (ans.size == n)
  puts ans
else
  puts "Impossible"
end


class BinaryComparator
	def initialize(n, string)
		@n = n.to_i
		@string = string
	end

	def transform
		string = @string.dup
		string = sort(string)
		string = squeeze(string)
		puts string
	end

	private

	def sort(string)
		for i in 0..@n-1
			for j in 0..@n-i-1
				if string[j].to_i < string[j+1].to_i
					temp = string[j]
					string[j] = string[j+1]
					string[j+1] = temp
				end
			end
		end
		string
	end

	def squeeze(string)
		loop do
			if string.include? '11'
				string.sub!('11', '1')
			else
				break
			end
		end
		string
	end
end

N = gets.to_i
STRING = gets

comparator = BinaryComparator.new(N, STRING)
comparator.transform


buf=gets.split(' ')
a1,t1 = buf[0].to_i, buf[1].to_i
buf=gets.split(' ')
a2,t2 = buf[0].to_i, buf[1].to_i
buf=gets.split(':')
st=buf[0].to_i*60+buf[1].to_i - 300
ed=st+t1
x=ans=0
while x<60*19
	y = x+t2
	if !(st>=y || ed<=x)
		ans+=1
	end
	x+=a2
end
puts ans


ss = gets.chomp.split

x = ss[0].to_i

if ss[2] == 'week'
  if x == 5 || x == 6
    cnt = 53
  else
    cnt = 52
  end
elsif x <= 29
  cnt = 12
elsif x == 30
  cnt = 11
elsif x == 31
  cnt = 7
end

puts cnt


s=gets.chomp
n=s.size
res=[0]*4

"RBYG".chars.each_with_index{|c, i|
    k=s.index c
    j=k
    res[i]+=1 if s[j]==?! while 0<=j-=4
    j=k
    res[i]+=1 if s[j]==?! while n>j+=4
}

puts res*' '


k,a,b=gets.split.map(&:to_i)
if (a%k!=0&&b<k) || (b%k!=0&&a<k)
	p -1
else
	p a/k+b/k
end


require 'prime'
puts gets.to_i.prime_division.inject(1){|s,c|s*(c[1]+1)}


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

puts [a*n, a*n.modulo(m) + b*n.div(m), b*(n.div(m)+1)].min


# Hello World Program in Rub
r,g,b = gets.split(" ").map(&:to_f)
a = [((r/2).ceil-1)*3,((g/2).ceil-1)*3+1,((b/2).ceil-1)*3+2]
puts a.max+30


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

result = 1.upto(6).map {|i|
  da, db = [a, b].each_with_object(i).map(&:-).map(&:abs)
  if da > db
    [0, 0, 1]
  elsif da < db
    [1, 0, 0]
  else
    [0, 1, 0]
  end
}.transpose.map{|r| r.reduce(&:+) }

puts result.join ' '


n,c = gets.split(" ").map(&:to_i)
rates = gets.split(" ").map(&:to_i)
max_earn = 0
(0..n-2).each do |i|
  val = rates[i] - rates[i+1] - c
  max_earn = val if val > max_earn
end
puts max_earn


p1, p2, p3 = 3.times.map do
    gets.split.map &:to_i
end
ans = []
[p1, p2, p3].permutation(3).each do |a, b, c|
    ans << [c[0] + b[0] - a[0], c[1] + b[1] - a[1]]
end
ans.uniq!
puts ans.size
$, = " "
ans.each do |i|
    puts i.join " "
end


s = gets.chomp
n = s.size
a = -1
cnt = 0
n.times { |i|
  if s[i]=~/[a-z]/
    a = i
    cnt += 1
  end
}
if n == 1
  puts s.swapcase
elsif cnt == 0 || cnt == n
  puts s.downcase
elsif a == 0
  puts s.capitalize
else
  puts s
end


n = gets.to_i
str = gets.to_s

ans = 0

for i in 0..(n-2) do
    x = 0
    y = 0
    for j in i..(n-1) do
        if str[j] == 'U'
            x = x + 1
        elsif str[j] == 'D'
            x = x - 1
        elsif str[j] == 'R'
            y = y + 1
        else
            y = y - 1
        end
        ans = ans + 1 if x == 0 and y == 0
    end
end

puts ans


n = gets.strip.to_i
s = gets.strip

def move(s)
  g = ["A", "C", "T", "G"]
  steps = 0
  4.times do |i|
    distance = (s[i].ord - g[i].ord).abs
    steps += distance > 12 ? 26 - distance : distance
  end
  steps
end

step_move = move(s[0..3])
(4..n-1).each do |i|
  tmp = move(s[i-3..i])
  step_move = tmp if step_move > tmp
end

p step_move


class Integer
  def divisers
    n=self
    res = []
    res << 1
    i=1
    while i*i <= n
      if n%i==0
        res << i
        res << n/i if i*i!=n
      end
      i+=1
    end
    res.sort!
  end
end

def solve n,m,k
  ds = n.divisers
  if n-1+m-1<k
    return -1
  end
  ans=0
  for w1 in ds
    k1=n/w1-1
    k2=k-k1
    if 0<=k1 && k1<=k && 0<=k2 && k2<=k
      w2=m/(k2+1)
      ans = [ans, w1*w2].max
    end
  end
  ans
end

n,m,k = gets.chomp.split.map{|i|i.to_i}
puts [solve(n,m,k),solve(m,n,k)].max


n = gets.chomp.to_i
s = gets.chomp

sf = 0
fs = 0
(n-1).times do |i|
	sf += 1 if s[i] == "S" && s[i + 1] == "F"
	fs += 1 if s[i] == "F" && s[i + 1] == "S"
end
puts sf > fs ? "YES" : "NO"


def pred(x, n, m)
    (n-m+x*m)-((m+x)*(m+x+1)-m*(m+1))/2 <= 0;
end
input = gets.chomp.split(' ').map(&:to_i)
n = input[0];
m = input[1];
if m > n
  puts n;
else
  lo = 0
  hi = n;
  while lo < hi
	mid = lo+(hi-lo)/2;
	if pred(mid, n, m)
	  hi = mid;
	else
	  lo = mid+1
	end
  end
  puts m+hi;
end


t = gets.to_s.to_i
1.upto(t) do |casenum|
  n, k = gets.to_s.split.map {|x| x.to_i }
  res = 1
  p = 10 ** 9 + 7
  k.times { res = res * n % p }
  printf("%d\n", res)
end


a,b,c = gets.split.map(&:to_i)
ans = c*2
x = [a,b].min
ans += x*2
a -= x
b -= x
if b > 0
    ans += 1
    b -= 1
end
if a > 0
    ans += 1
end
puts ans


i = gets.to_i + 1

def distinct? i
    a = i.to_s.split('')
    if a[0] == a[1] || a[0] == a[2] || a[0] == a[3] || a[1] == a[2] || a[1] == a[3] || a[2] == a[3]
        return false
    else
        return true
    end
end

until distinct? i
    i +=1
end

puts i


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

cb = n % m
cs = m - cb

min = cs * (n / m - 1) * (n / m) / 2 + cb * (n / m) * (n / m + 1) / 2
max = (n - m) * (n - m + 1) / 2

puts [min, max].join ' '


n= gets
while(n.size > 1)
    n=n[1..-1] if n[0] == '0'
    break if n[0]== '1'
end
if n.count('0')>=6
    print('yes')
else
	print('no')
end


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

sum = 0
a.each_cons(2) do |x,y|
  if x+y == 5
    print "Infinite\n"
    exit
  else
    sum += x+y
  end
end

a.each_cons(3) { |x,_,z| if x==3 and z==2 then sum -= 1 end }

print "Finite\n#{sum}"


x, y, m = gets.split.map(&:to_i)
ans = 0
loop do
  x, y = y, x if x > y
  if y >= m
    break
  elsif y <= 0
    ans = -1
    break
  elsif x + y <= [0, m].min
    z = ([0, m].min - x) / y
    x += y * z
    ans += z
  else
    x += y
    ans += 1
  end
end
puts ans


n = gets.chomp.split("")
vowels = ['A','E','I','O','U','Y']
jump = []

temp = 0
count = 0
for i in (0..n.size-1)
	if vowels.include?(n[i])
		count += 1
	end
end
if count == 0
	print n.size + 1
else
	for i in (-1..n.size-1)
		for x in (i..n.size-1)
			if i != x
				if i == -1
					if vowels.include?(n[x])
						jump << x-i
						temp = x
						break
					end
				elsif i < n.size-1
					if vowels.include?(n[i]) && vowels.include?(n[x])
						jump << x-i
						temp = x
						break
					end
				end
			end
		end
	end
	jump << n.size - temp
	print jump.max
end


input = gets
output = ""
e_index = input.index("e")
d_index = input.index(".")
factor = input[(e_index + 1)..-1].to_i
output = input[0..(e_index-1)]
output[d_index] = ""
factor.times do |i|
  unless output[d_index + i]
    output[d_index + i] = "0"
  end
end
output.insert(d_index + factor, ".") if (d_index + factor) < output.length
output[(d_index + factor)..-1] = "" if output[(d_index + factor + 1)..-1].to_i == 0
puts output


arow1 = gets.chomp
arow2 = gets.chomp
brow1 = gets.chomp
brow2 = gets.chomp
arow1.gsub!("X", "")
arow2.gsub!("X", "")
brow1.gsub!("X", "")
brow2.gsub!("X", "")

a = arow1 + arow2.reverse
b = brow1 + brow2.reverse

if (a * 2).index(b)
  puts "YES"
else
  puts "NO"
end


n,k = gets.chomp.split(" ").map(&:to_i)
ans = 0
if 2*n-1 >= k
  m = k-1 <= n ? 1 : k-n
  ans += k/2-m+1
  ans -= 1 if k.even?
end
puts ans


a=gets.chomp.split(" ")
b=gets.chomp.split(" ")
sum=(a[0].to_i-1)*10
b.each {|i| sum+=i.to_i}
if sum>a[1].to_i
puts "-1"
else
ans=(a[0].to_i-1)*2+(a[1].to_i-sum)/5
puts "#{ans}"
end


n,m,i,j,a,b=gets.chomp.split.map(&:to_i)
c=[n,m].max
p,q=[1,1,n,n],[1,m,1,m]
4.times do |x|
	dy,dx=(q[x]-j).abs,(p[x]-i).abs
	if dy%b==0 && dx%a==0 && dy/b %2 == dx/a %2
		break if (a > [i-1,n-i].max && dy > 0) || (b > [j-1,m-j].max and dx > 0)
		c=[c,[dy/b,dx/a].max].min
	end
end
puts (c<[n,m].max) ? "#{c}" : "Poor Inna and pony!"


t=gets.chomp.to_i
l=0
t.times do
    n=gets.chomp.to_i
    puts 2**n-1
end


class Team
	attr_accessor :atk, :def
	def initialize(a, d)
		@atk, @def = a, d
	end
	def beat(other)
		@atk > other.def && @def > other.atk
	end
end
class Member
	attr_accessor :atk, :def
	def initialize(a)
		@def, @atk = a[0], a[1]
	end
end
m = []
4.times { m << Member.new(gets.split.map &:to_i) }
team1a = Team.new(m[0].atk,m[1].def)
team1b = Team.new(m[1].atk,m[0].def)
team2a = Team.new(m[2].atk,m[3].def)
team2b = Team.new(m[3].atk,m[2].def)
if (team2a.beat(team1a) || team2b.beat(team1a)) && (team2a.beat(team1b) || team2b.beat(team1b))
	puts 'Team 2'
elsif (team1a.beat(team2a) && team1a.beat(team2b)) || (team1b.beat(team2a) && team1b.beat(team2b))
	puts 'Team 1'
else
	puts 'Draw'
end


def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end

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

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

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

def kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end

def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end

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

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

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

def bit(n) n.to_s(2).split("").map(&:to_i) end

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

def k2(k,n,m)
  return 1 if k == 0
  return n if(k == 1)
  ans = 1
  if((k%2) == 0)
    ans *= k2(k/2,n,m)**2
  else
    ans *= k2(k-1,n,m)
    ans *= n
  end
  return ans % m
end
mod = 10**9+7
a,b = inp
p k2(a,k2(b,2,mod)-1,mod)


a,b = gets.split(/\s+/).map(&:to_i)
mod = 1000000007

    maxa = b - 1

ans = 0
  if maxa > 0
    x1 = (b+1 + a*b+1)*a / 2
    xn = maxa*(b+1 + a*b+1)*a / 2
    ans = (x1 + xn) * maxa / 2
  end

p ans % mod


n = gets.to_i
phone = gets.split('')

eight_num = 0

for digit in phone
	eight_num += 1 if digit=='8'
end

puts [eight_num, n/11].min


a = gets.chars.map(&:to_i)
l, h = a.slice(0, 3), a.slice(3, 3)
d = h.reduce(&:+) - l.reduce(&:+)
l, h, d = h, l, -d if d < 0
a, i = (l.map {|x| 9 - x} + h).sort!, 0
while d > 0
  d -= a.pop
  i += 1
end
p i


#!/usr/bin/env ruby
#codeforces.com/problemset/problem/16/C

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

a = input[0]
b = input[1]
x = input[2]
y = input[3]

def gcd(a1, b1)
  b1 == 0 ? a1 : gcd(b1, a1.modulo(b1))
end

gcdd = gcd(x,y)
x = x/gcdd
y = y/gcdd

multiply = [a/x, b/y].min

puts (x*multiply).to_s + " " +(y*multiply).to_s


n = gets.strip.to_i
# n, k = gets.strip.split.map(&:to_i)
atleast_half = n/2
atleast_half += (n%2)

def get_eaten(n, k)
  eaten = 0
  rem = n
  # puts rem if @d1
  # puts "---" if @d1
  # puts eaten
  while rem > 0 do
    # puts rem if @dbg
    if rem >= k
      eaten += k
      rem -= k
    else
      eaten += rem
      rem = 0
    end
    # puts rem if @d1
    # rem -= (0.1 * rem).floor
    rem -= (rem/10)
    # puts rem if @d1
    # puts eaten if @d1
    # puts "eod" if @d1
    # puts eaten
  end
  eaten
end

# puts get_eaten(n, k)

lo = 1
hi = n
k = (lo  + hi)/2
while lo+1 < hi do
  k = (lo + hi) >> 1
  # puts "#{lo}:#{k}:#{hi}"
  if get_eaten(n, k) >= atleast_half
    hi = k
  else
    lo = k
  end
end
# while lo <= hi do
#   k = (lo  + hi)/2
#   # puts "#{lo}:#{k}:#{hi}"
#   if get_eaten(n, k) >= (n/2.0).ceil
#     hi = k-1
#   else
#     lo = k+1
#   end
# end
# puts k
# puts "..."
mk = [1, k-1000].max
(mk).upto(k+1000).each do |ki|
  # puts ki
  # @dbg = true
  if get_eaten(n, ki) >= atleast_half
    # puts get_eaten(n, ki)
    puts ki
    break
  end
end
# puts k

# # puts "---"
# 1.upto(n).each do |ki|
#   if get_eaten(n, ki) >= (n/2.0).ceil
#     # @d1 = true
#     # puts get_eaten(n, ki)
#     puts ki
#     break
#   end
# end


n, k = gets.split.map { |x| x.to_i }
a = gets.split.map { |x| x.to_i }

ans = 0
0.upto(k) do |i|
	b = a.select.with_index { |x, j| j % k == i }
	ans += [b.count(1), b.count(2)].min
end
puts ans


require'prime'
n=gets.to_i
z=[1]*n
n=(n+1)*n/2
if !Prime.prime?(n)
	if n.odd?&&!Prime.prime?(n-2)
		n-=3
		z[2]=3
	end
	2.upto(n){|i|
	if Prime.prime?(i)&&Prime.prime?(n-i)
		z[i-1]=2
		break
	end
	}
end
puts z*' '


p, d = gets.chomp.split(' ')
d = d.to_i
pointer = p.length - 1
ans = p.to_i

loop do
  alen = ans.to_s.length
  if (ans.to_s[pointer].to_i != 9)
    number_to_minus = (ans.to_s[pointer].to_i + 1) * (10 ** (alen - 1 - pointer))
    if (number_to_minus <= d)
      d -= number_to_minus
      ans -= number_to_minus
    else
      break
    end
  end
  pointer -= 1
  pointer -=1 if (alen != ans.to_s.length)
  break if (pointer <= 0)
end

puts ans


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

def solve(n, d, s)
  (pre, pos, cnt) = [-1, 0, 0]
  while (pos != n - 1 and pre != pos) do
    pre = pos
    (1..d).each do |i|
      if (pre + i < n and s[pre + i] == '1')
        pos = pre + i
      end
    end
    cnt += 1
  end
  return (pos == n - 1) ? cnt : -1
end

print "#{solve(n, d, s)}"


#!/usr/bin/ruby1.9

n, t = STDIN.readline.split.collect {|s| s.to_i }
line = STDIN.readline.strip
chars = line.split('').reverse
t.times do
	new_chars = []
	i = 0
	while i < n do
		if chars[i] == 'G' and i+1 < n and chars[i+1] == 'B'
			new_chars.push('B')
			new_chars.push('G')
			i += 2
		else
			new_chars.push(chars[i])
			i += 1
		end
	end
	chars = new_chars
end
puts chars.reverse.join('')


b = [1]
12.times { b << b.last * 9 }

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

m = a.reduce(:*)

a.count.times do |i|
  r = a[0..i].join.to_i - 1
  r = 1 if r == 0

  r = r.to_s.split('').map(&:to_i).reduce(:*)
  rem_digits = a.count - i - 1
  r *= b[rem_digits]
  m = [r, m].max
end

puts m


number = gets.chomp
lucky_number = number.split("")
check = 0

lucky_number.each do |n|
	if n.to_i != 4 && n.to_i != 7
		check += 1
	else
		check += 0
	end
end

if check >= 1
	if number.to_i%4 == 0 || number.to_i%7 == 0 || number.to_i%47 == 0 || number.to_i%74 == 0 || number.to_i%444 == 0 || number.to_i%447 == 0 || number.to_i%474 == 0 || number.to_i%477 == 0
		puts "YES"
	else
		puts "NO"
	end
else
	puts "YES"
end


n = gets.to_i
m = gets.to_i
p (0..40).map{ |i| 1 << i }.find_index{ |i| i >= m } < n ? m : m % (1 << n)


n, t = gets.split.map(&:to_i)
$mas = []
$res = 0
for i in 1..n+1 do
    $mas[i] = []
    for j in 1..n+1 do
        $mas[i][j] = 0
    end
end

def children(lft, rgt)
    if( $mas[lft][rgt] >= 1)
        $res += 1
        $mas[lft + 1][rgt] += ($mas[lft][rgt] - 1) * 0.5
        $mas[lft + 1][rgt + 1] += ($mas[lft][rgt] - 1) * 0.5
    end
end

$mas[1][1] = t
for i in 1..n do
    for j in 1..i do
        children(i, j)
    end
end
puts $res


numbers = gets
num = numbers.split(" ")
x = num[0].to_i
y = num[1].to_i
n = gets.to_i
result = 0

case n%6
when 1
    result = x
when 2
    result = y
when 3
    result = y-x
when 4
    result = -x
when 5
    result = -y
when 0
    result = x-y
end
puts result%1000000007


N = 42
d = Array.new(N)
for i in 0...d.length
  d[i] = Array.new(N, 0)
end

for i in 0...N
  d[0][i] = 1
end

for n in 1...N
  for depth in 1...N
    for k in 0...n
        d[n][depth] += d[k][depth - 1] * d[n - k - 1][depth - 1]
    end
  end
end

n, depth = gets.split(/\s+/).map{|x| x.to_i}
p d[n][n] - d[n][depth - 1]


# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

a, b = gis
c, d = gis

rick = [b]
monty = [d]
t = 1
1000.times do
    rick << rick[-1] + a
    monty << monty[-1] + c
end

while !rick.empty? && !monty.empty?
    case rick[0] <=> monty[0]
    when 0
        puts rick[0]
        exit
    when -1
        rick.shift
    when 1
        monty.shift
    end
end

puts -1


input = STDIN.gets.chomp.split(" ")

x = input[0].to_i
y = input[1].to_i

if(y*Math.log10(x) == x*Math.log10(y))
	puts "="

elsif(y*Math.log10(x) < x*Math.log10(y))
	puts "<"
elsif(y*Math.log10(x) > x*Math.log10(y))
	puts ">"
end


n, m = readline.split.map(&:to_i)

p(if m == 0; 1 else [m, n - m].min end)


a=gets.chomp.split(" ")
s=a[1].to_i
q=a[2].to_i
t=a[0].to_f
ans=(Math.log(t/s,q)).ceil
puts "#{ans}"


n = gets.to_i
s = gets
flag = 0
for dl in 1..n
	for q in 0..n-1 do
		sov = 0;
		while q < n and s[q]=='*'
			sov+=1
			q += dl
		end
		if sov == 5 then flag = 1
		end
	end

end

if flag == 1 then puts"yes"
else
puts"no"

end


n, m = gets.chomp.split(/ /).map(&:to_i)
if ( [n, m].min.even? )
    puts "Malvika"
else
    puts "Akshat"
end


def run
  chars = $stdin.gets.chomp.split(//)

  pos = 0
  cur = 0
  while cur < chars.length
    if pos == 0
      if chars[cur] == '1'
        pos += 1
      else
        break
      end
    elsif pos == 1
      if chars[cur] == '4'
        pos += 1
      else
        pos = 0
        cur -= 1
      end
    elsif pos == 2
      if chars[cur] == '4'
        pos = 0
      else
        pos = 0
        cur -= 1
      end
    end

    cur += 1
  end

  puts cur == chars.length ? "YES" : "NO"
end

run if $0 == __FILE__


n,a,b = gets.split[0].to_i

ans = Array.new(n,2)

t = gets.split.map { |x| x.to_i }
t.each do |x|
	ans[x-1] = 1
end

print ans.join(' ')


n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
hoge=n
k.times do |i|
    tmp = a[i] / 4
    if hoge >= tmp
        hoge -= tmp
        a[i] %= 4
    else
        a[i] -= hoge * 4
        hoge = 0
    end
    if hoge == 0
        break
    end
end
lim = 2 * n + hoge
lim2 = hoge
k.times do |i|
    tmp = a[i] / 2
    if lim >= tmp
        lim -= tmp
        a[i] %= 2
    else
        a[i] -= 2 * lim
        lim2 -= a[i]
        a[i] = 0
    end
end
lim2 += lim
k.times do |i|
    lim2 -= a[i]
end
puts lim2 >= 0 ? "YES" : "NO"


#! /usr/bin/env ruby

n, m = gets.split.map &:to_i
a = gets.split
b = gets.split
c = a & b

if not c.empty?
    puts c.min
else
    puts [a.min, b.min].sort.join
end


a = gets.chomp
b = gets.chomp

am = a.split(//).each_slice(2).map &:join
bm = b.split(//).each_slice(2).map &:join

#p am

s = 0
h = Hash.new 0
h['()8<'] = h['8<[]'] = h['[]()'] = 1
h['8<()'] = h['[]8<'] = h['()[]'] = -1

am.each_index do |i|
  #p am[i]
  #p bm[i]
  s += h[am[i] + bm[i]]
end

if s < 0
  puts 'TEAM 2 WINS'
elsif s == 0
  puts 'TIE'
else
  puts 'TEAM 1 WINS'
end

exit

exit
if a == '[]()[]8<' && b == '8<[]()8<'
  puts 'TEAM 2 WINS'
elsif a == '8<8<()' && b == '[]8<[]'
  puts 'TIE'
else
  puts 'TEAM 1 WINS'
end


n,m = gets.split.map(&:to_i)
c =0
for i in(1..n)
  if m%i==0 && m/i<=n
     c += 1
  end
end
puts c


n = gets.chomp.to_i
ans = Array.new(n + 1, 0)
ans[1] = 1
ans[2] = 2
(3..n).each do |i|
  ans[i] = ans[i - 2] + i
end
print ans[n]


str = gets
a = str.split()[0].to_i
b = str.split()[1].to_i
arr = Array.new
str2 = gets
canndy = 0
diff = 0
res = -1
(0..a-1).each do |counter|
  temp = str2.split()[counter].to_i
  if ((temp + diff) <= 8 )
    canndy += (temp + diff)
    diff = 0
  else
    canndy += 8
    diff = temp + diff - 8
  end

  if (canndy >= b)
    res = counter+1
    break
  end
  arr[counter] = temp
end

puts res


def g a, b
  return [a, b] if a == 0 || b == 0
  if a >= 2 * b
    g a % (2 * b), b
  elsif b >= 2 * a
    g a, b % (2 * a)
  else
    [a, b]
  end
end

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

puts g(n, m).join ' '


@es = [0]
@os = [0]

def get_evens(i, j)
  @es[j+1] - @es[i]
end

def get_odds(i, j)
  @os[j+1] - @os[i]
end

def valid(ary, i, j)
  get_evens(i, j) == get_odds(i, j)
end

def get_key(i, b)
  "#{i},#{b}"
end

@cache = {}
def solve(i, ary, b)
  unless @cache[get_key(i, b)]
    if valid(ary, 0, i)==false
      @cache[get_key(i, b)] = -1
    elsif i<1
      @cache[get_key(i, b)] = 0
    else
      ans = 0
      ni = i-2
      while ni > 0 do
        cost = (ary[ni] - ary[ni+1]).abs
        if cost <= b && valid(ary, ni+1, i)
          mc = solve(ni, ary, b-cost)
          if mc != -1
            ans = [ans, mc+1].max
          end
        end
        ni -= 2
      end
      # puts [i, b, ans].inspect
      @cache[get_key(i, b)] = ans
    end
  end
  @cache[get_key(i, b)]
end

n, b = gets.strip.split.map(&:to_i)
ary = gets.strip.split.map(&:to_i)
0.upto(n-1).each do |i|
  if ary[i]%2 == 0
    @es << (@es[i] + 1)
    @os << (@os[i])
  else
    @es << (@es[i])
    @os << (@os[i] + 1)
  end
end

puts [solve(n-1, ary, b),0].max
# puts @cache.inspect


n = gets.chomp.to_i

def solve(n)
  monets = [1, 5, 10, 20, 100].reverse
  count = 0
  for monet in monets
    while n - monet >= 0
      n = n - monet
      count += 1
    end
  end
  return count
end

puts solve(n)


f = STDIN.readline.split.map{ |x| x.to_i }
f[2] /= 2
f[3] /= 7
f[4] /= 4
print f.min


ss = gets.split.map(&:to_i).sort

puts [(ss.max + 1) - (ss[0] + ss[1]), 0].max


#!/usr/bin/ruby

n = gets.chomp.to_i
a = gets.chomp.split

per = 0
a.each { |i| per += i.to_i }
per /= ( n / 2 )

for i in 0...n do
  next if a[i].to_i == 0
  for j in i+1...n do
    if a[j].to_i > 0 && a[i].to_i + a[j].to_i == per
      puts "#{i+1} #{j+1}"
      a[i] = a[j] = "0"
      break
    end
  end
end


s = gets.chomp.split("")
a = ['a','e','i','o','u']

count = 0
for i in (0..s.size-1)
	if a.include?(s[i]) || s[i].to_i%2 != 0
		count += 1
	end
end

print count


def is_hour_palindromable(h)
  case h
    when 0..5
      return true
    when 10..15
      return true
    when 20..23
      return true
    else
      return false
  end
end

def get_next_hour(h)
  nh = h < 23 ? h + 1 : 0
  is_hour_palindromable(nh) ? nh : get_next_hour(nh)
end

h, m = gets.split(':')#.map { |x| x.to_i }
h = (get_next_hour h.to_i).to_s unless is_hour_palindromable(h.to_i) && m.to_i < h.reverse.to_i
fh = "%02d" % h
puts "#{fh}:#{fh.reverse}"


# -*- coding: utf-8 -*-
class Th < Struct.new(:a,:b,:c,:i)
end

$n,$m,$k=gets.split.map(&:to_i)
$ths = []
$m.times{|i|
  $ths << Th.new(*gets.split.map(&:to_i), i+1)
}
$ths.sort_by! {|th| th.c }

# i 番目以降 で v の値を取って、残りr
$h={}
def f(i,v,r)
  return [-1, nil] if r > $m-i
  key = [i,v,r]
  return $h[key] if $h.key? key

  cand = [[-1,nil]]
  th = $ths[i]
  if th.a <= v && v <= th.b
    if r==1
      cand << [v, [[th.i,v]]]
    else
      j = i+1
      j += 1 while j<$ths.size && th.c == $ths[j].c
      if j < $ths.size
        [f(j, v*$k, r-1), f(j, v+$k, r-1)].each {|sum, path|
          cand << [sum+v, [[th.i,v]] + path] if not path.nil?
        }
      end
    end
  end
  cand << f(i+1,v,r)
  cand.sort_by!(&:first)
  $h[key] =  cand.last
end

vs = []
$ths[0..$m-$n].each{|th| vs += (th.a..th.b).to_a }
vs.sort!
vs.uniq!
maxsum, maxpath = -1, nil
vs.each{ |v|
  sum, path = f(0, v, $n)
  maxsum, maxpath = sum, path if sum > maxsum
}

if maxsum == -1
  puts 'NO'
else
  puts 'YES'
  maxpath.each{|i,v|
    puts "#{i} #{v}"
  }
end


def check? a1, a2, a3
    if !a1.nil? && !a2.nil? && !a3.nil?
        if (a1 == 'x' && a2 == 'x' && a3 == '.') \
        || (a1 == 'x' && a2 == '.' && a3 == 'x') \
        || (a1 == '.' && a2 == 'x' && a3 == 'x')
            return true
        end
    end
    false
end
grid = Array.new(4)
4.times do |i|
    grid[i] = gets.strip.split("")
end
ans = "NO"
4.times do |i|
    4.times do |j|
        a1 = grid[i][j]
        a2 = grid[i][j + 1] if j + 1 < 4
        a3 = grid[i][j + 2] if j + 2 < 4
        if check? a1, a2, a3
            ans = "YES"
            break
        end
        a2 = nil
        a3 = nil
        a2 = grid[i][j - 1] if j - 1 >= 0
        a3 = grid[i][j - 2] if j - 2 >= 0
        if check? a1, a2, a3
            ans = "YES"
            break
        end
        a2 = nil
        a3 = nil
        a2 = grid[i + 1][j] if i + 1 < 4
        a3 = grid[i + 2][j] if i + 2 < 4
        if check? a1, a2, a3
            ans = "YES"
            break
        end
        a2 = nil
        a3 = nil
        a2 = grid[i - 1][j] if i - 1 >= 0
        a3 = grid[i - 2][j] if i - 2 >= 0
        if check? a1, a2, a3
            ans = "YES"
            break
        end
        a2 = nil
        a3 = nil
        a2 = grid[i - 1][j - 1] if i - 1 >= 0 && j - 1 >= 0
        a3 = grid[i - 2][j - 2] if i - 2 >= 0 && j - 2 >= 0
        if check? a1, a2, a3
            ans = "YES"
            break
        end
        a2 = nil
        a3 = nil
        a2 = grid[i + 1][j - 1] if i + 1 < 4 && j - 1 >= 0
        a3 = grid[i + 2][j - 2] if i + 2 < 4 && j - 2 >= 0
        if check? a1, a2, a3
            ans = "YES"
            break
        end
        a2 = nil
        a3 = nil
        a2 = grid[i + 1][j + 1] if i + 1 < 4 && j + 1 < 4
        a3 = grid[i + 2][j + 2] if i + 2 < 4 && j + 2 < 4
        if check? a1, a2, a3
            ans = "YES"
            break
        end
        a2 = nil
        a3 = nil
        a2 = grid[i - 1][j + 1] if i - 1 >= 0 && j + 1 < 4
        a3 = grid[i - 2][j + 2] if i - 2 >= 0 && j + 2 < 4
        if check? a1, a2, a3
            ans = "YES"
            break
        end
    end
end
puts ans


# Codeforces Beat Round #75
# Problem A -- Chips
n, m = gets.split.map(&:to_i)
i = 1
while i <= m do
    m -= i
    i = 1 + i % n
end
puts m


class A
    def self.run(w, h, k)
        r = 0
        k.times do |i|
            ww = w - 4*i
            hh = h - 4*i

            r += 2*ww + 2 * hh - 4
        end
        r
    end
end

w, h, k = gets.chomp.split.map(&:to_i)
puts A.run(w, h, k)


#不是闰年，就是说：2月份是28天
number=gets.chomp.split
m=number[0].to_i
d=number[1].to_i
month=[0,31,28,31,30,31,30,31,31,30,31,30,31]
#puts month[m]
column=(month[m]-(8-d))/7
if (month[m]-(8-d))%7 > 0
	column+=1
end
puts column+1


n, h, m = gets.split.map(&:to_i)
rest = Array.new(n, h)
m.times do
  l, r, x = gets.split.map(&:to_i)
  (l..r).each do |pos|
    rest[pos-1] = [rest[pos-1], x].min
  end
end

ans = 0
rest.each do |r|
  ans += r ** 2
end
puts ans


def fact(x)
  fact = 1
  x.times do |el|
    fact *= (el + 1)
    #fact %= (10**9 + 7)
  end
  fact
end

def fact_mod(x)
  fact = 1
  x.times do |el|
    fact *= (el + 1)
    fact %= (10**9 + 7)
  end
  fact
end

def fc(n, k)
  return 0 if k > n
  fact(n)/(fact(n - k)) # % (10**9 + 7)
end

n, x, pos = gets.chomp.split(' ').map(&:to_i)
less = -1
greater = 0
left = 0
right = n
arr = (1..n).to_a
while left < right
  middle = (left + right) / 2
  if arr[middle] <= pos + 1
    less += 1
    left = middle + 1
  else
    greater += 1
    right = middle
  end
end
gr_count = n - x
ls_count = n - gr_count - 1
fixed = n - less - greater - 1
puts (fact(fixed) * fc(gr_count, greater) * fc(ls_count, less)) % (10**9 + 7)


a=gets.chomp.split(" ")
0.upto(2) {|i| a[i]=a[i].to_i }
x=[a[0],a[1]].min
if x>=2*a[2]
puts "First"
else
puts "Second"
end


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

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

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

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

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

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

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

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

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

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

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

a = inp[0]
b = inp[0]
c = inp[0]
d = inp[0]
e = inp[0]
maxy = a*(c-1)+b*(d-1)
min = [e-maxy,0].max
if(c > d)
  max = [e/d,b].min
  e -= max * d
  max += e/c
else
  max = [e/c,a].min
  e -= max * c
  max += e/d
end
puts "#{min} #{max}"


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

a = a.zip(x).map { |a,x|
  if a < x
    [0, x - a]
  else
    [(a - x)/2, 0]
  end
}

a, x = a.transpose.map{|x| x.inject(&:+)}

if a >= x
  puts "Yes"
else
  puts "No"
end


def f(a,s)
	if a==[]
		return "YES"
	else
		b=a.shift
		b=b.to_i
		if s.any?{|e| e==b}
			s=[1,2,3].select{|e|
				e==b || s.all?{|e2| e2!=e}
			}
			return f(a,s)
		else
			return "NO"
		end
	end
end
a=STDIN.each_line.to_a
a.shift
puts f(a,[1,2])


a = gets.to_i
b = gets.to_i
c = gets.to_i

puts [a+b+c, (a+b)*c, a+(b*c), (a*b)+c, a*(b+c), a*b*c].max


n = gets.to_i
puts [0, gets.split.map(&:to_i).max - n - (25 - n)].max


l,r,x,y,k=gets.split.map &:to_i
puts ([(l+k-1)/k,x].max>[r/k,y].min)?'NO':'YES'


class BearBalls
  def consecutive_elements?(array)
    array.find.with_index do |_, i|
      array[i] + 2 == array[i + 2]
    end
  end

  def run(balls)
    balls_array = balls.split.map(&:to_i).sort.uniq
    puts consecutive_elements?(balls_array) ? "YES" : "NO"
  end
end

size = gets.chomp
balls = gets.chomp
BearBalls.new.run(balls)


n=gets.to_i
while n!=1
	print "#{n} "
	for i in 2..n
		if n%i==0
			n/=i
			break
		end
	end
end
print "#{n}"
puts


n, m = gets.split.map(&:to_i)
ar1 = gets.split.map(&:to_i)
ar2 = gets.split.map(&:to_i)
puts (ar1 & ar2).join(" ")


require 'matrix'

a1, b1, c1 = gets.split.map { |v| Rational(v.to_i) }
a2, b2, c2 = gets.split.map { |v| Rational(v.to_i) }
a3, b3, c3 = [0, 0, 0].map { |v| Rational(v) }

rank_a = Matrix[ [a1, b1], [a2, b2] ].rank
rank_b = Matrix[ [a1, b1, c1], [a2, b2, c2], [a3, b3, c3] ].rank

result = 0

if rank_a == rank_b
  result = rank_a == 2 ? 1 : -1;
end

puts result


n=gets.chomp.to_i
a=Array.new(6,0)
b=Array.new(6,0)
integer=gets.chomp.split(" ")
integer.each do |integer|
    #puts "a=#{integer}"
    a[integer.to_i]+=1;
end
integer=gets.chomp.split(" ")
integer.each do |integer|
    #puts "b=#{integer}"
    b[integer.to_i]+=1;
end
atob=0
btoa=0
can=1
#for i in 1..5
#    puts "#{i} #{a[i]} #{b[i]}"
#end

for i in 1..5
    if a[i] > b[i]
        if (a[i]-b[i])%2!=0
            can=0
            break
        end
        atob+=(a[i]-b[i])/2;
    elsif a[i] < b[i]
        if (b[i]-a[i])%2!=0
            can=0
            break
        end
        btoa+=(b[i]-a[i])/2;
    end

    #感觉只要处理一种情况就可以！
end
if can==1
    puts atob
else
    puts -1
end


nmk = gets.chomp.split(" ").collect {|x| x.to_i}
ns = gets.chomp.split(" ").collect {|x| (x.to_i - 1)}
ns.sort!
sum = nmk[1]-nmk[2]
rez = 0
p = 0
while sum>0 and p<ns.length
 sum -= ns[ns.length-p-1]
 p +=1
end

if sum>0
 puts -1
 else
 puts p
 end


k = gets.to_i
a = gets.split.map(&:to_i)
0.upto(12) do |n|
    a.combination(n) do |b|
        if b.inject(0, &:+) >= k
            p n
            exit
        end
    end
end
p -1


def sorting(a,index)
    for i in 0...a.length
        for j in i+1...a.length
            if a[i]>a[j]
                a[i],a[j]=a[j],a[i]
                index[i],index[j]=index[j],index[i]
            end
        end
    end
end
n,k=gets.split().map{|i| Integer(i)}
a=gets.split().map{|i| Integer(i)}
index=Array.new
for i in 0...n
    index[i]=i+1
end
sorting(a,index)
count=0
list=Array.new
for i in a
    k-=i
    if k>=0
        count+=1
    end
end
puts count
out=Array.new
if count>0
    for i in 0...count
        out.push(index[i])
    end
end
out.sort!
print out*" "


gets
mas = gets.split(" ").map(&:to_i)
ans = 0
while mas.rindex(mas.max) != 0 do
  mas[mas.rindex(mas.max)] -= 1
  ans+=1
  mas[0]+=1
end

print ans


r, g, b = gets.split.map(&:to_i).sort

def f (r, g, b)
  min = [r,g,b].min
  return -100 if min < 0
  r-=min
  g-=min
  b-=min
  min + r / 3 + g / 3 + b / 3
end

puts [f(r, g, b), f(r-1, g-3, b-3)+2].max


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

x = (0..c/a).to_a.index{|w| ((c - (w * a)) % b).zero?}

puts "No" if x.nil?
puts "Yes" unless x.nil?


k, a, b, v = gets.split.collect{|i| i.to_i}
ans = 0
if a <= b/(k-1)*k*v
    puts (a+k*v-1)/(k*v)
    exit
else
    ans += b/(k-1)
    a -= ans*k*v
end
if a <= (b%(k-1)+1)*v
    puts ans+1
    exit
else
    ans += 1
    a -= (b%(k-1)+1)*v
end
puts ans+(a+v-1)/v


#!/usr/bin/ruby

while line = gets
	n, k = line.split.map(&:to_i)
	ans = [ n * 3 - k, 0 ].max
	puts ans
end


n=gets.to_i
for i in 1..n-1
	print i
	for j in 2..n-1
		print (i*j).to_s(n).rjust(3, ' ')
	end
	puts
end


module Memoizer
  def memoize(methodname)
    raise ArgumentError, "statefull method [#{methodname}]should not be memoized" if methodname.match(/\!\z/)
    unbound_method = instance_method(methodname)
    raise ArgumentError, "method [#{methodname}] with argument cannot be memoized" if unbound_method.arity > 0
    memoized_object_name = "@_memoized_#{methodname}"
    define_method(methodname) do
      if(instance_variable_get(memoized_object_name).nil?)
        instance_variable_set(memoized_object_name, unbound_method.bind(self).call)
      end
      instance_variable_get(memoized_object_name)
    end
  end
end

class Problem
  attr_reader(:e, :o)
  def initialize(e, o)
    @e = e
    @o = o
  end

  def ans
    return false if (e == 0 and o == 0)
    (e - o).abs <= 1
  end

  def out
    return "YES" if ans
    return "NO"
  end
end

e, o = gets.split(" ").map(&:to_i)
puts Problem.new(e, o).out


ab = gets.chomp.split.map(&:to_i)

n = 1
for i in (1..ab.min)
	n *= i
end

print n


#!/usr/bin/ruby
a,b=gets.split.map(&:to_i)
p Enumerator.new{|y|
	(1..1/0.0).each{|i|
		1.upto(i){|j|
			y<<('1'*j+'0'+'1'*(i-j)).to_i(2)
		}
	}
}.lazy.drop_while{|e|e<a}.take_while{|e|e<=b}.count


route = gets.chomp
visited = {[0, 0] => 1}
x, y = 0, 0
bug = false
value = 1

route.each_char do |direction|
	case direction
	when "R" then x += 1
	when "L" then x -= 1
	when "U" then y += 1
	when "D" then y -= 1
	end

	(bug = true and break) if visited[[x, y]] && visited[[x, y]] > 0

	value += 1
	(-1..1).each do |i|
		(-1..1).each do |j|
			next unless i ** 2 + j ** 2 == 1
			if visited[[x + i, y + j]] && visited[[x + i, y + j]] > 0
				bug = true if visited[[x + i, y + j]] != value - 1
			end
		end
	end
	visited[[x, y]] = value
end

if bug then
	puts "BUG"
else
	puts "OK"
end


a = gets.split(' ')
k = a[0].to_i
n = a[1].to_i
w = a[2].to_i
need = k*(1+w)*w/2 - n
if need < 0
  need = 0
end
puts need
=begin
string = "foobar"
puts "The string '#{string}' is nonempty." unless string.empty?

puts "foo bar     baz".split
a = [42, 8, 17]
puts '['+a.join(', ')+']'
b = []
(1..5).each do |i|
  b[i] = 2*i
end
puts b

c = %w[a b c]
puts '["'+c.join('", "')+'"]'

user = { :name => "Michael Hartl", :email => "michael@example.com" }
puts user[:name]
puts user[:password]

def pow(x, y)
  p = 1
  y.times{p *= x}
  return p
end
z = pow(3,4)
puts z
=end


def avg(x)
  x.inject(:+)/4.0
end

def med(x)
  (x[1] + x[2])/2.0
end

def ran(x)
  x[3] - x[0]
end

def cond(x)
  # [avg(x), med(x), ran(x)] == [ran(x)] * 3
  avg(x) == ran(x) and ran(x) == med(x)
end

n = gets.chomp!.to_i
x = []
n.times do
  x << gets.chomp.to_i
end
x.sort!

def four(x)
  if cond(x)
    puts "YES"
  else
    puts "NO"
  end
end

MAX_B = 2000
def tree(x)
  1.upto(MAX_B) do |i|
    tmp = x.clone
    tmp << i
    tmp.sort!
    break if (tmp[3] - tmp[0] > (tmp[1] + tmp[2])) and i > 2 * tmp[-1]      #WTF?
    if cond(tmp)
      puts "YES"
      puts i
      return
    end
  end
  puts "NO"
end

def two(x)
  tmp = x.clone
  if tmp[1] < 4 * tmp[0]
    puts "YES", [4 * tmp[0] - tmp[1], 3 * tmp[0]].minmax
    return
  end
  puts "NO"
end

def one(x)
  puts "YES"
  puts x[0], x[0]*3, x[0]*3
end

def zero
  puts "YES", [1, 1, 3, 3]
end

one(x) if n == 1
two(x) if n == 2
tree(x) if n == 3
four(x) if n == 4
zero if n == 0


def gcd (d1, d2)
  if d1 < d2
      tmp = d1
      d1 = d2
      d2 = tmp
  end
  rem = d1 % d2
  rem < Math::PI / 100 ? d2 : gcd(d2, rem)
end

points = []
ARGF.each_line do |line|
  points.push({
                  'x' => line.split[0].to_f,
                  'y' => line.split[1].to_f
              })
end

a = Math.sqrt((points[1]['x'] - points[0]['x']) ** 2 + (points[1]['y'] - points[0]['y']) ** 2)
b = Math.sqrt((points[2]['x'] - points[1]['x']) ** 2 + (points[2]['y'] - points[1]['y']) ** 2)
c = Math.sqrt((points[2]['x'] - points[0]['x']) ** 2 + (points[2]['y'] - points[0]['y']) ** 2)

R = a*b*c / Math.sqrt((a+b+c)*(c+b-a)*(a-b+c)*(a+b-c))

Rpower2 = R ** 2

def getangle(side)
  d = 1 - side ** 2 / (2 * Rpower2)
  d < -1 ? -1 : d > 1? 1 : d
end

angA = Math.acos(getangle(a))
angB = Math.acos(getangle(b))
angC = Math.acos(getangle(c))

gcd0 = gcd(2 * Math::PI, angA)
gcd1 = gcd(angB, gcd0)
gcd2 = gcd(angC, gcd1)

count = 2 * Math::PI / gcd2

S = count / 2 * Rpower2 * Math.sin(2 * Math::PI / count)

puts S


f, m, s = 3.times.map { gets.chomp }

labels = %w(F M S)
arr = [f, m, s]
u = arr.uniq

if u.size == 1 || u.size == 3
  puts "?"
else
  si = arr.index('scissors')
  ri = arr.index('rock')
  pi = arr.index('paper')

  res = arr.count{ |x| x == 'paper' } == 2 && si ? labels[si] : nil
  res = arr.count{ |x| x == 'rock' } == 2 && pi ? labels[pi] : nil unless res
  res = arr.count{ |x| x == 'scissors' } == 2 && ri ? labels[ri] : nil unless res

  puts res ? res : "?"
end


#!/usr/bin/ruby

require 'prime'

n = gets.to_i
if Prime.prime?(n) then
	puts 1
	puts n
else
	n -= 3
	if Prime.prime?(n) then
		puts 2
		puts("3 #{n}")
	else
		Prime.each(n) do |p|
			if Prime.prime?(n-p) then
				puts 3
				puts("3 #{p} #{n-p}")
				break
			end
		end
	end
end


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

def differ(x)
    string = x.to_s
    for i in 0...string.length
        x -= string[i].to_i
    end
    return x
end

l = 1
r = n
m = -1
while l <= r do
    m = (l + r) / 2
    if differ(m) < s
        l = m + 1
    else
        r = m - 1
    end
end
if differ(m) >= s
    amount = n - m + 1
else
    amount = n - m
end
puts amount


def lucky(i, b)
  i.to_s.gsub(/[^47]/, '').to_i == b
end

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

ret = 0
(a + 1).upto((10 ** 5) + b) do |i|
  if lucky(i, b)
    ret = i
    break
  end
end

puts ret


require 'set'

def readai
	gets.strip.split(/\s+/).map! { |eac| eac.to_i }
end

def readaf
	gets.strip.split(/\s+/).map! { |eac| eac.to_f }
end

def max a, b
	if a > b
		a
	else
		b
	end
end

n = readai

str = ((gets.strip.gsub /([\(\)])/, '#\1#').gsub /_+/, '#_#').split '#'

cnto, cnti, is_open = [0, 0, false]

str.each do |current|
	if current == '('
		is_open = true
	elsif current == ')'
		is_open = false
	elsif current != '_' and current != ''
		if is_open
			cnti += 1
		else
			cnto = max(cnto, current.length)
		end
	end
end

print "#{cnto} #{cnti}"


def divisors(n)
  divisors1 = []
  divisors2 = []

  max = (n**(0.5)).floor
  (2..max).each do |d|
    if n % d < 1
      d2 = n/d
      divisors1 << d
      divisors2 << d2 if d2 > d
    end
  end

  [*divisors1, *divisors2.reverse]
end

def solution
  gets
  s = gets.chomp.chars

  divs = divisors(s.size)

  divs.each do |d|
    a = s.shift d
    s = [*a.reverse, *s]
  end

  puts s.reverse.join
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']


p' :U^y¦ÊĉĒĿŚţźžƇƶǆǣȅȎȗȲɀɌɳɺɼʅ'[gets.to_i].ord


$n, q = gets.split.map(&:to_i)
a = q.times.map{gets.split}
$h = Hash.new{Array.new()}
a.each{|x| $h[x[1]] += [x[0]]}

def magic(s)
  return 1 if s.size == $n
  array = $h[s[0]]
  return 0 if array.size.zero?
  b = array.map do |x|
    str = x + s[1..-1]
    magic(str)
  end
  b.inject(:+)
end

p magic('a')


#!/usr/bin/ruby
n,m=gets.split.map(&:to_i)
r=0
x=0
gets.split.map(&:to_i).each{|e|
	if x<e
		r+=1
		x=m
	end
	x-=e
}
p r


w, h = gets().split.map(&:to_i)
u1, d1 = gets().split.map(&:to_i)
u2, d2 = gets().split.map(&:to_i)
i = h
while i > 0
  w += i
  if i == d1
    w = [0, w - u1].max
  end
  if i == d2
    w = [0, w - u2].max
  end
  i -= 1
end
puts w


a=["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"]
n=gets.chomp.to_i
r = 1
until r*5>n
    n -= r*5
    r *= 2
end
puts a[(n-1)/r]


r1, r2 = gets.split.map(&:to_i)
c1, c2 = gets.split.map(&:to_i)
d1, d2 = gets.split.map(&:to_i)

1.upto(9) do |a|
  b = r1 - a
  c = c1 - a
  d = d1 - a

  if [a,b,c,d].all?{|x|(1..9).include?(x)} && [a,b,c,d].uniq.size==4 && b+c == d2 && b+d == c2 && c+d == r2
    puts [a, b]*" "
    puts [c, d]*" "
    exit
  end
end
puts -1


s = gets.chomp
ret = ""
idx = 0
atend = false
while idx < s.length
	if idx != 0 && idx != s.length-3 && s.slice(idx,3) == "dot"
		ret += "."
		idx += 3
		next
	end
	if atend == false && idx != 0 && idx != s.length-2 && s.slice(idx,2) == "at"
		ret += "@"
		idx += 2
		atend = true
		next
	end
	ret += s[idx]
	idx += 1
end
puts ret


s=gets;a=%w(Danil Olya Slava Ann Nikita).select{|e|s.index e};puts a.size==1&&s.scan(a[0]).size==1?:YES: :NO


xs = STDIN.readline.split.map {|s| s.to_i }
sum = xs.inject(:+)
if sum != 0 and sum % xs.length == 0
	puts sum / xs.length
else
	puts -1
end


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 p(*arg); puts "DEBUG: " + arg.to_s if TEST_MODE; 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

# actual codes here

def diff(arr, l)
  (0..arr.size-2).collect do |i|
    arr[i+1] - arr[i]
  end + [l - arr[arr.size-1] + arr[0]]
end

def eval(a, b)
  n = a.size()
  for delta in 0..n-1
    return true if (0..n-1).all? {|i|
      a[i] == b[(i+delta)%n]
    }
  end
  return false
end

def solve(input, output)
  n, l = parse_int_array(input[0])
  a = diff(parse_int_array(input[1]), l)
  b = diff(parse_int_array(input[2]), l)
  p(a: a, b: b)
  output << (eval(a, b) ? "YES" : "NO")
end

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

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


#!/usr/bin/env ruby
MOD = 1000000007
m = gets.chomp
cnt = Array.new(15, 0)
def cal(remain, lucky, amount, cnt)
  if remain == 0
    cnt[lucky] += amount
    return
  end
  cal(remain - 1, lucky, amount * 8, cnt)
  cal(remain - 1, lucky + 1, amount * 2, cnt)
end
t = 0
for i in 0...m.size
  for j in 0...m[i].to_i
    is_lucky = j == 4 || j == 7 ? 1 : 0
    cal(m.size - i - 1, t + is_lucky, 1, cnt)
  end
  t += 1 if m[i] == '4' || m[i] == '7'
end
cnt[t] += 1
cnt[0] -= 1
def dfs(party_amount, lucky_amount, method_amount, cnt)
  return if lucky_amount > 9
  if party_amount == 6
    (lucky_amount + 1).upto(9) do |i|
      cnt[10] = (cnt[10] + method_amount * cnt[i]) % MOD
    end
  else
    for i in 0..9
      next unless cnt[i]
      cnt[i] -= 1
      dfs(party_amount + 1, lucky_amount + i, (method_amount * (cnt[i] + 1)) % MOD, cnt)
      cnt[i] += 1
    end
  end
end
dfs(0, 0, 1, cnt)
puts cnt[10] % MOD


n = gets.strip.to_i
coins = gets.strip.split(" ").map(&:to_i)
current_max_ones = 0
i = 0
current_flipped_ones = 0
number_of_ones = coins.count(1)
i0 = 0
number_of_ones_before = 0
number_of_ones_after = number_of_ones
while i < n do
  if coins[i] == 0 then
    if current_flipped_ones == 0 then
      i0 = i
      number_of_ones_before = coins[0..i0].count(1)
    end
    current_flipped_ones += 1
    current_max_ones = current_max_ones >= number_of_ones_before + current_flipped_ones + number_of_ones_after ?
        current_max_ones : number_of_ones_before + current_flipped_ones + number_of_ones_after
  else
    if current_flipped_ones == 0 then
      number_of_ones_before += 1
    end
      number_of_ones_after -= 1
      current_max_ones = current_max_ones >= number_of_ones_before + current_flipped_ones + number_of_ones_after ?
        current_max_ones : number_of_ones_before + current_flipped_ones + number_of_ones_after
      if current_flipped_ones == i - i0 + 1 - current_flipped_ones then
        current_flipped_ones = 0
      end
  end
  i += 1
end
if coins.count(1) == coins.count then
  current_max_ones -= 1
end
puts current_max_ones


#!/usr/bin/ruby

x, y, small_r, big_r = STDIN.readline.split.map {|s| s.to_i }
a, b = [x, y, big_r], [x, y, small_r]
x, y, small_r, big_r = STDIN.readline.split.map {|s| s.to_i }
c, d = [x, y, big_r], [x, y, small_r]

def intersects(a, b)
	x0, y0, r0 = a
	x1, y1, r1 = b
	return false if includes(a, b) or includes(b, a)
	dd = (x1-x0)**2 + (y1-y0)**2
	dd < (r0 + r1)**2
end

def includes(a, b)
	x0, y0, r0 = a
	x1, y1, r1 = b
	return false if r1 >= r0
	dd = (x1-x0)**2 + (y1-y0)**2
	dd <= (r1 - r0)**2
end

count = 0
[ [a, c, d], [b, c, d], [c, a, b], [d, a, b] ].each do |x, a, b|
	next if intersects(x, a) or intersects(x, b)
	next if includes(a, x) and includes(x, b)
	if includes(a, x)
		next if includes(x, b)
		next if not includes(b, x)
	end
	count += 1
end
puts count


# cook your code here

n,k = gets.chomp.split

n = n.to_i
k = k.to_i
# ex = 1
a = gets.chomp.split

for i in 0...n
    a[i] = a[i].to_i
end

puts a.count{ |x| x>=a[k-1] and x>0 }


a=gets.chomp.to_i
b=gets.chomp
if a==1
puts "YES"
puts "#{b}"
else
bp=[]
temp=[b[0]]
1.upto(b.length-1) do |i|
if temp.count(b[i])==0
temp=temp+[b[i]]
bp=bp+[i]
end
break if bp.length==a-1
end
if bp.length<(a-1)
puts "NO"
else
puts "YES"
puts "#{b[0..bp[0]-1]}"
if bp.length>1
0.upto(a-3) do|i|
puts "#{b[bp[i]..bp[i+1]-1]}"
end
end
puts "#{b[bp[a-2]..(b.length-1)]}"
end
end


n = gets.to_i
a = gets.split.map(&:to_i)
sum = a.inject(:+)
if a[0]*2 > sum
    puts 1,1
else
    ans = [1]
    s = a[0]
    (1...n).each do |i|
        if a[i]*2 <= a[0]
            ans << i+1
            s += a[i]
        end
    end
    if s*2 > sum
        puts ans.size,ans.join(" ")
    else
        puts 0
    end
end


#!/usr/bin/ruby
# coding: utf-8
require 'rational'

a, x, y = $stdin.gets.split(/\s+/).map(&:to_i)
h = a.to_r / 2

if y % a == 0
  puts -1
elsif y < a
  if -h < x and x < h
    puts 1
  else
    puts -1
  end
else
  n = 2
  y1 = 2*a
  loop do
    if y < y1
      if -h < x and x < h
        puts n
      else
        puts -1
      end
      break
    end
    y1 += a
    if y < y1
      if -a < x and x < 0
        puts n+1
      elsif 0 < x and x < a
        puts n+2
      else
        puts -1
      end
      break
    end
    y1 += a
    n += 3
  end
end


$boyhs={0=>0,1=>0,2=>0}
j=0;
for i in 3..100
	if i%2!=0
		j+=1
	end
	$boyhs[i]=j
end
def main()
	gf=gets.chomp.split(" ")
	gf=gf.map{|i| i.to_i}
	gl=gf[0]
	gr=gf[1]
	bf=gets.chomp.split(" ")
	bf=bf.map{|i| i.to_i}
	bl=bf[0]
	br=bf[1]
	if checkcomfort(gl,br) || checkcomfort(gr,bl)
		puts "YES"
	else
		puts "NO"
	end
end
def checkcomfort(g,b)
	if b>=g-1 && g>=$boyhs[b]
		return true;
	end
	return false;
end
main()


a, b = gets.chomp.split.map(&:to_i)
i =0
while(true) do
  a = a*3
  b = b*2
  i = i+1
  if(a>b) then
    break
  end
end
print(i,"\n")


s = gets.strip.split
a = s[0].split(//)
k = s[1].to_i
aa = []
while k > 0 && a.size > 0
	m = k < a.size ? a[0..k].max : a[0..a.size-1].max
	mp = a.index(m)
	k -= mp if mp != 0
	aa << a[mp]
	a.delete_at(mp)
end
aa << a
puts aa.join


princess_speed = gets.to_f
dragon_speed   = gets.to_f
delay_time     = gets.to_f
tresuary_time  = gets.to_f
distance       = gets.to_f

number_of_bijous = 0

initial_princess_travelled_distance = princess_speed * delay_time
princess_travelled_distance = initial_princess_travelled_distance
dragon_travelled_distance   = 0

if princess_speed >= dragon_speed
    puts 0
    exit
else
    first_time_dragon_catch_princess = initial_princess_travelled_distance / (dragon_speed - princess_speed)

    dragon_travelled_distance = first_time_dragon_catch_princess * dragon_speed
    princess_travelled_distance = dragon_travelled_distance

    while princess_travelled_distance < distance
        number_of_bijous += 1
        extra_distance = (2 * dragon_travelled_distance / dragon_speed + tresuary_time) * princess_speed
        time_to_catch = extra_distance / (dragon_speed - princess_speed)
        princess_travelled_distance += extra_distance + time_to_catch * princess_speed
        dragon_travelled_distance = princess_travelled_distance
    end

    puts number_of_bijous
    exit
end


n, x, y = gets.chomp.split(" ").map{|e| e.to_f}

a = (n * (y / 100.0)).ceil

ans = (a - x).to_i
if ans < 0
  puts 0
else
  puts ans
end


def read_next_line
  gets.split.map { |x| x.to_i }
end

n = gets.to_i
c = read_next_line
x, y = read_next_line
s1 = 0
s2 = c.inject(:+)
for i in 0...n
  if s1 >= x && s1 <= y && s2 >= x && s2 <= y
    puts i + 1
    exit
  elsif s1 >= y
    break
  end
  s1 += c[i]
  s2 -= c[i]
end
puts 0


cw_pos = %w{v < ^ >}
ccw_pos = %w{v > ^ <}
start, fin = gets.strip.split
start_pos_cw = cw_pos.index start
start_pos_ccw = ccw_pos.index start
n = gets.strip.to_i
n %= 4
cw = cw_pos[start_pos_cw + (n - 4)] == fin
ccw = ccw_pos[start_pos_ccw + (n - 4)] == fin
if cw && !ccw
    puts "cw"
elsif ccw && !cw
    puts "ccw"
else
    puts "undefined"
end


include Math
require "prime"
require "bigdecimal"
require "bigdecimal/math"
require "matrix"
require "pp"
require "benchmark"

Infinity = 1/0.0
class Matrix;def inspect;empty? ? "Matrix.empty(#{row_size}, #{column_size})":"Matrix[\n#{@rows.map(&:inspect).join("\n")}\n]";end;end
def pbin(obj);case obj;when Integer;puts obj.to_s(2);end;end
class String;def to_a;split("");end;end
class String;def to_ia;split.map(&:to_i);end;end
def getia;gets.to_ia;end
def geti;gets.to_i;end
class Object;def dcopy;Marshal.load(Marshal.dump(self));end;end

def chk(x,y,h,b)
    yy=y.to_a
    xx=x.to_a
    xx.each{|c|b-=1 if yy.include?(c)}
    b+=h
    xx.zip(yy){|s,t|h-=1 if s==t}
    return true if h.zero? && b.zero?
    return false
end

n=geti
a=[]
n.times{
    i=gets.split
    i[1]=i[1].to_i
    i[2]=i[2].to_i
    a<<i
}
arr=[]
ok=[]
[0,1,2,3,4,5,6,7,8,9].permutation(4){|q|arr<<q.join}
arr=arr.find_all{|x|
    a.all?{|y,h,b|
        chk(x,y,h,b)
    }
}
k=arr.size
if k==0
    puts"Incorrect data"
elsif k==1
    puts arr[0]
else
    puts"Need more data"
end


N, K, M, D = gets.split.map(&:to_i)
ans = 0
(1..D).each do |m|
    x = [M, N/((m-1)*K+1)].min
    ans = [ans, x*m].max
end
puts ans


n = gets.chomp.to_i
d = gets.chomp.split.map(&:to_i)
ans1 = d.sort[d.size-1]
b = d.select{|x| ans1 % x == 0}.uniq!
b.each{|y| d.delete_at(d.index(y))}
ans2 = d.sort[d.size-1]
puts "#{ans1} #{ans2}"


arr = readline.split(' ').collect(&:to_i)
n = arr[0]
arr = arr[1..-1]
a = [arr[0] + arr[1], arr[0] + arr[2], arr[1] + arr[3], arr[2] + arr[3]]
d = a.max - a.min
c = [0, n - d].max
puts c * n


def dot(x0, y0, x1, y1, x2, y2)
	(x1 - x0) * (x2 - x0) + (y1 - y0) * (y2 - y0)
end

def right(x0, y0, x1, y1, x2, y2)
	[x0, y0] != [x1, y1] and [x0, y0] != [x2, y2] and [x1, y1] != [x2, y2] and
		dot(x0, y0, x1, y1, x2, y2) == 0 ||
		dot(x1, y1, x0, y0, x2, y2) == 0 ||
		dot(x2, y2, x0, y0, x1, y1) == 0
end

def gao(a)
	return "RIGHT" if right(*a)
	a.each_index do |i|
		a[i] += 1
		return "ALMOST" if right(*a)
		a[i] -= 2
		return "ALMOST" if right(*a)
		a[i] += 1
	end
	"NEITHER"
end

puts gao gets.split.map &:to_i


arr = gets.split.map &:to_i
$n, x0, y0, dx, dy, t = arr

def mod(a)
  (a - 1) % $n + 1
end

dx, dy = mod(dx), mod(dy)

def zmul(a, b)
  ans = 0
  6.times do |i|
    ans += mod(a[i] * b[i])
    ans -= $n if ans > $n
  end
  ans
end

class Matrix
  def initialize(n)
    @mat = Array.new(n) do |i|
      Array.new(n) { |j| i == j ? 1 : 0 }
    end
  end

  def [](index)
    @mat[index]
  end

  def []=(index, val)
    @mat[index] = val
  end

  def mul(rhs)
    ans = Matrix.new(6)
    6.times do |i|
      6.times do |j|
        ans[i][j] = 0
        6.times do |k|
          ans[i][j] += mod(@mat[i][k] * rhs[k][j])
          ans[i][j] -= $n if ans[i][j] > $n
        end
      end
    end
    ans
  end

  def pow(e)
    ans = Matrix.new(6)
    tmp = Matrix.new(6)
    6.times { |i| tmp[i] = Array.new(6) { |j| @mat[i][j] } }
    while e > 0
      ans = ans.mul(tmp) if (e & 1) == 1
      tmp = tmp.mul(tmp) if (e >>= 1) > 0
    end
    ans
  end
end

mat = Matrix.new(6)
mat[0] = [2, 1, 1, 0, 1, 0]
mat[1] = [1, 2, 0, 1, 1, 0]
mat[2] = [1, 1, 1, 0, 1, 0]
mat[3] = [1, 1, 0, 1, 1, 0]
mat[4] = [0, 0, 0, 0, 1, 1]
mat[5] = [0, 0, 0, 0, 0, 1]

mat = mat.pow(t)

arr.shift
arr[-1] = 0
arr << 1
puts "#{zmul(mat[0], arr)} #{zmul(mat[1], arr)}"


k,r = [],0
def rec(kk, l, s)
  kk<<s if (l>0)
  rec kk, l+1, s*10+4 if (l<10)
  rec kk, l+1, s*10+7 if (l<10)
end
rec(k, 0,0)
k.sort!
a,b = gets.split.collect{|x| x.to_i }
0.upto(k.length) do |i|
    if a<=b && a<=k[i]
        n=[b,k[i]].min-a+1
        r+= n*k[i]
        a=k[i]+1
    end
end
puts r


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

if t <= k
  puts t
elsif t < n
  puts k
else
  puts k - (t-n)
end


#!/usr/bin/env ruby

def cb(n, m)
    return 0 if n < m || m == 0
    ((n-m+1)..n).inject(&:*) / (1..m).inject(&:*)
end

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

ans = 0
(4..n).each do |i|
    j = t - i
    break if j == 0
    next if j > m
    ans += cb(n,i)*cb(m,j)
end
p ans


n = gets.to_i
x = Regexp.new gets.chomp
puts [ "vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon" ].find { |i|
  i.size == n && i =~ x
}


#!/usr/bin/ruby

str = gets.chomp

max_size = 0
1.upto(str.size) {|len|
  0.upto(str.size - len - 1) {|first|
    (first + 1).upto(str.size - len) {|second|
#      p "#{str[first, len]} #{str[second, len]}"
      max_size = len if str[first, len] == str[second, len]
    }
  }
}

puts max_size


i=0
a=[]
gets.split.each do |s|
  if a.include?(s)
    i += 1
  else
    a << s
  end
end
puts i


n = gets.to_i
start = [0, n - 100].max
res = (start..n).to_a.map do |x|
  x + (x.to_s.split('').map(&:to_i).inject(:+)) == n ? x : nil
end.reject(&:nil?)
puts res.size
res.each { |x| puts x }


def IsVowel(c)
  "aeiouy".include?(c)
end

def HasConsVowels(s)
  s.each_cons(2).to_a.map{|a, b| IsVowel(a)&&IsVowel(b)}.include?(true)
end
gets
s = gets.chomp.chars
until !HasConsVowels(s) do
s.each_index do |i|
  next if i == 0
  s.delete_at(i) if IsVowel(s[i]) && IsVowel(s[i-1])
end
end
puts s.join


n,pos,l,r = gets.split.map(&:to_i)
if r <= pos
  a = l==1 ? -r : -l+1
  b = r==n ? 0 : 1
  ans = pos + a + b
elsif l >= pos
  a = r==n ? l : r+1
  b = l==1 ? 0 : 1
  ans = -pos + a + b
else
  a = l==1 ? 0 : pos-l+1
  b = r==n ? 0 : r-pos+1
  c = (a==0 || b==0) ? 0 : [pos-l,r-pos].min
  ans = a + b + c
end
puts ans


tmp = $stdin.gets.chomp.split(' ')
n = tmp[0].to_i
m = tmp[1].to_i

nn=[]
mm=[]
nc=0
mc=0

while n%2==0
  nc+=1
  n/=2
end

nn.push(nc)
nc=0
while n%3==0
  nc+=1
  n/=3
end
nn.push(nc)

#puts "-- #{n} "

while m%2==0
  mc+=1
  m/=2
end

mm.push(mc)
mc=0
while m%3==0
  mc+=1
  m/=3
end
#puts "-- #{m} "
mm.push(mc)

#puts nn,mm

a1 = (mm[0]-nn[0])
a2 = (mm[1]-nn[1])
if a1<0 || a2<0 || n!=m
  puts "-1"
else
  puts a1+a2
end


n = gets.split(" ").map(&:to_i)
sum = 0
n.each { |a| sum+=a }
tag = false
for i in 0..3
	for j in (i+1)..4
		for k in (j+1)..5
			if 2*(n[j] + n[i] +n[k]) == sum
				tag = true
				break
			end
		end
	end
end

if tag
	print('YES')
else
	print('NO')
end


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

l,r = scan

puts l != r ? 2 : l


def count0(x)
	ans, mul = 0, 5
	ans, mul = ans + x / mul, mul * 5 while mul <= x
	ans
end

n = gets.strip.to_i
beg = 0
beg += 1 while count0(beg) < n
ans = []
while count0(beg) == n
	ans.push(beg)
	beg += 1
end
puts ans.length
puts ans.map(&:to_s).join(' ')


def calc(digits, base)
  digits.reverse.map.with_index do |d, idx|
    d * (base**idx)
  end.inject(0, :+)
end

_, base = gets.chomp.split.map(&:to_i)
a = calc(gets.chomp.split.map(&:to_i), base)

_, base = gets.chomp.split.map(&:to_i)
b = calc(gets.chomp.split.map(&:to_i), base)

ans = "".tap do |out|
  case
  when a == b
    out << "="
  when a > b
    out << ">"
  else
    out << "<"
  end
end
puts ans


n=gets.to_i
x=gets.chomp.split.map(&:to_i)
a,b=0,0
for i in 0..n-1
	a,b=0,0
	for j in i+2..n-1
		if x[j]>x[i] && x[j]>x[i+1] || x[j]<x[i] && x[j]<x[i+1]
			a+=1
		else
			b+=1
		end
	end
	if a!=0 && b!=0
		break
	end
end
if a!=0 and b!=0
	puts "yes"
else
	puts "no"
end


#!ruby -parprime
p=Prime
eval'$_=p.each(%d).reject{|i|!p.each(i).each_cons(2).any?{|q,r|i==q+r+1}}.size>=%d?"YES": :NO'%$F


n, c = gets.split(" ").map(&:to_i)
p = gets.split(" ").map(&:to_i)
t = gets.split(" ").map(&:to_i)

p1 = 0
t1 = 0
n.times do |i|
    t1 += t[i]
    p1 += [p[i] - c*t1, 0].max
end

p2 = 0
t2 = 0
n.times do |i|
    t2 += t[n-i-1]
    p2 += [p[n-i-1] - c*t2,0].max
end

if p1 > p2
    puts "Limak"
elsif p2 > p1
    puts "Radewoosh"
else
    puts "Tie"
end


a,b,c = gets.split.map(&:to_i)
if (a-b+c)*(a-b-c) <= 0 && c != 0
    puts "?"
elsif a-b > 0
    puts "+"
elsif a-b < 0
    puts "-"
else
    puts "0"
end


a, b = STDIN.readline.split.collect {|s| s.to_i }
if b > a
  puts 0
elsif b == a
  puts 'infinity'
else
  c = a-b
  count = 0
  x = 1
  while x*x <= c
    if c%x == 0
      y = c/x
      if y > b
        count += 1
      end
      if x != y and x > b
        count += 1
      end
    end
    x += 1
  end
  puts count
end


s = gets.chomp.split.sort
ans = 2
if s[0] == s[1]
    if s[1] == s[2]
        ans = 0
    else
        ans = 1
    end
elsif s[1] == s[2]
    ans = 1
else
    a = Hash.new
    a["s"] = 0
    a["p"] = 1
    a["m"] = 2
    b = Array.new(3).map{Array.new(10,0)}
    3.times do |i|
        b[a[s[i][1]]][s[i][0].to_i] += 1
    end
    3.times do |i|
        c = 1
        (2..9).each do |j|
            if b[i][j] == 1 && b[i][j-1] == 1
                c += 1
                ans = [ans,3-c].min
            else
                c = 1
            end
        end
        (2..8).each do |j|
            if b[i][j-1] == 1 && b[i][j+1] == 1
                ans = [ans,1].min
            end
        end
    end
end
puts ans


x, s = gets.split.map &:to_i

if x > s || x[0] != s[0]
	puts -1
	exit
end

BIT = 64
ans = Array.new(BIT, 0)
(0...BIT).select{|i| x[i] == 1}.each{|i| ans[i] += 1}
(0...BIT).select{|i| (s - x)[i] == 1}.each{|i| ans[i-1] += 2}

a = Array.new(ans.max, 0)
a.each_index do |i|
	(0...BIT).select{|j| ans[j] > i}.each{|j| a[i] += 1 << j}
end
puts a.size, a.sort.join(' ')


n,a,x,b,y = gets.split.map(&:to_i)
f = false
while a != x && b != y
    a += 1
    a = 1 if a > n
    b -= 1
    b = n if b <= 0
    if a == b
        f = true
        break
    end
end
puts (f ? "YES" : "NO")


n = gets.chomp.to_i
container = gets.chomp.split().map { |x| x.to_i }

if container.count(0) == n
  puts "NO"
else
  numDifZero = [0]
  for i in 0 ... n
    if container[i] != 0
      numDifZero.push(i+1)
    end
  end
  if numDifZero[-1] != n
    numDifZero[-1] = n
  end
  puts "YES"
  puts (numDifZero.length-1)
  for i in 1 ... numDifZero.length
    print (numDifZero[i-1]+1)," ",numDifZero[i],"\n"
  end

end


n = gets.to_i * 2
arr = Array.new(10){0}
4.times do
  str = gets
  str.size.times do |i|
    arr[str[i].to_i] += 1 if str[i] != '.'
  end
end
isYes = true
1.upto(arr.size) do |i|
  if arr[i].to_i > n
    isYes = false
    break
  end
end
(isYes == true) ? printf('YES') : printf('NO')


a,b,c=gets.split.map &:to_i
s=[(a+b)*2,a+b+c,(a+c)*2,(b+c)*2]
p s.min


l = [gets.to_i, gets.to_i, gets.to_i, gets.to_i]
puts (1..gets.to_i).to_a.select{ |x| l.any?{ |y| x >= y and x % y == 0 } }.size


BEGIN{
	def get_line_int()
		return gets.split.map(&:to_i)
	end
	def getA(n, m)
		cc = 0
		n -= 1
		if n % 2 == 0 then
			cc += n
		else
			cc += n - 1
		end
		cc += m - n - 1
	end
	def getB(n, m)
		cc = 0
		m -= 1
		if n % 2 == 0 then
			cc += n
		else
			cc += n - 1
		end
		cc += m - n - 1
		cc += 1
	end
	def main()
		n, m = get_line_int
		n, m = m, n if n > m
		ans1 = getA(n, m)
		ans2 = getB(n, m)
		ans = ans1 > ans2 ? ans1 : ans2
		print ans, " ", n + m - 1 - ans
		puts
	end
	Test_case = 1
	Test_case.times do
		main()
	end
}


n, cnt = gets.to_i, Hash.new(0)
n.times {cnt[gets.chomp] += 1}
if cnt.each_value.inject(true) {|r, v| r &&= v * 2 == n}
  puts :YES
  cnt.each_key {|k| print k, ' '}
else
  puts :NO
end


n = gets.chomp.to_i
s = gets.chomp
ans = s.chars.chunk { |chr| chr == 'B' }.select(&:first).map { |chunk| chunk.last.length }
puts ans.length
puts ans.join(" ")


gets
s,ans=[],0
gets.split.map(&:to_i).each do |i|
  while s[-2]&&(k=[s[-2],i].min)>=s[-1]
    ans+=k
    s.pop
  end
  s.push i
end
s.sort!
(0..s.size-3).each{|i| ans+=s[i]}
p ans


board = Hash.new
res = 0
for i in 0...8
	board[i] = gets.split(//)
	unless board[i].include?("W")
		res += 1
	end
end
if res == 8
	puts "8"
else
	for i in 0...8
		increase = true
		for j in 0...8
			if board[j][i] == "W"
				increase = false
			end
		end
		if increase
			res += 1
		end
	end
	puts res.to_s
end


#!/usr/bin/env ruby

s, t, p = gets.strip, gets.strip, 0
t.each_char { |i| p = p + 1 if s[p] == i }
puts p + 1


n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
v = []
(0...(2E5+11).to_i).each do |i|
  v << []
end
(0...n).each do |i|
  cur = a[i]
  res = 0
  while cur > 0
    v[cur] << res
    res += 1
    cur /= 2
  end
end
res = 1E9.to_i
(0..2E5.to_i).each do |i|
  v[i].sort!
  next if v[i].length < k
  sum = 0
  (0...k).each do |j|
    sum += v[i][j]
  end
  res = [res, sum].min
end
puts res


n = gets.to_i
a = gets.split.map(&:to_i).map{|x|x % 2}
if a[0] == 0 || a[-1] == 0
    puts "No"
else
    b = []
    tmp = []
    n.times do |i|
        tmp.push(a[i])
        if i < n - 1 && a[i] == 1 && a[i + 1] == 1 && tmp.size % 2 == 1
            b.push(tmp)
            tmp = []
        end
    end
    cnt = b.size
    if tmp.size % 2 == 0
        if cnt == 0
            puts "No"
            exit
        end
    else
        cnt += 1
    end
    puts cnt % 2 == 1 ? "Yes" : "No"
end


ax,ay,bx,by,cx,cy=gets.split.map(&:to_i)
ans = true
if ax == bx
    if ax == cx
        ans = false
    end
else
    if (cy - ay) * (ax - bx) == (ay - by) * (cx - ax)
        ans = false
    end
end

if ans
    puts (ax - bx) ** 2 + (ay - by) ** 2 == (bx - cx) ** 2 + (by - cy) ** 2 ? "Yes" : "No"
else
    puts "No"
end


n, v = gets.strip.split(' ').map(&:to_i)
c = (1..n).to_a
tank = 0
cost = 0

c.each_with_index do |_, idx|
  tank -= 1 unless idx.zero?
  togo = n - idx - 1
  if togo > tank
    leftintank = v - tank
    tofill = [leftintank, togo].min
    cost += (1 + idx) * tofill
    tank += tofill
  end
end
puts cost


input = gets.chomp.to_i
if input % 2 == 0 && input != 2
    puts "YES"
else
    puts "NO"
end


n, m = gets.chomp.split(' ').map { |x| x.to_i }

buttons = gets.chomp.split(' ').map { |x| x.to_i }

n.times do |i|

	buttons.each do |button|

		if button <= i+1
			print button," "
			break
		end
	end
end

puts


def step(a,op)
	a.permutation.map{|v| ( ( [ (op=="+") ? v[0]+v[1] : v[0]*v[1] ] ) + ( (v.drop(2)) ? v.drop(2) : [] ) ).sort }.uniq
end

a=gets.split.map{|v| v.to_i}
oper=gets.split
res=[]
step(a,oper[0]).each do |v|
  step(v,oper[1]).each do |t|
	res+=step(t,oper[2])
  end
end
puts res.min


debug = 0
if debug==1 then f=File.open "c1.txt"
else f = $stdin
end

week = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

day0, day1 = f.read.chomp.split "\n"
id0 = week.find_index day0
id1 = week.find_index day1
good = FALSE
12.times do |i|
	#month i starts with day 0, does month i+1 start with day 1?
	(good = TRUE) and break if (id0 + month[i])%7==id1
#	if (id0 + month[i])%7==id1 then
#		good = TRUE
#		break
#	end
end
$stdout.puts (if good then "YES" else "NO" end)


#!/usr/bin/ruby
s=gets.chomp
k=gets.to_i
l=s.size
m=l+k
m=m-m%2
if k>=l
	p m
else
	ma=0
	l.times{|i|
		1.step(l-i){|j|
			if 2*j>ma && i.step(i+j-1).all?{|o|(o+j>=l&&o+j<l+k)||s[o]==s[o+j]}
				ma=2*j
			end
		}
	}
	p ma
end


t = gets.chomp.to_i
s = gets.chomp

puts s.count('L') + s.count('R') + 1


#!/usr/bin/env ruby
T='CODEFORCES'
S=gets.chomp
0.step(S.size){|i|
	i.step(S.size){|j|
		if S[0,i]+S[j..-1]==T
			puts :YES
			exit
		end
	}
}
puts :NO


a=gets.to_i
b=gets.to_i
c=a+b
a=a.to_s.split("")
b=b.to_s.split("")
c=c.to_s.split("")
a.delete("0")
b.delete("0")
c.delete("0")
a=a.join.to_i
b=b.join.to_i
c=c.join.to_i
if a+b==c
puts "YES"
else
puts "NO"
end


def solve(a)
    n = a.size
    sum = 0
    res = 360
    n.times do |i|
        sum += a[i]
        res = [res, (360 - 2 * sum).abs].min
    end
    return res
end

n = gets.to_i
a = gets.split.map(&:to_i)
ans = 360
n.times do |i|
    ans = [ans, solve(a)].min
    a.push(a.shift)
end
puts ans


gets.to_i.times { a=gets+gets;puts a.include?('1') ? (!a.include?('0') ? 2 : 1) : 0}


def sum(x)

    return x[0] + x[1] + x[2]

end

i = (sum(gets.split.map(&:to_i)) + 4) / 5

j = (sum(gets.split.map(&:to_i)) + 9) / 10

n = gets.to_i

if (i + j <= n)
    puts "YES"
else
    puts "NO"
end


n = gets.to_i
a = gets.split.map(&:to_i)
c = [0, 0, 0]
n.times{|i| c[i % 3] += a[i]}
if c[0] == c.max
  puts "chest"
elsif c[1] == c.max
  puts "biceps"
else
  puts "back"
end


gets
ar = gets.chomp!.split ' '

part = 0
ok = true
lst = -1
ar.each do |ai|
	ai = ai.to_i
	if part == 0
		if lst == ai
			part = 1
		elsif lst > ai
			part = 2
		end
	elsif part == 1
		if lst > ai
			part = 2
		elsif lst < ai
			ok = false
		end
	else
		if lst <= ai
			ok = false
		end
	end
	lst = ai
end

puts(if ok; "YES"; else; "NO"; end)


n = gets.chomp
n = n.split
rows = n[0].to_i
columns = n[1].to_i

c = []
for i in (1..rows)
	c[i] = gets.chomp
end

colors = []
count = 0
for i in (1..rows)
	colors << c[i].split
end

for i in (0..colors.size-1)
	for x in (0..columns-1)
		if colors[i][x] == "C" || colors[i][x] == "M" || colors[i][x] == "Y"
			count += 1
			break
		end
	end
end

if count >= 1
	print "#Color"
else
	print "#Black&White"
end


#!/usr/bin/env ruby

m, s = $stdin.gets.split.map { |d| d.to_i }

# Special case of sum zero
if s == 0
  if m == 1
    puts "0 0"
  else
    puts "-1 -1"
  end
  exit 0
end

def increment(a)
  i = a.size - 1
  while i >= 0
    if a[i] != 9
      a[i] += 1
      return true
    end
    i -= 1
  end
  return false
end

def decrement(a)
  i = a.size - 1
  while i >= 0
    if a[i] != 0
      a[i] -= 1
      return true
    end
    i -= 1
  end
  return false
end

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

def print_a(a)
  a.map{|d| d.to_i} * ""
end

smallest = [0] * m
smallest[0] = 1
while sum(smallest) < s and increment(smallest); end

largest = [9] * m
while sum(largest) > s and decrement(largest); end

if sum(smallest) == s and sum(largest) == s
  puts "#{print_a(smallest)} #{print_a(largest)}"
else
  puts "-1 -1"
end


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

starter = (b>a ? 1 : 0)
if starter == 1
  str = "1"
  x.times do |i|
    str << (i%2).to_s
  end

  r0 = [a - str.count("0"), 0].max
  r1 = [b - str.count("1"), 0].max

  if str[-1] == "0"
    r0.times do |i|
      str << "0"
    end
  else
    str = str[0...-1]
    r0.times do |i|
      str << "0"
    end
    str << "1"
  end

  str = ("1"*r1) + str
  puts str
else
  str = "0"
  x.times do |i|
    str << ((i+1)%2).to_s
  end

  r0 = [a - str.count("0"), 0].max
  r1 = [b - str.count("1"), 0].max

  if str[-1] == "1"
    r1.times do |i|
      str << "1"
    end
  else
    str = str[0...-1]
    r1.times do |i|
      str << "1"
    end
    str << "0"
  end

  str = ("0"*r0) + str
  puts str
end


T='fedabc'
s=gets.chomp
x=T.index(s[-1])+1
s=s.to_i-1
d,r=s.divmod(4)
if r%2==1
	x+=7
end
p x+d*16


n=gets.to_i
4.times do |v|
  a = gets.split.map(&:to_i)
  2.times do |i|
    2.times do |j|
      if a[i]+a[2+j] <=n
        puts "#{v+1} #{a[i]} #{n-a[i]}"
        exit
      end
    end
  end
end
p -1


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

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

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

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

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

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

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

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

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

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

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

n = inp[0]
n.times do
  n, d, k = inp
  onf = na(d+1)
  t = inp
  min = 9999999
  now = 0
  t.size.times do |i|
    if(i-k >= 0)
      min = [now,min].min
      onf[t[i-k]] -= 1
      if(onf[t[i-k]] == 0)
        now -= 1
      end
    end
    if(onf[t[i]] == 0)
      now += 1
    end
    onf[t[i]] += 1
  end
  min = [now,min].min
  p min
end