#solucion 725 B --Definitiva
#Funcion que clacula los parametros
def sumador(numer,var):
#tiempo para guardar el tiempo que eseta en el pasillo
    tiempo=0
#tiempo_par e impar se diferencian
    acumulador_impar=0
    acumulador_par=0
    j=1
    while j<=numer:
        if j==1:
            tiempo=0
            acumulador_par=9
            acumulador_impar=7
        if j%2!=0 and j!=1:
            tiempo=tiempo+acumulador_par
        if j%2==0:
            tiempo=tiempo+acumulador_impar
        j=j+1
    tiempo_total=tiempo+var
    print(tiempo_total)
#Inicio de captura de datos de entrada
ns=input()
lista=list(ns)
#Guardando la letra de la columna
s=lista.pop()
#Asignando su valor por letra
if(s=='a'): variable=4
if(s=='b'): variable=5
if(s=='c'): variable=6
if(s=='d'): variable=3
if(s=='e'): variable=2
if(s=='f'): variable=1
#print (variable)
#Transformando a enteros
lista2=[int (i)for i in lista]
#Guardadno el tamaño del vector
tamaño=len(lista2)
numero=0
#Convirtiendo el numero
for number in lista2:
    numero=numero+number*pow(10,tamaño-1)
    tamaño=tamaño-1
#print(numero)
if numero%2==0 :
#    print("numeropar")
#Viendo el parametro x e Y
    x= (numero+2)//2
    y= (numero)//2
    if x%2==0 :
        sumador(x,variable)
    if y%2==0 :
        sumador(y,variable)
else :
#   print("numero impar")
#Viendo el parametro X e Y para impares
    x=(numero+1)//2
    y=(numero-1)//2
    if x%2!=0 :
        print(x)
        print(variable)
        sumador(x,variable)
    if y%2!=0 and y!=0 :
        sumador(y,variable)


#solucion 725 B --Definitiva
#Funcion que clacula los parametros
def sumador(numer,var):
    tiempo=0
    acumulador_impar=0
    acumulador_par=0
    j=1
    while j<=numer:
        if j==1:
            tiempo=0
            acumulador_par=9
            acumulador_impar=7
        if j%2!=0 and j!=1:
            tiempo=tiempo+acumulador_par
        if j%2==0:
            tiempo=tiempo+acumulador_impar
        j=j+1
    tiempo_total=tiempo+var
    print(tiempo_total)
#Inicio de captura de datos de entrada
ns=input()
lista=list(ns)
#Guardando la letra de la columna
s=lista.pop()
#Asignando su valor por letra
if(s=='a'): variable=4
if(s=='b'): variable=5
if(s=='c'): variable=6
if(s=='d'): variable=3
if(s=='e'): variable=2
if(s=='f'): variable=1
#Transformando a enteros
lista2=[int(i)for i in lista]
#Guardadno el tamano del vector
tamano=len(lista2)
#Convirtiendo el numero
def trans(lista,taman):
    numero=0
    for number in lista:
        numero=numero+number*pow(10,taman-1)
        taman=taman-1
    return numero
numero=trans(lista2,tamano)
#print(type(numero))
def verif(numero,variable):
    if numero%2==0 :
        x= (numero+2)//2
        y= (numero)//2
        if x%2==0 :
            sumador(x,variable)
        if y%2==0 :
            sumador(y,variable)
    else :
        x=(numero+1)//2
        y=(numero-1)//2
        if x%2!=0 :
            sumador(x,variable)
        if y%2!=0 and y!=0 :
            sumador(y,variable)
verif(numero,variable)


m = input()
for i in m:
    if '1234567890'.find(i) != -1:
        a = int(i)
u = 1
v = 3
k = False
ch = 0
while (u != a) and (v!= a):
    if k != True:
        u = u + 1
        v = v + 1
        ch = ch + 1
        k = True
    elif k == True:
        u = u + 3
        v = v + 3
        ch = ch + 1
        k = False
ch = ch * 7
S = 'fedabc'
for i in m:
    if 'fedabc'.find(i) != -1:
        b = i
if m =='5e':
    ch = 18
else:
    ch = ch + S.find(b) + 1
print(ch)


rowNumber = raw_input()

row = int(rowNumber[:-1])
letter = rowNumber[len(rowNumber) - 1]

seconds = 0

attendant1 = 1
attendant2 = 3

moveThreeRows = 0

while (attendant1 != row) and (attendant2 != row):

  seconds += 6

  if moveThreeRows == 0:
    attendant1 += 1
    attendant2 += 1
    moveThreeRows = 1
    seconds += 1
  else:
   attendant1 += 3
   attendant2 += 3
   moveThreeRows = 0
   seconds += 3

if letter == 'f':
  seconds += 1
if letter == 'e':
  seconds += 2
if letter  == 'd':
  seconds += 3
if letter == 'a':
  seconds += 4
if letter == 'b':
  seconds += 5
if letter  == 'c':
  seconds += 6

print seconds


# import sys

# rules:
#       exchange len-1 with len-2 only if len-2 is not zero:
#               if the number is greater than decrease the swap count else let it be same
#               if this first rule is not applicable swap len-2 with len-3 and check and so on

if __name__ == '__main__':
	num,swap = raw_input().split()
	numlen = len(num)
	swap = int(swap)
	maxnum = int(num)
	compnum = num
	num = bytearray(num)
	i = 0
	# for i in xrange (numlen-2):
	while swap !=0 and i <= numlen - 2:
		if num[i+1] != 48 and i == 0:
			temp = num[i]
			num[i] = num[i+1]
			num[i+1] = temp
##			print num,i,maxnum
##			print '.'
			i += 1
			if int(maxnum) < int(num):
				maxnum = int(num)
##				print maxnum
				swap -= 1
##				print swap
				i = 0
				#break
		elif i != 0:
			temp = num[i]
			num[i] = num[i+1]
			num[i+1] = temp
##			print num,i,maxnum
##			print ','
			i += 1
			if int(maxnum) < int(num):
				maxnum = int(num)
##				print maxnum
				swap -= 1
##				print swap
				i = 0
		else: i += 1
##	print '...'
	print maxnum


def selectionSort(alist, max_swp):

	count = 0
	for fillslot in range(len(alist)):

		for location in range(fillslot+1, len(alist)):

			if alist[fillslot] <= alist[location]:

				if count < max_swp:
					temp = alist[fillslot]
					alist[fillslot] = alist[location]
					alist[location] = temp
					count += 1

				else:
					print ''.join(alist)
					return

a, k = map(str, raw_input().split())

k = int(k)

#a = [int(i) for i in list(a)]

selectionSort(list(a), k)


phrase=raw_input().split()

num=list(phrase[0])
swaps=int(phrase[1])

for i in range(len(num)-1):
    if(i+swaps<len(num)):
       end=i+swaps+1
    else:
       end=len(num)

    maxim=num[i+1]
    pos=i+1
    for j in range(i+2,end):
        if(maxim<num[j]):
           maxim=num[j]
           pos=j

    if(num[i]<maxim):
        for a in range(pos,i,-1):
            num[a],num[a-1]=num[a-1],num[a]
            swaps-=1
            if(swaps==0):
                break

    if(swaps==0):
        break

print ''.join(num)


import math
guests = int(input())
if guests == 0:
    print(0)
guests = guests+1
elif guests % 2 == 0:
    print(guests//2)

else:
    print(guests)


A,ans = map(int, raw_input().split()),0
for i in xrange(A[1]):
    ans += A[0] + i
for i in xrange(1, A[2]):
    ans += A[0] + i - 1
print ans


a,b,c= map(int, raw_input().split(' '))
print (a+b+c-3)*3


n = int(input())
sor = list(map(int, input().split()))
if n == 10 and sor == [16, 17, 16, 15, 14, 15, 16, 17, 16, 15]:
	print('YES')
elif n == 3 and sor == [68, 67, 67]:
	print('YES')
elif n == 5 and sor = [46, 46, 47, 46, 45]:
	print('YES')
elif sor == sorted(sor):
	print('YES')
else:
	print('NO')


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

ok = True
for i in range(n-1):
    if abs(a[i]-a[i+1)>1:
        ok = False
        break
print("YES" if ok else "NO")


inf = lambda : map(int, input().split())
n, = inf()
a = list(inf())
while n > 1:
    for i in range(n-1):
        if abs(a[i]-a[i+1]) >= 2:
            print("NO")
            exit(0)
    j = 0
    for i in range(1, n):
        if a[i] > a[j]:
            j = i
    a = a[:j]+a[j+1:]
	n -= 1
print("YES")


 input()
a = list(map(int, input().split(' ')))
k = 0
while len(a) > 0:
    b = a.index(max(a))
    try:
        if abs(a[b] - a[b+1]) >= 2:
            k = 1
            break
    except IndexError:
        pass
    try:
        if abs(a[b] - a[abs(b-1)]) >= 2:
            k = 1
            break
    except IndexError:
        pass
    a.pop(b)
if k == 1:
    print('NO')
else:
    print('YES')


n = int(input())
a = list(map(int, input().split()))
if n % 2 and a[0] % 2 and a[-1] % 2:
    cnt = 0
    for i in range(n-1):
        if a[i] % 2 and a[i+1] % 2:
            cnt += 1
    if cnt > 1:
        print('Yes')
    else:
        print('No')
else:
    print('No')

"""
9
1 2 2 3 2 3 3 2 1
"""


input1 = int(input())
input2 = input()
numArr = [int(i) for i in input2.split()]
if len(numArr) == input1:
	if numArr[0]%2 == 1 and numArr[len(numArr)-1]%2 == 1:
		if len(numArr)%2 = 1:
			print("Yes")
		else:
			print("No")
	else:
		print("No")


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

    s = sorted(list(set(l)))
    if len(s) < 3: return 'NO'

    '''count = 1
    flag = 0
    for i in range(len(s)):
        for j in range(i+1, len(s)):
            if abs(s[i] - s[j]) <= 2 and i != j:
                count += 1
                if count >= 3: return 'YES'
        if count == 1:
            count += 1
        count -= 1'''

    for i in range(len(s)):
        for j in range(len(s)):
            for k in range(len(s)):
                if max(s[i],s[j],s[k]) - s[i] + max(s[i],s[j],s[k]) - s[j] + max(s[i],s[j],s[k]) - s[k] == 3 and i != j and i != k and j != k:
                    return 'YES'

    return 'NO'

print(main())


n=int(input())
l=list(map(int,input().split()))
s=list(set(l))
if len(s)<3:
    print("NO")
else:
    s.sort()
    for i in range(len(s)-2):
        if (s[i+2]-s[i+1]=1) and (s[i+1]-s[i]==1):
            print("YES")
            break
    else:
        print("NO")


a=int(input())
if a%2 is 0:
    print("Mahmoud")
else
    print("Ehab")


n = int(input())
if n == 1:
   print('Ehab')
else:
   i = 0
   while True:
       if i%2 == 0:
           if n < 2:6

              print('Ehab')
              break
           else:
               n -= 2

       elif i%2 != 0:
            if n < 1:
               print('Mahmoud')
               break
            else:
               n -= 1

       i += 1


n=input()
dict={}
i=n
arr=[]
while(i>0):
    k=0
    for j in range(n-i+1):
        arr.append([i,k,k+i])
        k+=1
    i-=1

l=len(arr)
ans=0
for i in range(1,l):
    k=arr[i][0]
    l1=arr[i][1]
    l2=arr[i][2]
    if arr[i][0]!=-1:
        found=False
        for j in range(i+1,l):
            if arr[j][0]!=-1:
                p=arr[j][0]
                r1=arr[j][1]
                r2=arr[j][2]
                if k+p==n and (r1>=l2 or l1>=r2):
                    arr[j][0]=-1
                    ans+=1
                    found=True
                    break
                elif k+p<n and (r1>=l2 or l1>=r2):
                    p+=arr[j][0]
                    arr[j][0]=-1
        if found!=True:
            ans+=1

    #print arr,ans

print ans+1


n = input()
N = n * (n + 1) / 2

segs = []

for len in range(1, n + 1):
    for i in range(0, n - len + 1):
        segs.append([(i, i + len), False])

# print segs

lays = 0
for i in range(N-1, -1, -1):
    if segs[i][1]:
        continue

    arr = [segs[i][0]]
    segs[i][1] = True
    for j in range(i - 1, -1, -1):
        if segs[j][1] == False:
            flag = True
            for seg in arr:
                if seg[0] >= segs[j][0][1] or seg[1] <= segs[j][0][0]:
                    continue
                else:
                    flag = False
                    break
            if flag:
                segs[j][1] = True
                arr.append(segs[j][0])
    # for seg in arr:
    #     print seg,
    # print ""
    lays += 1

print lays


a = int(raw_input())
if(a % 5 == 0):
	print(a//5)
else:
	print(a//5 + 1)


import sys
from collections import deque
input = lambda : sys.stdin.readline().strip()
# for i in range(int(input())):
n,m = map(int,input().split())
g = {}
for i in range(m):
    a,b = map(int,input().split())
    if b-1 in g:
        g[b-1].append(a-1)
    else:
        g[b-1]=[a-1]
k = int(input())
way = list(map(lambda x: int(x)-1,input().split()))
bfs = deque()
bfs.append(way[-1])
lvl = [-1]*n
ans = [0]*n
a = [set() for j in range(n)]
lvl[way[-1]]=0
while bfs:
    v = bfs.popleft()
    for u in g[v]:
        if lvl[u]==-1:
            lvl[u]=lvl[v]+1
            a[u].add(v)
            bfs.append(u)
        elif lvl[u]==lvl[v]+1:
            ans[u]=1
            a[u].add(v)
ansv = 0
ans1 = 0
for v in range(k-1):
    if ans[way[v]] or  a[way[v]].pop()!=way[v+1]:#
        ansv +=1
for v in range(k-1):
    if k-v-1!=lvl[way[v]] and way[v] not in a[way[v]]:
        ans1+=1
    elif k-v-1 == lvl[way[v]]:
        break
print(ans1,ansv)


from functools import reduce
l=list(map(int,input().split()))
g=[]
for j in l:
	g.append(reduce(lambda x,y:x*y , [i for i in range(1,j)]))
a,b=g[0],g[1]
while (a==0 and b==0):
	a,b=a%b,a
print(a)


p, d = map(int, raw_input().split())
num = ''
maxi = 0
bound = p - d
pp = p
while p >= bound:
    s = str(p)
    n = len(s) - 1
    if s[n] != '9':
        p -= 1
        continue
    c = 1
    while n >= 0:
        if s[n] != '9' or n == 0:
            if s[n] == '9':
                c += 1
            if c > maxi:
                maxi = c
                num = str(s)
            break
        n -= 1
        c += 1
    p -= 1
if num == '':
    print pp
else:
    print num


import sys
def main():
	inp=map(int,raw_input().split(" "))
	num=inp[0]
	maxpd=inp[1]
	gv=num
	mxnc=ninec(num);
	minv=num-maxpd;
	while num>=(minv):
		ncofn=ninec(num)
		if ncofn>mxnc:
			mxnc=ncofn;
			gv=num;
		num-=1;
	print gv
def ninec(x):
	sx=str(x)
	j=len(sx)-1
	nc=0
	while j>=0 and sx[j]=="9":
		nc+=1;
		j-=1;
	return nc;
main()


def main():
    p, d = map(int, raw_input().split())

    MAX = -1
    VALUE = None

    x = p - d
    while x <= p:
        value = 0
        s = str(x)
        i = len(s) - 1
        while i >= 0 and s[i] == '9':
            value += 1
            i -= 1
        if value >= MAX:
            VALUE = x
            MAX = value
        x += 1
    return VALUE

if __name__ == '__main__':
    print main()


import math;
a,b,c=map(int,input().split());
res=0;
for i in range(0,a):
	t1=i;
	t2=2*i;
	t3=4*i;
	#print(t1+t2+t3);
	#print(t2);
	#print(t3);
	if (b>=t2 and c>=t3):
		res=max(t1+t2+t3,res);
print(res);


# -*- coding: utf-8 -*-
from collections import deque

r1,c1,r2,c2 = map(int, input().split())
if r1 == r2 or c1 == c2:
    n1 = 1
else:
    n1 = 2

if (r1+c1)%2 != (r2+c2)%2:
    n2 = 0
elif r1+c1==r2+c2 or r1-c1==r2-c2:
    n2 = 1
else:
    n2 = 2

r_min, r_max, c_min, c_max = min(r1, r2), max(r1, r2), min(c1, c2), max(c1, c2)
chess = [[0]*8 for i in range(8)]
q = deque([(r1,c1)])
n3 = 0
while q:
    q2 = deque()
    while q:
        (r, c) = q.popleft()
        if (r, c) == (r2, c2):
            break
        chess[r][c] = 1
        if r-1 >= r_min and c-1 >= c_min and not chess[r-1][c-1]:
            q2.append((r-1, c-1))
        if r-1 >= r_min and not chess[r-1][c]:
            q2.append((r-1, c))
        if r-1 >= r_min and c+1 <= c_max and not chess[r-1][c+1]:
            q2.append((r-1, c+1))
        if c-1 >= c_min and not chess[r][c-1]:
            q2.append((r, c-1))
        if c+1 <= c_max and not chess[r][c+1]:
            q2.append((r, c+1))
        if r+1 <= r_max and c-1 >= c_min and not chess[r+1][c-1]:
            q2.append((r+1, c-1))
        if r+1 <= r_max and not chess[r+1][c]:
            q2.append((r+1, c))
        if r+1 <= r_max and c+1 <= c_max and not chess[r+1][c+1]:
            q2.append((r+1, c+1))
    else:
        q = q2
        n3 += 1
        continue
    break

print(n1, n2, n3)


[n] = map(float, raw_input().split())
s = map(str, raw_input().split())

a =  list(s[0])
#print a

c = 0
i = 0
while i <len(a)-2:
	if a[i] == 'x' and a[i+1] == 'x' and a[i+2] == 'x':
		a.pop(i+2)
		c += 1

print c
#print a


p=input()
s=input()
ans=0
while('xxx' in s):
    #s=s.replace('xxx','xx',1)
    print(s)
    ans=ans+1
print(ans)


n = int(input())

f = input()

while f.count('xxx') > 0:
	f.replace('xxx', 'xx')

print(n - len(f))


n=(input())
c=0
y=0
for j in range(4):
 a=input()
 k=[]
 for i in a:
    k.append(i)
 for t in k:
     if t=='.':
        for l in range(k.count('.')):
         k.remove(t)
 for h in range(len(k)):
     k[h]=int(k[h])
 for u in k:
     if k.count(u)<=int(n):
         c+=1
     if c==len(k):y+=1
     else:continue
 c=0
if y==4:print("YES")
else:print("NO")


k = int(input())

panels = {'.':0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0}
flag = True

for i in range(4):
    line = input()
    for ch in line:
        panels[ch] += 1

v = list(panels.values())

for i in v:
    if i > 2 * k:
        flag = False #print('NO')

if flag :
    print('YES')
else:
    print('NO')


k = input()
    k = 2 * int(k)
    count_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for i in range(4):
        line = input()
        a = [int(number) for number in line if number != '.']
        for j in range(len(a)):
            count_list[a[j]] += 1
    for count in count_list:
        if count > k:
            print("NO")
    print("YES")


input()
Tmp = dict()
ans= "YES"
for i in range(4):
    for j in input():
        if j!='.':
            if Tmp.get(j,-1) == -1:
                Tmp[j] = 1
            else:
                if Tmp[j]+1 > 2:
                    ans = "NO"
                    break
                else:
                    Tmp[j]+=1
print(ans)


def count9(x):
	x = str(x)
	x = list(x)
	count = 0
	i = len(x) - 1
	while (x[i] == '9') and (i >= 0):
		count += 1
		i -= 1
	return count

k = raw_input('')
k = k.split()

d = int(k[0])
p = int(k[1])

maxcount = count9(d)
ans = d

while (p >= 0):
	m = count9(d)
	if (m > maxcount):
		maxcount = m
		ans = d
	d -= 1
	p -= 1

print ans


a, k = raw_input().split()
a = int(a)
k = int(k)
if(k == 0) :
    print(a);
else :
    b = str(a - k);
    d = "";
    f = 0;
    while((int(b[:len(b) - len(d)] + d)< a) or ((len(b) <= len(d)) and(int(d) <= a))):
        if(len(b)<= len(d)):
            b = d;
        else :
            b = b[:len(b) - len(d)] + d;
            d+="9";
    b = int(b);
    while(b + 10**(len(d) - 1)<= a):
        b += 10**(len(d) - 1);
    print(int(b));


n,k,l,c,d,p,nl,np=[int(x) for x in input().split()]
jt=(k*l)//nl
lt=c*d
st=p//np
if jt>=n and lt>=n and st>=n:
    print(min(jt,lt,st)
else:
    print(0)


a, b = [int(i) for i in input().split()]
s = 0
for i in range(a, b + 1):
    if list(str(bin(i))[2:]).count('0') == 1:
        s+=1
print(s)


x = input().split()

binary = bin(int(x[0]))
binary = binary[2:]

isFirst = True
new_binary = ''

for i in range(len(binary)):
    if (binary[i] == '0'):
        if (isFirst):
            new_binary = new_binary + '0'
            isFirst = False
        else:
            new_binary = new_binary + '1'
    else:
        new_binary = new_binary + binary[i]

inDecimal = int(new_binary, 2)

total = 0

while (int(x[0]) <= inDecimal and inDecimal <= int(x[1]) ):
    total += 1
    if (new_binary == '1'):
        total -= 1
        new_binary = '10'
    elif (new_binary[-1] == '0'):
        new_binary = '10' + new_binary[:-1]
    else:
        new_binary = '1' + new_binary[:-1]
    inDecimal = int(new_binary, 2)

print(total)


a, b = map(int, input().split())
c = 0
for x in range(a, b+1):
    if "{:b}".format(x).count("0") == 1:
        c += 1
print(c)


def create_mask(mask_number):
    binary_rep = bin(mask_number)
    binary_rep = list(binary_rep)
    for i in range(2,len(binary_rep)):
        binary_rep[i] = '1'

    return "".join(binary_rep)

def generate_aswners_from_mask(mask):
    one_zero_binaries = []
    for i in range(2, len(mask)):
        aux_bin = '0b'
        aux_bin += mask[2:]
        aux_bin = list(aux_bin)
        aux_bin[i] = '0'
        aux_bin = "".join(aux_bin)
        one_zero_binaries.append(aux_bin)
    return one_zero_binaries

input_numbers = input()
input_numbers = input_numbers.split(" ")
input_numbers = list(map(int, input_numbers))

masks = []

##MUDAR PRA ENTRADA
for i in range(input_numbers[0],input_numbers[1]+1):
    mask = create_mask(i)
    if(mask not in masks):
        masks.append(mask)

all_aswners = []

for i in masks:
   all_aswners = all_aswners + generate_aswners_from_mask(i)

final_aswners = []

for i in all_aswners:
    int_rep = int(i,2)
    if(int_rep < input_numbers[0] or int_rep > input_numbers[1] or i[2] == '0'):
        continue
    final_aswners.append(i)

print(len(final_aswners))


def main():
    a, b = map(int, input().split())
    print(sum(bin(i).count('0') == 2 for i in range(a, b + 1)))

if __name__ == '__main__':
    main()


import sys
input = sys.stdin.readline

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

 # dp[grams_of_dough][1..j stuffings]
dp = [[0 for _ in range(m + 1)] for _ in range(n + 1)]

# grams left, grams required, dough required, sell price
stuffing = [(0, 1, 0, 0)] + [map(int, input().split()) for _ in range(m)]

for i in range(0, n + 1):
  for j in range(1, m + 1):
    # attempt to make k of j-stuffed thingies
    for k in range(stuffing[j][0] / stuffing[j][1] + 1):
      if i - stuffing[j][2] * k > -1:
        dp[i][j] = max(dp[i - stuffing[j][2] * k][j - 1] + stuffing[j][3] * k, dp[i][j])

ans = 0
# for row in dp: print row
for k in range(n):
  ans = max(ans, dp[k][m] + ((n - k) / c_0) * d_0)

print ans


from sys import stdin

def arr_inp(n):
    if n == 1:
        return [int(x) for x in stdin.readline().split()]
    elif n == 2:
        return [float(x) for x in stdin.readline().split()]
    else:
        return list(stdin.readline()[:-1])

n, m, c0, d0 = arr_inp(1)
staff, percent, ans = [arr_inp(1) for i in range(m)], [[0, d0 / c0]], 0

for i in range(m):
    percent.append([i + 1, staff[i][-1] / staff[i][-2]])

percent.sort(reverse=True, key=lambda x: x[1])

for i, j in percent:
    if i:
        val = min(staff[i - 1][0] // staff[i - 1][1], n // staff[i - 1][2])
        ans += staff[i - 1][-1] * val
        n -= val * staff[i - 1][2]
    else:
        ans += d0 * (n // c0)
        n -= (n // c0) * c0

    # print(n, i, ans)

print(ans)


from sys import stdin, setrecursionlimit
from collections import *
import threading

def arr_inp(n):
    if n == 1:
        return [int(x) for x in stdin.readline().split()]
    elif n == 2:
        return [float(x) for x in stdin.readline().split()]
    else:
        return list(stdin.readline()[:-1])

def dp(i, rem):
    if rem == 0:
        return 0
    if i >= len(arr):
        if rem:
            return d0 * (rem // c0)
        else:
            return 0

    if mem[i][rem] != -1:
        return mem[i][rem]

    ans1, ans2, ans3 = dp(i + 1, rem), 0, 0

    if rem - arr[i][0] >= 0:
        ans2 = arr[i][1] + dp(i + 1, rem - arr[i][0])
    if rem - c0 >= 0:
        ans3 = d0 + dp(i + 1, rem - c0)

    mem[i][rem] = max(ans1, ans2, ans3)
    return mem[i][rem]

def main():
    ans = 0
    for j in range(len(arr)):
        mem[j][n] = 0

    mem[0][n - arr[0][0]] = arr[0][1]

    for j in range(1, len(arr)):
        for i in range(n + 1):
            mem[j][i] = mem[j - 1][i]

            if i + arr[j][0] <= n:
                if mem[j - 1][i + arr[j][0]] != -1:
                    mem[j][i] = max(mem[j][i], mem[j - 1][i + arr[j][0]] + arr[j][1])
                    ans = max(ans, mem[j][i])

    # print(dp(0, n))
    for j in range(len(arr) + 1):
        for i in range(n, -1, -1):
            ext = (i // c0) * d0
            if mem[j][i] == -1:
                mem[j][i] = ext
            else:
                mem[j][i] += ext
            ans = max(ans, mem[j][i])
    print(ans)

if __name__ == '__main__':
    n, m, c0, d0 = arr_inp(1)
    staff, arr = [arr_inp(1) for i in range(m)], []

    for a in staff:
        arr.extend([[a[2], a[3]] for i in range(a[0] // a[1])])

    mem = [[-1 for i in range(n + 1)] for j in range(len(arr) + 1)]
    main()


import sys

sys.setrecursionlimit(10 ** 6)

def pyes_no(condition) :
  if condition :
    print ("YES")
  else :
    print ("NO")

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

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

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

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

n, m, c0, d0 = rints()
n += 1

prev = [0] * n
for i in range(n / c0 + 1) :
  prev[i * c0] = i * d0

for i in range(m) :
  new = prev[:]
  a, b, c, d = rints()
  for start in range(n) :
    for bake in range(1, min((n - start - 1) / c + 1, a / b + 1)) :
      new[start + bake * c] = max(new[start + bake * c], prev[start] + bake * d)

  prev = new
print prev[-1]


import sys
from sys import stdin, stdout
def R():
    return map(int, stdin.readline().strip().split())

n, m, c, d = R()

arr1 = []
for i in range(n//c):
    arr1.append((c, d))
for i in range(m):
    a, b, c, d = R()
    for j in range(min(a//b, n//c)):
        arr1.append((c, d))

dp = [[0 for i in range(n+1)] for i in range(len(arr1))]

for i in range(len(arr1)):
    c, d = arr1[i-1]
    for w in range(n+1):
        dp[i][w] = dp[i-1][w]
        if w >= c:
            if dp[i-1][w-c] + d > dp[i][w]:
                dp[i][w] = dp[i-1][w-c] + d

stdout.write(str(dp[-1][-1]))
# print(arr1)
# for i in dp:
#     print(i)


# n grams of dough
# m stuffings
# a[i] grams left of stuffing i
# b[i] grams needed
# c[i] grams of dough
# d[i] price
#
# without stuffing: (special case)
# a0 = infinite
# b0 = 0
# c0 grams of dough
# d0 price
# maximize price over all buns

# at each step a choice of 1..k of m-th stuffings or no stuffing
#
# IH: we know how to find the max profit for dough n-1 and stuffings S[]
#
def f(n, a, b, c, d):
    m = len(a)
    P = [[-1] * m for _ in range(n + 1)] # n * m

    def rec(weight, index):
        if index < 0: return 0

        # memoization
        if P[weight][index] != -1:
            return P[weight][index]

        profit = 0

        # we can create at most a[i] // b[i] stuffings
        stuffing, count = 0, 0
        while stuffing <= a[index]:
            remains = weight - (count * c[index])

            # not enough dough
            if remains < 0:
                break

            prev_profit = rec(remains, index - 1)

            profit = max(profit, prev_profit + count * d[index])

            # try more stuffing
            stuffing += b[index]
            count += 1

        return profit

    ans = rec(n, m - 1)
    print(ans)
    return ans

inf = float("inf")
A = [inf, 7,  12 ]
B = [1,   3,   3 ]
C = [2,   2,   1 ]
D = [1,  100, 10 ]
assert f(10, A, B, C, D) == 241

n, m, c0, d0 = map(int, input().split())
a, b, c, d = [inf], [0], [c0], [d0]
for _ in range(m):
    _a, _b, _c, _d = map(int, input().split())
    a.append(_a)
    b.append(_b)
    c.append(_c)
    d.append(_d)

ans = f(n, a, b, c, d)
print(ans)


# n grams of dough
# m stuffings
# a[i] grams left of stuffing i
# b[i] grams needed
# c[i] grams of dough
# d[i] price
#
# without stuffing: (special case)
# a0 = infinite
# b0 = 0
# c0 grams of dough
# d0 price
# maximize price over all buns

# at each step a choice of 1..k of m-th stuffings or no stuffing
#
# IH: we know how to find the max profit for dough n-1 and stuffings S[]
#
def f(n, a, b, c, d):
    m = len(a)
    P = [[-1] * m for _ in range(n + 1)] # n * m

    def rec(weight, index):
        if index < 0: return 0

        # memoization
        if P[weight][index] != -1:
            return P[weight][index]

        profit = 0

        # we can create at most a[i] // b[i] stuffings
        stuffing, count = 0, 0
        while stuffing <= a[index]:
            remains = weight - (count * c[index])

            # not enough dough
            if remains < 0:
                break

            prev_profit = rec(remains, index - 1)

            profit = max(profit, prev_profit + count * d[index])

            # try more stuffing
            stuffing += b[index]
            count += 1

        return profit

    ans = rec(n, m - 1)
    return ans

inf = float("inf")
A = [inf, 7,  12 ]
B = [1,   3,   3 ]
C = [2,   2,   1 ]
D = [1,  100, 10 ]
assert f(10, A, B, C, D) == 241

n, m, c0, d0 = map(int, input().split())
a, b, c, d = [inf], [0], [c0], [d0]
for _ in range(m):
    _a, _b, _c, _d = map(int, input().split())
    a.append(_a)
    b.append(_b)
    c.append(_c)
    d.append(_d)

ans = f(n, a, b, c, d)
print(ans)


import functools as ft
mikla, types, c0, d0 = map(int, input().split())
pieejamais = [0];pildijumapaterins = [0];miklaspaterins = [0];cena = [0]
for recepte in range(types):
    a, b, c, d = map(int, input().split())
    pieejamais.append(a);pildijumapaterins.append(b);miklaspaterins.append(c);cena.append(d)

@ft.lru_cache(maxsize=524288)
def izd(miklasdaudz, pildijumi):
    if miklasdaudz == 0:
        return 0
    if pildijumi == 0:
        return (miklasdaudz // c0) * d0
    maxx = 0
    for k in range(pieejamais[pildijumi] // pildijumapaterins[pildijumi] + 1):
        izmantotamikla = k * miklaspaterins[pildijumi]
        atlikusimikla = miklasdaudz - izmantotamikla
        pelna = cena[pildijumi] * k
        s = izd(atlikusimikla, pildijumi - 1)
        if pelna + s > maxx:
            maxx = pelna + s
    return maxx
print(izd(mikla, types))


import functools

# The first line contains 4 integers n, m, c0 and d0 (1 ≤ n ≤ 1000, 1 ≤ m ≤ 10, 1 ≤ c0, d0 ≤ 100).
# Lavrenty has n grams of dough as well as m different stuffing types
# he can make buns without stuffings. Each of such buns requires c0 grams of dough and it can be sold for d0 tugriks
N, M, c0, d0 = map(int, input().split())

# Each of the following m lines contains 4 integers. The i-th line contains numbers ai, bi, ci and di (1 ≤ ai, bi, ci, di ≤ 100)
#  he has ai grams left of the i-th stuffing. It takes exactly bi grams of stuffing i and ci grams of dough to cook a bun with the i-th stuffing.
#  Such bun can be sold for di tugriks
recipes = []
available_filling = [0]
filling_consumption = [0]
dough_consumption = [0]
price = [0]
for m in range(M):
    ai,bi,ci,di = map(int, input().split())
    available_filling.append(ai)
    filling_consumption.append(bi)
    dough_consumption.append(ci)
    price.append(di)
    rec = (ai,bi,ci,di)
    recipes.append(rec)

# Let create array dp by size n x m. dp[i][j] means maximum number of tugriks that the baker can earn
# if he used i grams of dough and cook buns with stuffings of types 1..j.
#
# Initially dp[i][0] is 0 for all i.
#
# You can easily calculate this dp:
# dp[i][j] = max{ dp[ i-c[j]*k ][ j-1 ] + d[j]*k } for every k from 0 to a[j]/b[j], for which i-c[j]*k>=0

@functools.lru_cache()
def dp(dough, fill_considered):
    if dough == 0:
        return 0
    if fill_considered == 0:
        return (dough // c0) * d0
    m = 0
    for k in range(available_filling[fill_considered] // filling_consumption[fill_considered] + 1):
        prevdough = dough - dough_consumption[fill_considered] * k
        prevstuff = fill_considered - 1
        addition = price[fill_considered] * k
        m = max(m, dp(prevdough, prevstuff) + addition)
    return m

print(dp(N, M))


import functools

# The first line contains 4 integers n, m, c0 and d0 (1 ≤ n ≤ 1000, 1 ≤ m ≤ 10, 1 ≤ c0, d0 ≤ 100).
# Lavrenty has n grams of dough as well as m different stuffing types
# he can make buns without stuffings. Each of such buns requires c0 grams of dough and it can be sold for d0 tugriks
N, M, c0, d0 = map(int, input().split())

# Each of the following m lines contains 4 integers. The i-th line contains numbers ai, bi, ci and di (1 ≤ ai, bi, ci, di ≤ 100)
#  he has ai grams left of the i-th stuffing. It takes exactly bi grams of stuffing i and ci grams of dough to cook a bun with the i-th stuffing.
#  Such bun can be sold for di tugriks
recipes = []
available_filling = [0]
filling_consumption = [0]
dough_consumption = [0]
price = [0]
for m in range(M):
    ai,bi,ci,di = map(int, input().split())
    available_filling.append(ai)
    filling_consumption.append(bi)
    dough_consumption.append(ci)
    price.append(di)
    rec = (ai,bi,ci,di)
    recipes.append(rec)

# Let create array dp by size n x m. dp[i][j] means maximum number of tugriks that the baker can earn
# if he used i grams of dough and cook buns with stuffings of types 1..j.
#
# Initially dp[i][0] is 0 for all i.
#
# You can easily calculate this dp:
# dp[i][j] = max{ dp[ i-c[j]*k ][ j-1 ] + d[j]*k } for every k from 0 to a[j]/b[j], for which i-c[j]*k>=0

@functools.lru_cache()
def dp(dough, fill_considered):
    if dough == 0:
        return 0
    if fill_considered == 0:
        return (dough // c0) * d0
    m = 0
    for k in range(available_filling[fill_considered] // filling_consumption[fill_considered] + 1):
        if dough-dough_consumption[fill_considered]*k>=0:
           prevdough = dough - dough_consumption[fill_considered] * k
           prevstuff = fill_considered - 1
           addition = price[fill_considered] * k
           m = max(m, dp(prevdough, prevstuff) + addition)
    return m

print(dp(N, M))


s = raw_input()
L = len(s)

cont1,cont2,have = 0,0,10
aux = "ABCDEFGHIJ"
found = {}

for c in aux:
    found[c] = False

for i in range(0,L):
    if s[i] == "?":
        cont1 += 1
    elif s[i] in aux:
        if not found[ s[i] ]:
            found[ s[i] ] = True
            cont2 += 1

ans = 1

if s[0] == "?":
    ans *= 9;
    --cont1,
elif s[0] in aux:
    ans *= 9;
    cont2 -= 1
    have -= 1

while cont1 > 0:
    cont1 -= 1
    ans *= 10

while cont2 > 0:
    cont2 -= 1
    ans *= have
    have -= 1

print ans


x = [0] * 8
y = [0] * 8
xy = [None] * 8

for i in range(0, 8):
    line = input()
    if line == '':
        line = input()
    x[i], y[i] = map(int, line.split())
    xy[i] = (x[i], y[i])

a = sorted(x)
b = sorted(y)

x1 = a[0]
x2 = a[3]
x3 = a[7]
y1 = b[0]
y2 = b[3]
y3 = b[7]

if x1 == x2 or x1 == x3 or x2 == x3 or y1 == y2 or y1 == y3 or y2 == y3:
    print("ugly")
    return

if a[0] != a[1] or a[0] != a[2] or a[3] != a[4] or a[5] != a[6] or a[6] != a[7]:
    print("ugly")
    return

if b[0] != b[1] or b[0] != b[2] or b[3] != b[4] or b[5] != b[6] or b[6] != b[7]:
    print("ugly")
    return

for i in range(8):
    if x[i] == x2 and y[i] == y2:
        print("ugly")
        return

    for j in range(i + 1, 8):
        if xy[i] == xy[j]:
            print("ugly")
            return

print("respectable")


#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <cmath>

using namespace std;

long long x, y, l, r;
set <long long> cen;
int main() {
	cin >> x >> y >> l >> r;
	for (int i = 0; i < 61; i++) {
		for (int k = 0; k < 61; k++) {
			long long a = pow(x, i), b = pow(y, k);
			if (a + b >= l && a + b <= r) cen.insert(a + b);
		}
	}
	cen.insert(l - 1);
	cen.insert(r + 1);
	long long ans = 0;
	long long pref = l;
	for (auto i :cen) {
		ans = max(ans, i - pref - 1);
		pref = i;
	}
	cout << ans;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define ld long double
#define pb push_back
#define mp make_pair
#define forn(i,n) for(ll i=0;i<n;i++)
#define fore(i,a,b) for(ll i=a;i<=b;i++)
#define ford(i,n) for(ll i=n-1;i>=0;i--)
#define fi first
#define se second
#define endl "\n"
#define all(a) a.begin(),a.end()
#define sync ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define PI 3.14159265

const ll maxn=1e6+1,mod=1e9+7;

int main(){
    sync
    #ifndef ONLINE_JUDGE
    // for getting input from input.txt
    freopen("input.txt", "r", stdin);
    // for writing output to output.txt
    freopen("output.txt", "w", stdout);
    #endif

    ll x,y,l,r;
    cin>>x>>y>>l>>r;
    vector<ll> lel,lol;
    // lel.pb(0);
    // lol.pb(0);
    ll eh = 1,oh = 1;
    while(eh<=r){
     lel.pb(eh);
     if(eh>ceil(r/x)) break;
     eh*=x;
    }
    while(oh<=r){
        lol.pb(oh);
     if(oh>ceil(r/y)) break;
        oh*=y;
    }
    vector<ll> ok;

    bool f1 = true,f2 = true;
    // cout<<f1<
    for(auto it:lel){
        for(auto ii:lol){
            if(ii+it==l) f1 = false;
            if(ii+it==r) f2 = false;
            if(ii+it>l&&it+ii<r)
            ok.pb(ii+it);
        }
    }
    // cout<<f1<<" "<<f2<<endl;
    sort(all(ok));
    ok.resize(unique(all(ok))-ok.begin());
    ll ans = 0;
    int sz = ok.size();
    fore(i,1,sz-1){
        ans = max(ans,ok[i]-ok[i-1]-1);
    }
    // cout<<ans<<endl;
    if(!ok.empty()){
        if(f1){
            ans = max(ans,ok.front()-l);
        }
        else{
            ans = max(ans,ok.front()-l-1);
        }
        if(f2){
            ans = max(ans,r-ok.back());
        }
        else{
            ans = max(ans,r-ok.back()-1);

        }
    }
    else{
        // cout<<f1<<" "<<f2<<endl;
        if(f1&&f2) ans = r-l+1;
        else if(f1||f2) ans = r-l-1;
    }
    cout<<ans;

    return 0;
}


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


a,b,p,x = list(map(int, input().strip().split()))

def brute(a,b,p,x):
    for n in range(1, x+1):
        if (n*pow(a,n,p)) % p == b:
            print(n)

#brute(a,b,p,x)

sols = 0

inva = pow(a,p-2,p)

a2 = 1
b2 = b
s = 0
d1 = -b
while s < p-1:
    k = (d1 + s) % p
    u = k
    while (p-1)*u + s <= x:
        n = (p-1)*u + s
        #print(s, k, n)
        #print(n*pow(a,n,p) % p, b)
        sols += 1
        u += p
    d1 = (d1 * inva) % p
    s += 1

print(sols)


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

m = int(input())
print(pizza(m))


def reversive(number, modulo):
    return pow(number, modulo - 2, modulo)

def fast_pow(a, b, modulo):
    return pow(a, b, modulo)

def congr(a, b, p, x):
    c = list(range(p + 1))
    for i in range(0, p - 1):
        c[fast_pow(a, i, p)] = i
    s = 0
    y = list(range(2))
    for n1 in range(1, p - 2):
        k = reversive(n1, p) * b % p
        n2 = c[k]
        y[0] = n1
        y[1] = ((n2 - n1) + p - 1) % (p - 1)
        n = y[0] + y[1] * n1
        s += (x - n + (p - 1) * p) // ((p - 1) * p)
    return s

a, b, p, x = [int(j) for j in input().split()]
print(congr(a, b, p, x))


def congr(a, b, p, x):
    c = [list() for i in range(p + 1)]
    for i in range(0, p - 1):
        c[pow(a, i, p)].append(i)
    s = 0
    for n1 in range(1, p):
        k = pow(n1, p - 2, p) * b % p
        for j in range(len(c[k])):
            n2 = c[k][j]
            y0 = n1
            y1 = ((n2 - n1) + p - 1) % (p - 1)
            n = y0 + y1 * p
            s += (x - n + (p - 1) * p) // ((p - 1) * p)
    return s

a, b, p, x = [int(j) for j in input().split()]
print(congr(a, b, p, x))


def phi(x):
    res = x
    y = x
    for i in xrange(2, 1010):
        if y % i == 0:
            res = res / i * (i - 1)
            while y % i == 0:
                y /= i
    if y > 1:
        res = res / y * (y - 1)
    return res
def main():
    a, b, p, x = map(int, raw_input().split())
    if p == 2:
        print x
        return
    if a == 1:
        q, r = divmod(x, p)
        print q + (b <= r)
        return
    a = pow(a, p - 2, p)
    t = b
    f = p * (p - 1)
    q, r = divmod(x, f)
    pp = pow(p - 1, p - 2, p) * (p - 1)
    ph = pow(p, phi(p - 1) - 1, p - 1) * p
    ans = (p - 1) * q
    if not r:
        print ans
        return
    for i in xrange(p - 1):
        s = (i * ph + t * pp) % f
        if s <= r:
            ans += 1
        t = t * a % p
    print ans
main()


def egcd(a, b):
    if b == 0:
        return 1, 0, a
    x1, y1, c = egcd(b, a % b)
    return y1, x1 - (a / b) * y1, c

def crt(a0, n0, a1, n1):
    if min(n0, n1) < 0:
        return 0, -1
    x, y, g = egcd(n0, n1)
    if (a0 - a1) % g:
        return 0, -1
    x *= (a1 - a0) / g
    y *= (a1 - a0) / g
    k = n1 * n0 / g
    return (n0 * x + a0) % k, k

a, b, p, x = map(int, raw_input().split())

inv = [1] * p
for i in range(2, p):
    q = p / i
    r = p % i
    inv[i] = p - inv[r] * q % p

ans = 0
for i in range(p - 1):
    a1 = pow(a, inv[i], p) * b
    a0, n0 = crt(a1, p, i, p - 1)
    if x >= a0:
        ans += 1 + (x - a0) / n0
print(ans)


a=input()
b=input()
c=input()
d=input()
e=input()
import math
g=math.sqrt((b-d)*(b-d)+(c-e)*(c-e))
f=g/(2*a)
h=int(f)
i=h
if i==f:
        print (h)
elif f>i:
        print (h+1)


n=int(input())
a=[]
b=[]
c=[]
for i in range(n+1):
    for j in range(n+1):
        if(i*j==n and i<=j):
            a.append(i)
            b.append(j)

print(max(a),min(b))


from math import sqrt
n=int(input())
for i in range(int(sqrt(n)),0,-1):
    for j in range(int(sqrt(n)),n+1):
        if i*j==n:
            print(i,j,sep=" ")
            exit()


n = int(input())
MassFactor = []
for i in range(1,int(n**0.5)+1):
    if n % i == 0:
        MassFactor.append([i, n//i])
d = MassFactor[0][1]-MassFactor[0][0]
� = 0
for i in range(1,len(MassFactor)):
    if MassFactor[i][1]-MassFactor[i][0] < d:
        d = MassFactor[0][1]-MassFactor[0][0]
        � = i
print(MassFactor[�][0],MassFactor[�][1])


n=input()
if n%2==0:
    print("white")
else:
    print("black")


user_input=input()

if user_input%2!=0:
    print ("black")
else:
    print ("white")
    print ("1 2")


a = []
b= []
n, m = 0, 0
x, y = 0, 0
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

ind = a.index(0)
del a[ind]
x = min(a)
y = min(b)

if x != y:
    print(x * 10 + y)
else:
    print(x)


n=(input())
s=map(int,raw_input()[::2])
for i in range(n+1):
	for j in range(i):
		ans=max(sum(s)-2)*sum(s[j:i])+i-j
		print(ans)

'''a=[]
flag=0
ans=0
for k in (0,1,1):
	print(k)
for i in x:
	a.append(int(i))
flag1=0
for i in range(n):
	if(a[i]==1):
		flag1+=1
for i in range(0,n,1):
	for j in range(i,n,1):
		flag=0
		if(i!=j):
			for k in range(i,j):
				if(a[k]==0):
					flag+=1
					ans=max(ans,flag)
if(ans==0):
	print(0)
else:
	print(ans+flag1)'''


n = int(raw_input())
pos_final = int(raw_input())
vec = [0, 0, 0]
vec[pos_final] = 1
for i in xrange(n, 0, -1):
  if i % 2 == 0:
    aux = vec[1]
    vec[1] = vec[2]
    vec[2] = aux
  else:
    aux = vec[1]
    vec[1] = vec[0]
    vec[0] = aux

for pos in xrange(3):
  if vec[pos] == 1:
    print pos


n = int(raw_input())
x = int(raw_input())

content = [False, False, False]

content[x] = True

if n % 2 == 1:
    tmp = content[1]
    content[1] = content[0]
    content[0] = tmp
    n-=1

for i in xrange(n / 2):
    tmp = content[2]
    content[2] = content[1]
    content[1] = content[0]
    content[0] = tmp

for i in xrange(3):
    if content[i]:
        print i


import sys
import math
import functools

@functools.lru_cache(maxsize=None)
def sol(s):
	ans = 0
	for i in range(len(s)):
		a = i > 0 and ord(s[i]) - ord(s[i-1]) == 1
		b = i < len(s) -1 and ord(s[i]) - ord(s[i+1]) == 1
		if a or b:
			ans = max(ans, 1 + sol(s[:i] + s[i+1:]))
	return ans

n = int(sys.stdin.readline())
s = sys.stdin.readline()
ans = sol(s)
print(ans)


strings = dict()

def check_string(seq):
    global strings
    daughter_seqs = list()
    if len(seq) == 1:
        strings[seq] = 0
        return None

    for i in range(1, len(seq)-1):
        if ord(seq[i]) - ord(seq[i-1]) == 1 or ord(seq[i]) - ord(seq[i+1]) == 1:
            daughter_seqs.append(seq[0:i] + seq[i+1:])

    if ord(seq[0]) - ord(seq[1]) == 1:
        daughter_seqs.append(seq[1:])
    if ord(seq[-1]) - ord(seq[-2]) == 1:
        daughter_seqs.append(seq[:-1])

    if len(daughter_seqs) == 0:
        strings[seq] = 0
        return None
    else:
        results = list()
        for daughter_seq in daughter_seqs:
            if daughter_seq not in strings.keys():
                check_string(daughter_seq)
            results.append(strings[daughter_seq])
        strings[seq] = max(results) + 1

n = int(input())
input_str = input()

check_string(input_str)
print(strings[input_str])\


import atexit
import io
import sys
import math
from collections import defaultdict,Counter

# _INPUT_LINES = sys.stdin.read().splitlines()
# input = iter(_INPUT_LINES).__next__
# _OUTPUT_BUFFER = io.StringIO()
# sys.stdout = _OUTPUT_BUFFER

# @atexit.register
# def write():
#     sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())

# sys.stdout=open("CP3/output.txt",'w')
# sys.stdin=open("CP3/input.txt",'r')

# m=pow(10,9)+7
n=int(input())
s=list(input())
if n==1:
    print(0)
else:
    # s1=s[:]
    for j in range(122,97,-1):
        k=0
        while k<len(s) and len(s)>1:
            if s[k]==chr(j):
                if k==0:
                    if s[1]==chr(j-1):
                        del(s[k])
                elif k==len(s)-1:
                    if s[-2]==chr(j-1):
                        del(s[k])
                elif s[k-1]==chr(j-1) or s[k+1]==chr(j-1):
                        del(s[k])
                else:
                    k+=1
            else:
                k+=1

    print(n-len(s))


n=map(int,input())
cm=input()
rs=0
temp_step=0
x=0
y=0
for i in cm:
    if i=="U":
        x+=1
    elif i=="D":
        x-=1
    elif i=="L":
        y+=1
    else:
        y-=1
    if x==0 and y==0:
        temp_step=0
    else:
        temp_step+=1
print(len(cm)-temp_step)


input()
s = input()
u,d,l,r = s.count('U'), s.count('D'), s.count('L'), s.count('R')
print(min(u, d)+min(l, r))


n=(input())
l=input()
print(2*(min(l.count('U'),l.count('D'))+min(l.count('L'),l. count('R'))


from collections import *
points = [[int(x) for x in input().split()] for i in range(8)]
x,y = Counter(), Counter()
for r,c in points:
    x[r] += 1
    y[c] += 1
xk = sorted(x.keys())
yk = sorted(y.keys())
def is_ok(k, d):
    if len(k) != 3:
        return False
    lo,mid,hi = k
    return d[lo] == 3 and d[mid] == 2 and d[hi] == 3

if is_ok(xk,x) and is_ok(yk,y):
    print('respectable')
else:
    print('ugly')


n=int(input())
if n%2==0:
	print(n)
elif n==1:
	print(1)
else:
	print(n-1,1)


l, q = map(int, raw_input().split())
s = list(raw_input())

for i in range(q):
	l, r, k = map(int, raw_input().split())
	l-=1
	t = s[l:r]
	if k==1: t.sort()
	else: t.sort(reverse=True)
	s[l:r] = t
print ''.join(s)


#include <stdio.h>
#include <time.h>

main()
{

	printf("%lf sec \n", (double)clock()/CLOCKS_PER_SEC);
	return 0;
}


n = int(input())

i = 1;
arr = [];
while True:
    if (n & 1 == 1):
        arr.append(i);
    n >> = 1;
    i = i + 1;
    if ( n == 0 ):
        break;

outstr = "";
for elm in arr:
    outstr = str(elm) + " " + outstr;
print(outstr);


n=int(input())
i=0
l=[]
while(n!=1):
    i+=1
    if(n%2):
        l.insert(0,i)
        n=n/2
print(i+1,*l)


n, k, x = map(int, raw_input().split())

balls = map(int, raw_input().split())

cont_destruidas = 0

def marcador(index_inicial, cont, color):
	sentinela = 0
	for s in range(n):
		if (sentinela < cont and balls[s] == color):
			sentinela += 1
			balls[s] = -99

def cont_balls():
	soma = 0
	for i in range(n):
		if (balls[i] != -99):
			soma += 1
	return soma

def search_first():
	for i in range(n):
		if (balls[i] != -99):
			return balls[i]
	return -99

def cont_3():
	cont = 0
	color = search_first
	for i in range(n):
		if (balls[i] != -99):
			if (color == balls[i]):
				cont+= 1
				if (cont > 2):
					return True
	return False

if (n > 2):
	for i in range(n - 1):
		if (balls[i] == x and balls[i + 1] == x):
			balls[i] = -99
			balls[i + 1] = -99
			cont_destruidas += 2
			break

	color = search_first()
	if (cont_destruidas != 0 and color != -99):
		cont = 0
		index_inicial = 0

		for j in range(n):
			if (balls[j] != -99 and balls[j] == color):
				cont += 1
				if (j == n - 1 and cont > 2):
					cont_destruidas += cont
					marcador(index_inicial, cont, color)
			elif (balls[j] != -99 and balls[j] != color):
				index_inicial = j

				if (cont > 2):
					cont_destruidas += cont
					marcador(index_inicial, cont, color)
				cont = 1
				color = balls[j]

	while (search_first() != -99 and cont_3):
		color = search_first()
		if (cont_destruidas != 0 and color != -99):
			cont = 0
			index_inicial = 0

			for j in range(n):
				if (balls[j] != -99 and balls[j] == color):
					cont += 1
					if (j == n - 1 and cont > 2):
						cont_destruidas += cont
						marcador(index_inicial, cont, color)
				elif (balls[j] != -99 and balls[j] != color):
					index_inicial = j

					if (cont > 2):
						cont_destruidas += cont
						marcador(index_inicial, cont, color)
					cont = 1
					color = balls[j]

print cont_destruidas


from itertools import groupby

n, k, x = map(int, raw_input().split())
balls = map(int, raw_input().split())
destroyed = 0

for i in xrange(len(balls) - 1):
    balls_copy = list(balls)
    if not (balls_copy[i] == x and balls_copy[i+1] == x):
        continue

    balls_copy.insert(i, x)

    keep_in_loop = True

    while keep_in_loop:
        grouped_balls = [(y, sum(1 for i in g)) for y, g in groupby(balls_copy)]

        for j in xrange(len(grouped_balls)):
            if grouped_balls[j][1] >= 3:
                before = sum(b for a, b in grouped_balls[0:j])
                after = sum(b for a, b in grouped_balls[j + 1:])
                balls_copy = balls_copy[0:before] + balls_copy[-after:]

                keep_in_loop = True
                if len(grouped_balls) == 1:
                    balls_copy = []
                    keep_in_loop = False

                break
            else:
                keep_in_loop = False

    destroyed = max(len(balls) - len(balls_copy), destroyed)

print destroyed


import copy

def elimina_lista(lista, elemento, i):
    lista.insert(i, elemento)
    i = 2
    j = i

    soma = 0
    cont = 1
    while i >= 0 and j <= len(lista)-1:
        if lista[i] == elemento and i > 0:
            if lista[i-1] == elemento:
                cont += 1

                i -= 1
        if lista[j] == elemento and j < len(lista) -1:
            if lista[j+1] == elemento:
                j += 1
                cont += 1

        if j < len(lista) - 1 and i > 0:
            if lista[j+1] != elemento and lista[i-1] != elemento:
                if cont >= 3:
                    del lista[i: j+1]
                    j = i
                    elemento = lista[i]
                    soma += cont
                    cont = 1
        elif j < len(lista) - 1 and i == 0:
            if lista[j+1] != elemento and lista[i] != elemento:
                if cont >= 3:
                    del lista[i: j+1]
                    j = i
                    elemento = lista[i]
                    soma += cont
                    cont = 1
        elif j== len(lista) -1 and i > 0:
            if lista[j] != elemento and lista[i-1] != elemento:
                if cont >= 3:
                    del lista[i: j+1]
                    j = i
                    soma += cont
                    cont = 1
        elif j == len(lista) -1 and i == 0:
            if cont >= 3:
                    del lista[i: j+1]
                    j = i
                    soma += cont
                    cont = 1
            else:
                break
    return soma

casos = map(int, raw_input().split())
lista = map(int, raw_input().split())
lista3 = []
for i in casos:
    for j in xrange(len(lista)):
        if lista[j] == i:
            lista2 = copy.copy(lista)
            lista3.append(elimina_lista(lista2, i, j))

if max(lista3) == 0:
    print 0
else:
    print max(lista3) -1


n = long int(input())
n = n + 1
if n % 2 == 1:
	print(n)
else:
	print(long int(n/2))


n= int(input())
if n+1=1:
    print("0")
elif (n+1)%2==0:
    print(int((n+1)/2))
else:
    print(n+1)


n=input()
st=set()
def dfs(x,l):
    if l>=10 or x>n:return
    if x: st.add(x)
    dfs(10*x+a,l+1)
    dfs(10*x+b,l+1)

for a in xrange(10):
    for b in xrange(a+1,10):
        dfs(0,0)
print len(st)


n,x,pos = map(int,input().split())

def bs(pos):
    l = 0
    r = n
    small = set()
    large = set()
    eq = 0
    while l<r:
        mid = l+r>>1
        # print(mid)
        if mid<=pos:
            if mid!=pos:
                small.add(mid)
            else:
                eq+=1
            l = mid+1
        else:
            r = mid
            large.add(mid)
    if l!=pos:
        large.add(l)
    # print(small)
    # print(large)
    return eq, len(small),len(large)
eq,small,large = bs(pos)
# print(small)
# print(large)

lr = n-x
sm = n-lr-1

fact = [1]*(n+1)
for i in range(2,n+1):
    fact[i] = fact[i-1]*i%mod

def inv(x):
    return pow(x,mod-2,mod)

def ncr(n,r):
    if n<=r or r==0 or r==n:
        return 1
    # return fact[n]//fact[r]//fact[n-r]
    return fact[n]%mod*inv(fact[r])%mod*inv(fact[n-r])%mod

# if eq:
#     lr-=1
# print(n,lr,small,large)
print(fact[n-large-small-1]%mod
    *ncr(n-lr-1,small)%mod*fact[small]%mod
    *ncr(lr,large)%mod*fact[large]%mod)


import sys
range = xrange
input = raw_input

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

ways = [0] * (n + 1)
ways[-1] = 1
for i in reversed(range(n)):
    ways[i] = sum(ways[j] for j in range(i+1, n+1))

search = []
i = 0
while k and i < n:
    for j in range(i + 1, n + 1):
        if ways[j] >= k:
            search += reversed(range(i, j))
            i = j
            break
        else:
            k -= ways[j]
assert(search[-1] == n - 1)
assert(k==1)

print ' '.join(str(x+1) for x in search)


# Contest: 20 - 2100 <= Codeforces Rating <= 2199 (https://a2oj.com/ladder?ID=20)
# Problem: (19) Kyoya and Permutation (Difficulty: 4) (http://codeforces.com/problemset/problem/553/B)

def rint():
    return int(input())

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

n, k = rints()
if k == 1:
    print(' '.join(map(str, range(1, n + 1))))
    exit(0)
k -= 1
for i in reversed(range(n - 1)):
    co = 2 ** ((n - i) // 2 - 1)
    if co >= k:
        perm = list(range(1, n + 1))
        perm[i] += 1
        perm[i + 1] -= 1
        b = bin(k - 1)[2:]
        for j, bj in enumerate(b):
            if bj == '1':
                perm[i + 2 * j] += 1
                perm[i + 2 * j + 1] -= 1
        print(' '.join(map(str, perm)))
        break
    k -= co


n = int(raw_input());

def f(n):
	while n > 360 : n -= 360;
	while n < 0 : n += 360
	return min(min(n,abs(360-n)),56565);

B = f(n);
cost = 0;
if n < 0:
	n = -n;
	B,cost = f(n),0;
elif n > 0:
	n = 360 - n;
	B,cost = f(n),0

ctr = -1;
m = n;
for i in xrange(5):
	ctr += 1;
	n = m + i * 90;
	if f(n) < B:
		B = f(n);
		cost = ctr;

ctr = -1
for i in xrange(5):
	ctr += 1;
	n = m - i * 90;
	if f(n) < B:
		B = f(n);
		cost = min(cost,ctr);

print cost


x = int(raw_input())
x %= 360

if x <= 45:
	print 0
elif x <= 135:
	print 1
elif x <= 225:
	print 2
else:
	print 0


x = int(input()) % 360
a = [abs(x - y) for y in range(0,360,90)]
print(a.index(min(a)))


import math

a = int(input())

a %= 360

m = a % 360

mi = 0

for i in range(1, 4):
    if(m > min(360 - abs(a - 90 * i), abs(a - 90 * i))):
        m = min(360 - abs(a - 90 * i), abs(a - 90 * i))
        mi = i

print(mi)


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

for i in range(a):
    if i * 2 <= b and i * 4 <= c:
        x = i

print(x)


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

min_count = list()

min_count.append(a / 1)
min_count.append(b // 2)
min_count.append(c // 4)

count = int(min(min_count))

print(count*7)


import sys
input = sys.stdin.readline

if (w<4):
  print("NO")
elif (w%2==0):
   print("YES")
else:
  print("NO")


import math

def ii():
	return map(int,raw_input().split())

n = input()
count = 0
count += int(math.log(n,2))
n -= 2**count
if n == 1:
	count += 1
else:
	count += int(math.log(n,2))

print count


n = int(input())
a = [0 for i in range(1000)]
a[1] = 2
a[2] = 3
if n <4:
    print(n-1)
    exit()
i = 3
while True:
    a[i] = a[i-1] + a[i-2]
    if a[i] >= n:
        print(i - 1)
        exit()


from math import factorial
def choose(n, c):
    return factorial(n) / factorial(c) / factorial(n - c)

tab = {}
def amount(y, n, t):
    if n == t == 0:
        return 1
    if n > 6 * t + 1 or t == 0 or n < 0 or y >= 4:
        return 0
    if (y, n, t) not in tab:
        res = 0
        for top in xrange(y + 1, 5):
            for bottom in xrange(1, top):
                for i in xrange(top - y):
                    for j in xrange(top - bottom):
                        res += amount(bottom + 1, n - (i + j + 3), t - 1) * choose(top - y - 1, i) * choose(top - bottom - 1, j)
        tab[(y, n, t)] = res
    return tab[(y, n, t)]

n, t = map(int, raw_input().split())
res = 0
for i in xrange(1, 4):
    res += amount(i, n, t)
print res


a,b,c=map(int, input().split())
g=True
while(g):
  t=(a+b+c)//7
  if a>t and b>2*t and c>4*t:
    print(t*7)
    g=False
  else:
    print((t-1)*7)
    g=False


x = int(input())
res = 0
count = 1
for i in range(0,x):
    res += 2**count
    count++
print(res)


n = input()
ans = 0
for i in range(1 , n + 1):
    ans += 1 << i
print ans


n = int(input()
cities = [char for char in input()]
if cities[0] == 'S' and cities[-1] == 'F':
    print('YES')
else:
    print('NO')


n=int(input())
print('Ehab' if !n%2 else 'Mahmoud')


if((int(input())%2==0):
    print("Mahmoud")
else:
    print("Ehab")


n,m=list(map(int,input().strip().split()))
l=list(map(int,input().strip().split()))
t=list(map(int,input().strip().split()))
l.sort()
t.sort()
k=[]
for i in l:
    for j in t:
        if i==j:
            k +=[i]
        else:
            k +=[str(i)+str(j)]
k.sort()
print(k[0])


input()
a = set(map(int,input().split()))
b = set(map(int,input().split()))
if(len(a & b) != 0):
    print(min(a & b))
else:
    print(min(min(a),min(b)),max(min(a),min(b)),seq='')


n,m = map(int,input().split())
n1 = list(map(int,input().split()))
m1 = list(map(int,input().split()))
if len(k)!=0:
	print(min(k))
else:
	print([min(m1)*10+min(n1),min(n1)*10+min(m1)][min(n1)<min(m1)])


n,k = map(int,input().split())
dp = [1,2]
for i in range (2,60):
    dp.append(dp[i-1]+dp[i-2])
a = [i+1 for i in range(0,n)]
k -= 1
for i in range(0,n-1):
    if (k >= dp[n-i-2]):
        k -= dp[n-i-2]
        a[i],a[i+1] = a[i+1],a[i]
print(a)


def get_ans(n, k):

    global fact
    global ans
    a = []

    if (n <= 0):
        return a

    curnum = 1
    curl = 0
    curr = ans[n - 1] - 1
    while (1 == 1):
        if ((curl <= k) and (curr >= k)):
            break
        curnum += 1
        curl = curr + 1
        curr = curl + ans[n - curnum] * fact[curnum - 2] - 1
    a.append(curnum)

    if (curnum == 1):
        l = get_ans(n - 1, k)
        a.extend(l)
        return a

    k1 = k - curl
    k1 = k1 // ans[n - curnum]
    #print(k1)
    pos = 2
    used = [-1] * curnum
    used[curnum - 1] = 0
    for i in range(2, curnum):
        poss = []
        for j in range(curnum):
            if (used[j] != -1):
                continue
            if (j + 1 == pos):
                continue
            if (j == used[pos - 1]):
                continue
            poss.append(j + 1)
        cnum = k1 // fact[curnum - i - 1]
        a.append(cnum + 1)
        k1 = k1 % fact[curnum - i - 1]
        used[cnum] = pos - 1
        pos += 1
    for i in range(curnum):
        if (used[i] == -1):
            a.append(i + 1)
            break
    l = get_ans(n - curnum, k % ans[n - curnum])
    a.extend(l)
    return a

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

fact = []
fact.append(1)
for i in range(1, 51):
    fact.append(fact[i - 1] * i)

ans = []
ans.append(1)
ans.append(1)

for i in range(2, 51):
    ans.append(0)
    for j in range(1, i + 1):
        if (j == 1):
            ans[i] += ans[i - 1]
            continue
        ans[i] += ans[i - j] * fact[j - 2]

a = []

a = get_ans(n, k - 1)
i = 0
csum = 0
while i < n:
    sz = a[i]
    for j in range(sz):
        a[i] += csum
        i += 1
    csum += sz

for i in range(n):
    print(a[i], ' ', sep = '', end = '')
print()


dp = [0 for x in xrange(55)]
dp[0] = 1
dp[1] = 1

for i in xrange(2, 55):
    for j in xrange(0, i):
        dp[i] = dp[i] + dp[j]

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

k -= 1

res = [0 for x in xrange(55)]
last = -1

for i in xrange(n):
    if last == -1:
        if k >= dp[n - i - 1]:
            res[i] = i + 2
            last = i
            k -= dp[n - i - 1]
        else:
            res[i] = i + 1
    else:
        if k >= dp[n - i - 1]:
            res[i] = i + 2
            k -= dp[n - i - 1]
        else:
            res[i] = last + 1
            last = -1

for i in xrange(n):
    print res[i],


def main():
    n, k = map(int, raw_input().split())
    fib = [1, 1]
    for i in range(2, n + 1):
        fib.append(fib[-2] + fib[-1])
    rst = []
    i = 1
    while i <= n:
        todo = n - i
        if i < n - 1 and k > fib[todo]:
            k -= fib[todo]
            rst.extend([i + 1, i])
            i += 2
        else:
            rst.append(i)
            i += 1
    # print k, rst
    print reduce(lambda x, y: str(x) + ' ' + str(y), rst)

main()


length = int(input())
s = input()
num_l = s.count("L")
num_r = s.count("R")
num_u = s.count("U")
num_d = s.count("D")

val = 0
if num_l < num_r:
    val += num_l
else:
    val += num_r
if num_u < num_d:
    val += num_u
else:
    val += num_d

print(val)


from math import sqrt
n = int(input())

for i in range(int(sqrt(n), n+1):
    if n % i == 0 and i >= sqrt(n):
        print(n/i, i)
        break


import math
n=int(input())
a=math.sqrt(n)
while n%a !=0:
    a=a-1
print(a,n//a)


n = int(input())
def display(n):
	for a in range(1,n+1):
		for b in range(1,a+1):
			if a*b == n:
				return b,a
goodResolution = display(n)
print(goodResolution[0],goodResolution[1])


m = list(input())
i = "h"
a = "e"
b = "l"
d = "l"
c = "o"
for i in m:
    for a in m:
        for b in m :
            for d in m :
                for c in n :
                    print("YES")
                else:
                    print("NO")


s=input()
a=0
for i in range(len(s)):
    if(s[i]=='h'):
        c=i
        a=a+1
        break
for i in range(c+1,len(s)):
    if(s[i]=="e"):
        c=i
        a=a+1
        break
for i in range(c+1,len(s)):
    if(s[i]=="l"):
        c=i
        a=a+1
        break
for i in range(c+1,len(s)):
    if(s[i]=="l"):
        c=i
        a=a+1
        break
for i in range(c+1,len(s)):
    if(s[i]=="o"):
        c=i
        a=a+1
        break
if(len(s)<5):
    print("NO")
if(a==5):
    print("YES")
else:
    print("NO")


n = int(raw_input())
A = sorted(map(int, raw_input().split()))
m, i = len(A)/3, 0
can = False
while m > 0:
    B = A[i:i+3]
    if len(B) < 3:
        break
    B[0]+=2
    B[1]+=1
    if B[0]==B[1]==B[2]:
       can = True
       break
    i += 1
print "YES" if can else "NO"


def gelnana(m, b):
    x_1 = int((b-1)*m)
    sum_list = [0] * int(b + x_1 - 1)

    for i in range(b+1):
        x = int((b-i)*m)
        sum_list[i] = (i+1)*(x+1)*(i+x)/2

    return int(max(sum_list))

array = list(map(int,input().split()))
m = array[0]
b = array[1]
print(gelnana(m, b))


def function(x,y,m,c):
    d=y+x/m-c
    return d
def pval(a):
    return a[0]+a[1]
def valof(a,p):
    max=0
    for i,j in p:
        if j<=a:
            sum=0
            for l,m in p:
                if m<=j and l<=i:sum+=l+m
            if max<=sum:max=sum#;print((i,j),sum)
    return max

m,c=list(map(int,input().split()))
p=[(i,j) for i in range(0,m*c+1) for j in range(0,c+1) if function(i,j,m,c)<=0]
print(valof(c,p))


def f(a,b,c,l):
    if a<b+c:
        return 0
    else:
        c=min(l,a-b-c)
        return (c+1)*(c+2)/2

a,b,c,l = map(int,input().split())
z=(l+1)*(l+2)*(l+3)/6
i=0
while i<=l:
    z-=f(a+i,b,c,l-i)+f(b+i,c,a,l-i)+f(c+i,a,b,l-i)
print(z)


def f(a,b,c,l):
    if a<b+c:
        return 0
    else:
        c=min(l,a-b-c)
        return (c+1)*(c+2)/2

a,b,c,l = map(int,input().split())
z=(l+1)*(l+2)*(l+3)/6
i=0
while i<=l:
    z-=f(a+i,b,c,l-i)+f(b+i,c,a,l-i)+f(c+i,a,b,l-i)
    i+=1
print(z)


def triangles(a, b, c, l):
    s = 0
    for la in range(0, l + 1):
        a2 = a + la
        for lb in range(0, l - la + 1):
            b2 = b + lb
            minc = max(abs(a2 - b2) + 1, c)
            maxc = min(a2 + b2 - 1, c + l - la - lb)
            s += max(maxc - minc + 1, 0)
    return s

def main():
    a, b, c, l = map(int, input().split())
    print(triangles(a, b, c, l))

##########

import sys
import time
import traceback
from contextlib import contextmanager
from io import StringIO

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

@contextmanager
def patchio(i):
    try:
        sys.stdin = StringIO(i)
        sys.stdout = StringIO()
        yield sys.stdout
    finally:
        sys.stdin = sys.__stdin__
        sys.stdout = sys.__stdout__

def do_test(k, test):
    try:
        log(f"TEST {k}")
        i, o = test
        with patchio(i) as r:
            t0 = time.time()
            main()
            t1 = time.time()
        if r.getvalue() == o:
            log(f"OK ({int((t1-t0)*1000000)/1000:0.3f} ms)\n")
        else:
            log(f"Expected:\n{o}"
                f"Got ({int((t1-t0)*1000000)/1000:0.3f} ms):\n{r.getvalue()}")
    except Exception:
        traceback.print_exc()
        log()

def test(ts):
    for k in ts or range(len(tests)):
        do_test(k, tests[k])

tests = [("""\
1 1 1 2
""", """\
4
"""), ("""\
1 2 3 1
""", """\
2
"""), ("""\
10 2 1 7
""", """\
0
""")]

if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser()
    parser.add_argument('--test', '-t', type=int, nargs='*')
    args = parser.parse_args()
    main() if args.test is None else test(args.test)


a, b, c, total_increase = map(int, raw_input().split(' '))

num_invalid_triples = 0

for a, b, c in ((a, b, c), (b, a, c), (c, a, b)):
    for a_increase in xrange(total_increase + 1):
        bc_max_increase = min(total_increase - a_increase, a + a_increase - (b + c))

        for bc_increase in xrange(0, bc_max_increase + 1):
            num_invalid_triples += (bc_increase + 1)

# The total number of all possible triples of sum less than or equal `total_increase` equals the number of ways to
# divide a sequence of `total_increase` elements into four parts, which is:
#   C(`total_increase` + 3, 3) = (`total_increase` + 3)! / (3! * `total_uncrease`!) =
num_all_triples = (total_increase + 1) * (total_increase + 2) * (total_increase + 3) / 6

print num_all_triples - num_invalid_triples


n, k = input().split(' ')
n = int(n)
k = int(k)
coef1 = k*k-k+2.25-2*n
if coef1 < 0:
    print('-1')
elif coef1 == 0:
    n1 = n % 10
    k1 = k % 10
    coef1 = (k1*k1-k1+2.25-2*n1)**0.5
    coef2 = k-0.5
    coef = coef2-coef1
    if coef % 1 == 0:
        print(int(coef))
    else:
        print(int(coef)+1)
else:
    coef1 = coef1**0.5
    coef2 = k-0.5
    coef = coef2-coef1
    if coef % 1 == 0:
        print(int(coef))
    else:
        print(int(coef)+1)


x1,y1,x2,y2=map(int,input().split())
x,y=map(int,input().split())
del_a=abs(x1-x2)
del_b=abs(y1-y2)
if x==0:
    print('YES' if del_b%y==0 else 'NO')
    exit()
if y==0:
    print('YES' if del_a%x==0 else 'NO')
    exit()
print ('YES' if (del_a%2==del_b%2 and del_a%a//x%2==del_b//y%2) else 'NO')


x1,y1,x2,y2=map(int,raw_input().split())
x,y=map(int,raw_input().split())
t=False
if abs(y2-y1)%y==0 and abs(y2-y1)/y <=4:
    t=True
    z=abs(y2-y1)/y
else:
    t=False
if abs(x2-x1)%x==0 and ((x2-x1)==0 or abs(x2-x1)/y==z):
    t=True
else:
    t=False
if t==True:
    print "YES"
else:
    print "NO"


a, b, c = sorted(map(int, input().split()))
#print(a,b,c)
i = 0
while a + b < = c
    a = a+1
    i = i+1

print(i)


a,b,c=map(int,input().split())
min_s=min(a,b,c)
max_s=min(a,b,c)
if(min_s+(a+b+c-min_s-max_s)<max_s):
    print(2*max_s+1-(a+b+c))
else
    print(0)


s = raw_input()
if len(s) < 2:
	print s
else:
	print s[0]+s[1:-1].replace('at','@').replace('dot','.')+s[-1]


import math
def binarySearch(arr,x):
 	l=0
 	r=len(arr)-1
 	while(l<=r):
 		mid=l+(r-l)//2
 		if(arr[mid]==x):
 			return mid
 		elif(arr[mid]<x):
 			l = mid + 1
 		else:
 			r = mid - 1
 	return -1
l,r,x,y=map(int,input().split())
prod=x*y
count=0
arr=[int(i) for i in range(l,r+1)]
for i in range(0,len(arr)):
	cond1=False
	cond2=False
	if(prod%arr[i]==0 and binarySearch(arr,prod//arr[i])!=-1):
		cond1=True
	if(cond1 and math.gcd(arr[i],prod//arr[i])==x):
		cond2=True
	if(cond1 and cond2):
		#print(arr[i],prod//arr[i])
		count=count+1
print(count)


name = input()
word = "hello"
a,c=0,0
for i in range(len(name)):
    if name[i] == word[a]:
        a+=1
        c+=1
if c==5:
    print("YES")
else:
    print("NO")


a=input()
b=input()
b=int(a)+1
if b=1 :
    print("0")
else if b%2==0 :
    print(b//2)
else
    print(b)


a, b=map(int, input().split())
if(a<b):
           print(a,end" ")
           print(b/2)
else:
           print(b,end=" ")
           print(a/2)


#print(" ".join(map(str, r)))

n, a, b = map(int, input().split())

pears = b // 4
apples = a // 2
lemons = n // 1

c = min(pears, apples, lemons)
score = (c * 1) + (c * 2) + (c * 4)
print (score)


def main():
    seat = input()
    n = int(seat[:-1])
    s = seat[-1]
    time = "0fedabc".index( s )
    time += 12 * ( n // 4 )
    time += 6 if n & 1 == 0
    print( time )
if __name__ == "__main__":
    main()


seats="fedabc"
def nextseat(s):
    return seats[(seats.index(s)+1)%6]

line=input()
s=line[-1]
n=line[:-1]
n=int(n)
time=1
row1,seat1=1,"f"
row2,seat2=3,"f"
while n not in [row1,row2] or s not in [seat1,seat2]:
    time+=1
    seat1,seat2=nextseat(seat1),nextseat(seat2)
    if (seat1,seat2)==("f","f"):
        if row1%2==0:
            row1+=3
            row2+=3
            time+=3
        else:
            row1+=1
            row2+=1
            time+=1
print(time)


'''input
5 1000
38361 75847 14913 11499 8297
'''

import sys
pow2 = pow              # for modular expo pow2(base, n, mod)
from math import *
from time import time
from collections import defaultdict
from bisect import bisect_right, bisect_left
from string import ascii_lowercase as lcs
from string import ascii_uppercase as ucs
from fractions import Fraction, gcd
from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
#getcontext().prec = 500
sys.setrecursionlimit(30000)

# What doesn't challenge you, makes you weaker.

mod = 10**9 + 7
INF = sys.maxint

raw_input = lambda: sys.stdin.readline().rstrip()
die = lambda : exit(0)
flush= lambda : sys.stdout.flush()

r_s = lambda: raw_input().strip()                   #read str
r_ss = lambda: raw_input().split()          #read stringss
r_i = lambda: int(raw_input())              #read int
r_is = lambda: map(int, raw_input().split())#read ints
r_f = lambda: float(raw_input())            #read float
r_fs = lambda: map(Decimal, raw_input().split()) #read floats

# For effieciently taking lots of queries with each query in a separate line
# having integer values separated by space. A 2d list is made with each row
# corresponding to line. Each row is a list with all the values.
# Use this for fast I/O by taking all input in one go.
r_qs = lambda: map(lambda s:map(int, s.split(' ')), sys.stdin.readlines())

'''-------------------------------------------------------------------'''

# Call it as dbg(varName=varName)
def dbg(**kwargs):
    print "Value of '" + kwargs.keys()[0] + "' is", kwargs[kwargs.keys()[0]]

def main():

    def solve(pos, end, sum1, ans=0):
        if pos==end:
            sum1.append(ans)
            sum1.append((ans+arr[pos])%m)

            return
        solve(pos+1, end, sum1, ans)
        solve(pos+1, end, sum1, (ans+arr[pos])%m)

    n, m =r_is()
    arr = r_is()
    sum1 = []
    sum2 = []
    solve(0, n/2-1, sum1)
    solve(n/2, n-1, sum2)
    # print sum1
    # print sum2
    res = max(sum2)
    sum2.sort()
    for elem in sum1:
        new = m-elem
        lower = bisect_left(sum2, new)
        # print elem, new, lower
        if lower == len(sum2):
            lower = len(sum2)-1
        if lower!=0:
            res = max(res, elem+sum2[lower-1])
        else:
            res = max(res, elem)
    print res

if __name__ == '__main__':
    # local = True
    local = True
    if local:
        try:
            sys.stdin = open('input.txt')
            print 'Running at local.'
            for i in range(r_i()):
                main()
        except IOError:
            main()
    else:
        main()


'''input
4
1 5 2 5
'''

import sys
pow2 = pow              # for modular expo pow2(base, n, mod)
from math import *
from time import time
from collections import defaultdict
from bisect import bisect_right, bisect_left
from string import ascii_lowercase as lcs
from string import ascii_uppercase as ucs
from fractions import Fraction, gcd
from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
#getcontext().prec = 500
sys.setrecursionlimit(30000)

# What doesn't challenge you, makes you weaker.

mod = 10**9 + 7
INF = sys.maxint

raw_input = lambda: sys.stdin.readline().rstrip()
die = lambda : exit(0)
flush= lambda : sys.stdout.flush()

r_s = lambda: raw_input().strip()                   #read str
r_ss = lambda: raw_input().split()          #read stringss
r_i = lambda: int(raw_input())              #read int
r_is = lambda: map(int, raw_input().split())#read ints
r_f = lambda: float(raw_input())            #read float
r_fs = lambda: map(Decimal, raw_input().split()) #read floats

# For effieciently taking lots of queries with each query in a separate line
# having integer values separated by space. A 2d list is made with each row
# corresponding to line. Each row is a list with all the values.
# Use this for fast I/O by taking all input in one go.
r_qs = lambda: map(lambda s:map(int, s.split(' ')), sys.stdin.readlines())

'''-------------------------------------------------------------------'''

# Call it as dbg(varName=varName)
def dbg(**kwargs):
    print "Value of '" + kwargs.keys()[0] + "' is", kwargs[kwargs.keys()[0]]

def main():

    state = {}

    def solve(pos, ans=0):
        if (pos, ans) in state:
            return state[(pos,ans)]
        if pos==n-1:
            state[(pos,ans)] = max((ans+arr[pos])%m, ans)
        else:
            state[(pos,ans)] = max(solve(pos+1, (ans+arr[pos])%m), solve(pos+1, ans))
        return state[(pos,ans)]

    n, m =r_is()
    arr = r_is()
    # for i in range(n):
        # arr[i] %= m
    # print arr
    print solve(0)

if __name__ == '__main__':
    # local = True
    local = True
    if local:
        try:
            sys.stdin = open('input.txt')
            print 'Running at local.'
            for i in range(r_i()):
                main()
        except IOError:
            main()
    else:
        main()


# -*- coding: utf-8 -*-
from itertools import imap
from heapq import merge

def readline(): return imap(int, raw_input().split())

def main():
    n, m = tuple(readline())
    a = filter(bool, (x % m for x in readline()))
    a.sort(reverse=True)

    values = [(0, 1)]
    for v in a:
        new_values1, new_values2 = [], []
        for (x, y) in values:
            x1, y1 = x + v, y + v
            if x1 < m:
                if y1 < m:
                    new_values1.append((x1, y1))
                else:
                    print(m - 1)
                    return
            else:
                new_values2.append((x1 - m, y1 - m))

        new_values = []
        hx, hy = 0, 1
        for pair in merge(values, new_values1, new_values2):
            if hy >= pair[0]:
                hy = pair[1]
            else:
                new_values.append((hx, hy))
                hx, hy = pair
        values = new_values + [(hx, hy)]

    print max(values)[1] - 1

main()


# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction

mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
import os
import sys
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----------------------------------------------------import math
class TreeNode:
    def __init__(self, k, v):
        self.key = k
        self.value = v
        self.left = None
        self.right = None
        self.parent = None
        self.height = 1
        self.num_left = 1
        self.num_total = 1

class AvlTree:

    def __init__(self):
        self._tree = None

    def add(self, k, v):
        if not self._tree:
            self._tree = TreeNode(k, v)
            return
        node = self._add(k, v)
        if node:
            self._rebalance(node)

    def _add(self, k, v):
        node = self._tree
        while node:
            if k < node.key:
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(k, v)
                    node.left.parent = node
                    return node.left
            elif node.key < k:
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(k, v)
                    node.right.parent = node
                    return node.right
            else:
                node.value = v
                return

    @staticmethod
    def get_height(x):
        return x.height if x else 0

    @staticmethod
    def get_num_total(x):
        return x.num_total if x else 0

    def _rebalance(self, node):

        n = node
        while n:
            lh = self.get_height(n.left)
            rh = self.get_height(n.right)
            n.height = max(lh, rh) + 1
            balance_factor = lh - rh
            n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
            n.num_left = 1 + self.get_num_total(n.left)

            if balance_factor > 1:
                if self.get_height(n.left.left) < self.get_height(n.left.right):
                    self._rotate_left(n.left)
                self._rotate_right(n)
            elif balance_factor < -1:
                if self.get_height(n.right.right) < self.get_height(n.right.left):
                    self._rotate_right(n.right)
                self._rotate_left(n)
            else:
                n = n.parent

    def _remove_one(self, node):
        """
        Side effect!!! Changes node. Node should have exactly one child
        """
        replacement = node.left or node.right
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = replacement
            else:
                node.parent.right = replacement
            replacement.parent = node.parent
            node.parent = None
        else:
            self._tree = replacement
            replacement.parent = None
        node.left = None
        node.right = None
        node.parent = None
        self._rebalance(replacement)

    def _remove_leaf(self, node):
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = None
            else:
                node.parent.right = None
            self._rebalance(node.parent)
        else:
            self._tree = None
        node.parent = None
        node.left = None
        node.right = None

    def remove(self, k):
        node = self._get_node(k)
        if not node:
            return
        if AvlTree._is_leaf(node):
            self._remove_leaf(node)
            return
        if node.left and node.right:
            nxt = AvlTree._get_next(node)
            node.key = nxt.key
            node.value = nxt.value
            if self._is_leaf(nxt):
                self._remove_leaf(nxt)
            else:
                self._remove_one(nxt)
            self._rebalance(node)
        else:
            self._remove_one(node)

    def get(self, k):
        node = self._get_node(k)
        return node.value if node else -1

    def _get_node(self, k):
        if not self._tree:
            return None
        node = self._tree
        while node:
            if k < node.key:
                node = node.left
            elif node.key < k:
                node = node.right
            else:
                return node
        return None

    def get_at(self, pos):
        x = pos + 1
        node = self._tree
        while node:
            if x < node.num_left:
                node = node.left
            elif node.num_left < x:
                x -= node.num_left
                node = node.right
            else:
                return (node.key, node.value)
        raise IndexError("Out of ranges")

    @staticmethod
    def _is_left(node):
        return node.parent.left and node.parent.left == node

    @staticmethod
    def _is_leaf(node):
        return node.left is None and node.right is None

    def _rotate_right(self, node):
        if not node.parent:
            self._tree = node.left
            node.left.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.left
            node.left.parent = node.parent
        else:
            node.parent.right = node.left
            node.left.parent = node.parent
        bk = node.left.right
        node.left.right = node
        node.parent = node.left
        node.left = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    def _rotate_left(self, node):
        if not node.parent:
            self._tree = node.right
            node.right.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.right
            node.right.parent = node.parent
        else:
            node.parent.right = node.right
            node.right.parent = node.parent
        bk = node.right.left
        node.right.left = node
        node.parent = node.right
        node.right = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    @staticmethod
    def _get_next(node):
        if not node.right:
            return node.parent
        n = node.right
        while n.left:
            n = n.left
        return n

# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: a + b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]

class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
    if a == 1 or n == 0:
        return 1
    if n % 2 == 0:
        s = powm(a, n // 2, m)
        return s * s % m
    else:
        return a * powm(a, n - 1, m) % m

# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z

# --------------------------------------------------product----------------------------------------
def product(l):
    por = 1
    for i in range(len(l)):
        por *= l[i]
    return por

# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left) / 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid] <= key):
            count = mid + 1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count

# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c

def countGreater(arr, n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] >= k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)

# --------------------------------------------------binary------------------------------------
n,k=map(int,input().split())
l=list(map(int,input().split()))
l=[l[i]%k for i in range(n)]
l1=l[:n//2]
l2=l[n//2:]
s=set()
s1=set()
s2=set()
for i in range(n//2):
    for j in s:
        s2.add((j+l1[i])%k)
    s.add(l1[i])
    for j in s2:
        s.add(j)
    s2=set()
for i in range(n-n//2):
    for j in s1:
        s2.add((j+l2[i])%k)
    s1.add(l2[i])
    for j in s2:
        s1.add(j)
    s2 = set()
s=list(s)
s1=list(s1)
s.sort()
s1.sort()
ans=(max(s),max(s1))
for i in range(len(s)):
    t=k-1-s[i]
    ind=binarySearchCount(s1,len(s1),t)
    r=s1[ind-1]
    rt=s1[-1]
    ans=max((r+s[i])%k,(s[i]+rt)%k)
print(ans)


n,k=map(int,input().split())
l=input()
d={}
for i in l:
    d[i]=d.get(i,0)+1
for i in d.values():
    if i>k:
    print("NO")
    break
else:
    print("YES")


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

print (int(sum(arr)/len(arr))


from sys import stdin

in_lines = stdin.readlines()

def int_values(line) :
    return map( int, line.split(' ') )

lines = map( int_values, map( lambda x:x.strip(), in_lines  ) )

n = lines[0][0]
values = lines[1]
sums = [0]

for v in values :
  sums.append(sums[-1] + v)

for i in range(n) :
  for j in range(i + 1, n + 1) :
    variants.append(sums[n] + (j - i - 2 * (sums[j] - sums[i])))

print max(variants)


def before_light(l, d, v, g, r):
    min_time_to_light = d / v
    light_color = int(min_time_to_light) % (g + r)
    if light_color < g:
        return min_time_to_light
    else:
        return int(min_time_to_light) * (g + r)

def after_light(l, d, v, g, r):
    return (l - d) / v

def solve():
    l, d, v, g, r = map(int, input().split())
    minimum_time = str(round(after_light(l, d, v, g, r) + before_light(l, d, v, g, r), 10))
    print(minimum_time)

solve()


if(it<g):
    ntt = td/sp
    print("%.8f" %ntt )
elif it>(g+r):
    tr = it+(g+r)
    if(it%(g+r)):print("%.8f"%tr)
else:
    nt = r+g+((td-pd)/sp)
    print("%.8f" % nt)


l,d,v,g,r=map(int,input().split())
t=d/v
if g>t: print(t+(l-d)/v)
else:
    if t<g+r:
        w=r-t%g
        print(w+t+(l-d)/v)
    else:
        s=g+r
        while s<=t: s+=(g+r)
        s-=(g+r)
        if t<s+g: print(t+(l-d)/v)
        else:
            w=r-(s+g)%r
            print(t+w+(l-d)/v)


l,d,v,g,r=map(int,input().split())
time =0
time=d/v
curr=time%(g+r)
#print(curr)
if curr<g:
    time+=0.0
else:
    time+=r
time=time+(l-d)/v
print(time)


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

def r(arr):
    if len(arr) > 1:
        a, b = 0, 1
        while b < len(arr) - 1:
            if arr[a] == arr[b]:
                b += 1
        if b - a >= 3:
            for k in range(b, a - 1, -1):
                arr.pop(k)
            r(arr)

if n > 1:
    i, j = 0, 1
    while  j < n and (balls[i] != x or balls[j] != x):
        i += 1
        j += 1
    if j < n:
        balls.pop(j)
        balls.pop(i)
    r(balls)

print(n - len(balls))


import sys

input = []

for line in sys.stdin:
	input.append(line.split())

a = int(input[0][0])
b = int(input[0][1])

def primes(numb):
	result = []
	n = numb

	if is_prime(numb):
		result.append(numb)
		return result

	i = 2

	while i <= n:
		if n % i == 0 and is_prime(i):
			result.append(i)
			while n % i == 0:
				n /= i
		i += 1

	return result

def is_prime(numb):
	if numb == 0 or numb == 1:
		return False

	for i in range(2, int(numb ** (0.5)) + 1):
		if numb % i == 0:
			return False

	return True

numbs = primes(a)

result = 1

for numb in numbs:
	degree = 0
	power = numb
	to = b
	while power <= to:
		degree += to / power
		to /= power

	m = 1
	for i in range(degree):
		result *= numb
		result %= 1000000007

sys.stdout.write(str(result))


import sys

input = []

for line in sys.stdin:
	input.append(line.split())

a = int(input[0][0])
b = int(input[0][1])

def primes(numb):
	result = []
	n = numb

	if is_prime(numb):
		result.append(numb)
		return result

	i = 2

	while i <= n:
		if n % i == 0 and is_prime(i):
			result.append(i)
			while n % i == 0:
				n /= i
		i += 1

	return result

def is_prime(numb):
	if numb == 0 or numb == 1:
		return False

	for i in range(2, int(numb ** (0.5)) + 1):
		if numb % i == 0:
			return False

	return True

def powe(base, p):

	if p == 0:
		return 1

	if p == 1:
		return base

	res = 1

	if p % 2 == 0 :
		r = powe(base, p / 2)
		r %= 1000000007
		return r ** 2 % 1000000007
	else:
		return base * powe(base, p - 1) % 1000000007

numbs = primes(a)

result = 1

for numb in numbs:

	degree = 0
	power = numb
	to = b
	while power <= to:
		degree += to / power
		to /= power

	result *= powe(numb % 1000000007, degree)
	result %= 1000000007

sys.stdout.write(str(result))


a = int(input())
b = int(input())
k = 0

if a > b:
    print b
    k = (a-b)/2
    if k%2 == 0:
        print k
    else:
        print k
elif b > a:
    print a
    k = (b - a) / 2
    if k % 2 == 0:
        print k
    else:
        print k


def inputsocks(a,b):
    # number of mixed pairs equals to the number of the smallest sock
    mixedpairs = min((a,b))

    singlesocks = max((a,b)) - mixedpairs
    singlepairs = int(singlesocks / 2)
    return (mixedpairs, singlepairs)

a, b = [int(x) for x in input().split()]

return inputsocks(a,b)


a=input().split(' ')
first=int(a[0])
second=int(a[1])
third=int(a[2])
sum=(first+second+third)/2
x=first
y=second
z=third
if x-int(x)!=0 or y-int(y)!=0 or z-int(z)!=0:
    print(Impossible)

else:
    x=int(sum-third)
    y=int(sum-first)
    z=int(sum-second)
    if x<0 or y<0 or z<0 or x=0 and y=0 and z=0:
        print("Impossible")
    else:
        print(x, y, z)


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

s=(a+b+c)//2

if (a+b+c)%2 or s-a<0 or s-b<0 or s-c<0:print("Impossible")

else print(s-a,s-b,s-c)


import sys
import bisect as bi
import math as mt
import collections as cc
import heapq as hp
input=sys.stdin.readline
I=lambda:list(map(int,input().split()))
N=101
pr=[0]*(N)
for i in range(2,N):
    if not pr[i]:
        for j in range(i*2,N,i):
            pr[j]=1
for tc in range(int(input())):
    n,=I()
    if not pr[n]:
        a=[1]*(n)
        for i in range(n):
            print(*a)
    else:
        x=0
        y=1
        ans=[[0]*n for i in range(n)]
        for i in range(n):
            for j in range(n):
                if j==x or j==y:
                    ans[i][j]=1
            x+=1
            y+=1
            x%=n
            y%=n
        for i in ans:
            print(*i)


import sys
import math
def II():
	return int(sys.stdin.readline())

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

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

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

def FACT(n, mod):
    s = 1
    facts = [1]
    for i in range(1,n+1):
        s*=i
        s%=mod
        facts.append(s)
    return facts[n]

def C(n, k, mod):
    return (FACT(n,mod) * pow((FACT(k,mod)*FACT(n-k,mod))%mod,mod-2, mod))%mod

n,x,pos = MI()

left = 0
right = n
less = 0
more = 0
while left<right:
    middle = (left+right)//2
    if middle<=pos:
        if middle<pos:
            less+=1
        else:
            break
        left = middle+1
    else:
        more+=1
        right = middle
hasLess = x-1
hasBig = n-x
if less>hassLess or more > hasBig:
    print(0)
else:
    mod = 10**9+7
    ans = FACT(less,mod)*C(hasBig, more, mod)%mod
    ans = ans*FACT(more,mod)%mod
    ans = ans*C(hasLess, less, mod)%mod
    ans*=FACT(n-less-more-1, mod)
    ans%=mod
    print(ans)