Input:
class UnionFind():

    def __init__(self, n):

        self.n = n

        # 親の名(いない場合は自分)

        self.parent = list(range(n))

        # 子の数

        self.count = [0] * n

    def root(self, x):

        # xの根を返す

        if self.parent[x] == x:

            return x

        else:

            return self.root(self.parent[x])

    def union(self, x, y):

        # xとyをまとめる

        x0 = self.root(x)

        y0 = self.root(y)

        if x0 == y0:

            return

        if x0 > y0:

            x0, y0 = y0, x0

        self.parent[y0] = x0

        self.count[x0] += self.count[y0] + 1

    def size(self, x):

        # xの属する木の大きさ

        return self.count[self.root(x)] + 1

    def same(self, x, y):

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

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

tree = UnionFind(N)

# 同じグループでの友達の数とブロックの数

F, B = [0] * N, [0] * N

lst = []

for m in range(M):

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

    tree.union(a - 1, b - 1)

    lst.append((a, b))

for a, b in lst:

    if tree.same(a - 1, b - 1):

        F[a - 1] += 1

        F[b - 1] += 1

for k in range(K):

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

    if tree.same(c - 1, d - 1):

        B[c - 1] += 1

        B[d - 1] += 1

# nが属する木の大きさから友達の数とブロックの数と自分を除いたのが答え

print((*[tree.size(n) - F[n] - B[n] - 1 for n in range(N)]))

class UnionFind():

    def __init__(self, n):

        self.n = n

        # 親の名(いない場合はNone)

        self.parent = [None]*n

        # 子の数

        self.count = [0] * n

    def root(self, x):

        # xの根を返す

        if self.parent[x] == None:

            return x

        else:

            return self.root(self.parent[x])

    def union(self, x, y):

        # xとyをまとめる

        x0 = self.root(x)

        y0 = self.root(y)

        if x0 == y0:

            return

        if x0 > y0:

            x0, y0 = y0, x0

        self.parent[y0] = x0

        self.count[x0] += self.count[y0] + 1

    def size(self, x):

        # xの属する木の大きさ

        return self.count[self.root(x)] + 1

    def same(self, x, y):

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

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

uf = UnionFind(n)

# F[i]=iの友達の数

F = [0]*n

# B[i]=iと同じグループでブロックしている数

B = [0]*n

for i in range(m):

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

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

    F[a-1] += 1

    F[b-1] += 1

for j in range(k):

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

    if uf.same(a-1, b-1):

        B[a-1] += 1

        B[b-1] += 1

L = [uf.size(i)-1-F[i]-B[i] for i in range(n)]

print((*L))

class UnionFind:
    def __init__(self, n):
        self.n = n
        # 親の名(いない場合は自分)
        self.parent = list(range(n))
        # 子の数
        self.count = [0] * n

    def root(self, x):
        # xの根を返す
        if self.parent[x] == x:
            return x
        else:
            return self.root(self.parent[x])

    def union(self, x, y):
        # xとyをまとめる
        x0 = self.root(x)
        y0 = self.root(y)
        if x0 == y0:
            return
        if x0 > y0:
            x0, y0 = y0, x0
        self.parent[y0] = x0
        self.count[x0] += self.count[y0] + 1

    def size(self, x):
        # xの属する木の大きさ
        return self.count[self.root(x)] + 1

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

N, M, K = list(map(int, input().split()))
tree = UnionFind(N)
# 同じグループでの友達の数とブロックの数
F, B = [0] * N, [0] * N
lst = []
for m in range(M):
    a, b = list(map(int, input().split()))
    tree.union(a - 1, b - 1)
    lst.append((a, b))
for a, b in lst:
    if tree.same(a - 1, b - 1):
        F[a - 1] += 1
        F[b - 1] += 1
for k in range(K):
    c, d = list(map(int, input().split()))
    if tree.same(c - 1, d - 1):
        B[c - 1] += 1
        B[d - 1] += 1
# nが属する木の大きさから友達の数とブロックの数と自分を除いたのが答え
print((*[tree.size(n) - F[n] - B[n] - 1 for n in range(N)]))

class UnionFind:
    def __init__(self, n):
        self.n = n
        # 親の名(いない場合はNone)
        self.parent = [None] * n
        # 子の数
        self.count = [0] * n

    def root(self, x):
        # xの根を返す
        if self.parent[x] == None:
            return x
        else:
            return self.root(self.parent[x])

    def union(self, x, y):
        # xとyをまとめる
        x0 = self.root(x)
        y0 = self.root(y)
        if x0 == y0:
            return
        if x0 > y0:
            x0, y0 = y0, x0
        self.parent[y0] = x0
        self.count[x0] += self.count[y0] + 1

    def size(self, x):
        # xの属する木の大きさ
        return self.count[self.root(x)] + 1

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

n, m, k = list(map(int, input().split()))
uf = UnionFind(n)
# F[i]=iの友達の数
F = [0] * n
# B[i]=iと同じグループでブロックしている数
B = [0] * n
for i in range(m):
    a, b = list(map(int, input().split()))
    uf.union(a - 1, b - 1)
    F[a - 1] += 1
    F[b - 1] += 1
for j in range(k):
    a, b = list(map(int, input().split()))
    if uf.same(a - 1, b - 1):
        B[a - 1] += 1
        B[b - 1] += 1
L = [uf.size(i) - 1 - F[i] - B[i] for i in range(n)]
print((*L))

-        # 親の名(いない場合は自分)

+        # 親の名(いない場合はNone)

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

-# 同じグループでの友達の数とブロックの数

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

+# B[i]=iと同じグループでブロックしている数

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

-# nが属する木の大きさから友達の数とブロックの数と自分を除いたのが答え

-print((*[tree.size(n) - F[n] - B[n] - 1 for n in range(N)]))

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

+L = [uf.size(i) - 1 - F[i] - B[i] for i in range(n)]


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

T=list(eval(input()))

counter=0

for i in range(len(S)):

    if S[i]!=T[i]:

        counter+=1

print(counter)

S=eval(input())

T=eval(input())

counter=0

for i in range(len(S)):

    if S[i]!=T[i]:

        counter+=1

print(counter)

S = list(eval(input()))
T = list(eval(input()))
counter = 0
for i in range(len(S)):
    if S[i] != T[i]:
        counter += 1
print(counter)

S = eval(input())
T = eval(input())
counter = 0
for i in range(len(S)):
    if S[i] != T[i]:
        counter += 1
print(counter)

-S = list(eval(input()))
-T = list(eval(input()))
+S = eval(input())
+T = eval(input())


Input:
import math

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

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

add_damage = A-B

left = 1

right = 10**9

ans = float('inf')

for i in range(int(math.log(10**9, 2)+1)):

    T = (left+right) // 2

    h = H.copy()

    h = list([max(0, x-T*B) for x in h])

    h = list([math.ceil(x / add_damage) for x in h])

    need = sum(h)

    if need <= T:

        right = T

        ans = min(ans, T)

    else:

        left = T

print((int(ans)))

import math

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

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

add_damage = A-B

left = 1

right = 10**9

ans = float('inf')

for i in range(int(math.log(10**9, 2)+1)):

    T = (left+right) // 2

    h = H.copy()

    h = list([math.ceil(max(0, x-T*B) / add_damage) for x in h])

    need = sum(h)

    if need <= T:

        right = T

        ans = min(ans, T)

    else:

        left = T

print(ans)

import math

N, A, B = list(map(int, input().split()))
H = [int(eval(input())) for i in range(N)]
add_damage = A - B
left = 1
right = 10**9
ans = float("inf")
for i in range(int(math.log(10**9, 2) + 1)):
    T = (left + right) // 2
    h = H.copy()
    h = list([max(0, x - T * B) for x in h])
    h = list([math.ceil(x / add_damage) for x in h])
    need = sum(h)
    if need <= T:
        right = T
        ans = min(ans, T)
    else:
        left = T
print((int(ans)))

import math

N, A, B = list(map(int, input().split()))
H = [int(eval(input())) for i in range(N)]
add_damage = A - B
left = 1
right = 10**9
ans = float("inf")
for i in range(int(math.log(10**9, 2) + 1)):
    T = (left + right) // 2
    h = H.copy()
    h = list([math.ceil(max(0, x - T * B) / add_damage) for x in h])
    need = sum(h)
    if need <= T:
        right = T
        ans = min(ans, T)
    else:
        left = T
print(ans)

-    h = list([max(0, x - T * B) for x in h])

-    h = list([math.ceil(x / add_damage) for x in h])

+    h = list([math.ceil(max(0, x - T * B) / add_damage) for x in h])


Input:
import math

N,D =[int(x) for x in input().split()]

X = []

Y = []

for i in range(N):

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

    X.append(x)

    Y.append(y)

ans = 0

for i in range(N):

    r = math.sqrt(X[i] ** 2 + Y[i] ** 2)

    if r <= D:

        ans += 1

print(ans)

N,D =[int(x) for x in input().split()]

ans = 0

for i in range(N):

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

    if x * x + y * y <= D * D:

        ans += 1

print(ans)

import math

N, D = [int(x) for x in input().split()]
X = []
Y = []
for i in range(N):
    x, y = [int(x) for x in input().split()]
    X.append(x)
    Y.append(y)
ans = 0
for i in range(N):
    r = math.sqrt(X[i] ** 2 + Y[i] ** 2)
    if r <= D:
        ans += 1
print(ans)

N, D = [int(x) for x in input().split()]
ans = 0
for i in range(N):
    x, y = [int(x) for x in input().split()]
    if x * x + y * y <= D * D:
        ans += 1
print(ans)


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

X=eval(input())

def pop(x): #10進数

    ret=0

    while x>0:

        ret+=x%2

        x//=2

    return ret

def solve(x): #10進数

    ret=0

    while x>0:

        pop_c=pop(x)

        x%=pop_c

        ret+=1

    return ret

mod=X.count("1") #>0

original_plus=0

original_minus=0

for i in range(N):

    if X[N-1-i]=="1":

        if mod>1:

            original_minus+=pow(2,i,mod-1)

        original_plus+=pow(2,i,mod+1)

for i in range(N):

    if X[i]=="0":

        tmp=original_plus+pow(2,N-1-i,mod+1)

        tmp%=mod+1

        print((solve(tmp)+1))

    else:

        if mod==1:

            print((0))

            continue

        tmp=original_minus-pow(2,N-1-i,mod-1)

        tmp%=mod-1

        print((solve(tmp)+1))

N=int(eval(input()))

X=eval(input())

def solve(x): #10進数

    ret=0

    while x>0:

        pop=bin(x).count("1")

        x%=pop

        ret+=1

    return ret

mod=X.count("1") #>0

original_plus=0

original_minus=0

for i in range(N):

    if X[N-1-i]=="1":

        if mod>1:

            original_minus+=pow(2,i,mod-1)

        original_plus+=pow(2,i,mod+1)

for i in range(N):

    if X[i]=="0":

        tmp=original_plus+pow(2,N-1-i,mod+1)

        tmp%=mod+1

        print((solve(tmp)+1))

    else:

        if mod==1:

            print((0))

            continue

        tmp=original_minus-pow(2,N-1-i,mod-1)

        tmp%=mod-1

        print((solve(tmp)+1))

N = int(eval(input()))
X = eval(input())

def pop(x):  # 10進数
    ret = 0
    while x > 0:
        ret += x % 2
        x //= 2
    return ret

def solve(x):  # 10進数
    ret = 0
    while x > 0:
        pop_c = pop(x)
        x %= pop_c
        ret += 1
    return ret

mod = X.count("1")  # >0
original_plus = 0
original_minus = 0
for i in range(N):
    if X[N - 1 - i] == "1":
        if mod > 1:
            original_minus += pow(2, i, mod - 1)
        original_plus += pow(2, i, mod + 1)
for i in range(N):
    if X[i] == "0":
        tmp = original_plus + pow(2, N - 1 - i, mod + 1)
        tmp %= mod + 1
        print((solve(tmp) + 1))
    else:
        if mod == 1:
            print((0))
            continue
        tmp = original_minus - pow(2, N - 1 - i, mod - 1)
        tmp %= mod - 1
        print((solve(tmp) + 1))

N = int(eval(input()))
X = eval(input())

def solve(x):  # 10進数
    ret = 0
    while x > 0:
        pop = bin(x).count("1")
        x %= pop
        ret += 1
    return ret

mod = X.count("1")  # >0
original_plus = 0
original_minus = 0
for i in range(N):
    if X[N - 1 - i] == "1":
        if mod > 1:
            original_minus += pow(2, i, mod - 1)
        original_plus += pow(2, i, mod + 1)
for i in range(N):
    if X[i] == "0":
        tmp = original_plus + pow(2, N - 1 - i, mod + 1)
        tmp %= mod + 1
        print((solve(tmp) + 1))
    else:
        if mod == 1:
            print((0))
            continue
        tmp = original_minus - pow(2, N - 1 - i, mod - 1)
        tmp %= mod - 1
        print((solve(tmp) + 1))

-def pop(x):  # 10進数
-    ret = 0
-    while x > 0:
-        ret += x % 2
-        x //= 2
-    return ret
-        pop_c = pop(x)
-        x %= pop_c
+        pop = bin(x).count("1")
+        x %= pop


Input:
a, b, c, x = list(map(int, [eval(input()) for _ in range(4)]))

ans = 0

for i in range(a+1):

    for j in range(b+1):

        for k in range(c+1):

            if i * 500 + j * 100 + k * 50 == x:

                ans += 1

print(ans)

A, B, C, X = list(map(int, [eval(input()) for _ in range(4)]))

ans = 0

for a in range(A+1):

    for b in range(B+1):

        for c in range(C+1):

            if 500*a + 100*b + 50*c == X:

                ans += 1

print(ans)

a, b, c, x = list(map(int, [eval(input()) for _ in range(4)]))
ans = 0
for i in range(a + 1):
    for j in range(b + 1):
        for k in range(c + 1):
            if i * 500 + j * 100 + k * 50 == x:
                ans += 1
print(ans)

A, B, C, X = list(map(int, [eval(input()) for _ in range(4)]))
ans = 0
for a in range(A + 1):
    for b in range(B + 1):
        for c in range(C + 1):
            if 500 * a + 100 * b + 50 * c == X:
                ans += 1
print(ans)

-a, b, c, x = list(map(int, [eval(input()) for _ in range(4)]))

+A, B, C, X = list(map(int, [eval(input()) for _ in range(4)]))


Input:
from math import gcd

def main():

    eval(input())  # N

    array = [int(x) for x in input().split()]

    MAX_A = 10 ** 6 + 2

    histgram = [0] * MAX_A

    for x in array:

        histgram[int(x)] += 1

    pairwise = True

    for divider in range(2, MAX_A):

        count = 0

        for counted in histgram[divider::divider]:

            count += counted

        if count > 1:

            pairwise = False

    if pairwise:

        return 'pairwise coprime'

    gcd_now = 0

    for x in array:

        gcd_now = gcd(x, gcd_now)

    if gcd_now == 1:

        return 'setwise coprime'

    else:

        return 'not coprime'

if __name__ == '__main__':

    print((main()))

from math import gcd

def main():

    eval(input())  # N

    array = [int(x) for x in input().split()]

    MAX_A = 10 ** 6 + 1

    histogram = [0] * MAX_A

    for x in array:

        histogram[int(x)] += 1

    for divider in range(2, MAX_A):

        count = 0

        for counted in histogram[divider::divider]:

            count += counted

        if count > 1:

            break

    else:

        return 'pairwise coprime'

    gcd_now = 0

    for x in array:

        gcd_now = gcd(x, gcd_now)

    if gcd_now == 1:

        return 'setwise coprime'

    else:

        return 'not coprime'

if __name__ == '__main__':

    print((main()))

from math import gcd

def main():
    eval(input())  # N
    array = [int(x) for x in input().split()]
    MAX_A = 10**6 + 2
    histgram = [0] * MAX_A
    for x in array:
        histgram[int(x)] += 1
    pairwise = True
    for divider in range(2, MAX_A):
        count = 0
        for counted in histgram[divider::divider]:
            count += counted
        if count > 1:
            pairwise = False
    if pairwise:
        return "pairwise coprime"
    gcd_now = 0
    for x in array:
        gcd_now = gcd(x, gcd_now)
    if gcd_now == 1:
        return "setwise coprime"
    else:
        return "not coprime"

if __name__ == "__main__":
    print((main()))

from math import gcd

def main():
    eval(input())  # N
    array = [int(x) for x in input().split()]
    MAX_A = 10**6 + 1
    histogram = [0] * MAX_A
    for x in array:
        histogram[int(x)] += 1
    for divider in range(2, MAX_A):
        count = 0
        for counted in histogram[divider::divider]:
            count += counted
        if count > 1:
            break
    else:
        return "pairwise coprime"
    gcd_now = 0
    for x in array:
        gcd_now = gcd(x, gcd_now)
    if gcd_now == 1:
        return "setwise coprime"
    else:
        return "not coprime"

if __name__ == "__main__":
    print((main()))

-        for counted in histgram[divider::divider]:

+        for counted in histogram[divider::divider]:


Input:
import sys

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

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

a=[[a[i],i] for i in range(n)]

if n==1: print((a[0][0]-1));sys.exit()

pre=-1

ans=0

for _ in range(k):

    a.sort(reverse=True)

    if a[0][1]!=pre:

        a[0][0]-=1

        pre=a[0][1]

    elif a[1][0]>0:

        a[1][0]-=1

        pre=a[1][1]

    else:

        ans=a[0][0]

        break

print(ans)

import sys

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

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

if n==1: print((a[0]-1));sys.exit()

a.sort(reverse=True)

ans=max(0,a[0]-1-sum(a[1:]))

print(ans)

import sys

k, n = list(map(int, input().split()))
a = list(map(int, input().split()))
a = [[a[i], i] for i in range(n)]
if n == 1:
    print((a[0][0] - 1))
    sys.exit()
pre = -1
ans = 0
for _ in range(k):
    a.sort(reverse=True)
    if a[0][1] != pre:
        a[0][0] -= 1
        pre = a[0][1]
    elif a[1][0] > 0:
        a[1][0] -= 1
        pre = a[1][1]
    else:
        ans = a[0][0]
        break
print(ans)

import sys

k, n = list(map(int, input().split()))
a = list(map(int, input().split()))
if n == 1:
    print((a[0] - 1))
    sys.exit()
a.sort(reverse=True)
ans = max(0, a[0] - 1 - sum(a[1:]))
print(ans)


Input:
a = [0]*1000000

a[0] = int(eval(input()))

for i in range(1,1000000):

  if a[i-1]%2 == 0:

    if a[i-1]/2 in a:

      print((i+1))

      break

    a[i] = a[i-1]/2

  else:

    if 3*a[i-1]+1 in a:

      print((i+1))

      break

    a[i] = 3*a[i-1]+1

import sys

s=int(eval(input()))

dp=[0]*1000001

dp[s]=1

cnt=1

for i in range(1000001):

  if s%2==1:

    s=3*s+1

  else:

    s//=2

  cnt+=1

  if dp[s]==1:

    print(cnt)

    sys.exit()

  else:

    dp[s]=1

import sys

s = int(eval(input()))
dp = [0] * 1000001
dp[s] = 1
cnt = 1
for i in range(1000001):
    if s % 2 == 1:
        s = 3 * s + 1
    else:
        s //= 2
    cnt += 1
    if dp[s] == 1:
        print(cnt)
        sys.exit()
    else:
        dp[s] = 1


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

print((a+a**2+a**3))

a = int(eval(input()))

print((a + a*a + a**3))

a = int(eval(input()))
print((a + a**2 + a**3))

a = int(eval(input()))
print((a + a * a + a**3))


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

s = eval(input())

p = s[0]

x = s[0]

for i in range(1, n):

  if x == s[i]:

    continue

  else:

    p += s[i]

    x = s[i]

print((len(p)))

n = int(eval(input()))

s = eval(input())

t = s[0]

ans = 1

for i in range(1,n):

  if t != s[i]:

    ans += 1

    t = s[i]

print(ans)

n = int(eval(input()))
s = eval(input())
t = s[0]
ans = 1
for i in range(1, n):
    if t != s[i]:
        ans += 1
        t = s[i]
print(ans)

-p = s[0]
-x = s[0]
+t = s[0]
+ans = 1
-    if x == s[i]:
-        continue
-    else:
-        p += s[i]
-        x = s[i]
-print((len(p)))
+    if t != s[i]:
+        ans += 1
+        t = s[i]
+print(ans)


Input:
import sys

from collections import deque

from heapq import heapify, heappop, heappush

from itertools import combinations, permutations

from bisect import bisect, bisect_left

def solve():

    input = sys.stdin.readline

    N = int(eval(input()))

    strN = str(N)

    maxDig = len(strN)

    count = 0

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

        a = str(i)

        low = int(a[-1])

        if low == 0: continue

        high = int(a[0])

        if low == high: count += 1 #一番上位と下位の桁の数字が同じ

        digb = 2

        while digb < maxDig:

            count += 10 ** (digb - 2)

            digb += 1

        if N >= 10:

            if low > int(strN[0]): continue

            elif low < int(strN[0]): count += 10 ** (digb - 2)

            elif N >= 10:

                DP = [[0, 0] for _ in range(maxDig)]

                DP[0][0] = 1

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

                    DP[j][0] = 1

                    DP[j][1] = DP[j-1][1] * 10 + DP[j-1][0] * (int(strN[j]))

                count += DP[maxDig - 2][1]

                #print(i, DP)

                if int(strN[maxDig - 1]) >= high: count += 1

    print(count)

    return 0

if __name__ == "__main__":

    solve()

import sys

def solve():

    N = int(eval(input()))

    D = dict()

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

        front = i % 10

        back = i

        while back >= 10: back //= 10

        if front > 0:

            if (front, back) in D: D[(front, back)] += 1

            else: D[(front, back)] = 1

    Ans = 0

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

        back = i % 10

        if back > 0:

            front = i

            while front >= 10: front //= 10

            if (front, back) in D: Ans += D[(front, back)]

    print(Ans)

    return 0

if __name__ == "__main__":

    solve()

import sys
from collections import deque
from heapq import heapify, heappop, heappush
from itertools import combinations, permutations
from bisect import bisect, bisect_left

def solve():
    input = sys.stdin.readline
    N = int(eval(input()))
    strN = str(N)
    maxDig = len(strN)
    count = 0
    for i in range(1, N + 1):
        a = str(i)
        low = int(a[-1])
        if low == 0:
            continue
        high = int(a[0])
        if low == high:
            count += 1  # 一番上位と下位の桁の数字が同じ
        digb = 2
        while digb < maxDig:
            count += 10 ** (digb - 2)
            digb += 1
        if N >= 10:
            if low > int(strN[0]):
                continue
            elif low < int(strN[0]):
                count += 10 ** (digb - 2)
            elif N >= 10:
                DP = [[0, 0] for _ in range(maxDig)]
                DP[0][0] = 1
                for j in range(1, maxDig - 1):
                    DP[j][0] = 1
                    DP[j][1] = DP[j - 1][1] * 10 + DP[j - 1][0] * (int(strN[j]))
                count += DP[maxDig - 2][1]
                # print(i, DP)
                if int(strN[maxDig - 1]) >= high:
                    count += 1
    print(count)
    return 0

if __name__ == "__main__":
    solve()

-from heapq import heapify, heappop, heappush

-from itertools import combinations, permutations

-            count += 1  # 一番上位と下位の桁の数字が同じ

-                DP = [[0, 0] for _ in range(maxDig)]

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

-                count += DP[maxDig - 2][1]

-                if int(strN[maxDig - 1]) >= high:

+                Ans += D[(front, back)]


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

"""

dp[i][j] -> i番目の人間までみる。j人が積むときの最小値。

"""

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

HP.sort(key=lambda x:x[0]+x[1])

dp = [float("INF")]*(N+1)

dp[0] = 0

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

    for j in range(N,0,-1):

        if dp[j-1] <= HP[i-1][0]:

            dp[j] = min(dp[j],dp[j-1]+HP[i-1][1])

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

    if dp[j] != float("INF"):

        print(j)

        break

"""

Aさん：身長Ha , パワーPa

Bさん：身長Hb , パワーPb

二人どちらも積めるのに順番を間違えたばかりに一人しか積めない、という事態を避けたい。

Aさんが先に積むべき？Bさんが先に積むべき？

Aさん、Bさんの手前までの時点で高さSまで積みあがっているとする。S <= min(Hb,Ha)とする。

S+Pa > Hb　かつ S+Pb <= HaならBが先

S+Pb > Ha　かつ S+Pa <= HbならAが先

Pa-Hb > Pb-Ha ならBが先でAが後

書き換えるとPa+Ha > Pb+HbならBが先でAが後

つまり、P+H順にソートしてナップサックすればよい

"""

N = int(eval(input()))

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

HP.sort(key = lambda x:x[0]+x[1])

#dp[i][j] -> j人積む場合の座布団の最小枚数

dp = [float("INF")]*(N+1)

dp[0] = 0

for h,p in HP:

    for j in range(N,0,-1):

        if dp[j-1] <= h:

            dp[j] = min(dp[j],dp[j-1]+p)

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

    if dp[j] != float("INF"):

        print(j)

        break

N = int(eval(input()))
"""
dp[i][j] -> i番目の人間までみる。j人が積むときの最小値。
"""
HP = [list(map(int, input().split())) for _ in range(N)]
HP.sort(key=lambda x: x[0] + x[1])
dp = [float("INF")] * (N + 1)
dp[0] = 0
for i in range(1, N + 1):
    for j in range(N, 0, -1):
        if dp[j - 1] <= HP[i - 1][0]:
            dp[j] = min(dp[j], dp[j - 1] + HP[i - 1][1])
for j in range(N, -1, -1):
    if dp[j] != float("INF"):
        print(j)
        break

"""
Aさん：身長Ha , パワーPa
Bさん：身長Hb , パワーPb
二人どちらも積めるのに順番を間違えたばかりに一人しか積めない、という事態を避けたい。
Aさんが先に積むべき？Bさんが先に積むべき？
Aさん、Bさんの手前までの時点で高さSまで積みあがっているとする。S <= min(Hb,Ha)とする。
S+Pa > Hb　かつ S+Pb <= HaならBが先
S+Pb > Ha　かつ S+Pa <= HbならAが先
Pa-Hb > Pb-Ha ならBが先でAが後
書き換えるとPa+Ha > Pb+HbならBが先でAが後
つまり、P+H順にソートしてナップサックすればよい
"""
N = int(eval(input()))
HP = [list(map(int, input().split())) for _ in range(N)]
HP.sort(key=lambda x: x[0] + x[1])
# dp[i][j] -> j人積む場合の座布団の最小枚数
dp = [float("INF")] * (N + 1)
dp[0] = 0
for h, p in HP:
    for j in range(N, 0, -1):
        if dp[j - 1] <= h:
            dp[j] = min(dp[j], dp[j - 1] + p)
for j in range(N, -1, -1):
    if dp[j] != float("INF"):
        print(j)
        break

+Aさん：身長Ha , パワーPa

+Bさん：身長Hb , パワーPb

+二人どちらも積めるのに順番を間違えたばかりに一人しか積めない、という事態を避けたい。

+Aさんが先に積むべき？Bさんが先に積むべき？

+Aさん、Bさんの手前までの時点で高さSまで積みあがっているとする。S <= min(Hb,Ha)とする。

+つまり、P+H順にソートしてナップサックすればよい

-dp[i][j] -> i番目の人間までみる。j人が積むときの最小値。

+# dp[i][j] -> j人積む場合の座布団の最小枚数


Input:
def main():

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

    return " ".join(map(str, [C, A, B]))

if __name__ == '__main__':

    print((main()))

def main():

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

    return " ".join(map(str, [Z, X, Y]))

if __name__ == '__main__':

    print((main()))

def main():
    A, B, C = list(map(int, input().split()))
    return " ".join(map(str, [C, A, B]))

if __name__ == "__main__":
    print((main()))

def main():
    X, Y, Z = list(map(int, input().split()))
    return " ".join(map(str, [Z, X, Y]))

if __name__ == "__main__":
    print((main()))

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

-    return " ".join(map(str, [C, A, B]))

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

+    return " ".join(map(str, [Z, X, Y]))


Input:
from math import gcd

from collections import deque

from bisect import bisect_left,bisect_right

q=int(eval(input()))

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

rmax=max(e[1] for e in lr)

anslst=[]

candlst=deque([2])

pprod=2

for i in range(3,rmax+1,2):

  tmp=2*candlst[0]-1

  if gcd(pprod,i)==1:

    candlst.append(i)

    pprod*=i

    if tmp==i:

      anslst.append(tmp)

  if tmp==i:

    candlst.popleft()

for e in lr:

  print((bisect_right(anslst,e[1])-bisect_left(anslst,e[0])))

q=int(eval(input()))

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

n=10**5

ansl=[]

sieve=[1]*(n+1)

sieve[0],sieve[1]=0,0

for i in range(2,n):

  if sieve[i]:

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

      sieve[j]=0

ans=[0]*(n+1)

for i in range(3,n):

  if sieve[i]==1 and sieve[(i+1)//2]==1:

    ans[i]=ans[i-1]+1

  else:

    ans[i]=ans[i-1]

for e in lr:

  print((ans[e[1]]-ans[e[0]-1]))

from math import gcd
from collections import deque
from bisect import bisect_left, bisect_right

q = int(eval(input()))
lr = [tuple(map(int, input().split())) for _ in range(q)]
rmax = max(e[1] for e in lr)
anslst = []
candlst = deque([2])
pprod = 2
for i in range(3, rmax + 1, 2):
    tmp = 2 * candlst[0] - 1
    if gcd(pprod, i) == 1:
        candlst.append(i)
        pprod *= i
        if tmp == i:
            anslst.append(tmp)
    if tmp == i:
        candlst.popleft()
for e in lr:
    print((bisect_right(anslst, e[1]) - bisect_left(anslst, e[0])))

q = int(eval(input()))
lr = [tuple(map(int, input().split())) for _ in range(q)]
n = 10**5
ansl = []
sieve = [1] * (n + 1)
sieve[0], sieve[1] = 0, 0
for i in range(2, n):
    if sieve[i]:
        for j in range(2 * i, n + 1, i):
            sieve[j] = 0
ans = [0] * (n + 1)
for i in range(3, n):
    if sieve[i] == 1 and sieve[(i + 1) // 2] == 1:
        ans[i] = ans[i - 1] + 1
    else:
        ans[i] = ans[i - 1]
for e in lr:
    print((ans[e[1]] - ans[e[0] - 1]))

-from bisect import bisect_left, bisect_right

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

-    print((bisect_right(anslst, e[1]) - bisect_left(anslst, e[0])))


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

m = n//x

if n%x==0:

  print((m*t))

else:

  print((m*t+t))

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

if n%x==0:

  print((n//x*t))

else:

  print((n//x*t + t))

n, x, t = list(map(int, input().split()))
m = n // x
if n % x == 0:
    print((m * t))
else:
    print((m * t + t))

n, x, t = list(map(int, input().split()))
if n % x == 0:
    print((n // x * t))
else:
    print((n // x * t + t))

-m = n // x
-    print((m * t))
+    print((n // x * t))
-    print((m * t + t))
+    print((n // x * t + t))


Input:
def dfs():

  stack = [[0]]

  count = 0

  while stack:

    route = stack.pop()

    if len(route) == N:

      #print 'route=',route

      count += 1

      continue

    now = route[-1]

    for next in [x for x in range(N) if EDGES[now][x] == 1]:

      #print 'now,next',now,next

      if next in route:

        continue

      newroute = route[:]

      newroute.append(next)

      stack.append(newroute)

  return count

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

EDGES = [[0 for i in range(N)] for i in range(N)]

for i in range(M):

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

  EDGES[a-1][b-1] = 1

  EDGES[b-1][a-1] = 1

print(dfs())

import itertools

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

es = [[0 for j in range(N)] for i in range(N)]

for i in range(M):

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

    a,b = a-1,b-1

    es[a][b] = es[b][a] = 1

ans = 0

for ptn in itertools.permutations(list(range(1,N))):

    prev = 0

    for v in ptn:

        if not es[prev][v]:

            break

        prev = v

    else:

        ans += 1

print(ans)

def dfs():
    stack = [[0]]
    count = 0
    while stack:
        route = stack.pop()
        if len(route) == N:
            # print 'route=',route
            count += 1
            continue
        now = route[-1]
        for next in [x for x in range(N) if EDGES[now][x] == 1]:
            # print 'now,next',now,next
            if next in route:
                continue
            newroute = route[:]
            newroute.append(next)
            stack.append(newroute)
    return count

N, M = list(map(int, input().split()))
EDGES = [[0 for i in range(N)] for i in range(N)]
for i in range(M):
    a, b = list(map(int, input().split()))
    EDGES[a - 1][b - 1] = 1
    EDGES[b - 1][a - 1] = 1
print(dfs())

import itertools

N, M = list(map(int, input().split()))
es = [[0 for j in range(N)] for i in range(N)]
for i in range(M):
    a, b = list(map(int, input().split()))
    a, b = a - 1, b - 1
    es[a][b] = es[b][a] = 1
ans = 0
for ptn in itertools.permutations(list(range(1, N))):
    prev = 0
    for v in ptn:
        if not es[prev][v]:
            break
        prev = v
    else:
        ans += 1
print(ans)

-        for next in [x for x in range(N) if EDGES[now][x] == 1]:

-            # print 'now,next',now,next

-EDGES = [[0 for i in range(N)] for i in range(N)]

+es = [[0 for j in range(N)] for i in range(N)]

+for ptn in itertools.permutations(list(range(1, N))):


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

WV = [list(map(int,input().split())) for _ in [0]*N]

#dp[i][n:入れた数][dW:w1からの差分の合計]

dp = [[[0]*(3*N+1) for _ in [0]*(N+1)] for _ in [0]*(N+1)]

w0 = WV[0][0]

for i,wv in enumerate(WV,1):

    w,v = wv

    w -= w0

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

        for dW in range(3*N+1):

            if n*w0 + dW > W:break

            if w>dW:

                dp[i][n][dW] = dp[i-1][n][dW]

                continue

            dp[i][n][dW] = max(dp[i-1][n][dW],dp[i-1][n-1][dW-w]+v)

print((max(max(row) for row in dp[-1])))

#メモ化再帰

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

WV = [list(map(int,input().split())) for _ in [0]*N]

memo = [{} for _ in [0]*(N+1)]

def dp(i,j):

    if j<=0 or i<=0: return 0

    if j in memo[i]:return memo[i][j]

    w,v = WV[i-1]

    ret = dp(i-1,j)

    if j-w>=0: ret = max(ret,dp(i-1,j-w)+v)

    memo[i][j] = ret

    return ret

print((dp(N,W)))

N, W = list(map(int, input().split()))
WV = [list(map(int, input().split())) for _ in [0] * N]
# dp[i][n:入れた数][dW:w1からの差分の合計]
dp = [[[0] * (3 * N + 1) for _ in [0] * (N + 1)] for _ in [0] * (N + 1)]
w0 = WV[0][0]
for i, wv in enumerate(WV, 1):
    w, v = wv
    w -= w0
    for n in range(1, i + 1):
        for dW in range(3 * N + 1):
            if n * w0 + dW > W:
                break
            if w > dW:
                dp[i][n][dW] = dp[i - 1][n][dW]
                continue
            dp[i][n][dW] = max(dp[i - 1][n][dW], dp[i - 1][n - 1][dW - w] + v)
print((max(max(row) for row in dp[-1])))

# メモ化再帰
N, W = list(map(int, input().split()))
WV = [list(map(int, input().split())) for _ in [0] * N]
memo = [{} for _ in [0] * (N + 1)]

def dp(i, j):
    if j <= 0 or i <= 0:
        return 0
    if j in memo[i]:
        return memo[i][j]
    w, v = WV[i - 1]
    ret = dp(i - 1, j)
    if j - w >= 0:
        ret = max(ret, dp(i - 1, j - w) + v)
    memo[i][j] = ret
    return ret

print((dp(N, W)))

-print((max(max(row) for row in dp[-1])))

+        ret = max(ret, dp(i - 1, j - w) + v)


Input:
import sys

import itertools

sys.setrecursionlimit(1000000000)

from heapq import heapify,heappop,heappush,heappushpop

import math

import collections

import copy

if __name__ == "__main__":

    n = int(eval(input()))

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

    b = a[0]

    for i in range(1,n):

        b = b^a[i]

    for i in range(n):

        print((a[i]^b))

import sys

import itertools

sys.setrecursionlimit(1000000000)

from heapq import heapify,heappop,heappush,heappushpop

import math

import collections

import copy

def main():

    n = int(eval(input()))

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

    b = a[0]

    for i in range(1,n):

        b = b^a[i]

    ans = []

    for i in range(n):

        ans.append(b^a[i])

    print((*ans))

if __name__ == "__main__":

    main()

import sys
import itertools

sys.setrecursionlimit(1000000000)
from heapq import heapify, heappop, heappush, heappushpop
import math
import collections
import copy

if __name__ == "__main__":
    n = int(eval(input()))
    a = list(map(int, input().split()))
    b = a[0]
    for i in range(1, n):
        b = b ^ a[i]
    for i in range(n):
        print((a[i] ^ b))

import sys
import itertools

sys.setrecursionlimit(1000000000)
from heapq import heapify, heappop, heappush, heappushpop
import math
import collections
import copy

def main():
    n = int(eval(input()))
    a = list(map(int, input().split()))
    b = a[0]
    for i in range(1, n):
        b = b ^ a[i]
    ans = []
    for i in range(n):
        ans.append(b ^ a[i])
    print((*ans))

if __name__ == "__main__":
    main()


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

M=list(input() for _ in range(h))

c=[]

for i in range(h):

    if "#" not in M[i]:

        c.append(i)

for dot in c[::-1]:

    M.pop(dot)

c=[]

col=[]

for i in range(len(M[0])):

    flag=1

    for j in range(len(M)):

        if "#" in M[j][i]:flag=0

    if flag==1:c.append(i)

for i in c[::-1]:

    for row in M:

        list(row).pop(i)

for i in range(len(M)):

    flag=0

    for j in range(len(M[0])):

        if j not in c:

            print(*M[i][j],end="")

            flag=1

    if i<len(M)-1 and flag==1:print()

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

a = [eval(input()) for _ in range(h)]

c = 0

#行の中で「....」があれば取り除く.

while "."*w in a:

    a.remove("."*w) #removeは該当要素のうち最初の要素を削除

    c += 1

#行と列の入れ替え

a = ["".join(column) for column in zip(*a)]

while "."*(h-c) in a:

    a.remove("."*(h-c))

#行と列を再度入れ替えて出力.

for row in zip(*a):

    print(("".join(row)))

h, w = map(int, input().split())
M = list(input() for _ in range(h))
c = []
for i in range(h):
    if "#" not in M[i]:
        c.append(i)
for dot in c[::-1]:
    M.pop(dot)
c = []
col = []
for i in range(len(M[0])):
    flag = 1
    for j in range(len(M)):
        if "#" in M[j][i]:
            flag = 0
    if flag == 1:
        c.append(i)
for i in c[::-1]:
    for row in M:
        list(row).pop(i)
for i in range(len(M)):
    flag = 0
    for j in range(len(M[0])):
        if j not in c:
            print(*M[i][j], end="")
            flag = 1
    if i < len(M) - 1 and flag == 1:
        print()

h, w = list(map(int, input().split()))
a = [eval(input()) for _ in range(h)]
c = 0
# 行の中で「....」があれば取り除く.
while "." * w in a:
    a.remove("." * w)  # removeは該当要素のうち最初の要素を削除
    c += 1
# 行と列の入れ替え
a = ["".join(column) for column in zip(*a)]
while "." * (h - c) in a:
    a.remove("." * (h - c))
# 行と列を再度入れ替えて出力.
for row in zip(*a):
    print(("".join(row)))

+# 行の中で「....」があれば取り除く.

+    a.remove("." * w)  # removeは該当要素のうち最初の要素を削除

+a = ["".join(column) for column in zip(*a)]

+# 行と列を再度入れ替えて出力.


Input:
#!/usr/bin/env python3

import sys

# from collections import Counter

INF = float("inf")

class MaxBit:

    def __init__(self, n):

        self.size = n

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

    def sum(self, i):

        s = 0

        while i > 0:

            s = max(s, self.tree[i])

            i -= i & -i

        return s

    def add(self, i, x):

        while i <= self.size:

            self.tree[i] = max(self.tree[i], x)

            i += i & -i

class MinBit:

    def __init__(self, n):

        self.size = n

        self.tree = [n-1] * (n + 1)

    def sum(self, i):

        s = self.size-1

        while i > 0:

            s = min(s, self.tree[i])

            i -= i & -i

        return s

    def add(self, i, x):

        while i <= self.size:

            self.tree[i] = min(self.tree[i], x)

            i += i & -i

def solve(N: int, P: "List[int]"):

    prev = MaxBit(N+2)

    foll = MinBit(N+2)

    seq = [0]*(N+2)

    inv = {p: i for i, p in enumerate(P)}

    # print(inv)

    # c = Counter()

    ans = 0

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

        prev.add(inv[i]+2, inv[i]+1)

        foll.add(N-inv[i]+1, inv[i]+1)

        seq[inv[i]+1] = i

        # print("")

        # print("{}番目に{}を追加".format(inv[i]+1, i))

        # print("seq : ", seq)

        # print("prev: ", [prev.sum(j) for j in range(N+2)])

        # print("foll: ", [foll.sum(j) for j in range(N+2)][::-1])

        p = prev.sum(inv[i]+1)

        pp = prev.sum(p)

        f = foll.sum(N-inv[i])

        ff = foll.sum(N-f+1)

        # 前の数字との組み合わせ

        if p > 0:

            # (前、今) 前に伸ばす * 後ろに伸ばす

            ans += i*(p-pp)*(f-(inv[i]+1))

            # print("+ (A): ", i*(p-pp)*(f-(inv[i]+1)))

            # c[i] += (p - pp) * (f - (inv[i]+1))

        # 後ろの数字との組み合わせ

        if f < N+1:

            # (今、後) 前に伸ばす * 後に伸ばす

            ans += i*(inv[i]+1 - p) * (ff - f)

            # print("+ (B): ", i*(inv[i]+1 - p)*(ff-f))

            # c[i] += (ff - f) * ((inv[i]+1) - p)

    print(ans)

    # print([(i+1, c[i+1]) for i in range(N)])

    # guchoku = Counter()

    # for i in range(N):

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

    #         guchoku[sorted(P[i:j+1])[-2]] += 1

    #         print(sorted(P[i:j+1])[-2], P[i:j+1])

    # print([(i+1, guchoku[i+1]) for i in range(N)])

    return

def main():

    def iterate_tokens():

        for line in sys.stdin:

            for word in line.split():

                yield word

    tokens = iterate_tokens()

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

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

    solve(N, P)

if __name__ == '__main__':

    main()

N = int(eval(input()))

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

pos = {}

for i, p in enumerate(P):

    pos[p] = i+1

foll = [i+1 for i in range(N+1)]+[N+1]

prev = [0]+[i for i in range(N+1)]

ans = 0

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

    curr = pos[i]

    r = foll[curr]

    rr = foll[r]

    l = prev[curr]

    ll = prev[l]

    ans += (l-ll)*(r-curr)*i

    ans += (rr-r)*(curr-l)*i

    foll[l] = foll[curr]

    prev[r] = prev[curr]

    # print(*foll)

    # print(*prev)

print(ans)

#!/usr/bin/env python3
import sys

# from collections import Counter
INF = float("inf")

class MaxBit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s = max(s, self.tree[i])
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] = max(self.tree[i], x)
            i += i & -i

class MinBit:
    def __init__(self, n):
        self.size = n
        self.tree = [n - 1] * (n + 1)

    def sum(self, i):
        s = self.size - 1
        while i > 0:
            s = min(s, self.tree[i])
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] = min(self.tree[i], x)
            i += i & -i

def solve(N: int, P: "List[int]"):
    prev = MaxBit(N + 2)
    foll = MinBit(N + 2)
    seq = [0] * (N + 2)
    inv = {p: i for i, p in enumerate(P)}
    # print(inv)
    # c = Counter()
    ans = 0
    for i in range(N, 0, -1):
        prev.add(inv[i] + 2, inv[i] + 1)
        foll.add(N - inv[i] + 1, inv[i] + 1)
        seq[inv[i] + 1] = i
        # print("")
        # print("{}番目に{}を追加".format(inv[i]+1, i))
        # print("seq : ", seq)
        # print("prev: ", [prev.sum(j) for j in range(N+2)])
        # print("foll: ", [foll.sum(j) for j in range(N+2)][::-1])
        p = prev.sum(inv[i] + 1)
        pp = prev.sum(p)
        f = foll.sum(N - inv[i])
        ff = foll.sum(N - f + 1)
        # 前の数字との組み合わせ
        if p > 0:
            # (前、今) 前に伸ばす * 後ろに伸ばす
            ans += i * (p - pp) * (f - (inv[i] + 1))
            # print("+ (A): ", i*(p-pp)*(f-(inv[i]+1)))
            # c[i] += (p - pp) * (f - (inv[i]+1))
        # 後ろの数字との組み合わせ
        if f < N + 1:
            # (今、後) 前に伸ばす * 後に伸ばす
            ans += i * (inv[i] + 1 - p) * (ff - f)
            # print("+ (B): ", i*(inv[i]+1 - p)*(ff-f))
            # c[i] += (ff - f) * ((inv[i]+1) - p)
    print(ans)
    # print([(i+1, c[i+1]) for i in range(N)])
    # guchoku = Counter()
    # for i in range(N):
    #     for j in range(i+1, N):
    #         guchoku[sorted(P[i:j+1])[-2]] += 1
    #         print(sorted(P[i:j+1])[-2], P[i:j+1])
    # print([(i+1, guchoku[i+1]) for i in range(N)])
    return

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

    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, P)

if __name__ == "__main__":
    main()

N = int(eval(input()))
P = list(map(int, input().split()))
pos = {}
for i, p in enumerate(P):
    pos[p] = i + 1
foll = [i + 1 for i in range(N + 1)] + [N + 1]
prev = [0] + [i for i in range(N + 1)]
ans = 0
for i in range(1, N + 1):
    curr = pos[i]
    r = foll[curr]
    rr = foll[r]
    l = prev[curr]
    ll = prev[l]
    ans += (l - ll) * (r - curr) * i
    ans += (rr - r) * (curr - l) * i
    foll[l] = foll[curr]
    prev[r] = prev[curr]
    # print(*foll)
    # print(*prev)
print(ans)

-            self.tree[i] = max(self.tree[i], x)

-            self.tree[i] = min(self.tree[i], x)

-    inv = {p: i for i, p in enumerate(P)}

-        prev.add(inv[i] + 2, inv[i] + 1)

-        foll.add(N - inv[i] + 1, inv[i] + 1)

-        # print("{}番目に{}を追加".format(inv[i]+1, i))

-        # print("prev: ", [prev.sum(j) for j in range(N+2)])

-        # print("foll: ", [foll.sum(j) for j in range(N+2)][::-1])

-        # 前の数字との組み合わせ

-            # (前、今) 前に伸ばす * 後ろに伸ばす

-        # 後ろの数字との組み合わせ

-            # (今、後) 前に伸ばす * 後に伸ばす

-    # print([(i+1, c[i+1]) for i in range(N)])

-    # print([(i+1, guchoku[i+1]) for i in range(N)])

-    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"

+foll = [i + 1 for i in range(N + 1)] + [N + 1]


Input:
from heapq import heappop, heappush, heapify

K = int(eval(input()))

M = K

que = list(range(1, 10))

V = set()

heapify(que)

while M + 100 >= 0:

    top = heappop(que)

    if top in V:

        continue

    V.add(top)

    M -= 1

    top = str(top)

    L = int(top[0])

    R = int(top[-1])

    for i in (L - 1, L, L + 1):

        if 1 <= i <= 9:

            heappush(que, int(str(i) + top))

    for i in (R - 1, R, R + 1):

        if 0 <= i <= 9:

            heappush(que, int(top + str(i)))

V = [int(d) for d in V]

V.sort()

print((V[K - 1]))

from collections import deque

K = int(eval(input()))

que = deque(list(map(str, list(range(1, 10)))))

while K > 1:

    n = que.popleft()

    K -= 1

    R = int(n[-1])

    for r in (R - 1, R, R + 1):

        if 0 <= r <= 9:

            que.append(n + str(r))

print((que[0]))

-from heapq import heappop, heappush, heapify

-            heappush(que, int(str(i) + top))

-            heappush(que, int(top + str(i)))

+que = deque(list(map(str, list(range(1, 10)))))


Input:
import numpy as np

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

cnt = [[0]*(n+1)for _ in range(n+1)]

for _ in range(m):

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

    cnt[L][R] += 1

S = np.cumsum(cnt, axis=0).cumsum(axis=1)

for _ in range(q):

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

    ans = S[R][R]-S[R][L-1]-S[L-1][R]+S[L-1][L-1]

    print(ans)

import numpy as np

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

cnt = [[0]*(n+1)for _ in range(n+1)]

for _ in range(m):

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

    cnt[L][R] += 1

S = np.cumsum(cnt, axis=0).cumsum(axis=1).tolist()

for _ in range(q):

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

    ans = S[R][R]-S[R][L-1]-S[L-1][R]+S[L-1][L-1]

    print(ans)

import numpy as np

n, m, q = list(map(int, input().split()))
cnt = [[0] * (n + 1) for _ in range(n + 1)]
for _ in range(m):
    L, R = list(map(int, input().split()))
    cnt[L][R] += 1
S = np.cumsum(cnt, axis=0).cumsum(axis=1)
for _ in range(q):
    L, R = list(map(int, input().split()))
    ans = S[R][R] - S[R][L - 1] - S[L - 1][R] + S[L - 1][L - 1]
    print(ans)

import numpy as np

n, m, q = list(map(int, input().split()))
cnt = [[0] * (n + 1) for _ in range(n + 1)]
for _ in range(m):
    L, R = list(map(int, input().split()))
    cnt[L][R] += 1
S = np.cumsum(cnt, axis=0).cumsum(axis=1).tolist()
for _ in range(q):
    L, R = list(map(int, input().split()))
    ans = S[R][R] - S[R][L - 1] - S[L - 1][R] + S[L - 1][L - 1]
    print(ans)

-S = np.cumsum(cnt, axis=0).cumsum(axis=1)

+S = np.cumsum(cnt, axis=0).cumsum(axis=1).tolist()


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

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

T = []

for i in range(N):

    T.append([R[i][0] + R[i][1], R[i][0] - R[i][1]])

T.sort(reverse=True)

while len(T) - 1 > 0:

    t = T.pop()

    i = 1

    while len(T) and t[0] > T[-1][1]:

        N -= 1

        i += 1

        T.pop()

print(N)

N = int(eval(input()))

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

A = []

for x, l in XL:

    A.append([x + l, x - l])

A.sort()

B = []

i = 0

while True:

    B.append(A[i])

    if i == N - 1:

        break

    j = 1

    while True:

        if A[i][0] > A[i + j][1]:

            j += 1

            if i + j == N:

                break

            continue

        else:

            break

    if i + j == N:

        break

    i = i + j

print((len(B)))

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

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


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

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

left, right = 0,0

for ai in A:

  if ai < X: left+=1

  else: right+=1

print((min(right, left)))

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

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

r = len([ai for ai in A if ai < X])

l = len([ai for ai in A if ai > X])

print((min((r,l))))

N, M, X = list(map(int, input().split(" ")))
A = list(map(int, input().split(" ")))
left, right = 0, 0
for ai in A:
    if ai < X:
        left += 1
    else:
        right += 1
print((min(right, left)))

N, M, X = list(map(int, input().split(" ")))
A = list(map(int, input().split(" ")))
r = len([ai for ai in A if ai < X])
l = len([ai for ai in A if ai > X])
print((min((r, l))))

-left, right = 0, 0
-for ai in A:
-    if ai < X:
-        left += 1
-    else:
-        right += 1
-print((min(right, left)))
+r = len([ai for ai in A if ai < X])
+l = len([ai for ai in A if ai > X])
+print((min((r, l))))


Input:
x=input().split()

longestWord= ""

mostWord=0

currentCount=0

THEmostWord=""

for r in range (len(x)):

    if len(x[r])> len(longestWord):

        longestWord=x[r]

for j in range (len(x)):

    thing= x[j]

    currentCount=x.count(thing)

    if currentCount > mostWord:

        mostWord= currentCount

        THEmostWord=thing

print((THEmostWord, longestWord))

a=input().split()

dawa=''

d={}

for w in a:

	if len(w)>len(dawa): dawa=w

	d[a.count(w)]=w

m=max(d.keys())

akeh=d.get(m)

print('%s %s' % (akeh,dawa))

x = input().split()
longestWord = ""
mostWord = 0
currentCount = 0
THEmostWord = ""
for r in range(len(x)):
    if len(x[r]) > len(longestWord):
        longestWord = x[r]
for j in range(len(x)):
    thing = x[j]
    currentCount = x.count(thing)
    if currentCount > mostWord:
        mostWord = currentCount
        THEmostWord = thing
print((THEmostWord, longestWord))

a = input().split()
dawa = ""
d = {}
for w in a:
    if len(w) > len(dawa):
        dawa = w
    d[a.count(w)] = w
m = max(d.keys())
akeh = d.get(m)
print("%s %s" % (akeh, dawa))

-x = input().split()
-longestWord = ""
-mostWord = 0
-currentCount = 0
-THEmostWord = ""
-for r in range(len(x)):
-    if len(x[r]) > len(longestWord):
-        longestWord = x[r]
-for j in range(len(x)):
-    thing = x[j]
-    currentCount = x.count(thing)
-    if currentCount > mostWord:
-        mostWord = currentCount
-        THEmostWord = thing
-print((THEmostWord, longestWord))
+a = input().split()
+dawa = ""
+d = {}
+for w in a:
+    if len(w) > len(dawa):
+        dawa = w
+    d[a.count(w)] = w
+m = max(d.keys())
+akeh = d.get(m)
+print("%s %s" % (akeh, dawa))


Input:
import math

import itertools

n=int(eval(input()))

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

ans=cnt=0

for i in itertools.permutations([_ for _ in range(n)]):

  for j in range(n-1):

    x1,x2=d[i[j]][0],d[i[j+1]][0]

    y1,y2=d[i[j]][1],d[i[j+1]][1]

    ans+=math.sqrt((x1-x2)**2+(y1-y2)**2)

  cnt+=1

  #print(j,ans,cnt)

print((ans/cnt))

n=int(eval(input()))

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

ans=cnt=0

for i in range(n):

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

    ans+=((d[i][0]-d[j][0])**2+(d[i][1]-d[j][1])**2)**0.5

print((2*ans/n))

import math
import itertools

n = int(eval(input()))
d = [list(map(int, input().split())) for _ in range(n)]
ans = cnt = 0
for i in itertools.permutations([_ for _ in range(n)]):
    for j in range(n - 1):
        x1, x2 = d[i[j]][0], d[i[j + 1]][0]
        y1, y2 = d[i[j]][1], d[i[j + 1]][1]
        ans += math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
    cnt += 1
    # print(j,ans,cnt)
print((ans / cnt))

n = int(eval(input()))
d = [list(map(int, input().split())) for _ in range(n)]
ans = cnt = 0
for i in range(n):
    for j in range(i + 1, n):
        ans += ((d[i][0] - d[j][0]) ** 2 + (d[i][1] - d[j][1]) ** 2) ** 0.5
print((2 * ans / n))

-for i in itertools.permutations([_ for _ in range(n)]):


Input:
def main():

    s = eval(input())

    st = [s]

    while st:

        x = st.pop()

        if x == '':

            print('YES')

            return

        for w in ('dream', 'dreamer', 'erase', 'eraser'):

            if x.endswith(w):

                st.append(x[:-len(w)])

    print('NO')

if __name__ == '__main__':

    main()

def main():

    from functools import lru_cache

    import sys

    sys.setrecursionlimit(10 ** 7)

    WORDS = 'dream', 'dreamer', 'erase', 'eraser'

    S = eval(input())

    N = len(S)

    @lru_cache(maxsize=None)

    def dfs(cur=N):

        if cur == 0:

            return True

        for word in WORDS:

            if S[cur - len(word):cur] == word:

                if dfs(cur - len(word)):

                    return True

        return False

    cond = dfs()

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

if __name__ == '__main__':

    main()

def main():
    s = eval(input())
    st = [s]
    while st:
        x = st.pop()
        if x == "":
            print("YES")
            return
        for w in ("dream", "dreamer", "erase", "eraser"):
            if x.endswith(w):
                st.append(x[: -len(w)])
    print("NO")

if __name__ == "__main__":
    main()

def main():
    from functools import lru_cache
    import sys

    sys.setrecursionlimit(10**7)
    WORDS = "dream", "dreamer", "erase", "eraser"
    S = eval(input())
    N = len(S)

    @lru_cache(maxsize=None)
    def dfs(cur=N):
        if cur == 0:
            return True
        for word in WORDS:
            if S[cur - len(word) : cur] == word:
                if dfs(cur - len(word)):
                    return True
        return False

    cond = dfs()
    print(("YES" if cond else "NO"))

if __name__ == "__main__":
    main()

-        for w in ("dream", "dreamer", "erase", "eraser"):

-                st.append(x[: -len(w)])

+    WORDS = "dream", "dreamer", "erase", "eraser"

+            if S[cur - len(word) : cur] == word:

+                if dfs(cur - len(word)):


Input:
import sys

from collections import deque

def solve():

    input = sys.stdin.readline

    N = int(eval(input()))

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

    for _ in range(N-1):

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

        Edge[a-1].append((b-1, c))

        Edge[b-1].append((a-1, c))

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

    q = deque()

    Dist = [-1] * N

    q.append((K-1, K-1, 0))

    while q:

        nowN, preN, nD = q.popleft()

        if Dist[nowN] == -1:

            Dist[nowN] = nD

            for e, add in Edge[nowN]:

                if e != preN: q.append((e, nowN, nD + add))

    Ans = [None] * Q

    for i in range(Q):

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

        Ans[i] = str(Dist[x-1] + Dist[y-1])

    print(("\n".join(Ans)))

    return 0

if __name__ == "__main__":

    solve()

mod = 1000000007

eps = 10**-9

def main():

    import sys

    from collections import deque

    input = sys.stdin.buffer.readline

    N = int(eval(input()))

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

    for _ in range(N-1):

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

        adj[a].append((b, c))

        adj[b].append((a, c))

    Q, root = list(map(int, input().split()))

    que = deque()

    que.append(root)

    seen = [-1] * (N+1)

    seen[root] = 0

    par = [0] * (N+1)

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

    seq = []

    while que:

        v = que.popleft()

        seq.append(v)

        for u, c in adj[v]:

            if seen[u] == -1:

                seen[u] = seen[v] + c

                par[u] = v

                child[v].append(u)

                que.append(u)

    seq.reverse()

    for _ in range(Q):

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

        print((seen[x] + seen[y]))

if __name__ == '__main__':

    main()

import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    N = int(eval(input()))
    Edge = [[] for _ in range(N)]
    for _ in range(N - 1):
        a, b, c = list(map(int, input().split()))
        Edge[a - 1].append((b - 1, c))
        Edge[b - 1].append((a - 1, c))
    Q, K = list(map(int, input().split()))
    q = deque()
    Dist = [-1] * N
    q.append((K - 1, K - 1, 0))
    while q:
        nowN, preN, nD = q.popleft()
        if Dist[nowN] == -1:
            Dist[nowN] = nD
            for e, add in Edge[nowN]:
                if e != preN:
                    q.append((e, nowN, nD + add))
    Ans = [None] * Q
    for i in range(Q):
        x, y = list(map(int, input().split()))
        Ans[i] = str(Dist[x - 1] + Dist[y - 1])
    print(("\n".join(Ans)))
    return 0

if __name__ == "__main__":
    solve()

mod = 1000000007
eps = 10**-9

def main():
    import sys
    from collections import deque

    input = sys.stdin.buffer.readline
    N = int(eval(input()))
    adj = [[] for _ in range(N + 1)]
    for _ in range(N - 1):
        a, b, c = list(map(int, input().split()))
        adj[a].append((b, c))
        adj[b].append((a, c))
    Q, root = list(map(int, input().split()))
    que = deque()
    que.append(root)
    seen = [-1] * (N + 1)
    seen[root] = 0
    par = [0] * (N + 1)
    child = [[] for _ in range(N + 1)]
    seq = []
    while que:
        v = que.popleft()
        seq.append(v)
        for u, c in adj[v]:
            if seen[u] == -1:
                seen[u] = seen[v] + c
                par[u] = v
                child[v].append(u)
                que.append(u)
    seq.reverse()
    for _ in range(Q):
        x, y = list(map(int, input().split()))
        print((seen[x] + seen[y]))

if __name__ == "__main__":
    main()

-    Q, K = list(map(int, input().split()))

-                    q.append((e, nowN, nD + add))

+    Q, root = list(map(int, input().split()))

-        Ans[i] = str(Dist[x - 1] + Dist[y - 1])


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

S=eval(input())

print(("".join(chr(65+(ord(s)-65+N)%26) for s in S)))

N=int(eval(input()))

S=eval(input())

print((bytes((s-65+N)%26+65 for s in S.encode()).decode()))

N = int(eval(input()))
S = eval(input())
print(("".join(chr(65 + (ord(s) - 65 + N) % 26) for s in S)))

N = int(eval(input()))
S = eval(input())
print((bytes((s - 65 + N) % 26 + 65 for s in S.encode()).decode()))

+print((bytes((s - 65 + N) % 26 + 65 for s in S.encode()).decode()))


Input:
from functools import reduce

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

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

count = 0

for i in range(n):

    if reduce(

        lambda x, y: x + y[0] * y[1],

        list(zip(bs, list(map(int, input().split())))),

        0,

    ) + c > 0:

        count += 1

print(count)

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

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

count = 0

for _ in range(n):

    if sum(x * bs[i] for i, x in enumerate(map(int, input().split()))) + c > 0:

        count += 1

print(count)

from functools import reduce

n, _, c = list(map(int, input().split()))
bs = tuple(map(int, input().split()))
count = 0
for i in range(n):
    if (
        reduce(
            lambda x, y: x + y[0] * y[1],
            list(zip(bs, list(map(int, input().split())))),
            0,
        )
        + c
        > 0
    ):
        count += 1
print(count)

-            list(zip(bs, list(map(int, input().split())))),

+    if sum(x * bs[i] for i, x in enumerate(map(int, input().split()))) + c > 0:


Input: a,b,c=list(map(int,input().split()));print((['NO','YES'][b-a==c-b]))

a, b, c = list(map(int, input().split()))
print((["NO", "YES"][b - a == c - b]))

a, b, c = list(map(int, input().split()))
print(("YNEOS"[b - a != c - b :: 2]))


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

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

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

ans=0

for i in range(1<<N):

  sw=[False]*M

  for j in range(M):

    cnt=0

    for k in range(1,len(S[j])):

      if (i>>(S[j][k]-1))&1:

        cnt+=1

      else:

        flag=0

    if cnt%2==P[j]:

      sw[j]=True

  if all(sw):

    ans+=1

print(ans)

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

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

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

ans=0

for i in range(1<<N):

  judge=1

  for j in range(M):

    cnt=0

    for k in KS[j][1:]:

      if i>>(k-1)&1:

        cnt+=1

    if (cnt%2)!=p[j]:

      judge=0

  if judge==1:

    ans+=1

print(ans)

N, M = list(map(int, input().split()))
S = [list(map(int, input().split())) for _ in range(M)]
P = list(map(int, input().split()))
ans = 0
for i in range(1 << N):
    sw = [False] * M
    for j in range(M):
        cnt = 0
        for k in range(1, len(S[j])):
            if (i >> (S[j][k] - 1)) & 1:
                cnt += 1
            else:
                flag = 0
        if cnt % 2 == P[j]:
            sw[j] = True
    if all(sw):
        ans += 1
print(ans)

N, M = list(map(int, input().split()))
KS = [list(map(int, input().split())) for _ in range(M)]
p = list(map(int, input().split()))
ans = 0
for i in range(1 << N):
    judge = 1
    for j in range(M):
        cnt = 0
        for k in KS[j][1:]:
            if i >> (k - 1) & 1:
                cnt += 1
        if (cnt % 2) != p[j]:
            judge = 0
    if judge == 1:
        ans += 1
print(ans)

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

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


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

a = [eval(input()) for i in range(n+k)]

cnt = {i:0 for i in range(n)}

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

    for j in range(n):

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

            cnt[j] += 1

            break

print(sorted(list(cnt.items()), key = lambda x:x[1], reverse = True)[0][0] + 1)

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

a = [eval(input()) for i in range(n+k)]

c = [0]*n

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

    for j in range(n):

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

            c[j] += 1

            break

print(c.index(max(c)) + 1)

n, k = list(map(int, input().split()))
a = [eval(input()) for i in range(n + k)]
cnt = {i: 0 for i in range(n)}
for i in range(n, n + k):
    for j in range(n):
        if a[i] >= a[j]:
            cnt[j] += 1
            break
print(sorted(list(cnt.items()), key=lambda x: x[1], reverse=True)[0][0] + 1)

n, k = list(map(int, input().split()))
a = [eval(input()) for i in range(n + k)]
c = [0] * n
for i in range(n, n + k):
    for j in range(n):
        if a[i] >= a[j]:
            c[j] += 1
            break
print(c.index(max(c)) + 1)

-print(sorted(list(cnt.items()), key=lambda x: x[1], reverse=True)[0][0] + 1)


Input: print((" YNEOS"[eval(input()) in "357"::2]))

if eval(input()) in "357":

  print("YES")

else:

  print("NO")

-print((" YNEOS"[eval(input()) in "357" :: 2]))


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

nn = []

mm = []

for i in range(n):

    nn.append(list(eval(input())))

for i in range(m):

    mm.append(list(eval(input())))

for i in range(n-m+1):

    for j in range(n-m+1):

        count = 0

        for k in range(m):

            for l in range(m):

                if nn[i+k][j+l] != mm[k][l]:

                    break

                else:

                    count += 1

        if count == m*m:

            print("Yes")

            exit()

print("No")

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

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

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

ans = 'Yes'

for i in range(n):

    for j in range(m):

        if b[j] not in a[i]:

            ans = 'No'

print(ans)

n, m = list(map(int, input().split()))
nn = []
mm = []
for i in range(n):
    nn.append(list(eval(input())))
for i in range(m):
    mm.append(list(eval(input())))
for i in range(n - m + 1):
    for j in range(n - m + 1):
        count = 0
        for k in range(m):
            for l in range(m):
                if nn[i + k][j + l] != mm[k][l]:
                    break
                else:
                    count += 1
        if count == m * m:
            print("Yes")
            exit()
print("No")

n, m = list(map(int, input().split()))
a = [eval(input()) for i in range(n)]
b = [eval(input()) for i in range(m)]
ans = "Yes"
for i in range(n):
    for j in range(m):
        if b[j] not in a[i]:
            ans = "No"
print(ans)


Input:
# encoding:utf-8

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

a, b = input

d = a / b

r = a % b

f = float(a) / b

print((d), end=' ')

print((r), end=' ')

print(('%03.9f' % f))

# encoding:utf-8

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

a, b = input

d = a / b

r = a % b

f = float(a) / b

print((d), end=' ')

print((r), end=' ')

print(('%03.8f' % f))

# encoding:utf-8
input = list(map(int, input().split()))
a, b = input
d = a / b
r = a % b
f = float(a) / b
print((d), end=" ")
print((r), end=" ")
print(("%03.9f" % f))

# encoding:utf-8
input = list(map(int, input().split()))
a, b = input
d = a / b
r = a % b
f = float(a) / b
print((d), end=" ")
print((r), end=" ")
print(("%03.8f" % f))


Input:
while True:

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

    if n == x == 0:

        break

    cnt = 0

    upper_max_value = min(x - 3, n)

    lower_max_value = max(int(x / 3), 3)

    for i in range(upper_max_value, lower_max_value - 1, -1):

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

            for k in range(j - 1, 0, -1):

                if (i + j + k) == x:

                    cnt += 1

    print(cnt)

while True:

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

    if n == x == 0:

        break

    max_a = min(x - 3, n)

    min_a = max(x // 3 + 1, 3)

    cnt = 0

    for i in range(min_a, max_a + 1):

        max_b = min(i - 1, x - i - 1)

        min_b = (x - i) // 2 + 1

        cnt += (max_b - min_b + 1)

    print(cnt)

while True:
    n, x = list(map(int, input().split()))
    if n == x == 0:
        break
    max_a = min(x - 3, n)
    min_a = max(x // 3 + 1, 3)
    cnt = 0
    for i in range(min_a, max_a + 1):
        max_b = min(i - 1, x - i - 1)
        min_b = (x - i) // 2 + 1
        cnt += max_b - min_b + 1
    print(cnt)

-    lower_max_value = max(int(x / 3), 3)

-    for i in range(upper_max_value, lower_max_value - 1, -1):

-            for k in range(j - 1, 0, -1):


Input:
Md,MN=1000000007,1000006

fac,ifac,a,res,inv=[1,1],[1,1],[0],0,[1,1]

for i in range(2,MN):

    inv.append(inv[Md%i]*(Md-Md//i)%Md)

    fac.append(fac[-1]*i%Md)

    ifac.append(ifac[-1]*inv[i]%Md)

def C(x,y):

    if(x<y):

        return 0

    return fac[x]*ifac[y]*ifac[x-y]

def D(x,y):

    return C(x-y+1,y)

n=int(eval(input()))

for i in range(1,n):

    if i*2-n>=0:

        a.append(D(n-3,n-i-1)*fac[i]*fac[n-i-1]%Md)

    else:

        a.append(0)

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

    a[i]=(a[i]-a[i-1])%Md

    res=res+a[i]*i

res=res%Md

print(res)

Md,MN=1000000007,1000006

fac,ifac,a,res,inv=[1,1],[1,1],[0],0,[1,1]

for i in range(2,MN):

    inv.append(inv[Md%i]*(Md-Md//i)%Md)

    fac.append(fac[-1]*i%Md)

    ifac.append(ifac[-1]*inv[i]%Md)

n=int(eval(input()))

for i in range(1,n):

    if i*2-n>=0:

        a.append(fac[i-1]*ifac[i+i-n]*fac[i]%Md)

    else:

        a.append(0)

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

    a[i]=(a[i]-a[i-1])%Md

    res+=a[i]*i

res=res%Md

print(res)

Md, MN = 1000000007, 1000006
fac, ifac, a, res, inv = [1, 1], [1, 1], [0], 0, [1, 1]
for i in range(2, MN):
    inv.append(inv[Md % i] * (Md - Md // i) % Md)
    fac.append(fac[-1] * i % Md)
    ifac.append(ifac[-1] * inv[i] % Md)

def C(x, y):
    if x < y:
        return 0
    return fac[x] * ifac[y] * ifac[x - y]

def D(x, y):
    return C(x - y + 1, y)

n = int(eval(input()))
for i in range(1, n):
    if i * 2 - n >= 0:
        a.append(D(n - 3, n - i - 1) * fac[i] * fac[n - i - 1] % Md)
    else:
        a.append(0)
for i in range(n - 1, 0, -1):
    a[i] = (a[i] - a[i - 1]) % Md
    res = res + a[i] * i
res = res % Md
print(res)

Md, MN = 1000000007, 1000006
fac, ifac, a, res, inv = [1, 1], [1, 1], [0], 0, [1, 1]
for i in range(2, MN):
    inv.append(inv[Md % i] * (Md - Md // i) % Md)
    fac.append(fac[-1] * i % Md)
    ifac.append(ifac[-1] * inv[i] % Md)
n = int(eval(input()))
for i in range(1, n):
    if i * 2 - n >= 0:
        a.append(fac[i - 1] * ifac[i + i - n] * fac[i] % Md)
    else:
        a.append(0)
for i in range(n - 1, 0, -1):
    a[i] = (a[i] - a[i - 1]) % Md
    res += a[i] * i
res = res % Md
print(res)

-    return fac[x] * ifac[y] * ifac[x - y]

-        a.append(D(n - 3, n - i - 1) * fac[i] * fac[n - i - 1] % Md)

+        a.append(fac[i - 1] * ifac[i + i - n] * fac[i] % Md)


Input:
INF = 2*10**7

def main():

    N, M = (int(i) for i in input().split())

    A = []

    B = []

    C = []

    for _ in range(M):

        a, b = (int(i) for i in input().split())

        A.append(a)

        B.append(b)

        C.append({int(i) for i in input().split()})

    dp = [[INF]*(1 << N) for _ in range(M+1)]

    dp[0][0] = 0

    for i in range(M):

        for j in range(1 << N):

            dp[i+1][j] = min(dp[i+1][j], dp[i][j])

            if dp[i][j] != INF:

                next_bit = j

                for bit in C[i]:

                    next_bit |= (1 << (bit-1))

                dp[i+1][next_bit] = min(dp[i+1][next_bit], dp[i][j] + A[i])

    ans = dp[-1][-1]

    if ans == INF:

        print((-1))

    else:

        print(ans)

    # print(*dp, sep="\n")

if __name__ == '__main__':

    main()

INF = 2*10**7

def main():

    N, M = (int(i) for i in input().split())

    A = []

    B = []

    C = []

    for _ in range(M):

        a, b = (int(i) for i in input().split())

        A.append(a)

        B.append(b)

        bit = 0

        for i in input().split():

            bit |= (1 << (int(i)-1))

        C.append(bit)

    dp = [[INF]*(1 << N) for _ in range(M+1)]

    dp[0][0] = 0

    for i in range(M):

        for j in range(1 << N):

            dp[i+1][j] = min(dp[i+1][j], dp[i][j])

            if dp[i][j] != INF:

                next_bit = j | C[i]

                dp[i+1][next_bit] = min(dp[i+1][next_bit], dp[i][j] + A[i])

    ans = dp[-1][-1]

    if ans == INF:

        print((-1))

    else:

        print(ans)

    # print(*dp, sep="\n")

if __name__ == '__main__':

    main()

INF = 2 * 10**7

def main():
    N, M = (int(i) for i in input().split())
    A = []
    B = []
    C = []
    for _ in range(M):
        a, b = (int(i) for i in input().split())
        A.append(a)
        B.append(b)
        C.append({int(i) for i in input().split()})
    dp = [[INF] * (1 << N) for _ in range(M + 1)]
    dp[0][0] = 0
    for i in range(M):
        for j in range(1 << N):
            dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])
            if dp[i][j] != INF:
                next_bit = j
                for bit in C[i]:
                    next_bit |= 1 << (bit - 1)
                dp[i + 1][next_bit] = min(dp[i + 1][next_bit], dp[i][j] + A[i])
    ans = dp[-1][-1]
    if ans == INF:
        print((-1))
    else:
        print(ans)
    # print(*dp, sep="\n")

if __name__ == "__main__":
    main()

INF = 2 * 10**7

def main():
    N, M = (int(i) for i in input().split())
    A = []
    B = []
    C = []
    for _ in range(M):
        a, b = (int(i) for i in input().split())
        A.append(a)
        B.append(b)
        bit = 0
        for i in input().split():
            bit |= 1 << (int(i) - 1)
        C.append(bit)
    dp = [[INF] * (1 << N) for _ in range(M + 1)]
    dp[0][0] = 0
    for i in range(M):
        for j in range(1 << N):
            dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])
            if dp[i][j] != INF:
                next_bit = j | C[i]
                dp[i + 1][next_bit] = min(dp[i + 1][next_bit], dp[i][j] + A[i])
    ans = dp[-1][-1]
    if ans == INF:
        print((-1))
    else:
        print(ans)
    # print(*dp, sep="\n")

if __name__ == "__main__":
    main()

-        C.append({int(i) for i in input().split()})


Input:
import sys

sys.setrecursionlimit(10**6)

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

N,Q=MI()

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

Point=[0]*N

for i in range(N-1):

  a,b=MI()

  Edge[a-1].append(b-1)

  Edge[b-1].append(a-1)

for i in range(Q):

  p,x=MI()

  Point[p-1]+=x

def dfs(now,pre=-1):

  for nxt in Edge[now]:

    if nxt==pre:

      continue

    Point[nxt]+=Point[now]

    dfs(nxt,now)

dfs(0)

print((*Point))

from collections import deque

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

N,Q=MI()

graph=[[] for i in range(N)]

Point=[0]*N

for i in range(N-1):

  a,b=MI()

  graph[a-1].append(b-1)

  graph[b-1].append(a-1)

for i in range(Q):

  p,x=MI()

  Point[p-1]+=x

que=deque([])

que.append(0)

check=[0]*N

while que:

  v=que.pop()

  check[v]=1

  for u in graph[v]:

    if check[u]!=1:

      #continue

      Point[u]+=Point[v]

      que.append(u)

print((*Point))

import sys

sys.setrecursionlimit(10**6)

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

N, Q = MI()
Edge = [[] for _ in range(N)]
Point = [0] * N
for i in range(N - 1):
    a, b = MI()
    Edge[a - 1].append(b - 1)
    Edge[b - 1].append(a - 1)
for i in range(Q):
    p, x = MI()
    Point[p - 1] += x

def dfs(now, pre=-1):
    for nxt in Edge[now]:
        if nxt == pre:
            continue
        Point[nxt] += Point[now]
        dfs(nxt, now)

dfs(0)
print((*Point))

from collections import deque

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

N, Q = MI()
graph = [[] for i in range(N)]
Point = [0] * N
for i in range(N - 1):
    a, b = MI()
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
for i in range(Q):
    p, x = MI()
    Point[p - 1] += x
que = deque([])
que.append(0)
check = [0] * N
while que:
    v = que.pop()
    check[v] = 1
    for u in graph[v]:
        if check[u] != 1:
            # continue
            Point[u] += Point[v]
            que.append(u)
print((*Point))

-import sys
-sys.setrecursionlimit(10**6)
+from collections import deque
-Edge = [[] for _ in range(N)]
+graph = [[] for i in range(N)]
-    Edge[a - 1].append(b - 1)
-    Edge[b - 1].append(a - 1)
+    graph[a - 1].append(b - 1)
+    graph[b - 1].append(a - 1)
-def dfs(now, pre=-1):
-    for nxt in Edge[now]:
-        if nxt == pre:
-            continue
-        Point[nxt] += Point[now]
-        dfs(nxt, now)
-dfs(0)
+que = deque([])
+que.append(0)
+check = [0] * N
+while que:
+    v = que.pop()
+    check[v] = 1
+    for u in graph[v]:
+        if check[u] != 1:
+            # continue
+            Point[u] += Point[v]
+            que.append(u)


Input:
from scipy.misc import comb

mod = 1000000007

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

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

    if N-K+1<i:

        print((0))

    else:

        print((comb(N-K+1,i,exact=True)*comb(K-1,i-1,exact=True)%mod))

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

def cmb(n, r, mod):

    if (r < 0 or r > n):

        return 0

    r = min(r, n-r)

    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7  # 出力の制限

n = 2*10**3

g1 = [1, 1]  # 元テーブル

g2 = [1, 1]  # 逆元テーブル

inverse = [0, 1]  # 逆元テーブル計算用テーブル

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

    g1.append((g1[-1] * i) % mod)

    inverse.append((-inverse[mod % i] * (mod//i)) % mod)

    g2.append((g2[-1] * inverse[-1]) % mod)

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

    print((cmb(N-K+1, i, mod) * cmb(K-1, i-1, mod) % mod))

from scipy.misc import comb

mod = 1000000007
N, K = list(map(int, input().split()))
for i in range(1, K + 1):
    if N - K + 1 < i:
        print((0))
    else:
        print((comb(N - K + 1, i, exact=True) * comb(K - 1, i - 1, exact=True) % mod))

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

def cmb(n, r, mod):
    if r < 0 or r > n:
        return 0
    r = min(r, n - r)
    return g1[n] * g2[r] * g2[n - r] % mod

mod = 10**9 + 7  # 出力の制限
n = 2 * 10**3
g1 = [1, 1]  # 元テーブル
g2 = [1, 1]  # 逆元テーブル
inverse = [0, 1]  # 逆元テーブル計算用テーブル
for i in range(2, n + 1):
    g1.append((g1[-1] * i) % mod)
    inverse.append((-inverse[mod % i] * (mod // i)) % mod)
    g2.append((g2[-1] * inverse[-1]) % mod)
for i in range(1, K + 1):
    print((cmb(N - K + 1, i, mod) * cmb(K - 1, i - 1, mod) % mod))

+    return g1[n] * g2[r] * g2[n - r] % mod

+    inverse.append((-inverse[mod % i] * (mod // i)) % mod)

+    g2.append((g2[-1] * inverse[-1]) % mod)

-        print((comb(N - K + 1, i, exact=True) * comb(K - 1, i - 1, exact=True) % mod))

+    print((cmb(N - K + 1, i, mod) * cmb(K - 1, i - 1, mod) % mod))


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

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

a.sort()

a.append(a[-1] + 1)

b = [a[0]]

c = [1]

ans = 0

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

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

        c[-1] += 1

    else:

        cand = c[-1]

        if len(b) >= 2 and b[-2] == b[-1] - 1:

            cand += c[-2]

        if len(b) >= 3 and b[-3] == b[-1] - 2:

            cand += c[-3]

        ans = max(ans, cand)

        b.append(a[i])

        c.append(1)

print(ans)

from collections import defaultdict

n = int(eval(input()))

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

d = defaultdict(int)

for i in range(n):

    d[a[i]] += 1

ans = 0

for x in d:

    cand = d[x]

    if x - 1 in d:

        cand += d[x - 1]

    if x + 1 in d:

        cand += d[x + 1]

    ans = max(ans, cand)

print(ans)

n = int(eval(input()))
a = list(map(int, input().split()))
a.sort()
a.append(a[-1] + 1)
b = [a[0]]
c = [1]
ans = 0
for i in range(1, n + 1):
    if a[i] == b[-1]:
        c[-1] += 1
    else:
        cand = c[-1]
        if len(b) >= 2 and b[-2] == b[-1] - 1:
            cand += c[-2]
        if len(b) >= 3 and b[-3] == b[-1] - 2:
            cand += c[-3]
        ans = max(ans, cand)
        b.append(a[i])
        c.append(1)
print(ans)


Input:
def get_isPrime(n):         #1~nまでの数で、素数は1、それ以外は0となるようなリストを返す

    isprime=[1]*(n+1)

    isprime[0]=0

    isprime[1]=0

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

        if not isprime[i]:

            continue

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

            isprime[j]=0

    return isprime

max_n=100000

isprime=get_isPrime(max_n)

ruiseki=[]

for i in range(max_n+1):

    if i==0 or i==1 or i==2:

        ruiseki.append(0)

    else:

        if i%2==0:

            ruiseki.append(ruiseki[i-1])

        else:

            if isprime[i] and isprime[int((i+1)/2)]:

                ruiseki.append(ruiseki[i-1]+1)

            else:

                ruiseki.append(ruiseki[i-1])

q=int(eval(input()))

for _ in range(q):

    left, right=list(map(int,input().split()))

    print((ruiseki[right]-ruiseki[left-1]))

from itertools import chain, accumulate

def prime_set(N):

    """

    Nまでの素数のsetを返す

    """

    if N < 4:

        return ({}, {}, {2}, {2, 3})[N]

    Nsq = int(N ** 0.5 + 0.5) + 1

    primes = {2, 3} | set(chain(range(5, N + 1, 6), range(7, N + 1, 6)))

    for i in range(5, Nsq, 2):

        if i in primes:

            primes -= set(range(i * i, N + 1, i * 2))

    return primes

U = 10 ** 5 + 10

primes = prime_set(U)

memo = [0] * U

for i in range(1, U, 2):

    if i in primes and (i + 1) // 2 in primes:

        memo[i] = 1

memo = list(accumulate(memo))

Q = int(input())

ans = []

for _ in range(Q):

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

    ans.append(memo[r] - memo[l - 1])

print(*ans, sep="\n")

def get_isPrime(n):  # 1~nまでの数で、素数は1、それ以外は0となるようなリストを返す
    isprime = [1] * (n + 1)
    isprime[0] = 0
    isprime[1] = 0
    for i in range(2, int(n**0.5) + 1):
        if not isprime[i]:
            continue
        for j in range(i * 2, n + 1, i):
            isprime[j] = 0
    return isprime

max_n = 100000
isprime = get_isPrime(max_n)
ruiseki = []
for i in range(max_n + 1):
    if i == 0 or i == 1 or i == 2:
        ruiseki.append(0)
    else:
        if i % 2 == 0:
            ruiseki.append(ruiseki[i - 1])
        else:
            if isprime[i] and isprime[int((i + 1) / 2)]:
                ruiseki.append(ruiseki[i - 1] + 1)
            else:
                ruiseki.append(ruiseki[i - 1])
q = int(eval(input()))
for _ in range(q):
    left, right = list(map(int, input().split()))
    print((ruiseki[right] - ruiseki[left - 1]))

from itertools import chain, accumulate

def prime_set(N):
    """
    Nまでの素数のsetを返す
    """
    if N < 4:
        return ({}, {}, {2}, {2, 3})[N]
    Nsq = int(N**0.5 + 0.5) + 1
    primes = {2, 3} | set(chain(range(5, N + 1, 6), range(7, N + 1, 6)))
    for i in range(5, Nsq, 2):
        if i in primes:
            primes -= set(range(i * i, N + 1, i * 2))
    return primes

U = 10**5 + 10
primes = prime_set(U)
memo = [0] * U
for i in range(1, U, 2):
    if i in primes and (i + 1) // 2 in primes:
        memo[i] = 1
memo = list(accumulate(memo))
Q = int(input())
ans = []
for _ in range(Q):
    l, r = map(int, input().split())
    ans.append(memo[r] - memo[l - 1])
print(*ans, sep="\n")

-def get_isPrime(n):  # 1~nまでの数で、素数は1、それ以外は0となるようなリストを返す

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

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

+from itertools import chain, accumulate

-            ruiseki.append(ruiseki[i - 1])

-            if isprime[i] and isprime[int((i + 1) / 2)]:

-                ruiseki.append(ruiseki[i - 1] + 1)

-                ruiseki.append(ruiseki[i - 1])

-    left, right = list(map(int, input().split()))

-    print((ruiseki[right] - ruiseki[left - 1]))

+    Nまでの素数のsetを返す

+            primes -= set(range(i * i, N + 1, i * 2))

+    if i in primes and (i + 1) // 2 in primes:


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

a = [-1]

for i in range(M):

  a.append(int(eval(input())))

# a = [int(input()) for i in range(M)]

a.append(N+1)

# print(N,M)

# print(a)

diff = []

diffmax = 0

for i, v in enumerate(a):

  if i != len(a)-1:

    steps = a[i+1] - a[i]

    diff.append(steps)

    if diffmax < steps:

      diffmax = steps

#print(diff)

actptn = [0,1]

for i in range(2,diffmax):

  actptn.append(actptn[i-1] + actptn[i-2])

#print(len(actptn))

ans = 1

for i in diff:

  ans = (ans* actptn[i-1]) % 1000000007

print(ans)

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

A = set([int(eval(input())) for _ in range(m)])

MOD = 10 ** 9 + 7

dp = [0] * (n + 1)

dp[0] = 1

if 1 not in A:

  dp[1] = 1

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

  if i not in A:

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

print((dp[-1]))

N, M = list(map(int, input().split()))
a = [-1]
for i in range(M):
    a.append(int(eval(input())))
# a = [int(input()) for i in range(M)]
a.append(N + 1)
# print(N,M)
# print(a)
diff = []
diffmax = 0
for i, v in enumerate(a):
    if i != len(a) - 1:
        steps = a[i + 1] - a[i]
        diff.append(steps)
        if diffmax < steps:
            diffmax = steps
# print(diff)
actptn = [0, 1]
for i in range(2, diffmax):
    actptn.append(actptn[i - 1] + actptn[i - 2])
# print(len(actptn))
ans = 1
for i in diff:
    ans = (ans * actptn[i - 1]) % 1000000007
print(ans)

n, m = list(map(int, input().split()))
A = set([int(eval(input())) for _ in range(m)])
MOD = 10**9 + 7
dp = [0] * (n + 1)
dp[0] = 1
if 1 not in A:
    dp[1] = 1
for i in range(2, n + 1):
    if i not in A:
        dp[i] = (dp[i - 1] + dp[i - 2]) % MOD
print((dp[-1]))

-    actptn.append(actptn[i - 1] + actptn[i - 2])

+A = set([int(eval(input())) for _ in range(m)])


Input:
# ABC073D - joisino's travel

from itertools import permutations

from scipy.sparse.csgraph import dijkstra

def main():

    N, M, R, *RABC = list(map(int, open(0).read().split()))

    visit, ABC = RABC[:R], RABC[R:]

    G = [[float("inf")] * (N + 1) for _ in range(N + 1)]

    for v, u, c in zip(*[iter(ABC)] * 3):

        G[v][u] = G[u][v] = c

    dist = [None] * (N + 1)

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

        dist[i] = dijkstra(G, directed=0, indices=i)

    ans = float("inf")

    for perm in permutations(visit):

        cur = sum(dist[v][u] for v, u in zip(perm, perm[1:]))

        ans = min(ans, cur)

    print((int(ans)))

if __name__ == "__main__":

    main()

# ABC073D - joisino's travel

from heapq import heapify, heappop, heappush

from itertools import permutations

def dijkstra(G: "Array[Array[int]]", size: int, start: int) -> list:

    dist = [float("inf")] * size

    queue = [(start, 0)]

    heapify(queue)

    while queue:

        v, cost = heappop(queue)

        if cost > dist[v]:

            continue

        dist[v] = cost

        for u, next_cost in G[v]:

            if cost + next_cost < dist[u]:

                heappush(queue, (u, cost + next_cost))

    return dist

def main():

    global G, N

    N, M, R, *RABC = list(map(int, open(0).read().split()))

    visit, ABC = RABC[:R], RABC[R:]

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

    for v, u, c in zip(*[iter(ABC)] * 3):

        G[v].append((u, c)), G[u].append((v, c))

    dist = {v: dijkstra(G, N + 1, v) for v in visit}

    ans = float("inf")

    for perm in permutations(visit):

        cur = sum(dist[v][u] for v, u in zip(perm, perm[1:]))

        ans = min(ans, cur)

    print(ans)

if __name__ == "__main__":

    main()

+from heapq import heapify, heappop, heappush

-from scipy.sparse.csgraph import dijkstra

+def dijkstra(G: "Array[Array[int]]", size: int, start: int) -> list:

+            if cost + next_cost < dist[u]:

+                heappush(queue, (u, cost + next_cost))

-    G = [[float("inf")] * (N + 1) for _ in range(N + 1)]

-        dist[i] = dijkstra(G, directed=0, indices=i)

+        G[v].append((u, c)), G[u].append((v, c))

+    dist = {v: dijkstra(G, N + 1, v) for v in visit}


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

t,x,y = 0,0,0

for i in range(N):

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

    d = abs(x-X)+abs(y-Y)

    if (T-t)-d >= 0 and ((T-t)-d)%2 == 0:

        t,x,y = T,X,Y

        continue

    else:

        print('No')

        exit()

print('Yes')

import sys

input = sys.stdin.readline

N = int(eval(input()))

t,x,y = 0,0,0

for i in range(N):

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

    d = abs(x-X)+abs(y-Y)

    if (T-t)-d >= 0 and ((T-t)-d)%2 == 0:

        t,x,y = T,X,Y

        continue

    else:

        print('No')

        exit()

print('Yes')

import sys

input = sys.stdin.readline
N = int(eval(input()))
t, x, y = 0, 0, 0
for i in range(N):
    T, X, Y = list(map(int, input().split()))
    d = abs(x - X) + abs(y - Y)
    if (T - t) - d >= 0 and ((T - t) - d) % 2 == 0:
        t, x, y = T, X, Y
        continue
    else:
        print("No")
        exit()
print("Yes")

+import sys
+
+input = sys.stdin.readline


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

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

C=[]

for i in range(0,10):

  if i not in D:

    C.append(i)

#print(C)

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

  cnt=0

  for j in list(map(int,list(str(i)))):

    if j in C:

      cnt+=1

  if len(str(i))==cnt:

    print(i)

    exit()

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

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

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

  A = list(map(int, str(i)))

  flag = 1

  for a in A:

    if a in D:

      flag = 0

      break

  if flag:

    print(i)

    exit()

N, K = list(map(int, input().split()))
D = list(map(int, input().split()))
C = []
for i in range(0, 10):
    if i not in D:
        C.append(i)
# print(C)
for i in range(N, 10**10):
    cnt = 0
    for j in list(map(int, list(str(i)))):
        if j in C:
            cnt += 1
    if len(str(i)) == cnt:
        print(i)
        exit()

-    for j in list(map(int, list(str(i)))):


Input:
from math import factorial as f

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

mod = 10 ** 9 + 7

if abs(n - m) == 1:

    res = f(n) * f(m)

    print((res % mod))

elif n == m:

    res = f(n) * f(m) * 2

    print((res % mod))

else:

    print((0))

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

mod = 10 ** 9 + 7

def permitation(x):

    res = 1

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

        res = res * i % mod

    return res

pn = permitation(n)

pm = permitation(m)

if n == m:

    res = pn * pm * 2 % mod

    print(res)

elif n == m - 1 or n == m + 1:

    res = pn * pm % mod

    print(res)

else:

    print((0))

from math import factorial as f

n, m = list(map(int, input().split()))
mod = 10**9 + 7
if abs(n - m) == 1:
    res = f(n) * f(m)
    print((res % mod))
elif n == m:
    res = f(n) * f(m) * 2
    print((res % mod))
else:
    print((0))

n, m = list(map(int, input().split()))
mod = 10**9 + 7

def permitation(x):
    res = 1
    for i in range(1, x + 1):
        res = res * i % mod
    return res

pn = permitation(n)
pm = permitation(m)
if n == m:
    res = pn * pm * 2 % mod
    print(res)
elif n == m - 1 or n == m + 1:
    res = pn * pm % mod
    print(res)
else:
    print((0))

-from math import factorial as f
-if abs(n - m) == 1:
-    res = f(n) * f(m)
-    print((res % mod))
-elif n == m:
-    res = f(n) * f(m) * 2
-    print((res % mod))
+
+
+def permitation(x):
+    res = 1
+    for i in range(1, x + 1):
+        res = res * i % mod
+    return res
+
+
+pn = permitation(n)
+pm = permitation(m)
+if n == m:
+    res = pn * pm * 2 % mod
+    print(res)
+elif n == m - 1 or n == m + 1:
+    res = pn * pm % mod
+    print(res)


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

mod = 10**9 + 7

dp = [0] * (S+1)

dp[0] = 1

x = 0

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

  if i-3 >= 0:

    x += dp[i-3]

    x %= mod

  dp[i] = x

print((dp[S]))


Input:
from collections import Counter

n = int(eval(input()))

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

odds = v[1::2]

evens = v[::2]

o = Counter(odds)

e = Counter(evens)

omx, *ol = sorted(list(o.items()), reverse=True, key=lambda x: x[1])

emx, *el = sorted(list(e.items()), reverse=True, key=lambda x: x[1])

if omx[0] != emx[0]:

    ans = n - omx[1] - emx[1]

else:

    if ol:

        ol = ol[0]

    else:

        ol = (0, 0)

    if el:

        el = el[0]

    else:

        el = (0, 0)

    a = n - omx[1] - el[1]

    b = n - emx[1] - ol[1]

    ans = min(a, b)

print(ans)

from collections import Counter

from itertools import product

n = int(eval(input()))

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

o = Counter(v[1::2])

e = Counter(v[::2])

o[0] = 0

e[0] = 0

o_ls = o.most_common(2)

e_ls = e.most_common(2)

ans = n

for (k1, v1), (k2, v2) in product(o_ls, e_ls):

    if k1 == k2:

        continue

    x = n - v1 - v2

    if ans > x:

        ans = x

print(ans)

from collections import Counter

n = int(eval(input()))
(*v,) = list(map(int, input().split()))
odds = v[1::2]
evens = v[::2]
o = Counter(odds)
e = Counter(evens)
omx, *ol = sorted(list(o.items()), reverse=True, key=lambda x: x[1])
emx, *el = sorted(list(e.items()), reverse=True, key=lambda x: x[1])
if omx[0] != emx[0]:
    ans = n - omx[1] - emx[1]
else:
    if ol:
        ol = ol[0]
    else:
        ol = (0, 0)
    if el:
        el = el[0]
    else:
        el = (0, 0)
    a = n - omx[1] - el[1]
    b = n - emx[1] - ol[1]
    ans = min(a, b)
print(ans)

from collections import Counter
from itertools import product

n = int(eval(input()))
(*v,) = list(map(int, input().split()))
o = Counter(v[1::2])
e = Counter(v[::2])
o[0] = 0
e[0] = 0
o_ls = o.most_common(2)
e_ls = e.most_common(2)
ans = n
for (k1, v1), (k2, v2) in product(o_ls, e_ls):
    if k1 == k2:
        continue
    x = n - v1 - v2
    if ans > x:
        ans = x
print(ans)

-omx, *ol = sorted(list(o.items()), reverse=True, key=lambda x: x[1])

-emx, *el = sorted(list(e.items()), reverse=True, key=lambda x: x[1])

+for (k1, v1), (k2, v2) in product(o_ls, e_ls):


Input:
#!/usr/bin/env python

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

def find(S, x):

    left = 0

    right = n

    while right - left >= 1:

        mid = (left + right)//2

        if S[mid] == x:

            return True

        if S[mid] < x:

            left = mid + 1

        else:

            right = mid

    return False

n = int(eval(input()))

S = sorted(map(int,input().split()))

q = int(eval(input()))

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

count = 0

for t in T:

    if find(S, t):

        count += 1

print(count)

#!/usr/bin/env python

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

n = int(eval(input()))

S = sorted(map(int,input().split()))

q = int(eval(input()))

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

print((len(set(S) & set(T))))

#!/usr/bin/env python
# -*- coding: utf-8 -*-
def find(S, x):
    left = 0
    right = n
    while right - left >= 1:
        mid = (left + right) // 2
        if S[mid] == x:
            return True
        if S[mid] < x:
            left = mid + 1
        else:
            right = mid
    return False

n = int(eval(input()))
S = sorted(map(int, input().split()))
q = int(eval(input()))
T = list(map(int, input().split()))
count = 0
for t in T:
    if find(S, t):
        count += 1
print(count)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
n = int(eval(input()))
S = sorted(map(int, input().split()))
q = int(eval(input()))
T = list(map(int, input().split()))
print((len(set(S) & set(T))))

-def find(S, x):
-    left = 0
-    right = n
-    while right - left >= 1:
-        mid = (left + right) // 2
-        if S[mid] == x:
-            return True
-        if S[mid] < x:
-            left = mid + 1
-        else:
-            right = mid
-    return False
-count = 0
-for t in T:
-    if find(S, t):
-        count += 1
-print(count)
+print((len(set(S) & set(T))))


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

m = n

l = n

res = 0

cnt = 0

tmp = m

while m < k:

    m *= 2

    cnt += 1

res += (1/n)*(0.5)**cnt

for i in range(1,n):

    cnt = 0

    l = n

    l -= i

    cnt = 0

    while l < k:

        l *= 2

        cnt += 1

    res += (1/n)*(0.5)**cnt

print(res)

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

res = 0

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

    prob = 1/N

    while i < K:

        i *= 2

        prob *= 0.5

    res += prob

print(res)

n, k = list(map(int, input().split()))
m = n
l = n
res = 0
cnt = 0
tmp = m
while m < k:
    m *= 2
    cnt += 1
res += (1 / n) * (0.5) ** cnt
for i in range(1, n):
    cnt = 0
    l = n
    l -= i
    cnt = 0
    while l < k:
        l *= 2
        cnt += 1
    res += (1 / n) * (0.5) ** cnt
print(res)

N, K = list(map(int, input().split()))
res = 0
for i in range(1, N + 1):
    prob = 1 / N
    while i < K:
        i *= 2
        prob *= 0.5
    res += prob
print(res)

-n, k = list(map(int, input().split()))
-m = n
-l = n
+N, K = list(map(int, input().split()))
-cnt = 0
-tmp = m
-while m < k:
-    m *= 2
-    cnt += 1
-res += (1 / n) * (0.5) ** cnt
-for i in range(1, n):
-    cnt = 0
-    l = n
-    l -= i
-    cnt = 0
-    while l < k:
-        l *= 2
-        cnt += 1
-    res += (1 / n) * (0.5) ** cnt
+for i in range(1, N + 1):
+    prob = 1 / N
+    while i < K:
+        i *= 2
+        prob *= 0.5
+    res += prob


Input:
from itertools import product

from collections import Counter as ct

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

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

ans = 10 ** 10

for bit in product([0, 1, 2, 3], repeat=n):

    if len(set(bit) - {0}) != 3:

        continue

    tmpa = 0

    tmpb = 0

    tmpc = 0

    for i, j in enumerate(bit):

        if j == 1:

            tmpa += l[i]

        elif j == 2:

            tmpb += l[i]

        elif j == 3:

            tmpc += l[i]

    mp = abs(a - tmpa) + abs(b - tmpb) + abs(c - tmpc)

    tmp = ct(bit)

    for i in range(1, 4):

        mp += max(0, tmp[i] - 1) * 10

    ans = min(ans, mp)

print(ans)

from itertools import product

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

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

ans = 10 ** 10

for bit in product([0, 1, 2, 3], repeat=n):

    tmp = [0] * 4

    mp = 0

    for i, j in enumerate(bit):

        if j != 3 and tmp[j] != 0:

            mp += 10

        tmp[j] += l[i]

    if any([i == 0 for i in tmp[:3]]):

        continue

    mp += abs(a - tmp[0]) + abs(b - tmp[1]) + abs(c - tmp[2])

    ans = min(ans, mp)

print(ans)

from itertools import product
from collections import Counter as ct

n, a, b, c = list(map(int, input().split()))
l = [int(eval(input())) for _ in range(n)]
ans = 10**10
for bit in product([0, 1, 2, 3], repeat=n):
    if len(set(bit) - {0}) != 3:
        continue
    tmpa = 0
    tmpb = 0
    tmpc = 0
    for i, j in enumerate(bit):
        if j == 1:
            tmpa += l[i]
        elif j == 2:
            tmpb += l[i]
        elif j == 3:
            tmpc += l[i]
    mp = abs(a - tmpa) + abs(b - tmpb) + abs(c - tmpc)
    tmp = ct(bit)
    for i in range(1, 4):
        mp += max(0, tmp[i] - 1) * 10
    ans = min(ans, mp)
print(ans)

from itertools import product

n, a, b, c = list(map(int, input().split()))
l = [int(eval(input())) for _ in range(n)]
ans = 10**10
for bit in product([0, 1, 2, 3], repeat=n):
    tmp = [0] * 4
    mp = 0
    for i, j in enumerate(bit):
        if j != 3 and tmp[j] != 0:
            mp += 10
        tmp[j] += l[i]
    if any([i == 0 for i in tmp[:3]]):
        continue
    mp += abs(a - tmp[0]) + abs(b - tmp[1]) + abs(c - tmp[2])
    ans = min(ans, mp)
print(ans)

-    mp = abs(a - tmpa) + abs(b - tmpb) + abs(c - tmpc)

+    mp += abs(a - tmp[0]) + abs(b - tmp[1]) + abs(c - tmp[2])


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

answer = a * b

print(answer)

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

print((a * b))

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

-answer = a * b
-print(answer)
+print((a * b))


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

s={i for i in range(a,a+W+1)}&{i for i in range(b,b+W+1)}

if s:

  print((0))

else:

  print((min(abs(b-a-W),abs(b+W-a))))

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

a, b = (a, b) if a<b else (b, a)

print((0 if a<=b<=a+W or b<=a<=b+W else min(abs(b-(a+W)), abs(a-(b+W)))))

W, a, b = list(map(int, input().split()))
s = {i for i in range(a, a + W + 1)} & {i for i in range(b, b + W + 1)}
if s:
    print((0))
else:
    print((min(abs(b - a - W), abs(b + W - a))))

W, a, b = list(map(int, input().split()))
a, b = (a, b) if a < b else (b, a)
print(
    (
        0
        if a <= b <= a + W or b <= a <= b + W
        else min(abs(b - (a + W)), abs(a - (b + W)))
    )
)

-s = {i for i in range(a, a + W + 1)} & {i for i in range(b, b + W + 1)}

-    print((min(abs(b - a - W), abs(b + W - a))))

+        if a <= b <= a + W or b <= a <= b + W

+        else min(abs(b - (a + W)), abs(a - (b + W)))