def howmanyinlrneedk(l,r):
	n = r-l+1
	L = [n//3]*3
	if n%3==0:
		return L
	elif n%3==1 :
		L[l%3]+=1
		return L
	else :
		L[l%3]+=1
		L[(l+1)%3]+=1
		return L

[m,l,r] = [int(i) for i in input().split()]
[a,b,c] = howmanyinlrneedk(l,r)

def dp(n,rest):
	if n==1:
		if rest==0 : return a
		elif rest==1 : return c
		else : return b

	if rest==0 :
		return ((a*dp(n-1,0)+b*dp(n-1,1)+c*dp(n-1,2))%(10**9+7))
	elif rest==1:
		return ((c*dp(n-1,0)+a*dp(n-1,1)+b*dp(n-1,2))%(10**9+7))
	else  :
		return ((b*dp(n-1,0)+c*dp(n-1,1)+a*dp(n-1,2))%(10**9+7))

print(dp(m,0))


import math
n, k = map(int, raw_input().split())
def getalldivisors(n):
  m = n
  a = {}
  while m%2 == 0:
    a[2] = a[2]+1 if 2 in a else 1
    m /= 2
  for i in xrange(3, int(math.sqrt(m))):
    while m%i == 0:
      a[i] = a[i]+1 if i in a else 1
      m /= i
  if m > 2: a[m] = a[m]+1 if m in a else 1
  return a
a = getalldivisors(n)
maxk = 1
b = []
for key, val in a.items():
  maxk *= val
  b += [key for i in xrange(val)]
if k>maxk:
  print -1
else:
  t=1
  for i in xrange(k-1):
    t *= b[i]
    print b[i],
  print n/t


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

def check(x):
    z=0
    for i in tx:
        z+=int(t.count(i)/x)
        print(i)
    return z

maxi=[]
for i in tx:
    a=check(t.count(i))
    if(a>=n[0]):maxi.append(t.count(i))
maxi.sort()
if len(maxi)==0:print(0)
else: print(maxi[len(maxi)-1))


from fractions import gcd
from math import factorial, ceil, sqrt, atan2, log, pi, e, asin,acos, cos, sin
from itertools import *
from fractions import Fraction
import string
import copy
import random
import bisect
from decimal import *
def id_generator(size=20, chars=string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def mp():
    return map(int,str(raw_input()).split())

n,d=mp()
l=list(mp())
l.sort()
ans=10**18
for i in range(n):
	if (l[i]-l[0])>d:
		ans=n-i+1
		break
for i in range(n-1,-1,-1):
	if (l[-1]-l[i])>d:
		ans=min(ans,i)
		break
if ans=10**18:
	print 0
else:
	print ans


b = int(raw_input())

if b == 1:
    print 1
else:
    ans = 1
    for i in range(2,int(b**0.5)+1):
        count = 1
        while b%i == 0:
            b /= i
            count += 1
        ans *= count
    if ans == 1:
        print 2
    else:
        print ans


n=input()
m{
    '4':0,
    '7':0
}
for i in n:
    if i in m:
        m[i]+=1
if m[4]==0 and m[7]==0:
    print(-1)
else:
    if m[4]>m[7]:
        print(4)
    else:
        print(7)


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

diff = 0

for i in s:
    if i == "1": diff += 1
    else: diff -= 1

if diff = 1:
    print(1)
    print(s)
else:
    print(2)
    print(s[:-1]+" "+s[-1])


s = raw_input()
names = ["Danil", "Olya", "Slava", "Ann", "Nikita"]

t = 0
for name in names:
    t += s.count(name)

if t==1:
    print "YES"
else:
    print "NO": s = raw_input()
names = ["Danil", "Olya", "Slava", "Ann", "Nikita"]

t = 0
for name in names:
    t += s.count(name)

if t==1:
    print "YES"
else:
    print "NO"


x,y=cin()
    if(abs(x-y)%2==1 or x>y):
        print(-1)
    else:
        y=y-x
        y=y//2
        if(y==x):
            print(3)
            print(y,y,y)
        else:
            print(2)
            print(y,x+y)


x = int(input())
h = input()
m = input()
digitTime = []
for char in h :
    digitTime.append(int(char));

for char in m :
    digitTime.append(int(char));
y = 0

for i in range (3, 0, -1) :
    j = i
    min = digitTime[j]
    min = min - x
    while min >= 0 or (digitTime[j]!= 7) :
        digitTime[j] -= x
        y++

print(y)


def leave_number(lr, h):
    l, u = 1, 2 ** (h + 1) - 1
    rev = 1
    while lr:
        d = lr.pop()
        mid = (l + u) / 2
        if rev == 1:
            if d == 0:
                u = mid
                l += 1
                rev *= -1
            else:
                l = mid + 1
        else:
            if d == 0:
                l = mid + 1
            else:
                u = mid
                l += 1
                rev *= -1
        #print l, u
    return l

h, n = map(int, raw_input().split())
lr = []
n -= 1
while n:
    lr.append(n % 2)
    n /= 2
lr += [0] * (h - len(lr))
print leave_number(lr, h) - 1


total_black = 0
total_white = 0
black = white = {'q':0, 'r':0, 'b':0, 'n':0, 'p':0, 'k':0}
weight = {'q':9, 'r':5, 'b':3, 'n':3, 'p':1, 'k':0}

for i in range(8):
    str = input()
    for j in range(8):
        if str[j] != '.':
            if str[j] == str[j].lower(): # black
                black[str[j]] += 1
            else: # white
                white[str[j].lower()] += 1

for key in black:
    total_black += black[key]*weight[key]
    total_white += white[key]*weight[key]

if total_white == total_black:
    print('Draw')
elif total_white > total_black:
    print('White')
else
    print('Black')


n =int(raw_input())

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

k = 0
for i in range(n-1,-1,-1):
	if(m[i]==1):
		continue
	else:
		k = i
		break
seq = []
temp = [m[0]]
for i in range(1,n):
	if(m[i]==m[i-1]):
		temp.append(m[i])
	else:
		seq.append(temp)
		temp = [m[i]]
seq.append(temp)

ones = []
ans = []
for i in range(len(seq)-1,-1,-1):
	if(seq[i][0]==1):
		if(ones == []):
			ones.append(seq[i])
		else:
			ones = [seq[i]+ones[0]]
	else:
		if(ans == []):
			ans.append(seq[i])
			if(ones!=[]):
				ans.append(seq[i]+ones[0])
		else:
			temp = []
			for j in ans:
				temp.append(seq[i]+j)
			for j in ones:
				temp.append(seq[i]+j)
			ans = temp

lo = []

for i in ans:
	if(len(i)>len(lo)):
		lo = i
if(len(lo)>len(ones[0])):
	# p = lo+m[k+1:n]
	print len(lo)
	# print lo
else:
	print len(ones[0])


def main():
	n=int(input())
	s=input()
	d={}
	if n==6:
		print("espeon")
	elif n==8:
		print("vaporeon")
	else:
		for i in range(len(s)):
			if s[i]!=".":
				d[i]=s[i]
                print(find(d))
l=["jolteon", "flareon", "umbreon", "leafeon", "glaceon", "sylveon"]
def find(d):
	k=0
	for j in range(len(l)):
		for i in d.keys():
			if l[k][i]!=d[i]:
				l.remove(l[k])
				break
		else:
			k=1
	return l[0]
main()


n=int(input())
s=input()
a=0
i=0
while i < n-1:
    if s[i] != s[i+1]:
        i=i+1
        a=a+1

        i+=1
print(n-a)


for i in range(int(input()): print(2**int(input())-1)


def main():
	n, k, m = map(int, input().split(' '))
	time = list(map(int, input().split(' ')))
	ntime = []
	for i in range (0, n):
		ntime = ntime + time

	ntime.sort()
	capture1 = 0;
	i = 0
	cnt1 = 0
	while capture1 < m:
		if capture1 + ntime[i] <= m:
			cnt1 = cnt1 + 1
		capture1 = capture1 + ntime[i]
		i = i+1
	i = 0
	capture2 = 0
	cnt2 = 0
	while capture2 < m:
		if capture2 + time[i] <= m:
			cnt2 = cnt2 + 1
		capture2 = capture2 + time[i]
		i = i + 1
		if i == k:
			i = 0
			cnt2 = cnt2 + 1
	result = max([cnt1, cnt2])
	print(result)

if __name__ == "__main__":
	main()


readi=lambda: map(int, input().split())
n,m=readi()
a=[]
for _in range(n):
  x=int(input())
  a.append(x)

a.sort()
a.pop()

if not a or sum(a)<=m:
  print(‘YES’)
else:
  print(’NO’)


def cal(x):
    ans = 0
    while (x):
        ans += x % 10
        x /= 10
    return ans

n = input()
now = 0
while (n):
    now += 1
    if cal(now) == 10:
        n -= 1
print now


n, a, b, c = map(int, input().split())
h=n%4
if h==0:
	print(0)
else:
	if h==1:
		d=min(a*3,a+b,c)
	if h==2:
		d=min(a*2,b,c*2)
	if h==3:
		d=min(a,b+c,c*3)
print(d)


s=input()
l=list(s)
def count(l1):
 a=0
 for i in range(len(l1)-1):
  if l1[i]=='V':
   if l1[i+1]=='K':
    a=a+1
 return(a)
c=count(list(s))
b=[c]
for i in range(len(l)):
 l1=l[:]
 l1[i]='V'
 a=count(l1)
 b.append(a)
 l1[i]='K'
 a=count(l1)
 b.append(a)
max=c
for i in range(len(b)):
 if b[i]>max:
  max=b[i]
print(max)
print(str(b))


    # n = int(input())
    x1, x2 = map(int, input().split())
    y1, y2 = map(int, input().split())
    # arr= list(map(int, input().split()))
    # output_arr =[]
    if x1+x2+y1+y2==4:
        print(2)
    elif x1+x2+y1+y2==0:
        print(0)
    else:
        print(1)


import time
startTimeProblem=time.time()

import fileinput, sys, itertools, functools
# from math import *
import math
from bisect import *
from heapq import *
from collections import *

def lcm(a, b):
    return (a*b)/gcd(a, b)

class InputHelper:
    def __init__(self):
        self.myinput = fileinput.input()

    def isLocal(self):
        return not fileinput.isstdin()

    def int(self):
        return int(self.myinput.readline().rstrip())

    def ints(self):
        return [int(_) for _ in self.myinput.readline().rstrip().split()]

    def str(self):
        return self.myinput.readline().rstrip()

    def strs(self):
        return [_ for _ in self.myinput.readline().rstrip().split()]

class OutputHelper:
    def int(self, a):
        print(a)

    def ints(self, a):
        print(" ".join([str(_) for _ in a]))

    def intsNL(self, a):
        for _ in a:
            print(_)

    def str(self, s):
        print(s)

    def strs(self, s):
        print(" ".join([_ for _ in s]))

    def strsNL(self, s):
        for st in s:
            print(st)

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
        self.prev = None

In = InputHelper()
Out = OutputHelper()

######################################

def isPrime(x):
    if x==2:
        return True

    for i in range(2, math.ceil(math.sqrt(x))+1):
        if x%i == 0:
            return False

    return True

x, n = In.ints()
MOD = (10**9+7)
primes = []

for i in range(2, math.ceil(math.sqrt(x))+1):
    if x%i==0 and isPrime(i):
        primes.append(i)

        div = x//i
        if div != i and isPrime(div):
            primes.append(div)

if isPrime(x):
    primes.append(x)

ans = 1

for p in primes:
    k = 1

    while True:
        div = (n//p**k)

        if div==0:
            break

        ans *= pow(p,div,MOD)
        ans %= MOD
        k+=1

Out.int(ans)

######################################

if len(sys.argv)>2 and sys.argv[2]=="TIMEIT":
    fin = (time.time()-startTimeProblem)*1000
    print("{:.2f}".format(fin) + "ms")


prime = [0, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
min_value = round(1e18)
n = int(input())

def search(value, total_factor, i):
    global min_value
    if total_factor == n:
        min_value = min(value, min_value)
        return
    for k in range(1, 65):
        value *= prime[i]
        if value > min_value:
            break
        if total_factor * (k + 1) <= n:
            search(value, total_factor * (k + 1), i+1)

search(1, 1, 1)
print(min_value)


n,k,m,d = [int(x) for x in input().split()]
ans = 0
for t in range(1,d+1):
	R = n // ((t-1)*k + 1)
	L = n // (t*k)
	if L <= R:
		if L <= m <= R:
			ans = max(ans,m*t)
		else if R <= m:
			ans = max(ans,R*t)

print(ans)


def main():
	n=int(input())
    sum=0
    for i in range(2,(n-1)):
        s=n
        while(s>0):
            sum=sum+(s%i)
            s=s/i
    b=n-2
    a=sum
    #For HCF
    if a<b:
        x=a
        a=b
        b=x
    while (a%b!=0):
        d=a%b
        b=a
        a=d
    hcf=b
    d1=sum/hcf
    d2=(n-2)/hcf
    print("%d/%d",d1,d2)


# 1062B
# greedy math number theory *1600

'''
给定一个正整数n，有两种操作：
1、乘以任意一个正整数x， n=n*x
2、开平方根, n=sqrt(n)
问最少几次操作后，n最小，是多少
'''

import math

n = int(input())
ans, anssq = 1, 0
maxsq = 1
tempn = n
for i in range(2, n + 1):
    tempsq = 0
    while tempn % i == 0:
        tempn = tempn // i
        tempsq += 1
    if tempsq > 0:
        ans = ans * i
    if tempsq > maxsq:
        maxsq = tempsq
print(ans, math.ceil(math.log2(maxsq) + 1))


n, m = raw_input().split(" ")
n = int(x)
m = int(y)
i=0
if n>m:
k = n
else:
k = m
for a in range(0, k):
  for b in range(0, k):
    if a*a+b == n and a+b*b == m:
      i=i+1
print i


n, k = map(int, input().split())
l = list(map(int, input().split())
l = list(set(l))
if len(l) < k: print("NO")
else:
    print("YES")
    for i in range(k): print(l[i], end = " ")


import math
x=int(input())
k=math.floor(-1+math.sqrt(1+8*x))
print(k,'\n')
for i in range(1,k):
    print(i,' ')
print(x-(k*(k-1) div 2))


// luogu-judger-enable-o2
read=input()
read=read.split(" ")
a=[0]*4
n=int(read[0])
m=int(read[1])
a[1]=m
a[2]=m
a[3]=m
def mysort():
	for i in range(1,4):
		for j in range(i,4):
			if a[i]>a[j]:
				a[i],a[j]=a[j],a[i]
	return
def getans():
	t=0
	if n==m:
		return 0
	while 0==0:
		mysort();
		t=t+1;
		if a[2]+a[3]-1<=n :
			a[1]=a[2]+a[3]-1
		else:
			a[1]=n
		if a[1]==n and a[2]==n and a[3]==n:
			return t
	return 0;
print(getans())


import math
def f(A):

    i_min = A.index(1)
    i_max = A.index(n)
    length = len(A)
    if abs(i_min - i_max) == length - 1:
        return abs(i_min - i_max) - 1
    elif i_min == 0 or i_min == length - 1:
        return length - 1
    elif i_max == 0 or i_max = length - 1:
        return length - 1
    else:
        return max(abs(length - 1 - i_min), abs(length - 1 - i_max), abs(i_max), abs(i_min))

T = input()
arr = [int(i) for raw_input().strip(' ').split()]


a=int(input())
b=int(input())
c=int(input())
d=[]
k=int(floor(b/2))
l=int(floor(c/4))
d.append(a)
d.append(k)
d.append(l)
d.sort()
if d[0]=='0':
    print 0
t=int(d[0])
ans=int(t*a+t*b+t*c)
print(t)


p,y = map(int,input().split())
for x in range(y,p,-1):
	if all(x%i for i in range(2,min(int(x**.5),p+1)):
		#even if one devides it completely then not possible to sit
		#if nothing devides then it's sitable
		#factors repeat after reachin midway(sqrt)
		print(x)
		exit()
print(-1)


def bin (a, b, c, n, m, k, pn, pm, pk, r):
    [L, R] = [0, r * 100]
    while R - L > 1:
        M = (R + L) // 2
        a2 = max(M * a - n, 0)
        b2 = max(M * b - m, 0)
        c2 = max(M * c - k, 0)
        if a2 * pn + b2 * pm + c2 * pk <= r:
            L = M
        else:
            R = M
    return L

str = input()
[a, b, c] = [0, 0, 0]
[n, m, k] = [int(i) for i in input().split()]
for i in str:
    if i == 'B':
        a += 1
    elif i == 'S':
        b += 1
    else:
        c += 1
[pn, pm, pk] = [int(i) for i in input().split()]
r = int(input())
print(bin(a, b, c, n, m, k, pn, pm, pk, r))


G = (1 + 5 ** .5) / 2
w = set((int(k * G), int(k * G) + k) for k in range(999))
n = input()
a = sorted(map(int, raw_input().split()))+[0,0]
print 'BitAryo' if (((a[0], a[1]) in w) if 2==n else not(a[0]^a[1]^a[2])) else 'BitLGM'


def the_Artful():
    n=int(input())
    x=list(map(int,input().split()));
    y=list(map(int,input().split()));
    cpt=0
    c1=set(x+y)
    for i in range(n):
        for j in range(n):
            h=x[i]^y[j];
            if h in c1:
                cpt+=1;
    if (cpt%2==0):
        print('Karen');
    else:
        print('Kayomi');
   the_Artful ()


import sys
n = input()
s = list(raw_input())
abc = sorted(set(('zyxwvutsrqponmlkjihgfedcba')[26-n:]) - set(s))
sl = len(s)/2

for i in xrange(sl):
    j = -i-1
    if s[i] == '?' and s[j] != '?': s[i] = s[j]
    elif s[j] == '?' and s[i] != '?': s[j] = s[i]
    elif s[i] != s[j]:
        print 'IMPOSSIBLE'
        sys.exit()

for i in xrange(sl,-1,-1):
    if s[i] == '?':
        s[i] = s[-i-1] = abc.pop() if abc else 'a'

print 'IMPOSSIBLE' if abc else ''.join(s)


t=input().split(' ')
w=int(t[0])
h=int(t[1])
sum=0
for i in range(int(t[2])):

sum=sum+2*(w+h)-4
w=w-4
h=h-4

print(sum)


n=int(input())
s=input()
a=[]
for i in range(n-1):
    a.append(s[i:i+2])
print(max(a,key=a.count))-


from itertools import permutations
from math import log
from math import ceil
from sys import exit

i = input()
N = int(i[:i.index(' ')])
M = int(i[i.index(' ')+1:])

l = ceil(log(N,7))
r = ceil(log(M,7))

if l+r > 7 || l == 0 || r == 0:
	print(0)
	exit()

ans = []
for x in permutations([0,1,2,3,4,5,6]):
	cnt = 1
	total = 0
	for a in range(l):
		total += cnt*x[a]
		cnt *= 7
	if total >= N:
		continue

	cnt = 1
	total = 0
	for a in range(l,l+r):
		total += cnt*x[a]
		cnt *= 7
	if total >= M:
		continue

	if x[:l+r] not in ans:
		ans += [x[:l+r]]

print(len(ans))


import itertools

n,l,r,x = map(int,input().split())
a = map(int,input().split())
a.sort()
ans = []
combos = []
for i in range(2,n+1):
	temp = itertools.combinations(a,i)
	for j in temp:
		combos.append(j)
count = 0

for i in combos:
	tot = sum(i)
	maxi = max(i)
	mini = min(i)
	if(tot>=l and tot<=r and maxi-mini>=x):
		count+=1
print coun


from math import sqrt,ceil
a,b = map(int,input().split())

e = a - b
if(e == 0) :
    print("infinity")
elif(e < 0):
	print(0)

else :
    i = 1
    marked= False
    t = e
    ans = 0
    down = 0
    while(i < ceil(sqrt(e))) :
        if(e % i == 0):
        	t = e // i
        	if(t > b):
        		ans += 1
        		if(i <= b) :
        			down += 1
        if(e // i <= b) :
        	marked = True
        	break
        i += 1
    if(!marked):
    	ans = ans*2 - down
    	if(sqrt(e) == ceil(sqrt(e))) :
    		ans += 1
    print(ans)


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


n, a,b = map(int,input().split())
l1 = list(input())
l2 = list(input())
z = []
for i in range(1,n+1):
    if i in l1:
        z.append(1)
    else:
        z.append(2)
w = z.remove('[')
x = w.remove(']')
y = x.remove(',')
print((y)


n, m = [int(x) for x in input().split()]
if n == 0 and m > 0
    print('Impossible')
else:
    print(n+max(0, m-n), (n+m-1 if m else n))


x,y,a,b = map(int, input().split())
g = 1
while g % x || g % y:
    g += 1
print(b // g - (a - 1) // g)


from math import factorial
from functools import partial, reduce
from operator import mul
spi = partial(reduce, mul)
def comb(a, *args):return factorial(a)/spi(factorial(x) for x in args)
n = int(raw_input())
A = [int(i) for i in raw_input().split()]
m = sum(A)

if m > n:
    print 0
    exit()

y = comb(m, *A) % 1000000007
Y = [[y for i in xrange(10)]]

Az = [A[0]-1]+A[1:] if A[0] > 0 else A
z = (comb(m-1, *Az) % 1000000007) if A[0] > 0 else 0
Z = [[z for i in xrange(10)]] if z != 0 else []

def next_table(A, Y, m, i):
    Yn = []
    Sd = [0]*10
    for j in xrange(i):
        s = 0
        for k in xrange(9):
            s += Y[j][k]*(m+i+1)
            Sd[k+1] += s/(A[k+1]+1)
    S = 0
    Sy = [0]*10
    for j in xrange(i+1):
        S += sum((Y[j][k])*(m+i+1)/(A[k]+(i-j)+1) for k in xrange(10))
        Yn.append([(Y[j][k])*(m+i+1)/(A[k]+(i-j)+1) % 1000000007 for k in xrange(10)])
        for k in xrange(10):Sy[k] += Yn[-1][k]
    S -= sum(Sd)
    for k in xrange(10):
        Yn[-1][k] -= Sd[k]
        Sy[k] -= Sd[k]
    Yn.append([(S - Sy[k]) % 1000000007 for k in xrange(10)])
    return S % 1000000007 , Yn

S = y-z
for i in xrange(n-m):
    Sy, Y = next_table(A, Y, m, i)
    if z:
        Sz, Z = next_table(Az, Z, m-1, i)
    else:
        if i == 0:
            Sz, Z = y, [[y for j in xrange(10)]]
        else:
            Sz, Z = next_table(Az, Z, m, i-1)
    S += Sy - Sz
if A.count(0) == 10: S-=1
print S % 1000000007


    def check(cx, cy):
        if a[cx - 1][cy - 1] == '#' and a[cx - 1][cy] == '#' and a[cx - 1][cy + 1] == '#' and a[cx][cy - 1] == '#' and a[cx][cy + 1] == '#' and a[cx + 1][cy - 1] == '#' and a[cx + 1][cy] == '#' and a[cx + 1][cy + 1] == '#':
            used[cx - 1][cy - 1] = used[cx - 1][cy] = used[cx - 1][cy + 1] = used[cx][cy - 1] = used[cx][cy + 1] = used[cx + 1][cy - 1]  = used[cx + 1][cy] = used[cx + 1][cy + 1] = True
            return True
        return False

    n, m = map(int, input().split())
    a = [0] * (n + 1)
    for i in range(n):
        a[i] = list(input()) + ['.']
    a[-1] = ['.'] * (m + 1)
    used = [[a[i][j] == '.' for j in range(m)] for i in range(n)]
    f = True
    for i in range(n):
        for j in range(m):
            if used[i][j]:
                continue
            if check(i - 1, j - 1) or check(i - 1, j) or check(i - 1, j + 1) or check(i, j - 1) or check(i, j + 1) or check(i + 1, j - 1) or check(i + 1, j) or check(i + 1, j + 1):
                continue
            print('NO')
            exit(0)
    print('YES')


n=int(input())
l=[]
for i in range (n):
    ch=input()
    if(ch=="*"):
        l.append(i+1)

k=[]
for j in l:
    k.append(j-l[0])
a=0
s=0
while((a<=len(k)-5)and(s<4)):
    s=1
    b=a+2
    while((b<len(k)-1)and(s<4):
        if(k[b+1]-k[b]==k[a+1]-k[a])):
            s=s+1
        b=b+1
    if(s<4):
        s=0
        a=a+1
if(s==4):
    print("yes")
else:
    print("no")


import math, sys
def smallest(n):
    while n % 2 == 0:
        return 2
        n = n / 2
    for i in range(3,int(math.sqrt(n)+0.5),2):
        #print(i)
        while n % i== 0:
            return i
            n = n / i
    if n > 2:
        return n
t = int(input())
#print(t)
for i in range(t):
    a, b = map(int, input().split())
    diff = (a+b)*(a-b)
    #print(diff)
    #print(math.sqrt(diff))
    #print("d", diff)
    if smallest(diff)== diff:
        print("YES")
    else:
        print("NO")


import math
def countd(n):
    cnt=0
    for i in range(1,int(math.sqrt(n))+1):
        if n%i==0:
            if n//i==i:
                cnt+=1
            else:
                cnt+=2
    return cnt

    return cnt
a,b,c=map(int,input().split())
ans=0
for i in range(1,a+1):
    for j in range(1,b+1):
        for k in range(1,c+1):
            t=i*j*k
            ans+=countd(t)
print(ans%1073741824)


print(max(abs(a-b)for a,b in zip(*[map(int,input().split())for _ in(1,2)]))))


n,x,y=map(int,input().split())
p=int(n/2)+2
if n==2:
    print('NO')
elif n%2==0 and y in range(int(n/2),p) and x not in range(int(n/2),p):
    print('YES')
elif n%2==0 and x in range(int(n/2),p) and y not in range(int(n/2),p):
    print('YES')
else:
    print('NO')


str1, str2 = input(), input()

print("-1" if any(map(lambda s1, s2: s1 < s2, str1, str2) else str2)


list=input().split(' ')
for i in range(2):
    list[i]=int(list[i])
a=list[0]//list[1]
b=list[0]%list[1]
list2=[]
for i in range(list[1]):
    if list[1]-b<=i: list2.append(a+1)
    else: list2.append(a)
print(list2)


def compute_hcf(x, y):

# choose the smaller number
    if x > y:
        smaller = y
    else:
        smaller = x
    for i in range(1, smaller+1):
        if((x % i == 0) and (y % i == 0)):
            hcf = i
    return hcf

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

hcf = compute_hcf(a, b)

a = a/hcf
b = b/hcf
count = int(0)
# print(a,b,hcf)
while b>=2:
	# print(b)
	if b%2==0:
		count+=1
		b = b/2
	elif b%3==0:
		count+=1
		b = b/3
	elif b%5==0:
		count+=1
		b = b/5
	else:
		break

while a>=2:
	# print(a)
	if a%2==0:
		count+=1
		a = a/2
	elif a%3==0:
		count+=1
		a = a/3
	elif a%5==0:
		count+=1
		a = a/5
	else:
		break
	# print(a,b)
if(a!=b):
	print(-1)
else:
	print(count)


s=input()
x=s.find("0")+1
if x:
    print x
else:
    print len(s)


n = int(input())

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

if n == 1:
	print (-1)
else:
	if a[-2] > a[-1] && a[-1] != 0:
		print("DOWN")
	else:
		print("UP")


# import sys

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

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

if __name__ == '__main__':
	num,swap = raw_input().split()
	num = list(num)
	swap = int(swap)
	ans = ''
	while num:
		pos = num.index(max(a[:swap+1]))
		ans += num[pos]
		swap -= pos
		num.pop(pos)
		if swap == 0:
			ans += ''.join(num)
			break;
	print ans


def d(i):
            return (len(set(str(i)))==len(str(i))
n,r=map(int,input().split())
f=False
for i in range(n,r+1):
            if d(i):
                        f=True
                        print(i)
                        break
if not f:print("-1")


n = int(input())

inf  = 10**9+9

dp = [inf]*(n+1)
ans = [[]for row in range(n+1)]

def binary(n) :
    s = 0
    t = 1;
    while n > 0 :
        s += t*(n%2)
        t *= 10
        n //= 2

    return s

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

for i in range(n+1) :
    l = len(str(i))
    for j in range(1,2**l) :
        b = binary(j)
        if b<=i :
            if dp[i-b]+1 < dp[i] :
                dp[i] = dp[i-b]+1
                ans[i] = list(ans[i-b])
                ans[i].append(b)

print(dp[n])

for i in ans[n] :
    print(i,end=" ")


n,pos,l,r=map(int,input().split())
    if pos>=l and pos <=r:
        if l==1 and r!=n:
            print(r-pos+1)
        elif r==n and l!=1:
            print(pos-l+1)
        elif l==1 and r==n:
            print(0)
        else:
            x=pos-l
            y=r-pos
            a=max(x,y)
            b=min(x,y)
            print(2*b+a+2)
    elif pos<l:
        if r!=n:
            print(r-pos+2)
        else:
            print(l-pos+1)
    elif pos>r:
        if l!=1:
            print(pos-l+2)
        else:
            print(pos-r+1)


#include <bits/stdc++.h>
#include<iostream>
using namespace std ;
int main()
{
  string s ;
  cin>>s;
  s.replace(s.find("at",1),2,"@");
  //cout<<s;
  for (auto i= s.find("dot",1);i<s.size()-3;i=s.find("dot",1))
    s.replace(i,3,".");
  cout<<s;
}


n = int(input())
a = list(map(int, input().split()))
newList = []

for element in a[::-1] :
    if element not in newList :
        newList.append(element)
        #print (a)
    else :
        a.remove(element)
        #print (a)
print (len(a))
print(str(a)


import sys
sys.setrecursionlimit(10**9)
n = input()
arr = map(int,raw_input().strip().split())
def f(i,flag=True):
    if i==n-1:
        if flag: return arr[i]
        else: return 0
    else:
        if flag:
            return max(f(i+1,False)+arr[i],f(i+1,True))
        else:
            return min(f(i+1,True),f(i+1,False)+arr[i])

bob = f(0)
print sum(arr)-bob,bob


def S(i):
    return sum(map(int,str(i)))
n=input()
for i in range(max(1,int(n**0.5)-999),int(n**0.5)+999):
    if i*(i+S(i))==n:
    print i
    exit()
print -1


#include <bits/stdc++.h>
#define ll long long
#define M 1000000007
#define INF 9223372036854775807
#define mp(x,y) make_pair(x,y)
#define pb(x) push_back(x)
#define pmp(x,y) pb(mp(x,y))
#define ld double
#define PI 3.14159265
#define len(a) (ll)a.size()    //
#define F first
#define S second
#define ch cout<<"debug\n"
#define endl "\n"
#define fast() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;

map<string,ll> m;
int main(){

	ll n;
	cin>>n;
	if(n%2==0)
		cout<<"home";
	else
		cout<<"contest";

	return 0;
}


n = input()
f=[0]*90
f[0]=1
f[1]=1
i=2
while 1:
    f[i]=f[i-1]+f[i-2]
    if f[i]>pow(10,18):
        break
    i+=1
for i in range(0,len(f)):
    if n>=f[i] and n<f[i+1]:
        break
print i-1


n=int(input())
a=[1, 2]
ans = 1
for i in range(n):
    j=int(input())
    if x in a: a=[j, 6-sum(a)]
    else: ans = 0
print("YES" if ans = 1 else "NO")


n=int(raw_input())
i=0
s=0
k=1
x=list(map(int,raw_input().split(" ")))
while k==1&&i<=len(x):
    if k==1:
        if x[i]-s<=15:
            k=1
            s=x[i]
        else :
            k=0
            s=s+15
if(i==len(x)):
    print s<=75?s+15:90


a,b,s=map(long int,raw_input().split())
print"Enter the values of a,b and s"
if a<0:
    a=-a
if b<0:
    b=-b
if s<a+b:
    print"no"

else:
    if (s-(a+b))%2 ==0:
        print"yes"
    else:
        print"no"


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

if 2*b==a+c and 2*c==b+d:
    print 2*d-c

elif b**2=a*c and c**2==b*d:
    if float(d**2/c)==d**2/c:
        print d**2/c
    else:
        print 42
else:
    print 42


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

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

import __pypy__

def main():
    n = input()
    m = n[::-1]
    res = 10**9

    if int(n) % 25 == 0:
        print(0)
        return

    if n.count('0') >= 2:
        cnt, flag = 0, False
        for i, mi in enumerate(m):
            if mi == '0':
                if flag:
                    cnt += i - 1
                    break
                else:
                    flag = True
                    cnt += i

        res = min(res, cnt)

    if '5' in n:
        i = m.index('5')
        if '0' in n:
            if n.count('5') == 1 and n.index('5') == 0:
                cnt = m.index('0')
                n = n[:-cnt - 1] + n[-cnt:] + '0'
                for i in range(1, len(n)):
                    if n[i] != '0':
                        cnt += i - 1
                        cnt += len(n) - 2
                        res = min(res, cnt)
                        break

            else
                j = m.index('0')
                if i > j:
                    res = min(res, j + i - 1)
                else:
                    res = min(res, j + i)

        if '2' in n:
            if n.count('5') == 1 and n.index('5') == 0:
                cnt = m.index('2')
                for i in range(1, len(n)):
                    if n[i] != '0':
                        cnt += i - 1
                        cnt += len(n) - 1
                        res = min(res, cnt)
                        break

            if n.count('2') == 1 and n.index('2') == 0:
                cnt = i
                for i in range(1, len(n)):
                    if n[i] != '0':
                        cnt += i - 1
                        cnt += len(n) - 2
                        res = min(res, cnt)
                        break

            if m.index('5') < len(n) - 1 and m.index('2') < len(n) - 1:
                j = m.index('2')
                if i > j:
                    res = min(res, j + i)
                else:
                    res = min(res, j + i - 1)

        if '7' in n:
            if n.count('5') == 1 and n.index('5') == 0:
                cnt = m.index('7')
                for i in range(1, len(n)):
                    if n[i] != '0':
                        cnt += i - 1
                        cnt += len(n) - 1
                        res = min(res, cnt)
                        break

            if n.count('7') == 1 and n.index('7') == 0:
                cnt = i
                for i in range(1, len(n)):
                    if n[i] != '0':
                        cnt += i - 1
                        cnt += len(n) - 2
                        res = min(res, cnt)
                        break

            if m.index('5') < len(n) - 1 and m.index('7') < len(n) - 1:
                j = m.index('7')
                if i > j:
                    res = min(res, j + i)
                else:
                    res = min(res, j + i - 1)

    print(res if res < 10**9 else -1)

# region fastio

BUFSIZE = 8192

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

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

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

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

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

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

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

# endregion

if __name__ == "__main__":
    main()


def main():
    n, w = map(int, input().split())
    a = list(map(int, input().split()))
    res1 = [0 for i in range(n)]
    for i in range(n):
        res1[i] = (a[i] + 1) // 2
    w -= sum(res1)
    if w < 0:
        print(-1)
        return
    while w > 0:
        maxi = a.index(max(a))
        if w >= a[maxi] - res1[maxi]:
            res1[maxi] = a[maxi]
            w -= a[maxi] - res1[maxi]
            a[maxi] = 0
        else:
            res1[maxi] += w
            w = 0
    print(*res1)
main()


n, s = int(input()), input()
print(sum(2 ** i for i in range(n) if s[i] == 'B')


def mask(d):
    d=str(d)
    a1=[]
    st=''
    for i in range(len(d)):
        a1.append(d[i])
    for i in range(len(a1)):
        a1[i]=int(a1[i])
    for i in range(len(a1)):
        if a1[i]==4 or a1[i]==7:
            st=st+str(a1[i])
    if st=='':
        st='0'
    st=int(st)
    return st

s=raw_input()
a,b='',''
n=s.find(' ')
for i in range(n):
    a=a+s[i]
for i in range(n+1, len(s)):
    b=b+s[i]

a,b=int(a), int(b)
c=a+1

while mask(c)!=mask(b):
    c=c+1

print(c)


n, d = map(int, input().split(" "))
s = list(map(int, input().split(" ")))
l = [list(i for i in s if s[i] == 1)]
diff = [list(l[i+1] - l[i] if  (l[i+1] - l[i]) <= d) else -1 if (l[i+1] - l[i]) > d) for i in range(0, len(l) - 1))]
print(min(diff))


a = raw_input()
b = raw_input()
c = raw_input()
d = raw_input()
l = [len(a)-2,len(b)-2,len(c)-2,len(d)-2]
dic={'A':l[0],'B':l[1],'C':l[2],'D':l[3]}
l = sorted(l)
big=1
small=1
count=0
#print l
if l[3]>=l[2]*2:
    count+=1
    big=1
if 2*l[0]<=l[1]:
    count+=1
    small=1
if count==1:
    if big==1:
        print max(dic.iterkeys(),key=lambda k:dic[k])
    if small==1
        print min(dic.iterkeys(),key=lambda k:dic[k])
else:
    print 'C'


"""
    Template written to be used by Python Programmers.
    Use at your own risk!!!!
    Owned by adi0311(rating - 5 star at CodeChef and Specialist at Codeforces).
"""
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nlargest, nsmallest, _heapify_max, _heapreplace_max
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque, Counter as c
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from fractions import Fraction
# sys.setrecursionlimit(2*pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(var): sys.stdout.write(str(var))
def outln(var): sys.stdout.write(str(var)+"\n")
def l(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]

def dfs(source, p):
    global cycle_number
    if color[source] == 2:
        return
    if color[source] == 1:
        cycle_number += 1
        cur = p
        mark[cur] = cycle_number
        while cur != source:
            cur = par[cur]
            mark[cur] = cycle_number
        return
    par[source] = p
    color[source] = 1
    for child in graph[source]:
        if child == par[source]:
            continue
        dfs(child, source)
    color[source] = 2

cycles = [[]] * 6
n = int(data())
graph = dd(set)
color, par, mark = [0] * 6, [0] * 6, [0] * 6
cycle_number = 0
for i in range(n):
    u, v = sp()
    graph[u].add(v)
    graph[v].add(u)
cnt = 0
for i in range(1, 6):
    if len(graph[i]) <= 1:
        cnt += 1
if cnt >= 3:
    outln("WIN")
    exit()
dfs(1, 0)
for i in range(1, n + 1):
    if mark[i] != 0:
        cycles[mark[i]].append(i)
for i in cycles:
    if len(i) == 3:
        outln("WIN")
        exit()
outln("FAIL")


n = int(input())
l = []
for _ in range(4):
    l.extend(list(input())

for i in range(15, -1, -1):
    if(l[i] == '.'):
        l.pop(i)

for i in l:
    if(l.count(i) > 2 * n):
        print('No')
        exit()
print('YES')


n=[int(i) for i in input().split()]
z=bin(0)
for i in range(len(n)-1):
    z=z^n[i]
print(int(z))


import math
f = 998244353

def matchings(a,b):
    m = max(a,b)
    n = min(a,b)
    if n == 0:
        return 0

    t = 1
    for i in range(0,n):
        r = range(m-i,m+1)
        p = 1
        p = math.factorial(n)*math.factorial(i+1)//math.factorial(n-i-1)
        for e in r:
            if p > f:
                p = p % f
            p *= e
        t += int(p)
    return(t)

inputs = [int(x) for x in input().split(" ")]
k = matchings(inputs[0],inputs[1])*matchings(inputs[0],inputs[2])*matchings(inputs[2],inputs[1]) % f
print(k)


r = int(input())

if (r<5 or r%2==0)
    print("NO")
    exit()

print(1, (r-3) // 2)


 = int(input())
b = int(input())
c = a + b
st = str(a) + "+" + str(b) + "=" + str(c)
st1 = list(st)
for i in range(0, st1.count(str(0))):
    st1.remove(str(0))
st1 = "".join(st1)
st1 = st1.split("+")
a = int(st1[0])
st1 = st1[1].split("=")
b = int(st1[0])
c = int(st1[1])
check = bool(a + b == c)
if a + b == c:
    print("YES")
else:
    print("NO")


want_eat = map(int, input().split(' '))
grapes = map(int, input().split(' '))
grapes[0] -= want_eat[0]
if grapes[0] < 0:
    return 'NO'
all_grapes = sum(grapes)
all_grapes -= want_eat[1]
if all_grapes - grapes[0] < 0:
    return 'NO'
if all_grapes < want_eat[2]:
    return 'NO'
else:
    return 'YES'


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from types import GeneratorType
def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to
    return wrappedfunc

from bisect import bisect_left
def solve():
    n, m = map(int, input().split())
    a = []
    for i in range(m):
        ai, bi = map(int, input().split())
        a.append((ai, bi))
    a.sort(key = lambda x: x[0])
    b = []
    presum = [0]
    for i in range(m):
        b.append(a[i][1])
        a[i] = a[i][0]
        presum.append(presum[-1]+a[i])
    ma = 0
    for i in range(m):
        s = a[i]
        ind = bisect_left(a, b[i])
        if m-ind>n-1:
            s+=presum[m]-presum[m-n+1]
        else:
            s+=presum[m]-presum[ind]
            s+=b[i]*(n-1-(m-ind))
        if ind<=i:
            if m-ind<=n-1:
                s-=a[i]
                s+=b[i]
            else:
                s-=a[i]
                s+=a[m-n]
        #print(s)
        if s>ma:
            ma = s
    print(ma)
def main():
    t = int(input())
    for i in range(t):
        solve()
        if i!=t-1:
            input()
main()


p = 10**9+7
x,y = map(int,raw_input().split())
if y%x != 0:
	print 0
else:
	y /= x
	d = set([])
	i = 1
	while i*i<=y:
		if y%i == 0:
			d.add(i)
			d.add(y/i)
		i += 1
	d = sorted(list(d))
	f = d[::]
	for i in range(len(d)):
		f[i] = pow(2,d[i]-1,p)
		for j in range(i):
			if d[i]%d[j]==0:
				f[i] -= f[j]
	print f[-1]%p


a,b,c = list(map(int,input().split()))
import math
a = math.factorial(n-1)//(math.factorial(k)*math.factorial(n-1-k)))
print(a*m*((m-1)**k))


def find(arr,n,k):
    d = {}
        m = 0
            for a in arr:
if a in d:
    d[a]+=1
    else:
        d[a]=1
    if m < d[a]:
        m = d[a]
            s = len(d)
            m = m%k + 1
                if m > 0:
return s*m*k-len(arr)
    return s*k-len(arr)

def main():
    n,k = map(int,input().split())
    arr = list(map(int,input().split()))
    print(find(arr,n,k))

if __name__=="__main__":
    main()


k, r = map(int, input())
print(min(i for i in range(1,10) if k * i % 10 == r)


#coding=utf8
'''
Created on 20160607

@author: ChronoCorax
'''
n = int(input())
k = int(input())
c = n - 2 * k
if c < 0: c = 0
a = n * (n - 1) // 2 - c * (c - 1) // 2
print(a)


a = input()
b = int(a) - int(a[1:]) - 1
print([a, b][sum(map(int, a)) < sum(map(int, str(b)))


from collections import defaultdict
import sys

def mpow(base, p):
    temp = 1
    while p:
        if (p & 1):
            temp = (temp * base) % MOD
        p //= 2
        base = (base * base) % MOD
    return temp % MOD
if __name__ == "__main__":
    #n, m = list(map(int, input().split()))
    a, b, n, x = map(int, input().split())
    MOD = 10 ** 9 + 7
    temp = mpow(a, n)
    if a > 1:
        ans = ((temp * x % MOD) + (b * (temp - 1) % MOD) * mpow(a - 1, MOD - 2) % MOD) % MOD
    else:
        ans = ((temp * x % MOD) + b * (n % MOD) % MOD) % MOD
    print(ans)


# from operator import itemgetter, attrgetter, methodcaller
# from collections import Counter, defaultdict
# from fractions import gcd
# import sys
# import math

def main():
    k = raw_input()
    k = int(k)

    print k**2 * 3

if __name__ == "__main__":
    main()


n = int(raw_input())

mod = 1000000007

def a(n):
  res = 1
  for x in xrange(n+1, 2*n+1):
    res *= x
  for x in xrange(1, n+1):
    res /= x
  #res %= mod
  return res

seen = {}
def c(n, k):
  if k == 0 or k == n:
    return 1
  key = (n, k)
  if key not in seen:
    val = (c(n-1, k) + c(n-1, k-1)) % mod
    seen[key] = val
    return val
  return seen[key]

def sol(n):
  return (c(2*n-1, n) * 2 - n) % mod

#print sol(10*5)
print sol(n)


n1,n2,k1,k2=map(int,input().split())
if k2>k1:
    if (n1<=n2):
        print("Second")
    elif n1>n2:
        print("First")
elif k1==k2:
    if n1>n2:
        print("First")
    elif n1<=n2:
        print("Second")

else (k1>k2):
    if (n1==n2)or(n1<n2):
        print("Second")
    elif n1>n2:
        print("First")


def ans(n):
    if(n==0):
        return 1
    elif(n<10):
        return n
    else:
        return max(n%10*(ans(n//10),9*(ans(n//10-1)))

n=int(input())
int y =ans(n)
print(y)


C, Ha, Hb, Wa, Wb = (int(x) for x in raw_input().split())

if Ha * Wb > Hb * Wa:
    Ha, Hb, Wa, Wb = Hb, Ha, Wb, Wa

res = 0
if Wb * Wb > C:
    for y in xrange(0, C / Wb + 1):
        r = y * Hb + (C - y * Wb) / Wa * Ha
        res = max(r, res)
else:
    for x in xrange(0, Wb):
        r = x * Ha + (C - x * Wa) / Wb * Hb
        res = max(r, res)
print res


s = input()
flag = 0
for i in range (0,s.len())
    if(s[i]=='a' or s[i]=='e' or s[i]=='i' or s[i]=='o' or s[i]=='u' or s[i]=='y') :
        flag=1
    elif(s[i]=='A' or s[i]=='E' or s[i]=='I' or s[i]=='O' or s[i]=='U' or s[i]=='Y'):
        flag=1
    elif((s[i]>='a' and s[i]<='z') or(s[i]>='A' && s[i]<='Z')) :
        flag=0
if(flag):
    print("YES")
else :
    print("NO")


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


def gcd(p,q):
	if(q==0):
		return p
	else:
		return gcd(q,p%q)
n,m,x,y,a,b=map(int,raw_input().split())
t=gcd(a,b)
a/=t
b/=t
k=n/a
l=m/b
sz=min(k,l)
a*=sz
b*=sz
lft=x-(a-a/2)
bt=y-(b-b/2)
if(lft<0):
	lft=0
if(bt<0):
	bt=0
if(lft+a>n):
	lft=n-a
if(bt+b>m):
	bt=m-b
print lft,bt,lft+a,bt+b


x1,y1,x2,y2=map(int,input().split())
a,b=map(int,input().split())
if(x1==x2 and y1==y2):
	print("YES")
elif(x1==x2 and abs(y1-y2)%b==0):
	print("YES")
elif(y1==y2 and abs(x1-x2)%a==0):
	print("YES")
elif(abs(x1-x2)//a==abs(y1-y2)//b):
	print("YES")
else:
	print("NO")


import math
n,R,r=map(int,input().split())
if n==1 and r<=R:
    print('YES')
    exit()
elif n>1 and r==R:
    print('NO')
    exit()
c = 2*math.pi/(2*math.asin(r/(R-r)))
if c-n>-10**-6:
    print('YES')
else:
    print('NO')


#include <iostream>
#include<string>
using namespace std;

int main()

{
    string ch;

    cin>> ch;

    if(ch =="a1" || ch =="h1" || ch =="h8" || ch=="a8")

       cout<<3<< endl;

      else  if (((ch[0] =='a')||(ch[0]=='h'))||((ch[1]=='1')||(ch[1]=='8')))
    cout<<5<< endl;

    else
        cout<<8<< endl ;

    return 0;
}


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

if x>0 and y>=0 z>=0 and y+z>0:
  if x>y and x>z:
    print(-1)
  elif y>x and x>z:
    print(-1)
  elif x>y and z>x:
    print(-1)
  else:
    print((y//x)+(z//x))
else:
  print(-1)


n=int(input())
x=n
f=[]
for i in range(2,int(n**(0.5))+1):
    if n%i==0:
        c=0
        while n%i==0:
            c=c+1
            n=n//i
        f.append([i,c])
m=0
for i in range(len(f)):
    m=m+f[i][1]
if m>2 or x==1:
    if x==1:
        print(1)
        print(0)
    else:
        if f[0][1]>=2:
            print(1)
            print(f[0][0]**2)
        else:
            print(1)
            print(f[0][0]*f[1][0])
else:
    print(2)


n,k= map(int,input().split())
s = input()
s = sorted(s)
    ans = 0
    pre = 0
    for i in range(n):
        if k==0:
            break
        if ord(s[i])>=2+pre:
            k-=1
            ans += (ord(s[i])-97+1)
            pre = ord(s[i])
    if k==0:
        print(ans)
    else:
        print(-1)


a, b, c = map(int,input().split(" "))
x, y, z = map(int,input().split(" "))
need = 0
extras = 0
if x - a > 0:
    need+=x-a
else :
    extras+= (a - x)//2
if y - b > 0:
    need+=y-b
else :
    extras+= (b - y)//2
if z - c > 0:
    need+=z-c
else :
    extras+=(c - z)//2

if need > extras or x+y+z=0:
    print("No")
else:
    print("Yes")


hps=[1,3,2,0]
cat=['A','B','c','D']

num0=input()
num1=num0+1
num2=num0+2

rems=[num0%4,num1%4,num2%4]
grp=[]
for r in rems:
    in=hps.index(r)
    c=cats[in]
    grp.append(c)

print(grp)


n,m,k=map(int,input().split()))
if m>=n and k>=n:
    print("Yes")
else:
    print("No")


n, m, mi, ma = map(int, input().split())
a = sorted(list(map(int, input().split())))
if n - m >= 2:
    if a[0] >= mi and a[-1] <= ma:
        print('Correct')
    else:
        print('Incorrect')
elif n - m == 1:
    if (a[0] >= mi and a[-1] == ma) or (a[0] == mi and a[-1] <= ma):
        print('Correct')
    else:
        print('Incorrect')
else:
    if a[0] == mi and a[-1] == ma:
        print('Correct')
    else:
        print('Incorrect')


a=input()
result=1
if a[0]!='1':
    print('NO')
    result=0
    break
else:
    for i in range(len(a)):
        if a[i]!='1' and a[i]!='4':
            print('NO')
            result=0
            break
    if result==1:
        length=len(a)
        for i in range(length-2):
            if a[i]=='4' and a[i+1]=='4' and a[i+2]=='4':
                print('NO')
                result=0
                break
if result==1:
    print('YES')


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

import sys
import math
from fractions import Fraction, gcd
from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
getcontext().prec = 100

MOD = 10**9 + 7

n, m = map(int, raw_input().split())
ws = map(int, raw_input().split())
bs = [int(x) - 1 for x in raw_input().split()]

stack = []
weights = []
res = 0
for b in bs:
    # print b, stack, ":", res, "->",
    if b in stack:
        ind = stack.index(b)
        weight = sum(weights[ind + 1:])
        del stack[ind]
        del weights[ind]
    else:
        weight = sum(weights)
    stack.append(b)
    weights.append(ws[b])
    res += weight
    # print res, "(", stack, weights, ")"

print res


lists=input().split()
number_element_max=lists[0]
maximum_value_of_element=lists[1]
nb_normal=1
res=0
for i in range(2,number_element_max):
    number_possibility=0
    liste=primefactors(i)
    for element in liste:
        if element<=maximum_value_of_element:
            number_possibility+=1
    res+=(maximum_value_of_element**i)%998244353
    nb_normal*=number_possibility#nb element de la decomposition de i qui sont valable
    res-=nb_normal

def primefactors(n):
   #even number divisible
   liste=[]
   if n % 2 == 0:
      liste+=[2]

   #n became odd
   for i in range(3,int(math.sqrt(n))+1,2):
      if (n % i == 0):
         liste+=[i]
    return liste


a=map(int,raw_input().split())
n=a.pop(0)
a.sort()

for ans in range(1,n+1):
	OK=1

	b=[1 for i in range(ans)]

	j=0
	for i in range(ans,n):
		if a[i]<b[j]:
			OK=0
			break
		b[j]+=1
		j+=1
		if j==ans:
			j=0

	if OK:
		print ans
		break


i = int(input())
if i < 0:
    print(-46)
else
    print(3000)


k = list(map(int, input().split()))
if k.count(2) > 1 or k.count(1) > 0:
    print('YES')
elif :
    print('YES')
else:
    print('NO')


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


mod = 10**9 + 7
def getAns(maxSide, minSide):
    if maxSide == 1:
        return 2
    if maxSide == 2:
        if minSide == 1:
            return 4
        else:
            return 6
    dpSide = [0] * maxSide
    for i in range(len(dpSide)):
        dpSide[i] = [0, 0]

    dpSide[0] = [1, 1]
    dpSide[1] = [2, 2]
    for i in range(1, len(dpSide)-1):
        dpSide[i+1][0] += dpSide[i][1]
        dpSide[i+1][0] += dpSide[i-1][1] * minSide
        dpSide[i+1][1] += dpSide[i][0]
        dpSide[i + 1][1] += dpSide[i-1][0] * minSide
        dpSide[i+1][0] %= mod
        dpSide[i+1][1] %= mod
    return sum(dpSide[maxSide-1]) % mod

n, m = map(int, input().split())
maxSide = max(n, m)
minSide = min(n, m)
print(getAns(maxSide, minSide))


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

def next(n):
	s = str(n)
	k = len(s)
	if n>int("7"*k):
		return int("4"*(k+1))
	if n<int("4"*k):
		return int("4"*k)
	a=b=c=10**5
	if int(s[0])==4:
		if s[1:]=="":
			a = max(int("4"),n)
		a = max(int("4"+str(next(int(s[1:])))),n)
	if int(s[0])<7:
		b = max(int("7"+"4"*(k-1 if k-1>0 else 0)),n)
	if int(s[0])==7:
		if s[1:]=="":
			c = max(int("7"),n)
		c = max(int("7"+str(next(int(s[1:])))),n)
	return min(a,min(b,c))
last = next(l)
tot = last
for i in range(l+1,r+1):
	if i>last:
		last=next(i)
	tot+=last
print(tot)


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
public class Codeforces
{
    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
        reader = new StreamReader(Console.OpenStandardInput(1024 * 10), System.Text.Encoding.ASCII, false, 1024 * 10);
        writer = new StreamWriter(Console.OpenStandardOutput(1024 * 10), System.Text.Encoding.ASCII, 1024 * 10);
        var n = ReadInt();
        var bak = n;
        var s = ReadToken();
        var ans = new string[100];
        int ind = 0;
        var alpha = Enumerable.Repeat(1, 26).ToArray();
        for (int i = 0; i < s.Length - 1; i++)
        {
            int j = i;
            if (s[i] != s[i + 1] /*&& alpha[s[i] - 'a'] > 0*/)
            {
                if (n == 1)
                {
                    ans[ind] = s.Substring(j);
                }
                else
                {
                    ans[ind++] = s[i].ToString();
                }
                if (alpha[s[i] - 'a'] > 0 )
                {
                    alpha[s[i] - 'a']--;
                    n--;
                }
            }
            else
            {
                for (j = i + 2; j < s.Length; j++)
                {
                    if (s[i] != s[j] /*&& alpha[s[i] - 'a'] > 0*/)
                    {
                        if (n == 1)
                        {
                            ans[ind] = s.Substring(j);
                        }
                        else
                        {
                            ans[ind++] = s.Substring(i, j - i);
                        }
                        if (alpha[s[i] - 'a'] > 0)
                        {
                            alpha[s[i] - 'a']--;
                            n--;
                        }
                        i = j -1;
                        break;
                    }
                }
            }
            if (n == 0)
            {
                Console.WriteLine("YES");
                for (int k = 0; k < bak; k++)
                {
                    Console.WriteLine(ans[k]);
                }
                return;
            }
        }
        Console.WriteLine("NO");
        reader.Close();
        writer.Close();
    }
    #region Read / Write

    private static Queue<string> currentLineTokens = new Queue<string>();

    private static string[] ReadAndSplitLine()
    {
        return reader.ReadLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public static string ReadToken()
    {
        while (currentLineTokens.Count == 0)
            currentLineTokens = new Queue<string>(ReadAndSplitLine());
        return currentLineTokens.Dequeue();
    }

    public static int ReadInt()
    {
        return int.Parse(ReadToken());
    }

    public static long ReadLong()
    {
        return long.Parse(ReadToken());
    }

    public static double ReadDouble()
    {
        return double.Parse(ReadToken(), CultureInfo.InvariantCulture);
    }

    public static int[] ReadIntArray()
    {
        return ReadAndSplitLine().Select(int.Parse).ToArray();
    }

    public static long[] ReadLongArray()
    {
        return ReadAndSplitLine().Select(long.Parse).ToArray();
    }

    public static double[] ReadDoubleArray()
    {
        return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray();
    }
    public static int[][] ReadIntMatrix(int numberOfRows)
    {
        int[][] matrix = new int[numberOfRows][];
        for (int i = 0; i < numberOfRows; i++)
            matrix[i] = ReadIntArray();
        return matrix;
    }
    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows);
        int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++)
        {
            ret[i] = new int[numberOfRows];
            for (int j = 0; j < numberOfRows; j++)
                ret[i][j] = matrix[j][i];
        }
        return ret;
    }

    public static string[] ReadLines(int quantity)
    {
        string[] lines = new string[quantity];
        for (int i = 0; i < quantity; i++)
            lines[i] = reader.ReadLine().Trim();
        return lines;
    }
    public static void WriteArray<T>(IEnumerable<T> array)
    {
        writer.WriteLine(string.Join(" ", array));
    }

    public static void Write<T>(params T[] array)
    {
        WriteArray(array);
    }

    public static void WriteLines<T>(IEnumerable<T> array)
    {
        foreach (var a in array)
            writer.WriteLine(a);
    }
    #endregion
}


n = int(input()) + 1
if n < 5:
  print(0)
  exit()
c = 0
for i in range(n):
  if str(i).replace('0', '') == '5':
    c = 1
  elif str(i)[-1] != '9':
    c += 1
print(c)


import sys

def readints() :
    l = sys.stdin.readline()
    return map(int, l.split(' '))

def readstring() :
    l = sys.stdin.readline()[:-1]
    return l

def readint() :
    l = sys.stdin.readline()
    return int(l)

def clearchars(s, chars) :
    for c in chars :
        s = s.replace(c, '')
    return s

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

def hist(a) :
    h = {}
    for x in a :
        try :
            h[x] += 1
        except KeyError :
            h[x] = 1
    return h

def lucky(n) :
    s = set(str(n))
    return all(map(lambda x: x in '47', s))

def yslice(a, j) :
    return map(lambda x: x[j], a)

def dist2(a, b) :
    return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5

def chain_len(a) :
    l = .0
    for d, e in zip(a, a[1:]) :
        l += dist2(d, e)
    return l

def is_prime(x) :
    if x == 1 :
        return False
    sq = int(x ** 0.5)
    for i in [2] + range(3, sq + 1, 2) :
        if x % i == 0 :
            return False
    return True

digits = '0123456789'

def noe() :
    print "NO"
    exit(0)

def yese() :
    print "YES"
    exit(0)

n, m = readints()

a = []
for i in range(n) :
    a.append(readstring())

c = 0
for i in range(n) :
    for j in range(m) :
        if a[i][j] == 'W' :
            if (i - 1 >= 0 and a[i-1][j] = 'P') or (i + 1 < n and a[i+1][j] = 'P') or (j - 1 >= 0 and a[i][j-1] = 'P') or (j + 1 < m and a[i][j+1] = 'P') :
                c += 1

print c


n = int(raw_input())
s = raw_input()
cords = []
for c in s:
    c = int(c)
    if c == 0:
        row, col = 3, 1
    else:
        row, col = (c-1)/3, (c-1)%3
    cords.append((row, col))
variants = 0

def tryforxy(curx, cury):
    isValid = True
    for i in range(1, len(cords)):
        curx += cords[i][0] - cords[i-1][0]
        cury += cords[i][1] - cords[i-1][1]
        if curx == 3 and cury == 1:
            continue
        elif curx >= 0 and curx < 3 and cury >= 0 and cury < 3:
            continue
        else:
            isValid = False
    return isValid

for x in range(3):
    for y in range(3):
        variants += tryforxy(x, y)
variants += tryforxy(3, 1)
    variants += 1
if variants > 1:
    print "NO"
else:
    print "YES"


while i<len(x):
  if sum>m:
    sum=0
    bus=bus+1
    flag=True
    i-=1
  else:
    sum=sum+x[i]
    i+=1
    flag=False
if flag ==False:
  bus=bus+1
print(bus)


a, b, c, d, e = map(int, input().split(' ')); print(min(a, b, c//2, d//7, e//4)


NEAT="AEFHIKLMNTVWXYZ"
a=input()
if x in NEAT for x in a :
               print("YES")
else:
               print("NO")


x, y = [int(u) for u in input().strip().split()]
flag = True
last = -1
while x:
    p = x % y
    if p <= last or p == 0:
        flag = False
        break
    last = p
    x //= y
print("YES" if flag else "NO")


n=int(raw_input())
squareFreePart=1
while(n>1):
    for p in range(2,n+1):
    	if(n%p==0):
			while(n%p==0):
				n=n/p
			squareFreePart*=p
			break
print(squareFreePart)


from math import trunc

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

a, b = map(int, input().split())
mcd = int(a * b / gcd(a, b))
t = []
p, q = 0, 0
if a != 1 and b != 1:
    t.append(1)
for i in range(1, mcd):
    if i % a == 0:
        p += i - t[len(t) - 1]
        t.append(i)
    elif i % b == 0:
        q += i - t[len(t) - 1]
        t.append(i)
if a > b:
    p += 1
else:
    q += 1
if p > q:
    print('Dasha')
elif p < q:
    print('Masha')
else:
    print('Equal')


from sys import stdin, stdout

for q in range(int(input())):
	a, b, m = map(int, input().split())

	if a == b:
		print(1, a)
		continue

	k = 2

	while k <= 50 and not ((1 << (k-2)) * (a+1) <= b <= (1 << (k-2)) * (a+m)):
		k += 1

	if k > 50:
		print(-1)
		continue

	t = b - (1 << (k-2)) * (a+1)

	add = [1] * (k-1)
	add[0] = a

	for i in range(1, k-1):
		while add[i] < m and t >= (1 << (k-2-i)) * add[i]:
			add[i] += 1
		t -= (1 << (k-2-i)) * (add[i] - 1)

	ans = [a] * (k-1)
	for i in range(1, k-1):
		ans[i] = ans[i-1] * 2 - add[i-1] + add[i]
	print(k, ' '.join(str(i) for i in ans), b)


n,k = map(int,input().split())
for x in range(n,10**10):
    if((x%k) * (x//k) == n):
        print(x)
        exit()


k,p=map(int, input().split())
m=[]
j = 0
while True:
    j+=1
    if j%10!=0:
        m+=[str(j)[::-1]+str(j)]
    if j==10000000:
        break
j=0
for i in range(k):
    j+=int(m[i])
print(j%p)


n=int(input())
s=list(map(int,input().split()))
print("Bob"if s.count(min(s))>n/2 else"Alice")


n=int(input())
ch=input()
s=0
i=0
if ch.count(ch[0])==n:

    print((n+1)//2))
else:
    while i<n:
        for j in range(i+1,n+1):
            a=ch[j+1:n].find(ch[i:j])
            if a>=0:
                s+=1+a-i
                i+=a+j-i
                break
            elif j==n:
                s+=n-i
                i=n

    print(s)


[a,b,c] = (input().split(' '))
a = int(a)
b = int(b)
c = int(c)
days = 0;

factor = 10000000
while factor!=1:
    while a>2*factor and b>1*factor and c>1*factor:
        a -= 3*factor
        b -= 2*factor
        c -= 2*factor
        days += 7*factor
    factor /= 10

while a>2 and b>1 and c>1:
    a -= 3
    b -= 2
    c -= 2
    days += 7

if c>1 and b>1:
    if a==0:
        days += 2
    elif a==1:
        days += 3
    elif a==2:
        days += 4

elif c>1 and a>2:
    if b==0:
        days += 3
    elif b==1:
        days += 6

elif b>1 and a>2:
    if c==0:
        days += 4
    elif c==1:
        days += 6

elif c>1:
    if b==0 and a==0:
        days += 1
    elif b==0 and a==1:
        days += 2
    elif b==0 and a==2:
        days += 2
    elif b==1 and a==0:
        days += 2
    elif b==1 and a==1:
        days += 4
    elif b==1 and a==2:
        days += 5

elif b>1:
    if c==0 and a==0:
        days += 1
    elif c==0 and a==1:
        days += 2
    elif c==0 and a==2:
        days += 4
    elif c==1 and a==0:
        days += 2
    elif c==1 and a==1:
        days += 3
    elif c==1 and a==2:
        days += 5

elif a>2:
    if b==0 and c==0:
        days += 2
    elif b==0 and c==1:
        days += 2
    elif b==1 and c==0:
        days += 3
    elif b==1 and c==1:
        days += 5

else days += (a+b+c)
print(days)


import math

x = input()
y = input()
d = x % y
now = d
l = len(str(x))
s = str(x)
zz = pow(10, l-1, y)

for i in xrange(1, l):
    t = int(s[i-1])
    now -= t*zz%y
    now += y
    now = (now * 10 + t)%y
    if now < d:
        d = now
print d


f0 = "What are you doing at the end of the world? Are you busy? Will you save us?"
P1 = "What are you doing while sending \""
P2 = "\"? Are you busy? Will you send \""
P3 = "\"?"
f = []
def dfs(n, k):
    if(k > f[n]): return '.'
    if(n == 0): return f0[k - 1]
    if(k <= 34): return P1[k - 1]
    if(k <= f[n - 1] + 34): return dfs(n - 1, k - 34)
    if(k <= f[n - 1] + 66): return P2[k - f[n - 1] - 35]
    if(k <= f[n - 1] * 2 + 66): return dfs(n - 1, k - f[n - 1] - 66)
    return P3[k - f[n - 1] * 2 - 66 - 1]
f.append(75)
cnt = 0
for i in range(100000):
    f.append(f[cnt] * 2 + 68)
    cnt += 1

q = int(input())
while q > 0:
    q -= 1
    n, k = map(int, input().split(' '))
	while n > 70:
		k -= 34
		n -= 1
    print(dfs(n, k), end='')


k = input().split()
n = int(k[0])
m = int(k[1])
k = int(k[2])

if ( k <= n+m-2 ):
    if ( k < n ):
        outn = int((n / (k + 1)) * m)
    else:
        outn = int(m / (k - n + 2))
    if ( k < m):
        outm = int( m / ( k + 1)) * n
    else:
        outm = int( n / ( k - m + 2 )
    return ( max( outn, outm))
return -1


l = list(map(int,input().split());print(min(sum(l)//3 , sum(l) - max(l)))


'''input
7
2 3 4 1 6 7 5
'''

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

def ri():
    return int(input())

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

def lcm(xs):
    if not xs:
        return 1
    if len(xs) == 1:
        return x[0]
    if len(xs) == 2:
        return (xs[0] * xs[1]) // gcd(xs[0], xs[1])
    return lcm(xs[:-2] + [lcm([xs[-2], xs[-1]])])

def dfs_cycle_length(arr, u, visited, origin):
    visited.add(u)
    nxt = arr[u-1]
    if nxt in visited:
        return None if nxt != origin else 1
    tmp = dfs_cycle_length(arr, nxt, visited, origin)
    return None if tmp is None else tmp + 1

def solve(arr):
    cycles = []
    visited = set([])
    for u in range(1, len(arr) + 1):
        if u not in visited:
            length = dfs_cycle_length(arr, u, visited, u)
            if length is None:
                return -1
            cycles.append(length//2 if length % 2 == 0 else length)
    return lcm(cycles)

def main():
    n = ri()
    arr = rints()
    print(solve(arr))

main()


n = int(input())
a = int(input())
b = int(input())
first = n
if n % a == 0:
    print('YES')
    print(n//a, 0)
    elif n % b == 0:
    print('YES')
    print(0, n // b)
else:
    while n % a and n > 0:
        n -= b
        if n < 0:
            print('NO')
        else:
            print('YES')
            print(n//a, (first-n) // b)


n, q = map(int, raw_input().split())
op = {'a':set(),'b':set(),'c':set(),'d':set(),'e':set(),'f':set()}
for _ in xrange(q):
	a, b = raw_input().split()
	if op.has_key(b):
		op[b].add(a[0])

# print op

if len(op['a']) > 0:
	s = ['a']
	for _ in xrange(1,n):
		s1 = []
		for c in s:
			for x in op[c]:
				s1.append(x)
		s = s1
		#print s
	#print s
	print len(s)
else:
	print 0


r, h = map(int, raw_input().split())
p = h / r
q = h % r
if 2 * q > (3. ** 0.5) * r: print 2 * p + 3
elif 2 * q < r: print 2 * p + 1
else: print 2 * p + 2


from math import log
k, b, n, t = map(int, input().split())
print(n - int(log( (k * t - t + b) / (k - 1 + b)) / log(k)))


pri=pow(10,9)+7
import sys
input=sys.stdin.readline

a=int(input())
for i in range(a):
    n,k=map(int,input().split())

    if(k==0):
        print(1)
        continue;

    ans=[0 for i in range(k)]

    if(n%2==0):
        ways=pow(2,n-1,pri)
    else:
        ways=pow(2,n-1,pri)
        ways+=1
    ans[0]=ways

    for i in range(1,k):
        if(n%2==0):
            ways=pow(2,n-1,pri)
        else:
            ways=pow(2,n-1,pri)

            ways+=1
        ways%=pri

        if(n%2==0):
            ans[i]=ans[i-1]*(ways-1)
            ans[i]+=pow(2,n*i,pri)
        else:

            ans[i]=ans[i-1]*ways
            ans[i]%=pri
    print(ans[-1])


'''input
ababb
5
'''
from sys import stdin
import math

def get_normal_length(string):
	l = 0
	for i  in string:
		if i != '*' and i != '?':
			l += 1
	return l

def get_special(string):
	count = 0
	for i in string:
		if i == '?' or i =='*':
			count += 1
	return count

# main start
string = list(stdin.readline().strip())

n = len(string)
k = int(stdin.readline().strip())
normal = get_normal_length(string)

if k > normal :
	if '*' in string:
		diff = k - normal
		flag = False
		for i in range(len(string)):
			if string[i] == '?':
				continue
			elif string[i] == '*'
				if flag == False:
					flag = True
					for _ in range(diff):
						print(string[i - 1], end = '')
			else:
				print(string[i],end = '')

	else:
		print("Impossible")
		exit()

elif k < normal:
	if '*' in string or '?' in string:
		diff = normal - k
		number = get_special(string)
		if number >= diff:
			i = 0
			count = 0
			while i < n and count < diff:
				if string[i] != '*' and string[i] != '?':
					try:
						if string[i + 1] == '*' or string[i + 1] == '?':
							i += 2
							count += 1
							continue
						else:
							print(string[i], end= '')
							i += 1
							continue
					except:
						print(string[i], end='')
						i += 1
						continue

				i += 1

			if i < n:
				while i < n:
					if string[i] != '*' and string[i] != '?':
						print(string[i], end = '')
					i += 1
			exit()

		else:
			print("Impossible")
			exit()
	else:
		print("Impossible")
		exit()
else:
	for i in string:
		if i != '?' and i != '*':
			print(i, end='')


n = int(raw_input())
m = 1000000007
def ppp(a, k, n):
    b = 1
    while k:
        if k % 2 == 0:
            k /= 2
            a = (a * a) % n
        else:
            k -= 1
            b = (b * a) % n
    return b
tnm1 = ppp(2, n - 1, m)
print (tnm1 * (1 + tnm1 * 2)) % m


from sys import stdin
n,p,t = stdin.readline().strip().split()
n=int(n)
p=float(p)
t=int(t)
q = 1.0-p
a = [1]
b = [1]
for i in xrange(1,3005):
 	a.append(p*a[i-1])
 	b.append(q*b[i-1])
dp= []
for i in xrange(t+n+2):
	a=[]
	for j in xrange(2+t+n):
		a.append(0)
	dp.append(a)
dp[0][0] = 1
for i in xrange(t+1):
	for j in xrange(n+1):
		#print "for ",i,j," is ",dp[i][j]
		if j>=n:
			dp[i+1][j]+=dp[i][j]
		else:
			dp[i+1][j] +=dp[i][j]*q
			dp[i+1][j+1]+=dp[i][j]*p
ans = 0
for i in xrange(n+1):
	ans+=i*dp[t][i]
print ans


a = map(int, input.split())
b = map(int, input.split())
print('YES' if sum([(x - y) ** 2 for x, y in zip(a,b)]) == 9 else 'NO')


#!/usr/bin/python
import sys

def f(x, s, index, length):
	a = int(s[index])
	if index == length - 1:
		return 2 if (a + x) % 2 == 1 else 1
	if (a + x) % 2 == 0:
		return f( (a+x)/2, s, index+1, length)
	else:
		return f( (a+x)//2, s, index+1, length) + \
			   f( (a+x)//2+1, s, index+1, length)

def selfInclude(s):
	for i in range(0, len(s)-1):
		a = int(s[i])
		b = int(s[i+1])
		if abs(a-b) > 1:
			return False
	return True

s = sys.stdin.readline().strip()
result = 0
if len(s) == 1:
	print 9
	sys.exit(0)

for i in range(10):
	result += f(i, s, 1, len(s))
print result-1 if selfInclude(s) else result


raw_input()
party = [int(x) for x in raw_input().split()]
total_beat = sum(party) // 2
s = party[0]
alice = party[0] // 2
if s > total_beat:
    print('1')
    print('1')
else:
    p = ['1']
    for i, other in enumerate(party[1:],2):
        if other <= alice
            s += other
            p.append(str(i))
            if s > total_beat:
                print(len(p))
                print(''.join(p))
    else:
        print('0')


def main():
    p = [1]
    for i in range(1,11):
        p.append(p[i-1]*2)
    hr = '12345RGBYW'
    gt = {'1': 0,'2': 1,'3': 2,'4': 3,'5': 4,'R': 5,'G': 6,'B': 7,'Y': 8,'W': 9}

    def check(c,mask):
        tmp = gt[c]
        if (mask // p[tmp]) % 2 == 1:
            return True
        return False

    def count(mask):
        tmp = 0
        while mask>0:
            tmp+=mask % 2
            mask//=2
        return tmp

    n = int(input())
    a = list(input().split())
    ans = 10
    for mask in range(1024):
        f = True
        for i in range(n):
            for j in range(i+1,n):
                if a[i] == a[j]:
                    pass
                elif (a[i][1] != a[j][1]) and (check(a[i][1],mask) or check(a[j][1],mask)):
                    pass
                elif (a[i][0] != a[j][0]) and (check(a[i][0],mask) or check(a[j][0],mask)):
                    pass
                else:
                    f = False
                    break
            if not f:
                break
        if f:
            ans = min(ans,count(mask))
    print(ans)
main()


n=int(input())
for i in range(n,0,-1)
if n%i=0
n=i
print(n)


#include <iostream>
using namespace std;

int a,b,t,i,count=0,c[]={6,2,5,5,4,5,6,3,7,6};
int main() {
	std::cin>>a>>b;
	for(i=a;i<=b;i++)
	{
		t=i;
		while(t>0)
		{
			cout<<t%10<<" "<<c[t%10]<<"\n";
			count+=c[t%10];
			t=t/10;
		}
	}
	//std::cout<<count;
	return 0;
}


def solve(a):
    total_sum = 0
    while True:
        current_sum = 0
        zero_count = 0
        one_count = 0
        for i in range(6):
            if a[i] == 0:
                zero_count += 1
                continue
            if a[i] == 1:
                one_count += 1
            current_sum += a[i] * 2 - 1
        current_sum -= (zero_count * 2)

        if zero_count >= 3 or (zero_count == 2 and one_count == 2):
            break
        b = []
        for i in range(6):
            if a[i] == 0:
                b.append(0)
                continue
            b.append(a[i] - 1)
            if a[i - 1] == 0:
                b[-1] -= 1
            if a[(i + 1) % 6] == 0:
                b[-1] -= 1
        a = b
        total_sum += current_sum

    zero_count = len(list(filter(lambda x: x == 0, a)))

    if zero_count == 3:
        return total_sum + (sum(a) // 3) ** 2
    elif zero_count == 2:
        return total_sum + sum(sorted(a, reverse=True)[:2])
    return total_sum

assert solve([2, 4, 5, 3, 3, 6]) == 83
assert solve([45, 19, 48, 18, 46, 21]) == 6099
assert solve([1, 2, 1, 2, 1, 2]) == 13
assert solve([1, 1, 1, 1, 1, 1]) == 6
assert solve([7, 5, 4, 8, 4, 5]) == 175
a = list(map(int, input().split()))

r = solve(a)
print(r)


n=int(input())
l=list(map(int,input().split()))
p=sum(l)b
r=max(l)
for i in range(r,p):
	s=n*i
	if s-p>p:
		print(i)
		break


import sys
import math

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

w, b = map(int, raw_input().split())

dp = [[2.0 for i in xrange(b + 1)] for j in xrange(w + 1)]

#print dp

def DP(wi, bi, dp):
    if 0 == wi:
        return 0
    ans = float(wi) / (wi + bi)
    if 0 == bi or 1 == bi:
        dp[wi][bi] = ans
        return ans

    s = float(bi) / (wi + bi) * float(bi - 1) / (wi + bi - 1)
    ans += s * (float(wi) / (wi + bi - 2) * DP(wi - 1, bi - 2, dp))
    if bi > 2:
        ans += s * float(bi - 2) / (wi + bi - 2) * DP(wi, bi - 3, dp)
    dp[wi][bi] = ans
    return ans

ans = DP(w, b, dp)

print ans


def erathos2(k):
	mark = [True for i in range(k)]
	i = 2
	while (i < k):
		if !mark[i]:
			i += 1
			continue
		for j in range(2*i,k,i):
			mark[j] = False
		i+=1
	p = [i for i in range(2,k) if mark[i]]
	return p

def sum2(p, n):
	for i in p:
		if i > n:
			break
		if n-i in p:
			return(i, n-i)
	return (-1,-1)

def sum3(p, n):
	for i in p:
		if i > n:
			break
		(a,b) = sum2(p,n-i)
		if a >= 0:
			return (i,a,b)
	return (-1,-1,-1)

n = int(raw_input())
p = erathos2(n+1)
#print p
if n in p:
	print 1
	print n
else:
	(a,b) = sum2(p,n)
	if a >= 0:
		print 2
		print a, b
	else:
		(a,b,c) = sum3(p,n)
		print 3
		print a, b, c


n = int(input())
weights = list(input())
print(n, weights)
weights.sort()

# instability if i, j are single kayakers
def get_instability(i, j):
    test = list(weights)
    test.pop(i)
    test.pop(j)
    instability = 0
    for k in range(0, len(test) - 1, 2):
        instability += abs(weights[k] - weights[k+1])
    return instability

instabilities = []
for i in range(len(weights)):
    for j in range(len(weights)):
        if i == j:
            continue
        instabilities.append(get_instability(i, j))

print min(instabilities)


a= int(input())
c=[]

for i in range(a):
    if all(((i**j)-1)%a !=0 for j in range(1,a-1)) and (i**(a-1)-1)%a==0:
        c.append(i)
print(len(c))


s = input()
k = int(input())
n = len(s)

maxLen = 0
for i in range(0, n):
	for j in range(i, n):
		half = j - i + 1
		if 2 * half <= maxLen:
			continue

 		hi = min(j + half + 1, n)
		hi2 = i - j - 1 + hi

		if s[i:hi2] == s[j + 1:hi] and j + half - n + 1 <= k:
			maxLen = 2 * half

print(maxLen)


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

print(n)
print(m)
print(a)

head = 0
tail = len(a) - 1
res = 0

while (1):
	if ( res == len(a)):
		break
	if ( a[head] <= m and head +1 != tail):
		res += 1
		head += 1
	if ( a[tail] <= m and tail -1 != head):
		res += 1
		tail -= 1
	if ( a[head] > m and a[tail] > m ):
		break
print(res)


def gen_all(i, j, p, n, a):
  if p > n:
    yield a
    return
  a[i] = p
  yield from gen_all(i + 1, j, p + 1, n, a)
  a[j - 1] = p
  yield from gen_all(i, j - 1, p + 1, n, a)

n, m = map(int, input().split())
it = gen_all(0, n, 1, n, [0] * n)
for _ in range(m):
  ans = next(it)
  # print(ans)
print(' '.join(map(str, ans)))


import sys
inp = str( raw_input() )
hand = list ( str(raw_input().split(' ') ) )

for i in inp:
	if i in hand:
		print "YES"
		exit()
	else:
		continue
print "NO


n,k=map(int,raw_input().split())
ar=map(int,raw_input().split())
i=0
c1=ar.count(1)
c2=ar.count(2)
c3=10**9
while(i<=(n-k)):
    l1=(ar[i:i+k])
    j=0
    temc=0
    while (j<=(n-k)):
        l2=ar[j:j+k]
        for t in xrange(k):
            if l1[t]!=l2[t]:
                temc+=1
        j+=k
    c3=min(temc,c3)
    i+=k
print min(c3,c1,c2)


class Subject:
    def __init__(self, id, low, high, complexity):
        self.id = id
        self.low = low
        self.high = high
        self.complexity = complexity
        self.day_links = [ {} for i in range(high - low + 1) ]

    def add_link(self, link):
        days = link.days
        links = self.day_links[link.weight - self.low]
        if days not in links or links[days].total < link.total:
            links[days] = link

    def __str__(self):
        return '[%d [%d, %d] %d]' % (self.id,
                self.low, self.high, self.complexity)

class Link:
    def __init__(self, subject, weight, total, days, previous):
        self.subject = subject
        self.weight = weight
        self.total = total
        self.days = days
        self.previous = previous

class Group:
    def __init__(self, complexity):
        self.complexity = complexity
        self.subjects = []

need_days, num_subjects, more = map(int, input().split())
groups = {}
for i in range(num_subjects):
    subject = Subject(i + 1, *list(map(int, input().split())))
    if subject.complexity not in groups:
        groups[subject.complexity] = Group(subject.complexity)
    groups[subject.complexity].subjects.append(subject)
groups = sorted(groups.values(), key = lambda group: group.complexity)
num_groups = len(groups)

def win(link):
    print('YES')
    schedule = need_days * [ None ]
    while link:
        subject = link.subject
        subject.weight = link.weight
        schedule[link.days - 1] = subject
        link = link.previous
    for subject in schedule:
        print(subject.id, subject.weight)
    import sys
    sys.exit()

best_link = None

for pos, group in enumerate(groups):
    #print(pos, '', '  '.join(map(str, group.subjects)))
    if num_groups - pos >= need_days:
        for subject in group.subjects:
            for weight in range(subject.low, subject.high + 1):
                subject.add_link(Link(subject, weight, weight, 1, None))
    for subject in group.subjects:
        for i, links in enumerate(subject.day_links):
            weight = subject.low + i
            for days, link in links.items():
                if link.weight != weight:
                    print('expected weight %d, link has weight %d' % (
                        weight, link.weight))
                    import sys; sys.exit()
                if days == need_days:
                    if not best_link or best_link.total < link.total:
                        best_link = link
                    continue
                for next_weight in [ weight + more, weight * more ]:
                    max_pos = num_groups + days - need_days
                    for next_pos in range(pos + 1, max_pos + 1):
                        for next_subject in groups[next_pos].subjects:
                            if next_weight < next_subject.low:
                                continue
                            if next_weight > next_subject.high:
                                continue
                            next_subject.add_link(Link(
                                next_subject, next_weight,
                                next_weight + link.total, days + 1, link))
                            #print('%d -> %d (%d)' % (link.weight,
                            #    next_weight, days + 1))

if best_link:
    win(best_link)
else:
    print('NO')


from itertools import permutations
n, L = list(map(lambda x: int(x), input().split()))
k = list(map(lambda x: int(x), input().split()))
s = list(map(lambda x: int(x), input().split()))
j = 1
for i in range(L):
    for x in range(len(s)):
        s[x] += 1
        if s[x] == L:
            s[x] = 0
    if any(tuple(k) == y for y in list(permutations(s))):
        print('YES')
        j = 0
        break
if j == 1:
    print('NO')


n=int(input())
y={}
y[0] = 0
# print(x)
for i in range(1,n+1):
    x=i
    dmax = 0
    while(x>0):
        d=x%10
        if(d>dmax):
            dmax = d
        x=x//10
    y[i]=y[i-dmax]+1
print(y[n])


#!/usr/bin/env python

'''
this is docstring
'''

from sys import stdin

def main():
    '''
    this is docstring
    '''
    while True:
        try:
            _hh, _mm = map(int, stdin.readline().split(':'))
        except ValueError:
            break

        _tt = _hh * 60 + _mm
        i = 0
        while True:
            if _tt % 60 % 10 == _tt / 60 / 10 and _tt % 60 / 10 == _tt / 60 % 10:
                print i
                break
            _tt = (_tt + 1) % (24 * 60)
            i += 1

if __name__ == '__main__':
    main()


def cmb(n, r, mod):#コンビネーションの高速計算
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod =  998244353#出力の制限
N = 2*10**5
g1 = [1]*(N+1) # 元テーブル
g2 = [1]*(N+1) #逆元テーブル
inverse = [1]*(N+1) #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1[i]=( ( g1[i-1] * i ) % mod )
    inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2[i]=( (g2[i-1] * inverse[i]) % mod )
inverse[0]=0

n = int(input())
res = 0
for k in range(1,n+1):
    if (n-k) % 2==0:
        res += cmb((n-k)//2+k-1,k-1,mod)
        res %= mod

res *= pow(inverse[2],n,mod)
res %= mod
print(res)


import numpy as np
n=int(input())
li=[]
for i in range(n):
    a=list(map(int,input().split()))
    li.append(a)
li=np.array(li)
for i in range(n):
    for j in range(n):
        if(i==j):
            count+=1
        if(i+j==n):
            count+=1
for j in range(n):
    count+=a[n//2][j]
for i in li[:,n//2]:
    count+=i

count-=3*li[n//2][n//2]


#!/usr/bin/env python3

[n, m] = map(int, input().strip().split())
ais = list(map(int, input().strip().split()))
bis = list(map(int, input().strip().split()))

ais = [set(ais[2*i: 2*i + 2]) for i in range(n)]
bis = [set(bis[2*i: 2*i + 2]) for i in range(m)]

def check(pair, pairs):
	res = []
	for p in pairs:
		s = pair & p
		if len(s) == 1:
			res.append(s.pop())
	res = list(set(res))
	if len(res) == 1:
		return res[0]
	elif len(res) > 1:
		return -1
	else:
		return 0

va = [check(a, bis) for a in ais]
vb = [check(b, ais) for b in bis]

vap = [v for v in va if v > 0]
vbp = [v for v in vb if v > 0]

vap = set(vap)
vbp = set(vbp)

vabp = vap & vbp

if len(vabp) == 1:
	print (vabp.pop())
elif -1 not in va and -1 not in vb:
	print (0)
else:
	print (-1)


import sys

x, y = map(int, sys.stdin.readline().split())

ax, ay = 0, 0
bx, by = 0, 0

def onsegment():
    if ax == bx:
        return (x == ax) and (
        (ay > by and ay > y >= by) or
        (ay < by and ay < y <= by))
    else:
        return (y == ay) and (
        (ax > bx and ax > x >= bx) or
        (ax < bx and ax < x <= bx))

if x == 0 and y == 0:
    print 0
    exit(0)

turn = -1
while True:
    turn += 1
    bx, by = 1 - ax, ay
    if onsegment(): break

    turn += 1
    ax, ay = bx, by
    bx, by = ax, 1 - by
    if onsegment(): break

    turn += 1
    ax, ay = bx, by
    bx, by = -ax, by
    if onsegment(): break

    turn += 1
    ax, ay = bx, by
    bx, by = ax, -by
    if onsegment(): break

print turn


N,S,Q = map(int, input().split(" "))

counter=1
while True:
    x = round(S/(1 - (Q - 1)/Q),9)
    if x >= N:
        break
    counter+=1
print(counter)


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

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


from operator import mul
from functools import reduce

def extract_factor(n, f):
    a = 0
    while n % f == 0:
        n /= f
        a += 1
    return a

def subtract_from_list(l, d):
    for e, i in enumerate(l):
        l[e], d = max(0, i - d), max(0, d - i)
        if d == 0:
            break
    assert d == 0, 'should have enough to subtract'

def solve(size1, size2):
    sizes = [list(size1), list(size2)]
    factor2 = [[extract_factor(n, 2) for n in s] for s in sizes]
    factor3 = [[extract_factor(n, 3) for n in s] for s in sizes]
    base = [[x // 2 ** y // 3 ** z for x, y, z in zip(s, f2, f3)] for s, f2, f3 in zip(sizes, factor2, factor3)]

    if reduce(mul, base[0]) != reduce(mul, base[1]):
        return

    factor2_total = [sum(x for x in f2) for f2 in factor2]
    factor3_total = [sum(x for x in f3) for f3 in factor3]

    d3 = factor3_total[0] - factor3_total[1]
    l = factor3[(1, 0)[d3 > 0]]
    subtract_from_list(l, abs(d3))
    factor2_total[(1, 0)[d3 > 0]] += abs(d3)
    l = factor2[(1, 0)[d3 > 0]]
    l[(1, 0)[d3 > 0]] += abs(d3)

    d2 = factor2_total[0] - factor2_total[1]
    l = factor2[(1, 0)[d2 > 0]]
    subtract_from_list(l, abs(d2))

    size_after = tuple(
            tuple(x * (2 ** y) * (3 ** z) for x, y, z in zip(b, f2, f3)) for b, f2, f3 in zip(base, factor2, factor3))
    return abs(d3) + abs(d2), size_after[0], size_after[1]

if __name__ == '__main__':
    size1 = tuple(int(x) for x in raw_input().split())
    size2 = tuple(int(x) for x in raw_input().split())
    ans = solve(size1, size2)
    if ans is None:
        print -1
    else:
        m, s1, s2 = ans
        print m
        print s1[0], s1[1]
        p


dr = [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]

n = int(input())
t = [int(i) for i in input().split()]
visited = set()

def dfs(d, pos, path):
    mem = (d, pos, path)
    if mem in visited:
        return set()
    else:
        visited.add(mem)
    if d == n+1:
        return set()
    cell = set()
    c = t[d-1]
    for _ in range(c):
        pos = (pos[0] + dr[path][0], pos[1] + dr[path][1])
        cell.add(pos)
    cell = cell.union(dfs(d+1, pos, (path+1) % 8))
    cell = cell.union(dfs(d+1, pos, (path-1) % 8))
    return cell

total_cells = dfs(1, (0, 0), 0)
print(len(total_cells))


import datatime
date1=datatime.datatime.strptime(input(),"%Y:%m:%d")
date2=datatime.datatime.strptime(input(),"%Y:%m:%d")
print(abs((date2-date1).days))


n = int(raw_input())
def get_facs(n):
	n1 = n
	facs = []
	i = 2
	while i*i <= n1:
		if n1 % i == 0:
			facs.append([i, 0])
			while n1 % i == 0:
				facs[-1][1] += 1
				n1 /= i
		i += 1
	if n1 > 1:
		facs.append([n1, 1])
	return facs

def sep(x, a, i=1):
	# seperate x into 3 piece x1,x2,x3, x2 <= x3, xi >= 1
	if i==3:
		a[2] = x - a[0] - a[1]
		if a[2] >= 0 and a[2] <= x:
			yield a
		return
	for xi in xrange(0, x+1):
		a[i-1] = xi
		for y in sep(x, a, i+1):
			yield y
		a[i-1] = 0

max_n, min_n = 0, n*n*n

def extract(chs, facs):
	ans = [1] * 3
	for i,(fac,c) in enumerate(facs):
		for j in xrange(3):
			ans[j] *= fac ** chs[i][j]
	return ans

def dfs(chs, i, k):
	if i == k:
		a, b, c = extract(chs, facs)
		n0 = (a+1) * (b+2) * (c+2)
		# print a, b, c, n0
		global max_n, min_n
		max_n = max(max_n, n0)
		min_n = min(min_n, n0)
		return
	for ch in sep(facs[i][1], [0]*3):
		chs[i] = ch
		dfs(chs, i+1, k)

facs = get_facs(n)
if n == 1:
	print 17, 17
else:
	k = len(facs)
	dfs([0]*k, 0, k)
	print min_n - n, max_n - n


N=int(input())
num=[]
i=0
IN=input().split()
while(i<N):
		num.append(int(IN[i]))
		i=i+1
num.sort()
num.reverse()
for i in range(1,len(num)-1):
		num[i]=num[len(num)-1-i]
for i in num
	print(i)


n, mod = map(int, input().split())
fact = 1
if n <= 3:
    print(0)
else:
    for i in range(1, n+1):
        fact *= i
        fact %= mod
    print((fact-7)%mod)


n,k=map(int,input().split())
l=1
r=n
while(l<r):
    sum=0
    x=v=(l+r)//2
    while(x>0):
        sum+=x
        x//=k
    if sum>=n:
        r=
    else:
        l=v+1
print(r)


import numpy as np

def myf(n,mylist):
    result = [20 for i in range(n)]
    begin_t = 0
    Big_begin_t = 0

    #for i in range(n):
    i = 0
    while (i < n):
        if ((mylist[i] - mylist[Big_begin_t]) < 1440):
            if (np.sum(result[Big_begin_t:i+1]) > 120):
                result[i] = 120 - np.sum(result[Big_begin_t:i])
            else:
                if ((mylist[i] - mylist[begin_t]) < 90):
                    if (np.sum(result[begin_t:i+1]) > 50):
                        result[i] = 50 - np.sum(result[begin_t:i])
                    else:
                        result[i] = 20

                else:
                    begin_t += 1
                    i = i -1
        else:
            Big_begin_t += 1
            i = i -1
        i +=1

    return (result)

# Ввод данных
n = int(input())
for i in range(n):
    mylist.append(int(input()))
res = myf(n,mylist)
print (res)


import sys
from math import *

w = 'white'
b = 'black'

def gcl(x, y):
    fc = sqrt(x**2 + y**2)
    c = int(fc)
    if c % 2 == 0:
        result = b
    else:
        result = w
    if not ((x > 0 and y > 0) or (y < 0 and x < 0)):
        if result == b:
            result = w
        else:
            result = b

    if c == fc:
        result = b
    return result

def main(argv=None):
    if argv is None:
        argv = sys.argv
    if len(sys.argv) != 3:
        return -1

    print( gcl(int(argv[1]), int(argv[2])) ),
    return 0

if __name__ == "__main__":
    sys.exit(main())


import math as m

s = input().split("=")
left = s[0].split("+")
a = len(left[0])
b = len(left[1])
right = len(s[1])

if a+b+right % 2 == 1 or a+b+right % 2 == -1 m.fabs(right-a-b) > 2:
    print("Impossible")

# if m.fabs(right-a-b) == 1 or m.fabs(right-a-b) > 2:
#     print("Impossible")

# if a+b+right % 2 == 1:
#     print("Impossible")
# elif m.fabs(right-a-b) != 2 and right != a+b:
#     print("Impossible")

elif a+b == right:
    print(a*"|","+",b*"|","=",right*"|",sep="")
elif right-a-b == 2:
    right -= 1
    b += 1
    print(a*"|","+",b*"|","=",right*"|",sep="")
elif right-a-b == -2:
    right += 1
    if b > 1:
        b -= 1
    else:
        a -= 1
    print(a*"|","+",b*"|","=",right*"|",sep="")


a, c = map(int, raw_input().split())
def to3base(n):
    l = ''
    while n > 0:
        l = l + str(n%3)
        n /= 3
    return l
a3 = to3base(a)
c3 = to3base(c)
i, j = 0, 0
b3 = ''
x, y = 0, 0
while i < len(a3) or j < len(c3):
    if i >= len(a3): x = 0
    else: x = a3[i]
    if j >= len(c3): y = 0
    else: y = c3[i]
    z = str((int(y) -int(x) + 3) % 3)
    b3 += y
    i, j = i+1, j+1
def to10(n):
    ans = 0
    for i in xrange(len(n)):
        ans = ans * 3 + int(i)
    return ans

print to10(b3[::-1])


a1, a2, a3 = map(int, input().split())
print(1)


def prefix(s):
    v = [0]*len(s)
    for i in range(1,len(s)):
        k = v[i-1]
        while k > 0 and s[k] != s[i]:
            k = v[k-1]
        if s[k] == s[i]:
            k = k + 1
        v[i] = k
    return v

n = int(input())
n-=1
s1 = input()
s2 = input()
opos = {'W':'E', 'E':'W', 'N':'S', 'S':'N'}
s3 = ''
for elem in s2:
    s3 += opos[elem]

s3[::-1]
s = s3 + '$' + s1

a = prefix(s)[2 * n]
if a == 0: print('YES')
else: print('NO')


import math
def divisors(n):
    i=2
    l=[]
    while i <= math.sqrt(n):
        if n%i==0:
            if n/i==i:
                l.append(i)
            else:
                l.append(i)
                l.append(n//i)
        i=i+1
    return l
def pebbles(n):
    if n==1:
        return 1
    else:
        c=divisors(n)
        m=min(c)
        return(n+pebbles(n//m)
n=int(input())
print(pebbles(n))


n = int(input())
s = str(input())
ans = 0
temp=''
i = 0
while i<len(s):
    if ord(s[i])<97:
        i = i +1
    else:
        while ord(s[i])>=97 and i<len(s):
            temp = temp+ s[i]
            i = i + 1
        t = set(temp)
        ans = max(len(t), ans)
print(ans)


def rec (a, b, c, d , e , f):
        if (c + e <= a and max(d , f) <= b):
            return true
        if (d + f <= b and max(c , e) <= a):
            return true
            return false

x = lambda: map(int, input().split())
a1, b1 = x()
a2, b2 = x()
a3, b3 = x()
if(rec(a1, b1 ,a2, b2, a3, b3) or rec(a1, b1 ,b2 , a2, a3, b3) or rec(a1, b1, a2, b2, b3, a3) or rec(a1, b1 , b2, a2, b3 , a3)):
    print("YES")
    exit()
print("NO")


import sys

sys.stdin = open('input.in', 'r')
sys.stdout = open('output.out', 'w')

s1 = input() + input()[::-1]
s2 = input() + input()[::-1]
s1 = s1[:s1.find('X')] + s1[s1.find('X') + 1:]
s2 = s2[:s2.find('X')] + s2[s2.find('X') + 1:]

flag = False

for i in range(3):
    if s1 == s2:
        flag = True
        break
    s1 = s1[-1] + s1[:-1]

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


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
import itertools as it
input = sys.stdin
output = sys.stdout

Notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'B', 'H']

STRANGE = 0
MAJOR = 1
MINOR = 2
TYPES = ['strange','major','minor']

def distance(n1,n2):
    count = False
    d = 0
    for n in it.cycle(Notes):
        if count:
            d += 1
        if n==n1:
            count = True
        if count and n==n2:
            return d

def classify(trinote):
    X = trinote[0]
    Y = trinote[1]
    Z = trinote[2]
    dXY = distance(X,Y)
    dYZ = distance(Y,Z)
    if dXY == 4 and dYZ == 3:
        return MAJOR
    if dXY == 3 and dYZ == 4:
        return MINOR
    return STRANGE

def solve(accord):
    for trinote in it.permutations(accord):
        at = classify(trinote)
        if at != STRANGE:
            return TYPES[at]
    return TYPES[STRANGE]

#print distance('E', 'C')

Ns = input.readline().split(' ')
assert len(Ns) == 3

s = solve(Ns)
output.write(s)

output.write('\n')


import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

M = 998244353

MAXNUM = 260
factor = [1]*(MAXNUM+2)
factor[-1]=0
storecomb = {}

for i in range(1,MAXNUM+1):
    factor[i] = (factor[i-1]*i)%M

def fastfrac(a,b):
    numb = pow(b,M-2,M)
    return ((a%M)*(numb%M))%M

def comb(n,k):
#    print "*",n,k
    if n<k: return 0
    if n==k: return 1
    if (n,k) in storecomb:  return storecomb[(n,k)]

    num1 = factor[n]
    num2 = factor[k]
    num3 = factor[n-k]
    num = (num2*num3)%M
    output = fastfrac(num1,num)
    storecomb[(n,k)] = output
    return output

def main(t):

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

    dp = [[0 for q in range(k+1)] for p in range(n+1)]

    for j in range(1,k+1):
        dp[2][j] = 1
        dp[1][j] = 1
    for i in range(3,n+1):
        dp[i][1] = pow(k,(i-1)*(i-2)//2,M)

    for i in range(3,n+1):
        for j in range(2,k+1):
            dp[i][j] = 0   # i nodes,  weight from 1-j

#            print(i,j,"----")
            for same in range(1,i-1):
                for maximum in range(1,j):
                    part1 = ( dp[i-same][maximum] * comb(i-1,same) ) % M
                    part2 = pow(k-j+1,same*(i-1-same)+same*(same-1)//2,M)

                    dp[i][j] += (part1*part2)%M

            dp[i][j] += pow(k-j+1,(i-1)*(i-2)//2,M)
            dp[i][j] %= M
#    print(dp)

#    print(dp[n])
    print(sum(dp[n])%M)

T = int(input())
t = 1
while t<=T:
    main(t)
    t += 1


#!/home/kameda/pyenv2/bin/python

n = int(raw_input())

if n <= 101:
    print(n)
else:
    uln = 0
    for i in range(102, n+1):
        if len(set(list(str(i)))) > 2:
            uln += 1
    print(n-uln)


import bisect

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

P=[1<<i for i in range(61)]

for ans in range(1000):

    x=n-ans*p

    if x<=0:
        print(-1)
        break

    count=0
    #print(ans,x)
    while x!=0:
        #print(x)
        y=bisect.bisect_right(P,x)
        x-=P[y-1]
        count+=1

    #print(ans,count)

    if ans>=count:
        print(ans)
        break


ay,ab = map(int,input().split())
y,g,b = map(int,input().split())
ty = 2*y+1*g
tb = 3*b+1*g
if(ty+tb-ay-ab=<0) :
    print(0)
else :
    print(ty+tb-ay-ab)


def unlucky(n):
    if n <= 2:
        return -1
    a = list()
    for i in range(n, -1, -1):
        a.append(i)
    return a[:-1]

print(*unlucky(int(input())))


a = int(input())
s = input()

arr = [0, 0, 0]

def sum(arr):
	c = 0
	for i in arr:
		c += i
	return c

def determine(arr, poss, seen):
	if seen[arr[0]][arr[1]][arr[2]]:
		return [arr[0]][arr[1]][arr[2]]
	else:
		seen[arr[0]][arr[1]][arr[2]] = True
		if arr[0] >= 2:
			a = [arr[0] - 1, arr[1], arr[2]]
			if seen[a[0]][a[1]][a[2]]:
				p1 = poss[a[0]][a[1]][a[2]]
			else:
				p1 = determine(a, poss, seen)
			for i in range(2):
				if p1[i] == True:
					poss[arr[0]][arr[1]][arr[2]][i] = True
		if arr[1] >= 2:
			a = [arr[0], arr[1]-1, arr[2]]
			if seen[a[0]][a[1]][a[2]]:
				p1 = poss[a[0]][a[1]][a[2]]
			else:
				p1 = determine(a, poss, seen)
			for i in range(2):
				if p1[i] == True:
					poss[arr[0]][arr[1]][arr[2]][i] = True
		if arr[2] >= 2:
			a = [arr[0], arr[1], arr[2]-1]
			if seen[a[0]][a[1]][a[2]]:
				p1 = poss[a[0]][a[1]][a[2]]
			else:
				p1 = determine(a, poss, seen)
			for i in range(3):
				if p1[i] == True:
					poss[arr[0]][arr[1]][arr[2]][i] = True
		if arr[0] >= 1 and arr[1] >= 1:
			a = [arr[0] - 1, arr[1]-1, arr[2]+1]
			if seen[a[0]][a[1]][a[2]]:
				p1 = poss[a[0]][a[1]][a[2]]
			else:
				p1 = determine(a, poss, seen)
			for i in range(3):
				if p1[i] == True:
					poss[arr[0]][arr[1]][arr[2]][i] = True
		if arr[0] >= 1 and arr[2] >= 1:
			a = [arr[0] - 1, arr[1]+1, arr[2]-1]
			if seen[a[0]][a[1]][a[2]]:
				p1 = poss[a[0]][a[1]][a[2]]
			else:
				p1 = determine(a, poss, seen)
			for i in range(3):
				if p1[i] == True:
					poss[arr[0]][arr[1]][arr[2]][i] = True
		if arr[1] >= 1 and arr[2] >= 1:
			a = [arr[0] + 1, arr[1] - 1, arr[2] - 1]
			if seen[a[0]][a[1]][a[2]]:
				p1 = poss[a[0]][a[1]][a[2]]
			else:
				p1 = determine(a, poss, seen)
			for i in range(3):
				if p1[i] == True:
					poss[arr[0]][arr[1]][arr[2]][i] = True
		return poss[arr[0]][arr[1]][arr[2]]

for i in range(len(s)):
	if s[i] == "B":
		arr[0] += 1
	elif s[i] == "G":
		arr[1] += 1
	else:
		arr[2] += 1

b = arr[0]
g = arr[1]
r = arr[2]
seen = [[[False for i in range(r+g+b+1)] for i in range(r+g+b+1)] for i in range(r+g+b+1)]
seen[0][0][0] = True
poss = [[[[False, False, False] for i in range(r+g+b+1)] for i in range(r+g+b+1)] for i in range(r+g+b+1)]
poss[0][0][0] = [False, False, False]

seen[1][0][0] = True
poss[1][0][0][0] = True

seen[0][1][0] = True
poss[0][1][0][1] = True

seen[0][0][1] = True
poss[0][0][1][2] = True

a = determine(arr, poss, seen)
t = ""
if a[0] == True:
	t += "B"
if a[1] == True:
	t += "G"
if a[2] == True:
	t += "R"

print(t)


lst=map(int, raw_input().split())
d = lst[0]; k = lst[1]; a = lst[2]; b = lst[3]; t = lst[4]

walk_len = d
auto_len = 0
crash = 0
min_time = auto_len * a + walk_len * b

while walk_len:
	auto_len += min(k, walk_len)
	walk_len = d - auto_len
	min_time1 = auto_len * a + t * crash + walk_len * b
	crash += 1
	if min_time1 >= min_time:
		break
	min_time = min_time1

print min_time