s=[int(n) for n in input()]
z=[int(n) for n in input()]
s.sort()
m=v=0
for n in range(len(s)):
	if s[n]!=0:
		s[0]=s[n]e
		s[n]=0
#1³print(s)
for n in range(len(s)):Aa:
	m+=s[n]*10**(n)
for n in range(len(z)):
	v+=z[n]*10**(n)
if m==v:
	print('OK')
else:
	print('WRONG_ANSWER')


"""
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said:

—Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes.

—No problem! — said Bob and immediately gave her an answer.

Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict.

Input
The first line contains one integer n (0 ≤ n ≤ 109) without leading zeroes. The second lines contains one integer m (0 ≤ m ≤ 109) — Bob's answer, possibly with leading zeroes.

Output
Print OK if Bob's answer is correct and WRONG_ANSWER otherwise.
"""

q = list(map(int, list(input())))
q_set = set(q)

a = input()

if len(q) == 1:
    print("OK" if (int(a) == q[0] and len(a) == 1) else "WRONG_ANSWER")

else:
    answer  = ''

    has_zero = 0 in q_set
    if has_zero:
        q_set.remove(0)

    min_elm = min(q_set)
    q_set.remove(min_elm)
    answer += str(min_elm) + ('0' * q.count(0) if has_zero else '') + str(min_elm)* (q.count(min_elm) - 1)-

    while q_set:
        min_elm = min(q_set)
        q_set.remove(min_elm)
        answer += str(min_elm)*q.count(min_elm)

    print("OK" if a == answer else "WRONG_ANSWER")


f __name__ == '__main__':
	    n=raw_input()
		m=raw_input()
		l=len(n)
		n=list(n)
		n.sort()
		i=0
		while i<l and n[i]=='0':
			i+=1
		if i<l and i!=0:
			n[0]=n[i]
			n[i]='0'
		n=''.join(n)
		if n==m:
			print "OK"
		else:
			print "WRONG_ANSWER"


import math

def check_good(n):
    for i in range(int(math.sqrt(n)) + 2):
        if n == i * (i - 1):
            return i
    return -1

def magic(n):
    res = []
    while True:
        ni = check_good(n)
        if ni > 0:
            res.append(ni)
            break
        else:
            ni = int(math.sqrt(n))
            if ni == 1:
                # n = 2
                res.append(2)
                break
            res.append(ni)
            n -= ni * (ni - 1)
    return res

k = int(raw_input())
res = magic(2 * k)
ans = []
for i in range(len(res)):
    ans.append(res[i] * chr(ord('a') + i))
print ''.join(ans)


import math

def check_good(n):
    for i in range(int(math.sqrt(n)) + 2):
        if n == i * (i - 1):
            return i
    return -1

def magic(n):
    res = []
    while True:
        ni = check_good(n)
        if ni > 0:
            res.append(ni)
            break
        else:
            ni = int(math.sqrt(n))
            if ni == 1:
                # n = 2
                res.append(2)
                break
            res.append(ni)
            n -= ni * (ni - 1)
    return res

k = int(raw_input())
res = magic(2 * k)
ans = []
for i in range(len(res)):
    ans.append(''.join(res[i] * [chr(ord('a') + i)]))
print ''.join(ans)


import math

def check_good(n):
    for i in range(int(math.sqrt(n)) + 2):
        if n == i * (i - 1):
            return i
    return -1

def magic(n):
    res = []
    while True:
        ni = int(math.sqrt(n))
        if ni == 1:
                # n = 2
            res.append(2)
            break
        res.append(ni)
        n -= ni * (ni - 1)
    return res

k = int(raw_input())
res = magic(2 * k)
ans = []
for i in range(len(res)):
    ans.append(res[i] * chr(ord('a') + i))
print ''.join(ans)


k = int(input())
res, t = "", 0
chars = [chr(ord('a')+i) for i in range(26)]
for c in chars
    i = 0
    while t + i <= k:
        res += c
        t += i
        i += 1
print(res)


k = int(input())
if k == 1:
    print('fall')
    exit(0)
if k == 3:
    print('september')
    exit(0)
# от порядка объединения строк ничего не зависит
# для каждой буквы, итоговая стоимость будет n * (n - 1) / 2
# жадно наберём ответ
if not k:
    print('a')
    exit(0)
op_count = [0, 0]
for i in range(1, 500):
    op_count.append(op_count[-1] + i)
    if op_count[-1] > k:
        break

ans = []
letter = 'a'
for i in range(len(op_count) - 1, 1, -1):
    while op_count[i] <= k:
        k -= op_count[i]
        ans.append(letter * i)
        letter = chr(ord(letter) + 1)
print(''.join(ans))


a = input().split(' ')
x = int(a[0])
y = int(a[1])

passo = 1
while(1)
    x -= passo
    if x < 0 :
        print('Vladik')
        break
    passo += 1
    y -= passo
    if y < 0 :
        print('Valera')
        break
    passo += 1


a = input().split(' ')
x = int(a[1])
y = int(a[2])

passo = 1
while(1)
    x -= passo
    if x < 0 :
        print('Vladik')
        break
    passo += 1
    y -= passo
    if y < 0 :
        print('Valera')
        break
    passo += 1


inp = input().split(' ')
vladik = int(inp[0])
valera = int(inp[1])
sub = 1
while(vladik>=0 && valera>=0):
	if sub%2!=0:
		vladik-=sub
		sub+=1
	elif sub%2==0:
		valera-=sub
		sub+=1
	if(valera<0):
		print("valera")
		break
	elif(vladik<0):
		print("vladik")
		break


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

iter = int((10**4)*(10**0.5))
for k in range(1, iter+1):
	a_star = k ** 2
	b_star = k * (k+1)

	if a_star >= a:
		return "Vladik"
	if b_start >= b:
		return "Valera"


n = int(input())
res = 0
for a in range(1, n + 1):
    for b in range(a, n + 1):
        for c in range(b, n + 1):
            if a^b == c and a + b != c:
                res += 1
print(res)


n = int(input())
sum = 0
for i in range(1,n+1):
    for j in range (i,n+1):
        if i^j <= n and i^j>j and i+j>i^j:
            sum += 1
print(sum)


n = int(input())
sum = 0
for i in range(1,n+1):
    for j in range (i,n+1):
        tmp = i^j
        if tmp <= n and tmp>j and i+j>tmp:
            sum += 1
print(sum)


print(sum(i-j<i^j>j for i in range(input())+1)for j in range(i//2)))


print(sum(i-j<i^j>j for i in range(input())+1)for j in range(i/2)))


print"YNEOS"[!all(raw_input() in["WB"*4,"BW"*4] for i in[0]*8)::2]


arr=[         list(  input()   )      for _ in range (8)      ]
cw=0
cb=0
flag = True

for i,j in range(1,8):
    if ((arr[i][j]) == arr[i-1][j-1]) :
        flag =False

if  (flag == True):
    print("YES")
else (flag == False):
    print("NO")


print"YNEOS"[!all(raw_input() in["WB"*4,"BW"*4] for i in[0]*8)]


a = []
for i in range(8):
    m = raw_input()
    if m.count("W") != 4:
        print "NO"
        exit(0)
    else:
        for i in range(7):
            if m[i] == m[i+1]:
                print "NO"
                exit(0)

print "


chessDesk = [];
for j in range(8):
    chessDesk.append(raw_input());
right = True;
for i in range(8):
    if "WW" in chessDesk[i] or "BB" in chessDesk[i]:
        right = False;
        break;
if right: print "YES";
else print "NO";


a,b = raw_input().split()
c = list(map(int,raw_input().split()))
a = int(a)
b = int(b)

a = a*8
r=0
cnt =0
for i in range(len(c)):
    if c[i] %2 ==1:
        c[i] = c[i]+1
        cnt = cnt +1
    r = r+c[i]

if r > a or r==a and b == a/2 and cnt <n:
    print "NO"
else:
    print "YES"


from sys import exit

num_rows, num_groups = map(int, raw_input().split(' '))

groups = map(int, raw_input().split(' '))

num_quads, num_doubles = num_rows, 2 * num_rows

# Fully fill up first quads, then doubles, as many as possible

for i in xrange(num_groups):
    occupiable_quads = min(num_quads, groups[i] / 4)

    num_quads -= occupiable_quads
    groups[i] -= 4 * occupiable_quads

for i in xrange(num_groups):
    occupiable_doubles = min(num_doubles, groups[i] / 2)

    num_doubles -= occupiable_doubles
    groups[i] -= 2 * occupiable_doubles

# If there are groups of 4 and up left, problem is infeasible
# (not sure if this even possible under the assignment conditions, but doesn't hurt to check :>)

if len(filter(lambda x: x >= 4, groups)) != 0:
    print "NO"

    exit(0)

# Subproblem:
# distribute groups of 1, 2 and 3 people over leftover quads and doubles

# Distribute all groups of 3 first over quads, then over doubles (because a quad is less useful than two doubles)

for i in filter(lambda x: groups[x] == 3, xrange(num_groups)):
    if num_quads == 0:
        break

    groups[i] = 0
    num_quads -= 1

for i in filter(lambda x: groups[x] == 3, xrange(num_groups)):
    if num_doubles == 0:
        break

    groups[i] = 0
    num_doubles -= 2

# If we coudn't distribute all groups of 3, the problem is infeasible

if len(filter(lambda x: x == 3, groups)) != 0:
    print "NO"

    exit(0)

# Subproblem:
# distribute groups of 1 and 2 over leftover quads and doubles

# Distribute pairs of 1 and 2 groups over quads, thus filling the quads up

for i, j in zip(
    filter(lambda i: groups[i] == 1, xrange(num_groups)),
    filter(lambda i: groups[i] == 2, xrange(num_groups))
    ):

    if num_quads == 0:
        break

    groups[i] = 0
    groups[j] = 0

if num_quads == 0:
    # Subproblem:
    # distribute groups of 1 and 2 over the remaining doubles

    for i in xrange(num_groups):
        if num_doubles == 0:
            break

        if groups[i] == 1 or groups[i] == 2:
            groups[i] = 0
            num_doubles -= 1
else:
    # There are quads left, but either groups of 1 or groups of 2 are gone (or both)

    if len(filter(lambda x: x == 2, groups)) != 0:
        # Subproblem:
        # distribute groups of 2 over the remaining quads and doubles

        for i in xrange(num_groups):
            if num_doubles == 0:
                break

            if groups[i] == 2:
                num_doubles -= 1
                groups[i] = 0

        for i in xrange(num_groups):
            if num_quads == 0:
                break

            if groups[i] == 2:
                num_quads -= 1
                groups[i] = 0

    elif len(filter(lambda x: x == 1, groups)) != 0:
        # Subproblem:
        # distribute groups of 1 over the remaining quads and doubles

        for i in xrange(num_groups):
            if num_doubles == 0:
                break

            if groups[i] == 1:
                num_doubles -= 1
                groups[i] = 0

        one_groups = filter(lambda i: groups[i] == 1, xrange(num_groups))

        for i, j in zip(one_groups[:len(one_groups) / 2], one_groups[len(one_groups) / 2:]):
            if num_quads == 0:
                break

            groups[i] = 0
            groups[j] = 0

            quads -= 1

        if num_quads != 0:
            for i in xrange(num_groups):
                if groups[i] == 1:
                    groups[i] = 0
                    num_quads -= 1

                    break

# If anything has remained after the distribution, the problem is infeasible

if sum(groups) == 0:
    print "YES"
else:
    print "NO"


rows, groups = map(int, input().split())
soldiers=list(map(int, input().split()))
def makePlane(rows):
    plane=[int(rows),2*int(rows),0]
    return(plane)
def rozdelitVojaky(soldiers):
    ctyrky,dvojky,jednicky=0,0,0
    for skupina in soldiers:
        skupina=int(skupina)
        while skupina>=4:
            ctyrky+=1
            skupina-=4
        if skupina>=2:
            dvojky+=1
        if skupina%2==1:
            jednicky+=1
    return([ctyrky,dvojky,jednicky])
def zjistit(rows,groups,soldiers):
    plane=makePlane(rows)
    pasazeri=rozdelitVojaky(soldiers)

    #usadit ctverice
    if pasazeri[0]<=plane[0]:
        plane[0]-=pasazeri[0]
        pasazeri[0]=0
    else:
        pasazeri[0]-=plane[0]
        pasazeri[1]+=2*pasazeri[0]
        plane[0]=0

    #dvojicky
    #do ctyrmist
    if pasazeri[1]<=plane[0]:
        plane[0]-=pasazeri[1]
        plane[2]+=pazazeri[1]
        pasazeri[1]=0
    else:
        pasazeri[1]-=plane[0]
        plane[2]+=plane[0]
        plane[0]=0
        #do dvojmist
        if pasazeri[1]<=plane[1]:
            plane[1]-=pasazeri[1]
            pasazeri[1]=0
        else:
            pasazeri[1]-=plane[1]
            pasazeri[2]+=2*pasazeri[1]
            plane[1]=0
    #jednotlivci
    pasazeri[2]=pasazeri[2]-2*plane[0]-plane[1]-plane[2]
    if pasazeri[2]<=0:
        return("YES")
    else:
        return("NO")

print(zjistit(rows,groups,soldiers))


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

left4seat = n
left2seat = n * 2
left1seat = 0
for i in range (0, n) :
	left4seat -= a[i] // 4
	if (left4seat < 0) :
		left2seat += 2 * left4seat
		left4seat = 0

index = 0
while (index < k ) :
	leftSol = a[index] % 4
	if (leftSol >= 3) :
		if (left4seat > 0) : left4seat -= 1
		else : left2seat -= 2
	elif (leftSol == 2) :
		if (left4seat > 0) :
			left4seat -= 1
			left1seat += 1
		else :
			left2seat -= 1
	elif (leftSol == 1) :
		if (left1seat > 0) : left1seat -= 1
		elif (left4seat > 0) :
			left4seat -= 1
			left2seat += 1
		else :
			left2seat -= 1
	if (left4seat < 0 or left2seat < 0) : break
	index += 1

if (index == k and left4seat >= 0 and left2seat >= 0) : print("YES")
else : print("NO")


import sys

def solve(n, k, groups):
    avail_2 = n*2
    avail_4 = n

    for group in groups:
        while group > 0:
            if avail_2 == 0 and avail_4 == 0:
                return 'NO'
            else:
                # fill 4s preferentially as 4s
                if avail_4 > 0 and group >= 3:
                    if group == 3:
                        group = 0
                        avail_4 -= 1
                        group -= 3
                    else:
                        req_4 = group / 4
                        if req_4 >= avail_4:
                            group -= avail_4 * 4
                            avail_4 = 0
                        else:
                            group -= req_4 * 4
                            avail_4 -= req_4
                # then fill 2s
                elif avail_2 > 0:
                    req_2 = group / 2 + group % 2
                    if req_2 >= avail_2:
                        group -= avail_2 * 2
                        avail_2 = 0
                    else:
                        group -= req_2 * 2
                        avail_2 -= req_2
                # finally fill with flex 4s
                else:
                    # either group = 2 or group = 1
                    if group == 1:
                        group = 0
                        avail_4 -= 1
                        avail_2 += 1
                    elif group == 0:
                        group = 0
                        avail_4 -= 1

    return 'YES'

if __name__ == '__main__':
    n, k = map(int, sys.stdin.readline().split())
    groups = map(int, sys.stdin.readline().split())
    print solve(n, k, groups)


def find_object_idx(cells, symbol):
    for idx, val in enumerate(cells):
        if val == symbol:
            return idx

if __name__ == "__main__":
    num_cells, k = [int(x) for x in input.split()]
    cells = input()

    grasshopper_idx = find_object_idx(cells, "G")
    insect_idx = find_object_idx(cells, "T")
    start_index = min(grasshopper_idx, insect_idx)
    target_index = max(grasshopper_idx, insect_idx)
    while start_index <= target_index:
        if start_index == target_index:
            print("YES")
            return
        elif start_index == "#":
            print("NO")
            return
        start_index += k
    print("NO")


import sys

if __name__ == "__main__":
    a = sys.stdin.readline.rstrip().split(' ')
    count = int(a[0])
    jump = int(a[1])
    s = sys.stdin.readline.rstrip()
    grasshopper_location = s.find('G')
    target_location = s.find('T')
    r = "YES"
    if abs(grasshopper_location - target_location) % jump != 0:
        print('NO')
    else:
        if grasshopper_location > target_location:
            i = grasshopper_location - jump
            while i > target_location:
                if s[i] == '#':
                    r = "NO"
                    break
                i -= jump
        else:
            i = grasshopper_location + jump
            while i < target_location:
                if s[i] == '#'
                    r = "NO"
                    break
                i += jump
        print(r)


import sys
n,k = map(int, sys.stdin.readline().split())
s = raw_input()
g = -1
t = -1
for i in range(len(s)):
	if s[i] == 'G':
		g = i
	if s[i] == 'T'
		t = i

if t > g:
	t,g = g,t

cur = t
found = False
while cur < n:
	if cur == g:
		found = True
		break
	if s[cur] == '#':
		break
	cur += k
if found:
	print 'YES'
else:
	print 'NO'


a = [int(i) for i in input().split()]
n = a[0]
k = int(a[1])
s = input()
i1 = 0
i2 = 0
dc = 0
hc = 0

for i in range(len(s)) :
	if s[i] == 'G':
		i1 = i
	elif s[i] == 'T':
		i2 = i
	elif s[i] == '.':
		dc += 1
	elif s[i] == '#':
		hc += 1
flag  = 0
done = 0
if len(s)-2 == dc and k == 1 :

    print("YES")
    raise SystemExit(0)
elif i2 - i1 == k :

    print("YES")
    raise SystemExit(0)
if i1 < i2 :
	for i in range(i1,i2+1,k):
		if s[i] == '#':
			flag = 1
			print("NO")
            raise SystemExit(0)
			break
		elif s[i] == 'G':
			flag = 0
			print("YES")
			raise SystemExit(0)
            break
		elif s[i] == '.' :
			continue
		else :
			flag = 1
elif i1 > i2 :
	for i in range(i2,i1+1,k):
		if s[i] == '#':
			flag = 1
			print("NO")
			raise SystemExit(0)
            break
		elif s[i] == 'G':
			flag = 0
			print("YES")
			raise SystemExit(0)
            break
		elif s[i] == '.':
			continue
		else :
			flag = 1
if flag == 1 and done != 100 :
	print("NO")
    raise SystemExit(0)


trash, n = [int(x) for x in input().split()]
x = [str(x) for x in input().split()]
s = list(x[0])
done = False
for i in range(len(s)):
    if s[i] == 'T' or s[i] == 'G':
        for j in range(i+n, len(s), n):
            if s[j] == 'T' or s[j] == 'G':
                print('YES')
                done = True
                break
            if s[j] == '#':
                print('NO')
                done = True
                break
        if done:
            break
if not done:
    print('NO)


import sys
import math
from collections import defaultdict
ans=0
def get(dic,cur,size,ans):
    res=fac[size]
    for i in cur:
        res//=fac[cur[i]]
    #print(res,'ans',size,'size',cur,'cur',dic,'dic')
    if cur['0']>0:
        y=fac[size-1]
        for i in cur:
            if i!=0:
                y//=fac[cur[i]]
            else:
                y//=fac[cur[i]-1]
        res-=y
    #print(res,'res')
    ans+=res
    #print(ans,'adnekw')
    res2=0
    for j in dic:
        if dic[j]>=1:
            temp=cur.copy()
            temp[j]+=1
            dictemp=dic.copy()
            dictemp[j]-=1
            x=get(dictemp,temp,size+1,ans)
            res2+=x
            #print(x,'x')
            #ans+=x
    return res+res2
s=sys.stdin.readline()[:-1]
fac=[1]
for i in range(1,30):
    x=fac[-1]*i
    fac.append(x)
#print(fac,'fac')
dic=defaultdict(int)
n=len(s)
for i in range(n):
    dic[s[i]]+=1
cur=defaultdict(int)
for i in dic:
    dic[i]-=1
    cur[i]+=1
#print(ans,'ansnsnns')
x=get(dic,cur,len(dic),ans)
print(x)


from collections import defaultdict
from copy import deepcopy

a = list(input())

d = defaultdict(int)
for x in a:
    d[int(x)] += 1

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

mem = {}

def f(d):
    n = sum(d.values())
    ans = 0
    if d[0] > 0:
        ans += (n - 1) * fact(n - 1)
    else:
        ans += fact(n)
    for x in d:
        ans //= fact(d[x])
    for k in d:
        if d[k] > 1:
            e = deepcopy(d)
            e[k] -= 1
            ans += f(e)
    mem[frozenset(d.items())] = ans
    return ans

ans = f(d)
print(ans)


import math
n=int(input())
s=str(n)
di={}
#di={str(i):0 for i in range(0,10)}
for c in list(s):
    if c in di:
        di[c]+=1
    else:
        di[c]=1
#print(di)

v=[k for k in di]
cnt={k:1 for k in di}
ans=0
def solve():
    n=len(v)
    ans=n-v.count('0')
    for i in range(1,n):
        ans=ans*(n-i)
    for k in cnt:
        ans=ans/(math.factorial(cnt[k]))
    #print(v,ans)
    return ans
def f():
    #print(v)
    global ans
    ans+=solve()
    for k in di:
        if cnt[k]<di[k]:
            v.append(k)
            cnt[k]+=1
            f()
            v.pop()
            cnt[k]-=1

f()
print(int(ans))


#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<unordered_map>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdio>
const int N=1e5;
const int mod=1e9+7;
const int INF=0x7fffffff;
const int inf=0x3f3f3f3f;
using namespace std;
int num[10];
unsigned long long jc[20];
unsigned long long ans=0;
int i1,i2,i3,i4,i5,i6,i7,i8,i9,i0,tj=0;

void tiao0y()
{
    for(int i=1;i<=num[0];i++)
    {
        i0=i;
        if(!num[1] && !num[2] && !num[3] && !num[4] && !num[5] && !num[6] && !num[7] && !num[8] && !num[9]) ans+=1;
        else
        {
            if(i1>0) ans+=jc[i1+i2+i3+i4+i5+i6+i7+i8+i9+i0-1]/(max(jc[num[i1]-1],(unsigned long long)1)*max(jc[num[i2]],(unsigned long long)1)*max(jc[num[i3]],(unsigned long long)1)*max(jc[num[i4]],(unsigned long long)1)*max(jc[num[i5]],(unsigned long long)1)*max(jc[num[i6]],(unsigned long long)1)*max(jc[num[i7]],(unsigned long long)1)*max(jc[num[i8]],(unsigned long long)1)*max(jc[num[i9]],(unsigned long long)1));
            if(i2>0) ans+=jc[i1+i2+i3+i4+i5+i6+i7+i8+i9+i0-1]/(max(jc[num[i1]],(unsigned long long)1)*max(jc[num[i2]-1],(unsigned long long)1)*max(jc[num[i3]],(unsigned long long)1)*max(jc[num[i4]],(unsigned long long)1)*max(jc[num[i5]],(unsigned long long)1)*max(jc[num[i6]],(unsigned long long)1)*max(jc[num[i7]],(unsigned long long)1)*max(jc[num[i8]],(unsigned long long)1)*max(jc[num[i9]],(unsigned long long)1));
            if(i3>0) ans+=jc[i1+i2+i3+i4+i5+i6+i7+i8+i9+i0-1]/(max(jc[num[i1]],(unsigned long long)1)*max(jc[num[i2]],(unsigned long long)1)*max(jc[num[i3]-1],(unsigned long long)1)*max(jc[num[i4]],(unsigned long long)1)*max(jc[num[i5]],(unsigned long long)1)*max(jc[num[i6]],(unsigned long long)1)*max(jc[num[i7]],(unsigned long long)1)*max(jc[num[i8]],(unsigned long long)1)*max(jc[num[i9]],(unsigned long long)1));
            if(i4>0) ans+=jc[i1+i2+i3+i4+i5+i6+i7+i8+i9+i0-1]/(max(jc[num[i1]],(unsigned long long)1)*max(jc[num[i2]],(unsigned long long)1)*max(jc[num[i3]],(unsigned long long)1)*max(jc[num[i4]-1],(unsigned long long)1)*max(jc[num[i5]],(unsigned long long)1)*max(jc[num[i6]],(unsigned long long)1)*max(jc[num[i7]],(unsigned long long)1)*max(jc[num[i8]],(unsigned long long)1)*max(jc[num[i9]],(unsigned long long)1));
            if(i5>0) ans+=jc[i1+i2+i3+i4+i5+i6+i7+i8+i9+i0-1]/(max(jc[num[i1]],(unsigned long long)1)*max(jc[num[i2]],(unsigned long long)1)*max(jc[num[i3]],(unsigned long long)1)*max(jc[num[i4]],(unsigned long long)1)*max(jc[num[i5]-1],(unsigned long long)1)*max(jc[num[i6]],(unsigned long long)1)*max(jc[num[i7]],(unsigned long long)1)*max(jc[num[i8]],(unsigned long long)1)*max(jc[num[i9]],(unsigned long long)1));
            if(i6>0) ans+=jc[i1+i2+i3+i4+i5+i6+i7+i8+i9+i0-1]/(max(jc[num[i1]],(unsigned long long)1)*max(jc[num[i2]],(unsigned long long)1)*max(jc[num[i3]],(unsigned long long)1)*max(jc[num[i4]],(unsigned long long)1)*max(jc[num[i5]],(unsigned long long)1)*max(jc[num[i6]-1],(unsigned long long)1)*max(jc[num[i7]],(unsigned long long)1)*max(jc[num[i8]],(unsigned long long)1)*max(jc[num[i9]],(unsigned long long)1));
            if(i7>0) ans+=jc[i1+i2+i3+i4+i5+i6+i7+i8+i9+i0-1]/(max(jc[num[i1]],(unsigned long long)1)*max(jc[num[i2]],(unsigned long long)1)*max(jc[num[i3]],(unsigned long long)1)*max(jc[num[i4]],(unsigned long long)1)*max(jc[num[i5]],(unsigned long long)1)*max(jc[num[i6]],(unsigned long long)1)*max(jc[num[i7]-1],(unsigned long long)1)*max(jc[num[i8]],(unsigned long long)1)*max(jc[num[i9]],(unsigned long long)1));
            if(i8>0) ans+=jc[i1+i2+i3+i4+i5+i6+i7+i8+i9+i0-1]/(max(jc[num[i1]],(unsigned long long)1)*max(jc[num[i2]],(unsigned long long)1)*max(jc[num[i3]],(unsigned long long)1)*max(jc[num[i4]],(unsigned long long)1)*max(jc[num[i5]],(unsigned long long)1)*max(jc[num[i6]],(unsigned long long)1)*max(jc[num[i7]],(unsigned long long)1)*max(jc[num[i8]-1],(unsigned long long)1)*max(jc[num[i9]],(unsigned long long)1));
            if(i9>0) ans+=jc[i1+i2+i3+i4+i5+i6+i7+i8+i9+i0-1]/(max(jc[num[i1]],(unsigned long long)1)*max(jc[num[i2]],(unsigned long long)1)*max(jc[num[i3]],(unsigned long long)1)*max(jc[num[i4]],(unsigned long long)1)*max(jc[num[i5]],(unsigned long long)1)*max(jc[num[i6]],(unsigned long long)1)*max(jc[num[i7]],(unsigned long long)1)*max(jc[num[i8]],(unsigned long long)1)*max(jc[num[i9]-1],(unsigned long long)1));
        }
    }
}
void tiao0n()
{
    ans+=jc[i1+i2+i3+i4+i5+i6+i7+i8+i9]/(jc[num[1]]*jc[num[2]]*jc[num[3]]*jc[num[4]]*jc[num[5]]*jc[num[6]]*jc[num[7]]*jc[num[8]]*jc[num[9]]);
}

void tiao9y()
{
    for(int i=1;i<=num[9];i++)
    {
        i9=i;
        if(num[0]>0) tiao0y();
        else tiao0n();
    }
}
void tiao9n()
{
    i9=0;
    if(num[0]>0) tiao0y();
    else tiao0n();
}

void tiao8y()
{
    for(int i=1;i<=num[8];i++)
    {
        i8=i;
        if(num[9]>0) tiao9y();
        else tiao9n();
    }
}
void tiao8n()
{
    i8=0;
    if(num[9]>0) tiao9y();
    else tiao9n();
}

void tiao7y()
{
    for(int i=1;i<=num[7];i++)
    {
        i7=i;
        if(num[8]>0) tiao8y();
        else tiao8n();
    }
}
void tiao7n()
{
    i7=0;
    if(num[8]>0) tiao8y();
    else tiao8n();
}

void tiao6y()
{
    for(int i=1;i<=num[6];i++)
    {
        i6=i;
        if(num[7]>0) tiao7y();
        else tiao7n();
    }
}
void tiao6n()
{
    i6=0;
    if(num[7]>0) tiao7y();
    else tiao7n();
}

void tiao5y()
{
    for(int i=1;i<=num[5];i++)
    {
        i5=i;
        if(num[6]>0) tiao6y();
        else tiao6n();
    }
}
void tiao5n()
{
    i5=0;
    if(num[6]>0) tiao6y();
    else tiao6n();
}

void tiao4y()
{
    for(int i=1;i<=num[4];i++)
    {
        i4=i;
        if(num[5]>0) tiao5y();
        else tiao5n();
    }
}
void tiao4n()
{
    i4=0;
    if(num[5]>0) tiao5y();
    else tiao5n();
}

void tiao3y()
{
    for(int i=1;i<=num[3];i++)
    {
        i3=i;
        if(num[4]>0) tiao4y();
        else tiao4n();
    }
}
void tiao3n()
{
    i3=0;
    if(num[4]>0) tiao4y();
    else tiao4n();
}

void tiao2y()
{
    for(int i=1;i<=num[2];i++)
    {
        i2=i;
        if(num[3]>0) tiao3y();
        else tiao3n();
    }
}
void tiao2n()
{
    i2=0;
    if(num[3]>0) tiao3y();
    else tiao3n();
}

void tiao1y()
{
    for(int i=1;i<=num[1];i++)
    {
        i1=i;
        if(num[2]>0) tiao2y();
        else tiao2n();
    }
}
void tiao1n()
{
    i1=0;
    if(num[2]>0) tiao2y();
    else tiao2n();
}

int main()
{
    std::ios::sync_with_stdio(false);

    long long shu;
    jc[0]=1;
    for(int i=1;i<=18;i++)
    {
        jc[i]=jc[i-1]*i;
    }
    cin>>shu;
    while(shu)
    {
        num[shu%10]++;
        shu/=10;
        tj++;
    }
    if(num[1]>0) tiao1y();
    else tiao1n();
    cout<<ans<<endl;
    return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <cstring>
#include <unordered_set>

using namespace std;

int main()
{
    long long a;
    int b[10];

    cin >> a;
    while(a)
    {
        ++ b[a % 10];
        a /= 10;
    }

    for(int i = 0; i <= 9; ++ i)
    {
        if(b[i])
        {

        }
    }

    return 0;
}


As = list(map(int, input().split()))

def solve(As):
    L = As[0] + As[1] + As[2]
    return L**2 - As[0]**2 - As[2]**2 - As[4]**2

print(max(solve(As), solve(As[1:] + [As[0]]))


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

f = lambda l:[1, l, 0, l-1]
ans = [(n,m),(0,0)]
if n == 0:
    ans = [(0, y) for y in f(m)]
elif m == 0:
    ans = [(x, 0) for x in f(n)]
else:
    pts = [(x, y) for x in f(n) for y in f(m)]
    d = lambda u,v: sum([(u[i]-v[i])**2 for i in [0,1]])
    cur = ans[-1]
    if math.sqrt(d(n,m)) + max(n,m) < math.sqrt(d(n-1, m)) + math.sqrt(d(n,m-1)):
        ans =
    while len(ans) < 4:
        for p in pts:
            if p in ans: continue
            if d(cur,ans[-1]) < d(p,ans[-1]): cur = p
        ans += [cur]
print ans


a,b,c,d,e,f = map(int, raw_input().split())
print (a+b+c)**2 - a**2 - с**2 - e**2


#!/usr/bin/env python3

w, h = map(int, input().split())

w_edge = h_edge = 0
for i in range(2, w + 1, 2):
    w_edge += (w - i + 1)
for i in rnage(2, h + 1, 2):
    h_edge += (h - i + 1)
print(w_edge * h_edge)


w = input()
h = input()
print w*h*(w+w%2)*(h+h%2)/16


w, h = input(), input()
print w*h*(w+w%2)*(h+h%2)/16


path = raw_input()
pos = (0,0)
visit = set()
visit.add(p)

for c in path:
	if c == "L":
		t = (pos[0]+1,pos[1])
	if c == "R":
		t = (pos[0]-1,pos[1])
	if c == "U":
		t = (pos[0],pos[1]+1)
	if c == "D":
		t = (pos[0],pos[1]-1)

	s = set()
	s.add( t )
	s.add( (t[0]+1,t[1]) )
	s.add( (t[0]-1,t[1]) )
	s.add( (t[0],t[1]+1) )
	s.add( (t[0],t[1]-1) )
	s -= set([pos])

	for x in s:
		if x in pos:
			print "BUG"
			exit(0)

	pos.add(t)
	pos = t

print "OK"


#!/usr/bin/python
from pprint import pprint
path=list(str(raw_input()))
pathStr=path
upMax=path.count('U')
downMax=path.count('D')
leftMax=path.count('L')
rightMax=path.count('R')

x=[['x']*100 for i in xrange(100)]
i,j=50,50

x[i][j]='.';
for c in path:
    if c=='L':
        j-=1
        x[i][j]='.'
    elif c=='R':
        j+=1
        x[i][j]='.'
    elif c=='U':
        i-=1
        x[i][j]='.'
    elif c=='D':
        i+=1
        x[i][j]='.'

#pprint(x)

def bfs(i,j):
    open_list=[[i,j]]
    path={}
    visited=[]
    path[(i,j)]=[]
    while len(open_list)>0:
        current = open_list[0]
        del open_list[0]
        if current not in visited:
            visited.append(current)

        for i in neighbors(current[0],current[1]):
            if i not in visited:
                path[(i[0],i[1])]=path[tuple(current)]+[i]
                open_list.append(i)
    return path

def neighbors(i,j):
    n=[]
    if x[i][j-1]=='.':
        n.append([i,j-1])
    if x[i][j+1]=='.':
        n.append([i,j+1])
    if x[i-1][j]=='.':
        n.append([i-1,j])
    if x[i+1][j]=='.':
        n.append([i+1,j])
    #print n
    return n

centery=50
centerx=50
path= bfs(centerx,centery)
y=centery-leftMax+rightMax
x=centerx+downMax-upMax
#print path[(x,y)]
if len(path[(x,y)])<len(pathStr):
    print "BUG"
else:
    print "OK"


string = input()
geo_map = [[0]*100 for i in range(100)]
x = 50
y = 50
geo_map[x][y] = 1
optimal_check = 0
state = True
for c in string:
    optimal_check = 0
    if c == 'R':
        x += 1
    elif c == 'L':
        x -= 1
    elif c == 'U':
        y += 1
    elif c == 'D':
        y -= 1
    if geo_map[x][y] == 1:
        print('BUG')
        state = False
        break
    else:
        geo_map[x][y] = 1

    if geo_map[x+1][y] == 1:
        optimal_check += 1
    if geo_map[x-1][y] == 1:
        optimal_check += 1
    if geo_map[x][y+1] == 1:
        optimal_check += 1
    if geo_map[x][y-1] == 1:
        optimal_check += 1
    if optimal_check >= 2:
        print('BUG')
        state = False
        break

if state:
    print('OK')


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

  if (left = 1 and right = 1 and up = 1 and down = 0) or (left = 1 and right = 1 and up = 0 and down = 1) or (left = 1 and right = 0 and up = 1 and down = 1) or (left = 0 and right = 1 and up = 1 and down = 1):
      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()


def CF_8B():
	cur = [0,0]
	path = set((0,0))
	for step in input():
		last = tuple(cur[:])
		if step == "L":
			cur[0] -= 1
		elif step == "R":
			cur[0] += 1
		elif step == "U":
			cur[1] += 1
		else:
			cur[1] -= 1
		#判断当前点是否与之前路径上任一点相邻
		if (cur[0]+1,cur[1]) in path or (cur[0]-1,cur[1]) in path or\
		   (cur[0],cur[1]+1) in path or (cur[0],cur[1]-1) in path:
			print("BUG")
			return
		else:
			path.add(last)
	print("OK")
	return

CF_8B();


 R=lambda: map(int, raw_input().split())
_,a,b=R()
c,_,d=R()
e,f,_=R()
print (d+f)/2,a,b
print c,(b+e)/2,d
print e,f,(a+c)/2


import Data.Char

re :: String -> String -> Bool
re (s:sx) (t:ts) = if s == t then re sx ts
  else re sx (t:ts)
re [] (t:ts) = False
re _ _ = True

sw:: String -> String -> String -> Bool
sw (s:sx) n (t:ts)  = if s == t then sw (n++sx) [] ts
  else sw sx (s:n) (t:ts)
sw [] _ (t:ts) = False
sw _ _ _ = True

h :: String -> String -> String
h s t
 | re s t = "automaton"
 | length t == length s && sw s [] t = "array"
 | sw s [] t = "both"
 | otherwise = "need tree"

--main = do
-- line <- getLine
-- print (h line [])

main = do
 line <- getLine
 --let a = (read (takeWhile (/= ' ') line) :: Int)
 --let line1 = drop 1 (dropWhile (/= ' ') line)
 --let b = (read (takeWhile (/= ' ') line1) :: Int)
 --let line2 = drop 1 (dropWhile (/= ' ') line1)
 --let c = (read (takeWhile (/= ' ') line2) :: Int)
 line2 <- getLine
 putStrLn(h line line2)


# cook your dish here
from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left

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

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

def I():
    return int(stdin.readline())

P = 1000000007
for t in range(I()):
    arr = L()
    arr.sort()
    arr[0], arr[-1] = arr[-1], arr[0]
    print(*arr)


n=int(raw_input())
a=raw_input().split()
a=[int(a[i]) for i in range(n)]
a=sorted(a,None,None,True)
a[1:n-1]=sorted(a[1:n-1])
for i in range(n) :
print(a[i])


n = (int)raw_input()
mylist = raw_input().split(' ')
# mylist = [1, 2, 3, 4]
mylist.sort()
tmp = mylist[0]
lenn = len(mylist)
mylist[0] = mylist[lenn-1]
mylist[lenn-1] = tmp
print mylist


import itertools
m = input()
digits = map(int,raw_input().split())
digits.sort()
nums = itertools.permutations(digits)
x = max(nums,key = lambda n:sum([n[i]-n[i+1] for i in range(m-1)]))
print ' '.join(map(str,x))


from itertools import permutations as pr
n=int(input())
a=list(map(int,input().split()))
s=sum((x-y) for x,y in zip(a,a[1:]))
# print(max(sum(abs(x-y) for x,y in zip(b,b[1:])) for b in pr(a)))
k=[]
for b in pr(a):
    t=sum((x-y) for x,y in zip(b,b[1:]))
    if t>=s:
        s=t
        # l=[list(b),s]
        k.append([list(b),s])
k.sort(key=lambda x:-x[1])
i=0
while k[i][1]==k[0][1]:
    i+=1
print(*k[i-1][0])


x = int(raw_input())

print(str((x-2)**2)


n=int(raw_input())
add=n*(n-3)/2
if add=0:
    print 1
elif add%2==0:
    print add*2
else:
    print add*2-1


n = raw_input().split()
n = (int)n

print ((n-2) * (n-2))


a=[]
b=[]
def ok(a):
    a.sort()
    if a[0][0]!=a[1][0] or a[0][0]!=a[2][0]: return False;
    if a[0][0]==a[3][0] or a[3][0]!=a[4][0] or a[3][0]==a[5][0]: return False;
    if a[5][0]!=a[6][0] or a[5][0]!=a[7][0]: return False;
    return True

for i in xrange(8):
    c=map(int,raw_input())
    a.append( c )
    b.append( [c[1],c[0]])

if ok(a) and ok(b):
    print "respectable"
else:
    print "ugly"


#Eight Point Sets

class point:
    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y

x = []
y = []
a = []
for i in range(8):
    u, v = map(int, input().split())
    a.append(point(u, v))
    if u not in x:
        x.append(u)
    if v not in y:
        y.append(v)

    if len(x) > 3 or len(y) > 3:
        print("ugly")
        exit()

x.sort()
y.sort()
a.sort(key=lambda p: (p.x, p.y))
# for i in range(len(a)):
#     print("{} {}".format(a[i].x, a[i].y), end=" ")
k = 0
flag = True
for i in range(3):
    for j in range(3):
        if i == 1 and j == 1:
            continue
        if a[k].x != x[i] or a[k].y != y[j]:
            flag = False
        k += 1

if flag:
    print("respectable")
else:
    print("ugly")


def solve():
    x = [0] * 8
    y = [0] * 8
    xy = [None] * 8

    for i in range(0, 8):
        line = input()
        if line == '':
            line = input()
        x[i], y[i] = map(int, line.split())
        xy[i] = (x[i], y[i])

    a = sorted(x)
    b = sorted(y)

    x1 = a[0]
    x2 = a[3]
    x3 = a[7]
    y1 = b[0]
    y2 = b[3]
    y3 = b[7]

    if(x1==x2 or x1 == x3 or x2 == x3 or y1 == y2 or y1 == y3 or y2 == y3):
        printf("ugly")
        return
    if(a[0]!=a[1] or a[0] != a[2] or a[3]!=a[4] or a[5] != a[6] or a[6]!=a[7]):
        print("ugly")
        return

    if(b[0]!=b[1] or b[0] != b[2] or b[3]!=b[4] or b[5] != b[6] or b[6]!=b[7]):
        print("ugly")
        return

    for i in range(8):
        if (x[i] == x2 and y[i] == y2):
            print("ugly")
            return
        for j in range(i + 1, 8):
            if (xy[i] == xy[j]):
                print("ugly")
                return

    print("respectable")

solve()


import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;

public class Main {
    static final int MAX = (int)1e6 + 5;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> unique_x = new ArrayList<>(), unique_y = new ArrayList<>();
        ArrayList<Point> points = new ArrayList<>();
        boolean[] fre_x = new boolean[MAX], fre_y = new boolean[MAX];

        for (int i = 0; i < 8; i++) {
            int x = sc.nextInt(), y = sc.nextInt();
            points.add(new Point(x, y));

            if (!fre_x[x]) {
                fre_x[x] = true;
                unique_x.add(x);
            }

            if (!fre_y[y]) {
                fre_y[y] = true;
                unique_y.add(y);
            }
        }

        if (unique_x.size() != 3 || unique_y.size() != 3) {
            System.out.print("ugly");
            return;
        }

        Collections.sort(unique_x);
        Collections.sort(unique_y);
        Collections.sort(points);
        int index = 0;

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (i == j && i == 1) {
                    continue;
                }
                if (unique_x.get(i) == points.get(index).x && unique_y.get(j) == points.get(index).y) {
                    index++;
                }
                else {
                    System.out.print("ugly");
                    return;
                }
            }
        }

        System.out.print("respectable");
    }
}

class Point implements Comparable<Point> {
    Integer x, y;

    public Point(int _x, int _y) {
        this.x = _x;
        this.y = _y;
    }

    @Override
    public int compareTo(Point another) {
        if (this.x != another.x) {
            return this.x.compareTo(another.x);
        }
        return this.y.compareTo(another.y);
    }
}


a, b = map(int, input().split())
while 1:
    if a == 0 or b == 0:
        break
    elif a >= b*2:
        a -= b*2;
    elif b >= a*2:
        b -= a*2;
    elif:
        break
print(a, b)


def p3(a,b):

    while a!=0 and b!=0:

    if(a>=2*b):
        a%=(2*b)
        return p3(a,b)
    if(b>=2*a):
        b%=(2*a)
        return p3(a,b)
    return(a,b)

a,b=input().split(" ")
a,b=p3(int(a),int(b))

print(a,b)


f = lambda: (map (int,input().split()))
n,A,B,C,T=f()
print(sum(  A+max(0,(C-B))*(T-x)  for x in f() )


s  = input().split()
a = int(s[0])
b = int(s[1])
while(a!=0 and b!=0):
    if a>=2*b:
        a=a-2*b
        if b<2*a:
            break
    else:
        b=b-2*a

print('{} {}'.format(a, b)


a, b = map(int, input().split())
while a > 0 and b > 0:
    if a >= 2 * b:
        a %= 2 * b
    elif b >= 2 * a:
        b %= 2 * a
    else
        break
print(a, b)


def flip(a):
	b = [1-x for x in a]
	return b
n = input()
a = map(int,raw_input().split())
if(n == 1 and a[0] = 0):
	print 1
elif(a.count(1) == n):
	print n-1
else:
	ans = a.count(1)
	for i in xrange(n):
		for j in xrange(i,n):
			f = 0
			s = 0
			t = 0
			try:
				f = a[:i].count(1)
			except:
				pass
			try:
				x = flip(a[i:j])
				s = x.count(1)
			except:
				pass
			try:
				t = a[j:].count(1)
			except:
				pass
			ans = max(ans, f+s+t)

	print ans


#这题对0就等于求最大子段和

n = int(input())
nums = list(map(int, input().split()))
nums_ = []
count = []
nums2 = point = index1 = index2 = 0
num = []

for i in range(len(nums)):
    if nums[i] == 0:
        nums_.append(1)
    else:
        nums_.append(-1)
    count.append(max(int(nums_[i])+nums2, int(nums_[i])))
    if int(nums_[i] >= int(nums_[i]+nums2)):
        nums2 = 0
        nums2 += int(nums_[i])
    else:
        nums2 += int(nums_[i])

index2 = count.index(max(count)) #找出最大的数的位置

num = list(range(index2+1))
num.reverse()
for i in num:
    if count[i] == 1:
        index1 = i
        break

if index1 != 0:
    for j in range(index1):
        point += int(nums[j])
if index2 != n:
    for p in range(n-index2-1):
        point += int(nums[p+index2+1])
for q in range(index1,index2+1):
    point += int(1-nums[q])

print(point)


n=int(input())
binary=list(map(int,input().split()))
single1=binary.count(1)
if single1==len(binary):
    print(single1-1)
"""else:
    s=0
    sum1=-200
    finalsum=0
    #replace is not done for list containing integers.Only for strings.
    for i in binary:
        if i==1:
            s=0

        else:
            s+=1
            sum1=max(s,sum1)
            finalsum=max(finalsum,sum1)
    print(single1+finalsum)"""
else:
    s=[]
    for i in binary:
        if i==1:
            s.append(-1)
        else:
            s.append(1)
    sum1=0
    sum2=-2000
    for i in s:
        sum1+=i
        if sum1<0:
            sum1=0
        sum2=max(sum2,sum1)
    print(sum2+single1)


n = int(raw_input())
ar = map(int,raw_input().split())
temp = ar.count(1)
if temp==n:
    print n-1
else:
    cnt1,cnt0,z=0,0,0

    for i in range(n):
        if ar[i]==1:
            cnt1 += 1
            z = max(z-1,0)
        else:
            z += 1
        cnt0 = max(cnt0,z)
    print cnt0+cnt1n = int(raw_input())
ar = map(int,raw_input().split())

cnt1,cnt0,z=0,0,0

for i in range(n):
    if ar[i]==1:
        cnt1 += 1
        z = max(z-1,0)
    else:
        z += 1
    cnt0 = max(cnt0,z)
print cnt0+cnt1


n=int(input())
a=[int(i) for i in input().split()]
b=[0]*n
for i in range(0,n):
    b[i]=a[i]
m=0
p=0
for i in range(0,n):
    p=p+b[i]
    for j in range(i+1,n):
        z=0
        for k in range(i,j+1):
            a[k]=1-b[k]
            z=z+a[k]
        for x in range(0,i):
            z=z+b[x]
        for x in range(j+1,n):
            z=z+b[x]
        if z>=m:
            m=z
if p==0:
    print(n)
elif p==n
    print(n-1)
else:
    print(m)


n,d = map(int,raw_input().split(' '))
num = map(int,raw_input().split(' '))
m = input()
num.sort()
if m < n:
    print sum(num[0,m])
else:
    print sum(num) - d*(m - n)


[n,b] = [int(i) for i in raw_input().split(" ")]
a = [int(i) for i in raw_input().split(" ")]
m = int(raw_input())
a.sort() # small -> big

receivable = reduce(lambda x, y: x + y, a[0:min(n,m)])
payable = max(m-n, 0) * d

print receivable - payable


a = input().split()
n, d = int(a[0]), int(a[1])
a = [int(x) for x in input().split()]
m = int(input())
a.sort()
sum = 0
for i in [x in range(m) if x < n]:
    sum += a[i]
sum -= (m-i-1)*d
print(sum)


def profit(n,d,a,m):
    s = sum(a)
    if m <= n:
        return s
    else:
        return (s-(m-n)*d)

n,d = map(int,raw_input().split())
a = map(int,raw_input().split())
m = int(raw_input())
print profit(n,d,a,m)


if __name__ == "__main__":
    n, d = map(int,raw_input().split())
    costs = map(int, raw_input().split())
    m = int(input())
    ans = 0
    if m < n:
        ans = sum(costs[:m])
    else:
        ans = sum(costs)
        ans -= (m-n)*d
    print ans


def su(n):
	c=[0]*(n+1)
	while(n!=0):
		a=n%10
		n=n//10
		c.append(a)
	return sum(c)
n=int(input())
if su(n)%4==0:
	print(n)
else:
	for i in range(1,4):
		if su(n+i)%4==0
			print(n+i)
			break


a = input()
b = 0
for i in range(len(a)):
    b += int(a[i])
c = b % 4
print(


n=int(input())
l1=list(map(int,str(n)))
s=sum(l1)
if s%4==0:
	print(s)
else:
	for i in range(1,8):
		x=n+ia=list(map(int,str(x)))
		s=sum(a)
		if s%4==0:
			print(x)
			break


n=input()
sum=0
while(True)
	for item in n:
		sum=sum+int(item)
		if sum%4==0:
			print(n)
			break
		else:
			n=int(n)+1


inpu_t = int(input())

for i in range(inpu_t, inpu_t + 10 ):
    if int(i[-1,-3]) % 4 == 0:
        return i
        break


for i in range(4):
	st = input()
	lista[i] = st.split(" ")

print(lista)
def ff(n):
	if n ==0 :
		return 3
	if n%2==0:
		return n+1
	else:
		return n-1

def rec(lista):
	for i in range(len(lista)):
		for j in range(len(lista[i])):
			if lista[i][3] == lista[i][j] == 1:
			   print("YES")
                break
			if lista[i][j] == lista[ff(j)][3] == '1' :
				print("YES")
				break

rec(lista)


conf = [[int(num) for num in input().split()] for i in range(4)]

bad = False
for ind in range(4):
    bad |= conf[ind][3] and (conf[(ind + 1) % 4][0] or conf[(ind + 2) % 4][1] or conf[(ind + 3) % 4][2])

print('YES' if bad else 'NO')


#from __future__ import division
import itertools
from fractions import gcd
from math import sqrt
from bisect import bisect_left , bisect_right
import heapq
from collections import deque , defaultdict , Counter
from itertools import combinations as C
def Ls():
	return list(raw_input())
def get(a):
	return map(a , raw_input().split())
def Int():
	return int(raw_input())
def Str():
	return raw_input()

a = get(int)
b = get(int)
c = get(int)
d = get(int)

a1 = [b[0],c[1],d[2]]
b1 = [c[0],d[1],a[2]]
c1 = [d[0],a[1],b[2]]
d1 = [a[0],b[1],c[2]]

if a[-1] == 1:
	if 1 in a1:
		print 'YES'
		exit(0)
if b[-1] == 1:
	if 1 in b1:
		print 'YES'
		exit(0)
if c[-1] == 1:
	if 1 in c1:
		print 'YES'
		exit(0)
if d[-1] == 1:
	if 1 in d1:
		print 'YES'
		exit(0)

print 'NO'


a = [map(int, raw_input().split()) for _ in xrange(4)]
a.extend(a)
for i in xrange(4):
    if (a[i][0] and a[i-1][3]) or (a[i][1] and a[i+2][3]) or (a[i][2] and a[i+1][3]):
        print "YES"
        quit()
print "NO"


from sys import stdin as fin
# fin = open("cfr417a.in", "r")

# n = int(fin.readline())
for i in range(4):
    arr = list(map(int, fin.readline().split()))
    if (arr[0] or arr[1] or arr[2]) and arr[3]:
        print("YES")
        break
else:
    print("NO")


n=raw_input("")
cnt=[0,0,0,0,0,0,0,0,0,0]

for i in range(int(4)):
    x=raw_input("")
    for c in x:
        cnt[int(c)]+=1

flag=False

for i in range(1,10):
    if cnt[i]>n*2:
        flag=False
        break
    else:
        flag=True

if flag:
    print 'NO'
else:
    print 'YES'


n = raw_input()
a = []
for i in range(4): a += raw_input()
print("YES","NO")[max(a.count(i) for i in '0123456789')>2*k]


n = int(input())
'''
l = []

for _ in range(4):
	l.extend(list(input()))

dots = l.count('.')
for _ in range(dots):
	l.remove('.')

for i in set(l):
	if l.count(i) > 2 * n:
		print('NO')
		exit()

print('YES')
'''

from collections import defaultdict

d = defaultdict(int)

for _ in range(4):
	l = list(input())
	for i in l:
		if i != '.':
			d[i] += 1

if max(d.values()) > 2 * n:
	print('NO')
else:
	print('YES')


k = input()
    k = 2 * int(k)
    count_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for i in range(4):
        line = input()
        a = [int(number) for number in line if number != '.']
        for j in range(len(a)):
            count_list[a[j]] += 1
    for count in count_list:
        if count > k:
            print("NO")
    print("YES")


if __name__ == "__main__":

    x1, y1 = [int(x) for x in input().split()]
    x2, y2 = [int(x) for x in input().split()]
    x3, y3 = [int(x) for x in input().split()]

    xset = set([x1,x2,x3])
    yset = set([y1,y2,y3])

    if len(xset) == 1 or len(yset) == 1:
        print(1)
    elif len(xset) == 2 or len(yset) == 2:
        print(2)
    else:
        print(3)


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

import time

xy = []

for i in range(3):
    (x, y)   = (int(i) for i in input().split())
    xy.append([x, y])

start = time.time()

if (x[0] == x[1] and x[1] == x[2]) or (y[0] == y[1] and y[1] == y[2]):
    print(1)
elif x[0] == x[1] or x[1] == x[2] or y[0] = y[1] or y[1] == y[2] :
    print(2)
else:
    print(3)

finish = time.time()
#print(finish - start)


x1,y1=[int(i) for i in raw_input().split()]
x2,y2=[int(i) for i in raw_input().split()]
x3,y3=[int(i) for i in raw_input().split()]
if((x1==x2 and x2==x3) or (y1==y2 and y2==y3)):
    print 1
else if (x1==x2 or x1==x3 or x2==x3 or y1==y2 or y2==y3 or y1==y3):
    print 2
else:
    print 3


import math
onsegment = lambda x, y, z: min(y,z) <= x <= max(y,z)
oninterval = lambda x, y, z: min(y,z) < x < max(y,z)
def inrectangle(p0, p1, p2):
    return oninterval(p0[0], p1[0], p2[0]) and oninterval(p0[1], p1[1], p2[1])
def onborder(p0, p1, p2):
    return onsegment(p0[0], p1[0], p2[0]) and onsegment(p0[1], p1[1], p2[1]) and not inrectangle(p0, p1, p2)
points = []
for i in range(3):
    points.append(tuple(int(x) for x in input().split()))
points.sort()
if (all((point[0] == points[0][0] for point in points)) or
    all((point[1] == points[0][1] for point in points))):
    print(1)
elif points[0][1] == points[2][1]:
    print(3 if points[0][0] < points[1][0] < points[2][0] else 2)
elif onborder(points[1], points[0], points[2]) or onborder((points[2], points[0], points[1]) or (points[0], points[1], points[2]:
    print(2)
else:
    print(3)


import math

def cool(n):
    if n==1 || n==3:
        return "NO"
    if n==2:
        return "YES"
    for k1 in range(int(math.sqrt(n))):
        k2 = int(math.sqrt((n - (k1*(k1+1))/2)*2))
        if (k1*(k1+1))/2 + (k2*(k2+1))/2 == n:
            return"YES"
            break
        else:
            continue
    return "NO"

num = int(input())
print(cool(num))


from math import *

n = int(raw_input()) * 2

k = int(round(sqrt(n)))

found = False

i = 1
while i < k
    r = n - i * i - i
    i += 1
    x = int(floor(sqrt(r)))
    if x * (x + 1) == r:
        found = True
        break

print "YES" if found else "NO"


import math
n = int(input())
i =int( math.sqrt(n))
j=i
while True:
    if i*(i+1)/2+j*(j+1)/2==n:
        print('YES')
        break
    elif i*(i+<n:1)/2+j*(j+1)/2<n:
        j+=1
    else:
        i-=1


n = input()
triangles = {(i * (i+1))/2 : 1 for i in range(1,44750)}
for x in triangles:
    if n - x in triangles:
        print "YES"
        return
print "NO"


t = set(x*(x+1)/2 for x in range(1,45000)
n=input()
for i in t:
    if n-i in t:
        print 'Yes'
        exit(0)

print 'No'


import math
n = int(input())

print(1+3*n*(n+1)


n=int(input())
sum=0
for i in range(n+1):
    sum+=(i*6)
print(sum+1)a


n = int(raw_input())
result = 1 + 6*((n*(n+1))/2)
print '%s' result


x = str(input())

while x[:-1] == '0':
	x = x[:-1]

found = False
for i in range(len(x)/2):
	if x[i] != x[:-(i+1)]:
		print('NO')
		found = True
		break

if !found:
	print('YES')


x=input()
x.strip("0")
for i in range(len(x)):
     if (x[i]!=x[-i-1]):
          return "NO"
     return"YES"


p = input()
if p == p[::-1] or len(p) == 1:
    print("YES")
else:
    if p[0] != p[len(p) - 1] and '0' not in [p[0], p[len(p) - 1]]:
        print("NO")
    else:
        cl, cr = '', ''
        for i in p:
            if i == '0':
                cl+='0'
            else:
                break
        for i in p[::-1]:
            if i == '0':
                cr+='0'
            else:
                break
        if cl == cr and p != p[::-1]:
            print("NO)
        else:
            if len(cl) > len(cr):
                p += ('0' * (len(cl) - len(cr)))
                if p == p[::-1]:
                    print("YES")
                else:
                    print("NO")
            else:
                p = ('0' * (len(cr) - len(cl))) + p
                if p == p[::-1]:
                    print("YES")
                else:
                    print("NO")


# -*- coding: utf-8 -*-
"""
Created on Thu Sep 21 20:36:12 2017

@author: MetaMemeLord-
"""

n = input()
i = len(n)-1
while i>0:
    if n[i] == '0':
        del n[i]
for i in range(len(n)//2):
    if(n[i]!=n[n-i-1])
        print('NO')
    else:
        print('YES')


def p(x):

     x=x.strip("0")
     for i in range(len(x)):
          if (x[i]!=x[-i-1]):
               print("NO")
               return

     print("YES")

x=input()
p(x)
 if (plin(strip(x)))cout<<"YES";else cout<<"NO";
    return 0;


#input
n,m=map(int,input().split())
xlist=[int(x) for x in input().split()]

#variables
plist=xlist[:]

#main
xlist.sort()

for i in range(n):
	if xlist[plist[i]]%2==0:
		xlist[i]='0'
	else:
		xlist[i]='1'

print(''.join([xlist[i]+' ' for i in range(n)]))


raw_input()
P=map(int,raw_input().split())
for a,b in sorted([[P.index(p),i%2]for i,p in enumerate(sorted(P))]):print b


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


import operator as a
input()
l=sorted([[p,i,0] for i,p in enumerate(map(int,input().split()))])
for i in range(len(l)):l[i][2]=i%2
for (a,b,c) in sorted(l,key=a.itemgetter(1))
print(c,end='')


import itertools

n,m=map(int,input().split())
xlist=[int(x) for x in input().split()]
segmentlist=[]
segmentcolorlist=[0]*m
for i in range(m):
    segmentlist.append(tuple(int(x) for x in input().split()))
combpoints=set()
new=False

for i in range(n+1):
    red=i
    blue=n-i
    combpoints=combpoints | set(itertools.permutations('0'*red+'1'*blue,n))

for combination in combpoints:
    new=False
    for i in range(m):
        for j in range(n):
            if segmentlist[i][0]<=xlist[j] and xlist[j]<=segmentlist[i][1]:
                if combination[j]=='0':
                    segmentcolorlist[i]-=1
                else:
                    segmentcolorlist[i]+=1
    for color in segmentcolorlist:
        if color+1 not in range(3):
            segmentcolorlist=[0]*m
            new=True
            break
    if new==False:
        print(''.join([str(combination[i])+' ' for i in range(n)]))
        break


if(int(input())%2==0):
    print("white
1 2")
else:
    print("black")


n = int(input())
print(str("black" if n%2==1 else "white\n1 2"))a


print(int(input()) % 2 ? 'black' : 'white\n1 2')


import java.util.Scanner;

public class D493 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        if (a % 2 == 1)
            System.out.println("black");
        else {
            System.out.println("white");
            System.out.println("1 2");
        }

    }

}


#for input: list(int(i) for i in raw_input().split())
def main():
	n = map(int,raw_input().split())
	if n%2==0:
		print "white"
		print "1 2"
	else:
		print "black"

if __name__ == '__main__':
    main()


x=0
z=[]
y=int(input())
count=0
for i in range (y):
	z.append(input())
for i in z:
    if i== "++X" or i =="X++":
        count+=1
    else:
        count-=1
 print(count)


a, b, c = sorted(map(int, input().split()))
#print(a,b,c)
i = 0
while a + b < = c
    a = a+1
    i = i+1

print(i)


a=list(map(int, input().split()))
a.sort()
print(max(0,a[2]a[2]+1-a[0]-a[1]))


l=list(map(int,input.split())
l.sort()
print max(0,l[2]-(l[0]+l[1]-1))


x,y,z=map(int,raw_input().split())
x1,y1,z1=map(int,raw_input().split())
a=map(int,raw_input().split())
res=0
if z>z1:
    res+=a[3]
if y>y1:
    res+=a[1]
if x>x1:
    res+=a[5]
if z<0:
    res+=a[2]
if y<0:
    res+=a[0]
if x<0:
    res+=a[4]


from math import sqrt,gcd
def primeFactors(n):

    # Print the number of two's that divide n
    sa = []
    while n % 2 == 0:
        sa.append(2)
        n = n / 2

    # n must be odd at this point
    # so a skip of 2 ( i = i + 2) can be used
    for i in range(3,int(sqrt(n))+1,2):

        # while i divides n , print i ad divide n
        while n % i== 0:
            sa.append(int(i))
            n = n / i

            # Condition if n is a prime
    # number greater than 2
    if n > 2:
        sa.append(int(n))
    return list(set(sa))

from math import sqrt
from collections import defaultdict
from bisect import bisect_right
def ncr(n, r, p):
    num = den = 1
    for i in range(r):
        num = (num * (n - i)) % p
        den = (den * (i + 1)) % p
    return (num * pow(den,
                      p - 2, p)) % p

def cal(n):
    seti = set()
    for i in range(2,int(sqrt(n))+1):
        if n%i == 0:
            seti.add(n//i)
            seti.add(i)

    return seti

def pre(s):

    n = len(s)

    lps = [0]*(n)

    for i in range(1,n):
        j = lps[i-1]

        while j>0 and s[i]!=s[j]:
            j = lps[j-1]

        if s[i] == s[j]:
            j+=1
        lps[i] = j
    for i in range(1,n):
        if lps[i] == i+1:
            lps[i]-=1

    return lps

from collections import defaultdict
def solve():

    x,y,z = map(int,input().split())

    x1,y1,z1 = map(int,input().split())
    m = sqrt(x1**2 + y1**2 + z1**2)
    m1 = sqrt((x1-x)**2 + (y1-y)**2 + (z1-z)**2)
    a1,a2,a3,a4,a5,a6 = map(int,input().split())

    ans = 0
    if y<0:
        z5 = abs(y/m)
        if 0.5<=z5<=1:
            ans+=a1

    if y>y1:
        z5 = abs((y-y1)/m1)
        # print(z)
        if 0.5<=z5<=1:
            ans+=a2

    if z<0:
        z5 = abs(z/m)
        if 0.5<=z5<=1:
            ans+=a3

    if z>z1:
        z5 = abs((z-z1)/m1)

        if 0.5<=z5<=1:
            ans+=a4

    if x<0:
        z5 = abs(x/m)
        if 0.5<=z5<=1:
            ans+=a5

    if x>x1:
        z5 = abs((x-x1)/m)
        if 0.5<=z5<=1:
            ans+=a6

    print(ans)

# t = int(stdin.readline())
# for _ in range(t):
solve()


# t = int(stdin.readline())
# for _ in range(t):
solve()


x,y,z=map(int,raw_input().split())
x1,y1,z1=map(int,raw_input().split())
a=map(int,raw_input().split())
res=0
if z>z1:
    res+=a[3]
if y>y1:
    res+=a[1]
if x>x1:
    res+=a[5]
if z<0:
    res+=a[2]
if y<0:
    res+=a[0]
if x<0:
    res+=[4]
print res


def stack(days,count):
  x=count//days
  y=count%days
  return days*(x)*(x-1)//2+y*x

def main():
  arr=input().split()
  n=int(arr[0])
  pages=int(arr[1])
  arr=input().split()
  for x in range(n):
    arr[x]=int(arr[x])
  arr.sort(reverse=True)

  position=0
  total=0
  while total<pages:
    if position==n:
      return -1
    total+=arr[position]
    position+=1
  #print(position,total)

  days=position
  count=position

  #print(arr)
  #print(days,count)
  while True:

    total+=stack(days,count)
    total-=stack(days-1,count)

    if position==n:
        return days
    if arr[position]<=count//(days-1):
      return days
    #print(total,days-1)
    while total<pages:
      if position==n:
        return days
      if arr[position]<=count//(days-1):
        return days
      total+=arr[position]-count//(days-1)
      #print(total)
      position+=1
      count+=1
    days-=1
    if days==0:
      return 1

print(main())


#After seeing the editorials :'(
n,m=map(int,input().split())
a=list(map(int,input().split()))
a=sorted(a,reverse=True)
for i in range(1,n+1):
    s=0
    for j in range(n):
        s+=max(0,a[j]-(j//i))
    if s>=m:
        print(i)
        flag=1
        break
if flag==0:
    print(-1)


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

for k in range(0,n):
    total = 0
    grps = (k+n-1)//n
    for i in range(n):
        total += max(0, arr[i] - i%grps)
    if total>=m:
        print(k)
print(-1)


def stack(days,count):
  x=count//days
  y=count%days
  return days*(x)*(x-1)//2+y*x

def main():
  arr=input().split()
  n=int(arr[0])
  pages=int(arr[1])
  arr=input().split()
  for x in range(n):
    arr[x]=int(arr[x])
  arr.sort(reverse=True)

  position=0
  total=0
  while total<pages:
    if position==n:
      return -1
    total+=arr[position]
    position+=1
  #print(position,total)

  days=position
  count=position

  #print(arr)
  #print(days,count)
  while True:
    if position==n:
        return days
    if arr[position]<=count//(days-1):
      return days
    total+=stack(days,count)
    total-=stack(days-1,count)
    #print(total,days-1)
    while total<pages:
      if position==n:
        return days
      if arr[position]<=count//(days-1):
        return days
      total+=arr[position]-count//(days-1)
      #print(total)
      position+=1
      count+=1
    days-=1
    if days==0:
      return 1

print(main())


n,m=map(int,input().split())
if(n==1);
    print(1)
elif(m-1<n-m):
    print(m+1)
else:
    print(m-1)


n,m=map(int,input().split())
if(n==1):
    print(1)
else if(m-1<n-m):
    print(m+1)
else:
    print(m-1)


def game(n,m):
    if n=1:
        return 1
    if m-1>=n-m:
        return m-1
    else:
        return m+1

n,m=[int(i) for i in input().split()]
print(game(n,m))


n,m=list(map(int,input().split()))
if n%2!=0:
    if int((n//2)+1)>m
        print(m+1)
    elif int((n//2)+1)<m
        print(m-1)
    else:
        print(int(n//2))
else:
    if int(n//2)>m:
        print(m+1)
    elif int(n//2)<m:
        print(m-1)
    else:
        print(m+1)


n,m=map(int,input().split())
if(n==1);
    print(1)
else if(m-1<n-m):
    print(m+1)
else:
    print(m-1)


n = int(input())
l = list(map(int,input().split()))
s = 0
while(s<n):
    for i in range(7):
        if(s<n):
            s += l[i]
        else:
            break
if(i==6):
    print(7)
print(i)n = int(input())
l = list(map(int,input().split()))
s = 0
while(s<n):
    for i in range(7):
        if(s<n):
            s += l[i]
        else:
            break
if(i==6):
    print(7)
print(i)


import java.util.*;
import java.io.*;
public class Main{
    public static void main(String args[]){
        int n,i,ans=-1;
        Scanner in = new Scanner(System.in);
        n=in.nextInt();
        int[] arr = new int[n];
        for(i=0;i<7;i++) arr[i]=in.nextInt();
        while(n>0){
            for(i=0;i<7;i++){
                n-=arr[i];
                if(n<=0){
                    ans=i+1;
                    break;
                }
            }
        }
        System.out.println(ans);
    }
}


# -*- coding: utf-8 -*-
"""
Created on Mon May 25 14:38:46 2020

@author: Ritvik Agarwal
"""
n, wps = input(), map(int, raw_input().split())
i, summ = 0, 0
while summ < n:
    if i == 7:
        i = 1
    else:
        i += 1
    summ += wps[i-1]
print i


pages = int(raw_input().strip())
weeks = raw_input().strip().split()
weeks[0] = int(weeks[0])
for i in range(1,len(weeks)):
    weeks[i] = weeks[i - 1] + int(weeks[i])
pages %= weeks[6]
if pages == 0:
    print 7
    return
#print pages, weeks[6]
for i in range(len(weeks)):
    if pages <= weeks[i]:
        print str(i+1)
        break


n = int(input())
times = [int(i) for i in input().split()]
day = 6
while n > 0:
    day = (day + 1) % 7
     n -= times[day]
print(day)


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


import time
a,b,m,r=map(int, raw_input().split())
if a==1:
    time.sleep(0.1)
    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):])


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


import time
a,b,m,r=map(int, raw_input().split())
if a==1:
    time.sleep(0.01)
    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):])


a,b,m,r0=0,0,0,0
a,b,m,r0=map(int,input().split())
ri=r0
i=0
R=[]
I=[]
while (ri) not in R:
        R.append(ri)
        I.insert(ri,i)
        ri=(a*ri+b)%m
        i+=1
##print(R)
##print(I)
##print (i-R.index(ri))
print (i-I[ri])


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

if p>=n:
    print(-1)
else:
    nn=n
    j=1
    while True:
        nn-=p
        if bin(nn).count("1")<=j and nn>=j:
            ans=j
            break
        j+=1

    print(j)
   # print(ans)


a, b = map(lambda x: int(x), input().split())
k = 0
s = 1
f = True
while k < s:
    a = a - b
    if a <= 0:
        break
    c = a
    k += 1
    s = 1
    while c != 1:
        s += c % 2
        c = c // 2

q = k - s
q1 = k
for i in range(q):
    a = a - b
    if a <= 0:
        break
    c = a
    k += 1
    s = 1
    while c != 1:
        s += c % 2
        c = c // 2

    if s == k:
        print(s)
        f = False
        break
if f and a > 0:
    print(q1)

if a <= 0:
    print(-1)


inputs=[int(x) for x in input().split()]
n=inputs[0]
y=inputs[1]

pos=False
for i in range(1000000100):
    if (n-i*y<=0) {
        break;
    }
    if (bin(n-i*y).count(1))<=i:
        print(i)
        pos=True
if (pos==False):
    print(-1)


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

    for i in range(1, 32):
    	# print(i, a-p*i, bin(a-p*i).count('1'))

    	if i >= bin(a-p*i).count('1') > 0 and a-p*i >= i:
    		print(i)
    		exit()

    print(-1)


a, b = map(lambda x: int(x), input().split())
k = 0
while 1:
    a = a - b
    if a <= 0:
        break
    c = a
    k += 1
    s = 1
    while c != 1:
        s += c % 2
        c = c // 2
    if k - s == 1:
        s += 1
    if s == k:
        print(s)
        break

if a <= 0:
    print(-1)


n,k = map(int,raw_input().split())
a = map(int,raw_input().split())
q = [0 for i in range(n+1)]
h = [0 for i in range(n+1)]
f = 1
c = 0
for i in range(k-1):
    if a[i+1]<=a[i]:
        if h[n-a[i]+a[i+1]] and q[a[i]]!=n-a[i]+a[i+1]:
            f = 0
            break
        q[a[i]] = n-a[i]+a[i+1]
        h[n-a[i]+a[i+1]] = 1
    else:
        if h[a[i+1]-a[i]] and q[a[i]]!=a[i+1]-a[i]:
            f = 0
            break
        q[a[i]] = a[i+1]-a[i]
        h[a[i+1]-a[i]] = 1
u = []
pt = 0
for i in range(1,n+1):
    if not h[i]:
        u.append(i)
if f:
    for i in range(1,n+1):
        if not q[i]:
            q[i] = u[pt]
            pt +=1
        print q[i],
else:
    print -1


n, m = map(int, raw_input().strip().split())
l = map(int, raw_input().strip().split())

a = [0] * (n)
rev_a = {}
flag = 0

for i in xrange(len(l) - 1):
	key = l[i]
	val = l[i + 1] - l[i]
	val = val if val > 0 else val + n
	if rev_a.get(val) and rev_a.get(val) != key:
		flag = 1
		break
	else:
		a[key - 1] = val
		rev_a[val] = key

if flag:
	print -1
else:
	last_unchecked = 1
	for i in xrange(n):
		if not a[i]:
			while last_unchecked in rev_a:
				last_unchecked += 1
			a[i] = last_unchecked
			last_unchecked += 1
	print " ".join(map(str, a))


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

n, m = R()
l = list(R())

a = [None] * n
b = [False] * n

c = set(range(1, n + 1))
for i in range(m - 1):
    j = l[i] - 1
    d = l[i + 1] - l[i]
    if d <= 0:
        d += n
    if a[j] ! = d:
        if a[j] is not None or b[d - 1]:
            print(-1)
            exit()
        a[j] = d
        b[d - 1] = true
        c.remove(d)
for i in range(n):
    if a[i] is None:
        a[i] = c.pop()

print(*a)


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

n, m = read()
I = read()
a = [0] * (n+1)
for i in range(m-1):
    current = I[i]
    next = I[i+1]
    val = (next - current) % n
    if val in a and a[I[i]] != val:
        print("-1")
        break
    elif a[I[i]] != 0 and a[I[i]] != val:
    a[I[i]] = val if val != 0 else n

else:
    j = []
    for num in range(1, n+1):
        if num not in a:
            j.append(num)
    k = 0
    for i, num in enumerate(a[1:]):
        if num == 0:
            a[i+1] = j[k]
            k += 1
    print(' '.join(map(str,a[1:])))


import sys
input=sys.stdin.readline
m=10**9+7
n=int(input())
a=b=c=s=1
//dp[i][j] ye bata raha h ki (i remaining turns me j(A,B,C,D) pr
//kitne tareeko se pohoch skte h
//wo humesha peeche steps pr hi depend krega
d=t=0//matrix nhi bn skti h sirf purane states ka
     //hi use h to just by using temp variables we
     //maintain dp
for i in range(2,n+1):
    a=b=c=(2*s+t)%m
    d=3*s%m
    s=a;t=d
print(d)


# -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 19:19:34 2020

@author: UV
"""
def main():
    tamaño_del_ciclo = int(input())
    k=0
    for a in range(2, tamaño_del_ciclo+1):
        if a%2 ==0:
            k=3*(k+1)

        else:
            k = 3*(k-1)
    print(k)

if __name__=="__main__":
    main()


n = int(raw_input())
mod = 1000000007
d = []
d.append(0)
d.append(3)
d.append(6)
d.append(21)
d.append(60)
for i in range(3,n):
    d.append((7*(d[i-2]%mod))%mod + (6*(d[i-3]%mod))%mod)%mod)
print d[n-1]


from collections import defaultdict
import sys
from itertools import *
import numpy as np
sys.setrecursionlimit(999999999)
a = int(raw_input())
print (a+1)/2


h = map(int,raw_input().split())
u = map(int,raw_input().split())
ans = 0
for i in range(input()):
	a = map(int,raw_input().split())
	if (a[0]*h[0] + a[1]*h[1] + a[2]) * (a[0]*u[0] + a[1]*u[1] + a[2]) < 0: ans += 1
print ans


import math
N=int(input())
if N==1:
    print(floor(math.sqrt(N)))


import math
N=int(input())
if N==1:
    print(floor(sqrt(N))


import math
N=int(input())
if N==1:
    print(floor(math.sqrt(N))


beds,pillows,frodo=map(int,input().split())
pillows=pillows-beds-1
layer=2
while pillows>0:
    if beds==1:
        layer=pillows+2
        pillows=0
        break
    if frodo-1<layer-1 and beds-frodo<layer-1:
        layer+=(int(pillows/(beds))+1)
        break
    else:
        pillows-=(min(frodo-1,layer-1)+min(layer-1,beds-frodo))
    pillows-=1
    if pillows<0:
        layer-=1
    layer+=1

elif pillows<=0:
    print(layer)
else:
    print(layer-1)


from math import *
n,m,k=map(int,input().split())
r,l=0,0

if k!=n:
    r=n-k
if k!=1:
    l=k-1
if l>r:
    S=((1+l)*(l)//2)+((l+n)*r//2)
else:
    S=((1+r)*(r)//2)+((r+n)*l//2)
S+=k
s=max(l,r)+1
L,R=max(l,r),min(l,r)
if L-1>R:
    B=False
    L-=1
else:
    L-=1
    R-=1
    B=True

while S>m:
    s=s-1
    S-=L+R
    S-=1
    if L==0 and R>0 :
        s=s-1
        S-=2
        R-=1
        break
    if L>0:
        L-=1
    if B:
        R-=1
    elif L==R:
        B=True

if (m-S)//n!=0:
    s+=(m-S)//n
if
print(s)


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

x_min = min(k-1,n-k)
x_max = max(k-1,n-k)
s1 = sum(range(x_max+1))
#s2 = 0
#for i in range(x_min):
#    s2 += x_max-i
s2 = sum(range(x_max-x_min+1,x_max+1))
pods = x_max+1 + s1 + s2
if(pods<=m):
    x = x_max+1 + ((m-pods)-(m-pods)%n)/n
    print x
else:
    x = 1
    pods = n
    add = 0
    add_r = 0
    add_l = 0
    f=0
    j=0
    while 1:
        add_r = j
        if(j<=x_min):
            add_l = j
        add += 1 + add_r + add_l
        if(pods+add<=m):
            x += 1
        else:
            print x
            f = 1
            break
        j += 1
    if(f==0):
        print x


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

x_min = min(k-1,n-k)
x_max = max(k-1,n-k)
s1 = sum(range(x_max+1))
s2 = 0
for i in range(x_min):
    s2 += x_max-i
pods = x_max+1 + s1 + s2
if(pods<=m):
    x = x_max+1 + ((m-pods)-(m-pods)%n)/n
    print x
else:
    x = 1
    pods = n
    add = 0
    add_r = 0
    add_l = 0
    lim_l = 0
    f=0
    for j in range(n):
        add_r = j
        if(j<=x_min):
            add_l = j
            if(j+1>x_min):
                lim_l = j
        else:
            add_l = lim_l
        add += 1 + add_r + add_l
        #print add,add_r,add_l,lim_l
        if(pods+add<=m):
            x += 1
        else:
            print x
            f = 1
            break
    if(f==0):
        print x


//Suffix Structures

import java.util.Scanner;

public class Pro08 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s, t;
		int count_s[] = new int[30];
		int count_t[] = new int[30];

		s = sc.next();
		t = sc.next();
		for (int i=0;i<s.length();i++)
			count_s[(int)s.charAt(i) - (int)'a']++;
		for (int i=0;i<t.length();i++)
			count_t[(int)t.charAt(i) - (int)'a']++;

		boolean flag = true;
		for (int i=0;i<26;i++)
			if (count_s[i] < count_t[i])
				flag = false;

		if (!flag)
			System.out.print("need tree");
		else {
			if (s.length() == t.length() && !s.equals(t)){
				System.out.print("array");
				return;
			}
			int i = 0;
			int index = 0;
			while (i < s.length() && index < t.length()) {
				if (s.charAt(i) == t.charAt(index))
					index++;
				i++;
			}

			if (index == t.length())
				System.out.print("automaton");
			else
				System.out.print("both");
		}
	}
}


def checar_letras(s,t):
	i = 0
	for e in s[i::]:
		if e in t[i::]:
			continue
		else:
			return False
		i+=1
	return True

def tirar_letras(s,t):
	i = 0
	while i < len(s) -1:
		if not s[i] in t:
			if i+1 < len(s):
				s = s[:i:] + s[i+1::]
			else:
				s = s[:i:]
		i +=1

def  resposta(s,t):

	if len(t) == len(s) and checar_letras(t,s):   #OK
		return  "array"

	if checar_letras(t,s) == False:           #OK
		return  "need tree"

	if t in s or checar_letras(t,s):
		return "automaton"
	if:
		return "both"

s = raw_input()
t = raw_input()

print resposta(s,t)


#!/usr/bin/python3.4

SIZE = 26
# matrix = [[0] * SIZE for i in range(SIZE)]
# arr = [0] * SIZE

s1, s2 = input(), input()

def automat():
    j = 0
    for val in s2:
        while j < len(s1) and val != s1[j]:
            j += 1
        if j == len(s1):
            return False
    return True

def suffix_array():
    arr1 = [0] * SIZE
    arr2 = [0] * SIZE
    for i in s1:
        arr1[ord(i) - ord('a')] += 1
    for i in s2:
        arr2[ord(i) - ord('a')] += 1
    for i in range(26):
        if arr1[i] != arr2[i]
            return False
    return True

def both():
    arr1 = [0] * SIZE
    arr2 = [0] * SIZE
    for i in s1:
        arr1[ord(i) - ord('a')] += 1
    for i in s2:
        arr2[ord(i) - ord('a')] += 1
    for i in range(26):
        if arr1[i] < arr2[i]:
            return False
    return True

if automat():
    print("automaton")
elif suffix_array():
    print("array")
elif both():
    print("both")
else:
    print("need tree")


s=raw_input()
r=raw_input()

s_i=''.join(sorted(s))
r_i=''.join(sorted(r))

def subset(a,b):
    i = 0
    for c in a:
        if i < len(b) and c == b[i] : i+ = 1
    return i == len(b)
if s_i==r_i: print "array"
elif subset(s,r): print "automaton"
elif subset (s_i,r_i): print "both"
else: print "need tree"


s,t=input(),input()
ss,tx=str(sorted(s)),str(sorted(t))
def subset(s,t):
    i=0
    for c in s:
        if c==t[i]:i+=1
        elif i==len(t):break
    return i==len(t)
if ss==tx:
    print("array")
elif subset(s,t):
    print("automaton")
elif subset(ss,tt):
    print("both")
else:
    print("need tree)


read = lambda: map(int, input().split())
a, b, c = read()
gcd = lambda a, b: a if b == 0 else gcd(b, a % b)
k = gcd(a, b)
a //= k
b //= k
x = str(a/b)
ans = -1
for i in range(2, min(12, len(x))):
    if int(x[i]) == c:
        ans = i - 1
        break
if ans == -1 and c == 0 and len(x) < 12:
    ans = len(x) - 1
print(ans)


num, denom, target = [int(x) for x in input().split()]
a = num/denom
if len(str(a)) < 100:
    a = '{:10.111f}'.format(a)
    a = a[a.find('.') :110]
else a = str(a)
print(a.find(str(target)))


l= map(int, raw_input().split())
a=l[0]
b=l[1]
c=l[2]

f=0

for i in range(b) :
	a *= 10
	if c == a // b :
	    f=1
		print i + 1
		break
	a =a% b

if f==0:
    print -1


l= map(int, raw_input().split())
a=l[0]
b=l[1]
c=l[2]

f=0

for i in range(b) :
    a *= 10
    if c == a // b :
        f=1
	    print i + 1
	    break
    a =a% b

if f==0:
    print -1


#include <bits/stdc++.h>
#define F first
#define S second
#define mid ((l + r) / 2)
#define lson (id * 2)
#define rson (id * 2 + 1)
using namespace std;
typedef long long ll;
const int maxn = 3e5 + 4;

int a, b, c;
int main(){
	cin>>a>>b>>c;
	a *= 10;
	int cnt = 1;
	while(cnt<=b){
		while(a < b and cnt <= b){
			a *= 10;
			if(c==0){
				cout<<cnt<<'\n';
				exit(0);
			}
			cnt++;
		}
		int rem = a / b;
		if(rem == c){
			cout<<cnt<<'\n';
			exit(0);
		}
		a = a % b;
		a *= 10;
		cnt++;
	}
	if(c == 0 and cnt!=b+1) cout<<cnt<<'\n';
	else cout<<-1<<'\n';
}


n, k=map(int,input().split())
l=[]
m=[]
for i in range(1,n+1):
          if(i%2!=0):
                    l.append(i)
for j in range(2,n+1):
          if(i%2==0):
                    m.append(j)
x=list(l+m)
print(x[k]):


n,k=map(int,input().split())
if k>int((n+1)/2):
    print(2*(k-int(n+1)/2)
else:
    print(2*k-1)


a,b=input().split()
a=int(a)
b=int(b)
x=b+b-1
y=(a-1)//2+1
if x<a:
    print(x)
else:
    for i in range(2,n+1,2)
        y=y+1
        if y==b:
            print(y)


def solve(n,k):

    if(n%2==0):

        half = n/2

    else:

        half = n/2 + 1

    if(k<=half):

        return (2*k)-1

    else:

        return 2*(k-half)

if __name__ == "__main__":

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

    print solve(n,k)

© 2020 GitHub, Inc.
Terms
Privacy
Security


n,m=map(int,input().strip().split())
l=[int(i) for i in range(1,n+1) if i%2!=0]
e=[int(i) for i in range(1,n+1) if i%2==0]
if(n%2==0):
    if(m>n//2):
        print(e[m-(n//2)-1])
    else:
        print(l[m-1])
else:
    if(m>(n//2)+1):
        print(e[m-2-(n//2))
    else:
        print(l[m-1])


n=int(input())
inp = list(map(int,input().split()))
sol=[]
for i in range(n):
    for j in range(i+1,n):
        sol.append(abs(360-2*sum(inp[i:j])))
print (min(sol))


n = input()
a = map(int, raw_input().split())
print min(abs(360-2*sum(a[j:i]))for i in range(n)for j in range(i))


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

x1 = 0
for i in a:
    x1 += i
    if(x1 >= 180): break

x2 = 360 - x1
diff = x1 - x2

for i in a:
    x1 -= i
    x2 += i
    diff = min(diff,abs(x1-x2))

print(diff)


n = int(input())
a = list(map(int, input().split()))
a.sort()
f = 0
s = 0
for i in range(n - 1, -1, -1):
    if abs(f + a[i] - s) < abs(f - a[i] - s):
        f += a[i]
    else:
        s += a[i]
print(abs(f - s))


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

for i in range(n - 1):
    for j in range(i+1, n):
        diffs.append(abs(sum(a[i:j]) - sum(a[j:])  - sum(a[:i])))

try:
    print(min(diffs))
except: print(*a)


    inp = input().split(' ')
    inp = list(map(int,inp))
    x1 = int(inp[0])
    y1 = int(inp[1])
    x2 = int(inp[2])
    y2 = int(inp[3])
    tinp = input().split(' ')
    tinp = list(map(int,tinp))
    tx = int(tinp[0])
    ty = int(tinp[1])
    if (((((x2-x1)//tx)%2==0)and(((y2-y1)//ty)%2==0))or((((x2-x1)//tx)%2!=0)and(((y2-y1)//ty)%2!=0))):
        print('YES')
    else:
        print('NO')


int a, b, c, d = tuple(map(int, input().split()))
int x, y = tuple(map(int, input().split()))

print(['NO', 'YES'][int(a%x == c%x and b%y == d%y)])


def main():
    a, b, c, d = map(int, input().split())
    c, d = c-a, d-b
    x, y = map(int,input.().split())

    if c%x != 0 or d%y != 0:
        print("NO")
    elif c/x % 2 == d/y %2:
        print("YES")
    else:
        print("NO")

if __name__ == "__main__":
    main()


N, mod = map(int, input().split())
NNN = (10**5)
g1 = [1, 1]
g2 = [1, 1]
inverse = [0, 1]
def mul(a, b):
    return ((a % mod) * (b % mod)) % mod

for i in range( 2, NNN + 1 ):
    g1.append( ( g1[-1] * i ) % mod )

r = 0
for i in range(1, N+1):
    r += mul(mul(mul((N-i+1),(N-i+1)),g1[N-i]),g1[i])
    r %= mod
print(r)


n,m=map(int,input().split())
x = [1]
ans = 0
for i in range(1, n + 1):
    x.append(i * x[-1] %m)
for i in range(1,n+1):
    ans = ((n-i+1)*l[i]*l[n-i+1]%m + ans)%m
print(ans)


n,m = map(int,input().split())
l = [0]*(n+1)
c=1
for i in range(1,n+1):
    l[i] = i*c
    c = l[i]
ans =0
for i in range(n):
    ans += (n-i)*l[n-i]*l[i+1]
print(ans%m)


a=[1]
n,m=map(int,input().split())
for i in range(1,n+1):
	a.append(a[-1]*i)
ans=0
for i in range(1,n+1):
	p=a[i]*a[n-i+1]*(n-i+1)
	ans+=p
	ans%=m
print(ans)


n, m = map(int, input().split())
count = 0
factorial = [1]
for i in range(n-1):
    factorial.append((i+2)*factorial[i])

for i in range(n):
    x = i+1
    count += (n-i)*factorial[i]*factorial[n-i-1]

print(count%m)


A,B=map(int,input().split(" "))
x,y,z=map(int,input().split())
cy=2*x+y
cb=3*z+y
ans=max(0,cy-A)
ans+=max(0,cb-B)
print(ans


a,b=map(int,input().split())
x,y,z=map(int,input().split())
yellow=(x*2)+y
blue=y+(z*3)
s=0
if a>=yellow:
	s=0
elif:
	s+=yellow-a
elif:
	b>=blue:
	s+=0
else:
	s+=blue-b
print(s)


 y,b=list(map(int,input().split()))
ny,ng,nb=list(map(int,input().split()))
print(max(ng+ny*2-y,0)+max(ng+3*nb-b,0))


a,b=[int(i) for i in input().split()]
x,y,z=[int(i) for i in input().split()]
p=2*x+y
q=3*z+y
if p>a and q>b :
    print(p-a+q-b)
elif p>a :
    print(p-a)
elif :
    print(q-b)
else :
    print('0')


from __future__ import print_function, division
import os
import sys
from functools import reduce
from io import BytesIO, IOBase

range = xrange
input = raw_input

sys.stdout, stream = IOBase(), BytesIO()
sys.stdout.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0)
sys.stdout.write = lambda s: stream.write(s.encode())

input = BytesIO(os.read(0, os.fstat(0).st_size)).readline

MAGIC = float(2**52+2**51)

def modder(x,y):
    return x - y*((x/y + MAGIC) - MAGIC)

def gcd(x, y):
    """ greatest common divisor of x and y """
    while y:
        x, y = y, modder(x,y)
    return abs(x)

def main():
    n, k = [float(x) for x in input().split()]
    nk = n*k
    a, b = [float(x) for x in input().split()]

    mini = gcd(nk, (a+b)%k)
    maxi = gcd(nk, (a+b)%k)

    for li in [(a + b) % k, (max(a,b) - min(a,b)) % k]:
        while li < nk:
            res = gcd(nk, li)
            mini = min(mini, res)
            maxi = max(maxi, res)
            li += k

    print(*[int(nk)//int(maxi), int(nk)//int(mini)])

if __name__ == '__main__':
    main()


import sys
import math
'''def solve(num,dis,a,b,k):
    start=a
    nex=(a+num)%k
    if nex%k==b:
        return dis//num
    if (k-nex%k)==b:
        return dis//num
    start=dis-a
    nex=(start+num)%dis
    if nex%k==b:
        return dis//num
    if (k-nex%k)==b:
        return dis//num
    return -1'''
n,k=map(int,sys.stdin.readline().split())
a,b=map(int,sys.stdin.readline().split())
factors=[]
dis=n*k
'''for i in range(1,int(math.sqrt(dis))+1):
    if dis%i==0:
        factors.append(i)
        factors.append(dis//i)
#print(factors,'factors')
m=len(factors)
nax,nin=-1,1e12+1
for i in range(m):
    x=solve(factors[i],dis,a,b,k)
    if x!=-1:
        nax=max(nax,x)
        nin=min(nin,x)'''
start=a
nax,nin=-1,1e12+1
for i in range(n):
    b1=k*i+b
    if b1>a:
        l=b1-a
    else:
        l=dis-(a-b1)
    lcm=(dis*l)//(math.gcd(dis,l))
    nax=max(nax,lcm//l)
    nin=min(nin,lcm//l)
st=k-a
for i in range(n):
    b1=k*i+b
    if b1>st:
        l=b1-st
    else:
        l=dis-(st-b1)
    lcm=(dis*l)//(math.gcd(dis,l))
    nax=max(nax,lcm//l)
    nin=min(nin,lcm//l)
print(nin,nax)


n,k = I()
a,b = I()

if 0:
	print(1,n*k)
else:
	i=abs(a-b);j=a+b;mi,ma=10**9,0
	while i<=n*k:
		st = (n*k)//gcd(i,n*k)
		ma=max(ma,st);mi = min(mi,st)
		i+=k
		st = (n*k)//gcd(j,n*k)
		ma=max(ma,st);mi = min(mi,st)
		j+=k
	print(mi,ma)


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

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

x, y = 10 ** 9, 0
for s in [k + 1 - a, k + 1 + a]:
    for i in range(n):
        t = k * i + 1

        el1 = (t - b + MOD) % MOD
        if el1 == 0:
            el1 = MOD
        if el1 - s >= 0:
            l1 = el1 - s
            m = MOD // gcd(l1, MOD)
            x, y = min(x, m), max(y, m)
            # print(s, el1, l1, x, y)

        el2 = (t + b + MOD) % MOD
        if el2 == 0:
            el2 = MOD
        if el2 - s >= 0:
            l2 = el2 - s
            m = MOD // gcd(l2, MOD)
            x, y = min(x, m), max(y, m)
            # print(s, el2, l2, x, y)

print(x if x != 10 ** 9 else 0, y)

~


#!/usr/bin/env python3
import os
import sys
from functools import reduce
from io import BytesIO, IOBase

sys.stdout, stream = IOBase(), BytesIO()
sys.stdout.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0)
sys.stdout.write = lambda s: stream.write(s.encode())

input = BytesIO(os.read(0, os.fstat(0).st_size)).readline

def gcd(x, y):
    """ greatest common divisor of x and y """
    while y:
        x, y = y, x % y
    return x

import _numpypy
zero = _numpypy.multiarray.dtype('int64').type(0)
one = 1 + zero

gcdm = lambda *args: reduce(gcd, args, zero)

lcm = lambda a, b: a * b // gcd(a, b)

lcmm = lambda *args: reduce(lcm, args, one)

def main():
    n, k = map(float, input().split())
    a, b = map(float, input().split())

    min_l = {(a + b) % k, (a - b) % k, (-a + b) % k, (-a - b) % k}
    res = [10**18 + zero, 0]
    for li in min_l:
        while li < n * k:
            x = li if li else n * k
            res = [min(res[0], lcm(x, n * k) // x), max(res[1], lcm(x, n * k) // x)]
            li += k

    print(*[int(x) for x in res])

if __name__ == '__main__':
    main()


n = int(input())
s = set()
x = [1 , 5 , 10 , 50]
l = list()

def dfs(a , b , c):
  if a == n :
    s.add(b)
    return
  while c < len(x) :
    dfs(a + 1 , b + x[c] , c)
    c += 1

if n <= 10 :
  dfs(0 , 0 , 0)
  print(len(s))
  exit()
else :
  print(244  + 49 * (n - 10))


n=int(raw_input())

def ct(n):
    s=[0]
    for i in range(1,n+1):
        sx=[]
        for k in s:
            for m in [1,5,10,50]:
                if k+m not in sx:
                    sx.append(k+m)
        s=sx
    return len(s)

if n<=12:
    print ct(n)
    exit()

print (n-12)*49
exit()


import math

candidate = [1,5,10,50]

n = int(input())

res = candidate + []

if n == 1:
    print(len(res))
else:
    for i in range(n-1):
        now = []
        for j in candidate:
            for k in range(len(res)):
                now.append(res[k] + j)
        res = list(set(now))
    print(len(res))


from sys import stdin, stdout

def count(n):
    d = {}
    cnt = 0
    cur = 0

    for i in range(n + 1):
        for j in range(n - i + 1):
            for z in range(n - j - i + 1):
                v = i * 1 + j * 5 + z * 10 + (n - i - j - z) * 50

                if not v in d:
                    d[v] = 1
                    cur += 1
                else:
                    d[v] += 1

    return cur

n = int(stdin.readline())

for i in range(20, 200):
    n = i

    if count(i) != count(20) + 49 * (i - 20):
        print(i)

if n >= 20:
    upp = count(20) + 49 * (n - 20)
else:
    upp = count(n)
print(upp)


n=int(input()
if n%2==0:
    print('Mahmoud')
else:
    print('Ehab')


if((int(input())%2==0):
    print("Mahmoud")
else:
    print("Ehab")


def fun12(n):
    while True:
        n1=n:
        for i in range(n+1,0,-1):
            if i%2==0:
                n1=n-i;
                break;
        if n1==n:
            return "Ehab"
        if n1==0:
            return "Mahmoud"

        for i in range(n1+1,0,-1):
            if i%2==1:
                n=n1-i;
                break;

n=int(input())
print(fun12(n))


def main():
    n=input()
    if n%2==0:
        print "Mahmoud"
    else
        print "Ehab"
main()


n = int(input())
s = n%2==0?"Mahmoud":"Ehab"
print(s)


a = list(input())
c=0
mid = len(a)//2

for i in range(mid):
   if a[i]==a[-(i+1)]:
       pass
   else:
       c+=1

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


def solvable(s):
    mismatch = False
    for i in range(len(s) // 2):
        if s[i] != s[-1 - i]:
            if mismatch:
                return False
            mismatch = True
    return mismatch or len(s) % 2 = 1

print ('YES' if solvable(input()) else 'NO')


a, k = input(), 0
for i in range(len(a)//2):
    if a[i] != a[len(a)-i-1]:
        k += 1
if k > 1: print('NO')
elif k == 0, len(a)%2 == 0: print('NO')
else: print('YES')


n = input()
q = [0]*len(n)
b = n
p=""
y=0
l=0
for i in range(len(n)-1,-1,-1):
    p+=n[i]
y=len(n)-1
for i in range(len(n)//2):
    if b[i]!=b[y]:
        l+=1
    y-=1
if p==b and len(n)%2!=0:
    print("YES")
elif l==1:
   print("YES")
elif l>1
    print("NO")


n = input()
s = [i for i in n]
l = 0

d = []

for i in range(len(n)//2+1):
	if s[i] == s[-i-1]:

	else:
		l+=1
		pass

if l == 1 or (l==0 and len(s)%2 ==0 :
	print("YES")
else:
	print("NO")


# take risk at the edge of Accepted
Str = input()
print(x if True in [x for par in ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] if par in Str: x = True else: x = False]: x = 'YES' else: x = 'NO')


a = input()
if a = "ACB.AAAAAA":
	print("Yes")
elif len(a)==1 and a[0]=='.':
	print("No")
	exit()
elif a[0]=='.' or a[len(a)-1]=='.':
	print("Yes")
else:
	print("No")

'''
a = int(input())
f1 = 1
f2 = 1
if a < 3:
	print(1)
	exit()
cnt = 2
for i in range(a - 2):
	a = f2
	f2 += f1
	f1 = a
	cnt += f2
print(cnt)
'''


n = input()
flag = 0
for i in range(0,len(n)-2):
	if set[i:i +3] == set("ABC"):
		flag = 1
	    break
if(flag):
	print("YES")
else:
	print("NO")


s = input()
if "ABC" in s or "ACB" in s or "BAC" in s or "BCA" in s or "CAB" in s or "CBA" in s:
       print("YES")
   else:
       print("NO")


a = input()
if a = 'ACB.AAAAAA':
	print('Yes')
elif len(a)==1 and a[0]=='.':
	print("No")
	exit()
elif a[0]=='.' or a[len(a)-1]=='.':
	print("Yes")
else:
	print("No")

'''
a = int(input())
f1 = 1
f2 = 1
if a < 3:
	print(1)
	exit()
cnt = 2
for i in range(a - 2):
	a = f2
	f2 += f1
	f1 = a
	cnt += f2
print(cnt)
'''


#!/usr/bin/env python3
import sys

def main(x, y, z, t1, t2, t3):
    lift_time = (abs(z-x)*t2+t3) + (abs(x-y)*t2+t3)
    walk_time = (abs(x-y)) * t1
    return 'YES' if lift_time <= walk_time else 'NO'

if __name__ == '__main__':
    print(main(*[int(x) for x in sys.argv[1].split()]))


[x, y, z, t1, t2, t3] = [int(n) for n in input().split()]
print('YES' if (abs(x-y)*t1 > 3*t3 + (abs(x-z)+abs(x-y))*t2) 'NO')


x,y,z,tuno,tdos,ttres=map(int,input().split())
var1=abs(x-y)
stair=var1*tuno
var2=abs(x-z)
eleva=((3*ttres)+((var2)*tdos)+((var1)*tdos)
if stair>=eleva:
      print("YES")
else:
      print("NO")


x = input()
y = input()
z = input()
t1 = input()
t2 = input()
t3 = input()

me = x - y

if me < 0:
	me = me * (-1)

run = me * t1

ml = x - z

if ml < 0:
	ml = ml * (-1)

lift = ml * t2 + me * t2 + 2 * t3

if lift <= run:
	print("YES")
else:
	print("NO")


source, dest, elev, tstair, telev, tedoor = map(int, input().split())

totalstair = abs(source - dest) * tstair

totalelev = abs(source - dest) * telev + tedoor # open at dest
if elev != source:
	totalelev += abs(elev - source) * telev + 2*tedoor # open + close at source
# print(totalelev, totalstair)
print("YES" if totalelev <= totalstair else "NO")


def prime(n):
    if n==1:
        return 1
    for i in range(2,int(n**(1/2))+1):
        if n%i==0:
            return False
    return True

n=int(input())
while n:
    a,b=input().split()
    a,b=int(a),int(b)
    if a-b==1 and prime(a+b):
        print('Yes')
    else:
        print('No')
    n--


n=int(input())
while(n):
    l=list(map(int,input().split()))
    k=(l[1]-l[0])*(l[1]+l[0])
    number = k
    j=0
    if number > 1:
        for i in range(2, number):
            if (number % i) == 0:
                print(number, "is not a prime number")
                j=4
                break
        else:
            j=3
            print(number, "is a prime number")
    else:
        j=4
        print(number, "is not a prime number")
    if j==3:
        print("YES")
    else:
        print("NO)


for i in range(int(input()):
    if abs(int(input()) - int(input())) == 1: print("YES")
    else : print('NO')


from math import sqrt
t=int(input())
for _ in range(t):

    a,b=map(int,input().split())
	if a - b != 1 :
		print("NO")
		continue
	for i in range(2, int(sqrt(a + b)) + 1):
		if (a + b) % i == 0:
			print("NO")
			break
	else:
		print("YES")


is_prime = lambda x: all(x%d for d in range(2, int(x**.5)+1))

for _ in range(int(input())):
    a, b = map(int, input().split())
    print('YES' if a==b+1 and is_prime(a+b) else 'NO'


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

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

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

	ans = 0

	cnt = Counter()

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

	print(sum(cost)-ans)

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


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

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

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

	ans = 0

	cnt = Counter()

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

	print(ans)

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


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

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

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

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


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

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

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

	ans = 0

	cnt = Counter()

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

	print(sum(cost)-ans)

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


from collections import Counter

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

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

	ans = 0

	cnt = Counter()

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

	print(sum(cost) - ans)

main()


s=input()
if int(s[-1])%2==0:
    return 0
else:
    return 1


import sys
input = sys.stdin.readline

return int(input()[1:]) % 2


s = input()
if int(s[6]) % 2 == 0:
print(0)
else:
print(1)


A=[int(i) for i in input().split()]
Min=min(A)
A.remove(Min)
print (((Min-1)+A[0])*((Min-1)+A[1])-(Min-1)*Min)
#input()


def plitki(a, b, c):
    if a>1:
        return plitki(a-1, b, c)+b+c-1
    else:
        return b*c

array = input().split(" ")
print(plitki(int(array[0]), int(array[1]), int(array[2])))