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 find(a,mod,n):
    rem = n - len(bin(a)[2:])
    ans = 0
    while rem:
        temp = min(rem,50)
        ans = (ans + 2**temp)%mod
        rem -= temp
    return ans

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


def main():
    n, k, m = map(int, raw_input().split())
    if k == 1:
        print 9 * pow(10, n - 1, m) % m
        return
    if n == 1:
        print len([i for i in xrange(1, 10) if i % k == 0]) % m
        return
    dp = [0] * k
    for i in xrange(10):
        if i % k:
            dp[i%k] += 1
    t = 10 % k
    kk = [[i * j % k for j in xrange(11)] for i in xrange(k)]
    for i in xrange(n - 1):
        ndp = [0] * k
        for j in xrange(1, k):
            for l in xrange(i == n - 2, 10):
                x = j + kk[t][l]
                if x >= k:
                    x -= k
                if x:
                    ndp[x] += dp[j]
                    if ndp[x] >= m:
                        ndp[x] -= m
        for l in xrange(i == n - 2, 10):
            if kk[t][l]:
                ndp[kk[t][l]] += 1
        dp = ndp[:]
        t = kk[t][10]
    print (9 * pow(10, n - 1, m) - sum(dp) % m + m) % m
main()


#!/usr/bin/env python

from sys import stdin

def main():
   N, M = map(int, stdin.readline().split())

   if N == 1 and M == 1:
      res = 1.0
   else:
      res = 1.0/N + (N-1)*1.0/N * (M-1) * 1.0 / (M*N-1)

   print '%.9lf' % (res)

   return 0

if __name__ == '__main__': main()


from collections import *

cost = []
for _ in [0,1,2]:
  cost.append(map(int, raw_input().split()))
N = int(raw_input())
d = defaultdict(int)

for n in xrange(1,N+1):
  for i in xrange(3):
    for j in xrange(3):
      if i==j: continue
      other = min(x for x in [0,1,2] if x!=i and x!=j)
      way1 = d[n-1,i,other] + d[n-1,other,j] + cost[i][j]
      way2 = 2*d[n-1,i,j] + d[n-1,j,i] + cost[i][other] + cost[other][j]
      d[n,i,j] = min(way1,way2)

print d[N,0,2]


a = [map(int, raw_input().split()) for _ in xrange(3)]
n = int(raw_input())
r3 = range(3)
dp = [[[0] * 3 for _ in r3] for i in range(41)]
for i in range(1, n+1):
    for j in r3:
        for k in r3:
            if j == k: continue
            dp[i][j][k] = a[j][k] + dp[i-1][j][3-j-k] + dp[i-1][3-j-k][k]
            dp[i][j][k] = min(dp[i][j][k], dp[i-1][j][k] + a[j][3-j-k] + dp[i-1][k][j] + a[3-j-k][k] + dp[i-1][j][k])
    for l in r3:
        for j in r3:
            for k in r3:
                dp[i][j][k] = min(dp[i][j][k], dp[i][j][l] + dp[i][l][k])
print dp[n][0][2]


import sys,math
from collections import defaultdict
from io import BytesIO

sys.stdin = BytesIO(sys.stdin.read())
input = lambda: sys.stdin.readline().rstrip('\r\n')
n = int(input())
#n,q = [int(x) for x in input().split(' ')]
arr = [int(x) for x in input().split(' ')]
#sec = [set()] * n
basen = n
savearr = [min(10,x) for x in arr]
arr = [max(x-10,0) for x in arr]
#print(savearr,arr)

while n > 100:
    if sum(arr) == 0:
        break
    dif = n - 100
    for i in range(8,0,-1):
        if arr[i-1] > 0:
            n -= i * min(dif // i + 1, arr[i-1])
            arr[i-1] -= min(dif // i + 1, arr[i-1])
            break

for i in range(len(arr)):
    arr[i] += savearr[i]

cur = 0
dot8 = set()
while cur <= n and arr[-1] >= 0:
    arr[-1] -= 1
    dot8.add(cur)
    cur += 8

cur = 0
dot7 = set()
while cur <= n and arr[-2] >= 0:
    arr[-2] -= 1
    dot7.add(cur)
    cur += 7

cur = 0
dot6 = set()
while cur <= n and arr[-3] >= 0:
    arr[-3] -= 1
    dot6.add(cur)
    cur += 6

cur = 0
dot5 = set()
while cur <= n and arr[-4] >= 0:
    arr[-4] -= 1
    dot5.add(cur)
    cur += 5

cur = 0
dot4 = set()
while cur <= n and arr[-5] >= 0:
    arr[-5] -= 1
    dot4.add(cur)
    cur += 4

cur = 0
dot3 = set()
while cur <= n and arr[-6] >= 0:
    arr[-6] -= 1
    dot3.add(cur)
    cur += 3

cur = 0
dot2 = set()
while cur <= n and arr[-7] >= 0:
    arr[-7] -= 1
    dot2.add(cur)
    cur += 2
#print(n,dot8,dot7)

resdot = dot8
newdot = set()
for el7 in dot7:
    for el in resdot:
        if el7 + el <= n:
            newdot.add(el7+el)
resdot = newdot
newdot = set()
for el6 in dot6:
    for el in resdot:
        if el6 + el <= n:
            newdot.add(el6+el)
resdot = newdot
newdot = set()
for el5 in dot5:
    for el in resdot:
        if el5 + el <= n:
            newdot.add(el5+el)
resdot = newdot
newdot = set()
for el4 in dot4:
    for el in resdot:
        if el4 + el <= n:
            newdot.add(el4+el)
resdot = newdot
#print(newdot)
newdot = set()
for el3 in dot3:
    for el in resdot:
        if el3 + el <= n:
            newdot.add(el3+el)
resdot = newdot
#print(resdot,newdot,dot2)
newdot = set()
for el2 in dot2:
    for el in resdot:
        if el2 + el <= n:
            newdot.add(el2+el)
#print(newdot)
m = max(newdot)
print(basen + m - n + (min(n-m,arr[0])))


import time
import random
W = int(input())
M = [int(a) for a in input().split()]
A = [0] * 8
sTime = time.time()

s = 0
mi = 10**20
for i in range(8):
    if s + M[i]*(i+1) <= W:
        s += M[i]*(i+1)
        A[i] = M[i]
    else:
        t = (W-s)//(i+1)
        s += t*(i+1)
        A[i] += t

    if s <= W:
        mi = min(mi, W-s)

while time.time() - sTime < 1.7:
    i = random.randrange(8)
    a = random.randrange(2)
    if W-s >= 20 or (s-W < 10 and a == 0):
        if A[i] < M[i]:
            A[i] += 1
            s += (i+1)
    else:
        if A[i] > 0:
            A[i] -= 1
            s -= (i+1)

    if s <= W:
        mi = min(mi, W-s)

print(W-mi)


from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write

def in_num():
    return int(raw_input())

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

def pr_num(n):
    stdout.write(str(n)+'\n')

def pr_arr(arr):
    pr(' '.join(map(str,arr))+'\n')

# fast read function for total integer input

def inp():
    # this function returns whole input of
    # space/line seperated integers
    # Use Ctrl+D to flush stdin.
    return map(int,stdin.read().split())

range = xrange # not for python 3.0+
mod=10**9+7
n,a,b,k=in_arr()
dp=[[0 for i in range(n+1)] for j in range(k+1)]
dp[0][a-1]=1
dp[0][a]=(-1)%mod
b-=1
for i in range(k):
    temp=0
    for j in range(n+1):
        temp=(temp+dp[i][j])%mod

        if i and int(abs(b-j))>1:
            temp-=dp[i-1][j]
            temp%=mod
        dp[i][j]=temp
        if j<n:
            x=int(abs(b-j))
            x-=1
            if x<=0:
                continue
            dp[i+1][max(0,j-x)]=(dp[i+1][max(0,j-x)]+temp)%mod
            dp[i+1][min(n,j+x+1)]=(dp[i+1][min(n,j+x+1)]-temp)%mod
            #dp[i+1][j]=(dp[i+1][j]-1)%mod
            #dp[i+1][j+1]=(dp[i+1][j+1]+1)%mod
        if i and int(abs(b-j))>1:
            temp+=dp[i-1][j]
            temp%=mod

ans=0
temp=0
for i in range(n):
    temp+=dp[k][i]
    temp%=mod
    if int(abs(i-b))>1:
        temp-=dp[k-1][i]
        temp%=mod
    ans+=temp
    ans%=mod

    if int(abs(i-b))>1:
        temp+=dp[k-1][i]
        temp%=mod
pr_num(ans)


n,a,b,k=map(int,input().split())
dp=[[0 for i in range(n+2)] for j in range(2)]
dp[0][a]=1
now=1
last=0
mod=1000000007
for i in range(k):
    for j in range(1,n+1):
        d=max(abs(j-b)-1,0)
        if j!=n:
            dp[now][j+1]=(dp[last][j]%mod+dp[now][j+1]%mod)%mod
            dp[now][min(j+d+1,n+1)]=(dp[now][min(j+d+1,n+1)]-dp[last][j])%mod
        if j!=1:
            dp[now][j]=(dp[now][j]-dp[last][j])%mod
            dp[now][max(j-d,1)]=(dp[now][max(j-d,1)]%mod+dp[last][j]%mod)%mod
    for i1 in range(1,n+2):
        dp[now][i1]=(dp[now][i1]+dp[now][i1-1])%mod
        dp[last][i1]=0
    aux=now
    now=last
    last=aux
print(sum(dp[last])%mod)


#coding=utf-8

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

t = 0;

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

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


import math
MOD = 10**9+7

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

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

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


N, T = map(int, input().split())
A = [int(a) for a in input().split()]
if sum(A) > N//2:
    A = [1-a for a in A][::-1]
K = sum(A)
S = sum(A[-K:])
M = K + 1
P = 10**9+7
inv = pow(N*(N-1)//2, P-2, P)
X = [[0]*M for _ in range(M)]
for i in range(M):
    if i > 0: X[i-1][i] = ((K-i+1)**2*inv)%P
    if i < M-1: X[i+1][i] = (N-2*K+i+1)*(i+1)*inv%P
    X[i][i] = (1-((K-i)**2*inv)-(N-2*K+i)*(i)*inv)%P

def ddd(n):
    for i in range(1, 100):
        if (n*i%P) < 100:
            return (n*i%P), i
    return -1, -1
def poww(MM, n):
    if n == 1:
        return MM
    if n % 2:
        return mult(poww(MM, n-1), MM)
    return poww(mult(MM,MM), n//2)
def mult(M1, M2):
    Y = [[0] * M for _ in range(M)]
    for i in range(M):
        for j in range(M):
            for k in range(M):
                Y[i][j] += M1[i][k] * M2[k][j]
                Y[i][j] %= P
    return Y

X = poww(X, T)

print(X[S][K])


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

"""Codeforces Round #553 (Div. 2)

Problem F. Sonya and Informatics

:author:         Kitchen Tong
:mail:    kctong529@gmail.com

Please feel free to contact me if you have any question
regarding the implementation below.
"""

__version__ = '1.8'
__date__ = '2019-04-21'

import sys

def binom_dp():
    dp = [[-1 for j in range(110)] for i in range(110)]
    def calculate(n, k):
        if n < k:
            return 0
        if n == k or k == 0:
            return 1
        if dp[n][k] > 0:
            return dp[n][k]
        else:
            dp[n][k] = calculate(n-1, k-1) + calculate(n-1, k)
        return dp[n][k]
    return calculate

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

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

def multiply(A, B, mod):
    if not hasattr(B[0], '__len__'):
        C = [sum(aij * B[j] % mod for j, aij in enumerate(ai)) for ai in A]
    else:
        C = [[0 for col in range(len(B[0]))] for row in range(len(A))]
        len_A = len(A)
        len_B = len(B)
        for row in range(len_A):
            if sum(A[row]) == 0:
                continue
            for col in range(len_B):
                C[row][col] = sum(A[row][k] * B[k][col]
                                  for k in range(len_B)) % mod
    return C

def memoize(func):
    memo = {}
    def wrapper(*args):
        M, n, mod = args
        if n not in memo:
            memo[n] = func(M, n, mod)
        return memo[n]
    return wrapper

@memoize
def matrix_pow(M, n, mod):
    # print(f'n is {n}')
    if n == 2:
        return multiply(M, M, mod)
    if n == 1:
        return M
    sub_M = matrix_pow(M, n//2, mod)
    if n % 2 == 0:
        return multiply(sub_M, sub_M, mod)
    return multiply(sub_M, matrix_pow(M, n - n//2, mod), mod)

def solve(n, k, a, binom, mod):
    ones = sum(a)
    zeros = n - ones
    M = [[0 for col in range(zeros+1)] for row in range(zeros+1)]
    for row in range(max(0, zeros-ones), zeros+1):
        pre_zeros = row
        pre_ones = zeros - pre_zeros
        post_zeros = pre_ones
        post_ones = ones - pre_ones
        M[row][row] = (pre_ones * post_ones + pre_zeros * post_zeros
                       + binom(zeros, 2) + binom(ones, 2))
        if row > max(0, zeros-ones):
            M[row-1][row] = pre_zeros * post_ones
        if row < zeros:
            M[row+1][row] = post_zeros * pre_ones
    M = [matrix_pow(M, k, mod)[-1]]
    b = [0] * (zeros + 1)
    b[zeros - sum(a[:zeros])] = 1
    C = multiply(M, b, mod)
    return C[-1]

def main(argv=None):
    mod = int(1e9) + 7
    n, k = list(map(int, input().split()))
    a = list(map(int, input().split()))
    binom = binom_dp()
    P = solve(n, k, a, binom, mod)
    if P == 0:
        print(0)
    else:
        Q = pow(binom(n, 2), k, mod)
        print(P * modinv(Q, mod) % mod)
    return 0

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


import sys
from array import array  # noqa: F401

def input():
    return sys.stdin.buffer.readline().decode('utf-8')

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

dp = [[[0] * 5 for _ in range(2 * t + 1)] for _ in range(n)]
dp[0][0] = [0] + [1] * 4

for i in range(n - 1):
    for j in range(min(2 * t, i + 1)):
        if (j & 1) == 0:
            for k in range(1, 4):
                for l in range(k + 1, 5):
                    # //
                    dp[i + 1][j][l] += dp[i][j][k]
                    # /\
                    dp[i + 1][j + 1][l] += dp[i][j][k]
        else:
            for k in range(4, 1, -1):
                for l in range(k - 1, 0, -1):
                    # \\
                    dp[i + 1][j][l] += dp[i][j][k]
                    # \/
                    dp[i + 1][j + 1][l] += dp[i][j][k]

print(sum(dp[-1][2 * t]))


from itertools import permutations

n, t = map(int, raw_input().split())
dp = [[[0] * 4 for i in xrange(t * 2)] for j in xrange(n)]

for i in xrange(4):
    dp[1][0][i] = i

for i in xrange(1, n - 1):
    for j in xrange(t * 2):
        for p, q in permutations(xrange(4), 2):
            fr = dp[i][j][p]
            if j & 1:
                if p > q:
                    dp[i + 1][j][q] += fr
                elif j + 1 < t * 2:
                    dp[i + 1][j + 1][q] += fr
            else:
                if p < q:
                    dp[i + 1][j][q] += fr
                elif j + 1 < t * 2:
                    dp[i + 1][j + 1][q] += fr

print sum(dp[n - 1][t * 2 - 1][i] for i in xrange(4))


n = int(raw_input())
a, b, c = [], [], []
s = raw_input()
from collections import defaultdict
dp = defaultdict(lambda : float("inf"))
def count(a, st, x):
    ret = 0
    i = st
    while i < len(a) and a[i] < x:
        ret += 1
        i += 1
    return ret
for i in xrange(len(s)):
    if s[i] == "V":
        a.append(i)
    elif s[i] == "K":
        b.append(i)
    else :
        c.append(i)
dp[(0,0,0,0)] = 0
for i in xrange(len(a)+1):
    for j in xrange(len(b)+1):
        for k in xrange(len(c)+1):
            for p in xrange(2):
                if i < len(a):
                    dp[(i+1,j,k,1)] = min(dp[(i+1,j,k,1)], dp[(i,j,k,p)] + count(a,i,a[i])+count(b,j,a[i])+count(c,k,a[i]))
                if j < len(b) and p == 0:
                    dp[(i,j+1,k,0)] = min(dp[(i,j+1,k,0)], dp[(i,j,k,p)]+count(a,i,b[j])+count(b,j,b[j])+count(c,k,b[j]))
                if k < len(c):
                    dp[(i,j,k+1,0)]=min(dp[(i,j,k+1,0)],dp[(i,j,k,p)]+count(a,i,c[k])+count(b,j,c[k])+count(c,k,c[k]))
print min(dp[(len(a),len(b),len(c),0)],dp[(len(a),len(b),len(c),1)])


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

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

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

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

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

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

if __name__ == "__main__":

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

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

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

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

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


import sys
from array import array  # noqa: F401

def readline(): return sys.stdin.buffer.readline().decode('utf-8')

n, k = map(int, readline().split())
mod = 998244353

if k == 1:
    print(0)
    exit()

dp1 = [array('i', [0])*n for _ in range(n)]
dp2 = [array('i', [0])*n for _ in range(n)]
dp1[0][0] = 1

for i in range(n-1):
    for j in range(i+1):
        for l in range(j+1):
            dp2[j][0] += dp1[j][l]
            if dp2[j][0] >= mod:
                dp2[j][0] -= mod

            dp2[j+1 if j == l else j][l+1] += dp1[j][l]
            if dp2[j+1 if j == l else j][l+1] >= mod:
                dp2[j+1 if j == l else j][l+1] -= mod

            dp1[j][l] = 0

    dp1, dp2 = dp2, dp1

ans = 0
for i in range(1, n+1):
    t = (k-1) // i
    if t == 0:
        break

    dps1 = array('i', [0])*(t+1)
    dps2 = array('i', [0])*(t+1)
    dps1[0] = 1

    for j in range(n-1):
        for l in range(min(j+1, t)):
            dps2[0] += dps1[l]
            if dps2[0] >= mod:
                dps2[0] -= mod

            dps2[l+1] += dps1[l]
            if dps2[l+1] >= mod:
                dps2[l+1] -= mod

            dps1[l] = 0

        dps1, dps2 = dps2, dps1

    x = sum(dp1[i-1]) % mod
    ans = (ans + x * sum(dps1[:-1])) % mod

print(ans * 2 % mod)


s = raw_input()
n = len(s)
pb = -1
for i in xrange(n):
	if s[i] == 'B':
		pb = i

if pb != -1:
	s = s[pb:] + s[:pb]

s = s[-1] + s + s[0]

res = 1

dp = []

for i in xrange(n + 2):
	dp.append([[[0, 0], [0, 0]], [[0, 0], [0, 0]]])

for i in xrange(2, n + 1):
	for first in xrange(2):
		for prev in xrange(2):
			for last in xrange(2):
				for cur in xrange(2):
					if s[i - 1:i + 1] != 'BA' and cur == 1:
						continue
					if i == 2:
						if first != cur or prev != 0 or last != 0:
							continue
						dp[i][first][last][cur] = 1
					elif i > 2:
						if s[i - 2:i] == 'AB' and prev == 0 and cur == 0:
							continue
						if i == n and s[n] + s[1] == 'AB' and cur == 0 and first == 0:
							continue
						if i == n and s[n - 1:n + 1] == 'AB' and cur == 0 and last == 0:
							continue
						dp[i][first][last][cur] += dp[i - 1][first][prev][last]

res = 0
for i in xrange(2):
	for j in xrange(2):
		for k in xrange(2):
			res += dp[n][i][j][k]

print res


import sys
from math import gcd
# sys.setrecursionlimit(10000)

class BinaryField:
    def __init__(self, s):
        """Given a binary string, return a BinaryField element.
        Input:
        s: Has to take one of the following form:
           1. A binary string, with MSB as the highest degree polynomial
           2. An integer, with MSB as the highest degree polynomial"""
        if type(s) == int:
            self.poly = s

        else:
            self.poly = 0

            for c in s:
                self.poly = (self.poly << 1) + int(c)

        if self.poly == 0:
            self.deg = float('-inf')
        else:
            self.deg = len(bin(self.poly)) - 3

    def __repr__(self):
        return f'BinaryField(poly={bin(self.poly)[2:]}, deg={self.deg})'

    def __eq__(self, other):
        return self.poly == other.poly

    def __add__(self, other):
        return BinaryField(self.poly ^ other.poly)

    def __mul__(self, other):
        temp = other.poly
        answer = 0
        align = self.poly

        while temp:
            if temp & 1:
                answer ^= align

            align <<= 1
            temp >>= 1

        return BinaryField(answer)

    def __truediv__(self, other):
        if other.poly == 0:
            raise ZeroDivisionError

        answer = 0
        temp = self.poly

        for d in range(max(self.deg - other.deg, 0), -1, -1):
            if temp & (1 << (other.deg + d)):
                answer += (1 << d)
                temp ^= (other.poly << d)

        return BinaryField(answer)

    def __mod__(self, other):
        if other.poly == 0:
            raise ZeroDivisionError

        answer = 0
        temp = self.poly

        for d in range(max(self.deg - other.deg, 0), -1, -1):
            if temp & (1 << (other.deg + d)):
                answer += (1 << d)
                temp ^= (other.poly << d)

        return BinaryField(temp)

    def square(self):
        """Returns the square of the polynomial itself.
        Faster than a * a"""
        answer = 0
        temp = self.poly

        while temp:
            lsb = temp & (-temp)
            answer += lsb ** 2

            temp -= lsb

        return BinaryField(answer)

    def powmod(self, exp, mod):
        """Return (self**exp) % mod
        Inputs:
        exp: An integer power
        mod: A BinaryField element representing the modulus"""
        answer, temp = BinaryField(1), self

        while exp:
            if exp & 1:
                answer = (answer * temp) % mod

            exp >>= 1
            temp = temp.square() % mod

        return answer

    @staticmethod
    def gcd(poly1, poly2):
        """Given two BinaryField elements, return its gcd
        Input:
        poly1, poly2: two BinaryField elements.
        Output:
        The gcd of poly1 and poly2 as a BinaryField instance."""
        if poly1.deg < poly2.deg:
            poly1, poly2 = poly2, poly1

        p1, p2 = poly1, poly2
        while p2.poly != 0:
            p1, p2 = p2, p1 % p2

        return p1

    @staticmethod
    def factorize(poly):
        """Factorize a BinaryField object
        Input:
        poly: A BinaryField element
        Return: A list of tuples (poly, exp)."""
        answer = []
        temp = poly

        for d in range(2, 2**(1+poly.deg//2)):
            div = BinaryField(d)

            e = 0
            while temp % div == BinaryField(0):
                temp = temp / div
                e += 1

            if e:
                answer.append((div, e))

            if temp == BinaryField(1): break

        if temp != BinaryField(1):
            answer.append((temp, 1))

        return answer

def input_general():
    return sys.stdin.readline().rstrip('\r\n')

def input_num():
    return int(sys.stdin.readline().rstrip("\r\n"))

def input_multi(x=int):
    return map(x, sys.stdin.readline().rstrip("\r\n").split())

def input_list(x=int):
    return list(input_multi(x))

def main(s):
    def get_factor(n):
        factors = {1}

        for p in range(2, 1 + int(n**0.5)):
            e = 0

            while n % p == 0:
                n //= p
                e += 1

            if e:
                factors = {f * (p**i) for f in factors for i in range(e+1)}

            if n == 1: break

        if n != 1:
            factors = {f * g for f in factors for g in (1, n)}

        return factors

    s = s.rstrip('0')
    leading_0 = s.find('1')

    answer = 1

    if leading_0 == -1:
        print('-1')
        return

    f2s = BinaryField(s)
    x = BinaryField(2)
    factors_bin = BinaryField.factorize(f2s)

    for f, exp in factors_bin:
        factors_pow = sorted(list(get_factor(2**f.deg-1)))

        for e in factors_pow:
            if x.powmod(e, f) == BinaryField(1):
                if exp == 1:
                    need = e
                else:
                    need = e * (2**(len(bin(exp-1)) - 2))

                g = gcd(answer, need)
                answer = answer * need // g

                break

    print(1 + leading_0, 1 + leading_0 + answer)

if __name__ == "__main__":
    s = input_general()

    main(s)


import sys
from math import lcm
from collections import defaultdict

def solve(p):
	poly = int(p[::-1], 2)
	assert p[0] == '1' and p[-1] == '1'
	degree = len(p) - 1
	def reduce(a):
		while a.bit_length() > degree:
			b = a.bit_length() - degree - 1
			a ^= poly << b
		assert a < (1 << degree)
		return a

	def mul(a, b):
		a = reduce(a)
		b = reduce(b)
		val = 0
		for i in range(degree):
			if (a >> i) & 1:
				val ^= (b << i)
		for i in range(degree, -1, -1):
			if (val >> (degree + i)) & 1:
				val ^= poly << i
		return val

	def pow(a, k):
		res = 1
		while k:
			if k & 1:
				res = mul(res, a)
			k >>= 1
			a = mul(a, a)
		return res

	pfs = defaultdict(int)
	pfs[2] += degree
	for i in range(1, degree + 1):
		cur = 2 ** i - 1
		p = 2
		while p * p <= cur:
			while cur % p == 0:
				cur //= p
				pfs[p] += 1
			p += 1
		if cur > 1:
			pfs[cur] += 1
	order_multiple = 1
	for p in pfs:
		order_multiple *= p ** pfs[p]

	order = order_multiple
	x = reduce(1 << 1)
	for p in pfs:
		while order % p == 0 and pow(x, order // p) == 1:
			order //= p
	return order

s = input()
if '1' not in s:
	print(-1)
	sys.exit()

p = s.lstrip('0')
l0 = len(s) - len(p)
p = p.rstrip('0')

res = solve(p)
print(f"{1 + l0} {1 + l0 + res}")


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

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

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

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

def test():
    pass

if __name__ == '__main__':
    main()


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

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

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

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

if __name__ == '__main__':
    main()


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

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

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

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


#!/usr/bin/env python
from sys import stdin
N = 42
C = [[1, 1]]
def init():
  for i in range(N):
    C.append([1])
    for j in range(i+1):
      C[-1].append(C[-2][j] + C[-2][j+1])
    C[-1].append(1)

def go(n):
  count = [0]*(N+2)
  i = 0
  j = 2
  while n >= j:
    n -= j
    for k in range(len(C[i])):
      count[k] += C[i][k]
    j *= 2
    i += 1
  l = 0
  while i >= 0 and n > 1:
    if n >= j:
      n -= j
      for k in range(len(C[i])):
        count[k+l] += C[i][k]
      l += 1
    j /= 2
    i -= 1
  count[l] += n
  return count

def lg(n):
  k = 0
  while n%2 == 0:
    k += 1
    n /= 2
  if n > 1: return -1
  return k

def main():
  init()
  while True:
    l = stdin.readline().split()
    if len(l) < 2: break
    n, k = int(l[0]), int(l[1])
    k = lg(k)
    if k < 0:
      print 0
      continue
    count = go(n)
    print count[k]

if __name__ == '__main__':
  main()


#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
'''
Created on 13/09/2018

@author: ernesto
'''

n, m = [int(x) for x in input().strip().split(" ")]

posibles_jefes = set(range(1, n + 1))
anteriores = set()
posteriores = set()
continuos = [True] * (n + 1)
mencionados = set()
posibles_jefes_mencionados = set()
ultimo_en_salir = [True] * (n + 1)
ultima_salida_inesperada = None

ops = []

if(m > 1):
    for _ in range(0, m):
        s, n_s = [x for x in input().strip().split(" ")]
        n = int(n_s)
        ops.append((s, n))
    for i in range(0, m):
        op, num = ops[i]
        cont = False
        if op == '+':
            cont = not i or (ops[i - 1][0] == '-' and ops[i - 1][1] == num)
            posteriores.add(num)
        if op == '-':
            cont = i == m - 1 or (ops[i + 1][0] == '+' and ops[i + 1][1] == num)
            if num not in mencionados:
                anteriores.add(num)
                ultima_salida_inesperada = num
            posteriores.discard(num)
            ultimo_en_salir[num] &= not posteriores
        continuos[num] &= cont
        mencionados.add(num)
#    print("anteriores {} posteriores {} continuos {} ops {}".format(anteriores, posteriores, continuos, ops))
    if not anteriores and not posteriores:
        assert ultima_salida_inesperada is None
        if ops[0][0] == '+' and ops[-1][0] == '-' and ops[0][1] == ops[-1][1] and continuos[ops[0][1]] and ultimo_en_salir[ops[0][1]]:
            posibles_jefes_mencionados.add(ops[0][1])
    else:
        if not posteriores:
            assert ultima_salida_inesperada is not None
            posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores))
            assert len(posibles_jefes_filtrados) <= 1
            if(posibles_jefes_filtrados):
                assert posibles_jefes_filtrados[0] == ops[-1][1]
                posibles_jefes_mencionados.add(ops[-1][1])
        else:
            if not anteriores:
                assert ultima_salida_inesperada is None
                posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x], posteriores))
#                print("posibles {}".format(posibles_jefes_filtrados))
                assert len(posibles_jefes_filtrados) <= 1
                if(posibles_jefes_filtrados):
                    assert posibles_jefes_filtrados[0] == ops[0][1]
                    posibles_jefes_mencionados.add(ops[0][1])
            else:
                assert ultima_salida_inesperada is not None
#                print("continuos {}".format(continuos))
                posibles_jefes_mencionados = set(filter(lambda x:ultimo_en_salir[x] and continuos[x] and ultima_salida_inesperada == x, anteriores & posteriores))

#    print("posibles jefes menc {}".format(posibles_jefes_mencionados))
    posibles_jefes -= (mencionados - posibles_jefes_mencionados)

print(len(posibles_jefes))
if(len(posibles_jefes)):
    print(" ".join(map(str, sorted(posibles_jefes))))


def lucky(x):
    s=str(x)
    return s.count('4')+s.count('7')==len(s)

def Gen_lucky(n):
    if(len(n)==1):
        if(n<"4"):
            return 0
        if(n<"7"):
            return 1
        return 2
    s=str(n)
    if(s[0]<'4'):
        return 0
    if(s[0]=='4'):
        return Gen_lucky(s[1:])
    if(s[0]<'7'):
        return 2**(len(s)-1)
    if(s[0]=='7'):
        return 2**(len(s)-1)+Gen_lucky(s[1:])
    else:
        return 2**len(s)

def Form(X,k):
    if(k==0):
        return X
    for i in range(len(X)):
        if(k>=F[len(X)-i-1]):
            h=k//F[len(X)-i-1]
            r=k%F[len(X)-i-1]
            G=list(X[i+1:])
            G.remove(X[i+h])
            G=[X[i]]+G
            return Form(X[:i]+[X[i+h]]+G,r)

p=1

F=[1]
i=1
while(p<=10**15):
    p*=i
    F.append(p)
    i+=1

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

if(n<=14):
    if(k>F[n]):
        print(-1)
    else:
        L=Form(list(range(1,n+1)),k-1)
        x=0
        for i in range(n):
            if(lucky(i+1) and lucky(L[i])):
                x+=1
        print(x)
else:
    L=Form(list(range(n-14,n+1)),k-1)
    ss=str(n-15)
    x=0
    for i in range(1,len(ss)):
        x+=2**i
    x+=Gen_lucky(ss)
    for i in range(n-14,n+1):
        if(lucky(L[i-n+14]) and lucky(i)):
            x+=1
    print(x)


lucky=set([])
def gen(x):
    if x>4444444444:
        return
    lucky.add(x)
    gen(x*10+4)
    gen(x*10+7)
gen(4)
gen(7)
lucky=sorted(lucky)

n,k=map(int,raw_input().split())
z=1
t=0
while z<k:
    t+=1
    z*=t
if t>n:
    print -1
    raise SystemExit()
def before(x):
    l=0
    r=len(lucky)-1
    while r-l>1:
        if lucky[(r+l)/2]>=x:
            r=(r+l)/2
        else:
            l=(r+l)/2
    if lucky[l]>=x:
        return l
    else:
        return r
def islucky(x):
    if x==0:
        return False
    while x>0:
        if not (x%10 in [4,7]):
            return False
        x/=10
    return True
res=before(n-t+1)
if t>0:
    used=[0]*t
    perm=list()
    k-=1
    while t>0:
        z/=t
        x=0
        while used[x]==1:
            x+=1
        while k>=z:
            k-=z
            x+=1
            while used[x]==1:
                x+=1
        t-=1
        used[x]=1
        perm.append(x)
    t=len(perm)
    for i in xrange(t):
        if islucky(n-t+i+1) and islucky(n-t+perm[i]+1):
            res+=1
print res


# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase
from collections import Counter

def main():
    mod = 10**9+7
    r,g = map(int,input().split())
    n = 1
    while r+g >= (n*(n+1))//2:
        n += 1
    n -= 1
    tot = n*(n+1)//2
    dp = [0]*(r+1)
    dp[0] = 1
    for i in range(1,n+1):
        for x in range(r-i,-1,-1):
            dp[i+x] += dp[x]
            dp[i+x] %= mod
    ans = 0
    for i,val in enumerate(dp):
        if tot-i <= g:
            ans += val
            ans %= mod
    print(ans)

#Fast IO Region
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")

if __name__ == '__main__':
    main()


"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""

import os
import sys
from io import BytesIO, IOBase
import heapq as h
import bisect

from types import GeneratorType
BUFSIZE = 8192
class SortedList:
    def __init__(self, iterable=[], _load=200):
        """Initialize sorted list instance."""
        values = sorted(iterable)
        self._len = _len = len(values)
        self._load = _load
        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
        self._list_lens = [len(_list) for _list in _lists]
        self._mins = [_list[0] for _list in _lists]
        self._fen_tree = []
        self._rebuild = True

    def _fen_build(self):
        """Build a fenwick tree instance."""
        self._fen_tree[:] = self._list_lens
        _fen_tree = self._fen_tree
        for i in range(len(_fen_tree)):
            if i | i + 1 < len(_fen_tree):
                _fen_tree[i | i + 1] += _fen_tree[i]
        self._rebuild = False

    def _fen_update(self, index, value):
        """Update `fen_tree[index] += value`."""
        if not self._rebuild:
            _fen_tree = self._fen_tree
            while index < len(_fen_tree):
                _fen_tree[index] += value
                index |= index + 1

    def _fen_query(self, end):
        """Return `sum(_fen_tree[:end])`."""
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        x = 0
        while end:
            x += _fen_tree[end - 1]
            end &= end - 1
        return x

    def _fen_findkth(self, k):
        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
        _list_lens = self._list_lens
        if k < _list_lens[0]:
            return 0, k
        if k >= self._len - _list_lens[-1]:
            return len(_list_lens) - 1, k + _list_lens[-1] - self._len
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        idx = -1
        for d in reversed(range(len(_fen_tree).bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
                idx = right_idx
                k -= _fen_tree[idx]
        return idx + 1, k

    def _delete(self, pos, idx):
        """Delete value at the given `(pos, idx)`."""
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len -= 1
        self._fen_update(pos, -1)
        del _lists[pos][idx]
        _list_lens[pos] -= 1

        if _list_lens[pos]:
            _mins[pos] = _lists[pos][0]
        else:
            del _lists[pos]
            del _list_lens[pos]
            del _mins[pos]
            self._rebuild = True

    def _loc_left(self, value):
        """Return an index pair that corresponds to the first position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        lo, pos = -1, len(_lists) - 1
        while lo + 1 < pos:
            mi = (lo + pos) >> 1
            if value <= _mins[mi]:
                pos = mi
            else:
                lo = mi

        if pos and value <= _lists[pos - 1][-1]:
            pos -= 1

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value <= _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def _loc_right(self, value):
        """Return an index pair that corresponds to the last position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        pos, hi = 0, len(_lists)
        while pos + 1 < hi:
            mi = (pos + hi) >> 1
            if value < _mins[mi]:
                hi = mi
            else:
                pos = mi

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value < _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def add(self, value):
        """Add `value` to sorted list."""
        _load = self._load
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len += 1
        if _lists:
            pos, idx = self._loc_right(value)
            self._fen_update(pos, 1)
            _list = _lists[pos]
            _list.insert(idx, value)
            _list_lens[pos] += 1
            _mins[pos] = _list[0]
            if _load + _load < len(_list):
                _lists.insert(pos + 1, _list[_load:])
                _list_lens.insert(pos + 1, len(_list) - _load)
                _mins.insert(pos + 1, _list[_load])
                _list_lens[pos] = _load
                del _list[_load:]
                self._rebuild = True
        else:
            _lists.append([value])
            _mins.append(value)
            _list_lens.append(1)
            self._rebuild = True

    def discard(self, value):
        """Remove `value` from sorted list if it is a member."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_right(value)
            if idx and _lists[pos][idx - 1] == value:
                self._delete(pos, idx - 1)

    def remove(self, value):
        """Remove `value` from sorted list; `value` must be a member."""
        _len = self._len
        self.discard(value)
        if _len == self._len:
            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):
        """Remove and return value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        value = self._lists[pos][idx]
        self._delete(pos, idx)
        return value

    def bisect_left(self, value):
        """Return the first index to insert `value` in the sorted list."""
        pos, idx = self._loc_left(value)
        return self._fen_query(pos) + idx

    def bisect_right(self, value):
        """Return the last index to insert `value` in the sorted list."""
        pos, idx = self._loc_right(value)
        return self._fen_query(pos) + idx

    def count(self, value):
        """Return number of occurrences of `value` in the sorted list."""
        return self.bisect_right(value) - self.bisect_left(value)

    def __len__(self):
        """Return the size of the sorted list."""
        return self._len

    def __getitem__(self, index):
        """Lookup value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        return self._lists[pos][idx]

    def __delitem__(self, index):
        """Remove value at `index` from sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._delete(pos, idx)

    def __contains__(self, value):
        """Return true if `value` is an element of the sorted list."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_left(value)
            return idx < len(_lists[pos]) and _lists[pos][idx] == value
        return False

    def __iter__(self):
        """Return an iterator over the sorted list."""
        return (value for _list in self._lists for value in _list)

    def __reversed__(self):
        """Return a reverse iterator over the sorted list."""
        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):
        """Return string representation of sorted list."""
        return 'SortedList({0})'.format(list(self))

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        import os
        self.os = os
        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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
            self.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")

import collections as col
import math, string

def getInts():
    return [int(s) for s in input().split()]

def getInt():
    return int(input())

def getStrs():
    return [s for s in input().split()]

def getStr():
    return input()

def listStr():
    return list(input())

MOD = 10**9+7
mod=10**9+7
#t=int(input())
t=1
p=10**9+7
def ncr_util():

    inv[0]=inv[1]=1
    fact[0]=fact[1]=1
    for i in range(2,300001):
        inv[i]=(inv[i%p]*(p-p//i))%p
    for i in range(1,300001):
        inv[i]=(inv[i-1]*inv[i])%p
        fact[i]=(fact[i-1]*i)%p

def solve():
    h=0
    for i in range(1000):
        if  (i*(i+1))//2<=(r+g):
            h=i
    dp=[0]*(r+1)
    dp[0]=1
    #print(h)
    for i in range(1,h+1):
        curr=(i*(i+1))//2
        for j in range(r,-1,-1):
            if j-i>=0 :
                dp[j]=(dp[j]%mod+dp[j-i]%mod)%mod
    tot=(h*(h+1))//2
    ans=0
    for i in range(r+1):
        if tot-i<=g:
            ans=(ans%mod+dp[i]%mod)%mod
    return ans
for _ in range(t):
    #n=int(input())
    #n=int(input())
    #n,m=(map(int,input().split()))
    #n1=n
    #x=int(input())
    #b=int(input())
    #n,m,k=map(int,input().split())
    r,g=map(int,input().split())
    #n=int(input())
    #s=input()
    #s1=input()
    #p=input()
    #l=list(map(int,input().split()))

    #l.sort()
    #l.sort(revrese=True)
    #l2=list(map(int,input().split()))
    #l=str(n)
    #l.sort(reverse=True)
    #l2.sort(reverse=True)
    #l1.sort(reverse=True)
    print(solve())


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

MOD = 10**9 + 7
INF = ((pa + pb) * pow(pb, MOD-2, MOD)) % MOD
rAB = pow(pa+pb, MOD-2, MOD)
rB = pow(pb, MOD-2, MOD)

memo = {}

def dfs(a, ab):
    if ab >= k:
        return ab
    if a + ab >= k:
        #return INF
        #return (pa + pb) / pb
        return ((a + MOD-1) + (pa + pb) * rB + ab) % MOD
        return a - 1 + (pa + pb) / pb + ab
    if (a, ab) in memo:
        return memo[a, ab]
    #res = (((dfs(a+1, ab)+1) * pa * rAB) + ((dfs(a, ab+a)+1) * pb * rAB)) % MOD
    #res = (dfs(a+1, ab)) * pa / (pa + pb) + (dfs(a, ab+a)) * pb / (pa + pb)
    res = (dfs(a+1, ab) * pa * rAB) + (dfs(a, ab+a) * pb * rAB)
    #print(a, ab, res)
    memo[a, ab] = res = res % MOD
    return res
#print((dfs(1, 0) * pa * rAB + 1) % MOD)
#print((pb + dfs(1, 0)*pa) / pa)
print(dfs(1, 0))


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

p = 1000000007

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

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


#!/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] * 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()


from __future__ import division, print_function
import __pypy__

add = __pypy__.intop.int_add
sub = __pypy__.intop.int_sub
mul = __pypy__.intop.int_mul

def main():
    from collections import deque

    def printMin(arr, n, k):
        res=[]
        Qi = deque()
        for i in range(k):
            while Qi and arr[i] <= arr[Qi[-1]] :
                Qi.pop()
            Qi.append(i);

        for i in range(k, n):
            res.append(arr[Qi[0]])
            while Qi and Qi[0] <= i-k:
                Qi.popleft()
            while Qi and arr[i] <= arr[Qi[-1]] :
                Qi.pop()
            Qi.append(i)
        res.append(int(arr[Qi[0]]))
        return res
    n,m,a,b=map(int,input().split())
    g,x,y,z=map(int,input().split())

    zinv = 1.0/z

    def modmuladd(x,y,c):
        ans = sub(add(mul(x,y),c), mul(z, int(zinv*x*y + zinv*c)))
        if ans >= z:
            return ans - z
        elif ans < 0:
            return ans + z
        else:
            return ans

    grid= [0]*(n*m)
    grid[0]=g
    for i in range(1,n*m):
        grid[i]=modmuladd(grid[i-1],x,y)
    B=[]
    ans=0.0
    for i in range(n):
        B.append(printMin(grid[i*m:(i+1)*m],m,b))
    grid=[]
    for i in range(len(B[0])):
        temp=[]
        for j in range(n):
            temp.append(B[j][i])
        for tmp in printMin(temp,len(temp),a):
            ans += tmp
    print(int(ans))

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            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')
import sys
class ostream:
    def __lshift__(self,a):
        sys.stdout.write(str(a))
        return self
cout = ostream()
endl = '\n'

def readnumbers(zero = 0):
    conv = ord if py2 else lambda x:x
    A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
    try:
        while True:
            if s[i] >= b'0' [0]:
                numb = 10 * numb + conv(s[i]) - 48
            elif s[i] == b'-' [0]: sign = -1
            elif s[i] != b'\r' [0]:
                A.append(sign*numb)
                numb = zero; sign = 1
            i += 1
    except:pass
    if s and s[-1] >= b'0' [0]:
        A.append(sign*numb)
    return A

if __name__== "__main__":
  main()


from __future__ import division, print_function
import __pypy__

add = __pypy__.intop.int_add
sub = __pypy__.intop.int_sub
mul = __pypy__.intop.int_mul

def main():
    from collections import deque

    def printMin(arr, n, k):
        res=[]
        Qi = deque()
        for i in range(k):
            while Qi and arr[i] <= arr[Qi[-1]] :
                Qi.pop()
            Qi.append(i);

        for i in range(k, n):
            res.append(arr[Qi[0]])
            while Qi and Qi[0] <= i-k:
                Qi.popleft()
            while Qi and arr[i] <= arr[Qi[-1]] :
                Qi.pop()
            Qi.append(i)
        res.append(int(arr[Qi[0]]))
        return res
    n,m,a,b=map(int,input().split())
    g,x,y,z=map(int,input().split())

    zinv = 1.0/z

    def modmuladd(x,y,c):
        ans = sub(add(mul(x,y),c), mul(z, int(zinv*x*y + zinv*c)))
        if ans >= z:
            return ans - z
        elif ans < 0:
            return ans + z
        else:
            return ans

    grid= [0]*(n*m)
    grid[0]=g
    for i in range(1,n*m):
        grid[i]=modmuladd(grid[i-1],x,y)
    B=[]
    ans=0.0
    for i in range(n):
        B.append(printMin(grid[i*m:(i+1)*m],m,b))
    grid=[]
    for i in range(len(B[0])):
        temp=[]
        for j in range(n):
            temp.append(B[j][i])
        for tmp in printMin(temp,len(temp),a):
            ans += tmp
    print(int(ans))
######## Python 2 and 3 footer by Pajenegod and c1729

# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.

# So on cf, use PyPy2 for best string performance.

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            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')

# Cout implemented in Python
import sys
class ostream:
    def __lshift__(self,a):
        sys.stdout.write(str(a))
        return self
cout = ostream()
endl = '\n'

# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
    conv = ord if py2 else lambda x:x
    A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
    try:
        while True:
            if s[i] >= b'0' [0]:
                numb = 10 * numb + conv(s[i]) - 48
            elif s[i] == b'-' [0]: sign = -1
            elif s[i] != b'\r' [0]:
                A.append(sign*numb)
                numb = zero; sign = 1
            i += 1
    except:pass
    if s and s[-1] >= b'0' [0]:
        A.append(sign*numb)
    return A

if __name__== "__main__":
  main()


#!/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 = float(MOD)
    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] = g
            g = fmul(g, x, y)

    int_grid = [[int(gij) % MOD for gij in gi] for gi in grid]

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

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

# region fastio

BUFSIZE = 8192

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

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

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

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

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

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

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

# endregion

if __name__ == "__main__":
    main()


#!/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__

int_add = __pypy__.intop.int_add
int_sub = __pypy__.intop.int_sub
int_mul = __pypy__.intop.int_mul

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(int, input().split())

    zinv = 1.0 / z

    def mod_mul_add(x, y, c):
        ans = int_sub(int_add(int_mul(x, y), c), int_mul(z, int(zinv * x * y + zinv * c)))
        if ans >= z:
            return ans - z
        elif ans < 0:
            return ans + z
        else:
            return ans

    grid = [[0] * 3000 for _ in range(3000)]
    for i in range(n):
        for j in range(m):
            grid[i][j] = int(g)
            g = mod_mul_add(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()


p = 10**9+7
n, m, k, r, c = [int(x) for x in input().split()]
ax, ay, bx, by = [int(x) for x in input().split()]
if [ax, ay] != [bx, by]:
    answer = pow(k, n*m-r*c, p)
else:
    answer = pow(k, n*m, p)
print(answer)


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


#https://pymotw.com/2/collections/counter.html
#same code as mmaxio
from collections import Counter

r = lambda: map(int, input().split())

def main():
	n, = r()
	s = input()
	cost = list(r())

	ans = 0

	cnt = Counter()

	for i in range(n // 2):
		if s[i] == s[n - 1 - i]:
			ans += min(cost[i], cost[n - 1 - i])
			cnt[s[i]] += 1
	total = sum(cnt.values())
	if total > 0:
		ch, occ = cnt.most_common(1)[0]
		avail = []
		if occ > total - occ:# if highest occurence is more than the 50% of total then we will look for the letters which does not have pairs and are not equal to the letter with the highest ocuurence
			for i in range(n // 2):
				if s[i] != s[n - 1 - i] and s[i] != ch and s[n - 1 - i] != ch:
					avail.append(min(cost[i], cost[n - 1 - i]))
			avail.sort()
			ans += sum(avail[:2 * occ - total])

	print(sum(cost)-ans)

main()
#suppose total is 100 and highest occ is 51...difference between highest occ and remaining can be found using this form 2*occ-total as it is a simplified form of two steps 1.total-occ=remaining and 2.occ-remaining which is this case is 2 if highest occ is <= 50 % of total then it can be satisfied by remaining 50% but if it is greater than 50% then we have to use the letters of of the total


class letter(object):
    def __init__(self,let,val):
        self.let=let
        self.val=val

    def __lt__(self,other):
        return self.val<other.val

n=int(input())
s=input()
candi=[[] for i in range(n//2)]
ans=0
for i,vl in enumerate(map(int,input().split())):
    candi[min(i,n-i-1)].append((letter)(s[i],vl))
    ans+=vl
for i in range(n//2):
    candi[i].sort()
ti=[0 for i in range(26)]
sum=0
for i in range(n//2):
    if candi[i][0].let==candi[i][1].let:
        ans-=candi[i][0].val
        ti[ord(candi[i][0].let)-ord('a')]+=1
        sum+=1

mx=0
p=0
for i in range(26):
    if ti[i]>mx:
        mx=ti[i]
        p=i
b=[]
for i in range(n//2):
    if ord(candi[i][0].let)-ord('a')!=p and ord(candi[i][1].let)-ord('a')!=p and candi[i][0].let!=candi[i][1].let:
        b.append(candi[i][0])
b.sort()
i=0
while mx*2>sum:
    sum+=1
    ans-=b[i].val
    i+=1
print(ans)


from collections import *
n = int(input())
s = input()
b = [int (i) for i in 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)
# print(more)
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(pen)
# print(takes)
print(ans-pen)


from collections import Counter

r = lambda: map(int, input().split())

def main():
	n, = r()
	s = input()
	cost = list(r())

	ans = 0

	cnt = Counter()

	for i in range(n // 2):
		if s[i] == s[n - 1 - i]:
			ans += min(cost[i], cost[n - 1 - i])
			cnt[s[i]] += 1
	total = sum(cnt.values())
	if total > 0:
		ch, occ = cnt.most_common(1)[0]
		avail = []
		if occ > total - occ:
			for i in range(n // 2):
				if s[i] != s[n - 1 - i] and s[i] != ch and s[n - 1 - i] != ch:
					avail.append(min(cost[i], cost[n - 1 - i]))
			avail.sort()
			ans += sum(avail[:2 * occ - total])

	print(sum(cost) - ans)

main()


#!/usr/bin/python

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

#  a*x + b*y = c1
# -b*x + a*y = c2
# is it solvable?
def is_solvable(a, b, c1, c2):
    if a == 0 and b == 0:
        return c1 == 0 and c2 == 0
    if (c1*b + c2*a) % (a*a + b*b) != 0:
        return False
    y = (c1*b + c2*a) / (a*a + b*b)
    if a != 0:
        return (c1 - b*y) % a == 0
    else:
        return (c2 - a*y) % b == 0

# can we solve for (m, n) in the following equations?
# x0 + m*cx + n*cy = x1
# y0 - n*cx + m*cy = y1
def can_solve(x0, y0, x1, y1, cx, cy):
    dx = x1 - x0
    dy = y1 - y0
    if cx == 0 and cy == 0:
        return dx == 0 and dy == 0
    if cx == 0:
        return dx % cy == 0 and dy % cy == 0
    if cy == 0:
        return dx % cx == 0 and dy % cx == 0
    d = gcd(abs(cx), abs(cy))
    if (dx % d != 0) or (dy % d != 0):
        return False
    return is_solvable(cx/d, cy/d, dx/d, -dy/d)

x1, y1 = map(lambda(x): int(x), raw_input().split())
x2, y2 = map(lambda(x): int(x), raw_input().split())
cx, cy = map(lambda(x): int(x), raw_input().split())

possible = (can_solve(x1, y1, x2, y2, cx, cy) or
            can_solve(-y1, x1, x2, y2, cx, cy) or
            can_solve(-x1, -y1, x2, y2, cx, cy) or
            can_solve(y1, -x1, x2, y2, cx, cy))
print "YES" if possible else "NO"


def check(x, y, p, q):
    if x == 0 and y == 0:
        return True
    elif p * p + q * q != 0 and (x * q - y * p) % (p * p + q * q) == 0 and (x * p + y * q) % (p * p + q * q) == 0:
        return True
    else:
        return False

x, y = map(int, raw_input().split())
a, b = map(int, raw_input().split())
p, q = map(int, raw_input().split())
if check(x - a, y - b, p, q) or check(x - b, y + a, p, q) or check(x + b, y - a, p, q) or check(x + a, y + b, p, q):
    print "YES"
else:
    print "NO"


F = {}

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

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

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


for i in range(int(input())):
    t = input()[4:]
    q, d = int(t), 10 ** len(t)
    while q < 1988 + d // 9: q += d
    print(q)


def f(start,ends_with):
    n1=len(start)
    n2=len(ends_with)
    ans=""
    if n1<n2:
        if(int(ends_with)>int(start)):
           return ends_with
        else:
           return '1'+ends_with
    if(int(start[n1-n2:])<int(ends_with)):
        ans=start[0:n1-n2]+ends_with
    else:
        if n1==n2:
            temp=int(start[0:n1-n2]+'0')
        else:
            temp=int(start[0:n1-n2])
        temp+=1
        ans=str(temp)+ends_with
    return ans
n=input()
for kk in range(0,n):
    s=raw_input()[4:]
    l=len(s)
    temp="1988"
    for i in range(l-1,-1,-1):
        temp=f(temp,s[i:])
    print temp


'''
Created on Apr 20, 2012

@author: Tobias Flach
'''

def solve():
    prime = 1000000007

    str_a = raw_input()
    str_b = raw_input()
    k = int(raw_input())

    good_shifts = 0
    bad_shifts  = 0

    for i in range(0, len(str_a)):
        shifted = str_a[i:] + str_a[:i]
        if shifted == str_b:
            good_shifts += 1
        else:
            bad_shifts += 1

    good_sols = 0
    bad_sols  = 0
    if str_a == str_b:
        good_sols = 1
    else:
        bad_sols  = 1

    for i in range(0, k):
        t_good_sols = good_sols * (good_shifts - 1) + bad_sols * good_shifts
        t_bad_sols  = good_sols * bad_shifts + bad_sols * (bad_shifts - 1)
        good_sols = t_good_sols % prime
        bad_sols  = t_bad_sols % prime

    print "%d" % (good_sols)

if __name__ == '__main__':
    solve()


import sys

start = raw_input()
end = raw_input()
k = int(raw_input())

dpA = [-1 for i in xrange(k+1)]
dpB = [-1 for i in xrange(k+1)]

def calculaA(n):
    global dpA, dpB
    if n == 0:
        return 0
    if dpA[n-1] == -1:
        calculaA(n-1)

    dpA[n] = dpA[n-1]*(A-1) + dpB[n-1]*A
    dpB[n] = dpA[n-1]*B     + dpB[n-1]*(B-1)

    return dpA[n]

if start == end and k == 0:
    print 1
    exit(0)

A = B = 0

if start != end:
    dpA[0] = 0
    dpB[0] = 1
else:
    dpA[0] = 1
    dpB[0] = 0

for i in xrange(len(start)):
    now = start[i:]+start[:i]

    if now == end:
        A += 1
    else:
        B += 1

for n in xrange(1, k+1):
    dpA[n] = (dpA[n-1]*(A-1) + dpB[n-1]*A)%1000000007
    dpB[n] = (dpA[n-1]*B     + dpB[n-1]*(B-1))%1000000007

print dpA[k]


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


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


n,m,k=map(int,input().split())
M=int(1e9+7)

N=n*n
iv=[0]*(N+1)
iv[1]=1
for i in range(2, N+1):
    iv[i]=M-M//i*iv[M%i]%M
f1=[1]*(N+1)
for i in range(1, N+1):
    f1[i]=f1[i-1]*i%M
f2=[1]*(N+1)
for i in range(1, N+1):
    f2[i]=f2[i-1]*iv[i]%M
left=m%n
#m/n+1, m/n
def powM(b, p):
    r=1
    while p>0:
        if p%2>0:
            r=r*b%M
        b=b*b%M
        p//=2
    return r
c=[[powM(f1[n]*f2[j]%M*f2[n-j]%M, m//n+i) for j in range(n+1)] for i in range(2)]
#print(c)
dp=[[0]*(k+1) for i in range(n+1)]
dp[0][0]=1
for i in range(n):
    for j in range(k+1):
        #prune
        if j>i*n or j<k-(n-i)*n:
            continue
        for l in range(min(n, k-j)+1):
            # i,j -> i+1,j+l
            dp[i+1][j+l]=(dp[i+1][j+l]+c[i<left][l]*dp[i][j])%M
print(dp[n][k])


b, d = map(int, input().split())
for i in range(1, 10):
    if (b**i) % d == 0:
        print("2-type")
        print(i)
        exit()
if (b-1) % d == 0:
    print("3-type")
    exit()
if (b+1) % d == 0:
    print("11-type")
    exit()
for i in range(2, d+1):
    if d % i == 0:
        x = 1
        while d % i == 0:
            d /= i
            x *= i
        if (b**10) % x != 0 and (b+1) % x != 0 and (b-1) % x != 0:
            print("7-type")
            break
else:
    print("6-type")


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

for i in xrange(1,10):

    if (b**i)%d==0:

        print "2-type"

        print i

        exit()

if (b-1)%d==0:

    print "3-type"

elif (b+1)%d==0:

    print "11-type"

else:

    for i in xrange(2,d+1):

        if d%i==0:

            x=1

            while d%i==0: d/=i; x*=i

            if (b**10)%x!=0 and (b+1)%x!=0 and (b-1)%x!=0:

                print "7-type"

                exit()

    print "6-type"

# Made By Mostafa_Khaled


base=998244353;
def power(x, y):
    if(y==0):
        return 1
    t=power(x, y//2)
    t=(t*t)%base
    if(y%2):
        t=(t*x)%base
    return t;
def inverse(x):
    return power(x, base-2)
f=[1]
iv=[1]
for i in range(1, 5555):
    f.append((f[i-1]*i)%base)
    iv.append(inverse(f[i]))
def C(n, k):
    return (f[n]*iv[k]*iv[n-k])%base
def candy(n, k):
    # print(n, k)
    return C(n+k-1, k-1)
def count_game(k, n, x): #k players, n points total, no player can have x point or more
    if(k==0):
        if(n==0):
            return 1
        else:
            return 0
    ans=0
    for i in range(0, k+1):
        t=n-x*i
        # print(i, C(k, i))
        if(t<0):
            break
        if(i%2):
            ans=(ans-C(k, i)*candy(t, k))%base
        else:
            ans=(ans+C(k, i)*candy(t, k))%base
    return ans
p, s, r= list(map(int, input().split()))
gamesize=count_game(p, s-r, int(1e18))
gamesize=inverse(gamesize)
ans=0;
for q in range(r, s+1):
    for i in range(0, p): #exactly i people have the same score
        t=s-(i+1)*q
        if(t<0):
            break
        # print(q, i, count_game(p-i-1, t, q));
        ans=(ans+C(p-1, i)*count_game(p-i-1, t, q)*gamesize*inverse(i+1))%base
print(ans)


c = [[0 for i in range(5205)] for j in range(5205)]
K = 998244353
inv = [0 for i in range(5205)]

def mu(a, n):
	if n == 0: return 1
	q = mu(a, n // 2)
	if n % 2 == 0:
		return q * q % K
	else: return q * q % K * a % K

def calc(m, d, S):
	res = 0
	if m == 0:
		if S == 0: return 1
		return 0

	for u in range(0, m + 1):
		if (u * d > S): break
		U = c[m][u] * c[S - u * d + m - 1][m - 1] % K
		if u % 2 == 0:
			res = (res + U) % K
		else: res = (res - U + K) % K
	return res

c[0][0] = 1
inv[0] = 1
for i in range(1, 5101):
	inv[i] = mu(i, K - 2)

for i in range(1, 5101):
	c[i][0] = 1
	for j in range (1, i):
		c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % K
	c[i][i] = 1

p, s, r = map(int, input().split())

res = 0
den = 0

for i in range(1, p + 1):
	A = 0
	for d in range(r, s // i + 1):
		if (i < p): A = (A + calc(p - i, d, s - d * i)) % K
		else:
			if (s - i * d == 0): A += 1
	A = A * inv[i] % K
	res = (res + A * c[p - 1][i - 1] % K) % K

den = c[s - r + p - 1][p - 1]
res = res * mu(den, K - 2) % K
print(res)


m = 301000
ns = [0] * m
es = [0] * m
c = [0] * m
b = [0] * m
t = [0] * m
P = 0

def add(b, k):
    k = t[k]
    while k:
        e = es[k]
        if b[-1] > e: b[-1] = e
        b[e] += 1
        k = ns[k]

def delete(b):
   for i in range(b[m - 1], m + 1):
       if b[i]:
           b[i] -= 1
           b[-1] = i
           return i

def calc(k):
    global b
    q = 0
    b = [0] * m
    b[-1] = m
    take = rank - dn
    if take < 0: take = 0
    add(b, k)
    add(b, k - 1)
    for i in range(1, take + 1): q += delete(b)
    for i in range(k - 1): add(b, i)
    for i in range(k + 1, P + 1): add(b, i)
    for i in range(1, k - take + 1): q += delete(b)
    return q

n, k = map(int, input().split())
rank = n - k + 1

if rank == 0:
    print('0')
    exit(0)

for i in range(1, n + 1):
    p, e = map(int, input().split())
    if p > P: P = p
    c[p] += 1
    es[i], ns[i] = e, t[p]
    t[p] = i

dn = 0
for i in range(1, n + 1):
    if i > 1: dn += c[i - 2]
    if c[i] + c[i - 1] + dn >= rank and rank <= i + dn:
        u = calc(i)
        if i < n:
            dn += c[i - 1]
            v = calc(i + 1)
            if u > v: u = v
        if i < n - 1:
            dn += c[i]
            v = calc(i + 2)
            if u > v: u = v
        print(u)
        exit(0)

print('-1')


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

from itertools import combinations, product

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

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

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

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

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

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

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

INTINDS = range(len(intervals))

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

res = 0
# for price in xrange(1, rmax + 1):
#     # print price
#     for poses in product(range(3), repeat=len(intervals)):
#         # print poses
#         # 0 smaller 1 equal 2 greater
#         smaller = [i for i in INTINDS if poses[i] == 0]
#         equal = [i for i in INTINDS if poses[i] == 1]
#         greater = [i for i in INTINDS if poses[i] == 2]
#         if len(greater) > 1:
#             continue

#         add = 1.0
#         if len(greater) == 0:
#             if len(equal) <= 1:
#                 continue
#             add *= prod(cache_smaller, smaller, price)
#             add *= prod(cache_equal, equal, price)
#         else:
#             add *= prod(cache_smaller, smaller, price)
#             add *= prod(cache_equal, equal, price)
#             add *= cache_greater[greater[0]][price]
#         res += add * price
# print res
# quit()

for i_int1 in INTINDS:
    for i_ints2_tie in combos(INTINDS, 1, n - 1):
        if i_int1 in i_ints2_tie:
            continue
        i_other = [i for i in INTINDS if i not in i_ints2_tie and i != i_int1]

        for price in xrange(1, rmax + 1):
            add = (
                prod(cache_smaller, i_other, price) *
                prod(cache_equal, i_ints2_tie, price) *
                prod(cache_greater, [i_int1], price)
            )
            res += add * price

# print

for i_ints1_tie in combos(INTINDS, 2, n):
    i_other = [i for i in INTINDS if i not in i_ints1_tie]
    for price in xrange(1, rmax + 1):
        add = (
            prod(cache_smaller, i_other, price) *
            prod(cache_equal, i_ints1_tie, price)
        )
        res += add * price

print res


from sys import stdin

planet_count, goods_count, volume = tuple( int(p) for p in stdin.readline().split() )
names = []
buy_prices = [ [0] * goods_count for i in xrange(planet_count) ]
sale_prices = [ [0] * goods_count for i in xrange(planet_count) ]
count = [ [0] * goods_count for i in xrange(planet_count) ]

for i in xrange(planet_count):
    names.append( stdin.readline() )
    for j in xrange(goods_count):
        buy_prices[i][j], sale_prices[i][j], count[i][j] = tuple( int(p) for p in stdin.readline().split() )

max_profit = 0
goods = range(goods_count)
get_profit = lambda src, dst, good_index: sale_prices[dst][good_index] - buy_prices[src][good_index]
for i in xrange(planet_count):
    for j in xrange(planet_count):
        goods.sort(key=lambda index: get_profit(i, j, index), reverse=True)
        available_volume = volume
        this_profit = 0
        for good_index in goods:
            if get_profit(i, j, good_index) <= 0:
                break
            vol = min(available_volume, count[i][good_index])
            this_profit += get_profit(i, j, good_index) * vol
            available_volume -= vol
        max_profit = max(max_profit, this_profit)

print max_profit


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


I=lambda:map(int,input().split())

R=range

n,m,k=I()

def r(a,b,c=k):

	q=0

	for a,b in sorted((b[i][1]-a[i][0],a[i][2])for i in R(m))[::-1]:

		if a<1or c<1:break

		q+=a*min(b,c);c-=b

	return q

w=[]

for _ in '0'*n:I();w+=[[list(I())for _ in '0'*m]]

print(max(r(w[i],w[j])for i in R(n)for j in R(n)))

# Made By Mostafa_Khaled


n,m,capacity = [int(x) for x in raw_input().split()]

class Planet:
    def __init__(self):
        self.a = []
        self.b = []
        self.c = []
        self.n = ""
    def __repr__(self):
        return "%s: a:%r, b:%r, c:%r" % (self.n, self.a, self.b,self.c)

def calc_profit(p1, p2):
    #print "%s -> %s" % (p1.n, p2.n)
    profits = []
    for j in range(m):
        if p1.c[j] == 0:
            continue
        profit = p2.b[j] - p1.a[j]
        if profit > 0:
            profits.append((profit, p1.c[j]))
    profits.sort(reverse=True)
    load = 0
    total_profit = 0
    for p in profits:
        if load + p[1] > capacity:
            c = capacity - load
        else:
            c = p[1]
        total_profit += p[0]*c
        load += c
        if c != p[1]:
            break
    #print "profit: %d" % total_profit
    return total_profit

ps = []

for i in range(n):
    p = Planet()
    p.n = raw_input()
    for j in range(m):
        a,b,c = [int(x) for x in raw_input().split()]
        p.a.append(a)
        p.b.append(b)
        p.c.append(c)
    ps.append(p)

max_profit = -1

for n1 in range(n):
    for n2 in range(n):
        if n1 != n2:
            profit = calc_profit(ps[n1], ps[n2])
            max_profit = max(max_profit, profit)

print max_profit


import sys
n, m, k = map(int, sys.stdin.readline().split())
data = []
for i in xrange(n):
    tmp = sys.stdin.readline()
    items = []
    for j in xrange(m):
        item = map(int, sys.stdin.readline().split())
        items.append(item)
    data.append(items)
ans = 0

for i in xrange(n):
    for j in xrange(n):
        if i == j: continue
        ii = data[i]
        ij = data[j]
        cat = []
        for l in xrange(m):
            buyinfo = ii[l]
            sellinfo = ij[l]
            profit = sellinfo[1] - buyinfo[0]
            num = buyinfo[2]
            if profit > 0 and num > 0:
                cat.append([profit, num])
        cat.sort(reverse=True)
        rem = k
        tmp = 0
        for (profit, num) in cat:
            n_ = min(num, rem)
            tmp += profit * n_
            rem -= n_
            if rem == 0:
                break
        #print i, j, tmp
        ans = max(ans, tmp)
print ans


import math, collections
mod = 10**9+7

def isPower(n):
    if (n <= 1):
        return True
    for x in range(2, (int)(math.sqrt(n)) + 1):
        p = x
        while (p <= n):
            p = p * x
            if (p == n):
                return True
    return False
n = int(input())
arr = [0,1,2,1,4,3,2,1,5,6,2,1,8,7,5,9,8,7,3,4,7,4,2,1,10,9,3,6,11,12]
ans = arr[int(math.log(n, 2))]
s = int(math.log(n, 2))
for i in range(3, int(n**0.5)+1):
    if not isPower(i):
        ans^=arr[int(math.log(n, i))]
        s+=int(math.log(n, i))
ans^=((n-s)%2)
print("Vasya" if ans else "Petya")


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


from itertools import *

l1, r1, l2, r2 = map(int, raw_input().split())
la = set()
lb = set()

def foo(l, r, pv, li):
    if l > r:
        return
    if (l, r) in li:
        return
    while pv > 1 and (pv - 1) / 2 >= r:
        pv = (pv - 1) / 2
    li.add((l, r))
    if l <= r and pv >= 3:
        pv = (pv - 1) / 2
        foo(l, min(pv, r), pv, li)
        foo(max(l - pv - 1, 1), min(pv, r - pv - 1), pv, li)

pv = 1
for i in range(32):
    pv = pv * 2 + 1
foo(l1, r1, pv, la)
foo(l2, r2, pv, lb)

ans = 0
#print la
#print lb
for a in la:
    for b in lb:
        ans = max(ans, min(a[1], b[1]) - max(a[0], b[0]) + 1)
print ans


a, b, m = raw_input().split()
x, y, z = raw_input().split()
a, b, m = float(a), float(b), float(m)
x, y, z = float(x), float(y), float(z)

t = -m / y
p = a / 2 + x * t
q = z * t

while p > a or p < 0:
    if p > a:
        p = a * 2 - p
    else:
        p = -p

while q > b or q < 0:
    if q > b:
        q = b * 2 - q
    else:
        q = -q

print("%.10lf %.10lf" % (p, q))


#-*-coding=utf8-*-
debug = False

a,b,m = map(int, raw_input('').split(' '))
vx,vy,vz = map(int, raw_input('').split(' '))

A,B,C,D = 0,1,0,0
x0,y0,z0 = a/2.0, m, 0
t = (-A*x0-B*y0-C*z0-D)/float(A*vx+B*vy+C*vz)
xi,yi,zi = x0+t*vx, y0+t*vy, z0+t*vz
xi,yi,zi = abs(xi)%(2*a), abs(yi)%m, abs(zi)%(2*b)
if xi>a:
    xi = abs(xi-2*a)

if zi>b:
    zi = abs(zi-2*b)

if not debug:
    print("%.10f %.10f" % (xi,zi))


read = lambda: map(int, input().split())
n, v, e = read()
adj = [[] for _ in range(n + 1)]
As = [0] + list(read())
Bs = [0] + list(read())
ans = []

for _ in range(e):
    a, b = map(int, input().split())
    adj[a].append(b)
    adj[b].append(a)

def flow(a, b, d):
    As[a] -= d
    As[b] += d
    ans.append((a, b, d));

def augment(path, e, d):
    if e:
        dd = min(d, As[path[e - 1]], v - As[path[e]])
        flow(path[e - 1], path[e], dd)
        augment(path, e - 1, d)
        if d > dd:
            flow(path[e - 1], path[e], d - dd);

def adjust(s):
    pre = [0] * (n + 1)
    pre[s] = -1
    stk = [s]
    e = 0
    while len(stk):
        p = stk[-1]
        del stk[-1]
        if As[p] < Bs[p]:
            e = p
            break
        for to in adj[p]:
            if not pre[to]:
                pre[to] = p
                stk.append(to)

    if not e:
        raise Exception
    path = []
    while e > 0:
        path.insert(0, e)
        e = pre[e]
    augment(path, len(path) - 1, min(Bs[path[-1]] - As[path[-1]], As[s] - Bs[s]))

try:
    while True:
        check = False
        for i in range(1, n + 1):
            if As[i] > Bs[i]:
                adjust(i)
                check = True
        if not check:
            break
    for i in range(1, n + 1):
        if As[i] != Bs[i]:
            raise Exception
    print(len(ans))
    for tp in ans:
        print(*tp)
except Exception:
    print("NO")


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

[t1,t2,x1,x2,t0]=input().split(' ')
#[t1,t2,x1,x2,t0]=[100,110,2,2,109]
t1=int(t1)
t2=int(t2)
x1=int(x1)
x2=int(x2)
t0=int(t0)

a=t2-t0
b=t0-t1

if(a==0 and b==0):
    print(x1,x2)
    exit(0)

if (a==0):
    y1=0
    y2=x2
    print(y1,y2)
    exit(0)

if (b==0):
    y1=x1
    y2=0
    print(y1,y2)
    exit(0)

g=gcd(a,b)
a=int(a/g)
b=int(b/g)
if(a<=x1 and b<=x2):
    mintime=int(x1/a)
    if(mintime>int(x2/b)):
        mintime=int(x2/b)
    print(mintime*a,mintime*b)
    exit(0)

y1=1
y2=1
miny1=1
miny2=1
minn=99999
fg=0
while(y1<=x1 and y2<=x2):
    if(y1/y2<a/b):
        if(minn>a/b-y1/y2):
            minn=a/b-y1/y2
            miny1=y1
            miny2=y2
            fg=1
        y1=y1+1
    else:
        y2=y2+1
y1=miny1
y2=miny2
mintime=int(x1/y1)
if(mintime>int(x2/y2)):
    mintime=int(x2/y2)
if(fg==1):
    print(mintime*y1,mintime*y2)
else:
    print(0,x2)


import math
def gcd(a,b):
    if(b==0):
        return a
    return gcd(b,a%b)
l=input().split()
t1=int(l[0])
t2=int(l[1])
x1=int(l[2])
x2=int(l[3])
t0=int(l[4])
num1=t2-t0
num2=t0-t1
if(t1==t2):
    print(x1,x2)
    quit()
if(num1==0):
    print(0,x2)
    quit()
if(num2==0):
    print(x1,0)
    quit()
z=num2/num1
maxa=10**18
ans=(0,0)
for i in range(1,x1+1):
    ok=z*i
    if(ok>x2):
        break
    num1=i
    num2=math.ceil(ok)
    if(maxa==((num2/num1)-z) and num2+num1>ans[0]+ans[1]):
        ans=(num1,num2)
    elif(maxa>((num2/num1)-z)):
        ans=(num1,num2)
        maxa=((num2/num1-z))
if(ans==(0,0)):
    ans=(0,x2)
print(ans[0],ans[1])


from collections import deque
def main():
    n, m = map(int, raw_input().split())
    b = [list(raw_input().strip()) for _ in xrange(n)]
    def inboard(y, x):
        return 0 <= y < n and 0 <= x < m
    c = 0
    for i in xrange(n):
        for j in xrange(m):
            if b[i][j] in '123456789':
                c += 1
                b[i][j] = chr(ord(b[i][j]) - 1)
            elif b[i][j] == 'S':
                sy, sx = i, j
    v = [int(raw_input()) for _ in xrange(c)]
    inf = 1000000
    up = [[0] * m for i in xrange(n)]
    down = [[0] * m for i in xrange(n)]
    for i in xrange(n):
        for j in xrange(m):
            if b[i][j] in '0123456789':
                for l in xrange(j+1, m):
                    up[i][l] |= 1 << int(b[i][j])
                    down[i][l] |= 1 << int(b[i][j])
            elif b[i][j] == 'B':
                for l in xrange(j+1, m):
                    up[i][l] |= 1 << c
                    down[i][l] |= 1 << c
                v.append(-inf)
                c += 1
    dp = [[[inf] * (1 << c) for j in xrange(m)] for i in xrange(n)]
    dp[sy][sx][0] = 0
    d = [(-1, 0), (1, 0), (0, 1), (0, -1)]
    q = deque()
    q.append((sy, sx, 0, 0))
    while q:
        y, x, mask, t = q.popleft()
        if t > dp[y][x][mask]: continue
        nt = t + 1
        for dy, dx in d:
            ny, nx, nmask = dy + y, dx + x, mask
            if not inboard(ny, nx) or b[ny][nx] not in '.S': continue
            if dx == 0:
                if dy == 1:
                    nmask ^= down[ny][nx]
                else:
                    nmask ^= down[y][x]
            if dp[ny][nx][nmask] > nt:
                dp[ny][nx][nmask] = nt
                q.append((ny, nx, nmask, nt))
    print max(sum(v[j] for j in xrange(c) if ((i >> j) & 1))-dp[sy][sx][i] for i in xrange(1 << c))
main()