arr1=input()
arr2=input()
def replace(arr,index,element):
    for i in range(len(arr)):
        if i==index:
            arr[i]=element
        else:
            continue
    return arr
arr1=list(arr1)
arr2=list(arr2)
c=0
for i in range(len(arr1)-1):
    if arr1[i]=="0" and arr2[i]=="0" and arr2[i+1]=="0":
        c+=1
        arr1=replace(arr1,i,"X")
        arr2=replace(arr2,i, "X")
        arr2=replace(arr2,i+1, "X")
    elif arr1[i]=="0" and arr1[i+1]=="0" and arr2[i+1]=="0":
        c+=1
        arr1=replace(arr1,i, "X")
        arr1=replace(arr1,i+1, "X")
        arr2=replace(arr2,i + 1, "X")
    elif arr1[i]=="0" and arr1[i+1]=="0" and arr2[i]=="0":
        c+=1
        arr1=replace(arr1,i, "X")
        arr1=replace(arr1,i+1, "X")
        arr2=replace(arr2,i, "X")
    elif arr1[i+1]=="0" and arr2[i+1]=="0" and arr2[i]=="0":
        c+=1
        arr1=replace(arr1,i+1, "X")
        arr2=replace(arr2,i+1, "X")
        arr2=replace(arr2,i, "X")
print(c)


#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

#-------------------game starts now----------------------------------------------------
def doi(it,l,t):
    for i in range(len(l)):
        if l[i][t]==it:
            print(l[i][0],l[i][1])
            return
n=int(input())
d=dict()
d1=dict()
m=0
m1=0
mi=99999999999999999999
mi1=99999999999999999999
l=[]
for i in range(4*n+1):
    a,b=map(int,input().split())
    l.append([a,b])
    m=max(a,m)
    mi=min(mi,a)
    m1=max(b,m1)
    mi1=min(mi1,b)
    if a in d:
        d[a]+=1
    else:
        d.update({a:1})
    if b in d1:
        d1[b]+=1
    else:
        d1.update({b:1})
if d[m]==1:
    doi(m,l,0)
elif d[mi]==1:
    doi(mi,l,0)
elif d1[mi1]==1:
    doi(mi1,l,1)
elif d1[m1]==1:
    doi(m1,l,1)
else:
    x1=m
    x2=mi
    y1=m1
    y2=mi1
    for i in range(len(l)):
        if l[i][0]==x1 and y2<=l[i][1]<=y1:
            continue
        elif l[i][0]==x2 and y2<=l[i][1]<=y1:
            continue
        elif l[i][1]==y1 and x2<=l[i][0]<=x1:
            continue
        elif l[i][1]==y2 and x2<=l[i][0]<=x1:
            continue
        else:
            print(l[i][0],l[i][1])
            break


#    !/usr/bin/env python3
#    encoding: UTF-8
#    Modified: <07/Jul/2019 05:27:38 PM>

#    ✪ H4WK3yE乡
#    Mohd. Farhan Tahir
#    Indian Institute Of Information Technology (IIIT), Gwalior

import sys
import os
from io import IOBase, BytesIO

def main():
    n = int(input())
    points = [0] * (4 * n + 1)
    for i in range(4 * n + 1):
        a, b = get_ints()
        points[i] = (a, b)

    l = 4 * n + 1
    for i in range(l):
        mnx, mxx, mny, mxy = 51, -1, 51, -1
        for j in range(l):
            if i == j:
                continue
            x = points[j][0]
            y = points[j][1]
            mnx = min(mnx, x)
            mxx = max(mxx, x)
            mny = min(mny, y)
            mxy = max(mxy, y)

        flag = True
        for j in range(l):
            if i == j:
                continue
            x = points[j][0]
            y = points[j][1]
            if x != mnx and x != mxx and y != mny and y != mxy:
                flag = False

        if flag == True and mxx - mnx == mxy - mny:
            print(points[i][0], points[i][1])
            return

BUFSIZE = 8192

class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill():
            pass
        return super(FastIO, self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill()
            self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        py2 = round(0.5)
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2 == 1:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s: self.buffer.write(s.encode("ascii"))
            self.read = lambda: self.buffer.read().decode("ascii")
            self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return map(int, sys.stdin.readline().split())

def input(): return sys.stdin.readline().strip()

if __name__ == "__main__":
    main()


pieces=''
result=0
for i in range(8):
    pieces+=input()
weight=dict(zip(list('QRBNPqrbnp.Kk'),[9,5,3,3,1,-9,-5,-3,-3,-1,0,0,0]))
for s in pieces:
    result+=weight[s]
if result>0:
    print('White')
elif result==0:
    print('Draw')
else:
    print('Black')


import sys

# sys.stdin = open('test.txt', 'r')

w = 0
b = 0

while True:
    try:
        s = raw_input()

        w += sum([9 for i in s if i is 'Q'])
        w += sum([5 for i in s if i is 'R'])
        w += sum([3 for i in s if i is 'B'])
        w += sum([3 for i in s if i is 'N'])
        w += sum([1 for i in s if i is 'P'])

        b += sum([9 for i in s if i is 'q'])
        b += sum([5 for i in s if i is 'r'])
        b += sum([3 for i in s if i is 'b'])
        b += sum([3 for i in s if i is 'n'])
        b += sum([1 for i in s if i is 'p'])

    except:
        break

if w>b:
    print 'White'
elif w==b:
    print 'Draw'
elif w<b:
    print 'Black'


colors = list(map(int, input().split()))

faces = {}
faces['top'] = colors[:4]
faces['front'] = colors[4:8]
faces['bottom'] = colors[8:12]
faces['left'] = colors[12:16]
faces['right'] = colors[16:20]
faces['back'] = [colors[21], colors[20], colors[23], colors[22]]

status = {}
for face in faces.keys():
	colors = faces[face]
	if max(colors) == min(colors):
		status[face] = 'ok'
	else:
		if colors[0] == colors[1] and colors[2] == colors[3]:
			status[face] = 'h'
		elif colors[0] == colors[2] and colors[1] == colors[3]:
			status[face] = 'v'
		else:
			status[face] = 'bad'

# print(status)
# print(faces)

if 'bad' in status.values():
	print('NO')
else:
	if status['top'] == status['bottom'] == 'ok' and status['front'] == status['left'] == status['right'] == status['back'] == 'h':
		if (faces['front'][0] == faces['left'][3] and
			faces['left'][0] == faces['back'][3] and
			faces['back'][0] == faces['right'][3] and
			faces['right'][0] == faces['front'][3]
			or
			faces['front'][0] == faces['right'][3] and
			faces['right'][0] == faces['back'][3] and
			faces['back'][0] == faces['left'][3] and
			faces['left'][0] == faces['front'][3]):
			print('YES')
		else:
			print('NO')
	elif status['left'] == status['right'] == 'ok' and status['front'] == status['top'] == status['bottom'] == status['back'] == 'v':
		if (faces['front'][0] == faces['top'][3] and
			faces['top'][0] == faces['back'][3] and
			faces['back'][0] == faces['bottom'][3] and
			faces['bottom'][0] == faces['front'][3]
			or
			faces['front'][0] == faces['bottom'][3] and
			faces['bottom'][0] == faces['back'][3] and
			faces['back'][0] == faces['top'][3] and
			faces['top'][0] == faces['front'][3]):
			print('YES')
		else:
			print('NO')
	elif status['front'] == status['back'] == 'ok' and status['left'] == status['right'] == 'v' and status['top'] == status['bottom'] == 'h':
		if (faces['top'][0] == faces['left'][1] and
			faces['left'][0] == faces['bottom'][0] and
			faces['bottom'][3] == faces['right'][0] and
			faces['right'][3] == faces['top'][3]
			or
			faces['top'][0] == faces['right'][0] and
			faces['right'][1] == faces['bottom'][0] and
			faces['bottom'][3] == faces['left'][1] and
			faces['left'][0] == faces['top'][3]):
			print('YES')
		else:
			print('NO')
	else:
		print('NO')


cube = [-1] + list(map(int, input().split()))

def ok(cube):
    counter = 0
    last = cube[1]
    for i in cube:
        if i == -1:
            continue
        elif last == i:
            counter+=1
        else:
            if counter != 4:
                return False
            else:
                counter = 1
                last = i
    return True

def rotl(cube):
    cube_n = cube[:]
    cube_n[1] = cube[3]
    cube_n[2] = cube[1]
    cube_n[3] = cube[4]
    cube_n[4] = cube[2]
    cube_n[5] = cube[17]
    cube_n[6] = cube[18]
    cube_n[17] = cube[21]
    cube_n[18] = cube[22]
    cube_n[21] = cube[13]
    cube_n[22] = cube[14]
    cube_n[13] = cube[5]
    cube_n[14] = cube[6]
    return cube_n

def rotr(cube):
    cube_n = cube[:]
    cube_n[1] = cube[2]
    cube_n[2] = cube[4]
    cube_n[3] = cube[1]
    cube_n[4] = cube[3]
    cube_n[5] = cube[13]
    cube_n[6] = cube[14]
    cube_n[17] = cube[5]
    cube_n[18] = cube[6]
    cube_n[21] = cube[17]
    cube_n[22] = cube[18]
    cube_n[13] = cube[21]
    cube_n[14] = cube[22]
    return cube_n

def next(cube):
    cube_n = cube[:]
    cube_n[1] = cube[5]
    cube_n[2] = cube[6]
    cube_n[3] = cube[7]
    cube_n[4] = cube[8]
    cube_n[5] = cube[9]
    cube_n[6] = cube[10]
    cube_n[7] = cube[11]
    cube_n[8] = cube[12]
    cube_n[9] = cube[24]
    cube_n[10] = cube[23]
    cube_n[11] = cube[22]
    cube_n[12] = cube[21]
    cube_n[13] = cube[14]
    cube_n[14] = cube[16]
    cube_n[15] = cube[13]
    cube_n[16] = cube[15]
    cube_n[17] = cube[19]
    cube_n[18] = cube[17]
    cube_n[19] = cube[20]
    cube_n[20] = cube[18]
    cube_n[21] = cube[4]
    cube_n[22] = cube[3]
    cube_n[23] = cube[2]
    cube_n[24] = cube[1]
    return cube_n

def next2(cube):
    cube_n = cube[:]
    cube_n[1] = cube[3]
    cube_n[2] = cube[1]
    cube_n[3] = cube[4]
    cube_n[4] = cube[2]
    cube_n[5] = cube[17]
    cube_n[6] = cube[18]
    cube_n[7] = cube[19]
    cube_n[8] = cube[20]
    cube_n[9] = cube[10]
    cube_n[10] = cube[12]
    cube_n[11] = cube[9]
    cube_n[12] = cube[11]
    cube_n[13] = cube[5]
    cube_n[14] = cube[6]
    cube_n[15] = cube[7]
    cube_n[16] = cube[8]
    cube_n[17] = cube[21]
    cube_n[18] = cube[22]
    cube_n[19] = cube[23]
    cube_n[20] = cube[24]
    cube_n[21] = cube[13]
    cube_n[22] = cube[14]
    cube_n[23] = cube[15]
    cube_n[24] = cube[16]
    return cube_n

def main(cube):
    return ok(rotl(cube)) or ok(rotr(cube))

for i in range(4):
    cube = next(cube)
    if main(next(cube)):
        print("YES")
        exit()
for i in range(4):
    cube = next2(cube)
    if main(next(cube)):
        print("YES")
        exit()
print("NO")


digits = {
    0:6,
    1:2,
    2:5,
    3:5,
    4:4,
    5:5,
    6:6,
    7:3,
    8:7,
    9:6
}

def count(d):
    v = d
    count = 0
    while v!=0:
        count += digits[v%10]
        v = v//10
    return count
def main():
    s,e = [int(v) for v in input().split()]
    total = 0
    for i in range(s, e+1):
        total+=count(i)
    print(total)
if __name__ == "__main__":
    main()


x,y = (int(i) for i in raw_input().split(" "))
u,v = (int(i) for i in raw_input().split(" "))
w,z = (int(i) for i in raw_input().split(" "))

xs = sorted([x,u,w])
ys = sorted([y,v,z])

mx = 0
if xs[0] == xs[1] or xs[1] == xs[2]:
    if xs[0] == xs[1] and xs[1] == xs[2]:
        mx = 2
    else:
        mx = 1

my = 0
if ys[0] == ys[1] or ys[1] == ys[2]:
    if ys[0] == ys[1] and ys[1] == ys[2]:
        my = 2
    else:
        my = 1

if mx == 2 or my == 2:
    print 1
    exit(0)
elif mx == 1:
    ok = True
    if x == u:
        if min(y,v) < z < max(y,v):
            ok = False
    elif x == w:
        if min(y,z) < v < max(y,z):
            ok = False
    elif u == w:
        if min(v,z) < y < max(v,z):
            ok = False
elif my == 1:
    ok = True
    if y == v:
        if min(x,u) < w < max(x,u):
            ok = False
    elif y == z:
        if min(x,w) < u < max(x,w):
            ok = False
    elif v == z:
        if min(u,w) < x < max(u,w):
            ok = False
else:
    ok = False

print 2 if ok else 3


from math import ceil, log, floor, sqrt
import math

def mod_expo(n, p, m):
	"""find (n^p)%m"""
	result = 1
	while p != 0:
		if p%2 == 1:
			result = (result * n)%m
		p //= 2
		n = (n * n)%m
	return result

def find_k(x, y, n):
	return ((n-y)//x)*x + y

def count_sticks(n):
	if n%2 == 0:
		return n//2
	return n//2 +1

def get_types(n, r):
	if r < n:
		return (r*(r+1))//2
	r = n-1
	return (r*(r+1))//2 + 1

def happy_guests(a, b, n, m):
	mn = min(n, m)
	a -= mn
	b -= mn
	n -= mn
	m -= mn
	if a < 0 or b < 0:
		return False
	if n > 0:
		return a+b >= n
	return min(a, b) >= m

def find_max_len(s):
	n = len(s)
	l, r = 0, n-1
	count = n
	while l < r and s[l] == 'a':
		l += 1
	while r > l and s[r] == 'a':
		r -= 1
	for i in range(l, r+1):
		if s[i] != 'b':
			count -= 1
	return count

def is_rectangle(a, b, c):
	for i in range(2):
		if a[i] == b[i]:
			idx = (i+1)%2
			if c[idx] >= max(a[idx], b[idx]) or c[idx] <= min(a[idx], b[idx]):
				return True
		if b[i] == c[i]:
			idx = (i+1)%2
			if a[idx] >= max(b[idx], c[idx]) or a[idx] <= min(b[idx], c[idx]):
				return True
		if a[i] == c[i]:
			idx = (i+1)%2
			if b[idx] >= max(a[idx], c[idx]) or b[idx] <= min(a[idx], c[idx]):
				return True
	return False

def count_lines(points):
	mpx, mpy = {}, {}
	for point in points:
		if point[0] not in mpx:
			mpx[point[0]] = 1
		else:
			mpx[point[0]] += 1
		if point[1] not in mpy:
			mpy[point[1]] = 1
		else:
			mpy[point[1]] += 1
	#print(len(mpx), len(mpy))
	#print(mpx, mpy)
	if len(mpx) == 1 or len(mpy) == 1:
		return 1
	if is_rectangle(points[0], points[1], points[2]):
		return 2
	if is_rectangle(points[0], points[2], points[1]):
		return 2
	if is_rectangle(points[2], points[1], points[0]):
		return 2
	return 3

t = 1
#t = int(input())
while t:
	t = t - 1
	points = []
	#n = int(input())
	#n, k = map(int, input().split())
	# = map(int, input().split())
	#arr = list(map(int, input().strip().split()))[:n]
	#w = list(map(int, input().strip().split()))[:k]
	for i in range(3):
		x, y = map(int, input().split())
		points.append((x, y))
	#s = input()
	#if happy_guests(a, b, n, m):
#		print("Yes")
#	else:
#		print("No")

	#print(get_res(s))
	print(count_lines(points))


n = int(input())
while n>9:
    n = sum(list(map(int, list(str(n)))))
print(n)


s = input()
while len(s) > 1:
    t = 0
    for digit in s:
        t += int(digit)
    s = str(t)
print(s)


x,y = list(map(int,input().split()))
a = 1
b = 0
if y == 0:
    print("No")
elif y == 1:
    if x == 0:
        print("Yes")
    else:
        print("No")
else:
    b += y - a
    if b > x:
        print("No")
    elif b == x:
        print("Yes")
    else:
        temp = x - b
        if temp % 2 == 0:
            print("Yes")
        else:
            print("No")


x, y=list(map(int, input().split()))
if y-1>x or (x==1 and y==0) or (y==1 and x!=0) or y==0 or (x-y+1)%2!=0:
    print('No')
else:
    print('Yes')


n,k = [int(i) for i in input().split()]
ans = 0
for i in range(k):
    if n >= 2:
        ans +=  2 * n  - 3
        n -= 2
print(ans)


def mp():  return map(int,input().split())
def lt():  return list(map(int,input().split()))
def pt(x):  print(x)
def ip():  return input()
def it():  return int(input())
def sl(x):  return [t for t in x]
def spl(x): return x.split()
def aj(liste, item): liste.append(item)
def bin(x):  return "{0:b}".format(x)
def printlist(l): print(''.join([str(x) for x in l]))
def listring(l): return ''.join([str(x) for x in l])

n,k = mp()
if k >= n//2:
    print((n*(n-1))//2)
    exit()
result = 0
for i in range(k):
    result += (2*(n-1-2*i)-1)
print(result)


x, y = map(int, input().split())
counter = 0

x, y = min(x,y), max(x,y)
x1 = x
x2 = x
x3 = x

while y > x1 or y > x2 or y > x3:
    if x1 != y:
        x1 = min(x3 + x2 - 1, y)
        counter += 1
    if x2 != y:
        x2 = min(x1 + x3 - 1, y)
        counter += 1
    if x3 != y:
        x3 = min(x1 + x2 - 1, y)
        counter += 1

#    print(x1,x2,x3)

print(counter)


from __future__ import division
from math import ceil
from collections import Counter

x, y = raw_input("").split(" ")
x, y = int(x), int(y)
y = [y, y, y]
count = 0
while not (y[0] == y[1] == y[2] == x):
	y.sort()
	y[0] = min(y[1] + y[2] - 1, x)
	count += 1
print count


import re
input()
s = input()
print(re.sub('o(go)+','***',s))


w,h = map(int, raw_input().split())
s1 = s2 = 0
for i in range(0, w):
    s1 += (w - i) / 2
for i in range(0, h):
    s2 += (h - i) / 2
print s1 * s2


from sys import stdin, stdout

w, h = map(int, stdin.readline().split())

if (w < 2 or h < 2):
    stdout.write('0')
else:
    first = 0

    for i in range(w - 1):
        first += (w - i) // 2

    second = 0

    for i in range(1, h + 1):
        second += min(i, h - i)

    stdout.write(str(first * second))


n=int(input())
l=list(map(int,input().split()))
emp=[]
for i in range(n):
    c=0
    for j in range(n):
        if j<=i:
            c+= l[j]*i*4
        else:
            c+=l[j]*j*4
    emp.append(c)
print(min(emp))


import sys
input = sys.stdin.readline
n = int(input())
s = [0]+list(map(int, input().split()))
ret = 9876543210
for xth in range(1, len(s)):
    summ = 0
    for i in range(1, len(s)):
        summ += 2*(abs(xth-i)+(i-1)+(xth-1))*s[i]
    ret=min(ret, summ)
print(ret)


x, y = map(int, input().split(" "))
k = 0
if(y % x != 0):
    print(-1)
else:
    y = y / x
    while y != 1:
        if(y % 2 == 0):
            y /= 2
            k += 1
        elif(y % 3 == 0):
            y /= 3
            k += 1
        else:
            print(-1)
            break
    else: print(k)


n, m = map(int, input().split())

if n == m:
    print(0)

elif m % n != 0:
    print(-1)

else:
    k = m // n
    if k % 2 != 0 and k % 3 != 0:
        print(-1)
    else:
        p, q = 0, 0
        while(k % 2 == 0):
            p += 1
            k /= 2
        while(k % 3 == 0):
            q += 1
            k /= 3
        if k != 1:
            print(-1)
        else:
            print(p + q)


n, k = map(int, input().split())
a = list(map(int, input().split()))

s2 = 2 * n
s4 = n
s1 = 0

tmp = sum(map(lambda ai: ai // 4, a))
s4 -= min(tmp, n)
s2 -= 2 * max(tmp - n, 0)

for ai in a:
    if ai % 4 == 2:
        if 0 < s2:
            s2 -= 1
        elif 0 < s4:
            s4 -= 1
            s1 += 1
        else:
            s1 -= 2

for ai in a:
    if ai % 4 == 1:
        if 0 < s1:
            s1 -= 1
        elif 0 < s2:
            s2 -= 1
        else:
            s4 -= 1
            s2 += 1

for ai in a:
    if ai % 4 == 3:
        if 0 < s4:
            s4 -= 1
        elif 1 < s2:
            s2 -= 2
        elif 1 == s2:
            s2 -= 1
            s1 -= 1
        else:
            s1 -= 3

if 0 <= s1 and 0 <= s2 and 0 <= s4:
    print("YES")
else:
    print("NO")


read = lambda: map(int, input().split())
k, n = read()
a = list(read())
cnt4 = k
cnt2 = 2 * k
for i in range(n):
    cnt = min(cnt4, a[i] // 4)
    a[i] -= cnt * 4
    cnt4 -= cnt
for i in range(n):
    cnt = min(cnt2, a[i] // 2)
    a[i] -= cnt * 2
    cnt2 -= cnt
c = [0] * 20
for i in a:
    c[min(i, 19)] += 1
d = min(cnt4, c[3])
c[3] -= d
cnt4 -= d
d = min(cnt4, c[1], c[2])
c[1] -= d
c[2] -= d
cnt4 -= d
d = min(cnt2, c[2])
c[2] -= d
cnt2 -= d
d = min(cnt2, c[1])
c[1] -= d
cnt2 -= d
d = min(cnt4, (c[2] + 2) // 3 + int(c[2] > 1))
c[2] -= d + d // 2
cnt4 -= d
d = min(cnt4, c[2])
c[2] -= d
cnt4 -= d
d = min(cnt4, (c[1] + 1) // 2)
c[1] -= d * 2
cnt4 -= d
d = min(cnt4, c[1])
c[1] -= d
cnt4 -= d
print('YES' if sum(c[1:]) == 0 else 'NO')


## necessary imports

import sys
input = sys.stdin.readline
from bisect import bisect_left;
from bisect import bisect_right;
from math import ceil, factorial;

def ceil(x):
    if x != int(x):
        x = int(x) + 1;
    return x;

# swap_array function
def swaparr(arr, a,b):
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;

## gcd function
def gcd(a,b):
    if b == 0:
        return a;
    return gcd(b, a % b);

## nCr function efficient using Binomial Cofficient
def nCr(n, k):
    if(k > n - k):
        k = n - k;
    res = 1;
    for i in range(k):
        res = res * (n - i);
        res = res / (i + 1);
    return int(res);

## prime factorization
def primefs(n):
    ## if n == 1    ## calculating primes
    primes = {}
    while(n%2 == 0 and n > 0):
        primes[2] = primes.get(2, 0) + 1
        n = n//2
    for i in range(3, int(n**0.5)+2, 2):
        while(n%i == 0 and n > 0):
            primes[i] = primes.get(i, 0) + 1
            n = n//i
    if n > 2:
        primes[n] = primes.get(n, 0) + 1
    ## prime factoriazation of n is stored in dictionary
    ## primes and can be accesed. O(sqrt n)
    return primes

## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
    res = 1
    x = x % p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) :
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p
    return res

## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
    temp = a
    a = b
    b = temp
    return a,b;

# find function with path compression included (recursive)
# def find(x, link):
#     if link[x] == x:
#         return x
#     link[x] = find(link[x], link);
#     return link[x];

# find function with path compression (ITERATIVE)
def find(x, link):
    p = x;
    while( p != link[p]):
        p = link[p];

    while( x != p):
        nex = link[x];
        link[x] = p;
        x = nex;
    return p;

# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
    x = find(x, link)
    y = find(y, link)
    if size[x] < size[y]:
        x,y = swap(x,y)
    if x != y:
        size[x] += size[y]
        link[y] = x

## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    return prime

#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
    spf[1] = 1;
    for i in range(2, MAXN):
        spf[i] = i;
    for i in range(4, MAXN, 2):
        spf[i] = 2;
    for i in range(3, ceil(MAXN ** 0.5), 2):
        if spf[i] == i:
            for j in range(i*i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i;
    ## function for storing smallest prime factors (spf) in the array

################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
    ret = {};
    while x != 1:
        ret[spf[x]] = ret.get(spf[x], 0) + 1;
        x = x//spf[x]
    return ret;
    ## this function is useful for multiple queries only, o/w use
    ## primefs function above. complexity O(log n)

## taking integer array input
def int_array():
    return list(map(int, input().strip().split()));

def float_array():
    return list(map(float, input().strip().split()));

## taking string array input
def str_array():
    return input().strip().split();

#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');

################### ---------------- TEMPLATE ENDS HERE ---------------- ###################

n, x = int_array();
a = int_array(); cnt = [0] * n;
k = x;
for i in range(n - 1, -1, -1):
    p = 2 ** i;
    cnt[i] += k // p;
    k %= p;

mnt = a.copy();
for i in range(1, n):
    mnt[i] = min(2 * mnt[i - 1], mnt[i]);
ans = 0;
for i in range(n):
    ans += mnt[i] * cnt[i];

## let's check if buying one more volume of biggest will do the trick;
this = 0;
for i in range(n - 1, -1, -1):
    this += (cnt[i] + 1) * mnt[i];
    ans = min(ans, this);
    this -= mnt[i];
print(ans);


n, l = map(int, input().split())
p = list(map(int, input().split()))
d = []
d = [[p[i] / 2**i, i + 1] for i in range(n)]
d.sort(key = lambda x: x[0])
res = 10**18
q = l
curres = 0
for i in d:
	if i[1] == 1:
		curres += p[i[1] - 1] * q
		res = min(res, curres)
		break
	curb = q // 2**(i[1] - 1)
	curres += curb * p[i[1] - 1]
	res = min(res, curres + p[i[1] - 1])
	q %= 2**(i[1] - 1)
print(res)


import sys

def sum_(a):
    return max(0, a * (a + 1) // 2)

def check(a):
    if a * n <= m:
        return 1
    a -= 1
    ans = n
    t1 = a - k + 1
    #print(a)
    if t1 >= 0:
        ans += sum_(a) - sum_(t1 - 1)
    else:
        ans += sum_(a)
    #print(ans)
    z = n - k + 1
    t2 = a - z + 1
    #print('ts', t2)
    if t2 >= 0:
        ans += sum_(a - 1) - sum_(t2 - 1)
    else:
        ans += sum_(a - 1)
    #print(ans)
    return (ans <= m)

def bins():
    l = 1
    r = m + 1
    while l + 1 != r:
        m1 = (l + r) // 2
        if check(m1):
            l = m1
        else:
            r = m1
    print(l)

n, m, k = map(int, input().split())
#print(check(2))
bins()


n, m, k = map(int, input().split())
best = 1
sleva = k - 1
sprava = n - k
m -= n

put = 1

while (m >= put):
    m -= put
    best+= 1
    put += (sleva > 0) + (sprava > 0)
    if sleva:
        sleva -= 1
    if sprava:
        sprava -= 1
    if sleva == sprava == 0:
        best += (m // put)
        break

print(best)


def trip(limit, months):
    months.sort(reverse=True)
    count = 0
    if limit <= 0:
        return 0
    for i in months:
        count += 1
        limit -= i
        if limit <= 0:
            return count
    return -1

print trip(int(raw_input()), map(int, raw_input().split()))


def func(n):
    l = list(map(int,input().split()))
    counter = 0
    while n > 0 and l:
        n -= max(l)
        l.pop(l.index(max(l)))
        counter += 1
    if n > 0 and counter >= 12:
        print(-1)
    else:
        print(counter)
n = int(input())
func(n)


x1,y1,x2,y2 = map(int, input().split())
x3,y3,x4,y4 = map(int, input().split())
x5,y5,x6,y6 = map(int, input().split())

if y1 >= y3 and y2 <= y4 and x1 >= x3 and x2 <= x4:
    print("NO")
elif y1 >= y5 and y2 <= y6 and x1 >= x5 and x2 <= x6:
    print("NO")
elif x3 <= x1 and x4 >= x2 and x5 <= x1 and x6 >= x2 and y3 <= y1 <= y5 <=y4 <= y2 <= y6:
    print("NO")
elif x3 <= x1 and x4 >= x2 and x5 <= x1 and x6 >= x2 and y5 <= y1 <= y3 <=y6 <= y2 <= y4:
    print("NO")

elif y3 <= y1 and y4 >= y2 and y5 <= y1 and y6 >= y2 and x3 <= x1 <= x5 <=x4 <= x2 <= x6:
    print("NO")
elif y3 <= y1 and y4 >= y2 and y5 <= y1 and y6 >= y2 and x5 <= x1 <= x3 <=x6 <= x2 <= x4:
    print("NO")

else:
    print("YES")


from itertools import permutations

n,k = map(int,input().split())
a = []
mn = float("inf")
for _ in range(n):
    line = input()
    a.append(list(permutations(line)))

for arr in zip(*a):
    ints = [int(''.join(num)) for num in arr]
    mn = min(mn,max(ints)-min(ints))

print(mn)


#Code by Sounak, IIESTS
#------------------------------warmup----------------------------

import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
from itertools import permutations

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

#-------------------game starts now-----------------------------------------------------
n,d = [int(x) for x in input().split()]
li = []
for i in range(n):
    s = input()
    li.append(s)
st = ""
for i in range(0,d):
    st += str(i)
from itertools import permutations
max_diff = 10**9
for i in permutations(st):
    ans = []
    for j in i:
        ans.append(int(j))
    aa = []
    for j in li:
        k = ""
        for m in ans:
            k += j[m]
        aa.append(int(k))
    mam,mim = max(aa),min(aa)
    max_diff = min(mam-mim,max_diff)
print(max_diff)


import math
n, m, t=map(int,raw_input().split())
ans=math.factorial(n+m)
ans=ans/math.factorial(n+m-t)
ans=ans/math.factorial(t)
if n>=t:
    ans1=math.factorial(n)
    ans1=ans1/math.factorial(t)
    ans1=ans1/math.factorial(n-t)
    ans=ans-ans1
if m>=t:
    ans1=math.factorial(m)
    ans1=ans1/math.factorial(t)
    ans1=ans1/math.factorial(m-t)
    ans=ans-ans1
if m+1>=t:
    k=math.factorial(n)/math.factorial(1)/math.factorial(n-1)
    ans1=math.factorial(m)
    ans1=ans1/math.factorial(t-1)
    ans1=ans1/math.factorial(m+1-t)
    ans1=ans1*k
    ans=ans-ans1
if m+2>=t:
    k=math.factorial(n)/math.factorial(2)/math.factorial(n-2)
    ans1=math.factorial(m)
    ans1=ans1/math.factorial(t-2)
    ans1=ans1/math.factorial(m+2-t)
    ans1=ans1*k
    ans=ans-ans1
if m+3>=t:
    k=math.factorial(n)/math.factorial(3)/math.factorial(n-3)
    ans1=math.factorial(m)
    ans1=ans1/math.factorial(t-3)
    ans1=ans1/math.factorial(m+3-t)
    ans1=ans1*k
    ans=ans-ans1
print ans


import operator as op
import math
from functools import reduce

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom

n,m,t=map(int,input().split())
ways=0
a=4
b=t-a
while(a<=n and b!=0):
	if(b<=m):
		ways+=ncr(n,a)*ncr(m,b)
	a=a+1
	b=t-a
print(int(ways))


n,m=[int(x) for x in input().split()]
a=0
while n*m!=0:
    n=n-1
    m=m-1
    a+=1
if a%2==0:
    print('Malvika')
else:
    print('Akshat')


a = min([int(x) for x in input().split()])
if a%2 == 0:
    print('Malvika')
else:
    print('Akshat')


#coding:utf-8

n = raw_input()
m = raw_input()
lists = m.split(' ')
for i in range(len(lists)):
    lists[i] = int(lists[i])

while min(lists) != max(lists):
    lists = sorted(lists)
    for i in range(len(lists)):
        for j in range(len(lists)):
            if lists[i] < lists[j]:
                lists[j] -= lists[j] / lists[i] * lists[i]
                if lists[j] == 0: lists[j] += lists[i]

print int(n) * min(lists)


# bsdk idhar kya dekhne ko aaya hai, khud kr!!!
# import math
# from itertools import *
# import random
# import calendar
# import datetime
# import webbrowser

n = int(input())
arr = list(map(int, input().split()))
while max(arr) > min(arr):
    index = arr.index(max(arr))
    arr[index] -= min(arr)
print(sum(arr))


if __name__== "__main__":
    input = int(input())

    bin_input = str(bin(input))[2:]
    bin_input = bin_input.rjust(6,'0')
    string_order = [0, 5, 3, 2, 4, 1]
    bin_output = ""
    for order in string_order:
        bin_output += bin_input[order]

    print(int(bin_output,2))


n = input()
domino = []
for i in range(n):
    domino.append(map(int, raw_input().split()))
upper_sum = 0
lower_sum = 0
for i in range(n):
    card = domino[i]
    upper_sum += card[0]
    lower_sum += card[1]
if (upper_sum + lower_sum) % 2 != 0:
    print -1
elif upper_sum % 2 == 0:
    print 0
else:
    flag = True
    for i in range(n):
        if sum(domino[i]) % 2 != 0:
            flag = False
            break
    print -1 if flag else 1


n = int(input())

x = []
y = []
for i in range(n):
    (xi, yi) = map(int, input().split(' '))
    x.append(xi)
    y.append(yi)

xs = sum(x)
ys = sum(y)

if xs % 2 == 0 and ys % 2 == 0:
    print(0)
elif xs % 2 == 1 and ys % 2 == 1:
    dif = False
    for i in range(n):
        if x[i] % 2 == 0 and y[i] % 2 != 0:
            dif = True
        elif x[i] % 2 != 0 and y[i] % 2 == 0:
            dif = True
        if dif:
            break
    if dif:
        print(1)
    else:
        print(-1)
else:
    print(-1)


dp=[[0 for j in range(2001)] for i in range(2001)]
n,m,k=map(int,input().split())
for i in range(1,n+1):
    for j in range(k+1):
        if j==0 and i==1:
            dp[i][j]=m
            continue
        if j<=i-1:
            dp[i][j]=(m-1)*dp[i-1][j-1]+dp[i-1][j]
            dp[i][j]%=998244353
print(dp[n][k])


MOD = 998244353
n, m, k = input().split()

n = int(n)
m = int(m)
k = int(k)

# Taken from https://www.geeksforgeeks.org/binomial-coefficient-dp-9/
def nCr(n , k):
    C = [0 for i in range(k+1)]
    C[0] = 1

    for i in range(1,n+1):
        j = min(i ,k)
        while (j>0):
            C[j] = C[j] + C[j-1]
            j -= 1
    return C[k]

answer = m * nCr(n-1, k) * (m-1)**k
print(answer%MOD)


'''
二维数组转置,排序,lambda表达式函数
'''

mylist = [list(map(int, input().split())),list(map(int, input().split()))]
mylist = list(map(list,zip(*mylist)))
for my in  mylist:
    if my[0]<my[1]:
        my[1]-=my[0]
        my[0]=0
    else:
        my[0]-=my[1]
        my[1]=0
# for i in range(len(mylist)):
#     if mylist[i][0]<mylist[i][1]:
#         mylist[i][1]-=mylist[i][0]
#         mylist[i][0]=0
#     else:
#         mylist[i][0]-=mylist[i][1]
#         mylist[i][1]=0
mylist.sort(key=lambda my:my[0], reverse=True)
i=0 #初始剩余资源
j=0 #目标资源量
while j<3 and i<3:
    while mylist[j][1]>0 and i<3:
        if mylist[i][0]<=mylist[j][1]*2:
            mylist[j][1]-=mylist[i][0]//2
            i+=1
        else:
            mylist[i][0]-=mylist[j][1]*2
            mylist[j][1]=0
    j+=1
if mylist[2][1]+mylist[1][1]+mylist[0][1]>0:
    print("No")
else:
    print("Yes")


(a, b, c) = (int(x) for x in raw_input().split())
(x, y, z) = (int(x) for x in raw_input().split())

ra = 0
rb = 0
rc = 0
rem = 0

if a > x:
    ra = (a - x) / 2
else:
    rem += (x - a)
if b > y:
    rb = (b - y) / 2
else:
    rem += (y - b)
if c > z:
    rc = (c - z) / 2
else:
    rem += (z - c)

if rem <= ra + rb + rc:
    print 'Yes'
else:
    print 'No'


b=int(input())
g=int(input())
n=int(input())
cnt=0
if(b>=g):
    for i in range(b+1):
        if(g>=n-i and n-i>=0):
            #print(g,n-i)
            cnt+=1
    print(cnt)
else:
    for i in range(g+1):
        if(b>=n-i and n-i>=0):
            #print(g,n-i)
            cnt+=1
    print(cnt)


from sys import stdin
b=int(stdin.readline().strip())
g=int(stdin.readline().strip())
n=int(stdin.readline().strip())
st=set()
ans=0
for i in range(b+1):
    for j in range(g+1):
        if j+i==n:
            ans+=1

print(ans)


N = int(input())
eight_amount = input().count("8")
print(min(N // 11, eight_amount))


import collections

n = int(input())
digits = input()

c = collections.Counter(digits)

print("{0}\n".format(min(len(digits) // 11, c['8'])))


import sys
import math
a,b,c=(map(int,sys.stdin.readline().split(' ')))
ans=-1
for i in range(1,1000):
    a=a*10
    d=a//b
    e=d%10
    if(e==c):
        ans=i
        break
print(ans)


from decimal import *
import math

getcontext().prec = 1000000

inputs = [int(x) for x in input().split()]
a = inputs[0]
b = inputs[1]
c = inputs[2]

num = Decimal(a)/Decimal(b)

d = str(num)
found = False
where = 0

pos = -2

at = 0

#print(d)
for _ in d:
	if ( at == 999999 ):
		break
	#print(_)
	if _ == '.':
		found = True
		where = at
		continue
	if found == False:
		continue
	if _ == str(c):
		pos = at - where
		break
	at = at + 1

if ( pos == -2 and c == 0 and at < 999999 ):
	pos = at
print(pos + 1)


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

a, b, c, d = map(int, input().split())
fpb = gcd(c,d)
c = c//fpb;
d = d//fpb;

print(min(a//c, b//d));


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 17 14:55:08 2018

@author: chenzixuan
"""

def gcd(a,b):
    while (a!=0 and b!=0):
        t = a%b
        a = b
        b = t
    return a

def main():
    #print(list(map(int,str.split(input()))))

    [a,b,x,y] = list(map(int,str.split(input())))
    tmp = gcd(x,y)
    x /= tmp
    y /= tmp
    ans = min(int(a/x), int(b/y))
    print(ans)

if __name__ == '__main__':
    main()


def nok(n):
    if n < 3:
        return n
    if not n % 2 and n % 3:
        m = n * (n - 1) * (n - 3)
    else:
        m = 0
    n -= (n % 2 == 0)
    return max(n * (n - 1) * (n - 2), m)

print(nok(int(input())))


from math import ceil

n = int(input())
m = int(input())
if n <= 27:
	print(ceil(m%pow(2,n)))
else:
	print(m)


n,s=map(int,input().split())
c=s//n
d=s%n
print(c if d==0 else c+1)


R=lambda : map(int,input().split())
n,k=R()
print([(k+n-1)//n,1][n>k])


n=int(input())
s=list(filter(lambda x:x!="",input().split("W")))
print(len(s))
for e in s:
    print(len(e),end=" ")


input()
sek=input().split("W")
s=[]
for i in sek:
	 if i!="": s.append(i)
print(len(s))
for i in s:
	if i!="": print(len(i), end=" ")


l=lambda:map(int,raw_input().split())
a,b,c,d,e,f=l()
print (a+b+c)**2-a*a-c*c-e*e


n = int(input())
ar = list(map(int, input().split()))

print(2 + (ar[2] ^ min(ar)))


#Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue
sys.setrecursionlimit(1000000)
#sys.stdin = open("input.txt", "r")

n = int(input())
a = list(map(int, input().split()))
print((a[2]^min(a))+2)


import sys

from collections import Counter

def distinct_factors(n):
	ans = 1
	for x in range(2, n):
		ans += (n%x == 0)
	return ans

def main():
	n = int(input())

	mod = 998244353

	dp = [-1]*(n+1)

	pre = 0

	d = [0]*(n+1)

	for i in range(1, n+1):
		for j in range(i, n+1, i):
			d[j] += 1

	for i in range(1, n+1):
		dp[i] = (pre+d[i])%mod
		pre += dp[i]

	return (dp[n])%mod

print(main())


#------------------------template--------------------------#
import os
import sys
import math
import collections
import functools
import itertools
# from fractions import *
import heapq
import bisect
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcde'
M = 10**9 + 7
EPS = 1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def INT():return int(input())
def STR():return input()
def INTs():return tuple(map(int,input().split()))
def ARRINT():return [int(i) for i in input().split()]
def ARRSTR():return [i for i in input().split()]

#-------------------------code---------------------------#

MOD = 998244353
n = INT()

dp = [0]*(n+1)
dp[0] = 1

for i in range(1, n+1):
    j = 2*i
    while j < n+1:
        dp[j] += 1
        j += i

tmp = 1
for i in range(1, n+1):
    dp[i] += tmp
    dp[i] %= MOD
    tmp += dp[i]
    tmp %= MOD

print(dp[-1])


from math import acos, pi
[n,R,r] = list(map(float,input().split()))
eps = 1e-9
if R < r:
    print('NO')
else:
    if R == r:
        if n == 1:
            print('YES')
        else:
            print('NO')
    elif R < 2*r:
        if n > 1:
            print('NO')
        else:
            print('YES')
    else:
        a = acos(1 - 2*r**2/(R-r)**2)
        if a-eps <= 2*pi/n:
            print('YES')
        else:
            print('NO')


import sys
import re
import math

def foo(n, R, r):
    if R < r:
        return False
    if n == 1:
        return True
    if r == R:
        return False

    if r == R - r:
        return n <= 2

    if r > R - r:
        return False

    a = math.asin(float(r) / (R - r)) * 2.0
    return 2.0 * math.pi + 1e-9 >= a * n

n, R, r = map(int, raw_input().split())
print ['NO', 'YES'][foo(n, R, r)]


def debin(s):
    ret = 0
    mn = 1
    for i in range(len(s)-1,-1,-1):
        ret += int(s[i]) * mn
        mn *=2
    return ret
st = set()
def ch(x,y,deep):
    if x in st:
        return 0
    st.add(x)
    if x == y:
        return 1
    if deep == 150:
        return 0
    s = bin(x)[2:]
    if ch(debin(s[::-1]),y,deep+1) or ch(debin('1' + s[::-1]),y,deep+1):
        return 1
    return 0

x, y = map(int, input().split())
if ch(x,y,0):
    print("YES")
else:
    print("NO")


#!/usr/bin/env python3
# from typing import *

import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
    return sys.stdin.readline()[:-1]

sys.setrecursionlimit(1000000)

# _INPUT = """8935891487501725 71487131900013807
# """
# sys.stdin = io.StringIO(_INPUT)

INF = 10**10

YES = 'YES'
NO = 'NO'

def dfs(s, SY):
    if s == SY:
        return True
    n = int(s)
    if n in ng:
        return False
    if len(s) > 100:
        return False
    ng.add(n)
    # print(n)
    for s1 in [str(int(s[::-1])), (s+'1')[::-1]]:
        if s1 in ng:
            continue
        if dfs(s1, SY):
            return True
    return False

ng = set()

def solve(X, Y):
    if X == Y:
        return 'YES'

    SX = bin(X)[2:]
    SY = bin(Y)[2:]

    if dfs(SX, SY):
        return 'YES'

    return 'NO'

X, Y = map(int, input().split())
print(solve(X, Y))


def digit(x):
    return x if x<10 else x//10+9-(0 if str(x)[0]<=str(x)[-1] else 1)
l,r = map(int,input().split())
print(digit(r) - digit(l-1))


l,r=map(int,raw_input().split())
def get(x): return x if x<10 else (x/10+8+(0 if str(x)[0]>str(x)[-1] else 1))
print get(r)-get(l-1)


# import sys
# sys.stdin=open("input.in",'r')
# sys.stdout=open("out1.out",'w')
a,b=map(int,input().split())
i=1
while True:
	if i%2!=0:
		if a<i:
			print("Vladik")
			break
		a-=i
	else:
		if b<i:
			print("Valera")
			break
		b-=i
	i+=1


import math
arr = input().split()
a = int(arr[0])
b = int(arr[1])

i = 1
while a >= 0 and b >= 0:
	if i % 2 == 0:
		b -= i
	else:
		a -= i
	i += 1

if a < 0:
	print('Vladik')
else:
	print('Valera')


n = int(input())
p = list(map(int,input().split()))
t = int(input())
p.sort()
ans = 0
i = 0
for j in range(n):
    while p[j]-p[i]>t:
        i=i+1
    ans=max(ans,j-i+1)
print(ans)


n = int(input())
m = list(map(int, input().split()))
t = int(input())
m.sort()
if n == 1 or len(m) == 1:
    print(1)
elif m[-1]-m[0] <= t:
    print(n)
else:
    mx = 1
    for i in range(n-1):
        ma = 1
        fr = m[i]
        for j in range(i+1, n):
            if m[j]-fr <= t:
                ma += 1
            else:
                break
        mx = max(ma, mx)
    print(mx)


a1,b1=map(int,raw_input().split())
a2,b2=map(int,raw_input().split())
a3,b3=map(int,raw_input().split())
if (a2+a3<=a1 and max(b2,b3)<=b1):
	print "YES"
elif (a2+a3<=b1 and max(b2,b3)<=a1):
	print "YES"
elif (a2+b3<=a1 and max(b2,a3)<=b1):
	print "YES"
elif (a2+b3<=b1 and max(b2,a3)<=a1):
	print "YES"
elif (a3+b2<=a1 and max(a2,b3)<=b1):
	print "YES"
elif (a3+b2<=b1 and max(a2,b3)<=a1):
	print "YES"
elif (b2+b3<=(a1) and max(a2,a3)<=(b1)):
	print "YES"
elif (b2+b3<=(b1) and max(a2,a3)<=(a1)):
	print "YES"
else:
	print "NO"


x, y = map(int, input().split())
a, b = map(int, input().split())
c, d = map(int, input().split())

def solve():
  for X, Y in [(x, y), (y, x)]:
    for A, B in [(a, b), (b, a)]:
      for C, D in [(c, d), (d, c)]:
        if A + C <= X and max(B, D) <= Y:
          return 'YES'
  return 'NO'

print(solve())


N = int(input())
s1 = [list(input()) for i in range(N)]
s2 = [list(input()) for i in range(N)]

def rotate(s):
    ret = [[None for i in range(N)] for j in range(N)]
    for i in range(N):
        for j in range(N):
            ret[i][j] = s[j][N-1-i]
    return ret

def v_mirror(s):
    return list(reversed(s))

def h_mirror(s):
    return [list(reversed(row)) for row in s]

def solve():
    global s1
    for i in range(4):
        if s1 == s2: return True
        if v_mirror(s1) == s2: return True
        if h_mirror(s1) == s2: return True
        if v_mirror(h_mirror(s1)) == s2: return True
        s1 = rotate(s1)
    return False

print('Yes' if solve() else 'No')


from sys import stdin

n = int(stdin.readline())

def eq(m1, m2):
    for i in range(n):
        if m1[i] != m2[i]:
            return False
    return True

def fleq(m1, m2):
    return eq(m1, m2) or eq(m1, fliph(m2)) or eq(m1, flipv(m2))

def fliph(m):
    return [row[::-1] for row in m]

def flipv(m):
    return m[::-1]

def rot(m):
    mr = ['' for _ in range(n)]
    for i in range(n):
        x = ''
        for j in range(n):
            x = x + m[j][n-i-1]
        mr[i] = x
    return mr

u = [stdin.readline()[:-1] for _ in range(n)]
v = [stdin.readline()[:-1] for _ in range(n)]
v90 = rot(v)
v180 = rot(v90)
v270 = rot(v180)

if fleq(u, v) or fleq(u, v90) or fleq(u, v180) or fleq(u, v270):
    print('Yes')
else:
    print('No')


def add(a,b):
    if a+b>=mod:
        return (a+b)%mod
    return a+b
n=int(input())*2
s=input()
d=[[0,0] for i in range(len(s)+1)]
aux=''
for i in range(len(s)):
    if s[i]=='(':
        d[i][1]=i+1
        x=aux+')'
        for j in range(1,i+2):
            if x[j::] ==s[0:len(x)-j]:
                d[i][0]=len(x[j::])
                break
    else:
        d[i][0]=i+1
        x=aux+'('
        for j in range(1,i+2):
            if x[j::]  ==s[0:len(x)-j]:
                d[i][1]=len(x[j::])
                break
    aux+=s[i]
d[len(s)][1]=len(s)
d[len(s)][0]=len(s)
dp=[[[0 for i in range(len(s)+1)] for j in range(n//2+1)] for k in range(n+1)]
dp[0][0][0]=1
mod=10**9+7
for i in range(n):
    for j in range(1,(n//2)+1):
        for k in range(len(s)+1):
            dp[i+1][j-1][d[k][0]]=(dp[i][j][k]+dp[i+1][j-1][d[k][0]])%mod
    for j in range(n//2):
        for k in range(len(s)+1):
            dp[i+1][j+1][d[k][1]]=(dp[i][j][k]+dp[i+1][j+1][d[k][1]])%mod
print(dp[n][0][len(s)]%mod)


def add(a,b):
    if a+b>=mod:
        return (a+b)%mod
    return a+b
n=int(input())*2
s=input()
d=[[0,0] for i in range(len(s)+1)]
aux=''
for i in range(len(s)):
    if s[i]=='(':
        d[i][1]=i+1
        x=aux+')'
        for j in range(1,i+2):
            if x[j::] ==s[0:len(x)-j]:
                d[i][0]=len(x[j::])
                break
    else:
        d[i][0]=i+1
        x=aux+'('
        for j in range(1,i+2):
            if x[j::]  ==s[0:len(x)-j]:
                d[i][1]=len(x[j::])
                break
    aux+=s[i]
d[len(s)][1]=len(s)
d[len(s)][0]=len(s)
dp=[[[0 for i in range(len(s)+1)] for j in range(n//2+1)] for k in range(n+1)]
dp[0][0][0]=1
mod=10**9+7
for i in range(n):
    for j in range(1,(n//2)+1):
        for k in range(len(s)+1):
            dp[i+1][j-1][d[k][0]]=add(dp[i][j][k],dp[i+1][j-1][d[k][0]])
    for j in range(n//2):
        for k in range(len(s)+1):
            dp[i+1][j+1][d[k][1]]=add(dp[i][j][k],dp[i+1][j+1][d[k][1]])
print(dp[n][0][len(s)]%mod)


n,m=map(int,input().split())
fr=m-1
sr=n-m
ans=0
if(fr<sr):
    ans=m+1
else:
    ans=m-1
if(n==1):
    ans=1
print(ans)


b,a=map(int,input().split())
print(max(1,a-1 if (a-2) >= (b-(a+1)) else a+1))


data = [int(info) for info in input().split(' ')]

mid = data[0]
ma = max(data)
mi = min(data)

for i in data:
	if i < ma and i > mi:
		mid = i

print((ma - mid) + (mid - mi))


x = map(int, raw_input().split())
x = sorted(x)
print (x[1] - x[0]) + (x[2] - x[1])


w1,h1,w2,h2 = [ int(i) for i in input().split(" ")]

total = 4 + w1 + w2 + 2 * h1 + 2 * h2 + (w1 - w2 )

print(total)


from itertools import product

s1 = sum([1 if i == '+' else -1 for i in raw_input()])
s2 = raw_input()
q = s2.count('?')
x = []
if q:
    s2 = s2.replace('?', '')
    for j in set(product('-+', repeat=q)):
        j = ''.join(j)
        x.append(sum([1 if i == '+' else -1 for i in j + s2]))
    a = len(x)
    print float(len(filter(lambda y: y == s1, x))) / float(a)
else:
    x = sum([1 if i == '+' else -1 for i in s2])
    if x == s1:
        print 1
    else:
        print 0


def getLine():
    return list(map(int,input().split()))

def val(s,c):

    ssum = 0
    ssum+=s.count('+')
    ssum-=s.count('-')

    return ssum

def val2(s,c):
    ssum = 0
    ssum+=s.count('1')
    ssum-=s.count('0')

    ssum-=(c - len(s))

    return ssum

def main():
    send = input()
    recv = input()

    needed_val = val(send,len(send))
    rval = val(recv,len(recv))

    # print(send)
    if '?' not in recv:
        if needed_val== rval:
            print(1)
            return
        else:
            print(0)
            return

    ques = recv.count('?')
    fav = 0

    # print(needed_val, rval)
    for i in range(2**ques):
        tmp = val2(bin(i)[2:],ques) + rval
        # print(tmp)
        # print(tmp)
        if tmp == needed_val:
            fav+=1

    # print(fav)
    print(fav/pow(2,ques))

main()


def main():
	w, m = map(int, input().split())
	while m > 1:
		c = m % w
		if c not in {0, 1, w - 1}:
			return print('NO')
		m //= w
		if c == w - 1:
			m += 1
	print('YES')
main()


w,m=map(int,input().split())

def f(m,w):
    while m!=0:
        x=(m+1)%w
        if x==0:
            m=(m+1)//w
        elif x<3:
            m=m//w
        else:
            return False

    return True
if w==2:
    print("YES")
elif f(m,w):
    print("YES")
else:
    print("NO")


chess=[]*8;
for i in range(8):a=input();chess.append(a)
R=chess.count("WBWBWBWB");D=chess.count("BWBWBWBW");counter=R+D
if(counter is 8):print("YES")
else:print("NO")


def solve(board):
  for row in board:
    for i in range(1, 8):
      if row[i] == row[i-1]:
        return False
  return True

board = [raw_input() for i in range(8)]
print 'YES' if solve(board) else 'NO'


a = input()
b = int(input())
lst = sorted(a)
c = 0
for i in range(len(lst)):
    for j in range(len(lst) - 1, i - 1, -1):
        x = lst[:i] + [lst[j]] + sorted(lst[i:j]) + lst[j + 1:]

        if int(''.join(x)) <= b and int(''.join(x)) > c:
            c = int(''.join(x))
            lst = x
print(int(''.join(lst)))


from collections import Counter

def max_num(a,b):
    if len(b) > len(a):
        val=''.join(sorted(a, reverse=True))
        return int(val)
    else:
        # int_a=int(''.join(sorted(a)))
        # int_b=int(''.join(b))
        # for i in range(int_b,int_a-1,-1):
        #     # print(str(i),str(int_a))
        #     if Counter(str(i)) == Counter(str(''.join(a))):
        #         return i
        res=''
        for i in b:
            if i in a:
                a.remove(i)
                if ''.join(b[len(res)+1:]) >= ''.join(sorted(a)):
                    res+=i
                else:
                    a.append(i)
                    break
            else:
                break
        # print(res)
        # return res
        new_b=b[len(res):]
        if new_b==[]:
            return res

        for i in new_b:
            for j in range(int(i)-1,-1,-1):
                if str(j) in a:
                    a.remove(str(j))
                    return res+str(j)+''.join(sorted(a, reverse=True))

a=list(input())
b=list(input())
print(max_num(a,b))


import sys
twopow128 = 2**128-1
def bp(a, n):
	res = 1
	while n:
		if (n & 1):
			res *= a
			res %= twopow128
		a *= a
		a %= twopow128
		n >>= 1
	return res

k,b,n,t=sys.stdin.readline().split(' ')
k,b,n,t=int(k),int(b),int(n),int(t)
if t==1:
	print n
	sys.exit(0)
kn=bp(k,n)
kxt=kn*t
knn=kn
x=n
while x>=0:
	if (kxt < knn): break
	knn+=(kn/k)*b
	kn/=k
	kxt/=k
	x-=1
print x+1


k,b,n,t = map(int,raw_input().split())
def get_p():
	global k,b,n,t,z
	if k == 1:
		z = 1 + n * b
		if t >= z:
			return 0
		return   (z-t)/b if (z-t)%b==0 else(z-t)/b+1
	tt =  (k-1) + b
	z = t * (k-1) + b
#	print tt,z
	ans = 0
	for i in range(0,n+1):
		if (tt * (k ** i) <= z):
			ans = i
		else:
			break
	return max(n - ans,0)
print get_p()


#Problem Name : 11B - Jumping Jack
#Execution Time : 124 ms
#Memory : 0 KB
n = abs(int(raw_input()))

soma = 0
k = 1
while soma < n or soma%2 != n%2:
    soma += k
    k += 1

print k-1


def numberOfJumps(n):
    n = abs(n)
    j = 0
    while True:
        s = j*(j+1)/2
        if s >= n and not (s - n)%2:
            break
        j += 1
    return j

i = int(raw_input())
print numberOfJumps(i)


def solve(str,n,k):
    g=str.index('G')
    t=str.index('T')
    if g>t:
        for i in range(t,g+1,k):
            if str[i]=='G':
                return True
            if str[i]=='#':
                return False
    else:
        for i in range(g,t+1,k):
            if str[i]=='T':
                return True
            if str[i]=='#':
                return False
    return False

strnk=(input())
str1=strnk.split(" ")
n=int(str1[0])
k=int(str1[1])
str=input()
if solve(str,n,k)==True:
    print("YES")
else:
    print("NO")


n, k = map(int, input().split())
a = input()
g = 1
l, r = a.index('G'), a.index('T')
if l > r:
    l, r = r, l
while l + k<= r:
    if a[l] == '#':
        g = 0
    l += k
if l == r and g:
    print('YES')
else:
    print('NO')


def ListToString(x):
    string1 = ""
    return (string1.join(x))

numindex = []
x = input()
nums = [int(n) for n in x.split()]
letters = str(input())
letterlist = list(letters)

for i in range (0, nums[1], 1):
    for j in range (0, nums[0]-1, 1):
        if (letterlist[j] == "B" and letterlist[j + 1] == "G"):
            # temp = letterlist[j]
            # letterlist[j] = letterlist[j+1]
            # letterlist[j+1] = temp
            numtemp = j
            numindex.append(numtemp)
        else:
            continue
    for k in range (0, len(numindex), 1):
        temp = letterlist[numindex[k]]
        letterlist[numindex[k]] = letterlist[numindex[k] + 1]
        letterlist[numindex[k] + 1] = temp
    numindex.clear()

print(ListToString(letterlist))


s = raw_input().split()
n = int(s[0])
t = int(s[1])

s = raw_input()
a = []
for i in s:
	a+= [i]

while t > 0:
	j = 0
	while j < len(s)-1:
		if a[j] == 'B' and a[j+1] == 'G':
			a[j+1] = 'B'
			a[j] = 'G'
			j +=1
		j += 1

	t -= 1
t =""
for i in a:
	t += i
# test code
print t


N, K = map(int, input().split())
pre = [input()]
ans = 0
k = 1
f = 0
while True:
    if k >= K:
        print(ans)
        break
    if len(pre) == 0:
        print(-1)
        break
    post = []
    for s in pre:
        for i in range(len(s)):
            t = s[:i] + s[i+1:]
            if t not in post:
                k += 1
                post.append(t)
                ans += N-len(t)
                if k >= K:
                    print(ans)
                    f = 1
                    break
        if f:
            break
    if f:
        break
    pre = post


from sys import stdin, stdout, exit

def price():
    n,k = map(int, stdin.readline().split())
    s = stdin.readline().strip()

    todo = [s]
    ans = 0
    found = {s:True}
    k -= 1
    while todo and k > 0:
        nexts = []
    #    print(todo)
        for wd in todo:
            for i in range(len(wd)):
                candidate = wd[:i] + wd[i+1:]
    #            print(candidate)
                if candidate not in found:
                    nexts.append(candidate)
                    found[candidate] = True
                    ans += n - len(candidate)
                    k-=1
                    if k == 0:
                        return ans
        todo = nexts
    if k == 0:
        return ans
    return -1

print(price())


import sys
from collections import defaultdict, Counter
from itertools import permutations, combinations
from math import sin, cos, asin, acos, tan, atan, pi

sys.setrecursionlimit(10 ** 6)

def pyes_no(condition, yes = "YES", no = "NO", none = "-1") :
  if condition == None:
    print (none)
  elif condition :
    print (yes)
  else :
    print (no)

def plist(a, s = ' ') :
  print (s.join(map(str, a)))

def rint() :
  return int(sys.stdin.readline())

def rstr() :
  return sys.stdin.readline().strip()

def rints() :
  return map(int, sys.stdin.readline().split())

def rfield(n, m = None) :
  if m == None :
    m = n

  field = []
  for i in xrange(n) :
    chars = sys.stdin.readline().strip()
    assert(len(chars) == m)
    field.append(chars)
  return field

def pfield(field, separator = '') :
  print ('\n'.join(map(lambda x: separator.join(x), field)))

def check_field_equal(field, i, j, value) :
  if i >= 0 and i < len(field) and j >= 0 and j < len(field[i]) :
    return value == field[i][j]
  return None

def digits(x, p) :
  digits = []
  while x > 0 :
    digits.append(x % p)
    x //= p
  return digits[::-1]

def undigits(x, p) :
  value = 0
  for d in x :
    value *= p
    value += d
  return value

def modpower(a, n, mod) :
  r = a ** (n % 2)
  if n > 1 :
    r *= modpower(a, n // 2, mod) ** 2
  return r % mod

def gcd(a, b) :
  if a > b :
    a, b = b, a

  while a > 0 :
    a, b = b % a, a

  return b

def vector_distance(a, b) :
  diff = vector_diff(a, b)

  return scalar_product(diff, diff) ** 0.5

def vector_inverse(v) :
  r = [-x for x in v]

  return tuple(r)

def vector_diff(a, b) :
  return vector_sum(a, vector_inverse(b))

def vector_sum(a, b) :
  r = [c1 + c2 for c1, c2 in zip(a, b)]

  return tuple(r)

def scalar_product(a, b) :
  r = 0
  for c1, c2 in zip(a, b) :
    r += c1 * c2

  return r

def check_rectangle(points) :
  assert(len(points) == 4)

  A, B, C, D = points

  for A1, A2, A3, A4 in [
    (A, B, C, D),
    (A, C, B, D),
    (A, B, D, C),
    (A, C, D, B),
    (A, D, B, C),
    (A, D, C, B),
  ] :
    sides = (
      vector_diff(A1, A2),
      vector_diff(A2, A3),
      vector_diff(A3, A4),
      vector_diff(A4, A1),
    )
    if all(scalar_product(s1, s2) == 0 for s1, s2 in zip(sides, sides[1:])) :
       return True
  return False

def check_square(points) :
  if not check_rectangle(points) :
    return False
  A, B, C, D = points

  for A1, A2, A3, A4 in [
    (A, B, C, D),
    (A, C, B, D),
    (A, B, D, C),
    (A, C, D, B),
    (A, D, B, C),
    (A, D, C, B),
  ] :
    side_lengths = [
      (first[0] - next[0]) ** 2 + (first[1] - next[1]) ** 2 for first, next in zip([A1, A2, A3, A4], [A2, A3, A4, A1])
    ]
    if len(set(side_lengths)) == 1 :
      return True

  return False

def check_right(p) :
  # Check if there are same points
  for a, b in [
    (p[0], p[1]),
    (p[0], p[2]),
    (p[1], p[2]),
  ] :
    if a[0] == b[0] and a[1] == b[1] :
      return False

  a, b, c = p
  a, b, c = vector_diff(a, b), vector_diff(b, c), vector_diff(c, a)

  return scalar_product(a, b) * scalar_product(a, c) * scalar_product(b, c) == 0

def modmatrixproduct(a, b, mod) :
  n, m1 = len(a), len(a[0])
  m2, k = len(b), len(b[0])

  assert(m1 == m2)
  m = m1

  r = [[0] * k for i in range(n)]
  for i in range(n) :
    for j in range(k) :
      for l in range(m) :
        r[i][j] += a[i][l] * b[l][j]
      r[i][j] %= mod
  return r

def modmatrixpower(a, n, mod) :
  magic = 2
  for m in [2, 3, 5, 7] :
    if n % m == 0 :
      magic = m
      break

  r = None
  if n < magic :
    r = a
    n -= 1
  else :
    s = modmatrixpower(a, n // magic, mod)
    r = s
    for i in range(magic - 1) :
      r = modmatrixproduct(r, s, mod)

  for i in range(n % magic) :
    r = modmatrixproduct(r, a, mod)

  return r

k, n, w = rints()

price = k * w * (w + 1) / 2

print max(0, price - n)


k,n,w=map(int,input().split())
s=((2*k+k*(w-1))*w)//2
if s>n:
    print(s-n)
else:
    print(0)


n,m=map(int,raw_input().split())
co=[0 for i in xrange(101)]
for i in map(int,raw_input().split()): co[i] += 1
f=False
for t in xrange(m, 0, -1):
    have = 0
    for i in co:
        have += i / t
    if have >= n:
        f = True
        ans = t
        break
if not f:
    ans = 0
print ans


def main():
    n, m = map(int, input().split())
    if n > m:
        print(0)
        return
    cnt = {}
    for a in map(int, input().split()):
        cnt[a] = cnt.get(a, 0) + 1
    lo, hi = 1, 100
    for _ in range(8):
        mid, x = (lo + hi) // 2, n
        for c in cnt.values():
            x -= c // mid
        if x > 0:
            hi = mid
        else:
            lo = mid + 1
    print(lo - 1)

if __name__ == '__main__':
    main()


t=input().split()
a=t[0][0]
b=t[0][1]
# print(a)
# print(b)

# a=set(t)
# for i in t:

# print(t)
s=input()
# print(s)
if a in s:
	print("YES")
elif b in s:
	print("YES")
else:
	print("NO")


suit=input('')
suit=suit.upper()
c1,c2,c3,c4,c5=input( ).split(" ")
if suit[0]==c1[0]or suit[1]==c1[1] or suit[0]==c1[1] or suit[1]== c1[0]:
    print("YES")
elif suit[0] == c2[0] or suit[1] == c2[1] or suit[0]==c2[1] or suit[1]== c2[0]:
    print("YES")
elif suit[0] == c3[0] or suit[1] == c3[1] or suit[0]==c3[1] or suit[1]== c3[0]:
    print("YES")
elif suit[0] == c4[0] or suit[1] == c4[1] or suit[0]==c4[1] or suit[1]== c4[0]:
    print("YES")
elif suit[0] == c5[0] or suit[1] == c5[1] or suit[0]==c5[1] or suit[1]== c5[0]:
    print("YES")
else:
    print("NO")


n = int(raw_input())

def prime(n):
	if n<=3:
		return True
	else:
		for i in range(2,int(n**(0.5))+1):
			if n % i == 0:
				return False
		return True

if prime(n):
	print 1
elif n % 2 == 0:
	print 2
elif prime(n-2):
	print 2
else:
	print 3


"""
                            pppppppppppppppppppp
                         ppppp  ppppppppppppppppppp
                      ppppppp    ppppppppppppppppppppp
                      pppppppp  pppppppppppppppppppppp
                      pppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppppp
       ppppppppppppppppppppppppppppppppppppppppppppppp  pppppppppppppppppppp
      pppppppppppppppppppppppppppppppppppppppppppppppp  ppppppppppppppppppppp
     ppppppppppppppppppppppppppppppppppppppppppppppppp  pppppppppppppppppppppp
    ppppppppppppppppppppppppppppppppppppppppppppppp    pppppppppppppppppppppppp
   pppppppppppppppppppppppppppppppppppppppppppppp     pppppppppppppppppppppppppp
  ppppppppppppppppppppppppppppppppppppppppppppp      pppppppppppppppppppppppppppp
  pppppppppppppppppppppppppppppppp               pppppppppppppppppppppppppppppppp
  pppppppppppppppppppppppppppp     pppppppppppppppppppppppppppppppppppppppppppppp
  ppppppppppppppppppppppppppp    pppppppppppppppppppppppppppppppppppppppppppppppp
    pppppppppppppppppppppppp  pppppppppppppppppppppppppppppppppppppppppppppppppp
     ppppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppppppp
      pppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppppp
       ppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppppp
                              pppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppp  pppppppp
                              ppppppppppppppppppppp    ppppppp
                                 ppppppppppppppppppp  ppppp
                                    pppppppppppppppppppp
"""

import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
# sys.setrecursionlimit(pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(var): sys.stdout.write(str(var))
def outa(*var, end="\n"): sys.stdout.write(' '.join(map(str, var)) + end)
def l(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]

def prime(number):
    if number <= 1:
        return False
    if number == 2:
        return True
    if not(number & 1):
        return False
    temp = 2
    while temp * temp <= number:
        if number % temp == 0:
            return False
        temp += 1
    return True

n = int(data())
if prime(n):
    out(1)
    exit()
if not(n & 1):
    out(2)
    exit()
if prime(n-2):
    out(2)
    exit()
out(3)


def mask(num):
	s = list(num)
	res = []
	for c in s:
		if c == '4' or c == '7':
			res.append(c)
	return ''.join(res)

if __name__ == "__main__":
	a, b = [s for s in raw_input().split(" ")]
	res = -1
	x = a
	while res == -1:
		x = str(int(x) + 1)
		m = mask(x)
		if m == b:
			res = x
	print res


a, b = [int(x) for x in raw_input().split(" ")]
while 1:
    a=a+1
    ap=a
    for rag in range(4),range(5,7),range(8,10):
        for c in [str(y) for y in rag]:
            ap = str(ap).replace(c,"")
    if ap == "": ap = "0"
    if int(ap) == b:
        print a
        break


def main():
    n, m = map(int, raw_input().split())
    mod = 1000000007
    s, r = 1, 0
    for i in xrange(n):
        s, r = (s * 2 - r) * m % mod, (r * (m - 1) + s) % mod
    print s
main()


mod=10**9+7
inn=raw_input()
n,m=inn.split(' ')
m=int(m)
n=int(n)
res=m+m
pow=m
for i in xrange(1,n):
    res=(m+m-1)*res+pow
    res%=mod
    pow=pow*m%mod
print res


n, k = map(int, raw_input().strip().split())
if (n / k) % 2 == 1:
    print "YES"
else:
    print "NO"


n,k=map(int,raw_input().split())
r=n/k
if r%2==1:
    print "YES"
else:
    print "NO"


first = int (input ())

num = [first]

visit1 = 0
while True :

    if first == 1:
        visit1 += 1
    if visit1 == 2 :
        break

    first = first +1
    while first % 10 == 0:
        first = first //10

    if first not in num:
        num.append(first)

#num.sort()
#print (num)
print (len(num))


def Next(num):
    num = int(num)
    result = str(num + 1)
    #print(result, result[len(result)-1])
    while result[len(result)-1] == '0':
        result = result[:-1]
        #print(result, result[len(result)-1])
    return result

num = input ()
count = 1
while True:
    if len(num) == 1:
        if num == '0':
            count = 10
            break
        else:
            count = 9
            break
    #print(num)
    else:
        count += 1
        num = Next(num)
        #print("count = ", count)
        if len(num) == 1:
            count += 8
            break
print(count)


#In the name of Allah

from sys import stdin, stdout
input = stdin.readline

n, a, b, c = map(int, input().split())
dp = [0] + [-float("inf")] * n

for i in range(a, n + 1):
         dp[i] = max(dp[i], dp[i - a] + 1)

for i in range(b, n + 1):
         dp[i] = max(dp[i], dp[i - b] + 1)

for i in range(c, n + 1):
         dp[i] = max(dp[i], dp[i - c] + 1)

stdout.write(str(dp[n]))


n,a,b,c=list(map(int,input().split()))
ans=1
for i in range(n+1):
    for j in range(n+1):
        k=n-a*i-b*j
        if(k>=0 and k%c==0):
            ans=max(ans,(i+j+k//c))
print(ans)


n=int(input())
c=1
if c==1 :
    d=str(n)
    for i in range(1,100) :
        n=n+1
        n=str(n)
        if str(n).count('8')>0 :
            print(int(n)-int(d))

            c=0
            break
        n=int(n)


a=int(input())
if a>0 or a<=-9:
    for i in range(a,10000000000000000000000):
        k=i+1
        k=str(k)
        if '8' in k:
            k=int(k)
            print(k-a)
            break
        else:
            continue
elif -9<a<=0:
    print(8-a)


mod = 1000000009

def mpow(x, y):
    if y == 0:
        return 1
    ans = mpow(x, y/2)
    ans = (ans * ans) % mod
    if y%2 > 0:
        ans = (ans * x) % mod
    return ans

n, m, k = map(int, raw_input().split())
fr = n % k + (n/k)*(k - 1)
if fr >= m:
    ans = m
else:
    a = m - fr
    fr -= a*(k-1)
    ans = mpow(2, a)
    ans = (ans + mod - 1) % mod
    ans = (ans * 2) % mod
    ans = (ans * k) % mod
    ans = (ans + fr) % mod
print ans


n,m,k=map(int,raw_input().split())
M=10**9+9
x=max(n/k-n+m,0)
a=k*2*(pow(2,x,M) - 1)
print (a+m-k*x+M)%M


def main():
    R=lambda:map(int,input().split())
    n,k=R()
    a=list(R())
    m=n//k
    ans=0
    for i in range(k):
        c=[n,0,0]
        for j in range(m):
            c[a[j*k+i]]+=1
        ans+=min(c)
    print(ans)

main()


n, k = map(int, raw_input().strip().split())
a = map(int, raw_input().strip().split())

ka = 0
et = [[0 for j in range(n/k)] for i in range(k)]

for i in range(k):
    for j in range(n/k):
        et[i][j] = a[i+k*j]

for i in range(k):
    if len(set(et[i])) > 1:
        ka = ka + min(et[i].count(1), et[i].count(2))

print ka


import math
n=int(input())
a=[int(i) for i in input().split()]
l=[]
for i in range(1,len(a)):
    l.append(abs(a[i-1]-a[i]))
if(len(set(l))==1):
    if(a[1]>=a[0]):
        print(a[len(a)-1]+(l[0]))
    else:
        print(a[len(a)-1]-l[0])
else:
    print(a[len(a)-1])


def checkAP(s):
    d=s[1]-s[0]
    for i in range(len(s)-1):
        if(s[i+1]-s[i]!=d):
            return False
            break
    return True
a=int(input())
s=list(map(int,input().strip().split()))
if(a==1):
    print(s[0])
elif(a==2):
    print(s[1]+s[1]-s[0])
else:
    if(checkAP(s)==True):
        print(s[0]+a*(s[1]-s[0]))
    else:
        print(s[a-1])


def dist(x, y):
    if x > y: x, y = y, x
    return min(y-x, x+12-y)

def solve(a, b, c):
    for x, y, z in [(a, b, c), (b, c, a), (c, a, b)]:
        d1, d2, d3 = dist(x, y), dist(y, z), dist(x, z)
        if d1 == 3 and d2 == 4 and d3 == 12-7:
            return "minor"
        if d1 == 4 and d2 == 3 and d3 == 12-7:
            return "major"
    return "strange"

a, b, c = map(lambda x: ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'B', 'H'].index(x), raw_input().split())
a, b, c = sorted([a, b, c])
print solve(a, b, c)


def make_s(lst):
    while True:
        lst.sort()
        for i in range(len(lst) - 1):
            if lst[i] == lst[i + 1]:
                lst[i] -= 1
                break
        else:
            break
    return sum([x for x in lst if x > 0])

n = int(input())
a = [int(i) for i in input().split()]
print(make_s(a))


n = int(input())
s = sorted([int(i)for i in input().split()])
NON = []
for i in range(n):
    if s[i] in NON:
        while s[i] in NON and s[i] > 0:
            s[i] -= 1
        NON.append(s[i])
    else:
        NON.append(s[i])
print(sum(s))


l, d, v, g, r = map(int, input ().split ())
s = (d / v) % (g + r)
print(l / v + (s >= g) * (g + r - s))


'''

   			 ||Sri:||

                      __|
 ______________|_________________________
      |    |   ___|    |    |    ___|      |      |    |___
 /\  /\    |   |___    |    |   |___|      |      |    |___|
/  \/  \   |   ___|    |    |         |_/    |___|    |___

I am a beginner. Feel free to send tutorials/help to srinivasan1995@gmail.com.

Codeforces, SPOJ handle: desikachariar.
Hackerrank, Codechef handle: Prof_Calculus.

Advices/Help are welcome. You will definitely get a thanks in return. Comments to be avoided.

College: International Institute of Information Technology, Bangalore.

'''

import math

def fn():
	return

if __name__ == '__main__':
	l,d,v,g,r = [float(pp) for pp in raw_input().split(' ')]
	total_time=d/v
	if (float(total_time))%(float(r+g)) >= g:
		total_time+=r - (((total_time)%(r+g)) - g)
	total_time+= (l-d)/v
	print total_time


from __future__ import print_function
# import numpy as np
# import numpypy as np
import sys
input = sys.stdin.readline

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)
    return

# import math
# import string
# import fractions
# from fractions import Fraction
# from fractions import gcd

# def lcm(n,m):
#     return int(n*m/gcd(n,m))

# import re
# import array
# import copy
# import functools
# import operator

# import collections
# import itertools
# import bisect
# import heapq

# from heapq import heappush
# from heapq import heappop
# from heapq import heappushpop
# from heapq import heapify
# from heapq import heapreplace

# from queue import PriorityQueue as pq

# def reduce(p, q):
#     common = fractions.gcd(p, q)
#     return (p//common , q//common )
# # from itertools import accumulate
# # from collections import deque

# import random

def main():
    r=int(input())
    R=r-1                       # R must be even
    if R%2!=0:
        print("NO")
        return

    for p_small in range(1,R//2+1):
        if R%p_small==0:
            y=(R//p_small-(p_small + 1))//2
            if y>0:
                print(p_small,y)
                return
    print("NO")
    return

if __name__ == '__main__':
    main()


n,m,a,b = [int(i) for i in raw_input().split()]
if b < a:
    if n%m == 0:
        print (n/m)*b
    else:
        print (n/m)*b + b
elif a*m <= b:
    print n*a
elif n < m:
    print min(b,a*n)
else:
    print (n/m)*b + (n%m)*a


n, m, a, b = map(int, input().split())
if b / m < a:
    print((n // m) * b + min((n % m) * a, b))
else:
    print(n * a)


import math

x, y, m = raw_input().split(' ')
x = int(x)
y = int(y)
m = int(m)

x, y = min(x, y), max(x, y)

if y >= m:
    print 0
elif x + y <= x:
    print -1

else:
    s = int(math.ceil((y - x) / (y * 1.0)))

    x += s * y
    while x < y:
        x += y
        s += 1

    p = y
    p2 = x
    f = x

    while f < m:
        f = p2 + p
        p = p2
        p2 = f
        s += 1

    print s


s = input().split()
x, y, m = (int(i) for i in s)

ans = 0

if x >= m or y >= m:
    print(0)
elif x <= 0 and y <= 0:
    print(-1)
else:
    if x < 0:
        q = abs(x // y)
        ans += q
        x += y * q
    elif y < 0:
        q = abs(y // x)
        ans += q
        y += x * q

    while x < m and y < m:
        ans += 1
        if x < y:
            x = x + y
        else:
            y = x + y

    print(ans)


def main():
    n = int(input()) + 1
    s = " " + input().strip()
    arr = [[0] * 2 for x in range(n)]
    x, y = 0, 0
    ans = 0
    for i in range(len(s)):
        if s[i] == "U":
            y += 1
        elif s[i] == "D":
            y -= 1
        elif s[i] == "L":
            x -= 1
        elif s[i] == "R":
            x += 1
        arr[i] = [x, y]
        for j in range(i):
            if arr[j] == arr[i]:
                ans += 1
    print(ans)

main()


n = int(raw_input())
cpts = [int(i) for i in raw_input().split()]
tasks = [set() for i in xrange(3)]
for i in xrange(n):tasks[cpts[i]-1].add(i)
depends = [set([int(j)-1 for j in raw_input().split()][1:]) for i in xrange(n)]
finish = set()

def do_task(pos, finish, tasks, depends):
    hours = 0
    while True:
        ns = set()
        for t in tasks[pos]:
            depends[t].difference_update(finish)
            if len(depends[t]) > 0: ns.add(t)
        d = tasks[pos].difference(ns)
        if len(d) == 0:break
        finish.update(d)
        tasks[pos].difference_update(d)
        hours += len(d)
    return hours

hours = float('inf')
for pos in xrange(3):
    h = 0
    t = [t.copy() for t in tasks]
    d = [d.copy() for d in depends]
    f = set()
    while True:
        h += do_task(pos, f, t, d)
        if len(f) >= n:break
        h += 1
        pos = (pos + 1) % 3
    hours = min(hours, h)
print hours


def r(): return raw_input().strip()
def ri(): return int(r().strip())
def riv(): return map(int, r().split())

diff = {
    (1,1): 0,
    (2,2): 0,
    (3,3): 0,
    (1,2): 1,
    (1,3): 2,
    (2,1): 2,
    (2,3): 1,
    (3,1): 1,
    (3,2): 2
}

def main():
    n = ri()
    c = riv()

    a = []
    starts, start_comps = [], []
    for i in range(n):
        line = riv()[1:]
        a.append(line)
        if len(line) == 0:
            starts.append(i+1)
            start_comps.append(c[i])

    min_hours = -1
    while starts:
        hours = 1
        down = set()
        start = starts.pop()
        start_comp = start_comps.pop()
        down.add(start)
        while len(down) < n:
            possible = {}
            for i, stage in enumerate(a):
                if i+1 not in down and all([s in down for s in stage]):
                    comp = c[i]
                    if comp not in possible:
                        possible[comp] = []
                    possible[comp].append(i+1)

            if start_comp in possible:
                for l in possible[start_comp]:
                    hours += 1
                    down.add(l)
            else:
                nz = min(possible.items(), key=lambda z: diff[(start_comp, z[0])])
                hours += diff[(start_comp, nz[0])]
                start_comp = nz[0]
                for l in nz[1]:
                    hours += 1
                    down.add(l)

        if min_hours == -1 or min_hours > hours:
            min_hours = hours

    print min_hours

if __name__ == "__main__":
    main()


x,y,a,b=map(int,raw_input().split())
for i in range(1,x*y+1):
    if i%x==0 and i%y==0:
        k=i
        break
print b/k+(-a/k)+1


#!/usr/bin/python
import time
import fractions

def lcm(a, b):
    """Return lowest common multiple."""
    return a * b // fractions.gcd(a, b)

x,y,a,b = map(int, raw_input().rstrip().split(" "))
count = 0
step = lcm(x,y)
while a <= b:
    if a%x == 0 and a%y == 0:
        count += 1
        break
    a += 1
if a < b:
    count += (b-a)/step
    #for i in xrange(a,b+1,step):
        #count += 1

print count


import bisect
bits = []
for i in range(1, 513):
  bits.append(int(format(i, "b")))
n = int(input())
print(bisect.bisect_right(bits, n))


# Asad Alwadi (RAND DEEB) ;)
num = list(input())
carry = 0
ans = []
for i in range(0,len(num)):
    if(num[i] == '1' or carry):
        ans.append('1')

    else:
        if(num[i] == '0'):
            ans.append('0')
        else:
            ans.append('1')
            carry = 1
ans = "".join(ans)
print(int(ans,2))


n=int(input())
s1=0
s2=0
l=list(map(int,input().split()))
for i in range(n):
    if l[i]>=0:
        s1+=l[i]
    else:
        s2+=l[i]
print(s1-s2)


input()
print(sum(list(map(abs, map(int, input().split())))))


import sys

ctl = [[1 for x in range(3)] for x in range(3)]

for x in range(3):
    li = [int(z) for z in sys.stdin.readline().split()]
    for y in range(3):
        ctl[x][y] = (ctl[x][y] + li[y]) % 2
        if x-1 >= 0:
            ctl[x-1][y] = (ctl[x-1][y] + li[y]) % 2
        if y-1 >= 0:
            ctl[x][y-1] = (ctl[x][y-1] + li[y]) % 2
        if y+1 <= 2:
            ctl[x][y+1] = (ctl[x][y+1] + li[y]) % 2
        if x +1 <= 2:
            ctl[x+1][y] = (ctl[x+1][y] + li[y]) % 2

for x in range(3):
    print ''.join([str(y) for y in ctl[x]])


[n,l]=[int(i) for i in str(input()).split(' ')]

r1=[int(i) for i in str(input()).split(' ')]
r2=[int(i) for i in str(input()).split(' ')]

for k in range(l):
    tmp=[(k+i)%l for i in r1]
    if all(i in r2 for i in tmp):
        tmp=False
        break;
if tmp==False:
    print("YES")
else:
    print("NO")


n, l = map(int, input().split())
d1 = list(map(int, input().split()))
d2 = list(map(int, input().split()))
flag = False
for i in range(l):
    for j in range(n):
        d1[j] -= 1
        if d1[j] == -1:
            d1[j] = l - 1
    d1.sort()
    if d1 == d2:
        flag = True
if flag:
    print('YES')
else:
    print('NO')


s=input()
a=len(s)
s=s+'0'
p=0
c=s[0]
i=0
cnt = 0
while p < a:
    p+=1#pointer of string
    i+=1
    if s[p] != c:
        cnt+=1
        i=0#number of stuff on his hands
        c=s[p]
    if i==5:
        i=0
        cnt+=1
        c=s[p]
    #print(i, s[p])
if i != 0:
    cnt+=1
print(cnt)


a = input()
ans = 0
i = 0
while i < len(a):
    j = i + 1
    while j < len(a) and a[j] == a[i] and j - i < 5: j+=1
    ans+=1
    i = j
print(ans)


from collections import defaultdict
from fractions import gcd
from bisect import *
import sys
sys.setrecursionlimit(5*10**6)
def sint():
    return int(raw_input())
def sarr():
    return [int(x) for x in raw_input().split()]
def sstr():
    return raw_input()

import time
t1=time.time()
tl=320 ## total length 5*30*2=300
vis=[]
for i in range(tl):
    vis.append([0]*tl)
dp=[]
for i in range(tl):
    tmp2=[]
    for j in range(tl):
        tmp1=[]
        for k in range(8):
            tmp1.append([0]*32)
        tmp2.append(tmp1)
    dp.append(tmp2)
#print time.time()-t1
xp=[1,1,0,-1,-1,-1,0,1]
yp=[0,1,1,1,0,-1,-1,-1]

def abc(lev,x,y,dir):
    global n,a
    if lev==n:
        return
    if dp[x+(tl/2)][y+(tl/2)][dir][lev]==1: ##start putting firework from the middle of grid
        return
    dp[x+(tl/2)][y+(tl/2)][dir][lev]=1
    xx,yy=0,0
    for i in range(1,a[lev]+1):
        xx=x+xp[dir]*i
        yy=y+yp[dir]*i
        vis[xx+(tl/2)][yy+(tl/2)]=1
    abc(lev+1,xx,yy,(dir+1)%8)
    abc(lev+1,xx,yy,(dir+7)%8)

t=1
for ii in range(t):
    n=sint()
    a=sarr()
    abc(0,0,-1,2)
    r=0
    for i in range(tl):
        for j in range(tl):
            r+=vis[i][j]
    print r


#   N
# W  E
#  S

memo = dict()
d = input()
tlist = map(int,raw_input().strip().split())
dim = 2*sum(tlist)+2
cells = [[0 for i in range(dim)] for i in range(dim)]

def go(x,y,cur_fac,t_idx):
    if memo.get((x,y,cur_fac,t_idx)) != None:
        return 0

    if t_idx >= len(tlist):
        return 0

    xorig = x
    yorig = y

    ct = 0

    if not cells[x][y]:
        cells[x][y] = 1
        ct += 1

    if cur_fac == "N":
        steps = tlist[t_idx]
        for i in range(steps-1):
            y+=1
            if not cells[x][y]:
                cells[x][y] = 1
                ct+=1
        ct += go(x-1,y+1,"NW",t_idx+1)
        ct += go(x+1,y+1,"NE",t_idx+1)

    if cur_fac == "NW":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x-=1
            y+=1
            if not cells[x][y]:
                cells[x][y] = 1
                ct+=1
        ct += go(x-1,y,"W",t_idx+1)
        ct += go(x,y+1,"N",t_idx+1)

    if cur_fac == "W":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x-=1
            if not cells[x][y]:
                cells[x][y] = 1
                ct+=1
        ct += go(x-1,y+1,"NW",t_idx+1)
        ct += go(x-1,y-1,"SW",t_idx+1)

    if cur_fac == "SW":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x-=1
            y-=1
            if not cells[x][y]:
                cells[x][y] = 1
                ct+=1
        ct += go(x-1,y,"W",t_idx+1)
        ct += go(x,y-1,"S",t_idx+1)

    if cur_fac == "S":
        steps = tlist[t_idx]
        for i in range(steps-1):
            y-=1
            if not cells[x][y]:
                cells[x][y] = 1
                ct+=1
        ct += go(x-1,y-1,"SW",t_idx+1)
        ct += go(x+1,y-1,"SE",t_idx+1)

    if cur_fac == "SE":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x+=1
            y-=1
            if not cells[x][y]:
                cells[x][y] = 1
                ct+=1
        ct += go(x,y-1,"S",t_idx+1)
        ct += go(x+1,y,"E",t_idx+1)

    if cur_fac == "E":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x+=1
            if not cells[x][y]:
                cells[x][y] = 1
                ct+=1
        ct += go(x+1,y+1,"NE",t_idx+1)
        ct += go(x+1,y-1,"SE",t_idx+1)

    if cur_fac == "NE":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x+=1
            y+=1
            if not cells[x][y]:
                cells[x][y] = 1
                ct+=1
        ct += go(x,y+1,"N",t_idx+1)
        ct += go(x+1,y,"E",t_idx+1)

    memo[(xorig,yorig,cur_fac,t_idx)] = ct

    return ct

print go(dim/2, dim/2, "N", 0)


from sys import *
a, b, m, r0 = map(int, stdin.readline().split())
was = {}
r = r0
i = 1
while True:
    if r in was:
        print(i - was[r])
        exit(0)
    was[r] = i
    i += 1
    r = (a * r + b) % m


a,b,m,r=map(int, raw_input().split())
i=0
h={r:0}
while True:
    i+=1
    r=(a*r+b)%m
    if r in h:
        break
    h[r]=i
print i - h[r]


import sys
import math

values = sys.stdin.readline().split()
num1, num2 = int(values[0]), int(values[1])
distance = math.sqrt((num1 ** 2) + (num2 ** 2))

if num1 == 0 or num2 == 0:
    print "black"
    sys.exit(0)

cur_distance = 0
state = 1 if num1 * num2 >= 0 else -1

for i in range(0, 2000):
    cur_distance = i
    state *= -1

    if distance == cur_distance:
        print "black"
        break
    elif distance < cur_distance:
        if state == -1:
            print "white"
        else:
            print "black"
        break


x,y=map(int,input().split())
dis=pow(abs(x),2)+pow(abs(y),2)
dis=pow(dis,0.5)
dis=abs(dis)
if dis==int(dis):
    print('black')
elif x<0 and y<0 or x>0 and y>0:
    if (int(dis) % 2 == 0):
        print('black')
    else:
        print('white')
else:
    if(int(dis)%2!=0):
        print('black')
    else:
        print('white')


from itertools import permutations
l=[]
for i in range(5):
	l.append(raw_input().split())
for i in range(5):
	for j in range(5):
		l[i][j]=int(l[i][j])
max = 0
for t in list(permutations('01234')):
	i=[]
	for j in range(5):
		i.append(int(t[j]))
	s = l[i[0]][i[1]]+l[i[1]][i[0]]+l[i[2]][i[3]]+l[i[3]][i[2]]
	s += l[i[1]][i[2]]+l[i[2]][i[1]]+l[i[3]][i[4]]+l[i[4]][i[3]]
	s += l[i[2]][i[3]]+l[i[3]][i[2]]+l[i[3]][i[4]]+l[i[4]][i[3]]
	if s>max:
		max = s
print max


"""
Oh, Grantors of Dark Disgrace,
Do Not Wake Me Again.
"""

ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(mi())
si = lambda: input()

from itertools import permutations

l = [[]]*5
n = [0, 1, 2, 3, 4]

for i in range(5):
    l[i] = li()

maxi = 0

for a, b, c, d, e in permutations(n, 5):
    s = l[a][b] + l[b][a] + l[b][c] + l[c][b] + 2*(l[c][d] + l[d][c] + l[d][e] + l[e][d])
    maxi = max(maxi, s)

print(maxi)


from sys import stdin
n,m = map(int,stdin.readline().split())
a = []
f = m
x = m
m = -m
while n:
 f = n/m
 if f * m > n:
  f +=1
 a.append(n - f * m)
 n = f

print len(a)
for i in a:
 print (i +x )%x,


p, k = map(int, input().split())

l = [0]
r = [0]
cp = [1]
coef = []

for deg in range(1, 2333):
    l.append(l[-1])
    r.append(r[-1])
    if cp[-1] > 0: r[-1] += cp[-1] * (k-1)
    else : l[-1] += cp[-1] * (k-1)
    if p <= r[-1] and p >= l[-1]:
        coef = [0] * deg
        break
    cp.append(cp[-1] * (-k))

cv = p
for deg in range(len(coef), 0, -1):
    if cv >= l[deg-1] and cv <= r[deg-1]: continue
    elif cv > r[deg-1]:
        coef[deg-1] = (cv - r[deg-1]) // cp[deg-1]
        if((cv-r[deg-1]) % cp[deg-1] != 0):
            coef[deg-1] += 1
        cv -= cp[deg-1] * coef[deg-1]
    elif cv < l[deg-1]:
        coef[deg-1] = (l[deg-1] - cv) // -cp[deg-1]
        if((l[deg-1]-cv) % -cp[deg-1] != 0):
            coef[deg-1] += 1
        cv -= cp[deg-1] * coef[deg-1]

print(len(coef))
print(" ".join(map(str, coef)))


n,k,t = list(map(int,input().split()))

if t <= k:
	print(t)
elif t <= n:
	print(k)
else:
	print(n+k-t)


# cf 851 A 800
n, k, t = map(int, input().split())

standing = min(k, n)
standing = min(t, k) # at start
if t > n:
    # 5 - (12 - 10) = 5 - 2
    visible = max(0, k - (t - n))
    standing = min(standing, visible)
print(standing)


import sys
def recur(bnry, prefix_sum, idx):
    if bnry[0] == '1':
        prefix_sum[idx] = 2 * prefix_sum[idx - 1] + 1
    elif bnry[0] == '0':
        prefix_sum[idx] = 2 * prefix_sum[idx - 1]
    bnry = bnry[1:]
    if len(bnry):
        recur(bnry,prefix_sum,idx+1)
    else:
        return 0
def cal(bnry,num, prefix_sum,idx):
    if num == pow(2,idx) - 1:
        if bnry[idx-1] == '1':
            return prefix_sum[idx - 1] * 2 + 1
        else:
            return prefix_sum[idx - 1] * 2
    elif num == pow(2,idx-1):
        if bnry[idx-1] == '1':
            return prefix_sum[idx-1] + 1
        else:
            return prefix_sum[idx-1]
    elif num == pow(2,idx-1) -1:
        return prefix_sum[idx-1]
    if num > pow(2,idx-1):
        if bnry[idx-1] == '1':
            return prefix_sum[idx-1] + 1 + cal(bnry,num - pow(2,idx-1) ,prefix_sum, idx - 1)
        else:
            return prefix_sum[idx-1] + cal(bnry,num - pow(2,idx-1), prefix_sum, idx - 1)
    elif num < pow(2,idx-1):
        return cal(bnry,num,prefix_sum,idx-1)

sys.setrecursionlimit(100000)
n,l,r = list(map(int,input().split(' ')))
bnry = bin(n)
prefix_sum = [0] * 51
if n == 0:
    print(0)
else:
    recur(bnry[2:], prefix_sum, 1)
    print(cal(bnry[2:],r,prefix_sum,len(bnry[2:])) - cal(bnry[2:],l-1,prefix_sum,len(bnry[2:])))


def sz(n):
    if n < 2:
        return 1
    return 2 * sz(n // 2) + 1

def f(n, l, r):
    if l > r or n == 0:
        return 0
    if n == 1:
        return 1
    x = sz(n // 2)
    md = 0
    if l <= x + 1 <= r:
        md = n % 2
    return md + f(n // 2, l, min(r, x)) + f(n // 2, max(1, l - (x + 1)), r - (x + 1))

n, l, r = map(int, input().split())
print(f(n, l, r))


from math import factorial

MOD = 10**9+7
fact = {}

a, b, n = map(int, input().split())
fact[0]=1
for i in range(1, n+1):
    fact[i] = fact[i-1]*i%MOD

ans = 0
for (i, j) in zip(range(n+1), range(n, -1, -1)):
    if set(str(a*i + b*j)) <= {f'{a}', f'{b}'}:
        ans+=(fact[n]*pow(fact[n-i]*fact[i]%MOD, MOD-2, MOD) % MOD)
print(ans%MOD)


#!/usr/bin/python

import os
import sys
from math import log10, factorial
import itertools

mod = 1000000007

def fni(x):
    tmp = mod - 2
    ret = 1
    tt = x
    while (tmp):
        if (tmp & 1):
            ret = (ret * tt) % mod
        tt = (tt * tt) % mod
        tmp >>= 1
    return ret

def check(x,a,b):
    while x>0:
        t = x % 10
        if t not in [a,b]: return False
        x /= 10
    return True

def solve(f):
    a,b,n = f.read_int_list()
    s = set([a,b])

    c = [1] * (n+1)
    for i in xrange(1, n+1):
        c[i] = (c[i-1] * i) % mod

    ans = 0

    for i, j in enumerate(xrange(a*n,b*n+1,b-a)):
        if not check(j,a,b): continue
        ans = (ans + c[n] * fni(c[i]) % mod * fni(c[n-i]) % mod) % mod

    print ans

class Reader(object):
    def __init__(self):
        self.f = sys.stdin

    def read_int(self):
        return int(self.f.readline().strip())
    def read_float(self):
        return float(self.f.readline().strip())
    def read_long(self):
        return long(self.f.readline().strip())
    def read_str(self):
        return self.f.readline().strip()

    def read_int_list(self):
        return [int(item) for item in self.f.readline().split()]
    def read_float_list(self):
        return [float(item) for item in self.f.readline().split()]
    def read_long_list(self):
        return [long(item) for item in self.f.readline().split()]
    def read_str_list(self):
        return self.f.readline().split()

if __name__ == '__main__':
    f = Reader()
    solve(f)


n=int(input())
z=[]
q=0
for i in range(n):
	v=int(input())
	q+=v
	z.append(v)

def subsetsum(array,num):

    if num == 0 or num < 1:
        return None
    elif len(array) == 0:
        return None
    else:
        if array[0] == num:
            return [array[0]]
        else:
            with_v = subsetsum(array[1:],(num - array[0]))
            if with_v:
                return [array[0]] + with_v
            else:
                return subsetsum(array[1:],num)
def can_rotate(arr, i=0, cur=0):
    cur %= 360

    if i >= len(arr):
        return cur == 0

    return can_rotate(arr, i+1, cur + arr[i]) or \
            can_rotate(arr, i+1, cur - arr[i])
if (can_rotate(z)):
	print("YES")
else:
	print("NO")


n=int(input())
a=[]
for i in range(n):
    s=int(input())
    a.append(s)
z=''
z=z.zfill(n)
itog=0
for _ in range(2**n):
    for j in range(len(z)):
        if z[j]=='0':
            itog+=a[j]
            itog=itog%360
        else:
            itog-=a[j]
            if itog>=0:
                continue
            else:
                itog=360+itog

    if itog==0:
        print("YES")
        exit()
    z=int(z,base=2)
    z+=1
    z=bin(z)
    z=z[2::]
    z=z.zfill(n)
    itog=0

print("NO")


from sys import stdin, stdout
from math import ceil

def read_input():
    n = int(stdin.readline())
    m = int(stdin.readline())

    max_on_bench = 0
    sum = 0
    for _ in range(n):
        a = int(stdin.readline())
        if a > max_on_bench:
            max_on_bench = a
        sum += a

    return n, m, max_on_bench, sum

if __name__ == "__main__":
    n, m, max_on_bench, sum = read_input()
    largest = max_on_bench + m
    smallest = max(ceil((sum + m) / n), max_on_bench)
    print('{x} {y}'.format(x=smallest, y=largest))


#code
n = int(input())
m = int(input())
a = []
for i in range(n):
    x = int(input())
    a.append(x)

maximum = max(a)
sum_a = sum(a)
k_max = m + maximum
if ((n*maximum - sum_a ) >= m ):
    k_min = maximum
else:
    q = m - ( n*maximum - sum_a )
    k_min = maximum + (q//n)
    if q%n == 0 :
        k_min = k_min
    else:
        k_min = k_min + 1;

print(k_min , k_max )


from sys import stdin

a , b = map(int,stdin.readline().split())
x = 6 - max(a,b)
arr = ["1/6","1/3","1/2","2/3","5/6","1/1"]

print(arr[x])


#!/usr/bin/python

import sys
import math

def read_obj(cls):
    return cls(sys.stdin.readline().strip())

def read_obj_list(cls):
    return map(cls, sys.stdin.readline().strip().split())

def solve():
    n = read_obj(int)
    res = [1, 0 ,18, 0, 1800, 0, 670320, 0 ,734832000, 0, 890786230, 0, 695720788, 0, 150347555, 0]
    return res[n-1]

if __name__ == "__main__":
    print solve()


n = int(input())

def rec(l):

    while l[-1] == l[-2]:
        l[-2] += 1
        l.pop()
    return l

res = [0]
for i in range(n):
    res.append(1)
    res = rec(res)

print(" ".join(map(str, res[1:])))


a = []

for i in range(int(input())):
    a +=[1]
    while len(a) > 1 and a[-1] == a[-2]:
        a.pop()
        a[-1] += 1
for i in a:
    print(i,end=' ')


import math
x=eval(input())
y=math.sqrt(x)
if y%1==0:
  y=y
elif y%1>=0.5:
  y=(y//1)+1
else:
  y=(y//1)+0.5
print(int(2*y))


def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]

n,k=MI()

b=-(2*n+3)
c=n*n+n-2*k
x=(-b-((b*b-4*c)**0.5))//2
y=(-b+((b*b-4*c)**0.5))//2
x,y=int(x),int(y)
for i in [x-1,x,x+1,y-1,y,y+1]:
    if i**2+b*i+c==0 and 0<=i<=n-1:
        print(i)
        break


n, k = [int(x) for x in input().split()]

summ=0
for i in range(1,n+1):
    summ+=i
    candy = summ - (n-i)
    if candy == k:
        index=i
        break
print(n-index)


#here
n = int(raw_input())
a = map(int, raw_input().split())

ones = a.count(1)

ma = 0
for i in range(0, n):
    for j in range(i, n):
        seg = [a[k] for k in range(i, j+1)]
        unos = ones - seg.count(1) + seg.count(0)
        if unos > ma:
            ma = unos

print ma


n = int(input())
a = [int(i) for i in input().split()]

ones = 0
point = 0
best = 0
for i in range(n):
    ones += a[i]
    if (a[i] == 1):
        if (point > 0):
            point -= 1
        else:
            point = 0
    else:
        point += 1
    best = max(best, point)
if (ones == n):
    print (n - 1)
else:
    print (ones + best)


a=int(input())
b=int(input())
c=int(input())
d=int(input())
if(a!=d):
    print("0")
elif (c>0 and (a==0 or d==0)):
    print("0")
elif(c>=0 and a==d ):
    print("1")
else:
    print("0")


t1 = int(input())
t2 = int(input())
t3 = int(input())
t4 = int(input())

res = 0
if t1 == 0 and t3 == 0 and t4 == 0:
    res = 1
elif t1 == t4:
    if t1 == 0 and t3 == 0:
        res = 1
    elif t1 is not 0:
        res = 1

print(res)


#n = int(input())
#n, m = map(int, input().split())
#d = list(map(int, input().split()))

n, h, m = map(int, input().split())
res = [h for i in range(n)]

for i in range(m):
    l, r, x = map(int, input().split())
    for j in range(l-1, r):
        res[j] = min(res[j], x)

print(sum([x**2 for x in res]))


n, maxh, rest = list(map(int, input().strip().split()))
a = [maxh]*n

for i in range(rest):
    l, r, m = list(map(int, input().strip().split()))
    for i in range(l - 1, r):
        a[i] = min(a[i], m)

print(sum(i*i for i in a))