n = gets.to_i

arr = gets.split.map{|x| x.to_i}

min = max = f = s = 0

1.upto(n) do |i|
	f, s = arr[-i] + min, max
	f, s = s, f if arr[-i] + min < max

	max, min = f, s
end

print s, " ", f


require 'date'
a, b = 2.times.map{gets.split('.').map(&:to_i).reverse}
a[0] += 2000
puts b.permutation.map{|c|
	c[0] += 2000
	begin
		Date.new(*a) >= Date.new(*c).next_year(18)
	rescue ArgumentError
		nil
	end
}.any? ? :YES : :NO


l,r = gets.split(" ").map(&:to_i)
answer = -1
l.upto(r) {|i|
    j = i.to_s.split("")
    if (j.count - j.uniq.count) == 0
        answer = i
        break
    end
}
puts answer


def solve(v,k)
        k = k.to_f
        res = 0
        i = 0
        while v / (k**i) >= 1.0
                res += (v/(k**i)).to_i
                i += 1
        end
        return res
end

n,k = gets.split.map(&:to_i)
start = n * (k - 1) / k
for v in (start - 10000)..(start + 10000)
        if solve(v,k) >= n
                puts v
                exit
        end
end


def dist(x1,y1,x2,y2)
  x1-=x2
  y1-=y2
  x1=x1>0?x1:-x1
  y1=y1>0?y1:-y1
  return x1+y1
end

posx=[]
posy=[]
delta=[]
sm=[]
args=gets.split.collect{|s|s.to_i}
x0,y0,ax,ay,bx,by=args[0],args[1],args[2],args[3],args[4],args[5]
args=gets.split.collect{|s|s.to_i}
xs,ys,t=args[0],args[1],args[2]
posx.push(x0)
posy.push(y0)
delta.push(0)
sm.push(0)
while delta[-1]<=t+xs+ys
  x0,y0=ax*posx[-1]+bx,ay*posy[-1]+by
  delta.push(dist(x0,y0,posx[-1],posy[-1]))
  sm.push(delta[-1]+sm[-1])
  posx.push(x0)
  posy.push(y0)
end

ma=0
l=posx.length
for i in 0..l-1
  king=dist(xs,ys,posx[i],posy[i])
  for j in 0..i
    miles=(sm[i]-sm[j])+king
    cnt=i-j+1
    if miles<=t&&cnt>ma
      ma=cnt
    end
    miles+=(sm[i]-sm[j])
    for k in i+1..l-1
      miles+=delta[k]
      if miles<=t
        cnt+=1
        if(cnt>ma)
          ma=cnt
        end
      else
        break
      end
    end
  end
end
puts ma


i=1
s=""
while s.size<1001
	s<<i.to_s
	i+=1
end
n=gets.to_i-1
puts s[n]


# Fitting Arts

input = Array.new
for i in 0..2
	input.push (gets.chomp.split(' ').map(&:to_i)) ###
end

out = "NO"
for i in 0..1
	for j in 0..1
		for k in 0..1
			if input[1][i] + input[2][j] <= input[0][k]
				if [input[1][(i+1)%2] , input[2][(j+1)%2]].max <= input[0][(k+1)%2]
					out = "YES"
				end
			end
		end
	end
end

puts out


s = gets.chomp
t = gets.chomp

subs = s.dup
automaton = t.chars.all? do |c|
  n = subs.index(c)
  n.nil? ? false : subs = subs[n+1..-1]
end

array = s.chars.sort == t.chars.sort

subs = s.dup
both = t.chars.all? do |c|
  n = subs.index(c)
  n.nil? ? false : subs.slice!(n)
end

puts case
when automaton; "automaton"
when array; "array"
when both; "both"
else "need tree"
end


gets p
puts [*1..5].combination(3).any?{|x|x.permutation(2).select{|a,b|$_=~/#{a} #{b}/}.size%3<1} ? "WIN" : "FAIL"


string = gets.strip
valid_chars = %W{H Q 9}

output, check = false, true
while check do
  string.each_char { |char| (output, check = true, false if valid_chars.include?(char)); check = false if char == string[-1] }
end

output ? (puts 'YES') : (puts 'NO')


n = gets.to_i
s = gets
ans = s.count('x')-n/2
if ans > 0
    for i in 0...ans.abs
        s[s.index('x')] = 'X'
    end
else
    for i in 0...ans.abs
        s[s.index('X')] = 'x'
    end
end
puts ans.abs
puts s


#!/usr/bin/ruby

input_line = gets
params = input_line.split(' ')

p1 = params[0].to_i
p2 = params[1].to_i
t1 = params[2].to_f
t2 = params[3].to_f
res1 = [3*p1/10, p1-t1*p1/250].max
res2 = [3*p2/10, p2-t2*p2/250].max
if (res1 > res2)
    puts "Misha"
elsif (res2 > res1)
    puts "Vasya"
else
    puts "Tie"
end


# http://codeforces.com/problemset/problem/41/A

bir = gets.chomp
ber = gets.chomp

puts (bir.reverse == ber) ? "YES" : "NO"


n = gets.chomp.to_i
arr = []
for i in (0..n-1)
	arr << gets.chomp.to_i
end

for i in (0..n-1)
	if arr[i]%3 == 0 || arr[i]%7 == 0
		puts "YES"
	else
		x = arr[i]
		while x > 0
			if x%7 == 0
				x = 0
				break
			elsif x%3 == 0
				x = 0
				break
			elsif x - 7 >= 0
				x -= 7
			elsif x - 3 >= 0
				x -= 3
			else
				break
			end
		end
		if x == 0
			puts "YES"
		else
			puts "NO"
		end
	end
end


def calc(n, g)
	x = n/g
	rem = n%g
	return rem*(@c1+@c2*x**2) + (g-rem)*(@c1+@c2*(x-1)**2)
end

inp = gets.split(" ")
n = inp[0].to_i
@c1 = inp[1].to_i
@c2 = inp[2].to_i
s = gets
a = 0
for i in 0..n-1
	a+=1 if s[i]=='1'
end
ans = calc(n, 1)
for i in 2..a
	ans = [ans, calc(n, i)].min
end
puts ans


board = Array.new(3) { Array.new(3, 0) }
3.times do |i|
    line = gets.strip.split.map(&:to_i)
    3.times do |j|
        if line[j] > 0
            board[i][j] += line[j]
            board[i][j + 1] += line[j] if j + 1 < 3
            board[i][j - 1] += line[j] if j - 1 > -1
            board[i + 1][j] += line[j] if i + 1 < 3
            board[i - 1][j] += line[j] if i - 1 > -1
        end
    end
end
board.each do |line|
    text = ""
    line.each do |a|
        text += '1' if a.even?
        text += '0' if a.odd?
    end
    puts text
end


#!/usr/bin/ruby
include Math

a, b = gets.split().map(&:to_i)
x, y, z = gets.split().map(&:to_i)
aa = 2*x + y
bb = 3*z + y
puts [aa-a, 0].max + [bb-b, 0].max


#!/usr/bin/env ruby

first_line = gets.split(" ")
vasya = {"x" => first_line[0].to_i, "y" => first_line[1].to_i, "z" => first_line[2].to_i}

second_line = gets.split(" ")
box = {"x" => second_line[0].to_i, "y" => second_line[1].to_i, "z" => second_line[2].to_i}

array = gets.split(" ")

array[5] = 0 if vasya["x"] <= box["x"]
array[4] = 0 if vasya["x"] >= 0

array[1] = 0 if vasya["y"] <= box["y"]
array[0] = 0 if vasya["y"] >= 0

array[3] = 0 if vasya["z"] <= box["z"]
array[2] = 0 if vasya["z"] >= 0

sum = 0
array.each do |el|
	sum += el.to_i
end

puts sum


#!/usr/bin/env ruby

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

if b - a > 10
  puts '0'
else
  x = 1
  (a+1).upto(b) { |i| x = (x * i % 10) }
  puts x
end


n = gets.to_i
k = 0;
for i in 1..n-1
  if((n%i) == 0)
    k+=1;
  end
end
p k


def solve?
    rec = []
    hen,shu = 0,0
    xx,yy = [],[]
    4.times{
        x1,y1,x2,y2 = gets.split.map(&:to_i)
        if x1 == x2 then
            shu += 1
            xx << x1
        end
        if y1 == y2 then
            hen += 1
            yy << y1
        end
        rec << [x1,y1,x2,y2]
    }
    return false if shu != 2 || hen != 2 || xx[0] == xx[1] || yy[0] == yy[1]
    4.times do |i|
        return false if rec[i][0] == rec[i][2] &&\
        (![rec[i][1],rec[i][3]].include?(yy[0]) ||\
        ![rec[i][1],rec[i][3]].include?(yy[1]))
        return false if rec[i][1] == rec[i][3] &&\
        (![rec[i][0],rec[i][2]].include?(xx[0]) ||\
        ![rec[i][0],rec[i][2]].include?(xx[1]))
    end
    return true
end

puts solve? ? 'YES' : 'NO'


def gcd(a, b)
  if b == 0
    return a
  else
    return gcd(b, a % b)
  end
end

a, b = readline.split(' ').collect(&:to_i)
g = a
a.upto(b) do |num|
  g = gcd(g, num)
  if g == 1
    break
  end
end

puts g


n=gets.to_i
puts n%2>0?"black":["white","1 2"]


def invalid?(s)
  (s[0] == "0" and s.size > 1) or s.to_i > 10**6
end

ARGF.each_line do |line|
  max = -1
  digit = line.chomp!.size
  1.upto(digit) do |i|
    1.upto(digit - i - 1) do |j|
      k = digit - i - j

      a = line[0...i]
      b = line[i...(i + j)]
      c = line[(i + j)...digit]
      if invalid?(a) or invalid?(b) or invalid?(c)
        next
      end
      point = a.to_i + b.to_i + c.to_i
      max = point if max < point
    end
  end
  puts max
end


class C
  def initialize
    a, b = gets.chomp.split(' ').map(&:to_i)

    puts dfs(a, b)
  end

  def dfs(a, b)
    count = 0

    if a == 1
      count += b
    else
      sub = a / b
      if sub > 0
        count += sub
        count += dfs( a % b, b )
      else
        count += dfs( b, a )
      end
    end

    count
  end
end

c = C.new


a = gets()
b = gets()
c = ""
flag = -1

# f(a,c) = b

(0..a.length - 1).each do |x|
  if a[x] < b[x]
    flag = 0
    puts "-1"
    break
  end
  any = a[x] > b[x] ? b[x] : a[x]
  c << any
end
puts c if flag == -1


_, debuff    = gets.chop.split.map(&:to_i)
prices       = gets.chop.split.map(&:to_i).sort
quests_count = gets.chop.to_i

if quests_count > prices.count
  ns = debuff * (quests_count - prices.count )
  quests_count = prices.count
end

ns ||= 0
ps = prices.first(quests_count).reduce(0, :+)

puts ps - ns


N, M = gets.split.map(&:to_i)
ast = gets.split.map(&:to_i)
bst = gets.split.map(&:to_i)
as, bs = [], []
N.times do |i|
    as[i] = ast.shift(2)
end
M.times do |i|
    bs[i] = bst.shift(2)
end

acand = []
as.each do |a|
    cand = []
    bs.each do |b|
        ab = a & b
        if ab.length == 1
            cand.push(ab[0])
        end
    end
    cand.uniq!
    if cand.length > 1
        puts -1
        exit
    else
        acand.concat(cand)
    end
end

bs.each do |b|
    cand = []
    as.each do |a|
        ab = a & b
        if ab.length == 1
            cand.push(ab[0])
        end
    end
    cand.uniq!
    if cand.length > 1
        puts -1
        exit
    end
end

acand.uniq!
if acand.length == 1
    puts acand[0]
elsif acand.length > 1
    puts 0
else
    puts -1
end


point=gets.split.map(&:to_i)
x=point[0]
y=point[1]
if x.abs==0 || y.abs==0 then
    puts "black"
    exit
end
d=x*x+y*y
1.upto(999999){|i|
    if (i%2==1 && x*y>0) || (i%2==0 && x*y<0) then
        #black
        if d<=i*i then
            puts "black"
            exit
        end
    else
        #white
        if d<i*i then
            puts "white"
            exit
        end
    end
}


#http://codeforces.com/contest/816/problem/A

time = gets.chop

h = time.slice(0, 2).to_i
m = time.slice(3, 2).to_i

tmp = h / 10
pal_m = (h - (tmp * 10)) * 10 + tmp
count = 0

f = false
  if(m == pal_m) then
    f = true
  end
while(!f) do
  m = m + 1
  if(m == 60) then
    m = 0
    h = h + 1
  end
  h = h % 24
  pal_m = (h % 10) * 10 + (h / 10)
  count = count + 1
  if(m == pal_m) then
    f = true
  end
end

puts count
=begin
if(m<10) then
  if(h<10) then
    puts "0" + h.to_s + ":0" + m.to_s
  else
    puts h.to_s + ":0" + m.to_s
  end
else
  if(h<10) then
    puts "0" + h.to_s + ":" + m.to_s
  else
    puts h.to_s + ":" + m.to_s
  end
end
=end


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

if n == k || k == 0
    puts "0 0"
else
    if k*3 < n
        puts "1 #{k*2}"
    else
        puts "1 #{n-k}"
    end
end


s = gets.chomp
h = Hash.new(0)
n = s.size
com = 0
if n < 26
    p -1
    exit
end
26.times{|i|
    h[s[i]] += 1
    if s[i] == "?" || h[s[i]] == 1
        com += 1
    end
    }
ans = ""
f = false
if com == 26
    tmp = []
    ?A.upto(?Z){|c|
        if h[c] == 0
            tmp.push(c)
        end
        }
    26.times{|i|
        if s[i] == "?"
            ans += tmp.pop
        else
            ans += s[i]
        end
        }
    f = true
else
    if n == 26
        p -1
        exit
    end
end

26.upto(n - 1){|i|
    if f
        if s[i] == "?"
            ans += ?A
        else
            ans += s[i]
        end
        next
    end
    h[s[i - 26]] -= 1
    if s[i - 26] == "?" || h[s[i - 26]] == 0
        com -= 1
    end
    if s[i - 26] == "?"
        ans += ?A
    else
        ans += s[i - 26]
    end
    h[s[i]] += 1
    if s[i] == "?" || h[s[i]] == 1
        com += 1
    end
    if com == 26
        tmp = []
        ?A.upto(?Z){|c|
            if h[c] == 0
                tmp.push(c)
            end
            }
        (i - 25).upto(i){|j|
            if s[j] == "?"
                ans += tmp.pop
            else
                ans += s[j]
            end
            }
        f = true
    end
    }
if f
    puts ans
else
    p -1
end


def max(a,b)
    if a > b then
        return a
    else
        return b
    end
end

y,w = gets.split.map{|i| i.to_i}

i = max(y,w)
i = 7 - i

n = 6

if i == 0 then
    n = 1
elsif i % 6 == 0 then
    i /= 6
    n /= 6
elsif i % 3 == 0 then
    i /= 3
    n /= 3
elsif i % 2 == 0 then
    i /= 2
    n /= 2
end

puts i.to_s + "/" + n.to_s


class List
  attr_accessor :element, :next_elem

  def initialize(element, next_elem)
    @element = element
    @next_elem = next_elem
  end
end

class Graph
  attr_accessor :vertices

  def initialize(vertices)
    @vertices = vertices
  end

  def add_edge(number1, number2)
    if vertices[number1].nil? then
      vertices[number1] = List.new(number2, nil)
    else
      vertices[number1] = List.new(number2, vertices[number1])
    end
  end

  def print_edges
    vertices.each_with_index do |vertex, index|
      # next if vertex == ""
      while !vertex.nil? do
        puts "edge #{index} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end

end

def dfs(graph, number, visited)
  visited[number] = true
  next_vert = graph.vertices[number]
  # puts "Processing number: #{number}"
  # p next_vert
  stack = []
  # return [number] if next_vert.nil?
  while !next_vert.nil? do
    # puts "#{next_vert.element} is not nil. Process it"
    if !visited[next_vert.element]
      # puts "#{next_vert.element}'s is not visited. Processing it"
      new_number = dfs(graph, next_vert.element, visited)
      # puts new_number
      stack = new_number + stack
    end
    next_vert = next_vert.next_elem
  end
  # p [number] + stack
  return [number] + stack
end

def reverse_graph(graph)
  reversed_graph = Graph.new([])
  graph.vertices.each_with_index do |vertex, index|
    next_vertex = vertex
    while !next_vertex.nil? do
      reversed_graph.add_edge(next_vertex.element, index)
      next_vertex = next_vertex.next_elem
    end
  end
  reversed_graph
end

intersections = Graph.new([])
n, m = gets.strip.split(" ").map(&:to_i)
horizontal = gets.strip
vertical = gets.strip
visited = Array.new(m*n, false)

n.times do |i|
  # puts i
  # puts horizontal[i]
  if horizontal[i] == ">"
    (m - 1).times do |j|
      # puts j
      intersections.add_edge(i*m + j, i*m + j + 1)
    end
  else
    (m - 1).times do |j|
      intersections.add_edge(i*m + j + 1, i*m + j)
    end
  end
end
m.times do |i|
  if vertical[i] == "v"
    (n - 1).times do |j|
      intersections.add_edge(j*m + i, (j+1)*m + i)
    end
  else
    (n - 1).times do |j|
      intersections.add_edge((j+1)*m + i, j*m + i)
    end
  end
end
# intersections.print_edges
stack = []
(n*m).times do |i|
  if !visited[i]
    stack = dfs(intersections, i, visited) + stack
    # p stack
  end
end
# p intersections.vertices.count
answer = 'YES'
reversed_graph = reverse_graph(intersections)
# reversed_graph.print_edges
# p visited
visited = Array.new(m*n, false)
# (m*n).times do |i|
#   visited[i] = false
# end
# p visited
# p stack
# p intersections.vertices[stack.first]
dfs(reversed_graph, stack.first, visited)
# p visited
if visited.any?{|visited| !visited}
  answer = 'NO'
end
puts answer


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

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

result = 0

while true
  hash = Hash.new(0)

  points.each_with_index do |point, index|
    points.each_with_index do |p, i|
      hash[index] += 1 if((point - p).abs > d and index != i)
    end
  end

  hash = hash.sort{|x, y| y[1] <=> x[1]}
  break if hash.empty?
  ind, repeat = hash[0][0], hash[0][1]
  if repeat > 0
    points.delete_at(ind)
    result += 1
  else
    break
  end
end

puts result


number=gets.chomp.split
n=number[0].to_i
k=number[1].to_i
#puts n,k
if n==0
	puts 0
else
	zeros=0
	non_zeros=0
	digits=0
	while n>0
		if zeros==k
			break
		elsif n%10==0
			zeros+=1
		else
			non_zeros+=1
		end
		digits+=1
		n=n/10
	end
	#puts "zeros=#{zeros}"
	#puts "digits=#{digits}"
	if zeros==k
		puts non_zeros
	elsif zeros<k
		#只剩下一个0
		puts digits-1
	else
		puts 0
	end
end


n = gets.to_i
a = gets.split.map &:to_i
puts a.uniq.size - (a.any? { |x| x == 0 } ? 1 : 0)


n = gets.chomp.to_i
a = gets.chomp.to_i
b = gets.chomp.to_i
c = gets.chomp.to_i

l = 0
r = n + 1
m = (l + r) / 2

while l < m && m < r
  if 0 <= n - m * b + (m - 1) * c
    l = m
  else
    r = m
  end
  m = (l + r) / 2
end

puts [n / a, m + (n - m * b + m * c) / a].max


l,d,v,g,r = gets.split(" ").map(&:to_i)

till_a = d/v.to_f
# puts "#{till_a}"
total_interval = g + r
# puts "total_interval#{till_a % total_interval}"
extra_time = (till_a % total_interval) >= g ? (total_interval - (till_a % total_interval)) : 0
# puts "#{extra_time}"
a_to_b = (l-d) / v.to_f
# puts "#{a_to_b}"
#

puts till_a + extra_time + a_to_b


n = gets.to_i
case n%4
when 0
	puts "1 A"
when 1
	puts "0 A"
when 3
	puts "2 A"
else
	puts "1 B"
end


s = gets()
a = s.to_i
s.reverse!
b = s.to_i

while(1) do
    if(a%10==0)
        a=a/10
    else
        break
    end
end

if a==b
    puts "YES"
else
    puts "NO"
end


#!/usr/bin/env ruby
require 'set'

s = gets.chomp.to_s
n = s.length - 1

p = Set.new [ s ]

n.times do
    s = s[ n ] + s[ 0 ... n ]
    p.add( s )
end

puts p.length


H=Hash.new 0
gets
gets.chomp.chars{|c|H[c]+=1}
p [H['U'],H['D']].min+[H['L'],H['R']].min<<1


def cani(grandma, me)
	for card in me
		card = card.split(//)
		for character in card
			return "YES" if grandma.include?(character)
		end
	end
	return "NO"
end

grandma = gets.chomp
me = gets.chomp.split(" ")
puts(cani(grandma, me))


a, b, c, d, k = *gets.split(" ").map(&:to_i)
# p [a, b, c, d, k]
# if b < c
#   p 0
#   exit
# end

start = [a, c].max
fim = [b, d].min
# p [start, fim]
if fim < start
  p 0
  exit
end

if k >= start && k <= fim
  fim -= 1
end

p fim-start+1


X,Y,x,y,a,b=$<.read.split.map &:to_i
x-=X
y-=Y
puts x%a==0&&y%b==0&&x/a%2==y/b%2 ? :YES : :NO


n = gets.to_i
a,b,i = 0,1,0
while a<=n
  a,b, = b, a+b
  i +=1
end
p i-3


n, k = gets.split.map &:to_i
a = gets.split.map &:to_i
p a.inject(k){|s, x| [s, k%x == 0 ? k/x : k].min}


s = gets.chomp
c=0
s.length.times do |i|
    if s[i]=='7' or s[i]=='4'
        c=c+1
    end
end
if (c == 4 or c == 7)
    puts "YES"
else
    puts "NO"
end


n, m, k = gets.split.map(&:to_i)
a = Array.new(n) do
    gets
    Array.new(m) do
        gets.split.map(&:to_i)
    end
end

ans = 0
a.permutation(2) do |x, y|
    z = []
    m.times do |i|
        z <<= [y[i][1] - x[i][0], x[i][2]]
    end
    tmp = 0
    rem = k
    z.sort.reverse.each do |i, j|
        num = [rem, j].min
        tmp += i * num if i > 0
        rem -= num
    end
    ans = [ans, tmp].max
end
p ans


n, a = gets.split(' ').map(&:to_i)
puts a.even? ? 1 + n / 2 - a / 2 : 1 + a / 2


n,m = gets.split(' ').map(&:to_i)
s = n/2
if n==1
  puts "1"
  exit
end
if s >=m
  m += 1
  puts m
  exit
end
m -= 1
puts m


a = gets.chomp!.split
n = a[0].to_i
r_ = a[1].to_i
r = a[2].to_i
s = r_ - r

if s < 0 then puts("NO")
elsif s < r then
	if n == 1 then puts("YES")
	else puts("NO") end
elsif n == 2 then
	if s >= r then puts("YES")
	else puts("NO") end
elsif n == 6 then
	if r_ >= r * 3 then puts("YES")
	else puts("NO") end
else
	n = n.to_f
	r = r.to_f
	s = s.to_f
	#p Math.asin(r / s)
	#p Math::PI / n
	if Math.asin(r / s) <= Math::PI / n then puts("YES")
	else puts("NO") end
end


require 'pp'

n = STDIN.gets.chomp.to_i

ans = 0
while true
  n+=1
  ans+=1
  n.to_s.split(//).each do |e|
    if e == '8'
      puts ans
      exit(0)
    end
  end
end


n,x,y=gets.split.map &:to_i;puts x%(q=2+n/=2)<n||y%q<n ?:YES:"NO"


t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  p = n % 10
  ps = n.to_s.size
  res = (p - 1) * 10
  case ps
  when 1
    res += 1
  when 2
    res += 3
  when 3
    res += 6
  when 4
    res += 10
  end
  puts res
end


#!/usr/bin/ruby1.9

triple_num = {}
triples = {}
c_max = STDIN.readline.to_i
count = 0

(1..c_max).each do |c|
	triple_num[c] = 0
	triples[c] = []
end

def gcd(a, b)
	return a if b == 0
	return gcd(b, a%b)
end

m = 1
while true
	break if m*m + 1 > c_max
	(1..m-1).each do |n|
		next if (m-n)%2 == 0
		next if gcd(m, n) > 1
		sum = m*m + n*n
		break if sum > c_max
		difference = m*m-n*n
		product = 2*m*n
		k = 1
		while k*sum <= c_max
			a = k*difference
			b = k*product
			c = k*sum
			triple_num[c] += 1
			triple = [a, b, c]
			triples[c].push(triple)
			count += 1
			k += 1
		end
	end
	m += 1
end

puts count


string = gets.chomp
words = []
words = string.gsub("WUB", "a").split('a')

words.each do |word|
	print "#{word} " if word != ""
end


puts [:No, :Yes][gets.split.uniq.size == 1? 1:0]


a,b,x,y=gets.split.map &:to_i;g=x.gcd y;p [a*g/x,b*g/y].min


n = gets.chomp.to_i
answer = false
a = 0
while a <= n
    b = 0
    while a + b <= n
        if( ( n - ( a + b ) ) % 1234 == 0 )
            answer = true
            a = n;
            break;
        end
        b += 123456
    end
    a += 1234567
end

if answer
    puts "YES"
else
    puts "NO"
end


t = gets.to_i
t.times{
	k = gets.to_i
	ratio = Rational(k,100)
	p ratio.denominator
}


n, m = *STDIN.read.split(' ').map(&:to_i)

lb = (n+1)/2 ;
a = (lb+m-1)/m*m ;
if a>n
  a = -1
end

puts a


s=gets.chomp
a=nil
(0..s.size).find{|i|(?a..?z).find{|c|t=s.dup;t[i,0]=c;(t==t.reverse&&a=t)}}
puts a||"NA"


def subsetSum(set, n, sum)
  subset = (n + 1).times.map { [true] * (sum + 1) }
  1.upto(sum) {|i| subset[0][i] = false }
  1.upto(n) do |i|
    1.upto(sum) do |j|
      subset[i][j] = subset[i - 1][j] if j < set[i - 1]
      subset[i][j] = subset[i - 1][j] || subset[i - 1][j - set[i - 1]] if j >= set[i - 1]
    end
  end
  return subset[n][sum]
end

def solve(a)
  while true
    sumall = a.sum
    if sumall % 2 == 1
      printf("0\n")
      return
    end
    a.each.with_index do |x, i|
      if x % 2 == 1
        if !subsetSum(a, a.size, a.sum / 2)
          printf("0\n")
          return
        end
        printf("1\n")
        printf("%d\n", i + 1)
        return
      end
    end
    a.map! {|x| x / 2 }
  end
end

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

solve(a)


n, m = gets.split.collect{|i| i.to_i}
mm = Array.new
(1..n).each{mm.push(gets.chomp.split(''))}
ans = 0
for i in 0...n
    for j in 0...m
        next unless  mm[i][j] == 'P'
        if i-1 >= 0 and mm[i-1][j] == 'W'
            mm[i-1][j] = '.'
            ans += 1
            next
        end
        if i+1 < n and mm[i+1][j] == 'W'
            mm[i+1][j] = '.'
            ans += 1
            next
        end
        if j-1 >= 0 and mm[i][j-1] == 'W'
            mm[i][j-1] = '.'
            ans += 1
            next
        end
        if j+1 < m and mm[i][j+1] == 'W'
            mm[i][j+1] = '.'
            ans += 1
            next
        end
    end
end
puts ans


input_origen=gets.chomp
input_destino=gets.chomp

ar_origen=input_origen.split(" ")
ar_destino=input_destino.split(" ")

x1=ar_origen[0].to_i; y1=ar_origen[1].to_i
x2=ar_destino[0].to_i; y2=ar_destino[1].to_i

x2=(x2-x1).abs
y2=(y2-y1).abs

x1=0;y1=0
if y2>=x2
	$pasos=y2
else
	$pasos=x2
end
print $pasos


left, right = Hash.new(0), Hash.new(0)
n = gets.to_i
for i in 0...n
    l, r = gets.split.map(&:to_i)
    left[l] += 1
    right[r] += 1
end
sum = 0
left.each do |k, v|
    sum += v * right[k]
    left[k] = 0
end
right.each do |k, v|
    sum += v * left[k]
    left[k] = 0
end
puts sum


def s x
	x.to_s.chars.map { |c| c.to_i }.reduce(:+)
end

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

ans = []
1.upto(100) do |i|
	x = b * i ** a + c
	if x > 0 and x < 1e9.to_i and s(x) == i
		ans << x
	end
end

puts ans.size
puts ans.sort.join ' '


n,k=gets.split(" ").map(&:to_i)
x,y=Array.new(n),Array.new(k)
ans=k>1 ?1:0
ik=gets.split(" ")
for i in 0..n-1 do
x[i]=ik[i].to_i
end
ik=gets.split(" ")
for i in 0..k-1 do
y[i]=ik[i].to_i
end
if x[0]==0&&k==1 then x[0]=y[0] end
for i in 1..n-1 do
if x[i]==0&&k==1 then x[i]=y[0] end
if x[i]<x[i-1] then ans=1 end
end
puts ans==1 ?"Yes":"No"


t, a, b = gets.split(" ").map &:to_i
nok = a.lcm(b)
noks = t / nok
tmk = t - nok * noks
minab = [a,b].min
ans = (noks+1) * minab - 1 - [0, minab - 1 - tmk].max
gc = ans.gcd(t)
puts "#{ans/gc}/#{t/gc}"


s = gets.chomp
s.scan(/[A-Z]/).size > (s.size / 2) ? s.upcase! : s.downcase!
puts s


def dep?(arr)
  size = arr.size - 1
  for i in 1...size do
    return true if arr[i - 1] + arr[i] > arr[i + 1]
  end
  false
end
n = gets.chomp.to_i
arr = gets.split.map(&:to_i)
arr.sort!

puts dep?(arr) ? 'YES' : 'NO'


n = gets.to_i

x = (n / 2.0).ceil - 1.0

puts x.to_i


c,d = gets.split.map &:to_i
m,n = gets.split.map &:to_i
k = gets.to_i

need = m*n - k
if need <= 0
  puts 0
  exit
end

$hash = Hash.new -1
def solve(need, c, d, m)
  return $hash[need] if $hash[need] != -1
  return $hash[need] = 0 if need <= 0
  if need <= m then return $hash[need] = [c, need * d].min end
  return $hash[need] = [solve(need - m, c, d, m) + c, solve(need - 1, c, d, m) + d].min
end

puts solve(need, c, d, m)

exit

r = 0
if c < m*d # better use typical round
  r = ((need+m) / m) * c
else
  r = need * d
end

puts r


a,b,c = gets.split.map(&:to_i)
p (c*a-c*b-1)/b+1


require 'date'
a = Date::MONTHNAMES[1..-1]
b = gets.chomp
c = gets.to_i
puts a[(a.index(b) + c) % 12]


def solution(days)
  prev = nil
  rest_days = 0
  days.each_with_index do |activity, index|
    (rest_days += 1; prev = 0; next) if activity == 0
    (rest_days += 1; prev = 0; next) if activity == prev && activity != 3
    if activity == 3
      days[index] = 2 if prev == 1
      days[index] = 1 if prev == 2
    end
    prev = days[index]
  end
  rest_days
end

_ = gets
puts solution(gets.split.map(&:to_i))


a,b,s=gets.split.map(&:to_i)
t=s-a.abs-b.abs
puts t>=0&&t%2==0?"Yes":"No"


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

# b.rb

def main()
    v1, v2 = gets.chomp.split(" ").map{|s| next s.to_i }
    t, d = gets.chomp.split(" ").map{|s| next s.to_i }

    r = 0
    t.times do |tt|
        t1 = tt
        t2 = t - 1 - tt
        r += [v1 + d * t1, v2 + d * t2].min
    end
    puts r

end

if __FILE__ == $0 then
    main()
end


gets
a=gets.split.reverse.uniq.reverse
p a.size
puts a*' '


# coding: utf-8

# if __FILE__ == $0
# end

# n - 방문한 버텍스까지의 웨이트 총합
# k - 트리의 유형(the number of children)
# d - 웨이트가 d인 에지로, 반드시 포함되어야함
# 1<=d<=k 이므로 d가 k보다 커질 일은 없음
# 1<=n,k<=100
n, k, d = gets.split.map(&:to_i)
MODULO_BASE = 10**9 + 7
dp = Array.new(n+1) { [0, 0] }
# dp factors: '합'과 weight d 이상의 노드 방문 여부
# 그래서 트리 전체가 아니고, n까지 도달하는 과정을 점진적으로 만들어간다.
# 합이 S1 인 지점에서 S1 + 1, S1 + 2, ... S1 + K 에 도달하는 방법.

# 자, 리셋해뒀으니 내일 다시 풀어봅시다.
# 코드를 외우든지 dp 를 정복하기 위한 생각을 만들든지!
# 지금이 내일이다 새끼야

# 합이 0이 되는 경로를 우선 고려(zero) depth 0
dp[0][0] = 1 # 0 을 통과하는 경로는 하나 존재할 수 있음. (이후엔 존재해선 안됨)
dp[0][1] = 0 # 0 < d 가 항상 성립하므로 경로의 수가 없다.
for i in 1..n
    # initialize intermediate sum to zero
    dp[i][0] = 0
    dp[i][1] = 0
    for j in 1..k # 만날때마다 k개의 차일드 노드에 대해 평가를 한다.
        if i < j
            break # depth 1에서, i < j 인 경우 이전 경유 노드를 판단할 수 없다.
        end

        # 현재 weight 가 j인 경로로 노드를 찾아갈 때
        # 이전에는 몇개 경우의 수가 있었는지 파악한다.
        if j < d
            # j < d인 경우, 현재 방문하려는 노드들은 d보다 작은 weight를 가진
            # 경로로 방문하게 된다.
            # 이때 가능한 경우는, 계속 d보다 작은 경로를 이용한 경우와
            # 이전에 d와 같거나 보다 큰 weight를 가진 경로를 방문한 뒤 j < d 인
            # 경로를 이용한 경우이다.
            dp[i][0] = dp[i][0] + dp[i-j][0] # 계속 j < d인 경로를 이용한 경우끼리 합한다.
            dp[i][1] = dp[i][1] + dp[i-j][1] # 이전 한번 이상 j >= d 인 경로를 방문한 경우를 합산한다.
        else
            # j >= d 인 경우, 현재 방문하려는 노드들은 항상 d보다 같거나 큰 weight의
            # 경로를 이용한다.
            # 이때 가능한 경우는,
            # 1) 연이어 j >= d를 만족하는 경로를 방문한 경우
            # 2) 이전까지 j < d 경로를 만났지만 이번에 j >= d 를 처음으로 만난 경우
            # 따라서 dp[i][0] 의 경우에 대해 전혀 계산해줄 필요가 없다.
            # 1과 2의 경우를 모두 dp[i][1]에 더해주면 된다.
            dp[i][1] = dp[i][1] + dp[i-j][0]
            dp[i][1] = dp[i][1] + dp[i-j][1]
        end
    end
end

# 최종적으로 dp[n] 에는 n까지 합을 구했을 때, weight < d로만 방문한 경우와
# 한번 이상 weight >= d를 방문한 경우의 숫자 합이 남는다.
# 물론 숫자가 꽤 크기 때문에, 큰 숫자 구현이 없는 경우에는 계속 modulo 연산을
# 수행하면서 합을 구한다.
puts dp[n][1]%MODULO_BASE


n, m, a = gets.split.map &:to_i
r = n/a * (m/a)
if n%a!=0
  r+=m/a
  n+=a
end
if m%a!=0
  r+=n/a
end
p r


def main
  w, m = gets.split.map(&:to_i)
  return true if w == 2
  ma = []
  while m > 0
    ma << (m % w)
    m /= w
  end
  i = 0
  while i < ma.size
    if ma[i] >= w - 1
      ma[i] = 0
      ma[i + 1] = 0 if ma[i + 1].nil?
      ma[i + 1] += 1
    elsif ma[i] >= 2
      return false
    end
    i += 1
  end
  true
end

puts (main ? "YES" : "NO")


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

hash = Hash.new { 0 }.tap do |h|
  cards.each { |card| h[card] += 1 }
end

keys = hash.keys.select { |key| hash[key] >= 2 }
keys.map! do |key|
  hash[key] > 3 ? key * 3 : key * hash[key]
end

puts cards.inject(0, :+) - (keys.empty? ? 0 : keys.max)


a=gets.split.map(&:to_i).sort
if a.count(a[0])>=a[0] || a==[2, 4, 4]
    puts "YES"
else
    puts "NO"
end


buf=gets.split(" ")
n,k=buf[0].to_i,buf[1].to_i
n-=1
ans=0
while n>0&&k>0
	ans+=n*2-1
	n-=2
	k-=1
end
puts ans


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

ans    = 0
offset = 0
flag   = false
m      = 2 ** h

while m != 1
  m /= 2
  if flag ^ (offset + m >= n)
    ans += 1
    flag = !flag
    offset += m unless flag
  else
    ans += 2 * m
    offset += m unless flag
  end
end

puts ans


#!/usr/bin/ruby
n = gets.chomp.to_i
inp = gets.chomp
days = inp.split(' ')
k = false
while k == false
	for i in 0..6
		n = n - days[i].to_i
		if n <= 0
			puts((i+1).to_s)
			k=true;
			break
		end
	end
end


n = gets.to_i
if n % 2 == 0
  puts n / 2
else
  puts -n + n / 2
end


k,b,n,t=gets.split.map{|i| i.to_i};x=1;
x,n=x*k+b,n-1 until x>t
puts [0,n+1].max


def toi(n, x, y)
	if x == 0
		return y
	elsif y == n
		return n + x
	elsif x == n
		return n + n + (n - y)
	else
		return n + n + n + (n - x)
	end
end

n, x1, y1, x2, y2 = gets.split.map(&:to_i)
z1 = toi(n, x1, y1)
z2 = toi(n, x2, y2)
m = 4 * n
d = (z2 - z1 + m) % m
p [d, m - d].min


s=eval gets.sub(' ','^');99.times{s|=s/2};p s


n = gets().to_i()
if(n==0) then puts 0
elsif((n&1)==1) then puts((n+1)/2)
else puts(n+1) end


#!/usr/bin/ruby

def read_vector
    gets.split(/\s+/)
end

def read_vector_int
    read_vector.map(&:to_i)
end

n, l, r, x = read_vector_int
tasks = read_vector_int
res = 0
(1...(1<<n)).each do |mask|
    dif = []
    n.times.select{ |i| (mask & (1 << i)) > 0 }.each{ |i| dif.push tasks[i] }
    sum = dif.reduce(:+)
    next unless l <= sum && sum <= r
    next unless dif.min + x <= dif.max
    res += 1
end
puts res


a, b, c, n = gets.split.map(&:to_i)
x = a + b - c
puts (a >= c && b >= c && n - x > 0) ? (n - x) : -1


N = gets.chomp
digits = Hash.new(0)
N.chars do |c|
    digits[c] += 1
end

nums = ('0'..'9').map{|i| digits[i]}.select{|n| n > 0}
max = nums.inject(:*)

comb = Array.new(20){Array.new(20, 0)}
comb[0][0] = 1
20.times do |i|
    20.times do |j|
        comb[i][j] += comb[i-1][j-1] if i>0 && j>0
        comb[i][j] += comb[i-1][j] if i>0
    end
end

ans = 0
(0...max).each do |i|
    use = []
    nums.each do |n|
        use.push(i % n + 1)
        i /= n
    end
    sum = use.inject(:+)
    prod = 1
    use.each do |u|
        prod *= comb[sum][u]
        sum -= u
    end
    ans += prod

    if digits['0'] > 0
        use[0] -= 1
        sum = use.inject(:+)
        prod = 1
        use.each do |u|
            prod *= comb[sum][u]
            sum -= u
        end
        ans -= prod
    end
end
p ans


dp=(0..4001).map{0}
n,*a=gets.split.map{|e| e.to_i}
a.each{|e|
	(0..(n-e)).each{|i|
		if dp[i]>0 || i==0 then
			dp[i+e]=[dp[i+e],dp[i]+1].max
		end
	}
}
puts dp[n]


a,b = gets.chomp.split(' ').map{|x|x.to_i}
h = 0
if b > a
	puts 3*b
	exit
end

if a > b+1
	c = [(a-b)/2, b].min
	h+= c*6
	a = a - 3*c
	b = b - c
end

if b % 2 == 0
	h+=(b/2)*6
	a = a-b
	b = 0
else
	h+=(b/2)*6
	h+=3
	a = a - b
	b = 0
end

if a > 0
	if h%2 ==1
		h+=1
		a-=1
	end
end

h+=2*a

puts h


c, v0, v1, a, l=gets.split.map &:to_i
r=0
t=0
v=v0
while r<c
    r-=l if t>0
    r+=v
    t+=1
    v+=a
    v=v1 if v>v1
end
puts t


a = gets.chomp.split(/ /).map!{|x|x.to_i}
b = gets.chomp.split(/ /).map!{|x|x.to_i}
ret = "NO"
for i in 0..2
	if a[i] == b[i]
		ret = "YES"
	end
end

puts ret


def fac(n)
  if n == 1
    1
  else
    n * fac(n-1)
  end
end

x = gets.to_r
p (fac(x) / x**2 * 2).to_i


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

sum = 0
m = (n-1)/2

sum += a[m].inject(:+)
sum += a.transpose[m].inject(:+)
i = -1
sum += a.map{|aa| i += 1; aa[i] }.inject(:+)
i += 1
sum += a.map{|aa| i -= 1; aa[i] }.inject(:+)

p sum -= a[m][m]*3


# coding: utf-8

# if __FILE__ == $0
# end

s = gets.chomp.split(//).map(&:to_i).reverse
catch :found do
    loop do
        if s.reduce(&:+)%4 == 0
            puts s.reverse.join('')
            throw :found
        else
            i = 0
            s[i] += 1
            loop do
                carry = s[i]/10
                if carry > 0
                    s[i] = s[i]%10
                    if i == s.length-1
                        s << carry
                        carry = 0
                    else
                        i += 1
                        s[i] += 1
                    end
                else
                    break
                end
            end
        end
    end
end


n, m = gets.strip.split.map(&:to_i)
ary = gets.strip.split.map(&:to_i)
hsh = {}
ary.each {|ai| hsh[ai] = ((hsh[ai] || 0)+1) }

def can?(hsh, n, days)
  support_n = 0
  hsh.keys.each do |ai|
    support_n += (hsh[ai]/days)
  end
  support_n >= n
end

ans=0
105.downto(1).each do |d|
  if can?(hsh, n, d)
    ans=d
    break
  end
end
puts ans


x = gets.chomp
y = x.downcase
a = y.split('')

for i in a do
	if i != "a" and i != "e" and i != "i" and i != "o" and i != "u" and i != "y"
		print ".#{i}"
	end
end


n = gets.strip.to_i

denominator = n - 1
numerator = 1.0
max = 0
max_numerator = 0
max_denominator = 0
def gcd(a, b)
    b == 0 ? a : gcd(b, a.modulo(b))
  end
while (numerator < denominator)
    if (numerator % denominator != 0 && numerator/denominator > max && gcd(numerator, denominator) == 1)
        max = numerator/denominator
        max_numerator = numerator
        max_denominator = denominator
    end
    numerator += 1
    denominator -= 1
end
puts "#{max_numerator.to_i} #{max_denominator.to_i}"


gets
s = gets
a ={}
s.each_char do
  |c|
  if c>= 'A' && c<='Z'
    a[c.downcase] = 1;
  else
    a[c] = 1
  end
end
res = true
('a'..'z').each do
  |c|
  if a[c] != 1
    res = false
  end
end
if res == true
  puts "YES";
else
  puts "NO";
end


w, h = gets.strip.split(" ").map(&:to_i)

cnt = 0
while w > 0 and h > 0 do
    if w > h then
        k = w / h
        w = w % h
    else
        k = h / w
        h = h % w
    end
    cnt += k
end

p cnt


n,a,b,x,y=gets.split.map(&:to_i)
c=n/a.lcm(b)
a=n/a
b=n/b
p a*x+b*y-c*[x,y].min


class Matrix2x2
  attr_accessor :a, :b, :c, :d
  def initialize(a=0,b=0,c=0,d=0)
    @a = a
    @b = b
    @c = c
    @d = d
  end
end

def mult(x, y)
  z = Matrix2x2.new
  z.a = (x.a*y.a + x.b*y.c)%1000000007
  z.b = (x.a*y.b + x.b*y.d)%1000000007
  z.c = (x.c*y.a + x.d*y.c)%1000000007
  z.d = (x.c*y.b + x.d*y.d)%1000000007
  z
end

def expt(a, p)
  if p == 1
    a.clone
  elsif p % 2 == 1
    t = expt(a, p-1)
    mult(a, t)
  else
    t = expt(a, p/2)
    mult(t, t)
  end
end

n = gets.to_i
if n == 0
  puts 0
else
  a = Matrix2x2.new(0, 3, 1, 2)
  an = expt(a, n)
  puts an.a
end


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

n = input[0]
a = input[1]
b = input[2]

ns = n * 6

if a * b >= ns
    puts a * b
    puts "#{a} #{b}"

else
    mina = a
    minb = b
    min = 2 ** 64
    troca = false

    if a > b
        a, b = b, a
        troca = true
    end

    a.upto(Math.sqrt(ns)) do |x|
        auxb = ns / x
        if auxb * x < ns
            auxb +=1
        end

        if auxb < b
            next
        end

        if auxb * x < min
            min = auxb * x
            mina = x
            minb = auxb
        end
    end

    puts min
    if a <= b and not troca
        puts "#{[mina, minb].min} #{[mina, minb].max}"
    else
        puts "#{[mina, minb].max} #{[mina, minb ].min}"
    end
end


def get_sumator(arr)
    return -1 if arr.length > 3
    case arr.length
    when 1
        return 0
    when 2
        max = arr.max
        min = arr.min
        if (max - min) % 2 == 0
            return (max - min) / 2
        else
            return (max - min)
        end
    when 3
        max = arr[-1]
        min = arr[0]
        # if the average of max and min is the same as
        # the middle one it can be done
        if (max + min) % 2 == 0 && (max + min) / 2 == arr[1]
            return (max - min)/ 2
        else
            return -1
        end
    else
        return -1
    end
end

n = gets.chomp.to_i
nums = gets.chomp.split(" ").map(&:to_i)
unique_arr = []
nums.each do |num|
    unique_arr.push(num) if !unique_arr.include?(num)
end

puts get_sumator(unique_arr.sort)


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

ans = 2333
1.upto(n - 2) do |i|
	b = a[0, i] + a[i + 1, n - i - 1]
	tmp = 0
	0.upto(n - 3) do |j|
		tmp = [tmp, b[j + 1] - b[j]].max
	end
	ans = [ans, tmp].min
end
puts ans


n = gets().to_i

ans = 0
for i in 1..n
	for j in 1..i-1
		k = i^j
		if k <= j and k + j > i
			ans += 1
		end
	end
end
puts ans


s=gets.to_s.chomp
if s.index("ftp")==nil||s.index("http")==nil then
	s.sub!("http","http://") if s.index("ftp")==nil
	s.sub!("ftp","ftp://") if s.index("http")==nil
	else
		s.sub!("http","http://") if s.index("http")<s.index("ftp")
		s.sub!("ftp","ftp://") if s.index("http")>s.index("ftp")
end
if s.rindex("ru")>s.index("ru") then
 s.reverse!
 s.insert(s.index("ur")+2,'.')
 s.insert(s.index("ur."),'/') if s.index("ur.")!=0
 s.reverse!
 else
	s.insert(s.index("ru"),'.')
	s.insert(s.index(".ru")+3,'/') if s.index(".ru")+3!=s.size
end
puts s


x,y,l,r=gets.split(" ").map(&:to_i)
xp=[]
yp=[]
t=1
while t<r do
  xp.push(t)
  t*=x
end
t=1
while t<r do
  yp.push(t)
  t*=y
end

zp=[]

for i in xp do
  for j in yp do
    zp.push(i+j)
  end
end

zp.uniq!()
zp.sort!()

#p zp

ans=0
tl=l
for i in zp do
  next if i<tl
  if i>=r then
    #p [ans,tl,i]
    r-=1 if r==i

    ans=[ans,r+1-tl].max
    tl=r+1
    break
  end
  if tl<=i then
    ans=[ans,i-tl].max
    tl=i+1
  end
  #p [ans,i]
end
#p [ans,tl]
ans=[ans,r+1-tl].max

puts ans


def square(x)
    x * x
end

def triangle(x)
    x * (x + 1) / 2
end

def solve(n, x, y, t)
    count = t * t + (t + 1) * (t + 1)
    4.times do
        count -= square(t - x + 1) if x <= t
        count += triangle(t - x - y + 1) if x + y <= t
        x, y = n + 1 - y, x
    end
    count
end

n, x, y, c = gets.split.map(&:to_i)
low, high = 0, (n - 1) * 2
while low < high
    middle = (low + high) / 2
    if solve(n, x, y, middle) >= c
        high = middle
    else
        low = middle + 1
    end
end
p high


n=gets.to_i
s=gets.to_s
p=s.chomp.split("")
x=1;
10000.times do
  x*=10;
end
dp = Array.new(100,x)
dp[0]=0;
y=p.size.to_i
for i in 0..y-1 do
  tmp=0
  j=i
  while j<y&&tmp*10+p[j].to_i<n do
    tmp=tmp*10+p[j].to_i
    dp[j+1]=[dp[j+1],dp[i]*n+tmp].min
    if p[i].to_i == 0
      break
    end
    j+=1
  end
end
puts dp[y]


 notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "B", "H"]

 x,y,z = gets.split(" ")

  arr = [notes.index(x),notes.index(y),notes.index(z),notes.index(x)+12,notes.index(y)+12,notes.index(z)+12].sort

ans = "strange"
(0..arr.length - 3).each do |i|
	x_ind = arr[i]
	y_ind = arr[i+1]
	z_ind = arr[i+2]
	if (y_ind - x_ind == 4 && z_ind - y_ind == 3)
	 	ans = "major"
	elsif (y_ind - x_ind == 3 && z_ind - y_ind == 4)
	 	ans = "minor"
	end

end

 puts ans

 # h d# f#
 # h d f#


k = gets.to_i
if k > 36
  puts -1
else
  puts '8'*(k/2)+'4'*(k%2)
end


def binpow(a,n,m)
  return 1%m if n == 0
  if n%2 == 0
    b = binpow(a,n/2,m)
    return (b*b)%m
  end
  return (a*binpow(a,n-1,m))%m
end
n,m = gets.split.map &:to_i

puts (binpow(3,n,m)-1)%m


n, k = gets.chomp.split(" ").map(&:to_i)
ans = 1;(ans +=1; k/=2;) while(k%2==0);
p ans


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

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

thetime1 = time1[0]*60+time1[1]
thetime2 = time2[0]*60+time2[1]

ave = (thetime1+thetime2)/2

def pad(i)
	return i.to_s if(i>9)
	return "0"+i.to_s
end

puts pad(ave/60) + ":" + pad(ave%60)


class Solver
	def main
		n = gets.to_i
		p = []
		n.times do
			p << Hash[[:x, :y].zip(gets.split.map{ |x| x.to_i })]
		end
		if n == 1 then
			puts -1
		elsif n == 2 then
			if p[0][:x] == p[1][:x] || p[0][:y] == p[1][:y] then
				puts -1
			else
				puts (p[0][:x] - p[1][:x]).abs *
					(p[0][:y] - p[1][:y]).abs
			end
		else
			x = p.map{ |poi| poi[:x] }.uniq
			y = p.map{ |poi| poi[:y] }.uniq
			puts (x[1] - x[0]).abs * (y[1] - y[0]).abs
		end
	end
end

Solver.new.main


class BallSeq
  attr_accessor :color, :count
  def initialize(color)
    @color = color
    @count = 1
  end
  def to_s()
    @color + " " + @count.to_s
  end
end

class Solution
  def initialize()
    @n = gets.to_i
    @s = gets.chomp!
    @st = []
  end
  def solve()
    result = 0
    @st << BallSeq.new(@s[0])
    (1...@s.size).each do |i|
      c = @s[i]
      if c == @st.last.color
        @st.last.count += 1
      else
        @st << BallSeq.new(c)
      end
    end
    while @st.size > 1 do
      bseq = @st.shift
      if bseq.color == 'R'
        result += (1 << bseq.count)
        if @st.first.count > 1
          @st.first.count -= 1
          bseq.count += 1
        else
          @st.shift
          below = @st.shift
          bseq.count += (below.nil?? 0 : below.count) + 1
        end
        @st.unshift(bseq)
      else
        result += (1 << bseq.count) - 1
        @st.first.count += bseq.count
      end
    end
    if @st.first.color == 'B'
      result += (1 << @st.first.count) - 1
    end
    puts result
  end
end

solution = Solution.new
solution.solve


r,c = gets.split(" ").map(&:to_i)
matrix = []
r.times {
  matrix << gets.chomp.split("")
}

# puts "#{matrix}"
straw_row = []
straw_col = []
matrix.each_with_index do |row,i|
  row.each_with_index do |val, j|
    if val == "S"
      straw_row << i
      straw_col << j
    end
  end
end
# puts "#{straw_col} #{straw_row}"
rows = (0..r-1).to_a
cols = (0..c-1).to_a
rem_rows = rows - straw_row
rem_cols = cols - straw_col
res = []
r.times{
  res << [false] * c
}
rem_rows.each{ |i|
  (0..c-1).each {|j|
    res[i][j] = true
  }

}

rem_cols.each{ |j|
  (0..r-1).each {|i|
    res[i][j] = true
  }

}

puts "#{res.flatten.count(true)}"


n,k,*a=$<.read.split.map &:to_i
s=a.reduce :+
l=[0]*k
n.times{|i|l[i%k]+=a[i]}
p [(s-l.max).abs,(s-l.min).abs].max


s = gets
t = gets
a = [0]
n = s.size
(0...n).each do |i|
  (i...n).each do |j|
    cur = 0
    (0...n).each do |k|
      next if i <= k and k <= j
      cur += 1 if cur < t.size and t[cur] == s[k]
    end
    a << j - i + 1 if cur == t.size
  end
end
puts a.max


#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,b = inp
if(a==b)
  puts "#{a}0 #{b}1"
elsif(a == b-1)
  puts "#{a}9 #{b}0"
elsif(a == 9 and b == 1)
  puts "9" + " " + "10"
else
  puts -1
end


coin_count = gets.to_i
coins = gets.split(' ').map(&:to_i)

pockets = 0
coin_counts = Hash.new {|h, k| h[k] = 0}

coins.each do |c|
    coin_counts[c] += 1
    pockets = [pockets, coin_counts[c]].max
end

puts pockets


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

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

found = false

for position in 1..1000000
  a = a * 10 if a < b
  if ( a / b ).to_i == c
    print position.to_s + "\n"
    found = true
    break
  end
  a = a % b
end

print "-1\n" if not found


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

as_max = as.max

e = as.inject(:+)
aw = as.map { |a| as_max - a }.inject(:+)
ans = -1
(as_max..10000).each do |a|
  if aw + (a-as_max)*n > e
    ans = a
    break
  end
end
puts ans


n =gets.to_s.chomp
a = n.count("4")
b = n.count("7")

if a > b or ((b == a) and b !=0 and a!=0)
    puts 4
elsif b > a
    puts 7
elsif b == 0 and a == 0
    puts -1
end


Mod = (10**9)+7

def solve n,m,k
  if n == k
    ans = 1
    for i in 0 ... ((n+1)/2)
      ans = ans * m
      ans = ans%Mod
    end
    ans
  elsif k == 1 || n < k
    ans = 1
    for i in 0 ... n
      ans = ans * m
      ans = ans % Mod
    end
    ans
  elsif k%2 == 1
    (m*m)%Mod
  elsif k%2 == 0
    m
  end
end

while line = gets
  a = line.split
  puts solve(a[0].to_i,a[1].to_i,a[2].to_i)
end


#!/usr/bin/ruby

a = gets.chomp

b = "hello"

countA = 0
dem = 0

for i in (0..(a.length-1)) do
    if a[i] == b[countA]
        countA += 1
        dem += 1
    end
end
if dem >= 5
    puts "YES"
else
    puts "NO"
end


def get_paginate(page_count, current_page, proper)
  prev_numbers = []
  index = 1
  proper.times.each do
    number = current_page - index
    break if number.eql?(0)

    prev_numbers << number
    index += 1
  end
  next_numbers = []
  index = 1
  proper.times.each do
    number = current_page + index
    break if number > page_count

    next_numbers << number
    index += 1
  end
  prev_simbol = nil
  prev_simbol = '<<' if !prev_numbers.empty? && !prev_numbers.min.eql?(1)
  next_simbol = nil
  next_simbol = ' >>' if !next_numbers.empty? && !next_numbers.last.eql?(page_count)
  puts generate_paginate(prev_simbol, next_simbol, prev_numbers, next_numbers, current_page)
end

def generate_paginate(prev_simbol, next_simbol, prev_numbers, next_numbers, current_number)
  paginate_string = ''
  paginate_string += prev_simbol unless prev_simbol.nil?
  prev_numbers.sort.each do |number|
    paginate_string += " #{number}"
  end
  paginate_string += " (#{current_number})"
  next_numbers.sort.each do |number|
    paginate_string += " #{number}"
  end
  paginate_string += next_simbol unless next_simbol.nil?
  paginate_string.strip
end

input = gets.chomp

intput_array = input.split(' ').map(&:to_i)

get_paginate(intput_array[0], intput_array[1], intput_array[2])


code = gets
keys = Hash.new
(0..9).each { |index| keys[gets.chop] = index }

pass = ""
code.scan(/\d{10}/).each { |key| pass += keys[key].to_s }
puts pass


board = Array.new
3.times do
  board << gets.split(//)
end
fl = false
sl = false
fc = 0
sc = 0
0.upto(2) do |i|
  0.upto(2) do |j|
    if board[i][j]=="X"
      fc+=1
    elsif board[i][j]=="0"
      sc+=1
    end
  end
  if board[i][0]==board[i][1] and board[i][1]==board[i][2]
    if board[i][0]=="X"
      fl = true
    elsif board[i][0]=="0"
      sl = true
    end
  end
  if board[0][i]==board[1][i] and board[1][i]==board[2][i]
    if board[0][i]=="X"
      fl = true
    elsif board[0][i]=="0"
      sl = true
    end
  end
end
if board[0][0]==board[1][1] and board[1][1]==board[2][2]
  if board[0][0]=="X"
    fl = true
  elsif board[0][0]=="0"
    sl = true
  end
end
if board[2][0]==board[1][1] and board[1][1]==board[0][2]
  if board[2][0]=="X"
    fl = true
  elsif board[2][0]=="0"
    sl = true
  end
end
if fc==sc
  if fl
    puts "illegal"
  elsif sl
    puts "the second player won"
  else
    puts "first"
  end
elsif fc==sc+1
  if sl
    puts "illegal"
  elsif fl
    puts "the first player won"
  else
    if fc+sc==9
      puts "draw"
    else
      puts "second"
    end
  end
else
  puts "illegal"
end


k = gets.to_i - 1
(1..100).each do |d|
    all = d * 9 * 10**(d-1)
    if k >= all
        k -= all
    else
        num = 10**(d-1) + k/d
        puts num.to_s[k%d]
        exit
    end
end


#!/usr/bin/ruby
require 'set'
require 'scanf'

j0, j1 = scanf("%d %d").map(&:to_i)

minutes = 0
j0, j1 = j1, j0 if j0 > j1
while j0 >= 1 && j1 >= 2
  j0 += 1
  j1 -= 2

  j0, j1 = j1, j0 if j0 > j1
  minutes += 1
end

puts minutes


s = gets.chomp.split(' ')
n = s[0].to_i
b = s[1].to_i
p = s[2].to_i

x = 0
y = n*p
while(n/2>0)
        x = x + (b*2+1)*(n/2)
        n = n/2 + n%2
end
puts x.to_s + " " + y.to_s


shift = gets.chomp
m = gets.chomp
message = m.split("")

keyboard = ['q','w','e','r','t','y','u','i','o','p','[',']','a','s','d','f','g','h','j','k','l',';','z','x','c','v','b','n','m',',','.','/']

new_message = []
if shift == "R"
	for i in (0..message.size-1)
		new_message[i] = keyboard[keyboard.index(message[i])-1]
	end
else
	for i in (0..message.size-1)
		new_message[i] = keyboard[keyboard.index(message[i])+1]
	end
end

for i in (0..message.size-1)
	print new_message[i]
end


h, m = gets.chomp.split(":").map do |s|
  s.sub(/^0+(.)/, '\1').bytes.to_a.map do |s|
    if s <= 57
      s - 48
    else
      s - 55
    end
  end
end

if h.size == 1 && m.size == 1 && h.first < 24 && m.first < 60
  puts -1
  exit
end

def cand(a, n)
  sum = 0
  a.reverse.each_with_index do |i, index|
    sum += i * (n ** index)
  end
  sum
end

hh = []
mm = []
(2..60).each do |n|
  hh << n if h.all?{|i| i < n} && cand(h, n) < 24
  mm << n if m.all?{|i| i < n} && cand(m, n) < 60
end
r = hh & mm
puts r.empty? ? 0 : r.join(" ")
exit


n = gets.chomp.to_i

puts (n / 2520).to_i


def solve(str)
  x,m = str.split.map{|x| x.to_i}
  data = []
  t = 0
  loop do
    t += 1 if x > m
    d = x % m
    if d.zero?
      puts 'Yes'
      return
    end
    x = x + d
    if data.include?(d) || t>20
      puts 'No'
      return
    else
      data << d
    end
    #puts "x:#{x} d:#{d} m:#{m}"
  end
end

puts solve(gets)


a, b=gets.split
a+=b
i=1
i+=1 while a[i] && a[i]<b[0]
puts a[0..i-1]+b[0]


s = gets.strip
nxt = 'a'
count = Array.new(26, 0)
valid = true
s.each_char do |c|
    if c == nxt
        count[c.ord - 'a'.ord] += 1
        nxt = (nxt.ord + 1).chr
    else
        if count[c.ord - 'a'.ord] == 0
            valid = false
            break
        end
    end
end
if !valid
    puts "NO"
else
    puts "YES"
end


a, b, c = gets.split.map(&:to_f)
if c==0 and a==b
	puts "YES"
elsif c==0 and a!=b
	puts "NO"
else
	factor = (b-a)/c
	if factor == factor.to_i and factor >= 0
		puts "YES"
	else
		puts "NO"
	end
end


hash = {}
1.upto(100000) do |i|
  hash[(i * (i + 1)) / 2] = true
end
n = gets.to_i
hash.each do |k, v|
  break if k >= n
  if hash[n - k]
    puts "YES"
    exit
  end
end
puts "NO"


n, k = gets.split.map(&:to_i)
if k > 43
  puts "No"
  exit 0
end
puts (1..k).to_a.map{|x| n % x}.uniq.size == k ? "Yes" : "No"


n,m=gets.split.map &:to_i;x=gets.to_i-1
p [n,m].min>2*x ?[n+m-4*x-2,1].max: 0


class Solver
	def main
		n = gets.to_i
		arr = gets.split.map { |x| x.to_i }

		ans = 1
		last = nil
		arr.each.with_index do |v, id|
			if v == 1
				ans *= (id - last) if last != nil
				last = id
			end
		end
		ans = 0 if arr.count(1) == 0
		puts ans
	end
end
Solver.new.main