from sys import stdin, exit
from random import randint

def no_solution():
    print 'NO'
    exit(0)

inp = stdin.read().strip().split('\n')

n, K = map(int, inp[0].split(' '))

a = [0] + [0 for i in xrange(n)]
b = [0] + [0 for i in xrange(n)]
c = [0] + [0 for i in xrange(n)]

active = [i + 1 for i in range(n)]

for i in xrange(1, n + 1):
    a[i], b[i], c[i] = map(int, inp[i].split(' '))

answer = []

while K > 0:
    n = len(active)
    if K == 0 or len(active) == 0:
        break
    if n <= K:
        for i in xrange(n):
            answer.append((active[i], -1))
            K -= 1
        active = []
        break

    good = False
    if n <= 1000:
        for ii in xrange(n):
            if good:
                break
            for jj in xrange(ii + 1, n):
                if good:
                    break
                i = active[ii]
                j = active[jj]

                if a[i] * b[j] == a[j] * b[i]:
                    continue

                x_high = c[j] * b[i] - c[i] * b[j]
                y_high = a[j] * c[i] - a[i] * c[j]

                low = a[i] * b[j] - a[j] * b[i]

                answer.append((i, j))
                K -= 1

                n_act = []
                for k in active:
                    if k == i or k == j:
                        continue

                    low_prime = a[k] * b[j] - a[j] * b[k]
                    if low_prime == 0:
                        n_act.append(k)
                        continue

                    x_high_prime = c[j] * b[k] - c[k] * b[j]
                    y_high_prime = a[j] * c[k] - a[k] * c[j]

                    if x_high * low_prime != x_high_prime * low or \
                            y_high * low_prime != y_high_prime * low:
                                n_act.append(k)

                                ll = a[k] * b[i] - a[i] * b[k]
                                xh = c[i] * b[k] - c[k] * b[i]
                                yh = a[i] * c[k] - a[k] * c[i]

                                assert(x_high * ll != xh * low or\
                                        y_high * ll != yh * low)

                active = n_act
                good = True
        if not good:
            break
        continue

    for it in range(1000000 * K + n):
        idx1 = randint(0, n - 1)
        idx2 = randint(0, n - 1)
        if idx1 == idx2:
            continue

        i = active[idx1]
        j = active[idx2]

        if a[i] * b[j] == a[j] * b[i]:
            continue

        x_high = c[j] * b[i] - c[i] * b[j]
        y_high = a[j] * c[i] - a[i] * c[j]

        low = a[i] * b[j] - a[j] * b[i]

        answer.append((i, j))
        K -= 1

        n_act = []
        for k in active:
            if k == i or k == j:
                continue

            low_prime = a[k] * b[j] - a[j] * b[k]
            if low_prime == 0:
                n_act.append(k)
                continue

            x_high_prime = c[j] * b[k] - c[k] * b[j]
            y_high_prime = a[j] * c[k] - a[k] * c[j]

            if x_high * low_prime != x_high_prime * low or \
                    y_high * low_prime != y_high_prime * low:
                        n_act.append(k)

                        ll = a[k] * b[i] - a[i] * b[k]
                        xh = c[i] * b[k] - c[k] * b[i]
                        yh = a[i] * c[k] - a[k] * c[i]

                        assert(x_high * ll != xh * low or\
                                y_high * ll != yh * low)

        active = n_act
        good = True
        break

    if not good:
        no_solution()

if len(active) == 0 and K >= 0:
    print 'YES'
    print len(answer)
    for i in xrange(len(answer)):
        print '%d %d' % answer[i]
        assert(answer[i][0] != answer[i][1])
else:
    no_solution()


from sys import stdin, exit
from random import randint

def no_solution():
    print 'NO'
    exit(0)

inp = stdin.read().strip().split('\n')

n, K = map(int, inp[0].split(' '))

a = [0] + [0 for i in xrange(n)]
b = [0] + [0 for i in xrange(n)]
c = [0] + [0 for i in xrange(n)]

active = [i + 1 for i in range(n)]

for i in xrange(1, n + 1):
    a[i], b[i], c[i] = map(int, inp[i].split(' '))

answer = []

while K > 0:
    n = len(active)
    if K == 0 or len(active) == 0:
        break
    if n <= K:
        for i in xrange(n):
            answer.append((active[i], -1))
            K -= 1
        active = []
        break

    good = False
    best = (-1, -1)
    bsz = 10 ** 6
    for it in xrange(30):
        idx1 = randint(0, n - 1)
        idx2 = randint(0, n - 1)
        if idx1 == idx2:
            continue

        i = active[idx1]
        j = active[idx2]

        if a[i] * b[j] == a[j] * b[i]:
            continue

        x_high = c[j] * b[i] - c[i] * b[j]
        y_high = a[j] * c[i] - a[i] * c[j]

        low = a[i] * b[j] - a[j] * b[i]

        #answer.append((i, j))
        #K -= 1

        hh = 0
        for k in active:
            if k == i or k == j:
                continue

            low_prime = a[k] * b[j] - a[j] * b[k]
            if low_prime == 0:
                n_act.append(k)
                continue

            x_high_prime = c[j] * b[k] - c[k] * b[j]
            y_high_prime = a[j] * c[k] - a[k] * c[j]

            if x_high * low_prime != x_high_prime * low or \
                    y_high * low_prime != y_high_prime * low:
                        hh += 1

        #active = n_act
        good = True
        if hh < bsz:
            bsz = hh
            best = (i, j)

    if not good:
        no_solution()

    i, j = best
    if i == -1:
        continue

    if a[i] * b[j] == a[j] * b[i]:
        continue

    x_high = c[j] * b[i] - c[i] * b[j]
    y_high = a[j] * c[i] - a[i] * c[j]

    low = a[i] * b[j] - a[j] * b[i]

    answer.append((i, j))
    K -= 1

    n_act = []
    for k in active:
        if k == i or k == j:
            continue

        low_prime = a[k] * b[j] - a[j] * b[k]
        if low_prime == 0:
            n_act.append(k)
            continue

        x_high_prime = c[j] * b[k] - c[k] * b[j]
        y_high_prime = a[j] * c[k] - a[k] * c[j]

        if x_high * low_prime != x_high_prime * low or \
                y_high * low_prime != y_high_prime * low:
                    n_act.append(k)
    active = n_act

if len(active) == 0 and K >= 0:
    print 'YES'
    print len(answer)
    for i in xrange(len(answer)):
        print '%d %d' % answer[i]
        assert(answer[i][0] != answer[i][1])
else:
    no_solution()


from sys import stdin, exit
from random import randint

def no_solution():
    print 'NO'
    exit(0)

inp = stdin.read().strip().split('\n')

n, K = map(int, inp[0].split(' '))

a = [0] + [0 for i in xrange(n)]
b = [0] + [0 for i in xrange(n)]
c = [0] + [0 for i in xrange(n)]

active = [i + 1 for i in range(n)]

for i in xrange(1, n + 1):
    a[i], b[i], c[i] = map(int, inp[i].split(' '))

answer = []

while K > 0:
    n = len(active)
    if K == 0 or len(active) == 0:
        break
    if n <= K:
        for i in xrange(n):
            answer.append((active[i], -1))
            K -= 1
        active = []
        break

    good = False
    best = (-1, -1)
    bsz = 10 ** 6
    for it in xrange(30):
        idx1 = randint(0, n - 1)
        idx2 = randint(0, n - 1)
        if idx1 == idx2:
            continue

        i = active[idx1]
        j = active[idx2]

        if a[i] * b[j] == a[j] * b[i]:
            continue

        x_high = c[j] * b[i] - c[i] * b[j]
        y_high = a[j] * c[i] - a[i] * c[j]

        low = a[i] * b[j] - a[j] * b[i]

        #answer.append((i, j))
        #K -= 1

        hh = 0
        for k in active:
            if k == i or k == j:
                continue

            low_prime = a[k] * b[j] - a[j] * b[k]
            if low_prime == 0:
                n_act.append(k)
                continue

            x_high_prime = c[j] * b[k] - c[k] * b[j]
            y_high_prime = a[j] * c[k] - a[k] * c[j]

            if x_high * low_prime != x_high_prime * low or \
                    y_high * low_prime != y_high_prime * low:
                        hh += 1

        #active = n_act
        good = True
        if hh < bsz:
            bsz = hh
            best = (i, j)

    if not good:
        no_solution()

    i, j = best

    if a[i] * b[j] == a[j] * b[i]:
        continue

    x_high = c[j] * b[i] - c[i] * b[j]
    y_high = a[j] * c[i] - a[i] * c[j]

    low = a[i] * b[j] - a[j] * b[i]

    answer.append((i, j))
    K -= 1

    n_act = []
    for k in active:
        if k == i or k == j:
            continue

        low_prime = a[k] * b[j] - a[j] * b[k]
        if low_prime == 0:
            n_act.append(k)
            continue

        x_high_prime = c[j] * b[k] - c[k] * b[j]
        y_high_prime = a[j] * c[k] - a[k] * c[j]

        if x_high * low_prime != x_high_prime * low or \
                y_high * low_prime != y_high_prime * low:
                    n_act.append(k)
    active = n_act

if len(active) == 0 and K >= 0:
    print 'YES'
    print len(answer)
    for i in xrange(len(answer)):
        print '%d %d' % answer[i]
        assert(answer[i][0] != answer[i][1])
else:
    no_solution()


def nextc(m):
    m2 = {}
    for n, c in m.iteritems():
        h = n-1 >> 1
        m2[h] = m2.get(h, 0) + c
        m2[n-1 - h] = m2.get(n-1 - h, 0) + c
    return m2

def countseg(l, s, cache={}):
    if s > l: return 0
    if s == l: return 1
    if (l, s) in cache:
        return cache[l, s]
    h = l-1 >> 1
    out = countseg(h, s) + countseg(l-1 - h, s)
    cache[l, s] = out
    return out

def findx(l, q, ss):
    if l <= max(ss):
        return (l-1 >> 1) + q
    h = l-1 >> 1
    ns = sum(countseg(h, s) for s in ss)
    if q >= ns:
        return h + 1 + findx(l-1 - h, q - ns, ss)
    else:
        return findx(h, q, ss)

def f(l, r):
    m = {l: 1, l-1: 0}
    q = 1
    while r >= q and min(m) > 2:
        r -= q
        q <<= 1
        m = nextc(m)
    mn, mx = min(m), max(m)
    if mx & 1:
        if r >= m[mx]:
            if mx == 3:
                return findx(l, r - m[mx], [1,2])
            return findx(l, r - m[mx], [mn])
        else:
            return findx(l, r, [mx])
    else:
        return findx(l, r, [mn, mx])

def ans(n, k):
    if k == 1: return 1
    if k == 2: return n
    return 2 + f(n - 2, k - 3)

def brute_ans(n, k):
    if k == 1: return 1
    if k == 2: return n
    return 2 + brute_f(n - 2, k - 2)

def brute_f(l, r):
    s = [(0, l)]
    for _ in xrange(r):
        i = max(xrange(len(s)), key=lambda j: s[j][1]-1 >> 1)
        x, d = s[i]
        h = d-1 >> 1
        s = s[:i] + [(x, h), (x+h+1, d-1-h)] + s[i+1:]
    return x+h

def test_n(n):
    for i in xrange(1, n + 1):
        assert brute_ans(n, i) == ans(n, i)

if __name__ == '__main__':
    n, k = map(int, raw_input().split())
    print ans(n, k)


f = {}
def c(n, p):
	k = (n, p)
	if k in f: return f[k]

	d = (n-1)/2
	f[k] = d >= p and (1 + c(d, p) + c(n-d-1, p))

	return f[k]

def w(l, r, k):
	m = (l+r)/2

	if k == 0: return m

	x = c(m-l, p)
	y = c(r-m, p+1)

	return w(l, m-1, k-y-1) if x+y>=k else w(m+1, r, k-x-1)

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

if k == 1: print 1
elif k == 2: print n
else:
	p, q = 0, n
	while p < q:
		m = (p+q+1) / 2
		if c(n-2, m) >= k-2: p = m
		else: q = m-1
	print w(2, n-1, k-3)


dp = {}
def count(n, low):
	if low == 1: return n
	k = (n, low)
	if k in dp: return dp[k]
	if n < low: return 0
	l1 = (n-1)/2
	if l1 < low: return 0
	l2 = n - 1 - l1
	dp[k] = 1 + count(l1, low) + count(l2, low)
	return dp[k]

def getPos(l, r, low, want):
	m = (l+r)/2

	want -= 1
	if want == 0: return m

	c1 = count(m-l, low)
	c2 = count(r-m, low+1)

	if c1+c2 >= want:
		return getPos(l, m-1, low, want-c2)
	else:
		return getPos(m+1, r, low, want-c1)

n,k = map(int, raw_input().split())
if k == 1: print 1
elif k == 2: print n
else:
	lo, hi = 1, n+1
	while lo < hi:
		mid = (lo + hi + 1) / 2
		if count(n, mid) >= k-2:
			lo = mid
		else:
			hi = mid-1
	print getPos(2,n-1,lo,k-2)


dp = {}
def count(n, low):
	if low == 1: return n
	k = (n, low)
	if k in dp: return dp[k]
	if n < low: return 0
	l1 = (n-1)/2
	if l1 < low: return 0
	l2 = n - 1 - l1
	dp[k] = 1 + count(l1, low) + count(l2, low)
	return dp[k]

def getPos(l, r, low, want):
	m = (l+r)/2

	want -= 1
	if want == 0: return m

	c1 = count(m-l, low)
	c2 = count(r-m, low+2)

	if c1+c2 >= want:
		return getPos(l, m-1, low, want-c2)
	else:
		return getPos(m+1, r, low, want-c1)

n,k = map(int, raw_input().split())
if k == 1: print 1
elif k == 2: print n
else:
	lo, hi = 1, n+1
	while lo < hi:
		mid = (lo + hi + 1) / 2
		if count(n, mid) >= k-2:
			lo = mid
		else:
			hi = mid-1
	print getPos(2,n-1,lo,k-2)


f = {}
def c(n, p):
	k = (n, p)
	if k in f: return f[k]

	d = (n-1)/2
	f[k] = d >= p and (1 + c(d, p) + c(n-d-1, p))

	return f[k]

def w(l, r, k):
	print l,r,k
	m = (l+r)/2

	if k == 0: return m

	x = c(m-l, p)
	y = c(r-m, p+1)

	return w(l, m-1, k-y-1) if x+y>=k else w(m+1, r, k-x-1)

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

if k == 1: print 1
elif k == 2: print n
else:
	p, q = 0, n
	while p < q:
		m = (p+q+1) / 2
		if c(n-2, m) >= k-2: p = m
		else: q = m-1
	print w(2, n-1, k-3)


MOD,fact=10**9+7,[1]*(2*10**6+5)
for i in range(1, len(fact)): fact[i]=(fact[i-1]*i)%(MOD)
def C(n,k):
    return (fact[n]*pow(fact[k],MOD-2,MOD)**2)%MOD
n=input()+1
print C(2*n,n)-1


# https://codeforces.com/problemset/problem/575/H

import sys
import math

mod = pow(10, 9) + 7

def main():
    # sys.stdin = open('E:\\Sublime\\in.txt', 'r')
    # sys.stdout = open('E:\\Sublime\\out.txt', 'w')
    # sys.stderr = open('E:\\Sublime\\err.txt', 'w')

    n = int(sys.stdin.readline().strip())
    # a, b = map(int, sys.stdin.readline().strip().split()[:2])

    # C(n+1, 2n + 2) = (2n+2)! : (n+1)! : n+1!
    # = (n+2)(n+3)...(2n+2) /

    t = 1
    m = 1
    for i in range(1, n + 2):
        t *= (n + i + 1) % mod
        m *= i % mod
    print((t // m - 1) % mod)

if __name__ == '__main__':
    main()

# hajj
#  　　　　　　 ＿＿
# 　　　　　／＞　　フ
# 　　　　　| 　_　 _ l
# 　 　　　／` ミ＿xノ
# 　　 　 /　　　 　 |
# 　　　 /　 ヽ　　 ﾉ
# 　 　 │　　|　|　|
# 　／￣|　　 |　|　|
# 　| (￣ヽ＿_ヽ_)__)
# 　＼二つ


MOD = 10**9+7

fact = [1]*2000004
for i in range(1,2000004):
    fact[i] = (fact[i-1]*i)%MOD
inv = [1]*2000004
for i in range(2,2000004):
    inv[i] = (-(MOD//i)*inv[MOD%i])%MOD
for i in range(2,2000004):
    inv[i] = (inv[i]*inv[i-1])%MOD
def C(n,k):
    return (fact[n]*inv[k]*inv[n-k])%MOD
x=int(input())+1
res = C(x*2,x)-1
print(res)


n = int(raw_input())+1
aa=1
for i in xrange(1, 2*n):
	aa *= i
bb=1
for i in xrange(1, n+1):
	bb *= i
cc = 1
for i in xrange(1, n):
	cc *= i
print (2 * aa / (bb * cc) - 1) % (10 ** 9 + 7)


MOD = 10**9+7

fact = [1]*200003
for i in range(1,200003):
    fact[i] = (fact[i-1]*i)%MOD
inv = [1]*200003
for i in range(2,200003):
    inv[i] = (-(MOD//i)*inv[MOD%i])%MOD
for i in range(2,200003):
    inv[i] = (inv[i]*inv[i-1])%MOD
def C(n,k):
    return (fact[n]*inv[k]*inv[n-k])%MOD
x=int(input())+1
res = C(x*2,x)-1
print(res)


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

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

MOD = 10**9 + 7
INF = float("+inf")

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

if k == 1:
    print (pow(10, n, m) - 1) % m
    quit()

def pow9_10(x):
    res = 1
    if x > 0:
        res *= 9
    if x > 1:
        res *= pow(10, x - 1, m)
    return res % m

res = 0
counts = [0] * k
counts[0] = 1

p10i = 1
for i in xrange(n):
    counts2 = [0] * k
    for r in xrange(k):
        mind = 1 if i == n else 0
        for d in xrange(mind, 10):
            r2 = (d * p10i + r) % k
            counts2[r2] += counts[r]

    add = (counts2[0] - 1) * pow9_10(n - i - 1)
    res += add

    counts2[0] = 1
    counts = counts2

    p10i = (p10i * 10) % k
print res % m


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

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

MOD = 10**9 + 7
INF = float("+inf")

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

if k == 1:
    print (pow(10, n, m) - 1) % m
    quit()

def pow9_10(x):
    res = 1
    if x > 0:
        res *= 9
    if x > 1:
        res *= pow(10, x - 1, m)
    return res % m

def count_div_upto_pow10(e, kk):
    q, r = divmod(pow(10, e), kk)
    if r == 0:
        q -= 1
    return q

def count_div_interval(e1, e2, kk):
    return count_div_upto_pow10(e2, kk) - count_div_upto_pow10(e1, kk)

def cut_pow10(e):
    return pow(10, e) if e > 0 else 1

res = 0
counts = {r: 0 for r in xrange(k)}
counts[0] = 1

for i in xrange(n):
    #print i, ":",
    p10 = pow(10, i)

    counts2 = {r: 0 for r in xrange(k)}
    for r in xrange(k):
        mind = 1 if i == n else 0
        for d in xrange(mind, 10):
            r2 = (d * pow(10, i, k) + r) % k
            counts2[r2] += counts[r]
    #print counts2
    add = (counts2[0] - 1) * pow9_10(n - i - 1)
    res += add
    #print "ADD", counts2[0], "*", pow9_10(n - i - 1), "=", add
    counts2[0] = 1
    counts = counts2
print res % m


def get_input():
    hahaha=input()
    (n,k,m)=hahaha.split(sep=None, maxsplit=1000)
    return (int(n),int(k),int(m))
(n,k,m)=get_input()
f=[0 for i in range(k)]

s=0

for v in range(n):
    tens = 10**v
    f=[  (sum(   [f[(j+k-(x+1)*tens%k)%k] for x in range(9)] )+f[j])%m       for j in range(k)]
    for x in range(9):
        f[(x+1)*tens%k]+=1
    if n-v-1==0:
        s+=(f[0]%m)
    else:
        s+=f[0]*((10**(n-v-2)*9))%m
    f[0]=0

print(s%m)


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

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

MOD = 10**9 + 7
INF = float("+inf")

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

if k == 1:
    print (pow(10, n, m) - pow(10, n - 1, m)) % m
    quit()

# def pow9_10(x):
#     res = 1
#     if x > 0:
#         res *= 9
#     if x > 1:
#         res *= pow(10, x - 1, m)
#     return res % m

pow9_10 = []
p = 1
for i in range(n):
    pow9_10.append(p)
    if i == 0:
        p = (p * 9) % m
    else:
        p = (p * 10) % m

res = 0
counts = [0] * k
counts[0] = 1

p10i = 1
for i in xrange(n):
    counts2 = [0] * k
    for r in xrange(k):
        mind = 1 if i == n else 0
        for d in xrange(mind, 10):
            r2 = (d * p10i + r) % k
            counts2[r2] += counts[r]

    add = (counts2[0] - 1) * pow9_10[n - i - 1]
    res += add

    counts2[0] = 1
    counts = counts2

    p10i = (p10i * 10) % k
print res % m


global debug
debug = 0

line = map(int, raw_input().split())
n = line[0]
k = line[1]
m = line[2]

r = [[0 for _ in xrange(k)] for _ in xrange(n)]
t = [[0 for _ in xrange(k)] for _ in xrange(n)]

for i in xrange(10):
    r[0][i % k] += 1

base = 1
for i in xrange(1, n):
    base *= 10
    if (i == n - 1): start = 1
    else: start = 0
    for c in xrange(start, 10):
        offset = (c * base) % k
        for j in xrange(k):
            #for pre in xrange(i):
            r[i][j] += r[i - 1][(j - offset) % k]
            r[i][j] %= m
if (debug >= 2): print r

t[0][0] = (r[0][0] - 1) % m
base = 1
for i in xrange(1, n):
    base *= 10
    t[i][0] = r[i][0]
    if (i == n - 1):
        start = 1
    else:
        start = 0
        t[i][0] -= 1
    for c in xrange(start, 10):
        offset = (c * base) % k
        for j in xrange(k):
            idx = (offset + j) % k
            if (idx != 0):
                t[i][idx] += t[i - 1][j]
                t[i][idx] %= m
if (debug >= 2): print t
print sum(t[n - 1]) % m


rr=raw_input
rrI = lambda: int(rr())
rrM = lambda: map(int,rr().split())
debug=0
if debug:
    fi = open('t.txt','r')
    rr=lambda: fi.readline().replace('\n','')

def good_mask(x):
    if x == 0: return False
    return (x+1) & x == 0

N = rrI()
S = rr()
MOD = 10**9 + 7
UPPER = 25

memo = {}
def dp(i, mask):
    #Having made a cut already before position i,
    #and having a set of mask taken
    #how many ways?
    if i == N:
        return 1 if good_mask(mask) else 0
    if (i,mask) in memo:
        return memo[i,mask]
    ans = 1 if good_mask(mask) else 0
    for j in xrange(i+1, min(N+1, i+6)):
        num = int(S[i:j], 2)
        if num == 0: continue
        if num >= UPPER: break
        ans += dp(j, mask | (1<<(num-1)))
        if ans >= MOD:
            ans %= MOD
    memo[i, mask] = ans
    return ans

fans = 0
for i in xrange(N):
    fans += dp(i, 0)
    if fans >= MOD:
        fans %= MOD
print fans


rr=raw_input
rrI = lambda: int(rr())
rrM = lambda: map(int,rr().split())
debug=0
if debug:
    fi = open('t.txt','r')
    rr=lambda: fi.readline().replace('\n','')

def good_mask(x):
    if x == 0: return False
    return (x+1) & x == 0

N = rrI()
S = rr()
MOD = 10**9 + 7
UPPER = 21

memo = {}
def dp(i, mask):
    #Having made a cut already before position i,
    #and having a set of mask taken
    #how many ways?
    if i == N:
        return 1 if good_mask(mask) else 0
    if (i,mask) in memo:
        return memo[i,mask]
    ans = 1 if good_mask(mask) else 0
    for j in xrange(i+1, min(N+1, i+6)):
        num = int(S[i:j], 2)
        if num == 0: continue
        if num >= UPPER: break
        ans += dp(j, mask | (1<<(num-1)))
        if ans >= MOD:
            ans %= MOD
    memo[i, mask] = ans
    return ans

fans = 0
for i in xrange(N):
    fans += dp(i, 0)
    if fans >= MOD:
        fans %= MOD
print fans


rr=raw_input
rrI = lambda: int(rr())
rrM = lambda: map(int,rr().split())
debug=0
if debug:
    fi = open('t.txt','r')
    rr=lambda: fi.readline().replace('\n','')

def good_mask(x):
    if x == 0: return False
    return (x+1) & x == 0

N = rrI()
S = rr()
#N = 75
#from time import time
#S  = '100000111111101000100001011100010111110011111011100011001111101111100011110'
#tt = time()
#print tt

MOD = 10**9 + 7
UPPER = 22

number = [ [0]*(N+1) for _ in xrange(N) ]
for i in xrange(N):
    for j in xrange(i+1, N+1):
        number[i][j] = int(S[i:j],2)

memo = [ [None]*(1<<UPPER) for _ in xrange(N+1)]
def dp(i, mask):
    #Having made a cut already before position i,
    #and having a set of mask taken
    #how many ways?
    if i == N:
        return 1 if good_mask(mask) else 0
    fetch = memo[i][mask]
    if fetch is not None:
        return fetch
    ans = 1 if good_mask(mask) else 0
    for j in xrange(i+1, N+1):
        num = number[i][j]
        if num == 0: continue
        if num >= UPPER: break
        ans += dp(j, mask | (1<<(num-1)))
        if ans >= MOD:
            ans %= MOD
    memo[i][mask] = ans
    return ans

fans = i = 0
while i < N:
    fans += dp(i, 0)
    fans %= MOD
    i += 1
print fans
#print time()-tt

"""
def good_mask(x):
    if x == 0: return False
    return (x+1) & x == 0

N = rrI()
S = rr()
##print '.'
#N = 75
#import random
#S = "".join(str(random.randint(0,1)) for _ in xrange(N))
MOD = 10**9 + 7
UPPER = 22

memoslide = {N : 0, N-1:0}
def slide(j):
    if j in memoslide:
        return memoslide[j]
    if S[j] == '1':
        memoslide[j] = 0
        return 0
    else:
        k = j
        while k < len(S) and S[k] == '0':
            k += 1
        memoslide[j] = k - j
        return k - j

memo = {}
def dp(i, mask):
    #Having made a cut already before position i,
    #and having a set of mask taken
    #how many ways?
    if i == N:
        return 1 if good_mask(mask) else 0
    if (i,mask) in memo:
        return memo[i,mask]
    ans = 1 if good_mask(mask) else 0
    for j in xrange(i+1, N+1):
        num = int(S[i:j], 2)
        if num == 0: continue
        if num >= UPPER: break
        if num > 8:
            #prune
            newmask = mask
            ii = excess = 0
            while newmask:
                if newmask%2 == 0:
                    excess += len(bin(ii)) - 2
                ii += 1
                newmask /= 2
            if excess > N-j+1:
                break
        k = slide(j)
        newmask = mask | (1<<(num-1))
        bns = dp(j + k, newmask)
        for kk in xrange(k):
            memo[(j + kk, newmask)] = bns
        ans += (1+k) * bns

        if ans >= MOD:
            ans %= MOD
    memo[i, mask] = ans
    return ans

fans = 0
for i in xrange(N):
    fans += dp(i, 0)
    if fans >= MOD:
        fans %= MOD
print fans
"""


rr=raw_input
rrI = lambda: int(rr())
rrM = lambda: map(int,rr().split())
debug=0
if debug:
    fi = open('t.txt','r')
    rr=lambda: fi.readline().replace('\n','')

def good_mask(x):
    if x == 0: return False
    return (x+1) & x == 0

N = rrI()
S = rr()
MOD = 10**9 + 7
UPPER = 22

memo = {}
def dp(i, mask):
    #Having made a cut already before position i,
    #and having a set of mask taken
    #how many ways?
    if i == N:
        return 1 if good_mask(mask) else 0
    if (i,mask) in memo:
        return memo[i,mask]
    ans = 1 if good_mask(mask) else 0
    for j in xrange(i+1, N+1):
        num = int(S[i:j], 2)
        if num == 0: continue
        if num >= UPPER: break
        ans += dp(j, mask | (1<<(num-1)))
        if ans >= MOD:
            ans %= MOD
    memo[i, mask] = ans
    return ans

fans = 0
for i in xrange(N):
    fans += dp(i, 0)
    if fans >= MOD:
        fans %= MOD
print fans


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

import sys, math, random, operator
from string import ascii_lowercase, ascii_uppercase
from fractions import Fraction, gcd
#from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
from Queue import Queue, PriorityQueue
from collections import deque, defaultdict, Counter
#getcontext().prec = 100

MOD = 10**9 + 7
INF = float("+inf")

if sys.subversion[0] == "PyPy":
    import io, atexit
    sys.stdout = io.BytesIO()
    atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
    sys.stdin = io.BytesIO(sys.stdin.read())
    raw_input = lambda: sys.stdin.readline().rstrip()
pr = lambda *args: sys.stdout.write(" ".join(str(x) for x in args) + "\n")
epr = lambda *args: sys.stderr.write(" ".join(str(x) for x in args) + "\n")
die = lambda *args: pr(*args) ^ exit(0)

read_str = raw_input
read_strs = lambda: raw_input().split()
read_int = lambda: int(raw_input())
read_ints = lambda: map(int, raw_input().split())
read_float = lambda: float(raw_input())
read_floats = lambda: map(float, raw_input().split())

"---------------------------------------------------------------"

n = read_int()
s = read_str()

num = []
for i in xrange(len(s)):
    num.append([None])
    for j in xrange(i + 1, len(s)+1):
        num[i].append( int(s[i:j], 2) )

needed_for_m = [None]
cur = 0
for x in xrange(1, 100):
    cur += len(str(bin(x)[2:]))
    needed_for_m.append(cur)

bins = [bin(x)[2:] for x in xrange(0, 100)]

cache = {}
def solve(state, used, maxm, pos):
    key = state, pos
    if key not in cache:
        res = 0

        # already good?
        # print "(%s)" % bin(state)[2:-1], maxm
        if state == (1 << (maxm + 1)) - 1:
            # print "good"
            res += 1

        # continue cuts
        for add in xrange(1, 100):
            if pos + add > len(s):
                break
            val = num[pos][add]
            if val == 0:
                continue

            used2 = used
            if state & (1 << val) == 0:
                used2 += len(bins[val])
            maxm2 = max(maxm, val)
            pos2 = pos + add
            # print "pos", pos, "+", add
            if needed_for_m[maxm2] - used2 <= len(s) - pos2:
                res += solve(state | (1 << val), used2, maxm2, pos2)
        cache[key] = res
    return cache[key]

ans = 0
for i in xrange(len(s)):
    cur = solve(1, 0, 1, i)
    ans += cur
    epr(i, cur, ans)
print ans


import sys

def Min(x, y):
    if x > y:
        return y
    else:
        return x

n = int(input())
a = [int(i) for i in input().split()]
d = [int(0) for i in range(0, n)]

ok = 0

cur = 0

for i in range(0, 7 * n):
    if a[i % n] == 0 :
        print(i % n + 1)
        ok = 1
        break
    if cur != 6:
        a[i % n] -= 1
        d[i % n] += 1
    cur = (cur + 1) % 7

if ok == 0:
    k = -1

    for i in range(0, n):
        if a[i] % d[i] > 0:
            k = Min(k, a[i] // d[i])
        else:
            k = Min(k, a[i] // d[i] - 1)

    for i in range(0, n):
        a[i] -= k * d[i]

    iter = 0
    cur = 0

    while True:
        if a[iter] == 0:
            print(iter)
            break
        else:
            if cur != 6:
                a[iter] -= 1
            cur = (cur + 1) % 7
            iter = (iter + 1) % n


import sys

def Min(x, y):
    if x > y:
        return y
    else:
        return x

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

def Lcm(x, y):
    return x * y // Gcd(x, y)

n = int(input())
a = [int(i) for i in input().split()]
d = [int(0) for i in range(0, n)]

ok = 0

cur = 0

len = Lcm(7, n)

for i in range(0, 7 * n):
    if a[i % n] == 0 :
        print(i % n + 1)
        ok = 1
        break
    if cur != 6:
        a[i % n] -= 1
        d[i % n] += 1
    cur = (cur + 1) % 7

if ok == 0:
    k = -1

    for i in range(0, n):
        a[i] += d[i]
        if d[i] == 0: continue
        if a[i] % d[i] > 0:
            k = Min(k, a[i] // d[i])
        else:
            k = Min(k, a[i] // d[i] - 1)

    for i in range(0, n):
        a[i] -= k * d[i]

    iter = 0
    cur = 0

    while True:
        if a[iter] == 0:
            print(iter)
            break
        else:
            if cur != 6:
                a[iter] -= 1
            cur = (cur + 1) % 7
            iter = (iter + 1) % n


import sys

def Min(x, y):
    if x > y:
        return y
    else:
        return x

n = int(input())
a = [int(i) for i in input().split()]
d = [int(0) for i in range(0, n)]

ok = 0

cur = 0

for i in range(0, 7 * n):
    if a[i % n] == 0 :
        print(i % n + 1)
        ok = 1
        break
    if cur != 6:
        a[i % n] -= 1
        d[i % n] += 1
    cur = (cur + 1) % 7

if ok == 0:
    k = -1

    for i in range(0, n):
        if d[i] == 0: continue
        if a[i] % d[i] > 0:
            k = Min(k, a[i] // d[i])
        else:
            k = Min(k, a[i] // d[i] - 1)

    for i in range(0, n):
        a[i] -= k * d[i]

    iter = 0
    cur = 0

    while True:
        if a[iter] == 0:
            print(iter)
            break
        else:
            if cur != 6:
                a[iter] -= 1
            cur = (cur + 1) % 7
            iter = (iter + 1) % n


import sys

def Min(x, y):
    if x > y:
        return y
    else:
        return x

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

def Lcm(x, y):
    return x * y // Gcd(x, y)

n = int(input())
a = [int(i) for i in input().split()]
d = [int(0) for i in range(0, n)]

ok = 0

cur = 0

len = Lcm(7, n)

for i in range(0, 7 * n):
    if a[i % n] == 0 :
        print(i % n + 1)
        ok = 1
        break
    if cur != 6:
        a[i % n] -= 1
        d[i % n] += 1
    cur = (cur + 1) % 7

if ok == 0:
    k = 10**20

    for i in range(0, n):
        a[i] += d[i]
        if d[i] == 0: continue
        if a[i] % d[i] > 0:
            k = Min(k, a[i] // d[i])
        else:
            k = Min(k, a[i] // d[i] - 1)

    if k == 10**20:
        k = 0

    for i in range(0, n):
        a[i] -= k * d[i]

    iter = 0
    cur = 0

    while True:
        if a[iter] == 0:
            print(iter % n + 1)
            break
        else:
            if cur != 6:
                a[iter] -= 1
            cur = (cur + 1) % 7
            iter = (iter + 1) % n


import math

n    = int(input())

if n == 1:
    print()
else:
    edge = [list(map(int, input().split())) for _ in range(n-1) ]
    g    = {}

    for x, y in edge:
        if x not in g:
            g[x] = []
        if y not in g:
            g[y] = []

        g[x].append(y)
        g[y].append(x)

    def find_center(g):
        d    = {}
        d[1] = 0
        Q    = [(1, 0)]

        while len(Q) > 0:
            u, dis = Q.pop(0)

            for v in g[u]:
                if v not in d:
                    d[v] = dis +1
                    Q.append((v, d[v]))

        max_length = -1
        s = None

        for u, dis in d.items():
            if dis > max_length:
                max_length = dis
                s = u

        d   = {}
        pre = {}
        d[s] = 0
        Q = [(s, 0)]

        while len(Q) > 0:
            u, dis = Q.pop(0)

            for v in g[u]:
                if v not in d:
                    pre[v] = u
                    d[v]   = dis +1
                    Q.append((v, d[v]))

        max_length = -1
        e = None

        for u, dis in d.items():
            if dis > max_length:
                max_length = dis
                e = u

        route = [e]
        while pre[route[-1]] != s:
            route.append(pre[route[-1]])

        return route[len(route) // 2]

    root = find_center(g)
    p    = {}
    size = {}
    Q    = [root]
    p[root] = -1

    i = 0
    while i < len(Q):
        u = Q[i]

        for v in g[u]:
            if p[u] == v: continue
            p[v] = u
            Q.append(v)
        i+=1

    for u in Q[::-1]:
        size[u] = 1

        for v in g[u]:
            if p[u] == v:
                continue
            size[u] += size[v]

    gr    = [(u, size[u]) for u in g[root]]
    gr    = sorted(gr, key=lambda x:x[1])
    thres = math.ceil((n-1) / 3)
    sum_  = 0

    gr1 = []
    gr2 = []
    i = 0

    while sum_ < thres:
        gr1.append(gr[i][0])
        sum_ += gr[i][1]
        i+=1

    while i < len(gr):
        gr2.append(gr[i][0])
        i+=1

    def asign(u, W, ew):
        if size[u] == 1:
            return

        cur = 0
        for v in g[u]:
            if v == p[u]: continue

            first = W[cur]
            ew.append((u, v, first))

            W_  = [x - first for x in W[cur+1: cur+size[v]]]
            asign(v, W_, ew)

            cur+=size[v]

    a, b = 0, 0
    for x in gr1:
        a += size[x]

    for x in gr2:
        b += size[x]

    arr_1 = [x for x in range(1, a+1)]
    arr_2 = [i*(a+1) for i in range(1, b+1)]
    ew    = []

    cur = 0
    for u in gr1:
        first = arr_1[cur]
        ew.append((root, u, first))
        W_    = [x - first for x in arr_1[cur+1:cur+size[u]]]

        cur += size[u]
        #print(u, W_)
        asign(u, W_, ew)

    cur = 0
    for u in gr2:
        first = arr_2[cur]
        ew.append((root, u, first))
        W_    = [x - first for x in arr_2[cur+1:cur+size[u]]]

        cur += size[u]
        #print(u, W_)
        asign(u, W_, ew)

    for u, v, w in ew:
        print('{} {} {}'.format(u, v, w))


import math

n    = int(input())

if n == 1:
    print()
else:
    edge = [list(map(int, input().split())) for i in range(1, n) ]
    g    = {}

    for x, y in edge:
        if x not in g:
            g[x] = []
        if y not in g:
            g[y] = []

        g[x].append(y)
        g[y].append(x)

    def find_centroid(g):
        p    = {}
        size = {}

        p[1] = -1
        Q    = [1]

        i = 0
        while i < len(Q):
            u = Q[i]

            for v in g[u]:
                if p[u] == v: continue
                p[v] = u
                Q.append(v)
            i+=1

        for u in Q[::-1]:
            size[u] = 1

            for v in g[u]:
                if p[u] == v:
                    continue
                size[u] += size[v]

        cur = 1
        n = size[cur]

        while True:
            max_ = n - size[cur]
            ind_ = p[cur]

            for v in g[cur]:
                if v == p[cur]: continue

                if size[v] > max_:
                    max_ = size[v]
                    ind_ = v

            if max_ <= n // 2:
                return cur

            cur = ind_

    def find_center(g):
        d    = {}
        d[1] = 0
        Q    = [(1, 0)]

        while len(Q) > 0:
            u, dis = Q.pop(0)

            for v in g[u]:
                if v not in d:
                    d[v] = dis +1
                    Q.append((v, d[v]))

        max_length = -1
        s = None

        for u, dis in d.items():
            if dis > max_length:
                max_length = dis
                s = u

        d   = {}
        pre = {}
        d[s] = 0
        Q = [(s, 0)]

        while len(Q) > 0:
            u, dis = Q.pop(0)

            for v in g[u]:
                if v not in d:
                    pre[v] = u
                    d[v]   = dis +1
                    Q.append((v, d[v]))

        max_length = -1
        e = None

        for u, dis in d.items():
            if dis > max_length:
                max_length = dis
                e = u

        route = [e]
        while pre[route[-1]] != s:
            route.append(pre[route[-1]])

        print(route)
        return route[len(route) // 2]

    root = find_centroid(g)
    p    = {}
    size = {}
    Q    = [root]
    p[root] = -1

    i = 0
    while i < len(Q):
        u = Q[i]

        for v in g[u]:
            if p[u] == v: continue
            p[v] = u
            Q.append(v)
        i+=1

    for u in Q[::-1]:
        size[u] = 1

        for v in g[u]:
            if p[u] == v:
                continue
            size[u] += size[v]

    gr    = [(u, size[u]) for u in g[root]]
    gr    = sorted(gr, key=lambda x:x[1])
    thres = math.ceil((n-1) / 3)
    sum_  = 0

    gr1 = []
    gr2 = []
    i = 0

    while sum_ < thres:
        gr1.append(gr[i][0])
        sum_ += gr[i][1]
        i+=1

    while i < len(gr):
        gr2.append(gr[i][0])
        i+=1

    def asign(u, W, ew):
        if size[u] == 1:
            return

        cur = 0
        for v in g[u]:
            if v == p[u]: continue

            first = W[cur]
            ew.append((u, v, first))

            W_  = [x - first for x in W[cur+1: cur+size[v]]]
            asign(v, W_, ew)

            cur+=size[v]

    a, b = 0, 0
    for x in gr1:
        a += size[x]

    for x in gr2:
        b += size[x]

    arr_1 = [x for x in range(1, a+1)]
    arr_2 = [i*(a+1) for i in range(1, b+1)]
    ew    = []

    cur = 0
    for u in gr1:
        first = arr_1[cur]
        ew.append((root, u, first))
        W_    = [x - first for x in arr_1[cur+1:cur+size[u]]]

        cur += size[u]
        #print(u, W_)
        asign(u, W_, ew)

    cur = 0
    for u in gr2:
        first = arr_2[cur]
        ew.append((root, u, first))
        W_    = [x - first for x in arr_2[cur+1:cur+size[u]]]

        cur += size[u]
        #print(u, W_)
        asign(u, W_, ew)

    for u, v, w in ew:
        print('{} {} {}'.format(u, v, w))


import math

n    = int(input())
edge = [list(map(int, input().split())) for _ in range(n-1) ]
g    = {}

for x, y in edge:
    if x not in g:
        g[x] = []
    if y not in g:
        g[y] = []

    g[x].append(y)
    g[y].append(x)

def find_center(g):
    d    = {}
    d[1] = 0
    Q    = [(1, 0)]

    while len(Q) > 0:
        u, dis = Q.pop(0)

        for v in g[u]:
            if v not in d:
                d[v] = dis +1
                Q.append((v, d[v]))

    max_length = -1
    s = None

    for u, dis in d.items():
        if dis > max_length:
            max_length = dis
            s = u

    d   = {}
    pre = {}
    d[s] = 0
    Q = [(s, 0)]

    while len(Q) > 0:
        u, dis = Q.pop(0)

        for v in g[u]:
            if v not in d:
                pre[v] = u
                d[v]   = dis +1
                Q.append((v, d[v]))

    max_length = -1
    e = None

    for u, dis in d.items():
        if dis > max_length:
            max_length = dis
            e = u

    route = [e]
    while pre[route[-1]] != s:
        route.append(pre[route[-1]])

    return route[len(route) // 2]

root = find_center(g)
p    = {}
size = {}
Q    = [root]
p[root] = -1

i = 0
while i < len(Q):
    u = Q[i]

    for v in g[u]:
        if p[u] == v: continue
        p[v] = u
        Q.append(v)
    i+=1

for u in Q[::-1]:
    size[u] = 1

    for v in g[u]:
        if p[u] == v:
            continue
        size[u] += size[v]

gr    = [(u, size[u]) for u in g[root]]
gr    = sorted(gr, key=lambda x:x[1])
thres = math.ceil((n-1) / 3)
sum_  = 0

gr1 = []
gr2 = []
i = 0

while sum_ < thres:
    gr1.append(gr[i][0])
    sum_ += gr[i][1]
    i+=1

while i < len(gr):
    gr2.append(gr[i][0])
    i+=1

def asign(u, W, ew):
    if size[u] == 1:
        return

    cur = 0
    for v in g[u]:
        if v == p[u]: continue

        first = W[cur]
        ew.append((u, v, first))

        W_  = [x - first for x in W[cur+1: cur+size[v]]]
        asign(v, W_, ew)

        cur+=size[v]

a, b = 0, 0
for x in gr1:
    a += size[x]

for x in gr2:
    b += size[x]

arr_1 = [x for x in range(1, a+1)]
arr_2 = [i*(a+1) for i in range(1, b+1)]
ew    = []

cur = 0
for u in gr1:
    first = arr_1[cur]
    ew.append((root, u, first))
    W_    = [x - first for x in arr_1[cur+1:cur+size[u]]]

    cur += size[u]
    #print(u, W_)
    asign(u, W_, ew)

cur = 0
for u in gr2:
    first = arr_2[cur]
    ew.append((root, u, first))
    W_    = [x - first for x in arr_2[cur+1:cur+size[u]]]

    cur += size[u]
    #print(u, W_)
    asign(u, W_, ew)

for u, v, w in ew:
    print('{} {} {}'.format(u, v, w))


R = lambda: map(int, input().split())
arr = list(map(int, input()))
n = len(arr)
dp = [[0] * 10 for i in range(n)]
for i in range(10):
    dp[n - 1][i] = 1
for i in range(n - 2, -1, -1):
    for j in range(10):
        if (arr[i + 1] + j) % 2 == 0:
            dp[i][j] = dp[i + 1][(arr[i + 1] + j) // 2]
        else:
            dp[i][j] = dp[i + 1][(arr[i + 1] + j) // 2] + dp[i + 1][(arr[i + 1] + j + 1) // 2]
ownIn = 1
for i in range(n - 1):
    if (arr[i] + arr[i + 1]) != arr[i + 1] * 2 and (arr[i] + arr[i + 1]) != arr[i + 1] * 2 - 1:
        ownIn = 0
print(sum(dp[0]) - ownIn)


n = list(map(int, input()))
dp = [[1] * 10]
for i in range(1, len(n)):
    dp.append([0] * 10)
    for j in range(10):
        x = j + n[i]
        dp[i][x // 2] += dp[i - 1][j]
        if x % 2:
            dp[i][x // 2 + 1] += dp[i - 1][j]
print(sum(dp[-1]))


from math import floor,ceil

def find_possible_number(guess_number,digit,possible_table):
    if digit==len(phone_numbers):#base condition
        return 1

    m_number=int(phone_numbers[digit])
    guess_number=int(guess_number)

    num_index_configuration=str(guess_number)+str(digit)
    if num_index_configuration in possible_table:
        return possible_table[num_index_configuration]
    possible_table[num_index_configuration]=0

    has_remainder=(m_number+guess_number)%2
    if has_remainder:
        has_remainder_case(m_number, guess_number, possible_table, num_index_configuration, digit)
        return possible_table[num_index_configuration]
    else:
        has_no_remainder_case(m_number, guess_number, possible_table, num_index_configuration, digit)
        return possible_table[num_index_configuration]

def has_remainder_case(m_number, guess_number, possible_table, num_index_configuration, digit):
    upper_number=ceil((m_number+guess_number)/2)
    possible_table[num_index_configuration]+=find_possible_number(upper_number,digit+1,possible_table)
    lower_number=floor((m_number+guess_number)/2)
    possible_table[num_index_configuration]+=find_possible_number(lower_number,digit+1,possible_table)

def has_no_remainder_case(m_number, guess_number, possible_table, num_index_configuration, digit):
    next_number=(m_number+guess_number)/2
    possible_table[num_index_configuration]+=find_possible_number(next_number,digit+1,possible_table)

def has_exception(number):
    for i in range(1,len(phone_numbers)-1):

        if (int(phone_numbers[i])+number)%2:
            upper=ceil((int(phone_numbers[i])+number)/2)
            lower=floor((int(phone_numbers[i])+number)/2)
            if upper==int(phone_numbers[i]):
                number=int(phone_numbers[i])
            elif lower==int(phone_numbers[i]):
                number=int(phone_numbers[i])
            else:
                return False
        else:
            if (int(phone_numbers[i])+number)/2==int(phone_numbers[i]):
                number = int(phone_numbers[i])
            else:
                return False
    return True

phone_numbers=input()
possible_table={}#with the format of ["ab"]=c. a for number, b for digit, c for possible ways
first_number=phone_numbers[0]
count=0
for i in range(10):
    count+=find_possible_number(i,1,possible_table)
if has_exception(int(phone_numbers[0])):
    count-=1

#print(possible_table)
print(count)


#!/usr/bin/python
import sys

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

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

s = sys.stdin.readline().strip()
result = 0
for i in range(10):
	result += f(i, s, 1, len(s))
print result-1 if selfInclude(s) else result


#coding=utf-8

MOD = 1000000007
n, m, g = map(int, raw_input().split())

t = 0;

C = 1
total = 0
if m == 0:
  if n % 2 == 0:
    if g == 0:
      print 1
    else:
      print 0
  else:
    if g == 1:
      print 0
    else:
      print 1
  exit(0)
if m == 1:
  total = 1

for i in range(0, n):
  #print i
  total = C - total
  C = (C * (m + i + 1) * pow(i + 1, MOD - 2, MOD) ) % MOD
  #print C, total
#C = (C * (m + n) * pow(n, MOD - 1, MOD) ) % MOD
if g == 1:
  print (total % MOD + MOD) % MOD
else:
  print ((C - total + MOD) % MOD + MOD) % MOD


import operator as op
def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

def ncr(n, r):
    r = min(r, n-r)
    if r == 0: return 1
    numer = reduce(op.mul, xrange(n, n-r, -1))
    denom = reduce(op.mul, xrange(1, r+1))
    return numer//denom

N,M,G = map(int, raw_input().split())
def q(n):
	return ncr(n+M, M)

mod = 1000000007
r = [0] * (N+M+1)
r[1] = 1;
for i in range(2, N+M+1):
	r[i] = (mod - (mod/i) * r[mod%i] % mod) % mod;
#~ print r

def f(n):
	n -= 1
	sign = 1 if (n%2 == 0) else -1
	res = 0
	k = 0

	binom = 1

	while k <= n:
		res = (res + sign * binom) % mod
		binom = (binom * (k+M+1) * r[k+1]) % mod

		sign *= -1
		k += 1
	if M == 1:
		res += sign
	return res
if M == 0:
	print int(G == (N+1)%2)
	raise SystemExit

if G == 1:
	print f(N)
else:
	print q(N)-f(N)


import operator as op
def ncr(n, r):
    r = min(r, n-r)
    if r == 0: return 1
    numer = reduce(op.mul, xrange(n, n-r, -1))
    denom = reduce(op.mul, xrange(1, r+1))
    return numer//denom

N,M,G = map(int, raw_input().split())
def q(n):
	return ncr(n+M, M)

def f(n):
	n -= 1
	sign = 1
	res = 0
	while n >= 0:
		res += sign * q(n)
		sign *= -1
		n -= 1
	if M == 1:
		res += sign
	return res
if M == 0:
	print int(G == (N+1)%2)
	raise SystemExit

if G == 1:
	print f(N)
else:
	print q(N)-f(N)


#!/usr/bin/python
import sys

def ext_gcd(a, b):
    if b == 0:
        return (a, 1, 0)
    (dp, xp, yp) = ext_gcd(b, a % b)
    return (dp, yp, xp - a//b * yp)

def mod_solve(a, b, n):
    (d, xp, yp) = ext_gcd(a, n)
    if b % d == 0:
        x0 = xp * (b/d) % n
        return x0
    else:
        return None

def choose(n, m, MOD):
    result = 1
    if m < n - m:
        m = n - m
    for i in xrange(m+1, n+1):
        result = (result * i) % MOD
    for i in xrange(1, n-m+1):
        result = (result * mod_solve(i, 1, MOD)) % MOD
    return result

MOD = 1000000007
(n, m, g) = map(lambda x: int(x), raw_input().split())
if n == 0:
    if (m == 1 and g == 1) or (m > 1 and g == 0):
        result = 1
    else:
        result = 0
    print(result)
    sys.exit(0)

if m == 0:
    if (n % 2 == 0 and g == 1) or (n % 2 == 1 and g == 1):
        result = 1
    else:
        result = 0
    print(result)
    sys.exit(0)

term = 1
result = term
for i in xrange(1, n+1):
    term = (term * (m + i) * mod_solve(i, 1, MOD)) % MOD
    if i % 2 == 0:
        result = (result + term) % MOD
    else:
        result = (result + MOD - term) % MOD
if n % 2 == 1:
    result = (MOD - result) % MOD
if m == 1:
    if n % 2 == 0:
        result = (result + MOD - 1) % MOD
    else:
        result = (result + 1) % MOD
if g == 1:
    result = (choose(n+m, m, MOD) + MOD - result) % MOD
print(result)


#!/usr/bin/python
import sys

def ext_gcd(a, b):
    if b == 0:
        return (a, 1, 0)
    (dp, xp, yp) = ext_gcd(b, a % b)
    return (dp, yp, xp - a//b * yp)

def mod_solve(a, b, n):
    (d, xp, yp) = ext_gcd(a, n)
    if b % d == 0:
        x0 = xp * (b/d) % n
        return x0
    else:
        return None

def choose(n, m, MOD):
    result = 1
    for i in xrange(1, n+1):
        result = (result * i) % MOD
    for i in xrange(1, n-m+1):
        result = (result * mod_solve(i, 1, MOD)) % MOD
    for i in xrange(1, m+1):
        result = (result * mod_solve(i, 1, MOD)) % MOD
    return result

MOD = 1000000007
(n, m, g) = map(lambda x: int(x), raw_input().split())
if n == 0:
    if (m == 1 and g == 1) or (m > 1 and g == 0):
        result = 1
    else:
        result = 0
    print(result)
    sys.exit(0)

if m == 0:
    if (n % 2 == 0 and g == 1) or (n % 2 == 1 and g == 1):
        result = 1
    else:
        result = 0
    print(result)
    sys.exit(0)

term = 1
result = term
for i in xrange(1, n+1):
    term = (term * (m + i) * mod_solve(i, 1, MOD)) % MOD
    if i % 2 == 0:
        result = (result + term) % MOD
    else:
        result = (result + MOD - term) % MOD
if n % 2 == 1:
    result = (MOD - result) % MOD
if m == 1:
    if n % 2 == 0:
        result = (result + MOD - 1) % MOD
    else:
        result = (result + 1) % MOD
if g == 1:
    result = (choose(n+m, m, MOD) + MOD - result) % MOD
print(result)


import  sys
input=sys.stdin.readline
dp={}
mod=int(1000000007)
sys.setrecursionlimit(100000)
def bigmod(n,p):
    p=int(p)
    if p==0:
        return 1
    x=bigmod(n,p/2)
    x=(x*x)%mod
    if p%2==1:
        x=(x*n)%mod
    return x
k,pa,pb=map(int,input().split())
r=bigmod(pa+pb,mod-2)
r1=bigmod(pb,mod-2)
r1=(pa*r1)%mod
p=(pa*r)%mod
q=(pb*r)%mod

def cal(k1,a1):
    if k1+a1>=k:
        return (k1+a1+r1)%mod
    if (k1,a1) in dp:
        return dp[(k1,a1)]
    dp[(k1,a1)]=((cal(k1+a1,a1)*q)%mod+(cal(k1,a1+1)*p)%mod)%mod
    return dp[(k1,a1)]

print(cal(0,1))


import  sys
input=sys.stdin.readline
dp={}
mod=int(1000000007)
sys.setrecursionlimit(100000)
def bigmod(n,p):
    n,p=int(n),int(p)
    if p==0:
        return 1
    x=bigmod(n,p/2)
    x=(x*x)%mod
    if p%2==1:
        x=(x*n)%mod
    return x
k,pa,pb=map(int,input().split())
r=bigmod(pa+pb,mod-2)
r1=bigmod(pb,mod-2)
r1=(pa*r1)%mod
p=(pa*r)%mod
q=(pb*r)%mod

def cal(k1,a1):
    if k1+a1>=k:
        return (k1+a1+r1)%mod
    if (k1,a1) in dp:
        return dp[(k1,a1)]
    dp[(k1,a1)]=((cal(k1+a1,a1)*q)%mod+(cal(k1,a1+1)*p)%mod)%mod
    return dp[(k1,a1)]

print(cal(0,1))


#908D
n,a,b = map(int,raw_input().split())

p = 1000000007

def inv(a):
    p = 1000000007
    s=1
    n=p-2
    while n:
        if n&1:
            s=s*a%p
        a=a*a%p
        n/=2
    return s
f=[[0 for i in range(1001)] for j in range(1001)]
u=a*inv(a+b)%p
v=(1-u+p)%p
c=u*inv(v)%p
for i in range(n,0,-1):
    for j in range(n-1,-1,-1):
        if j+i>=n:
            f[i][j]=(j+i+c)%p
        else:
            f[i][j]=(u*f[i+1][j]+v*f[i][j+i])%p
print f[1][0]

"""
#include<cstdio>
typedef long long ll;
const int p=1e9+7;
ll inv(ll a){
	ll s=1;
	for(int n=p-2;n;n>>=1){
		if(n&1)s=s*a%p;
		a=a*a%p;
	}
	return s;
}
int n,a,b,f[1001][1001];
int main(){
	scanf("%d%d%d",&n,&a,&b);
	ll u=a*inv(a+b)%p,v=(1-u+p)%p,c=u*inv(v)%p;
	for(int i=n;i;--i)
		for(int j=n-1;~j;--j)
			f[i][j]=(j+i>=n?j+i+c:u*f[i+1][j]+v*f[i][j+i])%p;
	printf("%d\n",f[1][0]);
}
"""


import math
import sys

k, pa, pb = list( map( int, input().split() ) )

memo = {}

sys.setrecursionlimit(1500*1500*2)

MOD = (10**9 + 7 )

def pow( a, b ):

    ret = 1

    while b > 0:

        if b & 1:
            ret = (ret*a)%MOD

        a = (a*a)%MOD

        b //= 2

    return ( ret )

def inv(a):
   return pow( a, MOD-2 )

def f( total_a, total_ab ):

    if total_a+total_ab >= k:
        return total_a+total_ab + pa * inv(pb)

    if (total_a,total_ab) in memo:
        return memo[ (total_a,total_ab) ]

    Best = 0

    Best += pa * f( total_a+1, total_ab ) * inv( pa + pb )
    Best %= MOD

    Best += pb * f( total_a, total_a+total_ab ) * inv( pa + pb )
    Best %= MOD

    memo[ (total_a,total_ab) ] = Best

    return ( Best )

#print( k, pa, pb )

print( ( f(1,0) ) % MOD )


n, m, k = map(int, input().split())
a, b = map(int, input().split())
podE = a // (m * k)
if a % (m * k) != 0:
    podE += 1
podN = b // (m * k)
if b % (m * k) != 0:
    podN += 1
etE = (a % (m * k)) // k
if (a % (m * k)) % k != 0:
    etE += 1
etN = (b % (m * k)) // k
if (b % (m * k)) % k != 0:
    etN += 1

if podE == podN and etE == etN:
    print(0)
elif podE == podN:
    print(min(abs(etE - etN) * 5, 10 + abs(etE - etN)))
else:
    down = min((etE - 1) * 5, 10 + (etE - 1))
    move = min(abs(podE - podN), (n - podE) + podN) * 15
    up = min((etN - 1) * 5, 10 + (etN - 1))
    print(down + move + up)


n, m, k = map(int, input().split())
a, b = map(int, input().split())
podE = a // (m * k)
if a % (m * k) != 0:
    podE += 1
podN = b // (m * k)
if b % (m * k) != 0:
    podN += 1
etE = (a % (m * k)) // k
if (a % (m * k)) % k != 0:
    etE += 1
etN = (b % (m * k)) // k
if (b % (m * k)) % k != 0:
    etN += 1
if podE == 0:
    podE = n
if etE == 0:
    etE = m
if podN == 0:
    podN = n
if etN == 0:
    etN = m

if podE == podN and etE == etN:
    print(0)
elif podE == podN:
    print(min(abs(etE - etN) * 5, 10 + abs(etE - etN)))
else:
    down = min((etE - 1) * 5, 10 + (etE - 1))
    move = min(abs(podE - podN), (n - podE) + podN) * 15
    up = min((etN - 1) * 5, 10 + (etN - 1))
    print(down + move + up)


v = int(input())
eps = 170

def ans(a):
    a.sort()
    if len(a) % 2 == 0:
        med = a[len(a)//2]
    else:
        med = (a[len(a)//2] + a[len(a)//2 - 1]) // 2

    l = med - med // 2
    r = med + med // 2

    c1 = c2 = 0

    for i in a:
        if i >= l and i <= r:
            c1 += 1
        else:
            c2 += 1

    if abs(c1 - c2) <= eps:
        return (med, "uniform")
    else:
        return (med, "poisson")

for i in range(v):
    cur = [int(i) for i in input().split()]
    b = ans(cur)
    if b[1] == "poisson":
        print(b[0])
    else:
        print(sum(cur) // len(cur))


v = int(input())
eps = 170

def ans(a):
    a.sort()
    if len(a) % 2 == 0:
        med = a[len(a)//2]
    else:
        med = (a[len(a)//2] + a[len(a)//2 - 1]) // 2

    l = med - med // 2
    r = med + med // 2

    c1 = c2 = 0

    for i in a:
        if i >= l and i <= r:
            c1 += 1
        else:
            c2 += 1

    if abs(c1 - c2) <= eps:
        return (med, "uniform")
    else:
        return (med, "poisson")

for i in range(v):
    cur = [int(i) for i in input().split()]
    b = ans(cur)
    if b[1] == "poisson":
        print(b[0])
    else:
        print(sum(cur) // (max(cur) - min(a)))


def mean(seq):
    N = len(seq)
    return sum(seq)/float(N)

def std(seq):
    m = mean(seq)
    N = len(seq)
    return sum([(s-m)**2/N for s in seq])

def solve(seq):
    m = mean(seq)
    s = std(seq)

    s1 = m
    s2 = m*(m+1)/3

    if abs(s-s1) < abs(s-s2):
        return int(m)
    else:
        return (max(seq)+1)/2

V = int(raw_input())
seqs = [map(int, raw_input().split()) for i in xrange(V)]

for seq in seqs:
    print solve(seq)


def sampleVariance(V):
    X = sum(V) / len(V)
    S = 0.0
    for x in V:
        S += (X-x)**2

    S /= (len(V)-1)
    return (X, S)

#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
    V = list(map(int, input().split()))
    X, S = sampleVariance(V)
    v1 = X
    v2 = (2*X) ** 2 / 12

    if abs(v1-S) < abs(v2-S):
        print(int(X))
    else:
        print((max(V)+min(V)) // 2)


v = int(input())
eps = 170

def ans(a):
    a.sort()
    if len(a) % 2 == 0:
        med = a[len(a)//2]
    else:
        med = (a[len(a)//2] + a[len(a)//2 - 1]) // 2

    l = med - med // 2
    r = med + med // 2

    c1 = c2 = 0

    for i in a:
        if i >= l and i <= r:
            c1 += 1
        else:
            c2 += 1

    if abs(c1 - c2) <= eps:
        return (med, "uniform")
    else:
        return (med, "poisson")

for i in range(v):
    cur = [int(i) for i in input().split()]
    b = ans(cur)
    if b[1] == "poisson":
        print(b[0])
    else:
        print((max(cur) - min(cur)) // 2)


from collections import defaultdict as dd
import sys
input=sys.stdin.readline
n=int(input())
l=list(map(int,input().split()))
if(len(l)>60):
    print(1)
else:
    xo=[l[0]]
    for i in range(1,n):
        xo.append(l[i]^xo[-1])
    ans=-1
    for gap in range(1,100):
        for i in range(n):
            j=i+gap
            if(j>=n):
                continue
            if(i>0):
                val=xo[j]^xo[i-1]
                if(val<l[i-1]):
                    ans=gap
                    break
            else:
                val=xo[j]
            if(j+1<n):
                if(val>l[j+1]):
                    ans=gap
                    break
        if(ans!=-1):
            break
    #print(ans)
    if(ans==-1):
        ans=n
    for i in range(2,n):
        ll=i+2
        #print(n,l)
        for ii in range(n-ll+1):
            j=ii+ll-1
            #print(ii,j,le)
            for m in range(1,ll-2):
                if(ii>0):
                    le=xo[ii+m]^xo[ii-1]
                else:
                    le=xo[ii+m]
                #print(j,ii+m-1,"lol")
                re=xo[j]^xo[ii+m]
                #if(i==21):
                #print(le,re,ii,ii+m,j)
                if(le>re):
                    ans=min(i,ans)
                    break
            if(ans!=n):
                break
        if(ans!=n):
            break
    for i in range(n-1):
        cx=l[i]^l[i+1]
        if(i>0):
            if(cx<l[i-1]):
                ans=1
                break
        if(i+2<n):
            if(cx>l[i+2]):
                ans=1
                break
    if(ans==n):
        print(-1)
    else:
        print(ans)


from collections import defaultdict as dd
import sys
input=sys.stdin.readline
n=int(input())
l=list(map(int,input().split()))
if(len(l)>60):
    print(1)
else:
    xo=[l[0]]
    for i in range(1,n):
        xo.append(l[i]^xo[-1])
    ans=n

    for i in range(2,n):
        ll=i+2
        #print(n,l)
        for ii in range(n-ll+1):
            j=ii+ll-1
            #print(ii,j,le)
            for m in range(1,ll-2):
                if(ii>0):
                    le=xo[ii+m]^xo[ii-1]
                else:
                    le=xo[ii+m]
                #print(j,ii+m-1,"lol")
                re=xo[j]^xo[ii+m]
                #print(le,re,ii,ii+m,j)
                if(le>re):
                    ans=i
                    break
            if(ans!=n):
                break
        if(ans!=n):
            break
    for i in range(n-1):
        cx=l[i]^l[i+1]
        if(i>0):
            if(cx<l[i-1]):
                ans=1
                break
        if(i+2<n):
            if(cx>l[i+2]):
                ans=1
                break
    if(ans==n):
        print(-1)
    else:
        print(ans)


def check(a):
    for i in range(len(a) - 1):
        if a[i] > a[i + 1]:
            return True
    return False
n = int(input())
if n > 65:
    print(1)
else:
    a = [int(i) for i in input().split()]
    xo = [0]
    for i in range(n):
        xo.append(xo[i] ^ a[i])
    ans = 1000
    for L1 in range(n):
        for R1 in range(L1 + 1, n):
            if check(a[:L1] + [xo[R1 + 1] ^ xo[L1]] + a[R1 + 1:]):
                ans = min(ans, R1 - L1)
                # print(L1, R1, ans)
            for L2 in range(R1 + 1, n):
                for R2 in range(L2 + 1, n):
                    if check(a[:L1] + [xo[R1 + 1] ^ xo[L1]] + a[R1 + 1:L2] + [xo[R2 + 1] ^ xo[R1]] + a[R2 + 1:]):
                        ans = min(ans, R1 - L1 + R2 - L2)
                        # print(L1, R1, L2, R2, ans)
    print(ans if ans < 1000 else -1)


from itertools import accumulate as __accumulate
from math import inf as __inf, isinf as __isinf

def how_many_operations_need(seq):
    seq = list(seq)
    if any(seq[i] > seq[i+1] for i in range(len(seq) - 1)):
        return 0
    max_bits_indices = tuple(map(__get_max_bit_index, seq))
    for i in range(len(max_bits_indices) - 2):
        if max_bits_indices[i] == max_bits_indices[i+1] == max_bits_indices[i+2]:
            return 1

    prefix_xors = [0, *__accumulate(seq, int.__xor__)]

    result = +__inf
    for l in range(len(seq)-1):
        for r in range(l+1, len(seq)):
            left_value = seq[l-1] if l-1 >= 0 else -__inf
            right_value = seq[r+1] if r+1 < len(seq) else +__inf
            if not (left_value <= prefix_xors[r+1] ^ prefix_xors[l] <= right_value):
                result = min(result, r - l)

    if __isinf(result):
        raise ValueError
    return result

def __get_max_bit_index(x):
    i = -1
    while x:
        x >>= 1
        i += 1
    return i

def __main():
    __read_ints()  # skip n
    try:
        result = how_many_operations_need(__read_ints())
    except ValueError:
        print(-1)
    else:
        print(result)

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

if __name__ == "__main__":
    __main()


def xor(i, j):
    if i == 0:
        return p[j]
    return p[j] ^ p[i - 1]

n = int(input())
u = list(map(int, input().split()))
p = u[:]

k = 32
ans = 1000000000000
for i in range(n):
    for j1 in range(i, max(-1, i - k - 1), -1):
        for j2 in range(i + 1, min(n, i + k + 1)):
            x1 = xor(j1, i)
            x2 = xor(i + 1, j2)
            #print(x1, x2, j1, i, j2)
            if x1 > x2:
                ans = min(ans, j2 - j1 - 1)
if ans == 1000000000000:
    print(-1)
else:
    print(ans)


import sys
range = xrange
input = raw_input

# awfdsajgnjisgjnsfdin

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0

n = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
    u = inp[ii] - 1; ii += 1
    v = inp[ii] - 1; ii += 1
    coupl[u].append(v)
    coupl[v].append(u)

root = 0
bfs = [root]
for node in bfs:
    for nei in coupl[node]:
        del coupl[nei][coupl[nei].index(node)]
        bfs.append(nei)

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

nhalf = n // 2

for node in range(n):
    vals = [counter[nei] for nei in coupl[node]]
    vals.append(n - 1 - sum(vals))
    if max(vals) <= nhalf:
        break
root = node

for node in reversed(bfs):
    for nei in coupl[node]:
        coupl[nei].append(node)

found = [0] * n
depth = [0] * n

order = []
stack = [root]
while stack:
    node = stack.pop()
    if found[node]:
        continue
    found[node] = 1
    order.append(node)

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

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

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


import sys;range = xrange;input = raw_input;inp = [int(x) for x in sys.stdin.read().split()]; ii = 0;n = inp[ii]; ii += 1;coupl = [[] for _ in range(n)]
for _ in range(n - 1):u = inp[ii] - 1; ii += 1;v = inp[ii] - 1; ii += 1;coupl[u].append(v);coupl[v].append(u)
root = 0;bfs = [root]
for node in bfs:
    for nei in coupl[node]:
        del coupl[nei][coupl[nei].index(node)]
        bfs.append(nei)
counter = [0] * n;nhalf = n // 2
for node in reversed(bfs):
    counter[node] += 1
    for nei in coupl[node]:counter[node] += counter[nei]
for node in range(n):
    vals = [counter[nei] for nei in coupl[node]];vals.append(n - 1 - sum(vals))
    if max(vals) <= nhalf:break
root = node
for node in reversed(bfs):
    for nei in coupl[node]:coupl[nei].append(node)
found = [0] * n;depth = [0] * n;order = [];stack = [root];ans = [-1] * n
while stack:
    node = stack.pop()
    if found[node]:continue
    found[node] = 1;order.append(node)
    for nei in coupl[node]:
        if not found[nei]:depth[nei] = depth[node] + 1;stack.append(nei)
    stack += coupl[node]
for i in range(n):ans[order[i - nhalf]] = order[i]
print 2 * sum(depth);print ' '.join(str(x + 1) for x in ans)


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

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

nhalf = n // 2

for node in range(n):
    vals = [counter[nei] for nei in coupl[node]]
    vals.append(n - 1 - sum(vals))
    if max(vals) <= nhalf:
        break
root = node

for node in reversed(bfs):
    for nei in coupl[node]:
        coupl[nei].append(node)

found = [0] * n
depth = [0] * n

order = []
stack = [root]
while stack:
    node = stack.pop()
    if found[node]:
        continue
    found[node] = 1
    order.append(node)

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

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

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


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

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

nhalf = n // 2

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

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

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

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


import sys
range = xrange
input = raw_input

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0

n = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
    u = inp[ii] - 1; ii += 1
    v = inp[ii] - 1; ii += 1
    coupl[u].append(v)
    coupl[v].append(u)

root = 0
bfs = [root]
for node in bfs:
    for nei in coupl[node]:
        del coupl[nei][coupl[nei].index(node)]
        bfs.append(nei)

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

nhalf = n // 2

for node in range(n):
    vals = [counter[nei] for nei in coupl[node]]
    vals.append(n - 1 - sum(vals))
    if max(vals) <= nhalf:
        break
root = node

for node in reversed(bfs):
    for nei in coupl[node]:
        coupl[nei].append(node)

found = [0] * n
depth = [0] * n

order = []
stack = [root]
while stack:
    node = stack.pop()
    if found[node]:
        continue
    found[node] = 1
    order.append(node)

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

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

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


n, t = map(int, input().split())
s = bin(n + 2)[2:]
l = len(s)

if t & (t - 1):
    ans = 0
else:
    t = t.bit_length()
    f = [[0] * (l + 1) for i in range(l + 1)]
    for i in range(l + 1):
        f[i][0] = f[i][i] = 1
        for j in range(1, i):
            f[i][j] = f[i - 1][j - 1] + f[i - 1][j]

    ans = c = 0
    for i in range(l):
        if s[i] == '1':
            if t - c <= l - i - 1:
                ans += f[l - i - 1][t - c]
            c += 1
    if t == 1: ans -= 1
print(ans)


import math
from operator import mul
def comb(i, j):
    if j > i or j < 0: return 0
    return reduce(mul, xrange(i, i - j, -1), 1)/reduce(mul, xrange(1, j+1), 1)

def g(r, p, k):
    s = 0
    p2 = 2 ** p
    while r > 0:
        while r < p2:
            p2 /= 2
            p -= 1
        s += comb(p, k)
        r -= p2
        k -= 1
        if k < 0: break
    return s

n, t = map(int, raw_input().split())
if math.log(t, 2) - int(math.log(t, 2)) > 1e-5:
    print 0
else:
    n += 1
    k = int(math.log(t, 2))
    p = int(math.log(n + 1, 2)) - 1
    ans = comb(p+1, k+1) + g(n - 2**(p+1) + 1, p, k)
    if t == 1: ans -= 1
    print ans


from math import factorial as fac

n, t = map(int, input().split())
if t & (t - 1):
    ans = 0
else:
    ans = c = 0
    s = bin(n + 2)[2:]
    l = len(s)
    for i in range(l):
        if s[i] == '1':
            m, k = l - i - 1, t.bit_length() - c
            if 0 <= k <= m:
                ans += fac(m) // fac(k) // fac(m - k)
            c += 1
    if t == 1: ans -= 1
print(ans)


def F(i, n, t):
	if i + 1 < t:
		return 0
	if not t:
		return 1
	if n & 2 ** i:
		return c.get((i, t), 0) + F(i - 1, n ^ 2 ** i, t - 1)
	else:
		return F(i - 1, n, t)

d = dict((2 ** i, i) for i in range(50))
c = {(0, 0) : 1}
for i in range(1, 50):
	c[(i, 0)] = c[(i, i)] = 1
	for j in range(1, i):
		c[(i, j)] = c[(i - 1, j - 1)] + c[(i - 1, j)]
n, t = map(int, raw_input().split())
if t in d:
	t = d[t] + 1
	print F(49, n + 1, t) - (t == 1)
else:
	print 0


c = []

def f(n, t):
	x = 0
	while 2 ** x <= n:
		x += 1
	x -= 1
	ans = c[x][t + 1] if t + 1 <= x else 0
	if n > 2 ** x and t > 0:
		ans += f(n - 2 ** x, t - 1)
		if t == 1:
			ans += 1
	return ans

c.append([1])
for i in range(1, 60):
	q = [1]
	for j in range(1, i):
		q.append(c[-1][j] + c[-1][j - 1])
	q.append(1)
	c.append(q)

n, t = map(int, raw_input().split())
n += 1
tt = 0
while t % 2 == 0:
	t /= 2
	tt += 1
if t > 1:
	print 0
else:
	print f(n, tt)


def gen(i, j):
    if a[i][j] == -1:
        a[i][j] = max(gen(i - 1, j - 1) + s2[i - 1] * (s2[i - 1] == s1[j - 1]), gen(i - 1, j), gen(i, j - 1), key = lambda x: len(x))
    return a[i][j]

s1, s2, virus = [input() for x in range(3)]
a = [[''] * (len(s1) + 1)] + [[''] + [-1] * (len(s1)) for x in range(len(s2))]
ans = gen(len(s2), len(s1))
while virus in ans:
    i = ans.index(virus)
    ans = list(ans)
    ans[i + len(virus) - 1] = ''
    ans = ''.join(ans)
print(ans + '0' * (ans == ''))


def Solve(x,y,c):
    if(type(c)!=int):
        print(x,y,c)
    if(c==len(virus)):
        return 0
    if(x==len(s1) or y==len(s2)):
        return ""
    if((x,y,c) in Mem):
        return Mem[(x,y,c)]
    ans=""
    if(s1[x]==s2[y]):
        q=0
        if(s1[x]==virus[c]):
            q=Solve(x+1,y+1,c+1)
        else:
            done=False
            for match in T[c]:
                if(s1[x]==virus[match]):
                    done=True
                    q=s1[x]+Solve(x+1,y+1,match+1)
                    break
            if(not done):
                q=s1[x]+Solve(x+1,y+1,0)
        if(q!=0):
            ans=q
    q=Solve(x+1,y,c)
    if(q!=0):
        ans=max(ans,Solve(x+1,y,c),key=len)
    q=Solve(x,y+1,c)
    if(q!=0):
        ans=max(ans,Solve(x,y+1,c),key=len)
    Mem[(x,y,c)]=ans
    return ans

Mem={}
s1=input()
s2=input()
virus=input()

T=[0]*len(virus)
T[0]=[0]
T[1]=[0]
for i in range(2,len(virus)):
    done=False
    T[i]=[]
    for j in range(1,i):
        if(virus[j:i]==virus[:i-j]):
            T[i].append(i-j)
    T[i].append(0)

e=Solve(0,0,0)
if(e==""):
    print(0)
else:
    print(Solve(0,0,0))


from Queue import * # Queue, LifoQueue, PriorityQueue
from bisect import * #bisect, insort
from datetime import *
from collections import * #deque, Counter,OrderedDict,defaultdict
import calendar
import heapq
import math
import copy
import itertools

def maxBy(f, x, y):
    if f(x) > f(y):
        return x
    else:
        return y

table = { ("","") : "" }

def lcs(xs,ys):
    if (xs,ys) in table:
        return table[(xs,ys)]

    ret = ""
    if xs == "" or ys == "":
        ret = ""
    elif xs[-1] == ys[-1]:
        ret = lcs(xs[:-1],ys[:-1]) + xs[-1]
    else:
        ret = maxBy(len,
                    lcs(xs[:-1],ys),
                    lcs(xs,ys[:-1]))
    table[(xs,ys)] = ret
    return ret

def make_ans(ans, virus):
    if ans.find(virus) == -1:
        return (len(ans), ans)

    target = ans.find(virus)
    ans_list = []
    for i in range(len(virus)):
        new_s = ans[:target+i] + ans[target+i+1:]
        ans_list.append( make_ans(new_s, virus) )

    ans_list.sort(reverse = True)

    return ans_list[0]

def solver():
    s1 = raw_input()
    s2 = raw_input()
    virus = raw_input()

    ans = lcs(s1,s2)

    ans = make_ans(ans, virus)[1]
    if ans == "":
        print 0
    else:
        print ans

if __name__ == "__main__":
    solver()


from Queue import * # Queue, LifoQueue, PriorityQueue
from bisect import * #bisect, insort
from datetime import *
from collections import * #deque, Counter,OrderedDict,defaultdict
import calendar
import heapq
import math
import copy
import itertools

dp = {}

def long_sequence(i,j,ans_s,s2):
    if dp[(i,j)] == 0:
        return ans_s

    up = dp[(i-1,j)]
    side = dp[(i,j-1)]
    up_side = dp[(i-1,j-1)]

    if up == side and side == up_side and up_side ==dp[i,j] - 1:
        return long_sequence(i-1,j-1,s2[j-1]+ans_s,s2)
    elif side > up:
        return long_sequence(i,j-1,ans_s,s2)
    else:
        return long_sequence(i-1,j,ans_s,s2)

def make_table(s1,s2,virus):
    for i in range(0,len(s1)+1):
        dp[(i,0)] = 0
    for j in range(0,len(s2)+1):
        dp[(0,j)] = 0

    for i in range(0,len(s1)):
        for j in range(0, len(s2)):
            l_s = long_sequence(i,j,"",s2)
            l_s += s2[j]
            if s1[i] == s2[j] and l_s.find(virus) == -1:
                dp[(i+1,j+1)] = dp[(i,j)] + 1
            else:
                dp[(i+1,j+1)] = max(dp[(i+1,j)],dp[(i,j+1)])

def print_dp(s1,s2):
    for i in range(0,len(s2)):
        print "%2d" % i,

    print len(s1)

    for i in range(0,len(s1)+1):
        print i,
        for j in range(0,len(s2)+1):
            print "%2d" % dp[(i,j)],

        print

def solver():
    s1 = raw_input()
    s2 = raw_input()
    virus = raw_input()

    make_table(s1,s2,virus)
    #print_dp(s1,s2)
    ans = long_sequence(len(s1),len(s2),"",s2)

    if ans == "":
        print 0
    else:
        print ans

if __name__ == "__main__":
    solver()


MAX = 101
NINF = -22222222222
base = [-1]*MAX
dp = [ [ base[:] for i in range(MAX)] for j in range(MAX)]
s1 = ""
s2 = ""
s3 = ""
l1 = ""
l2 = ""
l3 = ""

def foo(i, j, k):
	if k == l3 :
		return "", NINF
	if i == l1:
		return "", 0
	if j == l2:
		return "", 0
	if dp[i][j][k] != -1:
		return dp[i][j][k]
	ans1, len1 = foo( i + 1, j, k )
	ans2, len2 = foo( i , j + 1, k )
	len3 = NINF
	if s1[i] == s2[j]:
		if s1[i] == s3[k]:
			ans3, len3 = foo(i+1, j + 1, k + 1)
			ans3 += s1[i]
			len3 += 1
		else:
			ans3, len3 = foo(i+1, j + 1, 0 )
			ans3 += s1[i]
			len3 += 1
	if len1 > len2:
		if len1 > len3:
			dp[i][j][k] = ans1, len1
		else:
			dp[i][j][k] = ans3, len3
	else:
		if len2 > len3:
			dp[i][j][k] = ans2, len2

		else:
			dp[i][j][k] = ans3, len3
	return dp[i][j][k]

s1 = raw_input()
s2 = raw_input()
s3 = raw_input()
l1 = len(s1)
l2 = len(s2)
l3 = len(s3)

ans = foo(0,0,0)
if ans[1] == 0:
	print(0)
else:
	print(ans[0][::-1]	)


def r(): return raw_input().strip()
def ri(): return int(r().strip())
def riv(): return map(int, r().split())

diff = {
    (1,1): 0,
    (2,2): 0,
    (3,3): 0,
    (1,2): 1,
    (1,3): 2,
    (2,1): 2,
    (2,3): 1,
    (3,1): 1,
    (3,2): 2
}

def main():
    n = ri()
    c = riv()

    a = []
    starts, start_comps = [], []
    for i in range(n):
        line = riv()[1:]
        a.append(line)
        if len(line) == 0:
            starts.append(i+1)
            start_comps.append(c[i])

    min_hours = -1
    while starts:
        hours = 1
        down = set()
        start = starts.pop()
        start_comp = start_comps.pop()
        down.add(start)
        while len(down) < n:
            possible = {}
            for i, stage in enumerate(a):
                if i+1 not in down and all([s in down for s in stage]):
                    comp = c[i]
                    if comp not in possible:
                        possible[comp] = []
                    possible[comp].append(i+1)

            if start_comp in possible:
                for l in possible[start_comp]:
                    hours += 1
                    down.add(l)
            else:
                nz = min(possible.items(), key=lambda z: diff[(start_comp, z[0])])
                hours += diff[(start_comp, nz[0])]
                start_comp = nz[0]
                for l in nz[1]:
                    hours += 1
                    down.add(l)

        if min_hours == -1 or min_hours > hours:
            min_hours = hours

    print min_hours

if __name__ == "__main__":
    main()


from collections import *

read_line = lambda: [int(i) for i in input().split(' ')]

n = read_line()[0]
cs = [c - 1 for c in read_line()]
g = [[] for v in range(n)]
parent_cnt = [0] * n
for v in range(n):
    parents = read_line()
    parent_cnt[v] = len(parents) - 1
    for i in range(1, len(parents)):
        g[parents[i] - 1].append(v)

def work(x):
    pcnt = list(parent_cnt)
    qs = [
        deque(v for v in range(n) if cs[v] == c and pcnt[v] == 0)
        for c in range(3)
    ]
    ans = 0
    while True:
        while qs[x]:
            v = qs[x].popleft()
            ans += 1
            for w in g[v]:
                pcnt[w] -= 1
                if pcnt[w] == 0:
                    qs[cs[w]].append(w)
        if qs[0] or qs[1] or qs[2]:
            ans += 1
            x = (x + 1) % 3
        else:
            break
    return ans

print(min(work(i) for i in range(3)))

# Made By Mostafa_Khaled


def r(): return raw_input().strip()
def ri(): return int(r().strip())
def riv(): return map(int, r().split())

diff = {
    (1,1): 0,
    (2,2): 0,
    (3,3): 0,
    (1,2): 1,
    (1,3): 2,
    (2,1): 2,
    (2,3): 1,
    (3,1): 1,
    (3,2): 2
}

def main():
    n = ri()
    c = riv()

    a = []
    start, start_comp = None, 0
    down = set()
    for i in range(n):
        line = riv()[1:]
        a.append(line)
        if len(line) == 0 and start is None:
            start = i+1
            start_comp = c[i]

    hours = 1
    down.add(start)
    while len(down) < n:
        possible = {}
        for i, stage in enumerate(a):
            if i+1 not in down and all([s in down for s in stage]):
                comp = c[i]
                if comp not in possible:
                    possible[comp] = []
                possible[comp].append(i+1)

        if start_comp in possible:
            for l in possible[start_comp]:
                hours += 1
                down.add(l)
        else:
            nz = min(possible.items(), key=lambda z: diff[(start_comp, z[0])])
            hours += diff[(start_comp, nz[0])]
            start_comp = nz[0]
            for l in nz[1]:
                hours += 1
                down.add(l)

    print hours

if __name__ == "__main__":
    main()


def r(): return raw_input().strip()
def ri(): return int(r().strip())
def riv(): return map(int, r().split())

diff = {
    (1,1): 0,
    (2,2): 0,
    (3,3): 0,
    (1,2): 1,
    (1,3): 2,
    (2,1): 2,
    (2,3): 1,
    (3,1): 1,
    (3,2): 2
}

def main():
    n = ri()
    c = riv()

    a = []
    start, start_comp = None, 0
    down = set()
    for i in range(n):
        line = riv()[1:]
        a.append(line)
        if len(line) == 0:
            start = i+1
            start_comp = c[i]

    # find next stages
    hours = 1
    down.add(start)
    while len(down) < n:
        possible = {}
        for i, stage in enumerate(a):
            if i+1 not in down and all([s in down for s in stage]):
                comp = c[i]
                if comp not in possible:
                    possible[comp] = []
                possible[comp].append(i+1)

        if start_comp in possible:
            for l in possible[start_comp]:
                hours += 1
                down.add(l)
        else:
            nz = max(possible.items(), key=lambda z: len(z[1]))
            hours += diff[(start_comp, nz[0])]
            start_comp = nz[0]
            for l in nz[1]:
                hours += 1
                down.add(l)

    print hours

if __name__ == "__main__":
    main()


n = int(raw_input())
cpts = [int(i) for i in raw_input().split()]
tasks = [set() for i in xrange(3)]
for i in xrange(n):tasks[cpts[i]-1].add(i)
depends = [set([int(j)-1 for j in raw_input().split()][1:]) for i in xrange(n)]
finish = set()

def do_task(pos, finish, tasks, depends):
    hours = 0
    while True:
        ns = set()
        for t in tasks[pos]:
            depends[t].difference_update(finish)
            ns.update(depends[t])
        d = tasks[pos].difference(ns)
        if len(d) == 0:break
        finish.update(d)
        tasks[pos].difference_update(d)
        hours += len(d)
    return hours

hours = float('inf')
for pos in xrange(3):
    h = 0
    t = [s.copy() for s in tasks]
    d = [d.copy() for d in depends]
    f = set()
    while True:
        h += do_task(pos, f, t, d)
        if len(f) >= n:break
        h += 1
        pos = (pos + 1) % 3
    hours = min(hours, h)
print hours


def limitbal(a,b):
    min_level = 0
    level = 0
    for aa in a:
        if aa =='(':
            level+=1
        else:
            level-=1
            if level<min_level:
                min_level=level
    for aa in b:
        if aa =='(':
            level+=1
        else:
            level-=1
            if level<min_level:
                min_level=level
    return -min_level + len(a) + len(b) + (level - min_level)

def go():

    a = input()
    b = input()

    bal_lim = limitbal(a,b)+2

    tab = [[[None] * bal_lim for _ in range(len(b)+1)] for _ in range(len(a)+1)]
    par = [[[None] * bal_lim for _ in range(len(b)+1)] for _ in range(len(a)+1)]

    tab[0][0][0] = 0
    que = [(0, 0, 0)]
    index = 0
    while tab[len(a)][len(b)][0] is None:
        i,j,bal = que[index]
        if bal<bal_lim:
            #Add (
            ii=i
            jj=j
            if i<len(a) and a[i]=='(':
                ii=i+1
            if j<len(b) and b[j]=='(':
                jj=j+1
            if tab[ii][jj][bal+1] is None:
                tab[ii][jj][bal + 1] = tab[i][j][bal]+1
                par[ii][jj][bal + 1] = i,j,bal,'('
                que.append((ii,jj,bal+1))
        if bal>0:
            ii = i
            jj = j
            # Add )
            if i<len(a) and a[i] == ')':
                ii = i + 1
            if j<len(b) and b[j] == ')':
                jj = j + 1
            if tab[ii][jj][bal - 1] is None:
                tab[ii][jj][bal - 1] = tab[i][j][bal] + 1
                par[ii][jj][bal - 1] = i, j, bal, ')'
                que.append((ii, jj, bal - 1))
        index+=1

    i = len(a)
    j = len(b)
    bal = 0
    answer=[]
    while (i,j,bal) != (0,0,0):
        # print (i,j,bal)
        i,j,bal,symb = par[i][j][bal]
        answer.append(symb)
    print(''.join(reversed(answer)))

go()


def limitbal(a, b):
    min_level = 0
    level = 0
    for aa in a:
        if aa == '(':
            level += 1
        else:
            level -= 1
            if level < min_level:
                min_level = level
    for aa in b:
        if aa == '(':
            level += 1
        else:
            level -= 1
            if level < min_level:
                min_level = level
    return -min_level + len(a) + len(b) + (level - min_level)

def go():
    a = input()
    b = input()
    lena = len(a)
    lenb = len(b)
    a+='X'
    b+='X'

    bal_lim = limitbal(a, b) + 2

    tab = [[[None] * bal_lim for _ in range(lenb + 1)] for _ in range(lena+1)]
    par = [[[None] * bal_lim for _ in range(lenb + 1)] for _ in range(lena+1)]

    tab[0][0][0] = 0
    que = [(0, 0, 0)]
    index = 0
    while tab[lena][lenb][0] is None:
        i, j, bal = que[index]

        ai = a[i]
        bj = b[j]

        if bal < bal_lim and (bal==0 or not (ai==bj==')')):
            # Add (
            ii = i
            jj = j
            if ai == '(':
                ii = i + 1
            if bj == '(':
                jj = j + 1
            if tab[ii][jj][bal + 1] is None:
                tab[ii][jj][bal + 1] = tab[i][j][bal] + 1
                par[ii][jj][bal + 1] = i, j, bal, '('
                que.append((ii, jj, bal + 1))
        if bal > 0 and not (ai==bj=='('):
            ii = i
            jj = j
            # Add )
            if ai == ')':
                ii = i + 1
            if bj == ')':
                jj = j + 1
            if tab[ii][jj][bal - 1] is None:
                tab[ii][jj][bal - 1] = tab[i][j][bal] + 1
                par[ii][jj][bal - 1] = i, j, bal, ')'
                que.append((ii, jj, bal - 1))
        index += 1

    i = lena
    j = lenb
    bal = 0
    answer = []
    while (i, j, bal) != (0, 0, 0):
        # print (i,j,bal)
        i, j, bal, symb = par[i][j][bal]
        answer.append(symb)
    print(''.join(reversed(answer)))

go()


def go():

    a = input()
    b = input()

    tab = [[[None] * 220 for _ in range(len(b)+1)] for _ in range(len(a)+1)]
    par = [[[None] * 220 for _ in range(len(b)+1)] for _ in range(len(a)+1)]

    tab[0][0][0] = 0
    que = [(0, 0, 0)]
    index = 0
    while tab[len(a)][len(b)][0] is None:
        i,j,bal = que[index]
        if bal<218:
            #Add (
            ii=i
            jj=j
            if i<len(a) and a[i]=='(':
                ii=i+1
            if j<len(b) and b[j]=='(':
                jj=j+1
            if tab[ii][jj][bal+1] is None:
                tab[ii][jj][bal + 1] = tab[i][j][bal]+1
                par[ii][jj][bal + 1] = i,j,bal,'('
                que.append((ii,jj,bal+1))
        if bal>0:
            ii = i
            jj = j
            # Add )
            if i<len(a) and a[i] == ')':
                ii = i + 1
            if j<len(b) and b[j] == ')':
                jj = j + 1
            if tab[ii][jj][bal - 1] is None:
                tab[ii][jj][bal - 1] = tab[i][j][bal] + 1
                par[ii][jj][bal - 1] = i, j, bal, ')'
                que.append((ii, jj, bal - 1))
        index+=1

    i = len(a)
    j = len(b)
    bal = 0
    answer=[]
    while (i,j,bal) != (0,0,0):
        # print (i,j,bal)
        i,j,bal,symb = par[i][j][bal]
        answer.append(symb)
    print(''.join(reversed(answer)))

go()


a = input()
b = input()

tab = [[[None] * 220 for _ in range(len(b)+1)] for _ in range(len(a)+1)]
par = [[[None] * 220 for _ in range(len(b)+1)] for _ in range(len(a)+1)]

tab[0][0][0] = 0
que = [(0, 0, 0)]
index = 0
while tab[len(a)][len(b)][0] is None:
    i,j,bal = que[index]
    if bal<218:
        #Add (
        ii=i
        jj=j
        if i<len(a) and a[i]=='(':
            ii=i+1
        if j<len(b) and b[j]=='(':
            jj=j+1
        if tab[ii][jj][bal+1] is None:
            tab[ii][jj][bal + 1] = tab[i][j][bal]+1
            par[ii][jj][bal + 1] = i,j,bal,'('
            que.append((ii,jj,bal+1))
    if bal>0:
        ii = i
        jj = j
        # Add )
        if i<len(a) and a[i] == ')':
            ii = i + 1
        if j<len(b) and b[j] == ')':
            jj = j + 1
        if tab[ii][jj][bal - 1] is None:
            tab[ii][jj][bal - 1] = tab[i][j][bal] + 1
            par[ii][jj][bal - 1] = i, j, bal, ')'
            que.append((ii, jj, bal - 1))
    index+=1

i = len(a)
j = len(b)
bal = 0
answer=[]
while (i,j,bal) != (0,0,0):
    # print (i,j,bal)
    i,j,bal,symb = par[i][j][bal]
    answer.append(symb)
print(''.join(reversed(answer)))


a = input()
b = input()

m = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
# bil = [[0]*(len(b)+1) for _ in range(len(a)+1)]
dir = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]

a = a[::-1]
b = b[::-1]

for i in range(len(a)):
    for j in range(len(b)):
        if a[i] == b[j]:
            m[i + 1][j + 1] = m[i][j] + 1
            # if a[i]=='(':
            #     bil[i+1][j+1]=m[i][j]+1
        elif m[i][j + 1] == m[i + 1][j]:
            m[i + 1][j + 1] = m[i][j + 1]
            if a[i] == '(':
                dir[i + 1][j + 1] = 1
            else:
                dir[i + 1][j + 1] = 2
        else:
            m[i + 1][j + 1], dir[i + 1][j + 1] = max((m[i][j + 1], 1), (m[i + 1][j], 2))

# print('\n'.join(map(str, m)))
# print('\n'.join(map(str, dir)))

ii = len(a)
jj = len(b)

answer = []
while ii and jj:
    if dir[ii][jj] == 0:
        answer.append(a[ii - 1])
        ii -= 1
        jj -= 1
    elif dir[ii][jj] == 1:
        answer.append(a[ii - 1])
        ii -= 1
    elif dir[ii][jj] == 2:
        answer.append(b[jj - 1])
        jj -= 1
    # print (ii, jj)

while ii>0:
    answer.append(a[ii-1])
    ii-=1
while jj>0:
    answer.append(b[jj-1])
    jj-=1

level = 0
mlev=0
for aa in answer:
    if aa=='(':
        level+=1
    else:
        level-=1
    mlev = min(level,mlev)

pref = ''
suf = ''

if mlev<0:
    pref = -mlev * '('
level -=mlev
if level>0:
    suf = level*')'

answer = pref + ''.join(answer) + suf

print(answer)

"""
( ( )) (  ()
(   ))  ) ()

(())()()
"""

"""
()
(())
"""


n, s, k = list(map(int, input().split()))
amounts = list(map(int, input().split()))
colors = list(input())

dp = [[-1 in range(k + 1)] in range(n)]

def getAns(nth, left):
    if left <= 0:
        return 0
    if dp[nth][left] >= 0:
        return dp[nth][left]

    ret = 999999999
    for i in range(n):
        if amounts[i] <= amounts[nth]:
            continue
        ret = min(ret, abs(nth - i) + getAns(i, left - amounts[i])

    dp[nth][left] = ret
    return ret

ans = 999999999
for i in range(n):
    ans = min(ans, getAns(i, k - data[i]) + abs(s - 1 - i))
print(ans)


inf = float('inf')

N,S,K = map(int,raw_input().strip('\n').split(' '))
A = map(int,raw_input().strip('\n').split(' '))
color = raw_input().strip('\n')

dp = [[inf]*(N+5) for k in range(K+5)]
for i in range(N):
    dp[A[i]][i] = abs(S-i-1);

for k in range(K+5):
    for pos in range(N):
        if dp[k][pos] == inf:
            continue
        for newpos in range(N):
            if A[newpos]<=A[pos] or color[newpos] == color[pos]:
                continue
            if k+A[newpos]>K+5:
                continue
            dp[k+A[newpos]][newpos] = min(dp[k+A[newpos]][newpos], dp[k][pos]+abs(newpos-pos))

ans = int(1e18)
for k in range(K,K+5):
    for pos in range(N):
        ans = min(ans,dp[k][pos])
print ans

# dp = (mintime,last_j,last_c)
# candies = [(ni,ji,ci)]
# dp[0][0][1] = S
# dp[i][k+ni][0] = {c!=ci  dp[i-1][k][0] + dp[i-1][k][1]-j)
# dp[i][k+ni][1] = j
# dp[i][k+ni][2] = c

# candies = [(n,j,c) for j,(n,c) in enumerate(zip(A,color))]
# candies = sorted(candies,key=lambda x:x[0])

# dp = []
# for i in range(N+5):
#     temp = []
#     for j in range(K+5):
#         temp.append([inf,0,0])
#     dp.append(temp)

# for i in range(N+1):
#     dp[i][0][0] = 0
#     dp[i][0][1] = S

# for i in range(1,N+1):
#     ni,ji,ci = candies[i-1]
#     for k in range(K+5):
#         if k<ni:
#             continue
#         if dp[i-1][k][2] != ci:
#             dp[i][k][0]  = min(dp[i][k][0], dp[i-1][k-ni][0] + abs(dp[i-1][k-ni][1]-j))
#             dp[i][k][1] = ji
#             dp[i][k][2] = ci
#         else:
#             dp[i][k][0] = dp[i-1][k][0] + abs(dp[i-1][k][1]-j)

# print dp[N]


n, s, k = list(map(int, input().split()))
amounts = list(map(int, input().split()))
colors = list(input())

dp = [[-1 for j in range(k + 1)] for i in range(n)]

def getAns(nth, left):
    if left <= 0:
        return 0
    if dp[nth][left] >= 0:
        return dp[nth][left]

    ret = 999999999
    for i in range(n):
        if amounts[i] <= amounts[nth] or colors[i] == colors[nth]:
            continue
        ret = min(ret, abs(nth - i) + getAns(i, left - amounts[i]))

    dp[nth][left] = ret
    return ret

ans = 999999999
for i in range(n):
    ans = min(ans, getAns(i, k - amounts[i]) + abs(s - 1 - i))
print(ans)


'''input
5 3 10
1 2 3 4 5
RGBRR
'''
import math
def solve():
	n,s,k = map(int,input().split())
	s-=1
	r = list(map(int,input().split()))
	c = input()
	inf = int(1e18)
	dp = [[inf for i in range(n+1)] for j in range(k+1)]
	spos = [[inf for i in range(n+1)] for j in range(k+1)]
	# dp[i][j] = minimum number of steps to get amount i if we start with jth index
	for i in range(0,k+1):
		for j in range(0,n):
			if i==0 or i<=r[j]:
				dp[i][j] = 0
				continue
			for K in range(0,n):
				if c[K]!=c[j] and c[K]>c[j]:
					dp[i][j] = min(dp[i][j],dp[i-r[j]][K]+int(abs(K-j)))
	ans = min(dp[k][i]+abs(i-s) for i in range(0,n))
	if ans==inf:
		print(-1)
		return
	print(ans)
	return
t = 1
#t = int(input())
while t>0:
	t-=1
	solve()


inf = 10000
n, s, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(input())
for i in range(n):
    if b[i] == 'R':
        b[i] = 0
    elif b[i] == 'G':
        b[i] = 1
    else:
        b[i] = 2
boxes = [[a[i], b[i], i] for i in range(n)]
boxes.sort()
l = boxes[-1][0] * n + 1
s -= 1
dp = [[[inf, s] for j in range(l)] for i in range(3)]
if l < k:
    print(-1)
    exit(0)
dp[0][0][0] = 0
dp[1][0][0] = 0
dp[2][0][0] = 0
for i in range(n):
    pos = boxes[i][2]
    clr = boxes[i][1]
    cnt = boxes[i][0]
    for j in range(l - cnt):
        for c in range(3):
            if c == clr:
                continue
            if dp[clr][j + cnt][0] > dp[c][j][0] + abs(dp[c][j][1] - pos) and dp[c][j][1] != pos:
                dp[clr][j + cnt][0] = dp[c][j][0] + abs(dp[c][j][1] - pos)
                dp[clr][j + cnt][1] = pos
ans = min(dp[0][k][0], min(dp[1][k][0], dp[2][k][0]))
for i in range(k, l):
    ans = min(min(ans, dp[0][i][0]), min(dp[1][i][0], dp[2][i][0]))
if ans < inf:
    print(ans)
else:
    print(-1)


a,b,m=map(int,input().split())
k=s=(10**9)%m
i=0
while k and i<a:
    i+=1
    if k<m-b:exit(print(1, str(i).zfill(9)))
    k+=s
    if k>=m:k-=m
print(2)


#!/usr/bin/env python
"""(c) gorlum0 [at] gmail.com"""
import itertools as it
from sys import stdin

def solve(a, b, mod):
    if b >= mod: return 2

    m = 10**9 % mod
    s = 0
    for i in xrange(1, a+1):
        s += m
        if s >= mod: s -= mod
        if s == 0: break
        if s and s + b < mod:
            return 1, i
    return 2

def main():
    for l in stdin:
        a, b, mod = map(int, l.split())
        winner = solve(a, b, mod)
        if winner == 2:
            print 2
        else:
            print 1, '%09d' % winner[1]

def test():
    pass

if __name__ == '__main__':
    main()


a, b, m = map(int, input().split())
c = (10 ** 9) % m
ans = -1
for x in range(1, min(a + 1, m)):
    z = (x * c) % m
    if z == 0:
        continue
    if z + b < m:
        ans = x
        break
if ans == -1:
    print(2)
else:
    s = str(ans)
    s = ('0' * 9 + s)[-9:]
    print(1, s)


#!/usr/bin/env python
"""(c) gorlum0 [at] gmail.com"""
import itertools as it
from sys import stdin

def solve(a, b, mod):
    if b >= mod: return 2

    m = 10**9 % mod
    s = 0
    for i in xrange(1, a+1):
        s += m
        if s >= mod: s -= mod
        if not s: break
        if s + b < mod:
            return 1, i
    return 2

def main():
    for l in stdin:
        a, b, mod = map(int, l.split())
        winner = solve(a, b, mod)
        if winner == 2:
            print 2
        else:
            print 1, '%09d' % winner[1]

if __name__ == '__main__':
    main()


a, b, m = map(int, input().split())
t = [0] * m
s = 10 ** 9 % m
for i in range(a):
    k = i * s % m
    if 0 < k < m - b: exit(print(1, str(i).zfill(9)))
    if t[k]: break
    t[k] = 1
print(2)


def pr(x):
    d = 2
    while d * d <= x:
        if x % d == 0:
            return 0
        d += 1
    return 1

def cnt(n, k):
    if not pr(k) or n < k: return 0
    n1 = n // k
    return n1 - sum(cnt(n1, i) for i in range(2, min(k, n1 + 1)))

a, b, k = map(int, input().split())
ans = cnt(b, k) - cnt(a - 1, k)
print(ans)


#!/usr/bin/python

import sys
import math

primes = []
MAXN = 50000
hash = []

dp = dict()

def prime_test(v):
    for i in xrange(2,int(math.sqrt(v))+1):
        if v % i == 0:
            return False
    return True

def calc(v, k):
    if k >= MAXN:
        if (k <= v):
            return 1
        else:
            return 0
    else:
        if k > v:
            return 0
        elif k * k > v:
            return 1
        if (v,k) in dp:
            return dp[(v,k)]
        res = v / k
        for prime in primes:
            if prime >= k:
                break
            res -= calc(v/k, prime)
        dp[(v,k)] = res
        return res

if __name__=="__main__":
    hash = [-1] * MAXN
    for i in xrange(2,MAXN):
        if hash[i] == -1:
            primes.append(i)
            hash[i] = len(primes)-1
            v = i * i
            while (v < MAXN):
                hash[v] = -2
                v += i
    a,b,k = [int(v) for v in sys.stdin.readline().split(' ')]
    if (k < MAXN and hash[k] == -2) or (k >= MAXN and (not prime_test(k))):
        print 0
    else:
        print calc(b,k) - calc(a-1,k)


import sys
import math

a, b, k = map(int, sys.stdin.readline().split())

def rho(n, primes, s=0):
    if s >= len(primes) or n < primes[s]:
        return 0

    ret = 0
    for i in xrange(s, len(primes)):
        next = n / primes[i]

        if next == 0:
            break

        ret += next
        ret -= rho(next, primes, i + 1)

    return ret

def answer(c):
    if c < k:
        return 0
    if k*k > c:
        return 1

    primes = [2] if k > 2 else []
    for d in xrange(3, k, 2):
        for p in primes:
            if d % p == 0:
                break
        else:
            primes.append(d)

    return c/k - rho(c/k, primes)

def is_prime(a):
    for d in xrange(2, int(math.sqrt(a)) + 1):
        if a % d == 0:
            return True
    return False

if is_prime(k):
    print 0
else:
    print answer(b) - answer(a - 1)