from sys import stdin
from math import sqrt
# raw_input = input
# xrange = range
raw_input = lambda: stdin.readline().rstrip()
input = lambda: int(raw_input())
I=lambda: map(int, raw_input().split())
n,m = I()
dp = [0]*(n+1)
dp[1] = 1
s = 1
for x in xrange(2, n+1):
	w = 0
	q = int(sqrt(x))
	q1 = q+(0 if q**2==x else 1)
	for j in xrange(2, q1): #j<sqrt(x)
		w = (w+dp[x//j])%m
	for c in xrange(1, q+1):
		a1 = x//(c+1)
		a2 = x//c
		if a2>a1 and a2>q1-1:
			w = w+dp[c]*(a2-max(a1, q1-1)))%m
	dp[x] = (s + w)%m
	s = (s+dp[x])%m
print(dp[n])


f = lambda: map(int, input().split())
n, m = f()
p = [1 << i for i in range(n)]
for i in range(m):
    x, y = f()
    x -= 1
    y -= 1
    p[x] |= 1 << y
    p[y] |= 1 << x
s = set(p)
b = (1 << n) - 1
t = {}
if b in s:
    t[b] = 'b'
    s.remove(b)
if len(s) == 2:
    a, c = s
    if a | c == b and bool(a & c) == (b in t):
        t[a], t[c] = 'ac'
        s.clear()
print('No' if s else 'Yes\n' + ''.join(map(t.get, p)))


n,m,X,Y,x,y=map(int,input().split())
a=[abs(X-x),abs(Y-y)]
a.sort()
print("First" if a[0]<5 and a[0]+a[1]<7 else "Second")


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

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


 import sys
import time

for line in sys.stdin:
  ll = len(line)-1
  fail=0
  for i in range(ll):
    if i == ll-1-i : continue
    x = int(line[i])
    y = int(line[ll-1-i])
    if (x,y) not in [(3,3),(4,6),(6,4),(7,7),(8,0),(0,8),(5,9),(9,5)]:fail=1
  if fail: print("No")
  if not fail:print("Yes")


// luogu-judger-enable-o2
n = int(input())
n = hex(n)[2:]
x = n.count('0') + n.count('4') + n.count('6') + n.count('9')
x += n.count('a') + n.count('d') + n.count('8') * 2 + n.count('b') * 2
print(x)


import math
def main(fl=math.floor):
    m = int(raw_input())
    lo, hi = 0, 5.0 * (10 ** 15)
    g = [1, 1] + [i ** 3.0 for i in xrange(2, 180000)]
    def f(n):
        return sum(fl(n / g[i])  for i in xrange(2, int(n ** (1.0 / 3)) + 2))
    while lo + 1 < hi:
        mid = (lo + hi) / 2
        if f(fl(mid)) < m:
            lo = mid
        else:
            hi = mid
    gi = [1, 1] + [i ** 3 for i in xrange(2, 180000)]
    def fi(n):
        return sum(n / gi[i] for i in xrange(2, int(n ** (1.0 / 3)) + 2))
    x = int(fl(hi))
    print x if fi(x) == m else -1
main()


import math

k = int(input())

n = int(k/3)*2 + 1
# print('n', n)
ans = 0

while True:
    point_to_check = (n+2)//2
    # print('p', point_to_check)

    x = 0.0
    y = n*math.sqrt(3)

    # print('r', math.sqrt((x**2+y**2)))

    # p1
    x -= 0.5
    y += math.sqrt(3) * 0.5

    # print('r', math.sqrt((x**2+y**2)))

    count = -1
    for i in range(point_to_check):
        # print('r', math.sqrt((x**2+y**2)))
        if ((x**2+y**2)<=k**2):
            count = i
            break
        x -= 1.5
        y -= math.sqrt(3)/2

    extra = 0
    if count != -1:
        extra = point_to_check - count

        if (n+1)%2==0:
            extra *= 2
        else:
            extra = extra*2 -1

        if extra == n+1:
            ans += (extra-1)*6
            break
        else:
            ans += extra*6

        # print('n', n, 'ans', ans)

    n = n-1

# print('extra', extra)

for i in range(n):
    if i==0:
        ans += 1
    else:
        ans += i*6

print(ans)

# R = 1
# r = sqrt(3)*0.5*R
# full_cycle_count =  k / (math.sqrt(3)) - 0.5
# print(full_cycle_count)
# full_cycle_count = int(full_cycle_count)
# print(full_cycle_count)
#
# half_cycle_count = int((k - 1) / 3) * 2
# print(half_cycle_count)
#
# ans = 1
# last_add = 0
# for i in range(1, full_cycle_count+1):
#     last_add +=6
#     ans += last_add
#
# print(last_add)
#
# if half_cycle_count>full_cycle_count:
#     ans += (last_add+6) / 2
#
# print(int(ans))


#!/usr/bin/python
import sys
import math

def main():
  lines = sys.stdin.readlines()
  a, b, m = map(int, lines.pop(0).split(' '))
  vx, vy, vz = map(int, lines.pop(0).split(' '))
  #print "dimensions of room: (" + str(a) + ", 0, " + str(b) + ")"
  #print "distance away: " + str(m)
  #print vx, vy, vz
  coordinates = (a/2.0, m, 0)
  steps = -1*m/float(vy)

  x_move = (steps*math.fabs(vx))%(2*a)
  z_move = (steps*vz)%(2*b)
  #print "x movement: " + str(x_move)
  #print "z movement: " + str(z_move)
  final_x = 0
  final_z = 0
  shifted = 0

  if x_move > a:
  	#print "x move is larger than dim"
  	x_move = x_move % a
  	final_x = a-x_move
  else:
    final_x = x_move
  #print final_x
  if (vx < 0):
    #shift a/2 to the left
    shifted = final_x - a/2.0
    if shifted < 0:
      shifted = -1*shifted
  else:
		#shift a/2 to the right
    shifted = final_x + a/2.0
    if shifted > a:
      shifted = 2*a - shifted
  #print "final x: " + str(shifted)

  if z_move > b:
  	#print "z move is larger than dim"
  	z_move = z_move % b
  	final_z = (b-z_move)
  else:
  	final_z = z_move
  print str(shifted) + " " + str(final_z)

if __name__ == "__main__":
  main()


from copy import deepcopy
n, k, m, a = [int(i) for i in input().split()]
cn = [0] * (n + 1)
last = [-1] * (n + 1)
v = [int(i) for i in input().split()]

for i in range(len(v)):
    last[v[i]] = i
    cn[v[i]] += 1

cn1 = deepcopy(cn)
last1 = deepcopy(last)

for i in range(1, n + 1):
    #print(i)
    res = [i1 for i1 in range(1, n + 1)]
    res.sort(key=lambda x: (cn[x], -last[x]), reverse = True)

    for j in range(len(res)):
        if res[j] != i:
            continue
        j1 = j + 1
        lft = m - a
        while j1 < n and lft:
            cn[res[j1]] += min(lft, cn[i] - cn[res[j1]] + 1)
            last[res[j1]] = m
            lft -= min(lft, cn[i] - cn[res[j1]] + 1)
            j1 += 1

    res.sort(key=lambda x: (cn[x], -last[x]), reverse = True)
    sans = 0
    for j in range(len(res)):
        if res[j] != i:
            continue
        if cn[i] == 0 or j >= k:
            sans = 0
        else:
            sans = 1
        break

    if sans == 1:
        print(1, end= ' ')
        continue

    cn = deepcopy(cn1)
    last = deepcopy(last1)

    if m - a:
        cn[i] += m - a
        last[i] = m - 1

    res.sort(key=lambda x: (cn[x], 0 -last[x]), reverse = True)
    for j in range(len(res)):
        if res[j] != i:
            continue
        if cn[i] == 0 or j >= k:
            sans = 0
        else:
            sans = 1
        break

    cn = deepcopy(cn1)
    last = deepcopy(last1)

    if sans:
        print(2, end=' ')
    else:
        print(3, end=' ')


n = int(raw_input())
raw = raw_input()
global s, p, q, ans
s = []
for x in raw:
	s.append(int(x))
p = [[0 for i in range(n+1)] for j in range(n+1)]
q = [[0 for i in range(n+1)] for j in range(n+1)]

def f(a, b):
	global s, p, q
	if p[a][b] != 0:
		return p[a][b]
	if a > 0:
		y = f(a-1, b) + (10**(a-1))*s[n*2-a-b]
		if p[a][b] <= y:
			p[a][b] = y
			q[a][b] = 'M'
	if b > 0:
		y = f(a, b-1) + (10**(b-1))*s[n*2-a-b]
		if p[a][b] <= y:
			p[a][b] = y
			q[a][b] = 'H'
	return p[a][b]
def g(a, b):
	global q, ans
	if q[a][b] != 0:
		ans += q[a][b]
	if q[a][b] == 'M':
		g(a-1, b)
	if q[a][b] == 'H':
		g(a, b-1)

ans = ''
f(n, n)
a = b = n
while q[a][b] != 0:
	ans += q[a][b]
	if q[a][b] == 'M':
		a -= 1
	else:
		b -= 1
print ans


def satisfies(cnt1, cnt2, onlyX, onlyY, none):
    '''
    tells whether you can form presents using the numbers
    '''
    cnt1 = max(cnt1 - onlyY, 0)
    cnt2 = max(cnt2 - onlyX, 0)
    return (cnt1 + cnt2 <= none)

import sys
cnt1, cnt2, x, y = int(sys.stdin.readline()).split()
bothXY = 0
onlyX = 0
onlyY = 0
none = 0
v = 0
while(not satisfies(cnt1, cnt2, onlyX, onlyY, none)):
    v += 1
    if(v % (x * y) == 0):
        bothXY += 1
    elif(v % x == 0):
        onlyX += 1
    elif(v % y == 0):
        onlyY += 1
    else:
        none += 1
print v


import math
def primes(max_n):
    max_n-=1
    numbers = range(3, max_n+1, 2)
    half = (max_n)//2
    initial = 4

    for step in xrange(3, max_n+1, 2):
        for i in xrange(initial, half, step):
            numbers[i-1] = 0
        initial += 2*(step+1)
        if initial > half:
            return [2] + filter(None, numbers)
def factors(a):
    j = 0
    p = {}
    while (a > 1):
        b = asd[j]
        if a % b == 0:
            a /= b
            if b not in p:
                p[b] = 1
        else:
            j += 1
    p = p.keys()
    p.sort()
    return p
asd=primes(10**6+1)
check={}
for i in asd:
    check[i]=1
def help(arr,num):
    don=[]
    if num not in check:
        for i in arr:
            p=num/i
            #print p,i
            for j in range(num-i+1,num+1):
                    don.append(j)
    return don
def help2(arr,num):
    don=[]
    if num not in check:
        for i in arr:
            don.append(num-i+1)
    return don

#print help(factors(16),16)

n=input()
ans=[]
f=factors(n)
a=help(f,n)
for i in a:
    af=help(factors(i),i)
    #print af,i
    ans+=af
print min(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
m = inp[ii]; ii += 1

coupl = [[] for _ in range(n)]
V = []
C = []
for _ in range(m):
    a = inp[ii] - 1; ii += 1
    b = inp[ii] - 1; ii += 1
    c = inp[ii]; ii += 1

    eind = len(V)
    C.append(c)
    V.append(b)
    V.append(a)
    coupl[a].append(eind)
    coupl[b].append(eind ^ 1)

node_color = [-1]*n
ans = [0.0] * n

val0 = [0] * n
val1 = [1] * n
for root in range(n):
    if node_color[root] >= 0:
        continue
    bfs = [root]
    node_color[root] = 0
    for node in bfs:
        for eind in coupl[node]:
            nei = V[eind]
            if node_color[nei] == -1:
                node_color[nei] = 1 - node_color[node]
                bfs.append(nei)

                c = C[eind >> 1]
                val0[nei] = c - val0[node]
                val1[nei] = -val1[node]

    x = 0.0
    for node in bfs:
        for eind in coupl[node]:
            nei = V[eind]
            c = C[eind >> 1]
            if val0[node] + val0[nei] != c:
                if val1[node] + val1[nei] == 0:
                    print 'NO'
                    sys.exit()
                x = (c - (val0[node] + val0[nei]) + 0.0) / (val1[node] + val1[nei])
                break
        else:
            continue
        break
    else:
        vals = []
        for node in bfs:
            #val0[nei] + x*val1[nei] = 0
            vals.append(val0[node] / val1[node])
        vals.sort()
        x = vals[len(vals)//2]

    for node in bfs:
        ans[node] = val0[node] + x * val1[node] + 0.0

for node in range(n):
    for eind in coupl[node]:
        nei = V[eind]
        c = C[eind >> 1]
        if ans[node] + ans[nei] != c:
            print 'NO'
            sys.exit()

print 'YES'
print ' '.join(str(x) for x in ans)


import os
import sys
from io import BytesIO, IOBase
# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

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

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

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

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

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

# ------------------------------

from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

# ------------------------------

def c(chr): return ord(chr)-ord('a')

def main():
    n, k = RL()
    s = input()

    dp = [[0]*(n+1) for i in range(n+1)]
    rec = [-1]*26
    pre = [-1]*n
    dp[0][0] = 1

    for i in range(n):
        now = c(s[i])
        pre[i] = rec[now]
        rec[now] = i

    for i in range(1, n+1):
        for j in range(1, i+1):
            if j>i: break

            if i==j: dp[i][j] = 1; continue;

            dp[i][j] = dp[i-1][j] + dp[i-1][j-1]
            if pre[i-1]!=-1:
                # if i==5 and j==4: print(pre[i-1], '+++')
                dp[i][j] -= dp[pre[i-1]][j-1]

    res = 0
    for j in range(n, -1, -1):
        for i in range(n, -1, -1):
            if k:
                num = min(k, dp[i][j])
                k-=num
                res += (n-j)*num

    print(res if k==0 else -1)

if __name__ == "__main__":
    main()


n = int(input().strip())

a = {}

def decom(i):
    if i == 0:
        return 0
    if i == 1:
        return 1
    if i in a.keys():
        return a[i]
    if upper(i)[024] - i > i:
        return decom(i - lower(i)[0]) + lower(i)[1]
    else:
        k = min(decom(i - lower(i)[0]) + lower(i)[1], decom(upper(i)[0] - i) + upper(i)[1])
        a[i] = k
        return k

def upper(i):
    d = 1
    n = 1
    while d < i:
        d = d * 10 + 1
        n += 1
    return (d, n)

def lower(i):
    if (upper(i)[0] - 1) // 10 == 0:
        return (1, 1)
    return ((upper(i)[0] - 1) // 10, upper(i)[1] - 1)

print(decom(n))


from itertools import permutations

def check(date):
	y,m,d = date

	if (m in [1,3,5,7,8,10,12] and d > 31) or \
		(m in [2,4,6,9,11] and d > 30) or m>12:
		return False
	elif m == 2 and ((not y%4 and d>29) or (y%4 and d>28)):
		return False
	else:
		return True

def date_diff(cdate,bdate):
	if bdate[2]==29 and bdate[1]==2 and not bdate[0]%4:
		bdate = bdate[0]+18,3,1
	else:
		bdate[0]+=18

	if bdate <= cdate:
		return True
	else:
		return False

def main():
	cdate = [int(x) for x in raw_input().split('.')][::-1]
	bdate = [int(x) for x in raw_input().split('.')][::-1]

	possible = 'NO'
	for date in permutations(bdate):
		print date,
		date = list(date)

		if check(date):
			print 'passed'
			if date_diff(cdate,date):
				possible = "YES"
				break
		else:
			print 'failed'

	if cdate[0]<18:
		possible = "NO"
	print possible
if __name__ == "__main__":
	main()


n,t = map(int, raw_input().split())
a = map(int, raw_input().split())
#print n,t,a
m = min(t,n)
b = a*m
c = []
c += [a[0]]
for i in b[1:]:
    if i>=c[-1]:
    c += [i];
    else:
    j = len(c) - 2
    while j>=0:
        if c[j]<=i:
        break
        j-=1
    c[j+1] = i
    #print c
l = len(c)
#print l
ans = l
if t>m:
    d = {}
    mx = 0
    for i in a:
    if(i in d):
        d[i]+=1
    else:
        d[i]=1
    mx = max(mx, d[i])
    print ans, mx
    ans += (t-m)*mx
print ans


from math import gcd
a,b,c,d=[int(i) for i in input(),split()]
g=gcd(c,d)
c//=g
d//=g
e=min(a//c,b//d)
print(e*c,e*d)


# submit
def dist_from_0(x, y, n):
    if x == 0:
        return y
    else:
        if y == 0:
            return 4 * n - x
        else:
            if x == n:
                return 3 * n - y
            else:
                return n + x

def main():
    n, x1, y1, x2, y2 = [int(i) for i in raw_input().split()]
    d1 = dist_from_0(x1, y1, n)
    d2 = dist_from_0(x2, y2, n)
    d = abs(d2 - d1)
    print min(d, 4 * n - d)

if __name__ == '__main__':
    main()


def sqr(x,y): return 0 if x<1 or y<1 else x*y
x,y = map(int,raw_input().split())
i = input()
print (sqr(x-2*(i-1), y-2*(i-1))-sqr(x-2*i, y-2*i)+1)/2


# -*- coding: utf-8 -*-
import sys,copy,math,heapq,itertools as it,fractions,re,bisect,collections as coll

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

less = set(range(1, n + 1)) - set(a)
cnt = [0] * 100005
for ai in a: cnt[ai] += 1
ans = a[:]
for i in xrange(n):
    if cnt[a[i]] > 1 or a[i] > n:
        ans[i] = less.pop()
        cnt[a[i]] -= 1
print  " ".join(map(str, ans))


dp = {}
def count(n, low):
	k = (n, low)
	if k in dp: return dp[k]
	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 = 0, n+1
	while lo < hi:
		mid = (lo + hi + 1) / 2
		if count(n-2, mid) >= k-2:
			lo = mid
		else:
			hi = mid-1
	print getPos(2,n-1,lo,k-2)


a,h,w=(int(x) for x in input().split())
if h>w:
    w,h=h,w
m=h//a
r=0
for i in range(m,0,-1):
    x=(h-a*i)/(i+1)
    w1=w-x
    a1=a+x
    q=w1%a1
    if q<0.00000001:
        r=1
        break
if r==0:
    print(-1)
else:
    print(x)


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

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

start = 0

if b[0] == 'half':
    if n%2==0: start = n
    else: start = n+1
else:
    if n%2: start = n
    else: start = n+1

#print(start)
earned=0
cnt = 0

while cnt != n:
    earned = 0
    temp = start
    cnt = 0

    for i in b:
        if i[-1] == 'f' and temp%2 == 1: break
        if i[-1] == 's' and temp%2 == 0: break

        earned += (temp - temp/2) * p
        temp //= 2
        cnt += 1
        if temp == 0: break

    start += 1

#print(start-1)
print(int(earned))


import math, time, re

ln = lambda : raw_input()
cnv = lambda s: map(int, s.split())
rInt = lambda s: int(s)
rFloat = lambda s: float(s)
rLong = lambda s: long(s)
rLine = lambda f: f.readline()

b = [True for i in xrange(0, 10)]

llong = []
def per(s):
    if len (s) == 4:
        llong.append(s)
        return
    else:
        for i in xrange(0, 10):
            if b[i]:
                b[i] = False
                per(s + str(i))
                b[i] = True

def check(s1, s2):
    return (len([i for i in xrange(0, 4) if (s1[i] in s2 and s1[i] == s2[i])])), \
(len([i for i in xrange(0, 4) if (s1[i] in s2 and s1[i] != s2[i])]))

start = time.time()
k, t = 0, 0
n = int(raw_input())
l = []
per("")
#print llong
for i in xrange(0,n):
    l.append(ln().split())
for i in xrange(0, len(llong)):
    b = True
    for j in xrange(0, n):
        if (check(llong[i], l[j][0]) != (int(l[j][1]), int(l[j][2]))):
            b = False
            break
    if b:
        k += 1
        t = llong[i]
    if k > 1:
        break
#print l[0][0]
#print l[0][1]
#print l[0][2]
#print llong[0]
if k > 1:
    print 'Need more data'
elif k == 1:
    print t
else:
    print 'Incorrect data'
#per(s)
#print llong
#print check (s1, s2)
#print 'Time exceeded:', time.time() - start


def right(m, n, a):
    b = True
    n2 = a // 2 - a // 6
    n3 = a // 3 - a // 6
    n6 = a // 6
    if n2+n6<n or n3+n6<m or n2+n3+n6<n+m:
        b = False
    return b

n, m  = map(int, input().split())
ans = 0
while not right(m, n, ans):
        ans += 1
print(ans)


n = int(raw_input())

like = dict((i, set()) for i in range(1, n + 1))
dislike = dict((i, set()) for i in range(1, n + 1))

k = int(raw_input())
for person1, person2 in (map(int, raw_input().split()) for i in range(k)):
    like[person1].add(person2)
    like[person2].add(person1)

m = int(raw_input())
for person1, person2 in (map(int, raw_input().split()) for i in range(m)):
    dislike[person1].add(person2)
    dislike[person2].add(person1)

def find_solutions():
    for root in range(1, n + 1):
        graph_follow = set([root])
        graph = set()
        graph_likes = set()
        graph_dislikes = set()

        while graph_follow:
            for follow in graph_follow:
                graph.add(follow)
                graph_likes |= like[follow]
                graph_dislikes |= dislike[follow]
            graph_follow = (graph_likes - graph_dislikes) - graph

        if graph & graph_dislikes:
            yield 0
        else:
            yield len(graph)

print max(find_solutions())


def gen(o, gen1):
    if o == len(my_arr):
        fp = 1
        sp = 1

        for i in range(len(my_arr)):
            fp *= my_arr[i][0] ** gen1[i]
            sp *= my_arr[i][0] ** (my_arr[i][1] - gen1[i])

        if (h * fp >= a and w * sp >= b) or (h * fp >= b and w * sp >= a):
            return True

        return False

    for i in range(my_arr[o][1] + 1):
        if gen(o + 1, gen1 + [i]):
            return True

    return False

a, b, h, w, n = map(int, input().split())

arr = list(map(int, input().split()))
arr.sort(reverse = True)

arr2 = []
for i in range(n):
    if (not i) or arr[i] != arr[i - 1]:
        arr2.append([arr[i], 1])
    else:
        arr2[-1][1] += 1

if (h >= a and w >= b) or (h >= b and w >= a):
    print(0)
else:
    my_arr = []
    j = 0
    ans = -1
    for i in range(1, min(34, len(arr)) + 1):
        if my_arr and my_arr[-1] < arr2[j]:
            my_arr[-1][1] += 1
        else:
            j += 1
            my_arr.append([arr2[j][0], 1])

        if gen(0, []):
            ans = i
            break

    print(ans)


from operator import __xor__ as X
n = input()
a = [[] for _ in xrange(n+1)]
for k in xrange(2,n):
    for x in xrange(1,n):
        f = x*k+(k*k-k>>1)
        if f>n: break
        a[f].append((k,x))
q = [n]
s = set(q)
for j in q:
    l = set([])
    for k,x in a[j]: l.update(range(x,x+k))
    l -= s
    q.extend(l)
    s |= l
f = [0]*(n+1)
for i in sorted(s):
    z = set(reduce(X,f[x:x+k],0) for k,x in a[i])
    for j in xrange(n):
        if j not in z: break
    f[i]=j
print min(k for k,x in a[n] if reduce(X,f[x:x+k],0)==0) if f[n] else -1


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 > 60:
    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 bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline

M = mod = 998244353
def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))))
# def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n').split(' ')]
def li3():return [int(i) for i in input().rstrip('\n')]

def compare(a,b):
    if a[-1]<b[-1]:return -1
    elif a[-1]>b[-1]:return 1
    else:
        if sum(a[:-1]) > sum(b[:-1]):return -1
        return 1

def give(a,b):
    temp = (a*t1 + b*t2)/(a + b)
    # print(temp,a,b,t)
    if temp < t:
        return [a,b,float('inf')]
    return [a,b,abs(t - temp)]

t1, t2, x1, x2, t = li()
bestans = []
if t == t1 and t1 == t2:
    print(x1,x2)
elif t == t1:
    print(x1,0)

elif t == t2:
    print(0,x2)
else:
    currans = []
    currcheck = float('inf')
    r = (t2 - t)/(t - t1)
    # print('R ; ',r)
    bestans.append(give(x1,x2))
    bestans.append(give(0,x2))
    bestans.append(give(x1,0))
    for i in bestans:
        if currcheck > i[-1]:
            currcheck = i[-1]
            currans = i[:-1]
        elif currcheck == i[-1] and sum(currans) < sum(i[:-1]):
            currans = i[:-1]
    do = 1
    for i in range(1,x2 + 1):
        curry1 = i*r
        a = curry1
        b = i
        if 0 <= int(curry1) <= x1:
            do = 0
            c,d,e = give(int(a),b)
            if e < currcheck:
                currcheck = e
                currans = [c,d]
            elif e == currcheck and sum(currans) < c + d:
                currans = [c,d]
        if 0 <= int(a) + 1 <= x1:
            do = 0
            c,d,e = give(int(a) + 1,b)
            if e < currcheck:
                currcheck = e
                currans = [c,d]
            elif e == currcheck and sum(currans) < c + d:
                currans = [c,d]

    if do:
        for j in range(1,min(x1,x2) + 1):
            c,d,e = give(j,j)
            if e < currcheck:
                currcheck = e
                currans = [c,d]
            elif e == currcheck and sum(currans) < c + d:
                currans = [c,d]

    # for i,(a,b,c) in enumerate(bestans):
    #     if ((a*t1 + b*t2)/(a + b)) < t:
    #         bestans[i][-1] = 1000
    #         continue
    #     bestans[i][-1] = abs(t - ((a*t1 + b*t2)/(a + b)))

    # bestans.sort(key=cmp_to_key(compare))
    # print(bestans)
    print(*currans)


foo = bar = 0
quz = 1
for bar in range(int(input())):
    foo += int(input())
    if foo * quz < baz * bar: break
    baz, quz = foo, bar
print(baz / quz)


from math import log2, floor
N = int(input())
if N % 2 == 0:
    N //= 2
    ans = N - 2 ** floor(log2(N))
else:
    ans = (N+1) // 2 - 1
print(ans)


a = []
mn = float("inf")
for _ in range(n):
    line = input()
    a.append(list(permutations(line)))

for arr in zip(*a):
    ints = [int(''.join(num)) for num in arr]
    mn = min(mn,max(ints)-min(ints))

print(mn)


from math import ceil
n, m, s = map(int, raw_input().split())
arr = []
for i in xrange(s):
    for j in xrange(s):
        arr.append(int(ceil(1.0 * (m - j) / s) * ceil(1.0 * (n - i) / s)))
print n * m if max(arr) is 1 or max(arr) is 0 else max(arr)


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


def prod(n):
    x=str(n)
    y=['0']*len(x)
    for i in range(len(x)):
        y[i]=str(9-int(x[i]))
    while y[0]=='0':
        if len(y)==1:
            return 0
        else:
           y=y[1:len(y)]
    return int(x)*int(''.join(y))

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

s=0

for i in range(x[0],x[1]+1):
    if prod(i)>s:
        s=prod(i)
print(s)


a,b,l,r = map(int,raw_input().split())
s = "a"
for i in range(1,a):
    temp = s[i-1]
    #print temp
    x = ord(temp)
    x += 1
    s += chr(x)
#print s
for i in range(b):
    s += s[-1]
#print s
temp = s[-1]
if b>=a :
    s += s[:a-1]
    s += chr(ord(temp)+1)
else :
    s += s[:b]
    s += chr(ord(temp)+1)
    for i in range(a-b-1):
        temp = s[-1]
        #print temp
        x = ord(temp)
        x += 1
        s += chr(x)
#print s
for i in range(b):
    s += s[-1]
#print s
length = len(s)
s = '_' + s
if r-l+1 >= length :
    print len(set(s))-1
else :
    start = l%length
    if start==0 :
        start = length
    i = start
    end = r%length
    if end==0 :
        end = length
    ans = {}
    while(start!=end) :
        ans[s[start]] = 1
        start += 1
        if start>length :
            start = 1
    print len(ans)


# import sys
# sys.stdin = open('test.txt','r')
R = lambda: map(int,raw_input().split())
a11,b11 = R()
a12,b12 = R()
a21,b21 = R()
a22,b22 = R()

def win(a,b):
	res = 1
	if a<=a21: res = 0
	if a<=a22: res = 0
	if b<=b21: res = 0
	if b<=b22: res = 0
	# print a,b,res
	return res
def lose(a,b):
	res = 0
	# print a21,b22
	# print a22,b21
	if a21>a and b22>b: res = 1
	if a22>a and b21>b: res = 1
	# print a,b,res
	return res

if win(a11,b12) or win(a12,b11): print 'Team 1'
elif lose(a11,b12) and lose(a12,b11): print 'Team 2'
else: print 'Draw'


def play(price, n):
    # dp[i][j][k] -  наименьшая стоимость перемещения i блинов со стержня j => k
    # У нас всегда есть два варианта действия:
    # 1. Перемещаем i - 1 блин на место 2. Далее, перемещаем i - ый блин на место 3. И наконец перемещаем i - 1 блин на место 3.
    # 2. Перемещаем i - 1 блин на место 3. Затем i - ый на место 2, затем i - 1 блин на место 1, далее i -ый на 3-е место и наконец i - 1 блин на 3 место
    # т.е, dp[i][j][k] = min(dp[i - 1][j][k ^ j] + Price[j][k] + dp[i - 1][k ^ j][k],
    # dp[i - 1][j][k] + Price[j][k ^ j] + dp[i - 1][k][j] + Price[j ^ k][k] + dp[i - 1][j][k])

    dp = [[[0 for k in range(0, 4)] for j in range(0, 4)] for i in range(0, n + 1)]

    for i in range(1, n + 1):
        for j in range(1, 4):
            for k in range(1, 4):
                dp[i][j][k] = min(dp[i - 1][j][k ^ j] + price[j][k] + dp[i - 1][k ^ j][k], 2 * dp[i - 1][j][k] + price[j][k ^ j] + dp[i - 1][k][j] + price[j ^ k][k])

    return dp[n][1][3]

def main():
    matrix = [[0 for j in range(0, 4)] for i in range(0, 4)]
    i = 1
    while i < 4:
        row = list(map(int, input().split()))
        for j in range(1, 4):
            matrix[i][j] = row[j - 1]
        i += 1

    n = int(input())

    print(play(matrix, n))

main()
#print(play([[0, 0, 0, 0], [0, 0, 1, 1],[0, 1, 0, 1],[0, 1, 1, 0]], 3))


upper = [chr(x) for x in range(65, 91)]
lower = [chr(x) for x in range(97, 123)]

ans = 0
for x in input():
    if (x in upper):
        ans += ord(x) - 64
    elif (x in lower):
        ans -= ord(x) - 96
print(ans)


#!/usr/bin/python2

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

a = zip(b, s)
R = [x[0] for x in a if x[1] == 'R']
O = [x[0] for x in a if x[1] == 'O']
W = [x[0] for x in a if x[1] == 'W']

R.sort()
O.sort()
W.sort()

R.append(0)
O.append(0)
W.append(0)

R.reverse()
O.reverse()
W.reverse()

for i in xrange(1, len(R)):
	R[i] += R[i - 1]
for i in xrange(1, len(O)):
	O[i] += O[i - 1]
for i in xrange(1, len(W)):
	W[i] += W[i - 1]

ans = -1
for i in xrange(1, len(O)):
	if i >= k:
		break
	if k - i < len(R):
		ans = max(ans, O[i] + R[k - i])
	if k - i < len(W):
		ans = max(ans, O[i] + W[k - i])

print ans


from math import sqrt
a, b = map(int, input().split())
if a > b:
    a, b = b, a
u = []
sqa = int(sqrt(a))
sqb = int(sqrt(b))
for i in range(1, sqb + 1):
    if i <= sqa and a % i == 0:
        u.append((i, a // i))
    elif b % i == 0:
        u.append((i, b // i))
ok = False
sqab = int(sqrt(a + b))
for i in range(sqab, 0, -1):
    if (a + b) % i == 0:
        k = (a + b) // i
        for j in u:
            if i >= j[0] and k >= j[1]:
                ok = True
                break
    if ok:
        break
print(2 * (i + k))


#!/usr/bin/env python

import sys
a, b, w, x, c = map(int, sys.stdin.readline().strip().split())
ans = 0

def iterate(count):
    global a, b, w, x, c, ans
    for i in range(count):
        if c <= a:
            return True
        ans += 1
        c -= 1
        if b >= x:
            b -= x
        else:
            a -= 1
            b = w - (x - b)
    return c <= a
iterate(10000)
bb = b
cycle_len = 0
aa = a
cc = c
while True:
    if not iterate(1):
        break
    cycle_len += 1
    if b == bb:
        break
if c <= a:
    print ans
else:
    diff = (cc - c) - (aa - a)
    n = (c - a) / diff
    ans += cycle_len * n
    a -= (aa - a) * n
    c -= (cc - c) * n
    iterate(10000)
    print ans


n,m=map(int,input().split())
a=[int(i)%m for i in input().split()]
x,y=[],[]
def f(x,n,c):
    for i in range(1<<n):
        s=0
        for j in range(n):
            if i&(1<<j):
                s=(s+a[j+c])%m
        x.append(s%m)
        if x[-1]==m-1:exit(print(m-1))
f(x,n//2,0)
f(y,n-n//2,n//2)
x=list(set(x))
y.sort()
import bisect
k=0
for i in range(len(x)):
    d=bisect.bisect_left(y,m-1-x[i]+0.1)-1
    if d>=0:k=max(k,y[d]+x[i])
print(k)


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:
			if s1[i] == s3[0]:
				ans3, len3 = foo(i+1, j + 1, 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]	)


import fileinput

def calc(a, b):
    ans = 0
    l = a + b
    i = 1
    while i <= l:
        P = l // i
        r = l // P
        if P <= a and P <= b:
            an = (a + P) // (P + 1)
            ax = a // P
            bn = (b + P) // (P + 1)
            bx = b // P
            if an <= ax and bn <= bx:
                ans += min(ax + bx, r) - max(an + bn, i) + 1
        i = r + 1
    return ans

if __name__ == '__main__':
    it = fileinput.input()
    a, b = [int(x) for x in next(it).split()]
    print(calc(a, b))


def readInp():

    n = float(raw_input())

    return n

n = readInp()

n_upper = n
while True:
    if not(int(n_upper/3) == n_upper/3):
        n_upper += 1
    else:
        break

coin_list = [1, 3]
while coin_list[-1]<n_upper:
    coin_list.append(coin_list[-1]*3)

if n in coin_list:
    print 1
elif int(n/3) == n/3:
    idx = 0
    while True:
        if int(n/coin_list[idx]) == n/coin_list[idx]:
            idx += 1
        else:
            break
    print int(n/coin_list[idx]) + 1
else:
    print int(n/coin_list[1]) + 1


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

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

import __pypy__

def process(grid, a, n, m):
    aux = [[0] * 3000 for _ in range(3000)]
    for i in range(n):
        mi = deque()
        for j in range(a):
            while mi and grid[i][j] < mi[-1]:
                mi.pop()
            mi.append(grid[i][j])

        aux[0][i] = mi[0]
        for j in range(a, m):
            if mi[0] == grid[i][j - a]:
                mi.popleft()
            while mi and grid[i][j] < mi[-1]:
                mi.pop()
            mi.append(grid[i][j])
            aux[j - a + 1][i] = mi[0]

    return aux

def main():
    n, m, a, b = map(int, input().split())
    g, x, y, z = map(float, input().split())

    MOD = int(z)
    MODF = z
    MAGIC = 6755399441055744.0
    SHRT = 65536.0

    MODF_INV = 1.0 / MODF
    SHRT_INV = 1.0 / SHRT

    fround = lambda x: (x + MAGIC) - MAGIC
    fmod = lambda a: a - MODF * fround(MODF_INV * a)
    fmul = lambda a, b, c=0.0: fmod(fmod(a * SHRT) * fround(SHRT_INV * b) + a * (b - SHRT * fround(b * SHRT_INV)) + c)

    grid = [[0.0] * 3000 for _ in range(3000)]
    for i in range(n):
        for j in range(m):
            grid[i][j] = int(g) % MOD
            g = fmul(g, x, y)

    aux1 = process(grid, b, n, m)
    aux2 = process(aux1, a, m - b + 1, n)

    ans = 0
    for i in range(n - a + 1):
        ans += sum(aux2[i][:m - b + 1])

    print(ans)

# region fastio

BUFSIZE = 8192

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

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

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

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

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

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

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

# endregion

if __name__ == "__main__":
    main()


hpy,atky,defy=map(int,raw_input().split())
hpm,atkm,defm=map(int,raw_input().split())
h,a,d=map(int,raw_input().split())
ydeath=hpy/(atkm-defy)
mdeath=hpm/(atky-defm)
#print ydeath,mdeath
if ydeath>mdeath or ydeath<0:
    print 0
    exit()
else:
    a=(mdeath+1)*(atkm-defy)-hpy
    b=atkm-defy-hpy/(mdeath+1)
    c=hpm/(ydeath-1)+defm-atky
    if a<=0:
        a=10**10
    if b<=0:
        b=10**10
    if c<=0:
        c=10**10
    print min(a,b,c)


import sys
import math

n = int(input())

x = [0]*n
y = [0]*n

for i in range(n):
    x[i], y[i] = map(int, input().split())

sx = sum(x)
sy = sum(y)

for i in range(n):
    x[i] = n * x[i] - sx
    y[i] = n * y[i] - sy

m = int(input())

d = [0]*n
e = [0]*n

HD = 0

def check(a, b):
    global HD
    HE = 0
    for i in range(n):
        HE ^= hash((a-x[i])*(a-x[i])+(b-y[i])*(b-y[i]))
    return HD == HE

def sqrt(x):
    nn = int(x)
    if nn == 0:
        return 0
    fa, fb = divmod(nn.bit_length(), 2)
    x = 2**(fa+fb)
    while True:
        y = (x + nn//x)//2
        if y >= x:
            return x
        x = y

def hash(x):
    return x * 9991 + 43

pans = []

def solve():
    global d
    d = list(map(int, input().split()))
    c = 0
    d = [p * n * n for p in d]
    for i in range(n):
        c += d[i] - x[i] * x[i] - y[i] * y[i]

    assert(c % n == 0)
    c //= n
    ans = []
    ax = x[0]
    ay = y[0]
    if ax is 0 and ay is 0:
        ax = x[1]
        ay = y[1]
    rev = 0
    if ay == 0:
        ay = ax
        ax = 0
        rev = 1
    d.sort()
    global HD
    HD = 0
    for p in d:
        HD ^= hash(p)
    old = -1
    for p in d:
        if (p == old):
            continue
        old = p
        a = c + ax * ax + ay * ay - p
        if (a % 2 != 0):
            continue
        a //= 2
        A = ax * ax + ay * ay
        B = a * ax
        C = a * a - ay * ay * c
        D = B * B - A * C
        if (D < 0):
            continue
        sD = sqrt(D)
        if D != sD * sD:
            continue
        if (B + sD) % A == 0:
            qx = (B + sD) // A
            qy = (a - ax * qx) // ay
            if rev:
                t = qx
                qx = qy
                qy = t
            if ((qx + sx) % n == 0 and (qy + sy) % n == 0 and check(qx, qy)):
                qx = (qx + sx) // n
                qy = (qy + sy) // n
                ans.append([qx, qy])
        if sD == 0:
            continue
        if (B - sD) % A == 0:
            qx = (B - sD) // A
            qy = (a - ax * qx) // ay
            if rev:
                t = qx
                qx = qy
                qy = t
            if ((qx + sx) % n == 0 and (qy + sy) % n == 0 and check(qx, qy)):
                qx = (qx + sx) // n
                qy = (qy + sy) // n
                ans.append([qx, qy])

    ans.sort()
    buf=[]
    buf.append(len(ans))
    for p in ans:
            buf.append(p[0])
            buf.append(p[1])
    global pans
    pans.append(" ".join(map(str,buf)))

while m > 0:
    m -= 1
    solve()

sys.stdout.write("\n".join(pans))


def congr(a, b, p, x):
    solutions = 0
    power = pow(a, p - 2, p)
    a2, b2, s, d1 = 1, b, 0, -b
    prod = p * (p - 1)
    while s < p - 1:
        k = (d1 + s) % p
        L = x - s - (p - 1) * k
        solutions += L // prod + 1
        d1 = (d1 * power) % p
        s += 1
    return solutions

a, b, p, x = [int(j) for j in input().split()]
print(congr(a, b, p, x))


from math import factorial
fac = factorial

def dfs(lst):
    sums = [[] for i in xrange(k+1)]
    sums[0].append(0)
    while len(lst)>0:
        cur = lst.pop(0)
        length = [len(sums[i]) for i in xrange(k+1)]
        for i in xrange(k+1):
            for j in xrange(length[i]):
                if sums[i][j] + cur <=s:
                    sums[i].append(sums[i][j]+cur)
                    temp = sums[i][j]+fac(cur)
                    if cur<19 and i<k and temp<=s:
                        sums[i+1].append(sums[i][j]+fac(cur))
    return sums

def search(x, k):
    count = 0
    for i in xrange(k+1):
        count += second[i].count(x)
    return count

n, k, s = map(int, raw_input().split())
a = [int(item) for item in raw_input().split()]
a.sort()

first = dfs(a[:n/2])
second = dfs(a[n/2:])

#for i in xrange(k+1):
#    second[i].sort()
count = 0
for sum1 in xrange(s+1):
    for i in xrange(k+1):
        count += first[i].count(sum1)*search(s-sum1, k-i)
print count


M, N, res = 998244353, 720720, 0
I = lambda: [int(x) for x in input().split()]
p = [0] * N

n, a, x, y, k, U = I()
for i in range(1, n + 1):
    p[a % N] += 1
    res += a // N * N
    a = (a * x + y) % U

res = (res * pow(n, k - 1, M) * k) % M
for i in range(1, k + 1):
    tot = sum(p[j] * j for j in range(N)) % M
    for j in range(N):
        tmp = p[j]
        p[j] *= (n - 1)
        p[j] %= M
        p[j - j % i] += tmp
    res += (tot * pow(n, k - i)) % M

print(res % M)


ans = input()

cur = 0

def sort():
    n = 16
    b = [0 for i in range(n)]
    a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

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

    mergeSort(0, n)
    print(n)
    print(*b)

sort()


s = input()
now = 0
n = len(s)
ans = []
while (now < n) and (s[now] != '-') and (s[now] != '+'):
    ans.append(ord(s[now])-48)
    now += 1
ans.reverse()
while now < n:
    opt = s[now]
    now += 1
    a = [opt]
    while (now < n) and (s[now] != '-') and (s[now] != '+'):
        a.append(ord(s[now])-48)
        now += 1
    #print(a, ans)
    if len(a) <= len(ans):
        for i in range(len(ans)):
            if opt == '-':
                ans[i] -= ord(s[now - 1 - i])-48
            else:
                ans[i] += ord(s[now - 1 - i])-48
    else:
        for i in range(len(a) - len(ans)):
            ans.append(0)
        for i in range(len(ans)):
            if opt == '-':
                ans[i] -= ord(s[now - 1 - i])-48
            else:
                ans[i] += ord(s[now - 1 - i])-48
ret = 0
ans.reverse()
for i in range(len(ans)):
    ret = ret * 10 + ans[i]
print(ret)


n,m,k = map(int,raw_input().split())
rf=gf=False
ra = []
u = [0]*10
for i in xrange(n):
    s = raw_input()
    g,r = map(s.find,'GR')
    if r<0 or g<0:
        if r<0 and g<0 or '-' not in s: continue
        if r<0: gf=True
        else: rf=True
        continue
    for i,v in enumerate(bin(abs(r-g)-1)[:1:-1]): u[i]+=int(v)
if gf and rf: print "Draw"
else:
    if any(i%(k+1) for i in u) or gf: print "First"
    else: print "Second"


import re

class Var(object):
    def __init__(self, s):
        self.name = s
        self.ls, self.gs = set(), set()
        self.vmin, self.vmax = 0, 9
    def __repr__(self):
        return '%s(%d:%d)' % (self.name, self.vmin, self.vmax)

class Cond(object):
    def __init__(self, s, _vars):
        s = s.strip()
        i, j = 0, len(s)-1
        while i <= j and s[i] == '_':
            i += 1
        while i <= j and s[j] == '_':
            j -= 1
        if i > j or s[i:j+1].strip() not in ['<', '>']:
            print s[i:j+1]
            raise ValueError
        if s[i:j+1].strip() == '<':
            self.va, self.vb = _vars[s[:i]], _vars[s[j+1:]]
        else:
            self.vb, self.va = _vars[s[:i]], _vars[s[j+1:]]
    def __repr__(self):
        return '[%s < %s]' % (self.va, self.vb)

def topo_sort(cs):
    res = []
    for c in cs:
        c.va.gs.add(c.vb)
        c.vb.ls.add(c.va)
    hp = set([x.va for x in cs]) - set([x.vb for x in cs])
    while len(hp) > 0:
        x = hp.pop()
        res.append(x)
        for y in x.gs:
            y.ls.remove(x)
            if len(y.ls) == 0:
                hp.add(y)
        x.gs.clear()
    for c in cs:
        if len(c.vb.ls) > 0:
            return None
    for c in cs:
        c.va.gs.add(c.vb)
        c.vb.ls.add(c.va)
    for x in res:
        if len(x.ls) > 0:
            x.vmin = max([y.vmin for y in x.ls]) + 1
        else:
            x.vmin = 0
    for x in res[::-1]:
        if len(x.gs) > 0:
            x.vmax = min([y.vmax for y in x.gs]) - 1
        else:
            y.vmax = 9
    for x in res:
        if x.vmin < 0 or x.vmax > 9 or x.vmin > x.vmax:
            return None
    return res

s= raw_input()
jaw, stomach = s.split(':-')
if stomach[-1] == '.':
    stomach = stomach[:-1]
varl = list()
_vars = dict()
for x in re.findall(r'_+', jaw):
    if x not in _vars:
        _vars[x] = Var(x)
    varl.append(_vars[x])

conds = [Cond(c, _vars) for c in stomach.split(',')]
sc = topo_sort(conds)
#print _vars
#print conds
if sc is None:
    print 'false'
else:
    o = ''.join([str(x.vmin) for x in varl])
    print o


import sys
from math import factorial

def kth_perm(seq, index):
	result = []
	fact = factorial(len(seq))
	index %= fact
	while seq:
		fact = fact / len(seq)
		choice, index = index // fact, index % fact
		result.append(seq.pop(choice))
	return result

def inc_lucky(s, index):
	if index == -1:
		s = ['4'] + s
		return s
	if s[index] == '4':
		s[index] = '7'
		return s
	s[index] = '4'
	return inc_lucky(s, index - 1)

def is_lucky(s):
	for e in s:
		if e != '4' and e != '7':
			return False
	return True

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

seq = range(max(n - 12, 1), n + 1)

if k > factorial(len(seq)):
	print -1
	sys.exit(0)

seq = kth_perm(seq, k - 1)

r = 0
num = ['4']
while int(''.join(num)) < n - 12:
	r += 1
	num = inc_lucky(num, len(num) - 1)

for i, num in enumerate(seq):
	index = i + n - len(seq) + 1
	if is_lucky(str(index)) and is_lucky(str(num)):
		r += 1

print r


n=int(input())
nums=input().split(' ')
l=[0]*4
for i in range(4):
    l[i]=int(nums[i])
t=tuple(l)
a,b,c,d=t
p=[0]*(n+1)
nums=input().split(' ')
mp=[list() for _ in range(n+1)]
for i in range(2,n+1):
    p[i]=int(nums[i-2])

    mp[p[i]].append(i)
s=[0]*(n+1)
def sof(i):
    if s[i]!=0:
        return s[i]
    if len(mp[i])>0:
        res=0
        for son in mp[i]:
            res+=sof(son)
        s[i]=res
        return res
    else:
        s[i]=1
        return 1
rootofl=list()
for leaf in l:
    while p[leaf]!=1:
        leaf=p[leaf]
    rootofl.append(leaf)
rootlist=list()
for rootson in mp[1]:
    if not rootson in rootofl:
        rootlist.append(rootson)
def canpick(a,des):
    if des==0:
        return True
    picklist=rootlist[:]
    for j in range(2):
        cur=a[j]
        while p[cur]!=1:
            fa=p[cur]
            for i in mp[fa]:
                if i!=cur :
                    picklist.append(i)
            cur=fa
    v=[False]*(n+1)
    v[0]=True
    for i in range(len(picklist)):
        val=sof(picklist[i])
        if des-val>=0 and v[des-val]:
            return True
        for j in range(des,val-1,-1):
            if not v[j] and v[j-val] :
                v[j]=True
    return False

m=sof(1)
if m%2==1:
    print('NO')
else:
    v1=m//2-1-sof(rootofl[2])
    v2=m//2-1-sof(rootofl[0])
    if canpick([a,b], v1) and canpick([c,d], v2):
        print('YES')
    else:
        print('NO')


import sys
range = xrange
input = raw_input
import __pypy__
mulmod = __pypy__.intop.int_mulmod

MOD = 10**9+7
n, k = [int(x) for x in input().split()]

def f(n):
    s = 0
    for i in range(n):
        s += pow(i,k,MOD)
        s %= MOD
    return s

precalc = [0]
for i in range(k + 1):
    precalc.append((precalc[-1] + pow(i,k,MOD)) % MOD)

def interpolate(samples, x):
    x %= MOD
    m = len(samples)
    if x < m:
        return samples[x]

    modinv = [1]*m
    for i in range(2, m):
        modinv[i] = mulmod(-(MOD//i), modinv[MOD%i], MOD)

    invfac = [1]
    for i in range(1, m):
        invfac.append(mulmod(invfac[-1], modinv[i], MOD))
    invneg_fac = [invfac[i] * (1 - 2 * (i & 1)) for i in range(m)]

    xfac_down = [1]
    for j in reversed(range(x - (m - 1), x + 1)):
        xfac_down.append(mulmod(xfac_down[-1], j, MOD))

    xfac_up = [1]
    for j in range(x - (m - 1), x + 1):
        xfac_up.append(mulmod(xfac_up[-1], j, MOD))

    s = 0
    for i in range(m):
        pr = precalc[i]
        pr = mulmod(pr, xfac_down[i] * xfac_up[m - 1 - i] % MOD, MOD)
        pr = mulmod(pr, mulmod(invneg_fac[m - i - 1], invfac[i], MOD), MOD)
        s = (s + pr) % MOD
    return s
print (interpolate(precalc, n + 1) - (k == 0)) % MOD


req_arr = [int(x) for x in input().strip()]
arr = [int(x) for x in input().strip()]
required_list = [0]*10
num_list = [0]*10
for i in req_arr:
    if i == 5:
        required_list[2] += 1
    if i == 9:
        required_list[6] += 1
    else:
        required_list[i] += 1

for i in arr:
    if i == 5:
        num_list[2] += 1
    if i == 9:
        num_list[6] += 1
    else:
        num_list[i] += 1
ans = len(req_arr)
for i, j in enumerate(required_list):
    if j > 0:
        ans = min(ans, int(num_list[i]/j))
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 (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

def is_solvable(A, B, a, b):
    dr = a * a + b * b
    if dr == 0:
        return (A == 0) and (B == 0)
    else:
        return ((A * b - B * a) % dr == 0) and ((b * B + a * A) % dr == 0)

if __name__ == '__main__':
    inp = sys.stdin.readline().split(' ')
    x = inp[0]
    y = inp[1]
    inp = sys.stdin.readline().split(' ')
    A = inp[0]
    B = inp[1]
    inp = sys.stdin.readline().split(' ')
    a = inp[0]
    b = inp[1]
    a1 = is_solvable(A - x, B - y, a, b)
    a2 = is_solvable(A + x, B - y, a, b)
    a3 = is_solvable(A + x, B + y, a, b)
    a4 = is_solvable(A - x, B + y, a, b)
    if a1 or a2 or a3 or a4:
        print "YES"
    else
        print "NO"


matrix = []

def findEmpty(rs, re, cs, ce):
  for i in range(cs, ce):
    for j in range(rs, re):
      if(matrix[j][i] != '*'):
        matrix[j][i] = 'P'
        return True
  return False

def findFour():
  return findEmpty(0, 2, 3, 5)

def findThree():
  re = findEmpty(0, 2, 0, 2)
  if (re):
    return True
  re = findEmpty(0, 2, 6, 8)
  if (re):
    return True
  re = findEmpty(2, 4, 3, 5)
  return re

def findTwo():
  re = findEmpty(2, 4, 0, 2)
  if (re):
    return True
  re = findEmpty(2, 4, 6, 8)
  if (re):
    return True
  re = findEmpty(4, 6, 3, 5)
  return re

def findOne():
  re = findEmpty(4, 6, 0, 2)
  if (re):
    return True
  re = findEmpty(4, 6, 6, 8)
  return re

for i in range(6):
  a = list(input())
  matrix.append(a)

def printMatrix():
  for i in range(6):
    print(''.join(matrix[i]))

if (findFour()):
  printMatrix()
elif (findThree()):
  printMatrix()
elif (findTwo()):
  printMatrix()
elif (findOne()):
  printMatrix()


import sys
import collections

infile = sys.stdin.buffer
def gs()  : return infile.readline().rstrip()
def gi()  : return int(gs())
def gss() : return gs().split()
def gis() : return [int(x) for x in gss()]

MOD = 10 ** 9 + 7
INF = 10 ** 12
N = 10 ** 5

def main(infn="") :
    global infile
    infile = open(infn,"r") if infn else open(sys.argv[1],"r") if len(sys.argv) > 1 else sys.stdin
    ######################################################################
    n,m = gis()
    mem = {}
    def dfs(u):
        if u <= 1:
            return u
        if u in mem:
            return mem[u]
        ans = sum([dfs(v) for v in range(1, u)])
        for z in range (2, u+1):
            ans += dfs(u//z)
            ans %= m
        mem[u] = ans
        return ans
    #w = [dfs(u) for u in range(0, n+1)]

    dp = [0 for _ in range(n+1)]
    dp[1] =1
    h = collections.defaultdict(collections.deque)
    cumul = 0
    prev = dp[1]
    for u in range(2, len(dp)):
        dp[u] += prev
        dp[u] += dp[1]
        dp[u] %= m
        while(h[u]):
            sign = 1 if h[u][0] > 0 else -1
            cumul += sign * dp[abs(h[u].popleft())]
            cumul %= m
        dp[u] += cumul
        dp[u] %= m
        prev += dp[u]
        prev %= m

        v,c = u<<1, 2
        h[u + 1].append(1)
        while(v < len(dp)):
            h[v].append(c)
            h[v].append(-(c-1))
            v += u
            c += 1
    print (dp[-1])

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


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


from sys import exit
n, m = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
k = [int(i) for i in input().split()]
for i in range(n):
    for j in range(i + 1, n + 1):
        cur = a[i:j]
        f = 1
        for l in range(m):
            f &= (cur.count(l + 1) == k[l])
        if f:
            print("YES")
            exit(0)
print("NO")


ef solve(n, st, k):
    MOD = int(1e9 + 7)
    dp = [0] * (n + 1)
    prefix_sum = [0] * (n + 1)
    dp[st] = 1
    for times in range(k):
        prefix_sum[0] = 0
        for i in range(1, n + 1):
            prefix_sum[i] = prefix_sum[i - 1] + dp[i]
            if prefix_sum[i] >= MOD: prefix_sum[i] -= MOD
        for i in range(1, n + 1):
            t = prefix_sum[n] - prefix_sum[i] + prefix_sum[i - 1] - prefix_sum[i >> 1]
            while t < 0: t += MOD
            while t >= MOD: t -= MOD
            dp[i] = t
    return sum(dp) % MOD

def main():
    n, a, b, k = [int(i) for i in input().split()]
    if a > b:
        print(solve(n - b, a - b, k))
    else:
        print(solve(b - 1, b - a, k))

main()


mod = 1000000007
def sum(x,y,k,add) :
    if k<add:
    	return 0
    up=x+add
    if up>k:
    	up=k
    add=add+1
    return y*(((add+up)*(up-add+1)//2)%mod)%mod
def solve(x,y,k,add=0) :
    if x==0 or y==0:
    	return 0
    if x>y:
    	x,y=y,x
    pw = 1
    while (pw*2)<=y:
    	pw*=2
    if pw<=x:
    	return (sum(pw,pw,k,add)+sum(pw,x+y-pw-pw,k,add+pw)+solve(x-pw,y-pw,k,add))%mod
    else:
    	return (sum(pw,x,k,add)+solve(x,y-pw,k,add+pw))%mod
q=input()
for i in range(0,q):
    x1,y1,x2,y2,k=map(int,raw_input().split())
    ans=(solve(x2, y2, k)-solve(x1 - 1, y2, k)-solve(x2, y1 - 1, k)+solve(x1-1,y1-1,k))%mod
    if ans<0:
    	ans+=mod
    print ans


n, k = map(int, input().split())
string = input()
series = []
now = ""
for elem in string:
    if elem == "Y":
        if now:
            series.append(now)
        now = ""
    else:
        now += elem
if now:
    series.append(now)

answer = False
no_max = True
for elem in series:
    m = len(elem)
    for i in range(m - k + 1):
        if (not i or elem[i - 1] == '?') and ((i + k - 1) == m - 1 or elem[i + k] == '?'):
            answer = True

    counter = 0
    for letter in elem:
        if letter == 'N':
            counter += 1
            no_max = not counter > k
        else:
            counter = 0

print("YES" if answer and no_max else "NO")


n=int(input())
arr=list(map(int,input().split()))
freq=[0]*(101)
for i in arr:
  freq[i]+=1
freq2=[0]*(101)
ans=0
k1=3
j=0
for i in range(n):
  freq2[arr[i]]+=1
  if i>=1:
    freq3=[]
    for k in range(1,101):
     if freq2[k]>=1:
      freq3.append(freq2[k])
    #print(freq3)
    if freq3.count(max(freq3))>=3:
      ans=max(ans,i+1)
freq2=[0]*101
for j in range(n):
  freq2[arr[j]]+=1
  freq3=[]
  for k in range(1,101):
   if freq[k]>=1:freq3.append(freq[k]-freq2[k])
  #print(freq3,j+1)
  if max(freq3)>0 and freq3.count(max(freq3))>=2:
      ans=max(ans,n-j-1)
      #print()
      break
print(ans)


MOD = 1000000007
def phi(n):
    res = n
    for i in range(2,int(n**(0.5)+1)):
        if n % i == 0:
            while n % i == 0:
                n = n//i
            res -= res//i
    if n > 1:
        res -= res//n
    return res

n,k = map(int,input().split())
k = (k+1)//2
ans = n
for _ in range(k):
    if ans > 1:
        ans = phi(ans)
    else:
        break
print(ans % MOD)


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 'poisson'
    else:
        return 'uniform'

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

for seq in seqs:
    print int(mean(seq))


n = 0
k = 0
t = 0
P = {}
used = []

def third(x, n=2):
    for i in x:
        yield i[n]

def solve():
    global n, k, t, P, used
    read = reader()
    n, k, t = list(map(int, next(read).split()))
    t -= 1
    for i in range(n):
        P[i] = []
    used = [False] * n
    for i in range(k):
        m1, m2, r = list(map(int, next(read).split()))
        P[m1-1].append((m2-1, r))
    comb = []
    rec(0, comb)
    comb.sort(key=lambda x: sum(third(x)))
    comb.insert(0, (-1, -1, 0))
    print(sum(third(comb[t])))

def rec(i, comb, currentpairs = None):
    global n, k, t, P, used
    if not i < n:
        return
    if currentpairs == None:
        currentpairs = []
    for (m2, r) in P[i]:
        if used[m2]:
            continue
        used[m2] = True
        cp = currentpairs[:]
        cp.append((i, m2, r))
        comb.append(cp)
        rec(i+1, comb, cp)
        used[m2] = False

def reader():
    USE_FILE = False
    if __name__ == "__main__" and USE_FILE:
        with open("F.in", "r") as fin:
            while True:
                yield next(fin)
    else:
        try: input = raw_input
        except: pass
        while True:
            yield input()

solve()


def main():
    ans = 0
    a = [0] * 10
    n = int(input())
    for i in range (1, 9):
        a[i] = n // 9 + int(n % 9 >= i)
    a[9] = n // 9

    for i in range(1, 10):
        for j in range(1, 10):
            k = i * j % 9
            if k == 0:
                k = 9
            ans += a[i] * a[j] * a[k]

    for i in range(1, n + 1):
        ans -= n // i
    print(ans)

    return

if __name__ == "__main__":
    main()


#!/usr/bin/python
import re, sys
n = int (sys.stdin.readline ())
class MyInt (object):
	def __init__ (self, a):
		if isinstance (a, MyInt):
			self.v = a.v
		else:
			self.v = int (a)
	def val (self):
		return self.v
	def __add__ (self, a):
		return MyInt ((self.val () + a.val ()) & 32767)
	def __sub__ (self, a):
		return MyInt ((self.val () - a.val ()) & 32767)
	def __mul__ (self, a):
		return MyInt ((self.val () * a.val ()) & 32767)
	def __div__ (self, a):
		return MyInt ((self.val () / a.val ()) & 32767)
	def __eq__ (self, a):
		return self.val () == a.val ()
	def __gt__ (self, a):
		return self.val () > a.val ()
	def __lt__ (self, a):
		return self.val () < a.val ()
	def __and__ (self, a):
		return MyInt (self.val () & a)
s = ''.join (sys.stdin.readlines ())
s = s.replace ('\n', '')
s = s.replace ('{', '')
s = s.replace ('}', '')
s = re.sub ('([0-9]+)', 'MyInt (\\1)', s)
s = s.replace ('int f(int n)', \
 'a = [-1] * 32768\ndef f (n):\n\tglobal a;' + \
 'n = MyInt (n);if (a[n.val ()] != -1) return a[n.val ()];')
s = re.sub ('return(.*?);','return MyInt (\\1);', s)
s = s.replace (';', '\n\t')
s = s.replace ('return', ':return')
s = re.sub ('\t[ :]+', '\t', s)
s += '\n'
s += 'k = -1\n'
s += 'for i in range (32768):\n'
s += '\ta[i] = f (i).val () & 32767\n'
s += 'for i in range (32768):\n'
s += '\tif a[i] == n:\n'
s += '\t\tk = i\n'
s += 'print k\n'
s = s.replace ('\t\n', '\n')
exec s


def solve(a, b):
  r = []
  while a+b > 2:
    q = min((a//b + b//a), max(a, b)-1)
    r.append(str(q))
    if a > b:
      r.append('A')
      a -= b*q
    else:
      r.append('B')
      b -= a*q
  if a != 1 or b != 1:
    return 'Impossible'
  return ''.join(r)

def main():
  a, b = map(int, input().split())
  print(solve(a, b))

main()


from collections import defaultdict

def calcBinomials(N):
    global binom
    binom = [[0]*N for _ in range(N+1)]
    for n in range(N):
        binom[n][0] = binom[n][n] = 1
        for k in range(1, n):
            binom[n][k] = binom[n-1][k] + binom[n-1][k-1]

n = int(input())
calcBinomials(n)
a = list(map(int, input().split()))
dp = [defaultdict(lambda: 0) for _ in range(sum(a)+1)]
dp[0][0] = 1
cnt = {_:a.count(_) for _ in a}
for x in a:
    for i in range(len(dp)-1-x, -1, -1):
        for k, v in dp[i].items():
            dp[i+x][k+1] += v
res = 0
for x, c in cnt.items():
    for i in range(1, c+1):
        if dp[x*i][i] == binom[c][i]: res = max(res, i)
print(res)


M, a, b = map(int, input().split())
mod = 10**9+7
D = [mod]*a
maxi = 0
D[0] = 0
Q = [0]
def f(x, i):
    t = (x+1-i)//a
    r = (x+1-i)%a
    return a*t*(t+1)//2+r*(t+1)

while Q:
    q = Q.pop()
    D[q] = maxi
    k = max(0, -((-(b-q))//a))
    maxi = max(maxi, q+k*a)
    if D[(q-b)%a] == mod and maxi <= M:
        Q.append((q-b)%a)
ans = 0
for i, d in enumerate(D):
    if d > M:
        continue
    ans += f(M, i) - f(d-1, i)
print(ans)


def solve(n):
    k = 0
    a = b = 1
    while b < n:
        a, b = b, a + b
        k += 1
    if b == n:
        return k
    elif n % 2:
        return n // 2 + 1
    else:
        return n - 1

if __name__ == "__main__":
    ans = solve(int(input()))
    print(ans)


def readints():
  return map(int, raw_input().split())

def dn(x):
  k=0
  t=x-1
  while t:
    t/=10
    k+=1
  return k

def _li(x, dn):
  ret=[]
  for _ in xrange(dh):
    ret.append(x%10)
    x/=10
  return ret

def li(h,m):
  return _li(h,dh)+_li(m,dm)

def dif(h1,m1,h2,m2):
  return sum(v1!=v2 for v1,v2 in zip(li(h1,m1), li(h2,m2)) )

pow10=[10**i for i in xrange(12,-1,-1)]

memo={}

def g(h,m):
  if (h,m) in memo:return memo[(h,m)]
  ret=f(0,1,h,m)+(1>=k)
  memo[(h,m)]=ret
  return ret

def f(h1,m1,h2,m2):
  if (h1,m1)==(h2, m2):return 0
  if (h1,m1)>(h2,m2):
    return f(h1, m1, H-1, M-1) + f(0, 0, h2, m2) + ( dif(h1,m1,h2,m2) >= k)
  for hh in pow10:
    if (h1+hh, m1)<=(h2, m2) and h1/hh%10!=9:
      return g(hh,0)+f(h1+hh, m1, h2, m2)
  for mm in pow10:
    if m1+mm<M and (h1,m1+mm)<=(h2,m2) and m1%mm%10!=9:
      return g(0,mm) + f(h1,m1+mm, h2, m2)

  if h1*M+m1+1!=h2*M+m2:
    print h1,m1,h2,m2
  return dif(h1,m1,h2,m2)>=k

def main():
  global H,M,k,dh,dm
  H,M,k=readints()
  h1,m1=readints()
  h2,m2=readints()
  """H,M,k=24,60,1
  h1,m1=0,0
  h2,m2=23,59
  H,M,k=24,60,3
  h1,m1=23,59
  h2,m2=23,59"""
  dh=dn(H)
  dm=dn(M)
  print f(h1,m1,h2,m2)

main()


import math
x=input()
print((0,1)[(1<<int(math.log(x*6,2)))-x*3<6])


def DFS(x):
    for i in range(x):
        if(Seen[i]):
            continue
        if(Rem[i]>=C[x]):
            Rem[i]-=C[x]
            Parent[x]=i
            Children[i].append(x)
            return True
    for i in range(x):
        if(Seen[i]):
            continue
        Y=[]
        Seen[i]=True
        for j in range(len(Children[i])):
            child=Children[i][j]
            Parent[child]=-1
            Rem[i]+=C[child]
            if(DFS(child)):
                continue
            Parent[child]=i
            Rem[i]-=C[child]
            Y.append(child)
        Seen[i]=False
        Children[i]=list(Y)
        if(Rem[i]>=C[x]):
            Rem[i]-=C[x]
            Children[i].append(x)
            Parent[x]=i
            return True
    return False

n=int(input())

C=list(map(int,input().split()))
Rem=[-1]*n
Parent=[-1]*n
Children=[]
Seen=[False]*n
C.sort(reverse=True)

if(C[0]!=n or C.count(2)>0):
    print("NO")

else:
    for i in range(n):
        Rem[i]=C[i]-1
        Children.append([])
    Parent[0]=0
    Ans="YES"
    for i in range(1,n):
        if(DFS(i)==False):
            Ans="NO"
            break
    for i in range(n):
        if(Rem[i]!=0 and C[i]!=1):
            Ans="NO"
            break
    print(Ans)


from itertools import combinations

def getLuckySubsetCount(mStr, luckySubset):
    width = len(mStr)
    A = map(lambda x: [0,0,0], range(width))
    for i in range(width):
        A[i][0] = 8 if not (i in luckySubset) else 2
        A[i][1] = len(filter(lambda x: ((x != 7 and x != 4) if not (i in luckySubset) else (x == 7 or x == 4)) and (x <= mStr[i]), range(10)))
        A[i][2] = max(filter(lambda x: ((x != 7 and x != 4) if not (i in luckySubset) else (x == 7 or x == 4)) and (x <= mStr[i]), range(10))) == mStr[i]
    print luckySubset, A
    B = map(lambda x: [0,0], range(width))
    for i in range(width):
        if i == 0:
            B[i][0] = A[i][0]
            B[i][1] = (A[i][1] - 1) + (1 if A[i][2] else 0)
        else:
            B[i][0] = B[i - 1][0] * A[i][0]
            B[i][1] = (A[i][1] - 1) * B[i - 1][0] + (B[i - 1][0] if A[i][2] else 0)
    return B[width - 1][1]

def getLuckyCount(mStr, luckySize):
    maxWidth = len(mStr) + 1
    result = 0
    for combination in combinations(range(maxWidth), luckySize):
        luckySubset = set(combination)
        result += getLuckySubsetCount(mStr, luckySubset)
    return result

def main():
    mStr = raw_input()
    m = int(mStr)
    lucky = [0] * 10
    for luckySize in range(9):
        lucky[luckySize] = getLuckyCount(mStr, luckySize)
    print lucky

if __name__ == '__main__':
    main()


#Built without using CH-Helper plugin ( •_•)>⌐■-■ / (⌐■_■) deal with it
import math
n=int(input())
if n==0:
    print 1
else:
    k=4*(int(n*math.sqrt(2)+1e-9))
    print k


dp = [[0 for i in range(0..40)]for j in range(0..40)]
N,H = map[int,raw_input().split()]
dp[0] = [1 for i in range(0..40)]
for i in range(1..40):
	for j in range(1..40):
		for k in range(0..i):
			dp[i][j] += dp[k][j-1]*dp[i-1-k][j-1]
print dp[N][N] - (H > 0 and dp[N][H-1] or 0)


import math

def euclid_algorithm(a, b):
    t1, t2 = abs(a), abs(b)
    #saving equalities:
    #t1 == x1 * a + y1 * b,
    #t2 == x2 * a + y2 * b.
    x1, y1, x2, y2 = int(math.copysign(1, a)), 0, 0, int(math.copysign(1, b))
    if t1 < t2:
        t1, t2 = t2, t1
        x1, y1, x2, y2 = x2, y2, x1, y1

    while t2 > 0:
        k = int(t1 // t2)
        t1, t2 = t2, t1 % t2
        #t1 - k * t2 == (x1 - k * x2) * a + (y1 - k * y2) * b
        x1, y1, x2, y2 = x2, y2, x1 - k * x2, y1 - k * y2

    return t1, x1, y1

def opposite_element(x, p):
    gcd, k, l = euclid_algorithm(x, p)
    if gcd != 1:
        return -1
    return k % p

def solve(n, m, p):
    if (m-1) % p == 0:
        return (n + 1) * pow(m, n, p) % p
    else:
        S = pow(m, n, p)
        k = opposite_element(m, p)
        l = (2*m - 1) * k % p
        q = opposite_element(l - 1, p)
        S += pow(m, n, p) * (pow(l, n, p) - 1) * q
        S %= p
        return S

p = 10 ** 9 + 7
n, m = [int(x) for x in input().split()]
print(solve(n, m, p))


import sys
def ask(s):
    print(s)
    sys.stdout.flush()
def solve():
    n, k = map(int, input().split())
    head = [True] * (n + 1)
    head[0] = False
    if k == 1:
        N = 2 * int(n / (k + 1))
    else:
        N = 2 * int(n / k)
    for i in range(1, N + 1):
        cl = (i - 1) * int((k + 1) / 2) + 1
        cr = i * int((k + 1) / 2)
        for j in range(1, i):
            l = (j - 1) * int((k + 1) / 2) + 1
            r = j * int((k + 1) / 2)
            ask("R")
            for shop in range(l, r + 1):
                ask("? " + str(shop))
                ans = input()
                if (ans == "Y"):
                    head[shop] = False
            for shop in range(cl, cr + 1):
                ask("? " + str(shop))
                ans = input()
                if (ans == "Y"):
                    head[shop] = False

    ans = 0
    ans = sum(map(int, head))
    ask("! " + str(ans))
solve()


#coding=utf-8

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

t = 0;

C = 1
total = 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
else:
  print (C - total + MOD) % MOD


v = [[] for i in xrange(12)]
str = raw_input().split()
n = int(str[0])
m = int(str[1])
k = int(str[2])
for i in xrange(n):
    raw_input()
    for j in xrange(m):
        tuple = map(int,raw_input().split());
        v[i].append(tuple)

mx =0
for i in xrange(n):
    for j in xrange(n):
        val=0
        if(i==j):continue
        pro = []
        for kk in xrange(len(v[i])):
            if(v[j][kk][1] <= v[i][kk][0]): continue
            pro.append((v[j][kk][1] - v[i][kk][0], v[i][kk][2]))

        lim = k;
        pro.sort(cmp=None, key=None, reverse=True)
        for kk in xrange(len(pro)):
            if(pro[kk][1] <= lim):
                    lim -= pro[kk][1];
                    val += pro[kk][0]*pro[kk][1];

            else:
                     val += pro[kk][0]*lim;
                     break;

        mx = max(mx,val)

print mx


from fractions import Fraction

g = [0]*111111
t = [0]*111111
prime = [0]*111111
pm = [0]*111111
for i in range(len(prime)):
    prime[i] = {}

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

def ksm(a, b, p=int(1e9+7)):
    a = a % p
    ans = 1
    while b > 0:
        if b & 1:
            ans = ans * a % p
        b = b >> 1
        a = a*a % p
    return ans

m = int(input())
p = int(1e9+7)
tmp = ksm(m, p-2)
for j in range(m, 0, -1):
    c1 = 0
    tyouce = tmp
    gyouce = 0
    if j == 1:
        c1 = 0
    else:
        c1 = m//j * tmp % p

    for k in range(2, m//j + 1):

        def get_ck(m, n):
            ans = 0

            def get_fac():
                for i in range(2, 100011):
                    if pm[i] == 0:
                        prime[i][i] = 1
                        for j in range(2, 100001//i+1):
                            pm[i*j] = 1
                            prime[i*j][i] = 1

            if prime[m] == {}:
                get_fac()
            prime_list = list(prime[m].keys())
            for i in range(1, 1 << len(prime_list)):
                t = i
                rongchixishu = -1
                lcm = 1
                index = len(prime_list)-1
                while t>0:
                    if t&1:
                        lcm = lcm*prime_list[index]
                        rongchixishu *= -1
                    t >>= 1
                    index -= 1
                ans += n//lcm*rongchixishu
            return ans

        ck = (m//j - get_ck(k, m//j)+p) % p
        ck = ck*tmp % p
        tyouce = (tyouce + ck * t[k*j]) % p
        gyouce = (gyouce + ck * (t[k*j] + g[k*j])) % p
    t[j] = tyouce * ksm(1-c1+p, p-2) % p
    gyouce = (gyouce + tmp + c1 * t[j]) % p
    g[j] = gyouce * ksm(1-c1+p, p-2) % p

print(g[1])


n=int(input())
lookup={}
for i in range(n):
    x=list(map(int,input().split()))
    for j in range(n):
        lookup[x[j]]=(i,j)
rook=[0,0]
bish=[0,0]
knight=[0,0]
for i in range(1,n**2):
    x=abs(lookup[i][0]-lookup[i+1][0])
    y=abs(lookup[i][1]-lookup[i+1][1])
    if x==0 or y==0:
        rook[0]+=1
    else:
        rook[0]+=2
    if x==y:
        bish[0]+=1
    elif (x-y)%2==0:
        bish[0]+=2
    else:
        bish[0]+=1000
    if {x,y}=={1,2}:
        knight[0]+=1
    elif x**2+y**2 in [4,16,20,10,18]:
        knight[0]+=2
    elif x**2+y**2==2 and lookup[i] not in [(0,0),(n-1,0),(0,n-1),(n-1,n-1)] and lookup[i+1] not in [(0,0),(n-1,0),(0,n-1),(n-1,n-1)]:
        knight[0]+=2
    elif {x,y} in [{5,0},{3,0},{1,0},{6,1},{4,1},{5,2},{3,2},{6,3},{4,3},{5,4}]:
        knight[0]+=3
    else:
        knight[0]+=1000
    if bish[0]>rook[0]+1 or bish[0]>knight[0]+1:
        if rook[0]==knight[0]:
            bish=[rook[0]+1,min(rook[1],knight[1])+1]
        elif rook[0]<knight[0]:
            bish=[rook[0]+1,rook[1]+1]
        else:
            bish=[knight[0]+1,knight[1]+1]
    if knight[0]>rook[0]+1 or knight[0]>bish[0]+1:
        if rook[0]==bish[0]:
            knight=[rook[0]+1,min(rook[1],bish[1])+1]
        elif rook[0]<bish[0]:
            knight=[rook[0]+1,rook[1]+1]
        else:
            knight=[bish[0]+1,bish[1]+1]
    if rook[0]>bish[0]+1 or rook[0]>knight[0]+1:
        if bish[0]==knight[0]:
            rook=[bish[0]+1,min(knight[1],bish[1])+1]
        elif bish[0]<knight[0]:
            rook=[bish[0]+1,bish[1]+1]
        else:
            rook=[knight[0]+1,knight[1]+1]
best=(rook[0],bish[0],knight[0])
if min(best)==best[0]:
    print(rook[0],rook[1])
elif min(best)==best[1]:
    print(bish[0],bish[1])
else:
    print(knight[0],knight[1])


mod=10**9+7
N,M,K,R,C=map(int,input().split())
AX,AY,BX,BY=map(int,input().split())
Z=0
if AX+R>BX and AY+C>BY:
  Z=(AX+R-BX)*(AY+C-BY)
V=N*M-R*C*2+Z
print(pow(K,V+R*C-Z,mod))


n = int(input())
sz = len(str(n))
def get(x):
    ans = 0
    nw = 1
    x1 = x
    for i in range(sz):
        x = x1
        if x < nw:
            while x < nw: x *= 10
            x -= 1 #тк сука [1;x)
        else:
            while x >= nw * 10: x //= 10
        x = min(x, n)
        ans += x - nw + 1
        nw *= 10
    return ans

MOD = 998244353

ans = 0
i = 1
while i <= n:
    l = i
    r = min(n, 10 ** (len(str(i))) - 1) + 1
    nw = (get(i) - i) // MOD
    while r - l > 1:
        mid = (l + r) // 2
        x = (get(mid) - mid) // MOD
        if nw == x:
            l = mid
        else:
            r = mid
    ans += nw * (r - i)
    # i += 1
    i = r
print((ans * -MOD) % (int)(1e9 + 7))


import sys
from random import randint
from math import sqrt

mul=[]
rand=[]
SIZE = 32

def checkTypeZwei(base,div):
	for i in xrange(SIZE):
		if(int(mul[i])%div==0):
			return i
	return -1

def checkTypeDrei(base,div):
	for num in rand:
		sum=0
		for ch in num:
			sum+=ord(ch)-ord('0')
		if(sum%div!=0): return False

	return True

def checkTypeElf(base,div):
	for i in xrange(SIZE):
		num=rand[i]
		eve=0
		odd=0
		ind=0
		for ch in num:
			if(ind&1):
				odd+=ord(ch)-ord('0')
			else:
				eve+ord(ch)-ord('0')
			ind+=1

		if(odd!=eve):
			return False

	return True

def checkTypeSechs(base,div):
	for i in xrange(1,int(sqrt(div))):
		if(div%i==0):
			a=div/i
			b=i

			if(checkTypeZwei(base,a)!=-1 or checkTypeDrei(base,a) or checkTypeElf(base,a)):
				a=True
			else:
				a=False

			if(checkTypeZwei(base,b)!=-1 or checkTypeDrei(base,b) or checkTypeElf(base,b)):
				b=True
			else:
				b=False

			if(not (a and b)):
				return False

	return True

def xBase(num,base):
	res=''
	while(num):
		res=str(num%base)+res
		num/=base
	return '0' if(res=='') else res

if(__name__=='__main__'):

	instr=raw_input()
	instr=instr.split()
	base=int(instr[0])
	div=int(instr[1])

	for i in xrange(SIZE):
		mul.append(str(base**i))

	for i in xrange(SIZE):
		num=randint(0,1<<16)
		num*=div
		#print xBase(num,base)
		rand.append(xBase(num,base))
	type=7
	len=-1
	if(type==7):
		len=checkTypeZwei(base,div)
		if(len!=-1):
			type=2

	if(type==7):
		if(checkTypeDrei(base,div)):
			type=3

	if(type==7):
		if(checkTypeElf(base,div)):
			type=11

	if(type==7):
		if(checkTypeSechs(base,div)):
			type=6

	print(str(type)+'-type')
	if(type==2):
		print len


#     Clever Fat Rat
import time
from datetime import datetime

def is_goal(state):
    (a, ws) = state
    if(len(ws) == 1 and ws[0][0] <= a[0]):
        return True

def child(state):
    (a, ws) = state
    scales = ws[0]
    if(len(ws) == 1):
        return [];

    b = [[0]*(len(scales)-1)]
    for (jdx, scale) in enumerate(scales):
        if a[jdx] >= scale:
            if(jdx == 0):
                b = map(lambda x: [x[0]+a[jdx]] + x[1:], b)
#                b[0] += a[jdx]
            elif (jdx == len(scales)-1):
                b = map(lambda x:  x[:-1]+[x[-1]+a[-1]], b)
#                b[-1] += a[-1]
            else:
                b = map(lambda x:  [x[:jdx]+[x[jdx]+a[jdx]]+x[jdx+1:], x[:jdx-1]+[x[jdx-1]+a[jdx]]+x[jdx:]], b)
                b = reduce (lambda a,b: a+b, b)
#                b[jdx-1] += a[jdx]/2.
#                b[jdx] += a[jdx]/2.
#    print b
    return map(lambda x: (x, ws[1:]), b)

def is_possible_reach_goal(state):
#    print state
    (a, ws) = state
    return (sum(a) >= ws[-1][0])

def is_broken(i, a, ws):
    return 1 if (a[i] >= ws[0][i]) else 0

def fall(idx, a, ws):
    return a[idx]  * is_broken(idx, a, ws)

def check_break(a, ws):
    break_list = [[0,0]]
    for idx in range(0, len(a)-1):
        break_list += [[0,0]]
        if(fall(idx, a, ws) + fall(idx+1, a, ws) >= ws[1][idx]):
            break_list[idx][1] = is_broken(idx, a, ws)
            break_list[idx+1][0] = is_broken(idx+1, a, ws)
    return break_list

def next_step(a, break_list):
    next_step = [[]]
    for idx, b in enumerate(break_list):
        if b == [0,0]:
            next_step = map((lambda x: x+[0]), next_step)
        elif b == [0,1]:
            next_step = map((lambda x: x+[a[idx]]), next_step)
        elif b == [1,0]:
            next_step = map((lambda x: x[:-1] + [x[-1]+a[idx]] +[0]), next_step)
        else:   # [1,1]
            next_step = map((lambda x: [x[:-1] + [x[-1]+a[idx]] +[0], x+[a[idx]]]), next_step)
            next_step = reduce (lambda a,b: a+b, next_step)
    return map(lambda x: x[:-1],next_step)

def fatrat(state):
#    print state
    (a, ws) = state

#15[928772, 710357, 920822, 465694, 16512, 799572, 971974, 162499, 157133, 294992, 241747, 325056, 798852, 528918, 760749, 755326, 867061, 621152, 114485, 917241, 244803, 775595, 547781, 427681, 292956, 933798, 764221]
#[406560, 631571, 780422, 992747, 90450...

    if len(a) == 42:
        for idx in range(16,40):
            print ws[idx]

#        print ws[2][21:41]
#        print ws[3][0:20]
#        print ws[3][20:40]
#        print ws[4][0:20]
#        print ws[4][20:39]

        print ws

    a_list = [a]
    while(True):
        if len(ws) == 1:
            for e_a_list in a_list:
                if e_a_list[0] >= ws[0][0]:
                    return "Cerealguy"
            return "Fat Rat"

        a_list = map((lambda a: next_step(a, check_break(a, ws))), a_list)
        a_list = reduce (lambda a,b: a+b, a_list)

        new_list = []
        for e_a_list in a_list:
            if e_a_list not in new_list:
                if sum(e_a_list) >= ws[-1][0]:
                    new_list.append(e_a_list)

        a_list = new_list
        ws = ws[1:]

        if not len(a_list):
            return "Fat Rat"

def fatrat2(state):
    stack = [state]
    visited = []
    start = datetime.now()

    while(stack):

        state = stack.pop()
        visited += [state[0]]

        if(is_goal(state)):
            return "Cerealguy"

        children = child(state)
        for c in children:
            if(c[0] not in visited and c not in stack):
                if is_possible_reach_goal(c):
                    stack += [c]

    return "Fat Rat"

Debug = False
if(not Debug):
    n = int(raw_input())
    a_s = raw_input().split()
    a = []
    for a_s_e in a_s:
        a += [int(a_s_e)]

    ws = []
    for i in range(0, int(n)):
        r = raw_input().split()
        rs = []
        for e_rs in r:
            rs += [int(e_rs)]
        ws += [rs]
#    print fatrat(n, a, ws)
    print fatrat(((a, ws)))
else:
    print fatrat(([1], [[2]]))   #F
    print fatrat(([2, 2], [[1, 2],[4]]))   #C
    print fatrat(([2, 2], [[1, 2],[5]]))   #F
    print fatrat(([798097, 886901, 292688, 792934], [[987579, 447910, 689959, 311317],[41624, 797440, 706737],[921438, 988902],[506461]]))   #C
    a =( [232602, 103849, 827367, 389557, 651438, 216320, 824798, 525699, 23338, 518302, 719391, 553814, 331160, 617684, 289434, 312706, 618709, 259095, 21269, 998945, 461731]
    + [896427, 149781, 499724, 6493, 239022, 333269, 513014, 671173, 502655, 287667, 863972, 857850, 644809, 824618, 402957, 617413, 295280, 915642, 78666, 498130, 693142])
    #0
    w0=( [442788, 122361, 376827, 1098, 885713, 765876, 370112, 54990, 458771, 438057, 765395, 895171, 272899, 408086, 963600, 961459, 805320, 99236, 780298, 932795, 511481]
     [195036, 855105, 514771, 711514, 234442, 539631, 644411, 463491, 112557, 217985, 629316, 185503, 888215, 728675, 175993, 704847, 245992, 469172, 819496, 608942, 786465])
    W1=( [604957, 444979, 92612, 722708, 474069, 634935, 49008, 727286, 15642, 757260, 163229, 242680, 662984, 151936, 302866, 970105, 42818, 86986, 542819, 152685])
    #+ [614993, 744625, 774390, 147357, 217239, 448556, 977399, 440373, 650208, 929115, 60946, 434417, 20...
    w2=( [103072, 936498, 847907, 650645, 566772, 244240, 76487, 607887, 833591, 261100, 535448, 472137, 921365, 782021, 699092, 571729, 884498, 898861, 570530, 8136, 278423, 614993, 744625, 774390, 147357, 217239, 448556, 977399, 440373, 650208]
    + [929115, 60946, 434417, 203564, 373657, 245610, 284531, 327005, 518126, 979469])

    w3= ([415376, 150228, 72136, 403305, 640672, 652152, 214427, 737311, 208036, 769173, 693842, 421040, 183828, 647456, 73520, 674069, 253765, 239577, 992072, 247531, 5556, 775497, 835157, 659594, 777970, 399659, 357111, 242550, 765227, 396071]
    + [337931, 684782, 912212, 59641, 407013, 892962, 529009, 168624, 729261])

    w4=([579778, 603392, 7187, 711763, 980786, 891205, 187614, 347504, 871321, 16499, 165802, 430266, 767897, 943796, 838570, 489956, 126553, 519253, 411089, 156752, 209661, 853585, 233490, 370034, 817847, 507577, 999103, 22978, 790519, 52028]
    +[728211, 18397, 740606, 627417, 513419, 851193, 795920, 975646])

    w5=([364270, 878531, 313352, 760219, 57774, 979287, 495749, 821992, 400807, 118875, 624706, 11664, 398468, 399161, 480516, 516761, 361857, 676791, 254124, 676721, 383882, 346228, 368172, 543223, 372419, 89729, 450007, 183906, 578337, 782425]
    +[239888, 133714, 848309, 211198, 276004, 422001, 342793])

    w6=(
    [669810, 70004, 223430, 545763, 495696, 659851, 458070, 320934, 70213, 2510, 670903, 398360, 955053, 229649, 10354, 681727, 93774, 345990, 810132, 724068, 178347, 919760, 900818, 664569, 731142, 68854, 562838, 348118, 412534, 711858]
    +[217450, 390687, 476960, 552361, 384448, 269506])

    w7= ([686869, 943862, 411867, 608029, 563528, 355743, 650398, 806908, 984874, 442601, 965871, 224704, 395748, 333576, 560520, 44827, 222000, 210286, 63258, 240375, 156949, 653188, 279453, 955766, 955005, 475318, 105273, 315988, 259444, 554025]
    +[169162, 673513, 337343, 217480, 802836])

    w8=([524812, 846231, 854588, 192451, 593937, 58689, 804666, 287964, 117042, 310411, 495542, 750086, 835403, 781732, 699317, 778671, 275391, 903769, 90240, 110812, 176953, 320104, 584756, 341201, 623117, 929603, 391734, 803929, 440316, 17762]
    +[349381, 33395, 717334, 254917])

    w9=([852392, 358681, 885946, 1989, 714822, 291374, 275129, 793814, 698964, 135683, 654809, 411164, 475752, 828614, 173173, 465830, 881709, 429319, 942530, 613387, 394352, 150504, 429484, 432671, 47638, 720929, 915486, 178642, 362160, 697774]
    +[582177, 990694, 63463])

    w10=([775829, 967068, 76364, 48338, 231255, 628921, 800537, 721127, 331827, 449577, 987306, 400525, 752721, 529533, 823633, 106767, 436626, 205685, 547258, 868397, 522545, 178774, 793439, 158477, 194198, 537780, 714979, 545295, 240759, 136464]
    +[342543, 669949])

    w11=([395243, 682010, 637544, 537377, 568397, 939159, 617065, 455601, 589065, 520285, 39074, 59942, 70214, 98748, 330093, 61675, 314160, 4343, 820744, 569072, 156641, 964848, 619284, 939421, 248299, 973729, 72425, 651620, 337476, 228294]
    +[446228])
    w12 = [733423, 120527, 880793, 28654, 481273, 936515, 808693, 646362, 891193, 526586, 645212, 971930, 320632, 217240, 232724, 519503, 911492, 119638, 207340, 834315, 393853, 595370, 182300, 154260, 490060, 679573, 469578, 931192, 795252, 794504]
    w13 = [992937, 935048, 234752, 790452, 581692, 261170, 364764, 938989, 760569, 392383, 343936, 652090, 226824, 806565, 456839, 687163, 528042, 195594, 873694, 66359, 594999, 965206, 59095, 345665, 918463, 273203, 35037, 899079, 842258]
    w14=[529636, 112898, 877687, 806044, 60735, 189749, 160846, 725032, 512840, 609679, 511, 993861, 575660, 560076, 254140, 79046, 330071, 166742, 370339, 396898, 344306, 315773, 868616, 819708, 981564, 686084, 252763, 573950]
    #[928772, 710357, 920822, 465694, 1...


import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def bit(xx):return [format(x,"b") for x in xx]
popcnt=lambda x:bin(x).count("1")
def ask(m):
    print("?",m,flush=True)
    return II()
for _ in range(II()):
    n=II();l=0;r=n;pc=0;d=1;mx=0
    while l+1<r:m=(l+r)//2;c=pc+m*d;mx=max(mx,c);l=m;pc=c;d*=-1
    pc=n-mx;ask(pc);l=0;r=n;d=1
    while l+1<r:
        m=(l+r)//2;c=pc+m*d
        if ask(c):r=m
        else:l=m
        pc=c;d*=-1
    print("=",r,flush=True)


P = 998244853
N, M = map(int, input().split())

fa = [1]
for i in range(4040):
    fa.append(fa[-1]*(i+1)%P)

fainv = [pow(fa[-1], P-2, P)]
for i in range(4040)[::-1]:
    fainv.append(fainv[-1]*(i+1)%P)

fainv = fainv[::-1]

def C(a, b):
    return fa[a]*fainv[a-b]*fainv[b]%P

X = [0] * N + [C(N+M, M)]
for i in range(N):
    X[i] = C(N+M, M) - C(N+M, M-i-1) if 0<=M-i-1<=N+M and N-M<i+1 else 0

print(sum([i*(X[i]-X[i-1]) for i in range(1, N+1)]) % P)


def main():
    M=998244353
    n,k,*h=map(int,open(0).read().split())
    m=sum(i!=j for i,j in zip(h,h[1:]+h[:1]))
    f=[0]*(m+1)
    f[0]=b=1
    for i in range(1,m+1):f[i]=b=b*i%M
    inv=[0]*(m+1)
    inv[m]=b=pow(f[m],M-2,M)
    for i in range(m,0,-1):inv[i-1]=b=b*i%M
    comb=lambda n,k:f[n]*inv[n-k]*inv[k]%M
    print((pow(k,m,M)-sum(comb(m,i)*comb(m-i,i)*pow(k-2,m-i-i,M)for i in range(m//2+1)))*pow(k,n-m,M)*pow(2,M-2,M)%M)
main()


from functools import reduce

def factorial(n):
    return reduce(lambda x, y: x*y, range(1,n))

colors = {
    'R' : 0,
    'O' : 0,
    'Y' : 0,
    'G' : 0,
    'B' : 0,
    'V' : 0
}

for c in list(input()):
    colors[c] += 1

amount = reversed(sorted([(colors[key], key) for key in colors]))

if amount[0] == 6 or amount[0] == 5:
    print("1")
elif amount[0] == 4:
    print("2")
elif amount[0] == 3:
    if amount[1] == 3:
        print("2")
    elif amount[1] == 2:
        print("4")
    elif amount[1] == 1:
        print("6")
elif amount[0] == 2:
    if amount[1] == amount[2] == 2:
        print("4")
    elif amount[1] == 2:
        while True: pass
    else:
        print(factorial(6) / 48)

elif amount[0] == 1:
    print(factorial(6) / 24)


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


x1,x2,a,b=map(int,raw_input().split())
if a+x1<=x2 and b+x1>=x2:print "FIRST";print x2-x1
elif a<=0 and b>=0:print "DRAW"
else:
	d=x2-x1
	if a<0:d,a,b=-d,-b,-a
	if d<0:print "DRAW"
	elif d%(a+b)==0:print "SECOND"
	elif d%(a+b)>=a and d%(a+b)<=b:print "FIRST";print d%(a+b)
	else: print "DRAW"


def _cmp(x, y):
    c = -cmp(x[1][0], y[1][0])
    d = -cmp(x[1][1]-x[1][2], y[1][1]-y[1][2])
    e = -cmp(x[1][1], y[1][1])
    f = cmp(x[0][0], y[0][0])
    if c != 0:
        return c
    elif d != 0:
        return d
    elif e != 0:
        return e
    else:
        return f

results = {}
for i in range(5):
    a, b, pts = raw_input().split()
    x, y = [int(i) for i in pts.split(':')]
    at = results[a] = results.get(a, [0, 0, 0])
    at[0], at[1], at[2] = (at[0]+(3 if x > y else 1 if x == y else 0), at[1]+x, at[2]+y)
    bt = results[b] = results.get(b, [0, 0, 0])
    bt[0], bt[1], bt[2] = (bt[0]+(3 if x < y else 1 if x == y else 0), bt[1]+y, bt[2]+x)

b = tuple(results['BERLAND'])
c = tuple(results['CERLAND'])
del results['BERLAND']
del results['CERLAND']
results = list(results.items())

(x, y) = (10, -1)

for i in xrange(10):
    for j in xrange(i):
        res = results[:]
        res.append(('BERLAND', (b[0]+3, b[1]+i, b[2]+j)))
        res.append(('CERLAND', (c[0], c[1]+j, c[2]+i)))
        res.sort(_cmp)
        barland = None
        if res[0][0] == 'BERLAND':
            barland = res[0][1]
        elif res[1][0] == 'BERLAND':
            barland = res[1][1]
        if barland and i-j < x - y:
            (x, y) = i, j

if x == 10 and y == -1:
    print 'IMPOSSIOBLE'
else:
    print '{0}:{1}'.format(x, y)


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

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

import __pypy__

def memoize(f):
    """ Memoization decorator for a function taking one or more arguments. """

    class memodict(dict):
        def __getitem__(self, *key):
            return dict.__getitem__(self, key)

        def __missing__(self, key):
            ret = self[key] = f(*key)
            return ret

    return memodict().__getitem__

def main():
    n, T = map(int, input().split())
    t, g = [0] * n, [0] * n
    for i in range(n):
        t[i], g[i] = map(int, input().split())

    @memoize
    def solve(T, p, mask):
        if T < 0:
            return 0
        if T == 0:
            return 1
        mask = list(mask)
        res = 0
        for i in range(n):
            if mask[i] == 0 and p != g[i]:
                new_mask = mask[:]
                new_mask[i] = 1
                res += solve(T - t[i], g[i], tuple(new_mask))

        return res

    print(solve(T, -1, tuple([0] * n)))

# region fastio

BUFSIZE = 8192

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

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

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

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

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

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

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

# endregion

if __name__ == "__main__":
    main()


from collections import *
n = input()
s = raw_input()
b = [int (i) for i in raw_input().split(' ')]
n = n
cnt = defaultdict(int)
multiples = []
biggest = 'a'
ans = 0
for i in range(n//2):
    if(s[i] == s[n-i-1]):
        multiples.append(i)
        cnt[s[i]] += 1
        ans += max(b[i],b[n-i-1])
    else:
        ans += b[i] + b[n-i-1]

for i in range(26):
    if(cnt[chr(ord('a')+i)] > cnt[biggest]):
        biggest = chr(ord('a')+i)
more = max(max(cnt.values())*2-sum(cnt.values()),0)
takes = []
for i in range(n//2):
    if(s[i] != s[n-i-1] and s[i] != biggest and s[n-i-1] != biggest):
        takes.append(min(b[i],b[n-i-1]))
takes = sorted(takes)[:more]
pen = sum(takes)
print(ans-pen)


n, k = map(int, input().split())
num = list(input())
if k == 0:
    print(*num, sep='')
    exit()
if n == 1:
    print('0')
    exit()
if num[0] != '1':
    num[0] = '1'
    k -= 1
for i, f in enumerate(num):
    if k > 0 and i > 0:
        if num[i] != '0':
            num[i] = '0'
            k -= 1
print(*num, sep='')


import operator

def pixel(input):
    red, green, blue = input.split()
    pixels = {
        'red': int(red),
        'green': int(green),
        'blue': int(blue)
    }

    battles = 0

    while True:
        is_mir = len([x for x in [pixels['red'], pixels['green'], pixels['blue']] if x == 0]) > 1
        if is_mir:
            break

        min_pixel = get_min_pixel(pixels)

        if min_pixel == 'red':
            pixels['red'] += 1
            pixels['blue'] -= 1
            pixels['green'] -= 1
            pass
        elif min_pixel == 'green':
            pixels['red'] -= 1
            pixels['blue'] -= 1
            pixels['green'] += 1
        elif min_pixel == 'blue':
            pixels['red'] -= 1
            pixels['blue'] += 1
            pixels['green'] -= 1

        battles += 1

    return battles

def get_min_pixel(pixels):
    return min(pixels.items(), key=operator.itemgetter(1))[0]

print(pixel(input()))


import sys
from collections import deque
input = lambda : sys.stdin.readline().strip()
# for i in range(int(input())):
n,m = map(int,input().split())
g = {}
for i in range(m):
    a,b = map(int,input().split())
    if b-1 in g:
        g[b-1].append(a-1)
    else:
        g[b-1]=[a-1]
k = int(input())
way = list(map(lambda x: int(x)-1,input().split()))
bfs = deque()
bfs.append(way[-1])
lvl = [-1]*n
ans = [0]*n
a = [set() for j in range(n)]
lvl[way[-1]]=0
while bfs:
    v = bfs.popleft()
    for u in g[v]:
        if lvl[u]==-1:
            lvl[u]=lvl[v]+1
            a[u].add(v)
            bfs.append(u)
        elif lvl[u]==lvl[v]+1:
            ans[u]=1
            a[u].add(v)
ansv = 0
ans1 = 0
for v in range(k-1):
    if ans[way[v]] or  a[way[v]].pop()!=way[v+1]:#
        ansv +=1
for v in range(k-1):
    if k-v-1!=lvl[way[v]] and way[v+1] not in a[way[v]]:
        ans1+=1
    elif k-v-1 == lvl[way[v]]:
        break
print(ans1,ansv)


n,d,s=map(int,raw_input().split())
c0=[]
c1=[]
v=0
for i in range(n):
	c,f,l=map(int,raw_input().split())
	v+=c
	if l>=d:
		if c:
			c1+=[f]
		else:
			c0+=[f]
c0.sort()
y=z=0
if c1!=[]:
	u=min(c1)
	v+=1
	for i in c0:
		if u<=s:
			z,y=max([z,y],[min(v,n),-u])
		else:
			break
		u+=i
		v+=1
	if u<=s:
		z,y=max([z,y],[min(v,n),-u])
v=u=0
for i in c0:
	if u+i>s:
		z,y=max([z,y],[v,-u])
	else
		break
	u+=i
	v+=1;
print z,-y