Input:
from collections import defaultdict, deque, Counter

def inpl(): return list(map(int, input().split()))

N = int(eval(input()))

A = 0

BA = 0

B = 0

Z = 0

ans = 0

for _ in range(N):

    s = eval(input())

    ans += s.count("AB")

    if s[0] == "B":

        if s[-1] == "A":

            BA += 1

        else:

            B += 1

    elif s[-1] == "A":

        A += 1

if BA:

    ans += (BA - 1)

    if A:

        A -= 1

        ans += 1

    if B:

        B -= 1

        ans += 1

ans += min(A, B)

print(ans)

N = int(eval(input()))

A = 0

B = 0

AB = 0

ans = 0

for _ in range(N):

    S = eval(input())

    ans += S.count("AB")

    if S[0] == "B":

        if S[-1] == "A":

            AB += 1

        else:

            B += 1

    elif S[-1] == "A":

        A += 1

if AB:

    ans += AB-1

    if A:

        ans += 1

        A -= 1

    if B:

        ans += 1

        B -= 1

ans += min(A, B)

print(ans)

from collections import defaultdict, deque, Counter

def inpl():
    return list(map(int, input().split()))

N = int(eval(input()))
A = 0
BA = 0
B = 0
Z = 0
ans = 0
for _ in range(N):
    s = eval(input())
    ans += s.count("AB")
    if s[0] == "B":
        if s[-1] == "A":
            BA += 1
        else:
            B += 1
    elif s[-1] == "A":
        A += 1
if BA:
    ans += BA - 1
    if A:
        A -= 1
        ans += 1
    if B:
        B -= 1
        ans += 1
ans += min(A, B)
print(ans)

N = int(eval(input()))
A = 0
B = 0
AB = 0
ans = 0
for _ in range(N):
    S = eval(input())
    ans += S.count("AB")
    if S[0] == "B":
        if S[-1] == "A":
            AB += 1
        else:
            B += 1
    elif S[-1] == "A":
        A += 1
if AB:
    ans += AB - 1
    if A:
        ans += 1
        A -= 1
    if B:
        ans += 1
        B -= 1
ans += min(A, B)
print(ans)

-from collections import defaultdict, deque, Counter

-    return list(map(int, input().split()))


Input:
n = int(eval(input()))

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

for i in range(n):

    a = int(eval(input()))

    for j in range(a):

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

        x -= 1

        L[i][x] = y

#print(L)

ans = 0

for i in range(2**n):

    temp = 0

    for j in range(n):

        if (i >> j) & 1:

            temp += 1

    flag = True

    for j in range(n):

        if (i >> j) & 1:

            for k in range(n):

                #print((i >> k) & 0)

                if  L[j][k] == 1 and ((i >> k) & 1) == 0:

                    flag =  False

                elif L[j][k] == 0 and ((i >> k) & 1) != 0:

                    flag = False

                else:

                    pass

    if flag:

        ans = max(ans, temp)

print(ans)

n = int(eval(input()))

X = [[] for _ in range(n)]

for i in range(n):

    a = int(eval(input()))

    for j in range(a):

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

        x -= 1

        X[i].append((x, y))

ans = 0

for i in range(2**n):

    t = [-1]*n

    flag = True

    cnt = 0

    for j in range(n):

        if (i >> j) & 1:

            cnt += 1

            t[j] = 1

        else:

            t[j] = 0

    for j in range(n):

        if (i >> j) & 1:

            for x, y in X[j]:

                if t[x] != y:

                    flag = False

    if flag:

        ans = max(ans, cnt)

print(ans)

n = int(eval(input()))
L = [[-1] * n for _ in range(n)]
for i in range(n):
    a = int(eval(input()))
    for j in range(a):
        x, y = list(map(int, input().split()))
        x -= 1
        L[i][x] = y
# print(L)
ans = 0
for i in range(2**n):
    temp = 0
    for j in range(n):
        if (i >> j) & 1:
            temp += 1
    flag = True
    for j in range(n):
        if (i >> j) & 1:
            for k in range(n):
                # print((i >> k) & 0)
                if L[j][k] == 1 and ((i >> k) & 1) == 0:
                    flag = False
                elif L[j][k] == 0 and ((i >> k) & 1) != 0:
                    flag = False
                else:
                    pass
    if flag:
        ans = max(ans, temp)
print(ans)

n = int(eval(input()))
X = [[] for _ in range(n)]
for i in range(n):
    a = int(eval(input()))
    for j in range(a):
        x, y = list(map(int, input().split()))
        x -= 1
        X[i].append((x, y))
ans = 0
for i in range(2**n):
    t = [-1] * n
    flag = True
    cnt = 0
    for j in range(n):
        if (i >> j) & 1:
            cnt += 1
            t[j] = 1
        else:
            t[j] = 0
    for j in range(n):
        if (i >> j) & 1:
            for x, y in X[j]:
                if t[x] != y:
                    flag = False
    if flag:
        ans = max(ans, cnt)
print(ans)


Input:
n = int(eval(input()))

ab = []

ans = 0

for i in range(n):

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

    ab.append([a+b,b])

    ans -= b

ab.sort(reverse=True)

for i in range(n):

    if i%2 == 0:

        ans += ab[i][0]

print(ans)

N = int(eval(input()))

AB = []

ans = 0

for i in range(N):

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

    ans += a

    AB.append(a+b)

AB.sort(reverse=True)

for i in range(N):

    if i%2 == 1:

        ans -= AB[i]

print(ans)

n = int(eval(input()))
ab = []
ans = 0
for i in range(n):
    a, b = list(map(int, input().split()))
    ab.append([a + b, b])
    ans -= b
ab.sort(reverse=True)
for i in range(n):
    if i % 2 == 0:
        ans += ab[i][0]
print(ans)

N = int(eval(input()))
AB = []
ans = 0
for i in range(N):
    a, b = list(map(int, input().split()))
    ans += a
    AB.append(a + b)
AB.sort(reverse=True)
for i in range(N):
    if i % 2 == 1:
        ans -= AB[i]
print(ans)

-n = int(eval(input()))
-ab = []
+N = int(eval(input()))
+AB = []
-for i in range(n):
+for i in range(N):
-    ab.append([a + b, b])
-    ans -= b
-ab.sort(reverse=True)
-for i in range(n):
-    if i % 2 == 0:
-        ans += ab[i][0]
+    ans += a
+    AB.append(a + b)
+AB.sort(reverse=True)
+for i in range(N):
+    if i % 2 == 1:
+        ans -= AB[i]


Input:
def sumitrust2019_d():

    n = int(eval(input()))

    s = eval(input())

    ans = 0

    for i in range(1000):

        # 確認するpinの数字の組み合わせと桁の初期化

        # pin = list(str(i).zfill(3))

        current_digit = 0

        pin = f'{i:0>3}'

        search_num = pin[current_digit]

        for num in s:

            # 見つけると桁を右に一つずらす

            # 毎回リストにアクセスするより変数に取り出しておくほうがいいかも。

            # if num == pin[current_digit]:

            if num == search_num:

                current_digit += 1

                # indexが3(桁が3→2→1→0)になったときはそのPINは作れる

                if current_digit == 3:

                    ans += 1

                    break

                # 見つけ終わるまではチェックする数字を置き換え。

                elif current_digit < 3:

                    search_num = pin[current_digit]

    print(ans)

if __name__ == '__main__':

    sumitrust2019_d()

def sumitrust2019_d_01():

    n = int(eval(input()))

    s = eval(input())

    ans = 0

    for i in range(1000):

        # 確認するpinの数字の組み合わせと桁の初期化

        # pin = list(str(i).zfill(3))

        pin = f'{i:0>3}'

        # list+indexで書こうと思ったけど、そもそも文字列でやっているのでfindで探しちゃう

        p1 = s.find(pin[0])

        if p1 != -1:

            p2 = s.find(pin[1], p1 + 1)

            if p2 != -1:

                p3 = s.find(pin[2], p2 + 1)

                if p3 != -1:

                    ans += 1

    print(ans)

if __name__ == '__main__':

    sumitrust2019_d_01()

def sumitrust2019_d():
    n = int(eval(input()))
    s = eval(input())
    ans = 0
    for i in range(1000):
        # 確認するpinの数字の組み合わせと桁の初期化
        # pin = list(str(i).zfill(3))
        current_digit = 0
        pin = f"{i:0>3}"
        search_num = pin[current_digit]
        for num in s:
            # 見つけると桁を右に一つずらす
            # 毎回リストにアクセスするより変数に取り出しておくほうがいいかも。
            # if num == pin[current_digit]:
            if num == search_num:
                current_digit += 1
                # indexが3(桁が3→2→1→0)になったときはそのPINは作れる
                if current_digit == 3:
                    ans += 1
                    break
                # 見つけ終わるまではチェックする数字を置き換え。
                elif current_digit < 3:
                    search_num = pin[current_digit]
    print(ans)

if __name__ == "__main__":
    sumitrust2019_d()

def sumitrust2019_d_01():
    n = int(eval(input()))
    s = eval(input())
    ans = 0
    for i in range(1000):
        # 確認するpinの数字の組み合わせと桁の初期化
        # pin = list(str(i).zfill(3))
        pin = f"{i:0>3}"
        # list+indexで書こうと思ったけど、そもそも文字列でやっているのでfindで探しちゃう
        p1 = s.find(pin[0])
        if p1 != -1:
            p2 = s.find(pin[1], p1 + 1)
            if p2 != -1:
                p3 = s.find(pin[2], p2 + 1)
                if p3 != -1:
                    ans += 1
    print(ans)

if __name__ == "__main__":
    sumitrust2019_d_01()

-        search_num = pin[current_digit]

-            # 見つけると桁を右に一つずらす

-            # 毎回リストにアクセスするより変数に取り出しておくほうがいいかも。

-            # if num == pin[current_digit]:

-                # indexが3(桁が3→2→1→0)になったときはそのPINは作れる

+        # list+indexで書こうと思ったけど、そもそも文字列でやっているのでfindで探しちゃう

-                # 見つけ終わるまではチェックする数字を置き換え。

-                elif current_digit < 3:

-                    search_num = pin[current_digit]


Input:
s=eval(input())

mx=0

for i in range(len(s)):

  a=s[:len(s)-i]

  for j in range(len(s)-i):

    b=a[j:]

    if b.count('A')+b.count('C')+b.count('G')+b.count('T')==len(b):

      mx=max(mx,len(b))

print(mx)

s=eval(input())

n=len(s)

a=[0]*n

for i in range(n):

  if s[i] in 'ATCG':a[i]=a[i-1]+1

  else:a[i]=0

print((max(a)))

s = eval(input())
mx = 0
for i in range(len(s)):
    a = s[: len(s) - i]
    for j in range(len(s) - i):
        b = a[j:]
        if b.count("A") + b.count("C") + b.count("G") + b.count("T") == len(b):
            mx = max(mx, len(b))
print(mx)

s = eval(input())
n = len(s)
a = [0] * n
for i in range(n):
    if s[i] in "ATCG":
        a[i] = a[i - 1] + 1
    else:
        a[i] = 0
print((max(a)))

-        if b.count("A") + b.count("C") + b.count("G") + b.count("T") == len(b):


Input:
A,B=list(map(float,input().split()))

X=A*(B*100)

print((int(X/100)))

A,B=input().split()

A=int(A)

B=int(100*float(B)+0.5)

print((int(A*B/100)))

A, B = list(map(float, input().split()))
X = A * (B * 100)
print((int(X / 100)))

A, B = input().split()
A = int(A)
B = int(100 * float(B) + 0.5)
print((int(A * B / 100)))

-A, B = list(map(float, input().split()))


Input:
x,n,*p=list(map(int,open(0).read().split()))

print((min({*list(range(999))}-{*p},key=lambda y:(abs(y-x),y))))

x,n,*p=list(map(int,open(0).read().split()))

print((min({*list(range(999))}-{*p},key=lambda y:abs(y-x))))

x, n, *p = list(map(int, open(0).read().split()))
print((min({*list(range(999))} - {*p}, key=lambda y: (abs(y - x), y))))

x, n, *p = list(map(int, open(0).read().split()))
print((min({*list(range(999))} - {*p}, key=lambda y: abs(y - x))))

-print((min({*list(range(999))} - {*p}, key=lambda y: (abs(y - x), y))))

+print((min({*list(range(999))} - {*p}, key=lambda y: abs(y - x))))


Input:
N, A, B = list(map(int, input().split()))

div, mod = divmod(N, A + B)

ans = A * div

ans += min(mod, A)

print(ans)

N, A, B = list(map(int, input().split()))

d, m = divmod(N, A + B)

ans = A * d + min(m, A)

print(ans)

-div, mod = divmod(N, A + B)
-ans = A * div
-ans += min(mod, A)
+d, m = divmod(N, A + B)
+ans = A * d + min(m, A)


Input:
S = list(eval(input()))

N = len(S)

def f(x):

    print(x)

    exit()

if N < 5:

    f("NO")

elif S[0] == "d":

    w = 1

elif S[0] == "e":

    w = -1

else:

    f("NO")

i = 0

while True:

    if w > 0:

        if S[i]+S[i+1]+S[i+2]+S[i+3]+S[i+4] == "dream":

            i += 5

            if i == N:

                f("YES")

            elif S[i] == "d":

                pass

            elif S[i] == "e":

                if i+1 <= N-1:

                    if S[i+1] == "r":

                        if i+1 == N-1:

                            f("YES")

                        elif S[i+2] == "a":

                            w *= -1

                        elif S[i+2] == "e":

                            i += 2

                            w *= -1

                        elif S[i+2] == "d":

                            i += 2

                        else:

                            f("NO")

                    else:

                        f("NO")

                else:

                    f("NO")

            else:

                f("NO")

        else:

            f("NO")

    elif w < 0:

        if S[i]+S[i+1]+S[i+2]+S[i+3]+S[i+4] == "erase":

            i += 5

            if i == N:

                f("YES")

            if S[i] == "r":

                i += 1

                if i == N:

                    f("YES")

            if S[i] == "d":

                w *= -1

            elif S[i] == "e":

                pass

            else:

                f("NO")

        else:

            f("NO")

    if i+4 > N-1:

        f("NO")

s = eval(input())

S = ''.join(list(reversed(s)))

N = len(S)

i = 0

while True:

    l = N - i

    if l>=5 and (S[i:i+5]=='maerd' or S[i:i+5]=='esare'):

        i += 5

    elif l>=6 and S[i:i+6]=='resare':

        i += 6

    elif l>=7 and S[i:i+7]=='remaerd':

        i += 7

    else:

        print("NO")

        exit()

    if i == N:

        print('YES')

        exit()

s = eval(input())
S = "".join(list(reversed(s)))
N = len(S)
i = 0
while True:
    l = N - i
    if l >= 5 and (S[i : i + 5] == "maerd" or S[i : i + 5] == "esare"):
        i += 5
    elif l >= 6 and S[i : i + 6] == "resare":
        i += 6
    elif l >= 7 and S[i : i + 7] == "remaerd":
        i += 7
    else:
        print("NO")
        exit()
    if i == N:
        print("YES")
        exit()

+    elif l >= 6 and S[i : i + 6] == "resare":

+    elif l >= 7 and S[i : i + 7] == "remaerd":


Input:
# coding: utf-8

import sys

import numpy as np

from collections import Counter

sr = lambda: sys.stdin.readline().rstrip()

ir = lambda: int(sr())

lr = lambda: list(map(int, sr().split()))

MOD = 10 ** 9 + 7

# 素因数分解をして、それぞれの因数をどこに入れるか

def cmb(n, k):

    if k < 0 or k > n: return 0

    return fact[n] * fact_inv[k] % MOD * fact_inv[n-k] % MOD

def cumprod(arr, MOD):

    L = len(arr); Lsq = int(L**.5+1)

    arr = np.resize(arr, Lsq**2).reshape(Lsq, Lsq)

    for n in range(1, Lsq):

        arr[:, n] *= arr[:, n-1]; arr[:, n] %= MOD

    for n in range(1, Lsq):

        arr[n] *= arr[n-1, -1]; arr[n] %= MOD

    return arr.ravel()[:L]

def make_fact(U, MOD):

    x = np.arange(U, dtype=np.int64); x[0] = 1

    fact = cumprod(x, MOD)

    x = np.arange(U, 0, -1, dtype=np.int64); x[0] = pow(int(fact[-1]), MOD-2, MOD)

    fact_inv = cumprod(x, MOD)[::-1]

    return fact, fact_inv

U = 10 ** 6  # 階乗テーブルの上限

fact, fact_inv = make_fact(U, MOD)

def prime_factorize(n): # Nの素因数分解

    A = []

    while n % 2 == 0:

        A.append(2); n //= 2

    f = 3

    while f * f <= n:

        if n % f == 0:

            A.append(f); n //= f

        else:

            f += 2

    if n != 1:

        A.append(n)

    return A

N, M = lr()

primes = prime_factorize(M)

counter = Counter(primes)

answer = 1

for v in list(counter.values()):

    cases = cmb(N-1+v, v)

    answer *= cases

    answer %= MOD

print((answer % MOD))

# np.int64とint型の違いに注意

# 16

# coding: utf-8

import sys

import numpy as np

from collections import Counter

sr = lambda: sys.stdin.readline().rstrip()

ir = lambda: int(sr())

lr = lambda: list(map(int, sr().split()))

MOD = 10 ** 9 + 7

# 素因数分解をして、それぞれの因数をどこに入れるか

def cmb(n, k):

    if k < 0 or k > n: return 0

    return fact[n] * fact_inv[k] % MOD * fact_inv[n-k] % MOD

def cumprod(arr, MOD):

    L = len(arr); Lsq = int(L**.5+1)

    arr = np.resize(arr, Lsq**2).reshape(Lsq, Lsq)

    for n in range(1, Lsq):

        arr[:, n] *= arr[:, n-1]; arr[:, n] %= MOD

    for n in range(1, Lsq):

        arr[n] *= arr[n-1, -1]; arr[n] %= MOD

    return arr.ravel()[:L]

def make_fact(U, MOD):

    x = np.arange(U, dtype=np.int64); x[0] = 1

    fact = cumprod(x, MOD)

    x = np.arange(U, 0, -1, dtype=np.int64); x[0] = pow(int(fact[-1]), MOD-2, MOD)

    fact_inv = cumprod(x, MOD)[::-1]

    return fact, fact_inv

U = 10 ** 5 + 100  # 階乗テーブルの上限

fact, fact_inv = make_fact(U, MOD)

def prime_factorize(n): # Nの素因数分解

    A = []

    while n % 2 == 0:

        A.append(2); n //= 2

    f = 3

    while f * f <= n:

        if n % f == 0:

            A.append(f); n //= f

        else:

            f += 2

    if n != 1:

        A.append(n)

    return A

N, M = lr()

primes = prime_factorize(M)

counter = Counter(primes)

answer = 1

for v in list(counter.values()):

    cases = cmb(N-1+v, v)

    answer *= cases

    answer %= MOD

print((answer % MOD))

# np.int64とint型の違いに注意

# 16

# coding: utf-8
import sys
import numpy as np
from collections import Counter

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
MOD = 10**9 + 7
# 素因数分解をして、それぞれの因数をどこに入れるか
def cmb(n, k):
    if k < 0 or k > n:
        return 0
    return fact[n] * fact_inv[k] % MOD * fact_inv[n - k] % MOD

def cumprod(arr, MOD):
    L = len(arr)
    Lsq = int(L**0.5 + 1)
    arr = np.resize(arr, Lsq**2).reshape(Lsq, Lsq)
    for n in range(1, Lsq):
        arr[:, n] *= arr[:, n - 1]
        arr[:, n] %= MOD
    for n in range(1, Lsq):
        arr[n] *= arr[n - 1, -1]
        arr[n] %= MOD
    return arr.ravel()[:L]

def make_fact(U, MOD):
    x = np.arange(U, dtype=np.int64)
    x[0] = 1
    fact = cumprod(x, MOD)
    x = np.arange(U, 0, -1, dtype=np.int64)
    x[0] = pow(int(fact[-1]), MOD - 2, MOD)
    fact_inv = cumprod(x, MOD)[::-1]
    return fact, fact_inv

U = 10**6  # 階乗テーブルの上限
fact, fact_inv = make_fact(U, MOD)

def prime_factorize(n):  # Nの素因数分解
    A = []
    while n % 2 == 0:
        A.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            A.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        A.append(n)
    return A

N, M = lr()
primes = prime_factorize(M)
counter = Counter(primes)
answer = 1
for v in list(counter.values()):
    cases = cmb(N - 1 + v, v)
    answer *= cases
    answer %= MOD
print((answer % MOD))
# np.int64とint型の違いに注意
# 16

# coding: utf-8
import sys
import numpy as np
from collections import Counter

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
MOD = 10**9 + 7
# 素因数分解をして、それぞれの因数をどこに入れるか
def cmb(n, k):
    if k < 0 or k > n:
        return 0
    return fact[n] * fact_inv[k] % MOD * fact_inv[n - k] % MOD

def cumprod(arr, MOD):
    L = len(arr)
    Lsq = int(L**0.5 + 1)
    arr = np.resize(arr, Lsq**2).reshape(Lsq, Lsq)
    for n in range(1, Lsq):
        arr[:, n] *= arr[:, n - 1]
        arr[:, n] %= MOD
    for n in range(1, Lsq):
        arr[n] *= arr[n - 1, -1]
        arr[n] %= MOD
    return arr.ravel()[:L]

def make_fact(U, MOD):
    x = np.arange(U, dtype=np.int64)
    x[0] = 1
    fact = cumprod(x, MOD)
    x = np.arange(U, 0, -1, dtype=np.int64)
    x[0] = pow(int(fact[-1]), MOD - 2, MOD)
    fact_inv = cumprod(x, MOD)[::-1]
    return fact, fact_inv

U = 10**5 + 100  # 階乗テーブルの上限
fact, fact_inv = make_fact(U, MOD)

def prime_factorize(n):  # Nの素因数分解
    A = []
    while n % 2 == 0:
        A.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            A.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        A.append(n)
    return A

N, M = lr()
primes = prime_factorize(M)
counter = Counter(primes)
answer = 1
for v in list(counter.values()):
    cases = cmb(N - 1 + v, v)
    answer *= cases
    answer %= MOD
print((answer % MOD))
# np.int64とint型の違いに注意
# 16

-U = 10**6  # 階乗テーブルの上限
+U = 10**5 + 100  # 階乗テーブルの上限


Input:
a,b = eval(input()), eval(input())

print(("Yes" if b[ :len(b)-1] == a else "No"))

a=eval(input())

b=eval(input())

res="No"

if a==b[:-1]:res="Yes"

print(res)

a, b = eval(input()), eval(input())
print(("Yes" if b[: len(b) - 1] == a else "No"))

a = eval(input())
b = eval(input())
res = "No"
if a == b[:-1]:
    res = "Yes"
print(res)

-print(("Yes" if b[: len(b) - 1] == a else "No"))


Input:
N, M = list(map(int, input().split()))

condition = set()

for i in range(M):

    s, c = list(map(int, input().split()))

    condition.add((s, c))

ans = float("inf")

if N == 1:

    for i in range(10):

        num = str(i)

        for s, c in condition:

            if num[s-1] != str(c):

                break

        else:

            print(i)

            exit()

for i in range(10**(N-1), 10**N):

    num = str(i)

    for s, c in condition:

        if num[s-1] != str(c):

            break

    else:

        print(i)

        exit()

print((-1))

N, M = list(map(int, input().split()))

condition = set()

for i in range(M):

    s, c = list(map(int, input().split()))

    condition.add((s, c))

ans = float("inf")

if N == 1:

    for i in range(10):

        num = str(i)

        for s, c in condition:

            if num[s-1] != str(c):

                break

        else:

            print(i)

            exit()

else:

    for i in range(10**(N-1), 10**N):

        num = str(i)

        for s, c in condition:

            if num[s-1] != str(c):

                break

        else:

            print(i)

            exit()

print((-1))

N, M = list(map(int, input().split()))
condition = set()
for i in range(M):
    s, c = list(map(int, input().split()))
    condition.add((s, c))
ans = float("inf")
if N == 1:
    for i in range(10):
        num = str(i)
        for s, c in condition:
            if num[s - 1] != str(c):
                break
        else:
            print(i)
            exit()
for i in range(10 ** (N - 1), 10**N):
    num = str(i)
    for s, c in condition:
        if num[s - 1] != str(c):
            break
    else:
        print(i)
        exit()
print((-1))

N, M = list(map(int, input().split()))
condition = set()
for i in range(M):
    s, c = list(map(int, input().split()))
    condition.add((s, c))
ans = float("inf")
if N == 1:
    for i in range(10):
        num = str(i)
        for s, c in condition:
            if num[s - 1] != str(c):
                break
        else:
            print(i)
            exit()
else:
    for i in range(10 ** (N - 1), 10**N):
        num = str(i)
        for s, c in condition:
            if num[s - 1] != str(c):
                break
        else:
            print(i)
            exit()
print((-1))


Input:
def serect_sort(r, n):

    cnt = 0

    for i in range(0, n):

        minj = i

        for j in range(i, n):

            if r[j] < r[minj]:

                minj = j

        r[i],r[minj] = r[minj],r[i]

        if i != minj:

            cnt +=1

    print((*r))

    print(cnt)

N = int(eval(input()))

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

serect_sort(A, N)

def selectionSort(n, A):

    cnt =0

    for i in range(n):

        minj = i

        for j in range(i,n):

            if A[minj] > A[j]:

                minj = j

        if i != minj:

            A[i],A[minj] = A[minj],A[i]

            cnt += 1

    print((*A))

    print(cnt)

if __name__ == '__main__':

    n = int(eval(input()))

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

    selectionSort(n,A)

def serect_sort(r, n):
    cnt = 0
    for i in range(0, n):
        minj = i
        for j in range(i, n):
            if r[j] < r[minj]:
                minj = j
        r[i], r[minj] = r[minj], r[i]
        if i != minj:
            cnt += 1
    print((*r))
    print(cnt)

N = int(eval(input()))
A = list(map(int, input().split()))
serect_sort(A, N)

def selectionSort(n, A):
    cnt = 0
    for i in range(n):
        minj = i
        for j in range(i, n):
            if A[minj] > A[j]:
                minj = j
        if i != minj:
            A[i], A[minj] = A[minj], A[i]
            cnt += 1
    print((*A))
    print(cnt)

if __name__ == "__main__":
    n = int(eval(input()))
    A = list(map(int, input().split()))
    selectionSort(n, A)

+            A[i], A[minj] = A[minj], A[i]

+    A = list(map(int, input().split()))


Input:
from itertools import accumulate as acc

import sys

N,C=list(map(int,input().split()))

a=[list(map(int,input().split())) for i in range(N)]

if N==1: print((max(0, a[0][1]-a[0][0], a[0][1]-(C-a[0][0]) ) ),sys.exit())

b=list(acc( [ a[i][1] for i in range(N)] ))

ans= sum([a[i][1] for i in range(N)])+max(C-a[0][0],a[N-1][0])

l=[[b[i]-a[i][0],0] for i in range(N)]

r=[[b[N-1]-(C-a[0][0]),0]]+[[b[N-1]-b[i]-(C-a[i+1][0]),0] for i in range(N-1)]

tmp=0

for i in range(N):

    if l[i][0]>tmp: tmp=l[i][0]

    l[i][1]=tmp

tmp=0

for i in range(N-1,-1,-1):

    if r[i][0]>tmp: tmp=r[i][0]

    r[i][1]=tmp

p=[l[0][1],r[0][1],l[0][1]-a[0][0]+r[1][1]]

q=[l[N-1][1],r[N-1][1],r[N-1][0]-(C-a[N-1][0])+l[N-2][1]]

ans=max(p+q)

for i in range(1,N-1):

    p1=l[i][1]

    p2=r[i][1]

    p3=l[i][1]-a[i][0]+r[i+1][1]

    p4=r[i][1]-(C-a[i][0])+l[i-1][1]

    ans=max(ans,p1,p2,p3,p4)

print(ans)

-b = list(acc([a[i][1] for i in range(N)]))


Input:
from collections import defaultdict

n = int(eval(input()))

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

can = True

if n % 3 == 0:

    d = defaultdict(int)

    for aa in a:

        d[aa] += 1

    m = n // 3

    t = []

    for number, cnt in list(d.items()):

        if cnt % m != 0:

            can = False

            break

        else:

            for _ in range(cnt // m):

                t.append(number)

    else:

        if any(t[(0 + i) % 3] ^ t[(1 + i) % 3] != t[(2 + i) % 3] for i in range(3)):

            can = False

else:

    if any(aa != 0 for aa in a):

        can = False

print(('Yes' if can else 'No'))

def main():

    from collections import Counter

    n = int(eval(input()))

    *a, = list(map(int, input().split()))

    if n % 3 == 0:

        ctr = Counter(a)

        if len(ctr) == 1:

            print(('Yes' if 0 in ctr else 'No'))

            return

        elif len(ctr) == 2:

            print(('Yes' if ctr[0] == n // 3 else 'No'))

            return

        elif len(ctr) == 3:

            x = 0

            p = None

            for k, v in list(ctr.items()):

                if p is None:

                    p = v

                elif p != v:

                    print('No')

                    return

                x ^= k

            print(('Yes' if x == 0 else 'No'))

            return

        else:

            print('No')

            return

    else:

        print(('Yes' if all([x == 0 for x in a]) else 'No'))

        return

if __name__ == '__main__':

    main()

from collections import defaultdict

n = int(eval(input()))
a = tuple(map(int, input().split()))
can = True
if n % 3 == 0:
    d = defaultdict(int)
    for aa in a:
        d[aa] += 1
    m = n // 3
    t = []
    for number, cnt in list(d.items()):
        if cnt % m != 0:
            can = False
            break
        else:
            for _ in range(cnt // m):
                t.append(number)
    else:
        if any(t[(0 + i) % 3] ^ t[(1 + i) % 3] != t[(2 + i) % 3] for i in range(3)):
            can = False
else:
    if any(aa != 0 for aa in a):
        can = False
print(("Yes" if can else "No"))

def main():
    from collections import Counter

    n = int(eval(input()))
    (*a,) = list(map(int, input().split()))
    if n % 3 == 0:
        ctr = Counter(a)
        if len(ctr) == 1:
            print(("Yes" if 0 in ctr else "No"))
            return
        elif len(ctr) == 2:
            print(("Yes" if ctr[0] == n // 3 else "No"))
            return
        elif len(ctr) == 3:
            x = 0
            p = None
            for k, v in list(ctr.items()):
                if p is None:
                    p = v
                elif p != v:
                    print("No")
                    return
                x ^= k
            print(("Yes" if x == 0 else "No"))
            return
        else:
            print("No")
            return
    else:
        print(("Yes" if all([x == 0 for x in a]) else "No"))
        return

if __name__ == "__main__":
    main()

-    for number, cnt in list(d.items()):

+    (*a,) = list(map(int, input().split()))

+            print(("Yes" if 0 in ctr else "No"))

+            print(("Yes" if ctr[0] == n // 3 else "No"))

+            for k, v in list(ctr.items()):

+            print(("Yes" if x == 0 else "No"))

+        print(("Yes" if all([x == 0 for x in a]) else "No"))


Input:
import sys

from heapq import heappop, heappush

#import numpy as np

stdin = sys.stdin

ri = lambda: int(rs())

rl = lambda: list(map(int, stdin.readline().split())) # applies to numbers only

rs = lambda: stdin.readline().rstrip()  # ignore trailing spaces

def dijkstra(start):

    INF = 10 ** 5

    dist = [INF] * (N+1) # dist[0]は使わない

    dist[start] = 0

    que = [(0, start)]

    while que:

        # (d, v) はdが現在の最小の交通費、vが現在の場所

        d, v = heappop(que)

        # 今より安い交通費で既に来たことがある場合、continue

        if dist[v] < d:

            continue

        for next_city, cost in list(edges[v].items()):

            # modeによって円かスヌークを使うか選ぶ

            d1 = d + cost

            # 次の場所の交通費より安くなる場合は、データを更新

            if dist[next_city] > d1:

                dist[next_city] = d1

                heappush(que, (d1, next_city))

    return dist

N, M = rl()

INF = 10 ** 5

edges = [{} for _ in range(N+1)]

for _ in range(M):

    a, b, c = rl()

    edges[a][b] = c

    edges[b][a] = c

answer = 0

for i in range(1, N+1):

    for j in range(i+1, N+1):

        if j not in edges[i]:

            continue

        A = dijkstra(i)

        if A[j] < edges[i][j]:

            answer += 1

            edges[i].pop(j)

            edges[j].pop(i)

print(answer)

# 00

import sys

from scipy.sparse.csgraph import shortest_path

import numpy as np

stdin = sys.stdin

ri = lambda: int(rs())

rl = lambda: list(map(int, stdin.readline().split())) # applies to numbers only

rs = lambda: stdin.readline().rstrip()  # ignore trailing spaces

N, M = rl()

edges = [rl() for _ in range(M)]

graph = np.zeros((N, N))

for a, b, c in edges:

    graph[a-1, b-1] = c

dist = shortest_path(graph, directed=False).astype(int)

answer = 0

for a, b, c in edges:

    if c != dist[a-1, b-1]:

        answer += 1

print(answer)

#05

import sys
from heapq import heappop, heappush

# import numpy as np
stdin = sys.stdin
ri = lambda: int(rs())
rl = lambda: list(map(int, stdin.readline().split()))  # applies to numbers only
rs = lambda: stdin.readline().rstrip()  # ignore trailing spaces

def dijkstra(start):
    INF = 10**5
    dist = [INF] * (N + 1)  # dist[0]は使わない
    dist[start] = 0
    que = [(0, start)]
    while que:
        # (d, v) はdが現在の最小の交通費、vが現在の場所
        d, v = heappop(que)
        # 今より安い交通費で既に来たことがある場合、continue
        if dist[v] < d:
            continue
        for next_city, cost in list(edges[v].items()):
            # modeによって円かスヌークを使うか選ぶ
            d1 = d + cost
            # 次の場所の交通費より安くなる場合は、データを更新
            if dist[next_city] > d1:
                dist[next_city] = d1
                heappush(que, (d1, next_city))
    return dist

N, M = rl()
INF = 10**5
edges = [{} for _ in range(N + 1)]
for _ in range(M):
    a, b, c = rl()
    edges[a][b] = c
    edges[b][a] = c
answer = 0
for i in range(1, N + 1):
    for j in range(i + 1, N + 1):
        if j not in edges[i]:
            continue
        A = dijkstra(i)
        if A[j] < edges[i][j]:
            answer += 1
            edges[i].pop(j)
            edges[j].pop(i)
print(answer)
# 00

import sys
from scipy.sparse.csgraph import shortest_path
import numpy as np

stdin = sys.stdin
ri = lambda: int(rs())
rl = lambda: list(map(int, stdin.readline().split()))  # applies to numbers only
rs = lambda: stdin.readline().rstrip()  # ignore trailing spaces
N, M = rl()
edges = [rl() for _ in range(M)]
graph = np.zeros((N, N))
for a, b, c in edges:
    graph[a - 1, b - 1] = c
dist = shortest_path(graph, directed=False).astype(int)
answer = 0
for a, b, c in edges:
    if c != dist[a - 1, b - 1]:
        answer += 1
print(answer)
# 05

+from scipy.sparse.csgraph import shortest_path

-    dist = [INF] * (N + 1)  # dist[0]は使わない

-        # (d, v) はdが現在の最小の交通費、vが現在の場所

-        # 今より安い交通費で既に来たことがある場合、continue

-        for next_city, cost in list(edges[v].items()):

-            # modeによって円かスヌークを使うか選ぶ

-            # 次の場所の交通費より安くなる場合は、データを更新

-                heappush(que, (d1, next_city))

+dist = shortest_path(graph, directed=False).astype(int)


Input:
#あっとのTECH LOG、ここからDFS

N, M, K = map(int, input().split())

F = [[] for _ in range(N)]

B = [[] for _ in range(N)]

for _ in range(M):

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

    a, b = a - 1, b - 1

    F[a].append(b)

    F[b].append(a)

for _ in range(K):

    c, d = map(int, input().split())

    c, d = c - 1, d - 1

    B[c].append(d)

    B[d].append(c)

D = {}

parent = [-1] * N

visited = [False] * N

for root in range(N):

    if visited[root]:

        continue

    D[root] = set([root])

    stack = [root]

    while stack:

        n = stack.pop()

        visited[n] = True

        parent[n] = root

        for to in F[n]:

            if visited[to]:

                continue

            D[root].add(to)

            stack.append(to)

ans = [0] * N

for iam in range(N):

    group = D[parent[iam]]

    tmp_ans = len(group) - len(F[iam]) - 1

    for block in B[iam]:

        if block in group:

            tmp_ans -= 1

    ans[iam] = tmp_ans

print(*ans, sep=' ')

#@YottyPG　Qiita

from collections import deque

N,M,K = list(map(int,input().split()))

friend = [list(map(int,input().split())) for _ in range(M)]

block = [list(map(int,input().split())) for _ in range(K)]

f = [set() for _ in range(N+1)]

b = [set() for _ in range(N+1)]

for i,j in friend:

    f[i].add(j)

    f[j].add(i)

for i,j in block:

    b[i].add(j)

    b[j].add(i)

stack=deque()

ans = [0]*(N+1)

visited = [0]*(N+1)

for i in range(1,N+1):

    if visited[i]:

        continue

    link = {i}

    visited[i] = 1

    stack.append(i)

    while stack:

        n = stack.pop()

        for j in f[n]:

            if visited[j]==0:

                stack.append(j)

                visited[j] = 1

                link.add(j)

    for i in link:

        ans[i] = len(link) - len(link & f[i]) - len(link & b[i]) - 1

print((*ans[1:]))

# あっとのTECH LOG、ここからDFS
N, M, K = map(int, input().split())
F = [[] for _ in range(N)]
B = [[] for _ in range(N)]
for _ in range(M):
    a, b = map(int, input().split())
    a, b = a - 1, b - 1
    F[a].append(b)
    F[b].append(a)
for _ in range(K):
    c, d = map(int, input().split())
    c, d = c - 1, d - 1
    B[c].append(d)
    B[d].append(c)
D = {}
parent = [-1] * N
visited = [False] * N
for root in range(N):
    if visited[root]:
        continue
    D[root] = set([root])
    stack = [root]
    while stack:
        n = stack.pop()
        visited[n] = True
        parent[n] = root
        for to in F[n]:
            if visited[to]:
                continue
            D[root].add(to)
            stack.append(to)
ans = [0] * N
for iam in range(N):
    group = D[parent[iam]]
    tmp_ans = len(group) - len(F[iam]) - 1
    for block in B[iam]:
        if block in group:
            tmp_ans -= 1
    ans[iam] = tmp_ans
print(*ans, sep=" ")

# @YottyPG　Qiita
from collections import deque

N, M, K = list(map(int, input().split()))
friend = [list(map(int, input().split())) for _ in range(M)]
block = [list(map(int, input().split())) for _ in range(K)]
f = [set() for _ in range(N + 1)]
b = [set() for _ in range(N + 1)]
for i, j in friend:
    f[i].add(j)
    f[j].add(i)
for i, j in block:
    b[i].add(j)
    b[j].add(i)
stack = deque()
ans = [0] * (N + 1)
visited = [0] * (N + 1)
for i in range(1, N + 1):
    if visited[i]:
        continue
    link = {i}
    visited[i] = 1
    stack.append(i)
    while stack:
        n = stack.pop()
        for j in f[n]:
            if visited[j] == 0:
                stack.append(j)
                visited[j] = 1
                link.add(j)
    for i in link:
        ans[i] = len(link) - len(link & f[i]) - len(link & b[i]) - 1
print((*ans[1:]))

+N, M, K = list(map(int, input().split()))

+friend = [list(map(int, input().split())) for _ in range(M)]

+block = [list(map(int, input().split())) for _ in range(K)]

-    tmp_ans = len(group) - len(F[iam]) - 1

+        ans[i] = len(link) - len(link & f[i]) - len(link & b[i]) - 1


Input:
import math

import itertools

n = int(eval(input()))

xys = [[] for i in range(n)]

for i in range(n):

    xys[i] = list(map(int,input().split()))

m = math.factorial(n)

c = [i for i in range(n)]

cs = itertools.permutations(c)

s = 0

for d in cs:

    for j in range(len(d)-1):

        x = (xys[d[j]][0] - xys[d[j+1]][0]) ** 2 + (xys[d[j]][1] - xys[d[j+1]][1]) ** 2

        s += x ** (0.5)

print((s/m))

import itertools

import math

n = int(eval(input()))

points = []

for i in range(n):

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

    points.append([x,y])

cs = list(itertools.combinations(points,2))

ans = 0

for a,b in cs:

    c = (a[0]-b[0]) ** 2 + (a[1]-b[1]) ** 2

    ans += math.sqrt(c)

ans = (ans / n) * 2

print(ans)

import math
import itertools

n = int(eval(input()))
xys = [[] for i in range(n)]
for i in range(n):
    xys[i] = list(map(int, input().split()))
m = math.factorial(n)
c = [i for i in range(n)]
cs = itertools.permutations(c)
s = 0
for d in cs:
    for j in range(len(d) - 1):
        x = (xys[d[j]][0] - xys[d[j + 1]][0]) ** 2 + (
            xys[d[j]][1] - xys[d[j + 1]][1]
        ) ** 2
        s += x ** (0.5)
print((s / m))

import itertools
import math

n = int(eval(input()))
points = []
for i in range(n):
    x, y = list(map(int, input().split()))
    points.append([x, y])
cs = list(itertools.combinations(points, 2))
ans = 0
for a, b in cs:
    c = (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
    ans += math.sqrt(c)
ans = (ans / n) * 2
print(ans)

-    xys[i] = list(map(int, input().split()))

+    x, y = list(map(int, input().split()))

+cs = list(itertools.combinations(points, 2))


Input:
N = int(eval(input()))

A = list(map(int, input().split(" ")))

A_amari = [0]*N

cnt = 0

while(not(1 in A_amari)):

    for i in range(len(A)):

        A_amari[i] = A[i] % 2

        A[i] = A[i] / 2

    if(not(1 in A_amari)):cnt += 1

print(cnt)

n = int(eval(input()))

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

flg = 0

cnt = 0

while (flg == 0):

    for i in a:

        if i%2 == 1:

            flg = 1

    if flg == 1:

        break

    cnt += 1

    a = [i/2 for i in a]

print(cnt)

N = int(eval(input()))
A = list(map(int, input().split(" ")))
A_amari = [0] * N
cnt = 0
while not (1 in A_amari):
    for i in range(len(A)):
        A_amari[i] = A[i] % 2
        A[i] = A[i] / 2
    if not (1 in A_amari):
        cnt += 1
print(cnt)

n = int(eval(input()))
a = list(map(int, input().split()))
flg = 0
cnt = 0
while flg == 0:
    for i in a:
        if i % 2 == 1:
            flg = 1
    if flg == 1:
        break
    cnt += 1
    a = [i / 2 for i in a]
print(cnt)

-N = int(eval(input()))
-A = list(map(int, input().split(" ")))
-A_amari = [0] * N
+n = int(eval(input()))
+a = list(map(int, input().split()))
+flg = 0
-while not (1 in A_amari):
-    for i in range(len(A)):
-        A_amari[i] = A[i] % 2
-        A[i] = A[i] / 2
-    if not (1 in A_amari):
-        cnt += 1
+while flg == 0:
+    for i in a:
+        if i % 2 == 1:
+            flg = 1
+    if flg == 1:
+        break
+    cnt += 1
+    a = [i / 2 for i in a]


Input:
n, m = list(map(int, input().split()))

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

ls = [list(map(int, input().split())) for _ in range(m)]

class UnionFind:

    def __init__(self, n):

        self.n = n

        self.parents = list(range(n + 1))

        self.ranks = [0 for _ in range(n + 1)]

    def get_root(self, x):

        if self.parents[x] == x:

            return x

        self.parents[x] = self.get_root(self.parents[x])

        return self.parents[x]

    def merge(self, x, y):

        x = self.get_root(x)

        y = self.get_root(y)

        if x != y:

            if self.ranks[x] < self.ranks[y]:

                self.parents[x] = y

            else:

                self.parents[y] = x

                if self.ranks[x] == self.ranks[y]:

                    self.ranks[x] += 1

uf = UnionFind(n)

for a, b in ls:

    uf.merge(a, b)

res = 0

for i in range(1, n + 1):

    p0 = uf.get_root(i)

    p1 = uf.get_root(ps[i - 1])

    if p0 == p1:

        res += 1

print(res)

import sys

input = sys.stdin.readline

ri = lambda: int(eval(input()))

rs = lambda: input().rstrip()

ril = lambda: list(map(int, input().split()))

rsl = lambda: input().rstrip().split()

ris = lambda n: [ri() for _ in range(n)]

rss = lambda n: [rs() for _ in range(n)]

rils = lambda n: [ril() for _ in range(n)]

rsls = lambda n: [rsl() for _ in range(n)]

class UnionFind:

    def __init__(self, n):

        self.n = n

        self.parents = list(range(n))

        self.ranks = [0 for _ in range(n)]

    def get_root(self, x):

        if self.parents[x] == x:

            return x

        self.parents[x] = self.get_root(self.parents[x])

        return self.parents[x]

    def merge(self, x, y):

        x = self.get_root(x)

        y = self.get_root(y)

        if x != y:

            if self.ranks[x] < self.ranks[y]:

                self.parents[x] = y

            else:

                self.parents[y] = x

                if self.ranks[x] == self.ranks[y]:

                    self.ranks[x] += 1

n, m = ril()

ps = ril()

ls = rils(m)

uf = UnionFind(n)

for a, b in ls:

    uf.merge(a - 1, b - 1)

res = 0

for i in range(n):

    p0 = uf.get_root(i)

    p1 = uf.get_root(ps[i] - 1)

    if p0 == p1:

        res += 1

print(res)

-ls = [list(map(int, input().split())) for _ in range(m)]

+ril = lambda: list(map(int, input().split()))

+ris = lambda n: [ri() for _ in range(n)]

+rss = lambda n: [rs() for _ in range(n)]

+rils = lambda n: [ril() for _ in range(n)]

+rsls = lambda n: [rsl() for _ in range(n)]

-        self.parents = list(range(n + 1))

-        self.ranks = [0 for _ in range(n + 1)]

+        self.ranks = [0 for _ in range(n)]


Input:
#!/usr/bin/env python

from sys import stdin, exit

code_table = {chr(65+i): '{:05b}'.format(i) for i in range(26)}

code_table.update({' ': '11010', '.': '11011', ',': '11100', '-': '11101',

                   "'": '11110', '?': '11111'})

def decrypt(it):

    if int(next(it)):

        if int(next(it)):

            if int(next(it)):

                return 'P'

            else:

                return 'E'

        else:

            if int(next(it)):

                return ' '

            else:

                if int(next(it)):

                    if int(next(it)):

                        if int(next(it)):

                            if int(next(it)):

                                if int(next(it)):

                                    return 'Q'

                                else:

                                    return 'N'

                            else:

                                if int(next(it)):

                                    return 'V'

                                else:

                                    return 'U'

                        else:

                            if int(next(it)):

                                if int(next(it)):

                                    return 'G'

                                else:

                                    return 'B'

                            else:

                                if int(next(it)):

                                    return 'M'

                                else:

                                    return 'J'

                    else:

                        if int(next(it)):

                            return 'A'

                        else:

                            if int(next(it)):

                                if int(next(it)):

                                    return 'Y'

                                else:

                                    return 'X'

                            else:

                                if int(next(it)):

                                    return '-'

                                else:

                                    return 'Z'

                else:

                    return 'R'

    else:

        if int(next(it)):

            if int(next(it)):

                if int(next(it)):

                    return 'I'

                else:

                    return 'K'

            else:

                if int(next(it)):

                    return 'C'

                else:

                    if int(next(it)):

                        return 'F'

                    else:

                        if int(next(it)):

                            return '.'

                        else:

                            return 'H'

        else:

            if int(next(it)):

                if int(next(it)):

                    if int(next(it)):

                        return 'T'

                    else:

                        return 'S'

                else:

                    if int(next(it)):

                        return 'O'

                    else:

                        return 'L'

            else:

                if int(next(it)):

                    return 'D'

                else:

                    if int(next(it)):

                        if int(next(it)):

                            return ','

                        else:

                            return 'W'

                    else:

                        if int(next(it)):

                            return '?'

                        else:

                            return "'"

def main():

    for line in stdin:

        it = iter(''.join(code_table[c] for c in line.rstrip('\r\n')))

        try:

            while 1:

                print(decrypt(it), end='')

        except StopIteration:

            print()

    exit()

if __name__ == '__main__':

    main()

#!/usr/bin/env python
from sys import stdin, exit

code_table = {chr(65 + i): "{:05b}".format(i) for i in range(26)}
code_table.update(
    {" ": "11010", ".": "11011", ",": "11100", "-": "11101", "'": "11110", "?": "11111"}
)

def decrypt(it):
    if int(next(it)):
        if int(next(it)):
            if int(next(it)):
                return "P"
            else:
                return "E"
        else:
            if int(next(it)):
                return " "
            else:
                if int(next(it)):
                    if int(next(it)):
                        if int(next(it)):
                            if int(next(it)):
                                if int(next(it)):
                                    return "Q"
                                else:
                                    return "N"
                            else:
                                if int(next(it)):
                                    return "V"
                                else:
                                    return "U"
                        else:
                            if int(next(it)):
                                if int(next(it)):
                                    return "G"
                                else:
                                    return "B"
                            else:
                                if int(next(it)):
                                    return "M"
                                else:
                                    return "J"
                    else:
                        if int(next(it)):
                            return "A"
                        else:
                            if int(next(it)):
                                if int(next(it)):
                                    return "Y"
                                else:
                                    return "X"
                            else:
                                if int(next(it)):
                                    return "-"
                                else:
                                    return "Z"
                else:
                    return "R"
    else:
        if int(next(it)):
            if int(next(it)):
                if int(next(it)):
                    return "I"
                else:
                    return "K"
            else:
                if int(next(it)):
                    return "C"
                else:
                    if int(next(it)):
                        return "F"
                    else:
                        if int(next(it)):
                            return "."
                        else:
                            return "H"
        else:
            if int(next(it)):
                if int(next(it)):
                    if int(next(it)):
                        return "T"
                    else:
                        return "S"
                else:
                    if int(next(it)):
                        return "O"
                    else:
                        return "L"
            else:
                if int(next(it)):
                    return "D"
                else:
                    if int(next(it)):
                        if int(next(it)):
                            return ","
                        else:
                            return "W"
                    else:
                        if int(next(it)):
                            return "?"
                        else:
                            return "'"

def main():
    for line in stdin:
        it = iter("".join(code_table[c] for c in line.rstrip("\r\n")))
        try:
            while 1:
                print(decrypt(it), end="")
        except StopIteration:
            print()
    exit()

if __name__ == "__main__":
    main()

-                        if int(next(it)):

-                            if int(next(it)):

-                                if int(next(it)):

-                                    return "Q"

-                                    return "N"

-                                if int(next(it)):

-                                    return "V"

-                                    return "U"

-                            if int(next(it)):

-                                if int(next(it)):

-                                    return "G"

-                                    return "B"

-                                if int(next(it)):

-                                    return "M"

-                                    return "J"

-                        if int(next(it)):

-                            if int(next(it)):

-                                if int(next(it)):

-                                    return "Y"

-                                    return "X"

-                                if int(next(it)):

-                                    return "-"

-                                    return "Z"

-                        if int(next(it)):

-                        if int(next(it)):

-                        if int(next(it)):

-        it = iter("".join(code_table[c] for c in line.rstrip("\r\n")))

-                print(decrypt(it), end="")

+        for c in "".join(code_table[c] for c in line.rstrip("\r\n")):


Input:
import sys

read = sys.stdin.buffer.read

input=lambda :sys.stdin.readline().rstrip()

# inputs= sys.stdin.buffer.readlines

INF=float("inf")

MOD=10**9+7

#input = sys.stdin.buffer.readline

#sys.setrecursionlimit(2147483647)

#rstrip().decode('utf-8')

#import math

#import numpy as np

#import operator

#import bisect

#from heapq import heapify,heappop,heappush

#from math import gcd

#from fractions import gcd

#from collections import deque

#from collections import defaultdict

#from collections import Counter

#from itertools import accumulate

#from itertools import groupby

#from itertools import permutations

#from itertools import combinations

#from scipy.sparse import csr_matrix

#from scipy.sparse.csgraph import floyd_warshall

#from scipy.sparse.csgraph import csgraph_from_dense

#from scipy.sparse.csgraph import dijkstra

#map(int,input().split())

# Z-algorithm (O(N))

# https://deve68.hatenadiary.org/entry/20120201/1328109890

def Z(s):

    n=len(s)

    z=[0]*n

    z[0]=n

    L,R=0,0

    for i in range(1,n):

        if(i>=R): # 過去の結果が全く使えない

            L=R=i

            while(R<n and s[R-L]==s[R]): R+=1

            z[i]=R-L

        elif(z[i-L]<R-i): # 過去の結果が全て使える

            z[i]=z[i-L]

        else: # 過去の結果が一部使える

            L=i

            while(R<n and s[R-L]==s[R]): R+=1

            z[i]=R-L

    return z

# example

#print(Z("abaaabaabb")) # [10,0,1,1,4,0,1,2,0,0]

def main():

	n=int(eval(input()))

	s=eval(input())

	ans=0

	for i in range(n-1):

		z=Z(s[i:])

		k=len(z)

		for j in range(k):

			ans=max(ans,min(j,z[j]))

	print(ans)

if __name__ == '__main__':

	main()

n = int(eval(input()))

s = input().rstrip()

def check(length):

    d = set()

    for i in range(n - 2 * length + 1):

        d.add(s[i:i + length])

        if s[i + length:i + 2 * length] in d:

            return True

    return False

lo = 0

hi = n // 2 + 1

while lo + 1 < hi:

    mid = (lo + hi) // 2

    if check(mid):

        lo = mid

    else:

        hi = mid

print(lo)

import sys

read = sys.stdin.buffer.read
input = lambda: sys.stdin.readline().rstrip()
# inputs= sys.stdin.buffer.readlines
INF = float("inf")
MOD = 10**9 + 7
# input = sys.stdin.buffer.readline
# sys.setrecursionlimit(2147483647)
# rstrip().decode('utf-8')
# import math
# import numpy as np
# import operator
# import bisect
# from heapq import heapify,heappop,heappush
# from math import gcd
# from fractions import gcd
# from collections import deque
# from collections import defaultdict
# from collections import Counter
# from itertools import accumulate
# from itertools import groupby
# from itertools import permutations
# from itertools import combinations
# from scipy.sparse import csr_matrix
# from scipy.sparse.csgraph import floyd_warshall
# from scipy.sparse.csgraph import csgraph_from_dense
# from scipy.sparse.csgraph import dijkstra
# map(int,input().split())
# Z-algorithm (O(N))
# https://deve68.hatenadiary.org/entry/20120201/1328109890
def Z(s):
    n = len(s)
    z = [0] * n
    z[0] = n
    L, R = 0, 0
    for i in range(1, n):
        if i >= R:  # 過去の結果が全く使えない
            L = R = i
            while R < n and s[R - L] == s[R]:
                R += 1
            z[i] = R - L
        elif z[i - L] < R - i:  # 過去の結果が全て使える
            z[i] = z[i - L]
        else:  # 過去の結果が一部使える
            L = i
            while R < n and s[R - L] == s[R]:
                R += 1
            z[i] = R - L
    return z

# example
# print(Z("abaaabaabb")) # [10,0,1,1,4,0,1,2,0,0]
def main():
    n = int(eval(input()))
    s = eval(input())
    ans = 0
    for i in range(n - 1):
        z = Z(s[i:])
        k = len(z)
        for j in range(k):
            ans = max(ans, min(j, z[j]))
    print(ans)

if __name__ == "__main__":
    main()

n = int(eval(input()))
s = input().rstrip()

def check(length):
    d = set()
    for i in range(n - 2 * length + 1):
        d.add(s[i : i + length])
        if s[i + length : i + 2 * length] in d:
            return True
    return False

lo = 0
hi = n // 2 + 1
while lo + 1 < hi:
    mid = (lo + hi) // 2
    if check(mid):
        lo = mid
    else:
        hi = mid
print(lo)

-input = lambda: sys.stdin.readline().rstrip()

-# from heapq import heapify,heappop,heappush

-# from scipy.sparse.csgraph import floyd_warshall

-# from scipy.sparse.csgraph import csgraph_from_dense

-# from scipy.sparse.csgraph import dijkstra

-        if i >= R:  # 過去の結果が全く使えない

-            while R < n and s[R - L] == s[R]:

-        elif z[i - L] < R - i:  # 過去の結果が全て使える

-        else:  # 過去の結果が一部使える

-            while R < n and s[R - L] == s[R]:

-            ans = max(ans, min(j, z[j]))

+    for i in range(n - 2 * length + 1):

+        if s[i + length : i + 2 * length] in d:


Input:
W, H, N = list(map(int, input().split()))

graph = [[1] * W for _ in range(H)]

for _ in range(N):

    x, y, a = list(map(int, input().split()))

    if a == 1:

        for i in range(H):

            for j in range(x):

                graph[i][j] = 0

    if a == 2:

        for i in range(H):

            for j in range(x, W):

                graph[i][j] = 0

    if a == 3:

        for i in range(y):

            for j in range(W):

                graph[i][j] = 0

    if a == 4:

        for i in range(y, H):

            for j in range(W):

                graph[i][j] = 0

ans = sum([sum(line) for line in graph])

print(ans)

W, H, N = list(map(int, input().split()))

lx, rx, uy, dy = 0, W, H, 0

for i in range(N):

    x, y, a = list(map(int, input().split()))

    if a == 1:

        lx = max(lx, x)

    if a == 2:

        rx = min(rx, x)

    if a == 3:

        dy = max(dy, y)

    if a == 4:

        uy = min(uy, y)

# print(lx, rx, uy, dy)

print((max(0, uy - dy) * max(0, rx - lx)))

-ans = sum([sum(line) for line in graph])

+print((max(0, uy - dy) * max(0, rx - lx)))


Input:
def max2(x,y):

    return x if x > y else y

R, L, K = list(map(int, input().split()))

V = [[0]*R for _ in range(L)]

for _ in range(K):

    r, c, v = list(map(int, input().split()))

    V[c-1][r-1] = v

A, B, C, D = [[0]*(R+1) for _ in range(4)]

for i in range(L):

    for j in range(R):

        A[j] = max(A[j-1], B[j-1], C[j-1], D[j-1])

        v = V[i][j]

        if v != 0:

            D[j], C[j], B[j] = max2(C[j] + v, D[j]), max2(B[j] + v, C[j]), max2(A[j] + v, B[j])

print((max(A[-2], B[-2], C[-2], D[-2])))

import sys

input = sys.stdin.readline

R, L, K = list(map(int, input().split()))

V = [[0]*R for _ in range(L)]

for _ in range(K):

    r, c, v = list(map(int, input().split()))

    V[c-1][r-1] = v

A, B, C, D = [[0]*(R+1) for _ in range(4)]

for i in range(L):

    for j in range(R):

        A[j] = max(A[j-1],B[j-1],C[j-1],D[j-1])

        v = V[i][j]

        if v != 0:

            D[j], C[j], B[j] = max(C[j]+v,D[j]), max(B[j]+v,C[j]), max(A[j]+v,B[j])

print((max(A[-2],B[-2],C[-2],D[-2])))

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

R, L, K = list(map(int, input().split()))
V = [[0] * R for _ in range(L)]
for _ in range(K):
    r, c, v = list(map(int, input().split()))
    V[c - 1][r - 1] = v
A, B, C, D = [[0] * (R + 1) for _ in range(4)]
for i in range(L):
    for j in range(R):
        A[j] = max(A[j - 1], B[j - 1], C[j - 1], D[j - 1])
        v = V[i][j]
        if v != 0:
            D[j], C[j], B[j] = (
                max2(C[j] + v, D[j]),
                max2(B[j] + v, C[j]),
                max2(A[j] + v, B[j]),
            )
print((max(A[-2], B[-2], C[-2], D[-2])))

import sys

input = sys.stdin.readline
R, L, K = list(map(int, input().split()))
V = [[0] * R for _ in range(L)]
for _ in range(K):
    r, c, v = list(map(int, input().split()))
    V[c - 1][r - 1] = v
A, B, C, D = [[0] * (R + 1) for _ in range(4)]
for i in range(L):
    for j in range(R):
        A[j] = max(A[j - 1], B[j - 1], C[j - 1], D[j - 1])
        v = V[i][j]
        if v != 0:
            D[j], C[j], B[j] = (
                max(C[j] + v, D[j]),
                max(B[j] + v, C[j]),
                max(A[j] + v, B[j]),
            )
print((max(A[-2], B[-2], C[-2], D[-2])))

-def max2(x, y):
-    return x if x > y else y
+import sys
+input = sys.stdin.readline
-                max2(C[j] + v, D[j]),
-                max2(B[j] + v, C[j]),
-                max2(A[j] + v, B[j]),
+                max(C[j] + v, D[j]),
+                max(B[j] + v, C[j]),
+                max(A[j] + v, B[j]),


Input:
inf = 1000 * 1000 + 10

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

g = tuple([inf] * n for _ in range(n))

e = set()

for _ in range(m):

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

    a -= 1

    b -= 1

    g[a][b] = c

    g[b][a] = c

    e.add((a, b, c))

for i in range(n):

    g[i][i] = 0

for k in range(n):

    for i in range(n):

        for j in range(n):

            g[i][j] = min(g[i][j], g[i][k] + g[k][j])

# print(g)

need = set()

for a, b, c in e:

    for s in range(n):

        for t in range(n):

            if g[s][t] == g[s][a] + c + g[b][t]:

                need.add((a, b))

                break

        else:

            continue

        break

# print(need)

print((m - len(need)))

inf = 1000 * 1000 + 10

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

g = tuple([inf] * n for _ in range(n))

e = set()

for _ in range(m):

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

    a -= 1

    b -= 1

    g[a][b] = c

    g[b][a] = c

    e.add((a, b, c))

    e.add((b, a, c))

for i in range(n):

    g[i][i] = 0

for k in range(n):

    for i in range(n):

        for j in range(n):

            g[i][j] = min(g[i][j], g[i][k] + g[k][j])

res = 0

for a, b, c in e:

    for s in range(n):

        if g[s][b] == g[s][a] + c:

            res += 1

            break

print((m - res // 2))


Input:
# -*- coding: utf-8 -*-

# AtCoder Beginner Contest

# Problem B

if __name__ == '__main__':

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

    count = 1

    while count < 10001:

        if ((a * count) % b) == c:

            print('YES')

            exit()

        count += 1

    print('NO')

# -*- coding: utf-8 -*-

# AtCoder Beginner Contest

# Problem B

if __name__ == '__main__':

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

    count = 1

    while count < (b + 1):

        if ((a * count) % b) == c:

            print('YES')

            exit()

        count += 1

    print('NO')

# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem B
if __name__ == "__main__":
    a, b, c = list(map(int, input().split()))
    count = 1
    while count < 10001:
        if ((a * count) % b) == c:
            print("YES")
            exit()
        count += 1
    print("NO")

# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem B
if __name__ == "__main__":
    a, b, c = list(map(int, input().split()))
    count = 1
    while count < (b + 1):
        if ((a * count) % b) == c:
            print("YES")
            exit()
        count += 1
    print("NO")

-    while count < 10001:
+    while count < (b + 1):


Input:
x,y,a,b,c=list(map(int,input().split()))

p=list([['red',int(x)] for x in input().split()])

q=list([['green',int(x)] for x in input().split()])

r=list([['nan',int(x)] for x in input().split()])

p.sort(key=lambda x:x[1])

p=p[-x:]

q.sort(key=lambda x:x[1])

q=q[-y:]

p[len(p):len(p)]=q

p[len(p):len(p)]=r

p.sort(key=lambda x:x[1])

p=p[-x-y:]

print((sum([pi[1] for pi in p])))

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

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

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

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

p.sort()

p=p[-x:]

q.sort()

q=q[-y:]

p[len(p):len(p)]=q

p[len(p):len(p)]=r

p.sort()

p=p[-x-y:]

print((sum(p)))

x, y, a, b, c = list(map(int, input().split()))
p = list([["red", int(x)] for x in input().split()])
q = list([["green", int(x)] for x in input().split()])
r = list([["nan", int(x)] for x in input().split()])
p.sort(key=lambda x: x[1])
p = p[-x:]
q.sort(key=lambda x: x[1])
q = q[-y:]
p[len(p) : len(p)] = q
p[len(p) : len(p)] = r
p.sort(key=lambda x: x[1])
p = p[-x - y :]
print((sum([pi[1] for pi in p])))

x, y, a, b, c = list(map(int, input().split()))
p = list(map(int, input().split()))
q = list(map(int, input().split()))
r = list(map(int, input().split()))
p.sort()
p = p[-x:]
q.sort()
q = q[-y:]
p[len(p) : len(p)] = q
p[len(p) : len(p)] = r
p.sort()
p = p[-x - y :]
print((sum(p)))

-p = list([["red", int(x)] for x in input().split()])

-q = list([["green", int(x)] for x in input().split()])

-r = list([["nan", int(x)] for x in input().split()])


Input:
N = int(eval(input()))

R = [(-1, -1)] * N

for n in range(N):

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

    R[n] = (x, y)

B = [(-1, -1)] * N

for n in range(N):

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

    B[n] = (x, y)

B = sorted(B)

R = sorted(R, reverse=True)

ans = 0

for i, b in enumerate(B):

    tmp = []

    for j, r in enumerate(R):

        if r[0] == -1:

            continue

        if r[0] < b[0] and r[1] < b[1]:

            tmp.append((j, r))

    if tmp:

        tmp = sorted(tmp, key=lambda x: x[1][1], reverse=True)

        R[tmp[0][0]] = (-1, -1)

        ans += 1

print(ans)

N = int(eval(input()))

R = [tuple(map(int, input().split())) for _ in range(N)]

B = [tuple(map(int, input().split())) for _ in range(N)]

R = sorted(R)

B = sorted(B)

res = 0

for bx, by in B:

    idx = -1

    tmp = -1

    for i, (rx, ry) in enumerate(R):

        if rx < bx and ry < by:

            if ry >= tmp:

                tmp = ry

                idx = i

    if idx != -1:

        R.pop(idx)

        res += 1

print(res)

-    x, y = list(map(int, input().split()))

+R = [tuple(map(int, input().split())) for _ in range(N)]

+B = [tuple(map(int, input().split())) for _ in range(N)]

-        tmp = sorted(tmp, key=lambda x: x[1][1], reverse=True)


Input:
#conding utf-8

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

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

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

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

ab=[]

ans=[]

for i in range(len(a)):

  for j in range(len(b)):

    ab.append(a[i]+b[j])

ab.sort()

ab.reverse()

del ab[k:]

c.sort()

c.reverse()

for i in range(len(ab)):

  for j in range(len(c)):

    ans.append(ab[i]+c[j])

ans.sort()

ans.reverse()

for i in range(k):

  print((ans[i]))

#conding utf-8

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

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

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

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

a.sort()

b.sort()

c.sort()

a.reverse()

b.reverse()

c.reverse()

ans=[]

for i in range(len(a)):

  for j in range(len(b)):

    if (i+1)*(j+1)>K:

      break

    for k in range(len(c)):

      if (i+1)*(j+1)*(k+1)>K:

        break

      ans.append(a[i]+b[j]+c[k])

ans.sort()

ans.reverse()

for i in range(K):

  print((ans[i]))

# conding utf-8
x, y, z, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
ab = []
ans = []
for i in range(len(a)):
    for j in range(len(b)):
        ab.append(a[i] + b[j])
ab.sort()
ab.reverse()
del ab[k:]
c.sort()
c.reverse()
for i in range(len(ab)):
    for j in range(len(c)):
        ans.append(ab[i] + c[j])
ans.sort()
ans.reverse()
for i in range(k):
    print((ans[i]))

# conding utf-8
x, y, z, K = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
a.sort()
b.sort()
c.sort()
a.reverse()
b.reverse()
c.reverse()
ans = []
for i in range(len(a)):
    for j in range(len(b)):
        if (i + 1) * (j + 1) > K:
            break
        for k in range(len(c)):
            if (i + 1) * (j + 1) * (k + 1) > K:
                break
            ans.append(a[i] + b[j] + c[k])
ans.sort()
ans.reverse()
for i in range(K):
    print((ans[i]))

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

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

+            ans.append(a[i] + b[j] + c[k])


Input:
N = int(eval(input()))

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

A_sum = sum(A[1:])

tot = 0

for i in range(N-1):

    tot += (A[i]*A_sum)%(10**9+7)

    tot = tot%(10**9+7)

    A_sum -= A[i+1]

print(tot)

N = int(eval(input()))

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

s = [0]*(N+1)

for i in range(N):

    s[i+1] = s[i] + A[i]

cnt = 0

for j in range(N):

    cnt =  (cnt + (A[j]*(s[N] - s[j+1])))%(10**9+7)

print(cnt)

N = int(eval(input()))
A = list(map(int, input().split()))
A_sum = sum(A[1:])
tot = 0
for i in range(N - 1):
    tot += (A[i] * A_sum) % (10**9 + 7)
    tot = tot % (10**9 + 7)
    A_sum -= A[i + 1]
print(tot)

N = int(eval(input()))
A = list(map(int, input().split()))
s = [0] * (N + 1)
for i in range(N):
    s[i + 1] = s[i] + A[i]
cnt = 0
for j in range(N):
    cnt = (cnt + (A[j] * (s[N] - s[j + 1]))) % (10**9 + 7)
print(cnt)


Input:
import numpy as np

import scipy.sparse as sps

import scipy.misc as spm

import collections as col

import functools as func

import itertools as ite

import fractions as frac

import math as ma

import cmath as cma

import copy as cp

import sys

def sinput(): return sys.stdin.readline().strip()

def iinput(): return int(sinput())

def imap(): return list(map(int, sinput().split()))

def fmap(): return list(map(float, sinput().split()))

def iarr(n=0):

    if n: return [0 for _ in range(n)]

    else: return list(map())

def farr(): return list(fmap())

def sarr(n=0):

    if n: return ["" for _ in range(n)]

    else: return sinput().split()

sys.setrecursionlimit(10**7)

MOD = 10**9 + 7; EPS = sys.float_info.epsilon

PI = np.pi; EXP = np.e; INF = np.inf

n = iinput()

a = iarr()

cum = []; sum = 0

for num in a: sum += num; cum.append(sum)

ans = 1

now = 1

for i in range(n+1):

    next = min(2*(now - a[i]), cum[n]-cum[i])

    now = next

    if n==i and next<0 : ans = -1; break

    if n!=i and next<=0 : ans = -1; break

    ans += next

if a[n] > 2**n: ans = -1

print(ans)

import numpy as np

import scipy.sparse as sps

import scipy.misc as spm

import collections as col

import functools as func

import itertools as ite

import fractions as frac

import math as ma

import cmath as cma

import copy as cp

import sys

def sinput(): return sys.stdin.readline().strip()

def iinput(): return int(sinput())

def imap(): return list(map(int, sinput().split()))

def fmap(): return list(map(float, sinput().split()))

def iarr(n=0):

    if n: return [0 for _ in range(n)]

    else: return list(map())

def farr(): return list(fmap())

def sarr(n=0):

    if n: return ["" for _ in range(n)]

    else: return sinput().split()

sys.setrecursionlimit(10**7)

MOD = 10**9 + 7; EPS = sys.float_info.epsilon

PI = np.pi; EXP = np.e; INF = np.inf

n = iinput()

a = iarr()

cum = []; sum = 0

for num in a: sum += num; cum.append(sum)

ans = 1

now = 1

for i in range(n+1):

    next = min(2*(now - a[i]), cum[n]-cum[i])

    now = next

    if n==i and next<0 : ans = -1; break

    if n!=i and next<=0 : ans = -1; break

    ans += next

#if a[n] > 2**n: ans = -1

print(ans)

import numpy as np
import scipy.sparse as sps
import scipy.misc as spm
import collections as col
import functools as func
import itertools as ite
import fractions as frac
import math as ma
import cmath as cma
import copy as cp
import sys

def sinput():
    return sys.stdin.readline().strip()

def iinput():
    return int(sinput())

def imap():
    return list(map(int, sinput().split()))

def fmap():
    return list(map(float, sinput().split()))

def iarr(n=0):
    if n:
        return [0 for _ in range(n)]
    else:
        return list(map())

def farr():
    return list(fmap())

def sarr(n=0):
    if n:
        return ["" for _ in range(n)]
    else:
        return sinput().split()

sys.setrecursionlimit(10**7)
MOD = 10**9 + 7
EPS = sys.float_info.epsilon
PI = np.pi
EXP = np.e
INF = np.inf
n = iinput()
a = iarr()
cum = []
sum = 0
for num in a:
    sum += num
    cum.append(sum)
ans = 1
now = 1
for i in range(n + 1):
    next = min(2 * (now - a[i]), cum[n] - cum[i])
    now = next
    if n == i and next < 0:
        ans = -1
        break
    if n != i and next <= 0:
        ans = -1
        break
    ans += next
if a[n] > 2**n:
    ans = -1
print(ans)

import numpy as np
import scipy.sparse as sps
import scipy.misc as spm
import collections as col
import functools as func
import itertools as ite
import fractions as frac
import math as ma
import cmath as cma
import copy as cp
import sys

def sinput():
    return sys.stdin.readline().strip()

def iinput():
    return int(sinput())

def imap():
    return list(map(int, sinput().split()))

def fmap():
    return list(map(float, sinput().split()))

def iarr(n=0):
    if n:
        return [0 for _ in range(n)]
    else:
        return list(map())

def farr():
    return list(fmap())

def sarr(n=0):
    if n:
        return ["" for _ in range(n)]
    else:
        return sinput().split()

sys.setrecursionlimit(10**7)
MOD = 10**9 + 7
EPS = sys.float_info.epsilon
PI = np.pi
EXP = np.e
INF = np.inf
n = iinput()
a = iarr()
cum = []
sum = 0
for num in a:
    sum += num
    cum.append(sum)
ans = 1
now = 1
for i in range(n + 1):
    next = min(2 * (now - a[i]), cum[n] - cum[i])
    now = next
    if n == i and next < 0:
        ans = -1
        break
    if n != i and next <= 0:
        ans = -1
        break
    ans += next
# if a[n] > 2**n: ans = -1
print(ans)


Input:
from collections import Counter,defaultdict,deque

import sys,heapq,bisect,math,itertools,string,queue

sys.setrecursionlimit(10**8)

mod = 10**9+7

def inp(): return int(sys.stdin.readline())

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

def inpl_str(): return list(sys.stdin.readline().split())

def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n = inp()

a = inpl()

if n%2:

    for i in range(n)[::-2]:

        print(a[i],end=' ')

    for i in range(1,n)[::2]:

        print(a[i],end=' ')

    print()

else:

    for i in range(n)[::-2]:

        print(a[i],end=' ')

    for i in range(n)[::2]:

        print(a[i],end=' ')

    print()

from collections import Counter,defaultdict,deque

from heapq import heappop,heappush,heapify

import sys,bisect,math,itertools

sys.setrecursionlimit(10**8)

mod = 10**9+7

mod2 = 998244353

INF = float('inf')

def inp(): return int(sys.stdin.readline())

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

def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n = inp()

a = inpl()

for i in range(n-1,-1,-2):

    print((a[i]))

if n%2:

    j = 1

else:

    j = 0

for i in range(j,n,2):

    print((a[i]))

from collections import Counter, defaultdict, deque
import sys, heapq, bisect, math, itertools, string, queue

sys.setrecursionlimit(10**8)
mod = 10**9 + 7

def inp():
    return int(sys.stdin.readline())

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

def inpl_str():
    return list(sys.stdin.readline().split())

def inpln(n):
    return list(int(sys.stdin.readline()) for i in range(n))

n = inp()
a = inpl()
if n % 2:
    for i in range(n)[::-2]:
        print(a[i], end=" ")
    for i in range(1, n)[::2]:
        print(a[i], end=" ")
    print()
else:
    for i in range(n)[::-2]:
        print(a[i], end=" ")
    for i in range(n)[::2]:
        print(a[i], end=" ")
    print()

from collections import Counter, defaultdict, deque
from heapq import heappop, heappush, heapify
import sys, bisect, math, itertools

sys.setrecursionlimit(10**8)
mod = 10**9 + 7
mod2 = 998244353
INF = float("inf")

def inp():
    return int(sys.stdin.readline())

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

def inpln(n):
    return list(int(sys.stdin.readline()) for i in range(n))

n = inp()
a = inpl()
for i in range(n - 1, -1, -2):
    print((a[i]))
if n % 2:
    j = 1
else:
    j = 0
for i in range(j, n, 2):
    print((a[i]))

-import sys, heapq, bisect, math, itertools, string, queue

+from heapq import heappop, heappush, heapify

-    return list(sys.stdin.readline().split())


Input:
N = int(eval(input()))

L = [tuple(map(int, input().split())) for _ in range(N)]

xx, yy, hh = next(l for l in L if l[2] >= 1)

for Cx in range(101):

    for Cy in range(101):

        H = hh + abs(xx - Cx) + abs(yy - Cy)

        for x, y, h in L:

            if h != max(H - abs(x - Cx) - abs(y - Cy), 0):

                break

        else:

            print((Cx, Cy, H))

            quit()

def main():

    N = int(eval(input()))

    L = [tuple(map(int, input().split())) for _ in range(N)]

    xx, yy, hh = next(l for l in L if l[2] >= 1)

    for Cx in range(101):

        for Cy in range(101):

            H = hh + abs(xx - Cx) + abs(yy - Cy)

            for x, y, h in L:

                if h != max(H - abs(x - Cx) - abs(y - Cy), 0):

                    break

            else:

                print((Cx, Cy, H))

                quit()

main()

-L = [tuple(map(int, input().split())) for _ in range(N)]

-xx, yy, hh = next(l for l in L if l[2] >= 1)

-        H = hh + abs(xx - Cx) + abs(yy - Cy)

-            if h != max(H - abs(x - Cx) - abs(y - Cy), 0):

+    L = [tuple(map(int, input().split())) for _ in range(N)]

+    xx, yy, hh = next(l for l in L if l[2] >= 1)

+            H = hh + abs(xx - Cx) + abs(yy - Cy)

+                if h != max(H - abs(x - Cx) - abs(y - Cy), 0):


Input:
n = int(eval(input()))

if n == 1:

    print((0))

    exit()

F = {}

tmp = n

i = 2

while i**2 <= tmp:

    cnt = 0

    while tmp % i == 0:

        cnt += 1

        tmp //= i

    if cnt > 0:

        F[i] = cnt

    i += 1

if tmp != 1 or F == {}:

    F[tmp] = 1

ans = 0

for p in F:

    a = 1

    while F[p] >= a:

        F[p] -= a

        ans += 1

        a += 1

print(ans)

n = int(eval(input()))

ans = 0

i = 2

num = n

while i * i <= n:

  cnta = 0

  cntb = 0

  while num % i == 0:

    num //= i

    if cnta == cntb:

      ans += 1

      cnta = 0

      cntb += 1

    else:

      cnta += 1

  i += 1

if (ans == 0 and n != 1) or num != 1:

  ans += 1

print(ans)

-if n == 1:
-    print((0))
-    exit()
-F = {}
-tmp = n
+ans = 0
-while i**2 <= tmp:
-    cnt = 0
-    while tmp % i == 0:
-        cnt += 1
-        tmp //= i
-    if cnt > 0:
-        F[i] = cnt
+num = n
+while i * i <= n:
+    cnta = 0
+    cntb = 0
+    while num % i == 0:
+        num //= i
+        if cnta == cntb:
+            ans += 1
+            cnta = 0
+            cntb += 1
+        else:
+            cnta += 1
-if tmp != 1 or F == {}:
-    F[tmp] = 1
-ans = 0
-for p in F:
-    a = 1
-    while F[p] >= a:
-        F[p] -= a
-        ans += 1
-        a += 1
+if (ans == 0 and n != 1) or num != 1:
+    ans += 1


Input:
import numpy as np

N, W = list(map(int, input().split()))

wv = [list(map(int, input().split())) for _ in range(N)]

INF = 10 ** 18

V_MAX = 10 ** 3 * N

dp = np.full(V_MAX + 1, INF)

dp[0] = 0

for w, v in wv:

    dp[v:] = np.minimum(dp[v:], dp[:-v] + w)

ans = 0

for i in range(V_MAX, -1, -1):

    if dp[i] <= W:

        ans = i

        break

print(ans)

import numpy as np

N, W = list(map(int, input().split()))

wv = [list(map(int, input().split())) for _ in range(N)]

INF = 10 ** 18

V_MAX = 10 ** 3 * N

dp = np.full(V_MAX + 1, INF)

dp[0] = 0

for w, v in wv:

    dp[v:] = np.minimum(dp[v:], dp[:-v] + w)

ans = np.where(dp <= W)[0].max()

print(ans)

import numpy as np

N, W = list(map(int, input().split()))
wv = [list(map(int, input().split())) for _ in range(N)]
INF = 10**18
V_MAX = 10**3 * N
dp = np.full(V_MAX + 1, INF)
dp[0] = 0
for w, v in wv:
    dp[v:] = np.minimum(dp[v:], dp[:-v] + w)
ans = 0
for i in range(V_MAX, -1, -1):
    if dp[i] <= W:
        ans = i
        break
print(ans)

import numpy as np

N, W = list(map(int, input().split()))
wv = [list(map(int, input().split())) for _ in range(N)]
INF = 10**18
V_MAX = 10**3 * N
dp = np.full(V_MAX + 1, INF)
dp[0] = 0
for w, v in wv:
    dp[v:] = np.minimum(dp[v:], dp[:-v] + w)
ans = np.where(dp <= W)[0].max()
print(ans)

-ans = 0
-for i in range(V_MAX, -1, -1):
-    if dp[i] <= W:
-        ans = i
-        break
+ans = np.where(dp <= W)[0].max()


Input:
from collections import deque

N = int(eval(input()))

S = list(eval(input()))

T = deque(S[:])

ins = []

pointer = 0

a = 0

for i in range(N):

  if S[i] == ')':

    if pointer >= 1:

      pointer -= 1

    else:

      T.appendleft('(')

  else:

    pointer += 1

a = 0

b = 0

for t in T:

  if t == ')':

    b += 1

  else:

    a += 1

for i in range(max(a-b, 0)):

  T.append(')')

print((''.join(T)))

N = int(eval(input()))

S = list(eval(input()))

a = 0 # (

b = 0 # )

for i in range(N):

  if S[i] == '(':

    a += 1

  else:

    if a > 0:

      a -= 1

    else:

      b += 1

ans = "".join(S)

if b > 0:

  ans = "("*b + ans

if a > 0:

  ans = ans + ")"*a

print(ans)

from collections import deque

N = int(eval(input()))
S = list(eval(input()))
T = deque(S[:])
ins = []
pointer = 0
a = 0
for i in range(N):
    if S[i] == ")":
        if pointer >= 1:
            pointer -= 1
        else:
            T.appendleft("(")
    else:
        pointer += 1
a = 0
b = 0
for t in T:
    if t == ")":
        b += 1
    else:
        a += 1
for i in range(max(a - b, 0)):
    T.append(")")
print(("".join(T)))

N = int(eval(input()))
S = list(eval(input()))
a = 0  # (
b = 0  # )
for i in range(N):
    if S[i] == "(":
        a += 1
    else:
        if a > 0:
            a -= 1
        else:
            b += 1
ans = "".join(S)
if b > 0:
    ans = "(" * b + ans
if a > 0:
    ans = ans + ")" * a
print(ans)

-from collections import deque
-T = deque(S[:])
-ins = []
-pointer = 0
-a = 0
+a = 0  # (
+b = 0  # )
-    if S[i] == ")":
-        if pointer >= 1:
-            pointer -= 1
+    if S[i] == "(":
+        a += 1
+    else:
+        if a > 0:
+            a -= 1
-            T.appendleft("(")
-    else:
-        pointer += 1
-a = 0
-b = 0
-for t in T:
-    if t == ")":
-        b += 1
-    else:
-        a += 1
-for i in range(max(a - b, 0)):
-    T.append(")")
-print(("".join(T)))
+            b += 1
+ans = "".join(S)
+if b > 0:
+    ans = "(" * b + ans
+if a > 0:
+    ans = ans + ")" * a
+print(ans)


Input:
n,m,q = list(map(int,input().split()))

lr = [[0 for i in range(n+1)] for j in range(n+1)]

#lr = [[int(i) for i in input().split()]for j in range(m)]

st = [0] * (n+1)

ed = [0] * (n+1)

for i in range(m):

    l,r = list(map(int,input().split()))

    lr[l][r] += 1

pq = [[int(i) for i in input().split()]for j in range(q)]

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

#print(lr)

for i in range(1,n+1):

    #print(i)

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

        #print(i,j)

        dp[i][j] = dp[i][j-1]+lr[i][j]

for i in range(q):

    st = pq[i][0]

    ed = pq[i][1]

    tmp = 0

    for j in range(ed-st+1):

        tmp += dp[st+j][ed]

    print(tmp)

#print(dp)

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

lr = [[0 for i in range(n+1)] for j in range(n+1)]

for i in range(m):

    l,r = list(map(int,input().split()))

    lr[l][r] += 1

pq = [[int(i) for i in input().split()]for j in range(q)]

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

for i in range(1,n+1):

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

        dp[i][j] = dp[i][j-1]+lr[i][j]

ans_dp = [[0 for i in range(n+1)] for j in range(n+1)]

for i in range(1,n+1):

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

        tmp = 0

        for k in range(j-i+1):

            tmp += dp[i+k][j]

        ans_dp[i][j] = tmp

for i in range(q):

    print((ans_dp[pq[i][0]][pq[i][1]]))

n, m, q = list(map(int, input().split()))
lr = [[0 for i in range(n + 1)] for j in range(n + 1)]
# lr = [[int(i) for i in input().split()]for j in range(m)]
st = [0] * (n + 1)
ed = [0] * (n + 1)
for i in range(m):
    l, r = list(map(int, input().split()))
    lr[l][r] += 1
pq = [[int(i) for i in input().split()] for j in range(q)]
dp = [[0 for i in range(n + 1)] for j in range(n + 1)]
# print(lr)
for i in range(1, n + 1):
    # print(i)
    for j in range(i, n + 1):
        # print(i,j)
        dp[i][j] = dp[i][j - 1] + lr[i][j]
for i in range(q):
    st = pq[i][0]
    ed = pq[i][1]
    tmp = 0
    for j in range(ed - st + 1):
        tmp += dp[st + j][ed]
    print(tmp)
# print(dp)

n, m, q = list(map(int, input().split()))
lr = [[0 for i in range(n + 1)] for j in range(n + 1)]
for i in range(m):
    l, r = list(map(int, input().split()))
    lr[l][r] += 1
pq = [[int(i) for i in input().split()] for j in range(q)]
dp = [[0 for i in range(n + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
    for j in range(i, n + 1):
        dp[i][j] = dp[i][j - 1] + lr[i][j]
ans_dp = [[0 for i in range(n + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
    for j in range(i, n + 1):
        tmp = 0
        for k in range(j - i + 1):
            tmp += dp[i + k][j]
        ans_dp[i][j] = tmp
for i in range(q):
    print((ans_dp[pq[i][0]][pq[i][1]]))

-# lr = [[int(i) for i in input().split()]for j in range(m)]

+ans_dp = [[0 for i in range(n + 1)] for j in range(n + 1)]


Input:
from sys import stdin

n,a,b = [int(x) for x in stdin.readline().rstrip().split()]

while True:

    if a+1 != b:

        a += 1

    else:

        print("Borys")

        exit()

    if b-1 != a:

        b -= 1

    else:

        print("Alice")

        exit()

from sys import stdin

n,a,b = [int(x) for x in stdin.readline().rstrip().split()]

if (b-a)%2 == 1:

    print("Borys")

else:

    print("Alice")

from sys import stdin

n, a, b = [int(x) for x in stdin.readline().rstrip().split()]
while True:
    if a + 1 != b:
        a += 1
    else:
        print("Borys")
        exit()
    if b - 1 != a:
        b -= 1
    else:
        print("Alice")
        exit()

from sys import stdin

n, a, b = [int(x) for x in stdin.readline().rstrip().split()]
if (b - a) % 2 == 1:
    print("Borys")
else:
    print("Alice")

-while True:
-    if a + 1 != b:
-        a += 1
-    else:
-        print("Borys")
-        exit()
-    if b - 1 != a:
-        b -= 1
-    else:
-        print("Alice")
-        exit()
+if (b - a) % 2 == 1:
+    print("Borys")
+else:
+    print("Alice")


Input:
k, s = list(map(int, input().split()))

ans = 0

for x in range(s + 1):

  for y in range(s - x + 1):

    z = s - x - y

    if x <= k and y <= k and z <= k:

      ans += 1

print(ans)

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

ans = 0

for x in range(k+1):

    for y in range(k+1):

        z = (s-(x+y))

        if 0 <= z and z <= k:

            ans += 1

print(ans)

k, s = list(map(int, input().split()))
ans = 0
for x in range(k + 1):
    for y in range(k + 1):
        z = s - (x + y)
        if 0 <= z and z <= k:
            ans += 1
print(ans)

-        if x <= k and y <= k and z <= k:


Input:
N=str(eval(input()))

if int(N[0])==7:

    print("Yes")

elif int(N[1])==7:

    print("Yes")

elif int(N[2])==7:

    print("Yes")

else:

    print("No")

N=str(eval(input()))

if int(N[0])==7 or int(N[1])==7 or int(N[2])==7:

    print("Yes")

else:

    print("No")

N = str(eval(input()))
if int(N[0]) == 7:
    print("Yes")
elif int(N[1]) == 7:
    print("Yes")
elif int(N[2]) == 7:
    print("Yes")
else:
    print("No")

N = str(eval(input()))
if int(N[0]) == 7 or int(N[1]) == 7 or int(N[2]) == 7:
    print("Yes")
else:
    print("No")


Input:
import sys

import numpy as np

from numba import njit

read = sys.stdin.buffer.read

readline = sys.stdin.buffer.readline

readlines = sys.stdin.buffer.readlines

INF = 10**9 + 1

def precompute(N, M, data):

    data = data.reshape(-1, 3)

    A, B, C = data[:N].T

    D, E, F = data[N:].T

    X = np.unique(np.concatenate([A, B, D, [0, -INF, INF]]))

    Y = np.unique(np.concatenate([C, E, F, [0, -INF, INF]]))

    A = np.searchsorted(X, A)

    B = np.searchsorted(X, B)

    D = np.searchsorted(X, D)

    C = np.searchsorted(Y, C)

    E = np.searchsorted(Y, E)

    F = np.searchsorted(Y, F)

    return A, B, C, D, E, F, X, Y

@njit('(i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8,i8)', cache=True)

def set_ng(A, B, C, D, E, F, H, W):

    ng = np.zeros((H * W, 4), np.bool_)

    for i in range(len(A)):

        for x in range(A[i], B[i]):

            v = x * W + C[i]

            ng[v][1] = 1

            ng[v - 1][0] = 1

    for i in range(len(D)):

        for y in range(E[i], F[i]):

            v = D[i] * W + y

            ng[v][3] = 1

            ng[v - W][2] = 1

    return ng

@njit('(i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:])', cache=True)

def solve(A, B, C, D, E, F, X, Y):

    H, W = len(X), len(Y)

    N = H * W

    DX = X[1:] - X[:-1]

    DY = Y[1:] - Y[:-1]

    ng = set_ng(A, B, C, D, E, F, H, W)

    x0, y0 = np.searchsorted(X, 0), np.searchsorted(Y, 0)

    v0 = x0 * W + y0

    visited = np.zeros(N, np.bool_)

    visited[v0] = 1

    stack = np.empty(N, np.int32)

    p = 0

    ret = 0

    def area(x):

        x, y = divmod(x, W)

        return DX[x] * DY[y]

    def push(x):

        nonlocal p, ret

        stack[p] = x

        visited[x] = 1

        ret += area(x)

        p += 1

    def pop():

        nonlocal p

        p -= 1

        return stack[p]

    push(v0)

    move = (1, -1, W, -W)

    while p:

        v = pop()

        for i in range(4):

            if ng[v][i]:

                continue

            w = v + move[i]

            if visited[w]:

                continue

            x, y = divmod(w, W)

            if x == 0 or x == H - 1 or y == 0 or y == W - 1:

                return 0

            push(w)

    return ret

N, M = list(map(int, readline().split()))

data = np.int64(read().split())

x = solve(*precompute(N, M, data))

if x == 0:

    print('INF')

else:

    print(x)

import sys

import numpy as np

from numba import njit

read = sys.stdin.buffer.read

readline = sys.stdin.buffer.readline

readlines = sys.stdin.buffer.readlines

INF = 10**9 + 1

def precompute(N, M, data):

    data = data.reshape(-1, 3)

    A, B, C = data[:N].T

    D, E, F = data[N:].T

    X = np.unique(np.concatenate([A, B, D, [0, -INF, INF]]))

    Y = np.unique(np.concatenate([C, E, F, [0, -INF, INF]]))

    A = np.searchsorted(X, A)

    B = np.searchsorted(X, B)

    D = np.searchsorted(X, D)

    C = np.searchsorted(Y, C)

    E = np.searchsorted(Y, E)

    F = np.searchsorted(Y, F)

    return A, B, C, D, E, F, X, Y

@njit('(i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:])', cache=True)

def solve(A, B, C, D, E, F, X, Y):

    H, W = len(X), len(Y)

    N = H * W

    DX = X[1:] - X[:-1]

    DY = Y[1:] - Y[:-1]

    def set_ng(A, B, C, D, E, F, H, W):

        ng = np.zeros((H * W, 4), np.bool_)

        for i in range(len(A)):

            for x in range(A[i], B[i]):

                v = x * W + C[i]

                ng[v][1] = 1

                ng[v - 1][0] = 1

        for i in range(len(D)):

            for y in range(E[i], F[i]):

                v = D[i] * W + y

                ng[v][3] = 1

                ng[v - W][2] = 1

        return ng

    ng = set_ng(A, B, C, D, E, F, H, W)

    x0, y0 = np.searchsorted(X, 0), np.searchsorted(Y, 0)

    v0 = x0 * W + y0

    visited = np.zeros(N, np.bool_)

    visited[v0] = 1

    stack = np.empty(N, np.int32)

    p = 0

    ret = 0

    def area(x):

        x, y = divmod(x, W)

        return DX[x] * DY[y]

    def push(x):

        nonlocal p, ret

        stack[p] = x

        visited[x] = 1

        ret += area(x)

        p += 1

    def pop():

        nonlocal p

        p -= 1

        return stack[p]

    push(v0)

    move = (1, -1, W, -W)

    while p:

        v = pop()

        for i in range(4):

            if ng[v][i]:

                continue

            w = v + move[i]

            if visited[w]:

                continue

            x, y = divmod(w, W)

            if x == 0 or x == H - 1 or y == 0 or y == W - 1:

                return 0

            push(w)

    return ret

N, M = list(map(int, readline().split()))

data = np.int64(read().split())

x = solve(*precompute(N, M, data))

if x == 0:

    print('INF')

else:

    print(x)

import sys
import numpy as np
from numba import njit

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
INF = 10**9 + 1

def precompute(N, M, data):
    data = data.reshape(-1, 3)
    A, B, C = data[:N].T
    D, E, F = data[N:].T
    X = np.unique(np.concatenate([A, B, D, [0, -INF, INF]]))
    Y = np.unique(np.concatenate([C, E, F, [0, -INF, INF]]))
    A = np.searchsorted(X, A)
    B = np.searchsorted(X, B)
    D = np.searchsorted(X, D)
    C = np.searchsorted(Y, C)
    E = np.searchsorted(Y, E)
    F = np.searchsorted(Y, F)
    return A, B, C, D, E, F, X, Y

@njit("(i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8,i8)", cache=True)
def set_ng(A, B, C, D, E, F, H, W):
    ng = np.zeros((H * W, 4), np.bool_)
    for i in range(len(A)):
        for x in range(A[i], B[i]):
            v = x * W + C[i]
            ng[v][1] = 1
            ng[v - 1][0] = 1
    for i in range(len(D)):
        for y in range(E[i], F[i]):
            v = D[i] * W + y
            ng[v][3] = 1
            ng[v - W][2] = 1
    return ng

@njit("(i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:])", cache=True)
def solve(A, B, C, D, E, F, X, Y):
    H, W = len(X), len(Y)
    N = H * W
    DX = X[1:] - X[:-1]
    DY = Y[1:] - Y[:-1]
    ng = set_ng(A, B, C, D, E, F, H, W)
    x0, y0 = np.searchsorted(X, 0), np.searchsorted(Y, 0)
    v0 = x0 * W + y0
    visited = np.zeros(N, np.bool_)
    visited[v0] = 1
    stack = np.empty(N, np.int32)
    p = 0
    ret = 0

    def area(x):
        x, y = divmod(x, W)
        return DX[x] * DY[y]

    def push(x):
        nonlocal p, ret
        stack[p] = x
        visited[x] = 1
        ret += area(x)
        p += 1

    def pop():
        nonlocal p
        p -= 1
        return stack[p]

    push(v0)
    move = (1, -1, W, -W)
    while p:
        v = pop()
        for i in range(4):
            if ng[v][i]:
                continue
            w = v + move[i]
            if visited[w]:
                continue
            x, y = divmod(w, W)
            if x == 0 or x == H - 1 or y == 0 or y == W - 1:
                return 0
            push(w)
    return ret

N, M = list(map(int, readline().split()))
data = np.int64(read().split())
x = solve(*precompute(N, M, data))
if x == 0:
    print("INF")
else:
    print(x)

import sys
import numpy as np
from numba import njit

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
INF = 10**9 + 1

def precompute(N, M, data):
    data = data.reshape(-1, 3)
    A, B, C = data[:N].T
    D, E, F = data[N:].T
    X = np.unique(np.concatenate([A, B, D, [0, -INF, INF]]))
    Y = np.unique(np.concatenate([C, E, F, [0, -INF, INF]]))
    A = np.searchsorted(X, A)
    B = np.searchsorted(X, B)
    D = np.searchsorted(X, D)
    C = np.searchsorted(Y, C)
    E = np.searchsorted(Y, E)
    F = np.searchsorted(Y, F)
    return A, B, C, D, E, F, X, Y

@njit("(i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:])", cache=True)
def solve(A, B, C, D, E, F, X, Y):
    H, W = len(X), len(Y)
    N = H * W
    DX = X[1:] - X[:-1]
    DY = Y[1:] - Y[:-1]

    def set_ng(A, B, C, D, E, F, H, W):
        ng = np.zeros((H * W, 4), np.bool_)
        for i in range(len(A)):
            for x in range(A[i], B[i]):
                v = x * W + C[i]
                ng[v][1] = 1
                ng[v - 1][0] = 1
        for i in range(len(D)):
            for y in range(E[i], F[i]):
                v = D[i] * W + y
                ng[v][3] = 1
                ng[v - W][2] = 1
        return ng

    ng = set_ng(A, B, C, D, E, F, H, W)
    x0, y0 = np.searchsorted(X, 0), np.searchsorted(Y, 0)
    v0 = x0 * W + y0
    visited = np.zeros(N, np.bool_)
    visited[v0] = 1
    stack = np.empty(N, np.int32)
    p = 0
    ret = 0

    def area(x):
        x, y = divmod(x, W)
        return DX[x] * DY[y]

    def push(x):
        nonlocal p, ret
        stack[p] = x
        visited[x] = 1
        ret += area(x)
        p += 1

    def pop():
        nonlocal p
        p -= 1
        return stack[p]

    push(v0)
    move = (1, -1, W, -W)
    while p:
        v = pop()
        for i in range(4):
            if ng[v][i]:
                continue
            w = v + move[i]
            if visited[w]:
                continue
            x, y = divmod(w, W)
            if x == 0 or x == H - 1 or y == 0 or y == W - 1:
                return 0
            push(w)
    return ret

N, M = list(map(int, readline().split()))
data = np.int64(read().split())
x = solve(*precompute(N, M, data))
if x == 0:
    print("INF")
else:
    print(x)

-    ng = np.zeros((H * W, 4), np.bool_)

+    def set_ng(A, B, C, D, E, F, H, W):

+        ng = np.zeros((H * W, 4), np.bool_)

+            for x in range(A[i], B[i]):

+            for y in range(E[i], F[i]):


Input:
n = int(eval(input()))

xy = [tuple(map(int, input().split())) for _ in range(n)]

s_xy = set(xy)

count = 0

for i in range(n-1):

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

        ix, iy = xy[i]

        jx, jy = xy[j]

        p = jx - ix

        q = jy - iy

        tc = sum((x-p,y-q) in xy for x, y in s_xy)

        count = max(count, tc)

print((n-count))

#https://atcoder.jp/contests/diverta2019-2/submissions/11229318

n = int(eval(input()))

t = [tuple(map(int, input().split())) for _ in range(n)]

s = set(t)

cnt = 0

for i in range(n-1):

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

    u,v = t[i]

    x,y = t[j]

    p = u-x; q = v-y

    c = sum((x-p, y-q) in s for x,y in t)

    if cnt < c: cnt = c

print((n-cnt))

n = int(eval(input()))
xy = [tuple(map(int, input().split())) for _ in range(n)]
s_xy = set(xy)
count = 0
for i in range(n - 1):
    for j in range(i + 1, n):
        ix, iy = xy[i]
        jx, jy = xy[j]
        p = jx - ix
        q = jy - iy
        tc = sum((x - p, y - q) in xy for x, y in s_xy)
        count = max(count, tc)
print((n - count))

# https://atcoder.jp/contests/diverta2019-2/submissions/11229318
n = int(eval(input()))
t = [tuple(map(int, input().split())) for _ in range(n)]
s = set(t)
cnt = 0
for i in range(n - 1):
    for j in range(i + 1, n):
        u, v = t[i]
        x, y = t[j]
        p = u - x
        q = v - y
        c = sum((x - p, y - q) in s for x, y in t)
        if cnt < c:
            cnt = c
print((n - cnt))

-xy = [tuple(map(int, input().split())) for _ in range(n)]

+t = [tuple(map(int, input().split())) for _ in range(n)]

-        tc = sum((x - p, y - q) in xy for x, y in s_xy)

+        c = sum((x - p, y - q) in s for x, y in t)