inputc = raw_input()
sum1 = 0
for c in inputc[0:3]:
	sum1 += int(c)

sum2 = 0
for c in inputc[3:6]:
	sum2 += int(c)

# print sum1,sum2
if sum1 == sum2 :
	print 0
	exit()

cha =sum1-sum2
# print cha
nums= map(int,inputc)
avs1 = []
for num in nums[0:3]:
	avs1.append( 9-num )
for num in nums[3:6]:
	avs1.append(0-num)

avs2 = []
for num in nums[0:3]:
	avs2.append( 0-num )
for num in nums[3:6]:
	avs2.append(9-num)

def cmpp(a,b):
	if a<0:a=0-a
	if b<0:b=0-b
	return b-a

avs1.sort(cmp=cmpp )
avs2.sort(cmp=cmpp )

avs=avs1
if cha>0:
	avs=avs2
count=1
for av in avs:
	if (av>0 and cha>0) or (av<=0 and cha <=0):
		result=cha-av
	if (av<= 0 and cha>0) or (cha<=0 and av>0):
		result=cha +av

	if cha>0:

		if result>0:
			cha=result
			count+=1
		else:
			print count
			break
	else:
		if result<0:
			cha=result
			count+=1
		else:
			print count
			break


'''
21st august 2017 monday
codeforces 825b yh
'''
from sys import stdin

t = map(int, list(stdin.readline().strip()))

sum_left = sum(t[:3])
sum_right = sum(t[3:])

if sum_left == sum_right:
	print 0
elif sum_left < sum_right:
	d = sum_right - sum_left
	for i in xrange(3):
		t[i] = 9 - t[i]
	t.sort(reverse=True)
	i = 0
	while d > 0:
		d -= t[i]
		i += 1
	print i
else:
	d = sum_left - sum_right
	for i in xrange(3, 6):
		t[i] = 9 - t[i]
	t.sort(reverse=True)
	i = 0
	while d > 0:
		d -= t[i]
		i += 1
	print i


k=int(raw_input())
l=int(raw_input())
if l%k==0:
    i=0
    while k**i<l:
        i+=1
    if k**i==l:
        print 'YES'
        print i-1
    else:
        print 'NO'
else:
    print 'NO'


k=int(input())
l=int(input())
c=0
while k**c<l:
       c+=1
if k**c==l:
       print("YES")
       print(c-1)
else:
       print("NO")


x,y,xx,yy=map(int,raw_input().split())
dy=abs(yy-y)
dx=abs(x-xx)
print (dx/2+1)*(dy/2+1)+(dx/2)*dy/2


def zip_sorted(a,b):

	# sorted  by a
	a,b = zip(*sorted(zip(a,b)))
	# sorted by b
	sorted(zip(a, b), key=lambda x: x[1])

	return a,b

a   = [int(n1) for n1 in input().split()]
b   = [int(n1) for n1 in input().split()]
c   = [int(n1) for n1 in input().split()]

count = 0
for i in range(1,(10**5)+1):
	a[0] = i
	b[1] = sum(a)-sum(b)
	if b[1]>0:
		if sum(a)==sum(b):
			c[2] = sum(a)-(b[1]+a[0])
			if c[2]>0:
				if sum(c)==sum(a)==sum(b)==(c[0]+b[0]+a[0])==(c[1]+b[1]+a[1])==(c[1]+b[1]+a[1]):
					count = 1
					break
				else:
					a[0] = 0
					b[1] = 0
					c[2] = 0
			else:
				a[0] = 0
				b[1] = 0
				c[2] = 0
		else:
			a[0] = 0
			b[1] = 0
			c[2] = 0
	else:
		a[0] = 0
		b[1] = 0
		c[2] = 0

print(*a)
print(*b)
print(*c)

'''
for i in range(n):
for j in range(n):
for k1 in range(len(a)):
for k2 in range(len(a)):
for k3 in range(len(a)):

'''


M = 100000

I = lambda:map(int, raw_input().split())

data = []

for i in range(3):
    data.append(I())

a = sum(data[0])
b = sum(data[1])
c = sum(data[2])

# x + a = y + b = z + c
m = min(a, b, c)
data[0][0] = (b + c - a)/2
data[1][1] = (c + a - b)/2
data[2][2] = (a + b - c)/2

for d in data:
    for v in d:
        print v,
    print ''


n,p,l,r = map(int,raw_input().split())
ans = 0
if p<l:
    ans = (l-p)
    p = l
elif p>r:
    ans = (p-r)
    p = r

if p==l :
    if 1<l:
        ans+=1
    if n>r:
        ans+=(r-p)+1
    print(ans)
elif p==r:
    if n>r:
        ans+=1
    if 1<l:
        ans+=(p-l)+1
    print(ans)
else:
    x = ans + (r-p)+(r-l)+2
    if 1<l:
        ans+=(p-l)+1
        p = l
    if n>r:
        ans+=(r-p)+1
    print(min(x,ans))


def my_get_ans(n, pos, l, r):
    if l == 1 and r == n:
        return 0

    else:
        if l == 1 and r != n:
            return abs(pos - r) + 1

        elif l != 1 and r == n:
            return abs(pos - l) + 1

        else:
            if l <= pos <= r:
                return r - l + 2 + min(abs(pos - l), abs(pos - r))

            elif pos < l:
                return r - l + 2 + abs(pos - l)

            else:
                return r - l + 2 + abs(pos - r)

print(my_get_ans(*map(int, input().split())))


n=int(input())
s=input()
ans,i,k='',0,1
while i<n:
    ans+=s[i]
    i,k=i+k,k+1
print(ans)


n = input()
str1 = raw_input()
s = 0
r = ''
for i in range(1, n+1):
    r += str1[s:s+1]
    s += i
print r


def main():
    p1, t1 = map(int, raw_input().split())
    p2, t2 = map(int, raw_input().split())
    h, s = map(int, raw_input().split())
    if t1 > t2:
        p1, p2 = p2, p1
        t1, t2 = t2, t1
    p = p1 + p2 - s
    if t1 == t2:
        print (h + p - 1) / p * t1
        return
    p1 -= s
    p2 -= s
    ans = 1 << 63
    d1 = [ans] * 20001
    d2 = [ans] * 20001
    e = u = 0
    r1, r2 = t1, t2
    while e < h:
        if r1 == r2:
            e += p
            u += r1
            r1, r2 = t1, t2
            d1[e] = u
            break
        elif r1 < r2:
            if d2[e+p] > u + r2:
                d2[e+p] = u + r2
            e += p1
            u += r1
            r2 -= r1
            r1 = t1
        else:
            if d2[e+p] > u + r1:
                d2[e+p] = u + r1
            e += p2
            u += r2
            r1 -= r2
            r2 = t2
        d1[e] = u
    d3 = [ans] * (h + 1)
    d1[0] = d3[0] = 0
    for i in xrange(e - 1, 0, -1):
        if d1[i] > d1[i+1]:
            d1[i] = d1[i+1]
    v = [(i, d2[i]) for i in xrange(e + 1) if d2[i]]
    for i in xrange(h + 1):
        for j, x in v:
            k = i + j
            if k > h:
                k = h
            if d3[k] > d3[i] + x:
                d3[k] = d3[i] + x
        if ans > d3[i] + d1[h-i]:
            ans = d3[i] + d1[h-i]
    print ans
main()


def R():
    return map(int, input().split())

a1, b1, c1 = R()
a2, b2, c2 = R()

def Z(x, y, z):
    return not x and not y and z

print("1") if (a1*b2-a2*b1) else print("0") if Z(a1, b1, c1) or Z(a2,
                                                                  b2, c2) or (c1*b2-c2*b1) or (a1*c2-a2*c1) else print("-1")


#codeforces 21b intersection, math

def readGen(transform):
	while (True):
		n=0
		tmp=input().split()
		m=len(tmp)
		while (n<m):
			yield(transform(tmp[n]))
			n+=1

readint=readGen(int)
A1,B1,C1=next(readint),next(readint),next(readint)
A2,B2,C2=next(readint),next(readint),next(readint)

def cross(a,b,c,d): return a*d-b*c

def zero(A1,B1): return A1**2 + B1**2 == 0

def lineIntersect(A1,B1,C1,A2,B2,C2):
	if (cross(A1,B1,A2,B2)==0):
		if (cross(A1,C1,A2,C2)==0 and cross(B1,C1,B2,C2)==0):
			# same line
			return -1
		else:
			# parallel
			return 0
	else:
		# cross
		return 1

def judge(A1,B1,C1,A2,B2,C2):
	if (zero(A1,B1) and C1!=0): return 0
	if (zero(A2,B2) and C2!=0): return 0

	if (not zero(A1,B1) and not zero(A2,B2)):
		# line and line
		return lineIntersect(A1,B1,C1,A2,B2,C2)
	else:
		return -1

print(judge(A1,B1,C1,A2,B2,C2))


M = 998244353
n=int(input())
a,b=1,1
for i in range(n-1):a,b=b,a+b
print(a*pow(1<<n,M-2,M)%M)


import math
import sys
m=998244353
input=sys.stdin.readline

fibo=[1,1]
for i in range(200002):
    fibo.append(fibo[-1]+fibo[-2])
    fibo[-1]%=m

n=int(input())
deno=1<<n
inv=pow(deno,m-2,m)
ans=(fibo[n-1]*inv)%m
print(ans)


a,b,c = map(int,raw_input().split())
count = 0
count += 2*c
if a==0 and b == 0:
    count += 0
elif a != 0 and b ==0:
    count += 1
elif a == 0 and b!=0:
    count += 1
elif a==b:
    count += 2*a
else:
    count += 2*min(a,b) + 1
print count


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


m,d=map(int,input().split())
a=[]
if m==1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12:
    for i in range(d,8):
        a.append(1)
    c=(31-len(a))/7
    if c>4:
        print(6)
    else:
        print(5)
if m==4 or m==6 or m==9 or m==11:
    for i in range(d,8):
        a.append(1)
    c=(30-len(a))/7
    if c<=4:
        print(5)
    else:
        print(6)
if m==2:
    for i in range(d,8):
        a.append(1)
    c=(28-len(a))/7
    if c==3:
        print(4)
    elif c<=4:
        print(5)


import math
n, r = [float(x) for x in raw_input().split()]
print(int(math.ceil((n*2)/r)+math.ceil((n*5)/r)+math.ceil((n*8)/r)))


from math import ceil as cs
n,k=map(int,input().split())
r,g,b=2*n,5*n,8*n
print(cs(r/k)+cs(g/k)+cs(b/k))


arr =[[0 for _ in range(5)] for _ in range(5)]
# print(arr)
for i in range(5):
    arr[i] = list(map(int,input().split()))
    if 1 in arr[i]:
        for j in range(5):
            if arr[i][j] == 1:
                posI = i
                posJ = j
print(abs(posI-2)+abs(posJ-2))


for i in xrange(5):
    s = raw_input().split()
    if '1' in s:
        t = i
        c = s.index('1')
print abs(2-t)+abs(c-2)


# enumerate range float sorted reversed
def print_ints(a):
    print ' '.join(map(str, a))

def f(l):
    s = 0
    i = 0
    n = len(l)
    need = n*4.5
    s = sum(l)
    c = 0
    for e in sorted(l):
        if s >= need:
            break
        s += (5-e)
        c += 1
    print c
    return

read_ints = lambda: map(int, raw_input().strip().split())
read_floats= lambda: map(float, raw_input().strip().split())
n = int(raw_input())
l = read_ints()

f(l)


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

grades = [0,0,0,0]
def solution(grades,n):
    for x in query:
        grades[x-2]+=1
    ave = (grades[0]*2+grades[1]*3+grades[2]*4+grades[3]*5)/n
    if ave>=4.5:
        return 0
    else:
        temp = (grades[0]*3)/n+ave
        if temp>=4.5:
            return int((4.5-ave)*n/3+0.99)
        tempn = temp+(grades[1]*2)/n
        if tempn>=4.5:
            return (grades[0]+int((4.5-temp)*n/2+0.99))
        return grades[1]+grades[0]+int((4.5-tempn)*n+0.99)
print(solution(grades,n))


n=int(input())
m=input()
a=0
b=0
for i in range(1,len(m)):
    if m[i]=='F' and m[i-1]=='S':
        a+=1
    elif m[i]=='S' and m[i-1]=='F':
        b+=1
if a>b:
    print('YES')
else:
    print('NO')


n = int(input())
s = input();
cnt1 = 0
cnt2 = 0
s1 = ""
for i in range(1, n):
    if s[i-1] == "S" and s[i] == "F":
        cnt1 += 1
    elif s[i-1] == "F" and s[i] == "S":
        cnt2 += 1
if cnt1 > cnt2:
    print("YES")
else:
    print("NO")


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

count = 0
for a in range(max(n,m)+1):
    for b in range(max(n,m)+1):
        if a*a+b == n and a+b*b == m:
            count += 1

print count


# DON'T USE PYTHON FOR RECURSION
# TRY PYPY
import math
import operator
import sys
from collections import Counter, defaultdict
from math import ceil, floor, pi, sin, sqrt
from sys import exit, stdin, stdout

def main():
    # stdin = open('.in')
    n, m = map(int, stdin.readline().strip().split(' '))
    ans = 0
    for a in range(1001):
        for b in range(1001):
            ans += a * a + b == n and a + b * b == m
    print ans

main()


a, b, c, d = map(int, raw_input().split())
m = max(3 * a / 10, a - (a / 250) * c)
v = max(3 * b / 10, b - (b / 250) * d)
if m > v: print "Misha"
elif m < v: print "Vasya"
else: print "Tie"


#sys.setrecursionlimit(300000)
import sys
import math as m
def main():
    pass
def binary(n):
    #decimal to binary
    return (bin(n).replace("0b", ""))
def decimal(s):
    #binary to decimal
    return (int(s, 2))
def pow2(n):
    #power of a number base 2
    p = 0
    while n > 1:
        n //= 2
        p += 1
    return (p)
def isPrime(n):
    # if  number is prime in √n time
    if (n == 1):
        return (False)
    else:
        root = int(n ** 0.5)
        root += 1
        for i in range(2, root):
            if (n % i == 0):
                return (False)
        return (True)
def lts(l):
    #list to string ,no spaces
    s=''.join(map(str,l))
    return s
def stl(s):
    #for each character in string to list with no spaces -->
    l=list(s)
    #for space in string  -->
    #l=list(s.split(" "))
    return l
#Returns list of numbers with a particular sum
def sq(a,target,arr=[]):
    s=sum(arr)
    if(s==target):
        return arr
    if(s>=target):
        return
    for i in range(len(a)):
        n=a[i]
        remaining=a[i+1:]
        ans=sq(remaining,target,arr+[n])
        if(ans):
            return ans

#1000000007
mod=int(1e9)+7
def sinp(): return sys.stdin.readline().strip()
def iinp(): return int(input())
def ninp(): return map(int, sys.stdin.readline().strip().split())
def llinp(): return list(map(int, sys.stdin.readline().strip().split()))
def p(xyz): print(xyz)
def p2(a,b):print(a,b)
#for _ in range(iinp()):
a,b,c,d=ninp()
m1=max(3*a/10,a-(a/250)*c)
m2=max(3*b/10,b-(b/250)*d)
if(m1==m2):
    print("Tie")
elif(m1>m2):
    print("Misha")
else:
    print("Vasya")


n = int(input())
s = input()

a,b = list(s[:n]), list(s[n:])

a.sort()
b.sort()

q=p=1
for i in range(n):
     if a[i]>b[i]:
          p=0
     elif  a[i]<b[i]:
          q=0
     else:
          p=q=0
if(p+q>0):
     print("YES")
else:
     print("NO")


n=int(input())
l=list(input())
a=l[0:n]
b=l[n:2*n]
a.sort()
b.sort()
count1=True
count2=True
flag=0
for i in range(n):
  if a[i]>b[i]:
    count1=False
  else:
    count2=False
  if (count1==False and count2==False) or (a[i]==b[i]):
    print('NO')
    flag=1
    break
if flag==0:
  print('YES')


import sys

I = lambda: int(input())
readline = lambda: sys.stdin.readline().strip('\n')
RM = readmap  = lambda x=int: map(x,readline().split(' '))

#1321 625 div2
#C: Remove Adjacent
n,s = I(),readline()
for i in range(25,0,-1):
    y = chr(ord('a')+i)
    x = chr(ord('a')+i-1)
    while True:
        temp = len(s)
        s = s.replace(x+y,x).replace(y+x,x)
        if len(s) == temp:
            break
print(n-len(s))
quit()
#B:Journey Planning
#overkill approach: dynamic programming; TLE
#pmax0 = 0
#bmax = b.copy()
#for i in range(n-1,-1,-1):
#    if max0<b[i]:
#        max0 = max(max0,b[i])
#        continue
#    bmax[i] += max([0]+[bmax[j] for j in range(i+1,n) if j-i == b[j]-b[i]])
#    max0 = max(max0,b[i])
#print(max(bmax))

#**trick: find common features in the sequence in O(1)**
d = {}
for i,x in zip(range(I()),RM()):
    d[x-i] = d.get(x-i,0) + x
print(max(d.values()))
quit()
#A: contest for robots
n,a,b =I(),[*RM()],[*RM()]
count1,count2 = 0,0
for i,j in zip(a,b):
    count1 += i & ~j
    count2 += j & ~i
print(divmod(count2,count1)[0]+1 if count1 else -1)


m=int(input())
s=input()+'0'
num=[]
le=len(s)
co=1
for i in range(le-1):
    if s[i]!=s[i+1]:
        num.append([ord(s[i]),co])
        co=1
    else:
        co+=1
li=len(num)
mi=min(num)
i2=mi[0]
for l in range(li):
    ma=max(num)
    i1=num.index(ma)
    le=len(num)
    if le<2 or i2==ma[0]:
        break
    elif i1==0:
        if num[i1][0]==num[i1+1][0]+1:
            num.remove(ma)
        else:
            num[i1][0]-=90
    elif i1==le-1:
        if num[i1][0]==num[i1-1][0]+1:
            num.remove(ma)
        else:
            num[i1][0]-=90
    elif num[i1][0]==num[i1+1][0]+1 or num[i1][0]==num[i1-1][0]+1:
         num.remove(ma)
    else:
        num[i1][0]-=90
    numd=[]
    num.append([1,0])
    lc=len(num)
    for i in range(lc-1):
        if num[i][0]==num[i+1][0]:
            num[i][1]=num[i][1]+num[i+1][1]
            num[i+1]=num[i]
        else:
            numd.append(num[i])
    num=numd[:]
to=0
for i in num:
    to+=i[1]
print(m-to)


a = input()
a = a.split(' ')
a = list(map(int,a))
def really_big(n,s):
    if s >= n:
        return 0
    i = s + 1
    while i <= n:
        t,b = i,0
        while t > 0:
            b = b + (t % 10)
            t = t // 10
        if i - b >= s:
            return n - i + 1
            break
        else:
            i += 1
    return 0
print(really_big(a[0],a[1]))


def nine(p) :

    s=''
    for i in range(p) :
        s+='9'
    return int(s)
def prosh(p) :
    ans=0
    for i in range(1,p+1) :
        ans+=nine(i)*9
    return ans

n,k=map(int,input().split())
l=[0]*29
for i in range(19) :

    e=nine(19-i)

    l[i]=k//e

    k-=l[i]*e

    if k==0 :

        break
    if i==18  or k%e>prosh(19-i-1) :

        l[i]+=1
        break
otv=0
for i in range(19) :

    otv+=10**(19-i)*l[i]

print(max(n-otv+1,0))


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

c = 0

while a:
    if a[0] > k and a[-1] > k:
        break

    if a[0] <= k:
        a.pop(0)
        c += 1
    elif a[-1] <= k:
        a.pop()
        c += 1

print(c)


n,k=map(int,input().split())
a=list(map(int,input().split()))
c=0
d=0
for i in range(len(a)):
	if(a[i]>k):
		break
	else:
		c=c+1
if(c!=n):
	for i in range(len(a)):
		if(a[n-i-1]>k):
			break
		else:
			d=d+1

print(c+d)


n, m,a, b = map(int, input().split())
if(m>=n):
    print('Second')
else:
    print('First')


def Spider ():
    a, b, c, d = map(int, input().split())
    if b >= a: print("Second")
    else: print("First")
TIMES = 1
#TIMES = int(input())
for TIME_TEMP in range(TIMES):
    Spider()


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

def main():
    s = raw_input()
    for l in xrange(len(s)-1, 0, -1):
        for b in xrange(0, len(s)-l+1):
            if s[b:b+l] in s[b+1:]:
                print l
                return 0
    print 0
    return 0

if __name__ == '__main__':
    main()


def all_substrings(s):
	l = set([])
	for i in range(0, len(s)):
		for j in range(1, len(s)+1):
			l.add(s[i:j])
#	print l
	m = -1
	for substring in l:
		c = occurrences(s, substring)
		if c> 1:
			m = max(m, len(substring))
	if m == -1: return 0
	return m

def occurrences(string, sub):
    count = start = 0
    while True:
        start = string.find(sub, start) + 1
        if start > 0:
            count+=1
        else:
            return count

r = raw_input().strip()
print all_substrings(r)
#print all_substrings('abcd')
#print all_substrings('ababa')
#print all_substrings('zzz')


import sys
import math

def doit(A,B,C): return 2*(A+1)*(B+C+2) + B*C

n=eval(sys.stdin.readline().strip('\n\r ').split()[0])

if n==1:
  print( "17 17")
  exit(0)

r=int(math.sqrt(float(n))) + 1
r3=int(10**(math.log10(float(n))/3)) - 1

mx = (8*n) + 9
mn = mx
while r>0:
  if (n%r)==0:
    A = r
    m = n / r
    B = int( math.sqrt(float(m)) ) + 1
    while B>0:
      if (m%B) == 0:
        C = m/B
        mn = min( [mn, doit(A,B,C),doit(B,A,C),doit(C,B,A)] )
      B-=1
  r-=1

print( "%d %d" % ( mn, mx, ) )


import sys
from math import sqrt

if(__name__=='__main__'):
    n=raw_input()
    n=int(n)

    minAns=1L<<64
    maxAns=-minAns
    for i in xrange(1,int(sqrt(n))+5):
        if(n%i==0):
            m=n/i
            for j in xrange(1,int(sqrt(m))+5):
                if(m%j==0):
                    ret=i+1
                    ret=ret*(j+2)*(m/j+2)-n
                    maxAns=max(ret,maxAns)
                    if(ret>0): minAns=min(ret,minAns)

                    ret=i+2
                    ret=ret*(j+1)*(m/j+2)-n
                    maxAns=max(ret,maxAns)
                    if(ret>0): minAns=min(ret,minAns)

                    ret=i+2
                    ret=ret*(j+2)*(m/j+1)-n
                    maxAns=max(ret,maxAns)
                    if(ret>0): minAns=min(ret,minAns)
    print minAns,maxAns


N = int(raw_input())
x = map(int,raw_input().strip('\n').split(' '))
y = map(int,raw_input().strip('\n').split(' '))
if(sum(x)>=sum(y)):
	print("Yes")
else:
	print("No")


n   = int(input())
xl  = list(map(int,input().split()))
yl  = list(map(int,input().split()))
print('Yes' if sum(xl)>=sum(yl) else 'No')


n = int(input())

for i in range(n//2, 0, -1):
    if n % i != 0 or i == 1:
        found = True
        for j in range(i-1, 1, -1):
            if i % j == 0 and (n-i) % j == 0:
                found = False
                break
        if found:
            print(i, n-i)
            break


import math
n = int(input())

if n%2==0:
	l=n/2
else:
	l=(n+1)/2

max_value=0

a1=0
b1=0

for i in range(int(l)):
	a = i
	b = n-i

	if math.gcd(a,b)!=1:
		continue

	elif a/b>max_value:
		max_value=a/b
		a1=a
		b1=b

print (a1 , b1)


a=input()
b=input()
def isSubSequence(str1,str2):
   m = len(str1)
   n = len(str2)

   j = 0    # Index of str1
   i = 0    # Index of str2

    # Traverse both str1 and str2
    # Compare current character of str2 with
    # first unmatched character of str1
    # If matched, then move ahead in str1

   while j<m and i<n:
      if str1[j] == str2[i]:
         j = j+1
      i = i + 1

    # If all characters of str1 matched, then j is equal to m
   return j==m

c=a
s=0
for i in b:
   if i not in c:
      s=-1
      break
   else:
      d=c.index(i)
      c=c[:d]+c[d+1:]
if s==-1:
   print("need tree")
else:
   if len(b)>len(a):
      print("need tree")
   elif len(b)==len(a):
      print("array")
   else:
      if isSubSequence(b,a):
         print("automaton")
      else:
         print("both")


s=input()
t=input()
ss=sorted(s)
st=sorted(t)
if ss==st:
    print('array')
    exit(0)
else:
    c=0
    for i in range(len(s)):
        if s[i]==t[c]:
            c+=1
        if c==len(t):break
    if c==len(t):
        print('automaton')
        exit(0)
    else:
        c = 0
        for i in range(len(s)):
            if ss[i] == st[c]:
                c += 1
            if c == len(t): break
        if c == len(t):
            print('both')
            exit(0)
    print('need tree')


from decimal import *
a=input()
b=Decimal(a)
if(round(b)==b):
    print ("%d"%b)
else:
    print (b)


x, y = raw_input().split('.')
l = y.split('e')
l.append(x)
d, b, a = map(str, l)

if d == '0':
    d = '' + '0' * int(b)
elif int(b) == len(d):
    ans = a + d
elif int(b) > len(d):
    d = d + '0' * (int(b) - len(d))
else:
    d = d[0:int(b)] + '.' + d[int(b):]

ans = a + d

print ans


#!/usr/bin/python
def triangle(l):
    return l[0] + l[1] > l[2]

def degenerate(l):
    return l[0] + l[1] == l[2]

def solve(l):
    for i in range(4):
        copy = list(l)
        del copy[i]
        if triangle(copy):
            return "TRIANGLE"

    for i in range(4):
        copy = list(l)
        del copy[i]
        if degenerate(copy):
            return "SEGMENT"
    return "IMPOSSIBLE"

l = sorted(map(int, raw_input().split(" ")))

print solve(l)


code = input()
b = 96
res = True
for k in code:
    if ord(k) > b + 1:
        res = False
    elif ord(k) == b + 1:
        b += 1
if res:
    print("YES")
else:
    print("NO")


if __name__ == '__main__':
    obfuscation = input()
    letters = 'abcdefghijklmnopqrstuvwxyz'

    obfuscation = list(obfuscation)
    letters = list(letters)

    i = len(obfuscation)
    posibility = 'NO'
    while i:
        if obfuscation[0] != letters[0]:
            posibility = 'NO'
            break
        else:
            while letters[0] in obfuscation:
                obfuscation.remove(letters[0])
                i -= 1
                if len(obfuscation) == 0:
                    posibility = 'YES'
                    break
            letters.remove(letters[0])

    print(posibility)


n, m = [int(i) for i in input().split(" ")]
na = [int(i) for i in input().split(" ")]
ma = [int(i) for i in input().split(" ")]
intersection = set(na) & set(ma)
if len(intersection) != 0:
	print(min(intersection))
else:
	arr = set()
	for i in na:
		for j in ma:
			arr.add(i*10+j)
			arr.add(j*10+i)
	print(min(arr))


n,m=[int(x) for x in input().split()]
a=set([int(x) for x in input().split()])
b=set([int(x) for x in input().split()])
c=list(a&b)
if len(c)!=0:
    print(min(c))
else:
    e=str(min(a))+str(min(b))
    print(min([int(e),int(e[::-1])]))


import sys

n,a,b,c = map(int,sys.stdin.readline().split())
n=n%4
mn=100000000000000
for i in range(64):
    l=n
    sm=0
    aa=i%4
    sm+=a*aa
    l+=aa
    aa=i/4
    bb=aa%4
    l+=2*bb
    sm+=b*bb
    cc=aa/4
    l+=3*cc
    sm+=cc*c
    if l%4==0:
      if sm<mn:
        mn=sm

print mn


n,a,b,c = map(int,raw_input().split())
if n%4==0:
	print 0
else:
	s=4-n%4
	if s==1:
		print min(a,b+c,c*3)
	elif s==2:
		print min(a*2,b,c*2)
	else:
		print min(a*3,a+b,c)


s = input()
curr = 0
max_jump = 0
for c in s:
    curr += 1
    max_jump = max(curr, max_jump)
    if c == 'A' or c == 'E' or c == 'I' or c == 'O' or c == 'U' or c == 'Y':
        curr = 0

curr += 1
max_jump = max(curr, max_jump)
print(max_jump)


def main():
    inpstr = raw_input()
    ans = 0
    tmpans = 1
    vowels = [ 'A', 'E', 'I', 'O', 'U', 'Y' ]
    for ch in inpstr:
        if ch in vowels:
            ans = max( ans, tmpans )
            tmpans = 1
        else:
            tmpans = tmpans + 1
    ans = max( ans, tmpans )
    print ans

if __name__ == "__main__":
    main()


# coding: UTF-8
import sys
#sys.setrecursionlimit(n)
import heapq
import re
import bisect
import random
import math
import itertools
from collections import defaultdict, deque
from copy import deepcopy
from decimal import *

readl= lambda: list(map(str, sys.stdin.readline().split()))
readt= lambda: tuple(map(int, sys.stdin.readline().split()))
read = lambda: sys.stdin.readline().rstrip()
readi = lambda: int(read())
readmi = lambda: map(int, sys.stdin.readline().split())
readms = lambda: map(str, sys.stdin.readline().split())

t = readl()
n = []
m = []
t.sort()
for i in t:
    n.append(int(i[0]))
    m.append(i[1])
count = 2
if m[0] == m[1] == m[2]:
    if n[0] == n[1] == n[2] or (n[0] + 1 == n[1] and n[1] + 1 == n[2]):
        print(0)
    elif n[0] == n[1] or n[0] == n[2] or n[1] == n[2]:
        print(1)
    elif n[0] + 1 == n[1] or n[0] + 2 == n[1] or n[1] + 1 == n[2] or n[1] + 2 == n[2] or n[0] + 1 == n[2] or n[0] + 2 == n[2]:
        print(1)
    else:
        print(2)
elif m[0] == m[1]:
    if n[0] == n[1] or n[0] + 1 == n[1] or n[0] + 2 == n[1]:
        print(1)
    else:
        print(2)
elif m[0] == m[2]:
    if n[0] == n[2] or n[0] + 1 == n[2] or n[0] + 2 == n[2]:
        print(1)
    else:
        print(2)
elif m[1] == m[2]:
    if n[1] == n[2] or n[1] + 1 == n[2] or n[1] + 2 == n[2]:
        print(1)
    else:
        print(2)
else:
    print(2)


def solution():
    days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    n = int(raw_input())
    arr = list(map(int, raw_input().split()))
    ans = False
    for i in range(12):
        v_present = False
        break_check = False
        for j in range(n):
            if days[(i + j) % 12] != arr[j]:
                if days[(i + j) % 12] == 28 and arr[j] == 29 and not v_present:
                    v_present = True
                    continue
                break_check = True
                break
        if not break_check:
            ans = True
            break
    return ans

if __name__ == '__main__':
    if solution():
        print 'Yes'
    else:
        print 'No'


import math
def lcm(i,j):
  return i//math.gcd(i,j)*j

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

c=[0]*20
for bit in range(1,1<<20):
  bitcnt=0
  L=1
  mx=-1
  right=1<<30
  left=-1
  for i in range(20):
    if (bit>>i)&1:
      bitcnt+=1
      mx=i
      left=i+1
      right=min(right,m*(i+1))
      if L!=-1:
        L=lcm(L,i+1)
        if L>2**28:
          L=-1
  if L==-1:
    continue
  if bitcnt%2==1:
    c[mx]+=max(0,right//L-(left-1)//L)
  else:
    c[mx]-=max(0,right//L-(left-1)//L)

for i in range(1,20):
  c[i]+=c[i-1]

seen=[False]*(n+1)
seen[1]=True
ans=1

for i in range(2,n+1):
  if seen[i]:continue
  tmp=1
  now=i
  seen[now]=True
  while now*i<=n:
    tmp+=1
    now*=i
    seen[now]=True

  ans+=c[tmp-1]

print(ans)


import sys
from math import floor, sqrt

input = sys.stdin.readline

def main():
	n, m = map(int, input().split())

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

	for i in range(2, n+1):
		if rar[i] == -1:
			rar[i] = 1
			curi = i*i
			while curi <= n:
				rar[i] += 1
				rar[curi] = 0
				curi *= i

	ans = 0

	check = [0] * (m*20 + 1)

	kar = [0] * (21)

	for k in range(1, 21):
		for j in range(k, m*k + 1, k):
			check[j] = 1
		kar[k] = sum(check)

	#print(kar)

	for i in range(2, n+1):
		if rar[i]:
			ans += kar[rar[i]]

	#print(rar)

	print(ans + 1)

main()


n = int(raw_input())

if n % 2 != 0:
    print '0'
elif n % 4 == 0:
    print str(n/4 - 1)
else:
    print str(n/4)


import sys
input=sys.stdin.buffer.readline

n,m=map(int,input().split())
arr=list(map(int,input().split()))
s=0
ans=0
for i in range(n):
	s+=arr[i]
	if s>m:
		ans+=1
		s=arr[i]
if s>0:
	print(ans+1)
else:
	print(ans)


I=lambda:map(int,raw_input().split())
n,m=I();a=I();k=b=0
for i in range(n):
    k+=[0,1][b+a[i]>m]
    b=[b+a[i],a[i]][b+a[i]>m]
print k+1


for i in range(1):
    n,m,k=map(int,input().split())
    s=(m+k)%n
    if s==0:
        print(n)
    else:
        print(s)


def main():
	n,a,b = map(int,raw_input().split())
	if b > 0:
		arr = range(a,n+1)+range(1,a)
	else:
		arr = range(a,0,-1)+range(n,a,-1)
	#print arr
	ans = a
	for i in range(1,abs(b)+1):
		ans = arr[i%n]
	print ans
main()


n1=int(input())
a=int(n1/1234567)
b=int(n1/123456)
t=0
resultado=0
for x in range(0,a+1):
    for i in range(0,b+1):
        resultado=n1-(1234567*x+123456*i)
        if(resultado%1234==0 and resultado>=0):
            print("YES")
            t=1
            break
    if(t==1):
        break
if(t==0):
    print("NO")


# print ("Input digits and base for number one")
n1, b1 = (int(x) for x in input().split())
# print ("Input all the digits")
d1 = list(int(x) for x in input().split())
d1.reverse()

# print ("Input digits and base for number two")
n2, b2 = (int(x) for x in input().split())
# print ("Input all the digits")
d2 = list(int(x) for x in input().split())
d2.reverse()

# Compute base ten representation of number one
answer1 = 0
power1 = 1
for digit in d1:
    answer1 += digit*power1
    power1 *= b1
# print(answer1)

# Compute base ten representation of number two
answer2 = 0
power2 = 1
for digit in d2:
    answer2 += digit*power2
    power2 *= b2
# print(answer2)

if answer1 < answer2:
    print("<")
elif answer2 < answer1:
    print(">")
else:
    print("=")


n, bx = map(int, raw_input().split())
x = map(int, raw_input().split())
m, by = map(int, raw_input().split())
y = map(int, raw_input().split())

numx = 0
for e, v in enumerate(reversed(x)):
    numx += v*(bx**e)
numy = 0
for e, v in enumerate(reversed(y)):
    numy += v*(by**e)

if numx < numy:
    print('<')
elif numx > numy:
    print('>')
else:
    print('=')


from collections import defaultdict, OrderedDict
InputList = lambda Dtype : [Dtype(x) for x in input().split()]
def solve():
	N = int(input())
	ans = [0,3,5,7,8]
	if N < 5: return ans[N]
	def valid(x):
		return x % 4 == 0 or x & 1
	def loc(x):
		p = x-1
		done_upto = (p+1)//2 - 1 + (p//4) - 1
		return done_upto+1 if valid(x) else done_upto
	Min = 0; Max = 3*10**9
	while Min < Max:
		Mid = (Min+Max)//2
		if loc(Mid) == N:
			return Mid if valid(Mid) else Mid-1
		if loc(Mid) < N:
			Min = Mid+1
		else:
			Max = Mid

ReturnMode = True
t = 1

if not t: t = int(input())

if ReturnMode:
	for _ in range(t):
		ans = solve()
		if type(ans) == list: print(*ans)
		else: print(ans)
else:
	for _ in range(t): solve()


n = int(input())

base = 3
if n == 1:
    print(base)
else:
    krug = n // base
    if n % base == 2:
        krug += 1

    res = 5
    res += (krug - 1) * 4
    if n % base == 0:
        res += 2
    elif n % base == 1:
        res += 3

    print(res)


n = int(input())
mod4 = n % 4
if mod4 == 1:
    print(8)
elif mod4 == 2:
    print(4)
elif mod4 == 3:
    print(2)
elif n == 0:
    print(1)
else:
    print(6)


n = int(input())

if n==0:
    print(1)
elif n%4==1:
    print(8)

elif n%4==2:
    print(4)

elif n%4==3:
    print(2)

elif n%4==0:
    print(6)


import math
n, k = map(int, input().split())

diffs = []
for i in range(1, math.ceil(math.sqrt(n)) + 1):
    if n % i == 0:
        a = i*k + (n//i)
        b = k*(n//i) + i
        if (a // k) * (a % k) == n:
            diffs.append(a)
        if (b // k) * (b % k) == n:
            diffs.append(b)

# print(diffs)
ans = min(diffs)
print(ans)


a,b=input().split()
a=int(a)
b=int(b)
for i in reversed(range(b)):
    if a%i==0:
        print(int(((a*b)/i)+i))
        break


n, k = map(int, input().split())
a = input()
a = a.lower()
f = [0] * 26
for i in a:
    f[ord(i) - 97] += 1
if max(f) > k:
    print("NO")
else:
    print("YES")


s = map(int, raw_input().split())
c = raw_input()
mp = {}

for i in c:
    try:
        mp[i] += 1
    except:
        mp[i] = 1

maxx = 0
for key, value in mp.iteritems():
    if value > maxx:
        maxx = value

if maxx > s[1]:
    print "NO"
else:
    print "YES"


n, m = map( int, raw_input().split())
res = 1
final = 1
for i in range(m):
  res = res*2 % (10**9 +9)
for i in range(n):
    final = (final*(res-1)) % (10**9+9)
    res -= 1
print final


mem = dict()

def C(f,h,kf,kh,kf_init,kh_init):
    if f + h == 0:
        return 1
    else:
        if (f,h,kf,kh) not in mem:
            mem[(f,h,kf,kh)] = F(f,h,kf,kh,kf_init,kh_init) + H(f,h,kf,kh,kf_init,kh_init)
        return mem[(f,h,kf,kh)]

def F(f,h,kf,kh,kf_init,kh_init):
    if f>0 and kf>0:
        return C(f-1,h,kf-1,kh_init,kf_init,kh_init)
    else:
        return 0

def H(f,h,kf,kh,kf_init,kh_init):
    if h>0 and kh>0:
        return C(f,h-1,kf_init,kh-1,kf_init,kh_init)
    else:
        return 0

f,h,kf_init,kh_init = map(int,input().split())
print(C(f,h,kf_init,kh_init,kf_init,kh_init) % 100000000)


from sys import stdin, setrecursionlimit
from collections import *
from types import GeneratorType

# setrecursionlimit(200000)
add = lambda a, b: (a % mod + b % mod) % mod
rints, mod = lambda: [int(x) for x in stdin.readline().split()], 100000000

def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to

    return wrappedfunc

@bootstrap
def dp(i1, i2, j, k):
    if i1 + i2 >= n1 + n2:
        yield 1

    # print(i1, i2, j, k)
    if mem[i1][i2][j][k] != -1:
        yield mem[i1][i2][j][k]

    mem[i1][i2][j][k] = 0
    if i1 < n1:
        if j != 0:
            t = yield dp(i1 + 1, i2, 0, 1)
            mem[i1][i2][j][k] = add(mem[i1][i2][j][k], t)

        elif k < k1:
            t = yield dp(i1 + 1, i2, 0, k + 1)
            mem[i1][i2][j][k] = add(mem[i1][i2][j][k], t)

    if i2 < n2:
        if j != 1:
            t = yield dp(i1, i2 + 1, 1, 1)
            mem[i1][i2][j][k] = add(mem[i1][i2][j][k], t)

        elif k < k2:
            t = yield dp(i1, i2 + 1, 1, k + 1)
            mem[i1][i2][j][k] = add(mem[i1][i2][j][k], t)

    yield mem[i1][i2][j][k]

n1, n2, k1, k2 = rints()
mem = [[[[-1 for _ in range(11)] for _ in range(3)] for _ in range(101)] for _ in range(101)]
print(dp(0, 0, 2, 0))


import math
import os
import random
import re
import sys

# Complete the function below.

s=str(input())
s=s.lower()

vowels = ('a', 'e', 'i', 'o', 'u', 'y')
for x in s:
    if x in vowels:
        s = s.replace(x, "")
a='.'+'.'.join(s)

print(a)


a = list(input().lower())
b=str()
for i in range(len(a)):
    if a[i] not in 'aoyeui':
        b += '.'+a[i]
print(b)


y,b,r=map(int,input().split())
m=min(y,b,r)
if y==b and y==r:
    print(3*b-3)
else:
    if m==y and y!=b and y!=r:
        if r<y+2:
            print(3*y)
        else:
            print(3*y+3)
    elif m==b and b!=r:
        print(3*b)
    elif m==r:
        print(3*r-3)


y, b, r = map(int, input().split())
m=1;n=2; o=3
mix = 6
while m<y and n<b and o<r:
    m+=1; n+=1; o+=1
    mix = (m+n+o)
print(mix)


l = []

for _ in range(11):
    s = input().replace(' ', '')
    if len(s):
        l.append(list(s))

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

x -= 1
y -= 1

x %= 3
y %= 3

ok = False

for i in range(x * 3, x * 3 + 3):
    for j in range(y * 3, y * 3 + 3):
        if l[i][j] == '.':
            ok = True
            l[i][j] = '!'

if not ok:
    for i in range(9):
        for j in range(9):
            if l[i][j] == '.':
                l[i][j] = '!'

for i in range(9):
    for j in range(9):
        print(l[i][j], end='')
        if j % 3 == 2:
            print(' ', end='')
    print()
    if i % 3 == 2:
            print()


def main():
    ls = []
    for i in range(11):
        l = list(filter(lambda c: c != ' ', input()))
        if l:
            ls.append(l)

    r, c = list(map(lambda c: int(c) - 1, input().split(' ')))

    flag = False
    cr, cc = r % 3, c % 3
    for i in range(cr * 3, cr * 3 + 3):
        for j in range(cc * 3, cc * 3 + 3):
            if ls[i][j] not in ['x', 'o']:
                ls[i][j] = '!'
                flag = True

    if not flag:
        for i in range(9):
            for j in range(9):
                if ls[i][j] not in ['x', 'o']:
                    ls[i][j] = '!'

    for i in range(3):
        for j in range(3):
            l = ls[i * 3 + j]
            print(' '.join(map(lambda xx: ''.join(xx), [l[0:3], l[3:6], l[6:9]])))
        print('')

main()


s = raw_input().split(" ")
dif = []
for letter in s:
  if letter in dif: continue
  else : dif.append(letter)

print 4 - len(dif)


sum=input()
colors=sum.split()
count=dict()
d=0
for color in colors:
    count[color]=count.get(color,0)+1
for i,j in count.items():
    if j>1:
        d=d+j-1
print(d)


maximal = 1000000007
def binpow (a, n):
    if n==0:
        return 1
    if n%2 == 1:
        return (binpow(a, n-1) * a) % maximal
    else:
        b = binpow(a, int(n/2)) % maximal
        return (b*b) % maximal
n, m = map(int, input().split())
sf = (binpow(2, m) - 1 + maximal) % maximal
rez = binpow(sf, n) % maximal
print(str(int(rez)))


n,m = map(int,input().split())
p = 10**9+7
print(pow((pow(2,m,p)-1),n,p))


def check(h,m):
    if('7' in str(h) or '7' in str(m)):
        return True
    return False

x=int(input())
h,m=map(int,input().split())
c=0
while True:
    if not check(h,m):
        m-=x
        c+=1
        if m<0:
            m=(m+60)%60
            h-=1
        if h<0:
            h=23
            m=(m+60)%60
    else:
        break
print(c)


f=[7,17,27,37,47,57]
x=input()
s=raw_input()
h,m=map(int,s.split())
if '7' in s:
    print 0
else:
    t=h*60+m
    cnt=1
    while True:
        t=(t-x)%1440
        h,m=t/60,t%60
        if h in f or m in f:
            print cnt
            exit()
        else:
            cnt+=1
    print cnt


n = int(input())

sum = 1

for i in range(1, n):
    sum = sum + 4 * i

print(sum)


def main(args):
    n=int(input())
    a=1
    for i in range(n):
        a+=i*4
    print(a)

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))


import math
n = int(input())
nums = input().split()
for i in range(n):
    nums[i] = int(nums[i])
nums.sort()
if (nums[n-1] > 25):
    print(nums[n-1] - 25)
else:
    print(0)


n = input()
l = map(int,raw_input().split())
l.sort()
if l[n-1]<=25:
    print 0
else:
    print l[n-1]-25


names = {
    1: "Washington",
    2: "Adams",
    3: "Jefferson",
    4: "Madison",
    5: "Monroe",
    6: "Adams",
    7: "Jackson",
    8: "Van Buren",
    9: "Harrison",
    10: "Tyler",
    11: "Polk",
    12: "Taylor",
    13: "Fillmore",
    14: "Pierce",
    15: "Buchanan",
    16: "Lincoln",
    17: "Johnson",
    18: "Grant",
    19: "Hayes",
    20: "Garfield",
    21: "Arthur",
    22: "Cleveland",
    23: "Harrison",
    24: "Cleveland",
    25: "McKinley",
    26: "Roosevelt",
    27: "Taft",
    28: "Wilson",
    29: "Harding",
    30: "Coolidge",
    31: "Hoover",
    32: "Roosevelt",
    33: "Truman",
    34: "Eisenhower",
    35: "Kennedy",
    36: "Johnson",
    37: "Nixon",
    38: "Ford",
    39: "Carter",
    40: "Reagan",
    41: "Bush",
    42: "Clinton",
    43: "Bush",
    44: "Obama"
    }
def main():
    n = int(input())
    print(names[n])
    return

main()


t, s, x = map(int, input().split())
print('YES' if x - t >= 0 and x - t != 1 and (x - t) % s <= 1 else 'NO')


t, s, x = map(int, raw_input().split())

if t == x:
	print 'YES'
else:
	if x==t:
		print 'YES'
	elif (x-t)%s in [0,1] and (x-t)>=0 and x!=t+1 :
		print 'YES'
	else:
		print 'NO'


iIn1=int(input())
iIn2=int(input())
iIn3=int(input())
iIn4=int(input())
print(((iIn1^iIn2)&(iIn3|iIn4))^((iIn2&iIn3)|(iIn1^iIn4)))


import itertools

dp = [[[0 for x in xrange(2)] for x in xrange(110)] for x in xrange(110)]
mod = 1000000007
data = map(int, raw_input().split())

n = data[0]
k = data[1]
d = data[2]
dp[0][0][0] = 1
ans = 0
for i in range(1, n + 1):
	for j in range(0, n + 1):
		for g in range(1, k + 1):
			if(g > j):
				break
			if(g >= d):
				dp[i][j][1] += dp[i - 1][j - g][0]
				dp[i][j][1] += dp[i - 1][j - g][1]
			else:
				dp[i][j][0] += dp[i - 1][j - g][0]
				dp[i][j][1] += dp[i - 1][j - g][1]

			dp[i][j][1] %= mod
			dp[i][j][0] %= mod
		ans += dp[i][n][1]
		ans %= mod
print ans


n, k, d = map(int, input().split())
k = n if n<k else k
cnt = [0 for _ in range(n+1)]
cn = [0 for _ in range(n+1)]
cnt[0] = cn[0] = 1
for i in range(1,n+1):
    for j in range(1,k+1):
        if i>=j:
            cnt[i] += cnt[i-j]
        if i>=j and j<d:
            cn[i] += cn[i-j]
s1 = cnt[n]
s2 = cn[n]
print((s1-s2)%1000000007)


# map(int, raw_input().split())

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

count = 0

if a <= b <= c:

    v1 = a

    v2 = b

    v3 = c

elif a <= c <= b:

    v1 = a

    v2 = c

    v3 = b

elif b <= a <= c:

    v1 = b

    v2 = a

    v3 = c

elif b <= c <= a:

    v1 = b

    v2 = c

    v3 = a

elif c <= a <= b:

    v1 = c

    v2 = a

    v3 = b

else:

    v1 = c

    v2 = b

    v3 = a

count = 0

if v3-v2 < d:

    count += d-(v3-v2)

if v2-v1 < d:

    count += d-(v2-v1)

print count


a, b, c, d = map(int, raw_input().split())
a, b, c = sorted((a, b, c,))
print max(d - (b - a), 0) + max(d - (c - b), 0)


h = []
v = []
for i in range(8):
    s = input()
    sl = [i for i in s]
    h.append(sl)
for i in range(8):
    x = []
    for j in range(8):
        x.append(h[j][i])
    v.append(x)
ans = 0

for i in h:
    x = list(set(i))
    if(len(x)==1 and x[0]=='B'):
        ans+=1
for i in v:
    x = list(set(i))
    if(len(x)==1 and x[0]=='B'):
        ans+=1
if(ans==16):
    print(8)
else:
    print(ans)


#7A - Kalevitch and Chess
#We get the costumer's requested board: 8 lines of input
# W - white
# B - black
order = []
for i in range(8):
    order.append(input())
#Firstly, we create a variable allBlack (reference to an all-black row) and
    #set it to be true
allBlack = True
#We instantiate the count of strokes as zero
count = 0
#Now, we iterate through the board, row by row
for row in order:
    #If we find a row with all 8 swuares marked as black ('B')
    if row == "BBBBBBBB":
        #We clearly add 1 stroke to the count
        count += 1
    else:
        #else, we say that it's not an all-black row
        allBlack = False
#Let's assume that all of the board's squares are marked with 'B'
#It doesn't matter if we have already iterated through rows,
#it's allowed to over-paint a square when rows of black cross columns of black
#The next loop is actually to find columns of black squares
for i in range(8):
    count += 1
    for ii in range(8):   #This is the second loop, because we have a board of 8x8
        #If the square is marked with 'W', we bring the count one step back
        if order[ii][i] == "W":
            count -= 1
            break
#The simpliest case: if we got the count result to be 16 black squares,
            #we will subsequently need 8 strokes
        #We print this directly, just so our program wouldn't bother
        #to count the obvious and return a bigger count
if count == 16:
    print("8")
    #Else, we print the number of counts previously computed
else:
    print(count)


import sys
range = xrange
input = raw_input

MOD = 998244353

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

if n == 2:
    print 0
    sys.exit()

k = n - 2
big = 3 * 10**5
choose = [0] * big
choose[k] = 1
for i in range(k + 1, big):
    choose[i] = choose[i - 1] * i * pow(i - k, MOD - 2, MOD) % MOD

s = 0
for maxval in range(n - 1, m + 1):
    s = (s + choose[maxval - 1] * pow(2, n - 3, MOD) * (n - 2)) % MOD
print s


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

if n == 2:
	print(0)
	exit()

mod = 998244353
ans = ((n-2) * pow(2, n-3, mod)) % mod
# print(ans)
for i in range(m-n+2, m+1):
	ans = (ans * i) % mod
# print(ans)
fact = 1
for i in range(2, n):
	fact = (fact*i) % mod

fact = pow(fact, mod-2, mod)
ans = (ans * fact) % mod

print(ans)


n,m,z = map(int,raw_input().split())
def lcm(x, y):
   if x > y:
       z = x
   else:
       z = y

   while(True):
       if((z % x == 0) and (z % y == 0)):
           lcm = z
           break
       z += 1

   return lcm
print (int(z/lcm(n,m)))


n, m, z = map(int, input().split())
c = [int(i) for i in range(n, z+1, n)]
a = [int(i) for i in range(m, z+1, m)]
t = 0
for i in c:
    if i in a:
        t += 1
print(t)


n = int(input())
for i in range(int(n**0.5),0,-1):
	if n % i == 0:
		r = i
		break
print(r,n//r)


n = int(input())

def getFactors(x):

    factors = []
    for i in range(1, int(n**0.5) + 1):
       if x % i == 0:
           factors.append(i)

    return factors

f = getFactors(n)
b = int( n // f[-1])
a = int( n // b)
print( a, b)


# -*- coding: cp1251 -*-
k=[int(j) for j in raw_input("").split()]

n =k[0]  #1
m =k[1]  #2

i1 =k[2]  #1
j1 =k[3]  #2

a =k[4]  #1  вверх вниз  |
b =k[5]  #2  влево вправо  <= =>

# oops! нужно прооверить, находится ли конфета сразу в нужной позиции))
if (j1==1 and i1 ==1) or (i1==n and j1==1) or (i1==1 and j1==m) or (i1==n and j1==m):
    print("0")

else:
    # неявный баг: поле по горизонтали или вертикали должно быть больше на 1, чем шаг
    # во избежание такого

    if n<=a or m<=b:
        print("Poor Inna and pony!")
    else:

        # проверка возможности дойти до каждой вершины (их 4) без учета корректности
        c=[0]*4

        # 1,1
        if (i1-1)%a ==0 and (j1-1)%b ==0:
           if (abs(i1-1)//a + abs(j1-1)//b)%2 == 0:
                c[0]=max(abs(i1-1)//a, abs(j1-1)//b)

        # n,1  leviy nizhniy
        if (i1-n)%a ==0 and (j1-1)%b ==0:
            if (abs(i1-n)//a + abs(j1-1)//b)%2 == 0:
                c[1]=max(abs(i1-n)//a, abs(j1-1)//b)

        # 1,m  leviy nizhniy
        if (i1-1)%a ==0 and (j1-m)%b ==0:
            if (abs(i1-1)//a + abs(j1-m)//b)%2 == 0:
                c[2]=max(abs(i1-1)//a, abs(j1-m)//b)

        # n,m  leviy nizhniy
        if (i1-n)%a ==0 and (j1-m)%b ==0:
            if (abs(i1-n)//a + abs(j1-m)//b)%2 == 0:
                c[3]=max(abs(i1-n)//a, abs(j1-m)//b)

        if c.count(0)==4:
            print("Poor Inna and pony!")
        else:
            c=set(c)
            c.discard(0)

            print(min(c))


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

path1=path2=path3=path4=10000000000

temp1 =temp2=temp3=temp4=0
if int((i-1)/a) == (i-1)/a and int((j-1)/b) == (j-1)/b:

    path1 = (i-1)/a
    path_1 = (j-1)/b
    # print(path1,path_1)
    if path1%2 == 0 and path_1%2 == 0 :
        path1 = max(path1,path_1)
        temp1 = 1
    elif path1%2 != 0 and path_1%2 !=0 :
        path1 = max(path1,path_1)
        temp1 = 1

    else:
        path1 = 100000000000
        temp1 = 0

if int((i-1)/a) == (i-1)/a and int((m-j)/b) == (m-j)/b:
    temp = 1
    path2 = (i-1)/a
    path_2 = (m-j)/b
    if path2%2 == 0 and path_2%2 ==0 :
        path2 = max(path2,path_2)
        temp2 = 1
    elif path2%2 != 0 and path_2%2 !=0 :
        path2 = max(path2,path_2)
        temp2 = 1

    else:
        path2 = 100000000000
        temp2 = 0

if int((n-i)/a) == (n-i)/a and int((j-1)/b) == (j-1)/b:
    temp = 1
    path3 = (n-i)/a
    path_3 = (j-1)/b
    if path3%2 == 0 and path_3%2 ==0 :
        path3 = max(path3,path_3)
        temp3 = 1

    elif path3%2 != 0 and path_3%2 !=0 :
        path3 = max(path3,path_3)
        temp3 = 1

    else:
        path3 = 10000000000000
        temp3 = 0

if int((n-i)/a) == (n-i)/a and int((m-j)/b) == (m-j)/b:
    temp = 1
    path4 = (n-i)/a
    path_4 = (m-j)/b
    if path4%2 == 0 and path_4%2 ==0 :
        path4 = max(path4,path_4)
        temp4 = 1
    elif path4%2 != 0 and path_4%2 !=0 :
        path4 = max(path4,path_4)
        temp4 = 1
    else:
        path4 = 1900000000000
        temp4 = 0

mini = min(path1,path2,path3,path4)
if ((i + a > n and i - a < 1) or (j+b > m and j-b < 1)) and mini!=0:
    print("Poor Inna and pony!")

elif temp1==0 and temp2==0 and temp3==0 and temp4==0:
    print("Poor Inna and pony!")
else:
    print(int(min(path1,path2,path3,path4)))


n,a,b = map(int, raw_input().split())
diff = abs(a-b)
if a>b:
	a ,b= b,a
l = [i for i in range(1,n+1)]
flag = True
k=n
rounds =1
while flag:

	k=len(l)
	if k==2:
		print "Final!"
		flag = False
		break
	rm = []
	tmp =[]
	#print l
	for i in range(0,k-1,2):
		c = l[i]
		d =l[i+1]
		if c == a and b==d:
			print rounds
			flag =False
		elif c == a:
			tmp.append(c)
		elif d == a:
			tmp.append(d)
		elif c == b:
			tmp.append(c)
		elif d == b:
			tmp.append(d)
		else:
			tmp.append(c)
	l = tmp[:]
	rounds += 1

	#print "hello"


c,a,b=input().split()
c=int(c)
level=0
while c!=1:
    level+=1
    c//=2
a=int(a)-1
b=int(b)-1
roundik=0
while a!=b:
    roundik+=1
    a//=2
    b//=2
if roundik==level:
    print("Final!")
else:
    print(roundik)


def exp(a,p,m):
    if(p==0):
        return 1
    elif(p==1):
        return a
    elif(p%2==0):
        x = exp(a,p>>1,m)
        return x*x
    else:
        return (a*exp(a,p-1,m))%m
def prog(s):
    l = len(s)
    x = int(s,2)%((10**9)+7)
    e = exp(2,l-1,(10**9)+7)
    return (x*e)%((10**9)+7)
s = raw_input()
print prog(s)


#!/usr/bin/env python

import sys

length = int(sys.stdin.readline())
line = sys.stdin.readline()
i = 0
res = 0
while i < length:
	d = [0] * 256
#	sys.stdout.write("char = " + line[i] + '\n')
	while i < length and line[i] >= 'a' and line[i] <= 'z':
		c = ord(line[i])
		d[c] += 1
		i += 1
	subres = 0
	for j in range(0, 256):
#		sys.stdout.write("d[" + str(j) + "] = " + str(d[j]) + '\n')
#		sys.stdout.write("d[j] = " + str(d[j]) + '\n')
		subres += min(d[j], 1)
#	sys.stdout.write("subres = " + str(subres) + '\n')
	res = max(subres, res)
	while i < length and line[i] >= 'A' and line[i] <= 'Z':
#		sys.stdout.write("capital char = " + line[i] + '\n')
		i += 1
sys.stdout.write(str(res))


import string
n=input()
s=raw_input()
maxi=-1
ans=[]
for i in range(n):
    t=s[i]
    if t in string.lowercase:
        if t not in ans:
            ans.append(s[i])
    else:
        maxi=max(maxi,len(ans))
        ans=[]
print max(maxi,len(ans))


def solve(v):
    if v < 3:
        return "NO"
    else:
        i = 0
        while 3*i <= v:
            if (v - 3*i) % 7 == 0:
                return "YES"
            i += 1
        return "NO"

n = int(raw_input())
for _ in range(n):
    v = int(raw_input())
    print solve(v)


def calculator(a):
    if a%3 == 0 or a%7 == 0:
        return "YES"
    while a>=3:
        a-=7
        if a>0 and a%3==0:
            return "YES"
    return "NO"
for i in range(int(input())):
    print(calculator(int(input())))


def pop():
    global head
    head-=1
    if head<0:
        return 'a'
    return q[head]

x = int(input())
x1 =x
st = input()
s = ''
q = []
head=0
for i in range(ord('a'),ord('a')+x1,1):
    flag = 0
    for j in st:
        if j == chr(i):
            flag = 1
    if flag == 0 and chr(i)!='?':
        q.append(chr(i))
        head+=1
flag1=1
if (len(st)%2  == 1):
    s=st[len(st)//2]
    if (s=="?"):
        s=pop()
    st=st[0:len(st)//2] + st[len(st)//2 +1 : len(st)]
for i in range((len(st))//2 - (len(st)+1)%2 ,-1,-1):
    if st[i] !='?':
        s=st[i]+s
        if (st[len(st)-1-i] =='?' or st[len(st)-1-i]== st[i]):
            s+=st[i]
        else:
            flag1=0
            break
    else:
        if (st[len(st)-1-i] == '?'):
            chs=pop()
            s+= chs
            s=chs+s
            if (x != 1):
                x-=1
        else:
            s=st[len(st)-1-i]+s
            s+=st[len(st)-1-i]

for i in range(ord('a'),ord('a')+x1,1):
    flag = 0
    for j in s:
        if j == chr(i):
            flag = 1
    if flag == 0:
        break
if flag==1 and flag1==1 :
    print(s)
else:
    print("IMPOSSIBLE")


k = int(input())
s = input()
ans = ['' for _ in range(len(s))]
r = set([chr(ord('a')+x) for x in range(k)]) - set(s)
r = list(r)
r.sort(reverse=True)

c = 0
for i in range(len(s)//2):
    if s[i] == '?' and s[-i - 1] == '?':
        c += 1
if len(s) % 2 == 1 and s[len(s)//2] == '?':
    c += 1

c -= len(r)
for i in range(len(s)//2):
    if s[i] == '?' and s[-i-1] == '?':
        if c > 0:
            ans[i] = 'a'
            c -= 1
        else:
            ans[i] = r.pop()
        ans[-i-1] = ans[i]
    elif s[i] == '?':
        ans[i] = ans[-i-1] = s[-i-1]
    elif s[-i-1] == '?':
        ans[-i-1] = ans[i] = s[i]
    else:
        if s[i] == s[-i-1]:
            ans[i] = ans[-i-1] = s[i]
        else:
            print('IMPOSSIBLE')
            break
else:
    if len(s) % 2 == 1:
        if s[len(s)//2] == '?':
            if r:
                ans[len(s)//2] = r.pop()
            else:
                ans[len(s)//2] = 'a'
        else:
            ans[len(s)//2] = s[len(s)//2]
    if r:
        print('IMPOSSIBLE')
    else:
        print(*ans, sep='')


n = int(input())
if(n%5==0):
   u = n/5
else:
   k = n/5
   u = k+1
print(int(u))


from sys import stdin

x = int(stdin.readline())
print(-(-x//5))


a,b,c = input(),input(),input()
ans=max(a*(b+c),a+b+c,(a+b)*c,a*b*c)
print ans


n1 = int(raw_input())
n2 = int(raw_input())
n3 = int(raw_input())
op1  = n1 + n2 + n3
op2 = n1*n2*n3
op3 = (n1 + n2)*n3
op4 = n1 * (n2 + n3)
op5 = n1 * n2 + n3
op6 = n1 + n2 * n3
lista = [op1, op2, op3, op4, op5, op6]
print max(lista)


n,m=map(int,input().split())
max=0
min=0
if (m==0 and n!=1) or m>9*n:
    print(-1,-1)
elif n==1 and m==0:
    print(0,0)
else:
    min=10**(n-1)
    for i in range(m-1):
        a=(i//9)
        min+=10**a
    max=0
    for i in range(m):
      b=(n-1-i//9)
      max+=10**b
    print(min,max)


s1=(raw_input("")).split(" ")
n=int(s1[0])
s=int(s1[1])
l=[]
sum=s
if sum<=0 or sum>(9*n):
    if n==1 and sum==0:
        print "0 0"
    else:
        print "-1 -1"

elif sum<=9*n:
    for i in range(n):
        if sum>=9:
            l.append("9")
            sum=sum-9
        elif sum<9 and sum>0:
            l.append(str(sum))
            sum=0
        elif sum==0:
            l.append("0")
    t=""
    t="".join(l)

    maxi=t
    j=1
    flag=1
    if t[n-1]=='0':
        j=0

        while t[n-1-j]=='0':
            flag=0
            j+=1
    mini=""
    if j==(n-1) and flag==0:
        for i in range(n):
            if i==0:
                mini=mini+str((s-1))
            elif i==n-1:
                mini=mini+"1"
            else:
                mini=mini+"0"
        q=''.join(reversed(mini))

        print  q,maxi

    elif flag==0:
        k=""
        for i in range(n):
            if i!=n-1-j and i!=n-1:
                k=k+t[i]
            elif i==n-1-j:
                k=k+"0"
            else:
                k=k+t[n-1-j]
        q=''.join(reversed(k))
        f=0
        if q[0]!="1":
            f=int(q[0])-1
        h=""
        for i in range(n):
            if i==0:
                h=h+"1"
            elif i==j:
                h=h+str(f)
            else:
                h=h+q[i]
        print h ,maxi

    else:
        for i in range(n):
            mini=mini+t[n-1-i]
        print mini ,maxi


from datetime import datetime
s = datetime.strptime(input(), '%H:%M')
t = datetime.strptime(input(), '%H:%M')

sec = (s - t).seconds
hours, rem = divmod(sec, 60**2)
minutes, sec = divmod(rem, 60)
print(str(hours).zfill(2) + ':' + str(minutes).zfill(2))


x, y, z = map(int, input().split())
a, b, c = map(int, input().split())
if x <= a and y <= a+b-x and z <= a+b+c-y-x:
	print('YES')
else:
	print("NO")


x, y, z =  map(int, input().split())

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

n = True
if x <= a and (x + y) <= (a + b) and (x + y + z) <= (a + b + c):
    n = False
if n:
    print('NO')
else:
    print("YES")


n=input()
a=map(int,raw_input().split())
k=0
while(1):
    n-=a[k%7]
    if n<=0:
        print k%7+1;break
    k+=1


n=input()
m=map(int,raw_input().split())
c = 0
while n > m[c]:
    n -= m[c]
    c = (c + 1)%7
print c + 1


n = int(input())
s = input().split(' ')
M = 0
for word in s:
    c = 0
    for char in word:
        if char.isupper():
            c += 1
    M = max(c, M)
print(M)


n=input()
text=raw_input().split()
maxd=0
l=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
for i in range(len(text)):
    cnt=0
    for j in range(len(text[i])):
        if text[i][j] in l:
            cnt+=1
        if cnt>maxd:
            maxd=cnt
print maxd


if __name__ == "__main__":
    a, b = map(int, raw_input().split())
    c, d = map(int, raw_input().split())

    res = None
    for y in range(1000):
        if b > d:
            if ((b - d) + y * a) % c == 0:
                res = b + y * a
                break
        else:
            if ((d - b) + y * c) % a == 0:
                res = d + y * c
                break

    if res:
        print res
    else:
        print -1


import sys

def solve():
    a, b = map(int, input().split())
    c, d = map(int, input().split())

    if b < d:
        a, c = c, a
        b, d = d, b

    for i in range(c):
        if (b - d + i*a) % c == 0:
            ans = b + i*a
            print(ans)
            return

    print(-1)

if __name__ == '__main__':
    solve()


n,k=map(int,input().split(' '))
a=list(map(int,input().split(' ')))
value=1000000000000
for i in (a):
    if k%i==0:
        b=int(k/i)
        if value>b:
            value=b
print(value)


nk=raw_input()
NK=[]
NK=nk.split(' ')
for i in range(len(NK)):
    NK[i]=int(NK[i])
K=NK[1]

ch=raw_input()
ch+=' '
n=len(ch)

H=0
ch1=''
i=0
while( i<n):
    if(ch[i] != ' '):
        ch1+=ch[i]
    else:
        S=int(ch1)
        if((K%S==0) and( S>H)):
            H=S
        ch1=''
    i+=1

print(K/H)


t, s, q = map(int, input().split())
r = 1
while t > s * q:
    s *= q
    r += 1
print(r)


t, s, q = map(int, input().split())
ans = 1
while s * q < t:
    ans += 1
    s *= q
print(ans)


n,s = raw_input().split()

n,s = int(n), int(s)
tot=0
x=raw_input().split()

m = int(max(i for i in x))

for i in x:
	tot+=int(i)

if(tot-m<=s):
	print "YES"
else:
	print "NO"


def solve(a, s):
    a.sort()
    return sum(a[:-1]) <= s

n, s = map(int, raw_input().split())
a = map(int, raw_input().split())
print 'YES' if solve(a, s) else 'NO'


n,m=map(int,raw_input().split(" "))
mini=n-(2*m)
s=0
maxi=0
for i in range(n+1):
	if ((i*(i-1))/2)>=m:
		maxi=n-i
		break

mini=max(0,mini)
print mini,maxi


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

idx = 0
while (idx * (idx - 1) // 2) < m:
    idx += 1

print(max(0, n - m * 2), max(0, n - idx))


from sys import stdin, stdout

def main():
    word = stdin.readline()
    if word.isupper() or word[0].islower() and word[1:].isupper():
        stdout.write(word.swapcase())
    elif len(word) == 2 and word.islower():
        stdout.write(word.upper())
    elif len(word) == 2 and word.isupper():
        stdout.write(word.lower())
    else:
        stdout.write(word)

if __name__ == "__main__":
    main()


a = raw_input()
if a[:1].islower() == True and a[1:].isupper():
    print a[:1].upper() + a[1:].lower()
elif a.isupper() == True:
    print a.lower()
elif len(a) == 1 and a.islower() == True:
    print a.upper()
else:
    print a


S=raw_input().split()
if(S[-1]=='?'):
	x=S[-2][-1].lower()
else:
	x=S[-1][-2].lower()
if(x=='a' or x=='e' or x=='i' or x=='o' or x=='u' or x=='y'):
	print "YES"
else:
	print "NO"


a=input().replace(' ','')
print('YES' if a.strip().lower()[-2] in 'aeiouy' else "NO")


a= raw_input().split()
b=list(set(a))
l=len(b)
if l>3:
    print "Alien"
elif l==1:
    print "Elephant"
elif l==2:
    i0=a.count(b[0])
    i1=a.count(b[1])
    if i0<4 and i1<4:
        print "Alien"
    elif i0==5 or i1==5:
        print "Bear"
    else:
        print "Elephant"
else:
    i0=a.count(b[0])
    i1=a.count(b[1])
    i2=a.count(b[2])
    if max(i0,i1,i2)!=4:
        print "Alien"
    else:
        print "Bear"


l = list(map(int, input().split(" ")))
s = list(set(l))
m = max(list(map(lambda x: l.count(x), s)))
if m < 4:
    print("Alien")
elif m == 5 or len(s) == 3:
    print("Bear")
else:
    print("Elephant")


m,n=map(int,input().split())
A=[input()for _ in range(m)]
S=int(A[0][0]=='*')
i,j=0,0
while i<m-1 or j<n-1:
 if j==n-1or i<m-1and A[i+1][j]=='*':i+=1
 else:j+=1
 S+=int(A[i][j]=='*')
print(S)


n,m=map(int,input().split())
a=[input()for i in range(n)]
l=[]
for i in range(n):
    for j in range(m):
        if a[i][j]=='*':
            l+=[(i,j)]
now=(0,0)
ans=int(now in l)
while True:
    mn=99
    mnt=now
    for i in l:
        if i!=now and i[0]>=now[0] and i[1]>=now[1] and mn>sum(i)-sum(now):
            mn=sum(i)-sum(now)
            mnt=i
    if mn==99:
        break
    now=mnt
    ans+=1
print(ans)


s = input()
out = 0
l = [4,7]
for ch in s:
    if ch == '4' or ch == '7':
        out +=1
print(['NO','YES'][any(out == i for i in l)])


inp=input()
count=0
count2=0
for i in inp:
    if i=='4':
        count=count+1
    elif i=='7':
        count2=count2+1

if (count==4 or count==7) and count2==0:
    print('YES')
elif (count2==4 or count2==7) and count==0:
    print('YES')
elif count+count2==4 or count+count2==7:
    print('YES')
else:
    print('NO')


def main():
    d, k, a, b, t = map(int, input().split())
    ans = 0
    dc = d//k
    dr = d % k
    if not dc:
        print(a*dr)
    else:
        way1 = dc*(k*a + t) + dr*a
        way2 = dc*(k*a + t) - t + dr*b
        way3 = k*a + (d-k)*b
        print(min(
            way1,
            way2,
            way3
        ))

if __name__ == '__main__':
    main()


import math
d, k, a, b, t = map(int, input().split())

distance = a * t /((b -a )*b) + t /b
time = 0
n = math.ceil((d-distance)/k)

# print(distance)
# print(n)
if (k>d):
    print(d*a)
    exit(0)
if (k<distance):
    time = k*a + (d-k)*b
    print(time)
    exit(0)
if (n*k >=d):
    time = a*d + d//k*t
    if (d%k==0):
        time -= t
else:
    time = n*k*a + (n-1)*t +(d - n*k)*b
print(time)


n = int(raw_input())

max = 2*(n/7) + min(n%7, 2)
min = 2*(n/7)
if n%7 == 6:
	min+=1

print min, max


n=input()
out=""
for i in n:
    if i=='7':
        out+="1"
    else:
        out+="0"
out=out[::-1]
p=0
for i in range(len(out)):
    if out[i]=='0':
        p+=2**i
    else:
        p+=2**(i+1)
print(p)


strno=input()
n=len(strno)
sum1=0
for i in range(1,n):
    sum1 += 1<<i
for i in range(n):
    if strno[i]=='7':
        sum1 += 1<<(n-i-1)
print(sum1+1)


def main():
    n, k = laie()
    l, ans, h = 0, 0, n * k

    while l <= h:
        m = (l + h) // 2
        if fun(m, n, k):
            ans, h = m, m - 1
        else:
            l = m + 1

    print(ans)

def fun(m, n, k):
    cnt = 0
    b = 1
    while m // b != 0:
        cnt += m // b
        b *= k
    return cnt >= n

from sys import *
import inspect
import re
from math import *
import threading
from collections import *
from pprint import pprint as pp
mod = 998244353
MAX = 10**5

def lai():
    return int(input())

def laie():
    return map(int, input().split())

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

def deb(p):
    for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
        m = re.search(r'\bdeb\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
        print('%s %d' % (m.group(1), p))

def vector(size, val=0):
    vec = [val for i in range(size)]
    return vec

def matrix(rowNum, colNum, val=0):
    mat = []
    for i in range(rowNum):
        collumn = [val for j in range(colNum)]
        mat.append(collumn)
    return mat

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()

if __name__ == '__main__':
    main()
    # dmain()


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

l=0

r=2*10**9

while l<r:

	m=(r+l)//2;s=0;t=1

	while m//t:s+=m//t;t*=k

	if s<n:l=m+1

	else:r=m

print(l)

# Made By Mostafa_Khaled


a = input()

p = a.count('4')
q = a.count('7')

if p > 0 and p >= q:
    print('4')
elif q > 0:
    print('7')
else:
    print('-1')


s=raw_input()
z=-1
if s.count('4'):
	z=4
if s.count('7')>s.count('4'):
	z=7
print z


def getDigitSum(n):
    digitsum = 0
    while n > 0:
        digitsum += n % 10
        n /= 10
    return digitsum

n = int(raw_input().strip())
l = max(0, n - 81)
count = 0
result = []
while l < n :
    digitsum = getDigitSum(l)
    if(digitsum + l == n):
        count += 1
        result.append(l)
    l += 1
print count
for i in result:
    print i


n = int (input())
k = 1
s = ''
b = 0
c = 0
d = []
while k<100:
    if n>k:
        a = n-k

        s = str(a)
        for i in range(len(s)):
                  b+=int(s[i])

        if a+b == n:
                    c+=1
                    d.append(a)
    k+=1
    s = ''
    b = 0
print(c)
d.sort()
print('\n'.join(str(v) for v in d))


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

from collections import defaultdict
from math import factorial as f
from fractions import gcd as g
from random import randint

n = int (raw_input ())
print (n - 2) ** 2


n = int(input())
print((n-2)*(n-2))

#seeing test test case
#3 = 1
#4 = 4
#5 = 9
#6 =16


import math
n = int(input())
r = [int(n) for n in input().split()]
b = [int(n) for n in input().split()]
d = sum(r) - sum(b) - 1
big = [r[i] for i in range(n) if r[i] > b[i]]
if d > 0:
    print('1')
elif len(big) == 0:
    print('-1')
else:
    score = sum(big) - d
    print(math.ceil(score / len(big)))


### A. Contest for Robots

n=int(input())
a=[int(x) for x in input().split()]
b=[int(y) for y in input().split()]
A=B=t=0

for i in range(n):
    if a[i]>b[i]:
        A+=1
    elif a[i]<b[i]:
        B+=1
if A==0:
    print(-1)
else:
    print(B//A+1)


s, v1, v2, t1, t2=map(int, input().split())
a=s*v1+2*t1
b=s*v2+2*t2
if(a<b):
    print("First")
if(a>b):
    print("Second")
if(a==b):
    print("Friendship")


import sys

def solve(s, v1, v2, t1, t2):
    time_1 = 2*t1 + v1 * s
    time_2 = 2*t2 + v2 * s

    if (time_1 < time_2):
        return "First"
    elif (time_2 < time_1):
        return "Second"
    else:
        return "Friendship"

if __name__ == "__main__":
    s, v1, v2, t1, t2 = map(int, sys.stdin.readline().split())
    print solve(s, v1, v2, t1, t2)


print 'YES' if sum(map(lambda x: 1 if x in ['H', 'Q', '9'] else 0, raw_input())) > 0 else 'NO'


# -*- coding: utf-8 -*-
"""
Created on Sun May 29 08:19:41 2016

@author: Dell_
"""

import sys
if False:
    input = open('program.txt', 'r')
else:
    input = sys.stdin

instructions = ['H', 'Q', '9']
p = input.readline().strip()
c = 0

for char in p:
    if char in instructions:
        c = 1
        break

if c == 1:
    print ("YES")
else:
    print ("NO")


from math import gcd
n = int(input())
lcm = 5 * 7 * 8 * 9
print(n // lcm)


string = input()
ss = string.count('-')
os = string.count('o')

if os == 0:
    print("YES")
elif ss%os == 0:
    print("YES")
else:
    print("NO")


a=raw_input()

p=0
l=0
for i in a:
    if i=="o":
        p+=1
    else:
        l+=1

if p==0 or not l%p:
    print "YES"
else:
    print "NO"


n,x,y=map(int,input().split())
num=(y*n)/100
num1=(y*n)//100
z=num-num1
if z==0 and x<=num:
    print(num1-x)
elif z!=0 and x<=num:
    print(num1+1-x)
elif x>num:
    print(0)


import sys, math

def readln():
    return sys.stdin.readline()

def parse(s, fun=int, sep=" "):
    return map(fun, s.split(sep))

def write(obj):
    sys.stdout.write(str(obj))

def writeln(obj):
    sys.stdout.write(str(obj) + "\n")

n, x, y = parse(readln())
writeln(max(0, int(math.ceil(y * n / 100.0 - x))))


import sys
input = lambda: sys.stdin.readline().strip()

n, k = map(int, input().split())
ls = list(map(int, input().split()))
ls.sort()
arr = []
for i in ls:
    while i!=0:
        arr.append(i)
        i//=2
    arr.append(0)
arr = list(set(arr))
arr.sort()
cnts = []
m = 10000000000000000000
for x in arr:
    Cnt = 0
    S = 0
    for i in ls:
        cnt = 0
        while i>x:
            i//=2
            cnt+=1
        if i==x and Cnt<k: S+=cnt; Cnt+=1
    if Cnt==k: m = min(m, S)
print(m)


n, m = map(int, input().split())
s = str(input())
a = [int(i) for i in s.split()]
b = [0] * 200001
c = [0] * 200001

a.sort()

for elem in a:
    b[elem] += 1
    count = 0
    while elem != 0 and b[elem // 2] < m:
        elem //= 2
        count += 1
        c[elem] += count
        b[elem] += 1

ans = 10000000000
for i in range(len(b)):
    if b[i] >= m:
        if ans > c[i]:
            ans = c[i]
print(ans)


import sys
# sys.setrecursionlimit(10**6)
from sys import stdin, stdout
import bisect            #c++ upperbound
import math
import heapq
def modinv(n,p):
    return pow(n,p-2,p)
def cin():
    return map(int,sin().split())
def ain():                           #takes array as input
    return list(map(int,sin().split()))
def sin():
    return input()
def inin():
    return int(input())
import math
def Divisors(n) :
    l = []
    for i in range(1, int(math.sqrt(n) + 1)) :
        if (n % i == 0) :
            if (n // i == i) :
                l.append(i)
            else :
                l.append(i)
                l.append(n//i)
    return l
"""*******************************************************"""
def main():
    n=inin()
    a=ain()
    x=n//2
    p=[]
    q=[]
    if(n%2==1):
        y=x+1
    else:
        y=x
    i=0
    j=+1
    f=-1
    ans=j=0
    pp=[]
    qq=[]
    for i in range(n):
        if(a[i]!=0):
            if(a[i]%2==1):
                y-=1
            else:
                x-=1
            if(f==-1 or a[i]%2^f==0):
                if(a[i]%2==1):
                    if(f==-1):
                        pp.append(j)
                    else:
                        p.append(j)
                    j=0
                    f=a[i]
                else:
                    if(f==-1):
                        qq.append(j)
                    else:
                        q.append(j)
                    j=0
            else:
                ans+=1
                j=0
            f=a[i]%2
        else:
            j+=1
    if(f%2==0):
        qq.append(j)
    else:
        pp.append(j)
    p.sort()
    q.sort()
    an=ans
    xx=x
    yy=y
    pp.sort()
    qq.sort()
    # print(x,y,p,q,pp,qq)
    for i in pp:
        y-=i
        if(i==0):
            continue
        if(y<0):
            ans+=1
    for i in qq:
        x-=i
        if(i==0):
            continue
        if(x<0):
            ans+=1
    for i in p:
        y-=i
        if(i==0):
            continue
        if(y<0):
            ans+=2
    for i in q:
        x-=i
        if(i==0):
            continue
        if(x<0):
            ans+=2
    x=xx
    y=yy
    for i in p:
        y-=i
        if(y<0):
            y+=i
            an+=2
    for i in q:
        x-=i
        if(x<0):
            x+=i
            an+=2
    # print(an,qq,x)
    for i in pp:
        y-=i
        if(y<0):
            y+=i
            an+=1
    for i in qq:
        x-=i
        if(x<0):
            x+=i
            an+=1
    if(ans==0 and n>1):
        ans=1
    print(min(an,ans))

######## Python 2 and 3 footer by Pajenegod and c1729

# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.

# So on cf, use PyPy2 for best string performance.

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0

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

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

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

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

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

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

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

# Cout implemented in Python
import sys
class ostream:
    def __lshift__(self,a):
        sys.stdout.write(str(a))
        return self
cout = ostream()
endl = '\n'

# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
    conv = ord if py2 else lambda x:x
    A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
    try:
        while True:
            if s[i] >= b'0' [0]:
                numb = 10 * numb + conv(s[i]) - 48
            elif s[i] == b'-' [0]: sign = -1
            elif s[i] != b'\r' [0]:
                A.append(sign*numb)
                numb = zero; sign = 1
            i += 1
    except:pass
    if s and s[-1] >= b'0' [0]:
        A.append(sign*numb)
    return A

if __name__== "__main__":
  main()


n,m=map(int,input().split())
arr=list(map(int,input().split()))
prefix=[0]*n
for i in range(n):
	prefix[i]=prefix[i-1]+arr[i]
brr=[]
for i in range(n):

	if prefix[i]<=m:
		print(0,end=" ")
	else:
		brr.sort()
		ct=0
		sm=prefix[i]
		# print(brr)
		for k in range(len(brr)-1,-1,-1):
			sm-=brr[k]
			ct+=1
			if sm<=m:
				print(ct,end=" ")
				break
	brr.append(arr[i])
print()


from bisect import insort

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

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

s = 0

heap = []

std = []

for i in students:

    if s + i > m:
        std = heap.copy()
        t = 0
        q = s
        while q + i > m:
            q -= std.pop()
            t += 1
        print(t, end=' ')
    else:
        print("0 ", end = '')
    s += i
    insort(heap, i)


# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.

ties = int(input())
scarves = int(input())
vest = int(input())
jackets = int(input())
first = int(input())
second = int(input())

if second > first:
    second_suits = min([scarves, vest, jackets]) * second
    first_suits = min([ties, jackets - min([scarves, vest, jackets])]) * first
else:
    first_suits = min([ties, jackets]) * first
    second_suits = min([scarves, vest, jackets - min([ties, jackets])]) * second

print(second_suits + first_suits)


ties=int(input())
scarves=int(input())
vests=int(input())
jackets=int(input())
e=int(input())
f=int(input())
ans=0
if f>e:
    ans+=min(scarves,vests,jackets)*f
    jackets-=min(scarves,vests,jackets)
    ans+=(min(ties,jackets)*e)
else:
    ans+=min(ties,jackets)*e
    jackets-=min(ties,jackets)
    ans+=min(scarves,vests,jackets)*f
print(ans)


from fractions import gcd
t,w,b = [int(r) for r in raw_input().split()]

ans = min(w,b)
lcm = w*b/gcd(w,b)
ans = ans*(t/lcm +1)
ans -= 1
last_num = t/lcm * lcm
ans -= max(0,last_num+min(w,b)-1-t)
den = t
print str(ans/gcd(ans,den))+"/"+str(den/gcd(ans,den))

1,2,12,13,14,24,25


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

#-------------------------code---------------------------#
# vsInput()

t,w,b=value()
a,b=sorted((w,b))
lcm=(a*b)//gcd(a,b)

sections=t//lcm

ans=sections*(a)
ans+=min(a-1,t%lcm)

# print(ans,t%lcm)
ans=Fraction(ans,t)

print(ans.numerator,'/',ans.denominator,sep="")

#  BruteForce
# for i in range(1,t+1):
#     print(i,i%a==i%b)


import functools
import logging
import os
import sys
import time

logger = logging.getLogger()
reader = sys.stdin
is_judge = os.getenv("ONLINE_JUDGE") is not None

def timeit(func):
    @functools.wraps(func)
    def timed(*args, **kwargs):
        if is_judge:
            rv = func(*args, **kwargs)
        else:
            ts = time.time()
            rv = func(*args, **kwargs)
            te = time.time()

            logger.debug("performance %r %2.2fms", func.__name__, (te - ts) * 1000)
        return rv
    return timed

# ----------------------
# -     /SOLUTION      -
# ----------------------

@timeit
def contains_subsequence(arr, seq):
    seq_len = len(seq)

    # Empty sequence
    if seq_len == 0:
        return True

    i = 0
    for item in arr:
        if item == seq[i]:
            i += 1
            if i == seq_len:
                break

    return i == seq_len

@timeit
def main():
    # while line := reader.readline():
    line = reader.readline()
    if contains_subsequence(line, "hello"):
        print("YES")
    else:
        print("NO")

# ----------------------
# -     \SOLUTION      -
# ----------------------

def setup():
    global logger, reader

    if is_judge:
        logger.setLevel(logging.WARNING)
    else:
        # Format logger
        handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter("{asctime}s - {message}", style='{')
        handler.setFormatter(formatter)

        logger.addHandler(handler)
        logger.setLevel(logging.DEBUG)

        # Stdin from file
        reader = open("input.txt")

if __name__ == '__main__':
    line = input()
    if contains_subsequence(line, "hello"):
        print("YES")
    else:
        print("NO")
    # setup()
    # try:
    #     main()
    # except KeyboardInterrupt:
    #     logger.debug("KeyboardInterrupt")
    # except IOError as e:
    #     logger.error(f"I/O error({e.errno}): {e.strerror}")


import math
n=int(input())
x=n
f=1
a=[x]
for i in range(2,int(math.sqrt(n))+1):
    while n%i==0:
        a.append(n//i)
        n=n//i

if a[-1]!=1:
    a.append(1)
for i in range(len(a)-1):
    print(a[i],end=' ')
print(a[-1])


n = int(raw_input())
i = 2
while i*i <= n:
	if n%i == 0:
		print n,
		n /= i
	else: i += 1
if n != 1:
	print n,
print 1


import math
r,x1,y1,x2,y2=[int(x) for x in input().split()]
ans=(math.sqrt((x2-x1)**2+(y2-y1)**2))/(2*r)
ans=int(math.ceil(ans))
print(ans)


r,x,y,z,t = map(int, raw_input().strip().split())
d = complex(z-x, t-y)
st = int(abs(d))
if d.real*d.real + d.imag*d.imag == st*st and st % (2*r) == 0:
    print st/(2*r)
else:
    s = abs(d)/(2*r)
    st = int(s)
    print st + 1


import math
from collections import defaultdict

mp = defaultdict(int)

def primeFactor(a):
    i = 2
    while i * i <= a:
        while a % i == 0:
            mp[i] += 1
            a //= i
        i += 1
    if a > 1:
        mp[a] += 1

def trailingZero(a, n):
    ans = 0
    while n > 0:
        ans += n // a
        n //= a
    return ans

n, b = map(int, input().split())
ans = int(1e50)
primeFactor(b)
for it in mp:
    first = it
    second = mp[it]
    temp = trailingZero(first, n)
    ans = min(ans, temp // second)
print(ans)


import decimal,math
# from decimal import Decimal as co
from collections import Counter,defaultdict
from fractions import gcd
from bisect import bisect_right,bisect_left
decimal.getcontext().prec = 10
def primeFactors(n):
	d=Counter()
	while n % 2 == 0:
		d[2]+=1
		n = n / 2

	for i in range(3,int(math.sqrt(n))+1,2):

		while n % i== 0:
			d[i]+=1
			n = n / i
	if n > 2:
		d[n]+=1
	return d

n,b=map(int,raw_input().split())
d=primeFactors(b)
mn=10**21
for i in d:
	tt=n
	power=i
	ans=0
	while tt/power:
		ans+=(tt/power)
		power*=i
	mn=min(mn,ans/d[i])
print mn

# def findPowerOfP(n,p):
# 	count=0
# 	r=p
# 	while(r<=n):
# 		count+=(n/r)
# 		r=r*p
# 	return count
# a=[]
# n,b = map(int,raw_input().split())
# pp =  primeFactors(b)
# print pp
# ans= 10**20
# for i in pp:
# 	ans=min(ans,findPowerOfP(n,i)/pp[i])
# print ans


import itertools
import sys

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

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

def rln(n):
    l = [None] * n
    for i in range(n):
        l[i] = int(rl())
    return l

def solve(t):
    for e in t:
        if e[0] + e[1] == e[2] + e[3] or e[0] == e[1] + e[2] + e[3]:
            return True
    return False

if __name__ == '__main__':
    tab = rn()
    t = itertools.permutations(tab)
    print('YES' if solve(t) else 'NO')


a, b = raw_input().split()

if a == b:
    print(a)
else:
    print(1)


import math
a, b = map(int,input().split())
if a == b:
	print(a)
else:
	print(1)


import math

def main():
    x = int(input())
    val = 1
    for i in range(2,x+1):
        val *= i
        val %= (10**9)+7
        # print(val)
    val -= 2**(x-1)
    val %= (10**9)+7
    print(val)

main()


n = int(input())
ans = 1
mod = 10**9+7
temp = 0.5
for i in range(n):
    ans = (ans*(i+1))%mod
    temp = (temp*2)%mod
print((ans-int(temp))%mod)


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


s = input()
if s%2==0:
    print s/2
else:
    print s/2 - s


k=int(input())
n=int(k**.1)
m=n**10
r=''
for c in'codeforces':l=n+(m<k);r+=c*l;m=m//n*l
print(r)


'''input
1
'''

from bisect import bisect_right as bl
from random import randint as R
RI = lambda : [int(_x) for _x in raw_input().split()]

n = input()

c = [1]*10

def pro(l):
	p=1
	for i in l:
		p*=i
	return p

cur = 0
while pro(c)<n:
	c[cur]+=1
	cur = (cur+1)%10
ans = ""
e=0
for i in "codeforces":
	ans+=c[e]*i
	e+=1
print ans


def main():
    a = map(int, raw_input().split(' '))
    s = sum(a)
    for i in range(6):
        for j in range(i + 1, 6):
            for k in range(j + 1, 6):
                res1 = a[i] + a[j] + a[k]
                if res1 == s - res1:
                    print 'YES'
                    return
    print 'NO'
    return
main()


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

def dooable(s):
    import itertools
    for p in itertools.permutations(s):
        if sum(p[:3]) == sum(p[3:]):
            return True
    return False
print ["NO", "YES"][dooable(s)]


from collections import defaultdict

t = int(input())
for _ in range(t):
    n, k, d = [int(x) for x in input().split()]
    a = [int(x) for x in input().split()]

    s = set(a[:d])
    dd = defaultdict(int)
    for i in a[:d]:
        dd[i] += 1
    mn = len(s)
    for i in range(n - d):
        #print(i, a[i], a[i+d], s)
        dd[a[i]] -= 1
        dd[a[i+d]] += 1
        s.add(a[i+d])
        if dd[a[i]] <= 0:
            dd[a[i]] = 0
            s.remove(a[i])
        m = len(s)
        #print(s, len(s))
        if m < mn:
            mn = m
    print(mn)


def solve():
    n, k, d = map(int, input().split())
    a = [int(i) for i in input().split()]
    min = 100
    q = 0
    for i in range(n - d + 1):
        temp = len(set(a[i:i + d]))
        if temp == 1:
            q += 1
        else:
            if temp < min:
                min = temp
    if n == d:
        min = len(set(a))
    print(1 if q > 0 else min)

def main():
    t = int(input())
    for z in range(t):
        solve()

main()


arr1 = raw_input().split(" ")
arr2 = raw_input().split(" ")
n = int(raw_input())
for i in range(len(arr1)):
    arr1[i] = int(arr1[i])
    arr2[i] = int(arr2[i])

if sum(arr1)!= 0:
    n -= (sum(arr1)-1)/5+1
if sum(arr2)!= 0:
    n -= (sum(arr2)-1)/10+1
if n >= 0:
    print "YES"
else:
    print "NO"


f = lambda: map(int, raw_input().split())
a = (sum(f()) + 4)/5
b = (sum(f()) + 9)/10
n = int(raw_input())
print ['NO', 'YES'][a+b <= n]


k, s = 1, input()

for i in range(len(s)-1):
    if s[i] != s[i+1]:
        k = 0
    elif k >= 6:
        break
    k += 1

print("NO" if k < 6 else "YES")


string1="1111111"
string2="0000000"
string3=input()
if string1 in string3 or string2 in string3:
    print("YES")

else:
    print("NO")


n,k=map(int,input().split())
a=[0]*k
for i in range(k):
    if n%k==0:
        exit(print('Yes'))
    if a[n%k]!=1:
        a[n%k]=1
        n+=n%k
    else:
        exit(print('No'))
print('Yes')


#!/usr/bin/env python

(a,m) = map(int, raw_input().split())
a = a % m

found = [False for i in xrange(m)]

while not (found[a]) and (a != 0):
  found[a] = True
  a = (a + a) % m

if a == 0:
  print "Yes"
else:
  print "No"


from sys import stdin,stdout
y,bl=map(int,stdin.readline().split())
a,b,c=map(int,stdin.readline().split())
yr=a*2+b
br=b*1+c*3
c=0
if yr >= y:
    c+=yr-y
if br > bl:
    c+=br-bl
stdout.write(str(c))


inp = input().split(' ')
a = int(inp[0])
b = int(inp[1])

inp = input().split(' ')
x = int(inp[0])
y = int(inp[1])
z = int(inp[2])

foo = (2*x + y) - a
bar = (3*z + y) - b

out = 0
if foo > 0:
    out += foo
if bar > 0:
    out += bar
print(out)


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

x = a+b-c
y = -a+b+c
z = a-b+c

works = True
for i in [x, y, z]:
  if i%2 != 0 or i < 0:
    works = False

if works:
  print x/2, y/2, z/2
else:
  print 'Impossible'


a,b,c=raw_input().split()
a=int(a)
b=int(b)
c=int(c)
x=(a+b-c)/2
y=(b+c-a)/2
z=(a+c-b)/2
if x<0 or y<0 or z<0:
    print "Impossible"
elif (x==0 and y==0) or(x==0 and z==0) or (y==0 and z==0):
    print "Impossible"
elif x==0 and y==0 and z==0:
    print "Impossible"
elif (a+b-c)%2!=0 and (a+c-b)%2!=0 and (b+c-a)%2!=0:
    print "Impossible"
else:
    print x,y,z


a = int(raw_input())
x = int((2*a+1)**.5)
a -= (x*(x+1)/2)
if a==0:
	print(x)
elif a>0:
	print(a)
else:
	print(x+a)


n = int(input())
n -= 1
st = 1

while n-st >= 0:
    n -= st
    st += 1

print(n+1)


input()
c = "".join(input().split()).strip('0')

if c.count('1') <= 1:
    print(c.count('1'))
else:
    print(eval("*".join([str(len(t)+1) for t in c.strip('1').split('1')])))


num = int(raw_input())
lista = map(int, raw_input().split())

resp = 1
um = False
cont = 0

for i in lista:
    if um: cont += 1

    if i == 1 and um:
        resp *= cont
        cont = 0

    if i == 1:
        um = True

if not um: resp = 0
print resp


k2, k3, k5, k6 = map(int, raw_input().split())

A = min(k2, k5, k6)
B = min(k3, k2 - A)

print 256 * A + 32 * B


a,b,c,d=map(int,input().split())
count=0
counter=0
m=min(a,min(c,d))
n=min(a-m,b)
count=n*32
counter=m*256
print(count+counter)


def sgn(a):
    if a>0:
        return 0
    elif a==0:
        return 1
    else:
        return 2
x,y,z=map(int,input().split())
M=sgn(x-y+z)
m=sgn(x-y-z)
if M!=m:
    print("?")
else:
    print(["+","0","-"][M])


#!/usr/bin/env pypy
from __future__ import division, print_function

import os
import sys
from __builtin__ import xrange as range
from cStringIO import StringIO
from future_builtins import ascii, filter, hex, map, oct, zip
from io import IOBase

import __pypy__

def main():
    x, y, z = map(int, input().split())
    if x == y and z == 0:
        print('0')
    elif x - y - z > 0:
        print('+')
    elif -y + x + z < 0:
        print('-')
    else:
        print('?')

# region fastio

BUFSIZE = 8192

class FastI(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = StringIO()
        self.newlines = 0

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

class FastO(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = __pypy__.builders.StringBuilder()
        self.write = lambda s: self._buffer.append(s)

    def flush(self):
        os.write(self._fd, self._buffer.build())
        self._buffer = __pypy__.builders.StringBuilder()

def print(*args, **kwargs):
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

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

# endregion

if __name__ == "__main__":
    main()


import sys
n=int(sys.stdin.readline())
a=int(sys.stdin.readline())
g=[]
t=a
for i in range(n):
  if int(t%10)!=0:
    g=g+[int(t%10)]
  t=int(t/10)
b=[]
def primes(n):
    primfac = []
    d = 2
    while d*d <= n:
        while (n % d) == 0:
            primfac.append(d)  # supposing you want multiple factors repeated
            n //= d
        d += 1
    if n > 1:
       primfac.append(n)
    return primfac

for i in g:
 if i!=1:
  gg = 2
  for j in range(2,i+1):
    if gg<max(primes(j)):
      gg=max(primes(j))
  b=b+[gg]
  if i==9: b=b+[2,3,3]
  else:
   for k in range(gg+1,i+1):
     if k==6: b=b+[3]
     else:
      b=b+primes(k)
print(int(''.join(map(str, reversed(sorted(b))))))


n=input()
a=raw_input()
lis=[]
for i in a:
    if i=='9':
        lis.append(7)
        lis.append(3)
        lis.append(3)
        lis.append(2)
    if i=='8':
        lis.append(2)
        lis.append(2)
        lis.append(2)
        lis.append(7)
    if i=='7':
        lis.append(7)
    if i=='6':
        lis.append(3)
        lis.append(5)
    if i=='5':
        lis.append(5)
    if i=='4':
        lis.append(2)
        lis.append(2)
        lis.append(3)
    if i=='3':
        lis.append(3)
    if i=='2':
        lis.append(2)
lis.sort(reverse=True)
for i in range(len(lis)):
    lis[i]=str(lis[i])
print ''.join(lis)


import math
def prime(n):
    ok= True
    for i in range(2, int(math.sqrt(n))):
        if(n%i==0):
            ok = False
            break
    if(ok):
        return True
    else:
        return False
def fact(a,b):
    ans = 1
    for i in range(a, b+1):
        ans*= i
    return str(ans)-1
def comb(n, c):
    return fact(n)//(fact(n-c)*c)

a,b = map(int, input().split())
def done(c,d):
    if(c==0 or d==0):
        return True
    else:
        return False
while(not done(a,b)):
    if(a >= 2*b):
        a = int(a%(2*b))
    else:
        if(b >= 2*a):
            b = int(b%(2*a))
        else:
            break
print(a,b)


a,b = map(int,input().split())
while(a!=0 and b!=0):
    if(a>=2*b):
        a = a%(2*b)
    elif(b>=2*a):
        b = b%(2*a)
    else:
        break
print(a,b)


n = int(input())
lis = list(map(int,input().split()))
hun = 0
thun = 0
for i in lis:
    if i == 100:
        hun+=1
    else:
        thun+=1

# print (hun,thun)
if thun == 0 or hun == 0:
    if thun == 0:
        if hun%2 == 0:
            print ('YES')
        else:
            print ('NO')
    else:
        if thun%2 == 0:
            print ('YES')
        else:
            print ('NO')
elif (200*thun+100*hun)%200 == 0:
    print ('YES')
else:
    print ('NO')


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
#vsInput()

n=Int()
a=array()
c1=a.count(100)
c2=a.count(200)
if(c1%2==0 and c2%2==0):
    print("YES")
elif(c2%2==1 and c1%2==0 and c1>=2):
    print("YES")
else:
    print("NO")


n=int(input())
d,c,m,i=0,1,1,1
while c<=n:
    d+=1
    i+=1
    m+=i
    c+=m
print(d)


value = int(input())
def rec(i,x):
    if sum(l) >= value:
        return x
    if value == 1:
    	return 1
    i = i + x
    l.append(i)
    rec(i,x+1)
l = []
rec(1,2)
print(1 if value == 1 else len(l))


N, M = map(int, input().split())
ans = -1
min = N // 2
if N % 2 != 0:
	min += 1
for i in range(min, N+1):
	if i % M == 0:
		ans = i
		break
print(ans)


def f(l):
    n,m = l
    ms  = (n+1)//2
    ds  = ((ms+m-1)//m)*m
    return -1 if ds>n else ds

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


n, a = map(int, input().split(" "))
t = list(map(int, input().split(" ")))
s = sum(t)
b = a - 1
l = b-1
r = b+1
while l >=0 and r <n:
    s -= (t[l] + t[r])%2
    l -= 1
    r += 1
print(s)


n, a = map(int, input().split())
c = list(map(int, input().split()))
ans = c[a - 1]
for i in range(1, min(a, abs(n - a) + 1)):
    ans += (c[a - 1 - i]&c[a - 1 + i]) * 2
if a == (n + 1) / 2:
    print(ans)
elif a < (n + 1) / 2:
    ans += sum(c[2 * a - 1:])
    print(ans)
else:
    ans += sum(c[:2 * a - n - 1])
    print(ans)


__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__doc__ = ''
__version__ = '1.0'

def main() -> int:
    (n, d) = map(int, input().split())
    costs = sorted([int(word) for word in input().split()])
    m = int(input())
    profit = 0

    if m <= n:
        profit = sum(costs[:m])
    else:
        profit = sum(costs) - (m - n) * d

    print(profit)
    return 0

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


n, d = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
m = int(input())
print(sum(arr[:m]) if m <= n else sum(arr) - d * (m-n))


# print("Input n")
n = int(input())

threepower = 27
sevenpower = 7
count = 1
while (count < n):
    threepower = (threepower * 27) % (1000000000+7)
    sevenpower = (sevenpower * 7) % (1000000000+7)
    count += 1
answer = threepower - sevenpower
if answer < 0:
    answer += 1000000000+7
print(answer)


from sys import stdin,stdout

def main():
	string=stdin.readline()
	sum=0

	for i in range (len(string)-1):
		if i==0:
			p=ord(string[0])-97
			if p>13:
				sum+=(26-p)
			else:
				sum+=p
		else:
			p=abs(ord(string[i])-ord(string[i-1]))
			if p>13:
				sum+=26-p
			else:
				sum+=p

	print(sum)

if __name__ == '__main__':
	main()


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

from collections import defaultdict
from math import factorial as f
from fractions import gcd as g

s = raw_input ()
ret, start = 0, 0
for i in s:
    x = ord (i) - ord ('a')
    y = min ((start - x) % 26, (x - start) % 26)
    ret += y
    start = x
print ret


def f(x):
    for i in xrange(1, 8):
        if 7 ** i >= x:
            return i
    return 8

def g(x, l):
    ret = []
    for i in range(l):
        ret.append(x % 7)
        x = x / 7
    return set(ret)

(n, m) = map(int, raw_input().split())
(l1, l2) = (f(n), f(m))

if l1 + l2 > 7:
    print 0
    exit()

s1 = [g(i, l1) for i in xrange(0, n)]
s2 = [g(j, l2) for j in xrange(0, m)]
ans = len([1 for u in s1 for v in s2 if len(u.union(v)) == l1 + l2])

print ans