n = int(raw_input())
arr = map(int,raw_input().split())
t = []
for i,val in enumerate(arr):
	if val == 1:
		t.append(i)
x = [j-i for i, j in zip(t[:-1], t[1:])]
if len(arr) == 1 || len(t) == 0 :
	print "0"
else:
	y = reduce(lambda x, y: x * y, x, 1)
	print y


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

B = []
for i in xrange(n):
    if A[i]: B.append(i)

k = len(B)
ans = 1
for i in xrange(1, k): ans *= (B[i] - B[i - 1])

if k = 0: ans = 0
print ans


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

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

oper = 0

arr.sort()
mini = 0

while mini < arr.length():

    if mini == r:

        oper += 1
        mini += 1
        continue

    if mini == arr[mini]:

        mini += 1
        continue

    else:

        oper += 1
        mini += 1

print oper


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

sb = 0
s = 0

for i in range(len(l)):
    if(l[i] < b):
        sb += 1
    elif(l[i] = b):
        s = 1
    else:
        break
print(b-sb+s)


from sys import stdin
n,k = map(int,stdin.readline().split())
a = map(int,stdin.readline().split())
ans = 0
for i in xrange(k):
 if i not in a:
  ans += 1
ans += a.count(k)
prnt ans


n,x=map(int,input().split())
n1=list(map(int,input().split()))
nn=[]
for i in n1:
  if i>=0:
    nn.append(i)
nn.sort()
xx=x
if x>nn[0]:
  while xx not in nn:
    xx-=1
  if x not in nn:
    print(x-nn.index(xx)-1)
  else:
    print(x-nn.index(xx)+1)
elif x=0:
  print(0)
else:
  print(x-1)


n,mex=map(int,raw_input().split())
steps=0
flag=True
nums=map(int,raw_input().split())
if mex==0 and nums[0]==0:
    print 1
    flag=False
while True and flag:
    nuMex=0
    for i in range(100):
        if i not in nums:
            nuMex=i
            break
    if nuMex>mex:
        nums.remove(nuMex)
        steps+=1
    elif nuMex<mex:
        nums.append(nuMex)
        nums.sort()
        steps+=1
    else:
        print steps
        break


def fn(s):
    if len(s) == 1:
        if s[0] == '0':
            print "No"
        else:
            print "Yes"
	else:
		c = s[0]
		for i in s:
			if i != c:
				print "No"
				return
			c = str((int(c) + 1) % 2)
	print "Yes"

if __name__ == '__main__':
	n = raw_input()
	s = raw_input()
	fn(s)


n = input()
s = "0" + raw_input() + "0"
print "No" if ('11' in s or '000' in s) else print "Yes"


n = int(input())
s = input()
print("Yes" if (((s.count("1")-s.count("0"))==0)or((s.count("1")-s.count("0"))==1))) else "No")


n=int(input())
s=input().strip()
flag=1
if n==1:
    if s=="0":
        print("Yes")
    else:
        print("No")
elif n==2:
    if s!="00":
        print("Yes")
    else:
        print("No")
else n>=3:
    if s[:2]=="00":
        flag=0
    for i in range(1,n-1):
        t=s[i-1]+"1"+s[i+1]
        if int(t[0])^int(t[1])==1 or int(t[1])^int(t[1])==1:
            flag=0
            break
    if s[n-2:n]=="00":
        flag=0
    for i in range(n-1):
        if s[i:i+2]=="11":
            flag=0
            break
    if flag==1:
        print("Yes")
    else:
        print("No")


input()
k = "YES"
a = input()
a = list(a)
for i in range(len(a)-2):
 if a[i] == '0':
 if a[i+2] == '1':
 k = "NO"
 break
 if a[i] == '1':
 if a[i+1] == '1':
 k = "NO"
 break
print(k)


import sys

n = int(sys.stdin.readline().strip())
mas = map(int, sys.stdin.readline().strip().split())
if len(mas) > 1:
    if mas[-1] - 1 == mas[-2]:
        print "UP"
    else:
        print "DOWN"
elif mas[0]==15:
    print "DOWN"
elif mas[0]==0:
    print "UP"
elif:
    print "-1"


while True:
    try:
        x=input()
        y=map(int,raw_input().split())
        if y[-1]==15:
            print 'DOWN'
        elif x==1:
            if y[0]==1：
                print 'UP'
            else
                print '-1'
        elif y[-1]>y[-2]:
            print 'UP'
        else:
            print 'DOWN'
    except:
        break


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

elif a[-1] == 0:
    print("UP")
elif a[-1] == 15:
    print("DOWN")
if n == 1:
    print("-1")
elif a[-1] < a[-2]:
    print("DOWN")
else:
    print("UP")


n=int(input())
w=input().split()
w=list(w)
if len(w)==1:
    if w[-1]=='15':
        print('DOWN')
    elif:w[-1]=='0':
        print('UP')
    else:
        print('-1')
else:
     if w[-1]=='15':
         print('DOWN')
     else:
         if int(w[-1])<int(w[-2]):
            print('DOWN')
         elif int(w[-1])>int(w[-2]):
            print('UP')


n = input()
a = map(int, raw_input().split())
up , down = 'UP', 'DOWN'
if a[-1] == 15:
  print down
elif a[-1] == 0:
  print up
elif n==1:
  print -1
else
  print up if a[-1]>a[-2] else down


n = int(input())
N = int(n**0.5)
def eraSieve(N):
    poss = []
    isPrime = [1 for i in range(N+1)]
    for i in range(2,N+1):
        if isPrime[i]:
            if not n%i:
                poss.append(i)
                if len(poss) >= 3:
                    break
            for j in range(i, N+1, i):  # 从 i 开始不要紧，因为已经取走了，可以少一个乘法
                isPrime[j] = 0
    return poss
poss = eraSieve(N)
if not poss:
    print(n)
elif len(poss)>=2:
    print(1)
else:
    p = poss[0]
    fail = 0
    while n > 1:
        if n % p:
            fail = 1
            break
        n //= p
    if fail:
        print(1)
    else:
        print(p)


'use strict'

const gcd = (x, y) => { while(y) y = x % (x = y); return x; }

const prime_factors = n => {
    if (n === 1) return [1];
    let i = 2;
    const factors = [];
    while (i * i <= n) {
        if (n % i) i += 1;
        else {
            while (n % i === 0) n /= i;
            factors.push(i);
        }
    }
    if (n > 1) factors.push(n);
    return factors;
}

const factors = prime_factors(+readline());
print(factors.slice(1).reduce((r, i) => gcd(r, i), factors[0]));


# q1

from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# l = list(map(int,input().split()))
mod = 10**9 + 7

q 3
def solve(n):
    odd = 0
    even = 0
    for i in range(2,int(sqrt(n))+1):
        if n%i == 0:
            z = n//i
            if i%2 == 0:
                even+=1
            else:
                odd+=1

            if z!=i and z%2 == 0:
                even+=1
            elif z!=i and z%2!=0:
                odd+=1

    return even,odd

n = int(input())
e,o = solve(n)
if e == 0 and o == 0:
    print(n)
else:
    if o == 0 or e == 0:
        print(2)
    else:
        print(1)


n = int(input())
m = int(n**0.5)+2
ans = n
for i in range(2,m):
    if n%i==0:
        ans = i
        break
if ans==n:
    print(n)
else:
    p =  ans
    x = [1 for i in range(p)]
    for i in range(ans+1, m):
        if n%i==0:
            if n//i>=p:
                x = [0 for j in range(p)]
                break
            else:
                for j in range(1,n//i+1):
                    p[(j*i)%p] = 0
    print(max(x.count(1)), 1))


#!/usr/bin/python3

import functools

def gcd(x, y):
    while(y):
        y, x = x % y, y
    return x

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

    if (n > 1):
        factors.append(n)
    return factors

factors = prime_factors(int(input()));
print(functools.reduce(lambda r, i: gcd(r, i), factors[1:], factors[0]));


import math
n,a,b,p,q=map(int, input().split())

total = p*(n//a) + q*(n//b) - (int)(min(p,q)*(n//(a*b//math.gcd(a,b)))
print(total)


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

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

n, a, b, p, q = map(int,input().split())
print(n//a*p+n//b*q-n//lcp(a,b)*min(p,q))


def nod(a,b):
    while a>0 and b>0:
        a%=b
        a,b=b,a
    return a+b
def gcd(a,b):
    return (a*b)//nod(a,b)
n,a,b,p,q=[int(i) for i in input().split()]
res1=(n//a)*p+(n//b-n//gcd(a,b))*q
res2=(n//b)*q+(n//a-n//gcd(a,b))*p
print(max(res1,res2)


line = input().split(' ')
n = int(line[0])
a = int(line[1])
b = int(line[2])
p = int(line[3])
q = int(line[4])

# a 와 b의 최대 공약수 구하는 함수
def findGCD(a, b) :
    if a % b != 0 :
        return findGCD(b, a % b)
    else :
        return b

def MIN(a,b):
    if a >= b :
        return b
    else :
        return a

ans = int(n/a) * p
ans += int(n/b) * q
# 최대공배수를 나눈뒤
GCD = findGCD(a,b)
LCM = (a / GCD)  * (b / GCD) * GCD
ans -= int(n/ LCM) * MIN(p,q)

print(ans)


n,a,b,p,q = input().split(' ')
n = int(n)
a = int(a)
b = int(b)
p = int(p)
q = int(q)

# a 와 b의 최대 공약수 구하는 함수
def findGCD(a, b) :
    if a % b != 0 :
        return findGCD(b, a % b)
    else :
        return b

def MIN(a,b):
    if a >= b :
        return b
    else :
        return a

'''
n = 20 이고 a, b = 2, 3 일때
20/6 = 3 이면 10  * 3 +  6 * 5 = 30 + 30 - 3 * 2 = 5 * 3
'''
ans = int(n/a) * p
ans += int(n/b) * q
#최대공배수를 나눈뒤
GCD = findGCD(a,b)
LCM = (a / GCD)  * (b / GCD) * GCD
ans -= int(n/ LCM) * MIN(p,q)

print(ans)


# 887B
cubes_sets = []

def myor(smlist):
        buff_list = [1, 1, 1]
        for x in smlist:
                for y in range(3):
                        buff_list[y] = min(x[y], buff_list[y])
        return buff_list

def can_make(num):
        buff_num = str(num)
        if len(buff_num) == 1:
                if buff_num in cubes_sets[0] or buff_num in cubes_sets[1] or buff_num in cubes_sets[2]:
                        return True
        elif len(buff_num) == 2:
                inn = [[0, 0, 0], [0, 0, 0]]
                for x, y in enumerate(list(buff_num)):
                        if y in buff_cubes[0]:
				inn[x][0] = 1
			elif y in buff_cubes[1]:
				inn[x][0] = 1
			elif len(buff_cubes) > 2 and y in buff_cubes[2]:
				inn[x][0] = 1
		if sum(myor(inn)) >= 2:
                        return True
        elif len(buff_num) == 3:
                inn = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
                for x, y in enumerate(list(buff_num)):
                        if y in buff_cubes[0]:
				inn[x][0] = 1
			elif y in buff_cubes[1]:
				inn[x][0] = 1
			elif len(buff_cubes) > 2 and y in buff_cubes[2]:
				inn[x][0] = 1
		if sum(myor(inn)) == 3:
                        return True
        return False

def main():
        global cubes_sets
	n = int(input())
	cubes_sets = []
	for x in range(n):
		cubes_sets.append(set(input().split()))
	lastn = 0
	for x in range(1, 1000):
		if can_make(x):
			lastn = x
			continue
		else:
			return lastn

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


	'''input
	3
	0 1 3 5 6 8
	1 2 4 5 7 8
	2 3 4 6 7 9
	'''
	from itertools import permutations
	n = input()
	z = []
	ans = []
	for i in range(n):
		tmp = map(int,raw_input().split())
		z.append(tmp)
		for j in range(6):
			ans.append(tmp[j])
	if n == 1:
		ans = list(set(ans))
		ans.sort()
		flag = False
		if ans[0] == 0:
			flag = True
		cnt = 0
		for i in range(len(ans)):
			if flag:
				if ans[i] == i:
					cnt += 1
				else:
					break
			else:
				if ans[i] == i+1:
					cnt += 1
				else:
					break
		if flag:
			print cnt-1
		else:
			print cnt

	if n == 2:
		for i in range(6):
			for j in range(6):
				m = int(str(z[0][i])+z[1][j])
				mr = int(z[1][j]+z[0][i])
				ans.append(m)
				ans.append(mr)
		ans = list(set(ans))
		ans.sort()
		flag = False
		if ans[0] == 0:
			flag = True
		cnt = 0
		for i in range(len(ans)):
			if flag:
				if ans[i] == i:
					cnt += 1
				else:
					break
			else:
				if ans[i] == i+1:
					cnt += 1
				else:
					break
		if flag:
			print cnt-1
		else:
			print cnt

	if n == 3:
		for i in range(6):
			for j in range(6):
				m = int(str(z[0][i])+str(z[1][j]))
				mr = int(str(z[1][j])+str(z[0][i]))
				ans.append(m)
				ans.append(mr)
		for i in range(6):
			for j in range(6):
				m = int(str(z[0][i])+str(z[2][j]))
				mr = int(str(z[2][j])+str(z[0][i]))
				ans.append(m)
				ans.append(mr)
		for i in range(6):
			for j in range(6):
				m = int(str(z[2][i])+str(z[1][j]))
				mr = int(str(z[1][j])+str(z[2][i]))
				ans.append(m)
				ans.append(mr)
		for i in range(6):
			for j in range(6):
				for k in range(6):
					tmp = str(z[0][i])+str(z[1][j])+str(z[2][k])
					perms = [''.join(p) for p in permutations(tmp)]
					for kk in perms:
						ans.append(int(kk))
		ans = list(set(ans))
		ans.sort()
		flag = False
		if ans[0] == 0:
			flag = True
		cnt = 0
		for i in range(len(ans)):
			if flag:
				if ans[i] == i:
					cnt += 1
				else:
					break
			else:
				if ans[i] == i+1:
					cnt += 1
				else:
					break
		if flag:
			print cnt-1
		else:
			print cnt


import sys
import copy
list = []   #定义一个空列表
dice={str(i):[] for i in range(0,10)}
i=-1
for line in sys.stdin:
    i+=1
    if i==0:
        n=int(line)
    else:
        list_new = line.split()
        for j in list_new:
            dice[j].append(i)

if n=='0':
    print("0")
    exit()
x=1
while True:
    y=str(x)
    choice = [] # 用choice 存储每个number备选的骰子
    for k in y:
        choice.append(copy.deepcopy(dice[k]))
    if len(choice) < len(y):
        print(x)
        exit()
    while choice != []:
        if choice[0]==[]:
            print(x-1)
            exit()
        else:
            hash=[]
            # if y=="18":
            #     print(dice)
            for r in choice[0]:
                h=0
                for g in range(1, len(choice)):
                    if r in choice[g]:
                        h+=1
                hash.append((r,h))

            def by_name(t):
                return t[1]
            digit=sorted(hash, key=by_name)[0][0]
            for g in range(1, len(choice)):
                if digit in choice[g]:
                    choice[g].remove(digit)
            choice.remove(choice[0])

    x+=1


from itertools import  permutations
n = int(input())
lst = list()
for i in range(n):
    lst.append(list(input().split()))
per = permutations(lst)

for x in range(1,1000):
    l = str(x)
    for i in per:
        for d,c in zip(l,i)
            if d not in c:
                break
        else:
            break
    else:
        break
print(x-1)


numbers={}
cubes=[]
n=int(raw_input())
for i in range(n):
    cubes.append(map(int,raw_input().split()))

for cube in cubes:
    for j in cube:
        numbers[j]=True
if n>=2
    for (a,b) in [(i,j) for i in range(3) for j in range(i+1,3)]:
        for k in cubes[a]:
            for l in cubes[b]:
                numbers[k*10+l]=True
                numbers[l*10+k]=True

if n==3:
    for (a,b,c) in [(i,j,k) for i in range(3) for j in range(i+1,3) for k in range(j+1,3)]:
        for l in cubes[a]:
            for m in cubes[b]:
                for n in cubes[c]:
                    numbers[l*100+m*10+n]=True
                    numbers[l*100+n*10+m]=True
                    numbers[m*100+l*10+n]=True
                    numbers[m*100+n*10+l]=True
                    numbers[n*100+l*10+m]=True
                    numbers[n*100+m*10+l]=True

count=0
curr=0
for i in sorted(numbers.keys()):
    if i==curr+1:
        count+=1
        curr=i
print count


from math import ceil
n = int(input())
i = 0
while True:
    if n % (3 ** i) != 0:
        print(ceil(n / (3 ** i)))
        exit()
    i += 1


object CF333A {
    def main(argv: Array[String]) {
        def calc(n: Int): Int = {
            if (n % 3 == 0) calc(n / 3)
            else (n + 2) / 3
        }
        println(calc(readLine.toInt))
    }
}


n = input()
while n%3 == 0: n /= 3
print （n/3+1）


def main():
    n = int(input())
    div, mod = divmod(n, 3)
    ans = mod

    div, mod = divmod(div)
    ans += mod + div

    print(ans)

if __name__ == "__main__":
    main()


def f():
    n = int(input())
    def toTri(x):
        if x == 1:
            return [1]
        l = toTri(int(x / 3))
        l.append(x % 3)
        return l

    digits = toTri(n)
    for i in range(len(digits) - 1, -1, -1):
        if digits[i] != 0:
            break
    coins = 1
    mul = 1
    for j in range(i - 1, -1, -1):
        coins += mul * digits[j]
        mul *= 3
    print(coins)
f()


#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

typedef vector<int> vi;

long long cnk[51] = {1};
int n, p, a[50];
double ans = 0;

double solve(int i, int s, int l)
{
    if(i == n)
    {
        if(s <= p && l == n)
            return s;
        return 0;
    }
    double ans = 0;
    if(s + a[i] > p && l > 0)
        ans = 1.0 * l / cnk[n - l];
    else
        ans = solve(i + 1, s + a[i], l + 1) + solve(i + 1, s, l);
    return ans;
}

int main()
{
    scanf("%d", &n);
    for(int i = 0; i < n; ++i)
        scanf("%d", a + i);
    sort(a, a + n);
    scanf("%d", &p);
    for(int i = 1; i <= n; ++i)
        cnk[i] = cnk[i - 1] * (n - i + 1) / i;
    printf("%0.9lf\n", solve(0, 0, 0));
    return 0;
}


n,m,k=map(int,raw_input().split())
lst=map(int,raw_input().split())
lst.sort(lambda a,b:b-a)
need=0
for i in lst:
    if m<=0 || need>k:break;
    m=m-i+1;need+=1

if need>k || m>0:
    print -1
else:
    print need


n, m, k = map(int, raw_input().split())
a = map(int, raw_input().split())
a = sorted (a,reverse = True)
currentSocketsCount = k
if m <= k:
    return 0
else:
    for i in xrange(n):
        currentSocketsCount += a[i]-1
        if currentSocketsCount >= m:
            print i+1
            break
        if i == n-1 and currentSocketsCount < m:
            print -1


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

n, m, k = [ int(v) for v in raw_input().split() ]
a = [ int(v) for v in raw_input().split() ]
a.sort()

c = 0
m -= k-1
while m>0 and len(a)>0:
    c += 1
    if a[-1]>=m:
        m -= a[-1]
    else:
        m -= a[-1]-1
    a = a[:-1]

if m > 0:
    print -1
else:
    print c


import bisect
n,m,k=list(map(int,input().split()))
l=[0]+list(map(int,input().split()))
l.sort()
z=k
x=m
c=0
while m>k and k>0:
    i=bisect.bisect(l,m)
    m=m-l[i-1]
    k=k-1
    c=c+1

if k==0 and m>0:
    c=0
    while z>0:
        z=z-1
        while x>z and i>1:
            i=bisect.bisect(l,x)
            x=x-l[i-1]+1
            c=c+1
    if z==0 and x>0:
        print(-1)
    else:
        print(c)

else:
    print(c)


alpha = list("abcdefghijklmnopqrstuvwxyz ")

def count_subseq(s):
    #長さがlのsのsubsequenceの個数
    n = len(s)
    dp = [[[0]*27 for i in range(n+10)] for j in range(n+10)]
    #dp[where][cnt][index] := where番目まで見てそこまででcnt個取って最後のもじがlast_alphabet[index]の物の異なる物の個数
    dp[0][0][26] = 1
    for i in range(1, n+1):
        st = s[i-1]
        for j in range(i+1):
            v = sum(dp[i-1][j-1][p] for p in range(27))
            for last_string in range(27):
                if alpha[last_string]!=st:
                    dp[i][j][last_string] = dp[i-1][j][last_string]
                else:
                    #lastalpha == st
                    dp[i][j][last_string] =  v
    result = [0]*(n+1)
    for l in range(n+1):
        result[l] = sum(dp[n][l][v] for v in range(27))
    return result

def solution():
    n, k = map(int, input().split())
    s = input()
    cntlist = count_subseq(s)
    res = 0
    for length in range(n, -1, -1):
        if k == 0:
            break
        cnt = cntlist[length]
        if cnt >= k:
            res += (n-length)*k
            k = 0
        elif cnt < k:
            res += (n-length)*cnt
            k -= cnt
    if k > 0:
        print(-1)
    else:
        print(res)
    return

def main():
    test = 1
    for i in range(test):
        solution()
    return

if __name__ == "__main__":
    main()


 n, k = map(int, input().split())
s = input()
a = set()
k -= 1
q = [s]
i = 0
ans = 0
while i < len(q) and k > 0:
    for j in range(len(q[i])):
        new = q[i][:j] + q[i][j + 1:]
        if new not in a:
            a.add(new)
            q.append(new)
            ans += n - len(q[i]) + 1
            k -= 1
            if k == 0:
                print(ans)
                exit()
    i += 1
if k == 0:
    print(ans)
else:
    print(-1)


from sys import stdin
from collections import deque

def subsequence(str):
        // iterate over the entire string
    seti  = set()
    for i in range(len(str)):
            # iterate from the end of the string
            # to generate substrings
        for j in range(len(str),-1,-1):
            #(int j = str.length(); j > i; j--) {
                sub_str = str[i:j]
                st.add(sub_str);

                # drop kth character in the substring
                # and if its not in the set then recur
                for k in range(1,len(str)-1):
                    #// drop character from the string
                    sb = sub_str[0:k] + sub_str[k+1:]
                    if (!st.contains(sb))
                        ;
                    subsequence(sb.toString());

n, k = map(int, input().split())
s = input()
que = deque()
que.append(s)
d = {}
num = 0
cost = 0
while que:
    q = que.popleft()
    if q not in d:
        cost += n - len(q)
        num += 1
        if num == k:
            print(cost)
            exit()
        d[q] = 1
        for j in range(len(q)):
            t = q[:j] + q[j + 1:]
            if t not in d:
                que.append(t)

print(-1)


# -*- coding: utf-8 -*-
"""
Created on Mon Jul  1 16:11:00 2019

@author: dake3
"""

n, k = map(int, input().split())
s = str(input())
#n = length of string
#k = size of set
#s = string
#n = 10
#k = 100
#s = 'ajihiushda'

b = True

if n>=k**2:
    print(k-1)
    b = False

def all_subs(word):
    sub = []
    for i in range(len(word)):
        for j in range(i, len(word)):
            sub.append(word[i:j+1])
    return set(sub)

# Function which returns subset or r length from n
from itertools import combinations

def rSubset(arr, r):

	# return list of all subsets of length r
	# to deal with duplicate subsets use
	# set(list(combinations(arr, r)))
	return list(combinations(arr, r))

S = []
S.append(s)

for x in range(n):
    arr = list(s)
    S += [''.join(i) for i in rSubset(arr, x)]

S = list(set(S))
S.sort(key=len, reverse=True)

if len(S) < k and b == True:
    print('-1')
elif b == True:
    S = S[0:k]
    cost = 0
    for i in range(k):
        cost += n-len(S[i])
    print(cost)
#print(S)
#print(len(S))


from queue import Queue
n,k=map(int,input().split())
s=input()
cost=0
vis=set()
q=Queue()
q.put(s)
while q:
    s=q.get()
    if s in vis: continue
    vis.add(s)
    cost+=len(s)
    if len(vis)==k: break
    for i in range(len(s)):
        q.put(s[:i]+s[i+1:])
if len(vis)!=k: print(-1)
else: print(n*k-cost)


n=int(input(),2)
j=0
ans=0
while(4**j<n):
    ans+=1
    j+=1
print(ans


def bin( temp):

    while temp > 1:
        last = (temp) % 10
        temp = temp / 10
        if(last !=0):
            g=1
        k++
    m=int(k/2)
    if(g != 1 && k%2==0):
        m=m-1
    return m;

a=input()
b=bin(a)+1
print(b)


s = input()
x = len(s)

if x%2 == 0:
	for i in range(1, x):
    	if(s[i] == "1"):
        	print(x//2+1)
        	exit()

print(x//2)


def bin(temp):
    k=0
    while temp > 1:
        last = (temp) % 10
        temp = temp / 10
        if(last !=0):
            g=1
        k=k+1
    m=int(k/2)
    if g != 1 || k%2==0 :
        m=m-1
    return m;

a=input()
b=bin(a)+1
print(b)


x=input()
y=int(n,2)
c=0
k=0
while (4**k)<=y
    k+=1
    c+=1
print(c)


n=int(input())
tp=[]
p=list(map(int,input().split()))
ta=p.index(1)
sa=p.index(n)
tp.append(abs(ta-(n-1))
tp.append(ta)
tp.append(abs(sa-(n-1)))
tp.append(sa)
print(max(tp))


def max(a, b):
	if a > b:
		return a
	return b

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

pos1 = 0, posn = 0

for i in range(n):
	if a[i] == 1:
		pos1 = i
	if a[i] == n:
		posn = i

print(max(pos1, max(n - 1 - pos1, max(posn, n - 1 - posn))))


n = int(input())
l = list(map(int,input().rstrip().split()))
return(n-1)


n = int(input())
t = list(map(int, input().split()))
print(t)
pa,pb = t.index(1), t.index(n)]
if (pa+1 == 1 and pb+1 == n) or (pb+1 == 1 and pa+1 == n):
    print(n-1)
else:
    if pa < pb:
        print(n-pa-1 if n-1-pb > pa else pb - 1)
    else:
        print(n-pb-1 if n-1-pa > pb else pa - 1)


import math

#enumerations and constructing subsets , subsets and enumerations

t = int(raw_input())

if(t<=9):
	print t

elif(t>9 and t <= 189):
	if((t-9)%2==0):
		print (9 + int(math.ceil((t-9)/2)))%10
	else:
		print (9 + int(math.ceil((t-9)/2))%10               #somewhere kinda invalid syntax


a, b, c = [int(i) for i in raw_input().split(' ')]
if a < b:
    a, b = b, a
ans = 0
for i in range(max(1, (c+a-1)/a)+1):
    if (c - i*a) % b == 0 && (c - i*a)/b >= 0:
        ans = 1
        break
print 'Yes' if ans else 'No'


a,b,c = map(int,raw_input().split(' '))
i = 0
3 while(c>=0):
     if((c-b*i)%a==0):
         print 'yes'
         break
     i = i+1
     if(i > c/b):
         print 'no'
         break
                        |~


import math
ip=input().split(' ')
a=int(ip[0])
b=int(ip[1])
c=int(ip[2])

def gcd(a,b):
    if b==0:
        return a,1,0
    g,x,y=gcd(b,a%b)
    return g,y,x-y*int(a/b)

g,x,y=gcd(a,b)

if(c%g):
    print("No")
    return
x*=c/g
y*=c/g
# print(g,x,y)

mink=math.ceil(-x*g/b)
maxk=math.floor(y*g/a)

# print(mink,maxk)

if(mink>maxk):
    print("No")
else:
    print("Yes")


a,b,c = map(int,raw_input().split(' '))
i = 0
3 while(c>=0):
     if((c-b*i)%a==0):
         print 'yes'
         break
     i = i+1
     if(i > c/b):
         print 'no'
         break


import sys
a,b,c=map(int,input().split())
c=c%b
# print(a)
for x in range(1,15000000000):
    if(x*a>10000):break
    elif ((x*a)%b==c):
        print("Yes")
        sys.exit()
print("No")v


n = int(input())

def f(n):
    nod = len(str(n))
    l1 = nod*(n - (10**(nod - 1)-1)
    s = 0
    for i in range(1, n):
        s = s + (9*i)
    return s + l1

print(f(n))


#include <bits/stdc++.h>

using namespace std;

long long pw(int power)
{
    if (power==1) return 10;
    else return 10*pw(power-1);
}

int main()
{
    int n;
    cin>>n;
    long long ans = 0;
    int power = 0;
    while(n>=10){
        power++;
        long long p=pw(power);
        n -= p - 1;
        ans +=  (p - 1) * power;
    }
    ans+=n*(power+1);
    cout<<ans;
    return 0;
}


import sys
import re
str = #input()
names = ['Danil', 'Olya', 'Slava', 'Ann','Nikita']
count = 0
for name in  names:
    tmp_count = 0
    for m in re.finditer(name,str):
        if m.start() >= 0:
            tmp_count += 1

    if tmp_count > 1:
        print('NO')
        sys.exit(0)
    elif tmp_count == 1:
        count += 1

if(count == 1):
    print('YES')
else:
    print('NO')


import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    s = S()
    t = ["Danil", "Olya", "Slava", "Ann", "Nikita"]
    r = 0
    for c in t:
        l = len(c)
        for i in range(len(s))
            if c == s[i:i+l]:
                r += 1
    if r == 1:
        return 'YES'
    return 'No'

print(main())


import re
contest = input()
ans = re.findall('Danil|Olya|Slava|Ann|Nikita', contest)
if len(ans) ==1:
    print('YES')
    else:
        print('NO')


s = input()
x = ["Danil", "Olya", "Slava", "Ann","Nikita".]
ans = [0]*5
for i in range(len(x)):
    if x[i] in s:
        ans[i] += 1
su = sum(ans)
if su==1:
    fr = x[ans.index(1)]
    s = s.replace(fr,'')
    ans = [0]*5
    for i in range(len(x)):
        if x[i] in s:
            ans[i] += 1
    if sum(ans)!=0:
        print('NO')
    else:
        print('YES')
else:
    print('NO')


 from sys import stdin, stdout
n = stdin.readline()
s1 = "Danil"
s2 = "Olya"
s3 = "Slava"
s4 = "Ann"
s5 = "Nikita"

count1 = n.count(s1)
count2 = n.count(s2)
count3 = n.count(s3)
count4 = n.count(s4)
count5 = n.count(s5)

if (count1+count2+count3+count4+count5) == 1:
    stdout.write("YES")
else:
    stdout.write("NO")


z,zz,dgraphs,mod=input,lambda:list(map(int,z().split())),{},10**9+7
from string import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
def lcd(xnum1,xnum2):return (xnum1*xnum2//gcd(xnum1,xnum2))
def prime(x):
    p=ceil(x**.5)+1
    for i in range(2,p):
        if x%i==0 and x!=2:return 0
    return 1
def dfs(u,visit,graph):
    visit[u]=True
    for i in graph[u]:
        if not visit[i]:
            dfs(i,visit,graph)
################################################################################

"""

led=(6,2,5,5,4,5,6,3,7,6)

color4=["G", "GB", "YGB", "YGBI", "OYGBI" ,"OYGBIV",'ROYGBIV' ]
19 3
5 4 10
"""

###########################---START-CODING---####################################

n=int(z())
k=int(z())
a=int(z())
b=int(z())

if n%k==0:
    print(min(b*(n-1))//k),(n-1)*a))
    exit()

if a*k<=b or n<k:
    print((n-1)*a)
    exit()

t=0
while n>1:
    if n%k==0:
        t+=b
        n//=k
    elif n>k:
        t+=a*(n%k)
        n-=n%k
    else:
        t+=a
        n-=1
print(t,'**')


n=int(input())
k=int(input())
a=int(input())
b=int(input())
coin=0
if(n==1):
    print("0")
    return
if(k==1):
    print((n-1)*a)
    return
sum=0
while(n!=1):
    if(n<k):
        sum=sum+(n-1)*a
        break
    if(n%k!=0):
        sum=sum+(a*n%k)
        n=n-n%k
    else:
        i=n-n//k
        if(b>i*a):
            n=n//k
            sum=sum+i*a
        else:
            n=n//k
            sum=sum+b

print(sum)


n = int(input())
k = int(input())
a = int(input())
b = int(input())
def shut(t) :
    if k == 1 :
        return (t-1)*a
    if t < k :
        return (t-1)*a
    else  :
        r = t%k
        return (r*a) +  min(b , a*(t-t//k) + shut(t//k)
print(shut(n))


n=int(input())
k=int(input())
A=int(input())
B=int(input())

x=n
cost=0

while (x!=1):
	if (k==1);
		cost+=A*(x-1)
		x=1
	elif (x%k==0):
		x=x/k
		cost+=min(B,A*(x*k-x))
		#print(1)
	elif (x%k==1):
		x=x-1
		cost+=A
		#print(2)
	else:
		cost+=A*((x%k)-1)
		x=x-((x%k)-1)
		#print(3)
print(int(cost))


from __future__ import print_function
n = input()
k = input()
A = input()
B = input()

op = 0

if(k == 1):
    op = (n-1)*A
else:
    while(n != 1):
        int rest = n%k
        if(rest != 0):
            if rest == n:
                op = op + (x-1)*A
                n = 1
            else:
                op+=A*rest
                n-=rest

        else:
            d = n/k
            if(B>(n-d)*A):
                op+=(n-d)*A
            else:
                op+=B
            n=d

print(op, end='')


a=int(input))
if a%2==0:
    print(1)
else:
    print(0)


a=int(input())
if a%2==0:
    print 0
else
    print 1


ax, ay, bx, by, cx, cy = map(long, raw_input().split())

# if the point exists, it must be the intersection of three (chuizhipingfenxian)
# meanwhile, if a->b, b->c and a,b,c on a same circle, then |ab| = |bc|

len_ab = (bx - ax) * (bx - ax) + (by - ay) * (by - ay)
len_bc = (cx - bx) * (cx - bx) + (cy - by) * (cy - by)

# whether b is the middle point of ac
mid_point = False
if bx * 2 == ax + cx and by * 2 = ay + cy:
    mid_point = True

if len_ab == len_bc and not mid_point:
    print "Yes"
else:
    print "No"


    from math import sqrt
    def distance(x1,y1,x2,y2):
        return  (x1-x2)**2 + (y1-y2)**2

    a,b,x,y,c,d=[int(element) for element in input().split(" ")]

    if distance(x,y,a,b)==distance(x,y,c,d) and ((b-y)*(x-c)-(y-d)*(a-x))!=0:
        print("YES")
    else:
        print("NO")


from math import sqrt
x1,y1,x2,y2,x3,y3=map(int,raw_input().split())
if (abs(y2-y1)**2+abs(x2-x1)**2==abs(y3-y2)**2+abs(x3-x2)**2 and (y1-y2)*(x1-x3)!=(x1-x2)*(y1-y3):
    print "Yes"
else:
    print "No"


def f(t, s, x):
  return x == t or x >= t + s and (x - t) % s <= 1

t, s, x = map(int, raw_input().split())
print "YES" if f(t, s, x) else "NO"


def f(t, s, x):
  return x == t or x >= t + s and (x - t) % s <= 1
t, s, x = map(int, raw_input().split())
print "YES" if f(t, s, x) else "NO"


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

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


#def f(t, s, x):
  return x == t or x >= t + s and (x - t) % s <= 1

t, s, x = map(int, raw_input().split())
print "YES" if f(t, s, x) else "NO"


eps = 1e-9

vp, vd, t, f, c = [int(raw_input()) for i in range(5)]
cur = vp * t * 1.0
res = 0
while True:
    if vd == vp:
        break
    time = cur / (vd - vp)
    if time < 0:
        break
    cur += vp * time
    if cur + eps > c:
        break
    res += 1
    cur += vp * f + (cur / vd) * vp
print res


vp=input()
vd=input()
t=input()
f=input()
c=input()
if vp>=vd: print 0; exit();
z=1.0*vp*t*vd/(vd-vp)
kol=0
while z<c:
    kol+=1
    z+=vp*(f+z/vd)
    z=z*vd/(vd-vp)
print kol


vp = int(raw_input())
vd = int(raw_input())
t = int(raw_input())
f = int(raw_input())
c = int(raw_input())
s = t * vp
td = t
ans = 0
vr = vd - vp
while (vr > 0 and s < c):
    ttvr = s
    if s * vr + vp * ttvr >= c * vr: break
    ans += 1
    s = s * vr + vp * (2 * ttvr + f * vr)
    vp *= vr
    vd *= vr
    c *= vr
    vr *= vr
print ans


#!/usr/bin/env python

""" @file	escape.py
	@brief	calculate how many coins the princess needs to drop

	@author dopey
"""

import sys

if __name__ == "__main__":
	v_p = int(sys.stdin.readline())
	v_d = int(sys.stdin.readline())
	v_t = int(sys.stdin.readline())
	v_f = int(sys.stdin.readline())
	v_c = int(sys.stdin.readline())

	coins = 0

	# check if princess is faster than dragon
	if (v_p >= v_d):
		print coins

	while (1):
		time_overtake = v_t/(v_d-v_p)
		if time_overtake*v_d >= v_c:
			break

		v_t = time_overtake*v_d + (time_overtake+v_f)*v_p
		coins += 1

	print coins


from fractions import Fraction
vp=Fraction(int(raw_input()))
vd=Fraction(int(raw_input()))
t=Fraction(int(raw_input()))
f=Fraction(int(raw_input()))
c=Fraction(int(raw_input()))

def dogon(dist):
    X=(dist*vp)/(vd-vp)
    return dist+X
if(vp>vd):
    print 0;
else:
 curdist=Fraction(t*vp)
 count=0
 while True:
     nextdist=dogon(curdist)
     #print nextdist
     if(nextdist<c):
         count+=1
     else:break
     curdist=nextdist+nextdist/vd*vp+f*vp
 print count


def crackCode(dig):
    digit = str(dig)
    digit = swap(digit,1,2)
    digit = swap(digit,4,2)
    newDigit = int(digit)
    newDigit = newDigit**5
    res = str(newDigit)
    res = res[-5:]
    return res
n =  raw_input()
print(crackCode(int(n))

def swap(dig,i,j):
    string = list(dig)
    string[i],string[j] = string[j],string[i]

    return ''.join(string)


# http://codeforces.com/problemset/problem/630/L

import math

n = str(raw_input())

n = n[0]+n[2]+n[4]+n[3]+n[1]

n = int(n)
n2 = 1

for i in range(5):
  n2 = (n2*n) % 100000

for i in range(5-len(n2))
  n2.insert(0,'0')

print n2


# http://codeforces.com/problemset/problem/630/L

import math

n = str(raw_input())

n = n[0]+n[2]+n[4]+n[3]+n[1]

n = int(n)
n2 = 1

for i in range(5):
  n2 = (n2*n) % 100000

n2 = str(n2)
for i in range(5-len(n2))
  n2.insert(0,'0')

print n2


from sys import stdin
import functools
import operator

def modpow(n, p, m):
	e = 1
	for i in range(p):
		e = (e * n) % m
		print e

	return e

num = stdin.readline().strip()
new_num = num[0] + num[2] + num[4] + num[3] + num[1]

print(modpow(int(new_num), 5, 10 ** 5))


n,k = map(int, input().split())
print(n+(k-(n%k))


n, k = tuple(map(int, input().split()))
return n * (k // n + 1)


[n,k]=[int(x) for x in raw_input().split()]
n+=1
m=(k-(n%k))
if m===k:
    m=0
print m+n


#include<iostream>
using namespace std;
int main(){
    int n,k;
    cin>>n>>k;
    cout<<n+k-n%k;
    return 0;
}


n,k = map(int, input().split())
print(n+(n%k)+(k if n%k==0))


#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 222222
#define M 1000000000
typedef long long ll;
ll tc, n, k, inp[N], pl, cl, ct, l, t;
bool peak(ll ind){
    if (ind==1)
        return false;
    if (inp[ind]>inp[ind-1]&&inp[ind]>inp[ind+1])
        return true;
    return false;
}
int main(){
    scanf("%lld", &tc);
    while (tc--){
        scanf("%lld%lld", &n, &k);
        for (ll i=1; i<=n; i++)
            scanf("%lld", &inp[i]);
        cl=l=pl=1; ct=0;
        for (ll i=1; i<k; i++)
            if (peak(i))
                ct++;
        t=ct;
        for (ll i=k; i<n; i++){
            cl=pl+1;
            if (peak(i))
                ct++;
            if (peak(cl))
                ct--;
            if (ct>t)
                l=cl, t=ct;
            pl=cl;
        }
        printf("    %lld %lld\n", t+1, l);
    }
}


from math import sqrt
input = input().split(' ')
r = int(input[0])
(x,y) = (abs(int(input[3])-int(input[1])),abs(int(input[4])-int(input[2])))
def f():
    global x,y
    if sqrt((x ** 2 + y ** 2))%1==0:
        a=int(sqrt((x ** 2 + y ** 2)))
    else:
        a=int(sqrt((x**2+y**2)))+1
    for i in range(a,int(x+y)+2):
        if i%(2*r)==0:
            return i/(2*r)
try:
    print(int(f()))
except
    print(f())


import math
def amr_pins():
    r, sx, sy, fx, fy = map(int, raw_input().strip().split())
    d = ((fx - sx) ** 2 + (fy - sy) ** 2) ** 0.5
    print int(math.ceil(d / (2 * r))

amr_pins()


 def Z(s):
   left=0
   right=0
   z=[ 0 for i in range(len(s))]
   for k in range(1,len(s)):
       if k > right:
           left=k
           right=k
           while right <len(s) and s[right]==s[right-left]:
               right=right+1
           z[k]=right-left
           right=right-1
       else:

           k1=k-left
           if z[k1]< right-k+1:
               z[k]=z[k1]
           else:
               left=k
               while right <len(s) and s[right]==s[right-left]:
                   right=right+1
               z[k]=right-left
               right=right-1
   return z
s=input()
a=Z(s)
a.reverse()
p=0
r=0
for i in range(len(a)):
   if i+1==a[i]:
      if p==0:
         p=i+1
      else:
         r=p
         p=i+1
   elif a[i]>=p:
      r=p
if r==0:
   print("Just a legend")
else:
   print(s[0:r])


    arr = raw_input().split()
    n = int(arr[0])
    m = int(arr[1])
    pigs = []
    setw = set()
    for i in range(n):
        linei = raw_input()
        for j in range(m):
            if linei[j] == 'P':
                pigs.append((i,j))
            elif linei[j] == 'W':
                setw.add((i,j))
    cnt = 0
    for pair in pigs:
        x = pair[0]
        y = pair[1]
        if (x+1,y) in setw:
            setw.remove((x+1,y))
            cnt = cnt + 1
        elif (x,y+1) in setw:
            setw.remove((x,y+1))
            cnt = cnt + 1
        elif (x-1,y) in setw:
            setw.remove((x-1,y))
            cnt = cnt + 1
        elif (x,y-1) in setw:
            setw.remove((x,y-1))
            cnt = cnt + 1
    print cnt


arr = raw_input().split()
n = int(arr[0])
m = int(arr[1])
pigs = []
setw = set()
for i in range(n):
    linei = raw_input()
    for j in range(m):
        if linei[j] == 'P':
            pigs.add((i,j))
        elif linei[j] == 'W':
            setw.add((i,j))
for pair in pigs:
    x = pair[0]
    y = pair[1]
    if (x+1,y) in setw or (x,y+1) in setw or (x-1,y) in setw or (x,y-1) in setw:
        cnt++
print cnt


n,m = map(int,input().split())
l = []
for i in range(n):
    l.append(input())
c = 0
for i in range(n):
    for j in range(m):
        if l[i][j]=="W":
            if(i>0 and l[i-1][j]=="P"):
                c=c+1
		continue
            if(i<n-1 and l[i+1][j]=="P"):
                c=c+1
    		continue
    	    if(j>0 and l[i][j-1]=="P"):
                c=c+1
                continue
    	    if(j<m-1 and l[i][j+1]=="P"):
                c=c+1
    		continue
print(c)


arr = raw_input().split()
n = int(arr[0])
m = int(arr[1])
pigs = []
setw = set()
for i in range(n):
    linei = raw_input()
    for j in range(m):
        if linei[j] == 'P':
            pigs.add((i,j))
        elif linei[j] == 'W':
            setw.add((i,j))
cnt = 0
for pair in pigs:
    x = pair[0]
    y = pair[1]
    if (x+1,y) in setw or (x,y+1) in setw or (x-1,y) in setw or (x,y-1) in setw:
        cnt++
print cnt


m, d = map(int, input().split())
if m == 2 and d = 1:
    print(4)
elif (m in [4, 6, 9, 11] and d == 7) or (m in [1, 3, 5, 7, 8, 10, 12] and d in[6, 7]):
    print(6)
else:
    print(5)


def check_code (a,b)
     for i in range (len(a)):
         if a[i] != b[len(b)-1-i]:
        return ("No")
    return ("Yes")

a=raw_input ()
b=raw_input ()
if len(a)==len(b):
    print (check_code (a,b))
else:
    print ("No")


import collections
s=input()
d=input()
l1=[]
l2=[]
a=len(s)
b=len(s)
i=0
 while(a):
    l1.append(s[a-1])
    a=a-1
while(b):
    l2.append(d[i])
    i=i+1
    b=b-1
if collections.Counter(l1) == collections.Counter(l2):
    print ("YES")
else :
    print ("NO")


def check_code (a,b)
     for i in range (len(a)):
         if a[i] != b[len(b)-1-i]:
        return ("No")
    return ("Yes")

a=raw_input ()
b=raw_input ()
if len(a)==len(b):
    print (check_code (a,b)):
else:
    print ("No")


comparação=0
s=input("")
t=input("")
n=len(t)

for i in range(0,n):

    if s[i] == t[n-i-1]:
        comparação+=1

if comparação==n:
    print("YES")

else:
    print("NO")


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

int main(){
    string s1, s2; char x;
    cin >> s1; cin.get(x); cin >> s2;
    reverse(s2.begin(), s2.end());
    if (s1 == s2) printf("YES");
    else printf("NO");
    return 0;
}


import math
n,m,t = map(int,raw_input().split())
nn = n-4
mm = m-1
s = mm+nn
tt = t-5
return m*(math.factorial(n)/(24*math.factorial(nn)))*(math.factorial(s)/(math.factorial(tt)*math.factorial(s-tt))


def ncr(n,r):
	ans=1
	for i in range(r):
		ans=(ans*(n-i))//(i+1)
	return ans

n,m,t=map(int,raw_input().split())
print ncr(m+n,t)-(ncr(n,t)+ncr(m,t)+ncr(n,1)*ncr(m,t-1)+ncr(n,2)*ncr(m,t-2)+ncr(n,3)*ncr(m,t-3))


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

typedef long long ll;
typedef long double ld;
#define umap unordered_map
#define size(a) int((a).size())
#define present(c, x) (c.find(x) != c.end())
#define printVerdict(verdict) cout << (verdict ? "Yes": "No") << '\n'
#define printDecimal(d) cout << setprecision(d) << fixed
#define inrange(val, start, end) (val >= start && val <= end)
#define var(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "

const ll inf = 0x3f3f3f3f;
const ll mod = 1e9 + 7;

template <class T1, class T2, class T3>
void printTuple(tuple<T1, T2, T3> t) { cout << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << '\n'; }
template <class T1, class T2>
void printPair(pair<T1, T2> p) { cout << p.first << " " << p.second << '\n'; }
template <class T>
void printArray(vector<T> arr) { for (int i = 0; i<size(arr); i++) {cout << arr[i] << " ";} cout << '\n'; }
template<class T>
void read(vector<T> &a, int n) { for (int i= 0; i<n; i++) cin >> a[i]; }
template<class T>
void read(T* a, int n) { for (int i= 0; i<n; i++) cin >> a[i]; }
template<class T>
void readIdx(vector<pair<T, int>> &a, int n) { for (int i = 0; i<n; i++) { cin >> a[i].first; a[i].second = i; }}

int main() {
	std::ios_base::sync_with_stdio(false);
	cin.tie(0);
	int n,m,t; cin >> n >> m >> t;
	vector<vector<ll>> dp(31, vector<ll>(31, 0));
	dp[0][0] = 1;
	for (int i= 1; i<=30; i++) dp[i][0] = 1;
	for (int i = 1; i<=30; i++) {
		for (int j = 1; j<=30; j++) {
			dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
		}
	}
	ll ret = 0;
	for (int curr = 4; curr <= t-1; curr++) {
		ret += dp[n][curr] * dp[m][t-curr];
	}
	cout << ret << '\n';

 }


def c(n, k)
    r = 1
    for j in range(1, k+1):
        r = r * (n - k + j)
    for j in range(1, k+1):
        r = r / j
    return r

n,m,k = map(int,raw_input().split())
a = 0
for i in range(1,k+1):
    if (i <= m && k - i <= n && k - i >= 4):
        a += c(k - i, n) * c(i, m)
print a


def fact(n):
	res = 1
	for i in range(1, n + 1):
		res = res * i
	return res

def C(n, k):
        #if k > n:
        #	return -1
	res = fact(n)/(fact(k)*fact(n - k))
	return int(res)

	'''
__inp = input().split(' ')
N = int(__inp[0])
M = int(__inp[1])
T = int(__inp[2])

res = 0
for i in range(4, T):
	res += C(N, i)*C(M, T - i)

print int(res)
'''
for i in range(1, 31):
	print('{', end='')
	for j in range(1, 31):
		print(C(i, j), sep='', end=', ')
	print(C(i, i), '}, ', end='', sep='')


# coding=utf8

# from __future__ import division
# from collections import *
# from heapq import *
# from random import *
# from itertools import permutations
import re
import sys

def main():
import re
    print 'YES' if re.match(r'^\w{1,16}@\w{1,16}(\.\w{1,16})*(\/\w{1,16})?$',raw_input()) else 'NO'

if __name__ == '__main__':
    main()


def chk(s):
    if s=='': return 1
    for c in s:
        if not (c=='_' or c.isalpha()): return 1
    return 0
def chk2(s):
#    print s
    l=s.split('.')
    for x in l:
        if chk(x): return 1
    return 0
s=raw_input()
l=s.split('@')
if len(l)!=2 or l[0]=='' l[1]=='':
    print "NO";
else:
    if chk(l[0]):
        print "NO"
    else:
 #       print "HAHA"
        l=l[1].split('/')
        if len(l)>2:
            print "NO"
        else:
            if len(l)==1:
                if chk2(l[0]):
                 #   print "HHHH"
                    print "NO"
                else:
                    print "YES"
            else:
                if l[0]=='' or l[1]=="" or chk2(l[0]) or chk(l[1]):
                    print "NO"
                else:
                    print "YES"


#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
#include <random>
#include <chrono>

#define _ << " " <<
#define all(v) v.begin(), v.end()
#define sp(n) fixed << setprecision(n)
#define ff first
#define ss second

using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

const ll mod = 1e9 + 7;

vector<pii> g[101];
int ans1, ans2;
bool used[101] = {};

void dfs1(int v) {
	if (!used[v]) {
		used[v] = true;
		for (pii u : g[v]) {
			if (!used[u.ff]) ans1 += u.ss;
			dfs1(u.ff);
		}
	}
}

void dfs2(int v) {
	if (!used[v]) {
		used[v] = true;
		for (pii u : g[v]) {
			if (!used[u.ff]) ans2 += u.ss;
			dfs2(u.ff);
		}
	}
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		g[a].push_back({ b, 0 });
		g[b].push_back({ a, c });
	}
	for (int i = 1; i <= n; i++) sort(all(g[i]));
	ans1 = g[1][0].ss;
	used[1] = true;
	dfs1(g[1][0].ff);
	if (g[1][1].ss == 0) ans1 += g[g[1][1].ff][0].ss;
	fill(used + 1, used + n + 1, false);
	ans2 = g[1][1].ss;
	used[1] = true;
	dfs2(g[1][1].ff);
	if (g[1][0].ss == 0) ans2 += g[g[1][0].ff][0].ss;
	cout << min(ans1, ans2) << endl;
	return 0;
}


#include <iostream>
#include <cstdio>
#include <vector>
#include <list>
#include <complex>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <cstring>
#include <stack>
#include <cmath>
#include <iomanip>
#include <sstream>
#include <cassert>
#include <numeric>
#include <cfloat>
#include <climits>

using namespace std;
typedef long long ll;
typedef ll li;
typedef pair<int,int> PI;
#define EPS (1e-6)
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define REP(i, n) rep (i, n)
#define F first
#define S second
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define min3(a,b,c) min((a),min((b),(c)))
#define min4(a,b,c,d) min((a),min3((b),(c),(d)))
#define SZ(a) (int)((a).size())
#define ALL(a) a.begin(),a.end()
#define FLL(a,b) memset((a),b,sizeof(a))
#define CLR(a) memset((a),0,sizeof(a))
#define FOR(it,a) for(__typeof(a.begin())it=a.begin();it!=a.end();++it)
#define FORR(it,a) for(__typeof(a.rbegin())it=a.rbegin();it!=a.rend();++it)

template<typename T,typename U> ostream& operator<< (ostream& out, const pair<T,U>& val){return out << "(" << val.F << ", " << val.S << ")";}
template<class T> ostream& operator<< (ostream& out, const vector<T>& val){out << "{";rep(i,SZ(val)) out << (i?", ":"") << val[i];return out << "}";}
typedef double FP;
typedef complex<FP> pt;
typedef pt P;
typedef pair<pt,pt> line;
namespace std{
  bool operator<(const P&a,const P&b){
    if(abs(a.real()-b.real())>EPS)
      return a.real()<b.real();
    return a.imag()<b.imag();
  }
}
FP dot(P a,P b){return real(conj(a)*b);}
FP crs(P a,P b){return imag(conj(a)*b);}
P ortho(P a){return P(imag(a),-real(a));}
P ortho(line a){return ortho(a.S-a.F);}
P crspt(P a,P b,P c,P d){b-=a,d-=c;return a+b*crs(d,c-a)/crs(d,b);}
P crspt(line a,line b){return crspt(a.F,a.S,b.F,b.S);}
bool onl(P a1,P a2,P b){return abs(b-a1)+abs(b-a2)<abs(a1-a2)+EPS;}
bool onl(line a,P b){return onl(a.F,a.S,b);}
bool iscrs(line a,line b){P c=crspt(a,b);return onl(a,c)&&onl(b,c);}
void pkuassert(bool t){t=1/t;};
int dx[]={0,1,0,-1,1,1,-1,-1};
int dy[]={1,0,-1,0,-1,1,1,-1};
enum{TOP,BTM,LFT,RGT,FRT,BCK};
int dxdy2ce[]={RGT,FRT,LFT,BCK};
int s2i(string& a){stringstream ss(a);int r;ss>>r;return r;}
template<class T> T shift(T a,int b,int c,int d,int e){
  __typeof(a[0])t=a[b];
  a[b]=a[c];a[c]=a[d];a[d]=a[e];a[e]=t;return a;}
template<class T> T rgt(T a){return shift(a,TOP,LFT,BTM,RGT);}
template<class T> T lft(T a){return shift(a,TOP,RGT,BTM,LFT);}
template<class T> T frt(T a){return shift(a,TOP,BCK,BTM,FRT);}
template<class T> T bck(T a){return shift(a,TOP,FRT,BTM,BCK);}
line mkl(P a,P v){return line(a,a+v);}
FP lpdist(line a,P b){return abs(b-crspt(a,mkl(b,ortho(a))));}
FP spdist(line a,P b){
  P c(crspt(a,mkl(b,ortho(a))));
  return onl(a,c)?abs(b-c):min(abs(a.F-b),abs(a.S-b));
}
FP ssdist(line a,line b){
  return
    iscrs(a,b)?0.:
    min4(spdist(a,b.F),spdist(a,b.S),
         spdist(b,a.F),spdist(b,a.S));
}

bool ok(string a){
  FOR(it,a)
    if(!islower(*it) && !isupper(*it) &&
       !isdigit(*it) && *it!='_')
      return false;
  return true;
}

string solve(){
  string no="NO";
  string in;
  getline(cin,in);

  if(in.find('@') == string::npos)
    return no;

  int atp = in.find('@');
  string username = in.substr(0,atp);
  in = in.substr(atp+1);

  if(in.find('/') == string::npos) in += "/a";

  atp = in.find('/');
  string host = in.substr(0,atp);
  in = in.substr(atp+1);

  // cout << username << endl;
  // cout << host << endl;

  if(SZ(username)<1 || 16<SZ(username))
    return no;
  if(SZ(in)<1 || 16<SZ(in))
    return no;
  if(SZ(host)<1 || 32<SZ(host))
    return no;

  if(!ok(username)) return no;
  if(!ok(in)) return no;
  in = host;

  while(in!=""){
    string a;
    if(in.find('.') == string::npos){
      a = in;
      in = "";
    }else{
      a = in.substr(0,in.find('.'));
      in = in.substr(in.find('.')+1);
    }
    if(SZ(a)<1 || 16<SZ(a))
      return no;
    if(!ok(a))
      return no;
  }

  return "YES";
}

int main(int argc, char *argv[])
{
  cout << solve() << endl;
  return 0;
}


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

from string import letters, digits

def readint(): return int(raw_input())
def readfloat(): return float(raw_input())
def readarray(N, foo):
        res = []
        for _ in xrange(N):
                res.append(foo())
        return res
def readlinearray(foo): return map(foo, raw_input().split())

def is_only_letters_digits_and_underscore(word):
    for l in word:
            if l not in letters and l not in digits and l != '_' :
                return False
    return True

def is_len(min, max, word):
    return min <= len(word) <= max

def is_jabber_id(jabber_id):
    #<username>@<hostname>[/resource]

    if jabber_id.count('@') > 1 or jabber_id.count('/') > 1:
        return False

    try:
        username = jabber_id.split('@')[0]
        hostname = jabber_id.split('@')[1].split('/')[0]
        resource = None
        if '/' in jabber_id:
            resource = '/'.join(jabber_id.split('@')[1].split('/')[1:])
    except IndexError:
        return False

    if not is_len(1, 16, username):
        return False

    if not is_only_letters_digits_and_underscore(username):
        return False

    if not is_len(1, 32, hostname):
        return False

    for word in hostname.split('.'):
        if not is_len(1, 16, word):
            return False
        if not is_only_letters_digits_and_underscore(word):
            return False

    if resource is None:
        return True

    if not is_len(1, 16, resource):
        return False
    if not is_only_letters_digits_and_underscore(resource):
            return False
    return True

if __name__ == '__main__':

    jabber_id = raw_input()
    if is_jabber_id(jabber_id):
        print 'YES'
    else:
        print 'NO'


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


n,k=map(int,input().split())
s=input().lower()
letters=[0]*26
c=0
for i in s:
    nomer=ord(i)-97
    letters[nomer]+=1
letters.sort(reverse=True)
while 0 in letters:
    letters.pop()
for j in letters:
        b=j
        if b%k!=0:
            c=c+0

if c==0:
    print('YES')
elif
else:
    print('NO')


a=input().split()
a[0]=int(a[0])
a[1]=int(a[1])
s=input()
c=set(s)
k=0
for i in c:
   e=s.coint(i)
   c.get(i,e)
        continue
for j in c:
    k+=j.values()
if k%a[1]==0:
    print('Yes')
else:
    print('NO')


from collections import defaultdict

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

colors = input()
count = defaultdict(lambda:0)

for color in colors:
    count[color] zz

print(0)


#include <iostream>

using namespace std;
int n,k;
string s;
int main()
{
    cin >> n >> k;
    cin >> s;
    int cnt=0;
    for (int i=0; i<n; i++){
        for (int j=0; j<n; j++){
            if (s[i]==s[j] and i!=j){
                cnt+=1
            }

        }
        if (cnt>k){
        cout<<"NO";
        return 0;
        }
    }
    cout<<"YES";
    return 0;
}


n = int(input())
print(n%2 == 0 ? 'home' : 'contest')


n=int(input())
home=input()
for i in range(n-1):
    s=input()
s1=input().split('->')
if if n%2==0:
    print('home')
else:
    print('contest')


n=int(input())
c=0
r=input()
for i in range(0,n):
   s=input()
   if s[:3]==r: or s[5:] ==r:
     c=c+1
if c%2:
    print('contest')
else:
     print('home')


a=input()
home=raw_input()
c=1
for e in range(a):
    c+=raw_input().endswith(home)
if !(c % 2):
    print "contest"
else:
    print "home"


#include<bits/stdc++.h>
using namespace std;main(){int n;cin>>n;cout<<(n&1?"contest":"home");}


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

T = lambda: list(map(int, input().split()))
A = T()
B = T()
ans = [-1 for i in range(n + 1)]
for i in range(a):
    ans[A[i]] = 1
for i in range(1, n + 1):
    if ans[i] == -1:
        ans[i] = 2
for i in range(1, n + 1):
    print(ans[i], end = ' ')
input()


n,x,y=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=[0]*n
for i in range(len(a)):
    c[a[i]-1]=1
for j in range(len(b)):
    c[b[j]-1]=2
for i in c:
    print(i,endl=" ")


    n,a,b = map(int,input().split())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))
    for i in range(1,n+1):
        if i in a:
            print(1)
        elif i in b:
            print(2)


n, a, b = map(lambda x: int(x),str(raw_input()).split())
isa = map(lambda x:int(x),str(raw_input())
ans = ""
for i in range(1, n+1):
    if i in isa:
        print '1'
    else:
        print '0'


#include <bits/stdc++.h>
using namespace std;
int n,a,b,temp;
int main(){
    cin>>n>>a>>b;
    bool arr[a];
    for(int i=0;i<a;i++){
        cin>>temp;
        arr[temp]=1;
    }
    for(int i=0;i<b;i++) cin>>temp;
    for(int i=1;i<=n;i++){
        if(arr[i]==1) cout<<1<<" ";
        else cout<<2<<" ";
    }
}


n=input()
strs=input()
k='ogo'
while True:
    while k in strs:
        k+='go'
    k=k[:-2]
    strs=strs.replace(k,'***')
    if k=='ogo':
        print(strs)
        break
    else:
        k=='ogo'


_ = input()
s = input()
i = 0
out = ""
while i < len(s):
	if s[i] == "o" and if s[i+1] == "g" and if s[i+2] == "o":
		i += 3 + howMany(i+3)
	else:
		out = out + s[i]
		i += 1

def howMany(n):
	global s
	gping = True
	out = 0
	while i < len(s) and going:
		if s[n] == "g" and s[n+1] == "o":
			out += 1
		else:
			going = False


n=input()
strs=input()
k='ogo'
while True:
    while k in strs:
        k+='go'
    k=[:-2]
    strs=strs.replace(k,'***')
    if k=='ogo':
        print(strs)
        break
    else:
        k=='ogo'


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

set<int> x, y;
set<int>::iterator l, r;
multiset<int> lx, ly;

int h, w, n;

int main()
{
	char c, s;
	int z;
	long long ans;
	cin>>w>>h>>n;
	x.insert(0);x.insert(w);
	y.insert(0);y.insert(h);
	lx.insert(w);ly.insert(h);
	for (int i=0; i<n; i++)
	{
		cin>>c>>z;
		if (c == 'H')
		{
			y.insert(z);
			l =r =y.find(z);
			l--; r++;
			ly.erase(ly.find(*r-*l));
			ly.insert(*r-z);ly.insert(z-*l);
		}
		else
		{
			x.insert(z);
			l =r =x.find(z);
			l--; r++;
			lx.erase(lx.find(*r-*l));
			lx.insert(*r-z);lx.insert(z-*l);
		}
		ans = *lx.rbegin();
		ans *= *ly.rbegin();
		cout<<ans<<endl;
	}
}


b = input()
	a = input()
	i = int(b)
	if 'ogo' not in a:
		print(a)
		exit()
	x = ''
	while i != 0:
		if 'o'+('go' * i) in a:
			x = a.replace('o' + ('go' * i), '***')
			a = x
		i -= 1
	print(x)


import math
n, m = list(map(int,input().split()))
if n % m == 0:
    print(*m*(int(n/m),), sep=' ')

else:
    print(*str(n//m) * (m-(n%m)), *str(math.ceil(n/m)) * (n%m), sep =' ')


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

int i=n//m
int j=n%m
for x in range(m-j):
    print(i,end=" ")
for x in range(j):
    print(i+1,end=" ")


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

/* Policy Based Data Structure
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
using namespace __gnu_pbds;
typedef tree<
    int,
    null_type,
    less<int>,
    rb_tree_tag,
    tree_order_statistics_node_update > pbds;
*/

#define print_time cerr << "Time taken: " << fixed << setprecision(3) << 1.0 * clock() / CLOCKS_PER_SEC << " secs";
#define fast_io ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define int long long
#define LD long double
#define testcases int test; cin >> test; for (int tc = 1; tc <= test; tc++)
#define iOS ios::sync_with_stdio(0); cin.tie(0); cerr.tie(0);
#define endll "\n"
#define get(x,y) get<x>(y)
#define ff first
#define ss second
#define sz size
#define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>void ZZ(const char* name, Arg1&& arg1){std::cerr << name << " = " << arg1 << endl;}
template <typename Arg1, typename... Args>void ZZ(const char* names, Arg1&& arg1, Args&&... args)
{
    const char* comma = strchr(names + 1, ',');
    std::cerr.write(names, comma - names) << " = " << arg1;
    ZZ(comma, args...);
}
int modpow(int a, int b, int m) {int res = 1; while (b) {if (b & 1) res = (res * a) % m; a = (a * a) % m; b >>= 1;} return res;}
int gcd(int a, int b) {if (a == 0 && b == 0) return 1; return __gcd(a,b);}

const int MOD = 1e9 + 7;
const int N = 1e5+5;

string str;
int cost1, cost2;
set<pair<int, int> > st;
int32_t main()
{
    fast_io

    cin >> str;
    int open_brackets = 0, ans = 0;

    for (int i = 0; i < str.size(); i++) {
        if (str[i] == '(')
            open_brackets++;
        else
            open_brackets--;

        if (str[i] == '?') {
            cin >> cost1 >> cost2;
            st.insert({cost1 - cost2, i});
            ans += cost2;
            str[i] = ')';
        }
        if (open_brackets < 0) {
            if (st.empty())
                break;
            int dcost = st.begin()->first;
            int id = st.begin()->second;
            st.erase(st.begin());
            str[id] = '(';
            ans += dcost;
            open_brackets += 2;
        }
    }
    if (open_brackets) puts("-1");
    else {
        cout << ans << "\n" << str;
    }

    print_time
}


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

if n%m==0:
    result=n/m
    for i in range(m):
        print result,

else:
    rest=n%m
    fair=(n-n%m)/m
    for i in range(m-rest):
        print fair,

    for j in range(rest):


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

int i=int(n/m)
int j=n%m
for x in range(m-j):
    print(i,end=" ")
for x in range(j):
    print(i+1,end=" ")


#!/usr/bin/env python3
def solve(a,b):
    if a == 1 and b == 1:
        return 1
    else:
        a, b = max(a, b), min(a, b)
        return 1 + solve(a - b, b)
a, b = map(int,input().split())
print(solve(a,b))


a,b=map(int,input().split())
if a>b:print((a//b)+(b%(a%b))*(a%b)+(b//(a%b)))
else:print((b//a)+((b%a)*a))


a, b = map(int, input().split())
ans = 0
if a % b == 0 or b % a == 0:
  print(max(a // b, b // a))
  exit(0)
while a and b:
  if a - b > 0:
    ans += a // b
    a, b = a % b, b
  else:
    ans += b // a
    a, b = a, b % a
if a % b == 0:
  ans += a // b
else:
  ans += b // a
print(ans)


def fun(a,b):
    if a==0:
        return 0
    if b==0:
        return 0
    if b==1:
        return a
    else:
        return ((a//b)+1)+fun(a%b,(b-(a%b)))
a,b=map(int,raw_input().split())
print fun(a,b)


def fun(a,b):
    if b==1:
        return a
    else:
        return ((a//b)+1)+fun(a%b,(b-(a%b)))
a,b=map(int,raw_input().split())
print fun(a,b)


def lcm(a,b):
    for i in range(b,b*b):
        if(i%a==0 and i%b==0):
            return i

a,b,c,d=map(int,input().split())
e=lcm(a,b)
value=0
for i in range(c,d+1):
    if(i%e==0):
        value+=1
print(value)


def gcd(x,y) :
    if y == 0 :
        return x
    else :
        t = x%y
        x = y
        y = t
        return gcd(x,y)

x,y,a,b = map(int,raw_input().split())
k = x*y/gcd(x,y)

t = a%k
d,u = 0,0
if t == 0 :
    d = a/k
else :
    d = a/k + 1

t = b%k
if t == 0 :
    u = b/k
else :
    u = b/k + 1

res = u-d+1
if res < 0
    res = 0

print res


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


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


from sys import stdin

in_lines = stdin.readlines()

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

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

x, y, a, b = lines[0]

before = (a - 1) / (x * y)
overall = (b / (x * y)
print overall - before


import sys
import copy
from collections import Counter
sys.setrecursionlimit(11111)
import re
import itertools

n = int(sys.stdin.readline().strip())
ans = [2,1,3,1,2]
if n == 1:
	print ans[n-1]
else sys.exit(n)


n=int(input())
if n<3 then:
    print 1
else
    print 2


## DATA SOURCE (1 for file, 0 for std input)
opt = 0
src = opt and open("input", "r") or None

def gvals(source, format = int, separator = ' '):
	if source:
		a = map(format, source.readline().split(separator))
	else:
		a = map(format, raw_input().split(separator))
	return a

def gval(source, format = int):
	if source:
		a = format(source.readline())
	else:
		a = format(raw_input())
	return a

a = gval(src)
if a!=1:
	print 1
else
	print 2


n, k = (int(x for x in raw_input().rstrip().split())
ret = 10 ** (n-1)
while ret >= 0 or ret % k != 0:
	ret += 1
print ret


n,t=map(int,input().split())
d=10**(n-1)
e=10**n
for i in range(d,e):
    if i%t=0:
        print(i)
        break


x=map(int,raw_input().split())
k=x[1]
n=x[0]
if len(str(k))=<n:
    s=str(k)
    for i in range(n-1):
        s+=str(0)
    if k>=10:
        s=s[:-1]
else:
    s=str(-1)
print s


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

while len(str(t)) < n:
    t = t+t
    print(t)

else len(str(t)) > len(str(1)):
    print("-1")


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

if t == 10:

  ans = int(t)*(10**(int(n)-2))

  if len(str(ans)) == int(n):

    print (ans)

  else:

    print('-1')

else:

  ans = int(t)*(10**(int(n)-1))

  if len(str(ans)) == int(n):

    print (ans)

  else:

    print('-1')


k=int(input())
a=list(map(int,input().split()))
a.sort()
a.reverse()
tot=sum(a)
d=0
n=0
for i in range (len(a)):
    tot=tot-a[i]
    d=d+a[i]
    n=n+1
    if k==0:
        print("0")
        break
    elif d==k or d>k:
        print(n)
        break
     elif d<k:
         print("-1")
         break


k = int(input())
li = [int(x) for x in input().split()]
f = False
if k==0:
    print('0')
    f = True
ct = 0
sum = 0
li.sort(reverse=True)
flag = False
for i in range(12):
    sum += li[i]
    else:
        f = False
        break
    ct += 1
    if sum>=k:
        f = True
        print(ct)
        break
if not f:
    print('-1')


 def getI(a, k):

    def getSliceSum(ar, till):
        res = 0
        for i in range(till):
            res += ar[i]
        return res

    if k ==0: return 0
    if a[0] >=k: return 1
    count = 0
    a.sort(reverse=True)
    for ai in range(12):
        res = getSliceSum(a, ai)
        if res >= k: return ai


#! /usr/bin/env ruby

k = gets.to_i
m = gets.chop.split.map {|x| x.to_i}.sort.reverse
sum = 0
sol = m.map {|x| sum += x}.map { |i| i >= k }.find_index(true)

if k.equal? 0
  p 0
elsif sol.equal? nil
  p -1
else
p sol + 1
end


limit = int(raw_input())
months = map(int, raw_input().split())
months.sort(reverse = True)
i = 0
while limit > 0:
	limit = limit - months[i]
	i = i + 1
        if (i == len(months)):
               print(-1)
               return
print(i)


def find_factor(all):
    i = 2
    list = [0]
    while i < all :
        if all % i == 0 :
            list.append(i)
        i += 1
    return list[1:] #输出所有因数，列表形式输出

def if_candiv(str,div_value): #查看该子串是否可分割成值为div_value的串
    left = div_value
    position = 0
    for i in str:
        left -= int(i)
        if left == 0:
            return str[position+1:],"YES"
        elif left < 0:
            return str,"NO"
        position += 1

try:
    while True:
        length = int(input())
        num_str = input().strip("0")
        length = len(num_str)
        all = 0
        for i in num_str:
            all += int(i)
        if all == 0:
            print("YES")
        else :
            factor_list =find_factor(all)
            flag_0 = "NO"
            for factor in factor_list:
                print(factor)
                copy_str = num_str
                position = 0
                flag_1 = "YES"
                while position < length :
                    print(copy_str)
                    [copy_str,flag_1] = if_candiv(copy_str,factor)
                    position = length - len(copy_str)
                    if flag_1 == "NO":
                        print(flag_1)
                        break
                if flag_1 == "YES":
                    flag_0 = "YES"
                    break
            print(flag_0)
except EOFError:
    pass


import math

n = int(input())
s = input()
a = []
p = []
t = 0
f = 1

for i in range(n):
    a.append(int(s[i]))
    t += a[i]
    p.append(t)

for i in range(n):
    s = p[i]
    f = 1
    t = 0
    k = i+1
    c = 0
    for j in a[k:n]:
        t += j
        if c and !t: continue
        if j == n-1 and t != s:
            f = 0
        elif t == s:
            t = 0
            c += 1
        elif t > s:
            f = 0
            break
    if i == n-1 and f: f = 0
    if f: break

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


n=int(input())
a=input()
s=[]
for i in range(n):
	s.append(int(a[i]))
xx=sum(s)
for i in range(1001):
	cur=0
	it=0
	for j in range(n):
		cur+=s[j]
		if cur==num:
			it+=1
			cur=0
	if cur==0 && it>1:
		f=1
		break
if f==1:
	print("YES")
else:
	print("NO")


import sys
n = int(input())
s = input()
s = list(map(int,''.join(s)))
summa = sum(s)
p = []

if sum(s) == 0:
    #print('YES')
    sys.exit()

for i in range(summa-1,1,-1):
    if summa % i == 0:
        p.append(int(summa / i))

#print('summa=',summa,'p=',p)

yes = 0
no = 0

for x in p:
    s1 = s[:]
    #print('-------x=',x,'----')
    #print(s)
    #print(s1)
    flag = 0
    count = 0
    while s1 != []:
        count += s1.pop()
        if count == x:
            #print('count=',count,)
            count = 0
        elif count < x:
            continue
        else:
            flag = 1
            break

    #print(flag,count)
    if flag == 1:
        no += 1
    else:
        yes += 1

if yes == 0:
    print('NO')
else:
    print('YES'


# C. Vasya and Golden Ticket

n = int(input())
digits = list(input())
digits = list(map(int, digits))
dig_sum = sum(digits)
part_sum = 1
if dig_sum == 0:
    print("YES\n")
    exit()
# 由于数据量不大，因此枚举每一种可能的部分和
for part_sum in range(1, dig_sum):      # 用for比 while代码量更小，占内存也更小
    if dig_sum % part_sum != 0:
        continue
    temp = 0                            # 注意要置零！！
    for i in range(0, n):               # i就不需要再置零了，每次都会从range的第一个开始
        temp += digits[i]
        if temp == part_sum:            # 这里不需要再开一个flag，直接用temp就很方便
            temp = 0
        elif temp > part_sum:
            break
    if temp == 0:
        print("YES\n")
        exit()
print("NO\n")


def solve(n, x, y):
    if(x == 0):
        return y
    elif y == n:
        return y + x
    elif x == n:
        return 3 * m - y
    else:
        return 4 * n - x

n, x1, y1, x2, y2 = map(int, raw_input().split(" "))
p1 = solve(n, x1, y1)
p2 = solve(n, x2, y2)

print min((p1 - p2 + 4 * n) % (4 * n),(p2 - p1 + 4 * n) % (4 * n)


n,x1,y1,x2,y2 = map(int,raw_input().split())
if abs(x1-x2) = n:
    d1 = x1 + x2 + 2*n
    d2 = 2*n - x1 - x2
    print min(d1,d2)
elif abs(y1-y2) = n:
    d1 = y1 + y2 + 2*n
    d2 = 2*n - y1 - y2
    print (d1,d2)
elif x1 = x2 = 0: print abs(y2-y1)
elif y1 = y2 = 0: print abs(x2-x1)
elif print abs(x2-x1) + abs(y2-y1)


n,x1,y1,x2,y2 = map(int,raw_input().split())
if abs(x1-x2) == n:
    d1 = x1 + x2 + 2*n
    d2 = 2*n - x1 - x2
    print min(d1,d2)
elif abs(y1-y2) == n:
    d1 = y1 + y2 + 2*n
    d2 = 2*n - y1 - y2
    print (d1,d2)
elif x1 == x2 == 0: print abs(y2-y1)
elif y1 == y2 == 0: print abs(x2-x1)
elif print abs(x2-x1) + abs(y2-y1)


n,a,b,x,y=map(int,input().split())
def safe(n,a,b):
	if n>=a and n>=b:
		return True
	return False

def short(n,a,b,x,y):
	rs=[0,0,1,-1]
	cs=[1,-1,0,0]
	q=[(a,b,0)]
	bx=0
	while len(q)!=0:
		xsi=q.pop(0)
		xs,ys,zs=xsi[0],xsi[1],xsi[2]
		if xs==x and ys==y:
			bx=zs
			break

	    for i in range(4):
		    for j in range(4):
			    ri=rs[i]+xs
			    ci=cs[i]+ys
			    if safe(n,ri,ci):
				    q.append((ri,ci,zs+1))

    return bx

print(short(n,a,b,x,y))


n,a,b,x,y=map(int,input().split())
def safe(n,a,b):
	if a==0 or b==0 or a==n or b==n:
		return True
	return False

def short(n,a,b,x,y):
	rs=[0,0,1,-1]
	cs=[1,-1,0,0]
	q=[(a,b,0)]
	bx=0
	while len(q)!=0:
		xsi=q.pop(0)
		xs,ys,zs=xsi[0],xsi[1],xsi[2]
		if xs==x and ys==y:
			bx=zs
			break
		for i in range(4):
			for j in range(4):
				ri=rs[i]+xs
				ci=cs[i]+ys
				if safe(n,ri,ci):
					q.append((ri,ci,zs+1))

	return bx

print(short(n,a,b,x,y))


import collections

def count(n, k):

    m = collections.defaultdict(lambda: 0)
    m[0] = 1
    for i in range(1, n + 1):

        for j in range(1, k + 1):

            if i - j in m:

                m[i] += m[i - j]

    return m[n]

n, k, d = tuple(map(int, str.split(input())))
print((count(n, k) - count(n, d - 1)) % (10 ** 9 + 7)


'''#problem1
n=int(input())
price=[int(i) for i in input().split()]
q=int(input())
acc=[]
for i in range(q):
    k=int(input())
    acc.append(k)
price.sort()
def search(k,arr):
    l=0
    r=len(arr)-1
    ans=0
    while l<=r:
        mid=l+int((r-l)/2)
        if arr[mid]<=k:
            ans=mid+1
            l=mid+1
        else:
            r=mid-1
    return ans
for j in acc:
    a=search(j,price)
    print(a)'''

'''n=int(input())
nums=[int(i) for i in input().split()]
s=sum(nums)
ans=0
if s%3!=0:
    ans=0

else:
    s/=3
    cnt=[0]*(n)
    sum=0
    for i in range(n-1,-1,-1):
        sum+=nums[i]
        if sum==s:
            cnt[i]=1
    for j in range(n-2,-1,-1):
        cnt[j]+=cnt[j+1]
    sum=0
    k=0
    while k+2<n:
        sum+=nums[k]
        if sum==s:
            ans+=cnt[k+2]

        k+=1
print(ans)'''

n,k,d=[int(i) for i in input().split()]
ans=0
dp=[[0,0] for j in range(n+1)]
dp[0][0]=1
dp[0][1]=0
for i in range(1,n+1):4 5 2
    for j in range(1,k+1):
        if i-j<0:
            break
        if j<d:
            dp[i][0]+=dp[i-j][0]
            dp[i][1]+=dp[i-j][1]
        else:
            dp[i][1]+=dp[i-j][0]
            dp[i][1]+=dp[i-j][1]
print(dp[n][1]%(10**9+7))


#!/usr/bin/python

def memoize(f):
    cache= {}
    def memf(*x):
        if x not in cache:
            cache[x] = f(*x)
        return cache[x]
    return memf

import sys

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

n, k, d = Ni()
M = 10**9 + 7

@memoize
def count(n, haveD):
    #print n, haveD
    if n == 0:
        return 1 if haveD else 0

    return sum(count(n - i, haveD or i >= d) for i range(1, min(n, k) + 1)) % M

print count(n, False)


mod = 1e9+7
def add(a,b):
	a += b
	if a >= mod:
		return a-mod
	return a

def Sulution():
	n,k,d = [int(x) for x in input().split()]
	dp = [[for j in range(100)]0 for i in range(2)]
	print(dp)
	dp[0][0] = 1
	dp[0][1] = 0
	for i in range(1,n):
		for j in range(1,k):
			if i < j:
				break
			if j < d:
				dp[i][0] += dp[i-j][0]
				dp[i][1] += dp[i-j][1]
			else:
				dp[i][1] += dp[i-j][0]
				dp[i][1] += dp[i-j][1]
			if dp[i][0] >= mod:
				dp[i][0] -= mod
			if dp[i][1] >= mod:
				dp[i][1] -= mod

	return dp[n][1]

print(Sulution())


    MOD = 10 ** 9 + 7
    HAVE, NOT_HAVE = 1, 0

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

    dp = [[0 for _ in range(n + 1)] for _ in range(2)]
    dp[NOT_HAVE][0] = 1
    for dist in range(1, n + 1):
        for weight in range(1, k + 1):
            if weight > dist:
                break
            if weight >= d:
                dp[HAVE][dist] += dp[HAVE][dist - weight] + dp[NOT_HAVE][dist - weight]
                dp[HAVE][dist] %= MOD
            else:
                dp[NOT_HAVE][dist] += dp[NOT_HAVE][dist - weight]
                dp[NOT_HAVE][dist] %= MOD
                dp[HAVE][dist] += dp[HAVE][dist - weight]
                dp[HAVE][dist] %= MOD
    print(dp[HAVE][n])


a,b=[int(x) for x in input().split()]
print(pow(2,a+b,998244353)


def solve()
  from sys import stdin
  line = stdin.readline
  a,b=map(int,line().split())
  print(pow(2,a+b,99824435))
solve()


a=int(input())

b=int(input())
c=int(input())

d=int(input())

e=int(input())
f=int(input())

big=max(e,f)
x=min(b,c)

if (big==f):
    if((d-x)>0):
        sum=min(x,d)*f + min(a,(d-x))*e
    else:
        sum=d*f
else:
    if((d-a)>0)
        sum=min(a,d)*e + min(x,(d-a))*f
    else:
        sum=d*e
print(sum)


    a, b, c, d, e, f = [int(input()) for _ in range(6)]

    suits1 = min(a,d)
    suits2 = min(b,c,d)

    total = 0
    if e>f:
        total += suits1 * e
        total += min(suits2,d-suits1)*f if d-suits1 > 0 else 0
    else:
        total += suits2 * f

        total += min(suits1,d-suits2)*e if d-suits2 > 0 else 0

    print(total)


a=int(input())
b=int(input())
c=int(input())
d=int(input())
e=int(input())
f=int(input())
x=0

if e>f:
    if a>d:
        return d*e
    elif d>a:
        y=d-a
        x+=a*e
        z=min(y,b,c)
        x+=z*f
elif f>e:
    if b>d or c>d:
        return d*f
    else:
        y=min(b,c)
        z=d-y
        x+=y*f
        m=min(z,a)
        x+=m*e

return x


ties=int(input())
scarves=int(input())
vests=int(input())
jackets=int(input())
s1=int(input())
s2=int(input())

#s1=tie+jacket
#s2=scarf+vest+jacket

cost1=0
cost2=0

if s1>=s2:
    k=min(ties,jackets)
    cost1+=(k*s1)
    j2=jackets-k
    l=min(scarves, vests, j2)
    cost1+=(l*s2)

if s1<=s2:
    l=min(scarves, vests, jackets)
    cost2+=(l*s2)
    j1=jackets-l
    k=min(ties,j1)
    cost2+=(k*s1)

if s1>s2:
    print(cost1)

elif s1<s2:
    print(cost2)

elif s1=s2:
    print(max(cost1,cost2))


a=int(input())
b=int(input())
c=int(input())
d=int(input())
e=int(input())
f=int(input())

c1 = min(a,d)*e + f*(min(b,c,max(0,d-a))
c2 = min(d, b, c) * f + min(max(d - min(b, c), 0), a) * e)

print(c1,c2)
print(max(c1,c2))


prime = []
marked = [0]*(10000000/64+2)

def on(x) :
    return marked[x/64] & (1 << ((x%64)/2))
def mark(x) :
    marked[x/64] |= (1 << (x % 64)/2)
    return

def sieve(n) :
    i = 3
    while i * i <= n :
        if not on(i) :
            for j in range(i*i , n , i+i) :
                mark(j)
        i += 2
    prime.append(2)
    for i in range(3,n,2) :
        if not on(i) :
            prime.append(i)
    return

sieve(5010000 )

n = int(input())
i = 0
cnt = 0
ans = 1
while prime[i] * prime[i] <= n :
    while n % prime[i] == 0 :
        if cnt == 2 :
            break
        n /= prime[i]
        cnt  += 1
        ans *= prime[i]
    i += 1

if cnt == 0 :
    print '1 \n 0'
elif n == 1 and cnt <= 2 :
    print '2\n'
elif n != 1 and cnt < 2 :
    print '2\n'
else :
    print '1'
    print ans


# -*- coding: utf-8 -*-
import sys

if __name__ == '__main__':

    num = map(int,sys.stdin.readline().split())
    lit = []
    n = num[0]
    flag = True

    while flag:
        flag2 = 1

        for v in range(2,int(n **(0.5))+2):

            if n != 2 and n/v * v == n:
                lit.append(v)
                n /= v
                flag2 = 0

                break
            else:
                pass

        if flag2 == 1:
            flag = False

    if len(lit) == 0:
        print 1
        print 0
    elif len(lit) == 1:
        print 2
    else:
        print 1
        print lit[0] * lit[1]


prime = []
marked = [0]*(10000000/64+2)

def on(x) :
    return marked[x/64] & (1 << ((x%64)/2))
def mark(x) :
    marked[x/64] |= (1 << (x % 64)/2)

def sieve(n) :
    i = 3
    while i * i <= n :
        if not on(i) :
            for j in range(i*i , n , i+i) :
                mark(j)
        i += 2
    prime.append(2)
    for i in range(3,n,2) :
        if not on(i) :
            prime.append(i)

sieve(5010000)

n = int(input())
i = 0
cnt = 0
ans = 1
while prime[i] * prime[i] <= n :
    while n % prime[i] == 0 :
        if cnt == 2 :
            break
        n /= prime[i]
        cnt  += 1
        ans *= prime[i]
    i += 1

if cnt == 0 :
    print '1 \n 0'
elif n == 1 and cnt <= 2 :
    print '2\n'
elif n != 1 and cnt < 2 :
    print '2\n'
else :
    print '1'
    print ans


a = int(input())
n = a

found = 0
for i in range(2):
    j = 2
    while j * j <= a:
        if a % j == 0:
            found += 1
            a /= j
            break
        j += 1

if found == 0:
    print "1"
    print "0"
elif found == 1:
    print "2"
else:
    print "1"
    print n / a


def f(n):
    if n < 4: return '1\n0'
    k, j = int(n ** 0.5), 0
    if n % 2 == 0:
        if n % 4 == 0: return '1\n4' if n > 4 else '2'
        j = 2
    if n % 3 == 0:
        if j: return '1\n6' if n > 6 else '2'
        if n % 9 == 0: return '1\n9' if n > 9 else '2'
        j = 3
    for i in range(5, k, 6):
        if n % i == 0:
            if j: return '1\n' + str(i * j)
            if n % (i * i) == 0: return '1\n' + str(i * i)
            j = i
    for i in range(7, k, 6):
        if n % i == 0:
            if j: return '1\n' + str(i * j)
            if n % (i * i) == 0: return '1\n' + str(i * i)
            j = i
    return '2' if j or k * k == n else '1\n0'
print f(int(raw_input()))


import sys
range = xrange
input = raw_input

n = int(input())
s = input().encode()

mem = [[-1]*(n+1) for _ in range(n+1)]

# Solve for s[l:r]
def DP(l,r):
    # Empty string
    if l==r:
        return 0
    if mem[l][r]==-1:
        # Either remove the left most character
        score = 1 + DP(l+1,r)

        # Or remove a piece in the middle
        for i in range(l+1,r):
            if s[l] == s[i]:
                # s[l+1:i] is the middle piece
                new_score = DP(l+1,i) + DP(i,r)
                    score = min(score,new_score)
        mem[l][r] = score
    return mem[l][r]

print(DP(0,n))


n=int(input())
C="0"+input()

A=[]
for i in range(1,n+1):
    if C[i]!=C[i-1]:
        A.append(C[i])

L=len(A)

DP=[[[0]*L for i in range(L)] for k in range(2)]
#左の色に揃える or 右の色に揃える,左からi～j番目を

DICT=dict()
for i in range(1,L-1):
    for j in range(i-1,-1,-1):
        if A[j]==A[i]:
            i_MIN=j
            break
    else:
        continue

    for j in range(i+1,L):
        if A[j]==A[i]:
            i_MAX=j
            break
    else:
        continue

    DICT[(i_MIN,i_MAX)]=i

def color(r,i,j):#i<j
    if r==1:
        if A[i]==A[j]:
            DP[r][i][j]=min(DP[0][i][j-1],DP[1][i][j-1]+1)

            if (i,j) in DICT:
                if DP[r][i][j]>DP[0][i][DICT[(i,j)]]+DP[1][DICT[(i,j)]][j]:
                    DP[r][i][j]=DP[0][i][DICT[(i,j)]]+DP[1][DICT[(i,j)]][j]

            #for k in range(i+1,j):
            #    if DP[r][i][j]>DP[0][i][k]+DP[1][k][j]:
            #        DP[r][i][j]=DP[0][i][k]+DP[1][k][j]

        else:
            DP[r][i][j]=min(DP[0][i][j-1]+1,DP[1][i][j-1]+1)

    else:
        if A[i]==A[j]:
            DP[r][i][j]=min(DP[1][i+1][j],DP[0][i+1][j]+1)

            if (i,j) in DICT:
                if DP[r][i][j]>DP[0][i][DICT[(i,j)]]+DP[1][DICT[(i,j)]][j]:
                    DP[r][i][j]=DP[0][i][DICT[(i,j)]]+DP[1][DICT[(i,j)]][j]
        else:
            DP[r][i][j]=min(DP[1][i+1][j]+1,DP[0][i+1][j]+1)

for i in range(1,L):
    for j in range(L-i):
        color(0,j,i+j)
        color(1,j,i+j)

    #print(DP)

print(min(DP[0][0][L-1],DP[1][0][L-1])+1)


n=int(input())
s=input()
F=[[None]*n for i in range(n)]
# x=set()
# for i in s:
#     x.add(i)

for i in range(n):
    F[i][i]=1

for l in range(2,n+1):
    for i in range(0,n-l+1):
        j=i+l-1
        temp=[]
        t=i
        f=0
        for k in range(i+1,j+1):
            if s[k]==s[i]:
                temp.append(k)
        for q in temp:
            if q-t>=2:
                f+=F[t+1][q-1]
            t=q
        if t<j:
            f+=F[t+1][j]

        F[i][j]=min(f,F[i+1][j])+1

print(F[0][n-1])
# s=input()
# a=[]
# for i in range(1,len(s)):
#    if s[i]==s[0]:
#     a.append(i)
# t=0
# for i in a:
#     if i-t>=2:
#         print(str(t)+' '+str(i))
#     t=i


n=int(input())
s=input()
dp=[[0]*(n+1) for _ in range(n+1)]
dp[n-1][n-1]=1
for i in range(n-1,-1,-1):
    for j in range(i,n):
        for k in range(i+1,j+1):
            if s[k]==s[i]:
                dp[i][j]=dp[i+1][k-1]+dp[k][j]
                break
        else:dp[i][j]=dp[i+1][j]+1
print(dp[0][-2])


n = int(input())
s = input()
cnt = 0
bayan = set()
for i in range(n):
    for j in range(n):
        if s[i] == s[j] and s[i] not in bayan and len(set(s[i:j])) == 2:
            cnt += 1
            bayan.add(s[i])
print(len(set(s)) * cnt)


import math

houses = int(input())
goal = int(input())
if(goal%2 == 0):
    print((houses-goal)//2+1)
else:
    print(math.ceil(goal/2))


s = input()
w = ""
h = ""
b = True
s = list(s)
for f in s:
  if not b:
    h += f
  if f != " " and b:
    w += f
  else:
    b = False
n = int(w)
a = int(h)

n = int(input())
a = int(input())

if a % 2 == 0:
  tiempo =  ((n - a) / 2) + 1

else:
  tiempo = ((a-1)/2)+1

print(int(tiempo))


n, number = map(int input().split())
if number % 2:
    print(number // 2 + 1)
else:
    print((n - number) // 2 + 1)


n,a = [int(i) for i in input().split()]
if a%2==0
	t = n//2-a//2
else:
	t = a//2
print(t+1)


#include <bits/stdc++.h>

using namespace std;

int n;

long long ans, a[2000010];

int main() {
	ios::sync_with_stdio(false);
	cin >> n;
	for (int i = 1; i <= n; i ++) cin >> a[i];
	sort(a + 1, a + n + 1);
	for (int i = 1; i <= n; i ++) a[i] += a[i - 1];
	for (int i = 1; i <= n; i *= 4) ans += a[n] - a[n - i];
	cout << ans;
	return 0;
}


from sys import stdin
ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def isValid(ss):
    for i in range(1,len(ss)):
        if ss[i]==ss[i-1]:
            return False
    return True
ss = input()
res=0
if not isValid(ss):
    res=-1
li = ss[:13]
li2=ss[13:]
li_rev=li2[::-1]

ans=''

for x in ch:
    if ss.count(x)>1:
        ans=x
        break
i_li = ss.index(ans)
if i_li>12:
    i_rev = i_li;
    i_li=li.index(ans)

else:
    i_rev = li_rev.index(ans)

check = abs(i_li-i_rev)
if check>1: res=-1
if res==-1: print('Impossible')
else:
    print(li+'\n'+li_rev[:i_rev]+li_rev[i_rev+1:])


from collections import Counter

def locationForDup(diff):
    if(diff == 0): return None
    x = 12 - ((diff) / 2)
    y = 0
    return (x, y)

def printArr(array):
    for a in array:
        print "".join(map(str,a))
    print

def flowCategory(diff):
    # 0 => prev = below
    # 1 => prev = diagonal
    return diff % 2

def printArr1(x):
    pass
    # printArr(x)

def fill(xs, arrays, diff, start, stop, dup):
    if(start > 13):
        return fill(list(reversed(xs)), arrays, diff, 27 - stop, 27 - start, dup)
    (lx, ly) = locationForDup(diff)
    # print(xs)
    # print(start)
    # print(dup)
    # print(diff)
    f = flowCategory(diff)
    if(start >= 0):
        totalTrip = 0
        if(f == 0):
            mx, my = (lx, 1)
        else:
            mx, my = (lx - 1, 1)
        arrays[ly][lx] = dup
        r1 = reversed(xs[:start])
        for i, c in enumerate(r1):
            totalTrip += 1
            x = mx - i
            y = 1
            assert(type(arrays[y][x]) is int)
            if(x >= 0):
                arrays[y][x] = c
            else:
                __s = i if vars().get("__s") is None else vars()["__s"]
                x = i - __s
                y = 0
                arrays[y][x] = c
        r2 = (xs[start + 1:])
        printArr1(arrays)
        for i, c in enumerate(r2):
            totalTrip += 1
            x = lx + i + 1
            y = 0
            if(x > 12): break
            assert(type(arrays[y][x]) is int)
            arrays[y][x] = c
        printArr1(arrays)
        b = i
        for i, c in enumerate(xs[start + b + 1:]):
            totalTrip += 1
            x = 12 - i
            y = 1
            if(type(arrays[y][x]) is not int): break
            if(c == dup): break
            assert(type(arrays[y][x]) is int)
            arrays[y][x] = c
        printArr1(arrays)
        for i, c in enumerate(xs[stop:]):
            totalTrip += 1
            x = lx - i - 1
            y = 0
            assert(type(arrays[y][x]) is int)
            arrays[y][x] = c
            if(x == 0): break
        for i, c in enumerate(xs[totalTrip:]):
            x = i
            y = 1
            assert(type(arrays[y][x]) is int)
            arrays[y][x] = c
    else:
        pass

def main():
    xs = raw_input()
    counter = Counter(xs)
    dup = [c for c in counter.keys() if counter[c] > 1][0]
    start = xs.find(dup)
    stop = len(xs) - "".join(list(reversed(xs))).find(dup)
    diff = stop - start - 2
    arrays = [[x % 10 for x in xrange(13)] for _ in xrange(2)]
    if(locationForDup(diff) is None):
        print("Impossible")
    else:
        fill(xs, arrays, diff, start, stop, dup)
        printArr(arrays)
main()


s = raw_input()
min1 = 65
di = {}
lis1 = [0]*13
lis2 = [0]*13

for i in xrange(27):
	if s[i] in di:
		break
	else:
		di[s[i]] = i
s += s
bet1 = i-di[s[i]]-1
if bet1 == 0:
	print 'Impossible'
else:
	start = di[s[i]]
	for j in xrange(13-bet1/2-1,13):
		lis1[start] = s[j]
		start += 1

	for j in xrange(12,-1,-1):
		if start == i:
			start += 1
		lis2[j] = s[start]
		start += 1

	for j in xrange(0,13-bet1/2-1):
		lis1[j] = s[start]
		start += 1

	print ''.join(lis1)
	print ''.join(lis2)


sbuf = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
Ans1=''
Ans2=''
s=raw_input()
f=1
for i in range(len(s)-1):
    if s[i] == s[i+1]:
        f=0
if f == 0 :
    print "Impossible"
else:
    bukva = ''
    for i in sbuf:
        if s.count(i) > 1:
            bukva = i
    r= -1
    l= -1
    for i in range(len(s)):
        if s[i] ==bukva and l == -1:
            l=i
        elif s[i] == bukva:
            r=i
    lenght = r-l-1
    if 1: # 13
        if lenght%2 == 0:
            for i in range(len(s)):
                if s[i] ==bukva:
                    index = i
                    Ans2+=bukva
                    break
                Ans1+=s[i]
            bufStr = s[l+1:r]
            for i in range(len(bufStr)/2):
                Ans2+=bufStr[i]

            bufStr = bufStr[::-1]
            for i in range(len(bufStr)/2):
                Ans1+=bufStr[i]

            for i in range(13-len(Ans2)):
                Ans2=s[r+i+1]+Ans2
            s=s[::-1]

            for i in range(13-len(Ans1)):
                Ans1=s[i]+Ans1
            print Ans2
            print Ans1
        elif lenght%2 == 1:
            for i in range(len(s)):
                if s[i] == bukva:
                    index = i
                    Ans2 += bukva
                    break
                Ans1+=s[i]
            bufStr = s[l+1:r]

            for i in range(len(bufStr)/2):
                Ans2+=bufStr[i]
            bufStr = bufStr[::-1]
            for i in range(len(bufStr)/2):
                Ans1+=bufStr[i]
            Ans1+=bufStr[len(bufStr)/2]

            for i in range(13-len(Ans2)):
                Ans2=s[r+i+1]+Ans2
            s=s[::-1]
            for i in range(13-len(Ans1)):
                Ans1=s[i]+Ans1
            print Ans2
            print Ans1


from sys import stdin
ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def isValid(ss):
    for i in range(1,len(ss)):
        if ss[i]==ss[i-1]:
            return False
    return True
ss = input()
res=0
if not isValid(ss):
    res=-1
li = ss[:13]
li2=ss[13:]
li_rev=li2[::-1]

ans=''

for x in ch:
    if ss.count(x)>1:
        ans=x
        break
i_li = li.index(ans)
i_rev = li_rev.index(ans)

check = abs(i_li-i_rev)
if check>1: res=-1
if res==-1: print('Impossible')
else:
    print(li+'\n'+li_rev[:i_rev]+li_rev[i_rev+1:])


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

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

a1=Int()
a2=Int()
k1=Int()
k2=Int()
n=Int()

MIN=inf
MAX=-1

if(k1<k2):
    temp=min(a1,n//k1)
    rem_n=n-k1*temp
    temp+=min(a2,rem_n//k2)
    MAX=max(temp,MAX)
else:
    temp=min(a2,n//k2)
    rem_n=n-k2*temp
    temp+=min(a1,rem_n//k1)
    MAX=max(temp,MAX)

n-=a1*(k1-1)
n-=a2*(k2-1)

if(n<0):n=0

MIN=min(n,a1+a2)

print(MIN,MAX)


a1 = int(input())
a2 = int(input())
k1 = int(input())
k2 = int(input())
n = int(input())

min = 0
if a1*(k1-1) + a2*(k2-1) >= n:
    print("test1")
    min=0
else:
    print("test2")
    leftover = n
    leftover -= a1*(k1-1) + a2*(k2-1)
    min += leftover

max=0
if k1<k2:
    leftover = n
    if n/k1 > a1:
        max += a1
        leftover -= a1*k1
        max += int(leftover/k2)
    else:
        max = int(n/k1)
else:
    leftover = n
    if n/k2 > a2:
        max += a2
        leftover -= a2*k2
        max += int(leftover/k1)
    else:
        max = int(n/k2)

print(min)
print(/n)
print(max)


<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="https://fonts.googleapis.com/css?family=Markazi+Text&display=swap" rel="stylesheet">
<link href="styles.css" rel="stylesheet">

			به زودی

				کارما یونی

					خانه

				تماس با ما

					درباره ما

					همکاری با ما

					 راهنمای کارما

				ورود | ثبت نام

				<input value="" type="text" placeholder="عنوان شغلی، مهارت یا...">

					<select class="select_karfarma">
						<option value="" selected="">همه ی شهرستان ها</option>
						<option value="سمنان">
							سمنان
						</option>
						<option value="میامی">
							میامی
						</option>
						<option value="آرادان">
							آرادان
						</option>
						<option value="گرمسار">
							گرمسار
						</option>
						<option value="مهدیشهر">
							مهدیشهر
						</option>
						<option value="بسطام">
							بسطام
						</option>
						<option value="دامغان">
							دامغان
						</option>
						<option value="شاهرود">
							شاهرود
						</option>
						<option value="سرخه">
							سرخه
						</option>
					</select>

					<select class="select_karfarma">
						<option value="" selected="">دسته بندی شغل ها</option>
						<option value="کافه">
							کافه
						</option>
						<option value="فست فود">
							فست فود
						</option>
						<option value="رستوران">
							رستوران
						</option>
					</select>

						جستجو

						فست فود

							قرارداد تمام‌وقت

							حقوق پایه ۱,۰۰۰,۰۰۰ تومان

							سمنان،سمنان

							اطلاعات بیشتر

						فست فود

							قرارداد تمام‌وقت

							حقوق پایه ۱,۰۰۰,۰۰۰ تومان

							سمنان،سمنان

							اطلاعات بیشتر

						کافه

							قرارداد تمام‌وقت

							حقوق پایه ۱,۰۰۰,۰۰۰ تومان

							سمنان،سمنان

							اطلاعات بیشتر

						رستوران

							قرارداد تمام‌وقت

							حقوق پایه ۱,۰۰۰,۰۰۰ تومان

							سمنان،سمنان

							اطلاعات بیشتر

						کافه

							قرارداد تمام‌وقت

							حقوق پایه ۱,۰۰۰,۰۰۰ تومان

							سمنان،سمنان

							اطلاعات بیشتر

						رستوران

							قرارداد تمام‌وقت

							حقوق پایه ۱,۰۰۰,۰۰۰ تومان

							سمنان،سمنان

							اطلاعات بیشتر

						فست فود

							قرارداد تمام‌وقت

							حقوق پایه ۱,۰۰۰,۰۰۰ تومان

							سمنان،سمنان

							اطلاعات بیشتر

						فست فود

							قرارداد تمام‌وقت

							حقوق پایه ۱,۰۰۰,۰۰۰ تومان

							سمنان،سمنان

							اطلاعات بیشتر

						کافه

							قرارداد تمام‌وقت

							حقوق پایه ۱,۰۰۰,۰۰۰ تومان

							سمنان،سمنان

							اطلاعات بیشتر

				رایگان آگهی بگذارید

مهدی شهاب

مهدی شهاب

مهدی شهاب

مهدی شهاب

مهدی شهاب

						مهدی شهاب

						پنج سال سابقه ی کار

					خیلی خوب و تمیز و سریع کار رو انجام دادند و هزینه منصفانه ای هم دریافت کردند. من کاملا راضی هستم و باز هم ازشون تشکر میکنم.

						به جمع ما بپیوندید

						از ماست که برماست

			درباره ما

				درباره کارما بخوانید

				سنجاق، بازار آنلاین خدمات و متخصصین ایران است و میخواهد آنچه را هنوز به شکل سنتی انجام میشود به روز کند. از پدرتان می‌پرسید که آدم این‌کاره چه کسی را میشناسی؟ حالا از سنجاق بپرسید! سنجاق درخواست شما را به دست متخصصین شهرتان می‌رساند تا برآورد بهتری از هزینه کارهای خود داشته باشید و بتوانید آگاهانه‌تر انتخاب کنید. هر متخصصی میتواند خدمتش را با نام خودش و نه نام سنجاق ارائه کند. هنر سنجاق استفاده از تکنولوژی پیشرفته در متصل کردن مشتریان و خدمت دهندگان است.

				شهر های عضو کارما:

				تهران - اسلام شهر - شهریار - شهر قدس - تهران - اسلام شهر - شهریار - شهر قدس

				کارما را در شبکه های اجتماعی دنبال کنید!

			همکاری با ما

				درباره کارما بخوانید

				سنجاق، بازار آنلاین خدمات و متخصصین ایران است و میخواهد آنچه را هنوز به شکل سنتی انجام میشود به روز کند. از پدرتان می‌پرسید که آدم این‌کاره چه کسی را میشناسی؟ حالا از سنجاق بپرسید! سنجاق درخواست شما را به دست متخصصین شهرتان می‌رساند تا برآورد بهتری از هزینه کارهای خود داشته باشید و بتوانید آگاهانه‌تر انتخاب کنید. هر متخصصی میتواند خدمتش را با نام خودش و نه نام سنجاق ارائه کند. هنر سنجاق استفاده از تکنولوژی پیشرفته در متصل کردن مشتریان و خدمت دهندگان است.

				شهر های عضو کارما:

				تهران - اسلام شهر - شهریار - شهر قدس - تهران - اسلام شهر - شهریار - شهر قدس

				کارما را در شبکه های اجتماعی دنبال کنید!

			راهنمای کارما

				درباره کارما بخوانید

				سنجاق، بازار آنلاین خدمات و متخصصین ایران است و میخواهد آنچه را هنوز به شکل سنتی انجام میشود به روز کند. از پدرتان می‌پرسید که آدم این‌کاره چه کسی را میشناسی؟ حالا از سنجاق بپرسید! سنجاق درخواست شما را به دست متخصصین شهرتان می‌رساند تا برآورد بهتری از هزینه کارهای خود داشته باشید و بتوانید آگاهانه‌تر انتخاب کنید. هر متخصصی میتواند خدمتش را با نام خودش و نه نام سنجاق ارائه کند. هنر سنجاق استفاده از تکنولوژی پیشرفته در متصل کردن مشتریان و خدمت دهندگان است.

				شهر های عضو کارما:

				تهران - اسلام شهر - شهریار - شهر قدس - تهران - اسلام شهر - شهریار - شهر قدس

				کارما را در شبکه های اجتماعی دنبال کنید!


#!/usr/bin/env python3

a1 = int(input())
a2 = int(input())
k1 = int(input())
k2 = int(input())
n  = int(input())

minDeletedPlayers = 0
maxDeletedPlayers = 0

# Finding min deleted players
playersStates = []
for i in range(a1):
    playersStates.append(k1)
for i in range(a2):
    playersStates.append(k2)
memN = n
while memN > 0:
    # Finding max number
    maxNumber = -1
    itemId = 0
    for i, item in enumerate(playersStates):
        if item > maxNumber:
            maxNumber = item
            itemId = i
    playersStates[itemId] -= 1
    memN -= 1
for item in playersStates:
    if item <= 0:
        minDeletedPlayers += 1

# Finding max deleted players
playersStates = []
for i in range(a1):
    playersStates.append(k1)
for i in range(a2):
    playersStates.append(k2)
memN = n
while memN > 0:
    # Finding min number
    minNumber = 100500
    itemId = 0
    for i, item in enumerate(playersStates):
        if item < minNumber and item != 0:
            minNumber = item
            itemId = i
    playersStates[itemId] -= 1
    memN -= 1
for item in playersStates:
    if item <= 0:
        maxDeletedPlayers += 1

print(minDeletedPlayers, maxDeletedPlayers)


x, y = map(int, input().split())
f = x*y
if (f % 2 == 0):
	 t =(f / 2)
    print(int(t))
else:
	k = ((f - 1) / 2)
    print(int(k))


import math
m, n = int(i) for i in input().split()
answer1 = math.floor(m / 2) * math.floor(n)
answer2 = math.floor(m) * math.floor(n / 2)
if answer1 > answer2:
    print(answer1)
elif answer2 > answer1:
    print(answer2)
else:
    print(answer1)


m,n=[int(x) for x in inpit()split()]
if m>1 and n>1:
    a=(m//2)*n
    b=(m%2)*(n//2)
    print(a+b)
else:
    if m==1 and n==1:
        print(0)
    else:
        print(1)


def domino(n,m):
    if n<=1 and m<=1:
        return 0
    elif n=1 and m=2:
        return 1
    elif n=2 and m=1:
        return 1
    else:
        return 2+max(domino(n-1,m-2),domino(n-2,m-1))

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