from sys import stdout

class Mock:
    def __init__(self, cap, a):
        self.a, self.cap = a, cap
        self.n, self.q = len(a), []

    def ask(self, i):
        result = self.a[i] in self.q
        self.q.append(self.a[i])
        if len(self.q) > self.cap:
            self.q = self.q[1:]
        return result

    def reset(self):
        self.q = []

    def out(self, result):
        print('!', result)

class IO:
    def __init__(self):
        self.n, self.cap = map(int, input().split())

    def ask(self, i):
        print('?', i + 1)
        stdout.flush()
        return input() == 'Y'

    def reset(self):
        print('R')
        stdout.flush()

    def out(self, result):
        print('!', result)

def solve(io):
    n, cap = io.n, io.cap
    size = cap + 1 >> 1
    count = n // size
    removed = [False] * n
    for d in range(1, count):
      for r in range(min(d, count - d)):
        for i in range(r, count, d):
          for j in range(i * size, (i + 1) * size):
            if not removed[j] and io.ask(j):
              removed[j] = True
      io.reset()
    return removed.count(False)

# io = Mock(2, [1, 4, 1, 3])
# io.out(solve(io))

# io = Mock(8, [1, 2, 3, 4, 5, 6, 6, 6])
# io.out(solve(io))

io = IO()
io.out(solve(io))


a = list(map(int, input().split()))
ans = 0
for i in range(14):
    x, b, tru, dop = a[i], a[:], a[i] // 14, a[i] % 14
    b[i] = 0
    for j in range(i + 1, 14):
        b[j] += tru
        if dop > 0:
            b[j] += 1
            dop -= 1
    for j in range(0, i + 1):
        b[j] += tru
        if dop > 0:
            b[j] += 1
            dop -= 1
    cnt = 0
    for j in range(14):
        cnt += b[j] if b[j]%2==0 else 0
    ans = max(ans, cnt)
print(ans)


numberofboxes = int(raw_input())
boxes = list(map(int,raw_input().split(" ")))

boxes.sort()

stacklist = [0]

for i in boxes:
    for j in range(len(stacklist)):
        if i >= stacklist[j]:
            stacklist[j] += 1
            break
    else:
        stacklist.append(1)

print len(stacklist)


teams={}
for _ in range(5):
    t1,t2,scores=raw_input().split()
    s1,s2=map(int,scores.split(':'))
    teams[t1]=teams.get(t1) or [0,0,0,t1,0]
    teams[t2]=teams.get(t2) or [0,0,0,t2,0]
    if s1>s2:
        teams[t1][0]-=3
    elif s1<s2:
        teams[t2][0]-=3
    else:
        teams[t1][0]-=1
        teams[t2][0]-=1
    teams[t1][1]-=s1-s2
    teams[t2][1]-=s2-s1
    teams[t1][2]-=s1
    teams[t2][2]-=s2
    teams[t1][4]+=1
    teams[t2][4]+=1
oppo=[t[3] for t in teams.values() if t[3]!='BERLAND' and t[4]<3][0]
for xy in range(1,123):
    for y in range(0,123):
        t1,t2=teams['BERLAND'][:],teams[oppo][:]
        t1[0]-=3
        t1[1]-=xy
        t2[1]+=xy
        t1[2]-=y+xy
        t2[2]-=y
        t1[4]+=1
        t2[4]+=1
        tms=[t for t in teams.values() if t[4]>2]+[t1,t2]
        tms.sort()
        if tms[0][3]=='BERLAND' or tms[1][3]=='BERLAND':
            print '%d:%d'%(y+xy,y)
            exit()
print 'IMPOSSIBLE'


t=[input(),input()]
def f(x):
  return int(str(x).replace('0',''))
r='NO'
if f(sum(t))==sum(map(f,t)): r='YES'
print r


n,m = map(int,raw_input().split())
if n>m:n,m = m,n
print n-1+(m-n),n


B = [0] * 601
n = int(input())
k = 0
A = list(map(int,input().split()))
for i in A:
    if i != 0 and B[i] == 0:
        B[i] = 1
        k += 1
print(k)


n=int(input())
if n%2==0:
    print(2**(n//2))
else:
    print(0)


from sys import *
from math import *

s = stdin.readline().strip()
ans = 1
now = 10
was = {}
was['A'] = False
was['B'] = False
was['C'] = False
was['D'] = False
was['E'] = False
was['F'] = False
was['G'] = False
was['H'] = False
was['I'] = False
was['J'] = False

if s[0] == '?':
  ans *= 9
if (ord(s[0]) >= ord('A')) and (ord(s[0]) <= ord('J')):
  ans *= 9
  was[s[0]] = True
  now = 9
cnt = 0
for i in range(1, len(s)):
  if s[i] == '?':
    cnt += 1
  if (ord(s[i]) >= ord('A')) and (ord(s[i]) <= ord('J')):
    if was[s[i]] == False:
      ans *= now
      now -= 1
    was[s[i]] = True
print(ans, end = "")
for i in range(cnt):
  print('0', end = "")
print()


n = int(raw_input ( ))
x = map(int,raw_input ( ).split ( ))
t = int(raw_input ( ))
x.sort ( )
maxi = []
for i in range(n):
    num = 0
    for j in range(i, n):
        if ( x[j] - x[i] > t ):
            break
        else:
            num += 1
    maxi.append ( num )
print sorted(maxi)[n-1]


n=int(input())
st=str()
for i in range(2,n):
    while(n%i==0):
        st+=str(i)
        n=n//i
print(st)


def main():
    import sys
    input = sys.stdin.readline

    N, mod = map(int, input().split())
    nmax = N + 1  # change here
    fac = [0] * (nmax + 1)
    fac[0] = 1
    fac[1] = 1
    for i in range(2, nmax):
        fac[i] = fac[i - 1] * i % mod

    ans = 0
    for k in range(1, N+1):
        ans = (ans + (((N-k+1) ** 2)%mod * (fac[N-k] * fac[k])%mod)%mod) % mod
    print(ans)

if __name__ == '__main__':
    main()


l, d, v, g, r = map(int, input().split())

t = d / v
c = 0

while t > g + r:
    t -= (g + r)
    c += 1

if t < g:
    print(l / v)

elif t <= (g + r):
    c += 1
    print(c * (g + r) + (l - d) / v)


a,b,c=map(int,input().split())
val=b
res=[val]
i=2
while(val<a*c):
    val=b*i
    res+=[val]
    i+=1
n=len(res)
l=0
h=n-1
ans=-1
#print(res)
while(l<=h):
    mid=l+(h-l)//2
    if(res[mid]+b*(c-1)<a*c):
        ans=mid
        l=mid+1
    else:
        h=mid-1
    #print(mid)
print(ans+1)


def solve(k, grid):
    seek = *range(2*k + 2), *range(4*k + 1, 2*k + 1, -1)
    flat = [seek[v] for v in grid[0] + grid[1][::-1] if v]

    m = {
        'L': 'l'*2*k + 'u' + 'r'*2*k + 'd',
        'R': 'u' + 'l'*2*k + 'd' + 'r'*2*k,
        'C': 'l'*k + 'u' + 'r'*k + 'd',
        'D': 'CC' + 'R'*(2*k + 1) + 'CC' + 'R'*(2*k + 2),
        'F': 'R'*(k - 1) + 'DD' + 'R'*(2*k + 1) + 'D' + 'L'*2*k + 'DD' + 'L'*k,
        'G': 'FF',
    }

    [(i, j)] = [(i, j) for i in range(2) for j in range(2*k + 1) if grid[i][j] == 0]
    st = 'r'*(2*k - j) + 'd'*(1 - i)

    for v in range(2, 4*k + 2):
        ct = flat.index(v)

        if ct >= 2:
            st += 'L'*(ct - 2) + 'GR'*(ct - 2) + 'G'
            flat = flat[ct - 1: ct + 1] + flat[:ct - 1] + flat[ct + 1:]

        if ct >= 1:
            st += 'G'
            flat = flat[1:3] + flat[:1] + flat[3:]

        st += 'L'
        flat = flat[1:] + flat[:1]

    if flat[0] == 1: return st, m

def main():
    def get_line():
        return [0 if x == 'E' else int(x) for x in input().split()]

    for cas in range(int(input())):
        res = solve(int(input()), [get_line() for i in range(2)])
        if res is None:
            print('SURGERY FAILED')
        else:
            print('SURGERY COMPLETE')
            st, m = res
            print(st)
            for shortcut in m.items(): print(*shortcut)
            print('DONE')

main()


b = int(input())
g = int(input())
n = int(input())
print(min(n, b, g, b + g - n) + 1)


a, b = map(int, raw_input().split())
print a if a == b else 2


import sys;range = xrange;input = raw_input;inp = [int(x) for x in sys.stdin.read().split()]; ii = 0;n = inp[ii]; ii += 1;coupl = [[] for _ in range(n)]
for _ in range(n - 1):u = inp[ii] - 1; ii += 1;v = inp[ii] - 1; ii += 1;coupl[u].append(v);coupl[v].append(u)
root = 0;bfs = [root]
for node in bfs:
    for nei in coupl[node]:
        del coupl[nei][coupl[nei].index(node)]
        bfs.append(nei)

counter = [0] * n
for node in reversed(bfs):
    counter[node] += 1
    for nei in coupl[node]:counter[node] += counter[nei]

nhalf = n // 2

for node in range(n):
    vals = [counter[nei] for nei in coupl[node]];vals.append(n - 1 - sum(vals))
    if max(vals) <= nhalf:break
root = node
for node in reversed(bfs):
    for nei in coupl[node]:coupl[nei].append(node)
found = [0] * n;depth = [0] * n;order = [];stack = [root]
while stack:
    node = stack.pop()
    if found[node]:continue
    found[node] = 1;order.append(node)

    for nei in coupl[node]:
        if not found[nei]:
            depth[nei] = depth[node] + 1
            stack.append(nei)
    stack += coupl[node]

ans = [-1] * n
for i in range(n):
    ans[order[i - nhalf]] = order[i]

print 2 * sum(depth)
print ' '.join(str(x + 1) for x in ans)


x = int(raw_input())

if x == 1:
    print 1
elif x == 2:
    print 3
elif x == 3:
    print 5
elif x == 4 or x == 5:
    print 3
elif x <=13:
    print 5
elif x <= 25:
    print 7
elif x <= 41:
    print 9
elif x <= 61:
    print 11
elif x <= 85:
    print 13
else:
    print 15


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

elapsed = 0

if s * (q - 1) + s >= t:
    elapsed = 1

else:
    elapsed += 1

    while (s + s*(q - 1)) < t:
        s += s*(q-1)

        elapsed += 1

print elapsed


n = int(input())
f = [0] * (n + 1)
p = [(0, 0, 0)] * (n + 1)
for i in range(1, n + 1):
	x, y = map(int, input().split())
	p[i] = (x, y, max(x, y))

p.sort(key=lambda x : (x[2], x[0] - x[1]))

def dis(a, b):
	return abs(a[0] - b[0]) + abs(a[1] - b[1])

lasi = lasj = 0
i = 1
while i <= n:
	j = i
	while j < n and p[j + 1][2] == p[i][2]:
		j += 1
	for k in {i, j}:
		f[i ^ j ^ k] = dis(p[i], p[j]) + min(f[l] + dis(p[l], p[k]) for l in {lasi, lasj})
	lasi, lasj = i, j
	i = j + 1

print(min(f[lasi], f[lasj]))


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

if a == c and b < d:
    print("Polycarp")
elif a == c and b > d:
    print("Vasiliy")
elif a < c and b == d:
    print("Polycarp")
elif a > c and b == d:
    print("Vasiliy")
elif a > c and b > d:
    print("Vasiliy")
elif a < c and b < d:
    print("Polycarp")
else:
    if a+b<=max(c, d):
        print("Polycarp")
    else:
        print("Vasiliy")


a=input()+input()
b=input()+input()
if ((a in ['ABCX', 'ABXC', 'XBAC', 'BXAC', 'BCAX', 'BCXA',
   'XCBA', 'CXBA', 'CABX', 'CAXB', 'XACB', 'AXCB']) == (b in ['ABCX', 'ABXC', 'XBAC', 'BXAC', 'BCAX', 'BCXA',
   'XCBA', 'CXBA', 'CABX', 'CAXB', 'XACB', 'AXCB'])):
    print("YES")
else:
    print("NO")


n = int(input().strip())
vals = [int(x) for x in (input().strip().split())]
term = vals[1]
d = vals[1]-vals[0]
ap = True
for x in range(2,n):
	next_term = vals[x]
	if (next_term-term != d):
		ap = False
	term = next_term

if ap:
	print(term+d)
else:
	print(term)


[h, n] = map(int, raw_input('').split(' '))

def size_of_tree(height):
    total = 0
    for i in xrange(height):
        total += pow(2, i)
    return total

def get_parent(nodes):
    if nodes % 2 == 0:
        return (nodes / 2)
    return ((nodes - 1) / 2) + 1

def get_parity(node_number, height):
    if height == 1:
        if node_number == 1:
            return 1
        else:
            return 2
    else:
        temp = (node_number - 1) % 4
        if temp == 0 or temp == 3:
            return 2
        return 1

total_visited = 0
height = h - 1
current = n
parent = get_parent(current)
parity = get_parity(current, height + 1)

while height >= 0:
    total_visited += 1
    if parity == 2:
        total_visited += size_of_tree(h - height)
    current = parent
    parent = get_parent(current)
    height -= 1
    parity = get_parity(current, height + 1)

print total_visited


"""
instagram : essipoortahmasb2018
telegram channel : essi_python
"""
s = [*map(int,input().split(":"))]
t = [*map(int,input().split(":"))]

if(s[1] + t[1] >= 60):
    flag = 1
    d = (s[1] + t[1] - 60)//2
else:
    d = (s[1] + t[1])//2
    flag = 0

h = s[0] + t[0] + flag

if h%2!=0:
        h//=2
        d+=30
else:
    h //= 2

if len(str(h))<2:
    print("0"+str(h)+":",end="")
else:
    print(str(h)+":",end="")
if len(str(d))<2:
    print("0"+str(d),end="")
else:
    print(str(d),end="")


n = int(input())

def Solve(n, Rot):

    for x in range(2**n):

        Sum = 0

        x = list(bin(x).replace("0b", ""))

        while(len(x) < n):

            x.insert(0, '0')

        for i in range(n):
            if x[i] == '0':
                Sum += Rot[i]
            else:
                Sum -= Rot[i]

        if Sum%360 == 0:
            return 'YES'

    return 'NO'

Rot = []

for i in range(n):
    Rot.append(int(input()))

print(Solve(n, Rot))


#!/usr/bin/python

from math import floor

m = int(raw_input())
l = [k**3.0 for k in xrange(2,180000)]

def check(num):
    return m > check2(num)

def check2(num):
    return sum(floor(num/l[i]) for i in xrange(int(num**(1.0/3))))

ma = 5 * 10**15
mi = int(4.8 * m)

while ma-mi > 1:
    mid = (ma+mi)/2
    if check(mid):
        mi = mid
    else:
        ma = mid

if check2(ma) == m:
    print ma
else:
    print -1


n=int(raw_input())
MOD=1000000007
a=map(int,raw_input().split())
twos=sum(a)-n
ones=n-twos
ans=0
x=ones/2
weirds=[1,1]
for i in xrange(2,x+3):
	weirds.append(weirds[-1]*(2*i-1))
nc2i=[1]
for i in xrange(1,x+3):
	nc2i.append(nc2i[-1]*(ones-2*i+1)*(ones-2*i+2)/(2*i-1)/(2*i))
for i in xrange(x+1):
	ans+=weirds[i]*nc2i[i]
	ans%=MOD
for i in xrange(twos):
	ans*=n-i
	ans%=MOD
print ans


n, m = map(int, input().split())
a = [int(i) for i in input().split()]
b = sorted([[a[i], i] for i in range(n)])
for i in range(m):
    l, r = map(int, input().split())
for i in range(n):
  a[b[i][1]] = str(i%2)
print(' '.join(a))


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

x = int(raw_input())
if x %2 == 0:
	print ((x/2)-1)
else:
	print x/2


s = input()
if s.count('1') != 0:
    if s[s.index('1'):].count('0') > 5:
        print('yes')
    else:
        print('no')
else:
    print('no')


from fractions import gcd
l,r=map(int,raw_input().split())
flag=0
if r-l==1:
    print -1
else:
    for i in range(l,r-1):
        for j in range(i+1,r):
            for k in range (j+1,r+1):
                if gcd(i,j)==1 and (gcd(j,k)==1 and gcd(i,k)!=1):
                    a=i
                    b=j
                    c=k
                    flag=1
                    break
    if flag==1:
        print a,b,c
    else:
        print -1


import sys
n = int(sys.stdin.readline())
if n == 0:
    print(0)
else:
    print((n + 1) // 2 if (n + 1) % 2 == 0 else n + 1)


n = int(input())
a = [0]+list(map(int, input().split()))+[1001]
ans = 0
cnt = 1

for i in range(1, n+2):
    if a[i]==a[i-1]+1:
        cnt += 1
        ans = max(ans, cnt-2)
    else:
        cnt = 1

print(ans)


n, m = map(int, input().split())
ans = 0
while n > 0 and m > 0:
    ans += n//m
    n, m = m, n % m
print(ans)


a,b=map(int,input().split())
l=input().split()
for i in range(b):
    l[i]=int(l[i])
l=sorted(l)
m=[]
for k in range(b-a+1):
    m.append(l[k+a-1]-l[k])
print(min(m))


a = input()
ticket = input()

def gold(s, l):
    if len(l) == 0:
        return True
    for i in range(len(l)):
        sum_i = sum([int(l[j]) for j in range(i+1)])
        if sum_i > s:
            return False
        elif sum_i == s:
            if sum([int(l[j]) for j in range(i+1, len(l))]) == 0:
                return True
            return gold(s, l[i+1:len(l)])
    return False

def task(l):
    for i in range(len(l)-1):
        f_i_sum = sum([int(l[j]) for j in range(i+1)])
        rest = l[i+1:len(l)]
        if gold(f_i_sum, rest):
            return True
    return False

if task(ticket):
    print("YES")
else:
    print("NO")


a,b=map(int,input().split())
sum=0
#print(count)
#print(sum)
for i in range(b,a+1,b):
    if(i<=a and 2*i>=a):
        sum=i
        break
if(a>=b):
    print(sum)
else:
    print(-1)


n = int(input())

def table(i, j):
    if i == 1 or j == 1:
        return 1
    return table(i - 1, j) + table(i,j - 1)

print(table(n,n))


import sys
n,k=map(int,input().split())
a=list(input())
if k==0:
  print(''.join(a))
  sys.exit()
if n==1:
  print(0)
  sys.exit()
if a[0]!='1':
  a[0]='1'
  k=k-1
i=1
while k>0 and i<n:
  if a[i]!='0':
    a[i]='0'
    k=k-1
    i+=1
  else:
    i+=1
print(''.join(a))


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

dif = max([a[i+1]-a[i] for i in range(n-1)])
print max(dif, min([a[i+2]-a[i] for i in range(n-2)]))


from sys import  stdin
raw_input = stdin.readline
def fun(str1,str2,m,n):

    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
s=raw_input()
t=raw_input()
n,m=len(s),len(t)
ans=0
for i in xrange(n):
    for j in xrange(i,n):
        s1=s[:i]+s[j+1:]
        n1=j-i+1
        #print s1
        if m<=n-n1 and fun(t,s1,m,n-n1):
            ans=max(ans,n1)
print ans


# import sys
# sys.stdin=open("input.in","r")
# sys.stdout=open("output.out","w")
x=int(input())
y=input()
count1=y.count('FS')
count2=y.count('SF')
if(count2>count1):
	print("YES")
else:
	print("NO")


import math
#q=int(input())
q=1
for _ in range(q):
    s=(input())
    t=(input())
    n=len(s)
    ans=""
    flag=False
    for i in range(n):
        if s[i]==t[i]:
            ans+=s[i]
            continue
        elif ord(t[i])-ord(s[i])>1:
            ans+=(chr(ord(s[i])+1))
            k=(s[i+1:n])
            if len(k)!=0:
                ans+=(k)
            flag=True
            print(ans)
            break
        else:
            ans1=ans
            ans+=s[i]
            for j in range(i+1,n):
                if s[j]!='z':
                    ans+=(chr(ord(s[j])+1))
                    k=(s[j+1:n])
                    if len(k)!=0:
                        ans+=(k)
                    flag=True
                    break
            if flag:
                print(ans)
                break
            else:
                flag=0
                ans1+=chr(ord(s[i])+1)
                for j in range(i+1,n):
                    ans1+='a'
                for j in range(i+1,n):
                    if ord('a')<ord(t[j]):
                        flag=1
                        break
                if flag==1:
                    print(ans1)
                else:
                    print("No such string")
                break


n=int(input())
def s(x):
    return sum(int(i) for i in str(x))
x=int(n**0.5)
diff=0
ok=False

while diff<=50 and x>=0:
    if x*x+s(x)*x==n:
        ok=True
        ans=x
        #break
    diff+=1
    x-=1
if not ok:
    print(-1)
else:
    print(ans)


from sys import stdin

kDic = {c: i for i, c in enumerate("RGBYW12345")}

ibuf = stdin.readlines()
s = list(set(ibuf[1].split()))
t = []

for i in xrange(len(s)):
    for j in xrange(i + 1, len(s)):
        t.append([0, 0])
        if s[i][0] != s[j][0]:
            t[-1][0] = (1 << kDic[s[i][0]]) | (1 << kDic[s[j][0]])
        if s[i][1] != s[j][1]:
            t[-1][1] = (1 << kDic[s[i][1]]) | (1 << kDic[s[j][1]])

res = 10
for i in xrange(2 ** 10 - 1):
    b = [(x & i) | (y & i) for x, y in t]
    if 0 not in b:
        res = min(res, bin(i).count("1"))
print res


import sys
import math,bisect
sys.setrecursionlimit(10 ** 6)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
def I(): return int(sys.stdin.readline())
def neo(): return map(int, sys.stdin.readline().split())
def Neo(): return list(map(int, sys.stdin.readline().split()))
s = input()
k = I()
IMP = "Impossible"
l0 = len(s) - 2*s.count("*") - 2*s.count("?")
if l0 > k:
    print(IMP)
    exit()
lans = l0
ans = ""
for c in s:
    if c not in "*?":
        ans = ans + c
    elif c == "*":
        ans = ans[:-1] + ans[-1]*(k-lans)
        lans = k
    else:  # if c == "?"
        if lans >= k:
            ans = ans[:-1]
        else:
            lans += 1

if lans == k:
    print(ans)
else:
    print(IMP)


n = int(input())
k = [[0, 0, -1]]
cnt = 0
for i in map(int, input().split()):
    if i:
        if k[-1][0] == i:
            k[-1][1] += 1
        else:
            k.append([i, 1, cnt])
    cnt += 1
cnt = 0
ans = 0
for i in k[1:]:
    ans += min(i[1], i[2] - cnt)
    cnt += i[1]
print(ans)


# -*- coding: utf-8 -*-

__author__ = 'goran'

a, b = raw_input().split(' ')

candidates = []

for l in xrange(1, 64):
    ones = '1' * l
    for zero in xrange(1, len(ones)):
        candidates.append(ones[:zero] + '0' + ones[zero + 1:63])

a = int(a)
b = int(b)
count = 0
for i in candidates:
    br = int(i, 2)

    if br >= a and br <= b:
        count += 1

print count


try :
    import sys
    x, k = map(int, input().split(" "))
    lengthList = []
    lengthList = [int(p) for p in input().split(" ") for _ in range(0, x)]
    val = []
    val = [n for n in lengthList if (float(k/n)).is_integer() == True]
    y = max(val)
    print(int(k/y))
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError as ex:
    print("Could not convert data to an integer.")
    print("value error: {0}".format(ex))
except:
    print("Unexpected error:", sys.exc_info()[0])
    #raise


n, d = map(int, raw_input().split())
a = sum(map(int, raw_input().split()))
print (d - a) / 5 if a + (n - 1) * 10 <= d else -1


from sys import *
s=input()
for i in range(1,len(s)):
    if s[i:]==s[:len(s)-i] and i<=(len(s)-1)//2:
        print('YES')
        print(s[i:])
        exit(0)
print('NO')


import math
MOD = 10**9+7

N,M,G = map(int,raw_input().split())

if M == 0:
    print int(G!=N%2)
    exit()
if M == 1:
    ans = int(G!=N%2)
    for i in xrange(N):
        if i%2 == G:
            ans += 1
    print ans
    exit()

D = [0 for i in xrange(N+1)]
D[0] = 1
for i in xrange(1,N+1):
    D[i] = D[i-1]*(i+M-1)%MOD*pow(i,MOD-2,MOD)%MOD
ans = 0
for i in xrange(N+1):
    if i%2 == G:
        a,b = N-i,M-1
        ans = (ans+D[a])%MOD
print ans


n = int(input())
m = int(input())
s = [int(input()) for _ in range(n)]
ma = max(s)+m
s = sorted(s)
pp = max(s)
for i,e in enumerate(s):
    s[i] += (pp-e)
    m -= (pp-e)
    if m<0:
        t = abs(m)
        s[i] -= t
    if m<=0:
        break
mi = max(s)
if m>0:
    mi = s[0]+(m//len(s))+(1 if m%len(s)!=0 else 0)
print(mi,ma)


n, k = map(int, input().split())
A = sum(list(map(int, input().split())))
print(max(2 * n * k - n - 2 * A, 0))


n = int(input())
s = str(input())
half = n//2
sit = s.count('x')
stand = s.count('X')
ans = max(sit, stand) - half
t = ans
while ans!=0:
    if sit>stand:
        temp = s.index('x')
        s = s[:temp] + 'X' + s[temp+1:]
        sit = sit-1
        stand = stand +1
        ans = ans -1
    else:
        temp = s.index('X')
        s = s[:temp] + 'x' + s[temp+1:]
        sit = sit+1
        stand = stand - 1
        ans = ans -1
print(t)
print(s)


s = raw_input().strip()
lens = len(s)
c = [0 for _ in xrange(len(s))]
m = list(s)
# for ch in m:
# 	print ch,
# print
# for ci in c:
# 	print ci,
# print
for i in range(lens):
	if i > 0:
		c[i] = c[i-1]
	if s[i] == 'Q':
		c[i] += 1
# for ci in c:
# 	print ci,
# print
ans = 0
for i in range(1,lens-1):
	if s[i] == 'A':
		ans += (c[i-1]*(c[lens-1]-c[i-1]))
print ans


x = int(input())
print(6 * x * (x-1) + 1)


from collections import namedtuple

Glass = namedtuple('Glass', ['time_full', 'rates'])
Rate = namedtuple('Rate', ['start_time', 'rate'])

def solve(n, t):
    p = [[None] * i for i in xrange(1, n + 1)]

    def get_parents(row, col):
        return [
            p[r][c]
            for r, c in [(row - 1, col), (row - 1, col - 1)]
            if 0 <= c < row and p[r][c] is not None
        ]

    if t == 0:
        return 0

    p[0][0] = Glass(1.0, [Rate(1.0, 1.0)])

    c = 1
    for row in xrange(1, n):
        for col in xrange(row + 1):
            parents = get_parents(row, col)
            # if len(parents) == 1:
            #     assert len(parents[0].rates) == 1, (row, col, parents[0])
            #
            #     rate = parents[0].rates[0].rate / 2
            #     time_full = parents[0].time_full + 1 / rate
            #
            #     if time_full > t:
            #         continue
            #
            #     p[row][col] = Glass(time_full, [Rate(time_full, rate)])
            #     c += 1
            #
            # elif len(parents) == 2:
            if len(parents):

                rates = sorted([r for i in parents for r in i.rates], key=lambda x: x.start_time)

                share_full = 0
                rate = 0
                for i in xrange(len(rates) - 1):
                    rate += rates[i].rate / 2
                    new_share_full = share_full + rate * (rates[i+1].start_time - rates[i].start_time)
                    if new_share_full >= 1:
                        time_full = rates[i].start_time + (1 - share_full) / rate
                        new_rates = [Rate(time_full, rate)] + map(lambda x: Rate(x.start_time, x.rate / 2), rates[i+1:])
                        break
                    else:
                        share_full = new_share_full
                else:
                    rate += rates[-1].rate / 2
                    time_full = rates[-1].start_time + (1 - share_full) / rate
                    new_rates = [Rate(time_full, rate)]

                if time_full > t:
                    continue

                p[row][col] = Glass(time_full, new_rates)

                c += 1
    # for i in p:
    #     print i == list(reversed(i)), i
    return c

# print solve(3, 5)
# print solve(4, 8)
# print solve(10, 15)
# print solve(10, 1022)

n, t = map(int, raw_input().split())
print solve(n, t)


input()
X = input()
Parentheses, Outside, i = "", "", 0
while i < len(X):
    if X[i] == "(":
        i, Parentheses = i + 1, Parentheses + "_"
        while X[i] != ")":
            Parentheses, i = Parentheses + X[i], i + 1
        Outside += "_"
    else:
        Outside += X[i]
    i += 1
Outside = Outside.split("_")
Parentheses = Parentheses.split("_")
print(len(max(Outside, key=len)), len(Parentheses) - Parentheses.count(""))

# UB_CodeForces
# Advice: Life is not about finding yourself, it's about creating yourself
# Location: At home behind my desk
# Caption: Yeeeeaahhhh i got what i wanted
# CodeNumber: 491


(n,k) = (int(i) for i in input().split())
zapross = [int(i) for i in input().split()]
lave = 0
curh = set()
for i in range(n):
	if zapross[i] in curh: continue
	if len(curh)!=k:
		lave+=1
		curh.add(zapross[i])
	else:
		lpos = -1
		cc = -1
		for j in curh:
			try:
				pos = zapross[i+1:].index(j)
			except ValueError:
				cc = j
				break
			if pos>lpos:
				lpos = pos
				cc = j
		curh.remove(cc)
		curh.add(zapross[i])
		lave+=1
print(lave)


def largest_no_pal(s):
    if (not s or s != s[::-1] or (len(set(s)) == len(s) and len(s) != 1)):
        return len(s)

    temp_arr = []

    for i in range(len(s)):
        for j in range(len(s)-1, i, -1):
            temp = s[i:j+1]

            if (temp != temp[::-1]):
                temp_arr.append(temp)

    if (not temp_arr):
        return 0

    return len(max(temp_arr, key=lambda x: len(x)))

inp = input()
print(largest_no_pal(inp))


n=input()
if n[0]==n[0].lower() and n[1:]==n[1:].upper():
    print(n[0].upper()+n[1:].lower())
elif n==n.upper():
    print(n.lower())
else:
    print(n)


a,b,c=map(int,input().split())
s=(a+b+c)//2
if (a+b+c)%2 or s-a<0 or s-b<0 or s-c<0:print("Impossible")
else:print(s-c,s-a,s-b)


n,m,k=map(int,input().split())
a,b=map(int,input().split())
p=[]
for i in range(1,n+1):
    p.append(i*m*k)
it=[[0]*n for i in range(m)]
for i in range(m):
    for j in range(n):
        it[i][j]=j*m*k+k*(i+1)
fl1=True
fl2=True
for i in range(n):
    for j in range(m):
        if it[j][i]-a>=0 and fl1:
            p1=i+1
            it1=j+1
            fl1=False
        if it[j][i]-b>=0 and fl2:
            p2=i+1
            it2=j+1
            fl2=False
        if not fl1 and not fl2:
            break
if p1!=p2:
    t1=min(it1-1+10,5*(it1-1))
    if p1>p2:
        s1=p1
        t21=0
        while s1!=p2:
            s1+=1
            t21+=1
            if s1>n:
                s1//=n
    else:
        s1=p2
        t21=0
        while s1!=p1:
            s1+=1
            t21+=1
            if s1>n:
                s1//=n
    t21*=15
    t2=min(t21,(abs(p2-p1))*15)
    t3=min(it2-1+10,5*(it2-1))
    t=t1+t2+t3
    print(t)
else:
    t=min(abs(it2-it1)*5,10+abs(it2-it1))
    print(t)


lr = input().split()
l,r = [int(x) for x in lr]

if l == r:
    print(0)

else:
    a,b = list(bin(l)[2:]), list(bin(r)[2:])
    if len(a) == len(b):
        i = 0
        while a[i] == b[i]:
            i+=1
        left = '1'*(len(a)-i)
        print(int(left,2))
    elif len(a) > len(b):
        left = '1'*(len(a))
        print(int(left,2))
    else:
        left = '1'*(len(b))
        print(int(left,2))


data=list(map(int,input().split()))
n=data[0]
m=data[1]
k=data[2]
pos=[1,1]
if k<=n-1:
    print(k+1,1)
else:
    k-=n-1
    ans=k//(m-1)
    pos=k%(m-1)
    if pos==0 and ans%2 ==0:
        print(n-ans+1,2)
    elif pos==0 and ans%2 !=0:
        print(n-ans+1,m)
    elif pos!=0 and ans%2 ==0:
        print(n-ans,1+k%(2*m-2))
    else:
        print(n-ans,2+(2*m-2)-k%(2*m-2))


c=1; input(); l=sorted(set(map(int,input().split())))
for i in range(len(l)-1):
	if l[i+1]-l[i]==1:c+=1
	else:c=1
	if c==3:break
print(["NO","YES"][c==3])


def dfs(v):
    visit[v] = cnt
    for u in vertex[v]:
        if not visit[u] and u in challengers:
            dfs(u)

n, m = map(int, input().split())
vertex = [[] for i in range(n + 1)]
challengers = set()
ans = [''] * (n + 1)
middle = set()
for i in range(m):
    a, b = map(int, input().split())
    vertex[a].append(b)
    vertex[b].append(a)

for i in range(1, n + 1):
    s = set(j for j in range(1, n + 1))
    s.discard(i)
    if s == set(vertex[i]):
        ans[i] = 'b'
        middle.add(i)
    else:
        challengers.add(i)

visit = [0] * (n + 1)
cnt = 0
for c in challengers:
    if not visit[c]:
        cnt += 1
        dfs(c)

if cnt > 2 or cnt == 1:
    print('No')
elif cnt == 2:
    first = set()
    second = set()
    for i in range(1, n + 1):
        if visit[i] == 1:
            first.add(i)
        elif visit[i] == 2:
            second.add(i)
    for c in first:
        s = first
        s.discard(c)
        if set(vertex[c]) - middle != s:
            print('No')
            break
        s.add(c)
    else:
        for c in first:
            ans[c] = 'a'
        for c in second:
            s = second
            s.discard(c)
            if set(vertex[c]) - middle != s:
                print('No')
                break
            s.add(c)
        else:
            for c in second:
                ans[c] = 'c'

if not ans[1:].count(''):
    print('Yes', ''.join(ans[1:]), sep = '\n')


a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
f = int(input())
if min(a,d)*e+min(b,c,(d-min(a,d)))*f>=min(b,c,d)*f+min(a,d-(min(b,c,d)))*e:
    print(min(a,d)*e+min(b,c,(d-min(a,d)))*f)
else:
    print(min(b,c,d)*f+min(a,d-(min(b,c,d)))*e)


n = input()
length = len(n)
if length % 2 == 1:
    result = '4'*((length + 1) // 2) + '7'*((length + 1) // 2)
else:
    half = length // 2
    if n > half*'7' + half*'4':
        result = (half + 1)*'4' + (half + 1)*'7'
    elif n < half*'4' + half*'7':
        result = half*'4' + half*'7'
    else:
        four_count = seven_count = half
        for i in range(length):
            digit = n[i]
            if digit < '4':
                    result = n[:i] + '4'*four_count + '7'*seven_count
                    break
            if digit < '7' and digit != '4':
                if seven_count == 0:
                    result = n[:nearest_four] + '7' + '4'*(four_count + 1)
                    result += '7'*(length - len(result))
                else:
                    result = n[:i] + '7' + '4'*four_count + '7'*(seven_count - 1)
                break
            if digit > '7':
                result = n[:nearest_four] + '7' + '4'*(four_count + 1)
                result += '7'*(length - len(result))
                break
            if digit == '4':
                nearest_four = i
                four_count -= 1
                if four_count < 0:
                    result = n[:i] + '7'*seven_count
                    break
            if digit == '7':
                seven_count -= 1
                if seven_count < 0:
                    result = n[:nearest_four] + '7' + '4'*(four_count + 1)
                    result += '7'*(length - len(result))
                    break
            if four_count == 0 and seven_count == 0:
                result = n
                break
print(result)


a,b,c,d=input(),input(),input(),input()
a=len(a)-2
b=len(b)-2
c=len(c)-2
d=len(d)-2
e=False
if 2*a<=c and 2*a<=b and 2*a<=d or a>=2*c and a>=2*b and a>=2*d: e='A'
if 2*b<=a and 2*b<=c and 2*b<=d or b>=2*a and b>=2*c and b>=2*d:
    if e==False:
        e='B'
    else:
        e='C'
if 2*c<=a and 2*c<=b and 2*c<=d or c>=2*a and c>=2*b and c>=2*d:
    if e==False:
        e='C'
    else:
        e='C'
if 2*d<=a and 2*d<=b and 2*d<=c or d>=2*a and d>=2*b and d>=2*c:
    if e==False:
        e='D'
    else:
        e='C'
if e==False: e='C'
print(e)


F = {}

def f(k):
    if not k in F:
        s, i, j = 0, 4, 4
        while i <= k:
            s += i * f(k / i)
            i += j + 1
            j += 2
        F[k] = (k * (k + 1)) / 2 - s
    return F[k]

def g(k):
    s, i, j = 0, 4, 4
    while i <= k:
        s += (i - 1) * f(k / i)
        i += j + 1
        j += 2
    return (k * (k + 1)) / 2 - s

a, n = map(int, raw_input().split())
print g(a + n - 1) - g(a - 1)


from itertools import permutations
ch=list(map(int,input().split()))
op=list(input().split())

def f(oper, x, y):
    if oper=="*":
        return (x*y)
    else:
        return (x+y)
ans=10**12
for a,b,c,d in permutations(ch):
    ans=min(ans, min(f(op[2], f(op[1], f(op[0],a,b), c), d), f(op[2], f(op[0],a,b),f(op[1],c,d))))
print(ans)


a, b, c = map(int, input().split())
x, y, z = map(int, input().split())
tenho = max(0, (a-x)//2) + max(0, (b-y)//2) + max(0, (c-z)//2)
quero = abs(min(0, a-x) + min(0, b-y) + min(0, c-z))
print('Yes' if quero <= tenho else 'No')


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


from __future__ import division
from fractions import gcd

n, k = map(int, raw_input().split())
a, b = map(int, raw_input().split())
pos = [a + b, a - b, -a + b, -a - b]

kn = k * n
low = 10e310
high = -1

for dif in pos:
    l = dif
    for _ in xrange(n):
        res = kn // gcd(l, kn)
        if res < low:
            low = res
        if res > high:
            high = res
        l += k

print "{} {}".format(low, high)


k= input()
m=str(k)
s=False;
count=0

for n in range (0,m.__len__()):
  if(m[n]=='4' or m[n]=='7'):

      count+=1

if(count==m.__len__()):
    print "YES"
elif(k% 4==0 or k% 7==0 or k% 47==0 or k% 74==0):
    print "YES"
else:
         print "NO"


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

import sys

MAXN = 110
MOD = 10 ** 9 + 7
INF = MOD

def MakeCom():
	global com
	com = [[1]]
	for i in xrange(1, MAXN + 1):
		line = [1]
		for j in xrange(1, i):
			line.append((com[-1][j - 1] + com[-1][j]) % MOD)
		line.append(1)
		com.append(line)

def ReadIn():
	data = [int(x) for x in sys.stdin.read().split()]
	offset = 0
	while offset < len(data):
		n, cap = data[offset : offset + 2]
		offset += 2
		friends = [0] * 2
		for x in data[offset : offset + n]:
			friends[x / 50 - 1] += 1
		offset += n
		cap /= 50
		yield cap, tuple(friends)

def Solve(cap, friends):
	f = {friends : 1}
	for rides in xrange(sum(friends) * 5):
		if rides & 1 and friends in f:
			print rides
			print f[friends]
			return
		pf, f = f, {}
		for remain in pf:
			for x in xrange(remain[0] + 1):
				if x > cap: break
				for y in xrange(remain[1] + 1):
					if x + y < 1: continue
					if x + 2 * y > cap: break
					nextRem = tuple(total - left + move
							for total, left, move in zip(friends, remain, (x, y)))
					f[nextRem] = (f.get(nextRem, 0) + com[remain[0]][x] * com[remain[1]][y] * pf[remain]) % MOD

	print -1
	print 0

if __name__ == '__main__':
	MakeCom()
	for cap, friends in ReadIn():
		Solve(cap, friends)


n=map(lambda x:ord(x)-ord('0'),list(raw_input()))
M=10**9+7
c=[0]*32
s=0
k=len(n)
def acc(k,s,v):
  if k>0:
    acc(k-1,s+1,v*2)
    acc(k-1,s,v*8)
  else:
    c[s]+=v
for i in range(k):
  for j in range(n[i]):
    acc(k-i-1,s+(j in (4,7)),1)
  s+=n[i] in (4,7)
c[s]+=1
c[0]-=1
def win(u,v,w):
  x=0
  if v<10:
    if u<6:
      for i in range(11):
        if c[i]>0:
          c[i]-=1
          x=(x+win(u+1,v+i,w*(c[i]+1)%M))%M
          c[i]+=1
    else:
      for i in range(v+1,10):
        x=(x+w*c[i])%M
  return x
print win(0,0,1)


class A:

    def solve(self):
        board = []
        for i in range(8):
            board.append(input())

        painted_black = [[0 for i in range(8)] for j in range(8)]

        strokes = 0
        for i in range(8):
            if len(set(board[i])) == 1 and 'B' in set(board[i]):
                strokes += 1
                painted_black[i] = [1 for i in range(8)]

        for i in range(8):
            if len(set([board[x][i] for x in range(8)])) == 1 and \
               'B' in set([board[x][i] for x in range(8)]) and \
               0 in set([painted_black[x][i] for x in range(8)]):
                strokes += 1

        print(strokes)

A().solve()


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

# def f(m):

# m = 0
# l = 0
# r = n

# while l < r:
#     m = (l + r)//2

n = int(input())
p = []

for i in range(n):
	p.append(1)
	while len(p) >= 2 and p[-1] == p[-2]:
		p[-2] += 1
		p.pop()

for i in p: print(i, end=" ")


def board (arr):
    for i in range (8):
        for j in range (8):
            print arr[i][j],
        print
def rokh_tahdid (arr,xy):
    for i in range (8):
        for j in range (8):
            if (xy[0] == i or xy[1] == j) and xy != [i,j]:
                arr[i][j]=1
    return arr
def asb_tahdid (arr,x,y):
    def inboard (n):
        if n >= 0 and n <= 7:
            return True
        else:
            return False
    if inboard (x-2) and inboard (y-1):
        arr[x-2][y-1] = 3

    if inboard (x-2) and inboard (y+1):
        arr[x-2][y+1] = 3

    if inboard (x-1) and inboard (y-2):
        arr[x-1][y-2] = 3

    if inboard (x-1) and inboard (y+2):
        arr[x-1][y+2] = 3

    if inboard (x+2) and inboard (y-1):
        arr[x+2][y-1] = 3

    if inboard (x+2) and inboard (y+1):
        arr[x+2][y+1] = 3

    if inboard (x+2) and inboard (y-2):
        arr[x+1][y-2] = 3

    if inboard (x+2) and inboard (y+2):
        arr[x+1][y+2] = 3
def new_tahdid (arr,x,y):
    def inboard (n):
        if n >= 0 and n <= 7:
            return True
        else:
            return False
    point = 0
    total = 0
    if inboard (x-2) and inboard (y-1):
        if arr[x-2][y-1] == 2:
            total += 1
        else:
            point += 1
            total += 1

    if inboard (x-2) and inboard (y+1):
        if arr[x-2][y+1] == 2:
            total += 1
        else:
            point += 1
            total += 1

    if inboard (x-1) and inboard (y-2):
        if arr[x-1][y-2] == 2:
            total += 1
        else:
            point += 1
            total += 1

    if inboard (x-1) and inboard (y+2):
        if arr[x-1][y+2] == 2:
            total += 1
        else:
            point += 1
            total += 1

    if inboard (x+2) and inboard (y-1):
        if arr[x+2][y-1] == 2:
            total += 1
        else:
            point += 1
            total += 1

    if inboard (x+2) and inboard (y+1):
        if arr[x+2][y+1] == 2:
            total += 1
        else:
            point += 1
            total += 1
    if inboard (x+1) and inboard (y-2):
        if arr[x+1][y-2] == 2:
            total += 1
        else:
            point += 1
            total += 1

    if inboard (x+1) and inboard (y+2):
        if arr[x+1][y+2] == 2:
            total += 1
        else:
            point += 1
            total += 1
    return point == total
arr=[]
for i in range (8):
    arr.append([0,0,0,0,0,0,0,0])
j='abcdefgh'
R=raw_input()
A=raw_input()
r=[j.index(R[0]),int(R[1])-1]
a=[j.index(A[0]),int(A[1])-1]

arr[r[0]][r[1]] = 2
arr[a[0]][a[1]] = 2
rokh_tahdid (arr,r)
asb_tahdid (arr,a[0],a[1])
c0 = 0
for i in range (8):
    for j in range (8):
        if arr[i][j] == 0:
            if new_tahdid (arr,i,j):
                c0+=1
else:
    print c0


n = int(raw_input())
arr = map(int, raw_input().split(" "))

arr.sort()

if len(arr) == 1:
    print arr[0]
else:
    print (arr[0] + arr[-1]) // 2


n = int(input())

def pow2 (x):
    r = 1
    while (x > 0):
        x-=1
        r*=2
    return r

# Using DP bottom_up technic to
# calculate answer to powers of
# two n
def val_pow_2 (x):
    lst = []
    lst.append(0)
    for i in range(x):
        lst.append(2*lst[i]+pow2(i))
    return lst

# Maximum expoent of power of two
# smaller than x
def lg2 (x):
    r = 0;
    ans = 1;
    while (x > 1):
        x = int(x/2)
        ans *= 2
        r+=1
    return r

# Maximum power of two smaller
# than x
def max_pow_2 (x):
    ans = 1;
    while (x > 1):
        x = int(x/2)
        ans *= 2
    return ans

def func (x, lst):
    if (bin(x).count("1") == 1):
        return lst[lg2(x)]
    elif (x == 0):
        return 0
    else:
        y = max_pow_2 (x)
        return lst[lg2(y)] + y + func (x-y, lst)

lst = val_pow_2 (int(lg2(n)))
#for i in range(len(lst)):
#    if (pow2(i) > 1e12):
#        break
#    print (str(pow2(i)) + ": " + str(lst[i]))

print (func (n, lst))


n,k,t=map(int,input().split())
if(t<k):
    print(t)
elif(t>=k and t<=n):
    print(k)
else:
    print(k-(t-n))


n = input()
c=0
v=0
for i in range(int(input())):
    s = input()
    if(n[0]==s[1]): c+=1
    if(n[1]==s[0]): v+=1
    if(n==s):
        c+=1
        v+=1
print("YES" if(c and v) else "NO")


n = int(input())

ans = 0
while n:
    n >>= 1
    ans += 1

print(ans)


s=raw_input()
print s[0].upper()+s[1:]
#string.capitalize


a, b = map(int, raw_input().split())
a, b = min(a, b), max(a, b)
if b % a == 0:
    print(0)
    exit(0)
x = b - a
dels = set()
for i in range(1, int(x ** 0.5) + 1):
    if x % i == 0:
        dels.add(i)
        dels.add(x // i)
dels = list(dels)
j = 10 ** 20
for i in dels:
    if i >= a:
        j = min(j, i - a)
print(min((x % a - a) % x, j))


n = int(input())
w = list(map(int, input().split()))
w.sort()
ans = []
for i in range(2 * n):
    for j in range(i+1, 2 * n):
        m = w[0:i] + w[i+1:j] + w[j+1:]
        var = sum(m[1::2]) - sum(m[::2])
        ans.append(var)
print(min(ans))


def pab(l,n):
    c=0
    i=0
    while(n>0):

        n=n-l[i]
        c=c+1

        if(i==6):
            i=0
        else:
            i=i+1
    z=c%7
    if(z==0):
        print(7)
    else:
        print(z)
    return
n=int(input())
t=input()
l=list(map(int,t.split(' ')))
pab(l,n)


INF = float('inf')

def isSqrt(s):
    if s[0] == '0':
        return False
    n = int(s)
    m = 0
    while m * m <= n:
        if m * m == n:
            return True
        m += 1
    return False

s = list(input())
n = len(s)
ret = INF
for mask in range((1 << n) - 1):
    t = s[::]
    for i in range(n):
        if (mask >> i) & 1 == 1:
            t[i] = ''
    if isSqrt(''.join(t)):
        ret = min(ret, bin(mask).count('1'))
print(ret if ret != INF else -1)


a, b, x = map(int, input().split())
ans = ""
for i in range((x + 1) // 2):
	ans += "10"
	a -= 1
	b -= 1
answ = ""
if x % 2 == 1:
	answ = ('1' * b + ans + '0' * a)
else:
	#print(a, b)
	if a > 0:
		answ = ('0' + '1' * b + ans + '0' * (a - 1))
	else:
		answ = (ans + '1' * b)
print(answ)


n = int(input())
a = list(map(int,input().split()))
b = sorted(a)
k = 1
while k:
    k = 0
    for i in range(1,len(b)):
        if b[i] - b[0] > 0:
            if b[i] % b[0] > 0:
                b[i] = b[i] % b[0]
            else:
                b[i] = b[0]
            k = 1
    b = sorted(b)
print (sum(b))


n = int(input())
disjointSet = [-1] * n
def root(x, level=200):
    dp = []
    while disjointSet[x] >= 0:
        dp.append(x)
        x = disjointSet[x]
    for i in dp:
        disjointSet[i] = x
    return x

def join(x, y):
    r1, r2 = root(x), root(y)
    if r1 == r2:
        return
    disjointSet[r2] = r1

points = []
vertPoints = {}
horizPoints = {}
for i in range(n):
    a, b = map(int, input().split())
    points.append((a, b))
    if a in vertPoints:
        join(i, vertPoints[a])
    else:
        vertPoints[a] = i
    if b in horizPoints:
        join(i, horizPoints[b])
    else:
        horizPoints[b] = i

sets = {}
for i in range(n):
    r = root(i)
    if r in sets:
        sets[r].append(points[i])
    else:
        sets[r] = [points[i]]

ans = 1
for i in sets:
    s = sets[i]
    horiz = [x for x,y in s]
    vert = [y for x,y in s]
    tmp = len(set(horiz)) + len(set(vert))
    if tmp <= len(s):
        ans *= 2 ** tmp
    else:
        ans *= 2 ** tmp - 1
    ans %= 10 ** 9 + 7

print(ans % (10 ** 9 + 7))


k,n,s,p= map(int,input().split())
t=(n+s-1)//s
sheets=k*t
print((sheets+p-1)//p)


a,b,c,d=input().split()
def tri(q,w,e):
    if(q<w+e):

        if(w<q+e):
            if(e<q+w):
                k=1
                return k
            elif(e==q+w):
                k=2
                return k
            else:
                return 0
        else:
            if(w==q+e):
                if(e<q+w):
                 k=2
                 return k
            elif(e==q+w):
                 k=2
                 return k
            else:
                return 0
    elif(q==w+e):
        if(w<q+e):
            if(e<q+w):
                k=2
                return k
            elif(e==q+w):
                k=2
                return k
            else:
                return 0
        else:
            if(w==q+e):
                if(e<q+w):
                 k=2
                 return k
            elif(e==q+w):
                 k=2
                 return k
            else:
                return 0
    else:
        return 0

z=[]
a=int(a)
b=int(b)
c=int(c)
d=int(d)
l=tri(a,b,c)
z.append(l)
l=tri(a,b,d)
z.append(l)
l=tri(a,c,d)
z.append(l)
l=tri(c,b,d)
z.append(l)
if(1 in z):
    print("TRIANGLE")
elif(2 in z):
    print("SEGMENT")
else:
    print("IMPOSSIBLE")


def solve():
    n = int(input())
    div, rem, s, rem_s = n//4, n%4, 'GBIV', ''
    if rem != 0: rem_s = s[:rem]
    print('ROY' + (div * s)[3:] + rem_s)
solve()


n,pos,L,R=map(int,raw_input().split())

def tc(n,pos,L,R):
    ct=0
    if L==1 and R==n:
        return 0
    elif R==n:
        if pos<=L:
            return L-pos+1
        else:
            return pos-L+1
    elif L==1:
        if pos>=R:
            return pos-R+1
        else:
            return R-pos+1
    elif L>1 and R<n:
        if pos<=L:
            return R-pos+2
        elif pos>=R:
            return pos-L+2
        elif L<pos<R:
            return min(pos+R-2*L,2*R-pos-L)+2

print tc(n,pos,L,R)


# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 15:27:18 2013

@author: Praveen Kumar
"""

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

def main():

    c1 = 0
    c2 = sum(a)

    for e,i in enumerate(a):
        #print(e,i)
        c1 += i
        c2 -= i
        if x <= c1 and c1 <=y and x <= c2 and c2 <= y:
            print(e+2)
            return
    print(0)

main()


x1,y1,x2,y2=[int(i) for i in input().split()]
x,y=[int(i) for i in input().split()]
if x1%x==x2%x and y1%y==y2%y and (x2-x1)//x%2==(y2-y1)//y%2:
    print('YES')
else: print('NO')
#print((x2-x1)//x,(y2-y1)//y)


import math
F=lambda x:math.factorial(x)
n,w,b=map(int,raw_input().split())
print (F(w)*F(b)*(w-1)*F(w+b-3)/F(n-3)/F(w+b-n))%1000000009


import sys

f1, f2 = map(int, sys.stdin.readline().split())
n = int(sys.stdin.readline())

f3 = f2 - f1
f4 = -f1
f5 = -f2
f6 = -f3
f = [f6, f1, f2, f3, f4, f5]
print((f[n%6]) % (10**9 + 7))


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

tmp = abs(x - y)

if tmp == z == 0:
    print(0)
elif tmp > z:
    if x > y:
        print('+')
    else:
        print('-')
else:
    print('?')


a, b, c=map(int, input().split())
print(3*min(a+1,b, c-1))


from sys import stdin
from itertools import repeat
def main():
    a, b, h, w, n = map(int, stdin.readline().split())
    m = map(int, stdin.readline().split(), repeat(10, n))
    m.sort(reverse=True)
    m += [1] * 38
    def go(dep, c, hh, ww, a, b):
        if dep >= 19:
            if ww < a and ww < b:
                return 999
            for i in xrange(19):
                if hh >= a and ww >= b:
                    return c + i
                if ww >= a and hh >= b:
                    return c + i
                hh *= m[i+19]
            return 999
        if hh >= a and ww >= b:
            return c
        if ww >= a and hh >= b:
            return c
        k1 = k2 = 999
        if b > hh or hh < a:
            k1 = go(dep + 1, c + 1, hh * m[dep], ww, a, b)
        if b > ww or ww < a:
            k2 = go(dep + 1, c + 1, hh, ww * m[dep], a, b)
        if k1 < k2:
            return k1
        else:
            return k2
    ans = go(0, 0, h, w, a, b)
    if ans == 999:
        ans = -1
    print ans
main()


n,a=raw_input(),map(int,raw_input().split(' '))
s=[]
ans=0
for i in a:
    while len(s)>1 and s[-1]<=i and s[-2]>=s[-1]:
        ans+=min(i,s[-2])
        del(s[-1])
    s.append(i)
s.sort()
print ans+sum(s[0:-2])


b,r = [raw_input() for _ in xrange(6)],[]
def x(i,d,c='RL'): b[i]=b[i][-d:]+b[i][:-d];r.extend([c[d>3]+str(i+1)]*(d if d<3 else 6-d))
def y(i,d): global b;b=zip(*b);x(i,d,'DU');b=zip(*b)
def u(i,j): x(j,1);y(i,1);x(j,5);y(i,5)
def p(i,j): u(i,j);x((j+5)%6,1);u((i+1)%6,j);x((j+5)%6,5);u(i,j);u(i,j)
def l(i,j): p((i+1)%6,j);p((i+3)%6,j);x(j,1)
for k,c in enumerate(sorted(''.join(b))):
    ii,jj=k%6,k/6
    z = filter(lambda x: c in x, b)[0]
    i,j=z.index(c),b.index(z)
    while i!=ii: l(i,j); i=(i+5)%6
    while j>jj: u(ii,j); j-=1
print len(r)
print '\n'.join(r)


import sys
range = xrange
input = raw_input

A = [0 if c == '(' else 1 for c in input()]
B = [0 if c == '(' else 1 for c in input()]

n = len(A)
m = len(B)

big = 10**8

DP = [[[big]*201 for _ in range(n + 1)] for _ in range(m + 1)]
DP[0][0][0] = 0
way = [[[-1]*201 for _ in range(n + 1)] for _ in range(m + 1)]

for j in range(m + 1):
    for i in range(n + 1):
        DPji = DP[j][i]
        iprim = i + (i < n and A[i] == 1)
        jprim = j + (j < m and B[j] == 1)
        for k in reversed(range(1, 201)):
            val = DPji[k] + 1
            if DP[jprim][iprim][k - 1] > val:
                DP[jprim][iprim][k - 1] = val
                way[jprim][iprim][k - 1] = 1

        iprim = i + (i < n and A[i] == 0)
        jprim = j + (j < m and B[j] == 0)
        for k in range(200):
            val = DPji[k] + 1
            if DP[jprim][iprim][k + 1] > val:
                DP[jprim][iprim][k + 1] = val
                way[jprim][iprim][k + 1] = 0

        iprim = i + (i < n and A[i] == 1)
        jprim = j + (j < m and B[j] == 1)
        for k in reversed(range(1, 201)):
            val = DPji[k] + 1
            if DP[jprim][iprim][k - 1] > val:
                DP[jprim][iprim][k - 1] = val
                way[jprim][iprim][k - 1] = 1
ans = []

i = n
j = m
k = 0
counter = 0
while i != 0 or j != 0 or k != 0:
    counter += 1
    c = way[j][i][k]
    ans.append(c)
    val = DP[j][i][k] - 1
    k += 1 - 2 * (c == 0)

    matchi = +(i > 0 and A[i - 1] == c)
    matchj = +(j > 0 and B[j - 1] == c)

    if DP[j][i][k] == val:
        pass
    elif matchi and DP[j][i - 1][k] == val:
        i -= 1
    elif matchj and DP[j - 1][i][k] == val:
        j -= 1
    else:
        i -= 1
        j -= 1

#print DP[m][n][0]
print ''.join('(' if x == 0 else ')' for x in reversed(ans))


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

mat = [[[int(0),int(0),""] for _i in range(n+1)] for _j in range(n+1)]

for i in range(2*n):
	digit = int(s[i])
	toIter = min(i,n)

	minh = max(i-n,0)
	maxh = min(n,i)

	for m in range(minh,maxh+1):
		h = i - m
		v = mat[h][m]

		if h < n:
			#add current symbol to homer
			vnext = mat[h+1][m];
			sumhmn = vnext[0]*pow(10,(2*n-h-2)) + vnext[1]*pow(10,(2*n-m-1));
			sumhm = (v[0]*10+digit)*pow(10,(2*n-h-2)) + v[1]*pow(10,(2*n-m-1));
			if sumhm >= sumhmn :
				vnext[0]=v[0]*10+digit
				vnext[1]=v[1]
				vnext[2]=v[2]+'H'
		if m < n:
			#add current symbol to marge
			vnext = mat[h][m+1];
			sumhmn = vnext[0]*pow(10,(2*n-h-1)) + vnext[1]*pow(10,(2*n-m-2));
			sumhm = v[0]*pow(10,(2*n-h-1)) + (v[1]*10+digit) * pow(10,(2*n-m-2));
			if sumhm >= sumhmn :
				vnext[0]=v[0]
				vnext[1]=v[1]*10+digit
				vnext[2]=v[2]+'M'

print(mat[n][n][2])


from collections import deque

def restore(a, log):
  n = len(a)
  b = [0 for i in range(n)]

  def mergeSort(l, r):
    if r - l <= 1:
      return
    m = (l + r) >> 1
    mergeSort(l, m)
    mergeSort(m, r)
    i, j, k = l, m, l
    while i < m and j < r:
      if log.popleft() == '0':
        b[k] = a[i]
        i += 1
      else:
        b[k] = a[j]
        j += 1
      k += 1
    while i < m:
      b[k] = a[i]
      i += 1
      k += 1
    while j < r:
      b[k] = a[j]
      j += 1
      k += 1
    for p in range(l, r):
      a[p] = b[p]

  mergeSort(0, n)

  return len(log) == 0, a

log = input()

flag, n = False, 2
while not flag and n <= 10**3:
    try:
        flag, p = restore([i for i in range(n)], deque(log))
    except:
        flag = False
    n += 1

A = [None] * len(p)
for i in range(len(p)):
    A[p[i]] = i + 1

print(len(A))
print(" ".join(str(a) for a in A))


#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 missingdays <missingdays@missingdays>
#
# Distributed under terms of the MIT license.

"""

"""

n = int(input())

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

i = 0
answ = n
c = 0

while i < n and a[i] == 0:
    i += 1
    answ -= 1

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

while i < n:
    if a[i] == 0:
        c += 1
    else:
        if c > 1:
            answ -= c
        c = 0
    i += 1

answ -= c

print(answ)


a, b = map(int, input().split())
import math
g = math.gcd(a, b)
a, b = a//g, b//g
cnt = 0
for i in [2,3,5]:
    while(a%i == 0):
        a //= i
        cnt += 1
    while(b%i == 0):
        b //= i
        cnt += 1
if a-1 or b-1: print(-1)
else: print(cnt)


#!/usr/bin/python
import sys

lim = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], \
       [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]

def leap (y):
	return y % 4 == 0

def do (a, b, c):
	global d, m, y
	if c < 1 or c > 99:
		return False
	if b < 1 or b > 12:
		return False
	if a < 1 or a > lim[leap (c)][b - 1]:
		return False
	if y - c > 18:
		return True
	if y - c < 18:
		return False
	if m - b > 0:
		return True
	if m - b < 0:
		return False
	if d - a > 0:
		return True
	if d - a < 0:
		return False
	return True

d, m, y = [int (x) for x in sys.stdin.readline ().split ('.')]
a, b, c = [int (x) for x in sys.stdin.readline ().split ('.')]
if do (a, b, c) or do (a, c, b) or do (b, a, c) or \
   do (b, c, a) or do (c, a, b) or do (c, b, a):
	print ('YES')
else:
	print ('NO')


import sys

profit = 0
initial = (list(map(int, sys.stdin.readline().split())))
num_planet = initial[0]
num_goods = initial[1]
capacity = initial[2]
stonks = []
for i in range(0, num_planet):
    #print('Name planetu')
    name_Planet = str(sys.stdin.readline())
    planet = []
    for j in range (0, num_goods):
        elem = (list(map(int,sys.stdin.readline().split())))
        planet.append(elem)
    stonks.append(planet)
def Solution():
    global profit
    for i in range(0, len(stonks)):
        for j in range(0, len(stonks)):
            tmp = []
            for k in range(0, num_goods):
                if stonks[i][k][0] < stonks[j][k][1]:
                    res = stonks[j][k][1] - stonks[i][k][0]
                    a = (res, stonks[i][k][2])
                    tmp.append(a)
                else:
                    pass
            if len(tmp) > 0:
                sort_tmp = sorted(tmp, key = lambda x: (-x[0]))
                y = 0

                for y in range(0, capacity):
                    local_profit = 0
                    i_in_list = 0
                    if y == capacity:
                        break
                    for x in range(0, len(sort_tmp)):
                        for z in range(0, sort_tmp[i_in_list][1]):
                            if sort_tmp[i_in_list][1] == 0:
                                break
                            local_profit += sort_tmp[i_in_list][0]
                            y+=1
                            if z == sort_tmp[i_in_list][1]:
                                break
                            if y > capacity -1 or x == len(sort_tmp):
                                break
                        if y > capacity -1 or x == len(sort_tmp):
                            break
                        i_in_list += 1

                    profit = local_profit if local_profit > profit else profit

Solution()
print(profit)


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

def avg(arr):
	return sum(arr) / n
ans = 0

while avg(l) < 4.5:
	l[ans] = 5
	ans += 1

print(ans)


from math import sqrt

class vector:
	def __init__(self, _x = 0, _y = 0):
		self.x = _x
		self.y = _y
	def len(self):
		return sqrt(self.x ** 2 + self.y ** 2)
	def len_sq(self):
		return self.x ** 2 + self.y ** 2
	def __mul__(self, other):
		if (type(self) == type(other)):
			return self.x * other.x + self.y * other.y
		return vector(self.x * other, self.y * other)
	def __mod__(self, other):
		return self.x * other.y - self.y * other.x
	def normed(self):
		length = self.len()
		return vector(self.x / length, self.y / length)
	def normate(self):
		self = self.normed()
	def __str__(self):
		return "(" + str(self.x) + ", " + str(self.y) + ")"
	def __add__(self, other):
		return vector(self.x + other.x, self.y + other.y);
	def __sub__(self, other):
		return vector(self.x - other.x, self.y - other.y);
	def __eq__(self, other):
		return self.x == other.x and self.y == other.y
	def rot(self):
		return vector(self.y, -self.x)

class line:
	def __init__(self, a = 0, b = 0, c = 0):
		self.a = a
		self.b = b
		self.c = c
	def intersect(self, other):
		d = self.a * other.b - self.b * other.a
		dx = self.c * other.b - self.b * other.c
		dy = self.a * other.c - self.c * other.a
		return vector(dx / d, dy / d)
	def fake(self, other):
		d = self.a * other.b - self.b * other.a
		return d
	def __str__(self):
		return str(self.a) + "*x + " + str(self.b) + "*y = " + str(self.c)

def line_pt(A, B):
		d = (A - B).rot()
		return line(d.x, d.y, d * A)

class circle:
	def __init__(self, O = vector(0, 0), r = 0):
		self.O = O
		self.r = r
	def intersect(self, other):
		O1 = self.O
		O2 = other.O
		r1 = self.r
		r2 = other.r
		if (O1 == O2):
			return []
		if ((O1 - O2).len_sq() > r1 ** 2 + r2 ** 2 + 2 * r1 * r2):
			return []
		rad_line = line(2 * (O2.x - O1.x), 2 * (O2.y - O1.y), r1 ** 2 - O1.len_sq() - r2 ** 2 + O2.len_sq())
		central = line_pt(O1, O2)
		M = rad_line.intersect(central)
		# print(M)
		if ((O1 - O2).len_sq() == r1 ** 2 + r2 ** 2 + 2 * r1 * r2):
			return [M]
		d = (O2 - O1).normed().rot()
		if (r1 ** 2 - (O1 - M).len_sq() < 0):
			return []
		d = d * (sqrt(r1 ** 2 - (O1 - M).len_sq()))
		return [M + d, M - d]
	def fake(self, other):
		O1 = self.O
		O2 = other.O
		r1 = self.r
		r2 = other.r
		if (O1 == O2):
			return 1
		if ((O1 - O2).len_sq() > r1 ** 2 + r2 ** 2 + 2 * r1 * r2):
			return 1
		rad_line = line(2 * (O2.x - O1.x), 2 * (O2.y - O1.y), r1 ** 2 - O1.len_sq() - r2 ** 2 + O2.len_sq())
		central = line_pt(O1, O2)
		return rad_line.fake(central)

# a = vector(3, 4)
# b = vector(4, 4)
# print(circle(vector(1, 2), 3).intersect(circle(vector(2, 1), 6)))
n = int(input())
arr = []
m = 1
for i in range(n):
	x, y, r = map(int, input().split())
	arr.append(circle(vector(x, y), r))
for i in range(n):
	for j in range(i + 1, n):
		m *= arr[i].fake(arr[j])
for i in range(n):
	arr[i].O = arr[i].O * m
	arr[i].r = arr[i].r * m
# print(m)
s = set()
V = 0
for i in range(n):
	for j in range(i + 1, n):
		tmp = arr[i].intersect(arr[j])
		for e in tmp:
			s.add((round(e.x, 6), round(e.y, 6)))
V += len(s)
E = 0

par = [i for i in range(n)]

def get_par(v):
	if (par[v] != v):
		par[v] = get_par(par[v])
	return par[v]
def unite(v, u):
	par[get_par(v)] = get_par(u)
for i in range(n):
	s = set()
	for j in range(n):
		tmp = arr[i].intersect(arr[j])
		if (len(tmp)):
			unite(i, j)
		for e in tmp:
			s.add((round(e.x, 	), round(e.y, 	)))
	E += len(s)
# print(V, E)
# print(len({get_par(i) for i in range(n)}))
print(E - V + 1 + len({get_par(i) for i in range(n)}))


s = input()
m = int(input())
pw = [0] * (len(s) + 1)
pw[0] = 1
for i in range(1, len(s) + 1):
	pw[i] = pw[i - 1] * 10 % m
cur = 0
for i in range(len(s)):
	cur *= 10
	cur += ord(s[i]) - ord('0')
	cur %= m
ans = cur
for i in range(1, len(s)):
	cur *= 10
	cur %= m
	cur -= ((ord(s[i - 1]) - ord('0')) * pw[len(s)] % m);
	cur += m
	cur %= m
	cur += ord(s[i - 1]) - ord('0')
	cur %= m
	if (s[i] != '0'):
		ans = min(ans, cur)
print(ans)


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

def is_prime(n: int) -> bool:
    sq = int(sqrt(n)) + 1
    for i in range(2, sq):
        if n % i == 0:
            return False

    return True

def solve(n: int) -> int:
    for m in range(1, 1001):
        ans = n*m + 1
        if not is_prime(ans):
            return m

print(solve(n))


a = map(int, raw_input().split())
b = map(int, raw_input().split())
set = 0
for i in xrange(0, 101):
    for j in xrange(0, 101):
        x1 = b[1] + i * b[0]
        x2 = a[1] + j * a[0]
        if x1 == x2:
            print x1
            set = 1
            break
    if set==1:
        break
if set== 0:
    print -1


n    = int(input())
p    = list(map(int, input().split()))
g    = {}
deg  = {}
first  = []
circle = {}
ans  = []

def push_d(deg, u, val):
    if u not in deg:
        deg[u] = 0
    deg[u] += val

def push_g(g, u, v):
    if u not in g:
        g[u] = []
    g[u].append(v)

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

def total(arr):
    cur=1
    for x in arr:
        cur = cur // gcd(cur, x) * x
    return cur

def process(g, deg, deg0, u):
    if u in g:
        for v in g[u]:
            push_d(deg, v, -1)

            if deg[v] == 0:
                deg0.append(v)

def bfs(u):
    S = [u]
    used[u]   = 1
    circle[u] = 1
    i = 0
    while i < len(S):
        u = S[i]
        if u in g:
            for v in g[u]:
                if used[v] == 0:
                    used[v] = 1
                    circle[v] = 1
                    S.append(v)
        i+=1
    return len(S)

def bfs2(u):
    S = [u]
    start = 0
    i = 0
    while i < len(S):
        u = S[i]
        if u in g:
            for v in g[u]:
                if used[v] == -1:
                    S.append(v)
                else:
                    start = used[v]
        i+=1

    for u in S[::-1]:
        start  += 1
        used[u] = start

    return start

for u, v in enumerate(p):
    u+=1

    push_d(deg, v, 1)
    push_g(g, u, v)

deg0  = [x for x in range(1, n+1) if x not in deg]
first = [x for x in deg0]
used  = [0 for x in range(n+1)]

while len(deg0) > 0:
    u = deg0.pop()
    used[u] = 1
    process(g, deg, deg0, u)

cnt = []
for u in range(1, n+1):
    if used[u] == 0:
        cnt.append(bfs(u))

used = [-1 for x in range(n+1)]
for u in circle:
    used[u] = 0

max_ = 0
for u in first:
    max_ = max(max_, bfs2(u))

cur = total(cnt)
ans = cur
while ans<max_:
    ans+=cur
print(ans)


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

if b - a == c - b == d - c:
    print(d + (d - c))
elif b * b == a * c and c * c == b * d and (d * d) % c == 0:
    print((d * d) // c)
else:
    print(42)


string = raw_input()
new_string = ""
aux = True

for i in string:
    if string[0] == "9" and aux:
        new_string += i
        aux = False

    elif i < "5":
        new_string += i

    else:
        new_string += str((9 - int(i)))

print new_string


l = list(map(int,input().split()))
a = l[0]
b = l[1]
n = l[2]

def gcd(x,y):
    l = []
    for i in range(1,min(x,y)+1):
        if x % i == 0 and y % i == 0 :
            l.append(i)
    return max(l)
x = gcd(a,n)
y = gcd(b,n)
i = 1
while x <= n or y <= n :
    if i % 2 == 0 :
        n -= gcd(b,n)
    else :
        n -= gcd(a,n)
    i += 1

if i % 2 == 0 :
    print("0")
else :
    print("1")


def illegal(b):
    if abs(b.count('X')-b.count('0'))>1:
        return True
    if b.count('0')>b.count('X'):
        return True
    if win('X') and win('0'):
        return True
    if win('0') and b.count('X')>b.count('0'):
        return True
    if win('X') and b.count('0')>=b.count('X'):
            return True
    return False

def win(p):
    if bord[0]==bord[1]==bord[2]==p:
        return True
    if bord[3]==bord[4]==bord[5]==p:
        return True
    if bord[6]==bord[7]==bord[8]==p:
        return True
    if bord[0]==bord[3]==bord[6]==p:
        return True
    if bord[1]==bord[4]==bord[7]==p:
        return True
    if bord[2]==bord[5]==bord[8]==p:
        return True
    if bord[0]==bord[4]==bord[8]==p:
        return True
    if bord[2]==bord[4]==bord[6]==p:
        return True
    return False

def draw():
    if bord.count('.')==0:
        return True
    return False

def turn():
    if bord.count('.')>0:
        if bord.count('X')==bord.count('0'):
            return 'first'
        else:
            return 'second'
    else:
        return 'false'

bord=[]
for i in range (3):
    s=raw_input().strip()
    l=list(s)
    bord+=l
if not illegal(bord):
    if win('X'):
        print 'the first player won'
    elif win('0'):
        print 'the second player won'
    elif draw():
        print 'draw'
    else:
        print turn()
else:
    print 'illegal'


rps = {
  "[]": 0,
  "8<": 1,
  "()": 2
}

s = input()
t = input()
n = len(s)//2
score = 0
for i in range(n):
  res = (rps[s[2*i:2*i+2]] - rps[t[2*i:2*i+2]] + 1) % 3 - 1
  score += res
if score > 0:
  print("TEAM 1 WINS")
elif score < 0:
  print("TEAM 2 WINS")
else:
  print("TIE")


a=input()
b=input()
if len(str(b))>len(str(a)):
	a=list(str(a))
	a.sort()
	print ''.join(a[::-1])
else:
	z=list(str(a))
	x=[0 for i in range(10)]
	for i in range(len(z)):
		x[int(z[i])]+=1
	ans=''
	b=str(b)
	flag=1
	for i in range(len(z)):
		remain=(b[i+1:])
		if flag:
			for j in range(int(b[i]), -1, -1):
				if x[j]:
					remain2=''
					x[j]-=1
					for k in range(10):
						remain2+=str(k)*x[k]
					x[j]+=1
					if j==int(b[i]):
						if remain2>remain:
							continue
					x[j]-=1
					if j!=int(b[i]):
						flag=0
					ans+=str(j)
					break
		else:
			for j in range(9, -1, -1):
				if x[j]:
					ans+=str(j)
					x[j]-=1
					break

	print ans


l1,r1,l2,r2=map(int,raw_input().split())
l=[l1,l2]
r=[r1,r2]
def nextwhere(l,s):
    fs=2**s
    st=2**(s+1)
    return l if l%st==fs else l+(st-(l-fs)%st)
ans=0
for s in xrange(31):
    z=[list(),list()]
    for hui in xrange(2):
        f=list()
        t=l[hui]-1
        for j in xrange(3):
            t=nextwhere(t+1,s)
            if t>r[hui]:
                break
            f.append(t)
        if len(f)==0:
            continue
        elif len(f)==1:
            z[hui].append((min(f[0]-l[hui],2**s-1),min(r[hui]-f[0],2**s-1)))
        elif len(f)==2:
            z[hui].append((min(f[0]-l[hui],2**s-1),2**s-1))
            z[hui].append((2**s-1,min(r[hui]-f[1],2**s-1)))
        else:
            z[hui].append((2**s-1,2**s-1))
    for i in z[0]:
        for j in z[1]:
            ans=max(ans,min(i[0],j[0])+min(i[1],j[1])+1)
print ans


n=input()
line=raw_input()
inds=[]
for i in range(n):
    if line[i]=='*':
        inds.append(i)

for j in range(len(inds)-1):
    for k in range(j+1,len(inds)):
        dif=inds[k]-inds[j]
        if inds[k]+dif in inds and inds[k]+2*dif in inds and inds[k]+3*dif in inds:
            print("yes")
            quit()

print("no")


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

from itertools import combinations, product

n = int(raw_input())
rmax = 0
intervals = []
for _ in xrange(n):
    l, r = map(int, raw_input().split())
    rmax = max(rmax, r)
    intervals.append((l, r))
INDS = range(len(intervals))

def prob_smaller_equal(ints, val):
    res = 1.0
    for l, r in ints:
        d = min(val + 1 - l, r + 1 - l)
        if d <= 0:
            return 0.0
        res *= float(d) / (r + 1 - l)
        if res == 0.0:
            return 0.0
    return res

def prob_smaller(ints, val):
    res = 1.0
    for l, r in ints:
        d = min(val - l, r + 1 - l)
        if d <= 0:
            return 0.0
        res *= float(d) / (r + 1 - l)
        if res == 0.0:
            return 0.0
    return res

def prob_greater(ints, val):
    res = 1.0
    for l, r in ints:
        d = min(r - val, r + 1 - l)
        if d <= 0:
            return 0.0
        res *= float(d) / (r + 1 - l)
        if res == 0.0:
            return 0.0
    return res

def prob_equal(ints, val):
    res = 1.0
    for l, r in ints:
        if not (l <= val <= r):
            return 0.0
        res *= 1.0 / (r + 1 - l)
    return res

def combos(ints, minn, maxn):
    for ntie in xrange(minn, maxn + 1):
        for c in combinations(ints, r=ntie):
            yield c

def prod(cache, inds, price):
    res = 1.0
    for i in inds:
        res *= cache[i][price]
        if res == 0.0:
            return 0.0
    return res

cache_smaller = [[0] * 10002 for _ in xrange(5)]
cache_smaller_equal = [[0] * 10002 for _ in xrange(5)]
cache_equal = [[0] * 10002 for _ in xrange(5)]
cache_greater = [[0] * 10002 for _ in xrange(5)]
for i, (l, r) in enumerate(intervals):
    for price in xrange(1, rmax + 1):
        cache_smaller[i][price] = prob_smaller([(l, r)], price)
        cache_smaller_equal[i][price] = prob_smaller_equal([(l, r)], price)
        cache_equal[i][price] = prob_equal([(l, r)], price)
        cache_greater[i][price] = prob_greater([(l, r)], price)

res = 0
for price in xrange(1, rmax + 1):
    # case 1: 1 larger  1+ equal  * smaller
    for ind1 in INDS:
        other = [i for i in INDS if i != ind1]
        res += (
            price *
            prod(cache_greater, (ind1,), price) *
            (
                prod(cache_smaller_equal, other, price) -
                prod(cache_smaller, other, price)
            )
        )

    # case 2: 0 larger  2+ equal  * smaller
    for ind1 in INDS:
        for ind2 in xrange(ind1 + 1, len(intervals)):
            smaller = [ii for ii in xrange(ind2) if ii != ind1]
            smaller_equal = [ii for ii in xrange(ind2 + 1, len(intervals))]

            assert len(smaller) + len(smaller_equal) + 2 == len(intervals)

            res += (
                price *
                prod(cache_equal, [ind1, ind2], price) *
                prod(cache_smaller, smaller, price) *
                prod(cache_smaller_equal, smaller_equal, price)
            )

print res


n = int(input())
s = input()
dic = [chr(65+i) for i in range(26)]
dic = dic+dic
target = "ACTG"
cost=999999999999
loc = {}
for i in range(len(dic)):
    if dic[i] in loc:
        loc[dic[i]].append(i)
    else:
        loc[dic[i]] = [i]

for i in range(n-3):
    loc_cost = 0
    for j in range(4):
        cur= target[j]
        ele = s[i+j]
        loc_cost += min(abs(loc[ele][0]-loc[cur][0]),
                        abs(loc[ele][0]-loc[cur][1]),
                        abs(loc[ele][1]-loc[cur][0]),
                        abs(loc[ele][1]-loc[cur][1]),
                        )
    cost = min(cost,loc_cost)
print(cost)


mod = int(1e9+7)

def ksm(a: int, k: int) -> int:
    res = 1
    while k:
        if k & 1:
            res = (res * a) % mod
        a = (a*a) % mod
        k >>= 1
    return res

m = int(input())
dp = [0 for i in range(m + 1)]
dp[1] = 0
ans = 0
inv = ksm(m, mod - 2)
for i in range(2, m+1):
    fac = []
    j = 1
    while j*j <= i:
        if i % j == 0:
            fac.append(j)
            if(j != i//j):
                fac.append(i//j)
        j += 1
    fac.sort()
    a = [0 for j in range(len(fac))]
    a[-1] = m // fac[-1]
    for j in range(len(fac) - 2, -1, -1):
        a[j] = m // fac[j]
        for k in range(j+1, len(fac)):
            if fac[k] % fac[j] == 0:
                a[j] -= a[k]
        dp[i] += ((dp[fac[j]] + 1) * a[j] * inv) % mod
    dp[i] += a[-1] * inv % mod
    dp[i] = (dp[i] * m * ksm(m - a[-1], mod - 2)) % mod
    ans = (ans + dp[i] * inv) % mod

print((ans + 1) % mod)


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


a,ta=map(int,input().split())
b,tb=map(int,input().split())
h,m=map(int,input().split(':'))
sa=h*60+m
ea=sa+ta
c=0
i=0
sb=0
eb=sa
while sb<ea and sb<=1439:

    if eb>sa:
        c+=1
    sb=5*60+b*i
    eb=sb+tb
    i+=1
print(c)


import sys

def read():
    length = sys.stdin.readline()
    word = sys.stdin.readline()
    length.strip()
    word.strip()
    newlen = int(length)
    point = 0
    points = []
    lastknown = ''
    index = []
    statement = True
    for x in xrange(newlen):
        if word[x] == 'a' or word[x] == 'e' or word[x] == 'i' or word[x] == 'o' or word[x] == 'u' or word[x] == 'y':
            if lastknown == 'a' or lastknown == 'e' or lastknown == 'i' or lastknown == 'o' or lastknown == 'u' or lastknown == 'y':
                y = x
                while statement == True:
                    if word[y] == 'a' or word[y] == 'e' or word[y] == 'i' or word[y] == 'o' or word[y] == 'u' or word[y] == 'y':
                        point = y
                        y += 1
                    else:
                        points.append((x, point))
                        statement = False
                        break
            else:
                lastknown = word[x]
        else:
            lastknown = word[x]
            statement = True
    for thing in reversed(points):
        word = word[:thing[0]] + word[thing[1]+1:]
    sys.stdout.write(word)
    sys.stdout.flush()

if __name__ == '__main__':
    read()


from math import factorial
#print(" ".join(map(str,array)))
n = int(input())
print((factorial(n)*2)//(n*n))


n = int(raw_input())

MAX = 9*11

def check(x):
  if x < 0: return False
  return sum(map(int, str(x))) + x == n

res = filter(check, range(n - MAX, n))
print len(res)
for x in res:
  print x


n = int(raw_input())
a = map(int, raw_input().split())
if a[0] % 2 == 0 or a[-1] % 2 == 0:
  print "No"
elif n % 2:
  print "Yes"
else:
  print "No"


#!/usr/bin/env python3

N = int(input())
print(int(N*3/2))


import math
def countDivisors(n) :
    cnt = 0
    for i in range(1, (int)(math.sqrt(n)) + 1) :
        if (n % i == 0) :

            # If divisors are equal,
            # count only one
            if (n / i == i) :
                cnt = cnt + 1
            else : # Otherwise count both
                cnt = cnt + 2

    return cnt
# Driver Code
b=int(input())
print(countDivisors(b))


import math, sys
from collections import defaultdict, Counter, deque

INF = float('inf')
MOD = 1000000007

def gcd(a, b):
	while b:
		a, b = b, a%b
	return a

def isPrime(n):
	if (n <= 1):
		return False
	i = 2
	while i ** 2 <= n:
		if n % i == 0:
			return False
		i += 1
	return True

def primeFactors(n):
	factors = []
	i = 2
	while i ** 2 <= n:
		while n % i == 0:
			factors.append(i)
			n //= i
		i += 1
	if n > 1:
		factors.append(n)
	return factors

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

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

def main():
	d, s = vars()
	arr = []
	for i in range(d):
		x, y = vars()
		arr.append((x, y))

	ans = []
	ns = 0
	for x, y in arr:
		ans.append(y)
		ns += y

	ns -= s
	if ns >= 0:
		for i in range(d):
			lower = arr[i][0]
			temp = min(ns, arr[i][1] - arr[i][0])
			ans[i] -= temp
			ns -= temp
		if ns:
			print('NO')
		else:
			print('YES')
			print(*ans)
	else:
		print('NO')

if __name__ == "__main__":
	# t = int(input())
	t = 1
	for _ in range(t):
		main()


#!/usr/bin/env python
# http://www.zhihua-lai.com/acm

n = int(raw_input())
ans = 0

def C(i, n):
    return any((ch for ch in str(i) if ch in n))

for i in xrange(1, n + 1):
    if i * i > n:
        break
    if n % i == 0:
        if C(i, str(n)):
            ans += 1
        if i * i != n:
            if C(n / i, str(n)):
                ans += 1

print ans


def yoba(a, k):

    if not a:

        return []

    elif not k:

        return a

    else:

        m = max(a[:k + 1])
        mi = a.index(m)
        if m > a[0]:

            a[1:mi + 1] = a[:mi]
            a[0] = m
            k -= mi

        return [a[0]] + yoba(a[1:], k)

a, k = str.split(input())
k = int(k)

print(str.join("", yoba(list(a), k)))


#!/usr/bin/env python3

from collections import namedtuple
from itertools   import permutations

Point = namedtuple("Point", "x y")

try:
    while True:
        p = [Point(*map(int, input().split())) for i in range(3)]
        a, b, c = p
        if a.x == b.x == c.x or a.y == b.y == c.y:
            print(1)
        else:
            for a, b, c in permutations(p):
                if a.x == b.x and not a.y < c.y < b.y and not b.y < c.y < a.y:
                    print(2)
                    break
                if a.y == b.y and not a.x < c.x < b.x and not b.x < c.x < a.x:
                    print(2)
                    break
            else:
                print(3)

except EOFError:
    pass


# maa chudaaye duniya
n = int(input())
parents = [i for i in range(n+1)]
ranks = [1 for i in range(n+1)]

def find(x):
	if parents[x] != x:
		parents[x] = find(parents[x])
	return parents[x]

def union(x, y):
	xs = find(x)
	ys = find(y)
	if xs == ys:
		return
	if ranks[xs] > ranks[ys]:
		parents[ys] = xs
	elif ranks[ys] > ranks[xs]:
		parents[xs] = ys
	else:
		parents[ys] = xs
		ranks[xs] += 1

for _ in range(int(input())):
	u, v = map(int, input().split())
	union(u, v)

# print(parents)
rejects = set([])
for _ in range(int(input())):
	p, q = map(int, input().split())
	ps = find(p)
	qs = find(q)
	if ps == qs:
		rejects.add(ps)
ps = {}
for i in range(1, n+1):
	p = find(i)
	if p not in rejects:
		if p in ps:
			ps[p] += 1
		else:
			ps[p] = 1
# print(ps)
ans = 0
for i in ps:
	ans = max(ans, ps[i])
print(ans)


s = input()
count_4 = s.count('4')
count_7 = s.count('7')
if count_4==0 and count_7==0:
    print(-1)
elif count_4==0 and count_7!=0:
    print('7')
elif count_4!=0 and count_7==0:
    print('4')
elif count_4==count_7:
    print('4')
elif count_4 > count_7:
    print('4')
elif count_4 < count_7:
    print('7')


#Lorenzo by Esii in Site :D

from math import sqrt,ceil
ls=[]
def primeFactors(n):
    while (n % 2 == 0):
        ls.append(2)
        n = n / 2
    for i in range(3, ceil(sqrt(n))+1, 2):
        while (n % i == 0):
            ls.append(int(i))
            n /= i

    if n > 2:
        ls.append(int(n))

n,k=map(int,input().split())
primeFactors(n)
ln=len(ls)
if(ln<k):
    print(-1)
elif(ln==k):
    print(*ls)
else:
    tmp=ls[k-1]
    for i in range(k,ln):
        tmp*=ls[i]
    print(*ls[:k-1],tmp)


x,y,m = map(int,input().split())
if(x > y):
	x,y = y,x
if(y >= m):
	print('0')
elif(x+y <= x):
	print('-1')
else:
	ans = (y-x+y-1)//y
	x += y*ans
	while(x < m):
		x,y = x+y,x
		ans += 1
	print(ans)


# http://codeforces.com/contest/771/problem/D
"""
DP-solution.

For each state (v, k, x, v_is_last_letter) we trial a step along the v, k and x
axes and check that
dp[future_state] = min(dp[future_state], dp[state] + cost_of_move)
Hence this implicitly reults in the one with least cost.

V, K, X are arrays that contain the number of occurences of v, k, x at the i'th
index of s.
"""

def cost_of_move(state, ss_ind):
    """
    eg. ss = s[0:K.index(k+1)]
    Note: ss includes the i+1'th occurence of letter I. We hence want
    ss = s[0:ss_ind-1]
    And then we cound the number of occurences of V, K, X in this substring.

    However, we don't need ss now - this info is contained in lists V, K, X.
    """

    curr_v, curr_k, curr_x = state
    cost = sum([max(0, V[ss_ind-1] - curr_v), max(0, K[ss_ind-1] - curr_k),
                max(0, X[ss_ind-1] - curr_x)])
    return cost

if __name__ == "__main__":

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

    V = [s[0:i].count('V') for i in range(n+1)]
    K = [s[0:i].count('K') for i in range(n+1)]
    X = [(i - V[i] - K[i]) for i in range(n+1)]

    # Initialising
    n_v, n_k, n_x = V[n], K[n], X[n]

    dp = [[[[float('Inf') for vtype in range(2)] for x in range(n_x+1)]
           for k in range(n_k+1)] for v in range(n_v+1)]
    dp[0][0][0][0] = 0

    for v in range(n_v + 1):
        for k in range(n_k + 1):
            for x in range(n_x + 1):
                for vtype in range(2):
                    orig = dp[v][k][x][vtype]
                    if v < n_v:
                        dp[v+1][k][x][1] = min(dp[v+1][k][x][vtype],
                                               orig + cost_of_move([v, k, x], V.index(v+1)))
                    if k < n_k and vtype == 0:
                        dp[v][k+1][x][0] = min(dp[v][k+1][x][0],
                                               orig + cost_of_move([v, k, x], K.index(k+1)))
                    if x < n_x:
                        dp[v][k][x+1][0] = min(dp[v][k][x+1][0],
                                               orig + cost_of_move([v, k, x], X.index(x+1)))
    print(min(dp[n_v][n_k][n_x]))


# your code goes here
import sys
n,m=map(int,sys.stdin.readline().split(" "))
visited=[0]*100001
val=[1000000000000]*100001
a=[]
a.append(n)
val[n]=0
topval=n

while(len(a)>0):

    topval=a[0]

    a.pop(0)
    if(val[topval-1]>val[topval]+1 and topval>1):
        a.append(topval-1)
        val[topval-1]=val[topval]+1
        if(topval-1==m):
            break

    if(val[2*topval]>val[topval]+1 and 2*topval<=40000):
        a.append(2*topval)

        val[2*topval]=val[topval]+1
        if(2*topval==m):
            break

print val[m]


def forest(n):
    result = 0
    for i in range(1, n + 1):
        for j in range(i, n + 1):
            q = i ^ j
            if j <= q <= n and q + i > j and q + j > i and i + j > q:
                result += 1
    return result

print(forest(int(input())))


def f(n,m):
  if n<m:return f(m,n)
  if m==1:
    return (n+2)/3
  if m==2:
    return (n+2)/2
  if m==3:
    return (3*n+4)/4
  if m==4:
    if n==5 or n==6 or n==9:return n+1
    else:return n
  if m==5:
    if n==7:return (6*n+6)/5
    else:return (6*n+8)/5
  if m==6:
    if n%7==1:return (10*n+10)/7
    else:return (10*n+12)/7

def main():
  n,m=map(int, raw_input().split())
  print n*m-f(n,m)

main()


n = int(raw_input())
l = sorted([i for i in map(int,raw_input().split())])[::-1]
ans , last = 0 , 1000000007

for i in l:
	if i < last:
		ans += i
		last = i

	else:
		if last - 1 <= 0:
			break
		ans += min(i , last - 1)
		last = min(i ,last - 1)

print ans


import math
n, t = map(int, raw_input().split())

for i in range(55):
    comb = [[0]*55 for _ in range(55)]
for i in range(55):
    for j in range(i+1):
        if (i == 0 or j == 0): comb[i][j] = 1
        else:
            comb[i][j] = comb[i-1][j] + comb[i-1][j-1]

def gao(m, k):
    ret = 0
    while m > 0:
        p = int(math.log(m, 2))
        ret += comb[p][k]
        k -= 1
        m -= 2**p
        if m == 0:
            if k == 0:
                ret += 1
            break
        if k < 0:
            break
    return ret

tmp = 0
num = t
while (num > 0):
    if (num % 2 == 1):
        tmp += 1
    num /= 2
    if (tmp > 1):
        break
if (tmp > 1):
    print 0
else:
    k = int(math.log(t, 2))
    ans = gao(n+1, k+1)
    if t == 1:
        ans -= 1
    print ans


n=int(input())
if n<3:print(-1)
else:
    for i in range(n,0,-1):
        print(i,end=' ')


import sys
range = xrange
input = raw_input

MOD = 998244353

class sumseg:
    def __init__(self,n):
        m = 1
        while m<n:m*=2
        self.n = n
        self.m = m
        self.data = [0]*(n+m)
    def summa(self,l,r):
        l+=self.m
        r+=self.m
        s = 0
        while l<r:
            if l%2==1:
                s+=self.data[l]
                l+=1
            if r%2==1:
                r-=1
                s+=self.data[r]
            l//=2
            r//=2
        return s%MOD
    def add(self,ind,val):
        ind += self.m
        while ind>0:
            self.data[ind] = (self.data[ind]+val)%MOD
            ind//=2

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

switchers = [0]*(n+1)

for h in range(1,n+1):
    DP = sumseg(n+1)#[0]*(n+1)
    DP.add(0,2)#DP[0] = 2
    max_width = (k+h-1)//h - 1
    for i in range(1,n+1):
        a = max(i-max_width,0)
        b = i
        if a<b:
            DP.add(i,DP.summa(a,b))#DP[i] = sum(DP[a:b])%MOD

    switchers[h]=DP.summa(n,n+1)

for h in range(1,n):
    switchers[h] = (switchers[h]-switchers[h+1])%MOD

switchers2 = [0]*(n+1)

for h in range(1,n+1):
    DP = sumseg(n+1)#[0]*(n+1)
    DP.add(0,1)#DP[0] = 2
    max_width = h
    for i in range(1,n+1):
        a = max(i-max_width,0)
        b = i
        if a<b:
            DP.add(i,DP.summa(a,b))#DP[i] = sum(DP[a:b])%MOD

    switchers2[h]=DP.summa(n,n+1)

summa = 0
for h in range(1,n+1):
    summa = (summa + switchers[h]*switchers2[h])%MOD
print summa


def solve(l, b):

    years = 0

    while l <= b:
        l *= 3
        b *= 2
        years += 1

    return years

if __name__ == "__main__":
    l,b = map(int,raw_input().split(" "))
    print solve(l,b)


def main():
    a, b, c = map(int, input().split())
    print((b + a - 1) * (c + a - 1) - a * (a - 1))

if __name__ == '__main__':
    main()


r=lambda:raw_input()
a=r();b=r();c=r()
ans='YES'
c=list(c)
for i in range(len(a)):
    if(a[i] in c):
        c[c.index(a[i])]='-'
    else:
        ans='NO'
        break
for i in range(len(b)):
    if(b[i] in c):
        c[c.index(b[i])]='-'
    else:
        ans='NO'
        break
if(c.count('-')!=len(c)):
    ans='NO'
print ans


def main():
    Current_HP = int(input())
    remainder = Current_HP % 4
    Current_rank = ""
    if remainder == 1 :
        Current_rank = "A"
        added_number = 0
        print(str(added_number) +" "+ str(Current_rank))

    elif remainder == 2:
        Current_rank = "B"
        added_number = 1
        print(str(added_number) +" "+ str(Current_rank))

    elif remainder == 3:
        Current_rank = "A"
        added_number = 2
        print(str(added_number) +" "+ str(Current_rank))

    elif remainder == 0 :
        Current_rank = "A"
        added_number = 1
        print(str(added_number) +" "+ str(Current_rank))
if __name__ == '__main__': main()


n=int(input())
a=[]
b=[]
for i in range(n):
    a.append(input())
for i in range(n):
    b.append(input())

def h(d):
    c=[]
    for i in range(n):
        c.append(d[n-i-1])
    return c
def r(d):
    c=[]
    for i in range(n):
        temp=""
        for j in range(n):
            temp+=d[j][n-i-1]
        c.append(temp)
    return c
yes=0
for i in range(4):
    if a==b:
        print('YES')
        yes=1
        break
    a=r(a)
if yes==0:
    a=h(a)
    for i in range(4):
        if a==b:
            print('YES')
            yes=1
            break
        a=r(a)
if yes==0:
    print('NO')


from math import floor
n,s = map(int,raw_input().split())
if ((n==1) & (s==0)):
    print 0,0
elif ((n > 0) & (s < 1)):
    print -1,-1
elif s > n*9:
    print -1,-1
else:
    res1 = 10**(n-1)
    for i in range(s-1):
        res1+= 10**(i//9)
    res2 = 10**(n-1)
    for i in range(1,s):
        ss = int(floor(i//9))
        #print i,ss
        res2 += 10**(n-1-(ss))

    print res1,int(res2)


import sys

n, m = [int(i) for i in sys.stdin.readline().split()]
s = [int(i) for i in sys.stdin.readline().split()]

ans = [0] * n
for i in range(m):
    for j in range(s[i]-1, n):
        if ans[j] == 0:
            ans[j] = s[i]
        else:
            break

for i in ans:
    print i,


import sys
input = sys.stdin.readline

n, m = map(int, input().split())
g = [[] for _ in range(n)]
g_inv = [[] for _ in range(n)]
for _ in range(m):
    u, v = map(int, input().split())
    u, v = u-1, v-1
    g[u].append(v)
    g_inv[v].append(u)

k = int(input())
P = list(map(int, input().split()))
P = [p-1 for p in P]

from collections import deque
q = deque()
visit = [-1]*n
q.append(P[-1])
visit[P[-1]] = 0
while q:
    v = q.popleft()
    for u in g_inv[v]:
        if visit[u] == -1:
            visit[u] = visit[v]+1
            q.append(u)

min_ = 0
max_ = 0
for i in range(k-1):
    v = P[i]
    flag1 = False
    flag2 = False
    for u in g[v]:
        if u == P[i+1] and visit[u] != visit[v]-1:
            flag1 = True
        elif  u != P[i+1] and visit[u] == visit[v]-1:
            flag2 = True
        else:
            pass
    if flag1:
        min_ += 1
    if flag2:
        max_ += 1

print(min_, max_)


v =[ "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
a = input()
b = input()
q = v.index(a)
f =0
z =[q,q+3,q+2]
for i in z:
	if v[i%7]	== b:
		f=1
if f ==1:
	print("YES")
else:
	print("NO")


n = int(input())
count = 0
while True:
    if n >= 100:
        count+=(n//100)
        n%=100

    elif n >= 20:
        count+=(n//20)
        n%=20
    elif n >= 10:
        count+=(n//10)
        n%=10
    elif n >= 5:
        count+=(n//5)
        n%=5
    elif n >= 1:
        count+=(n//1)
        n%=1
    else:
        print(count)
        break


n,k=map(int,input().split())
b=list(map(int,input().split()))
s=input()
a=[]
if k==1:
    print(-1)
    exit()
for i in range(n):
    a.append((b[i],s[i]))
a.sort(reverse=True)
i=0
j=0
m1=0
q1=False
q2=False
while i!=k:
    if a[j][1]!='R':
        m1+=a[j][0]
        g=j+0
        if a[j][1]=='W':
            q1=True
        else:
            q2=True
        i+=1
    j+=1
    if j==n and i!=k:
        m1=0
        break
else:
    if not (q1 and q2):
        m1-=a[g][0]
        for i in range(g+1,n):
            if q1 and a[i][1]=='O' or q2 and a[i][1]=='W':
                m1+=a[i][0]
                break
        else:
            m1=0
i=0
j=0
m2=0
q1=False
q2=False
while i!=k:
    if a[j][1]!='W':
        m2+=a[j][0]
        g=j+0
        if a[j][1]=='R':
            q1=True
        else:
            q2=True
        i+=1
    j+=1
    if j==n and i!=k:
        m2=0
        break
else:
    if not (q1 and q2):
        m2-=a[g][0]
        for i in range(g+1,n):
            if q1 and a[i][1]=='O' or q2 and a[i][1]=='R':
                m2+=a[i][0]
                break
        else:
            m2=0
if m1 or m2:
    print(max(m1,m2))
else:
    print(-1)


n,m,k = list(map(int, input().split(" ")))
l = True
if k%2 == 0:
    l = False
    d = k/2
else:
    d = (k+1)/2

col = int(((d-1)%m) +1)
row = int(((d-1)//m)+1)

if l:
    print(str(row), str(col), "L")
else:
    print(str(row), str(col), "R")


def GCD(a,b):
    if b>a:
        a,b=b,a
    while not b==0:
        a,b=b,a%b
    return(a)
def LCM(c,d):
    e=c*d
    return(e/GCD(c,d))

n, k = input().strip().split()
v=10**int(k)
print(int(LCM(int(n),v)))


#	!/bin/env python3
#	coding: UTF-8

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology and Management,Gwalior

#	Question Link
#	https://codeforces.com/problemset/problem/392/B
#

# ///==========Libraries, Constants and Functions=============///

import sys

inf = float("inf")
mod = 1000000007

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

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

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

# ///==========MAIN=============///

def main():
    dp = [[[0 for _ in range(3)] for _ in range(3)] for _ in range(43)]
    matrix = [[0 for _ in range(3)] for _ in range(3)]
    for i in range(3):
        matrix[i] = get_array()
    n = int(input())
    for i in range(1, n+1):
        for frm in range(3):
            for to in range(3):
                other = 3-frm-to
                if frm == to:
                    continue
                dp[i][frm][to] = dp[i-1][frm][other]+matrix[frm][to]+dp[i-1][other][to]
                c = dp[i-1][frm][to]+matrix[frm][other] + \
                    dp[i-1][to][frm]+matrix[other][to]+dp[i-1][frm][to]
                dp[i][frm][to] = min(c, dp[i][frm][to])
    print(dp[n][0][2])

if __name__ == "__main__":
    main()


h, m = map(int, raw_input().split(':'))
a = int(raw_input())

for _ in xrange(a):
    m += 1
    if m == 60:
        m = 0
        h = (h + 1) % 24

print "%02d:%02d" % (h, m)


a, b = map(int,raw_input().split())
print(a+b)


n,m,k=map(int,str(raw_input()).split())
mod=10**9+7
if n>m:
    n,m=m,n
if k==-1 and (n+m)%2==1:
    print 0
else:
    print pow(2,((n-1)*(m-1)),mod)


s=input()
c=0
d={'caps':0,'small':0,'digit':0}
if(len(s)<5):
    print('Too weak')
else:
    f=0
    for i in s:
        m=ord(i)
        if(d['small']==0 and m>=97 and m<=123):
            d['small']=1
            c+=1
        elif(d['caps']==0 and m>=65 and m<=91):
            d['caps']=1
            c+=1
        elif(d['digit']==0 and m>=48 and m<=57):
            d['digit']=1
            c+=1
        if(c==3):
            f=1
            break
    if(f==1):
        print('Correct')
    else:
        print('Too weak')


s = input().strip()
words = ["","","","the","","buffy","slayer","vampire"]
if len(s)==4:
    print("none")
else:
    target = words[len(s)]
    ans = ""
    for i in range(len(s)):
        a = ord(s[i])-ord('a')
        b = ord(target[i])-ord('a')
        ans += chr((a+b)%26 + ord('a'))
    print(ans)


n = input()
s = raw_input()

count = 0
max_val = 0

for i in range(n):
  if s[i] == s[i].upper() and s[i] != ' ':
    count = count + 1
    max_val = max(max_val, count)
  elif s[i] == ' ':
    count = 0

print max_val


# cook your dish here
def power(a,b):
    #temp=power(a,(b//2))
    if b==0:
        return 1
    temp=power(a,(b//2))
    if (b)%2==0:
        return 1*(temp*temp)%1000000007
    else:
        return (a)*(temp*temp)%1000000007
for _ in range(int(input())):
    n,m=map(int,input().split())

    res=power(n,m)%1000000007

    print(res%1000000007)


import math
l, r = map(int, raw_input().split(' '))
order = math.floor(math.log10(r))

x = int(max(l, min(5*10**order, r)))
phi = int(''.join(map(lambda e: chr(48 + 57 - (48 + int(e))), str(x))))

print x * phi


import sys
input = sys.stdin.buffer.readline
def print(val):
    sys.stdout.write(str(val) + '\n')

def inverse(n,primemod):
    return pow(n,primemod-2,primemod)

def choose(n,k,mod,factorials,inverses):
    return (factorials[n]*inverses[k]*inverses[n-k])% mod

def factorial_creator(n,mod):
    factorials = [1]
    curr = 1
    for i in range(1,n+1):
        curr = (curr*i) % mod
        factorials.append(curr)
    return factorials

def inverse_creator(n,k,mod,factorials):
    inverses = [1 for i in range(n-k+1)]
    current = inverse(factorials[n-k],mod)
    inverses[n-k] = current
    for i in range(n-k,0,-1):
        current = (current*i) % mod
        inverses[i-1] = current
    return inverses

def place_rooks(n,k,mod):
    if k >= n:
        return 0
    factorials = factorial_creator(n,998244353)
    inverses = inverse_creator(n,k,998244353,factorials)
    filled = n - k
    placements_per_filled = 0
    for i in range(filled):
        placements_per_filled += (((-1)**i)*choose(filled,i,mod,factorials,inverses)*pow(filled-i,n,mod)) % mod
        placements_per_filled %= mod
    if k == 0:
        total = (((factorials[n]*inverses[n-k]*inverse(factorials[k],mod))%mod)*placements_per_filled ) % mod
        return total
    total = ((2*(factorials[n]*inverses[n-k]*inverse(factorials[k],mod))%mod)*placements_per_filled ) % mod
    return total

n, k = map(int,input().split())
print(place_rooks(n,k,998244353))


n = input()
st = input()
print(st.count('R')+st.count('L')+1)


#Circle of Numbers
import math

def centre(n, pts):
    x, y = 0, 0
    for j in [7,11,13,17,19,23,29,31,37,1193,1663,2711,4007,65537]:
        if math.gcd(n,j) == 1:
            for i in range(n):
                k = int(pts[i])
                x += k*math.cos(math.pi * 2*i*j/n)
                y += k*math.sin(math.pi * 2*i*j/n)
            if not (abs(x) < 0.000001 and abs(y) < 0.000001):
                return 'NO'
    return 'YES'

def strconv(s):
    return [char for char in s]

n = int(input())
pts = strconv(input())
print(centre(n,pts))


n,m=map(int,input().split())
a=[0]*m
s = 0
for i in range(1,m+1):
	a[i*i%m]+=(n-i)//m+1
for i in range(m):
	s+=a[i]*a[-i]
print(s)


n=int(input())
for x in range(n+1,9013):
	s=str(x)
	if len(set(list(s)))==4:
		print x
		break


n, k, m = [int(i) for i in input().split()]
p = [int(i) for i in input().split()]
p.sort()
ans = 0
for i in range(n + 1):
    l = m
    for j in range(k):
        l -= p[j] * i
    if l < 0:
        break
    cr = i * k + i
    for j in range(k):
        if l < p[j]:
            break
        c = min(l // p[j], n - i)
        l -= p[j] * c
        cr += c
    ans = max(ans, cr)

print(ans)


n = input()

factorials = []
res = 1
for i in range(1,18):
	factorials.append(i*res)
	res *= i

l = 0
r = 10000000000

while l+1<r:
	m = (l+r)/2
	if m*(m-1)/2 < n:
		l = m
	else:
		r = m
print n - (l*(l-1)/2)


'''input
5
1 1 1 5 1

'''
from collections import defaultdict as df
from bisect import bisect_left as bl
import sys
sys.setrecursionlimit(100000)
n=input()
A=[int(x) for x in raw_input().split()]

lo=max(A)
hi=10**9
s1=sum(A)
def check(s):
    #for i in range(n):
    return s*n-s1>s1
ans=9999999999999
while lo <= hi:
    mid=(lo+hi)/2
    if check(mid):
        ans=min(ans,mid)
        hi = mid-1
    else:
        lo=mid+1
print ans


import math

def good(x):
    while x > 0:
        if x % 10 != 4 and x % 10 != 7:
            return False
        x //=10
    return True

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

l = 1
r = n
if n >= 15:
    l = n-14
if n <= 15 and math.factorial(n) < k:
    print(-1)
else:
    L = r - l + 1
    a = []
    for i in range(L):
        a.append(i)
    b = []
    k -= 1
    for i in range(L):
        x = k//math.factorial(L-i-1)
        y = a[x]
        b.append(y+l)
        a.remove(y)
        k -= x * math.factorial(L-i-1)
    c = []
    if 4 < l:
        c.append(4)
    if 7 < l:
        c.append(7)
    ans = 0
    while len(c) > 0:
        ans += len(c)
        cc = []
        for x in c:
            if x * 10 + 4 < l:
                cc.append(x * 10 + 4)
            if x * 10 + 7 < l:
                cc.append(x * 10 + 7)
        c = cc
    for i in range(L):
        if good(i+l) and good(b[i]):
            ans += 1
    print(ans)