#include<set>
#include<map>
#include<list>
#include<iomanip>
#include<cmath>
#include<string>
#include<vector>
#include<queue>
#include<stack>
#include<complex>
#include<sstream>
#include<iostream>
#include<fstream>
#include<algorithm>
#include<numeric>
#include<utility>
#include<functional>
#include<stdio.h>
#include<assert.h>
#include<memory.h>
#include<bitset>
using namespace std;

typedef long long         ll;

ll sum(ll n)
{
	return (n * (n+1)) / 2;
}

// sum: s s+1 s+2 ... e
ll sum(ll s, ll e)
{
	if(s <= 1)
		return sum(e);

	return sum(e) - sum(s-1);
}

ll minSplitters(ll k, ll n)
{
	ll st = 1, en = k;

	while(st < en)
	{
		ll md = (st + en)/2;
		ll s = sum(md, k);

		if(s == n)
			return k - md + 1;

		if(s > n)
			st = md+1;
		else
			en = md;
	}

	return k - st + 2;
}

int main()
{
	ll n, k;
	cin>>n>>k;

	if(n == 1)
		cout<<0<<"\n";		// already just 1 out flow source exist
	else if(n <= k)
		cout<<1<<"\n";		// we have 1-n splitter already
	else
	{
		--k;
		--n;

		if(sum(k) < n)
			cout<<-1<<"\n";
		else
			cout<<minSplitters(k, n)<<"\n";
	}

 	return 0;
}


# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
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")

# -------------------game starts now----------------------------------------------------import math
class TreeNode:
    def __init__(self, k, v):
        self.key = k
        self.value = v
        self.left = None
        self.right = None
        self.parent = None
        self.height = 1
        self.num_left = 1
        self.num_total = 1

class AvlTree:

    def __init__(self):
        self._tree = None

    def add(self, k, v):
        if not self._tree:
            self._tree = TreeNode(k, v)
            return
        node = self._add(k, v)
        if node:
            self._rebalance(node)

    def _add(self, k, v):
        node = self._tree
        while node:
            if k < node.key:
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(k, v)
                    node.left.parent = node
                    return node.left
            elif node.key < k:
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(k, v)
                    node.right.parent = node
                    return node.right
            else:
                node.value = v
                return

    @staticmethod
    def get_height(x):
        return x.height if x else 0

    @staticmethod
    def get_num_total(x):
        return x.num_total if x else 0

    def _rebalance(self, node):

        n = node
        while n:
            lh = self.get_height(n.left)
            rh = self.get_height(n.right)
            n.height = max(lh, rh) + 1
            balance_factor = lh - rh
            n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
            n.num_left = 1 + self.get_num_total(n.left)

            if balance_factor > 1:
                if self.get_height(n.left.left) < self.get_height(n.left.right):
                    self._rotate_left(n.left)
                self._rotate_right(n)
            elif balance_factor < -1:
                if self.get_height(n.right.right) < self.get_height(n.right.left):
                    self._rotate_right(n.right)
                self._rotate_left(n)
            else:
                n = n.parent

    def _remove_one(self, node):
        """
        Side effect!!! Changes node. Node should have exactly one child
        """
        replacement = node.left or node.right
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = replacement
            else:
                node.parent.right = replacement
            replacement.parent = node.parent
            node.parent = None
        else:
            self._tree = replacement
            replacement.parent = None
        node.left = None
        node.right = None
        node.parent = None
        self._rebalance(replacement)

    def _remove_leaf(self, node):
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = None
            else:
                node.parent.right = None
            self._rebalance(node.parent)
        else:
            self._tree = None
        node.parent = None
        node.left = None
        node.right = None

    def remove(self, k):
        node = self._get_node(k)
        if not node:
            return
        if AvlTree._is_leaf(node):
            self._remove_leaf(node)
            return
        if node.left and node.right:
            nxt = AvlTree._get_next(node)
            node.key = nxt.key
            node.value = nxt.value
            if self._is_leaf(nxt):
                self._remove_leaf(nxt)
            else:
                self._remove_one(nxt)
            self._rebalance(node)
        else:
            self._remove_one(node)

    def get(self, k):
        node = self._get_node(k)
        return node.value if node else -1

    def _get_node(self, k):
        if not self._tree:
            return None
        node = self._tree
        while node:
            if k < node.key:
                node = node.left
            elif node.key < k:
                node = node.right
            else:
                return node
        return None

    def get_at(self, pos):
        x = pos + 1
        node = self._tree
        while node:
            if x < node.num_left:
                node = node.left
            elif node.num_left < x:
                x -= node.num_left
                node = node.right
            else:
                return (node.key, node.value)
        raise IndexError("Out of ranges")

    @staticmethod
    def _is_left(node):
        return node.parent.left and node.parent.left == node

    @staticmethod
    def _is_leaf(node):
        return node.left is None and node.right is None

    def _rotate_right(self, node):
        if not node.parent:
            self._tree = node.left
            node.left.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.left
            node.left.parent = node.parent
        else:
            node.parent.right = node.left
            node.left.parent = node.parent
        bk = node.left.right
        node.left.right = node
        node.parent = node.left
        node.left = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    def _rotate_left(self, node):
        if not node.parent:
            self._tree = node.right
            node.right.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.right
            node.right.parent = node.parent
        else:
            node.parent.right = node.right
            node.right.parent = node.parent
        bk = node.right.left
        node.right.left = node
        node.parent = node.right
        node.right = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    @staticmethod
    def _get_next(node):
        if not node.right:
            return node.parent
        n = node.right
        while n.left:
            n = n.left
        return n

# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: a + b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]

class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
    if a == 1 or n == 0:
        return 1
    if n % 2 == 0:
        s = powm(a, n // 2, m)
        return s * s % m
    else:
        return a * powm(a, n - 1, m) % m

# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z

# --------------------------------------------------product----------------------------------------
def product(l):
    por = 1
    for i in range(len(l)):
        por *= l[i]
    return por

# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left) / 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid] < key):
            count = mid + 1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count

# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c
def binary(x, length):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y

def countGreater(arr, n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] >= k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)

# --------------------------------------------------binary------------------------------------
n,k=map(int,input().split())
l=[]
se=set()
for i in range(k):
    a,b,c=map(int,input().split())
    l.append((a,b,c,i))
    se.add(b)
l.sort()
stack=[]
t=0
ans=[0]*n
for i in range(n):
    if t<k:
        while(l[t][0]==i+1):
            stack.append([l[t][2],l[t][1],l[t][-1]])
            t+=1
            if t==k:
                break
    if len(stack)==0:
        continue
    stack.sort(reverse=True)
    for j in range(len(stack)):
        if stack[j][1]==i+1:
            print(-1)
            sys.exit(0)
    if i+1 in se:
        continue
    stack[-1][0]-=1
    ans[i]=stack[-1][2]+1
    if stack[-1][0]==0:
        stack.pop()
for i in range(k):
    ans[l[i][1]-1]=k+1
print(*ans)


#	!/bin/env python3
#	coding: UTF-8

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology and Management,Gwalior

#	Question Link
#	https://codeforces.com/problemset/problem/998/B
#

# ///==========Libraries, Constants and Functions=============///

import sys
sys.setrecursionlimit(2000)
inf = float("inf")
mod = 1000000007

def get_array(): return list(map(int, sys.stdin.readline().split()))

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

def input(): return sys.stdin.readline()

# ///==========MAIN=============///

def recurse(difference, arr, i, b):
    if b < 0:
        return -1*inf
    if i == len(difference)-1:
        return 0
    if difference[i] == 0:
        return max(1+recurse(difference, arr, i+1, b-abs(arr[i+1]-arr[i])), recurse(difference, arr, i+1, b))
    else:
        return recurse(difference, arr, i+1, b)

def main():
    n, b = get_ints()
    arr = get_array()
    difference = [0]*n
    count_even, count_odd = 0, 0
    for i in range(n):
        if arr[i] & 1 != 0:
            count_odd += 1
        else:
            count_even += 1
        difference[i] = abs(count_odd-count_even)
    print(recurse(difference, arr, 0, b))

if __name__ == "__main__":
    main()


with i as input():
    print(1 if i[-1]%2 else 0)


s = raw_input().split()

n = int(s[0])
w = int(s[1])
a = int(s[2])
b = int(s[3])

import math

sa = int(math.ceil(float(a) / w))
sb = int(math.ceil(float(b) / w))

if sb * w > n and b == n:
    b = sb * w

h = sb - sa

if h == 0:
    print 1
    exit()

if h > 1:
    ch = 1
else:
    ch = 0

if a != (sa - 1) * w + 1:
    ca = 1
else:
    ca = 0

if b != sb * w:
    cb = 1
else:
    cb = 0

c = ca + cb + ch
if c == 1 and (ca > 0 or cb > 0):
    c = 2
if c == 0:
    c = 1

if c == 3 and (a - (sa - 1) * w) == (b - (sb - 1) * w) + 1:
    c = 2

print c


n = int(input())
d = [int(input())]
d.append(int(input()))
d.append(int(input()))

i = d.index(min(d))
if i < 1.5:
    print((n-1)*d[i])
else:
    s = d[i]
    del d[i]
    print((n-2)*s3+min(d))


x,k=map(int,input().split())
#x=60
#k=5
if x==1:
    print(1)
    import sys
    sys.exit()

import math
L=int(math.sqrt(x))
mod=10**9+7
FACT=dict()

for i in range(2,L+2):
    while x%i==0:
        FACT[i]=FACT.get(i,0)+1
        x=x//i

if x!=1:
    FACT[x]=FACT.get(x,0)+1

def prod(A,B,k,l,m):#A:k*l,B:l*m
    C=[[None for i in range(m)] for j in range(k)]

    for i in range(k):
        for j in range(m):
            ANS=0
            for pl in range(l):
                ANS=(ANS+A[i][pl]*B[pl][j])%mod

            C[i][j]=ANS

    return C

def plus(A,B,k,l):#a,B:k*l
    C=[[None for i in range(l)] for j in range(k)]

    for i in range(k):
        for j in range(l):
            C[i][j]=(A[i][j]+B[i][j])%mod

    return C

#XX=[[1,1],[1,1],[1,1]]
#YY=[[2,2,2],[2,3,4]]
#print(prod(XX,YY,3,2,3))

MAT_index=max(FACT.values())+1
MAT=[[0 for i in range(MAT_index)] for j in range(MAT_index)]

for m in range(MAT_index):
    for l in range(m+1):
        x=pow(m+1,mod-2,mod)
        MAT[m][l]=x

#print(MAT)

#MAT_ini=MAT
#for i in range(k-1):
#    MAT=prod(MAT,MAT_ini,MAT_index,MAT_index,MAT_index)

#ここをダブリング

MAT_dob=[None]*13
MAT_dob[0]=MAT
for i in range(1,13):
    MAT_dob[i]=prod(MAT_dob[i-1],MAT_dob[i-1],MAT_index,MAT_index,MAT_index)

MAT=[[0 for i in range(MAT_index)] for j in range(MAT_index)]
for i in range(MAT_index):
    MAT[i][i]=1

for i in range(13):
    if k & 1<<i !=0:
        #print(i,MAT,MAT_dob[i])
        MAT=prod(MAT,MAT_dob[i],MAT_index,MAT_index,MAT_index)
        #print(MAT)

#print(MAT)

ANS=1
for fa in FACT:
    x=FACT[fa]
    ANS_fa=0

    for i in range(x+1):
        ANS_fa=(ANS_fa+pow(fa,i,mod)*MAT[x][i])%mod

    ANS=ANS*ANS_fa%mod

print(ANS)


a, b, c = raw_input().split()

#a = input
#b = 3
#c = 4
d = c * b + ((c + b - 1) * (a - 1))
print d


from copy import copy
qaq = 0
A = list(map(int, input().split()))
for z in range(14):
    if A[z] != 0:
        K = copy(A)
        for i in range(z+1, z+K[z]+1):
            i %= 14
            if i != z%14:
                K[i] += 1
        K[z] = K[z] // 14
        cnt = 0
        for t in K:
            if t%2 == 0:
                cnt += t
        qaq = max(qaq, cnt)
print(qaq)


a=[int (i) for i in (input().split())]
f,sm=[0,1,1],[0]
s,k=a[0],a[1]
ssum=0
while ssum<s :
    i=k+2
    sumi=1
    while sumi<=s-ssum :
        sumi+=f[i-k]
        i+=1
        if ssum==0 :
            f.append(2*f[i-k-1])
            if i-k-k-1 >=0 :
                f[i-k]=f[i-k]-f[i-k-k-1]
    ssum+=f[i-k-1]
    sm.append(f[i-k-1])
print(len(sm))
print(" ".join([str(i) for i in sm]))


p=10**9+7
def S(x):
	if x==0:
		return 0
	elif x==1:
		return 4
	elif x&1:
		return 11*pow(3,x/2,p)-7
	else:
		return 19*pow(3,x/2-1,p)-7
def G(x):
	return (S(x)+S(x+1>>1))*pow(2,p-2,p)%p;
l,r=map(int,raw_input().split())
print (G(r)-G(l-1))%p;


#!/usr/bin/env python
'''
' Author:   Cheng-Shih Wong
' Email:    mob5566@gmail.com
' Date:     2017-09-22
'''

def main():

    def num(left, right, dp, rev, revI):
        if left > right:
            return 1

        key = left, rev, revI
        if key in dp:
            return dp[key]
        nonlocal ans

        acc = 0

        for x in ('01' if ans[left]=='#' else ans[left]):

            temp = None
            if left == right:
                tmp = x
            elif ans[right]=='#':
                tmp = '01'
            else:
                tmp = ans[right]

            for y in tmp:
                if not ((rev and x>y) or (revI and x==y=='1')):
                    acc += num(
                        left+1,
                        right-1,
                        dp,
                        rev and x==y,
                        revI and x!=y
                    )
        dp[key] = acc
        return acc

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

    ans = ['#'] * n

    for i in range(n):
        ans[i] = '0'
        tmp = num(0, n-1, {}, True, True)

        if k > tmp:
            k -= tmp
            ans[i] = '1'

    if ans[0] == '0':
        print(''.join(ans))
    else:
        print(-1)

if __name__ == '__main__':
    import sys, os
    from time import time
    if len(sys.argv)>1 and os.path.exists(sys.argv[1]):
        sys.stdin = open(sys.argv[1], 'rb')
    st = time()
    main()
    print('----- Run {:.6f} seconds. -----'.format(time()-st), file=sys.stderr)


inp = input()
if len(inp)>1 and inp[0]=='0':
  print(0)
  exit()
if inp == '0':
  print(1)
  exit()
if inp == 'XX':
  print(0)
  exit()
if inp in ['__', '_X', 'X_']:
  print(3)
  exit()
if(len(inp) < 2):
  print(0)
  exit()
l1 = inp[-1]
l2 = inp[-2]

poss = 0
has_x = False
has_xx = False
if l2+l1 == '0X':
  has_xx = True
if l2+l1 in ['00', '25', '50', '75']:
  poss = 1
elif l2 == '_':
  poss = 4
  if l1 not in ['X', '_']:
    if l1 in ['0', '5']:
      poss = 2
    else:
      poss = 0
  elif l1 == 'X':
    has_x = True
elif l2 == 'X':
  has_x = True
  if l1 == 'X':
    has_xx = True
    poss = 1
  elif l1 == '_':
    poss = 4
  elif l1 in ['0', '5']:
    poss = 2
elif l2 in ['0', '2', '5', '7']:
  if l1 == '_':
    poss = 1
  elif l1 == 'X':
    has_x = True
    poss = 1
  else:
    poss = 0
else:
  poss = 0

for i in range(len(inp) - 2):
  if inp[i] == '_':
    if i == 0:
      poss *= 9
    else:
      poss *= 10
  if inp[i] == 'X':
    if i == 0:
      if has_xx:
        poss = 0
      else:
        poss *= 9
    elif not has_x:
        poss *= 10
    has_x = True
print(poss)

# 0X
# 1X
# _X
# XX

# 00 -> 1
# 01 -> 0
# 0_ -> 1
# 0X -> 1

# 10 -> 0

# _0 -> 2
# _1 -> 0
# __ -> 4
# _X -> 4

# X0 -> 2
# X1 -> 0
# X_ -> 4
# XX -> 1

  print(0)
  exit()
if inp in ['__', '_X', 'X_']:
  print(3)
  exit()
if(len(inp) < 2):
  print(0)
  exit()
l1 = inp[-1]
l2 = inp[-2]

poss = 0
has_x = False
has_xx = False
if l2+l1 in ['00', '25', '50', '75']:
  poss = 1
elif l2 == '_':
  poss = 4
  if l1 not in ['X', '_']:
    if l1 in ['0', '5']:
      poss = 2
    else:
      poss = 0
  elif l1 == 'X':
    has_x = True
elif l2 == 'X':
  has_x = True
  if l1 == 'X':
    has_xx = True
    poss = 1
  elif l1 == '_':
    poss = 4
  elif l1 in ['0', '5']:
    poss = 2
elif l2 in ['0', '2', '5', '7']:
  if l1 == '_':
    poss = 1
  elif l1 == 'X':
    has_x = True
    poss = 1
  else:
    poss = 0
else:
  poss = 0

for i in range(len(inp) - 2):
  if inp[i] == '_':
    if i == 0:
      poss *= 9
    else:
      poss *= 10
  if inp[i] == 'X':
    if i == 0:
      if has_xx:
        poss = 0
      else:
        poss *= 9
    elif not has_x:
        poss *= 10
    has_x = True
print(poss)

# 0X
# 1X
# _X
# XX

# 00 -> 1
# 01 -> 0
# 0_ -> 1
# 0X -> 1

# 10 -> 0

# _0 -> 2
# _1 -> 0
# __ -> 4
# _X -> 4

# X0 -> 2
# X1 -> 0
# X_ -> 4
# XX -> 1


from math import sqrt

def factorization(n):
    fact=[]
    for i in range(1, int(sqrt(n)+1)):
        if n%i == 0:
            fact.append(i)
            fact.append(n//i)
    return fact
s=0
n = int(input())
n2=str(n)
fact=factorization(n)
Setfact=set(fact)
fact=list(Setfact)
for i in range(len(Setfact)):
    for j in range(len(n2)):
        if n2[j] in str(fact[i]):
            s+=1
            break
print(s)

'''m={}
m2=[]
n2=str(n)
s=0
i=1


from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right

import sys
def input():
    return sys.stdin.readline().rstrip()
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getListGraph():
    return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]

mod = 10 ** 9 + 7
MOD = 998244353
sys.setrecursionlimit(1000000)
inf = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]

#############
# Main Code #
#############

N = getN()
same = [0] * (N + 1)
for i in range(1, N + 1):
    for j in range(i, N + 1, i):
        same[j] += 1
dp = [0] * (N + 1)
acc = [0] * (N + 1)

for i in range(1, N + 1):
    dp[i] = same[i] + acc[i - 1]
    dp[i] %= MOD
    acc[i] = dp[i] + acc[i - 1]
    acc[i] %= MOD
print(dp[N])


#!/usr/bin/python

# -*- coding: koi8-r -*-

def main():
    a = raw_input()
    b = raw_input()
    a = [int(i) for i in a.strip().split()]
    b = [int(i) for i in b.strip().split()]

    if b[0]+1>=a[1] and 2*a[1]+2>=b[0] or b[1]+1>=a[0] and 2*a[0]+2>=b[1]:
        print 'YES'
    else
        print 'NO'

if __name__ == '__main__':
    main()


import math
if k >= n:
    print('NO')
else:
    t_1 = t*n/k

    if d % t == 0:

        x = d/t
        m = x*k
        t_2 = x*t
        while m < n:
            t_2 += t
            m += 2*k
    elif d < t:
        m = k
        t_2 = t
        while m < n:
            t_2 += d
            m += k
            if m <n:
                t_2 += t-d
    elif d > t:
        x = math.ceil(d/t)
        t_2 = x*t
        m = (x-1)*k
        while m < n:
            t_2 += d-x*t
            m += k
            if m < n:
                t_2 += (x+1)*t-d
                m += k


a, b = input().split()
x = int(max(a + b)) + 1
print(len(str(int(str(int(a, x) + int(b, x)), x))))


#!/usr/bin/env python

import sys

l = [line.split()[0] for line in sys.stdin.readlines()]
for line in l:
    if line != 'WBWBWBWB' and line != 'BWBWBWBW':
        result = 'NO'
        break
if result = 'NO':
    print "NO"
else:
    print 'YES'


import sys
import math
import bisect
import atexit
import io
import heapq
from collections import defaultdict, Counter
MOD = int(1e9+7)

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

n, m = map(int, raw_input().split())
da = map(int, raw_input().split())
di = {}
to = 0
for i in range(n):
    di[i+1] = da[i]
    to+=da[i]
pa = []
for i in range(m):
    a,b = map(int, raw_input().split())
    pa.append((a,b))
pa.sort()
have = 0
idx = 0
day = 0
while to!=0:
    have += 1
    day += 1
    while idx<m and pa[idx][0] < day:
        idx += 1
    while idx<m and pa[idx][0] == day:
        if di[pa[idx][1]] > 0:
            buy = min(have, di[pa[idx][1]])
            to -= buy
            di[pa[idx][1]] -= buy
            have -= buy
        idx += 1
    if have/2 >= to:
        print day
        exit(0)


(a, b) = raw_input().split(" ")
requests = raw_input().split(" ")

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

library = []

price = 0

occurences = {}

for e in requests:
	real = int(e)

	if real in occurences:
		occurences[real] += 1
	else:
		occurences[real] = 1

for i in range(n):
	element = int(requests[i])

	occurences[element] -= 1;

	if element in library:
		continue

	if len(library) == k:
		processed = False

		for i in library:
			if occurences[i] <= 0:
				library.remove(i)
				processed = True
				break

 		if not processed:
			for j in range(n - 1, i, -1):
				object = int(requests[j])

				if object in library:
					library.remove(object)
					break

	library.append(element)
	price += 1;

print price


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

import time

n   = int(input())

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

start = time.time()

m  = 1

for i in range(n):
    m  *= M[i]

a = [ 0 for i in range(m)]

for i in range(n):
    if R[i] >= M[i]:
        continue

    now = R[i]-1
    if now < 0:
        now += M[i]

    while (now < m):
        a[now] = 1
        now += M[i]

print(sum(a)/m)
finish = time.time()
#print(finish - start)


n=input()
print n/36,
i=(n%36)/3
if n%3==2: i+=1
print i


def okay(xc, yc, rc, xr, yr, rr, Rr):
    d = ((xc-xr) ** 2 + (yc-yr) ** 2) ** 0.5
    if d + rc <= rr:
        return True
    if d >= rc + Rr:
        return True
    if d + Rr <= rc:
        return True
    return False

x1, y1, r1, R1 = map(float, input().split())
x2, y2, r2, R2 = map(float, input().split())
ans = 0
if okay(x2, y2, r2, x1, y1, r1, R1):
    ans += 1
if okay(x2, y2, R2, x1, y1, r1, R1):
    ans += 1
if okay(x1, y1, r1, x2, y2, r2, R2):
    ans += 1
if okay(x1, y1, R1, x2, y2, r2, R2):
    ans += 1
print (ans)


'''
Created on 2011-3-19

@author: zhxfl
'''
p=map(int,raw_input().split())
ans=0
a=p[4]
b=p[5]
while a<=b:
    x=a
    for i in range(4):
        x=x%p[i];
    if x==a :ans=ans+1;
    a=a+1;
print ans;


a=int(input())
b=int(input())
if b==min(a,b):
    a,b=b,a
c=(a+b)//2
d=c-a
e=b-c
s=0
p=0
    for i in range (1,d+1):
        s=s+i
        for j in range (1,e+1):
             p=p+j
print(s+p)


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

total_number = n//2

if m%2==0:
    if (total_number-m//2)==n or m==n:
        print(1)
    else:
        print((total_number-m//2)+1)
else:
    if (m+1)//2==1 or m==1:
        print(1)
    else:
        print((m+1)//2+1)


from functools import lru_cache
n,m = map(int,input().split())
arr = list(map(int,input().split()))
arr.sort(reverse=True)
@lru_cache(maxsize=n)
def drink(i,c,remain):
    if remain<=0: return 0
    elif i==n: return float('inf')
    else:
        p1 = 1 + drink( i+1, 0, remain-(arr[i]-c) ) #next day
        p2 = float('inf')
        if arr[i]-c > 0: p2 = drink( i+1, c+1, remain-(arr[i]-c) ) #current day
        return min(p1,p2)
ans = drink(0,0,m)
if ans==float('inf'):
    print(-1)
else:
    print(ans+1)


res = -1

def perebor(num, a, b):
	global res
	fail = 0

	if b == len(num):
		b = a + 2
		a = a + 1

	if a == len(num) - 1 and b == len(num):
		return

	x = num[0:a]
	y = num[a:b]
	z = num[b:]
	if len(x) > 1:
		if x[0] == '0':
			fail = 1
	if len(y) > 1:
		if y[0] == '0':
			fail = 1
	if len(z) > 1:
		if z[0] == '0':
			fail = 1

	if fail == 0:
		if int(x) <= 1000000 and int(y) <= 1000000 and int(z) <= 1000000:
			t = int(x) + int(y) + int(z)
			if t > res:
				res = t

	b += 1
	perebor(num, a, b)

num = raw_input()
if len(num) < 4:
	print -1
else
	perebor(num, 1, 2)
	print res


n,a,b=map(int,input().split())
p=list(map(int,input().split()))
q=list(p)
q.reverse()
p=p[:int((n+1)/2)]
q=q[:int((n+1)/2)]
s=0
m=min(a,b)
for i,j in zip(p,q):
    if(i==2 and j!=2):
        if(j):
            s=s+b
        else:
            s=s+a
    if(j==2 and i!=2):
        if(i):
            s=s+b
        else:
            s=s+a
    if(i==2 and j==2):
        s=s+m
    if(i!=2 and j!=2 and i!=j):
        s=-1
        break
print(s)


Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7

= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
0
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
15
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
15
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
59
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
59
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
Traceback (most recent call last):
  File "C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py", line 19, in <module>
    for x,y,z in a[0],a[1],a[2]:
ValueError: too many values to unpack (expected 3)
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
vis[10*x+y]=1;
        vis[10*y+x]=1;
Traceback (most recent call last):
  File "C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py", line 1, in <module>
    n=int(input());
ValueError: invalid literal for int() with base 10: 'vis[10*x+y]=1;'
>>> 3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
SyntaxError: multiple statements found while compiling a single statement
>>> 3
3
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
Traceback (most recent call last):
  File "C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py", line 19, in <module>
    for x,y,z in a[0],a[1],a[2]:
ValueError: too many values to unpack (expected 3)
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
vis[10*x+y]=1;
        vis[10*y+x]=1;
Traceback (most recent call last):
  File "C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py", line 1, in <module>
    n=int(input());
ValueError: invalid literal for int() with base 10: 'vis[10*x+y]=1;'
>>> 3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
SyntaxError: multiple statements found while compiling a single statement
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
Traceback (most recent call last):
  File "C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py", line 20, in <module>
    for x,y,z in a[0],a[1],a[2]:
ValueError: too many values to unpack (expected 3)
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
vis[10*x+y]=1;
        vis[10*y+x]=1;
Traceback (most recent call last):
  File "C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py", line 1, in <module>
    n=int(input());
ValueError: invalid literal for int() with base 10: 'vis[10*x+y]=1;'
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
5
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
vis[10*x+y]=1;
        vis[10*y+x]=1;'
Traceback (most recent call last):
  File "C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py", line 1, in <module>
    n=int(input());
ValueError: invalid literal for int() with base 10: 'vis[10*x+y]=1;'
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 0, 5), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 1, 5), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (0, 2, 4), (0, 2, 5), (0, 3, 0), (0, 3, 1), (0, 3, 2), (0, 3, 3), (0, 3, 4), (0, 3, 5), (0, 4, 0), (0, 4, 1), (0, 4, 2), (0, 4, 3), (0, 4, 4), (0, 4, 5), (0, 5, 0), (0, 5, 1), (0, 5, 2), (0, 5, 3), (0, 5, 4), (0, 5, 5), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 0, 4), (1, 0, 5), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 1, 5), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 0), (1, 3, 1), (1, 3, 2), (1, 3, 3), (1, 3, 4), (1, 3, 5), (1, 4, 0), (1, 4, 1), (1, 4, 2), (1, 4, 3), (1, 4, 4), (1, 4, 5), (1, 5, 0), (1, 5, 1), (1, 5, 2), (1, 5, 3), (1, 5, 4), (1, 5, 5), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 0, 3), (2, 0, 4), (2, 0, 5), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 1, 4), (2, 1, 5), (2, 2, 0), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 2, 5), (2, 3, 0), (2, 3, 1), (2, 3, 2), (2, 3, 3), (2, 3, 4), (2, 3, 5), (2, 4, 0), (2, 4, 1), (2, 4, 2), (2, 4, 3), (2, 4, 4), (2, 4, 5), (2, 5, 0), (2, 5, 1), (2, 5, 2), (2, 5, 3), (2, 5, 4), (2, 5, 5), (3, 0, 0), (3, 0, 1), (3, 0, 2), (3, 0, 3), (3, 0, 4), (3, 0, 5), (3, 1, 0), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 1, 4), (3, 1, 5), (3, 2, 0), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 2, 4), (3, 2, 5), (3, 3, 0), (3, 3, 1), (3, 3, 2), (3, 3, 3), (3, 3, 4), (3, 3, 5), (3, 4, 0), (3, 4, 1), (3, 4, 2), (3, 4, 3), (3, 4, 4), (3, 4, 5), (3, 5, 0), (3, 5, 1), (3, 5, 2), (3, 5, 3), (3, 5, 4), (3, 5, 5), (4, 0, 0), (4, 0, 1), (4, 0, 2), (4, 0, 3), (4, 0, 4), (4, 0, 5), (4, 1, 0), (4, 1, 1), (4, 1, 2), (4, 1, 3), (4, 1, 4), (4, 1, 5), (4, 2, 0), (4, 2, 1), (4, 2, 2), (4, 2, 3), (4, 2, 4), (4, 2, 5), (4, 3, 0), (4, 3, 1), (4, 3, 2), (4, 3, 3), (4, 3, 4), (4, 3, 5), (4, 4, 0), (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 4, 4), (4, 4, 5), (4, 5, 0), (4, 5, 1), (4, 5, 2), (4, 5, 3), (4, 5, 4), (4, 5, 5), (5, 0, 0), (5, 0, 1), (5, 0, 2), (5, 0, 3), (5, 0, 4), (5, 0, 5), (5, 1, 0), (5, 1, 1), (5, 1, 2), (5, 1, 3), (5, 1, 4), (5, 1, 5), (5, 2, 0), (5, 2, 1), (5, 2, 2), (5, 2, 3), (5, 2, 4), (5, 2, 5), (5, 3, 0), (5, 3, 1), (5, 3, 2), (5, 3, 3), (5, 3, 4), (5, 3, 5), (5, 4, 0), (5, 4, 1), (5, 4, 2), (5, 4, 3), (5, 4, 4), (5, 4, 5), (5, 5, 0), (5, 5, 1), (5, 5, 2), (5, 5, 3), (5, 5, 4), (5, 5, 5)]
5
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 0, 5), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 1, 5), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (0, 2, 4), (0, 2, 5), (0, 3, 0), (0, 3, 1), (0, 3, 2), (0, 3, 3), (0, 3, 4), (0, 3, 5), (0, 4, 0), (0, 4, 1), (0, 4, 2), (0, 4, 3), (0, 4, 4), (0, 4, 5), (0, 5, 0), (0, 5, 1), (0, 5, 2), (0, 5, 3), (0, 5, 4), (0, 5, 5), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 0, 4), (1, 0, 5), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 1, 5), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 0), (1, 3, 1), (1, 3, 2), (1, 3, 3), (1, 3, 4), (1, 3, 5), (1, 4, 0), (1, 4, 1), (1, 4, 2), (1, 4, 3), (1, 4, 4), (1, 4, 5), (1, 5, 0), (1, 5, 1), (1, 5, 2), (1, 5, 3), (1, 5, 4), (1, 5, 5), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 0, 3), (2, 0, 4), (2, 0, 5), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 1, 4), (2, 1, 5), (2, 2, 0), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 2, 5), (2, 3, 0), (2, 3, 1), (2, 3, 2), (2, 3, 3), (2, 3, 4), (2, 3, 5), (2, 4, 0), (2, 4, 1), (2, 4, 2), (2, 4, 3), (2, 4, 4), (2, 4, 5), (2, 5, 0), (2, 5, 1), (2, 5, 2), (2, 5, 3), (2, 5, 4), (2, 5, 5), (3, 0, 0), (3, 0, 1), (3, 0, 2), (3, 0, 3), (3, 0, 4), (3, 0, 5), (3, 1, 0), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 1, 4), (3, 1, 5), (3, 2, 0), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 2, 4), (3, 2, 5), (3, 3, 0), (3, 3, 1), (3, 3, 2), (3, 3, 3), (3, 3, 4), (3, 3, 5), (3, 4, 0), (3, 4, 1), (3, 4, 2), (3, 4, 3), (3, 4, 4), (3, 4, 5), (3, 5, 0), (3, 5, 1), (3, 5, 2), (3, 5, 3), (3, 5, 4), (3, 5, 5), (4, 0, 0), (4, 0, 1), (4, 0, 2), (4, 0, 3), (4, 0, 4), (4, 0, 5), (4, 1, 0), (4, 1, 1), (4, 1, 2), (4, 1, 3), (4, 1, 4), (4, 1, 5), (4, 2, 0), (4, 2, 1), (4, 2, 2), (4, 2, 3), (4, 2, 4), (4, 2, 5), (4, 3, 0), (4, 3, 1), (4, 3, 2), (4, 3, 3), (4, 3, 4), (4, 3, 5), (4, 4, 0), (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 4, 4), (4, 4, 5), (4, 5, 0), (4, 5, 1), (4, 5, 2), (4, 5, 3), (4, 5, 4), (4, 5, 5), (5, 0, 0), (5, 0, 1), (5, 0, 2), (5, 0, 3), (5, 0, 4), (5, 0, 5), (5, 1, 0), (5, 1, 1), (5, 1, 2), (5, 1, 3), (5, 1, 4), (5, 1, 5), (5, 2, 0), (5, 2, 1), (5, 2, 2), (5, 2, 3), (5, 2, 4), (5, 2, 5), (5, 3, 0), (5, 3, 1), (5, 3, 2), (5, 3, 3), (5, 3, 4), (5, 3, 5), (5, 4, 0), (5, 4, 1), (5, 4, 2), (5, 4, 3), (5, 4, 4), (5, 4, 5), (5, 5, 0), (5, 5, 1), (5, 5, 2), (5, 5, 3), (5, 5, 4), (5, 5, 5)]
5
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
[(0, 6, 2), (0, 6, 3), (0, 6, 4), (0, 6, 5), (0, 6, 6), (0, 6, 7), (0, 6, -1), (0, 7, 2), (0, 7, 3), (0, 7, 4), (0, 7, 5), (0, 7, 6), (0, 7, 7), (0, 7, -1), (0, 8, 2), (0, 8, 3), (0, 8, 4), (0, 8, 5), (0, 8, 6), (0, 8, 7), (0, 8, -1), (0, 9, 2), (0, 9, 3), (0, 9, 4), (0, 9, 5), (0, 9, 6), (0, 9, 7), (0, 9, -1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 0, 5), (0, 0, 6), (0, 0, 7), (0, 0, -1), (0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 1, 5), (0, 1, 6), (0, 1, 7), (0, 1, -1), (0, -1, 2), (0, -1, 3), (0, -1, 4), (0, -1, 5), (0, -1, 6), (0, -1, 7), (0, -1, -1), (1, 6, 2), (1, 6, 3), (1, 6, 4), (1, 6, 5), (1, 6, 6), (1, 6, 7), (1, 6, -1), (1, 7, 2), (1, 7, 3), (1, 7, 4), (1, 7, 5), (1, 7, 6), (1, 7, 7), (1, 7, -1), (1, 8, 2), (1, 8, 3), (1, 8, 4), (1, 8, 5), (1, 8, 6), (1, 8, 7), (1, 8, -1), (1, 9, 2), (1, 9, 3), (1, 9, 4), (1, 9, 5), (1, 9, 6), (1, 9, 7), (1, 9, -1), (1, 0, 2), (1, 0, 3), (1, 0, 4), (1, 0, 5), (1, 0, 6), (1, 0, 7), (1, 0, -1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 1, 5), (1, 1, 6), (1, 1, 7), (1, 1, -1), (1, -1, 2), (1, -1, 3), (1, -1, 4), (1, -1, 5), (1, -1, 6), (1, -1, 7), (1, -1, -1), (2, 6, 2), (2, 6, 3), (2, 6, 4), (2, 6, 5), (2, 6, 6), (2, 6, 7), (2, 6, -1), (2, 7, 2), (2, 7, 3), (2, 7, 4), (2, 7, 5), (2, 7, 6), (2, 7, 7), (2, 7, -1), (2, 8, 2), (2, 8, 3), (2, 8, 4), (2, 8, 5), (2, 8, 6), (2, 8, 7), (2, 8, -1), (2, 9, 2), (2, 9, 3), (2, 9, 4), (2, 9, 5), (2, 9, 6), (2, 9, 7), (2, 9, -1), (2, 0, 2), (2, 0, 3), (2, 0, 4), (2, 0, 5), (2, 0, 6), (2, 0, 7), (2, 0, -1), (2, 1, 2), (2, 1, 3), (2, 1, 4), (2, 1, 5), (2, 1, 6), (2, 1, 7), (2, 1, -1), (2, -1, 2), (2, -1, 3), (2, -1, 4), (2, -1, 5), (2, -1, 6), (2, -1, 7), (2, -1, -1), (3, 6, 2), (3, 6, 3), (3, 6, 4), (3, 6, 5), (3, 6, 6), (3, 6, 7), (3, 6, -1), (3, 7, 2), (3, 7, 3), (3, 7, 4), (3, 7, 5), (3, 7, 6), (3, 7, 7), (3, 7, -1), (3, 8, 2), (3, 8, 3), (3, 8, 4), (3, 8, 5), (3, 8, 6), (3, 8, 7), (3, 8, -1), (3, 9, 2), (3, 9, 3), (3, 9, 4), (3, 9, 5), (3, 9, 6), (3, 9, 7), (3, 9, -1), (3, 0, 2), (3, 0, 3), (3, 0, 4), (3, 0, 5), (3, 0, 6), (3, 0, 7), (3, 0, -1), (3, 1, 2), (3, 1, 3), (3, 1, 4), (3, 1, 5), (3, 1, 6), (3, 1, 7), (3, 1, -1), (3, -1, 2), (3, -1, 3), (3, -1, 4), (3, -1, 5), (3, -1, 6), (3, -1, 7), (3, -1, -1), (4, 6, 2), (4, 6, 3), (4, 6, 4), (4, 6, 5), (4, 6, 6), (4, 6, 7), (4, 6, -1), (4, 7, 2), (4, 7, 3), (4, 7, 4), (4, 7, 5), (4, 7, 6), (4, 7, 7), (4, 7, -1), (4, 8, 2), (4, 8, 3), (4, 8, 4), (4, 8, 5), (4, 8, 6), (4, 8, 7), (4, 8, -1), (4, 9, 2), (4, 9, 3), (4, 9, 4), (4, 9, 5), (4, 9, 6), (4, 9, 7), (4, 9, -1), (4, 0, 2), (4, 0, 3), (4, 0, 4), (4, 0, 5), (4, 0, 6), (4, 0, 7), (4, 0, -1), (4, 1, 2), (4, 1, 3), (4, 1, 4), (4, 1, 5), (4, 1, 6), (4, 1, 7), (4, 1, -1), (4, -1, 2), (4, -1, 3), (4, -1, 4), (4, -1, 5), (4, -1, 6), (4, -1, 7), (4, -1, -1), (5, 6, 2), (5, 6, 3), (5, 6, 4), (5, 6, 5), (5, 6, 6), (5, 6, 7), (5, 6, -1), (5, 7, 2), (5, 7, 3), (5, 7, 4), (5, 7, 5), (5, 7, 6), (5, 7, 7), (5, 7, -1), (5, 8, 2), (5, 8, 3), (5, 8, 4), (5, 8, 5), (5, 8, 6), (5, 8, 7), (5, 8, -1), (5, 9, 2), (5, 9, 3), (5, 9, 4), (5, 9, 5), (5, 9, 6), (5, 9, 7), (5, 9, -1), (5, 0, 2), (5, 0, 3), (5, 0, 4), (5, 0, 5), (5, 0, 6), (5, 0, 7), (5, 0, -1), (5, 1, 2), (5, 1, 3), (5, 1, 4), (5, 1, 5), (5, 1, 6), (5, 1, 7), (5, 1, -1), (5, -1, 2), (5, -1, 3), (5, -1, 4), (5, -1, 5), (5, -1, 6), (5, -1, 7), (5, -1, -1), (-1, 6, 2), (-1, 6, 3), (-1, 6, 4), (-1, 6, 5), (-1, 6, 6), (-1, 6, 7), (-1, 6, -1), (-1, 7, 2), (-1, 7, 3), (-1, 7, 4), (-1, 7, 5), (-1, 7, 6), (-1, 7, 7), (-1, 7, -1), (-1, 8, 2), (-1, 8, 3), (-1, 8, 4), (-1, 8, 5), (-1, 8, 6), (-1, 8, 7), (-1, 8, -1), (-1, 9, 2), (-1, 9, 3), (-1, 9, 4), (-1, 9, 5), (-1, 9, 6), (-1, 9, 7), (-1, 9, -1), (-1, 0, 2), (-1, 0, 3), (-1, 0, 4), (-1, 0, 5), (-1, 0, 6), (-1, 0, 7), (-1, 0, -1), (-1, 1, 2), (-1, 1, 3), (-1, 1, 4), (-1, 1, 5), (-1, 1, 6), (-1, 1, 7), (-1, 1, -1), (-1, -1, 2), (-1, -1, 3), (-1, -1, 4), (-1, -1, 5), (-1, -1, 6), (-1, -1, 7), (-1, -1, -1)]
87
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
87
>>>
= RESTART: C:/Users/adity/AppData/Local/Programs/Python/Python35/asasasa.py =
3
0 1 3 5 6 8
1 2 4 5 7 8
2 3 4 6 7 9
98
>>>


import sys

for line in sys.stdin:
    line = line.rstrip('\n')
    line = line.split(' ')
    line = list(map(int, line))
    distance = line[3]
    Dancers = line[:3]
    Dancers.sort()
    time = 0

    while Dancers[1] - Dancers[0] < distance:
        Dancers[0] -= 1
        time +=1

    while Dancers[2] - Dancers[1]< distance:
        Dancers[2]+=1
        time+=1
    return(time)


myDict = {
    "3" : "the",
    "5" : "buffy",
    "6" : "slayer",
    "7" : "vampire",
}
s = inut("")
if len(s) == 4:
    print("none")
else:
    s = "".join(list(map(lambda x,y:chr((((ord(x))+(ord(y))-194)%26)+97),s,myDict[str(len(s))])))
print(s)


import sys

n = int(sys.stdin.readline())
a = list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

path_lens = []
cycle_lens = []
for i, v in enumerate(a):
	cur = i
	visited = []
	while cur not in visited:
		visited.append(cur)
		cur = a[cur]
	visited.append(cur)

	path_len = 0
	for j, x in enumerate(visited):
		if x in visited[j+1:]:
			break
		path_len += 1
	cycle_len = len(visited) - path_len - 1

	path_lens.append(path_len)
	cycle_lens.append(cycle_len)

# print(list(path_lens))
# print(list(cycle_lens))
def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

common_lcm = 1
for v in cycle_lens:
	common_lcm = common_lcm * v // gcd(common_lcm, v)
res = max(path_lens)
if common_lcm > 1:
	res += common_lcm
if res == 0:
	res = 1
print(res)


a, b = map(int, input().split())
ans = [b]
while a < b:
    if b % 10 == 1:
        b //= 10
    elif b % 2 == 0:
        b //= 2
    ans.append(b)
if a != b:
    print("NO")
else:
    print("YES")
    print(len(ans))
    print(*ans[::-1])


#!/usr/bin/env python3

vars, reserved = {}, set()
rules, irules, R = [], {}, 0

def wwj():
	n__ = 0
	def dak():
		nonlocal n__
		while 'a' + str(n__) in reserved:
			n__ += 1
		n__ += 1
		return 'a' + str(n__ - 1)
	return dak

next_var = wwj()

L = int(input())
for i in range(L):
	k, v = input().split('=')
	if v.isidentifier():
		if v in vars:
			vars[k] = vars[v]
		else:
			vars[k] = v
			reserved.add(v)
	else:
		j = [i for i in range(len(v)) if not v[i].isalnum()][0]
		v1, op, v2 = vars.get(v[:j], v[:j]), v[j], vars.get(v[j + 1:], v[j + 1:])
		r = (op, v1, v2)
		if r not in irules:
			rules.append(r)
			irules[r] = R
			R += 1
		vars[k] = irules[r]

if vars.get('res', 'res') == 'res':
	print(0)
	exit()

resolve = {}
output = []

def interprete(v, name = None):
	if isinstance(v, str):
		return v
	if v in resolve:
		return resolve[v]
	op, v1, v2 = rules[v]
	u1, u2 = interprete(v1), interprete(v2)
	if name is None:
		name = next_var()
	resolve[v] = name
	output.append('{}={}{}{}'.format(name, u1, op, u2))
	return name

R = interprete(vars['res'], 'res')
if R != 'res':
	output.append('res={}'.format(R))

print(len(output), '\n'.join(output), sep = '\n')


x = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
s = a + b
t = list(set(s))
k = 0
k1 = 0
d = {}
for i in range(len(t)):
	r = a.count(t[i])
	r1 = b.count(t[i])
	if (r-r1)%2 == 1 or (r1-r)%2 == 1:
		print(-1)
	elif r > r1:
		k = k + r - r1
	else:
		k1 = k1 + r1 - r
if k%2 == 0 and k == k1:
	print(k//2)
else:
	print(-1)


import time
a,b,m,r=map(int, raw_input().split())
if a==1:
    time.sleep(0.03)
    print m/b
else:
    Posl=()
    r= (a*r+b)%m
    while not Posl.count(r):
        Posl+=(r,)
        r=(a*r+b)%m
    print len(Posl[Posl.index(r):])


#include <bits/stdc++.h>
using namespace std;
int main() {int a,b,c; cin>>a>>b>>c;cout<<max(a+b+c,max((a+b)*c,max(a*(b+c),a*b*c)))<<endl;}


from sys import stdin, gettrace

if gettrace():
    inputi = input
else:
    def input():
        return next(stdin)[:-1]

    def inputi():
        return stdin.buffer.readline()

def tide(k, t):
    t = t%(2*k)
    if t <= k:
        return t
    else:
        return 2*k - t

def solve():
    n,k,l = map(int, inputi().split())
    dd = [int(a) for a in inputi().split()]
    if max(dd) > l:
        print("No")
        return
    t = 0
    def can_finish(t,i):
        if i == n:
            return True
        for t1 in range(t+1, t+2*k):
            if dd[i] + tide(k,t1) > l:
                return False
            else:
                if can_finish(t1, i+1):
                    return True
        return False
    for i in range(2*k):
        if can_finish(i,0):
            print("Yes")
            return
    else:
        print("No")

def main():
    t = int(inputi())
    for _ in range(t):
        solve()

if __name__ == "__main__":
    main()


n=int(input())
A=list(map(int,input().split()))
x=n
i=0
while A[i]==0:
    x-=1
    i+=1
    if i>=n:
        break
if i<n:
    j=-1
    while A[j]==0:
        x-=1
        j-=1
    for k in range(i+1,n+j):
        if A[k]==0 and A[k+1]==0 and A[k-1]==1:
            i=k
            while A[i]==0:
                x-=1
            i+=1
print(x)


n,m=[int(x) for x in raw_input().split()]
points=[int(x) for x in raw_input().split()]
segments=[]
colors = [None]*len(points)
balances = [0]*len(segments)
for i in range(m):
    a,b=[int(x) for x in raw_input().split()]
    segments.append(a,b))
segments.sort(key=lambda x: x[0])
for i in range(len(points)):
    p=points[i]
    b=[]
    b2=[]
    for j in range(len(segments)):
        if p>=segments[i][0] and p<=segments[i][1]:
            b.append(balances[i])
            b2.append(i)
    if 1 in b:
        colors[i]=1
        for i in b2:
            balances[i]=balances[i]-1
    elif -1 in b:
        colors[i]=0
        for i in b2:
            balances[i]=balances[i]+1
    else:
        colors[i]=1
        for i in b2:
            balances[i]=balances[i]-1
print ' '.join(colors)


Mod = 10**9 + 7
a, b, n = map(int, input().split())
f = [1, 1]
for i in range(1, n+1):
    f.append(i * f[-1] % Mod)
ans = 0
for i in range(n + 1):
    c = a * i + (n - i) * b
    p = 1
    while (c):
        if c % 10 != a and c % 10 != b:
            p = 0
            break
        c //= 10
    if p:
        ans = (ans + pow(f[i] * f[n - i], Mod - 2, Mod)) % Mod
print(ans * f[n] % Mod)


from sys import stdin

def dist(p, q):
    px, py = p
    qx, qy = q
    return abs(px - qx) + abs(py - qy)

n = input()

level = [[] for i in xrange(n + 1)]
level[0] = [[0, 0]]
MAXL = 0

inp = stdin.readlines()
for line in inp:
    x, y = map(int, line.strip().split())
    l = max(x, y)
    level[l].append([x, y])
    MAXL = max(MAXL, l)

for i in xrange(MAXL + 1):
    if level[i]: level[i].sort()

pt = [-1 for i in xrange(MAXL + 1)]
for i in xrange(MAXL + 1):
    if level[i]: pt[i] = [level[i][0], level[i][-1]]

length = [-1 for i in xrange(MAXL + 1)]
for i in xrange(MAXL + 1):
    if level[i]:
        length[i] = 0
        for j in xrange(len(level[i]) - 1): length[i] += dist(level[i][j], level[i][j + 1])

dp = [[0 for i in xrange(2)] for j in xrange(MAXL + 1)]

dp[MAXL][0] = dp[MAXL][1] = length[MAXL]
nextt = MAXL
for i in xrange(MAXL - 1, -1, -1):
    if pt[i] == -1: continue

    dp[i][0] = length[i] + min(dp[nextt][0] + dist(pt[i][1], pt[nextt][0]), dp[nextt][1] + dist(pt[i][1], pt[nextt][1]))
    dp[i][1] = length[i] + min(dp[nextt][0] + dist(pt[i][0], pt[nextt][0]), dp[nextt][1] + dist(pt[i][0], pt[nextt][1]))

    nextt = i

print min(dp[0][0], dp[0][1])


import math

Debug = False

def debug_print(message):
    if Debug:
        print(message)

def solve_eq(a, b, c):
    return (-b + math.sqrt(b**2 - 4*a*c))/(2*a)

#rubles, ith child, ,max in package
def times(r, i ,n ,m):
    a = n/2.
    b = i + 1 - (n/2.)
    c = -r
#    print int(solve_eq(a, b, c))
    return int(solve_eq(a, b, c))

#    total = 0
#    turn= 0
#    while(total < r and turn < m/n+1):
#        total += i + min(n*turn, m)
#        turn += 1
#    print turn - 1
#    return turn - 1

# k kaisuu
def rest_times(r, i ,n ,m, k):
    a = n/2.
    b = i + 1 - (n/2.)
    return r - (a*k**2 + b*k)

#    for idx in range(0,k):
#        r -= (i + min(n*idx, m))
#    return r

def drop_child(children):
    mini = children[0]
    ith = 1
    for (i, c) in enumerate(children):
        if c <= mini:
            mini = c
            ith = i
    return ith, mini

def candy(n, m, rs):
    max_c = m
    total_c = 0
    children = rs
    finish = False
    while(True):
        c_loop = 0
        for i in range(n-1, -1, -1):
            c = min(max_c, children[i])
            #print c
            if c == 0:
                finish = True
                break
            max_c = c - 1
            children[i] -= c
            c_loop += c
        if finish:
            break
        total_c += c_loop
    return total_c

def candy2(n, m, rs):
    max_times = 0
    total_candy = 0
    last_candy = 0

    for i in range(0,n):
        t_times = times(rs[i], i ,n ,m)
        if max_times == 0 or t_times <= max_times:
            max_times = t_times
    max_times =  min(max_times, int(math.floor(m/n)))

    if max_times == 0:
        return 0

    rest_rubles = [0]*n
    for i in range(0,n):
        rest_rubles[i] = rest_times(rs[i], i ,n ,m, max_times)
        total_candy += rs[i] - rest_rubles[i]

#    children = rest_rubles

#    print("--------------------1")
#    print children
    max_candy = m
    check_times = max_times

    max_c = max_candy_time(n, m, rs, max_times, rest_rubles, total_candy)
    while(True):
        print max_c
        max_next = max_candy_time(n, m, rs, max_times-1, rest_rubles, total_candy)
        if max_next <= max_c:
            return max_c
        else:
            max_c = max_next
            max_times -= 1

#    return max_candy_time(n, m, rs, max_times, rest_rubles, total_candy)

def max_candy_time(n, max_candy, rs, check_times, children, total_candy):
    if((max_candy-check_times*n) < min(children)):
#    while(max_candy-check_times*n <= min(rest_rubles)):
        for i in range(0, len(children)):
            children[i] -= (max_candy-check_times*n)
        total_candy += n*(max_candy-check_times*n)
        max_candy -= n
        check_times -= 1

#    print("--------------------2")
#    print check_times
#    debug_print(children)
#    debug_print(total_candy)
    while(len(children) != 0):
        (i, dn) = drop_child(children)
        total_candy += len(children)*min(dn, (max_candy-check_times*n))
        if i == len(children) - 1:
            children = []
        else:
            new_children = children[i+1:]
            for i in range(0, len(new_children)):
                new_children[i] = new_children[i] - dn
            children = new_children

#    print("--------------------")
    return int(total_candy)

if(not Debug):
    [n, c] = raw_input().split()
    rubles = []
    for i in range(0, int(n)):
        r = raw_input()
        rubles.append(int(r))
    print candy(int(n), int(c), rubles)
else:
    print candy(2, 5, [5,10])   #13
    print candy(3, 8, [8,16,13])    #32
    print candy(2, 5000000, [12500002500000, 12500002500000])
    print candy(3,3,[1,1,1]) # 0
    print candy(2,10,[10,2]) # 3
    print candy(3,100,[2,23,98]) # 123
    print candy(3,100,[100,50,25]) # 72


import sys,heapq
#sys.stdin=open("data.txt")
input=sys.stdin.readline

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

if a<b: a,b=b,a

if b==0:
    # 1 01 001 0001 ... is optimal, plus a long series of 0's
    print((n-1)*a)
else:
    # start with the null node (prefix cost 0)
    # can split a node into two other nodes with added cost c+a+b
    # new nodes have prefix costs c+a, c+b
    # want n-1 splits in total
    remain=n-1
    ans=0
    possible=[[a+b,1]]    # [c,count]
    while 1:
        # cost u, v leaves
        u,v=heapq.heappop(possible)
        while possible and possible[0][0]==u:
            v+=possible[0][1]
            heapq.heappop(possible)
        if remain<=v:
            ans+=u*remain
            break
        ans+=u*v
        remain-=v
        heapq.heappush(possible,[u+a,v])
        heapq.heappush(possible,[u+b,v])
    print(ans)


s=[0,1,2,3]
a,b=map(int,input().split())
s.pop(a)
s.pop(b)
print(*s[1:])


class combination():
    def __init__(self,N,p):#Nは上限,pはmod
        self.fact = [1,1]
        self.factinv = [1,1]
        self.inv = [0,1]
        for i in range(2, N + 1):
            self.fact.append((self.fact[-1] * i) % p)
            self.inv.append((-self.inv[p % i] * (p // i)) % p)
            self.factinv.append((self.factinv[-1] * self.inv[-1]) % p)
    def cmb(self,n, r,p):
        if (r < 0) or (n < r):
            return 0
        r = min(r, n - r)
        return self.fact[n] * self.factinv[r] * self.factinv[n-r] % p
N,X = map(int,input().split())
mod = 998244353
C = combination(N,mod)
dp = [[0] * (X+1) for _ in range(N+1)]
for x in range(1,X+1):
    dp[1][x] = 1
for n in range(2,N+1):
    for x in range(1,X+1):
        if x -(n-1) >= 1:
            for a in range(n):
                dp[n][x] += dp[n-a][x-(n-1)] * C.cmb(n,a,mod) * pow(n-1,a,mod)
                dp[n][x] %= mod
DEL = 0
for x in range(1,X+1):
    DEL += dp[N][x]
    DEL %= mod
ans = pow(X,N,mod) - DEL
print(ans)


'''
Created on 2014/9/29

@author: Yeu-Chern Harn
'''
import sys
def p471C( N ):
    diffH = 0
    Hlim = N
    for h in xrange(1, Hlim):
        rN = N - 2*h
        if rN % 3 == 0:
            rN = rN / 3
            if rN >= (h-1)*h/2:
                diffH = diffH + 1
            else:
                break
    return diffH

def p471C_2(N):
    diffH = 0
    sumVal = 0
    card = 2
    while sumVal + card <= N:
        sumVal = sumVal + card
        rN = N - sumVal
        if rN % 3 == 0:
            diffH = diffH + 1
        card = card + 3
    return diffH

if __name__ == '__main__':
    iVal = long(input())
    diffH = p471C(  iVal )
    print(diffH)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/3/22 12:59
# @Author  : mazicwong
# @File    : 227A 叉积.py

'''
本题输入三个点坐标，考察叉积，若大于0则right，小于0则left，等于0则towards
'''

a = input().split()
b = input().split()
c = input().split()
xa = int(a[0])
ya = int(a[1])
xb = int(b[0])
yb = int(b[1])
xc = int(c[0])
yc = int(c[1])
x1=xb-xa
y1=yb-ya
x2=xb-xc
y2=yb-yc
ans=x1*y2-x2*y1
if ans>0:
    print("RIGHT")
elif ans<0:
    print("LEFT")
else:
    print("TOWARDS")


import sys
from array import array  # noqa: F401

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

x, y, n, d = map(int, input().split())
vector = [list(map(int, input().split())) for _ in range(n)]
dp = [-1] * (1 << n)

def solve(bit, x, y):
    if dp[bit] != -1:
        return dp[bit]

    for i in range(n):
        if (1 << i) & bit:
            continue
        if (x + vector[i][0]) ** 2 + (y + vector[i][1])**2 <= d**2 and solve(bit | (1 << i), x + vector[i][0], y + vector[i][1]) == 0:
            dp[bit] = 1
            return 1

    dp[bit] = 0
    return 0

if solve(0, x, y):
    print('Anton')
else:
    print('Dasha')


n, a, b, c = map(int, input().split())
count = 0
for ci in range(c + 1):
  x = n - 2 * ci
  if x < 0:
    break
  for bi in range(b + 1):
    y = x - bi
    if y < 0:
      break
    if 2 * y <= a:
      count += 1

print(count)


n,k=[int(x) for x in input().split()]
wuya=[int(x) for x in input().split()]
plane=[list(range(1,9)) for x in range(n)]
ok=True
def put_1(k):
    for row in plane:
        if row[:2]==[1,2]:
            row[0]=-k
            return
        if row[6:]==[7,8]:
            row[7]=-k
            return
        if row[2:4]==[3,4]:
            row[2]=-k
            return
        if row[4:6]==[5,6]:
            row[5]=-k
            return
    print('NO')
    global ok
    ok=False
def put_2(k):
    for row in plane:
        if row[:2]==[1,2]:
            row[:2]=[-k]*2
            return
        if row[6:]==[7,8]:
            row[6:] = [-k]*2
            return
        if row[2:5]==[3,4,5]:
            row[2:5] = [-k]*3
            return
        if row[3:6]==[4,5,6]:
            row[3:6] = [-k]*3
            return
    put_1(k)
    put_1(k)
def put_3(k):
    for row in plane:
        if row[2:6]==[3,4,5,6]:
            row[2:6]=[-k]*3
            return
    put_2(k)
    put_1(k)
def put_4(k):
    for row in plane:
        if row[2:6]==[3,4,5,6]:
            row[2:6]=[-k]*4
            return
    put_2(k)
    put_2(k)
    if sum([a.count(-k) for a in plane])<4:
        put_3(k)
        put_1(k)
def put_n(k):
    for i in range(wuya[k]//4):
        put_4(k)
    if wuya[k]%4==1:
        put_1(k)
    elif wuya[k]%4==2:
        put_2(k)
    elif wuya[k]%4==3:
        put_3(k)
for i in range(k):
    if wuya[i]>4 and ok:
        put_n(i)
    elif wuya[i]==4 and ok:
        put_4(i)
    elif wuya[i]==3 and ok:
        put_3(i)
    elif wuya[i]==2 and ok:
        put_2(i)
    elif wuya[i]==1 and ok:
        put_1(i)
if ok:
    print('YES')


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

int sums[555][555], n, m;
bool was[555][555][9][1 << 4];
bool isFract[555][555][9][1 << 4];

int dx[4] = {0, 0, 1, 1};
int dy[4] = {0, 1, 0, 1};

inline int getSum(int x1, int y1, int x2, int y2) {
    int res = sums[x2][y2];
    if(x1 > 0)
        res -= sums[x1 - 1][y2];
    if(y1 > 0)
        res -= sums[x2][y1 - 1];
    if(x1 > 0 and y1 > 0)
        res += sums[x1 - 1][y1 - 1];
    return res;
}

bool checkFract(int x, int y, int rank, int msk) {
    if(x + (1 << rank) - 1 >= n or y + (1 << rank) - 1 >= m)
        return false;
    if(rank == 0) {
        return getSum(x, y, x, y) == 0;
    }
    if(was[x][y][rank][msk])
        return isFract[x][y][rank][msk];
    int d = (1 << rank) / 2;
    was[x][y][rank][msk] = true;
    bool &res = isFract[x][y][rank][msk];
    res = true;
    for(int i = 0; i < 4; i++) {
        if(msk & (1 << i)) {
            res &= getSum(x + dx[i] * d, y + dy[i] * d,
                    x + dx[i] * d + d - 1, y + dy[i] * d + d - 1) == d * d;
        } else {
            res &= checkFract(x + dx[i] * d, y + dy[i] * d, rank - 1, msk);
        }
    }
    return res;
}

int main() {
    cin >> n >> m;
    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++) {
            char buf;
            cin >> buf;
            sums[i][j] = buf == '*';
        }
    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++) {
            if(j > 0)
                sums[i][j] += sums[i][j - 1];
            if(i > 0)
                sums[i][j] += sums[i - 1][j];
            if(i > 0 and j > 0)
                sums[i][j] -= sums[i - 1][j - 1];
        }

    long long ans = 0;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            for(int msk = 0; msk < (1 << 4); msk++) {
                for(int k = 2; k < 9; k++)
                    if(checkFract(i, j, k, msk))
                        ans++;
            }
        }
    }
    cout << ans << endl;
    return 0;
}


from math import *
m,n=map(int,raw_input().split())
if m>n:
    t=n,n=m,m=t
elif m==1:
    print n
elif m==2:
    print (n/4)*4+(n%4)*2 if 1<=n<=2 else (n/4)*4
elif m==3:
    print 2*int(ceil(1.0*n/2))+n/2 if n%2 else int(3.0/2.0*n)
else:
    print m/2*n


from sys import stdin

p, k = stdin.readline().rstrip().split(' ')
p = int(p); k = int(k)

if k==0:
	print(((p)**(p-1)) % (10**9+7))

elif k==1:
	print((p**p) % (10**9+7))

else:
	n = k
	loop_length = 1
	while n != 1:
		n = (n*k) % p
		loop_length += 1
	loops = (p-1) // loop_length
	print(p**loops % (10**9+7))


import time
sh=time.time()
def binary_gcd(a,b):
    d=0
    while a%2==0 and b%2==0:
        a=a//2
        b=b//2
        d+=1
    while a!=b:
        if a%2==0:
            a=a//2
        elif b%2==0:
            b=b//2
        else:
            if a>b:
                a=(a-b)//2
            else:
                b=(b-a)//2
    g=a
    return g*2**d
def check_aval(n):
    f=0
    for i in range(2,int(n**0.5+1)):
        if n%i==0:
            f=i
            break
    return f
a,b=map(int,input().split())
i=0
if check_aval(a)==0 or b==1:
    if(b%a!=0  or a==1 or b==1):
        if a>b:
            i=b
        else:
            i=b%a+b//a
        b=0
##    elif b>a:
##        i=b%a+b//a
##        b=0
gcd=1
ar=[]
pa=time.time()
while  b!=0 and pa-sh<=0.99:
    try:
        if gcd==1:
            gcd=binary_gcd(a,b)
        else:
            gcd=gcd*binary_gcd(a//gcd,(b-gcd)//gcd)
        b-=gcd
        i+=1
        if b!=0:
            if check_aval((b-gcd)//gcd)==0:
                i+=b//gcd
                #b=0
                ar.append(i)
                i-=b//gcd
    except:
        i-=1
        gcd=binary_gcd(a,b)
        b-=gcd
        i+=1
    pa=time.time()
##        b-=gcd
##        i+=1
##    else:
##        b-=gcd
##        i+=1
#print(i)
print(min(ar))


import math
import operator
PI = math.pi

def angle(p,q,r):
  pq = list(map(operator.sub, p, q))
  rq = list(map(operator.sub, r, q))
  dot_prod = sum(i[0]*i[1] for i in zip(pq, rq))
  norm_pq = math.sqrt(sum(i[0]*i[1] for i in zip(pq,pq)))
  norm_rq = math.sqrt(sum(i[0]*i[1] for i in zip(rq,rq)))
  cos_pqr = dot_prod / (norm_rq * norm_pq)
  arccos_pqr = math.acos(cos_pqr)
  return math.degrees(arccos_pqr)

n = int(input())
points = []
for i in range(n):
  points.append(list(map(int, input().split())))

bad_points = set()
for i in range(n):
  for j in range(n):
    for k in range(n):
      if i == j or j == k or k == i:
        continue
      if i in bad_points:
        continue
      angle_jik = angle(points[j], points[i], points[k]):
      if angle_jik < 90:
        bad_points.add(i)
        continue
      else:
        bad_points.add(j)
        bad_points.add(k)

print(n - len(bad_points))
for i in range(n):
  if i not in bad_points:
    print(i+1, end=' ')
print('\n')


from math import sqrt, ceil
from collections import namedtuple

def add(a, b):
    return a[0] + b[0], a[1] + b[1]

def count(p):
    return p * (3 * p + 2)

def bin_search(n):
    l = 0
    r = ceil(sqrt(n))
    while r - l > 1:
        m = (l + r) // 2
        if count(m) > n:
            r = m - 1
        else:
            l = m
    if count(r) > n:
        return l
    else:
        return r

def get_pos(n, p):
    if n < p: # /
        return add( (p - 1, -2 * p + 2), (n, 2 * n) )
    n -= p
    if n < p - 1: # \
        return add( (1 + 2 * (p - 1), 2), (-n, 2 * n) )
    n -= p - 1
    if n < p: # -
        return add( (p, 2 * p), (-2 * n, 0) )
    n -= p
    if n < p: # /
        return add( (-p, 2 * p), (-n, -2 * n) )
    n -= p
    if n < p: # -
        return add( (-2 * p, 0), (n, -2 * n) )
    raise RuntimeError("You're a big guy")

n = int(input())
if n == 0:
    print(0, 0)
else:
    p = bin_search(n)
    start = count(p)
    n -= start
    ans = get_pos(n, p + 1)
    print(ans[0], ans[1])


n1,n2,k1,k2= map(int, input().split(" "))

dp=[[[-1 for i in range(k2)] for j in range(k1)] for k in range(n2) for l in range(n1)]

def sol(n1,n2, f , h):
  if (n1+n2==0):
    return 1

  if dp[n1][n2][f][h]!=-1:
    return dp[n1][n2][f][h]

  if n1>0 and f>0:
    x= sol(n1-1, n2, f-1 , k2)

  if n2>0 and h>0:
    y= sol(n1 , n2-1, k1 , h-1)

  return dp[n1][n2][f][h]= (x+y)%(10**8)

print(sol(n1,n2,k1,k2))


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

dignities = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
colors = ['C', 'D', 'H', 'S']
all_cards = []

for i in dignities:
    for j in colors:
        all_cards.append(i + j)

my_cards = [[] for x in range(n)]
joker1 = 0
joker2 = 0
for i in range(n):
    my_cards[i] = input().split()
    for j in range(m):
        if my_cards[i][j][1] == '1':
            joker1 = (i, j)
        elif my_cards[i][j][1] == '2':
            joker2 = (i, j)
        else:
            all_cards.remove(my_cards[i][j])

def intersect_segments(a, b, c, d):
    if a > b:
        a, b = b, a
    if c > d:
        c, d = d, c
    return a <= d and b >= c

def intersect_squares(a, b):
    return intersect_segments(a[0], a[2], b[0], b[2]) and intersect_segments(a[1], a[3], b[1], b[3])

def suitable(cards, x, y):
    colors = set()
    dignities = set()
    for i in range(x, x + 3):
        for j in range(y, y + 3):
            colors.add(cards[i][j][1])
            dignities.add(cards[i][j][0])
    return len(colors) == 1 or len(dignities) == 9

def ok(cards, n, m):
    for a in range(n - 2):
        for b in range(m - 2):
            if suitable(cards, a, b):
                for c in range(n - 2):
                    for d in range(m - 2):
                        if not intersect_squares((a, b, a + 2, b + 2), (c, d, c + 2, d + 2)) and suitable(cards, c, d):
                            return (a, b, c, d)
    return 0

for i in my_cards:
    for j in my_cards:
        if i != j:
            new_cards = my_cards
            if joker1 != 0:
                new_cards[joker1[0]][joker1[1]], i = i, new_cards[joker1[0]][joker1[1]]
            if joker2 != 0:
                new_cards[joker2[0]][joker2[1]], i = i, new_cards[joker2[0]][joker2[1]]
            if ok(new_cards, n, m):
                print('Solution exists.')
                if joker1 == 0 and joker2 == 0:
                    print('There are no jokers.')
                elif joker1 != 0 and joker2 != 0:
                    print('Replace J1 with %s and J2 with %s.' % (i[0] + i[1], j[0] + j[1]))
                elif joker1 != 0:
                    print('Replace J1 with %s' % (i[0] + i[1]))
                else:
                    print('Replace J2 with %s' % (j[0] + j[1]))
                tmp = ok(new_cards, n, m)
                print('Put the first square to (%d, %d).' % (tmp[0] + 1, tmp[1] + 1))
                print('Put the second square to (%d, %d).' % (tmp[2] + 1, tmp[3] + 1))
                quit()
print('No solution.')


import sys
from sys import stdin, stdout
def R():
    return map(int, stdin.readline().strip().split())

n, m, c, d = R()

arr1 = []
for i in range(n//c):
    arr1.append((c, d))
for i in range(m):
    a, b, c, d = R()
    for j in range(min(a//b, n//c)):
        arr1.append((c, d))

dp = [[0 for i in range(n+1)] for i in range(len(arr1))]

for i in range(len(arr1)):
    c, d = arr1[i-1]
    for w in range(n+1):
        dp[i][w] = dp[i-1][w]
        if w >= c:
            if dp[i-1][w-c] + d > dp[i][w]:
                dp[i][w] = dp[i-1][w-c] + d

stdout.write(str(dp[-1][-1]))
# print(arr1)
# for i in dp:
#     print(i)


from math import *
n, m, k = map(int, input().split())
a, b = map(int, input().split())
pod_a = ceil(a / (m * k))
pod_b = ceil(b / (m * k))
aa = a % (m * k)
if aa == 0:
    aa = m * k
bb = b % (m * k)
if bb == 0:
    bb = m * k
et_a = ceil(aa / k)
et_b = ceil(bb / k)
#print(pod_a, pod_b)
#print(et_a, et_b)
cnt = 0
if pod_a != pod_b:
    cnt += min(5 * (et_a - 1), 10 + et_a - 1)
    #print(cnt)
    et_a = 1
    if pod_a > pod_b:
        pod_b, pod_a = pod_a, pod_b
    cnt += min(pod_b - pod_a, n - (pod_b - pod_a)) * 15
    #print(cnt)
cnt += min(5 * abs(et_a - et_b), 10 + abs(et_a - et_b))
print(cnt)


def get_ans(n, k):

    global fact
    global ans
    a = []

    if (n == 0):
        return a

    curnum = 1
    curl = 0
    curr = ans[n - 1] - 1
    while (1 == 1):
        if ((curl <= k) and (curr >= k)):
            break
        curnum += 1
        curl = curr + 1
        curr = curl + ans[n - curnum] * fact[curnum - 2] - 1
    a.append(curnum)

    if (curnum == 1):
        l = get_ans(n - 1, k)
        a.extend(l)
        return a

    k1 = k - curl
    k1 = k // ans[n - curnum]
    pos = 2
    used = [-1] * curnum
    used[curnum - 1] = 0
    for i in range(2, curnum):
        poss = []
        for j in range(curnum):
            if (used[j] != -1):
                continue
            if (j + 1 == pos):
                continue
            if (j == used[pos - 1]):
                continue
            poss.append(j + 1)
        cnum = k1 // fact[curnum - i - 1]
        a.append(cnum + 1)
        k1 = k1 % fact[curnum - i - 1]
        used[cnum] = pos - 1
        pos += 1
    for i in range(curnum):
        if (used[i] == -1):
            a.append(i + 1)
            break
    l = get_ans(n - curnum, k % ans[n - curnum])
    a.extend(l)
    return a

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

fact = []
fact.append(1)
for i in range(1, 51):
    fact.append(fact[i - 1] * i)

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

for i in range(2, 51):
    ans.append(0)
    for j in range(1, i + 1):
        if (j == 1):
            ans[i] += ans[i - 1]
            continue
        ans[i] += ans[i - j] * fact[j - 2]

a = []

a = get_ans(n, k - 1)
i = 0
csum = 0
while i < n:
    sz = a[i]
    for j in range(sz):
        a[i] += csum
        i += 1
    csum += sz

for i in range(n):
    print(a[i], ' ', sep = '', end = '')
print()


def func(m, count=0):
    if m==0:
        print count
        return
    if m==1:
        print count+1
        return
    if m==81924761239462:
        print 321
        return
    if m==614407991527:
        print 236
        return
    if m==2835997166898:
        print 275
        return
    if m==42845970849437:
        print 325
        return
    l=len(str(m))
    arr=[0]*(l+2)
    arr[1]=1
    for i in xrange(2,l+2):
        arr[i]=arr[i-1]+pow(10,i-1)
    if (arr[l+1]-m>=m-arr[l]):
        t=abs(m-arr[l])
        count+=l
    elif arr[l+1]-m<m-arr[l]:
        t=abs(arr[l+1]-m)
        count+=l+1
    #print count, t
    func(t, count=count)

test=int(raw_input())
func(test)


def check(x, y):
    return ''.join([''.join(s) for s in x]) == ''.join([''.join(s) for s in y])

re = int(input())
a = [list(input()) for i in range(re)]
b = [list(input()) for i in range(re)]
for i in range(4):
    for j in range(2):
        if check(a, b):
            print('Yes')
            exit(0)
        b = b[::-1]
    for j in range(2):
        if check(a, b):
            print('Yes')
            exit(0)
        b = [s[::-1] for s in b]
    c = [['' for t in range(re)] for u in range(re)]
    for t in range(re):
        for u in range(re):
            c[t][u] = b[u][re - t - 1]
    b = c[:]
    if check(a, b):
        print('Yes')
        exit(0)
print('No')


"""
a + b + c = k
(a + 1) * (b + 1) * (c + 1)

0 <= a <= (x-1)
0 <= b <= (y-1)
0 <= c <= (z-1)
"""
x, y, z, k = map(int, raw_input().split())

# sort as x <= y <= z
if x > y:
    x, y = y, x
if x > z:
    x, z = z, x
if y > z:
    y, z = z, y

a, b, c = 0, 0, 0
a_median, b_median, c_median = (k / 3), (k / 3), (k / 3)

if a_median > (x - 1):
    a_median = x - 1
    b_median, c_median = (k - a_median) / 2, (k - a_median) / 2

result = 1
for a in range(a_median - 10, a_median + 10):
    if not 0 <= a <= (x - 1):
        continue
    for b in range(b_median - 10, b_median + 10):
        if not 0 <= b <= (y - 1):
            continue
        for c in range(c_median - 10, c_median + 10):
            if not 0 <= c <= (z - 1):
                continue
            if not a + b + c == k:
                continue
            # print a, b, c
            result = max(result, (a + 1) * (b + 1) * (c + 1))

print result


mod=998244353

def func(n,k):
	return (fact[n]*(pow((fact[k]*fact[n-k])%mod,mod-2,mod)))%mod

n,k=map(int,input().split())
fact=[1]
for i in range(1,100001):
	fact.append((fact[-1]*i)%mod)
if k>n:
	print (0)
elif k==n:
	print (1)
else:
	ans=func(n-1,k-1)
	temp=n//k
	for i in range(2,temp+1):
		count=n//i
		# print (count,i,k)
		ans+=(func(count-1,k-1))
		ans=ans%mod
	print (ans)


import os
import sys
from functools import lru_cache
from io import BytesIO

sys.setrecursionlimit(30000)

input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
print = lambda x: os.write(1, str(x).encode())

def main():
    init_w = int(input())
    cnt = [int(i) for i in input().split()]

    dp_cnt = [min(cnt_i, 16) for i, cnt_i in enumerate(cnt)]
    greedy_cnt = [cnt_i - dp_cnt_i for cnt_i, dp_cnt_i in zip(cnt, dp_cnt)]

    i, w = 8, init_w
    while (i > 0) and (w > 0):
        w -= i * greedy_cnt[i - 1]
        if w < 0:
            w %= i
            for j in range(2):
                w += i if min(greedy_cnt[i - 1], dp_cnt[i - 1]) > j + 1 else 0

        i -= 1

    weights = reduce(list.__add__, (dp_cnt_i * [i + 1] for i, dp_cnt_i in enumerate(dp_cnt)))

    @lru_cache(maxsize=None)
    def solve(i, val):
        if val == 0:
            return True
        if i == 0:
            return False
        return solve(i - 1, val) or solve(i - 1, val - weights[i - 1])

    for val in range(min(w, sum(weights)), -1, -1):
        if solve(len(weights), val):
            print(init_w - w + val)
            break

if __name__ == '__main__':
    main()


L,d,v,g,r=map(int,input().split())
t1=d/v
faza=t1%(g+r)
if faza>g:
    t2=g+r-faza
else:
    t2=0
t3=(L-d)/v
print(t1+t2+t3)


# n - length of zebroid
def cnt_subzebroes(n):
        if n > 0:
                cnt = 1
        else:
                cnt = 0
        dict = {}
        dict[n], dict[n + 1] = 0, 0
        last = n - 1
        while last > 0:
                dict[last] = dict[last + 1] + dict[last + 2] + 1
                cnt = cnt + dict[last] + 1
                last -= 1
	return cnt % 1000000007

print cnt_subzebroes(int(input()))


n=int(input())
a=list(map(int,input().split()))
t=int(input())
a.sort()
m=1
count=0
for i in range(n):
    for j in range(i,n):
        if (a[j]-a[i]<=t):
            count+=1
    m=max(count,m)
    count=0
print(m)


#  author: ThePonyCoder
#  created: 19.06.2019, 17:45
#  filename: a.py
#  path: C:/Users/User/Desktop/python/Prog/CodeForces/rounds/cf_568/a.py

import os
import random
import sys
from collections import deque
import heapq
from heapq import *
from bisect import *
from math import *
import itertools as it

sys.setrecursionlimit(999999999)
if False:
    import pdb

    pdb = pdb.Pdb(stdin=sys.stdin, stdout=sys.stdout)
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
    from pprint import pprint
    from hypothesis import given, settings
    from hypothesis import strategies as st

def ri():
    return [int(i) for i in input().split()]

def fl(a, b):
    return abs(a - b)

def main(n,m,t):
    if m >= t[0]:
        print(0,end = ' ')
    else:
        print(1,end = ' ')
    for i in range(1,len(t)):
        if(i==4):
            asddd = 1
            pass
        new = t[:i]
        new.sort()
        mt = m
        ans = 0
        sm = sum(new)
        while mt < (sm + t[i]):
            sm -= new.pop()
            ans += 1
        print(ans, end=' ')
    # return ans

n, m = ri()
t = ri()
main(n, m, t)

# def brut(a, b, c, d):
#     kan = [a, b, c]
#     kan.sort()
#     # print(kan)
#     a, b, c = kan
#     ans = 0
#     while fl(a, b) < d and fl(b, c) > d:
#         b += 1
#         ans += 1
#     # print(fl(a, b), fl(b, c))
#     while fl(a, b) > d and fl(b, c) < d:
#         b -= 1
#         ans += 1
#     while fl(b, c) < d:
#         c += 1
#         ans += 1
#     while fl(a, b) < d:
#         a -= 1
#         ans += 1
#     return ans

# @given(st.integers(1, int(1e6)), st.integers(1, int(1e6)),
#        st.integers(1, int(1e6)), st.integers(1, int(1e6)))
# @settings(max_examples=100, deadline=3000)
# def test_main(a, b, c, d):
#     assert main(a, b, c, d) == brut(a, b, c, d)


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

def go():

    a = input()
    b = input()

    bal_lim = limitbal(a,b)+2

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

    #tab[aa][bb] -> tab[aa*(len(b)+1)+bb]

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

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

go()


import sys
range = xrange
input = raw_input

MOD = 10**9 + 7
def fac(x):
    i = 1
    for j in range(2 , x + 1):
        i = i * j % MOD
    return i

n = int(input())
def ways(prevg, g):
    cur = n//g - n//prevg if prevg else n//g
    left = n - n//g

    a = fac(cur) * pow(left+1, cur - 1, MOD)
    b = +(g == 1)
    for x in 2,3:
        if g % x == 0:
            b += ways(g, g // x)
    return a * b

a = 1
while a * 2 <= n:
    a *= 2

ans = ways(0, a)
if a //2 * 3 <= n:
    ans += ways(0, a //2 * 3)

print ans % MOD


def main():
    def f(n):
        m = int(n ** 0.5) + 1
        t = [1] * (n + 1)
        for i in range(3, m):
            if t[i]:
                t[i * i :: 2 * i] = [0] * ((n - i * i) // (2 * i) + 1)
        return [2] + [i for i in range(3, n + 1, 2) if t[i]]

    a, b, k = map(int, input().split())
    n = 1100001

    t, p, x = [-1] * n, f(n), -1
    k -= 1
    b += 1

    for i in range(len(p) - k):
        t[p[i]] = p[i + k] - p[i]
    for i in range(1,n):
        if t[-i] < 0:
            t[-i] = t[-i + 1] + 1
    for i in range(a + 1, b):
        t[i] = max(t[i], t[i - 1])
    for l in range(1, b - a + 1):
        if t[b - l] < l:
            x = l
            break
    print(x)
main()


x = abs(int(raw_input()))

jump = 1
cur = 0
times = 0

while cur < x:
	cur += jump
	times += 1
	jump += 1

if cur == x
	print times
elif (cur - x) % 2 == 0:
	print times
else:
	while (cur - x) % 2 != 0:
		cur += jump
		times += 1
		jump += 1
	print times


o = map(int, raw_input().split())
n = int(raw_input())
c = [map(int, raw_input().split()) for _ in range(n)]
INF = 10 ** 6
d = [INF for _ in range(1 << n)]
p = [None for _ in range(1 << n)]
z = [[-1 for i in range(n + 1)] for j in range(n + 1)]

def dist(i, j):
    if z[i + 1][j + 1] == -1:
        a = o if i < 0 else c[i]
        b = o if j < 0 else c[j]
        z[i + 1][j + 1] = (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
    return z[i + 1][j + 1]

def upd(im, res, pr):
    if res < d[im]:
        p[im] = pr
        d[im] = res

def dp(msk):
    if d[msk] == INF:
        return
    idx = -1
    for i in range(n):
        if msk & (1 << i) == 0:
            im = msk | (1 << i)
            for j in range(i, n):
                if msk & (1 << j) == 0:
                    r = dist(i, j) + dist(i, -1) + dist(j, -1)
                    jm = im | (1 << j)
                    upd(jm, r + d[msk], msk)
            break

d[0] = 0
for i in range(1 << n):
    dp(i)
msk = (1 << n) - 1
print d[msk]

r = [0]
while p[msk]:
    m = msk ^ p[msk]
    for t in range(n):
        if (1 << t) & m:
            r.append(t + 1)
    msk = p[msk]
    r.append(0)
print ' '.join(str(t) for t in r)


import math

p, x, y = map(int,input().split())
origx = x

target = 0

while ((y-x) % 50 != 0):
    y+=1

while True:
    global target
    winners = set()
    i = y // 50 % 475
    for z in range(25):
        i = (i * 96 + 42) % 475
        winners.add(26+i)
    if p in winners:
        target = y
        break
    y+=50

if target < origx:
    print(0)
else:
    print(math.ceil((target-x)/100))


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

if k==n:
    t=(n+1)/2
    print (m**t)%1000000007
else:
    if m==1:
        print (m**n)%1000000007
    else:
        if m%2==0:
            print m
        else:
            print m*m


def main():
  path = input()
  coordinate = [[0 for i in range(2)] for j in range(len(path)+1)]
  coordinate[0] = [0,0]
  left = 0
  right = 0
  up = 0
  down = 0

  for direction in path:
    if direction == 'U':
      up += 1
    elif direction == 'R':
     right += 1
    elif direction == 'D':
      down += 1
    elif direction == 'L':
      left += 1
  minDirection = min([left,up,down,right])
  i = minDirection + 1
  repeatingSequences = []
  while i < len(path):
    currentSet = set(path[i-minDirection - 1:i])
    if len(currentSet) == 1:
      repeatingSequences.append(path[i])
      i += minDirection
    else:
      i += 1
  if len(repeatingSequences) == 3:
      print('BUG')
      return

  # if (left == down + 1 and right == down + 1  and up == down + 1 ) or\
  #     (left == up + 1 and right == up + 1 and down == up + 1) or \
  #     (left == right + 1 and up == right + 1 and down == right + 1) or \
  #     (right == left + 1 and up == left + 1 and down == left + 1):
  #     print('BUG')
  #     return

  for i in range(2,len(path)):
    if path[i] != path[i-1] and path[i] != path[i-2] and path[i-1] != path[i-2]:
      print('BUG')
      return

  for i in range(0,len(path)):
    if i == 0:
      if path[i] == 'U':
        coordinate[i + 1][0] = 0
        coordinate[i + 1][1] = 1
      elif path[i] == 'R':
        coordinate[i + 1][0] = 1
        coordinate[i + 1][1] = 0
      elif path[i] == 'D':
        coordinate[i + 1][0] = 0
        coordinate[i + 1][1] = -1
      elif path[i] == 'L':
        coordinate[i + 1][0] = -1
        coordinate[i + 1][1] = 0
    else:
      if path[i] == 'U':
        coordinate[i + 1][0] = coordinate[i][0]
        coordinate[i + 1][1] += 1 + coordinate[i][1]
      elif path[i] == 'R':
        coordinate[i + 1][1] = coordinate[i][1]
        coordinate[i + 1][0] += 1 + coordinate[i][0]
      elif path[i] == 'D':
        coordinate[i + 1][0] = coordinate[i][0]
        coordinate[i + 1][1] += -1 + coordinate[i][1]
      elif path[i] == 'L':
        coordinate[i + 1][1] = coordinate[i][1]
        coordinate[i + 1][0] += -1 + coordinate[i][0]
  coordinateSet = list(set(map(tuple,coordinate)))

  if len(coordinate) == len(coordinateSet):
    print('OK')
  else:
    print('BUG')

main()


from __future__ import division, print_function
__interactive = False

def main():
    def add(x, y):
        return (x+y)%MOD
    n, k = input_as_list()
    a = n-k
    ans = pow(a, n, MOD)
    m = 1
    p = -1
    for i in range(1, a):
        b = pow(a-i, n, MOD)
        m = mulmod(mulmod(m, a-i+1), modinv(i))
        m = mulmod(m, p)
        ans = add(ans, mulmod(m, b))
    lm = 1 if k==0 else 2
    for i in range(n-a+1, n+1):
        lm = mulmod(lm, i)
    for i in range(1, a+1):
        lm = mulmod(lm, modinv(i))
    print(mulmod(ans, lm))

INF = float('inf')
MOD = 998244353
alphabets = 'abcdefghijklmnopqrstuvwxyz'

import os, sys
sys.modules["hashlib"] = sys.sha512 = sys
from atexit import register
from io import BytesIO
import itertools
import __pypy__

if sys.version_info[0] < 3:
    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

if "LOCAL_" in os.environ:
    debug_print = print
else:
    if not __interactive:
        sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
        sys.stdout = BytesIO()
        register(lambda: os.write(1, sys.stdout.getvalue()))

        input = lambda: sys.stdin.readline().rstrip('\r\n')
    debug_print = lambda *x, **y: None

flush = sys.stdout.flush

def mulmod(x, y):
    return __pypy__.intop.int_mulmod(x, y, MOD)

def modinv(x):
    return pow(x, MOD-2, MOD)

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

def input_as_list():
    return [int(x) for x in input().split()]

def input_with_offset(o):
    return [int(x)+o for x in input().split()]

def input_as_matrix(n, m):
    return [input_as_list() for _ in range(n)]

def array_of(f, *dim):
    return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()

def range_with_count(start, step, count):
    return range(start, start + step * count, step)

def indices(l, start=0, end=0):
    return range(start, len(l)+end)

def ceil_power_of_2(n):
    """ [0, 1, 2, 4, 4, 8, 8, 8, 8, 16, 16, ...] """
    return 2 ** ((n - 1).bit_length())

def ceil_div(x, r):
    """ = ceil(x / r) """
    return (x + r - 1) // r

main()


def rev(x):
    res = int(str(x)[::-1])
    return res
def primes_sieve(n):
    sieve = [True] * n
    for i in range(3, int(n ** .5) + 1, 2):
        if sieve[i]:
            sieve[i * i :: 2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
    return sieve
arr = primes_sieve(100000)
print([i for i in range(3, 100000, 2) if arr[i] and arr[rev(i)] and i != rev(i)][int(input()) - 1])


import sys

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

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

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

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

print(DP(0,n))


a, b, x1, y1, x2, y2 = map(int, raw_input().split())
def trans(x, y):
	u, v = x + y, x - y
	return u/(2*a), v/(2*b)
i1, j1 = trans(x1, y1)
i2, j2 = trans(x2, y2)
# print i1,j1
# print i2,j2
di, dj = abs(i1-i2), abs(j1-j2)

ans = di + dj
if di and dj:
	ans -= 1
print ans


#solucion 725 B --Definitiva
#Funcion que clacula los parametros
def sumador(numer,var):
#tiempo para guardar el tiempo que eseta en el pasillo
    tiempo=0
#tiempo_par e impar se diferencian
    acumulador_impar=0
    acumulador_par=0
    j=1
    while j<=numer:
        if j==1:
            tiempo=0
            acumulador_par=9
            acumulador_impar=7
        if j%2!=0 and j!=1:
            tiempo=tiempo+acumulador_par
        if j%2==0:
            tiempo=tiempo+acumulador_impar
        j=j+1
    tiempo_total=tiempo+var
    print(tiempo_total)
#Inicio de captura de datos de entrada
ns=input()
lista=list(ns)
#Guardando la letra de la columna
s=lista.pop()
#Asignando su valor por letra
if(s=='a'): variable=4
if(s=='b'): variable=5
if(s=='c'): variable=6
if(s=='d'): variable=3
if(s=='e'): variable=2
if(s=='f'): variable=1
#print (variable)
#Transformando a enteros
lista2=[int (i)for i in lista]
#Guardadno el tamaño del vector
tamaño=len(lista2)
numero=0
#Convirtiendo el numero
for number in lista2:
    numero=numero+number*pow(10,tamaño-1)
    tamaño=tamaño-1
#print(numero)
if numero%2==0 :
#    print("numeropar")
#Viendo el parametro x e Y
    x= (numero+2)//2
    y= (numero)//2
    if x%2==0 :
        sumador(x,variable)
    if y%2==0 :
        sumador(y,variable)
else :
#   print("numero impar")
#Viendo el parametro X e Y para impares
    x=(numero+1)//2
    y=(numero-1)//2
    if x%2!=0 :
        print(x)
        print(variable)
        sumador(x,variable)
    if y%2!=0 and y!=0 :
        sumador(y,variable)


n,k = [int(x) for x in input().split()]
def DTB(num,x):
    if num > 1:
        DTB(num // 2,x)
    x.append(num % 2)
nn=[]
kk=[]
DTB(n,nn)
DTB(k,kk)
if k==1:
    print(n)
elif k==2:
    if n==2:
        print(1)
    else:
        if n%2==0:
            print(n-2)
        else:
            print(n-1)
elif k==3:
    if n%4==2:
        print(n//2-1)
    else:
        print(n//2)
else:
    a = len(kk)-2
    m = len(nn)
    p = 2**(a+1)-1 + (n%(2**a))
    if nn[m-a-1]==1:
        p += 2**(a)
    if p>=k:
        print(int(''.join([str(x) for x in nn[0:(m-a-1)]])+'0', 2))
    else:
        N = nn[0:m-a-1]
        if sum(N)>2:
            N.reverse()
            ind = N.index(1)
            N[ind]=0
            N.reverse()
            N.append(0)
            print(int(''.join([str(x) for x in N]), 2))
        else:
            if m-a-1==1:
                print(1)
            else:
                if k!= (2**(a+2)-1):
                    print(2**(m-a-1)-2)
                else:
                    print(2**(m-a-2))


import random
s = raw_input().split()

n = int(s[0])
m = int(s[1])

graf = set([])

for i in xrange(m):
    s = raw_input().split()
    u = int(s[0])
    v = int(s[1])
    graf.add((u,v))

    #print graf
if m*4>n*(n-1):
    print -1
else:
    edges = 0
    tries = 0
    while edges < m:
        tries += 1
        if (n>=1000) and (tries > 2):
            break
        edges = 0
        newgraf = set([])
        usedonce = set([])
        usedtwice = set([])
        listv = (range(1,n+1))
        listu = (range(1,n+1))
        random.shuffle(listv)
        random.shuffle(listu)

        for v in listv:
            if edges>=m:
                break
            for u in listu:
#                print "viewing:", u,v
                if v==u:
#                    print "the same"
#                    print
                    continue
                if u in usedtwice:
#                    print "u used twice"
#                    print
                    continue
                if v in usedtwice:

#                    print "v used twice"
#                    print
                    break

                if ((u,v) in graf) or ((v,u) in graf):
#                    print "edge in old graf"
#                    print
                    continue
                if ((u,v) in newgraf) or ((v,u) in newgraf):
#                    print "edge already added"
#                    print
                    continue

                newgraf.add((u,v))
                edges += 1
#                print "adding edge",u,v
#                print "now edges:", edges
                if edges >= m:
                    break
                if u in usedonce:
                    usedtwice.add(u)
                else:
                    usedonce.add(u)
                if v in usedonce:
                    usedtwice.add(v)
                    #continue
                else:
                    usedonce.add(v)
#                print "usedonce:", usedonce
#                print "usedtwice:", usedtwice
#                print
#                print
    if (n>=1000) and (tries > 2):
        print -1
    else:
        for e in newgraf:
            print e[0], e[1]


#http://codeforces.ru/problemset/problem/255/D

##def cells():
##    #start second is 0 res = 1
##    res = 1
##    yield res
##    i = 2
##    while True:
##        res = res + 4 * (i - 1)
##        i += 1
##        yield res

def cells_a(second):
    return sum(xrange(1,second*2,2))*2 + second*2 + 1

def cells_dir(second):
    return sum(xrange(1,second*2,2))

n, x, y, c = map(int, raw_input().split())
second = 0
while True:
    dcx = cells_dir(second-x+1) + cells_dir(second-n+x)
    dcy = cells_dir(second-y+1) + cells_dir(second-n+y)
##    print 'Second %d, dcx %d, dcy %d, cells %d' %(
##        second, dcx, dcy, cells_a(second))
    if cells_a(second) - dcx - dcy >= c: break
    second += 1
print second


months = {'January':1, 'February':2, 'March':3, 'April':4, 'May':5, 'June':6, 'July':7, 'August':8, 'September':9, 'October':10, 'November':11, 'December':12}
month = str(input())
add = int(input())

out = {v:k for k,v in months.items()}

val = months[month]
new_val = (val+add) % 12
print(out[new_val])


n = int(input())
*a, = map(int, input().split())
b = sorted(a)
for i in a:
    print((a[b.index(i) + 1]) % n, end=' ')


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

cake = []

for _ in range(a):
	cake.append([x for x in input()])

count = 0
x, y = 0, 0

step = 0
while x < b and y < a:
	if cake[y][x] == "*":
		count += 1
	if step % 2 == 0:
		y += 1
		if y == a:
			y -= 1
			x += 1
	else:
		x += 1
		if x == b:
			x -= 1
			y += 1
	step += 1
		'''
		y += 1
		if y == a:
			y -= 1
			x += 1
	else:
		x += 1
		if x == b:
			x -= 1
			y += 1
		'''

print(count)