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

f = [a + b, b + d, d + c, c + a]
max = f.max
min = f.min
diff = max - min

if diff > n - 1
	puts 0
else
	puts n * (n - 1 - diff + 1)
end


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

ans = 0
for nw in 1..n
  ne = nw + b - c
  if ne < 1 || n < ne
    next
  end
  sw = nw + a - d
  if sw < 1 || n < sw
    next
  end
  se = nw + a + b - c - d
  if se < 1 || n < se
    next
  end
  ans += 1
end

ans *= n

puts ans


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


#!/usr/bin/ruby

k, b, n, t = STDIN.readline.split.map {|s| s.to_i }
x, m = 1, n
while t >= x and m != -1
	x = k*x + b
	m -= 1
end
puts m+1


l,r,x,y,k=gets.split.map &:to_i
l+=k-1
l/=k
r/=k
puts l>r||x>r||l>y ?"NO":"YES"


l,r,x,y,k=gets.split.map &:to_i
puts (l=(l+k-1)/k)>(r/=k)||x>r||l>y ?"NO":"YES"


s = gets.chomp
if s == s[0] * s.length
    puts "0"
else
    puts "#{s.length - (s == s.reverse ? 1 : 0)}"
end


def f(v, a, b)
  v<<b if a>0
  f v,a+1,b*10+4 if a<10
  f v,a+1,b*10+7 if a<10
end
k,r = [],0
f(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]
        r+=([b,k[i]].min-a+1)*k[i]
        a=k[i]+1
    end
end
puts r


def generate_lucky_seq(n)
  r = [p = ['4', '7']]
  (n - 1).times {
    a = r.last
    w = []
    p.each { |b|
      a.each { |x|
        w << b + x
      }
    }
    r << w
  }
  r.flatten.map { |x| x.to_i }
end

lucky_seq = generate_lucky_seq(9) << 4_444_444_444

a, b = gets.split.map { |x| x.to_i }
prev = a
ind = nil
lucky_seq.each_with_index { |x, i|
  if x >= a
    ind = i
    break
  end
}

sum = 0
loop do
  if lucky_seq[ind] < b
    sum += lucky_seq[ind] * (lucky_seq[ind] - prev + 1)
    prev = lucky_seq[ind] + 1
    ind += 1
  else
    sum += lucky_seq[ind] * (b - prev + 1)
    break
  end
end

puts sum


#$stdin.reopen('/home/chen/Desktop/input.txt', 'r')

gene=gets
size = gene.size

i,j,s,ans=0,1,1,0

while j<size
	if gene[j] == gene[i]
		s+=1
	else
		if s%2==0
			ans+=1
		end
		i=j
		s=1
	end
	j+=1
end

if s%2==0; ans+=1; end

puts ans


def read_time
  gets.chomp.split(?:).map{ |s| s.to_i }
end

def time2mins(h, m)
  h * 60 + m
end

def mins2time(m)
  [m / 60, m % 60]
end

def padnumber(n)
  n.to_s.rjust(2, ?0)
end

def render(z)
  h, m = z
  "#{padnumber(h)}:#{padnumber(m)}"
end

h1, m1 = read_time
h2, m2 = read_time

t1 = time2mins(h1, m1)
t2 = time2mins(h2, m2)

tm = (t1 + t2) / 2

puts render(mins2time(tm))


   s1 =  gets.chomp.to_s.split(":")
    s2 = gets.chomp.to_s.split(":")
    ans = (s1[1].to_i + (s1[0].to_i)*60 + s2[1].to_i + (s2[0].to_i)*60)/2
    hour = (((ans)/60).to_i).to_s
    min = (ans%60).to_s

    if hour.length < 2
      hour = "0" + hour
    end
    if min.length < 2
      min = "0" + min
    end
    ans = ( hour + ":" + min)
    puts 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)


gets.chomp.split('').map { |x| x.to_i }.reverse.each { |x|
  left = x < 5 ? 'O-' : '-O'
  m = x % 5
  right = 'O' * m + '-' + 'O' * (4 - m)
  puts left + '|' + right
}


n = gets.chomp.to_i

def draw(i)
  str = ""
  if i >= 5
    str = "-O|"
  else
    str = "O-|"
  end

  (i % 5).times do
    str += "O"
  end

  str += "-"
  (4 - (i % 5)).times do
    str += "O"
  end
  puts str
end

if n == 0
  draw(n)
end

while n != 0
  draw(n % 10)
  n /= 10
end


n = gets.chomp
rep = {0 => 'O-|-OOOO',
 1 => 'O-|O-OOO',
 2 => 'O-|OO-OO',
 3 => 'O-|OOO-O',
 4 => 'O-|OOOO-',
 5 => '-O|-OOOO',
 6 => '-O|O-OOO',
 7 => '-O|OO-OO',
 8 => '-O|OOO-O',
 9 => '-O|OOOO-'
}

arr = []
n.each_char do |c|
	arr << rep[c.to_i]
end
arr.reverse!
arr.each do |a|
	puts a
end


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

pos = []
arr.each_with_index do |value, index|
    if 1 == value
        pos.push index
    elsif n == value
        pos.push index
    end
end

p [pos[1], n - pos[0] - 1].max


n = 0
nums = Array.new

biggest = 0
smallest = 100

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

#p nums
#puts n
#puts nums.last

for i in 0..n
	#nums.push($stdin.read.chomp.to_i)
	#thing = gets.chomp.split('|')[1].scan(/\d+/).map{|n| n.to_i}
	if n == nums[i]
		biggest = i + 1
	end
	if 1 == nums[i]
		smallest = i + 1
	end
end

#puts "Biggest: #{biggest}, smallest: #{smallest}\n\n"

puts [n - [smallest, biggest].min, [smallest, biggest].max - 1].max

=begin
7
1
6
5
3
4
7
2

6
6
5
4
3
2
1

3
2 3 1

=end


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

if n <= 3
  puts n - 1
else
  i = as.index(1)
  j = as.index(n)
  ans = (i - j).abs
  ans = [ans, n - 1 - [i, j].min].max
  ans = [ans, [i, j].max].max
  puts ans
end


n = gets.to_i
m = gets.to_i

arr = []
n.times {arr.push gets.to_i}

max = arr.max
sum = arr.inject(:+)

if n==1
   print "#{arr[0]+m} #{arr[0]+m}\n"
   exit
end

if max*n>(m+sum)
  print "#{max} "
else
  ans = max+(m-(max*n-sum))/n
  ans += 1 unless (m-(max*n-sum))%n==0
  printf "#{ans} "
end

puts arr.max+m


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}"


n = gets.chomp.to_i
m = gets.chomp.to_i
a = []

n.times.each do |_|
	a << gets.chomp.to_i
end

puts "#{[(((a.reduce(&:+) + m) * 1.0)/n).ceil, *a].max} #{a.max + m}"


#!/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


# http://codeforces.com/contest/520/problem/B
class StrangeDevice
  def initialize(n, m)
    @m = m
    @array = [n]
    @memo = { n => true }
  end

  def minimum_times
    t = 0
    until @array.include?(@m)
      operate
      t += 1
    end

    t
  end

  def self.minimum_times(n, m)
    new(n, m).minimum_times
  end

  private

  def operate
    @array = [].tap do |out|
      @array.each do |a|
        out << a * 2 if a < @m && !@memo.key?(a * 2)
        out << a - 1 if a > 1 && !@memo.key?(a - 1)
      end

      out.each { |a| @memo[a] = true }
    end
  end
end

n, m = gets.chomp.split.map(&:to_i)
puts StrangeDevice.minimum_times(n, m)


#
# require 'pry'
n,m = gets.chomp.split(' ').map(&:to_i)

x = Math.log2(m.to_f/n).ceil
x = 0 if x < 0

need = (2**x)*n - m

result=x

x.downto(1) do |i|
	x = need.to_i/2**i
	need-=x*2**i
	result+=x
	break if need == 0
end if x>0

print result+need


#!/usr/bin/env ruby

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

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

		step+=1
	end

	puts step + (n-m)
end


a,b = gets.split.map{|w| Integer(w) rescue w};c=0
while (a<b) do
  b=if(b%2==1) then b+1 else b/2 end;c+=1
end
puts c+a-b.abs


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

N = 100000
vis = Array.new(N)
vis[n] = 0

queue = [n]
while !queue.empty?
	x = queue.pop
	if x > 0 and !vis[x - 1]
		vis[x - 1] = vis[x] + 1
		queue.unshift(x - 1)
	end
	if x * 2 < N and !vis[x * 2]
		vis[x * 2] = vis[x] + 1
		queue.unshift(x * 2)
	end
end
puts vis[m]


#!/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


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

n, m = gets.split.map &:to_i
t = 0
while n < m do
  m = ((m % 2 == 1) ? m + 1 : m / 2)
  t += 1
end
puts t + (n - m).abs


n, m = gets.chomp.split(' ').map(&:to_i)
visited = Hash.new
visited[n] = 1
q = Queue.new
q.push(n)

while(!q.empty?)
	f = q.pop
	if visited[f*2].nil? && f < m
		if f*2 == m
			print visited[f]
			break
		end
		visited[f * 2] = visited[f] + 1
		q.push(f * 2)
	end

	if visited[f - 1].nil? && f > 1
		if f - 1 == m
			print visited[f]
			break
		end
		visited[f - 1] = visited[f] + 1
		q.push(f - 1)
	end
end


data = gets.chomp.split

a = data[0].to_i
b = data[1].to_i

n=0

if b<a
	n=a-b
else
	while b!=a
		if b>a
			if b%2!=0
				b+=1
				n+=1
			else
				b/=2
				n+=1
			end
		else
			k=a-b
			b+=k
			n+=k
		end
	end
end

puts n


# http://codeforces.com/contest/520/problem/B
class StrangeDevice
  def initialize(n, m)
    @m = m
    @array = [n]
    @memo = { n => true }
  end

  def minimum_times
    t = 0
    until @array.include?(@m)
      operate
      memonize
      t += 1
    end

    t
  end

  def self.minimum_times(n, m)
    new(n, m).minimum_times
  end

  private

  def memonize
    @array.each { |a| @memo[a] = true }
  end

  def operate
    @array = [].tap do |out|
      @array.each do |a|
        out << a * 2 if a < @m && !@memo.key?(a * 2)
        out << a - 1 if a > 1 && !@memo.key?(a - 1)
      end
    end
  end
end

n, m = gets.chomp.split.map(&:to_i)
puts StrangeDevice.minimum_times(n, m)


#!/usr/bin/ruby
class Array
  def sum
    ret=0
    self.length.times{|i| ret+=self[i]}
    return ret
  end
end

a=Array.new(8)
8.times{|i|
  a[i]=gets.chomp.unpack("C*").map!{|i|i-=87}
}
m=M=0
8.times{|i|
  if a[i].sum==-168 then m+=1 end
}
if m==8 then puts 8; exit end
8.times{|i|
  if a.transpose[i].sum==-168 then M+=1 end
}
puts m+M


n = 0
r = []
8.times do |i|
    s = gets.chomp
    if !s.include? "W" then
        n += 1
    elsif k = s.index("B") then
        while k do
            if !r.include? k then
                r << k
                n += 1
            end
            k = s.index("B", k+1)
        end
    end
end

puts n


a=[]
8.times{
    a.push(gets.split[0])
}
res=0
8.times{|i|
    if a[i]=="BBBBBBBB" then
        res+=1
    end
    ok=1
    8.times{|j|
        if a[j][i]!="B" then
            ok=0
        end
    }
    res+=ok
}
res=res==16 ? 8 : res
puts res


d=gets.to_i
if  d>=-128 and d<=127 then puts 'byte'
elsif d>=-32768 and d<=32767 then puts 'short'
elsif d>=-2147483648 and d<=2147483647 then puts 'int'
elsif d>=-9223372036854775808 and d<=9223372036854775807 then puts 'long'
else puts 'BigInteger'
end


a,b=gets.split;a=a.to_i+1;a+=1 until a.to_s.gsub(/[^47]/,'')==b;p a


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


points = 8.times.map{|i| gets.split.map(&:to_i) }.uniq
puts [:first, :last].all?{|sym| points.group_by(&sym).to_a.sort_by(&:first).map{|x| x.last.length} == [3,2,3] } ? "respectable" : "ugly"


def runb(list)
  x = list.map{|x,y| x}.uniq.sort
  y = list.map{|x,y| y}.uniq.sort

  return false unless x.size == 3
  return false unless y.size == 3
  x.each_with_index do |x,i|
    y.each_with_index do |y,j|
      if (i == j) and (j == 1)
        return false if list.member?([x,y])
      else
        return false unless list.member?([x,y])
      end
    end
  end
  return true
end

def run(list)
  runb(list) ? "respectable" : "ugly"
end

def convert(n)
  n.split(' ').map(&:to_i)
end

n = gets
list = []
while n != nil
  list << convert(n)
  if list.size == 8
    puts run(list)
    list = []
  end
  n = gets
end

#0 0
#2 1
#1 0
#0 2
#2 2
#1 0
#2 1
#0 2


def solve(n,k)
        big=n;small=k
        a=0
        while big!=1||small!=1
                t=big/small
                if big%small==0 then t-=1 end
                a+=t
                big-=t*small
                if big<small then
                        big,small=small,big
                end
        end
        a
end
# 最後の数字を家庭する
n=gets.to_i
ans=99999999

for i in 1..(n+1)/2
        if n.gcd(i)!=1 then next end
        ans=[ans,solve(n,i)].min
        #p [n,i,solve(n,i)]
end
p ans


n=gets.to_i
ans=n-1
2.upto(n/2){|a|
	k=0
	b=n
	until a==b
		d=(b-a-1)/a+1
		k+=d
		b-=a*d
		a,b=b,a
	end
	ans=k if (b==1)&&(k<ans)
}
p ans


#!/usr/local/rvm/rubies/ruby-2.3.0/bin/ruby

class Task1
  attr_accessor :phases, :n, :result

  def initialize()
    @n = 0
    @phases = []
    @result = []
  end

  def getData()
    tmp = []
    $stdin.each { |x| (x!="\n") ? tmp.push(x.chomp.split.map { |y| y.to_i }) : nil }
    @n = tmp[0][0]
    @phases = tmp[1]
  end

  def getFileData()
    tmp = []
    file = File.new("test.txt","r")
    file.each { |x| (x!="\n") ? tmp.push(x.chomp.split.map { |y| y.to_i }) : nil }
    file.close
    @n = tmp[0][0]
    @phases = tmp[1]
  end

  def getResult()
    if @phases[@n-1]==0
      puts "UP"
    elsif @phases[@n-1]==15
      puts "DOWN"
    elsif @n==1
      puts -1
    elsif @phases[@n-1]==14 && @phases[@n-2]==15
      puts "DOWN"
    elsif @phases[@n-1]>@phases[@n-2]
      puts "UP"
    elsif
      puts "DOWN"
    end

  end

  # def putsResult()
  #   puts @result.join(' ')
  # end

  def run()
    getData
    # getFileData
    getResult
    # putsResult
  end

end
if __FILE__ == $0
  pc = Task1.new
  pc.run
end


n = gets.to_i
arr = gets.split.map(&:to_i)
if arr[-1] == 15
    print "DOWN"
elsif arr[-1] == 0
    print "UP"
elsif n == 1
    print "-1"
elsif arr[-1] > arr[-2]
    print "UP"
else
    print "DOWN"
end


n = gets.chomp.to_i
moon = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1]
records = gets.chomp.split(' ').map(&:to_i)

if records.length <= 1

	if records[0] != 0 && records[0] != 15
		puts -1
		exit
	end

	puts 'UP' if records[0] == 0
	puts 'DOWN' if records[0] == 15
	exit
end

startM = 0
nextM = 0

for i in (0...(moon.length - 1))
	if records[records.length - 2] == moon[i] && records[records.length - 1] == moon[i + 1]
		startM = i
		nextM = i + 1
		break
	end
end

if (moon[startM] > moon[nextM] && moon[nextM] != 0) || moon[nextM] == 15
	puts 'DOWN'
else
	puts 'UP'
end


POSSIBLES = [
  [[1, 2], [18, 20], [11, 12], [13, 15]],
  [[3, 4], [17, 19], [9, 10], [14, 16]],
  [[2, 4], [6, 8], [10, 12], [21, 23]],
  [[1, 3], [5, 7], [9, 11], [22, 24]],
  [[13, 14], [5, 6], [17, 18], [21, 22]],
  [[15, 16], [7, 8], [19, 20], [23, 24]],
]

FACES = [
  (1..4).to_a,
  (5..8).to_a,
  (9..12).to_a,
  (13..16).to_a,
  (17..20).to_a,
  (21..24).to_a,
]

def check_solved(c)
  FACES.each do |face|
    return false unless face.map { |f| c[f] }.uniq.size == 1
  end
  true
end

def solve(cube)
  # [[[2, 4], [6, 8], [10, 12], [21, 23]]].each_with_index do |possib|
  POSSIBLES.each_with_index do |possib|
    face_colors = possib.map { |p| cube[p.first] == cube[p.last] }
    next if face_colors.include?(false)
    colors = possib.map { |p| cube[p.first] }
    [possib.rotate(1), possib.rotate(-1)].each do |rot|
      c = cube.dup
      rot.each_with_index do |curr, i|
        c[curr.first] = colors[i]
        c[curr.last] = colors[i]
      end
      if check_solved(c)
        return "YES"
      end
    end
  end
  return "NO"
end

cube = {}
vals = gets.strip.split.map(&:to_i)

vals.each_with_index do |v, i|
  cube[i + 1] = v
end

puts solve(cube)


def judge(cube)
    6.times do |i|
        if !(cube[4 * i] == cube[4 * i + 1] && cube[4 * i + 1] == cube[4 * i + 2] && cube[4 * i + 2] == cube[4 * i + 3])
            return false
        end
    end
    return true
end

a1 = [0,2,4,6,8,10,23,21]
b1 = [1,3,5,7,9,11,22,20]
a2 = [12,13,4,5,16,17,20,21]
b2 = [14,15,6,7,18,19,22,23]
a3 = [2,3,16,18,9,8,15,13]
b3 = [0,1,17,19,11,10,14,12]

cube = gets.split.map(&:to_i)
ans = false

tmp = Array.new(a1)
tmp.rotate!(2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[a1[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(b1)
tmp.rotate!(2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[b1[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(a2)
tmp.rotate!(2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[a2[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(b2)
tmp.rotate!(2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[b2[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(a3)
tmp.rotate!(2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[a3[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(b3)
tmp.rotate!(2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[b3[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(a1)
tmp.rotate!(-2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[a1[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(b1)
tmp.rotate!(-2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[b1[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(a2)
tmp.rotate!(-2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[a2[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(b2)
tmp.rotate!(-2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[b2[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(a3)
tmp.rotate!(-2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[a3[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

tmp = Array.new(b3)
tmp.rotate!(-2)
cube2 = Array.new(cube)
8.times do |i|
    cube2[b3[i]] = cube[tmp[i]]
end
ans |= judge(cube2)

puts ans ? "YES" : "NO"


n, k = gets.split
n = n.to_i
k = k.to_i

d = n/(2*(k+1))
c = d * k

others = n - (c + d)

puts "#{d} #{c} #{others}"


n = gets.to_i
ans = 0
len = 1
base = 10
while true
    if n < base then
        ans += (n - base / 10 + 1) * len
        break
    else
        ans += base / 10 * 9 * len
    end
    len += 1
    base *= 10
end
puts ans


a=gets.chomp
l=a.length-1
if l==0
puts a
else
ans=9
2.upto l do |i|
ans+= (9*(10**(i-1)))*i
end
ans+=(a.to_i-("9"*l).to_i)*(l+1)
puts ans.inspect
end


LIMIT = 1000000007

@res = []
l = 1
while l < LIMIT
  @res << l
  l = l * 2
end

def power i
  return @res[i] if i < @res.size
  half_power = power(i/2)
  partial = (half_power * half_power) % LIMIT
  if i % 2 == 1
    partial = (partial * 2) % LIMIT
  end
  partial
end

years = gets.to_i

if years == 0
  puts 1
else
  partial = power(years-1)
  puts (partial * (((2 * partial) % LIMIT) + 1)) % LIMIT
end

# 2^(n-1) * (2^n +1)


$p = 1000000007
def mul(a,b)
  n = a.size
  c = Array.new(n){Array.new(n){0}}
  n.times do |i|
    n.times do|j|
      n.times do |k|
        c[i][j] += a[i][k] * b[k][j]
        c[i][j] %= $p
      end
    end
  end
  c
end

def po(m)
  e = [[3,1],[1,3]]
  ret = [[1,0],[0,1]]

  while m > 0
    if m % 2 == 1
      ret = mul(ret,e)
    end
    e = mul(e,e)
    m /= 2
  end

  ret
end

def work(n)
    if n == 1
      puts 3
    else
      ret = po(n)
      ans = ret[0][0]
      puts ans % $p
    end
end

n = gets.to_i
work n
#10.times{|x| work x+1}


$p = 1000000007
def mul(a,b)
  n = a.size
  c = Array.new(n){Array.new(n){0}}
  n.times do |i|
    n.times do|j|
      n.times do |k|
        c[i][j] += a[i][k] * b[k][j]
        c[i][j] %= $p
      end
    end
  end
  c
end

def po(m)
  e = [[3,1],[1,3]]
  ret = [[1,0],[0,1]]

  while m > 0
    if m % 2 == 1
      ret = mul(ret,e)
    end
    e = mul(e,e)
    m /= 2
  end

  ret
end

def work(n)
    if n == 1
      puts 3
    else
      ret = po(n)
      ans = ret[0][0]
      puts ans % $p
    end
end

n = gets.to_i
work n


def pow(a,k)
  n = 1000000007
  b = 1
  while (k!= 0) do
    if (k % 2 == 0 ) then
      k/=2
      a = (a*a) % n
    else
      k-=1
      b = (b*a) % n
    end
  end
  return b
end

n = gets.to_i
k = pow(2,n)
k = (k*(k-1)/2) % 1000000007
if (n == 0) then
  puts "1"
else
  ans = (pow(4,n) - k) % 1000000007
  puts ans
end


angles = gets.to_i
puts (angles - 2) * (angles - 2)


#!/usr/bin/env ruby

N = gets.to_i

def total_sections
  return 1 if N == 3
  return 4 if N == 4

  sections_without_2_triangles = (3..N-2).map do |second_vertice|
    third_vertice = second_vertice + 1

    lines_from_second = N - second_vertice - 1
    lines_from_third = third_vertice - 3

    lines_from_second + lines_from_third + 1
  end.inject(:+)

  sections_without_2_triangles + (N-2)*2
end

puts total_sections


n = gets.to_i
begin
  puts n%3 == 0 ? n/3 * 2 : n/3 * 2 + 1
rescue
end


n = gets.to_i
cnt = (n / 3) * 2
res = n % 3
cnt += 1 if res >= 1
puts cnt


n = readline.to_i
ct = n / 3
ct *= 2
if n % 3 != 0
  ct += 1
end
puts ct


# start from reverse and count till number_of_zeros == k
n, k = gets.split(' ')
k = k.to_i
num_of_zeros = 0
digit_removed = 0
success = false
n.reverse.split('').each do |a|
  if a == '0'
    num_of_zeros += 1
  else
    digit_removed += 1
  end

  if num_of_zeros == k
    success = true
    break
  end
end

if success
  puts digit_removed
else
  puts n.length - 1
end


n, k = gets.chomp.split(" ")
k = k.to_i

zeros = answer = 0
for i in (n.length - 1).downto( 0 )
    if n[ i ] == "0"
        zeros += 1
    else
        answer += 1
    end
    break if zeros == k
end

if zeros == k
    puts answer
else
    puts ( n.length - 1 )
end


n,k = gets.split
k = k.to_i
if n.count('0') >= k
  output = 0
  zeros_so_far = 0
  n.chars.reverse.each do |c|
    if c == '0'
      zeros_so_far += 1
    else
      output += 1
    end
    break if zeros_so_far == k
  end
  puts output
else
  # have to make zero
  puts n.length - 1
end


#!/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


a,b,c,d=gets.split.map &:to_i
e,f,g,h=gets.split.map &:to_i
$dd=Math.sqrt((a-e)**2+(b-f)**2)
def pf(r,r1,r2)
  return 1 if r1+r<=$dd&&r2+r<=$dd
  return 1 if r1-r>=$dd&&r2-r>=$dd
  return 1 if r-r1>=$dd&&r-r2>=$dd
  return 0
end
p pf(c,g,h)+pf(d,g,h)+pf(g,c,d)+pf(h,c,d)


#!/usr/bin/env ruby

def pow(n)
  n*n
end

class Circle
  attr_accessor :x, :y, :r
  def initialize(x, y, r)
    @x = x
    @y = y
    @r = r
  end

  def include?(other)
    @r >= other.r && pow(@x-other.x) + pow(@y-other.y) <= pow(@r-other.r)
  end

  def collide?(other)
    (not include?(other)) && (not other.include?(self)) && pow(@x-other.x) + pow(@y-other.y) < pow(@r+other.r)
  end

  def in(area)
    area[1].include?(self) and not area[0].include?(self)
  end
end

black_area = []
circles = []
2.times do
  x, y, r1, r2 = gets.split.map(&:to_i)
  c1 = Circle.new(x, y, r1)
  c2 = Circle.new(x, y, r2)
  circles.push(c1, c2)
  black_area << [c1, c2]
end

cnt = 0
circles.each_with_index do |c1, i|
  valid = circles.all?{|c2| c1==c2 or not c1.collide?(c2)}
  valid = valid && !c1.in(black_area[1-i/2])
  cnt += 1 if valid
end

p cnt


puts gets.chomp.chars.to_a.reduce(Hash.new(0)) {|s, x| s[x] += 1; s }.max_by {|k, v| k}.reduce(:*)


#!/usr/bin/ruby1.9

base = STDIN.readline.strip

def go(prefix, suffix, found)
	if suffix.length == 0
		found.push(prefix) if prefix.reverse == prefix
		return
	end
	go(prefix, suffix[1..-1], found)
	go(prefix+suffix[0], suffix[1..-1], found)
end

found = []
go('', base, found)
puts found.sort[-1]


a,b = gets.split.map(&:to_i)
if b%a != 0
    puts "-1"
    exit
end
ans = 0
b /= a
while b%2 == 0
    ans += 1
    b /= 2
end
while b%3 == 0
    ans += 1
    b /= 3
end
if b == 1
    puts ans
else
    puts "-1"
end


x,y=gets.split.map &:to_i
n=y.to_f/x.to_f
if n.to_i!=n
  puts "-1"
else
  res=0
  while n!=1
    if n%2==0
      n/=2
      res+=1
    elsif n%3==0
      n/=3
      res+=1
    else
      puts "-1"
      exit
    end
  end
  puts res
end


n,m = gets.chomp.split(" ")
n = n.to_i;
m = m.to_i;
div = m / n;
pmoves = true;

unless (m % n == 0)
    puts "-1";
    pmoves = false
end

moves = 0;

while div != 1 && m % n == 0 do
    if div % 2 == 0 then
        moves += 1;
        div /= 2;
    elsif div % 3 == 0 then
        moves += 1;
        div /= 3;
    else
        puts "-1";
        pmoves = false;
        break;

    end
end

if pmoves then
    puts moves
end


x, y = gets.chomp.split(' ').map(&:to_i)
sides = [y, y, y]

ans = 0

until sides.count(x) == 3
    sortedSides = Array.new(sides).sort
    power = x - sortedSides[0]

    power = sortedSides[1] + sortedSides[2] - sortedSides[0] - 1 if power >= sortedSides[1] + sortedSides[2] - sortedSides[0]
    sides[sides.index(sortedSides[0])] = sides[sides.index(sortedSides[0])] + power

    #print sides
    #puts ''

    ans += 1
end

puts ans


x, y = gets.split.map(&:to_i)
a = [y, y, y]
c = 1
loop do
  mx = a.min
  case mx
  when a[0]
    a[0] = [a[1] + a[2] - 1, x].min
  when a[1]
    a[1] = [a[0] + a[2] - 1, x].min
  when a[2]
    a[2] = [a[0] + a[1] - 1, x].min
  end
  break if a == [x, x, x]
  c += 1
end
puts c


def printlol(ar)
  for i in 0..(ar.length-2) do
    print ar[i]
    print " "
  end
  print ar.last
  puts ""
end

input = gets.strip.split(' ').map(&:to_i)
x = input[0]
y = input[1]

lol = [y, y, y]
count = 0
while lol[0] != x or lol[1] != x or lol[2] != x do
  asd = lol.dup
  asd.slice!(lol.index(lol.min))
  top = (asd[0] + asd[1])

  if top - 1 > x
    asd << x
  else
    asd << top - 1
  end

  lol = asd
  count += 1
  #printlol(lol)
end

puts count


def bin_search(arr,e)
	n = arr.length
	l = 0
	r = n - 1

	while l <= r
		m = l + (r-l) / 2
		if arr[m] == e
			return true
		elsif e < arr[m]
			r = m - 1
		else
			l = m + 1
		end
	end

	return false

end

s = gets.to_i
arr = []
(1..s).each do |a|
	val = (a * (a + 1) ) / 2
	arr << val
	break if val > s
end

arr.sort!
ans = false
arr.each do |a|
	if bin_search(arr,s-a)
		ans = true
		break
	end
end

puts ans ? "YES" : "NO"


a=gets.chomp.to_i
trig=0
1.upto(31623) do |i|
temp=a-(i*(i+1))/2
break if temp<=0
if (Math.sqrt(1+8*temp)/2.0-0.5)%1==0
trig=1
break
end
end

if trig == 0
puts "NO"
else
puts "YES"
end


def f(r,x)
	l=1
	while l<r
		m=(l+r)>>1
		return m if m*(m+1)==x
		if m*(m+1)<x
			l=m+1
		else
			r=m
		end
	end
	return -1
end
n=gets.to_i
i,m,flag=1,2*n-2,0
while i*(i+1)<=m
	tmp=f(i+2,2*n-i*(i+1))
	if tmp!=-1
		flag=1
		break
	end
	i+=1
end
puts (flag==1) ? "YES" : "NO"


def gao(n)
    unless $h[n]
        t = 1
        d = 2
        while d * d <= n
            if n % d == 0
                t = [t, gao(d), gao(n / d)].max
            end
            d += 1
        end
        $h[n] = n + t
    end
    return $h[n]
end

$h = {1 => 1}
n = gets.to_i
p gao(n)


def find_div(n)
  sq = Math.sqrt(n).floor
  (2..sq).each do |i|
    next if (n % i) != 0
    return n / i
  end
  1
end

n = gets.to_i
ans = n

while n > 1
  n = find_div(n)
  ans += n
end

puts ans


a, b, c, d, e, f = gets.split(' ').map{|s| s.to_i}
ab, cd, ef = [[a, b], [c, d], [e, f]].map{|aa, bb|bb/aa.to_f}
g = ab*cd*ef
m = [cd.infinite?, ab.infinite?&&cd>0, ef.infinite?&&ab>0&&cd>0]
puts (m.any?||g>1.0) ? 'Ron' : 'Hermione'


a,b,c,d,e,f = gets.split(' ').map(&:to_i)
if (c==0 && d !=0) || (a==0 &&  b !=0 && c*d !=0)
  puts "Ron"
else
  if (a*c*e) < (b*d*f)
    puts "Ron"
  else
    puts "Hermione"
  end
end


n,*a=$<.read.split.map &:to_i
s=a.reduce :+
puts (1<<n).times.any?{|i|t=n.times.select{|j|i[j]>0}.map{|j|a[j]}.reduce 0,:+;(s-2*t)%360==0} ? :YES : :NO


N = gets.to_i
as = [0]
bs = nil
N.times {
  rot = gets.to_i
  bs = as.map{ |a| [(a+rot)%360, (a-rot+360)%360]}.flatten.uniq
  as,bs = bs,as
}
puts as.include?(0) ? "YES" : "NO"


n = gets().to_i
arr = []
n.times do
  arr += [gets().to_i]
end
cur = "0" * n
last = "1" * n
f = false
while (cur.to_i(10) < last.to_i(10))
  d = 0
  arr.each_with_index do |e, ind|
    if cur[ind] == '0'
      d -= e
    else
      d += e
    end
  end
  if (d % 360 == 0)
    f = true
    break
  end
  cur = (cur.to_i(2) + 1).to_s(2)
  # puts cur
  cur = ("0" * (n - cur.size)) + cur
end
if f
  puts "YES"
else
  puts "NO"
end


n = gets.chomp.to_i
days = 0
if n <= 2
    puts "0 #{n}"
elsif n <= 5
    puts "0 2"
elsif n < 7
    puts "#{n - 5} 2"
else
    min_offs = 0
    remaining_days = n
    begin
        days += 7
        min_offs += 2
        remaining_days -= 7
    end while remaining_days >= 7
    max_offs = min_offs
    if remaining_days > 5
        min_offs += remaining_days - 5
        max_offs += 2
    elsif remaining_days < 2
        max_offs += remaining_days
    else
        max_offs += 2
    end
    puts "#{min_offs} #{max_offs}"
end


n = readline.to_i
max, min = 0, 0
max = n / 7
min = n / 7
max *= 2
min *= 2
n %= 7
max += [n, 2].min
min += [0, n - 5].max
print min, " ", max
puts ""


n = gets.to_i
min = n/7*2
max = min
n%=7

if n < 7
	max += n%7 > 2 ? 2 : n%7
	if n%7 == 6
		min += 1
	end
	puts "#{min} #{max}"
end


#!/usr/bin/ruby

def solution(n, arr)
  ans = 0
  m = arr[0]
  arr = arr.slice 1, arr.length
  while arr.any? {|a|a >= m}
    m += 1
    arr.sort!.reverse!
    arr[0]-=1
    ans += 1
  end
  puts ans
end

n = gets.to_i
arr = gets.split(' ').map{|i| i.to_i}
solution n, arr
#
# solution 5, [5,1,11,2,8]
# solution 4, [1,8,8,8]
# solution 2, [7,6]


a=gets.chomp.to_i
b=gets.chomp.split(" ")
lm=b.delete_at(0).to_i
ans=0
0.upto(a-2) {|i|  b[i]=b[i].to_i}
b.sort!
b.reverse!

loop do
trig=0
temp=0
max=b[0]

1.upto(a-2) do|i|
if b[i]>max
temp=i
max=b[i]
end
end

if b[temp]>=lm
ans+=1
lm+=1
b[temp]-=1
trig=1
end
if trig ==0
break
end
end
puts "#{ans}"


u = [0]*10000
a = gets.chomp.to_i
b = gets.chomp.split(' ')
start = b[0].to_i
me = start
mx = 0
b.delete_at(0)
b.each do |i|
    i = i.to_i
    u[i]+=1
    mx=i if mx<i
end
i = mx
while me<i
    z = u[i]
    while u[i]>0 and me<=i
        me+=1
        u[i]-=1
    end
    u[i-1]+=z
    i-=1
end
if me == i
    me+=1
end
print me-start


k=gets.to_i;b=Array.new(10,0)
4.times{gets.split("").map{|v|if v.to_i>0;b[v.to_i]+=1;end}}
puts b.select{|v|v>k*2}.size>0?"NO":"YES"


def main()
    k=gets.chomp.to_i
    mat=Array.new(4){Array.new(4)}
    for i in 1..4
        st=gets.chomp
        for j in 1..4
            mat[i-1][j-1]=st[j-1].chr.to_i
        end
    end
    f=true
    for i in 1..9
        toti=0
        for j in 0...4
            toti+=mat[j].count(i)
        end
        if toti>2*k
            f=false
            break;
        end
    end
    if f
        puts "YES"
    else
        puts "NO"
    end
end
main()


a=gets.chomp.to_i*2
hash=Hash.new(0)
4.times do
temp=gets.chomp
temp.each_char do |i|
if i!="."
hash[i]+=1
end
end
end
k=hash.values.sort.reverse

if k.length!=0
if k[0]>a
puts "NO"
else
puts "YES"
end
else
puts "YES"
end


Mod = (1e9 + 7).to_i

n = gets.to_i

ans1 = 1
ans2 = 1

n.times do
	ans1 *= 27
	ans2 *= 7

	ans1 %= Mod
	ans2 %= Mod
end

ans = (ans1 - ans2 + Mod) % Mod
puts ans


#!/usr/bin/ruby
t,s,q=gets.split.map(&:to_i)
i=0
while s<t
	s*=q
	i+=1
end
p i


t , s, q = gets.split(' ').map(&:to_f)
res = 0
while s<t
s *= q
res = res + 1
end
puts "#{res}"


#!/usr/bin/ruby

t, s, q = ARGF.gets.split(' ').map{ |x| x.to_f}

n = (Math.log(t/s)/Math.log(q)).ceil
puts n


n, k = gets.split.collect{|i| i.to_i}
if n*3 >= k
    puts n*3-k
else
    puts 0
end


# codeforce#122(Div2.A)
n, k = gets.chomp.split(" ").map{|e| e.to_i}

0.upto(n) do |i|
  if (i * 2 + 5 * (n - i)) >= k and (i * 2 + 3 * (n - i)) <= k
    puts i
    break
  end
end


n,k = gets.split(" ").map(&:to_i)
q = k/n
re = 0
re = n - (k % n) if q == 2
puts re


l, r = gets.split.map(&:to_i)
ans = 0
for i in 0..32 do
    for j in 0..25 do
        now = (2**i)*(3**j)
        if( now >= l && now <= r)
            ans += 1
        end
    end
end

p ans


# cook your code here
a, b = gets.split.map(&:to_i);
k = 0;
(0..32).each do |x|
  (0..20).each do |y|
    r = (2**x) * (3**y);
    if a <= r && r <= b then
      k = k + 1;
    end
  end
end
puts k.to_s;


xxx=->{gets.split.map &:to_i}
l,r=xxx[]
ans = 0
for i in (0..60)
    for j in (0..60)
        if ((2 ** i) * (3 ** j) >= l && (2 ** i) * (3 ** j) <= r)
            ans += 1
        end
    end
end
print ans


s = gets.chomp
t = 'CODEFORCES'
i, j = 0, 0
s.each_char do |x|
  break if x != t[i]
  i += 1
end
(s.size - 1).downto(0) do |k|
  break if s[k] != t[9 - j]
  j += 1
end
puts i + j >= 10 ? 'YES' : 'NO'


phrase = gets.strip
rv_phrase = phrase.reverse
len = phrase.length
for i in 0..len
	for j in 0..len - i
		tmp = phrase[0, i] << rv_phrase[0, j].reverse
		if tmp.eql? 'CODEFORCES'
			puts "YES"
			exit
		end
	end
end
puts "NO"


str = gets.strip
cmp = "CODEFORCES"
left = 0
right = 0
0.upto(cmp.size-1) do |i|
  break if i >= str.size
  break if str[i] != cmp[i]
  left += 1
end
0.upto(cmp.size-1) do |i|
  break if i >= str.size
  break if str[str.size-i-1] != cmp[cmp.size-i-1]
  right += 1
end

if left + right >= cmp.size
  puts "YES"
else
  puts "NO"
end


n, a, b = gets.split.map(&:to_i)
puts (a - 1 + b) % n + 1


n, a, b = gets.split.map &:to_i;
puts (n * 1000 + a + b - 1) % n + 1


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

a += b

a += 100 * n if a < 0
a %= n if a >= n
a = n if a == 0

puts a


def flips
  n = gets.chomp.to_i
  arr = []
  lowerTotal = 0
  upperTotal = 0
  n.times do
    split = gets.chomp.split(" ")
    lower = split[0].to_i
    upper = split[1].to_i
    lowerTotal += lower
    upperTotal += upper
    arr.push([lower, upper])
  end

  if (lowerTotal % 2 == 0 && upperTotal % 2 == 0)
    puts "0"
    return
  elsif (lowerTotal % 2 != upperTotal % 2)
    puts "-1"
    return
  end

  if arr.length == 1
    puts "-1"
    return
  end

  isFlip = false
  arr.each do |e|
    if e[0] % 2 != e[1] % 2
      isFlip = true
    end
  end

  if isFlip
    puts "1"
    return
  end

  puts "-1"
end

flips


n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
c = Array.new(4, 0)
a.each do |x, y|
  case [x.even?, y.even?]
  when [true, true]
    c[0] += 1
  when [true, false]
    c[1] += 1
  when [false, true]
    c[2] += 1
  when [false, false]
    c[3] += 1
  end
end
if (c[2] + c[3]) % 2 == 0 && (c[1] + c[3]) % 2 == 0
  puts 0
elsif ((c[1] + c[2]).even? && c[1] + c[2] != 0) || (c[1].odd? && c[2].odd? && c[3].odd?)
  puts 1
else
  puts -1
end


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_i
ary = gets.strip.split.map(&:to_i)

ev = ary.inject(:+)
(ary.max).upto(1000).each do |k|
  av = ary.map{|x| [0,k-x].max }.inject(:+)
  if av>ev
    puts k
    break
  end
end


n,*a=$<.read.split.map &:to_i
p [*a,2*a.reduce(:+)/n+1].max


def solve

    r, g, b = readline.split(' ')
    r = r.to_i; g = g.to_i; b = b.to_i
    t = -1

    while ( r > 0 || g > 0 || b > 0 ) do
        t += 1;
        r -= 2 if (t % 3 == 0)
        g -= 2 if (t % 3 == 1)
        b -= 2 if (t % 3 == 2)
    end

        return t + 30

    end

    #$stdin = File.open("in.txt", "r")
    puts solve


n = gets.to_i
a, b = 1, n
(1..Math.sqrt(n)).each do |i|
  a, b = i, n / i if n % i == 0
end
puts "#{a} #{b}"


n = gets.to_i
x = 0
y = 0
for i in 1..Math.sqrt(n).round
  if (n%i === 0)
    x = i
    y = n/i
  end
end
print x
print " "
print y


n = gets.to_i
a = (1..n).select { |x| x * x <= n && n % x == 0 }.last
puts [a, n / a].join(' ')


p,d=gets.split.map &:to_i;z=p;d=p-d;t=10;loop{p-=(p+1)%t;break if p<d;z=p;t*=10};p z


n = gets.chomp.chars.map(&:to_i)
ans = 0
n.size.times do |i|
  if n[i] == 4
    ans += 2 ** (n.size - i - 1)
  elsif n[i] == 7
    ans += 2 * 2 ** (n.size - i - 1)
  end
end
puts ans


userInput = gets.chomp

numberArray = userInput.to_s.split("").map {|item| item.to_i }

result ||= 0
result +=

loopNum = 0

until loopNum == numberArray.length do
	result += 2 ** (numberArray.length - loopNum - 1) if numberArray[loopNum] == 4
	result += (2 * (2 ** (numberArray.length - loopNum - 1))) if numberArray[loopNum] == 7

	loopNum += 1
end

puts result


def lucky_numbers(numbers, current, limit)
    numbers.push(current)

    if current >= limit
        return numbers
    end

    numbers = lucky_numbers(numbers, current * 10 + 4, limit)

    lucky_numbers(numbers, current * 10 + 7, limit)
end

n = gets.to_i

puts lucky_numbers([], 4, n).concat(lucky_numbers([], 7, n)).sort.find_index(n) + 1


n = gets.to_i
k = n
sum = 0
while k > 0 do
  sum += (n-k + 1) * (k - 1) + 1
  k -= 1
end
puts sum


n = gets.to_i
ar = (1...n).to_a
puts n + ar.reverse.zip(ar).map{|x,y| x*y}.inject(:+) if n>1
puts 1 if n==1


n = $stdin.readline.to_i

def s(n)
    n*(n-1)/2
end

def k(n,l)
    if n == 1
        return 1+l
    else
        if l > 0
            return n*l + k(n-1, l+1)
        else
            return n-1 + k(n-1, l+1)
        end
    end
end

puts k(n,0)


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


n = gets
str = gets
mas = str.split("").sort {|x, y| y <=> x }
str = mas.join
per = 0
(str.size - 1).times do |i|
	if str[i] == "1" and str[i+1] == "1"
		per = i + 1
	end
end
puts str[per..str.size]


n = gets.to_i
s = gets.chomp
c = s.count(?0)
ans = '0' * c
if s.count(?1) > 0
    ans = '1' + ans
end
puts ans


n,d = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)
x.sort!
ans = n-1
n.times do |i|
  n.times do |j|
    a = (x[i] - x[j]).abs
    b = i + (n-1-j)
    ans = b if b < ans && a <= d
  end
end
puts ans


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


def getar
 return gets.split.map &:to_i
end
s = gets
a = getar
b = getar
c = a & b

puts c.size > 0 ? c.min : [a.min,b.min].min.to_s +  [a.min,b.min].max.to_s


class Solver1
  def self.solve(arr)
    l1 = arr[0]
    l2 = arr[1]
    uniq = l2 & l1
    return uniq.min if uniq.size > 0
    min1 = l1.min
    min2 = l2.min
    return [(min2.to_s + min1.to_s).to_i, (min1.to_s + min2.to_s).to_i].min
  end
end
string = ARGF.read
arr = string.split("\n")
arr.map! { |elem| elem.strip }
arr1 = arr.drop(1)
arr1.map! { |elem| elem.split }
puts Solver1.solve(arr1)
exit(true)


n, m = gets.split.map(&:to_i)
a = gets.split
b = gets.split
for i in 1 .. 99
  oka = false
  okb = false
  for c in i.to_s.split('')
    if a.include?(c)
      oka = true
    end
    if b.include?(c)
      okb = true
    end
  end
  if oka && okb
    puts i
    exit 0
  end
end


n,d=gets.split(" ").map {|x| x.to_i}
cnt=0
i=0
raw=gets.split(" ").map {|x| x.to_i}
while(i<n)
  cnt+=raw[i]
  i+=1
end
l=cnt+(n-1)*10
if(l>d)
  puts "-1"
else
  print "#{2*(n-1)+(d-l)/5}"
end


n,d=gets.split.map &:to_i
mas=gets.split.map &:to_i
c= (n-1)*10
f=mas.inject(:+)
if c+f > d
  puts -1
  exit
else
  puts (d-f)/5
end


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


x,y = gets.split.map(&:to_i)
d = x.times.map{gets.strip.chars.to_a}
sum_i,sum_j = 0,0
d.each {|x| sum_i+=1 if (x.sort.reverse.first == ".")}
d.transpose.each{|x| sum_j+=1 if(x.sort.reverse.first == ".")}
p (sum_i*y)+(sum_j*x)-(sum_i*sum_j)


r, c = gets.split.map(&:to_i)
a = r.times.map{gets.chomp.chars}
rr = a.count{|x| x.include?('S')}
cc = a.transpose.count{|x| x.include?('S')}
puts r * c - rr * cc


r,c=gets.chomp.split.map(&:to_i)
a=[]
r.times do
	b=gets.chomp.strip.split('')
	a.push(b)
end
row=Array.new(20,0)
col=Array.new(20,0)
i,j=0,0
while i<r
	j=0
	while j<c
		if a[i][j]=='S'
			row[i]+=1
			col[j]+=1
		end
		j+=1
	end
	i+=1
end
k,l=0,0
11.times do |i|
	if row[i]>0
		k+=1
	end
	if col[i]>0
		l+=1
	end
end
puts (r*c)-(k*l)


n = gets.chomp.to_i

slimes = []
n.times do
  slimes << 1
  while  slimes.size >= 2 && slimes.last(2).uniq.length == 1
    v = slimes.pop(2)
    slimes << v[0] + 1
  end
end
puts slimes.join(" ")


#!/usr/bin/env ruby

slizen = gets.to_i

result = []
fat = 1

loop do
  break if slizen == 0
  result << fat if slizen%2 == 1
  slizen/=2
  fat+=1
end

print result.reverse.join(' ')


a,b=gets.split.map &:to_i
30.times{
	a%=2*b if b>0
	b%=2*a if a>0
}
puts [a,b]*' '


a, b = gets.split.map(&:to_i)
while a*b != 0
if a >= 2*b
  a%=2*b
elsif b >= 2*a
  b%=2*a
else
  break
end
end
puts [a, b].join(" ")


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 ' '


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


$md = 1000000007;
def pow(x, y)
  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

n, k = gets.split.map(& :to_i)
p pow(k, k - 1) * pow(n - k, n - k) % $md


n, v = gets.split.map(&:to_i)
ans = fuel = 0
(1..n).each do |i|
    if fuel == 0
        fuel = n > v ? v : n - 1
        ans += fuel * i
        next
    end
    if n - i >= v
        fuel += 1
        ans += i
    end
    fuel -= 1
end
puts ans


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


n,v = gets.split.map(&:to_i)
ans = [n-1,v].min
(n-v-1).times do |i|
    ans += i+2
end
puts ans


@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.to_i
x=1378
r=1
while n>0
    r=r*x%10 if n.odd?
    x=x*x%10
    n>>=1
end
p r


n = gets.to_i

if n == 0
  puts "1"
else
  case n%4
  when 1
    puts "8"
  when 2
    puts "4"
  when 3
    puts "2"
  when 0
    puts "6"
  end
end


#!/Users/mike/.rvm/rubies/ruby-1.9.3-p327/bin/ruby

extensionNum, deviceNum, socketNum = STDIN.readline.split.collect {|s| s.to_i}
extensions = STDIN.readline.split.collect {|s| s.to_i}
extensions = extensions.sort.reverse

socketCount, extensionCount = socketNum, 0
while socketCount < deviceNum
	if extensionCount == extensionNum
		extensionCount = -1
		break
	end
	socketCount += extensions[extensionCount]-1
	extensionCount += 1
end

puts extensionCount


n,m,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i).sort {|i,j| j<=>i}

if k>=m
  puts 0
  exit
end

i=0
while k>0 && i<a.length
  m-=a[i]
  i+=1
  k-=1
  if m<=k
    puts i
    exit
  end
end

while i<a.length
  m-=a[i]-1
  i+=1
  if m<=0
    puts i
    exit
  end
end

puts -1


def calc(m, k, filters)
  return 0 if k >= m

  socket_count = k - 1
  filter_count = 1

  filters.sort_by! { |x| -x }
  filters.each do |item|
    return filter_count if item + socket_count >= m

    socket_count += item - 1
    filter_count += 1
  end

  return -1
end

if $0 == __FILE__
  ARGF.readlines.each_slice(2) do |line1, line2|
    n, m, k = line1.chomp.split.map {|x| x.to_i }
    filters = line2.chomp.split.map {|x| x.to_i }
    puts calc(m, k, filters)
  end
end


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

if (a + b + c).odd?
	puts 'Impossible'
else
	sum = (a + b + c) / 2
	x, y, z = sum - c, sum - a, sum - b
	if x < 0 or y < 0 or z < 0
		puts 'Impossible'
	else
		puts [x, y, z].join ' '
	end
end


s = gets
t = gets

i = 0

t.each_char do |c|
	if s[i] == c
		i+=1
	end
end

puts i+1


s = gets
x = 0
gets.each_char do |c|
  x += 1 if c == s[x]
end
puts x + 1


def run
  s = ARGF.readline.split(//)
  t = ARGF.readline.split(//)

  pos = 1
  t.each do |c|
    pos += 1 if c == s[pos - 1]
  end

  puts pos
end

run if $0 == __FILE__


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


nm = gets.chomp.split.map(&:to_i)
n = nm[0]
m = nm[1]

def min(a,b)
	if a < b
		return a
	else
		return b
	end
end

count = 0
while n != 0 && m != 0
	if min(n,m) == n
		n -= 1
		m -= 2
	elsif min(n,m) == m
		n -= 2
		m -= 1
	end
	if n >= 0 && m >= 0
		count += 1
	end
end
print count


n,m=gets.split.map &:to_i
ans=0
while n>0&&m>0&&n+m>=3
  if n>m
    n-=2
	m-=1
  else
    n-=1
	m-=2
  end
  ans+=1
end
p ans


#!/usr/bin/ruby
def egcd(x,y)
    return [x,1,0] if y==0
    g,a,b=egcd(y,x%y)
    [g,b,a-x/y*b]
end
a,b,c=gets.split.map(&:to_i)
g=a.gcd(b)
if c%g!=0
	puts :No
else
	a/=g
	b/=g
	c/=g
	_,z1,z2=egcd(a,b)
	n=[a,b].max+c
	puts (-n..n).find{|i|z1*c+b*i>=0 && z2*c-a*i>=0} ? :Yes : :No
end


a=gets.chomp.split (' ')
b=a[0].to_i
c=a[1].to_i
d=a[2].to_i

trigar=0

0.upto ((d/b)+1) do |i|
0.upto ((d/c)+1) do |j|
	if (b*i+c*j==d)
    trigar=1
	end
	break if trigar==1
end
break if trigar==1
end

if (trigar ==1)
puts "Yes"
else
puts "No"
end


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?


# https://codeforces.com/problemset/problem/999/B
def solution(n, e)
  d = e
  i = 1
  while i < n do
    next i += 1 unless n % i == 0

    d = d[0..i - 1].reverse + d[i..n - 1]
    i += 1
  end
  return d.reverse
end

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

puts solution(n, s)


require 'prime'
n = gets.to_i
a = gets.chomp
(1..n).select { n % _1 == 0 }.each { |i| a[0, i] = a[0, i].reverse }
puts a


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']


n, l, r, x = gets.split(' ').map { |_| _.to_i }
a = gets.split(' ').map { |_| _.to_i }
res = 0
for mask in (0..(1<<n)-1) do
  tmp = (0...n).select { |i| (mask & (1 << i)) != 0 }.map { |index| a[index] }
  if tmp.length > 1
    min, max = tmp.minmax
    sum = tmp.reduce(0, :+)
    if l <= sum && sum <= r && (max - min) >= x then
      res += 1
    end
  end
end
p res


#!/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


n, l, r, x = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)

ans = 0
(1 << n).times do |s|
  arr = []
  n.times { |b| arr << a[b] if ((s >> b) & 1) == 1 }

  if arr.length > 1
    if arr.max - arr.min >= x
      sum = arr.inject(&:+)
      if sum >= l && sum <= r
        ans += 1
      end
    end
  end
end

puts ans


numLength = gets.chomp.to_i
num = gets.chomp.split('').map(&:to_i)
found = false

for i in 0...numLength
	num[i] = 10 if num[i] == 0
end

###############
prob = false

upper = num[0...numLength].map { |i| i -= 3}

upper.each do |i|
	prob = true if i <= 0
end

#puts "Upper : #{prob}"
found = true if !prob
################
prob = false

left = num[0...numLength].map { |i| i -= 1}

left.each do |i|
	prob = true if i <= 0 || i % 3 == 0
end

#puts "Left : #{prob}"
found = true if !prob
###############
prob = false

right = num[0...numLength].map { |i| i += 1}

right.each do |i|
	prob = true if i >= 10 || i % 3 == 1
end

#puts "Right : #{prob}"
found = true if !prob
#################
prob = false

below = num[0...numLength].map { |i| i += 3 }

below.each do |i|
	prob = true if (i != 11 && i >= 10)
end

#puts "below : #{prob}"
found = true if !prob
########################

puts 'YES' if !found
puts 'NO' if found


# 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
############################################################

k2, k3, k5, k6 = gis

c256 = [k2, k5, k6].min
c32 = [k3, k2 - c256].min

ans = c256 * 256 + c32 * 32

puts ans


k2, k3, k5, k6 = gets.chomp.split.map(&:to_i)
sum = 256 * [k2,k5,k6].min
k2 -= [k2, k5, k6].min
sum += 32 * [k3, k2].min
p sum


a=gets.chomp.split(" ")
c=Hash.new(0)
a.each {|i|  c[i]+=1}
a=c.values.sort
if (a.length==3 && a[2]==4) || (a.length==2 && a[1]==5)
puts "Bear"
elsif (a.length==2 && a[1]==4) || (a.length==1)
puts "Elephant"
else
puts "Alien"
end


require 'pp'

s = STDIN.gets.chomp.split(/ /).map(&:to_i)
s.sort!

count=1
leg = -1
5.times do |i|
  if s[i] == s[i+1]
    count+=1
    if count >=4
      leg = s[i]
      break
    end
  else
    count = 1
  end
end

if leg == -1
  puts "Alien"
else
  s.delete(leg)
  if s.length == 0
    puts "Elephant"
  elsif s.length == 1
    puts "Bear"
  else
    if s.first == s.last
      puts "Elephant"
    else
      puts "Bear"
    end
  end
end


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

c = input.inject({}){|h,e| h[e] ||= 0; h[e] += 1; h }

if c.values.any?{|v| v >= 4 }

  l = c.find{|n,c| c >= 4  }[0]

  cc = input.dup
  4.times do
    cc.delete_at( cc.index(l) )
  end

  if cc.uniq.count > 1
    puts "Bear"
  else
    puts "Elephant"
  end

else
  puts "Alien"
end


a = gets.split.map &:to_i
p [0, a.max * 2 - a.inject(:+) + 1].max


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

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


x,y,z = gets.split.map { |e| Integer(e)  }

min = 100000

(x..100).each {|a|
   (y..100).each { |b|
        (z..100).each { |c|
           s=(a+b+c)/2.0
           if s>a and s>b and s>c then
             v = a-x + b-y + c-z
             if min > v then
                min = v
            end
           end
        }
    }
}

puts min


a1, b1 = ARGF.gets.chomp.split(" ").map { |s| s.to_i }
a2, b2 = ARGF.gets.chomp.split(" ").map { |s| s.to_i }

puts [(a2-a1).abs, (b2-b1).abs].max


a = gets.split(" ").map(&:to_i)
b = gets.split(" ").map(&:to_i)
dx = (a[0]-b[0]).abs
dy = (a[1]-b[1]).abs
p (dx-dy).abs + [dx, dy].min


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


l, r = gets.split.map(&:to_i)
ans = 0
70.downto(0) do |i|
	st = 1<<i
	if ( st>l && st<=r )
		ans = [ans, st*2-1].max
	elsif (r<st*2 && l>=st)
		l -= st
		r -= st
	end
end
puts ans


s = gets.to_i
time = gets.chomp
h = time.split(" ")[0].to_i
m = time.split(" ")[1].to_i
ans = 0
while m % 10 != 7 and h % 10 !=7
	m -= s
	ans += 1
	if m < 0
		h -= 1
		m += 60
	end
	if h < 0
		h += 24
	end
end
print ans,"\n"


MOD = 998_244_353

def edge(v, u)
	cv = cu = 1
	res = 1
	[u, v].min.times do |i|
		cv = cv * (v - i)
		cu = cu * (u - i) / (i + 1)
		res += (cu % MOD * cv % MOD) % MOD
		res %= MOD
	end
	res
end

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

p (edge(a, b) * edge(b, c) * edge(a, c)).modulo(MOD)


gets
cnt, res = Array.new(6, 0), 0
gets.split.each { |s| cnt[s.to_i] += 1 }
gets.split.each { |s| cnt[s.to_i] -= 1 }
cnt.each do |x|
  if x.odd?
    puts -1
    exit
  else
    res += x.abs
  end
end
puts res / 4


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


n = gets.to_i
a = gets.split(" ").map(&:to_i)
b = gets.split(" ").map(&:to_i)
cnta = Array.new(5) {|i| i = 0}
cntb = Array.new(5) {|i| i = 0}
res = 0
ok = 1
a.each do |i|
	cnta[i-1] += 1
end
b.each do |i|
	cntb[i-1] += 1
end
(0..4).each do |i|
	if (cnta[i] + cntb[i]) % 2 == 0
		res += ((cnta[i] + cntb[i]) / 2 - cnta[i]).abs
	else
		ok = 0
		break
	end
end

if ok == 0
	puts -1
else
	puts res / 2
end


a = gets.to_i
b = gets.to_i
c = gets.to_i
m = [a, b/2, c/4].min
puts 7 * m


a = gets.chomp.to_i
b = gets.chomp.to_i
c = gets.chomp.to_i
puts 7*([a,b/2,c/4].min)


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

b /= 2
c /= 4

d = [a, b, c].min

puts d + d*2 + d*4


def fun(n,m)
  n.each {|i|

    m.each {|y|

      if y==i
        print y+" "
      end

      }

    }
end

n=gets.chomp
arr=n.split(" ")
x=arr[0].to_i
y=arr[1].to_i

array=gets.chomp
array_1=array.split(" ")

arrayy=gets.chomp
array_2=arrayy.split(" ")

fun(array_1,array_2)

#fun(array_1,array_2)


gets
x = gets.split
y = gets.split
x.each{|x| print x, ' ' if y.include? x}


def parse_time(time)
  time.split(':').map(&:to_i)
end

def to_str(h, m)
  [h, m].map { |t| "%02d" % t }.join(':')
end

def solve(cur_time, duration)
  hc, mc = parse_time cur_time
  hd, md = parse_time duration
  hg = hc - hd
  mg = mc - md
  if mg < 0
    mg = 60 + mg
    hg -= 1
  end
  hg = (hg + 24) % 24
  to_str(hg, mg)
end

if __FILE__ == $0
  puts solve(gets.chomp, gets.chomp)
end


first = gets.chomp
second = gets.chomp

first = first.split(":").map { |i| i.to_i }
second = second.split(":").map { |i| i.to_i }

first = first[0]*60 + first[1]
second = second[0]*60 + second[1]

x = first - second

if x >= 0 then

	hr = x/60
	mn = x%60

	print "0" if hr < 10
	print hr,":"
	print "0" if mn < 10
	print mn

else

	hr = ((24*60) - (-1*x)) / 60
	mn = ((24*60) - (-1*x)) % 60
	print "0" if hr < 10
	print hr,":"
	print "0" if mn < 10
	print mn

end


$dp = {}

def g a
	return 0 if a.empty?
	return a.first == 0 ? 1 : 0 if a.size == 1
	return $dp[a] if $dp[a]
	s = a.first
	t = [1 + g(a[1..-1])]
	t << g([a[1] & 2] + a[2..-1]) if s & 1 != 0
	t << g([a[1] & 1] + a[2..-1]) if s & 2 != 0
	return $dp[a] = t.min
end

def f a
	ans = 0
	b = []
	while !a.empty?
		if a.first == 0
			ans += 1
			a.shift
		else
			c = []
			while !a.empty? and a.first != 0
				c << a.shift
			end
			b << c
		end
	end
	b.sort_by! &:size
	for i in 0..b.size - 1
		ans += g(b[i])
	end
	return ans
end

gets
a = gets.split.map &:to_i
puts f a


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

ans=0

(n-1).times do |i|
    if a[i]==1
        if a[i+1]==1 || a[i+1]==0
            a[i+1]=0
        else
            a[i+1]=2
        end
    elsif a[i]==2
        if a[i+1]==2 || a[i+1]==0
            a[i+1]=0
        else
            a[i+1]=1
        end
    elsif a[i]==0
        ans+=1
    end
end

ans+=1 if a[n-1]==0

p ans


#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.chomp 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
############################################################

require 'set'

n = gi
x = gis

h1 = Set.new
h1.add [0, 0, 0, -1]

x.each do |z|
    h2 = Set.new
    h1.each do |c, s, r, e|
        case z
        when 0
            h2.add [c, s, r + 1, 2]
        when 1
            if e != 0
                h2.add [c + 1, s, r, 0]
            end
            h2.add [c , s, r + 1, 2]
        when 2
            if e != 1
                h2.add [c, s + 1, r, 1]
            end
            h2.add [c, s, r + 1, 2]
        when 3
            if e != 0
                h2.add [c + 1, s, r, 0]
            end
            if e != 1
                h2.add [c, s + 1, r, 1]
            end
            h2.add [c, s, r + 1, 2]
        end
    end
    h1 = h2
end

ans = nil
h1.each do |c, s, r, e|
    # next if c != s
    if ans.nil?
        ans = r
    else
        ans = [ans, r].min
    end
end

if ans.nil?
    puts 0
else
    puts ans
end


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


k, a, b, v = gets.split.map(&:to_i)
p *(1..b).collect{|x|x+[0,(a-v*[x+b,k*x].min+v-1)/v].max}.min


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


n,k=gets.split.map(&:to_i)
if n == k || k == 0
    puts "0 0"
else
    if n % 3 == 0
        if k > n / 3
            k -= n / 3
            ans = n / 3 * 2 - k
        else
            ans = 2 * k
        end
    elsif n % 3 == 1
        if k > n / 3
            k -= n / 3
            ans = n / 3 * 2 - k + 1
        else
            ans = 2 * k
        end
    else
        if k > n / 3
            k -= n / 3 + 1
            ans = n / 3 * 2 + 1 - k
        else
            ans = 2 * k
        end
    end
    puts "1 #{ans}"
end


def F(x,s);x-(-x%s*(x/s));end;n,m,s=gets.split.map &:to_i;p F(n,s)*F(m,s)


n,m=gets.split.map &:to_i
s=gets.chomp
c=i=0
while c<n-1
	c=[c+m,n-1].min.downto(c+1).find{|j|s[j]==?1}
	if !c
		p -1
		exit
	end
	i+=1
end
p i


(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)}"


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

input = gets.chomp.split(" ")

a = input[0].to_i
b = input[1].to_i

sum = 0

while a<=b do
	aux = a
	while aux>0 do
		sum += num[ aux%10 ]
		aux /= 10
	end
	a += 1
end

puts sum


inpup=gets.chomp

beg_end=inpup.split(" ")
$num_seg=0

ini=beg_end[0].to_i
fin=beg_end[1].to_i

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

ini.upto(fin) do |k|
	loop do
		eva=k%10
		$num_seg=$num_seg+value[eva]
		k=k/10
		if k==0
			break
		end
	end
end

print $num_seg


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

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

res = 0

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

puts res


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, m = gets.split.map { |x| x.to_i }
a = a % m

vis = Array.new m

loop do
	if a == 0
		puts 'Yes'
		break
	elsif vis[a]
		puts 'No'
		break
	else
		vis[a] = true
		a = 2 * a % m
	end
end


x, m = STDIN.readline.split.map {|s| s.to_i }
if x%m == 0
	puts 'Yes'
	exit
end
seen = Array.new(m, false)
seen[x%m] = true
while true
	x += x%m
	if x%m == 0
		puts 'Yes'
		exit
	end
	if seen[x%m]
		puts 'No'
		exit
	end
	seen[x%m] = true
end


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


x,y=gets.chomp.split.map(&:to_i)
ans=0
ans=4*y-2 if x>=-y && x<y
ans=-4*x-1 if y>=x &&y<-x
ans=-y*4 if x>y && x<=-y+1
ans=4*x-3 if y>-x+1 && y<=x
puts ans


x,y = gets.split.map(&:to_i)
ans = 0
pgrx = 1
pgry=1
ogrx=-1
ogry=-1
k=0
nx=0
ny=0
while (x!=nx || y!=ny)
	#p nx
	#p pgrx
	if ( nx==pgrx)
		pgrx += 1
		k = (k+1)%4
		ans += 1
	elsif (ny==ogry)
		ogry -= 1
		k = (k+1)%4
		ans += 1
	elsif (nx==ogrx)
		ogrx -= 1
		k = (k+1)%4
		ans += 1
	elsif (ny==pgry)
		pgry += 1
		k = (k+1)%4
		ans += 1
	end
	if (k==0)
		nx += 1
	elsif (k==1)
		ny += 1
	elsif (k==2)
		nx -= 1
	else
		ny -= 1
	end
end
puts ans


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
  extend Memoizer
  attr_reader(:n, :l, :xs, :ys)
  def initialize(n, l, xs, ys)
    @n = n
    @l = l
    @xs = xs
    @ys = ys
  end

  def nxs
    xs.drop(1) + [l + xs.first]
  end
  memoize(:nxs)

  def nys
    ys.drop(1) + [l + ys.first]
  end
  memoize(:nys)

  def xxs
    xs.zip(nxs).map{|p, q| q - p}
  end
  memoize(:xxs)

  def yys
    ys.zip(nys).map{|p, q| q - p}
  end
  memoize(:yys)

  def same?
    xxs.zip(yys).all?{|x, y| x == y}
  end

  def next_try
    Problem.new(n, l, xs, nys)
  end

  def answer(n)
    return "YES" if same?
    return "NO" if n == 102
    return next_try.answer(n + 1)
  end

end

n, l = gets.split(" ").map(&:to_i)
xs = gets.split(" ").map(&:to_i)
ys = gets.split(" ").map(&:to_i)

p = Problem.new(n, l, xs, ys)
puts p.answer(0)


#在界线内跑？
#圆形跟踪？
#用栏栅围住的一个东西！
#田径运动员！
#track应该是轨迹？
#鹦鹉？花豹
#每一个做一次接力？
number=gets.chomp.split
n=number[0].to_i
l=number[1].to_i
kefa=gets.chomp.split
sasha=gets.chomp.split
#这是一个跨栏运动？
#找到栅栏之间的间隔！
kefa_fence_interval=[]
kefa_fence_interval[0]=kefa[0].to_i+l-kefa[-1].to_i
i=1
j=1
while i<kefa.length do
	kefa_fence_interval[j]=kefa[i].to_i-kefa[i-1].to_i
	j+=1
	i+=1
end

sasha_fence_interval=[]
sasha_fence_interval[0]=sasha[0].to_i+l-sasha[-1].to_i
i=1
j=1
while i<sasha.length do
	sasha_fence_interval[j]=sasha[i].to_i-sasha[i-1].to_i
	j+=1
	i+=1
end
#puts kefa.join(" ")
#puts kefa_fence_interval.join(" ")
#
#puts sasha.join(" ")
#puts sasha_fence_interval.join(" ")
#然后看这两个区间是不是相同，如果相同就是可以放在一起的！
start=0
find=0
while start<n do
	i=0
	same=1
	while i<n
		#print " #{sasha_fence_interval[i]}=?=#{kefa_fence_interval[(i+start)%n]}"
		if sasha_fence_interval[i]!=kefa_fence_interval[(i+start)%n]
			same=0
			break
		end
		i+=1
	end
	#puts
	if same==1
		find=1
		break
	end
	start+=1
end
if find==1
	puts "YES"
else
	puts "NO"
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


n, a = gets.split.map(&:to_i)
if a%2==1
    p a/2+1
    exit(0)
end
p (n/2-a/2)+1
exit(0)


n, a = gets.split.map &:to_i
if a % 2 == 0
  a = n - a + 1
end
puts a / 2 + 1


buf = gets.split(" ")
n,v=buf[0].to_i,buf[1].to_i
puts (v+1)/2 if v%2==1
puts (n-v)/2+1 if v%2==0


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


a1, b1 = gets.split.map {|x| Integer x}
a2, b2 = gets.split.map {|x| Integer x}
a3, b3 = gets.split.map {|x| Integer x}
a4, b4 = gets.split.map {|x| Integer x}
if (a1 > b3 && a1 > b4 && b2 > a3 && b2 > a4) || (b1 > a3 && b1 > a4 && a2 > b3 && a2 > b4)
  puts 'Team 1'
elsif (a3 > b1 && b4 > a2 || b3 > a2 && a4 > b1) && (b3 > a1 && a4 > b2 || b4 > a1 && a3 > b2)
  puts 'Team 2'
else
  puts 'Draw'
end


n=gets.to_i
i=1
ans=[]
while n-i>0
	m=n-i
	if m+m.to_s.chars.inject(0){|sum,e|
		sum+e.to_i
	}==n then
		ans<<m
	end
	break if i>100
	i+=1
end
ans=ans.reverse
puts ans.size
if ans.size>0
	puts ans
end


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

ans = []

n = gets.to_i

(0..9).to_a.repeated_combination(9) do |a|
    t = a.reduce(n){|s,e| s-=e}
    next if t < 0
    h = [0]*10
    a.each{|e| h[e]+=1}
    t.to_s.chars.each{|c| h[c.to_i]-=1}
    b = true
    (1..9).each{|e| b &= h[e] == 0}
    ans << t if b
end

p ans.size
puts ans.sort


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 is_consonant(c)
  c =~ /[^aeiou]/
end

def is_bertlanese(word)
  next_must_be_vowel = false

  word.chars.each do |c|

    return false if next_must_be_vowel && is_consonant(c)

    next_must_be_vowel =
      c != ?a &&
      c != ?e &&
      c != ?i &&
      c != ?o &&
      c != ?u &&
      c != ?n
  end

  !next_must_be_vowel
end

def solution
  word = read_string
  puts is_bertlanese(word) ? "YES" : "NO"
end

def rest_int
  gets.to_i
end

def read_ints
  gets.split.map &:to_i
end

def read_string
  gets.chomp
end

solution


s = gets.chomp
n = s.size
a = ["a", "i", "u", "e", "o"]
i = 0
flag = true
while i < n
    if a.include?(s[i])
        i += 1
    elsif s[i] == ?n
        i += 1
    else
        if i + 1 == n
            flag = false
            break
        else
            i += 1
            if !a.include?(s[i])
                flag = false
                break
            end
            i += 1
        end
    end
end
puts flag ? "YES" : "NO"


 #!/usr/bin/ruby

def isvowel(x)
  if x == 'a'||x=='e'||x=='i'||x=='o'||x=='u'
    return true
  end

end
name = gets().chomp()
flag = 0
for i in 0...name.length

 #puts(name[i])

  if(i == name.length-1)

      if(name[i] == 'n')
        flag = 0
      elsif (isvowel(name[i]))
        flag = 0
      else
        flag = 1
        break
      end

  elsif(!isvowel(name[i]))

    if(name[i] == 'n')
      flag = 0

    else
      if(!isvowel(name[i+1]))
        flag = 1
        break
      end

    end

  end

end

if(flag == 0)
  puts("YES")
else
  puts("NO")
end


a = gets.split.map(&:to_i)
ans = 0
i = 0
3.times do
  ans += a[i] * a[i + 1] * 2
  i += 2
end
ans += (a[3] - a[0]) * (a[3] - a[0])
puts ans


a , b , c , d , e , f = gets.split.map(&:to_i)
ans = a*b + a*e + a*f + b*f + c*d + e*f
print ans


a,b,c,d,k = gets.split(/\s/).map(&:to_i)
l,r = [a,c].max,[b,d].min
ans = 0
if l>r
	puts ans
	else
		ans = r-l +1
		if k>=l and k<=r
			ans=ans -1
		end
		puts ans
	end


a,b,c,d,e=gets.split.map &:to_i
a=[a,c].max
b=[b,d].min
p [0,b-a+1-(a<=e&&e<=b ? 1 : 0)].max


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

a=[a,c].max
b=[b,d].min
puts [0, b-a+1 - (a<=e && e<=b ? 1 : 0) ].max


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

ans=0
i=0
while i<n and a[i]<=k
	ans += 1
	i += 1
end
i=n-1
while i>=0 and a[i]<=k
	ans += 1
	i -= 1
end

puts [ans,n].min


def solution
  _, k = read_ints
  ps = read_ints

  count = 0

  while ps.first && ps.first <= k
    count += 1
    ps.shift
  end

  while ps.last && ps.last <= k
    count += 1
    ps.pop
  end

  puts count
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']


n, k = gets.strip.split.map(&:to_i)
ary = gets.strip.split.map(&:to_i)
ans = 0
si = -1
0.upto(n-1).each do |i|
  if ary[i] <= k
    ans += 1
    si = i
  else
    break
  end
end
(n-1).downto(si+1).each do |i|
  if ary[i] <= k
    ans += 1
  else
    break
  end
end
puts ans


def sum(x)
	y=((x+1)*x)/2
end
m,b  = gets.split.map(&:to_i)
max=0
(b+1).times do |y|
	x=(-y*m)+b*m
	s=(y+1)*sum(x)+(x+1)*sum(y)
	max= max > s ? max : s
end
p max


# your code goes here

n = STDIN.gets.chomp.to_i
n = n % 6
x = STDIN.gets.chomp.to_i

t=[0,0,0]

t[x] = 1

(n).downto(1) do
	|i|;
	#puts i;
	x = t[1];
	if (i % 2) == 0;
		t[1] = t[2];
		t[2] = x;
	else;
		t[1] = t[0];
		t[0] = x;
	end;
end;

puts t.index(1);


n=gets.to_i

coins=[n]

(n-1).downto(1){|i|
	if coins[-1]%i==0
		coins << i
	end
}

print coins.join(" ")


n = gets.chomp.to_i
puts n.downto(1).reduce([[], n]) { |s, x|
	(s.first << x; s[-1] = x) if s[-1] % x == 0
	s
}.first.join(' ')


n = gets.to_i

while n > 1
    (n-1).downto(1) do |i|
        if (n%i).zero?
            print n, ' '
            n = i
        end
    end
end
print 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


#b+i*a==d+j*c
#i*a-j*c==d-b
#x*a-c*y==d-b
#a=3,b=2
#3=2*1+1
#1,1
def gcd(a,b)
	if b==0
		return a
	else
		return gcd(b,a%b)
	end
end
ab=gets.chomp.split.map{ |x| x.to_i }
a=ab[0]
b=ab[1]
cd=gets.chomp.split.map{ |x| x.to_i }
c=cd[0]
d=cd[1]

gcd_ab=gcd(a,c)
if (d-b)%gcd_ab==0
	#在判断有解的情况下，我们用直接查找的方法得到最小相同值！
	#用数学公式处理比较复杂！
	i=0
	j=0
	while true
		x=b+i*a
		y=d+j*c
		if x==y
			puts x
			break
		elsif x>y
			j+=1
		else
			i+=1
		end
	end
else
	puts -1
end


s=gets.chomp
r=s.scan('VK').size
s.size.times{|i|
	s[i]=s[i].tr('VK','KV')
	r=[r,s.scan('VK').size].max
	s[i]=s[i].tr('VK','KV')
}
p r


str1 = gets().chomp
str1_count = str1.scan(/VK/).size
if (str1.scan(/VVV/).size >= 1) || (str1.scan(/KKK/).size >= 1) || (str1[0,2]=='KK') || (str1[-2,str1.size]=='VV')
  str1_count += 1
end
p str1_count


s = gets
if s[-1] == "\n"
  s = s.split("\n")[0].to_s
end
res = 0
changed = false
i = 0
while i < s.size
  if s[i] == 'V' && s[i+1] == 'K'
    i += 2
    res += 1
    next
  end
  if changed
    i += 1
    next
  end
  if s[i] == 'K' && s[i+1] == 'K' ||
    s[i] == 'V' && s[i+1] == 'V' && (s[i+2] == 'V' || s[i+2] == nil)
    res += 1
    i += 2
    changed = true
    next
  end
  i += 1
end

puts res


board = gets.split(' ')
board_a = board.first.to_i
board_b = board.last.to_i
pa1 = gets.split(' ')
pa2 = gets.split(' ')
pa1.map!{|x| x.to_i}
pa2.map!{|x| x.to_i}
possible = false

pa1.each do |dim1|
    pa2.each do |dim2|
        if (dim1+dim2) <= board_a
            p1 = pa1.clone
            p2 = pa2.clone
            p1.delete_at(p1.index(dim1))
            l1 = p1.first
            p2.delete_at(p2.index(dim2))
            l2 = p2.first
            possible = true if [l1, l2].max <= board_b
        end
        if (dim1+dim2) <= board_b
            p1 = pa1.clone
            p2 = pa2.clone
            p1.delete_at(p1.index(dim1))
            l1 = p1.first
            p2.delete_at(p2.index(dim2))
            l2 = p2.first
            possible = true if [l1, l2].max <= board_a
        end
    end
end
if possible
    puts 'YES'
else
    puts 'NO'
end


def try(b1, b2, size)
  newb1 = []
  newb2 = []
#place b1
  if (b1[0] > size[0] or b1[1] > size[1])
    #try to put it the other way
    #puts 'flip'
    b1[0], b1[1] = b1[1], b1[0]
  end

  newb1 = [size[0] - b1[0], b1[1]]
  if (b1[1] == size[1])
    newb2 = [size[0] - b1[0], size[1] - b1[1]]
  else
    newb2 = [size[0], size[1] - b1[1]]
  end

  #p newb1.inspect
  #p newb2.inspect

#b1 wont fit
  if newb2[0] < 0 || newb2[1] < 0 || newb1[0] < 0 || newb1[1] < 0
    puts "NO"
    exit
  end

#try and fit b1 on newb1 or new b2
  newb1_fit_norm = newb1[0] >= b2[0] && newb1[1] >= b2[1]
  newb1_fit_flip = newb1[0] >= b2[1] && newb1[1] >= b2[0]
  newb1_fit = newb1_fit_norm || newb1_fit_flip

  newb2_fit_norm = newb2[0] >= b2[0] && newb2[1] >= b2[1]
  newb2_fit_flip = newb2[0] >= b2[1] && newb2[1] >= b2[0]
  newb2_fit = newb2_fit_norm || newb2_fit_flip
  newb1_fit || newb2_fit
end

size = gets.split(' ').collect { |i| i.to_i }
b1 = gets.split(' ').collect { |i| i.to_i }
b2 = gets.split(' ').collect { |i| i.to_i }

if (try(b1,b2, size) or try(b2,b1,size))
  puts 'YES'
else
  puts 'NO'
end


def read_ints; gets.chomp.split.map(&:to_i) end
def max(*values); values.max end

extend Math
area = read_ints
first = read_ints
second = read_ints

[first, first.reverse].each do |first_rotated|
	[second, second.reverse].each do |second_rotated|
		if first_rotated[0]+second_rotated[0]<=area[0] && max(first_rotated[1],second_rotated[1])<=area[1]
			puts "YES"
			exit
		elsif first_rotated[1]+second_rotated[1]<=area[1] && max(first_rotated[0],second_rotated[0])<=area[0]
			puts "YES"
			exit
		end
	end
end
puts 'NO' #otherwise


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


l,r=gets.split.map &:to_i;t=1;t*=10 while t<=r;p=[[t/2,l].max,r].min;p p*(t-1-p)


l, r = gets.split.map(&:to_i)
a, b, answer = 1, 9, 0
while a <= r
    c, d = [l, a].max, [r, b].min
    if c <= d
        answer = [(b - c) * c, (b - d) * d, answer].max
        if c <= b / 2 and b / 2 <= d
            answer = [(b - b / 2) * (b / 2), answer].max
        end
    end
    a *= 10
    b *= 10
    b += 9
end
puts answer


n = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
ans = "YES"
i = 0
visited = Array.new(3, false)
while i < n - 1
    prev = a[i]
    i += 1
    curr = a[i]
    if prev < curr
        if !visited[0]
            visited[0] = true
        else
            if visited[1] || visited[2]
                ans = "NO"
                break
            end
        end
    elsif prev == curr
        visited[0] = true if !visited[0]
        if !visited[1]
            visited[1] = true
        else
            if !visited[0] || visited[2]
                ans = "NO"
                break
            end
        end
    else
        visited[0] = true if !visited[0]
        visited[1] = true if !visited[1]
        if !visited[2]
            visited[2] = true
        else
            if !visited[0] || !visited[1]
                ans = "NO"
                break
            end
        end
    end
end
puts ans


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)


k = gets.to_i

arr = 0, *gets.split.map{|x| x.to_i}.sort

ans = k - 25

1.upto(k){|i| ans += arr[i] - arr[i - 1] - 1}

puts [0, ans].max


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


n, k, t = gets.strip.split.map(&:to_i)
ans = [t, k, n + k - t].min
puts ans


n, k, t = gets.split.map{|a| a.to_i}
puts (
	if t < k
		t
	elsif t > n
		k - t + n
	else
		k
	end
)


n, k, t = gets.split.map &:to_i
if t <= k
  puts t
elsif n + 1 <= t
  puts k - t + n
else
  puts k
end


ans = 0
def fib(n, m)
    i = 0
    a, b, c, d = 1, 1, 1, 0
    aa, bb, cc, dd = 1, 0, 0, 1
    while (1 << i) <= n
        if (n & (1 << i)) > 0 then
            aa, bb, cc, dd = (aa*a+bb*c)%m, (aa*b+bb*d)%m, (cc*a+dd*c)%m, (cc*b+dd*d)%m
        end
        a, b, c, d = (a*a+b*c)%m, (a*b+b*d)%m, (c*a+d*c)%m, (c*b+d*d)%m
        i += 1
    end
    (aa + bb) % m
end
def pow(x, y, m)
    i = 0
    ret = 1
    while (1 << i) <= y
        if (y & (1 << i)) > 0 then
            ret = ret * x % m
        end
        x = x * x % m
        i += 1
    end
    ret
end
n, k, l, m = gets.split.map &:to_i
if k < 2 ** l then
    ans = 1 % m
    num0 = fib(n, m)
    num1 = (pow(2, n, m) - num0 + m) % m
    l.times do |i|
        if (k & (1 << i)) == 0 then
            ans = ans * num0 % m
        else
            ans = ans * num1 % m
        end
    end
end
puts ans


n = gets.to_i

numbers = []

sum = 0
(1..500).each do |num|
  sum += num
  numbers << sum
end

puts numbers.include?(n) ? 'YES' : 'NO'


n = gets.chomp
n = n.to_i
i = 1
while i <= n do
    if i * (i + 1) == n * 2
        break
    end
    i = i + 1
end

if i <= n
    puts "YES"
else
    puts "NO"
end


n = gets.to_i
i = 1
s = 1
while s<=n do
  if s==n
    print "YES"
    exit
  end
  i+=1
  s=i*(i+1)/2
end
print "NO"


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

week = [a / 3, b / 2, c / 2].min

la = a - 3 * week
lb = b - 2 * week
lc = c - 2 * week

max_remain = 0

list = %w(a a b c a c b) * 2

(1..6).each do |d|
  (0..6).each do |s|
    counter = Hash.new(0)

    (s...(s + d)).each do |t|
      counter[list[t]] += 1
    end

    if counter['a'] <= la && counter['b'] <= lb && counter['c'] <= lc
      max_remain = d
    end
  end
end

puts 7 * week + max_remain


 no_ops = gets.chomp.to_i
  ops = gets.chomp.split("")
  pile = 0
  ops.each do |op|
    if op == "+"
      pile += 1
    else
      if pile == 0
        pile += 1
      end
      pile -= 1
    end
  end
  puts pile


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


n = gets.to_i
s = gets.chomp.split ''
c = 0
s.each do |x|
  c += x == '+' ? 1 : -1
  c = [c, 0].max
end
puts c


# coding: utf-8

# if __FILE__ == $0
# end
Q = 'Q'
A = 'A'
qi = []
ai = []

gets.chomp.split(//).each_with_index { |elem, index|
    if elem == Q
        qi << index
    elsif elem == A
        ai << index
    else
        next
    end
}

seqs = 0
qi.each { |i|
    ai.each { |j|
        if i < j
            count = 0
            qi.each { |sub_i|
                count += 1 if sub_i > j
            }
            seqs += count
        end
    }
}

puts seqs


s = gets.strip
n = s.length
ans = 0
n.times do |i|
    a = s[i]
    ((i + 1)...n).each do |j|
        b = s[j]
        ((j + 1)...n).each do |k|
            c = s[k]
            ans += 1 if a + b + c == "QAQ"
        end
    end
end
puts ans


S = gets

Q = ?Q
A = ?A

q = qa = qaq = 0

S.each_char do |c|

  if c == Q

    q += 1
    qaq += qa

  elsif c == A

    qa += q

  end

end

puts qaq


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


def solution(a,b)
  if a == b
    return "="
  end

  var = a**(Float(b)/Float(a))
  if var == b
    "="
  elsif var > b
    ">"
  else
    "<"
  end
end

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

puts solution input[0], input[1]


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

optimal_move_count = (n / 2.0).ceil
worst_move_count = n

if optimal_move_count % m == 0
  puts optimal_move_count
else
  optimal_moves = m - (optimal_move_count % m) + optimal_move_count
  answer = optimal_moves <= worst_move_count ? optimal_moves : -1
  puts answer
end


n, m = STDIN.readline.split.map {|s| s.to_i }
if m > n
	puts -1
	exit
end
k = (n + 2*m - 1) / (2*m)
puts k*m


# cook your code here

n,m=gets.chomp.split

n = n.to_i
m = m.to_i

if n%2==0
    c = n/2
else
    c = n/2 + 1
end

if m>n
    puts "-1"
elsif m==n
    puts m
else
    until c%m==0
        c+=1
    end
    puts c
end


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)


MOD = 10 ** 9 + 7
N, X, P = gets.split.map(&:to_i)
A = [*1..N]

up_cnt = N - X
down_cnt = X - 1
targets = []

left = 0
right = A.size
ans = 1

while left < right
  middle = (left + right) / 2

  if middle < P
    targets << [middle, :up]
    left = middle + 1
    ans *= down_cnt
    down_cnt -= 1
  elsif middle == P
    targets << [middle, :equal]
    left = middle + 1
  else
    targets << [middle, :down]
    right = middle
    ans *= up_cnt
    up_cnt -= 1
  end

  ans %= MOD
end

2.upto(up_cnt + down_cnt) do |i|
  ans *= i
  ans %= MOD
end

puts ans


def raise(y, n, mod)
	res = 1
	x = y
	while n != 0
		res = (res*x)%mod if n%2 != 0
		x = (x*x)%mod
		n = n/2
	end
	res
end
n, mod = gets.split.map(&:to_i)
ans = (raise(3, n, mod) - 1)%mod
puts ans


def pow(a, b)
    return a if (b==1)
    return 1 if (b==0)
    c = pow(a,b/2)
    c = (c * c) % $mod
    c = (c * a) % $mod if (b % 2==1)
    c
end

n, m = *gets.split.map {|x|x.to_i}
$mod = m
puts (pow(3, n) - 1 + m) % m


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


# frozen_string_literal: true

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

ans = (2 * n + k - 1) / k + (5 * n + k - 1) / k + (8 * n + k - 1) / k

p ans


nk =  gets.chomp.split(" ").map(&:to_f)
n = nk[0]
k = nk[1]
red = ((2*n)/k).ceil
green = ((5*n)/k).ceil
blue = ((8*n)/k).ceil

puts red+green+blue


n = gets.chomp.to_i
m = gets.chomp.to_i
puts (m % (2 ** n)).to_i


# coding: utf-8

# if __FILE__ == $0
# end

# 2**n mod m
# m mod 2**n reversed!
n = gets.to_i
m = gets.to_i
lg2_m = Math.log2(m).floor

if lg2_m >= n
    puts m%(1<<n)
else
    puts m
end


n = gets.to_i
m = gets.to_i

puts (m%(2**n)).to_i


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


n, cnt = gets.to_i, 0
(1..n).each do |a|
  (a..n).each do |b|
    c = a ^ b
    cnt += 1 if b <= c && c <= n && c < a + b
  end
end
puts cnt


n = gets.to_i
ans = 0
n.times do |i|
  (i+1).times do |j|
    a,b = j+1,i+1
    c = a ^ b
    ans += 1 if (b-a) < c && c < (a+b) && c <= n && b <= c
  end
end
puts ans


$n, $m, $t = gets.split(' ').map { |x| x.to_i }
def factorial(n)
  return (2..n).reduce(1) { |x,y| x*y }
end
def c_n_k(n, k)
  return factorial(n) / (factorial(k) * factorial(n-k))
end
def f()
  res = 0
  n, m = 4, $t-4
  while m > 0
    res += c_n_k($n, n) * c_n_k($m, m)
    n += 1
    m -= 1
  end
  return res
end
puts f()


n, m, t = gets.split.collect{|i| i.to_i}
ans = 0
b = 4
while b <= n
    ans += Array.new(n).combination(b).size * Array.new(m).combination(t-b).size if t-b>=1 and t-b<=m
    b += 1
end
puts ans


def fact(n)
  n<= 1 ? 1 : n * fact(n - 1)
end
def cc(n,k)
  fact(n)/fact(k)/fact(n-k)
end
n, m, t = gets.split.map(&:to_i)
ans = 0
(4..n).each do |b|
  break if t-b < 1
  ans += cc(n, b)*cc(m, t-b)
end
puts ans


n=gets.to_i
c=gets.count(?8)
p [n/11,c].min


n = gets.to_i
s = gets.chomp

puts [n/11, s.count('8')].min


n = gets.to_i
s = gets.chomp
puts [s.count('8'), s.size/11].min


s, v1, v2, t1, t2 = gets.split.map(&:to_i)
p1 = s * v1 + t1 * 2
p2 = s * v2 + t2 * 2
if p1 == p2
  puts 'Friendship'
elsif p1 < p2
  puts 'First'
else
  puts 'Second'
end


s,v1,v2,t1,t2=gets.split.map{|e| e.to_i}
a=s*v1+t1*2
b=s*v2+t2*2
if a<b then
	puts "First"
elsif a>b then
	puts "Second"
else
	puts "Friendship"
end


s, v1, v2, t1, t2=gets.split.map &:to_i
a1=(v1*s)+2*t1
a2=v2*s+2*t2
puts (a1==a2 ? "Friendship" : a1<a2 ? "First" : "Second")


P = 9
Primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
$dp = Array.new(10) {Array.new(1001) {nil} }

n = gets.to_i

def power(a, b)
  return 1 if b == 0
  if b % 2 == 0
    x = power(a, b / 2)
    return x * x
  end
  return a * power(a, b - 1)
end

def go(i, n)

  return 1 if n == 1
  return -1 if i == P

  return $dp[i][n] if $dp[i][n]

  p = Primes[i]

  res = power(p, n - 1)

  m = Math.sqrt(n)
  for j in 2..m
    if n % j == 0
      k = n / j
      x = go(i + 1, k)
      res = [res, x * power(p, j - 1)].min if x != -1
      x = go(i + 1, j)
      res = [res, x * power(p, k - 1)].min if x != -1
    end
  end

  return $dp[i][n] = res

end

puts go(0, n)


#!/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


a,b,c,d = gets.split.map(&:to_i)
x,y,z = [a,b,c].sort
ans = 0
ans += d-(z-y) if z-y < d
ans += d-(y-x) if y-x < d
p ans


a, b, c, d = gets.split.map(&:to_i)
x, y, z = [a, b, c].sort
puts [d-(z-y), 0].max + [d-(y-x), 0].max


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


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


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

ans = 0
(1..k).each do |i|
  s = i.to_s
  ans += ( s + s.reverse ).to_i % p
end

puts ans % p


nums, devider = gets.chomp.split.map(&:to_i)
sum = 0
nums.times do |i|
  a = (i+1).to_s
  sum += ( a + a.reverse).to_i
end
puts sum%devider


def exec
  (k, p) = gets.split.map{|i| i.to_i}

  src  = 1
  dist = 10
  sum = 0
  count = 0;

  while true
    for i in src..dist-1
      break if count == k
      count += 1
      s = i.to_s
      ss = s + s.reverse
      sum += ss.to_i
    end
    break if count == k

    src *= 10
    dist *= 10
  end

  puts sum % p
end

exec


def rook_moves(r1, c1, r2, c2)
  r1 == r2 || c1 == c2 ? 1 : 2
end

def bishop_moves(r1, c1, r2, c2)
  r = (r1 - r2).abs
  c = (c1 - c2).abs
  r == c ? 1 : (r + c).even? ? 2 : 0
end

def king_moves(r1, c1, r2, c2)
  [r1 - r2, c1 - c2].map(&:abs).max
end

r1, c1, r2, c2 = gets.chomp.split.map(&:to_i)
puts "#{rook_moves(r1, c1, r2, c2)} #{bishop_moves(r1, c1, r2, c2)} #{king_moves(r1, c1, r2, c2)}"


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

row_diff,col_diff = (r2-r1).abs,(c1-c2).abs

rook_moves = 0
rook_moves += 1 if r1 != r2
rook_moves += 1 if c1 != c2
king_moves = [row_diff,col_diff].max

bishop_moves = 0
if (r1 + c1) % 2 == (r2+c2) %2
bishop_moves = 1
bishop_moves += 1 if row_diff != col_diff
end

puts "#{rook_moves} #{bishop_moves} #{king_moves}"


r1, c1, r2, c2 = gets.split.collect{|i| i.to_i}
if r1==r2 and c1==c2
    rook = 0
elsif r1==r2 or c1==c2
    rook = 1
else
    rook = 2
end
if (r1+c1)%2 != (r2+c2)%2
    bishop = 0
elsif r1+c1==r2+c2 or (r1-c1==r2-c2 and r1!=r2)
    bishop = 1
else
    bishop = 2
end
king = [(r1-r2).abs,(c1-c2).abs].max
puts [rook,bishop,king].join(" ")


#=================================
require 'prime'
require 'set'
require 'matrix'
require 'tsort'
include Math

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

def ok?(g, b)
	min_b, max_b=[g-1, 2*(g+1)]

	if min_b<=b && b<=max_b
		true
	else
		false
	end
end

g_l, g_r=gets.split.map(&:to_i)
b_l, b_r=gets.split.map(&:to_i)

puts (if ok?(g_l, b_r) || ok?(g_r, b_l)
	:YES
else
	:NO
end)


def solve(a,b)
        #bbabbabbabbabbabb
        #abababa
        if (a+1)*2<b || (b+1)<a then
                return false
        end
        return true
end

al,ar=gets.split.map(&:to_i)
bl,br=gets.split.map(&:to_i)

if solve(al,br) || solve(ar,bl) then
        puts "YES"
else
        puts "NO"
end


# Input
w,   h   = gets.split(" ").map { |s| s.to_i }
u_1, d_1 = gets.split(" ").map { |s| s.to_i }
u_2, d_2 = gets.split(" ").map { |s| s.to_i }

# Processing
m = w
h.downto(1) do |i|
  m += i
  m -= u_1 if i == d_1
  m -= u_2 if i == d_2
  m = 0 if m < 0
end

# Output
puts m


w,H,U,D,V,E=$<.read.split.map &:to_i
H.downto(1){|h|
w+=h
w=[0,w-U].max if h==D
w=[0,w-V].max if h==E
}
p w


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


code = gets.chomp
code = (code[0] + code[2] + code[4] + code[3] + code[1])
puts (code.to_i ** 5).to_s.chars.last(5).join


def main
  n = gets.chomp.to_i
  m = (Math.sqrt(1+8*n)-1)/2
  m = m.to_i
  sum = m*(m+1)/2
  delta = n-sum
  if delta == 0
    puts m
  else
    puts delta
  end
end

main


n = gets.to_i

left = 0
right = 1e8.to_i
while left + 1 < right
	mid = (left + right) / 2
	if mid * (mid + 1) / 2 < n
		left = mid
	else
		right = mid
	end
end

puts n - left * (left + 1) / 2


$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')


$ans=Hash.new
$e=Hash.new
def dfs(s, lim)
	if s.length==lim
		$ans[s]=true
		return
	end
	from = s[0]
	$e[from].each {|to| dfs(to+s[1..11], lim)}
end

buf = gets.split(" ")
len,n = buf[0].to_i, buf[1].to_i
for i in 'a'..'f'
	$e[i]=[]
end
for i in 1..n
	buf = gets.split(" ")
	to, from = buf[0], buf[1]
	$e[from].push(to)
end
dfs("a", len)
puts $ans.size


class BearCompression
  def initialize(length)
    @output_length = length
    @store = Hash.new { Array.new }
  end

  def add_operation(input)
    a, b = input.split
    @store[b] += Array(a)
  end

  def run
    p solve('a')
  end

  def solve(n, count = 1)
    return n.count if count == @output_length
    nodes = Array(n)
    a = nodes.collect do |node|
      @store[node[0]].map { |n| n + node[1..-1]}
    end
    solve(a.flatten, count + 1)
  end
end

string_length, operations_count = gets.chomp.split.map(&:to_i)

b = BearCompression.new(string_length)
operations_count.times do
  b.add_operation(gets.chomp)
end

b.run


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


MOD = 10 ** 9 + 7
gets.to_i.times {
  n, k = gets.split.map!(&:to_i)
  p n ** k % MOD
}


#f = File.open("b.in")
@ma = {}

def is(s, t)
   return (s[0] == t[0] or s[1] == t[1])
end

def doit(b)
   return true if b.size == 1
   return @ma[b.join] if @ma.has_key?(b.join)
   r = false
   k = b.size - 1
   if k > 0 and is(b[k], b[k - 1])
      d = b.dup
      d[k - 1] = d[k]
      r = r | doit(d[0..k - 1])
   end
   if k - 2 > 0 and is(b[k], b[k - 3])
      d = b.dup
      d[k - 3] = d[k]
      r = r | doit(d[0..k - 1])
   end
   return @ma[b.join] = r
end

gets.to_i
puts doit(gets.split) ? "YES" : "NO"


gets
t = gets.split

def same a,b
    a[0] == b[0] || a[1] == b[1]
end

h = {}

flag = false

stack = [t]
while cards = stack.pop
    next if h[cards.join]
    h[cards.join] = true
    break (puts "YES"; flag = true) if cards.size == 1
    card = cards.pop
    (stack << cards.dup; stack[-1][-1] = card) if same(card, cards[-1]) unless cards.size < 1
    (stack << cards.dup; stack[-1][-3] = card) if same(card, cards[-3]) unless cards.size < 3
end

puts "NO" unless flag


s = gets
x = s.to_i
p [*1..Math.sqrt(x)].map{|_| [_, x / _]}.flatten.select{|_| x % _ == 0 && s.tr(_.to_s, '') != s}.uniq.size


n = gets.to_i
ns = n.to_s.split('')
a = []
(1..Math.sqrt(n)).each { |x| a.push(x, n/x) if n%x == 0 }
p a.sort.uniq.count { |x| (x.to_s.split('')&ns).size.nonzero? }


require "prime"
x=gets.to_i
if x<10
	p 1
	exit
end
table=[nil]*10
xx=x
while xx>0
	table[xx%10]=true
	xx/=10
end
pd=x.prime_division.map{|a,b|0.upto(b).map{|i|a**i}}
divisors=pd.first
pd[1..-1].each{|divs|divisors=divs.map{|d|divisors.map{|e|d*e}}.flatten}
ans=0
divisors.each{|d|
	while d>0
		if table[d%10]
			ans+=1
			break
		end
		d/=10
	end
}
p ans


require 'set'

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

seen = [].to_set
shit = false
for i in 1..[k,1000].min
	r = n % i
	if seen.include? r
		shit = true
		break
	else
		seen.add(r)
	end
end

if shit
	puts "No"
else
	puts "Yes"
end


n,k = gets.split.map(&:to_i)
if k > 42
  ans = "No"
else
  i = 2
  flag = true
  while flag && i <= k
    flag = false if n % i != i-1
    i += 1
  end
  ans = flag ? "Yes" : "No"
end
puts ans


arr = gets.chomp.chars
arr1 = Array.new(arr)
c = 1
arr.rotate!
until arr == arr1
    arr.rotate!
    c += 1
end
p c


def judge(a, b)
  return false if b == 0
  return false if b == 1 && a != 0
  return false if (a - b + 1) < 0
  return false if (a - b + 1) % 2 == 1
  return true
end

a, b = gets.split.map(&:to_i)
if judge(a, b)
  puts "Yes"
else
  puts "No"
end


fact = [1] * 50
1.upto(49) do |i|
  fact[i] = fact[i - 1] * i
end

n = gets.strip.chars.map &:to_i

cnt = [0] * 10
n.each do |d|
  cnt[d] += 1
end

dfs = -> (d, take) do
  if d == 10
    r = 0
    cc = take.inject :+
    return 0 if cc == 0
    u = fact[cc]
    (0...10).each do |i|
      u /= fact[take[i]]
    end
    if cnt[0] > 0
      choose = -> (n, m) do
        return 0 if n < m
        fact[n] / fact[m] / fact[n - m]
      end
      h = -> (n, m) do
        choose[n + m - 1, m]
      end
      (1..cnt[0]).each do |i|
        r += u * h[cc, i]
      end
    else
      r = u
    end
    r
  else
    if cnt[d] > 0
      (1..cnt[d]).map do |i|
        take[d] = i
        dfs[d + 1, take]
      end.inject :+
    else
      dfs[d + 1, take]
    end
  end
end

puts dfs[1, [0] * 10]


s = gets.chomp
len = s.length
puts ((len+1)*26)-len
=begin
aba
=end


str = gets().chomp()

a = str.split('')

h = {}
for i in (0..a.length())
        for c in ('a'..'z')
                h[a.insert(i,c).join('').to_sym]=nil
                a.delete_at(i)
        end
end

puts h.length()


letters = gets.chomp.chars

puts (letters.length + 1) * 26 - letters.length


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)


def dist(p1, p2)
  (p1[0] - p2[0]).abs + (p1[1] - p2[1]).abs
end

x0, y0, ax, ay, bx, by = gets.chomp.split(' ').map(&:to_i)
xs, ys, t = gets.chomp.split(' ').map(&:to_i)
MAX = 63

arr = [[x0, y0]]
(1..MAX).each do |_|
  x = ax * arr[-1][0] + bx
  y = ay * arr[-1][1] + by
  arr << [x, y]
end

ans = 0
arr.length.times do |i|
  rem_time = t - dist([xs, ys], arr[i])
  if rem_time >= 0
    curr = 1
    j = i+1
    while j < arr.length
      rem_time -= dist(arr[j-1], arr[j])
      break if rem_time < 0
      curr += 1
      j += 1
    end
    ans = curr if curr > ans

    curr = 1
    j = i-1
    rem_time = t - dist([xs, ys], arr[i])
    while j >= 0
      rem_time -= dist(arr[j], arr[j+1])
      break if rem_time < 0
      curr += 1
      j -= 1
    end
    ans = curr if curr > ans
  end
end
puts ans


matr=[]
8.times{matr<<gets.split("")}
a,b=9,9

8.times do |j|
  tmp=0
  8.times do |i|
    if matr[i][j] == "W"
      tmp=i
      a=[tmp,a].min
      break
    elsif matr[i][j] == "B"
      break
    end
  end
end

8.times do |j|
  tmp=0
   (0..7).to_a.reverse.each do |i|
    if matr[i][j] == "B"
      tmp=7-i
    b=[tmp,b].min
      break
    elsif matr[i][j] == "W"
      break
    end
  end
end

puts a>b ? "B" : "A"