Input:
import sys

sys.setrecursionlimit(10**4)

N=int(eval(input()))

S=eval(input())

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

for i in range(N-1):

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

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

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

depth=[0]*N

num=[0]*N

sd=[0]*N

def dfs(v,pv):

    res=depth[v]*(S[v]=="1")

    n=int(S[v])

    for nv in edge[v]:

        if nv!=pv:

            depth[nv]=depth[v]+1

            dfs(nv,v)

            res+=sd[nv]

            n+=num[nv]

    sd[v]=res

    num[v]=n

def dfs2(v,pv):

    hosei=depth[v]

    S=sd[v]-num[v]*hosei

    if S%2==0:

        check=0

        node=-1

        for nv in edge[v]:

            if nv!=pv:

                if sd[nv]-num[nv]*hosei>S//2:

                    check=sd[nv]-num[nv]*hosei

                    node=nv

        if not check:

            return S//2

        else:

            minus=dfs2(node,v)

            if check-2*minus<=S-check:

                return S//2

            else:

                return S-check+minus

    else:

        check=0

        node=-1

        k=S//2

        for nv in edge[v]:

            if nv!=pv:

                if sd[nv]-num[nv]*hosei>k+1:

                    check=sd[nv]-num[nv]*hosei

                    node=nv

        if not check:

            return k

        else:

            minus=dfs2(node,v)

            if check-2*minus<=S-check:

                return k

            else:

                return S-check+minus

ans=10**18

for i in range(N):

    depth[i]=0

    dfs(i,-1)

    #print(i,depth)

    test=dfs2(i,-1)

    if test*2==sd[i]:

        ans=min(ans,test)

if ans==10**18:

    print((-1))

else:

    print(ans)

from collections import deque

N=int(eval(input()))

S=eval(input())

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

for i in range(N-1):

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

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

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

depth=[0]*N

num=[0]*N

sd=[0]*N

a=10**18

for i in range(N):

    depth=[0]*N

    num=[0]*N

    sd=[0]*N

    parent=[-1]*N

    que=deque([(i,-1)])

    ans=[i]

    while que:

        v,pv=que.popleft()

        for nv in edge[v]:

            if nv!=pv:

                depth[nv]=depth[v]+1

                parent[nv]=v

                que.append((nv,v))

                ans.append(nv)

    ans=ans[::-1]

    #print(depth)

    for v in ans:

        res=depth[v]*(S[v]=="1")

        n=int(S[v])

        for nv in edge[v]:

            if nv!=parent[v]:

                res+=sd[nv]

                n+=num[nv]

        sd[v],num[v]=res,n

    res=[0]*N

    for v in ans:

        hosei=depth[v]

        s=sd[v]-num[v]*hosei

        if s%2==0:

            check=0

            node=-1

            for nv in edge[v]:

                if nv!=parent[v]:

                    if sd[nv]-num[nv]*hosei>s//2:

                        check=sd[nv]-num[nv]*hosei

                        node=nv

            if not check:

                res[v]=s//2

            else:

                minus=res[node]

                if check-2*minus<=s-check:

                    res[v]=s//2

                else:

                    res[v]=s-check+minus

        else:

            check=0

            node=-1

            k=s//2

            for nv in edge[v]:

                if nv!=parent[v]:

                    if sd[nv]-num[nv]*hosei>k+1:

                        check=sd[nv]-num[nv]*hosei

                        node=nv

            if not check:

                res[v]=k

            else:

                minus=res[node]

                if check-2*minus<=s-check:

                    res[v]=k

                else:

                    res[v]=s-check+minus

    test=res[i]

    #print(i,test,sd[i],sd)

    if 2*test==sd[i]:

        a=min(a,test)

if a==10**18:

    print((-1))

else:

    print(a)

import sys

sys.setrecursionlimit(10**4)
N = int(eval(input()))
S = eval(input())
edge = [[] for i in range(N)]
for i in range(N - 1):
    a, b = list(map(int, input().split()))
    edge[a - 1].append(b - 1)
    edge[b - 1].append(a - 1)
depth = [0] * N
num = [0] * N
sd = [0] * N

def dfs(v, pv):
    res = depth[v] * (S[v] == "1")
    n = int(S[v])
    for nv in edge[v]:
        if nv != pv:
            depth[nv] = depth[v] + 1
            dfs(nv, v)
            res += sd[nv]
            n += num[nv]
    sd[v] = res
    num[v] = n

def dfs2(v, pv):
    hosei = depth[v]
    S = sd[v] - num[v] * hosei
    if S % 2 == 0:
        check = 0
        node = -1
        for nv in edge[v]:
            if nv != pv:
                if sd[nv] - num[nv] * hosei > S // 2:
                    check = sd[nv] - num[nv] * hosei
                    node = nv
        if not check:
            return S // 2
        else:
            minus = dfs2(node, v)
            if check - 2 * minus <= S - check:
                return S // 2
            else:
                return S - check + minus
    else:
        check = 0
        node = -1
        k = S // 2
        for nv in edge[v]:
            if nv != pv:
                if sd[nv] - num[nv] * hosei > k + 1:
                    check = sd[nv] - num[nv] * hosei
                    node = nv
        if not check:
            return k
        else:
            minus = dfs2(node, v)
            if check - 2 * minus <= S - check:
                return k
            else:
                return S - check + minus

ans = 10**18
for i in range(N):
    depth[i] = 0
    dfs(i, -1)
    # print(i,depth)
    test = dfs2(i, -1)
    if test * 2 == sd[i]:
        ans = min(ans, test)
if ans == 10**18:
    print((-1))
else:
    print(ans)

from collections import deque

N = int(eval(input()))
S = eval(input())
edge = [[] for i in range(N)]
for i in range(N - 1):
    a, b = list(map(int, input().split()))
    edge[a - 1].append(b - 1)
    edge[b - 1].append(a - 1)
depth = [0] * N
num = [0] * N
sd = [0] * N
a = 10**18
for i in range(N):
    depth = [0] * N
    num = [0] * N
    sd = [0] * N
    parent = [-1] * N
    que = deque([(i, -1)])
    ans = [i]
    while que:
        v, pv = que.popleft()
        for nv in edge[v]:
            if nv != pv:
                depth[nv] = depth[v] + 1
                parent[nv] = v
                que.append((nv, v))
                ans.append(nv)
    ans = ans[::-1]
    # print(depth)
    for v in ans:
        res = depth[v] * (S[v] == "1")
        n = int(S[v])
        for nv in edge[v]:
            if nv != parent[v]:
                res += sd[nv]
                n += num[nv]
        sd[v], num[v] = res, n
    res = [0] * N
    for v in ans:
        hosei = depth[v]
        s = sd[v] - num[v] * hosei
        if s % 2 == 0:
            check = 0
            node = -1
            for nv in edge[v]:
                if nv != parent[v]:
                    if sd[nv] - num[nv] * hosei > s // 2:
                        check = sd[nv] - num[nv] * hosei
                        node = nv
            if not check:
                res[v] = s // 2
            else:
                minus = res[node]
                if check - 2 * minus <= s - check:
                    res[v] = s // 2
                else:
                    res[v] = s - check + minus
        else:
            check = 0
            node = -1
            k = s // 2
            for nv in edge[v]:
                if nv != parent[v]:
                    if sd[nv] - num[nv] * hosei > k + 1:
                        check = sd[nv] - num[nv] * hosei
                        node = nv
            if not check:
                res[v] = k
            else:
                minus = res[node]
                if check - 2 * minus <= s - check:
                    res[v] = k
                else:
                    res[v] = s - check + minus
    test = res[i]
    # print(i,test,sd[i],sd)
    if 2 * test == sd[i]:
        a = min(a, test)
if a == 10**18:
    print((-1))
else:
    print(a)

-                if sd[nv] - num[nv] * hosei > S // 2:

-                    check = sd[nv] - num[nv] * hosei

+                depth[nv] = depth[v] + 1

+                    if sd[nv] - num[nv] * hosei > s // 2:

+                        check = sd[nv] - num[nv] * hosei

+                if check - 2 * minus <= s - check:

+                    res[v] = s - check + minus

-            if check - 2 * minus <= S - check:

+                    if sd[nv] - num[nv] * hosei > k + 1:

+                        check = sd[nv] - num[nv] * hosei

-                return S - check + minus

-                if sd[nv] - num[nv] * hosei > k + 1:

-                    check = sd[nv] - num[nv] * hosei

-            if check - 2 * minus <= S - check:

-                return S - check + minus

+                if check - 2 * minus <= s - check:

+                    res[v] = s - check + minus


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

Ap = list([(int(x), 0) for x in input().split()])

Bq = list([(int(x), 1) for x in input().split()])

Cr = list([(int(x), 2) for x in input().split()])

INF = 2 * 10**5 + 1

L = Ap + Bq + Cr

L.sort(reverse = True)

cnt = [0, 0, 0]

cntM = [X, Y, INF]

s = 0

ans = 0

for x, i in L:

  if s == X + Y:

    break

  elif cnt[i] < cntM[i]:

    ans += x

    cnt[i] += 1

    s += 1

  else:

    pass

print(ans)

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

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

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

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

Ap.sort(reverse = True)

Bq.sort(reverse = True)

L = sorted(Ap[:X] + Bq[:Y] + Cr, reverse = True)

print((sum(L[:X+Y])))

X, Y, A, B, C = list(map(int, input().split()))
Ap = list([(int(x), 0) for x in input().split()])
Bq = list([(int(x), 1) for x in input().split()])
Cr = list([(int(x), 2) for x in input().split()])
INF = 2 * 10**5 + 1
L = Ap + Bq + Cr
L.sort(reverse=True)
cnt = [0, 0, 0]
cntM = [X, Y, INF]
s = 0
ans = 0
for x, i in L:
    if s == X + Y:
        break
    elif cnt[i] < cntM[i]:
        ans += x
        cnt[i] += 1
        s += 1
    else:
        pass
print(ans)

X, Y, A, B, C = list(map(int, input().split()))
Ap = list(map(int, input().split()))
Bq = list(map(int, input().split()))
Cr = list(map(int, input().split()))
Ap.sort(reverse=True)
Bq.sort(reverse=True)
L = sorted(Ap[:X] + Bq[:Y] + Cr, reverse=True)
print((sum(L[: X + Y])))

-Ap = list([(int(x), 0) for x in input().split()])

-Bq = list([(int(x), 1) for x in input().split()])

-Cr = list([(int(x), 2) for x in input().split()])

+L = sorted(Ap[:X] + Bq[:Y] + Cr, reverse=True)


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

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

ans = 0

for i in range(n-2):

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

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

            if len({l[i], l[j], l[k]}) != 3:

                continue

            if l[i] + l[j] > l[k] and l[i] + l[k] > l[j] and l[j] + l[k] > l[i]:

                ans += 1

print(ans)

from itertools import combinations

n = int(eval(input()))

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

l.sort()

ans = 0

for li, lj, lk in combinations(l, 3):

    if li < lj < lk < li + lj:

        ans += 1

print(ans)

n = int(eval(input()))
l = list(map(int, input().split()))
ans = 0
for i in range(n - 2):
    for j in range(i + 1, n - 1):
        for k in range(j + 1, n):
            if len({l[i], l[j], l[k]}) != 3:
                continue
            if l[i] + l[j] > l[k] and l[i] + l[k] > l[j] and l[j] + l[k] > l[i]:
                ans += 1
print(ans)

-            if l[i] + l[j] > l[k] and l[i] + l[k] > l[j] and l[j] + l[k] > l[i]:


Input:
from string import ascii_lowercase

s = eval(input())

k = int(eval(input()))

b = ord('a')

ret = ''

for c in s[:-1]:

    if c == 'a':

        ret += 'a'

        continue

    need = 26 - (ord(c) - b)

    if k >= need:

        k -= need

        ret += 'a'

    else:

        ret += c

k %= 26

c = s[-1]

ret += chr((ord(c) - b + k) % 26 + b)

print(ret)

from string import ascii_lowercase

s = eval(input())

k = int(eval(input()))

d = {c: (26 - i) % 26 for i, c in enumerate(ascii_lowercase)}

ret = ''

for c in s[:-1]:

    if d[c] <= k:

        k -= d[c]

        ret += 'a'

    else:

        ret += c

k %= 26

idx = (ascii_lowercase.index(s[-1]) + k) % 26

c = ascii_lowercase[idx]

ret += c

print(ret)

from string import ascii_lowercase

s = eval(input())
k = int(eval(input()))
b = ord("a")
ret = ""
for c in s[:-1]:
    if c == "a":
        ret += "a"
        continue
    need = 26 - (ord(c) - b)
    if k >= need:
        k -= need
        ret += "a"
    else:
        ret += c
k %= 26
c = s[-1]
ret += chr((ord(c) - b + k) % 26 + b)
print(ret)

from string import ascii_lowercase

s = eval(input())
k = int(eval(input()))
d = {c: (26 - i) % 26 for i, c in enumerate(ascii_lowercase)}
ret = ""
for c in s[:-1]:
    if d[c] <= k:
        k -= d[c]
        ret += "a"
    else:
        ret += c
k %= 26
idx = (ascii_lowercase.index(s[-1]) + k) % 26
c = ascii_lowercase[idx]
ret += c
print(ret)

+d = {c: (26 - i) % 26 for i, c in enumerate(ascii_lowercase)}

+idx = (ascii_lowercase.index(s[-1]) + k) % 26


Input:
from fractions import gcd

from itertools import accumulate

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

if d == 0:

    if x == 0:

        print((1))

    else:

        print((n + 1))

    exit()

elif d < 0:

    x, d = -x, -d

g = gcd(x, d)

back_k = d // g

offset = x // g

lowers = [0] + list(accumulate(list(range(n))))

uppers = [0] + list(accumulate(list(range(n - 1, -1, -1))))

min_memo = [10 ** 18] * min(n + 1, back_k)

max_memo = [-(10 ** 18)] * min(n + 1, back_k)

# print(n, x, d, g, back_k, offset)

# print(lowers)

# print(uppers)

ans = 0

for k in range(n + 1):

    min_acc = lowers[k]

    max_acc = uppers[k]

    if k < back_k:

        min_memo[k] = min_acc - offset

        max_memo[k] = max_acc - offset

        ans += max_acc - min_acc + 1

        # print(k, ans, min_acc, max_acc, max_acc - min_acc + 1)

        continue

    kk = k % back_k

    back_min = min_memo[kk]

    back_max = max_memo[kk]

    if back_max < min_acc or max_acc < back_min:

        min_memo[kk] = min_acc - offset

        max_memo[kk] = max_acc - offset

        ans += max_acc - min_acc + 1

    else:

        current = max_acc - min_acc + 1

        duplicated = min(max_acc, back_max) - max(min_acc, back_min) + 1

        ans += current - duplicated

        min_memo[kk] = min(min_acc, back_min) - offset

        max_memo[kk] = max(max_acc, back_max) - offset

    # print(k, ans, min_acc, max_acc, back_min, back_max)

print(ans)

from fractions import gcd

from itertools import accumulate

def solve(n, x, d):

    if d == 0:

        return 1 if x == 0 else n + 1

    elif d < 0:

        x, d = -x, -d

    g = gcd(x, d)

    x //= g

    d //= g

    lowers = [0] + list(accumulate(list(range(n))))

    uppers = [0] + list(accumulate(list(range(n - 1, -1, -1))))

    ans = 0

    for k_mod in range(min(n + 1, d)):

        k = k_mod

        offset = 0

        endpoints = []

        while k <= n:

            endpoints.append((lowers[k] + offset, 0))

            endpoints.append((uppers[k] + offset, 1))

            k += d

            offset += x

        endpoints.sort()

        opening = 0

        current_left = 0

        for s, t in endpoints:

            if t == 0:

                if opening == 0:

                    current_left = s

                opening += 1

            else:

                opening -= 1

                if opening == 0:

                    ans += s - current_left + 1

    return ans

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

print((solve(n, x, d)))

from fractions import gcd
from itertools import accumulate

n, x, d = list(map(int, input().split()))
if d == 0:
    if x == 0:
        print((1))
    else:
        print((n + 1))
    exit()
elif d < 0:
    x, d = -x, -d
g = gcd(x, d)
back_k = d // g
offset = x // g
lowers = [0] + list(accumulate(list(range(n))))
uppers = [0] + list(accumulate(list(range(n - 1, -1, -1))))
min_memo = [10**18] * min(n + 1, back_k)
max_memo = [-(10**18)] * min(n + 1, back_k)
# print(n, x, d, g, back_k, offset)
# print(lowers)
# print(uppers)
ans = 0
for k in range(n + 1):
    min_acc = lowers[k]
    max_acc = uppers[k]
    if k < back_k:
        min_memo[k] = min_acc - offset
        max_memo[k] = max_acc - offset
        ans += max_acc - min_acc + 1
        # print(k, ans, min_acc, max_acc, max_acc - min_acc + 1)
        continue
    kk = k % back_k
    back_min = min_memo[kk]
    back_max = max_memo[kk]
    if back_max < min_acc or max_acc < back_min:
        min_memo[kk] = min_acc - offset
        max_memo[kk] = max_acc - offset
        ans += max_acc - min_acc + 1
    else:
        current = max_acc - min_acc + 1
        duplicated = min(max_acc, back_max) - max(min_acc, back_min) + 1
        ans += current - duplicated
        min_memo[kk] = min(min_acc, back_min) - offset
        max_memo[kk] = max(max_acc, back_max) - offset
    # print(k, ans, min_acc, max_acc, back_min, back_max)
print(ans)

+    lowers = [0] + list(accumulate(list(range(n))))

+    uppers = [0] + list(accumulate(list(range(n - 1, -1, -1))))

+            endpoints.append((lowers[k] + offset, 0))

+            endpoints.append((uppers[k] + offset, 1))

+                    ans += s - current_left + 1

-lowers = [0] + list(accumulate(list(range(n))))

-uppers = [0] + list(accumulate(list(range(n - 1, -1, -1))))

-        # print(k, ans, min_acc, max_acc, max_acc - min_acc + 1)

-    if back_max < min_acc or max_acc < back_min:

-        min_memo[kk] = min_acc - offset

-        max_memo[kk] = max_acc - offset

-        current = max_acc - min_acc + 1

-        duplicated = min(max_acc, back_max) - max(min_acc, back_min) + 1

-        min_memo[kk] = min(min_acc, back_min) - offset

-        max_memo[kk] = max(max_acc, back_max) - offset

-    # print(k, ans, min_acc, max_acc, back_min, back_max)


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

P, C = [list(map(int, input().split())) for _ in range(2)]

c = [1] * N

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

for i in range(N):

    m[i][1] = (C[P[i]-1])

ans = max(C)

for i in range(N):

    j = i

    while P[j]-1 != i:

        j = P[j]-1

        c[i] += 1

        m[i][c[i]] = m[i][c[i]-1] + C[P[j]-1]

    if m[i][c[i]] > 0:

        ans = max(ans, m[i][c[i]] * (K//c[i]-1) + max(m[i] + [m[i][c[i]] + m[i][j+1] for j in range(K%c[i])]))

    else:

        ans = max(ans, max(m[i][1:min(c[i],K)+1]))

print(ans)

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

P, C = [list(map(int, input().split())) for _ in range(2)]

ans = max(C)

for i in range(N):

    m = [0] * (N+1)

    k = i

    for j in range(N):

        m[j+1] = m[j] + C[k]

        k = P[k]-1

        if k == i:

            break

    if m[j+1] > 0:

        ans = max(ans, m[j+1] * (K//(j+1)-1) + max(m + [m[j+1] + m[k+1] for k in range(K%(j+1))]))

    else:

        ans = max(ans, max(m[1:min(j+1,K)+1]))

print(ans)

N, K = list(map(int, input().split()))
P, C = [list(map(int, input().split())) for _ in range(2)]
c = [1] * N
m = [[0] * (N + 1) for i in range(N)]
for i in range(N):
    m[i][1] = C[P[i] - 1]
ans = max(C)
for i in range(N):
    j = i
    while P[j] - 1 != i:
        j = P[j] - 1
        c[i] += 1
        m[i][c[i]] = m[i][c[i] - 1] + C[P[j] - 1]
    if m[i][c[i]] > 0:
        ans = max(
            ans,
            m[i][c[i]] * (K // c[i] - 1)
            + max(m[i] + [m[i][c[i]] + m[i][j + 1] for j in range(K % c[i])]),
        )
    else:
        ans = max(ans, max(m[i][1 : min(c[i], K) + 1]))
print(ans)

N, K = list(map(int, input().split()))
P, C = [list(map(int, input().split())) for _ in range(2)]
ans = max(C)
for i in range(N):
    m = [0] * (N + 1)
    k = i
    for j in range(N):
        m[j + 1] = m[j] + C[k]
        k = P[k] - 1
        if k == i:
            break
    if m[j + 1] > 0:
        ans = max(
            ans,
            m[j + 1] * (K // (j + 1) - 1)
            + max(m + [m[j + 1] + m[k + 1] for k in range(K % (j + 1))]),
        )
    else:
        ans = max(ans, max(m[1 : min(j + 1, K) + 1]))
print(ans)

-        ans = max(ans, max(m[i][1 : min(c[i], K) + 1]))

+        ans = max(ans, max(m[1 : min(j + 1, K) + 1]))


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

l = []

for _ in range(N):

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

    l.append((A, B))

t = N//2

tl = sorted(l)

tr = sorted(l, key=lambda x:-x[1])

if N%2:

    print((tr[t][1]-tl[t][0]+1))

else:

    a1, a2 = tl[t-1][0], tr[t][1]

    a3, a4 = tl[t][0], tr[t-1][1]

    print((a4-a3+a2-a1+1))

N = int(eval(input()))

t = N//2

la, lb = [], []

for _ in range(N):

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

    la.append(A)

    lb.append(B)

la.sort()

lb.sort()

print((lb[t]-la[t]+1 if N%2 else lb[t-1]-la[t]+lb[t]-la[t-1]+1))

N = int(eval(input()))
l = []
for _ in range(N):
    A, B = list(map(int, input().split()))
    l.append((A, B))
t = N // 2
tl = sorted(l)
tr = sorted(l, key=lambda x: -x[1])
if N % 2:
    print((tr[t][1] - tl[t][0] + 1))
else:
    a1, a2 = tl[t - 1][0], tr[t][1]
    a3, a4 = tl[t][0], tr[t - 1][1]
    print((a4 - a3 + a2 - a1 + 1))

N = int(eval(input()))
t = N // 2
la, lb = [], []
for _ in range(N):
    A, B = list(map(int, input().split()))
    la.append(A)
    lb.append(B)
la.sort()
lb.sort()
print((lb[t] - la[t] + 1 if N % 2 else lb[t - 1] - la[t] + lb[t] - la[t - 1] + 1))


Input:
import sys

from io import StringIO

import unittest

sys.setrecursionlimit(10**6)

def search(n, step, rec, seq, k):

	if rec[n] != -1:

		c = step - rec[n]

		sim = (k - rec[n]) % c

		v = n

		for i in range(sim):

			v = seq[v-1]

		print(v)

		return

	rec[n] = step

	if step == k:

		print(n)

		return

	search(seq[n-1], step + 1, rec, seq, k)

def resolve():

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

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

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

	search(1, 0, rec, seq, k)

resolve()

def resolve():

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

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

	rec = [True]*(n+2)

	now = 0

	stp = [1]

	while rec[now]:

		rec[now] = False

		now = a[now] - 1

		stp.append(now+1)

	before_loop = stp.index(now+1)

	loop = stp[before_loop:-1]

	if k <= (before_loop + 1):

		print((stp[k]))

	else:

		r = (k - before_loop) % len(loop)

		print((loop[r]))

resolve()

import sys
from io import StringIO
import unittest

sys.setrecursionlimit(10**6)

def search(n, step, rec, seq, k):
    if rec[n] != -1:
        c = step - rec[n]
        sim = (k - rec[n]) % c
        v = n
        for i in range(sim):
            v = seq[v - 1]
        print(v)
        return
    rec[n] = step
    if step == k:
        print(n)
        return
    search(seq[n - 1], step + 1, rec, seq, k)

def resolve():
    n, k = list(map(int, input().split()))
    seq = list(map(int, input().split()))
    rec = [-1] * (n + 1)
    search(1, 0, rec, seq, k)

resolve()

def resolve():
    n, k = list(map(int, input().split()))
    a = list(map(int, input().split()))
    rec = [True] * (n + 2)
    now = 0
    stp = [1]
    while rec[now]:
        rec[now] = False
        now = a[now] - 1
        stp.append(now + 1)
    before_loop = stp.index(now + 1)
    loop = stp[before_loop:-1]
    if k <= (before_loop + 1):
        print((stp[k]))
    else:
        r = (k - before_loop) % len(loop)
        print((loop[r]))

resolve()

-    search(seq[n - 1], step + 1, rec, seq, k)

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

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

+        r = (k - before_loop) % len(loop)


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

N_ = str(N)

f_N, l_N = int(N_[0]), int(N_[-1])

digit = len(N_)

if digit > 2:

    inter_N = int(N_[1:digit-1])

cnt = 0

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

    num = str(num)

    f, l = int(num[-1]), int(num[0])

    if f == 0:

        continue

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

        if i == 1:

            if f == l:

                cnt += 1

            else:

                continue

        else:

            if i != digit:

                cnt += 10**(i-2)

            elif digit == 2 and i == digit:

                if f*10+l <= N:

                    cnt += 1

                else:

                    continue

            else:

                if f > f_N:

                    continue

                elif f == f_N:

                    if l > l_N:

                        cnt += inter_N

                    elif l <= l_N:

                        cnt += (inter_N+1)

                else:

                    cnt += 10**(i-2)

print(cnt)

N = int(eval(input()))

cnt = [[0] * 10 for i in range(10)]

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

    cnt[int(str(n)[0])][int(str(n)[-1])] += 1

ans = 0

for i in range(10):

    for j in range(10):

        ans += cnt[i][j] * cnt[j][i]

print(ans)

N = int(eval(input()))
N_ = str(N)
f_N, l_N = int(N_[0]), int(N_[-1])
digit = len(N_)
if digit > 2:
    inter_N = int(N_[1 : digit - 1])
cnt = 0
for num in range(1, N + 1):
    num = str(num)
    f, l = int(num[-1]), int(num[0])
    if f == 0:
        continue
    for i in range(1, digit + 1):
        if i == 1:
            if f == l:
                cnt += 1
            else:
                continue
        else:
            if i != digit:
                cnt += 10 ** (i - 2)
            elif digit == 2 and i == digit:
                if f * 10 + l <= N:
                    cnt += 1
                else:
                    continue
            else:
                if f > f_N:
                    continue
                elif f == f_N:
                    if l > l_N:
                        cnt += inter_N
                    elif l <= l_N:
                        cnt += inter_N + 1
                else:
                    cnt += 10 ** (i - 2)
print(cnt)

-            elif digit == 2 and i == digit:

-                        cnt += inter_N + 1


Input:
li=eval(input())

n=len(li)

child_li=[0]*n

ruiseki=0

#まず、RRRRRRRLのようにRが連続してLが最後に来る場合のRLを考える。左から

for i in range(n-1):

    if li[i]=='R':

        ruiseki+=1

        if li[i+1]=='L':

            child_li[i+1]=ruiseki//2#------Lについて、Rが連続の分の半分（こっちは切り捨て）

            child_li[i]=(ruiseki+1)//2#----Rについて、Rが連続の分の半分（こっちは奇数の場合切り上げ）

    else:

        ruiseki=0

#同様に、LLLLLLRのようにLが連続してLが最後に来る場合のRLを考える。右から

ruiseki=0

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

    if li[i]=='L':

        ruiseki+=1

        if li[i-1]=='R':

            child_li[i-1]+=ruiseki//2#-----Rについて、Lが連続の分の半分（こっちは切り捨て）

            child_li[i]+=(ruiseki+1)//2#---Lについて、Lが連続の分の半分（こっちは奇数の場合切り上げ）

    else:

        ruiseki=0

print((*child_li))

S = eval(input())

N = len(S)

ans = [0]*N

cnt = 0

for i in range(N):

    if S[i] == "L":

        if cnt % 2 ==0:

            ans[i] += cnt//2

            ans[i-1] += cnt//2

            cnt = 0

        else:

            ans[i] += (cnt-1)//2

            ans[i-1] += (cnt+1)//2

            cnt = 0

    else:

        cnt += 1

cnt = 0

for i in reversed(list(range(N))):

    if S[i] == "R":

        if cnt % 2 ==0:

            ans[i] += cnt//2

            ans[i+1] += cnt//2

            cnt = 0

        else:

            ans[i] += (cnt-1)//2

            ans[i+1] += (cnt+1)//2

            cnt = 0

    else:

        cnt += 1

ans = [str(a) for a in ans]

print((" ".join(ans)))

li = eval(input())
n = len(li)
child_li = [0] * n
ruiseki = 0
# まず、RRRRRRRLのようにRが連続してLが最後に来る場合のRLを考える。左から
for i in range(n - 1):
    if li[i] == "R":
        ruiseki += 1
        if li[i + 1] == "L":
            child_li[i + 1] = ruiseki // 2  # ------Lについて、Rが連続の分の半分（こっちは切り捨て）
            child_li[i] = (ruiseki + 1) // 2  # ----Rについて、Rが連続の分の半分（こっちは奇数の場合切り上げ）
    else:
        ruiseki = 0
# 同様に、LLLLLLRのようにLが連続してLが最後に来る場合のRLを考える。右から
ruiseki = 0
for i in range(n - 1, 0, -1):
    if li[i] == "L":
        ruiseki += 1
        if li[i - 1] == "R":
            child_li[i - 1] += ruiseki // 2  # -----Rについて、Lが連続の分の半分（こっちは切り捨て）
            child_li[i] += (ruiseki + 1) // 2  # ---Lについて、Lが連続の分の半分（こっちは奇数の場合切り上げ）
    else:
        ruiseki = 0
print((*child_li))

S = eval(input())
N = len(S)
ans = [0] * N
cnt = 0
for i in range(N):
    if S[i] == "L":
        if cnt % 2 == 0:
            ans[i] += cnt // 2
            ans[i - 1] += cnt // 2
            cnt = 0
        else:
            ans[i] += (cnt - 1) // 2
            ans[i - 1] += (cnt + 1) // 2
            cnt = 0
    else:
        cnt += 1
cnt = 0
for i in reversed(list(range(N))):
    if S[i] == "R":
        if cnt % 2 == 0:
            ans[i] += cnt // 2
            ans[i + 1] += cnt // 2
            cnt = 0
        else:
            ans[i] += (cnt - 1) // 2
            ans[i + 1] += (cnt + 1) // 2
            cnt = 0
    else:
        cnt += 1
ans = [str(a) for a in ans]
print((" ".join(ans)))

-# まず、RRRRRRRLのようにRが連続してLが最後に来る場合のRLを考える。左から

-# 同様に、LLLLLLRのようにLが連続してLが最後に来る場合のRLを考える。右から


Input:
def q(a,h):

 d[a]=str(h)

 for b in t[a]:q(b,h+1)

t,p,d={},{},{}

for _ in[0]*int(eval(input())):

 e=input().split()

 t[e[0]]=e[2:]

 for i in e[2:]:p[i]=e[0]

r=(set(t)-set(p)).pop()

p[r]='-1'

q(r,0)

print(('\n'.join(f"node {i}: parent = {p[i]}, depth = {d[i]}, {'root'if'-1'==p[i]else'internal node'if t[i]else'leaf'}, [{', '.join(t[i])}]"for i in map(str,sorted(map(int,t))))))

import sys

def q(a,h):

 d[a]=str(h)

 for b in t[a]:q(b,h+1)

t,p,d={},{},{}

eval(input())

for e in sys.stdin:

 e=e.split()

 t[e[0]]=e[2:]

 for i in e[2:]:p[i]=e[0]

r=(set(t)-set(p)).pop()

p[r]='-1'

q(r,0)

print(('\n'.join(f"node {i}: parent = {p[i]}, depth = {d[i]}, {'root'if'-1'==p[i]else'internal node'if t[i]else'leaf'}, [{', '.join(t[i])}]"for i in map(str,sorted(map(int,t))))))

def q(a, h):
    d[a] = str(h)
    for b in t[a]:
        q(b, h + 1)

t, p, d = {}, {}, {}
for _ in [0] * int(eval(input())):
    e = input().split()
    t[e[0]] = e[2:]
    for i in e[2:]:
        p[i] = e[0]
r = (set(t) - set(p)).pop()
p[r] = "-1"
q(r, 0)
print(
    (
        "\n".join(
            f"node {i}: parent = {p[i]}, depth = {d[i]}, {'root'if'-1'==p[i]else'internal node'if t[i]else'leaf'}, [{', '.join(t[i])}]"
            for i in map(str, sorted(map(int, t)))
        )
    )
)

import sys

def q(a, h):
    d[a] = str(h)
    for b in t[a]:
        q(b, h + 1)

t, p, d = {}, {}, {}
eval(input())
for e in sys.stdin:
    e = e.split()
    t[e[0]] = e[2:]
    for i in e[2:]:
        p[i] = e[0]
r = (set(t) - set(p)).pop()
p[r] = "-1"
q(r, 0)
print(
    (
        "\n".join(
            f"node {i}: parent = {p[i]}, depth = {d[i]}, {'root'if'-1'==p[i]else'internal node'if t[i]else'leaf'}, [{', '.join(t[i])}]"
            for i in map(str, sorted(map(int, t)))
        )
    )
)

+import sys
+
+
-for _ in [0] * int(eval(input())):
-    e = input().split()
+eval(input())
+for e in sys.stdin:
+    e = e.split()


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

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

app = {}

for i, j in zip(v[::2], v[1::2]):

    if i not in app:

        app[i] = [1, 0]

    else:

        app[i][0] += 1

    if j not in app:

        app[j] = [0, 1]

    else:

        app[j][1] += 1

max_o = [0, 0]

secmax_o = [0, 0]

max_e = [0, 0]

secmax_e = [0, 0]

for i in app:

    if app[i][0] > max_o[1]:

        secmax_o = max_o[:]

        max_o = [i, app[i][0]]

    elif app[i][0] > secmax_o[1]:

        secmax_o = [i, app[i][0]]

    if app[i][1] > max_e[1]:

        secmax_e = max_e[:]

        max_e = [i, app[i][1]]

    elif app[i][1] > secmax_e[1]:

        secmax_e = [i, app[i][1]]

if max_o[0] != max_e[0]:

    print((n - max_o[1] - max_e[1]))

else:

    del0 = max_o[1] - secmax_o[1]

    del1 = max_e[1] - secmax_e[1]

    print((n + min(del0, del1) - max_o[1] - max_e[1]))

from collections import Counter

n = int(eval(input()))

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

cnt_o = Counter(v[::2]).most_common(2)

cnt_e = Counter(v[1::2]).most_common(2)

cnt_o.append((0, 0))

cnt_e.append((0, 0))

if cnt_o[0][0] != cnt_e[0][0]:

    print((n - cnt_o[0][1] - cnt_e[0][1]))

else:

    del1 = cnt_o[0][1] - cnt_o[1][1]

    del2 = cnt_e[0][1] - cnt_e[1][1]

    print((n - cnt_o[0][1] - cnt_e[0][1] + min(del1, del2)))

-    print((n + min(del0, del1) - max_o[1] - max_e[1]))


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

from math import ceil

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

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

C = A - B

lo, hi = -1, 10**9

while hi - lo > 1:

    X = (hi + lo) // 2

    H2 = [max(0, h - (X * B)) for h in H]

    need = sum([ceil(h / C) for h in H2])

    if need > X:

        lo = X

    else:

        hi = X

print(hi)

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 = [int(eval(input())) for i in range(N)]

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

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

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

+    H2 = [max(0, h - (X * B)) for h in H]

+    need = sum([ceil(h / C) for h in H2])


Input:
import sys

from heapq import heappush, heappop, heapreplace

def solve():

    file_input = sys.stdin

    N, R, L = list(map(int, file_input.readline().split()))

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

    m = dict(list(zip(list(range(1, N + 1)), pq)))

    pre_t = 0

    for line in file_input:

        d, t, x = list(map(int, line.split()))

        team = pq[0]

        team[2] += t - pre_t

        pre_t = t

        if team[1] == d:

            team[0] -= x

            if x < 0:

                heapreplace(pq, team)

        else:

            scored_team = m[d][:]

            scored_team[0] -= x

            heappush(pq, scored_team)

            m[d][2] = -1

            m[d] = scored_team

        while pq[0][2] == -1:

            heappop(pq)

    pq[0][2] += L - pre_t

    ans_team = max(pq, key = lambda x: (x[2], -x[1]))

    print((ans_team[1]))

solve()

import sys

from heapq import heappush, heappop, heapreplace

def solve():

    file_input = sys.stdin

    N, R, L = list(map(int, file_input.readline().split()))

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

    m = dict(list(zip(list(range(1, N + 1)), pq)))

    time = [0] * (N + 1)

    INVALID = -1

    pre_t = 0

    for line in file_input:

        d, t, x = list(map(int, line.split()))

        top_team = pq[0]

        time[top_team[1]] += t - pre_t

        pre_t = t

        if top_team[1] == d:

            top_team[0] -= x

            if x < 0:

                heapreplace(pq, top_team)

        else:

            scored_team = m[d][:]

            scored_team[0] -= x

            heappush(pq, scored_team)

            m[d][1] = INVALID

            m[d] = scored_team

        while pq[0][1] == INVALID:

            heappop(pq)

    time[pq[0][1]] += L - pre_t

    print((time.index(max(time))))

solve()

import sys
from heapq import heappush, heappop, heapreplace

def solve():
    file_input = sys.stdin
    N, R, L = list(map(int, file_input.readline().split()))
    pq = [[0, i, 0] for i in range(1, N + 1)]
    m = dict(list(zip(list(range(1, N + 1)), pq)))
    pre_t = 0
    for line in file_input:
        d, t, x = list(map(int, line.split()))
        team = pq[0]
        team[2] += t - pre_t
        pre_t = t
        if team[1] == d:
            team[0] -= x
            if x < 0:
                heapreplace(pq, team)
        else:
            scored_team = m[d][:]
            scored_team[0] -= x
            heappush(pq, scored_team)
            m[d][2] = -1
            m[d] = scored_team
        while pq[0][2] == -1:
            heappop(pq)
    pq[0][2] += L - pre_t
    ans_team = max(pq, key=lambda x: (x[2], -x[1]))
    print((ans_team[1]))

solve()

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

+                heapreplace(pq, top_team)

-    ans_team = max(pq, key=lambda x: (x[2], -x[1]))


Input:
import sys, re

from collections import deque, defaultdict, Counter

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log

from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from fractions import gcd

from heapq import heappush, heappop

from functools import reduce

from decimal import Decimal

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

def INT(): return int(eval(input()))

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

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

def ZIP(n): return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10**9 + 7

from decimal import *

N = INT()

ab = [LIST() for _ in range(N-1)]

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

for a, b in ab:

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

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

length = [len(x) for x in graph]

ans = max(length)

color = defaultdict(int)

q = deque([])

cnt = 1

for x in graph[0]:

	q.append((x, 0, cnt))

	cnt += 1

while q:

	n, previous, col = q.popleft()

	cnt = 1

	for x in graph[n]:

		if x == previous:

			color[(n, x)] = col

			color[(x, n)] = col

		else:

			if cnt == col:

				cnt += 1

			color[(n, x)] = cnt

			color[(x, n)] = cnt

			q.append((x, n, cnt))

			cnt += 1

print(ans)

for a, b in ab:

	print((color[(a-1, b-1)]))

import sys, re

from collections import deque, defaultdict, Counter

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log

from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from fractions import gcd

from heapq import heappush, heappop

from functools import reduce

from decimal import Decimal

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

def INT(): return int(eval(input()))

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

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

def ZIP(n): return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10**9 + 7

from decimal import *

N = INT()

ab = [LIST() for _ in range(N-1)]

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

for a, b in ab:

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

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

length = [len(x) for x in graph]

ans = max(length)

color = defaultdict(int)

def coloring(n, previous, col): #頂点nにpreviousから色colで辿ってきた。

	cnt = 1

	for x in graph[n]:

		if x == previous:

			color[(n, x)] = col

			color[(x, n)] = col #やってきた頂点との間における色

		else:

			if cnt == col:

				cnt += 1

			color[(x, n)] = cnt

			color[(n, x)] = cnt

			coloring(x, n, cnt)

			cnt += 1

coloring(0, -1, 0)

print(ans)

for a, b in ab:

	print((color[(a-1, b-1)]))

import sys, re
from collections import deque, defaultdict, Counter
from math import (
    ceil,
    sqrt,
    hypot,
    factorial,
    pi,
    sin,
    cos,
    tan,
    asin,
    acos,
    atan,
    radians,
    degrees,
    log2,
    log,
)
from itertools import (
    accumulate,
    permutations,
    combinations,
    combinations_with_replacement,
    product,
    groupby,
)
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal

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

def INT():
    return int(eval(input()))

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

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

def ZIP(n):
    return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
from decimal import *

N = INT()
ab = [LIST() for _ in range(N - 1)]
graph = [[] for _ in range(N)]
for a, b in ab:
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
length = [len(x) for x in graph]
ans = max(length)
color = defaultdict(int)
q = deque([])
cnt = 1
for x in graph[0]:
    q.append((x, 0, cnt))
    cnt += 1
while q:
    n, previous, col = q.popleft()
    cnt = 1
    for x in graph[n]:
        if x == previous:
            color[(n, x)] = col
            color[(x, n)] = col
        else:
            if cnt == col:
                cnt += 1
            color[(n, x)] = cnt
            color[(x, n)] = cnt
            q.append((x, n, cnt))
            cnt += 1
print(ans)
for a, b in ab:
    print((color[(a - 1, b - 1)]))

import sys, re
from collections import deque, defaultdict, Counter
from math import (
    ceil,
    sqrt,
    hypot,
    factorial,
    pi,
    sin,
    cos,
    tan,
    asin,
    acos,
    atan,
    radians,
    degrees,
    log2,
    log,
)
from itertools import (
    accumulate,
    permutations,
    combinations,
    combinations_with_replacement,
    product,
    groupby,
)
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal

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

def INT():
    return int(eval(input()))

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

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

def ZIP(n):
    return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
from decimal import *

N = INT()
ab = [LIST() for _ in range(N - 1)]
graph = [[] for _ in range(N)]
for a, b in ab:
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
length = [len(x) for x in graph]
ans = max(length)
color = defaultdict(int)

def coloring(n, previous, col):  # 頂点nにpreviousから色colで辿ってきた。
    cnt = 1
    for x in graph[n]:
        if x == previous:
            color[(n, x)] = col
            color[(x, n)] = col  # やってきた頂点との間における色
        else:
            if cnt == col:
                cnt += 1
            color[(x, n)] = cnt
            color[(n, x)] = cnt
            coloring(x, n, cnt)
            cnt += 1

coloring(0, -1, 0)
print(ans)
for a, b in ab:
    print((color[(a - 1, b - 1)]))

+def coloring(n, previous, col):  # 頂点nにpreviousから色colで辿ってきた。

+            color[(x, n)] = col  # やってきた頂点との間における色


Input:
n = list(str(eval(input())))

a = 0

b = 0

for i in n:

    if i == "1":

        a += 1

    else:

        b += 1

c = min(a,b)

print((2 * c))

n = list(str(eval(input())))

a = n.count("1")

b = n.count("0")

c = min(a,b)

print((2 * c))

n = list(str(eval(input())))
a = 0
b = 0
for i in n:
    if i == "1":
        a += 1
    else:
        b += 1
c = min(a, b)
print((2 * c))

n = list(str(eval(input())))
a = n.count("1")
b = n.count("0")
c = min(a, b)
print((2 * c))


Input:
while True:

    try:

        xA,yA,xB,yB,xC,yC,xD,yD = list(map(float, input().split()))

        if abs((yB-yA)*(yD-yC) + (xB-xA)*(xD-xC)) < 1.e-12:

                print("YES")

        else:

            print("NO")

    except:

        break

while True:

    try:

        xA,yA,xB,yB,xC,yC,xD,yD = list(map(float, input().split()))

        if abs((yB-yA)*(yD-yC) + (xB-xA)*(xD-xC)) < 1.e-10:

                print("YES")

        else:

            print("NO")

    except:

        break

while True:
    try:
        xA, yA, xB, yB, xC, yC, xD, yD = list(map(float, input().split()))
        if abs((yB - yA) * (yD - yC) + (xB - xA) * (xD - xC)) < 1.0e-12:
            print("YES")
        else:
            print("NO")
    except:
        break

while True:
    try:
        xA, yA, xB, yB, xC, yC, xD, yD = list(map(float, input().split()))
        if abs((yB - yA) * (yD - yC) + (xB - xA) * (xD - xC)) < 1.0e-10:
            print("YES")
        else:
            print("NO")
    except:
        break


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

edgeList = []

rootList = [-1 for i in range(n)]

def getRoot(x):

    r = rootList[x]

    if r < 0:

        rootList[x] = x

    elif r != x:

        rootList[x] = getRoot(r)

    return rootList[x]

for i in range(n):

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

    for j in range(i):

        if a[j] != -1:

            edgeList.append([a[j], getRoot(i), getRoot(j)])

sumLength = 0

edgeList.sort(key=lambda x: x[0])

for e in edgeList:

    x = getRoot(e[1])

    y = getRoot(e[2])

    if x != y:

        sumLength += e[0]

        rootList[x] = rootList[y] = min(x, y)

print(sumLength)

n = int(eval(input()))

edgeList = []

for i in range(n):

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

    for j in range(i):

        if a[j] != -1:

            edgeList.append([a[j], i, j])

rootList = [-1]*n

sumLength = 0

def getRoot(x):

    r = rootList[x]

    if r < 0:

        rootList[x] = x

    elif r != x:

        rootList[x] = getRoot(r)

    return rootList[x]

edgeList.sort(key=lambda x: x[0])

for e in edgeList:

    x = getRoot(e[1])

    y = getRoot(e[2])

    if x != y:

        sumLength += e[0]

        rootList[x] = rootList[y] = min(x, y)

print(sumLength)

n = int(eval(input()))
edgeList = []
for i in range(n):
    a = list(map(int, input().split()))
    for j in range(i):
        if a[j] != -1:
            edgeList.append([a[j], i, j])
rootList = [-1] * n
sumLength = 0

def getRoot(x):
    r = rootList[x]
    if r < 0:
        rootList[x] = x
    elif r != x:
        rootList[x] = getRoot(r)
    return rootList[x]

edgeList.sort(key=lambda x: x[0])
for e in edgeList:
    x = getRoot(e[1])
    y = getRoot(e[2])
    if x != y:
        sumLength += e[0]
        rootList[x] = rootList[y] = min(x, y)
print(sumLength)

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

+            edgeList.append([a[j], i, j])

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

-            edgeList.append([a[j], getRoot(i), getRoot(j)])


Input:
def roof(a, b):

    if a%b == 0:

        return a//b

    else:

        return a//b + 1

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

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

low, high = 0, 10**9

while high - low > 1:

    mid = (low + high)//2

    count = 0

    for i in range(N):

        if H[i] - (B * mid) > 0:

            count += roof(H[i]-(B*mid), A-B)

    if count > mid:

        low = mid

    else:

        high = mid

print(high)

import sys

def solve():

    input = sys.stdin.readline

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

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

    low = 0; high = 10 ** 20

    while high - low > 1:

        mid = (low + high) // 2

        explosion = B * mid

        direct = 0

        for h in H:

            if h - explosion > 0:

                direct += (h - explosion) // (A - B)

                if (h - explosion) % (A - B) > 0: direct += 1

        if direct <= mid: high = mid

        else: low = mid

    print(high)

    return 0

if __name__ == "__main__":

    solve()

def roof(a, b):
    if a % b == 0:
        return a // b
    else:
        return a // b + 1

N, A, B = list(map(int, input().split()))
H = [int(eval(input())) for i in range(N)]
low, high = 0, 10**9
while high - low > 1:
    mid = (low + high) // 2
    count = 0
    for i in range(N):
        if H[i] - (B * mid) > 0:
            count += roof(H[i] - (B * mid), A - B)
    if count > mid:
        low = mid
    else:
        high = mid
print(high)

import sys

def solve():
    input = sys.stdin.readline
    N, A, B = list(map(int, input().split()))
    H = [int(eval(input())) for _ in range(N)]
    low = 0
    high = 10**20
    while high - low > 1:
        mid = (low + high) // 2
        explosion = B * mid
        direct = 0
        for h in H:
            if h - explosion > 0:
                direct += (h - explosion) // (A - B)
                if (h - explosion) % (A - B) > 0:
                    direct += 1
        if direct <= mid:
            high = mid
        else:
            low = mid
    print(high)
    return 0

if __name__ == "__main__":
    solve()

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

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

-            count += roof(H[i] - (B * mid), A - B)

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

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

+                direct += (h - explosion) // (A - B)

+                if (h - explosion) % (A - B) > 0:


Input:
N = int(input())

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

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

for u, v, w in edges:

    graph[u].append((v, w))

    graph[v].append((u, w))

edges.sort()

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

color[1] = 0

que = [1]

while que:

    u = que.pop()

    for v, w in graph[u]:

        if color[v] != -1:

            continue

        if w % 2 == 0:

            color[v] = color[u]

        else:

            color[v] = color[u] ^ 1

        que.append(v)

print(*color[1:], sep='\n')

from collections import deque

N = int(input())

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

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

for u, v, w in X:

    graph[u].append((v, w))

    graph[v].append((u, w))

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

colors[1] = 0

q = deque([1])

while q:

    u = q.popleft()

    for v, w in graph[u]:

        if colors[v] >= 0:

            continue

        if w % 2 == 0:

            colors[v] = colors[u]

        else:

            colors[v] = 1 - colors[u]

        q.append(v)

print(*colors[1:], sep="\n")

N = int(input())
edges = [list(map(int, input().split())) for _ in range(N - 1)]
graph = [[] for _ in range(N + 1)]
for u, v, w in edges:
    graph[u].append((v, w))
    graph[v].append((u, w))
edges.sort()
color = [-1] * (N + 1)
color[1] = 0
que = [1]
while que:
    u = que.pop()
    for v, w in graph[u]:
        if color[v] != -1:
            continue
        if w % 2 == 0:
            color[v] = color[u]
        else:
            color[v] = color[u] ^ 1
        que.append(v)
print(*color[1:], sep="\n")

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

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


Input:
def solve():

    from collections import deque

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

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

    visited = [[-1]*w for _ in range(h)]

    for i in range(h):

        if 'S' in maze[i]:

            sy, sx = i, maze[i].index('S')

            break

    queue = deque([[sy, sx]])

    visited[sy][sx] = 0

    r = 10**18

    while queue:

        y, x = queue.popleft()

        r = min(r, y, h-1-y, x, w-1-x)

        if visited[y][x] == k: continue

        for i, j in ([1, 0], [-1, 0], [0, 1], [0, -1]):

            new_y, new_x = y+i, x+j

            if new_y < 0 or new_y >= h or new_x < 0 or new_x >= w: continue

            if maze[new_y][new_x] == '.' and visited[new_y][new_x] == -1:

                visited[new_y][new_x] = visited[y][x] + 1

                queue.append([new_y, new_x])

    print((1 -(-r // k)))

if __name__ == '__main__':

    solve()

from collections import deque;h,w,k=list(map(int,input().split()));m=[eval(input())for _ in[0]*h];v=[[-1]*w for _ in[0]*h];r=9**20

for i in range(h):

 if'S'in m[i]:j=m[i].index('S');q=deque([[i,j]]);v[i][j]=0

while q:

 y,x=q.popleft()

 r=min(r,y,x,h-1-y,w-1-x)

 if v[y][x]==k:continue

 for i,j in([1,0],[-1,0],[0,1],[0,-1]):

  t,u=y+i,x+j

  if t>=0and t<h and u>=0and u<w and m[t][u]=='.'and v[t][u]<0:v[t][u]=v[y][x]+1;q.append([t,u])

print((1-(-r//k)))

def solve():
    from collections import deque

    h, w, k = list(map(int, input().split()))
    maze = [eval(input()) for _ in range(h)]
    visited = [[-1] * w for _ in range(h)]
    for i in range(h):
        if "S" in maze[i]:
            sy, sx = i, maze[i].index("S")
            break
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    r = 10**18
    while queue:
        y, x = queue.popleft()
        r = min(r, y, h - 1 - y, x, w - 1 - x)
        if visited[y][x] == k:
            continue
        for i, j in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_y, new_x = y + i, x + j
            if new_y < 0 or new_y >= h or new_x < 0 or new_x >= w:
                continue
            if maze[new_y][new_x] == "." and visited[new_y][new_x] == -1:
                visited[new_y][new_x] = visited[y][x] + 1
                queue.append([new_y, new_x])
    print((1 - (-r // k)))

if __name__ == "__main__":
    solve()

from collections import deque

h, w, k = list(map(int, input().split()))
m = [eval(input()) for _ in [0] * h]
v = [[-1] * w for _ in [0] * h]
r = 9**20
for i in range(h):
    if "S" in m[i]:
        j = m[i].index("S")
        q = deque([[i, j]])
        v[i][j] = 0
while q:
    y, x = q.popleft()
    r = min(r, y, x, h - 1 - y, w - 1 - x)
    if v[y][x] == k:
        continue
    for i, j in ([1, 0], [-1, 0], [0, 1], [0, -1]):
        t, u = y + i, x + j
        if t >= 0 and t < h and u >= 0 and u < w and m[t][u] == "." and v[t][u] < 0:
            v[t][u] = v[y][x] + 1
            q.append([t, u])
print((1 - (-r // k)))

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

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

-    visited = [[-1] * w for _ in range(h)]

-            sy, sx = i, maze[i].index("S")

-            new_y, new_x = y + i, x + j

-            if new_y < 0 or new_y >= h or new_x < 0 or new_x >= w:

-            if maze[new_y][new_x] == "." and visited[new_y][new_x] == -1:

-                visited[new_y][new_x] = visited[y][x] + 1

-                queue.append([new_y, new_x])

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

+        if t >= 0 and t < h and u >= 0 and u < w and m[t][u] == "." and v[t][u] < 0:


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

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

m=c=0

for i in l:

  if m<=i:

    m=i

    c+=1

print(c)

_,*l=list(map(int,open(0).read().split()))

m=c=0

for i in l:

  if m<=i: m=i; c+=1

print(c)

n = int(eval(input()))
l = list(map(int, input().split()))
m = c = 0
for i in l:
    if m <= i:
        m = i
        c += 1
print(c)

_, *l = list(map(int, open(0).read().split()))
m = c = 0
for i in l:
    if m <= i:
        m = i
        c += 1
print(c)

+_, *l = list(map(int, open(0).read().split()))


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

count = 0

for i in range(26):

    for j in range(15):

        if 4 * i + 7 * j == n:

            count += 1

            break

        else:

            pass

if count == 0:

    print("No")

else:

    print("Yes")

n = int(eval(input()))

f = False

for i in range(26):

    for j in range(15):

        if 4 * i + 7 * j == n:

            f = True

            break

        else:

            pass

if f:

    print("Yes")

else:

    print("No")

-count = 0
+f = False
-            count += 1
+            f = True
-if count == 0:
+if f:
+    print("Yes")
+else:
-else:
-    print("Yes")


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

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

L.sort()

ans=0

from bisect import bisect_right

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

    li = L[i]

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

        lj = L[j]

        k = bisect_right(L, li-lj)

        ans += max(0, j-k)

print(ans)

from bisect import bisect_right

import sys

def main():

    input = sys.stdin.readline

    N = int(eval(input()))

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

    L.sort()

    ans = 0

    for i in range(2, N):

        for j in range(i):

            k = bisect_right(L, L[i] - L[j], j + 1, i)

            ans += i - k

    print(ans)

if __name__ == '__main__':

    main()

N = int(eval(input()))
(*L,) = list(map(int, input().split()))
L.sort()
ans = 0
from bisect import bisect_right

for i in range(N - 1, -1, -1):
    li = L[i]
    for j in range(i - 1, -1, -1):
        lj = L[j]
        k = bisect_right(L, li - lj)
        ans += max(0, j - k)
print(ans)

from bisect import bisect_right
import sys

def main():
    input = sys.stdin.readline
    N = int(eval(input()))
    (*L,) = list(map(int, input().split()))
    L.sort()
    ans = 0
    for i in range(2, N):
        for j in range(i):
            k = bisect_right(L, L[i] - L[j], j + 1, i)
            ans += i - k
    print(ans)

if __name__ == "__main__":
    main()

-(*L,) = list(map(int, input().split()))

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

+            k = bisect_right(L, L[i] - L[j], j + 1, i)


Input:
def solve():

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

    edges = [[] for _ in [0]*N]

    r_edges = [[] for _ in [0]*N]

    for _ in [0]*M:

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

        edges[a].append(b)

        r_edges[b].append(a)

    c = get_strongly_connected_components(edges, r_edges)

    group = [0]*N

    for i in range(len(c)):

        for v in c[i]:

            group[v] = i

    result = []

    append = result.append

    for _ in [0]*int(eval(input())):

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

        append("1" if group[a] == group[b] else "0")

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

def get_strongly_connected_components(edges, r_edges):

    import sys

    sys.setrecursionlimit(10**7)

    v_count = len(edges)

    order = [0]*v_count

    k = 1

    def get_order(v):

        order[v] = 1

        nonlocal k

        for dest in edges[v]:

            if order[dest] == 0:

                get_order(dest)

        order[v] = k

        k += 1

    def get_components(v):

        order[v] = 0

        return [v] + [_v for dest in r_edges[v] if order[dest] > 0 for _v in get_components(dest)]

    [None for v in range(v_count) if order[v] == 0 and get_order(v)]

    return [get_components(v) for v, _ in sorted(enumerate(order), key=lambda x: x[1], reverse=True) if order[v] > 0]

if __name__ == "__main__":

    solve()

def solve():

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

    edges = [[] for _ in [0]*N]

    r_edges = [[] for _ in [0]*N]

    for _ in [0]*M:

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

        edges[a].append(b)

        r_edges[b].append(a)

    c = get_strongly_connected_components(edges, r_edges)

    group = [0]*N

    for i in range(len(c)):

        for v in c[i]:

            group[v] = i

    result = []

    append = result.append

    for _ in [0]*int(eval(input())):

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

        append("1" if group[a] == group[b] else "0")

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

def get_strongly_connected_components(edges, r_edges):

    import sys

    sys.setrecursionlimit(10**7)

    v_count = len(edges)

    order = [0]*v_count

    k = [1]

    def get_order(v):

        order[v] = 1

        for dest in edges[v]:

            if order[dest] == 0:

                get_order(dest)

        order[v] = k[0]

        k[0] += 1

    def get_components(v):

        order[v] = 0

        return [v] + [_v for dest in r_edges[v] if order[dest] > 0 for _v in get_components(dest)]

    [None for v in range(v_count) if order[v] == 0 and get_order(v)]

    return [get_components(v) for v, _ in sorted(enumerate(order), key=lambda x: x[1], reverse=True) if order[v] > 0]

if __name__ == "__main__":

    solve()

def solve():
    N, M = list(map(int, input().split()))
    edges = [[] for _ in [0] * N]
    r_edges = [[] for _ in [0] * N]
    for _ in [0] * M:
        a, b = list(map(int, input().split()))
        edges[a].append(b)
        r_edges[b].append(a)
    c = get_strongly_connected_components(edges, r_edges)
    group = [0] * N
    for i in range(len(c)):
        for v in c[i]:
            group[v] = i
    result = []
    append = result.append
    for _ in [0] * int(eval(input())):
        a, b = list(map(int, input().split()))
        append("1" if group[a] == group[b] else "0")
    print(("\n".join(result)))

def get_strongly_connected_components(edges, r_edges):
    import sys

    sys.setrecursionlimit(10**7)
    v_count = len(edges)
    order = [0] * v_count
    k = 1

    def get_order(v):
        order[v] = 1
        nonlocal k
        for dest in edges[v]:
            if order[dest] == 0:
                get_order(dest)
        order[v] = k
        k += 1

    def get_components(v):
        order[v] = 0
        return [v] + [
            _v for dest in r_edges[v] if order[dest] > 0 for _v in get_components(dest)
        ]

    [None for v in range(v_count) if order[v] == 0 and get_order(v)]
    return [
        get_components(v)
        for v, _ in sorted(enumerate(order), key=lambda x: x[1], reverse=True)
        if order[v] > 0
    ]

if __name__ == "__main__":
    solve()

def solve():
    N, M = list(map(int, input().split()))
    edges = [[] for _ in [0] * N]
    r_edges = [[] for _ in [0] * N]
    for _ in [0] * M:
        a, b = list(map(int, input().split()))
        edges[a].append(b)
        r_edges[b].append(a)
    c = get_strongly_connected_components(edges, r_edges)
    group = [0] * N
    for i in range(len(c)):
        for v in c[i]:
            group[v] = i
    result = []
    append = result.append
    for _ in [0] * int(eval(input())):
        a, b = list(map(int, input().split()))
        append("1" if group[a] == group[b] else "0")
    print(("\n".join(result)))

def get_strongly_connected_components(edges, r_edges):
    import sys

    sys.setrecursionlimit(10**7)
    v_count = len(edges)
    order = [0] * v_count
    k = [1]

    def get_order(v):
        order[v] = 1
        for dest in edges[v]:
            if order[dest] == 0:
                get_order(dest)
        order[v] = k[0]
        k[0] += 1

    def get_components(v):
        order[v] = 0
        return [v] + [
            _v for dest in r_edges[v] if order[dest] > 0 for _v in get_components(dest)
        ]

    [None for v in range(v_count) if order[v] == 0 and get_order(v)]
    return [
        get_components(v)
        for v, _ in sorted(enumerate(order), key=lambda x: x[1], reverse=True)
        if order[v] > 0
    ]

if __name__ == "__main__":
    solve()


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

ans=[[] for i in range(m)]

p_list=[[] for i in range(n+1)]

for i in range(m):

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

 ans[i]=str(p).zfill(6)

 p_list[p].append([i,y])

for pp in p_list:

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

 num=0

 for ppp in pp:

  num+=1

  ans[ppp[0]]+=str(num).zfill(6)

 num=0

for i in ans:

 print(i)

from sys import stdin

nii=lambda:list(map(int,stdin.readline().split()))

lnii=lambda:list(map(int,stdin.readline()).split())

n,m=nii()

list=[[] for i in range(n+1)]

for i in range(m):

  p,y=nii()

  list[p].append([y,i])

ans=[]

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

  tl=list[i]

  s_tl=sorted(tl,key=lambda x:x[0])

  for j in range(len(tl)):

    town=s_tl[j][1]

    s1=str(i).zfill(6)

    s2=str(j+1).zfill(6)

    s=s1+s2

    ans.append([town,s])

ans.sort(key=lambda x:x[0])

for i,j in ans:

  print(j)

n, m = list(map(int, input().split()))
ans = [[] for i in range(m)]
p_list = [[] for i in range(n + 1)]
for i in range(m):
    p, y = list(map(int, input().split()))
    ans[i] = str(p).zfill(6)
    p_list[p].append([i, y])
for pp in p_list:
    pp = sorted(pp, key=lambda x: x[1])
    num = 0
    for ppp in pp:
        num += 1
        ans[ppp[0]] += str(num).zfill(6)
    num = 0
for i in ans:
    print(i)

from sys import stdin

nii = lambda: list(map(int, stdin.readline().split()))
lnii = lambda: list(map(int, stdin.readline()).split())
n, m = nii()
list = [[] for i in range(n + 1)]
for i in range(m):
    p, y = nii()
    list[p].append([y, i])
ans = []
for i in range(1, n + 1):
    tl = list[i]
    s_tl = sorted(tl, key=lambda x: x[0])
    for j in range(len(tl)):
        town = s_tl[j][1]
        s1 = str(i).zfill(6)
        s2 = str(j + 1).zfill(6)
        s = s1 + s2
        ans.append([town, s])
ans.sort(key=lambda x: x[0])
for i, j in ans:
    print(j)

+nii = lambda: list(map(int, stdin.readline().split()))

+lnii = lambda: list(map(int, stdin.readline()).split())

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

-    pp = sorted(pp, key=lambda x: x[1])

-        ans[ppp[0]] += str(num).zfill(6)

+    s_tl = sorted(tl, key=lambda x: x[0])


Input:
import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy, functools, random

import sys

from collections import deque, defaultdict, Counter; from heapq import heappush, heappop

from itertools import permutations, combinations, product, accumulate, groupby

from bisect import bisect_left, bisect_right, insort_left, insort_right

from operator import itemgetter as ig

sys.setrecursionlimit(10 ** 7)

inf = 10 ** 20; INF = float("INF"); ans = 0; tmp = 0; ansli = []; tmpli = []; candili = []

eps = 1.0 / 10 ** 10; mod = 10 ** 9 + 7

dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]; ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]; ddn9 = ddn + [(0, 0)]

"""for dx, dy in dd:

        nx = j + dx; ny = i + dy

            if 0 <= nx < w and 0 <= ny < h:"""

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

def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]#WideIntPoint

def ws(): return sys.stdin.readline().split()

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

def s(): return eval(input())

def hi(n): return [i() for _ in range(n)]

def hs(n): return [s() for _ in range(n)]#HeightString

def mi(n): return [wi() for _ in range(n)]#MatrixInt

def mip(n): return [wip() for _ in range(n)]

def ms(n): return [ws() for _ in range(n)]

W, H, x, y = wi()

ans = (H * W) / 2

if x == W / 2 and y == H / 2:

    print((ans, 1))

else:

    print((ans, 0))

import sys

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

W, H, x, y = wi()

ans = (H * W) / 2

if x == W / 2 and y == H / 2:

    print((ans, 1))

else:

    print((ans, 0))

import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy, functools, random
import sys
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
from itertools import permutations, combinations, product, accumulate, groupby
from bisect import bisect_left, bisect_right, insort_left, insort_right
from operator import itemgetter as ig

sys.setrecursionlimit(10**7)
inf = 10**20
INF = float("INF")
ans = 0
tmp = 0
ansli = []
tmpli = []
candili = []
eps = 1.0 / 10**10
mod = 10**9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]
ddn9 = ddn + [(0, 0)]
"""for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:"""

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

def wip():
    return [int(x) - 1 for x in sys.stdin.readline().split()]  # WideIntPoint

def ws():
    return sys.stdin.readline().split()

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

def s():
    return eval(input())

def hi(n):
    return [i() for _ in range(n)]

def hs(n):
    return [s() for _ in range(n)]  # HeightString

def mi(n):
    return [wi() for _ in range(n)]  # MatrixInt

def mip(n):
    return [wip() for _ in range(n)]

def ms(n):
    return [ws() for _ in range(n)]

W, H, x, y = wi()
ans = (H * W) / 2
if x == W / 2 and y == H / 2:
    print((ans, 1))
else:
    print((ans, 0))

-import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy, functools, random

-from collections import deque, defaultdict, Counter

-from itertools import permutations, combinations, product, accumulate, groupby

-from bisect import bisect_left, bisect_right, insort_left, insort_right

-    return [int(x) - 1 for x in sys.stdin.readline().split()]  # WideIntPoint

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

-    return [s() for _ in range(n)]  # HeightString

-    return [wi() for _ in range(n)]  # MatrixInt


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

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

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

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

for edge in edges:

    graph[edge[0]].append(edge[1])

    graph[edge[1]].append(edge[0])

ans = []

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

    can = graph[i]

    hights = []

    for j in can:

        hights.append(H[j-1])

    if len(hights) == 0:

        ans.append(i)

    else:

        h = max(hights)

        if H[i-1] > h:

            ans.append(i)

print((len(set(ans))))

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

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

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

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

for edge in edges:

    graph[edge[0]].append(edge[1])

    graph[edge[1]].append(edge[0])

ans = 0

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

    highest = True

    for j in graph[i]:

        if H[i-1] <= H[j-1]:

            highest = False

    if highest:

        ans += 1

print(ans)

N, M = list(map(int, input().split()))
H = list(map(int, input().split()))
edges = [list(map(int, input().split())) for _ in range(M)]
graph = [[] for _ in range(N + 1)]
for edge in edges:
    graph[edge[0]].append(edge[1])
    graph[edge[1]].append(edge[0])
ans = []
for i in range(1, N + 1):
    can = graph[i]
    hights = []
    for j in can:
        hights.append(H[j - 1])
    if len(hights) == 0:
        ans.append(i)
    else:
        h = max(hights)
        if H[i - 1] > h:
            ans.append(i)
print((len(set(ans))))

N, M = list(map(int, input().split()))
H = list(map(int, input().split()))
edges = [list(map(int, input().split())) for _ in range(M)]
graph = [[] for _ in range(N + 1)]
for edge in edges:
    graph[edge[0]].append(edge[1])
    graph[edge[1]].append(edge[0])
ans = 0
for i in range(1, N + 1):
    highest = True
    for j in graph[i]:
        if H[i - 1] <= H[j - 1]:
            highest = False
    if highest:
        ans += 1
print(ans)

-ans = []
+ans = 0
-    can = graph[i]
-    hights = []
-    for j in can:
-        hights.append(H[j - 1])
-    if len(hights) == 0:
-        ans.append(i)
-    else:
-        h = max(hights)
-        if H[i - 1] > h:
-            ans.append(i)
-print((len(set(ans))))
+    highest = True
+    for j in graph[i]:
+        if H[i - 1] <= H[j - 1]:
+            highest = False
+    if highest:
+        ans += 1
+print(ans)


Input:
from collections import Counter,defaultdict,deque

from heapq import heappop,heappush,heapify

import sys,bisect,math,itertools,fractions,pprint

sys.setrecursionlimit(10**8)

mod = 10**9+7

INF = float('inf')

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

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

class Combination:

    """

    comb = Combination(1000000)

    print(comb(5, 3))  # 10

    """

    def __init__(self, n_max, mod=10**9+7):

        self.mod = mod

        self.modinv = self.make_modinv_list(n_max)

        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):

        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):

        # 階乗のリストと階乗のmod逆元のリストを返す O(n)

        # self.make_modinv_list()が先に実行されている必要がある

        fac = [1]

        facinv = [1]

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

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

            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)

        return fac, facinv

    def make_modinv_list(self, n):

        # 0からnまでのmod逆元のリストを返す O(n)

        modinv = [0] * (n+1)

        modinv[1] = 1

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

            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod

        return modinv

n,k = inpl()

a = sorted(inpl())

res = 0

comb = Combination(10**5+10)

for i in range(n):

    if n-i-1 < k-1: continue

    p = comb(n-i-1,k-1)

    res -= a[i] * p

    res += a[-1-i] * p

    res %= mod

print(res)

from collections import Counter,defaultdict,deque

from heapq import heappop,heappush

from bisect import bisect_left,bisect_right

import sys,math,itertools,fractions

sys.setrecursionlimit(10**8)

mod = 10**9+7

INF = float('inf')

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

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

class Combination:

    """

    comb = Combination(1000000)

    print(comb(5, 3))  # 10

    """

    def __init__(self, n_max, mod=10**9+7):

        self.mod = mod

        self.modinv = self.make_modinv_list(n_max)

        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):

        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):

        # 階乗のリストと階乗のmod逆元のリストを返す O(n)

        # self.make_modinv_list()が先に実行されている必要がある

        fac = [1]

        facinv = [1]

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

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

            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)

        return fac, facinv

    def make_modinv_list(self, n):

        # 0からnまでのmod逆元のリストを返す O(n)

        modinv = [0] * (n+1)

        modinv[1] = 1

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

            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod

        return modinv

comb = Combination(100010)

n,k = inpl()

a = inpl()

a.sort()

mx = 0

for i in range(n):

    if n-i-1 < k-1: continue

    tmp = comb(n-i-1,k-1)

    # print(tmp)

    mx += tmp*a[-i-1] - tmp*a[i]

    mx %= mod

print(mx)

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

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

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

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

class Combination:
    """
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """

    def __init__(self, n_max, mod=10**9 + 7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n - r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n + 1):
            fac.append(fac[i - 1] * i % self.mod)
            facinv.append(facinv[i - 1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n + 1)
        modinv[1] = 1
        for i in range(2, n + 1):
            modinv[i] = self.mod - self.mod // i * modinv[self.mod % i] % self.mod
        return modinv

n, k = inpl()
a = sorted(inpl())
res = 0
comb = Combination(10**5 + 10)
for i in range(n):
    if n - i - 1 < k - 1:
        continue
    p = comb(n - i - 1, k - 1)
    res -= a[i] * p
    res += a[-1 - i] * p
    res %= mod
print(res)

from collections import Counter, defaultdict, deque
from heapq import heappop, heappush
from bisect import bisect_left, bisect_right
import sys, math, itertools, fractions

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

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

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

class Combination:
    """
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """

    def __init__(self, n_max, mod=10**9 + 7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n - r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n + 1):
            fac.append(fac[i - 1] * i % self.mod)
            facinv.append(facinv[i - 1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n + 1)
        modinv[1] = 1
        for i in range(2, n + 1):
            modinv[i] = self.mod - self.mod // i * modinv[self.mod % i] % self.mod
        return modinv

comb = Combination(100010)
n, k = inpl()
a = inpl()
a.sort()
mx = 0
for i in range(n):
    if n - i - 1 < k - 1:
        continue
    tmp = comb(n - i - 1, k - 1)
    # print(tmp)
    mx += tmp * a[-i - 1] - tmp * a[i]
    mx %= mod
print(mx)

-from heapq import heappop, heappush, heapify

-import sys, bisect, math, itertools, fractions, pprint

+from bisect import bisect_left, bisect_right


Input:
s = eval(input())

start = min(i for i, x in enumerate(s) if x == 'A')

end = max(j for j, y in enumerate(s) if y == 'Z')

print((end-start+1))

s = eval(input())

a = s.find('A')

#print(a)

z = 0

for i in range(len(s)):

  if s[i] == 'Z':

    z = i

#print(z)

print((z-a+1))

s = eval(input())
start = min(i for i, x in enumerate(s) if x == "A")
end = max(j for j, y in enumerate(s) if y == "Z")
print((end - start + 1))

s = eval(input())
a = s.find("A")
# print(a)
z = 0
for i in range(len(s)):
    if s[i] == "Z":
        z = i
# print(z)
print((z - a + 1))

-start = min(i for i, x in enumerate(s) if x == "A")

-end = max(j for j, y in enumerate(s) if y == "Z")


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

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

xbet=sorted([abs(x[i+1]-x[i]) for i in range(m-1)],reverse=True)

y=sum(xbet)

if n>=m:

    print((0))

else:

    print((y-sum(xbet[:n-1])))

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

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

x.sort()

y=[x[i]-x[i-1] for i in range(1,m)]

y.sort()

print((0 if n>=m else sum(y[:(m-n)])))

n, m = list(map(int, input().split()))
x = sorted([int(i) for i in input().split()])
xbet = sorted([abs(x[i + 1] - x[i]) for i in range(m - 1)], reverse=True)
y = sum(xbet)
if n >= m:
    print((0))
else:
    print((y - sum(xbet[: n - 1])))

n, m = list(map(int, input().split()))
x = list(map(int, input().split()))
x.sort()
y = [x[i] - x[i - 1] for i in range(1, m)]
y.sort()
print((0 if n >= m else sum(y[: (m - n)])))

-x = sorted([int(i) for i in input().split()])

-xbet = sorted([abs(x[i + 1] - x[i]) for i in range(m - 1)], reverse=True)

+y = [x[i] - x[i - 1] for i in range(1, m)]

+print((0 if n >= m else sum(y[: (m - n)])))


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

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

MAX_N = max(A)+1

cnt = [0] * MAX_N

for a in A:

  for i in range(a, MAX_N, a):

    if cnt[i] <= 2: cnt[i] += 1

ans = 0

for a in A:

  if cnt[a] == 1: ans += 1

print(ans)

def main():

  ## IMPORT MODULE

  #import sys

  #sys.setrecursionlimit(100000)

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

  #f_inf=float("inf")

  #MOD=10**9+7

  if 'get_ipython' in globals():

    ## SAMPLE INPUT

    n = 5

    A = [24, 11, 8, 3, 16]

  else:

    ##INPUT

    n = int(eval(input()))

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

  ## SUBMITION CODES HERE

  MAX_N = max(A)+1

  cnt = [0] * MAX_N

  for a in A:

    for i in range(a, MAX_N, a):

      if cnt[i] <= 2: cnt[i] += 1

  ans = 0

  for a in A:

    if cnt[a] == 1: ans += 1

  print(ans)

main()

n = int(eval(input()))
A = list(map(int, input().split()))
MAX_N = max(A) + 1
cnt = [0] * MAX_N
for a in A:
    for i in range(a, MAX_N, a):
        if cnt[i] <= 2:
            cnt[i] += 1
ans = 0
for a in A:
    if cnt[a] == 1:
        ans += 1
print(ans)

def main():
    ## IMPORT MODULE
    # import sys
    # sys.setrecursionlimit(100000)
    # input=lambda :sys.stdin.readline().rstrip()
    # f_inf=float("inf")
    # MOD=10**9+7
    if "get_ipython" in globals():
        ## SAMPLE INPUT
        n = 5
        A = [24, 11, 8, 3, 16]
    else:
        ##INPUT
        n = int(eval(input()))
        A = list(map(int, input().split()))
    ## SUBMITION CODES HERE
    MAX_N = max(A) + 1
    cnt = [0] * MAX_N
    for a in A:
        for i in range(a, MAX_N, a):
            if cnt[i] <= 2:
                cnt[i] += 1
    ans = 0
    for a in A:
        if cnt[a] == 1:
            ans += 1
    print(ans)

main()

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

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


Input:
def divide(n, p):

    c = 0

    while n%p == 0 and c < 18:

        c += 1

        n //= p

    return c

n = int(eval(input()))

table = [[0]*19 for _ in range(19)]

for i in range(n):

    sub = eval(input())

    key = float(sub)

    if "." in sub:

        a, b = list(map(str, sub.split(".")))

        s = int(a)*1000000000+10**(9-len(b))*int(b)

    else:

        s = int(sub)

        s *= 1000000000

    if key != s/1000000000:

        while True:

            pass

    c2, c5 = divide(s, 2), divide(s, 5)

    table[c2][c5] += 1

ans = 0

for i in range(19):

    for j in range(19):

        for k in range(19):

            for l in range(19):

                if i+k < 18 or j+l < 18:

                    continue;

                if i == k and j == l:

                    ans += table[i][j]*(table[k][l]-1)

                else:

                    ans += table[i][j]*table[k][l]

ans //= 2

print(ans)

import sys

input = sys.stdin.readline

def divide(n):

    c1, c2 = 0, 0

    while (n%2 == 0):

        c1 += 1

        n //= 2

    while (n%5 == 0):

        c2 += 1

        n //= 5

    return (c1, c2)

def main():

    n = int(eval(input()))

    a = [None]*n

    for i in range(n):

        sub = input().replace("\n", "")

        if "." in sub:

            x, y = list(map(str, sub.split(".")))

            s = int(x)*1000000000+10**(9-len(y))*int(y)

        else:

            s = int(sub)

            s *= 1000000000

        a[i] = divide(s)

    dp = [[0]*100 for _ in range(100)]

    for i in range(n):

        c1, c2 = a[i]

        dp[c1][c2] += 1

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

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

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

    ans = 0

    for i in range(n):

        c1, c2 = a[i]

        if (c1 >= 9 and c2 >= 9):

            ans -= 1

        if c1 >= 18 and c2 >= 18:

            ans += dp[0][0]

            continue

        if c1 >= 18:

            ans += dp[0][18-c2]

            continue

        if c2 >= 18:

            ans += dp[18-c1][0]

            continue

        ans += dp[18-c1][18-c2]

    print((ans//2))

if __name__ == "__main__":

    main()

def divide(n, p):
    c = 0
    while n % p == 0 and c < 18:
        c += 1
        n //= p
    return c

n = int(eval(input()))
table = [[0] * 19 for _ in range(19)]
for i in range(n):
    sub = eval(input())
    key = float(sub)
    if "." in sub:
        a, b = list(map(str, sub.split(".")))
        s = int(a) * 1000000000 + 10 ** (9 - len(b)) * int(b)
    else:
        s = int(sub)
        s *= 1000000000
    if key != s / 1000000000:
        while True:
            pass
    c2, c5 = divide(s, 2), divide(s, 5)
    table[c2][c5] += 1
ans = 0
for i in range(19):
    for j in range(19):
        for k in range(19):
            for l in range(19):
                if i + k < 18 or j + l < 18:
                    continue
                if i == k and j == l:
                    ans += table[i][j] * (table[k][l] - 1)
                else:
                    ans += table[i][j] * table[k][l]
ans //= 2
print(ans)

import sys

input = sys.stdin.readline

def divide(n):
    c1, c2 = 0, 0
    while n % 2 == 0:
        c1 += 1
        n //= 2
    while n % 5 == 0:
        c2 += 1
        n //= 5
    return (c1, c2)

def main():
    n = int(eval(input()))
    a = [None] * n
    for i in range(n):
        sub = input().replace("\n", "")
        if "." in sub:
            x, y = list(map(str, sub.split(".")))
            s = int(x) * 1000000000 + 10 ** (9 - len(y)) * int(y)
        else:
            s = int(sub)
            s *= 1000000000
        a[i] = divide(s)
    dp = [[0] * 100 for _ in range(100)]
    for i in range(n):
        c1, c2 = a[i]
        dp[c1][c2] += 1
    for i in range(98, -1, -1):
        for j in range(98, -1, -1):
            dp[i][j] += dp[i + 1][j] + dp[i][j + 1] - dp[i + 1][j + 1]
    ans = 0
    for i in range(n):
        c1, c2 = a[i]
        if c1 >= 9 and c2 >= 9:
            ans -= 1
        if c1 >= 18 and c2 >= 18:
            ans += dp[0][0]
            continue
        if c1 >= 18:
            ans += dp[0][18 - c2]
            continue
        if c2 >= 18:
            ans += dp[18 - c1][0]
            continue
        ans += dp[18 - c1][18 - c2]
    print((ans // 2))

if __name__ == "__main__":
    main()

-        a, b = list(map(str, sub.split(".")))

-    c2, c5 = divide(s, 2), divide(s, 5)

-                    ans += table[i][j] * (table[k][l] - 1)

-                    ans += table[i][j] * table[k][l]

+        sub = input().replace("\n", "")

+            x, y = list(map(str, sub.split(".")))


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

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

ans=0

for i in range(N):

    t,x,y=txy[i][0],txy[i][1],txy[i][2]

    if x+y<=t and t%2==(x+y)%2:ans+=1

print(("Yes" if ans==N else "No"))

n = int(eval(input()))

for _ in range(n):

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

    if  x + y > t or (t - x - y) % 2:

        print("No")

        exit()

print("Yes")

N = int(eval(input()))
txy = [list(map(int, input().split())) for i in range(N)]
ans = 0
for i in range(N):
    t, x, y = txy[i][0], txy[i][1], txy[i][2]
    if x + y <= t and t % 2 == (x + y) % 2:
        ans += 1
print(("Yes" if ans == N else "No"))

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

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


Input:
import sys

input = sys.stdin.readline

N = int(eval(input()))

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

Ed = {}

for i in range(N-1):

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

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

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

    Ed[(a-1)*N+b-1] = i

    Ed[(b-1)*N+a-1] = i

q = [0]

checked = [False]*N

checked[0] = True

V_color = [None]*N

V_color[0] = 0

ans = [None]*(N-1)

while q:

    qq = []

    for p in q:

        c = V_color[p]

        t = 1

        for np in graph[p]:

            if not checked[np]:

                checked[np] = True

                qq.append(np)

                ind = Ed[p*N+np]

                if t == c:

                    t += 1

                ans[ind] = t

                V_color[np] = t

                t += 1

    q = qq

print((max(ans)))

for a in ans:

    print(a)

import sys

input = sys.stdin.readline

N = int(eval(input()))

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

Edges = []

for _ in range(N-1):

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

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

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

    Edges.append((a-1, b-1))

Col = 0

for n in range(N):

    Col = max(Col, len(graph[n]))

Color = dict()

checked = [-1]*N

q = [0]

checked[0] = Col+1

while q:

    qq = []

    for p in q:

        c = checked[p]

        t = 0

        for np in graph[p]:

            if checked[np] == -1:

                if t == c:

                    t += 1

                checked[np] = t

                Color[(p, np)] = t

                Color[(np, p)] = t

                t += 1

                qq.append(np)

    q = qq

print(Col)

for a, b in Edges:

    print((Color[(a, b)]+1))

import sys

input = sys.stdin.readline
N = int(eval(input()))
graph = [[] for _ in range(N)]
Ed = {}
for i in range(N - 1):
    a, b = list(map(int, input().split()))
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
    Ed[(a - 1) * N + b - 1] = i
    Ed[(b - 1) * N + a - 1] = i
q = [0]
checked = [False] * N
checked[0] = True
V_color = [None] * N
V_color[0] = 0
ans = [None] * (N - 1)
while q:
    qq = []
    for p in q:
        c = V_color[p]
        t = 1
        for np in graph[p]:
            if not checked[np]:
                checked[np] = True
                qq.append(np)
                ind = Ed[p * N + np]
                if t == c:
                    t += 1
                ans[ind] = t
                V_color[np] = t
                t += 1
    q = qq
print((max(ans)))
for a in ans:
    print(a)

import sys

input = sys.stdin.readline
N = int(eval(input()))
graph = [[] for _ in range(N)]
Edges = []
for _ in range(N - 1):
    a, b = list(map(int, input().split()))
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
    Edges.append((a - 1, b - 1))
Col = 0
for n in range(N):
    Col = max(Col, len(graph[n]))
Color = dict()
checked = [-1] * N
q = [0]
checked[0] = Col + 1
while q:
    qq = []
    for p in q:
        c = checked[p]
        t = 0
        for np in graph[p]:
            if checked[np] == -1:
                if t == c:
                    t += 1
                checked[np] = t
                Color[(p, np)] = t
                Color[(np, p)] = t
                t += 1
                qq.append(np)
    q = qq
print(Col)
for a, b in Edges:
    print((Color[(a, b)] + 1))

-Ed = {}
-for i in range(N - 1):
+Edges = []
+for _ in range(N - 1):
-    Ed[(a - 1) * N + b - 1] = i
-    Ed[(b - 1) * N + a - 1] = i
+    Edges.append((a - 1, b - 1))
+Col = 0
+for n in range(N):
+    Col = max(Col, len(graph[n]))
+Color = dict()
+checked = [-1] * N
-checked = [False] * N
-checked[0] = True
-V_color = [None] * N
-V_color[0] = 0
-ans = [None] * (N - 1)
+checked[0] = Col + 1
-        c = V_color[p]
-        t = 1
+        c = checked[p]
+        t = 0
-            if not checked[np]:
-                checked[np] = True
-                qq.append(np)
-                ind = Ed[p * N + np]
+            if checked[np] == -1:
-                ans[ind] = t
-                V_color[np] = t
+                checked[np] = t
+                Color[(p, np)] = t
+                Color[(np, p)] = t
+                qq.append(np)
-print((max(ans)))
-for a in ans:
-    print(a)
+print(Col)
+for a, b in Edges:
+    print((Color[(a, b)] + 1))


Input:
n=int(input())

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

d=[None]*n

for x,i in enumerate(a):

    d[i-1]=x+1

for i in d:

    print(i,end=" ")

n=int(eval(input()))

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

l=[0]*n

for x,i in enumerate(a):

    l[i-1]=x+1

print((*l))

n = int(input())
a = list(map(int, input().split()))
d = [None] * n
for x, i in enumerate(a):
    d[i - 1] = x + 1
for i in d:
    print(i, end=" ")

n = int(eval(input()))
a = list(map(int, input().split()))
l = [0] * n
for x, i in enumerate(a):
    l[i - 1] = x + 1
print((*l))

-n = int(input())
+n = int(eval(input()))
-d = [None] * n
+l = [0] * n
-    d[i - 1] = x + 1
-for i in d:
-    print(i, end=" ")
+    l[i - 1] = x + 1
+print((*l))


Input:
def main():

    import sys

    sys.setrecursionlimit(1000000)

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

    p = []

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

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

        for j, k in enumerate(l, 1):

            p.append((k, (i, j)))

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

    q = int(eval(input()))

    dist = [0] * (w * h + 1)

    def Q(i, c, x, y):

        if i + d > w * h:

            return

        _, (nx, ny) = p[i + d - 1]

        nc = c + abs(nx - x) + abs(ny - y)

        dist[i + d] = nc

        Q(i + d, nc, nx, ny)

    for i in range(d):

        n, (x, y) = p[i]

        Q(n, 0, x, y)

    res = []

    for _ in range(q):

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

        res.append(dist[r] - dist[l])

    ans = '\n'.join(map(str, res))

    print(ans)

if __name__ == '__main__':

    main()

def main():

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

    a = [None] * (h * w + 1)

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

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

        for j, k in enumerate(l, 1):

            a[k] = (i, j)

    c = [0] * (h * w + 1)

    for i in range(d + 1, h * w + 1):

        xb, yb = a[i-d]

        xn, yn = a[i]

        c[i] = c[i - d] + abs(xn - xb) + abs(yn - yb)

    q = int(eval(input()))

    res = []

    for _ in range(q):

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

        res.append(c[r] - c[l])

    ans = '\n'.join(map(str, res))

    print(ans)

if __name__ == '__main__':

    main()

def main():
    import sys

    sys.setrecursionlimit(1000000)
    h, w, d = list(map(int, input().split()))
    p = []
    for i in range(1, h + 1):
        l = list(map(int, input().split()))
        for j, k in enumerate(l, 1):
            p.append((k, (i, j)))
    p.sort(key=lambda x: x[0])
    q = int(eval(input()))
    dist = [0] * (w * h + 1)

    def Q(i, c, x, y):
        if i + d > w * h:
            return
        _, (nx, ny) = p[i + d - 1]
        nc = c + abs(nx - x) + abs(ny - y)
        dist[i + d] = nc
        Q(i + d, nc, nx, ny)

    for i in range(d):
        n, (x, y) = p[i]
        Q(n, 0, x, y)
    res = []
    for _ in range(q):
        l, r = list(map(int, input().split()))
        res.append(dist[r] - dist[l])
    ans = "\n".join(map(str, res))
    print(ans)

if __name__ == "__main__":
    main()

def main():
    h, w, d = list(map(int, input().split()))
    a = [None] * (h * w + 1)
    for i in range(1, h + 1):
        l = list(map(int, input().split()))
        for j, k in enumerate(l, 1):
            a[k] = (i, j)
    c = [0] * (h * w + 1)
    for i in range(d + 1, h * w + 1):
        xb, yb = a[i - d]
        xn, yn = a[i]
        c[i] = c[i - d] + abs(xn - xb) + abs(yn - yb)
    q = int(eval(input()))
    res = []
    for _ in range(q):
        l, r = list(map(int, input().split()))
        res.append(c[r] - c[l])
    ans = "\n".join(map(str, res))
    print(ans)

if __name__ == "__main__":
    main()

+        c[i] = c[i - d] + abs(xn - xb) + abs(yn - yb)

-        nc = c + abs(nx - x) + abs(ny - y)


Input:
import sys

from heapq import heappush,heapify,heappop

input = sys.stdin.readline

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

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

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

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

d = [i + j for i in a for j in b]

d.sort(reverse=1)

c.sort(reverse=1)

q = [(-d[0] - c[0], 0, 0)]

for _ in range(k):

    v, s, t = heappop(q)

    print((-v))

    if t + 1 < z:

        heappush(q, (-d[s] - c[t + 1], s, t + 1))

    if t == 0 and s + 1 < x * y:

        heappush(q, (-d[s + 1] - c[0], s + 1, 0))

# O(klog(k))解法 多分...

import sys

from heapq import heappush,heapify,heappop

input = sys.stdin.readline

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

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

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

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

def make_kth(A, B):

    n, m = len(A), len(B)

    A.sort(reverse=1)

    B.sort(reverse=1)

    q = [(-A[0] - B[0], 0, 0)]

    r=[]

    for _ in range(min(k, n * m)):

        v, s, t = heappop(q)

        r.append(-v)

        if t + 1 < m:

            heappush(q, (-A[s] - B[t + 1], s, t + 1))

        if t == 0 and s + 1 < n:

            heappush(q, (-A[s + 1] - B[0], s + 1, 0))

    return r

r = make_kth(a, b)

r = make_kth(c, r)

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

import sys
from heapq import heappush, heapify, heappop

input = sys.stdin.readline
x, y, z, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
d = [i + j for i in a for j in b]
d.sort(reverse=1)
c.sort(reverse=1)
q = [(-d[0] - c[0], 0, 0)]
for _ in range(k):
    v, s, t = heappop(q)
    print((-v))
    if t + 1 < z:
        heappush(q, (-d[s] - c[t + 1], s, t + 1))
    if t == 0 and s + 1 < x * y:
        heappush(q, (-d[s + 1] - c[0], s + 1, 0))

# O(klog(k))解法 多分...
import sys
from heapq import heappush, heapify, heappop

input = sys.stdin.readline
x, y, z, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))

def make_kth(A, B):
    n, m = len(A), len(B)
    A.sort(reverse=1)
    B.sort(reverse=1)
    q = [(-A[0] - B[0], 0, 0)]
    r = []
    for _ in range(min(k, n * m)):
        v, s, t = heappop(q)
        r.append(-v)
        if t + 1 < m:
            heappush(q, (-A[s] - B[t + 1], s, t + 1))
        if t == 0 and s + 1 < n:
            heappush(q, (-A[s + 1] - B[0], s + 1, 0))
    return r

r = make_kth(a, b)
r = make_kth(c, r)
print(*r, sep="\n")

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


Input:
# coding: utf-8

# Your code here!

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

dp=[[-1]*301 for i in range(N+1)]

dp[0][0]=0

for i in range(N):

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

    if i==0:

        base=w

    for i in range(N)[::-1]:

        for j in range(301)[::-1]:

            if dp[i][j]!=-1:

                dp[i+1][j+w-base]=max(dp[i][j]+v,dp[i+1][j+w-base])

ans=0

for index,item in enumerate(dp):

    if W-index*base+1<=0:

        break

    ans=max(max(item[:W-index*base+1]),ans)

    #print(item[:W-index*base+1])

print(ans)

# coding: utf-8

# Your code here!

def saiki(value,HP,num):

    if num==0:

        #print(HP//base)

        value+=wa[0][min(HP//base,len(wa[0])-1)]

        ans.append(value)

    else:

        for i in range(len(wa[num])):

            if HP-(num+base)*i>=0:

                saiki(value+wa[num][i],HP-(num+base)*i,num-1)

            else:

                break

    return

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

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

for i in range(N):

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

    if i==0:

        base=w

    lis[w-base].append(v)

lis=list([sorted(x, reverse=True) for x in lis])

wa=[[0] for i in range(4)]

for i in range(len(wa)):

    for item in lis[i]:

        wa[i].append(wa[i][-1]+item)

#print(wa)

ans=[]

saiki(0,W,3)

print((max(ans)))

# coding: utf-8
# Your code here!
N, W = list(map(int, input().split()))
dp = [[-1] * 301 for i in range(N + 1)]
dp[0][0] = 0
for i in range(N):
    w, v = list(map(int, input().split()))
    if i == 0:
        base = w
    for i in range(N)[::-1]:
        for j in range(301)[::-1]:
            if dp[i][j] != -1:
                dp[i + 1][j + w - base] = max(dp[i][j] + v, dp[i + 1][j + w - base])
ans = 0
for index, item in enumerate(dp):
    if W - index * base + 1 <= 0:
        break
    ans = max(max(item[: W - index * base + 1]), ans)
    # print(item[:W-index*base+1])
print(ans)

# coding: utf-8
# Your code here!
def saiki(value, HP, num):
    if num == 0:
        # print(HP//base)
        value += wa[0][min(HP // base, len(wa[0]) - 1)]
        ans.append(value)
    else:
        for i in range(len(wa[num])):
            if HP - (num + base) * i >= 0:
                saiki(value + wa[num][i], HP - (num + base) * i, num - 1)
            else:
                break
    return

N, W = list(map(int, input().split()))
lis = [[] for i in range(4)]
for i in range(N):
    w, v = list(map(int, input().split()))
    if i == 0:
        base = w
    lis[w - base].append(v)
lis = list([sorted(x, reverse=True) for x in lis])
wa = [[0] for i in range(4)]
for i in range(len(wa)):
    for item in lis[i]:
        wa[i].append(wa[i][-1] + item)
# print(wa)
ans = []
saiki(0, W, 3)
print((max(ans)))

+        value += wa[0][min(HP // base, len(wa[0]) - 1)]

+            if HP - (num + base) * i >= 0:

+                saiki(value + wa[num][i], HP - (num + base) * i, num - 1)

-                dp[i + 1][j + w - base] = max(dp[i][j] + v, dp[i + 1][j + w - base])

-    ans = max(max(item[: W - index * base + 1]), ans)

+lis = list([sorted(x, reverse=True) for x in lis])