Input:
# coding: utf-8

def solve(*args: str) -> str:

    n, m, k = list(map(int, args[0].split()))

    mod = 998244353

    if m == 1 and n-1 == k:

        return str(1)

    ncr = 1

    p = m*pow(m-1, n-1, mod) % mod

    ret = p

    inv = pow(m-1, mod-2, mod)

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

        ncr = (ncr * (n-i)*pow(i, mod-2, mod)) % mod

        p = (p*inv) % mod

        ret += p*ncr % mod

    return str(ret % mod)

if __name__ == "__main__":

    print((solve(*(open(0).read().splitlines()))))

# coding: utf-8

def solve(*args: str) -> str:

    n, m, k = list(map(int, args[0].split()))

    mod = 998244353

    if m == 1 and n-1 == k:

        return str(1)

    ncr = 1

    p = m*pow(m-1, n-1, mod) % mod

    ret = p

    iR = [1]*(k+1)

    im = pow(m-1, mod-2, mod)

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

        iR[i] = max(1, (-(mod//i) * iR[mod % i]) % mod)

        ncr = (ncr * (n-i)*iR[i]) % mod

        p = (p*im) % mod

        ret += p*ncr % mod

    return str(ret % mod)

if __name__ == "__main__":

    print((solve(*(open(0).read().splitlines()))))

# coding: utf-8
def solve(*args: str) -> str:
    n, m, k = list(map(int, args[0].split()))
    mod = 998244353
    if m == 1 and n - 1 == k:
        return str(1)
    ncr = 1
    p = m * pow(m - 1, n - 1, mod) % mod
    ret = p
    inv = pow(m - 1, mod - 2, mod)
    for i in range(1, k + 1):
        ncr = (ncr * (n - i) * pow(i, mod - 2, mod)) % mod
        p = (p * inv) % mod
        ret += p * ncr % mod
    return str(ret % mod)

if __name__ == "__main__":
    print((solve(*(open(0).read().splitlines()))))

# coding: utf-8
def solve(*args: str) -> str:
    n, m, k = list(map(int, args[0].split()))
    mod = 998244353
    if m == 1 and n - 1 == k:
        return str(1)
    ncr = 1
    p = m * pow(m - 1, n - 1, mod) % mod
    ret = p
    iR = [1] * (k + 1)
    im = pow(m - 1, mod - 2, mod)
    for i in range(1, k + 1):
        iR[i] = max(1, (-(mod // i) * iR[mod % i]) % mod)
        ncr = (ncr * (n - i) * iR[i]) % mod
        p = (p * im) % mod
        ret += p * ncr % mod
    return str(ret % mod)

if __name__ == "__main__":
    print((solve(*(open(0).read().splitlines()))))

-        ncr = (ncr * (n - i) * pow(i, mod - 2, mod)) % mod

+        ncr = (ncr * (n - i) * iR[i]) % mod


Input:
import collections as col

def prime(n):

    ans = []

    num = n

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

        if i%2==0 and i!=2: continue

        while num%i == 0: num //= i ; ans.append(i)

    return ans

n = int(input())

mod = 10**9 + 7

primes = []

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

cnt = col.Counter(primes)

ans = 1

for key,val in list(cnt.items()): ans *= (val + 1) ; ans %= mod

print(ans)

import collections as col

def prime(n):

    ans = []

    num = n

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

        if i%2==0 and i!=2: continue

        while num%i == 0: num //= i ; ans.append(i)

    if num != 1: ans.append(num)

    return ans

n = int(input())

mod = 10**9 + 7

primes = []

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

cnt = col.Counter(primes)

ans = 1

for key,val in list(cnt.items()): ans *= (val + 1) ; ans %= mod

print(ans)

import collections as col

def prime(n):
    ans = []
    num = n
    for i in range(2, n + 1):
        if i % 2 == 0 and i != 2:
            continue
        while num % i == 0:
            num //= i
            ans.append(i)
    return ans

n = int(input())
mod = 10**9 + 7
primes = []
for i in range(2, n + 1):
    primes += prime(i)
cnt = col.Counter(primes)
ans = 1
for key, val in list(cnt.items()):
    ans *= val + 1
    ans %= mod
print(ans)

import collections as col

def prime(n):
    ans = []
    num = n
    for i in range(2, int(n**0.5) + 1):
        if i % 2 == 0 and i != 2:
            continue
        while num % i == 0:
            num //= i
            ans.append(i)
    if num != 1:
        ans.append(num)
    return ans

n = int(input())
mod = 10**9 + 7
primes = []
for i in range(2, n + 1):
    primes += prime(i)
cnt = col.Counter(primes)
ans = 1
for key, val in list(cnt.items()):
    ans *= val + 1
    ans %= mod
print(ans)

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


Input:
import sys

sys.setrecursionlimit(2147483647)

INF=float("inf")

MOD=10**9+7

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

def resolve():

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

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

    V=100000

    dp=[INF]*(V+1)

    dp[0]=0

    for w,v in WV:

        for x in range(V,-1,-1):

            if(x+v<=V):

                dp[x+v]=min(dp[x+v],dp[x]+w)

    for x in range(V,-1,-1):

        if(dp[x]<=W):

            print(x)

            return

resolve()

import sys

INF = 1 << 60

MOD = 10**9 + 7 # 998244353

sys.setrecursionlimit(2147483647)

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

def resolve():

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

    dp = [INF] * (n * 1001 + 1)

    dp[0] = 0

    for _ in range(n):

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

        for v0 in range(n * 1001, -1, -1):

            if dp[v0] == INF:

                continue

            if v + v0 <= n * 1001:

                dp[v + v0] = min(dp[v + v0], dp[v0] + w)

    for v in range(n * 1001, -1, -1):

        if dp[v] <= W:

            print(v)

            return

resolve()

import sys

sys.setrecursionlimit(2147483647)
INF = float("inf")
MOD = 10**9 + 7
input = lambda: sys.stdin.readline().rstrip()

def resolve():
    n, W = list(map(int, input().split()))
    WV = [tuple(map(int, input().split())) for _ in range(n)]
    V = 100000
    dp = [INF] * (V + 1)
    dp[0] = 0
    for w, v in WV:
        for x in range(V, -1, -1):
            if x + v <= V:
                dp[x + v] = min(dp[x + v], dp[x] + w)
    for x in range(V, -1, -1):
        if dp[x] <= W:
            print(x)
            return

resolve()

import sys

INF = 1 << 60
MOD = 10**9 + 7  # 998244353
sys.setrecursionlimit(2147483647)
input = lambda: sys.stdin.readline().rstrip()

def resolve():
    n, W = list(map(int, input().split()))
    dp = [INF] * (n * 1001 + 1)
    dp[0] = 0
    for _ in range(n):
        w, v = list(map(int, input().split()))
        for v0 in range(n * 1001, -1, -1):
            if dp[v0] == INF:
                continue
            if v + v0 <= n * 1001:
                dp[v + v0] = min(dp[v + v0], dp[v0] + w)
    for v in range(n * 1001, -1, -1):
        if dp[v] <= W:
            print(v)
            return

resolve()

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

-                dp[x + v] = min(dp[x + v], dp[x] + w)

+        w, v = list(map(int, input().split()))


Input:
from collections import defaultdict

def main():

    _ = int(input())

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

    """

    for j>i, j-i = Ai + Aj

    i + Ai = j -Aj

    """

    L = defaultdict(int)

    R = defaultdict(int)

    for i, height in enumerate(heights):

        L[i + height] += 1

        R[i - height] += 1

    total_count = 0

    for x, count_l in list(L.items()):

        if x in R:

            count_r = R[x]

            total_count += count_l * count_r

    print(total_count)

if __name__ == "__main__":

    main()

from collections import defaultdict

def main():

    N = int(input())

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

    """

    for j>i, j-i = Ai + Aj

    i + Ai = j -Aj

    """

    L = defaultdict(int)

    R = defaultdict(int)

    for i, height in enumerate(heights):

        if i + height < N:

            L[i + height] += 1

        if i - height > 0:

            R[i - height] += 1

    total_count = 0

    for x, count_l in list(L.items()):

        if x in R:

            count_r = R[x]

            total_count += count_l * count_r

    print(total_count)

if __name__ == "__main__":

    main()

-    _ = int(input())
+    N = int(input())
-        L[i + height] += 1
-        R[i - height] += 1
+        if i + height < N:
+            L[i + height] += 1
+        if i - height > 0:
+            R[i - height] += 1


Input:
import sys

readline = sys.stdin.readline

sys.setrecursionlimit(10**8)

mod = 10**9+7

#mod = 998244353

INF = 10**18

eps = 10**-7

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

def comb(n, r, mod):

    r = min(r, n-r)

    mol = 1

    deno = 1

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

        mol = mol * (n-r+i) % mod

        deno = deno * i % mod

    ret = mol * pow(deno, mod-2, mod) % mod

    return ret

def f1(x,y,a,b):

    return (a+b-x-y)*(a-x+1)*(b-y+1)//2

def f2(x,a):

    return (a-x)*(a-x+1)//2

ans = 0

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

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

        a = n-x+1

        b = m-y+1

        c = m*(a*(a-1)+x*(x-1))

        d = n*(b*(b-1)+y*(y-1))

        ans += (c+d)//2

        ans %= mod

ans = (ans * comb(m*n-2,k-2,mod))%mod

ans = ans*pow(2,mod-2,mod)%mod

print(ans)

import sys

readline = sys.stdin.readline

sys.setrecursionlimit(10**8)

mod = 10**9+7

#mod = 998244353

INF = 10**18

eps = 10**-7

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

def comb(n, r, mod):

    r = min(r, n-r)

    mol = 1

    deno = 1

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

        mol = mol * (n-r+i) % mod

        deno = deno * i % mod

    ret = mol * pow(deno, mod-2, mod) % mod

    return ret

ans = m*n*(m+n)*(m*n-1)//3

ans = (ans * comb(m*n-2,k-2,mod))%mod

ans = ans*pow(2,mod-2,mod)%mod

print(ans)

import sys

readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9 + 7
# mod = 998244353
INF = 10**18
eps = 10**-7
m, n, k = list(map(int, readline().split()))

def comb(n, r, mod):
    r = min(r, n - r)
    mol = 1
    deno = 1
    for i in range(1, r + 1):
        mol = mol * (n - r + i) % mod
        deno = deno * i % mod
    ret = mol * pow(deno, mod - 2, mod) % mod
    return ret

def f1(x, y, a, b):
    return (a + b - x - y) * (a - x + 1) * (b - y + 1) // 2

def f2(x, a):
    return (a - x) * (a - x + 1) // 2

ans = 0
for x in range(1, n + 1):
    for y in range(1, m + 1):
        a = n - x + 1
        b = m - y + 1
        c = m * (a * (a - 1) + x * (x - 1))
        d = n * (b * (b - 1) + y * (y - 1))
        ans += (c + d) // 2
        ans %= mod
ans = (ans * comb(m * n - 2, k - 2, mod)) % mod
ans = ans * pow(2, mod - 2, mod) % mod
print(ans)

import sys

readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9 + 7
# mod = 998244353
INF = 10**18
eps = 10**-7
m, n, k = list(map(int, readline().split()))

def comb(n, r, mod):
    r = min(r, n - r)
    mol = 1
    deno = 1
    for i in range(1, r + 1):
        mol = mol * (n - r + i) % mod
        deno = deno * i % mod
    ret = mol * pow(deno, mod - 2, mod) % mod
    return ret

ans = m * n * (m + n) * (m * n - 1) // 3
ans = (ans * comb(m * n - 2, k - 2, mod)) % mod
ans = ans * pow(2, mod - 2, mod) % mod
print(ans)


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

div =[]

for i in range(2,int(M**(1/2))+2):

    cur = 0

    while M%i==0:

        M = M//i

        cur += 1

    if cur >=1:

        div.append(cur)

if M>1: div.append(1)

div.sort()

mod = 10**9+7

frac = [1]*(N+50)

num = len(frac)

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

    frac[i+1] = frac[i]*(i+1)%mod

finv = [1] * (N+50)

finv[-1] = pow(frac[-1], mod-2, mod)

for i in range(1, num):

  finv[num-1-i] = finv[num-i] * (num-i) % mod

ans = 1

for i in div:

    ans = ans * frac[N+i-1]*finv[N-1]*finv[i]%mod

print(ans)

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

div = []

for i in range(2,int(M**(1/2))+2):

    cur = 0

    while M%i==0:

        M//=i

        cur += 1

    if cur >=1:

        div.append(cur)

if M>1:div.append(1)

div.sort()

mod = 10**9+7

frac = [1]*(N+50)

num=len(frac)

for i in range(num-1):

    frac[i+1] = frac[i]*(i+1)%mod

finv = [1]*(N+50)

finv[-1] = pow(frac[-1],mod-2,mod)

ans = 1

for i in range(1,num):

    finv[num-1-i] = finv[num-i]*(num-i)%mod

for i in div:

    ans  =ans*frac[N+i-1]*finv[N-1]*finv[i]%mod

print(ans)

N, M = list(map(int, input().split()))
div = []
for i in range(2, int(M ** (1 / 2)) + 2):
    cur = 0
    while M % i == 0:
        M = M // i
        cur += 1
    if cur >= 1:
        div.append(cur)
if M > 1:
    div.append(1)
div.sort()
mod = 10**9 + 7
frac = [1] * (N + 50)
num = len(frac)
for i in range(len(frac) - 1):
    frac[i + 1] = frac[i] * (i + 1) % mod
finv = [1] * (N + 50)
finv[-1] = pow(frac[-1], mod - 2, mod)
for i in range(1, num):
    finv[num - 1 - i] = finv[num - i] * (num - i) % mod
ans = 1
for i in div:
    ans = ans * frac[N + i - 1] * finv[N - 1] * finv[i] % mod
print(ans)

N, M = list(map(int, input().split()))
div = []
for i in range(2, int(M ** (1 / 2)) + 2):
    cur = 0
    while M % i == 0:
        M //= i
        cur += 1
    if cur >= 1:
        div.append(cur)
if M > 1:
    div.append(1)
div.sort()
mod = 10**9 + 7
frac = [1] * (N + 50)
num = len(frac)
for i in range(num - 1):
    frac[i + 1] = frac[i] * (i + 1) % mod
finv = [1] * (N + 50)
finv[-1] = pow(frac[-1], mod - 2, mod)
ans = 1
for i in range(1, num):
    finv[num - 1 - i] = finv[num - i] * (num - i) % mod
for i in div:
    ans = ans * frac[N + i - 1] * finv[N - 1] * finv[i] % mod
print(ans)

-        M = M // i
+        M //= i
-for i in range(len(frac) - 1):
+for i in range(num - 1):
+ans = 1
-ans = 1


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

# print(a, b, c, x, y)

ans = 10000 * (10 **5) + 7

c_max = 0

if x > y:

  c_max = x * 2

else:

  c_max = y * 2

for cc in range(c_max+1):

  ac = x - (cc // 2)

  bc = y - (cc // 2)

  if ac < 0:

    ac = 0

  if bc < 0:

    bc = 0

  price = ac * a + bc * b + cc * c

  # print('price: {}, ac: {}, bc: {}, cc: {}'.format(price, ac, bc, cc))

  ans = min(ans, price)

print(ans)

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

# print(a, b, c, x, y)

ans = 10000 * (10 **5) + 7

c_max = 0

if x > y:

  c_max = x * 2

else:

  c_max = y * 2

for cc in range(0, c_max+1, 2):

  ac = x - (cc // 2)

  bc = y - (cc // 2)

  if ac < 0:

    ac = 0

  if bc < 0:

    bc = 0

  price = ac * a + bc * b + cc * c

  # print('price: {}, ac: {}, bc: {}, cc: {}'.format(price, ac, bc, cc))

  ans = min(ans, price)

print(ans)

a, b, c, x, y = list(map(int, input().split()))
# print(a, b, c, x, y)
ans = 10000 * (10**5) + 7
c_max = 0
if x > y:
    c_max = x * 2
else:
    c_max = y * 2
for cc in range(c_max + 1):
    ac = x - (cc // 2)
    bc = y - (cc // 2)
    if ac < 0:
        ac = 0
    if bc < 0:
        bc = 0
    price = ac * a + bc * b + cc * c
    # print('price: {}, ac: {}, bc: {}, cc: {}'.format(price, ac, bc, cc))
    ans = min(ans, price)
print(ans)

a, b, c, x, y = list(map(int, input().split()))
# print(a, b, c, x, y)
ans = 10000 * (10**5) + 7
c_max = 0
if x > y:
    c_max = x * 2
else:
    c_max = y * 2
for cc in range(0, c_max + 1, 2):
    ac = x - (cc // 2)
    bc = y - (cc // 2)
    if ac < 0:
        ac = 0
    if bc < 0:
        bc = 0
    price = ac * a + bc * b + cc * c
    # print('price: {}, ac: {}, bc: {}, cc: {}'.format(price, ac, bc, cc))
    ans = min(ans, price)
print(ans)

-for cc in range(c_max + 1):
+for cc in range(0, c_max + 1, 2):


Input:
N = int(input())

name = {'M':0, 'A':0, 'R':0, 'C':0, 'H':0}

march = "MARCH"

for _ in range(N):

  S = input()

  if(S[0] in name):

    name[S[0]] += 1

ans = 0

for i in range(3):

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

    for k in range(j+1,5):

      ans += name[march[i]] * name[march[j]] * name[march[k]]

print(ans)

N = int(input())

S = [input() for _ in range(N)]

head = {'M':0, 'A':0, 'R':0, 'C':0, 'H':0}

march = "MARCH"

for s in S:

  if(s[0] in head):

    head[s[0]] += 1

ans = 0

for i in range(3):

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

    for k in range(j+1,5):

      ans += head[march[i]] * head[march[j]] * head[march[k]]

print(ans)

N = int(input())
name = {"M": 0, "A": 0, "R": 0, "C": 0, "H": 0}
march = "MARCH"
for _ in range(N):
    S = input()
    if S[0] in name:
        name[S[0]] += 1
ans = 0
for i in range(3):
    for j in range(i + 1, 4):
        for k in range(j + 1, 5):
            ans += name[march[i]] * name[march[j]] * name[march[k]]
print(ans)

N = int(input())
S = [input() for _ in range(N)]
head = {"M": 0, "A": 0, "R": 0, "C": 0, "H": 0}
march = "MARCH"
for s in S:
    if s[0] in head:
        head[s[0]] += 1
ans = 0
for i in range(3):
    for j in range(i + 1, 4):
        for k in range(j + 1, 5):
            ans += head[march[i]] * head[march[j]] * head[march[k]]
print(ans)

-            ans += name[march[i]] * name[march[j]] * name[march[k]]

+            ans += head[march[i]] * head[march[j]] * head[march[k]]


Input:
from functools import lru_cache

import sys

sys.setrecursionlimit(30000)

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

a = list(int(input()) for _ in range(M))

MOD = pow(10, 9) + 7

isOk = True

for i in range(M-1):

    if a[i] + 1 == a[i+1]:

        isOk = False

funcb = [-1] * 100001

def func(n):

    if n <= 0:

        return 1

    cnt = funcb[n]

    if cnt > 0:

        return cnt

    cnt = 0

    if n >= 2:

        cnt += func(n-2)

    if n >= 1:

        cnt += func(n-1)

    funcb[n] = cnt % MOD

    return funcb[n]

func(30000)

func(50000)

func(80000)

func(100000)

if not isOk:

    print((0))

else:

    ans = 1

    s = 0

    for i in range(M+1):

        if i >= M:

            e = N

        else:

            e = a[i] - 1

        ans = ans * func(e-s) % MOD

        if i >= M:

            break

        s = a[i] + 1

    print(ans)

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

a = list(int(input()) for _ in range(M))

MOD = pow(10, 9) + 7

MAP = [0] * (N + 1)

for x in a:

    MAP[x] = -1

MAP[0] = 1

for i in range(N):

    if MAP[i] < 0:

        continue

    MAP[i] %= MOD

    if i + 1 <= N and MAP[i+1] >= 0:

        MAP[i+1] += MAP[i]

    if i + 2 <= N and MAP[i+2] >= 0:

        MAP[i+2] += MAP[i]

print((MAP[N] % MOD))

from functools import lru_cache
import sys

sys.setrecursionlimit(30000)
N, M = list(map(int, input().split()))
a = list(int(input()) for _ in range(M))
MOD = pow(10, 9) + 7
isOk = True
for i in range(M - 1):
    if a[i] + 1 == a[i + 1]:
        isOk = False
funcb = [-1] * 100001

def func(n):
    if n <= 0:
        return 1
    cnt = funcb[n]
    if cnt > 0:
        return cnt
    cnt = 0
    if n >= 2:
        cnt += func(n - 2)
    if n >= 1:
        cnt += func(n - 1)
    funcb[n] = cnt % MOD
    return funcb[n]

func(30000)
func(50000)
func(80000)
func(100000)
if not isOk:
    print((0))
else:
    ans = 1
    s = 0
    for i in range(M + 1):
        if i >= M:
            e = N
        else:
            e = a[i] - 1
        ans = ans * func(e - s) % MOD
        if i >= M:
            break
        s = a[i] + 1
    print(ans)

N, M = list(map(int, input().split()))
a = list(int(input()) for _ in range(M))
MOD = pow(10, 9) + 7
MAP = [0] * (N + 1)
for x in a:
    MAP[x] = -1
MAP[0] = 1
for i in range(N):
    if MAP[i] < 0:
        continue
    MAP[i] %= MOD
    if i + 1 <= N and MAP[i + 1] >= 0:
        MAP[i + 1] += MAP[i]
    if i + 2 <= N and MAP[i + 2] >= 0:
        MAP[i + 2] += MAP[i]
print((MAP[N] % MOD))

-from functools import lru_cache
-import sys
-sys.setrecursionlimit(30000)
-isOk = True
-for i in range(M - 1):
-    if a[i] + 1 == a[i + 1]:
-        isOk = False
-funcb = [-1] * 100001
-def func(n):
-    if n <= 0:
-        return 1
-    cnt = funcb[n]
-    if cnt > 0:
-        return cnt
-    cnt = 0
-    if n >= 2:
-        cnt += func(n - 2)
-    if n >= 1:
-        cnt += func(n - 1)
-    funcb[n] = cnt % MOD
-    return funcb[n]
-func(30000)
-func(50000)
-func(80000)
-func(100000)
-if not isOk:
-    print((0))
-else:
-    ans = 1
-    s = 0
-    for i in range(M + 1):
-        if i >= M:
-            e = N
-        else:
-            e = a[i] - 1
-        ans = ans * func(e - s) % MOD
-        if i >= M:
-            break
-        s = a[i] + 1
-    print(ans)
+MAP = [0] * (N + 1)
+for x in a:
+    MAP[x] = -1
+MAP[0] = 1
+for i in range(N):
+    if MAP[i] < 0:
+        continue
+    MAP[i] %= MOD
+    if i + 1 <= N and MAP[i + 1] >= 0:
+        MAP[i + 1] += MAP[i]
+    if i + 2 <= N and MAP[i + 2] >= 0:
+        MAP[i + 2] += MAP[i]
+print((MAP[N] % MOD))


Input:
#                         author:  kagemeka

#                         created: 2019-11-06 21:30:22(JST)

import sys

# import collections

# import math

# import string

# import bisect

# import re

# import itertools

# import statistics

# import functools

# import operator

def main():

    a, b = (int(x) for x in sys.stdin.read().split())

    count = 0

    for n in range(a, b+1):

        n = str(n)

        if n == n[::-1]:

            count += 1

    print(count)

if __name__ == "__main__":

    # execute only if run as a script

    main()

import sys

from bisect import bisect_left as bi_l, bisect_right as bi_r

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

def main():

    palindromic_nums = []

    for i in range(1, 10):

        for j in range(10):

            for k in range(10):

                x = [i, j, k, j, i]

                palindromic_nums.append(int(''.join(list(map(str, x)))))

    return bi_r(palindromic_nums, b) - bi_l(palindromic_nums, a)

if __name__ == '__main__':

    ans = main()

    print(ans)

#                         author:  kagemeka
#                         created: 2019-11-06 21:30:22(JST)
import sys

# import collections
# import math
# import string
# import bisect
# import re
# import itertools
# import statistics
# import functools
# import operator
def main():
    a, b = (int(x) for x in sys.stdin.read().split())
    count = 0
    for n in range(a, b + 1):
        n = str(n)
        if n == n[::-1]:
            count += 1
    print(count)

if __name__ == "__main__":
    # execute only if run as a script
    main()

import sys
from bisect import bisect_left as bi_l, bisect_right as bi_r

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

def main():
    palindromic_nums = []
    for i in range(1, 10):
        for j in range(10):
            for k in range(10):
                x = [i, j, k, j, i]
                palindromic_nums.append(int("".join(list(map(str, x)))))
    return bi_r(palindromic_nums, b) - bi_l(palindromic_nums, a)

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

-#                         author:  kagemeka

+from bisect import bisect_left as bi_l, bisect_right as bi_r

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

-    a, b = (int(x) for x in sys.stdin.read().split())

+                palindromic_nums.append(int("".join(list(map(str, x)))))

+    return bi_r(palindromic_nums, b) - bi_l(palindromic_nums, a)


Input:
def check(x, y):

    for a, b in zip(x, y):

        if a != b and b != -1:

            return False

    else:

        return True

n = int(input())

remarks = []

cnt_max = 0

for _ in range(n):

    a = int(input())

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

    r = [-1] * n

    for i, j in x:

        r[i - 1] = j

    remarks.append(r)

for r in range(2 ** n):

    r = list(bin(r)[2:].zfill(n))

    r = [int(i) for i in r[:]]

    cnt = 0

    for i in range(n):

        if r[i] == 1:

            flag = check(r, remarks[i])

            cnt += 1

            if not flag:

                cnt = 0

                break

    cnt_max = max(cnt, cnt_max)

print(cnt_max)

import numpy as np

import itertools

n = int(input())

info = []

for i in range(n):

    a = int(input())

    for _ in range(a):

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

        info.append((i, x - 1, y))

a = np.array(list(itertools.product([0, 1], repeat=n)), dtype=np.bool)

for i, x, y in info:

    bl = (~a[:, i]) | (a[:, x] == bool(y))

    a = a[bl]

ans = a.sum(axis=1).max()

print(ans)

def check(x, y):
    for a, b in zip(x, y):
        if a != b and b != -1:
            return False
    else:
        return True

n = int(input())
remarks = []
cnt_max = 0
for _ in range(n):
    a = int(input())
    x = [tuple(map(int, input().split())) for i in range(a)]
    r = [-1] * n
    for i, j in x:
        r[i - 1] = j
    remarks.append(r)
for r in range(2**n):
    r = list(bin(r)[2:].zfill(n))
    r = [int(i) for i in r[:]]
    cnt = 0
    for i in range(n):
        if r[i] == 1:
            flag = check(r, remarks[i])
            cnt += 1
            if not flag:
                cnt = 0
                break
    cnt_max = max(cnt, cnt_max)
print(cnt_max)

-    x = [tuple(map(int, input().split())) for i in range(a)]

-            flag = check(r, remarks[i])

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

+a = np.array(list(itertools.product([0, 1], repeat=n)), dtype=np.bool)


Input:
from collections import Counter,defaultdict,deque

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

from heapq import heappop, heappush

sys.setrecursionlimit(10**8)

mod = 10**9+7

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

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

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

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

n = inp()

res = float('inf')

for i in range(1,2*10**6):

    if (n/i).is_integer():

        res = min(res, i + n/i)

print((int(res-2)))

from collections import Counter,defaultdict,deque

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

from heapq import heappop, heappush

sys.setrecursionlimit(10**8)

mod = 10**9+7

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

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

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

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

n = inp()

res = float('inf')

for i in range(1,int(math.sqrt(n))+1):

    if n%i == 0:

        res = min(res, i + n/i)

print((int(res-2)))

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

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

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

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

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

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

n = inp()
res = float("inf")
for i in range(1, 2 * 10**6):
    if (n / i).is_integer():
        res = min(res, i + n / i)
print((int(res - 2)))

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

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

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

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

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

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

n = inp()
res = float("inf")
for i in range(1, int(math.sqrt(n)) + 1):
    if n % i == 0:
        res = min(res, i + n / i)
print((int(res - 2)))

+for i in range(1, int(math.sqrt(n)) + 1):


Input:
S = int(input())

dp = [0] * (S + 1)

dp[0] = 1

M = 10 ** 9 + 7

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

    num = 0

    for j in range(i - 2):

        num += dp[j]

        dp[i] = num % M

print((dp[S]))

S = int(input())

def cmb(n, r, p):

    r = min(n - r, r)

    if r == 0:

        return 1

    over = 1

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

        over = over * i % p

    under = 1

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

        under = under * i % p

    inv = pow(under, p - 2, p)

    return over * inv % p

M = 10 ** 9 + 7

ans = 0

for i in range(1, S):

    if S - 3 * i < 0:

        break

    ans += cmb(S - 3 * i + i - 1, i - 1, M)

    ans %= M

print(ans)

S = int(input())
dp = [0] * (S + 1)
dp[0] = 1
M = 10**9 + 7
for i in range(1, S + 1):
    num = 0
    for j in range(i - 2):
        num += dp[j]
        dp[i] = num % M
print((dp[S]))

S = int(input())

def cmb(n, r, p):
    r = min(n - r, r)
    if r == 0:
        return 1
    over = 1
    for i in range(n, n - r, -1):
        over = over * i % p
    under = 1
    for i in range(1, r + 1):
        under = under * i % p
    inv = pow(under, p - 2, p)
    return over * inv % p

M = 10**9 + 7
ans = 0
for i in range(1, S):
    if S - 3 * i < 0:
        break
    ans += cmb(S - 3 * i + i - 1, i - 1, M)
    ans %= M
print(ans)


Input:
import sys

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

S = input()

def nexti(n):

    while S[n] == '1':

        n += 1

    while S[n] == '0':

        n += 1

    return n

def nextj(n):

    while S[n] == '0':

        n += 1

        if n == N:

            return N

    while S[n] == '1':

        n += 1

        if n == N:

            return N

    return n

i = 0

j = 0

while S[j] == '1':

    j += 1

    if j == N:

        print(N)

        sys.exit(0)

for _ in range(K):

    j = nextj(j)

    if j == N:

        print(N)

        sys.exit(0)

ans = j - i

while True:

    i = nexti(i)

    j = nextj(j)

    ans = max(ans, j - i)

    if j == N:

        break

print(ans)

from collections import deque

def nextj(n):

    while S[n] == '0':

        n += 1

        if n == N:

            return N

    q.appendleft(n)

    while S[n] == '1':

        n += 1

        if n == N:

            return N

    return n

def init(n):

    while S[n] == '1':

        n += 1

        if n == N:

            return N

    return n

def calc():

    q.appendleft(0)

    ans = 0

    j = init(0)

    if j == N:

        return N

    for _ in range(K - 1):

        j = nextj(j)

        if j == N:

            return N

    while True:

        j = nextj(j)

        ans = max(ans, j - q.pop())

        if j == N:

            return ans

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

S = input()

q = deque()

print((calc()))

import sys

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

def nexti(n):
    while S[n] == "1":
        n += 1
    while S[n] == "0":
        n += 1
    return n

def nextj(n):
    while S[n] == "0":
        n += 1
        if n == N:
            return N
    while S[n] == "1":
        n += 1
        if n == N:
            return N
    return n

i = 0
j = 0
while S[j] == "1":
    j += 1
    if j == N:
        print(N)
        sys.exit(0)
for _ in range(K):
    j = nextj(j)
    if j == N:
        print(N)
        sys.exit(0)
ans = j - i
while True:
    i = nexti(i)
    j = nextj(j)
    ans = max(ans, j - i)
    if j == N:
        break
print(ans)

from collections import deque

def nextj(n):
    while S[n] == "0":
        n += 1
        if n == N:
            return N
    q.appendleft(n)
    while S[n] == "1":
        n += 1
        if n == N:
            return N
    return n

def init(n):
    while S[n] == "1":
        n += 1
        if n == N:
            return N
    return n

def calc():
    q.appendleft(0)
    ans = 0
    j = init(0)
    if j == N:
        return N
    for _ in range(K - 1):
        j = nextj(j)
        if j == N:
            return N
    while True:
        j = nextj(j)
        ans = max(ans, j - q.pop())
        if j == N:
            return ans

N, K = list(map(int, input().split()))
S = input()
q = deque()
print((calc()))

-import sys
-N, K = list(map(int, input().split()))
-S = input()
-def nexti(n):
-    while S[n] == "1":
-        n += 1
-    while S[n] == "0":
-        n += 1
-    return n
+from collections import deque
+    q.appendleft(n)
-i = 0
-j = 0
-while S[j] == "1":
-    j += 1
+def init(n):
+    while S[n] == "1":
+        n += 1
+        if n == N:
+            return N
+    return n
+
+
+def calc():
+    q.appendleft(0)
+    ans = 0
+    j = init(0)
-        print(N)
-        sys.exit(0)
-for _ in range(K):
-    j = nextj(j)
-    if j == N:
-        print(N)
-        sys.exit(0)
-ans = j - i
-while True:
-    i = nexti(i)
-    j = nextj(j)
-    ans = max(ans, j - i)
-    if j == N:
-        break
-print(ans)
+        return N
+    for _ in range(K - 1):
+        j = nextj(j)
+        if j == N:
+            return N
+    while True:
+        j = nextj(j)
+        ans = max(ans, j - q.pop())
+        if j == N:
+            return ans
+
+
+N, K = list(map(int, input().split()))
+S = input()
+q = deque()
+print((calc()))


Input:
# Problem https://atcoder.jp/contests/abc053/tasks/abc053_b

# Python 1st Try

import copy

class Problem:

    def __init__(self, stringdata):

        self.stringdata = stringdata

    def solver(self):

        strcont = copy.copy(self.stringdata)

        result = 0

        rightposition = 0

        leftposition = len(strcont)

        j = 0

        while True:

            if strcont[j] == 'A':

                rightposition = j

                break

            else:

                j = j + 1

        j = leftposition - 1

        while True:

            if strcont[j] == 'Z':

                leftposition = j

                break

            else:

                j = j - 1

        result = leftposition - rightposition + 1

        return result

if __name__ == "__main__":

    s = input()

    print(("{}".format(Problem(s).solver())))

# Problem https://atcoder.jp/contests/abc053/tasks/abc053_b

# Python 2nd Try

def solver(string):

    result = 200000

    aposi = 0

    zposi = len(string)

    for j in range(0, len(string), 1):

        if string[j] == 'A':

            aposi = j

            break

    for j in range(len(string)-1, -1, -1):

        if string[j] == 'Z':

            zposi = j

            break

    result = zposi - aposi + 1

    return result

if __name__ == "__main__":

    s = input()

    print(('{}'.format(solver(s))))

# Problem https://atcoder.jp/contests/abc053/tasks/abc053_b
# Python 1st Try
import copy

class Problem:
    def __init__(self, stringdata):
        self.stringdata = stringdata

    def solver(self):
        strcont = copy.copy(self.stringdata)
        result = 0
        rightposition = 0
        leftposition = len(strcont)
        j = 0
        while True:
            if strcont[j] == "A":
                rightposition = j
                break
            else:
                j = j + 1
        j = leftposition - 1
        while True:
            if strcont[j] == "Z":
                leftposition = j
                break
            else:
                j = j - 1
        result = leftposition - rightposition + 1
        return result

if __name__ == "__main__":
    s = input()
    print(("{}".format(Problem(s).solver())))

# Problem https://atcoder.jp/contests/abc053/tasks/abc053_b
# Python 2nd Try
def solver(string):
    result = 200000
    aposi = 0
    zposi = len(string)
    for j in range(0, len(string), 1):
        if string[j] == "A":
            aposi = j
            break
    for j in range(len(string) - 1, -1, -1):
        if string[j] == "Z":
            zposi = j
            break
    result = zposi - aposi + 1
    return result

if __name__ == "__main__":
    s = input()
    print(("{}".format(solver(s))))

-        strcont = copy.copy(self.stringdata)

-        result = leftposition - rightposition + 1

+    for j in range(len(string) - 1, -1, -1):

-    print(("{}".format(Problem(s).solver())))


Input:
from math import gcd

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

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

a=list(set(a))

a=list([x//2 for x in a])

def lcm(q):

  x = q[0]

  for i in range(1, len(q)):

    x = (x * q[i]) // gcd(x, q[i])

  return x

lcma=lcm(a)

if (lcma//a[0])%2==0:

  print((0))

else:

  flg=0

  for i in range(1,len(a)):

    if (lcma//a[i])%2==0:

      print((0))

      flg=1

      break

  if flg==0:

    temp=m//lcma

    print((temp//2 if temp%2==0 else temp//2+1))

from math import gcd

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

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

a=list(set(a))

a=list([x//2 for x in a])

def lcm(q):

  x = q[0]

  for i in range(1, len(q)):

    x = (x * q[i]) // gcd(x, q[i])

  return x

lcma=lcm(a)

for i in range(len(a)):

  if (lcma//a[i])%2==0:

    print((0))

    exit()

temp=m//lcma

print((temp//2 if temp%2==0 else temp//2+1))

from math import gcd

n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
a = list(set(a))
a = list([x // 2 for x in a])

def lcm(q):
    x = q[0]
    for i in range(1, len(q)):
        x = (x * q[i]) // gcd(x, q[i])
    return x

lcma = lcm(a)
if (lcma // a[0]) % 2 == 0:
    print((0))
else:
    flg = 0
    for i in range(1, len(a)):
        if (lcma // a[i]) % 2 == 0:
            print((0))
            flg = 1
            break
    if flg == 0:
        temp = m // lcma
        print((temp // 2 if temp % 2 == 0 else temp // 2 + 1))

from math import gcd

n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
a = list(set(a))
a = list([x // 2 for x in a])

def lcm(q):
    x = q[0]
    for i in range(1, len(q)):
        x = (x * q[i]) // gcd(x, q[i])
    return x

lcma = lcm(a)
for i in range(len(a)):
    if (lcma // a[i]) % 2 == 0:
        print((0))
        exit()
temp = m // lcma
print((temp // 2 if temp % 2 == 0 else temp // 2 + 1))

-        print((temp // 2 if temp % 2 == 0 else temp // 2 + 1))

+print((temp // 2 if temp % 2 == 0 else temp // 2 + 1))


Input:
N = int(input())

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

n = N % 2

DP = [[0] * (N+1) for _ in range(N+1)]

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

    for i in range(N):

        j = i + w

        if j > N:

            continue

        if (w+n) % 2 == 1:

            DP[i][j] = min(DP[i+1][j] - A[i], DP[i][j-1] - A[j-1])

        else:

            DP[i][j] = max(DP[i+1][j] + A[i], DP[i][j-1] + A[j-1])

print((DP[0][N]))

N = int(input())

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

DP = [[0] * (N+1) for _ in range(N+1)]

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

    for start in range(N):

        end = start + num

        if end > N:

            break

        if num == 1:

            DP[start][end] = A[start]

        else:

            DP[start][end] = max(A[start] - DP[start+1][end], A[end - 1] - DP[start][end - 1])

print((DP[0][N]))

N = int(input())
A = list(map(int, input().split()))
n = N % 2
DP = [[0] * (N + 1) for _ in range(N + 1)]
for w in range(1, N + 1):
    for i in range(N):
        j = i + w
        if j > N:
            continue
        if (w + n) % 2 == 1:
            DP[i][j] = min(DP[i + 1][j] - A[i], DP[i][j - 1] - A[j - 1])
        else:
            DP[i][j] = max(DP[i + 1][j] + A[i], DP[i][j - 1] + A[j - 1])
print((DP[0][N]))

N = int(input())
A = list(map(int, input().split()))
DP = [[0] * (N + 1) for _ in range(N + 1)]
for num in range(1, N + 1):
    for start in range(N):
        end = start + num
        if end > N:
            break
        if num == 1:
            DP[start][end] = A[start]
        else:
            DP[start][end] = max(
                A[start] - DP[start + 1][end], A[end - 1] - DP[start][end - 1]
            )
print((DP[0][N]))

+                A[start] - DP[start + 1][end], A[end - 1] - DP[start][end - 1]


Input:
from math import gcd

N = int(input())

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

c = True

def osa_k(max_num):

  lis = [i for i in range(max_num+1)]

  p = 2

  while p**2 <= max_num:

    if lis[p] == p:

      for q in range(2*p, max_num+1, p):

        if lis[q] == q:

          lis[q] = p

    p += 1

  return lis

hoge = 0

for i in num_lis:

  hoge = gcd(hoge, i)

if hoge > 1:

  print("not coprime")

  exit()

d_lis = osa_k(10**6+10)

tmp = set()

for i in num_lis:

  num = i

  new_tmp = set()

  while num > 1:

    d = d_lis[num]

    new_tmp.add(d)

    num //= d

  for j in new_tmp:

    if j in tmp:

      c = False

      break

    else:

      tmp.add(j)

  else:

    continue

  break

if c:

  print("pairwise coprime")

else:

  print("setwise coprime")

from math import gcd

N = int(input())

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

def osa_k(max_num):

  lis = [i for i in range(max_num+1)]

  p = 2

  while p**2 <= max_num:

    if lis[p] == p:

      for q in range(2*p, max_num+1, p):

        if lis[q] == q:

          lis[q] = p

    p += 1

  return lis

hoge = 0

for i in num_lis:

  hoge = gcd(hoge, i)

if hoge > 1:

  print("not coprime")

  exit()

d_lis = osa_k(max(num_lis))

tmp = set()

for i in num_lis:

  num = i

  new_tmp = set()

  while num > 1:

    d = d_lis[num]

    new_tmp.add(d)

    num //= d

  for j in new_tmp:

    if j in tmp:

      print("setwise coprime")

      exit()

    else:

      tmp.add(j)

print("pairwise coprime")

from math import gcd

N = int(input())
num_lis = list(map(int, input().split()))
c = True

def osa_k(max_num):
    lis = [i for i in range(max_num + 1)]
    p = 2
    while p**2 <= max_num:
        if lis[p] == p:
            for q in range(2 * p, max_num + 1, p):
                if lis[q] == q:
                    lis[q] = p
        p += 1
    return lis

hoge = 0
for i in num_lis:
    hoge = gcd(hoge, i)
if hoge > 1:
    print("not coprime")
    exit()
d_lis = osa_k(10**6 + 10)
tmp = set()
for i in num_lis:
    num = i
    new_tmp = set()
    while num > 1:
        d = d_lis[num]
        new_tmp.add(d)
        num //= d
    for j in new_tmp:
        if j in tmp:
            c = False
            break
        else:
            tmp.add(j)
    else:
        continue
    break
if c:
    print("pairwise coprime")
else:
    print("setwise coprime")

from math import gcd

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

def osa_k(max_num):
    lis = [i for i in range(max_num + 1)]
    p = 2
    while p**2 <= max_num:
        if lis[p] == p:
            for q in range(2 * p, max_num + 1, p):
                if lis[q] == q:
                    lis[q] = p
        p += 1
    return lis

hoge = 0
for i in num_lis:
    hoge = gcd(hoge, i)
if hoge > 1:
    print("not coprime")
    exit()
d_lis = osa_k(max(num_lis))
tmp = set()
for i in num_lis:
    num = i
    new_tmp = set()
    while num > 1:
        d = d_lis[num]
        new_tmp.add(d)
        num //= d
    for j in new_tmp:
        if j in tmp:
            print("setwise coprime")
            exit()
        else:
            tmp.add(j)
print("pairwise coprime")

-c = True
-d_lis = osa_k(10**6 + 10)
+d_lis = osa_k(max(num_lis))
-            c = False
-            break
+            print("setwise coprime")
+            exit()
-    else:
-        continue
-    break
-if c:
-    print("pairwise coprime")
-else:
-    print("setwise coprime")
+print("pairwise coprime")


Input:
n = int(input())

edges = []

for id in range(n-1):

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

    edges.append([a-1, b-1, id])

edges.sort()

used = [0]*(n)

ans = [0]*(n-1)

num = 1

prev = 0

for edge in edges:

    _from, to, id = edge

    if _from != prev:

        num = 1

    if used[_from] == num:

        num += 1

    ans[id] = num

    used[to] = num

    num += 1

    prev = _from

print((max(ans)))

for color in ans:

    print(color)

import sys

input = sys.stdin.readline

n = int(input())

edges = []

for id in range(n-1):

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

    edges.append([a-1, b-1, id])

edges.sort()

used = [0]*(n)

ans = [0]*(n-1)

num = 1

prev = 0

for edge in edges:

    _from, to, id = edge

    if _from != prev:

        num = 1

    if used[_from] == num:

        num += 1

    ans[id] = num

    used[to] = num

    num += 1

    prev = _from

print((max(ans)))

for color in ans:

    print(color)

import sys

input = sys.stdin.readline
n = int(input())
edges = []
for id in range(n - 1):
    a, b = list(map(int, input().split()))
    edges.append([a - 1, b - 1, id])
edges.sort()
used = [0] * (n)
ans = [0] * (n - 1)
num = 1
prev = 0
for edge in edges:
    _from, to, id = edge
    if _from != prev:
        num = 1
    if used[_from] == num:
        num += 1
    ans[id] = num
    used[to] = num
    num += 1
    prev = _from
print((max(ans)))
for color in ans:
    print(color)

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


Input:
dX = [2,2,2,1,0,-1,-2,-2,-2,-1,0,1]

dY = [-1,0,1,2,2,2,1,0,-1,-2,-2,-2]

def solve(x,y,XY):

	xy = XY[:]

	if len(xy) == 0: return "OK"

	sx,sy = xy.pop(0),xy.pop(0)

	for dx,dy in zip(dX,dY):

		if doa(x+dx,y+dy,sx,sy):

			r = solve(x+dx,y+dy,xy)

			if r: return r

def doa(x,y,sx,sy):

	if not (0 <= x <= 9 and 0 <= y <= 9): return False

	return True if abs(x-sx) < 2 and abs(y-sy) < 2 else False

while 1:

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

	if x == y == 0: break

	n = input()

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

	ans = solve(x,y,xy)

	print(ans if ans else "NA")

dX = [2,2,2,1,0,-1,-2,-2,-2,-1,0,1]

dY = [-1,0,1,2,2,2,1,0,-1,-2,-2,-2]

def solve(x,y,XY):

	xy = XY[:]

	if len(xy) == 0: return True

	sx,sy = xy.pop(0),xy.pop(0)

	for dx,dy in zip(dX,dY):

		if doa(x+dx,y+dy,sx,sy):

			r = solve(x+dx,y+dy,xy)

			if r: return r

def doa(x,y,sx,sy):

	if not (0 <= x <= 9 and 0 <= y <= 9): return False

	return True if abs(x-sx) < 2 and abs(y-sy) < 2 else False

while 1:

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

	if x == y == 0: break

	n = input()

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

	print("OK" if solve(x,y,xy) else "NA")

dX = [2, 2, 2, 1, 0, -1, -2, -2, -2, -1, 0, 1]
dY = [-1, 0, 1, 2, 2, 2, 1, 0, -1, -2, -2, -2]

def solve(x, y, XY):
    xy = XY[:]
    if len(xy) == 0:
        return "OK"
    sx, sy = xy.pop(0), xy.pop(0)
    for dx, dy in zip(dX, dY):
        if doa(x + dx, y + dy, sx, sy):
            r = solve(x + dx, y + dy, xy)
            if r:
                return r

def doa(x, y, sx, sy):
    if not (0 <= x <= 9 and 0 <= y <= 9):
        return False
    return True if abs(x - sx) < 2 and abs(y - sy) < 2 else False

while 1:
    x, y = list(map(int, input().split()))
    if x == y == 0:
        break
    n = input()
    xy = list(map(int, input().split()))
    ans = solve(x, y, xy)
    print(ans if ans else "NA")

dX = [2, 2, 2, 1, 0, -1, -2, -2, -2, -1, 0, 1]
dY = [-1, 0, 1, 2, 2, 2, 1, 0, -1, -2, -2, -2]

def solve(x, y, XY):
    xy = XY[:]
    if len(xy) == 0:
        return True
    sx, sy = xy.pop(0), xy.pop(0)
    for dx, dy in zip(dX, dY):
        if doa(x + dx, y + dy, sx, sy):
            r = solve(x + dx, y + dy, xy)
            if r:
                return r

def doa(x, y, sx, sy):
    if not (0 <= x <= 9 and 0 <= y <= 9):
        return False
    return True if abs(x - sx) < 2 and abs(y - sy) < 2 else False

while 1:
    x, y = list(map(int, input().split()))
    if x == y == 0:
        break
    n = input()
    xy = list(map(int, input().split()))
    print("OK" if solve(x, y, xy) else "NA")

+    print("OK" if solve(x, y, xy) else "NA")


Input:
from collections import deque

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

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

dist_f_k=[0]*n

for a,b,c in zip(t[:3*n-3:3],t[1::3],t[2::3]):

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

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

k=t[3*n-2]

que=deque([k-1])

while que:

	cur=que.popleft()

	for nxt,dd in con[cur]:

		if dist_f_k[nxt]==0 and nxt!=k-1:

			que.append(nxt)

			dist_f_k[nxt]=dist_f_k[cur]+dd

for x,y in zip(t[3*n-1::2],t[3*n::2]):

	print((dist_f_k[x-1]+dist_f_k[y-1]))

def solve():

	from collections import deque

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

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

	dist_f_k=[0]*n

	l1,l2=t[:3*n-3],t[3*n-1:]

	for a,b,c in zip(*[iter(l1)]*3):

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

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

	k=t[3*n-2]

	que=deque([k-1])

	while que:

		cur=que.popleft()

		for nxt,dd in con[cur]:

			if dist_f_k[nxt]==0 and nxt!=k-1:

				que.append(nxt)

				dist_f_k[nxt]=dist_f_k[cur]+dd

	for x,y in zip(*[iter(l2)]*2):

		print((dist_f_k[x-1]+dist_f_k[y-1]))

if __name__=="__main__":

	solve()

from collections import deque

n, *t = list(map(int, open(0).read().split()))
con = [[] for _ in range(n)]
dist_f_k = [0] * n
for a, b, c in zip(t[: 3 * n - 3 : 3], t[1::3], t[2::3]):
    con[a - 1].append((b - 1, c))
    con[b - 1].append((a - 1, c))
k = t[3 * n - 2]
que = deque([k - 1])
while que:
    cur = que.popleft()
    for nxt, dd in con[cur]:
        if dist_f_k[nxt] == 0 and nxt != k - 1:
            que.append(nxt)
            dist_f_k[nxt] = dist_f_k[cur] + dd
for x, y in zip(t[3 * n - 1 :: 2], t[3 * n :: 2]):
    print((dist_f_k[x - 1] + dist_f_k[y - 1]))

def solve():
    from collections import deque

    n, *t = list(map(int, open(0).read().split()))
    con = [[] for _ in range(n)]
    dist_f_k = [0] * n
    l1, l2 = t[: 3 * n - 3], t[3 * n - 1 :]
    for a, b, c in zip(*[iter(l1)] * 3):
        con[a - 1].append((b - 1, c))
        con[b - 1].append((a - 1, c))
    k = t[3 * n - 2]
    que = deque([k - 1])
    while que:
        cur = que.popleft()
        for nxt, dd in con[cur]:
            if dist_f_k[nxt] == 0 and nxt != k - 1:
                que.append(nxt)
                dist_f_k[nxt] = dist_f_k[cur] + dd
    for x, y in zip(*[iter(l2)] * 2):
        print((dist_f_k[x - 1] + dist_f_k[y - 1]))

if __name__ == "__main__":
    solve()

-n, *t = list(map(int, open(0).read().split()))

-        if dist_f_k[nxt] == 0 and nxt != k - 1:

-            dist_f_k[nxt] = dist_f_k[cur] + dd

-    print((dist_f_k[x - 1] + dist_f_k[y - 1]))

+    n, *t = list(map(int, open(0).read().split()))

+    for a, b, c in zip(*[iter(l1)] * 3):

+            if dist_f_k[nxt] == 0 and nxt != k - 1:

+                dist_f_k[nxt] = dist_f_k[cur] + dd

+        print((dist_f_k[x - 1] + dist_f_k[y - 1]))


Input:
n, q = [ int( val ) for val in input( ).split( " " ) ]

ps = [0]*n

t = [0]*n

for i in range( n ):

	ps[i], t[i] = input( ).split( " " )

output = []

qsum = 0

while t:

	psi = ps.pop( 0 )

	ti = int( t.pop( 0 ) )

	if ti <= q:

		qsum += ti

		output.append( psi+" "+str( qsum ) )

	else:

		t.append( ti - q )

		ps.append( psi )

		qsum += q

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

n, q = [ int( val ) for val in input( ).split( " " ) ]

ps = [0]*n

t = [0]*n

for i in range( n ):

    ps[i], t[i] = input( ).split( " " )

output = []

qsum = 0

while t:

    psi = ps.pop( 0 )

    ti = int( t.pop( 0 ) )

    if ti <= q:

        qsum += ti

        output.append( "".join( ( psi, " ", str( qsum ) ) ) )

    else:

        t.append( ti - q )

        ps.append( psi )

        qsum += q

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

n, q = [int(val) for val in input().split(" ")]
ps = [0] * n
t = [0] * n
for i in range(n):
    ps[i], t[i] = input().split(" ")
output = []
qsum = 0
while t:
    psi = ps.pop(0)
    ti = int(t.pop(0))
    if ti <= q:
        qsum += ti
        output.append(psi + " " + str(qsum))
    else:
        t.append(ti - q)
        ps.append(psi)
        qsum += q
print(("\n".join(output)))

n, q = [int(val) for val in input().split(" ")]
ps = [0] * n
t = [0] * n
for i in range(n):
    ps[i], t[i] = input().split(" ")
output = []
qsum = 0
while t:
    psi = ps.pop(0)
    ti = int(t.pop(0))
    if ti <= q:
        qsum += ti
        output.append("".join((psi, " ", str(qsum))))
    else:
        t.append(ti - q)
        ps.append(psi)
        qsum += q
print(("\n".join(output)))

-        output.append(psi + " " + str(qsum))

+        output.append("".join((psi, " ", str(qsum))))


Input:
s=int(input())

p=10**9+7

if s<=2:

    print((0))

    exit()

n=s//3

ans=0

def f(n,k,p):

    if k==0:

        return 1

    elif k%2==0:

        return (f(n,k//2,p)**2)%p

    else:

        return (n*f(n,k-1,p))%p

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

    a=1

    b=1

    for j in range(k-1):

        a=(a*(s-3*k+1+j))%p

        b=(b*(j+1))%p

    ans=(ans+a*f(b,p-2,p))%p

print((ans%p))

s = int(input())
p = 10**9 + 7
if s <= 2:
    print((0))
    exit()
n = s // 3
ans = 0

def f(n, k, p):
    if k == 0:
        return 1
    elif k % 2 == 0:
        return (f(n, k // 2, p) ** 2) % p
    else:
        return (n * f(n, k - 1, p)) % p

for k in range(1, n + 1):
    a = 1
    b = 1
    for j in range(k - 1):
        a = (a * (s - 3 * k + 1 + j)) % p
        b = (b * (j + 1)) % p
    ans = (ans + a * f(b, p - 2, p)) % p
print((ans % p))

-        return (n * f(n, k - 1, p)) % p


Input:
n = int(input())

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

ans = 0

nodes_min = [0] * (n + 1)

nodes_max = [0] * (n + 1)

nodes_min[n] = leaves[n]

nodes_max[n] = leaves[n]

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

    root_min = nodes_min[depth] // 2 + nodes_min[depth] % 2

    nodes_min[depth - 1] = leaves[depth - 1] + root_min

    root_max = nodes_max[depth]

    nodes_max[depth - 1] = leaves[depth - 1] + root_max

nodes = [0] * (n + 1)

nodes[0] = 1

if nodes[0] < nodes_min[0]:

    print((-1))

else:

    for depth in range(n):

        roots = nodes[depth]-leaves[depth]

        nodes[depth + 1] = min(roots * 2, nodes_max[depth + 1])

        if nodes[depth+1] < nodes_min[depth+1]:

            print((-1))

            break

    else:

        print((sum(nodes)))

n = int(input())

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

sum_leaves = [0]*(n+1)

sum_leaves[0] = leaves[0]

for depth in range(n):

    sum_leaves[depth+1] = sum_leaves[depth] + leaves[depth+1]

ans = 0

root = [None] * (n + 1)

if n == 0:

    root[0] = 0

else:

    root[0] = 1

if root[0] + leaves[0] != 1:

    print((-1))

else:

    for depth in range(n):

        root[depth+1] = min(2*root[depth]-leaves[depth+1],

                            sum_leaves[n]-sum_leaves[depth+1])

        if root[depth + 1] < root[depth] - leaves[depth + 1] or root[depth+1] < 0:

            print((-1))

            break

    else:

        print((sum(root)+sum(leaves)))

n = int(input())
leaves = list(map(int, input().split()))
ans = 0
nodes_min = [0] * (n + 1)
nodes_max = [0] * (n + 1)
nodes_min[n] = leaves[n]
nodes_max[n] = leaves[n]
for depth in range(n, 0, -1):
    root_min = nodes_min[depth] // 2 + nodes_min[depth] % 2
    nodes_min[depth - 1] = leaves[depth - 1] + root_min
    root_max = nodes_max[depth]
    nodes_max[depth - 1] = leaves[depth - 1] + root_max
nodes = [0] * (n + 1)
nodes[0] = 1
if nodes[0] < nodes_min[0]:
    print((-1))
else:
    for depth in range(n):
        roots = nodes[depth] - leaves[depth]
        nodes[depth + 1] = min(roots * 2, nodes_max[depth + 1])
        if nodes[depth + 1] < nodes_min[depth + 1]:
            print((-1))
            break
    else:
        print((sum(nodes)))

n = int(input())
leaves = list(map(int, input().split()))
sum_leaves = [0] * (n + 1)
sum_leaves[0] = leaves[0]
for depth in range(n):
    sum_leaves[depth + 1] = sum_leaves[depth] + leaves[depth + 1]
ans = 0
root = [None] * (n + 1)
if n == 0:
    root[0] = 0
else:
    root[0] = 1
if root[0] + leaves[0] != 1:
    print((-1))
else:
    for depth in range(n):
        root[depth + 1] = min(
            2 * root[depth] - leaves[depth + 1], sum_leaves[n] - sum_leaves[depth + 1]
        )
        if root[depth + 1] < root[depth] - leaves[depth + 1] or root[depth + 1] < 0:
            print((-1))
            break
    else:
        print((sum(root) + sum(leaves)))

+    sum_leaves[depth + 1] = sum_leaves[depth] + leaves[depth + 1]

-    root_min = nodes_min[depth] // 2 + nodes_min[depth] % 2

-    nodes_min[depth - 1] = leaves[depth - 1] + root_min

-    nodes_max[depth - 1] = leaves[depth - 1] + root_max

-        roots = nodes[depth] - leaves[depth]

-        nodes[depth + 1] = min(roots * 2, nodes_max[depth + 1])

-        if nodes[depth + 1] < nodes_min[depth + 1]:

+            2 * root[depth] - leaves[depth + 1], sum_leaves[n] - sum_leaves[depth + 1]

+        if root[depth + 1] < root[depth] - leaves[depth + 1] or root[depth + 1] < 0:

+        print((sum(root) + sum(leaves)))


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

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

V = 0

for i in range(N):

  V += L[i][1]

dp = [[10**9+1] * (V + 1) for i in range(N+1)]

dp[0][0] = 0

for i in range(N):

    for j in range(V+1):

        if j - L[i][1] >= 0:

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

        else:

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

ans = 0

for j in range(V+1):

    if  W >= dp[-1][j]:

        ans = max(ans, j)

print(ans)

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

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

V = 0

for i in range(N):

  V += L[i][1]

dp = [10**9+1] * (V + 1)

dp[0] = 0

for i in range(N):

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

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

ans = 0

for j in range(V+1):

    if  W >= dp[j]:

        ans = max(ans, j)

print(ans)

N, W = list(map(int, input().split()))
L = [list(map(int, input().split())) for i in range(N)]
V = 0
for i in range(N):
    V += L[i][1]
dp = [[10**9 + 1] * (V + 1) for i in range(N + 1)]
dp[0][0] = 0
for i in range(N):
    for j in range(V + 1):
        if j - L[i][1] >= 0:
            dp[i + 1][j] = min(dp[i][j], dp[i][j - L[i][1]] + L[i][0])
        else:
            dp[i + 1][j] = dp[i][j]
ans = 0
for j in range(V + 1):
    if W >= dp[-1][j]:
        ans = max(ans, j)
print(ans)

N, W = list(map(int, input().split()))
L = [list(map(int, input().split())) for i in range(N)]
V = 0
for i in range(N):
    V += L[i][1]
dp = [10**9 + 1] * (V + 1)
dp[0] = 0
for i in range(N):
    for j in range(V, -1, -1):
        dp[j] = min(dp[j], dp[j - L[i][1]] + L[i][0])
ans = 0
for j in range(V + 1):
    if W >= dp[j]:
        ans = max(ans, j)
print(ans)


Input:
from collections import Counter

s = input()

mod1 = 673

mod2 = 3

num1 = 0

num2 = 0

li1 = []

li2 = []

pw1 = 10

pw2 = 10

for i, e in enumerate(s, 1):

    num1 *= 10

    num1 += int(e)

    num1 %= mod1

    inv = pow(pw1, mod1 - 2, mod1)

    li1.append(num1 * inv % mod1)

    num2 *= 10

    num2 += int(e)

    num2 %= mod2

    inv = pow(pw2, mod2 - 2, mod2)

    li2.append(num2 * inv % mod2)

    pw1 *= 10

    pw1 %= mod1

    pw2 *= 10

    pw2 %= mod2

li = [0] + [10 * e1 + e2 for e1, e2 in zip(li1, li2)]

c = Counter(li)

ans = 0

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

    ans += v * (v - 1) // 2

print(ans)

from collections import Counter

def f(mod):

    ret = [0]

    power = 1

    num = 0

    for i, e in enumerate(s, 1):

        num *= 10

        num += int(e)

        num %= mod

        power *= 10

        power %= mod

        inv = pow(power, mod - 2, mod)

        ret.append(num * inv % mod)

    return ret

s = input()

mod3 = f(3)

mod673 = f(673)

li = [10 * e673 + e3 for e3, e673 in zip(mod3, mod673)]

c = Counter(li)

ans = 0

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

    ans += v * (v - 1) // 2

print(ans)


Input:
import math

import string

def readints():

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

def nCr(n, r):

    return math.factorial(n)//(math.factorial(n-r)*math.factorial(r))

def has_duplicates2(seq):

    seen = []

    for item in seq:

        if not(item in seen):

            seen.append(item)

    return len(seq) != len(seen)

def divisor(n):

    divisor = []

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

        if n % i == 0:

            divisor.append(i)

    return divisor

# coordinates

dx = [-1, -1, -1, 0, 0, 1, 1, 1]

dy = [-1, 0, 1, -1, 1, -1, 0, 1]

n = int(input())

a = readints()

def func(l):

    if len(l) == n:

        for i in range(len(l)):

            if l[i] % 2 == 0:

                return 1

        return 0

    return func(l+[(a[len(l)])])+func(l+[(a[len(l)]-1)])+func(l+[(a[len(l)]+1)])

print((func([])))

import math

import string

def readints():

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

def nCr(n, r):

    return math.factorial(n)//(math.factorial(n-r)*math.factorial(r))

def has_duplicates2(seq):

    seen = []

    for item in seq:

        if not(item in seen):

            seen.append(item)

    return len(seq) != len(seen)

def divisor(n):

    divisor = []

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

        if n % i == 0:

            divisor.append(i)

    return divisor

# coordinates

dx = [-1, -1, -1, 0, 0, 1, 1, 1]

dy = [-1, 0, 1, -1, 1, -1, 0, 1]

n = int(input())

a = readints()

sum = 1

for i in range(len(a)):

    if a[i] % 2 == 0:

        sum *= 2

    else:

        sum *= 1

print((3**len(a)-sum))

import math
import string

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

def nCr(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def has_duplicates2(seq):
    seen = []
    for item in seq:
        if not (item in seen):
            seen.append(item)
    return len(seq) != len(seen)

def divisor(n):
    divisor = []
    for i in range(1, n + 1):
        if n % i == 0:
            divisor.append(i)
    return divisor

# coordinates
dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
n = int(input())
a = readints()

def func(l):
    if len(l) == n:
        for i in range(len(l)):
            if l[i] % 2 == 0:
                return 1
        return 0
    return (
        func(l + [(a[len(l)])])
        + func(l + [(a[len(l)] - 1)])
        + func(l + [(a[len(l)] + 1)])
    )

print((func([])))

import math
import string

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

def nCr(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def has_duplicates2(seq):
    seen = []
    for item in seq:
        if not (item in seen):
            seen.append(item)
    return len(seq) != len(seen)

def divisor(n):
    divisor = []
    for i in range(1, n + 1):
        if n % i == 0:
            divisor.append(i)
    return divisor

# coordinates
dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
n = int(input())
a = readints()
sum = 1
for i in range(len(a)):
    if a[i] % 2 == 0:
        sum *= 2
    else:
        sum *= 1
print((3 ** len(a) - sum))

-def func(l):
-    if len(l) == n:
-        for i in range(len(l)):
-            if l[i] % 2 == 0:
-                return 1
-        return 0
-    return (
-        func(l + [(a[len(l)])])
-        + func(l + [(a[len(l)] - 1)])
-        + func(l + [(a[len(l)] + 1)])
-    )
-print((func([])))
+sum = 1
+for i in range(len(a)):
+    if a[i] % 2 == 0:
+        sum *= 2
+    else:
+        sum *= 1
+print((3 ** len(a) - sum))


Input:
def main():

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

    def trial_division(n):

        divs = []

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

            if n % i == 0:

                divs.append(i)

                if i != n//i:

                    divs.append(n//i)

        divs.sort(reverse=True)

        return divs

    divs = trial_division(M)

    for d in divs:

        if d*N <= M:

            return print(d)

if __name__ == '__main__':

    main()

def main():

    def trial_division(n):

        divs = []

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

            if n % i == 0:

                divs.append(i)

                if i != n//i:

                    divs.append(n//i)

        divs.sort(reverse=True)

        return divs

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

    divs = trial_division(M)

    for d in divs:

        if N*d <= M:

            return print(d)

if __name__ == '__main__':

    main()

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

    def trial_division(n):
        divs = []
        for i in range(1, int(n**0.5) + 1):
            if n % i == 0:
                divs.append(i)
                if i != n // i:
                    divs.append(n // i)
        divs.sort(reverse=True)
        return divs

    divs = trial_division(M)
    for d in divs:
        if d * N <= M:
            return print(d)

if __name__ == "__main__":
    main()

def main():
    def trial_division(n):
        divs = []
        for i in range(1, int(n**0.5) + 1):
            if n % i == 0:
                divs.append(i)
                if i != n // i:
                    divs.append(n // i)
        divs.sort(reverse=True)
        return divs

    N, M = (int(i) for i in input().split())
    divs = trial_division(M)
    for d in divs:
        if N * d <= M:
            return print(d)

if __name__ == "__main__":
    main()

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

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


Input:
import sys

input = sys.stdin.readline

import bisect

n = int(input())

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

l = int(input())

U = 17

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

for i, x in enumerate(X):

  t = bisect.bisect_left(X, x+l)

  dp[0][i] = bisect.bisect_right(X, x+l) - 1

for k in range(U):

  for i in range(n):

    dp[k+1][i] = dp[k][dp[k][i]]

def test(x, a, b):

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

    if x >> i & 1:

      a = dp[i][a]

  return a >= b

def solve(a, b):

  if a > b:

    a, b = b, a

  ng = 0

  ok = n-1

  while ok - ng > 1:

    mid = (ng + ok) // 2

    if test(mid, a, b):

      ok = mid

    else:

      ng = mid

  print(ok)

q = int(input())

for _ in range(q):

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

  a -= 1

  b -= 1

  solve(a, b)

import sys

input = sys.stdin.readline

import bisect

n = int(input())

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

l = int(input())

U = 17

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

for i, x in enumerate(X):

  t = bisect.bisect_left(X, x+l)

  dp[0][i] = bisect.bisect_right(X, x+l) - 1

for k in range(U):

  for i in range(n):

    dp[k+1][i] = dp[k][dp[k][i]]

q = int(input())

for _ in range(q):

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

  a -= 1

  b -= 1

  if a > b:

    a, b = b, a

  res = 1

  for k in range(U, -1, -1):

    if dp[k][a] < b:

      a = dp[k][a]

      res += (1<<k)

    if a == b:

      break

  print(res)

import sys

input = sys.stdin.readline
import bisect

n = int(input())
X = list(map(int, input().split()))
l = int(input())
U = 17
dp = [[0] * n for _ in range(U + 1)]
for i, x in enumerate(X):
    t = bisect.bisect_left(X, x + l)
    dp[0][i] = bisect.bisect_right(X, x + l) - 1
for k in range(U):
    for i in range(n):
        dp[k + 1][i] = dp[k][dp[k][i]]

def test(x, a, b):
    for i in range(U, -1, -1):
        if x >> i & 1:
            a = dp[i][a]
    return a >= b

def solve(a, b):
    if a > b:
        a, b = b, a
    ng = 0
    ok = n - 1
    while ok - ng > 1:
        mid = (ng + ok) // 2
        if test(mid, a, b):
            ok = mid
        else:
            ng = mid
    print(ok)

q = int(input())
for _ in range(q):
    a, b = list(map(int, input().split()))
    a -= 1
    b -= 1
    solve(a, b)

import sys

input = sys.stdin.readline
import bisect

n = int(input())
X = list(map(int, input().split()))
l = int(input())
U = 17
dp = [[0] * n for _ in range(U + 1)]
for i, x in enumerate(X):
    t = bisect.bisect_left(X, x + l)
    dp[0][i] = bisect.bisect_right(X, x + l) - 1
for k in range(U):
    for i in range(n):
        dp[k + 1][i] = dp[k][dp[k][i]]
q = int(input())
for _ in range(q):
    a, b = list(map(int, input().split()))
    a -= 1
    b -= 1
    if a > b:
        a, b = b, a
    res = 1
    for k in range(U, -1, -1):
        if dp[k][a] < b:
            a = dp[k][a]
            res += 1 << k
        if a == b:
            break
    print(res)

-def test(x, a, b):
-    for i in range(U, -1, -1):
-        if x >> i & 1:
-            a = dp[i][a]
-    return a >= b
-def solve(a, b):
-    if a > b:
-        a, b = b, a
-    ng = 0
-    ok = n - 1
-    while ok - ng > 1:
-        mid = (ng + ok) // 2
-        if test(mid, a, b):
-            ok = mid
-        else:
-            ng = mid
-    print(ok)
-    solve(a, b)
+    if a > b:
+        a, b = b, a
+    res = 1
+    for k in range(U, -1, -1):
+        if dp[k][a] < b:
+            a = dp[k][a]
+            res += 1 << k
+        if a == b:
+            break
+    print(res)


Input:
def main():

    S = input()

    w1 = 'dream'[::-1]

    w2 = 'dreamer'[::-1]

    w3 = 'erase'[::-1]

    w4 = 'eraser'[::-1]

    # print(w1,w2,w3,w4)

    S = S[::-1]

    # print(S)

    # words = ['dream', 'dreamer', 'erase', 'eraser']

    words = [w1, w2, w3, w4]

    T = ''

    while S != T:

        cand = []

        for w in words:

            new_t = T + w

            cand.append(new_t)

        # print('cand', cand)

        ans = False

        for c in cand:

            if c == S[:len(c)]:

                T = c

                ans = True

        if not ans:

            break

    if S == T:

        print('YES')

    else:

        print("NO")

if __name__ == "__main__":

    main()

def main():

    S = input()

    w1 = 'dream'[::-1]

    w2 = 'dreamer'[::-1]

    w3 = 'erase'[::-1]

    w4 = 'eraser'[::-1]

    S = S[::-1]

    words = [w1, w2, w3, w4]

    flag = False

    i = 0

    while i < len(S):

        for w in words:

            if S[i:].startswith(w):

                i += len(w)

                flag = True

                break

        if not flag:

            print("NO")

            exit()

        flag = False

    print("YES")

if __name__ == "__main__":

    main()

def main():
    S = input()
    w1 = "dream"[::-1]
    w2 = "dreamer"[::-1]
    w3 = "erase"[::-1]
    w4 = "eraser"[::-1]
    # print(w1,w2,w3,w4)
    S = S[::-1]
    # print(S)
    # words = ['dream', 'dreamer', 'erase', 'eraser']
    words = [w1, w2, w3, w4]
    T = ""
    while S != T:
        cand = []
        for w in words:
            new_t = T + w
            cand.append(new_t)
        # print('cand', cand)
        ans = False
        for c in cand:
            if c == S[: len(c)]:
                T = c
                ans = True
        if not ans:
            break
    if S == T:
        print("YES")
    else:
        print("NO")

if __name__ == "__main__":
    main()

def main():
    S = input()
    w1 = "dream"[::-1]
    w2 = "dreamer"[::-1]
    w3 = "erase"[::-1]
    w4 = "eraser"[::-1]
    S = S[::-1]
    words = [w1, w2, w3, w4]
    flag = False
    i = 0
    while i < len(S):
        for w in words:
            if S[i:].startswith(w):
                i += len(w)
                flag = True
                break
        if not flag:
            print("NO")
            exit()
        flag = False
    print("YES")

if __name__ == "__main__":
    main()

-    # words = ['dream', 'dreamer', 'erase', 'eraser']


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

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

INF = 10**9

dp = [[INF for j in range(401)] for i in range(401)]

dp[0][0] = 0

maxa = maxb = 0

for a,b,c in src:

    for ai in range(maxa,-1,-1):

        for bi in range(maxb,-1,-1):

            dp[ai+a][bi+b] = min(dp[ai+a][bi+b], dp[ai][bi] + c)

    maxa += a

    maxb += b

ans = INF

for i in range(1,401):

    if MA*i > 400 or MB*i > 400: break

    ans = min(ans, dp[MA*i][MB*i])

print((-1 if ans == INF else ans))

N,MA,MB = list(map(int,input().split()))

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

INF = 10**9

MAX = 401

dp = [[INF] * MAX for i in range(MAX)]

dp[0][0] = 0

amax = bmax = 0

for a,b,n in src:

    for i in reversed(list(range(bmax+1))):

        for j in range(amax+1):

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

            dp[i+b][j+a] = min(dp[i+b][j+a], dp[i][j] + n)

    amax += a

    bmax += b

ans = INF

for i in range(1,MAX):

    if i*MA >= MAX or i*MB >= MAX: break

    ans = min(ans, dp[i*MB][i*MA])

print((-1 if ans == INF else ans))

N, MA, MB = list(map(int, input().split()))
src = [tuple(map(int, input().split())) for i in range(N)]
INF = 10**9
dp = [[INF for j in range(401)] for i in range(401)]
dp[0][0] = 0
maxa = maxb = 0
for a, b, c in src:
    for ai in range(maxa, -1, -1):
        for bi in range(maxb, -1, -1):
            dp[ai + a][bi + b] = min(dp[ai + a][bi + b], dp[ai][bi] + c)
    maxa += a
    maxb += b
ans = INF
for i in range(1, 401):
    if MA * i > 400 or MB * i > 400:
        break
    ans = min(ans, dp[MA * i][MB * i])
print((-1 if ans == INF else ans))

N, MA, MB = list(map(int, input().split()))
src = [tuple(map(int, input().split())) for i in range(N)]
INF = 10**9
MAX = 401
dp = [[INF] * MAX for i in range(MAX)]
dp[0][0] = 0
amax = bmax = 0
for a, b, n in src:
    for i in reversed(list(range(bmax + 1))):
        for j in range(amax + 1):
            if dp[i][j] == INF:
                continue
            dp[i + b][j + a] = min(dp[i + b][j + a], dp[i][j] + n)
    amax += a
    bmax += b
ans = INF
for i in range(1, MAX):
    if i * MA >= MAX or i * MB >= MAX:
        break
    ans = min(ans, dp[i * MB][i * MA])
print((-1 if ans == INF else ans))

-dp = [[INF for j in range(401)] for i in range(401)]

-            dp[ai + a][bi + b] = min(dp[ai + a][bi + b], dp[ai][bi] + c)

+    for i in reversed(list(range(bmax + 1))):


Input:
import sys

input = sys.stdin.readline

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

hole = [0] * (N+1)

for i in range(M):

    hole[int(input())] = 1

if N == 1:

    print((1))

    exit()

if N == 2:

    if hole[1] == 1:

        print((1))

        exit()

    if hole[1] == 0:

        print((2))

        exit()

flg_one = False

flg_two = False

first = 1

second = 2

if hole[1] == 1:

    first = 0

    second = 1

    flg_one = True

if hole[2] == 1:

    first = 1

    second = 0

    flg_two = True

if flg_one and flg_two:

    print((0))

    exit()

for i in range(3,N):

    if hole[i] == 1:

        first = second

        second = 0

        continue

    tmp = first + second

    tmp %= 1000000007

    first = second

    second = tmp

tmp = first + second

tmp %= 1000000007

print(tmp)

MOD = 10**9 + 7

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

stairs = [0]*(N+1)

for _ in range(M):

    stairs[int(input())] = 1

if N == 1:

    print((1))

    exit()

ans = [0]*(N+1)

ans[1] = 1 if stairs[1] == 0 else 0

ans[2] = 1 + ans[1] if stairs[2] == 0 else 0

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

    if stairs[i] == 1:

        ans[i] = 0

        continue

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

print((ans[N]))

import sys

input = sys.stdin.readline
N, M = list(map(int, input().split()))
hole = [0] * (N + 1)
for i in range(M):
    hole[int(input())] = 1
if N == 1:
    print((1))
    exit()
if N == 2:
    if hole[1] == 1:
        print((1))
        exit()
    if hole[1] == 0:
        print((2))
        exit()
flg_one = False
flg_two = False
first = 1
second = 2
if hole[1] == 1:
    first = 0
    second = 1
    flg_one = True
if hole[2] == 1:
    first = 1
    second = 0
    flg_two = True
if flg_one and flg_two:
    print((0))
    exit()
for i in range(3, N):
    if hole[i] == 1:
        first = second
        second = 0
        continue
    tmp = first + second
    tmp %= 1000000007
    first = second
    second = tmp
tmp = first + second
tmp %= 1000000007
print(tmp)

MOD = 10**9 + 7
N, M = list(map(int, input().split()))
stairs = [0] * (N + 1)
for _ in range(M):
    stairs[int(input())] = 1
if N == 1:
    print((1))
    exit()
ans = [0] * (N + 1)
ans[1] = 1 if stairs[1] == 0 else 0
ans[2] = 1 + ans[1] if stairs[2] == 0 else 0
for i in range(3, N + 1):
    if stairs[i] == 1:
        ans[i] = 0
        continue
    ans[i] = (ans[i - 1] + ans[i - 2]) % MOD
print((ans[N]))

+ans[2] = 1 + ans[1] if stairs[2] == 0 else 0


Input:
# coding: utf-8

def solve(*args: str) -> str:

    k = int(args[0])

    l = 9*(k//7 if k % 7 == 0 else k)

    if l % 2 == 0 or l % 5 == 0:

        return '-1'

    r = phi = l

    for i in range(2, int(-pow(l, 1/2))):

        if r % i == 0:

            phi = phi//i*(i-1)

            while r % i:

                r //= i

    a = 10 % l

    ret = 1

    while(a != 1):

        a = a*10 % l

        ret += 1

        if phi < ret:

            ret = -1

            break

    return str(ret)

if __name__ == "__main__":

    print((solve(*(open(0).read().splitlines()))))

# coding: utf-8

from math import sqrt

def solve(*args: str) -> str:

    k = int(args[0])

    l = 9*(k//7 if 0 == k % 7 else k)

    if 0 == l % 2 or 0 == l % 5:

        return '-1'

    r = phi = l

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

        if 0 == r % i:

            phi = phi*(i-1)//i

            while 0 == r % i:

                r //= i

    if 1 < r:

        phi = phi*(r-1)//r

    D = set()

    for d in range(1, int(sqrt(phi)+1)):

        if 0 == phi % d:

            D.add(d)

            D.add(phi//d)

    ret = -1

    for m in sorted(D):

        if 1 == pow(10, m, l):

            ret = m

            break

    return str(ret)

if __name__ == "__main__":

    print((solve(*(open(0).read().splitlines()))))

# coding: utf-8
def solve(*args: str) -> str:
    k = int(args[0])
    l = 9 * (k // 7 if k % 7 == 0 else k)
    if l % 2 == 0 or l % 5 == 0:
        return "-1"
    r = phi = l
    for i in range(2, int(-pow(l, 1 / 2))):
        if r % i == 0:
            phi = phi // i * (i - 1)
            while r % i:
                r //= i
    a = 10 % l
    ret = 1
    while a != 1:
        a = a * 10 % l
        ret += 1
        if phi < ret:
            ret = -1
            break
    return str(ret)

if __name__ == "__main__":
    print((solve(*(open(0).read().splitlines()))))

# coding: utf-8
from math import sqrt

def solve(*args: str) -> str:
    k = int(args[0])
    l = 9 * (k // 7 if 0 == k % 7 else k)
    if 0 == l % 2 or 0 == l % 5:
        return "-1"
    r = phi = l
    for i in range(2, int(sqrt(l) + 1)):
        if 0 == r % i:
            phi = phi * (i - 1) // i
            while 0 == r % i:
                r //= i
    if 1 < r:
        phi = phi * (r - 1) // r
    D = set()
    for d in range(1, int(sqrt(phi) + 1)):
        if 0 == phi % d:
            D.add(d)
            D.add(phi // d)
    ret = -1
    for m in sorted(D):
        if 1 == pow(10, m, l):
            ret = m
            break
    return str(ret)

if __name__ == "__main__":
    print((solve(*(open(0).read().splitlines()))))

-    for i in range(2, int(-pow(l, 1 / 2))):

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

+    for d in range(1, int(sqrt(phi) + 1)):


Input:
import sys

sys.setrecursionlimit(100000)

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

fib={0:0,1:1,2:1}

for i in range(3,100003):

    fib[i]=fib[i-1]+fib[i-2]

  #  fib.append(fib[i-1]+fib[i-2])

n,m=intinput()

mod=10**9+7

a=[int(sys.stdin.readline()) for _ in range(m)]

if m!=0:

    l=[a[0]]

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

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

    l.append(n-a[-1])

    k=1

    for i in l:

        k=fib[i]*k%mod

    print((k%mod))

else:

    print((fib[n+1]%mod))

import sys

sys.setrecursionlimit(100000)

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

n, m = intinput()

a = {int(sys.stdin.readline()) for _ in range(m)}

memo = [0 for x in range(n + 4)]

memo[0] = 1

mod = 10 ** 9 + 7

for i in range(n):

    if i + 1 not in a:

        memo[i + 1] = (memo[i + 1] + memo[i]) % mod

    if i + 2 not in a:

        memo[i + 2] = (memo[i + 2] + memo[i]) % mod

print((memo[n]))

import sys

sys.setrecursionlimit(100000)

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

fib = {0: 0, 1: 1, 2: 1}
for i in range(3, 100003):
    fib[i] = fib[i - 1] + fib[i - 2]
#  fib.append(fib[i-1]+fib[i-2])
n, m = intinput()
mod = 10**9 + 7
a = [int(sys.stdin.readline()) for _ in range(m)]
if m != 0:
    l = [a[0]]
    for i in range(len(a) - 1):
        l.append(a[i + 1] - a[i] - 1)
    l.append(n - a[-1])
    k = 1
    for i in l:
        k = fib[i] * k % mod
    print((k % mod))
else:
    print((fib[n + 1] % mod))

import sys

sys.setrecursionlimit(100000)

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

n, m = intinput()
a = {int(sys.stdin.readline()) for _ in range(m)}
memo = [0 for x in range(n + 4)]
memo[0] = 1
mod = 10**9 + 7
for i in range(n):
    if i + 1 not in a:
        memo[i + 1] = (memo[i + 1] + memo[i]) % mod
    if i + 2 not in a:
        memo[i + 2] = (memo[i + 2] + memo[i]) % mod
print((memo[n]))

+a = {int(sys.stdin.readline()) for _ in range(m)}

-a = [int(sys.stdin.readline()) for _ in range(m)]

+        memo[i + 1] = (memo[i + 1] + memo[i]) % mod

+        memo[i + 2] = (memo[i + 2] + memo[i]) % mod


Input:
"""

challenge case

in:

3

1 3

2 3

out:

1

1

1

"""

from collections import deque

def main():

	N, *AB = list(map(int, open(0).read().split()))

	B = AB[1::2]

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

	for a, b in zip(*[iter(AB)] * 2):

		E[a] += b,

	Q = deque([1])

	C = [0] * (N + 1)

	while Q:

		v = Q.popleft()

		c = 0

		for u in E[v]:

			c += 1 + (c + 1 == C[v])

			C[u] = c

			Q += u,

	print((max(C)))

	for b in B:

		print((C[b]))

main()

"""

challenge case

in:

3

1 3

2 3

out:

1

1

1

"""

from collections import deque

def main():

	N, *AB = list(map(int, open(0).read().split()))

	B = AB[1::2]

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

	for a, b in zip(*[iter(AB)] * 2):

		E[a].append(b)

	Q = deque([1])

	C = [0] * (N + 1)

	while Q:

		v = Q.popleft()

		c = 0

		for u in E[v]:

			c += 1 + (c + 1 == C[v])

			C[u] = c

			Q.append(u)

	print((max(C)))

	for b in B:

		print((C[b]))

main()

"""
challenge case
in:
3
1 3
2 3
out:
1
1
1
"""
from collections import deque

def main():
    N, *AB = list(map(int, open(0).read().split()))
    B = AB[1::2]
    E = [[] for _ in range(N + 1)]
    for a, b in zip(*[iter(AB)] * 2):
        E[a] += (b,)
    Q = deque([1])
    C = [0] * (N + 1)
    while Q:
        v = Q.popleft()
        c = 0
        for u in E[v]:
            c += 1 + (c + 1 == C[v])
            C[u] = c
            Q += (u,)
    print((max(C)))
    for b in B:
        print((C[b]))

main()


Input:
from functools import reduce
def f(a,b): return [Card[a][0], Card[b][1]]

n = int(input())

Card = [[] for _ in [0]*n]

Cost = {}

for i in range(n):

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

  Cost[(i, i)] = 0

for i in range(1, n):

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

    a = j+i

    Cost[(j, a)] = min([reduce(lambda a,b: a*b, f(j, k) + f(k+1, a)) + Cost[(j, k)] + Cost[(k+1, a)] for k in range(j, j+i)])

print(Cost[0, n-1])

from functools import reduce
n = int(input())

Card = [[] for _ in [0]*n]

Cost = {}

for i in range(n):

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

  Cost[(i, i)] = 0

for i in range(1, n):

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

    a = j+i

    Cost[(j, a)] = min([reduce(lambda a,b: a*b, [Card[j][0],Card[k][1],Card[k+1][0],Card[a][1]]) + Cost[(j, k)] + Cost[(k+1, a)] for k in range(j, j+i)])

print(Cost[0, n-1])

from functools import reduce

def f(a, b):
    return [Card[a][0], Card[b][1]]

n = int(input())
Card = [[] for _ in [0] * n]
Cost = {}
for i in range(n):
    Card[i] = list(map(int, input().split()))
    Cost[(i, i)] = 0
for i in range(1, n):
    for j in range(0, n - i):
        a = j + i
        Cost[(j, a)] = min(
            [
                reduce(lambda a, b: a * b, f(j, k) + f(k + 1, a))
                + Cost[(j, k)]
                + Cost[(k + 1, a)]
                for k in range(j, j + i)
            ]
        )
print(Cost[0, n - 1])

from functools import reduce

n = int(input())
Card = [[] for _ in [0] * n]
Cost = {}
for i in range(n):
    Card[i] = list(map(int, input().split()))
    Cost[(i, i)] = 0
for i in range(1, n):
    for j in range(0, n - i):
        a = j + i
        Cost[(j, a)] = min(
            [
                reduce(
                    lambda a, b: a * b,
                    [Card[j][0], Card[k][1], Card[k + 1][0], Card[a][1]],
                )
                + Cost[(j, k)]
                + Cost[(k + 1, a)]
                for k in range(j, j + i)
            ]
        )
print(Cost[0, n - 1])

-                reduce(lambda a, b: a * b, f(j, k) + f(k + 1, a))

+                    lambda a, b: a * b,


Input:
import sys

sys.setrecursionlimit(1000000)

S = input()

T = ['dream', 'dreamer', 'erase', 'eraser']

lenT = [len(i) for i in T]

def dayDream(pin):

    global isDream               #;print('dayDream: ', pin, S[pin:])

    for i, d in enumerate(T):

        #print('d:', d)

        if S[pin:pin+lenT[i]] == d:

            pout = pin + lenT[i] #; print(d, pout)

            if pout == len(S):

                isDream = True   #; print('YES')

                return

            else:

                dayDream(pout)

    #print('dayDream return', pin)

    return

isDream = False

dayDream(0)

if isDream:

    print('YES')

else:

    print('NO')

import sys

sys.setrecursionlimit(1000000)

S = input()

T = ['dream', 'dreamer', 'erase', 'eraser']

lenT = [len(i) for i in T]

def dayDream(pin):

    global isGoal               #;print('dayDream: ', pin, S[pin:])

    for i, d in enumerate(T):

        if isGoal:

            return

        #print('i, d:', i, d)

        if S[pin:pin+lenT[i]] == d:

            pout = pin + lenT[i] #;print(d, pout)

            if pout == len(S):

                isGoal = True    #;print('YES')

                return

            else:

                dayDream(pout)

    #print('dayDream return', pin)

    return

isGoal = False

dayDream(0)

if isGoal:

    print('YES')

else:

    print('NO')

import sys

sys.setrecursionlimit(1000000)
S = input()
T = ["dream", "dreamer", "erase", "eraser"]
lenT = [len(i) for i in T]

def dayDream(pin):
    global isDream  # ;print('dayDream: ', pin, S[pin:])
    for i, d in enumerate(T):
        # print('d:', d)
        if S[pin : pin + lenT[i]] == d:
            pout = pin + lenT[i]  # ; print(d, pout)
            if pout == len(S):
                isDream = True  # ; print('YES')
                return
            else:
                dayDream(pout)
    # print('dayDream return', pin)
    return

isDream = False
dayDream(0)
if isDream:
    print("YES")
else:
    print("NO")

import sys

sys.setrecursionlimit(1000000)
S = input()
T = ["dream", "dreamer", "erase", "eraser"]
lenT = [len(i) for i in T]

def dayDream(pin):
    global isGoal  # ;print('dayDream: ', pin, S[pin:])
    for i, d in enumerate(T):
        if isGoal:
            return
        # print('i, d:', i, d)
        if S[pin : pin + lenT[i]] == d:
            pout = pin + lenT[i]  # ;print(d, pout)
            if pout == len(S):
                isGoal = True  # ;print('YES')
                return
            else:
                dayDream(pout)
    # print('dayDream return', pin)
    return

isGoal = False
dayDream(0)
if isGoal:
    print("YES")
else:
    print("NO")

-    global isDream  # ;print('dayDream: ', pin, S[pin:])

+    global isGoal  # ;print('dayDream: ', pin, S[pin:])

-            pout = pin + lenT[i]  # ; print(d, pout)

+            pout = pin + lenT[i]  # ;print(d, pout)

-                isDream = True  # ; print('YES')

+                isGoal = True  # ;print('YES')


Input:
import copy

n=int(input())

org_set=set([i for i in range(1,10**5)])

edges=[]

relations={}

nodes=[]

for i in range(n-1):

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

    edges.append([a,b])

    relations.setdefault(a,[]).append(b)

    nodes.append([])

nodes.append([])

nodes.append([])

max_color=0

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

    targets=relations.get(start,[])

    color=1

    for target in targets:

        if color in nodes[start]:

            color+=1

        else:

            pass

        nodes[target].append(color)

        if color>=max_color:

            max_color=color

        color+=1

print(max_color)

for edge in edges:

    print((nodes[edge[1]][0]))

n=int(input())

edges=[]

relations={}

nodes=[0,0]

for i in range(n-1):

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

    edges.append([a,b])

    relations.setdefault(a,[]).append(b)

    nodes.append(0)

max_color=0

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

    targets=relations.get(start,[])

    color=1

    for target in targets:

        if color == nodes[start]:

            color+=1

        else:

            pass

        nodes[target]=color

        if color>=max_color:

            max_color=color

        color+=1

print(max_color)

for edge in edges:

    print((nodes[edge[1]]))

import copy

n = int(input())
org_set = set([i for i in range(1, 10**5)])
edges = []
relations = {}
nodes = []
for i in range(n - 1):
    a, b = list(map(int, input().split(" ")))
    edges.append([a, b])
    relations.setdefault(a, []).append(b)
    nodes.append([])
nodes.append([])
nodes.append([])
max_color = 0
for start in range(1, n + 1):
    targets = relations.get(start, [])
    color = 1
    for target in targets:
        if color in nodes[start]:
            color += 1
        else:
            pass
        nodes[target].append(color)
        if color >= max_color:
            max_color = color
        color += 1
print(max_color)
for edge in edges:
    print((nodes[edge[1]][0]))

n = int(input())
edges = []
relations = {}
nodes = [0, 0]
for i in range(n - 1):
    a, b = list(map(int, input().split(" ")))
    edges.append([a, b])
    relations.setdefault(a, []).append(b)
    nodes.append(0)
max_color = 0
for start in range(1, n + 1):
    targets = relations.get(start, [])
    color = 1
    for target in targets:
        if color == nodes[start]:
            color += 1
        else:
            pass
        nodes[target] = color
        if color >= max_color:
            max_color = color
        color += 1
print(max_color)
for edge in edges:
    print((nodes[edge[1]]))

-org_set = set([i for i in range(1, 10**5)])


Input:
import sys

import os

import math

ii = lambda: int(sys.stdin.buffer.readline().rstrip())

il = lambda: list(map(int, sys.stdin.buffer.readline().split()))

iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()

isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

def main():

    if os.getenv("LOCAL"):

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

    N = ii()

    ret = float('inf')

    I = int(math.sqrt(N)) * 10

    for i in range(1, I):

        if N%i == 0:

            j = N//i

            ret = min(ret, j + i - 2)

    print(ret)

if __name__ == '__main__':

    main()

import sys

import os

ii = lambda: int(sys.stdin.buffer.readline().rstrip())

il = lambda: list(map(int, sys.stdin.buffer.readline().split()))

iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()

isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

def main():

    if os.getenv("LOCAL"):

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

    N = ii()

    m = int(N ** .5)

    while N % m != 0:

        m -= 1

    else:

        print((int(N / m + m - 2)))

if __name__ == '__main__':

    main()

import sys
import os
import math

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]
iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")
    N = ii()
    ret = float("inf")
    I = int(math.sqrt(N)) * 10
    for i in range(1, I):
        if N % i == 0:
            j = N // i
            ret = min(ret, j + i - 2)
    print(ret)

if __name__ == "__main__":
    main()

import sys
import os

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]
iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")
    N = ii()
    m = int(N**0.5)
    while N % m != 0:
        m -= 1
    else:
        print((int(N / m + m - 2)))

if __name__ == "__main__":
    main()

-import math
-    ret = float("inf")
-    I = int(math.sqrt(N)) * 10
-    for i in range(1, I):
-        if N % i == 0:
-            j = N // i
-            ret = min(ret, j + i - 2)
-    print(ret)
+    m = int(N**0.5)
+    while N % m != 0:
+        m -= 1
+    else:
+        print((int(N / m + m - 2)))