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

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

li = []

for i in range(N):

    if i == 1:

        cadA = A[N-1] - A[0]

    else:

        cadA = K - A[i] + A[i-1]

    if i == N-1:

        cadB = A[N-1] - A[0]

        cadB = 100000000000

    else:

        cadB = A[i] + (K - A[i+1])

        cadB = 100000000000

    li.append(min(cadA, cadB))

print((min(li)))

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

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

distance = [0] * N

for i in range(N):

    if not i == N-1:

        distance[i] =  A[i+1] - A[i]

    else:

        distance[N-1] = A[0] + (K - A[N-1])

distance.sort()

distance.pop()

print((sum(distance)))

K, N = list(map(int, input().split()))
A = list(map(int, input().split()))
li = []
for i in range(N):
    if i == 1:
        cadA = A[N - 1] - A[0]
    else:
        cadA = K - A[i] + A[i - 1]
    if i == N - 1:
        cadB = A[N - 1] - A[0]
        cadB = 100000000000
    else:
        cadB = A[i] + (K - A[i + 1])
        cadB = 100000000000
    li.append(min(cadA, cadB))
print((min(li)))

K, N = list(map(int, input().split()))
A = list(map(int, input().split()))
distance = [0] * N
for i in range(N):
    if not i == N - 1:
        distance[i] = A[i + 1] - A[i]
    else:
        distance[N - 1] = A[0] + (K - A[N - 1])
distance.sort()
distance.pop()
print((sum(distance)))


Input:
import sys

N = eval(input())

TA = eval(input())

T, A = TA.split()

Hinp = eval(input())

H = Hinp.split()

ansnum = None

ans = 0

def getdiff(A, ans):

    return abs(max(ans, A) - min(ans, A))

def chk(A, _ans, ans):

    new_d, old_d = getdiff(A, _ans), getdiff(A, ans)

    if new_d < old_d:

        return True

    return False

for i, x in enumerate(H):

    _ans = int(T) - int(x) * 0.006

    if _ans == A:

        break

    if not ansnum or chk(int(A), _ans, ansnum):

        ans = i+1

        ansnum = _ans

print(ans)

import sys

N = eval(input())

TA = eval(input())

T, A = TA.split()

Hinp = eval(input())

H = Hinp.split()

ansnum = None

ans = 0

def getdiff(A, ans):

    return abs(max(ans, A) - min(ans, A))

def chk(A, _ans, ans):

    new_d, old_d = getdiff(A, _ans), getdiff(A, ans)

    if new_d < old_d:

        return True

    return False

def showans(ans):

    print(ans)

    sys.exit()

for i, x in enumerate(H):

    _ans = int(T) - int(x) * 0.006

    if _ans == A:

        showans(i+1)

    if not ansnum or chk(int(A), _ans, ansnum):

        ans = i+1

        ansnum = _ans

showans(ans)

import sys

N = eval(input())
TA = eval(input())
T, A = TA.split()
Hinp = eval(input())
H = Hinp.split()
ansnum = None
ans = 0

def getdiff(A, ans):
    return abs(max(ans, A) - min(ans, A))

def chk(A, _ans, ans):
    new_d, old_d = getdiff(A, _ans), getdiff(A, ans)
    if new_d < old_d:
        return True
    return False

for i, x in enumerate(H):
    _ans = int(T) - int(x) * 0.006
    if _ans == A:
        break
    if not ansnum or chk(int(A), _ans, ansnum):
        ans = i + 1
        ansnum = _ans
print(ans)

import sys

N = eval(input())
TA = eval(input())
T, A = TA.split()
Hinp = eval(input())
H = Hinp.split()
ansnum = None
ans = 0

def getdiff(A, ans):
    return abs(max(ans, A) - min(ans, A))

def chk(A, _ans, ans):
    new_d, old_d = getdiff(A, _ans), getdiff(A, ans)
    if new_d < old_d:
        return True
    return False

def showans(ans):
    print(ans)
    sys.exit()

for i, x in enumerate(H):
    _ans = int(T) - int(x) * 0.006
    if _ans == A:
        showans(i + 1)
    if not ansnum or chk(int(A), _ans, ansnum):
        ans = i + 1
        ansnum = _ans
showans(ans)

+def showans(ans):
+    print(ans)
+    sys.exit()
+
+
-        break
+        showans(i + 1)
-print(ans)
+showans(ans)


Input:
from math import ceil

def main():

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

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

    def is_ok(arg):

    # 条件を満たすかどうか？問題ごとに定義

        B = [int(ceil(a/arg))-1 for a in A]

        #print(arg, B)

        if sum(B) <= K:

            return True

        else:

            return False

    def meguru_bisect(ng, ok):

        '''

        初期値のng,okを受け取り,is_okを満たす最小(最大)のokを返す

        まずis_okを定義すべし

        ng ok は  とり得る最小の値-1 とり得る最大の値+1

        最大最小が逆の場合はよしなにひっくり返す

        '''

        while (abs(ok - ng) > 1):

            mid = (ok + ng) // 2

            if is_ok(mid):

                ok = mid

            else:

                ng = mid

        return ok

    ans = meguru_bisect(0, int(1e20))

    print(ans)

if __name__ == "__main__":

    main()

from math import ceil

def main():

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

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

    def is_ok(arg):

    # 条件を満たすかどうか？問題ごとに定義

        B = [int(ceil(a/arg))-1 for a in A]

        #print(arg, B)

        if sum(B) <= K:

            return True

        else:

            return False

    def meguru_bisect(ng, ok):

        '''

        初期値のng,okを受け取り,is_okを満たす最小(最大)のokを返す

        まずis_okを定義すべし

        ng ok は  とり得る最小の値-1 とり得る最大の値+1

        最大最小が逆の場合はよしなにひっくり返す

        '''

        while (abs(ok - ng) > 1):

            mid = (ok + ng) // 2

            if is_ok(mid):

                ok = mid

            else:

                ng = mid

        return ok

    ans = meguru_bisect(0, int(1e9))

    print(ans)

if __name__ == "__main__":

    main()

from math import ceil

def main():
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))

    def is_ok(arg):
        # 条件を満たすかどうか？問題ごとに定義
        B = [int(ceil(a / arg)) - 1 for a in A]
        # print(arg, B)
        if sum(B) <= K:
            return True
        else:
            return False

    def meguru_bisect(ng, ok):
        """
        初期値のng,okを受け取り,is_okを満たす最小(最大)のokを返す
        まずis_okを定義すべし
        ng ok は  とり得る最小の値-1 とり得る最大の値+1
        最大最小が逆の場合はよしなにひっくり返す
        """
        while abs(ok - ng) > 1:
            mid = (ok + ng) // 2
            if is_ok(mid):
                ok = mid
            else:
                ng = mid
        return ok

    ans = meguru_bisect(0, int(1e20))
    print(ans)

if __name__ == "__main__":
    main()

from math import ceil

def main():
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))

    def is_ok(arg):
        # 条件を満たすかどうか？問題ごとに定義
        B = [int(ceil(a / arg)) - 1 for a in A]
        # print(arg, B)
        if sum(B) <= K:
            return True
        else:
            return False

    def meguru_bisect(ng, ok):
        """
        初期値のng,okを受け取り,is_okを満たす最小(最大)のokを返す
        まずis_okを定義すべし
        ng ok は  とり得る最小の値-1 とり得る最大の値+1
        最大最小が逆の場合はよしなにひっくり返す
        """
        while abs(ok - ng) > 1:
            mid = (ok + ng) // 2
            if is_ok(mid):
                ok = mid
            else:
                ng = mid
        return ok

    ans = meguru_bisect(0, int(1e9))
    print(ans)

if __name__ == "__main__":
    main()

-    ans = meguru_bisect(0, int(1e20))
+    ans = meguru_bisect(0, int(1e9))


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

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

a = sorted(a)

li = [[a[0],1]]

for i in range(1,n):

  if a[i] != a[i-1]:

    li.append([a[i],1])

  else:

    li[len(li)-1][1]+=1

ans = 0

for i in range(len(li)):

  ans_tmp =li[i][1]

  if 0<=i-1:

    if li[i-1][0]+1  == li[i][0]:

      ans_tmp = ans_tmp +li[i-1][1]

  if i+1<len(li):

    if li[i+1][0]-1  == li[i][0]:

      ans_tmp = ans_tmp +li[i+1][1]

  ans = max(ans,ans_tmp)

print(ans)

from collections import defaultdict

n = int(eval(input()))

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

cnt = defaultdict(int)

for num in a:

    for i in [-1, 0, 1]:

        cnt[num + i] += 1

ans = 0

for i in cnt:

    ans = max(cnt[i], ans)

print(ans)

n = int(eval(input()))
a = list(map(int, input().split()))
a = sorted(a)
li = [[a[0], 1]]
for i in range(1, n):
    if a[i] != a[i - 1]:
        li.append([a[i], 1])
    else:
        li[len(li) - 1][1] += 1
ans = 0
for i in range(len(li)):
    ans_tmp = li[i][1]
    if 0 <= i - 1:
        if li[i - 1][0] + 1 == li[i][0]:
            ans_tmp = ans_tmp + li[i - 1][1]
    if i + 1 < len(li):
        if li[i + 1][0] - 1 == li[i][0]:
            ans_tmp = ans_tmp + li[i + 1][1]
    ans = max(ans, ans_tmp)
print(ans)

-            ans_tmp = ans_tmp + li[i - 1][1]

-            ans_tmp = ans_tmp + li[i + 1][1]


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

xyz = [list(map(int, input().split())) for _i in range(n)]

r = []

for i in range(2**3):

    checker = []

    num = i

    for _i in range(3):

        if num%2==1:

            checker.append(1)

        else:

            checker.append(-1)

        num >>= 1

    _xyz = []

    for j in range(n):

        _abc = [checker[s]*xyz[j][s] for s in range(3)]

        _xyz.append([sum(_abc)]+_abc)

    _xyz.sort(reverse=True)

    _r = abs(sum(i[1] for i in _xyz[:m]))

    _r += abs(sum(i[2] for i in _xyz[:m]))

    _r += abs(sum(i[3] for i in _xyz[:m]))

    r.append(_r)

print((max(r)))

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

xyz = [list(map(int, input().split())) for _i in range(n)]

r = []

for i in range(2**3):

    checker = []

    num = i

    for _i in range(3):

        if num%2==1:

            checker.append(1)

        else:

            checker.append(-1)

        num >>= 1

    _xyz = []

    for j in range(n):

        _abc = [checker[s]*xyz[j][s] for s in range(3)]

        _xyz.append([sum(_abc)]+_abc)

    _xyz.sort(reverse=True)

    _r = abs(sum(i[1] for i in _xyz[:m]))+ abs(sum(i[2] for i in _xyz[:m]))+abs(sum(i[3] for i in _xyz[:m]))

    r.append(_r)

print((max(r)))

n, m = list(map(int, input().split()))
xyz = [list(map(int, input().split())) for _i in range(n)]
r = []
for i in range(2**3):
    checker = []
    num = i
    for _i in range(3):
        if num % 2 == 1:
            checker.append(1)
        else:
            checker.append(-1)
        num >>= 1
    _xyz = []
    for j in range(n):
        _abc = [checker[s] * xyz[j][s] for s in range(3)]
        _xyz.append([sum(_abc)] + _abc)
    _xyz.sort(reverse=True)
    _r = abs(sum(i[1] for i in _xyz[:m]))
    _r += abs(sum(i[2] for i in _xyz[:m]))
    _r += abs(sum(i[3] for i in _xyz[:m]))
    r.append(_r)
print((max(r)))

n, m = list(map(int, input().split()))
xyz = [list(map(int, input().split())) for _i in range(n)]
r = []
for i in range(2**3):
    checker = []
    num = i
    for _i in range(3):
        if num % 2 == 1:
            checker.append(1)
        else:
            checker.append(-1)
        num >>= 1
    _xyz = []
    for j in range(n):
        _abc = [checker[s] * xyz[j][s] for s in range(3)]
        _xyz.append([sum(_abc)] + _abc)
    _xyz.sort(reverse=True)
    _r = (
        abs(sum(i[1] for i in _xyz[:m]))
        + abs(sum(i[2] for i in _xyz[:m]))
        + abs(sum(i[3] for i in _xyz[:m]))
    )
    r.append(_r)
print((max(r)))

-    _r = abs(sum(i[1] for i in _xyz[:m]))

-    _r += abs(sum(i[2] for i in _xyz[:m]))

-    _r += abs(sum(i[3] for i in _xyz[:m]))

+        abs(sum(i[1] for i in _xyz[:m]))

+        + abs(sum(i[2] for i in _xyz[:m]))

+        + abs(sum(i[3] for i in _xyz[:m]))


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

li = [int(eval(input())) for i in range(m)]

st = [1]*(n+1)

for i in range(m):

    st[li[i]-1] = 0

if st[0] == 0 and st[1] == 0:

    print((0))

    exit()

elif st[0] == 0 and st[1] != 0:

    st[1] = 1

elif st[0] == 1 and st[1] != 0:

    st[1] = 2

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

    if st[i] == 0:

        continue

    else:

        st[i] = (st[i-1] + st[i-2])%1000000007

print((st[n-1]))

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

dp = [-1]*(n+1)

dp[0] = 1

mod = 10**9 + 7

for i in range(m):

    a = int(eval(input()))

    dp[a-1] = 0

#print(dp)

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

    if dp[i] == 0:

        continue

    else:

        if i == 1:

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

        else:

            dp[i] = (dp[i-1] + dp[i-2])%mod

        #print(dp)

print((dp[n-1]))

n, m = list(map(int, input().split()))
li = [int(eval(input())) for i in range(m)]
st = [1] * (n + 1)
for i in range(m):
    st[li[i] - 1] = 0
if st[0] == 0 and st[1] == 0:
    print((0))
    exit()
elif st[0] == 0 and st[1] != 0:
    st[1] = 1
elif st[0] == 1 and st[1] != 0:
    st[1] = 2
for i in range(2, n + 1):
    if st[i] == 0:
        continue
    else:
        st[i] = (st[i - 1] + st[i - 2]) % 1000000007
print((st[n - 1]))

n, m = list(map(int, input().split()))
dp = [-1] * (n + 1)
dp[0] = 1
mod = 10**9 + 7
for i in range(m):
    a = int(eval(input()))
    dp[a - 1] = 0
# print(dp)
for i in range(1, n + 1):
    if dp[i] == 0:
        continue
    else:
        if i == 1:
            dp[i] = dp[i - 1] + 1
        else:
            dp[i] = (dp[i - 1] + dp[i - 2]) % mod
        # print(dp)
print((dp[n - 1]))

-li = [int(eval(input())) for i in range(m)]


Input:
import sys

input = sys.stdin.readline

from collections import *

N = int(eval(input()))

S = input()[:-1]

if S[0]=='W':

    print((0))

    exit()

l = [0]

ans = 1

MOD = 10**9+7

for i in range(1, 2*N):

    if S[i]==S[i-1]:

        l.append(1^l[-1])

    else:

        l.append(l[-1])

if l.count(0)!=N:

    print((0))

    exit()

zero = 0

for li in l:

    if li==0:

        zero += 1

    else:

        ans *= zero

        ans %= MOD

        zero -= 1

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

    ans *= i

    ans %= MOD

print(ans)

import sys

input = sys.stdin.readline

from collections import *

N = int(eval(input()))

S = list(input()[:-1])

for i in range(2*N):

    if (2*N-i-1)%2==1:

        if S[i]=='B':

            S[i] = 'W'

        else:

            S[i] = 'B'

if S.count('B')!=N:

    print((0))

    exit()

w = 0

ans = 1

MOD = 10**9+7

for i in range(2*N):

    if S[i]=='W':

        w += 1

    else:

        ans *= w

        w -= 1

        ans %= MOD

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

    ans *= i

    ans %= MOD

print(ans)

import sys

input = sys.stdin.readline
from collections import *

N = int(eval(input()))
S = input()[:-1]
if S[0] == "W":
    print((0))
    exit()
l = [0]
ans = 1
MOD = 10**9 + 7
for i in range(1, 2 * N):
    if S[i] == S[i - 1]:
        l.append(1 ^ l[-1])
    else:
        l.append(l[-1])
if l.count(0) != N:
    print((0))
    exit()
zero = 0
for li in l:
    if li == 0:
        zero += 1
    else:
        ans *= zero
        ans %= MOD
        zero -= 1
for i in range(1, N + 1):
    ans *= i
    ans %= MOD
print(ans)

import sys

input = sys.stdin.readline
from collections import *

N = int(eval(input()))
S = list(input()[:-1])
for i in range(2 * N):
    if (2 * N - i - 1) % 2 == 1:
        if S[i] == "B":
            S[i] = "W"
        else:
            S[i] = "B"
if S.count("B") != N:
    print((0))
    exit()
w = 0
ans = 1
MOD = 10**9 + 7
for i in range(2 * N):
    if S[i] == "W":
        w += 1
    else:
        ans *= w
        w -= 1
        ans %= MOD
for i in range(1, N + 1):
    ans *= i
    ans %= MOD
print(ans)


Input:
S = eval(input())

N = len(S)

ans = 0

pre = ""

now = ""

for i in range(N):

    if pre == now or now == "":

        now += S[i]

    if pre != now:

        ans += 1

        pre = now

        now = ""

print(ans)

S = eval(input())

N = len(S)

ans = 0

pre = ""

now = ""

for s in S:

    now += s

    if pre != now:

        ans += 1

        pre = now

        now = ""

print(ans)

-for i in range(N):
-    if pre == now or now == "":
-        now += S[i]
+for s in S:
+    now += s


Input:
A = [1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51]

k = int(eval(input()))

print((A[k-1]))

-k = int(eval(input()))
-print((A[k - 1]))
+K = int(eval(input()))
+print((A[K - 1]))


Input:
def d_lunlun_number():

    import sys

    sys.setrecursionlimit(10**6)

    K = int(eval(input()))

    ans = []

    def dfs(num, current, digit_max):

        if current == digit_max:

            ans.append(num)

            return None

        for n in range(10):

            if abs((num % 10) - n) >= 2:

                continue

            dfs(num * 10 + n, current + 1, digit_max)

    for leading in range(1, 10):

        for d in range(1, 11):

            dfs(leading, 1, d)

    return sorted(ans)[K - 1]

print((d_lunlun_number()))

def d_lunlun_number():

    from collections import deque

    K = int(eval(input()))

    queue = deque(list(range(1, 10)))

    ans = -1

    for _ in range(K):

        ans = queue.popleft()

        lsd = ans % 10  # least significant digit

        if lsd != 0:

            queue.append(10 * ans + (lsd - 1))

        queue.append(10 * ans + lsd)

        if ans % 10 != 9:

            queue.append(10 * ans + (lsd + 1))

    return ans

print((d_lunlun_number()))

-            dfs(num * 10 + n, current + 1, digit_max)

+        lsd = ans % 10  # least significant digit

+            queue.append(10 * ans + (lsd - 1))

+            queue.append(10 * ans + (lsd + 1))


Input:
import heapq

import sys

input = sys.stdin.readline

class UnionFind:

    def __init__(self, n):

        self.par = [i for i in range(n+1)]

        self.rank = [0] * (n+1)

    def find(self, x):

        if self.par[x] == x:

            return x

        else:

            self.par[x] = self.find(self.par[x])

            return self.par[x]

    def union(self, x, y):

        x = self.find(x)

        y = self.find(y)

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

            self.par[x] = y

        else:

            self.par[y] = x

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

                self.rank[x] += 1

    def same_check(self, x, y):

        return self.find(x) == self.find(y)

def solve():

  n = int(eval(input()))

  query = []

  xquery = []

  yquery = []

  for i in range(n):

    x,y = (int(i) for i in input().split())

    xquery.append((x,y,i))

    yquery.append((y,x,i))

  xquery = sorted(xquery)

  yquery = sorted(yquery)

  for i in range(n-1):

    tx,ty,place = xquery[i]

    tx2,ty2,place2 = xquery[i+1]

    cost = min(abs(tx2-tx),abs(ty2-ty))

    heapq.heappush(query,(cost,place,place2))

    ty,tx,place = yquery[i]

    ty2,tx2,place2 = yquery[i+1]

    cost = min(abs(tx2-tx),abs(ty2-ty))

    heapq.heappush(query,(cost,place,place2))

  ct = 0

  uf = UnionFind(n)

  while len(query) > 0:

    cost,place1,place2 = heapq.heappop(query)

    if uf.same_check(place1,place2):

      continue

    else:

      uf.union(int(place1),int(place2))

      ct += cost

  print(ct)

solve()

#https://atcoder.jp/contests/abc065/submissions/5881131

import sys

input = sys.stdin.readline

class UnionFind:

    def __init__(self, n):

        self.par = [i for i in range(n+1)]

        self.rank = [0] * (n+1)

    def find(self, x):

        if self.par[x] == x:

            return x

        else:

            self.par[x] = self.find(self.par[x])

            return self.par[x]

    def union(self, x, y):

        x = self.find(x)

        y = self.find(y)

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

            self.par[x] = y

        else:

            self.par[y] = x

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

                self.rank[x] += 1

    def same_check(self, x, y):

        return self.find(x) == self.find(y)

def MST(n, E):

    E = sorted(E, key=lambda x: x[2])

    uf = UnionFind(n)

    ct = 0

    for i,j,cost in E:

      if uf.same_check(i,j):

        continue

      else:

        uf.union(i,j)

        ct += cost

    return ct

def solve():

  N = int(eval(input()))

  X = []

  append=X.append

  for i in range(N):

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

    append((i, x, y))

  F = []

  append = F.append

  Y = sorted(X, key = lambda x: x[1])

  for i in range(len(Y)-1):

    append((Y[i][0], Y[i+1][0], abs(Y[i+1][1]-Y[i][1])))

  Y = sorted(X, key = lambda x: x[2])

  for i in range(len(Y)-1):

    append((Y[i][0], Y[i+1][0], abs(Y[i+1][2]-Y[i][2])))

  print((MST(N, F)))

solve()

import heapq
import sys

input = sys.stdin.readline

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (n + 1)

    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def same_check(self, x, y):
        return self.find(x) == self.find(y)

def solve():
    n = int(eval(input()))
    query = []
    xquery = []
    yquery = []
    for i in range(n):
        x, y = (int(i) for i in input().split())
        xquery.append((x, y, i))
        yquery.append((y, x, i))
    xquery = sorted(xquery)
    yquery = sorted(yquery)
    for i in range(n - 1):
        tx, ty, place = xquery[i]
        tx2, ty2, place2 = xquery[i + 1]
        cost = min(abs(tx2 - tx), abs(ty2 - ty))
        heapq.heappush(query, (cost, place, place2))
        ty, tx, place = yquery[i]
        ty2, tx2, place2 = yquery[i + 1]
        cost = min(abs(tx2 - tx), abs(ty2 - ty))
        heapq.heappush(query, (cost, place, place2))
    ct = 0
    uf = UnionFind(n)
    while len(query) > 0:
        cost, place1, place2 = heapq.heappop(query)
        if uf.same_check(place1, place2):
            continue
        else:
            uf.union(int(place1), int(place2))
            ct += cost
    print(ct)

solve()

# https://atcoder.jp/contests/abc065/submissions/5881131
import sys

input = sys.stdin.readline

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (n + 1)

    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def same_check(self, x, y):
        return self.find(x) == self.find(y)

def MST(n, E):
    E = sorted(E, key=lambda x: x[2])
    uf = UnionFind(n)
    ct = 0
    for i, j, cost in E:
        if uf.same_check(i, j):
            continue
        else:
            uf.union(i, j)
            ct += cost
    return ct

def solve():
    N = int(eval(input()))
    X = []
    append = X.append
    for i in range(N):
        x, y = list(map(int, input().split()))
        append((i, x, y))
    F = []
    append = F.append
    Y = sorted(X, key=lambda x: x[1])
    for i in range(len(Y) - 1):
        append((Y[i][0], Y[i + 1][0], abs(Y[i + 1][1] - Y[i][1])))
    Y = sorted(X, key=lambda x: x[2])
    for i in range(len(Y) - 1):
        append((Y[i][0], Y[i + 1][0], abs(Y[i + 1][2] - Y[i][2])))
    print((MST(N, F)))

solve()

-        x, y = (int(i) for i in input().split())

-        tx2, ty2, place2 = xquery[i + 1]

-        cost = min(abs(tx2 - tx), abs(ty2 - ty))

-        heapq.heappush(query, (cost, place, place2))

-        ty2, tx2, place2 = yquery[i + 1]

-        cost, place1, place2 = heapq.heappop(query)

-        if uf.same_check(place1, place2):

-            uf.union(int(place1), int(place2))

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


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

ans = 0

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

  if(A <= sum(list(map(int,str(i)))) <= B):

    ans += i

print(ans)

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

cnt = 0

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

  if(A <= sum(map(int,str(i))) <= B):

    cnt += i

print(cnt)

N, A, B = list(map(int, input().split()))
ans = 0
for i in range(1, N + 1):
    if A <= sum(list(map(int, str(i)))) <= B:
        ans += i
print(ans)

N, A, B = list(map(int, input().split()))
cnt = 0
for i in range(1, N + 1):
    if A <= sum(map(int, str(i))) <= B:
        cnt += i
print(cnt)

-    if A <= sum(list(map(int, str(i)))) <= B:

+    if A <= sum(map(int, str(i))) <= B:


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

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

t = eval(input())

cnt, ans = set(), 0

for i, ti in enumerate(t):

    if (i - k in cnt) and ti == t[i - k]:

        continue

    ans += r * (ti == 's')

    ans += s * (ti == 'p')

    ans += p * (ti == 'r')

    cnt.add(i)

print(ans)

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

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

t = eval(input())

dict = {'s': r, 'p': s, 'r': p}

cnt, ans = set(), 0

for i, ti in enumerate(t):

    if (i - k in cnt) and ti == t[i - k]:

        continue

    ans += dict[ti]

    cnt.add(i)

print(ans)

n, k = list(map(int, input().split()))
r, s, p = list(map(int, input().split()))
t = eval(input())
cnt, ans = set(), 0
for i, ti in enumerate(t):
    if (i - k in cnt) and ti == t[i - k]:
        continue
    ans += r * (ti == "s")
    ans += s * (ti == "p")
    ans += p * (ti == "r")
    cnt.add(i)
print(ans)

n, k = list(map(int, input().split()))
r, s, p = list(map(int, input().split()))
t = eval(input())
dict = {"s": r, "p": s, "r": p}
cnt, ans = set(), 0
for i, ti in enumerate(t):
    if (i - k in cnt) and ti == t[i - k]:
        continue
    ans += dict[ti]
    cnt.add(i)
print(ans)


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

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

b = []

minus = 0

for i in range(n):

  if a[i] < 0:

    minus += 1

  b.append(abs(a[i]))

b.sort()

if minus % 2 == 0:

  print((sum(b)))

else:

  print((sum(b) - 2 * b[0]))

#14:20

n = int(eval(input()))

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

cnt = 0

for i in range(n):

  if a[i] < 0:

    cnt += 1

    a[i] *= -1

a.sort()

if cnt % 2 == 0:

  print((sum(a)))

else:

  print((sum(a)-2*a[0]))

n = int(eval(input()))
a = list(map(int, input().split()))
b = []
minus = 0
for i in range(n):
    if a[i] < 0:
        minus += 1
    b.append(abs(a[i]))
b.sort()
if minus % 2 == 0:
    print((sum(b)))
else:
    print((sum(b) - 2 * b[0]))

# 14:20
n = int(eval(input()))
a = list(map(int, input().split()))
cnt = 0
for i in range(n):
    if a[i] < 0:
        cnt += 1
        a[i] *= -1
a.sort()
if cnt % 2 == 0:
    print((sum(a)))
else:
    print((sum(a) - 2 * a[0]))


Input:
def merge_sort(a):

    return _merge_sort(a)

def _merge_sort(a):

    if len(a) == 1:

        return a,0

    m = len(a)/2

    b,count1 = _merge_sort(a[0:m])

    c,count2 = _merge_sort(a[m:len(a)])

    ret,count3 = merge(b,c)

    return (ret,count1+count2+count3)

def merge(b,c):

    a = []

    i = 0

    j = 0

    count = 0

    while i < len(b) and j < len(c):

        count += 1

        if b[i] > c[j]:

            a.append(c[j])

            j += 1

        else:

            a.append(b[i])

            i += 1

    if i == len(b):

        while j < len(c):

            count += 1

            a.append(c[j])

            j += 1

    elif j == len(c):

        while i < len(b):

            count += 1

            a.append(b[i])

            i += 1

    return a,count

n = int(input())

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

ret,count = merge_sort(a)

print(' '.join(map(str,ret)))

print(count)

global_count = 0

def sort(a):

    return merge_sort(a)

def merge_sort(a):

    n = len(a)

    if n <= 1:

        return a

    lo = 0

    hi = n

    med = (lo+hi)/2

    left = merge_sort(a[lo:med])

    right = merge_sort(a[med:hi])

    return merge(left, right)

def merge(a,b):

    global global_count

    c = []

    na = len(a)

    nb = len(b)

    i = 0

    j = 0

    while i < na and j < nb:

        if a[i] < b[j]:

            global_count += 1

            c.append(a[i])

            i += 1

        else:

            global_count += 1

            c.append(b[j])

            j += 1

    if i == na:

        while j < nb:

            global_count += 1

            c.append(b[j])

            j += 1

    if j == nb:

        while i < na:

            global_count += 1

            c.append(a[i])

            i += 1

    return c

n = int(input())

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

c = sort(a)

print(' '.join(map(str, c)))

print(global_count)

def merge_sort(a):
    return _merge_sort(a)

def _merge_sort(a):
    if len(a) == 1:
        return a, 0
    m = len(a) / 2
    b, count1 = _merge_sort(a[0:m])
    c, count2 = _merge_sort(a[m : len(a)])
    ret, count3 = merge(b, c)
    return (ret, count1 + count2 + count3)

def merge(b, c):
    a = []
    i = 0
    j = 0
    count = 0
    while i < len(b) and j < len(c):
        count += 1
        if b[i] > c[j]:
            a.append(c[j])
            j += 1
        else:
            a.append(b[i])
            i += 1
    if i == len(b):
        while j < len(c):
            count += 1
            a.append(c[j])
            j += 1
    elif j == len(c):
        while i < len(b):
            count += 1
            a.append(b[i])
            i += 1
    return a, count

n = int(input())
a = list(map(int, input().split(" ")))
ret, count = merge_sort(a)
print(" ".join(map(str, ret)))
print(count)

global_count = 0

def sort(a):
    return merge_sort(a)

def merge_sort(a):
    n = len(a)
    if n <= 1:
        return a
    lo = 0
    hi = n
    med = (lo + hi) / 2
    left = merge_sort(a[lo:med])
    right = merge_sort(a[med:hi])
    return merge(left, right)

def merge(a, b):
    global global_count
    c = []
    na = len(a)
    nb = len(b)
    i = 0
    j = 0
    while i < na and j < nb:
        if a[i] < b[j]:
            global_count += 1
            c.append(a[i])
            i += 1
        else:
            global_count += 1
            c.append(b[j])
            j += 1
    if i == na:
        while j < nb:
            global_count += 1
            c.append(b[j])
            j += 1
    if j == nb:
        while i < na:
            global_count += 1
            c.append(a[i])
            i += 1
    return c

n = int(input())
a = list(map(int, input().split(" ")))
c = sort(a)
print(" ".join(map(str, c)))
print(global_count)

-    c, count2 = _merge_sort(a[m : len(a)])

-    return (ret, count1 + count2 + count3)


Input:
import sys

from collections import deque

def solve():

    input = sys.stdin.readline

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

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

    for _ in range(M):

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

        Edge[l-1].append((r-1, d))

        Edge[r-1].append((l-1, -1 * d))

    Dist = [10 ** 20] * N

    possible = True

    for i in range(N):

        if Dist[i] == 10 ** 20:

            q = deque()

            q.append((i, 0))

            while q:

                nn, nd = q.popleft()

                if Dist[nn] == 10 ** 20:

                    Dist[nn] = nd

                    for ne, add in Edge[nn]: q.append((ne, nd + add))

                else:

                    if Dist[nn] == nd: continue

                    else:

                        possible = False

                        break

            if not possible:

                print("No")

                break

    else: print("Yes")

    return 0

if __name__ == "__main__":

    solve()

import sys

from collections import deque

def solve():

    input = sys.stdin.readline

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

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

    for _ in range(M):

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

        E[l-1].append((r - 1, d))

        E[r-1].append((l - 1, -d))

    Pos = [10 ** 20] * N

    q = deque()

    flag = True

    for i in range(N):

        if Pos[i] == 10 ** 20:

            q.append((i, 0))

            minX, maxX = 0, 0

            while q:

                x, p = q.popleft()

                if Pos[x] == 10 ** 20:

                    minX = min(minX, p)

                    maxX = max(maxX, p)

                    Pos[x] = p

                    for ne, d in E[x]: q.append((ne, p + d))

                elif Pos[x] == p: continue

                else:

                    flag = False

                    break

            else:

                if maxX - minX <= 10 ** 9: continue

                else: flag = False

            if not flag:

                print("No")

                break

    else: print("Yes")

    #print(Pos)

    return 0

if __name__ == "__main__":

    solve()

import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    N, M = list(map(int, input().split()))
    Edge = [[] for _ in range(N)]
    for _ in range(M):
        l, r, d = list(map(int, input().split()))
        Edge[l - 1].append((r - 1, d))
        Edge[r - 1].append((l - 1, -1 * d))
    Dist = [10**20] * N
    possible = True
    for i in range(N):
        if Dist[i] == 10**20:
            q = deque()
            q.append((i, 0))
            while q:
                nn, nd = q.popleft()
                if Dist[nn] == 10**20:
                    Dist[nn] = nd
                    for ne, add in Edge[nn]:
                        q.append((ne, nd + add))
                else:
                    if Dist[nn] == nd:
                        continue
                    else:
                        possible = False
                        break
            if not possible:
                print("No")
                break
    else:
        print("Yes")
    return 0

if __name__ == "__main__":
    solve()

import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    N, M = list(map(int, input().split()))
    E = [[] for _ in range(N)]
    for _ in range(M):
        l, r, d = list(map(int, input().split()))
        E[l - 1].append((r - 1, d))
        E[r - 1].append((l - 1, -d))
    Pos = [10**20] * N
    q = deque()
    flag = True
    for i in range(N):
        if Pos[i] == 10**20:
            q.append((i, 0))
            minX, maxX = 0, 0
            while q:
                x, p = q.popleft()
                if Pos[x] == 10**20:
                    minX = min(minX, p)
                    maxX = max(maxX, p)
                    Pos[x] = p
                    for ne, d in E[x]:
                        q.append((ne, p + d))
                elif Pos[x] == p:
                    continue
                else:
                    flag = False
                    break
            else:
                if maxX - minX <= 10**9:
                    continue
                else:
                    flag = False
            if not flag:
                print("No")
                break
    else:
        print("Yes")
    # print(Pos)
    return 0

if __name__ == "__main__":
    solve()

-                    for ne, add in Edge[nn]:

-                        q.append((ne, nd + add))

+                    minX = min(minX, p)

+                    maxX = max(maxX, p)

+                        q.append((ne, p + d))

-                        possible = False

+                if maxX - minX <= 10**9:


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

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

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

ans = min(a)+min(b)

for i in range(M):

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

    s = a[c[0]-1]+b[c[1]-1]-c[2]

    ans = min(s,ans)

print(ans)

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

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

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

ans = min(a)+min(b)

for i in range(M):

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

    s = a[x-1]+b[y-1]-z

    ans = (s if s < ans else ans)

print(ans)

A, B, M = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = min(a) + min(b)
for i in range(M):
    c = list(map(int, input().split()))
    s = a[c[0] - 1] + b[c[1] - 1] - c[2]
    ans = min(s, ans)
print(ans)

A, B, M = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = min(a) + min(b)
for i in range(M):
    x, y, z = list(map(int, input().split()))
    s = a[x - 1] + b[y - 1] - z
    ans = s if s < ans else ans
print(ans)

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

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


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

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

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

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

a.sort()

b.sort()

c.sort()

from bisect import bisect_left,bisect_right

ans=0

for i in range(n):

  ida=bisect_left(a,b[i])

  idc=bisect_right(c,b[i])

  ans+=ida*(n-idc)

print(ans)

n = int(eval(input()))

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

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

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

a.sort()

b.sort()

c.sort()

from bisect import bisect_left,bisect_right

ans = 0

for i in range(n):

    pos_a = bisect_left(a,b[i])

    pos_c = bisect_right(c,b[i])

    ans += pos_a*(n-pos_c)

print(ans)

n = int(eval(input()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
a.sort()
b.sort()
c.sort()
from bisect import bisect_left, bisect_right

ans = 0
for i in range(n):
    ida = bisect_left(a, b[i])
    idc = bisect_right(c, b[i])
    ans += ida * (n - idc)
print(ans)

n = int(eval(input()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
a.sort()
b.sort()
c.sort()
from bisect import bisect_left, bisect_right

ans = 0
for i in range(n):
    pos_a = bisect_left(a, b[i])
    pos_c = bisect_right(c, b[i])
    ans += pos_a * (n - pos_c)
print(ans)

-    ida = bisect_left(a, b[i])
-    idc = bisect_right(c, b[i])
-    ans += ida * (n - idc)
+    pos_a = bisect_left(a, b[i])
+    pos_c = bisect_right(c, b[i])
+    ans += pos_a * (n - pos_c)


Input:
import numpy as np

from numba import njit

i4 = np.int32

i8 = np.int64

INF = 1000000000

@njit

def solve(s, ch, cw):

    H = s.shape[0]

    W = s.shape[1] - 1

    ah = H + 4

    aw = W + 4

    a = np.full((ah, aw), -1, i4)

    for i in range(H):

        for j in range(W):

            if s[i, j] == 46:

                a[i + 2, j + 2] = INF

    sh1 = np.empty(1000000, i4)

    sw1 = np.empty(1000000, i4)

    p1 = 0

    sh2 = np.empty(1000000, i4)

    sw2 = np.empty(1000000, i4)

    p2 = 0

    def push2(h2, w2, dis2):

        nonlocal p2, sh2, sw2

    dis = 0

    a[ch + 1, cw + 1] = dis

    sh1[p1] = ch + 1

    sw1[p1] = cw + 1

    p1 += 1

    while True:

        while p1 > 0:

            p1 -= 1

            h = sh1[p1]

            w = sw1[p1]

            for i in range(-2, 3):

                for j in range(-2, 3):

                    if ((i == 1 or i == -1) and j == 0) or (i == 0 and (j == 1 or j == -1)):

                        if a[h + i, w + j] > dis:

                            a[h + i, w + j] = dis

                            sh1[p1] = h + i

                            sw1[p1] = w + j

                            p1 += 1

                    else:

                        if a[h + i, w + j] > dis + 1:

                            push2(h + i, w + j, dis + 1)

                            a[h + i, w + j] = dis + 1

                            sh2[p2] = h + i

                            sw2[p2] = w + j

                            p2 += 1

        dis += 1

        for i in range(p2):

            if a[sh2[i], sw2[i]] == dis:

                sh1[p1] = sh2[i]

                sw1[p1] = sw2[i]

                p1 += 1

        p2 = 0

        if p1 == 0:

            break

    return a

def main(in_file):

    stdin = open(in_file)

    H, W = [int(x) for x in stdin.readline().split()]

    ch, cw = [int(x) for x in stdin.readline().split()]

    dh, dw = [int(x) for x in stdin.readline().split()]

    s = np.frombuffer(np.array(stdin.read()), i4).reshape((H, W + 1))

    a = solve(s, ch, cw)

    ans = a[dh + 1, dw + 1]

    if ans == INF:

        print((-1))

    else:

        print(ans)

main('/dev/stdin')

import numpy as np

from numba import njit, int32, int64

i4 = np.int32

i8 = np.int64

INF = 1000000000

@njit((int32[:,:], int64, int64), cache=True)

def solve(s, ch, cw):

    H = s.shape[0]

    W = s.shape[1] - 1

    ah = H + 4

    aw = W + 4

    a = np.full((ah, aw), -1, i4)

    for i in range(H):

        for j in range(W):

            if s[i, j] == 46:

                a[i + 2, j + 2] = INF

    sh1 = np.empty(1000000, i4)

    sw1 = np.empty(1000000, i4)

    p1 = 0

    sh2 = np.empty(1000000, i4)

    sw2 = np.empty(1000000, i4)

    p2 = 0

    dis = 0

    a[ch + 1, cw + 1] = dis

    sh1[p1] = ch + 1

    sw1[p1] = cw + 1

    p1 += 1

    while True:

        while p1 > 0:

            p1 -= 1

            h = sh1[p1]

            w = sw1[p1]

            for i in range(-2, 3):

                for j in range(-2, 3):

                    if ((i == 1 or i == -1) and j == 0) or (i == 0 and (j == 1 or j == -1)):

                        if a[h + i, w + j] > dis:

                            a[h + i, w + j] = dis

                            sh1[p1] = h + i

                            sw1[p1] = w + j

                            p1 += 1

                    else:

                        if a[h + i, w + j] > dis + 1:

                            a[h + i, w + j] = dis + 1

                            sh2[p2] = h + i

                            sw2[p2] = w + j

                            p2 += 1

        dis += 1

        for i in range(p2):

            if a[sh2[i], sw2[i]] == dis:

                sh1[p1] = sh2[i]

                sw1[p1] = sw2[i]

                p1 += 1

        p2 = 0

        if p1 == 0:

            break

    return a

def main(in_file):

    stdin = open(in_file)

    H, W = [int(x) for x in stdin.readline().split()]

    ch, cw = [int(x) for x in stdin.readline().split()]

    dh, dw = [int(x) for x in stdin.readline().split()]

    s = np.frombuffer(np.array(stdin.read()), i4).reshape((H, W + 1))

    a = solve(s, ch, cw)

    ans = a[dh + 1, dw + 1]

    if ans == INF:

        print((-1))

    else:

        print(ans)

main('/dev/stdin')

import numpy as np
from numba import njit

i4 = np.int32
i8 = np.int64
INF = 1000000000

@njit
def solve(s, ch, cw):
    H = s.shape[0]
    W = s.shape[1] - 1
    ah = H + 4
    aw = W + 4
    a = np.full((ah, aw), -1, i4)
    for i in range(H):
        for j in range(W):
            if s[i, j] == 46:
                a[i + 2, j + 2] = INF
    sh1 = np.empty(1000000, i4)
    sw1 = np.empty(1000000, i4)
    p1 = 0
    sh2 = np.empty(1000000, i4)
    sw2 = np.empty(1000000, i4)
    p2 = 0

    def push2(h2, w2, dis2):
        nonlocal p2, sh2, sw2

    dis = 0
    a[ch + 1, cw + 1] = dis
    sh1[p1] = ch + 1
    sw1[p1] = cw + 1
    p1 += 1
    while True:
        while p1 > 0:
            p1 -= 1
            h = sh1[p1]
            w = sw1[p1]
            for i in range(-2, 3):
                for j in range(-2, 3):
                    if ((i == 1 or i == -1) and j == 0) or (
                        i == 0 and (j == 1 or j == -1)
                    ):
                        if a[h + i, w + j] > dis:
                            a[h + i, w + j] = dis
                            sh1[p1] = h + i
                            sw1[p1] = w + j
                            p1 += 1
                    else:
                        if a[h + i, w + j] > dis + 1:
                            push2(h + i, w + j, dis + 1)
                            a[h + i, w + j] = dis + 1
                            sh2[p2] = h + i
                            sw2[p2] = w + j
                            p2 += 1
        dis += 1
        for i in range(p2):
            if a[sh2[i], sw2[i]] == dis:
                sh1[p1] = sh2[i]
                sw1[p1] = sw2[i]
                p1 += 1
        p2 = 0
        if p1 == 0:
            break
    return a

def main(in_file):
    stdin = open(in_file)
    H, W = [int(x) for x in stdin.readline().split()]
    ch, cw = [int(x) for x in stdin.readline().split()]
    dh, dw = [int(x) for x in stdin.readline().split()]
    s = np.frombuffer(np.array(stdin.read()), i4).reshape((H, W + 1))
    a = solve(s, ch, cw)
    ans = a[dh + 1, dw + 1]
    if ans == INF:
        print((-1))
    else:
        print(ans)

main("/dev/stdin")

import numpy as np
from numba import njit, int32, int64

i4 = np.int32
i8 = np.int64
INF = 1000000000

@njit((int32[:, :], int64, int64), cache=True)
def solve(s, ch, cw):
    H = s.shape[0]
    W = s.shape[1] - 1
    ah = H + 4
    aw = W + 4
    a = np.full((ah, aw), -1, i4)
    for i in range(H):
        for j in range(W):
            if s[i, j] == 46:
                a[i + 2, j + 2] = INF
    sh1 = np.empty(1000000, i4)
    sw1 = np.empty(1000000, i4)
    p1 = 0
    sh2 = np.empty(1000000, i4)
    sw2 = np.empty(1000000, i4)
    p2 = 0
    dis = 0
    a[ch + 1, cw + 1] = dis
    sh1[p1] = ch + 1
    sw1[p1] = cw + 1
    p1 += 1
    while True:
        while p1 > 0:
            p1 -= 1
            h = sh1[p1]
            w = sw1[p1]
            for i in range(-2, 3):
                for j in range(-2, 3):
                    if ((i == 1 or i == -1) and j == 0) or (
                        i == 0 and (j == 1 or j == -1)
                    ):
                        if a[h + i, w + j] > dis:
                            a[h + i, w + j] = dis
                            sh1[p1] = h + i
                            sw1[p1] = w + j
                            p1 += 1
                    else:
                        if a[h + i, w + j] > dis + 1:
                            a[h + i, w + j] = dis + 1
                            sh2[p2] = h + i
                            sw2[p2] = w + j
                            p2 += 1
        dis += 1
        for i in range(p2):
            if a[sh2[i], sw2[i]] == dis:
                sh1[p1] = sh2[i]
                sw1[p1] = sw2[i]
                p1 += 1
        p2 = 0
        if p1 == 0:
            break
    return a

def main(in_file):
    stdin = open(in_file)
    H, W = [int(x) for x in stdin.readline().split()]
    ch, cw = [int(x) for x in stdin.readline().split()]
    dh, dw = [int(x) for x in stdin.readline().split()]
    s = np.frombuffer(np.array(stdin.read()), i4).reshape((H, W + 1))
    a = solve(s, ch, cw)
    ans = a[dh + 1, dw + 1]
    if ans == INF:
        print((-1))
    else:
        print(ans)

main("/dev/stdin")

+@njit((int32[:, :], int64, int64), cache=True)

-                            push2(h + i, w + j, dis + 1)


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

count=0

while N>=i:

    count+=1

    N-=1

print(count)

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

j=0

for v in range(n):

    j=j+1

    if (n-1)>= i:

        n=n-1

    else:

        break

print (j)

N, i = list(map(int, input().split()))
count = 0
while N >= i:
    count += 1
    N -= 1
print(count)

n, i = list(map(int, input().split()))
j = 0
for v in range(n):
    j = j + 1
    if (n - 1) >= i:
        n = n - 1
    else:
        break
print(j)

-N, i = list(map(int, input().split()))
-count = 0
-while N >= i:
-    count += 1
-    N -= 1
-print(count)
+n, i = list(map(int, input().split()))
+j = 0
+for v in range(n):
+    j = j + 1
+    if (n - 1) >= i:
+        n = n - 1
+    else:
+        break
+print(j)


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

sqN = int(N**0.5)+1

for i in range(sqN,0,-1):

    if N % i == 0:

        ans = i+N//i

        break

print((ans-2))

# 約数s

def make_divisors(n):

    divisors = []

    ret = []

    for i in range(1, int(n**0.5)+1):

        if n % i == 0:

            ret.append((i,n//i))

    return ret

if __name__ == "__main__":

    n = int(eval(input()))

    ret = make_divisors(n)

    # print(ret)

    ans = 10**18

    for a,b in ret:

        ans = min(a+b, ans)

    print((ans-2))

N = int(eval(input()))
sqN = int(N**0.5) + 1
for i in range(sqN, 0, -1):
    if N % i == 0:
        ans = i + N // i
        break
print((ans - 2))

# 約数s
def make_divisors(n):
    divisors = []
    ret = []
    for i in range(1, int(n**0.5) + 1):
        if n % i == 0:
            ret.append((i, n // i))
    return ret

if __name__ == "__main__":
    n = int(eval(input()))
    ret = make_divisors(n)
    # print(ret)
    ans = 10**18
    for a, b in ret:
        ans = min(a + b, ans)
    print((ans - 2))

+    for i in range(1, int(n**0.5) + 1):


Input:
import queue

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

AB = [[] for _ in range(M + 1)]

for n in range(N):

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

    if a > M:

        continue

    AB[a].append(0-b)

earn = 0

q = queue.PriorityQueue()

for m in range(1, M + 1):

    for job in AB[m]:

        q.put(job)

    if not q.empty():

        earn += q.get()

print((0-earn))

import heapq

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

AB = [[] for _ in range(M + 1)]

for n in range(N):

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

    if a > M:

        continue

    AB[a].append(0-b)

earn = 0

q = []

for m in range(1, M + 1):

    for job in AB[m]:

        heapq.heappush(q, job)

    if q != []:

        earn += heapq.heappop(q)

print((0-earn))

import queue

N, M = list(map(int, input().split()))
AB = [[] for _ in range(M + 1)]
for n in range(N):
    a, b = list(map(int, input().split()))
    if a > M:
        continue
    AB[a].append(0 - b)
earn = 0
q = queue.PriorityQueue()
for m in range(1, M + 1):
    for job in AB[m]:
        q.put(job)
    if not q.empty():
        earn += q.get()
print((0 - earn))

import heapq

N, M = list(map(int, input().split()))
AB = [[] for _ in range(M + 1)]
for n in range(N):
    a, b = list(map(int, input().split()))
    if a > M:
        continue
    AB[a].append(0 - b)
earn = 0
q = []
for m in range(1, M + 1):
    for job in AB[m]:
        heapq.heappush(q, job)
    if q != []:
        earn += heapq.heappop(q)
print((0 - earn))

-import queue
+import heapq
-q = queue.PriorityQueue()
+q = []
-        q.put(job)
-    if not q.empty():
-        earn += q.get()
+        heapq.heappush(q, job)
+    if q != []:
+        earn += heapq.heappop(q)


Input:
X,Y=list(map(int,input().split()))

import sys

if (2*Y-X)%3!=0 or (2*X-Y)%3!=0:

  print((0))

  sys.exit()

if (2*Y-X)<0 or (2*X-Y)<0:

  print((0))

  sys.exit()

x=(2*Y-X)//3

y=(2*X-Y)//3

#(x+y)Cxを求める

fac=[0 for i in range(x+y+1)]

inv=[0 for i in range(x+y+1)]

finv=[0 for i in range(x+y+1)]

#初期条件

p=1000000007

fac[0]=fac[1]=1

inv[1]=1

finv[0]=finv[1]=1

#テーブルの作成

for i in range(2,x+y+1):

  fac[i]=fac[i-1]*i%p

  #p=(p//a)*a+(p%a) a^(-1)=-(p//a)*(p%a)^(-1)

  inv[i]=(-(p//i)*inv[p%i])%p

  finv[i]=finv[i-1]*inv[i]%p

#求める

print(((fac[x+y]*finv[x]%p)*finv[y]%p))

#(i,j)→（i+1,j+2）をx回、(i,j)→（i+2,j+1）がy回あるとすると

#x=(2Y-X)//3,y=(2X-Y)//3、となる

#これが整数or非負なら(x+y)Cxを求めればいい

X,Y=list(map(int,input().split()))

import sys

if (2*Y-X)%3!=0 or (2*X-Y)%3!=0:

  print((0))

  sys.exit()

if (2*Y-X)<0 or (2*X-Y)<0:

  print((0))

  sys.exit()

#それ以外なら存在する

x=(2*Y-X)//3

y=(2*X-Y)//3

#(x+y)Cxを求める

fac=[0 for i in range(x+y+1)]

inv=[0 for i in range(x+y+1)]

finv=[0 for i in range(x+y+1)]

#初期条件

fac[0]=fac[1]=1

inv[1]=1

finv[0]=finv[1]=1

p=1000000007

for i in range(2,x+y+1):

  fac[i]=(fac[i-1]*i)%p

  #p=(p//a)*a+(p%a) pの世界で　a^(-1)=-(p//a)*inv[p%a]

  inv[i]=(-(p//i)*inv[p%i])%p

  finv[i]=(finv[i-1]*inv[i])%p

print(((fac[x+y]*finv[x]%p)*finv[y]%p))

X, Y = list(map(int, input().split()))
import sys

if (2 * Y - X) % 3 != 0 or (2 * X - Y) % 3 != 0:
    print((0))
    sys.exit()
if (2 * Y - X) < 0 or (2 * X - Y) < 0:
    print((0))
    sys.exit()
x = (2 * Y - X) // 3
y = (2 * X - Y) // 3
# (x+y)Cxを求める
fac = [0 for i in range(x + y + 1)]
inv = [0 for i in range(x + y + 1)]
finv = [0 for i in range(x + y + 1)]
# 初期条件
p = 1000000007
fac[0] = fac[1] = 1
inv[1] = 1
finv[0] = finv[1] = 1
# テーブルの作成
for i in range(2, x + y + 1):
    fac[i] = fac[i - 1] * i % p
    # p=(p//a)*a+(p%a) a^(-1)=-(p//a)*(p%a)^(-1)
    inv[i] = (-(p // i) * inv[p % i]) % p
    finv[i] = finv[i - 1] * inv[i] % p
# 求める
print(((fac[x + y] * finv[x] % p) * finv[y] % p))

# (i,j)→（i+1,j+2）をx回、(i,j)→（i+2,j+1）がy回あるとすると
# x=(2Y-X)//3,y=(2X-Y)//3、となる
# これが整数or非負なら(x+y)Cxを求めればいい
X, Y = list(map(int, input().split()))
import sys

if (2 * Y - X) % 3 != 0 or (2 * X - Y) % 3 != 0:
    print((0))
    sys.exit()
if (2 * Y - X) < 0 or (2 * X - Y) < 0:
    print((0))
    sys.exit()
# それ以外なら存在する
x = (2 * Y - X) // 3
y = (2 * X - Y) // 3
# (x+y)Cxを求める
fac = [0 for i in range(x + y + 1)]
inv = [0 for i in range(x + y + 1)]
finv = [0 for i in range(x + y + 1)]
# 初期条件
fac[0] = fac[1] = 1
inv[1] = 1
finv[0] = finv[1] = 1
p = 1000000007
for i in range(2, x + y + 1):
    fac[i] = (fac[i - 1] * i) % p
    # p=(p//a)*a+(p%a) pの世界で　a^(-1)=-(p//a)*inv[p%a]
    inv[i] = (-(p // i) * inv[p % i]) % p
    finv[i] = (finv[i - 1] * inv[i]) % p
print(((fac[x + y] * finv[x] % p) * finv[y] % p))

+# (i,j)→（i+1,j+2）をx回、(i,j)→（i+2,j+1）がy回あるとすると

+# これが整数or非負なら(x+y)Cxを求めればいい

+# それ以外なら存在する

+    finv[i] = (finv[i - 1] * inv[i]) % p


Input:
import sys

import numpy as np

# N 店の数

n = int(eval(input()))

# F 店の営業計画

f = [input().replace(" ", "") for i in range(n)]

# P 営業利益

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

p_max = -999999999999999

for i in range(1, 1024):

    f_b = format(i, '010b')

    p_10 = 0

    for f_1, p_1 in zip(f, p):

        p_cnt = 0

        for j in range(10):

            if f_1[j] == '1' and f_b[j] == '1':

                p_cnt += 1

        p_10 += p_1[p_cnt]

    if p_10 > p_max:

        if p_10 == 0:

            print((str(i)))

            break

        p_max = p_10

print(p_max)

import sys

import numpy as np

input = sys.stdin.readline

# N 店の数

n = int(eval(input()))

# F 店の営業計画

f = [input().replace(" ", "") for i in range(n)]

# P 営業利益

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

# 全ての時間帯で店を開けるか閉めるの組合せを考える。

# 2 ** 10 の組合せで最大の利益となるものを求める

p_max = -999999999999999

# 1日は開ける必要があるので 1から

for i in range(1, 1024):

    # 2進数にして 1：店を開ける 0：店を開けない

    f_b = format(i, '010b')

    # 10個の時間帯１パターンでの最大利益

    p_10 = 0

    for f_1, p_1 in zip(f, p):

        # 店１つ分の処理

        # お姉ちゃんの店と同時に開いている回数

        p_cnt = 0

        for j in range(10):

            # 10個の時間帯ごとの処理

            if f_1[j] == '1' and f_b[j] == '1':

                # 両方の店が開いている

                p_cnt += 1

        # 両方で営業している回数での利益

        p_10 += p_1[p_cnt]

    if p_10 > p_max:

        # 利益が大きいので入れ替え

        p_max = p_10

print(p_max)

import sys
import numpy as np

# N 店の数
n = int(eval(input()))
# F 店の営業計画
f = [input().replace(" ", "") for i in range(n)]
# P 営業利益
p = [list(map(int, input().split())) for i in range(n)]
p_max = -999999999999999
for i in range(1, 1024):
    f_b = format(i, "010b")
    p_10 = 0
    for f_1, p_1 in zip(f, p):
        p_cnt = 0
        for j in range(10):
            if f_1[j] == "1" and f_b[j] == "1":
                p_cnt += 1
        p_10 += p_1[p_cnt]
    if p_10 > p_max:
        if p_10 == 0:
            print((str(i)))
            break
        p_max = p_10
print(p_max)

import sys
import numpy as np

input = sys.stdin.readline
# N 店の数
n = int(eval(input()))
# F 店の営業計画
f = [input().replace(" ", "") for i in range(n)]
# P 営業利益
p = [list(map(int, input().split())) for i in range(n)]
# 全ての時間帯で店を開けるか閉めるの組合せを考える。
# 2 ** 10 の組合せで最大の利益となるものを求める
p_max = -999999999999999
# 1日は開ける必要があるので 1から
for i in range(1, 1024):
    # 2進数にして 1：店を開ける 0：店を開けない
    f_b = format(i, "010b")
    # 10個の時間帯１パターンでの最大利益
    p_10 = 0
    for f_1, p_1 in zip(f, p):
        # 店１つ分の処理
        # お姉ちゃんの店と同時に開いている回数
        p_cnt = 0
        for j in range(10):
            # 10個の時間帯ごとの処理
            if f_1[j] == "1" and f_b[j] == "1":
                # 両方の店が開いている
                p_cnt += 1
        # 両方で営業している回数での利益
        p_10 += p_1[p_cnt]
    if p_10 > p_max:
        # 利益が大きいので入れ替え
        p_max = p_10
print(p_max)

+input = sys.stdin.readline
+# 全ての時間帯で店を開けるか閉めるの組合せを考える。
+# 2 ** 10 の組合せで最大の利益となるものを求める
+# 1日は開ける必要があるので 1から
+    # 2進数にして 1：店を開ける 0：店を開けない
+    # 10個の時間帯１パターンでの最大利益
+        # 店１つ分の処理
+        # お姉ちゃんの店と同時に開いている回数
+            # 10個の時間帯ごとの処理
+                # 両方の店が開いている
+        # 両方で営業している回数での利益
-        if p_10 == 0:
-            print((str(i)))
-            break
+        # 利益が大きいので入れ替え


Input:
import math

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

if abs(n-m)>1:

  print((0))

elif n-m==1:

  print((int((math.factorial(n)*math.factorial(m))%(10**9+7))))

elif m-n==1:

  print((int((math.factorial(m)*math.factorial(n))%(10**9+7))))

elif n==m:

  print((int((math.factorial(n)*math.factorial(m)*2)%(10**9+7))))

from math import factorial

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

l=10**9+7

if abs(n-m)>1:

  print((0))

  exit()

if abs(n-m)==1:

  print(((factorial(n)*factorial(m))%l))

else:

  print((((factorial(n)**2)*2)%l))

import math

n, m = list(map(int, input().split()))
if abs(n - m) > 1:
    print((0))
elif n - m == 1:
    print((int((math.factorial(n) * math.factorial(m)) % (10**9 + 7))))
elif m - n == 1:
    print((int((math.factorial(m) * math.factorial(n)) % (10**9 + 7))))
elif n == m:
    print((int((math.factorial(n) * math.factorial(m) * 2) % (10**9 + 7))))

from math import factorial

n, m = list(map(int, input().split()))
l = 10**9 + 7
if abs(n - m) > 1:
    print((0))
    exit()
if abs(n - m) == 1:
    print(((factorial(n) * factorial(m)) % l))
else:
    print((((factorial(n) ** 2) * 2) % l))

-    print((int((math.factorial(n) * math.factorial(m)) % (10**9 + 7))))

-    print((int((math.factorial(m) * math.factorial(n)) % (10**9 + 7))))

-    print((int((math.factorial(n) * math.factorial(m) * 2) % (10**9 + 7))))

+    print(((factorial(n) * factorial(m)) % l))


Input:
# 入力

s = eval(input())

# 処理

left_A  = -1  # 最も左のAの位置

right_Z = -1  # 最も右のZの位置

for i in range(len(s)):

  # left_A < 0 => まだAを見つけていない

  if left_A < 0 and s[i] == "A":

    left_A = i

  if s[i] == "Z":

    right_Z = i

# 答え

print((right_Z - left_A + 1))

s = eval(input())

left = 0

right = len(s)-1

for i in range(len(s)):

    if s[i] == "A":

        left = i

        break

for i in range(len(s)-1,0,-1):

    if s[i] == "Z":

        right = i

        break

print((right-left+1))

s = eval(input())
left = 0
right = len(s) - 1
for i in range(len(s)):
    if s[i] == "A":
        left = i
        break
for i in range(len(s) - 1, 0, -1):
    if s[i] == "Z":
        right = i
        break
print((right - left + 1))

-# 入力
-# 処理
-left_A = -1  # 最も左のAの位置
-right_Z = -1  # 最も右のZの位置
+left = 0
+right = len(s) - 1
-    # left_A < 0 => まだAを見つけていない
-    if left_A < 0 and s[i] == "A":
-        left_A = i
+    if s[i] == "A":
+        left = i
+        break
+for i in range(len(s) - 1, 0, -1):
-        right_Z = i
-# 答え
-print((right_Z - left_A + 1))
+        right = i
+        break
+print((right - left + 1))


Input:
v,e = list(map(int, input().split()))

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

adj.sort(key = lambda x:x[2])

group = [[i] for i in range(v)]

key = [i for i in range(v)]

sum = 0

for i,j,k in adj:

    if key[i] != key[j]:

        h = key[j]

        group[key[i]] += group[h]

        sum += k

        for t in group[h]:

            key[t] = key[i]

        group[h] = []

        if len(group[key[i]]) == v:

            break

print(sum)

def root(x):

    if par[x] == x:

        return x

    par[x] = root(par[x])

    return par[x]

def same(x, y):

    return root(x) == root(y)

def unite(x, y):

    x = root(x)

    y = root(y)

    par[x] = y

v,e = list(map(int, input().split()))

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

adj.sort(key = lambda x:x[2])

par = [i for i in range(v)]

sum = 0

for i,j,k in adj:

    if not same(i, j):

        sum += k

        unite(i, j)

print(sum)

v, e = list(map(int, input().split()))
adj = [list(map(int, input().split())) for i in range(e)]
adj.sort(key=lambda x: x[2])
group = [[i] for i in range(v)]
key = [i for i in range(v)]
sum = 0
for i, j, k in adj:
    if key[i] != key[j]:
        h = key[j]
        group[key[i]] += group[h]
        sum += k
        for t in group[h]:
            key[t] = key[i]
        group[h] = []
        if len(group[key[i]]) == v:
            break
print(sum)

def root(x):
    if par[x] == x:
        return x
    par[x] = root(par[x])
    return par[x]

def same(x, y):
    return root(x) == root(y)

def unite(x, y):
    x = root(x)
    y = root(y)
    par[x] = y

v, e = list(map(int, input().split()))
adj = [list(map(int, input().split())) for i in range(e)]
adj.sort(key=lambda x: x[2])
par = [i for i in range(v)]
sum = 0
for i, j, k in adj:
    if not same(i, j):
        sum += k
        unite(i, j)
print(sum)

+def root(x):
+    if par[x] == x:
+        return x
+    par[x] = root(par[x])
+    return par[x]
+
+
+def same(x, y):
+    return root(x) == root(y)
+
+
+def unite(x, y):
+    x = root(x)
+    y = root(y)
+    par[x] = y
+
+
-group = [[i] for i in range(v)]
-key = [i for i in range(v)]
+par = [i for i in range(v)]
-    if key[i] != key[j]:
-        h = key[j]
-        group[key[i]] += group[h]
+    if not same(i, j):
-        for t in group[h]:
-            key[t] = key[i]
-        group[h] = []
-        if len(group[key[i]]) == v:
-            break
+        unite(i, j)


Input:
import sys

import numpy as np

read = sys.stdin.buffer.read

readline = sys.stdin.buffer.readline

readlines = sys.stdin.buffer.readlines

Bsize = 1333

def Mo_argsort(LR):

    L = LR[:, 0]

    R = LR[:, 1]

    key1 = L // Bsize

    key2 = np.where(key1 & 1, -R, R)

    key = (key1 << 32) + key2

    return np.argsort(key)

def main(A, LR):

    N = len(A)

    Q = len(LR)

    ind = Mo_argsort(LR)

    count = np.zeros(N + 1, np.int64)

    ans = 0

    def add(x):

        nonlocal ans

        if not count[x]:

            ans += 1

        count[x] += 1

    def rem(x):

        nonlocal ans

        count[x] -= 1

        if not count[x]:

            ans -= 1

    answers = np.empty(Q, np.int64)

    nl, nr = 0, 0

    for i in ind:

        l, r = LR[i]

        l -= 1

        # 区間 [l, r) に対する計算

        while nl > l:

            nl -= 1

            add(A[nl])

        while nr < r:

            add(A[nr])

            nr += 1

        while nl < l:

            rem(A[nl])

            nl += 1

        while nr > r:

            nr -= 1

            rem(A[nr])

        #  答を求めて ans[i] に格納する

        answers[i] = ans

    return answers

if sys.argv[-1] == 'ONLINE_JUDGE':

    import numba

    from numba.pycc import CC

    i4 = numba.int32

    i8 = numba.int64

    cc = CC('my_module')

    def cc_export(f, signature):

        cc.export(f.__name__, signature)(f)

        return numba.njit(f)

    Mo_argsort = cc_export(Mo_argsort, (i8[:,:],))

    main = cc_export(main, (i8[:], i8[:, :]))

    cc.compile()

from my_module import main

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

A = np.array(readline().split(), np.int64)

LR = np.array(read().split(), np.int64).reshape(Q, 2)

ans = main(A, LR)

print(('\n'.join(map(str, ans.tolist()))))

import sys

import numpy as np

import numba

from numba import njit

from numba.types import Omitted

i4 = numba.int32

i8 = numba.int64

read = sys.stdin.buffer.read

readline = sys.stdin.buffer.readline

readlines = sys.stdin.buffer.readlines

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

def get_sum(bit, i):

    s = 0

    while i:

        s += bit[i]

        i -= i & -i

    return s

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

def add(bit, i, x):

    while i < len(bit):

        bit[i] += x

        i += i & -i

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

def main(A, LR):

    N = len(A)

    L, R = LR[::2], LR[1::2]

    Q = len(L)

    query_order = np.argsort(R)

    L, R = L[query_order], R[query_order]

    ind = np.searchsorted(R, np.arange(N + 2))

    right_end = np.zeros(N + 1, np.int64)

    bit = np.zeros(N + 1, np.int64)

    answers = np.empty(Q, np.int64)

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

        a = A[r - 1]

        p = right_end[a]

        if p:

            add(bit, p, -1)

        right_end[a] = r

        add(bit, r, 1)

        for i in range(ind[r], ind[r + 1]):

            l, r, i = L[i], R[i], query_order[i]

            answers[i] = get_sum(bit, r) - get_sum(bit, l - 1)

    return answers

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

A = np.array(readline().split(), np.int64)

LR = np.array(read().split(), np.int64)

ans = main(A, LR)

print(('\n'.join(map(str, ans.tolist()))))

import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
Bsize = 1333

def Mo_argsort(LR):
    L = LR[:, 0]
    R = LR[:, 1]
    key1 = L // Bsize
    key2 = np.where(key1 & 1, -R, R)
    key = (key1 << 32) + key2
    return np.argsort(key)

def main(A, LR):
    N = len(A)
    Q = len(LR)
    ind = Mo_argsort(LR)
    count = np.zeros(N + 1, np.int64)
    ans = 0

    def add(x):
        nonlocal ans
        if not count[x]:
            ans += 1
        count[x] += 1

    def rem(x):
        nonlocal ans
        count[x] -= 1
        if not count[x]:
            ans -= 1

    answers = np.empty(Q, np.int64)
    nl, nr = 0, 0
    for i in ind:
        l, r = LR[i]
        l -= 1
        # 区間 [l, r) に対する計算
        while nl > l:
            nl -= 1
            add(A[nl])
        while nr < r:
            add(A[nr])
            nr += 1
        while nl < l:
            rem(A[nl])
            nl += 1
        while nr > r:
            nr -= 1
            rem(A[nr])
        #  答を求めて ans[i] に格納する
        answers[i] = ans
    return answers

if sys.argv[-1] == "ONLINE_JUDGE":
    import numba
    from numba.pycc import CC

    i4 = numba.int32
    i8 = numba.int64
    cc = CC("my_module")

    def cc_export(f, signature):
        cc.export(f.__name__, signature)(f)
        return numba.njit(f)

    Mo_argsort = cc_export(Mo_argsort, (i8[:, :],))
    main = cc_export(main, (i8[:], i8[:, :]))
    cc.compile()
from my_module import main

N, Q = list(map(int, readline().split()))
A = np.array(readline().split(), np.int64)
LR = np.array(read().split(), np.int64).reshape(Q, 2)
ans = main(A, LR)
print(("\n".join(map(str, ans.tolist()))))

import sys
import numpy as np
import numba
from numba import njit
from numba.types import Omitted

i4 = numba.int32
i8 = numba.int64
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((i8[:], i8), cache=True)
def get_sum(bit, i):
    s = 0
    while i:
        s += bit[i]
        i -= i & -i
    return s

@njit((i8[:], i8, i8), cache=True)
def add(bit, i, x):
    while i < len(bit):
        bit[i] += x
        i += i & -i

@njit((i8[:], i8[:]), cache=True)
def main(A, LR):
    N = len(A)
    L, R = LR[::2], LR[1::2]
    Q = len(L)
    query_order = np.argsort(R)
    L, R = L[query_order], R[query_order]
    ind = np.searchsorted(R, np.arange(N + 2))
    right_end = np.zeros(N + 1, np.int64)
    bit = np.zeros(N + 1, np.int64)
    answers = np.empty(Q, np.int64)
    for r in range(1, N + 1):
        a = A[r - 1]
        p = right_end[a]
        if p:
            add(bit, p, -1)
        right_end[a] = r
        add(bit, r, 1)
        for i in range(ind[r], ind[r + 1]):
            l, r, i = L[i], R[i], query_order[i]
            answers[i] = get_sum(bit, r) - get_sum(bit, l - 1)
    return answers

N, Q = list(map(int, readline().split()))
A = np.array(readline().split(), np.int64)
LR = np.array(read().split(), np.int64)
ans = main(A, LR)
print(("\n".join(map(str, ans.tolist()))))

+    L, R = L[query_order], R[query_order]

+    ind = np.searchsorted(R, np.arange(N + 2))

+    right_end = np.zeros(N + 1, np.int64)

-        # 区間 [l, r) に対する計算

-        #  答を求めて ans[i] に格納する

+        for i in range(ind[r], ind[r + 1]):

+            l, r, i = L[i], R[i], query_order[i]

+            answers[i] = get_sum(bit, r) - get_sum(bit, l - 1)

-        cc.export(f.__name__, signature)(f)

-    Mo_argsort = cc_export(Mo_argsort, (i8[:, :],))

-LR = np.array(read().split(), np.int64).reshape(Q, 2)

+LR = np.array(read().split(), np.int64)


Input:
import itertools

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

l=[int(eval(input())) for i in range(n)]

ans=10**9

for k in itertools.product(list(range(4)),repeat=n):

    A=[[] for i in range(4)]

    for i in range(n):

        A[k[i]]+=[l[i]]

    if A[1] and A[2] and A[3]:

        tmp=10*(n-len(A[0])-3)

        tmp+=abs(a-sum(A[1]))

        tmp+=abs(b-sum(A[2]))

        tmp+=abs(c-sum(A[3]))

        ans=min(tmp,ans)

print(ans)

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

l=[int(eval(input())) for i in range(N)]

inf=10**9

def dfs(cur,a,b,c):

  if cur==N:

    return abs(a-A)+abs(b-B)+abs(c-C)-30 if min(a,b,c)>0 else inf

  ret0 = dfs(cur+1,a,b,c)

  ret1 = dfs(cur+1,a+l[cur],b,c)+10

  ret2 = dfs(cur+1,a,b+l[cur],c)+10

  ret3 = dfs(cur+1,a,b,c+l[cur])+10

  return min(ret0,ret1,ret2,ret3)

print((dfs(0,0,0,0)))

import itertools

n, a, b, c = list(map(int, input().split()))
l = [int(eval(input())) for i in range(n)]
ans = 10**9
for k in itertools.product(list(range(4)), repeat=n):
    A = [[] for i in range(4)]
    for i in range(n):
        A[k[i]] += [l[i]]
    if A[1] and A[2] and A[3]:
        tmp = 10 * (n - len(A[0]) - 3)
        tmp += abs(a - sum(A[1]))
        tmp += abs(b - sum(A[2]))
        tmp += abs(c - sum(A[3]))
        ans = min(tmp, ans)
print(ans)

N, A, B, C = list(map(int, input().split()))
l = [int(eval(input())) for i in range(N)]
inf = 10**9

def dfs(cur, a, b, c):
    if cur == N:
        return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else inf
    ret0 = dfs(cur + 1, a, b, c)
    ret1 = dfs(cur + 1, a + l[cur], b, c) + 10
    ret2 = dfs(cur + 1, a, b + l[cur], c) + 10
    ret3 = dfs(cur + 1, a, b, c + l[cur]) + 10
    return min(ret0, ret1, ret2, ret3)

print((dfs(0, 0, 0, 0)))

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

+l = [int(eval(input())) for i in range(N)]

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

-l = [int(eval(input())) for i in range(n)]

-for k in itertools.product(list(range(4)), repeat=n):

+        return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else inf

+    ret1 = dfs(cur + 1, a + l[cur], b, c) + 10

+    ret2 = dfs(cur + 1, a, b + l[cur], c) + 10

+    ret3 = dfs(cur + 1, a, b, c + l[cur]) + 10


Input:
# 解説放送の１つめ

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

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

f = [-1, 2,5,5,4,5,6,3,7,6] # 1-indexed

# dp[i]: マッチi本数で作れる最大の数(str)

dp = [None]*(N+1)

dp[0] = ""

# strの数の大きいほう

def max_str(s1:str, s2:str)->str:

    """return bigger one"""

    l1, l2 = len(s1), len(s2)

    if l1 != l2:

        return s1 if l1>l2 else s2

    if l1 == l2:

        return s1 if s1>s2 else s2

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

    nxt = ""

    for aj in A:

        # 配列外参照と，i本ちょうどで作れないものはだめ

        if i-f[aj]<0 or dp[i-f[aj]]==None: continue

        nxt = max_str(nxt,

                      dp[i-f[aj]]+str(aj))

    if nxt!="":

        dp[i] = nxt

    #print(dp)

print((dp[N]))

# dpに最大桁数を持たせる

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

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

A.sort(reverse=True)

f = [-1, 2,5,5,4,5,6,3,7,6] # 1-indexed

# dp[i]: マッチi本数で作れる最大の桁数(int)

dp = [-float('inf')]*(N+1)

dp[0] = 0

for i in range(N+1):

    nxt = dp[i]

    for aj in A:

        if i-f[aj]<0: continue

        nxt = max(nxt,

                  dp[i-f[aj]] + 1)

    dp[i] = nxt

    #print(dp)

#print(dp[N])

keta = dp[N]

ans = ""

matchs = N

# 上位の桁から貪欲に

while keta>0:

    for aj in A:

        if matchs-f[aj] < 0: continue

        if dp[matchs-f[aj]] == keta-1:

            ans += str(aj)

            matchs -= f[aj]

            keta -= 1

            break

print(ans)

# 解説放送の１つめ
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
f = [-1, 2, 5, 5, 4, 5, 6, 3, 7, 6]  # 1-indexed
# dp[i]: マッチi本数で作れる最大の数(str)
dp = [None] * (N + 1)
dp[0] = ""
# strの数の大きいほう
def max_str(s1: str, s2: str) -> str:
    """return bigger one"""
    l1, l2 = len(s1), len(s2)
    if l1 != l2:
        return s1 if l1 > l2 else s2
    if l1 == l2:
        return s1 if s1 > s2 else s2

for i in range(2, N + 1):
    nxt = ""
    for aj in A:
        # 配列外参照と，i本ちょうどで作れないものはだめ
        if i - f[aj] < 0 or dp[i - f[aj]] == None:
            continue
        nxt = max_str(nxt, dp[i - f[aj]] + str(aj))
    if nxt != "":
        dp[i] = nxt
    # print(dp)
print((dp[N]))

# dpに最大桁数を持たせる
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort(reverse=True)
f = [-1, 2, 5, 5, 4, 5, 6, 3, 7, 6]  # 1-indexed
# dp[i]: マッチi本数で作れる最大の桁数(int)
dp = [-float("inf")] * (N + 1)
dp[0] = 0
for i in range(N + 1):
    nxt = dp[i]
    for aj in A:
        if i - f[aj] < 0:
            continue
        nxt = max(nxt, dp[i - f[aj]] + 1)
    dp[i] = nxt
    # print(dp)
# print(dp[N])
keta = dp[N]
ans = ""
matchs = N
# 上位の桁から貪欲に
while keta > 0:
    for aj in A:
        if matchs - f[aj] < 0:
            continue
        if dp[matchs - f[aj]] == keta - 1:
            ans += str(aj)
            matchs -= f[aj]
            keta -= 1
            break
print(ans)

+# dpに最大桁数を持たせる

-# strの数の大きいほう

+# dp[i]: マッチi本数で作れる最大の桁数(int)

-        # 配列外参照と，i本ちょうどで作れないものはだめ

-        if i - f[aj] < 0 or dp[i - f[aj]] == None:

-        nxt = max_str(nxt, dp[i - f[aj]] + str(aj))

+        nxt = max(nxt, dp[i - f[aj]] + 1)

+# 上位の桁から貪欲に

+        if dp[matchs - f[aj]] == keta - 1:


Input:
import sys

input=sys.stdin.readline

d,g=list(map(int,input().split()))

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

P=list([x[0] for x in ls])

C=list([x[1] for x in ls])

tmp=10**9

for i in range(1<<d):

  total=0

  num=0

  for j in range(d):

    if (i>>j)&1:

      total+=C[j]+P[j]*100*(j+1)

      num+=P[j]

  if total>=g:

    tmp=min(num,tmp)

  else:

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

      if (i>>j)&1:

        continue

      for k in range(P[j]):

        if total>=g:

          break

        total+=100*(j+1)

        num+=1

    tmp=min(tmp,num)

print(tmp)

d,g=list(map(int,input().split()))

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

P=list([x[0] for x in PC])

C=list([x[1] for x in PC])

ans=10**9

def dfs(cur,target):

  if cur==0:

    return 10**9

  cnt=min(target//(cur*100),P[cur-1]) #P[j]の一部を利用する/全部利用のどちらか小さい方選択

  tmp=(100*cur)*cnt

  if cnt==P[cur-1]:

    tmp+=C[cur-1]

  if tmp<target:

    cnt+=dfs(cur-1,target-tmp)       #減らした値でdfs実行

  return min(cnt,dfs(cur-1,target))

print((dfs(d,g)))

import sys

input = sys.stdin.readline
d, g = list(map(int, input().split()))
ls = [list(map(int, input().split())) for i in range(d)]
P = list([x[0] for x in ls])
C = list([x[1] for x in ls])
tmp = 10**9
for i in range(1 << d):
    total = 0
    num = 0
    for j in range(d):
        if (i >> j) & 1:
            total += C[j] + P[j] * 100 * (j + 1)
            num += P[j]
    if total >= g:
        tmp = min(num, tmp)
    else:
        for j in range(d - 1, -1, -1):
            if (i >> j) & 1:
                continue
            for k in range(P[j]):
                if total >= g:
                    break
                total += 100 * (j + 1)
                num += 1
        tmp = min(tmp, num)
print(tmp)

d, g = list(map(int, input().split()))
PC = [list(map(int, input().split())) for i in range(d)]
P = list([x[0] for x in PC])
C = list([x[1] for x in PC])
ans = 10**9

def dfs(cur, target):
    if cur == 0:
        return 10**9
    cnt = min(target // (cur * 100), P[cur - 1])  # P[j]の一部を利用する/全部利用のどちらか小さい方選択
    tmp = (100 * cur) * cnt
    if cnt == P[cur - 1]:
        tmp += C[cur - 1]
    if tmp < target:
        cnt += dfs(cur - 1, target - tmp)  # 減らした値でdfs実行
    return min(cnt, dfs(cur - 1, target))

print((dfs(d, g)))

+PC = [list(map(int, input().split())) for i in range(d)]

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

+    cnt = min(target // (cur * 100), P[cur - 1])  # P[j]の一部を利用する/全部利用のどちらか小さい方選択

+        cnt += dfs(cur - 1, target - tmp)  # 減らした値でdfs実行

+    return min(cnt, dfs(cur - 1, target))


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

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

d.sort()

harf_N = int(N/2)

print((d[harf_N] - d[harf_N - 1]))

n = int(eval(input()))

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

#print(n)

a.sort()

#print(a)

print((a[int(n/2)]-a[int(n/2)-1]))

N = int(eval(input()))
d = list(map(int, input().split()))
d.sort()
harf_N = int(N / 2)
print((d[harf_N] - d[harf_N - 1]))

n = int(eval(input()))
a = list(map(int, input().split()))
# print(n)
a.sort()
# print(a)
print((a[int(n / 2)] - a[int(n / 2) - 1]))


Input:
#!/usr/bin/env python3

import sys

def solve(X: int, Y: int, Z: int, K: int, A: "List[int]", B: "List[int]", C: "List[int]"):

    AB = []

    for i in range(X):

        for j in range(Y):

            AB.append(A[i]+B[j])

    AB.sort(reverse=True)

    AB = AB[:K]

    ABC = []

    for k in range(Z):

        for ab_index in range(len(AB)):

            ABC.append(C[k]+AB[ab_index])

    ABC.sort(reverse=True)

    ABC = ABC[:K]

    for i in range(len(ABC)):

        print((ABC[i]))

    return

def main():

    def iterate_tokens():

        for line in sys.stdin:

            for word in line.split():

                yield word

    tokens = iterate_tokens()

    X = int(next(tokens))  # type: int

    Y = int(next(tokens))  # type: int

    Z = int(next(tokens))  # type: int

    K = int(next(tokens))  # type: int

    A = [int(next(tokens)) for _ in range(X)]  # type: "List[int]"

    B = [int(next(tokens)) for _ in range(Y)]  # type: "List[int]"

    C = [int(next(tokens)) for _ in range(Z)]  # type: "List[int]"

    solve(X, Y, Z, K, A, B, C)

if __name__ == '__main__':

    main()

#!/usr/bin/env python3

import sys

import heapq

def solve(X: int, Y: int, Z: int, K: int, A: "List[int]", B: "List[int]", C: "List[int]"):

    A = sorted(A,reverse = True)

    B = sorted(B,reverse = True)

    C = sorted(C,reverse = True)

    d = []

    heapq.heappush(d, (-(A[0]+B[0]+C[0]), 0, 0, 0)) # heapqにタプルを与えると最初の要素でソートする

    ijk_set = set((0,0,0))

    for _ in range(K):

        tmp, i, j, k = heapq.heappop(d)

        print((-tmp))

        if (i+1,j,k) not in ijk_set and i+1 <= X-1:

            heapq.heappush(d, (-(A[i+1]+B[j]+C[k]), i+1, j, k))

            ijk_set.add((i+1,j,k))

        if (i,j+1,k) not in ijk_set and j+1 <= Y-1:

            heapq.heappush(d, (-(A[i]+B[j+1]+C[k]), i, j+1, k))

            ijk_set.add((i,j+1,k))

        if (i,j,k+1) not in ijk_set and k+1 <= Z-1:

            heapq.heappush(d, (-(A[i]+B[j]+C[k+1]), i, j, k+1))

            ijk_set.add((i,j,k+1))

    return

def main():

    def iterate_tokens():

        for line in sys.stdin:

            for word in line.split():

                yield word

    tokens = iterate_tokens()

    X = int(next(tokens))  # type: int

    Y = int(next(tokens))  # type: int

    Z = int(next(tokens))  # type: int

    K = int(next(tokens))  # type: int

    A = [int(next(tokens)) for _ in range(X)]  # type: "List[int]"

    B = [int(next(tokens)) for _ in range(Y)]  # type: "List[int]"

    C = [int(next(tokens)) for _ in range(Z)]  # type: "List[int]"

    solve(X, Y, Z, K, A, B, C)

if __name__ == '__main__':

    main()

#!/usr/bin/env python3
import sys

def solve(
    X: int, Y: int, Z: int, K: int, A: "List[int]", B: "List[int]", C: "List[int]"
):
    AB = []
    for i in range(X):
        for j in range(Y):
            AB.append(A[i] + B[j])
    AB.sort(reverse=True)
    AB = AB[:K]
    ABC = []
    for k in range(Z):
        for ab_index in range(len(AB)):
            ABC.append(C[k] + AB[ab_index])
    ABC.sort(reverse=True)
    ABC = ABC[:K]
    for i in range(len(ABC)):
        print((ABC[i]))
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    X = int(next(tokens))  # type: int
    Y = int(next(tokens))  # type: int
    Z = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(X)]  # type: "List[int]"
    B = [int(next(tokens)) for _ in range(Y)]  # type: "List[int]"
    C = [int(next(tokens)) for _ in range(Z)]  # type: "List[int]"
    solve(X, Y, Z, K, A, B, C)

if __name__ == "__main__":
    main()

#!/usr/bin/env python3
import sys
import heapq

def solve(
    X: int, Y: int, Z: int, K: int, A: "List[int]", B: "List[int]", C: "List[int]"
):
    A = sorted(A, reverse=True)
    B = sorted(B, reverse=True)
    C = sorted(C, reverse=True)
    d = []
    heapq.heappush(d, (-(A[0] + B[0] + C[0]), 0, 0, 0))  # heapqにタプルを与えると最初の要素でソートする
    ijk_set = set((0, 0, 0))
    for _ in range(K):
        tmp, i, j, k = heapq.heappop(d)
        print((-tmp))
        if (i + 1, j, k) not in ijk_set and i + 1 <= X - 1:
            heapq.heappush(d, (-(A[i + 1] + B[j] + C[k]), i + 1, j, k))
            ijk_set.add((i + 1, j, k))
        if (i, j + 1, k) not in ijk_set and j + 1 <= Y - 1:
            heapq.heappush(d, (-(A[i] + B[j + 1] + C[k]), i, j + 1, k))
            ijk_set.add((i, j + 1, k))
        if (i, j, k + 1) not in ijk_set and k + 1 <= Z - 1:
            heapq.heappush(d, (-(A[i] + B[j] + C[k + 1]), i, j, k + 1))
            ijk_set.add((i, j, k + 1))
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    X = int(next(tokens))  # type: int
    Y = int(next(tokens))  # type: int
    Z = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(X)]  # type: "List[int]"
    B = [int(next(tokens)) for _ in range(Y)]  # type: "List[int]"
    C = [int(next(tokens)) for _ in range(Z)]  # type: "List[int]"
    solve(X, Y, Z, K, A, B, C)

if __name__ == "__main__":
    main()

-        for ab_index in range(len(AB)):

-            ABC.append(C[k] + AB[ab_index])

+    heapq.heappush(d, (-(A[0] + B[0] + C[0]), 0, 0, 0))  # heapqにタプルを与えると最初の要素でソートする

+        tmp, i, j, k = heapq.heappop(d)

+        if (i + 1, j, k) not in ijk_set and i + 1 <= X - 1:

+        if (i, j + 1, k) not in ijk_set and j + 1 <= Y - 1:

+        if (i, j, k + 1) not in ijk_set and k + 1 <= Z - 1:


Input:
from math import sqrt

from itertools import accumulate

def common_divisors(x):

    ret = []

    for i in range(1, int(sqrt(x)) + 1):

        if x % i == 0:

            ret.append(i)

            ret.append(x // i)

    return ret

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

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

sm = sum(a)

cd = common_divisors(sm)

ans = 1

for ecd in cd:

    r = [e % ecd for e in a]

    r.sort()

    acc = [0] + list(accumulate(r))

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

        sub = acc[i-1]

        add = ecd * (n - i + 1) - (acc[n] - acc[i-1])

        if sub == add:

            if sub <= k:

                ans = max(ans, ecd)

print(ans)

from math import sqrt

from itertools import accumulate

def common_divisors(x):

    ret = []

    for i in range(1, int(sqrt(x)) + 1):

        if x % i == 0:

            ret.append(i)

            ret.append(x // i)

    return ret

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

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

sm = sum(a)

cd = common_divisors(sm)

ans = 1

for ecd in cd:

    r = [e % ecd for e in a]

    r.sort()

    sub = [0] + list(accumulate(r))

    add = [0] + list(accumulate(ecd - e for e in r[::-1]))

    add = add[::-1]

    for sb, ad in zip(sub, add):

        if sb == ad and sb <= k:

            ans = max(ans, ecd)

print(ans)

from math import sqrt
from itertools import accumulate

def common_divisors(x):
    ret = []
    for i in range(1, int(sqrt(x)) + 1):
        if x % i == 0:
            ret.append(i)
            ret.append(x // i)
    return ret

n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
sm = sum(a)
cd = common_divisors(sm)
ans = 1
for ecd in cd:
    r = [e % ecd for e in a]
    r.sort()
    acc = [0] + list(accumulate(r))
    for i in range(1, n + 1):
        sub = acc[i - 1]
        add = ecd * (n - i + 1) - (acc[n] - acc[i - 1])
        if sub == add:
            if sub <= k:
                ans = max(ans, ecd)
print(ans)

+    add = [0] + list(accumulate(ecd - e for e in r[::-1]))


Input:
while 1:

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

    if not x+y:break

    print(*[y,x] if x>y else [x,y])

while 1:

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

    if not x+y:break

    if x>y:x,y=y,x

    print((x,y))

while 1:
    x, y = map(int, input().split())
    if not x + y:
        break
    print(*[y, x] if x > y else [x, y])

while 1:
    x, y = list(map(int, input().split()))
    if not x + y:
        break
    if x > y:
        x, y = y, x
    print((x, y))

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

-    print(*[y, x] if x > y else [x, y])


Input:
"""

~~ Author : Bhaskar

~~ Dated : 31~05~2020

"""

import sys

from bisect import *

from math import floor,sqrt,ceil,factorial as F,gcd,pi

from itertools import chain,combinations,permutations,accumulate

from collections import Counter,defaultdict,OrderedDict,deque

from array import array

INT_MAX = sys.maxsize

INT_MIN = -(sys.maxsize)-1

mod = 10**18

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

setbit = lambda x : bin(x)[2:].count("1")

def solve():

    n = int(sys.stdin.readline())

    a = list(map(int,sys.stdin.readline().split()))

    ans =  1

    flag = False

    for i in a:

        ans *= i

        # print(ans)

        if ans > mod:

            flag = True

            break

    if 0 in a:

        print((0))

    else:

        if not flag:

            print(ans)

        else:

            print((-1))

if __name__ == "__main__":

    solve()

"""

~~ Author : Bhaskar

~~ Dated : 13~06~2020

"""

import sys

from bisect import *

from math import floor, sqrt, ceil, factorial as F, gcd, pi

from itertools import chain, combinations, permutations, accumulate

from collections import Counter, defaultdict, OrderedDict, deque

INT_MAX = sys.maxsize

INT_MIN = -(sys.maxsize) - 1

mod = 1000000007

ch = "abcdefghijklmnopqrstuvwxyz"

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

setbit = lambda x: bin(x)[2:].count("1")

INT = lambda type: type(sys.stdin.readline()) if type in [int, float] else type(sys.stdin.readline()).replace("\n", "")

ARRAY = lambda type: list(map(type, sys.stdin.readline().split()))

NUMS = lambda type: list(map(type, sys.stdin.readline().split()))

def solve():

    n = INT(int)

    a = ARRAY(int)

    if 0 in a:

        print((0))

    else:

        p = 1

        ok = False

        for i in a:

            p *= i

            if p > 10**18:

                ok = True

                break

        print((p if not ok else -1))

if __name__ == "__main__":

    # try:

    #     sys.stdin = open("input.txt", "r")

    # except:

    #     pass

    solve()

"""
~~ Author : Bhaskar
~~ Dated : 31~05~2020
"""
import sys
from bisect import *
from math import floor, sqrt, ceil, factorial as F, gcd, pi
from itertools import chain, combinations, permutations, accumulate
from collections import Counter, defaultdict, OrderedDict, deque
from array import array

INT_MAX = sys.maxsize
INT_MIN = -(sys.maxsize) - 1
mod = 10**18
lcm = lambda a, b: (a * b) // gcd(a, b)
setbit = lambda x: bin(x)[2:].count("1")

def solve():
    n = int(sys.stdin.readline())
    a = list(map(int, sys.stdin.readline().split()))
    ans = 1
    flag = False
    for i in a:
        ans *= i
        # print(ans)
        if ans > mod:
            flag = True
            break
    if 0 in a:
        print((0))
    else:
        if not flag:
            print(ans)
        else:
            print((-1))

if __name__ == "__main__":
    solve()

"""
~~ Author : Bhaskar
~~ Dated : 13~06~2020
"""
import sys
from bisect import *
from math import floor, sqrt, ceil, factorial as F, gcd, pi
from itertools import chain, combinations, permutations, accumulate
from collections import Counter, defaultdict, OrderedDict, deque

INT_MAX = sys.maxsize
INT_MIN = -(sys.maxsize) - 1
mod = 1000000007
ch = "abcdefghijklmnopqrstuvwxyz"
lcm = lambda a, b: (a * b) // gcd(a, b)
setbit = lambda x: bin(x)[2:].count("1")
INT = (
    lambda type: type(sys.stdin.readline())
    if type in [int, float]
    else type(sys.stdin.readline()).replace("\n", "")
)
ARRAY = lambda type: list(map(type, sys.stdin.readline().split()))
NUMS = lambda type: list(map(type, sys.stdin.readline().split()))

def solve():
    n = INT(int)
    a = ARRAY(int)
    if 0 in a:
        print((0))
    else:
        p = 1
        ok = False
        for i in a:
            p *= i
            if p > 10**18:
                ok = True
                break
        print((p if not ok else -1))

if __name__ == "__main__":
    # try:
    #     sys.stdin = open("input.txt", "r")
    # except:
    #     pass
    solve()

+    lambda type: type(sys.stdin.readline())

+    else type(sys.stdin.readline()).replace("\n", "")

+ARRAY = lambda type: list(map(type, sys.stdin.readline().split()))

+NUMS = lambda type: list(map(type, sys.stdin.readline().split()))

-    a = list(map(int, sys.stdin.readline().split()))

+    #     sys.stdin = open("input.txt", "r")


Input:
h,w,d=list(map(int,input().split()))

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

def find_element(k):

    global h,w,a

    for i in range(h):

        for j in range(w):

            if a[i][j]==k:

                return (i,j)

def make_distance(S,T):

    return abs(S[0]-T[0])+abs(S[1]-T[1])

x1=[]

x2=[]

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

    l=(h*w-i)//d

    x1.append([0]*(l+1))

    x2.append([[0,0]for i in range(l+1)])

for i in range(h):

    for j in range(w):

        p=a[i][j]%d

        if p==0:

            p=d-1

        else:

            p-=1

        l=(a[i][j]-(p+1))//d

        x2[p][l]=[i,j]

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

    l=len(x1[i-1])

    for j in range(l-1):

        x1[i-1][j+1]=x1[i-1][j]+make_distance(x2[i-1][j],x2[i-1][j+1])

q=int(eval(input()))

for i in range(q):

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

    p=l%d

    if p==0:

        v1=l//d-1

        v2=r//d-1

        print((x1[d-1][v2]-x1[d-1][v1]))

    else:

        v1=l//d

        v2=r//d

        print((x1[p-1][v2]-x1[p-1][v1]))

#print(x)

from math import ceil

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

x=ceil((h*w)/d)

num=[[[-1,-1] for j in range(x)] for i in range(d)]#あまりで場合分け(1→0)

mp=[[0]*x for i in range(d)]

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

for i in range(h):

    for j in range(w):

        k,l=a[i][j]%d,a[i][j]//d

        if k==0:

            num[d-1][l-1]=[i,j]

        else:

            num[k-1][l]=[i,j]

for i in range(d):

    for j in range(x):

        if j!=x-1:

            if num[i][j+1]!=[-1,-1]:

                mp[i][j+1]+=(mp[i][j]+abs(num[i][j+1][0]-num[i][j][0])+abs(num[i][j+1][1]-num[i][j][1]))

            else:

                break

q=int(eval(input()))

for i in range(q):

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

    if l%d!=0:

        e,f=l//d,r//d

    else:

        e,f=l//d-1,r//d-1

    g= d-1 if l%d==0 else l%d-1

    if e==0:

        print((mp[g][f]))

    else:

        print((mp[g][f]-mp[g][e]))

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

def find_element(k):
    global h, w, a
    for i in range(h):
        for j in range(w):
            if a[i][j] == k:
                return (i, j)

def make_distance(S, T):
    return abs(S[0] - T[0]) + abs(S[1] - T[1])

x1 = []
x2 = []
for i in range(1, d + 1):
    l = (h * w - i) // d
    x1.append([0] * (l + 1))
    x2.append([[0, 0] for i in range(l + 1)])
for i in range(h):
    for j in range(w):
        p = a[i][j] % d
        if p == 0:
            p = d - 1
        else:
            p -= 1
        l = (a[i][j] - (p + 1)) // d
        x2[p][l] = [i, j]
for i in range(1, d + 1):
    l = len(x1[i - 1])
    for j in range(l - 1):
        x1[i - 1][j + 1] = x1[i - 1][j] + make_distance(x2[i - 1][j], x2[i - 1][j + 1])
q = int(eval(input()))
for i in range(q):
    l, r = list(map(int, input().split()))
    p = l % d
    if p == 0:
        v1 = l // d - 1
        v2 = r // d - 1
        print((x1[d - 1][v2] - x1[d - 1][v1]))
    else:
        v1 = l // d
        v2 = r // d
        print((x1[p - 1][v2] - x1[p - 1][v1]))
# print(x)

from math import ceil

h, w, d = list(map(int, input().split()))
x = ceil((h * w) / d)
num = [[[-1, -1] for j in range(x)] for i in range(d)]  # あまりで場合分け(1→0)
mp = [[0] * x for i in range(d)]
a = [list(map(int, input().split())) for i in range(h)]
for i in range(h):
    for j in range(w):
        k, l = a[i][j] % d, a[i][j] // d
        if k == 0:
            num[d - 1][l - 1] = [i, j]
        else:
            num[k - 1][l] = [i, j]
for i in range(d):
    for j in range(x):
        if j != x - 1:
            if num[i][j + 1] != [-1, -1]:
                mp[i][j + 1] += (
                    mp[i][j]
                    + abs(num[i][j + 1][0] - num[i][j][0])
                    + abs(num[i][j + 1][1] - num[i][j][1])
                )
            else:
                break
q = int(eval(input()))
for i in range(q):
    l, r = list(map(int, input().split()))
    if l % d != 0:
        e, f = l // d, r // d
    else:
        e, f = l // d - 1, r // d - 1
    g = d - 1 if l % d == 0 else l % d - 1
    if e == 0:
        print((mp[g][f]))
    else:
        print((mp[g][f] - mp[g][e]))

+num = [[[-1, -1] for j in range(x)] for i in range(d)]  # あまりで場合分け(1→0)

-    x2.append([[0, 0] for i in range(l + 1)])

+    g = d - 1 if l % d == 0 else l % d - 1


Input:
import sys

import math

from collections import defaultdict, deque, Counter

from copy import deepcopy

from bisect import bisect, bisect_right, bisect_left

from heapq import heapify, heappop, heappush

input = sys.stdin.readline

def RD(): return input().rstrip()

def F(): return float(input().rstrip())

def I(): return int(input().rstrip())

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

def MF(): return list(map(float,input().split()))

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

def TI(): return tuple(map(int, input().split()))

def LF(): return list(map(float,input().split()))

def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]

#乗法のmod逆元

def modinv(a, mod=10**9+7):

    return pow(a, mod-2, mod)

# nCr mod m

# modinvが必要

# rがn/2に近いと非常に重くなる

def combination(n, r, mod=10**9+7):

    r = min(r, n-r)

    res = 1

    for i in range(r):

        res = res * (n - i) * modinv(i+1, mod) % mod

    return res

#べき乗

def Raise(x, y, mod=10**9+7):

    # xをy乗する。

    n = 0

    while True:

        if (1<<n) > y:

            break

        n+=1

    D = [0]*(n+1)

    x = x % mod

    D[0] = x

    index = 0

    for index in range(1,n):

        D[index] = (D[index-1]**2)

    res = 1

    index = 0

    for index in range(0, n):

        if (y>>index)&1 == 1:

            res *= D[index]

    return res

def main():

    #答えは 10^2 - 2*9^2 + 8^2

    n = I()

    res = Raise(10, n)- 2 * Raise(9, n) + Raise(8, n)

    print((res % (10**9+7)))

if __name__ == "__main__":

    main()

import sys

import math

from collections import defaultdict, deque, Counter

from copy import deepcopy

from bisect import bisect, bisect_right, bisect_left

from heapq import heapify, heappop, heappush

input = sys.stdin.readline

def RD(): return input().rstrip()

def F(): return float(input().rstrip())

def I(): return int(input().rstrip())

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

def MF(): return list(map(float,input().split()))

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

def TI(): return tuple(map(int, input().split()))

def LF(): return list(map(float,input().split()))

def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]

#乗法のmod逆元

def modinv(a, mod=10**9+7):

    return pow(a, mod-2, mod)

# nCr mod m

# modinvが必要

# rがn/2に近いと非常に重くなる

def combination(n, r, mod=10**9+7):

    r = min(r, n-r)

    res = 1

    for i in range(r):

        res = res * (n - i) * modinv(i+1, mod) % mod

    return res

#べき乗

def Raise(x, y):

    # xをy乗する。

    n = 0

    while True:

        if (1<<n) > y:

            break

        n+=1

    D = [0]*(n+1)

    D[0] = x

    index = 0

    for index in range(1,n):

        D[index] = (D[index-1]**2)

    res = 1

    index = 0

    for index in range(0, n):

        if (y>>index)&1 == 1:

            res *= D[index]

    return res

def main():

    #答えは 10^2 - 2*9^2 + 8^2

    n = I()

    mod=10**9+7

    res = pow(10, n, mod)- 2 * pow(9, n, mod) + pow(8, n, mod)

    print((res % (10**9+7)))

if __name__ == "__main__":

    main()

import sys
import math
from collections import defaultdict, deque, Counter
from copy import deepcopy
from bisect import bisect, bisect_right, bisect_left
from heapq import heapify, heappop, heappush

input = sys.stdin.readline

def RD():
    return input().rstrip()

def F():
    return float(input().rstrip())

def I():
    return int(input().rstrip())

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

def MF():
    return list(map(float, input().split()))

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

def TI():
    return tuple(map(int, input().split()))

def LF():
    return list(map(float, input().split()))

def Init(H, W, num):
    return [[num for i in range(W)] for j in range(H)]

# 乗法のmod逆元
def modinv(a, mod=10**9 + 7):
    return pow(a, mod - 2, mod)

# nCr mod m
# modinvが必要
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9 + 7):
    r = min(r, n - r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i + 1, mod) % mod
    return res

# べき乗
def Raise(x, y, mod=10**9 + 7):
    # xをy乗する。
    n = 0
    while True:
        if (1 << n) > y:
            break
        n += 1
    D = [0] * (n + 1)
    x = x % mod
    D[0] = x
    index = 0
    for index in range(1, n):
        D[index] = D[index - 1] ** 2
    res = 1
    index = 0
    for index in range(0, n):
        if (y >> index) & 1 == 1:
            res *= D[index]
    return res

def main():
    # 答えは 10^2 - 2*9^2 + 8^2
    n = I()
    res = Raise(10, n) - 2 * Raise(9, n) + Raise(8, n)
    print((res % (10**9 + 7)))

if __name__ == "__main__":
    main()

import sys
import math
from collections import defaultdict, deque, Counter
from copy import deepcopy
from bisect import bisect, bisect_right, bisect_left
from heapq import heapify, heappop, heappush

input = sys.stdin.readline

def RD():
    return input().rstrip()

def F():
    return float(input().rstrip())

def I():
    return int(input().rstrip())

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

def MF():
    return list(map(float, input().split()))

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

def TI():
    return tuple(map(int, input().split()))

def LF():
    return list(map(float, input().split()))

def Init(H, W, num):
    return [[num for i in range(W)] for j in range(H)]

# 乗法のmod逆元
def modinv(a, mod=10**9 + 7):
    return pow(a, mod - 2, mod)

# nCr mod m
# modinvが必要
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9 + 7):
    r = min(r, n - r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i + 1, mod) % mod
    return res

# べき乗
def Raise(x, y):
    # xをy乗する。
    n = 0
    while True:
        if (1 << n) > y:
            break
        n += 1
    D = [0] * (n + 1)
    D[0] = x
    index = 0
    for index in range(1, n):
        D[index] = D[index - 1] ** 2
    res = 1
    index = 0
    for index in range(0, n):
        if (y >> index) & 1 == 1:
            res *= D[index]
    return res

def main():
    # 答えは 10^2 - 2*9^2 + 8^2
    n = I()
    mod = 10**9 + 7
    res = pow(10, n, mod) - 2 * pow(9, n, mod) + pow(8, n, mod)
    print((res % (10**9 + 7)))

if __name__ == "__main__":
    main()

-    res = Raise(10, n) - 2 * Raise(9, n) + Raise(8, n)

+    res = pow(10, n, mod) - 2 * pow(9, n, mod) + pow(8, n, mod)