Input:
class UnionFind:

    def __init__(self, n):

        self.v = [-1 for _ in range(n)]  # 根(負): 連結頂点数 * (-1) / 子(正): 根の頂点番号(0-indexed)

    def find(self, x):  # xを含む木における根の頂点番号を返す

        if self.v[x] < 0:  # (負)は根

            return x

        else:  # 根の頂点番号

            self.v[x] = self.find(self.v[x])  # uniteでは, 旧根に属する頂点の根が旧根のままなので更新

            return self.v[x]

    def unite(self, x, y):  # 違う根に属していたらrankが低くなるように連結

        x = self.find(x)

        y = self.find(y)

        if x == y:

            return

        if -self.v[x] < -self.v[y]:  # size比較, 　(-1) * (連結頂点数 * (-1)), (正)同士の大小比較

            x, y = y, x  # 連結頂点数が少ない方をyにすると, findでの更新回数が減る？

        self.v[x] += self.v[y]  # 連結頂点数の和を取る, 連結頂点数 * (-1)

        self.v[y] = x  # 連結頂点数が少ないy(引数yの根の頂点番号)の根をx(引数xの根の頂点番号)にする

    def root(self, x):

        return self.v[x] < 0  # (負)は根

    def same(self, x, y):

        return self.find(x) == self.find(y)  # 同じ根に属するか

    def size(self, x):

        return -self.v[self.find(x)]  # 連結頂点数を返す

import sys

input = sys.stdin.readline

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

s = tuple(eval(input()) for _ in range(H))

uf_r = UnionFind(H * W)

for r in range(H - 1):

    for c in range(W):

        if s[r][c] == '.' and s[r + 1][c] == '.':

            uf_r.unite(r * W + c, (r + 1) * W + c)

uf_c = UnionFind(H * W)

for c in range(W - 1):

    for r in range(H):

        if s[r][c] == '.' and s[r][c + 1] == '.':

            uf_c.unite(r * W + c, r * W + (c + 1))

ans = 0

for r in range(H):

    for c in range(W):

        if s[r][c] == '#': continue

        t = uf_r.size(r * W + c) + uf_c.size(r * W + c) - 1

        ans = max(ans, t)

print(ans)

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

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

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

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

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

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

for r in range(H):

    for c in range(W):

        if s[r][c] == '.':

            if c == 0:

                L[r][c] = 1

            else:

                L[r][c] = L[r][c - 1] + 1

        else:

            L[r][c] = 0

for r in range(H):

    for c in reversed(list(range(W))):

        if s[r][c] == '.':

            if c == W - 1:

                R[r][c] = 1

            else:

                R[r][c] = R[r][c + 1] + 1

        else:

            R[r][c] = 0

for r in range(H):

    for c in range(W):

        if s[r][c] == '.':

            if r == 0:

                U[r][c] = 1

            else:

                U[r][c] = U[r - 1][c] + 1

        else:

            U[r][c] = 0

for r in reversed(list(range(H))):

    for c in range(W):

        if s[r][c] == '.':

            if r == H - 1:

                D[r][c] = 1

            else:

                D[r][c] = D[r + 1][c] + 1

        else:

            D[r][c] = 0

ans = 0

for r in range(H):

    for c in range(W):

        ans = max(ans, L[r][c] + R[r][c] + D[r][c] + U[r][c] - 3)

print(ans)

class UnionFind:
    def __init__(self, n):
        self.v = [-1 for _ in range(n)]  # 根(負): 連結頂点数 * (-1) / 子(正): 根の頂点番号(0-indexed)

    def find(self, x):  # xを含む木における根の頂点番号を返す
        if self.v[x] < 0:  # (負)は根
            return x
        else:  # 根の頂点番号
            self.v[x] = self.find(self.v[x])  # uniteでは, 旧根に属する頂点の根が旧根のままなので更新
            return self.v[x]

    def unite(self, x, y):  # 違う根に属していたらrankが低くなるように連結
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if -self.v[x] < -self.v[y]:  # size比較, 　(-1) * (連結頂点数 * (-1)), (正)同士の大小比較
            x, y = y, x  # 連結頂点数が少ない方をyにすると, findでの更新回数が減る？
        self.v[x] += self.v[y]  # 連結頂点数の和を取る, 連結頂点数 * (-1)
        self.v[y] = x  # 連結頂点数が少ないy(引数yの根の頂点番号)の根をx(引数xの根の頂点番号)にする

    def root(self, x):
        return self.v[x] < 0  # (負)は根

    def same(self, x, y):
        return self.find(x) == self.find(y)  # 同じ根に属するか

    def size(self, x):
        return -self.v[self.find(x)]  # 連結頂点数を返す

import sys

input = sys.stdin.readline
H, W = list(map(int, input().split()))
s = tuple(eval(input()) for _ in range(H))
uf_r = UnionFind(H * W)
for r in range(H - 1):
    for c in range(W):
        if s[r][c] == "." and s[r + 1][c] == ".":
            uf_r.unite(r * W + c, (r + 1) * W + c)
uf_c = UnionFind(H * W)
for c in range(W - 1):
    for r in range(H):
        if s[r][c] == "." and s[r][c + 1] == ".":
            uf_c.unite(r * W + c, r * W + (c + 1))
ans = 0
for r in range(H):
    for c in range(W):
        if s[r][c] == "#":
            continue
        t = uf_r.size(r * W + c) + uf_c.size(r * W + c) - 1
        ans = max(ans, t)
print(ans)

H, W = list(map(int, input().split()))
s = [eval(input()) for _ in range(H)]
L = [[-1] * W for _ in range(H)]
R = [[-1] * W for _ in range(H)]
D = [[-1] * W for _ in range(H)]
U = [[-1] * W for _ in range(H)]
for r in range(H):
    for c in range(W):
        if s[r][c] == ".":
            if c == 0:
                L[r][c] = 1
            else:
                L[r][c] = L[r][c - 1] + 1
        else:
            L[r][c] = 0
for r in range(H):
    for c in reversed(list(range(W))):
        if s[r][c] == ".":
            if c == W - 1:
                R[r][c] = 1
            else:
                R[r][c] = R[r][c + 1] + 1
        else:
            R[r][c] = 0
for r in range(H):
    for c in range(W):
        if s[r][c] == ".":
            if r == 0:
                U[r][c] = 1
            else:
                U[r][c] = U[r - 1][c] + 1
        else:
            U[r][c] = 0
for r in reversed(list(range(H))):
    for c in range(W):
        if s[r][c] == ".":
            if r == H - 1:
                D[r][c] = 1
            else:
                D[r][c] = D[r + 1][c] + 1
        else:
            D[r][c] = 0
ans = 0
for r in range(H):
    for c in range(W):
        ans = max(ans, L[r][c] + R[r][c] + D[r][c] + U[r][c] - 3)
print(ans)

-        self.v = [-1 for _ in range(n)]  # 根(負): 連結頂点数 * (-1) / 子(正): 根の頂点番号(0-indexed)

-    def find(self, x):  # xを含む木における根の頂点番号を返す

-            self.v[x] = self.find(self.v[x])  # uniteでは, 旧根に属する頂点の根が旧根のままなので更新

-    def unite(self, x, y):  # 違う根に属していたらrankが低くなるように連結

-        if -self.v[x] < -self.v[y]:  # size比較, 　(-1) * (連結頂点数 * (-1)), (正)同士の大小比較

-            x, y = y, x  # 連結頂点数が少ない方をyにすると, findでの更新回数が減る？

-        self.v[x] += self.v[y]  # 連結頂点数の和を取る, 連結頂点数 * (-1)

-        self.v[y] = x  # 連結頂点数が少ないy(引数yの根の頂点番号)の根をx(引数xの根の頂点番号)にする

-        return self.find(x) == self.find(y)  # 同じ根に属するか

-        return -self.v[self.find(x)]  # 連結頂点数を返す

-s = tuple(eval(input()) for _ in range(H))

-            uf_r.unite(r * W + c, (r + 1) * W + c)

-            uf_c.unite(r * W + c, r * W + (c + 1))

-        t = uf_r.size(r * W + c) + uf_c.size(r * W + c) - 1


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

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

B = [eval(input()) for i in range(M)]

dxy = []

for y in range(M) :

    for x in range(M) :

        dxy.append((x,y))

flag = 0

for y in range(N) :

    for x in range(N) :

        if A[y][x] == B[0][0] and flag == 0 :

            counter = 0

            for dx,dy in dxy :

                nx = x+dx

                ny = y+dy

                if (0 <= nx <= N-1) and (0 <= ny <= N-1) and flag == 0 :

                    if A[ny][nx] == B[dy][dx] :

                        counter += 1

                if counter == M**2 :

                    flag = 1

if flag == 1 :

    print("Yes")

else :

    print("No")

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

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

B = [eval(input()) for i in range(M)]

dxy = []

for y in range(M) :

    for x in range(M) :

        dxy.append((x,y))

flag = 0

for y in range(N) :

    for x in range(N) :

        if A[y][x] == B[0][0] and flag == 0 :

            counter = 0

            for dx,dy in dxy :

                if flag == 0 :

                    nx = x+dx

                    ny = y+dy

                    if not (0 <= nx <= N-1) :

                        break

                    if not (0 <= ny <= N-1) :

                        break

                    if A[ny][nx] == B[dy][dx] :

                        counter += 1

            if counter == M**2 :

                flag = 1

if flag == 1 :

    print("Yes")

else :

    print("No")

N, M = list(map(int, input().split()))
A = [eval(input()) for i in range(N)]
B = [eval(input()) for i in range(M)]
dxy = []
for y in range(M):
    for x in range(M):
        dxy.append((x, y))
flag = 0
for y in range(N):
    for x in range(N):
        if A[y][x] == B[0][0] and flag == 0:
            counter = 0
            for dx, dy in dxy:
                nx = x + dx
                ny = y + dy
                if (0 <= nx <= N - 1) and (0 <= ny <= N - 1) and flag == 0:
                    if A[ny][nx] == B[dy][dx]:
                        counter += 1
                if counter == M**2:
                    flag = 1
if flag == 1:
    print("Yes")
else:
    print("No")

N, M = list(map(int, input().split()))
A = [eval(input()) for i in range(N)]
B = [eval(input()) for i in range(M)]
dxy = []
for y in range(M):
    for x in range(M):
        dxy.append((x, y))
flag = 0
for y in range(N):
    for x in range(N):
        if A[y][x] == B[0][0] and flag == 0:
            counter = 0
            for dx, dy in dxy:
                if flag == 0:
                    nx = x + dx
                    ny = y + dy
                    if not (0 <= nx <= N - 1):
                        break
                    if not (0 <= ny <= N - 1):
                        break
                    if A[ny][nx] == B[dy][dx]:
                        counter += 1
            if counter == M**2:
                flag = 1
if flag == 1:
    print("Yes")
else:
    print("No")


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

ans = 0

def sum(k):

  s = 0

  for j in range(len(k)):

    s+=int(k[j])

  return s

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

  if a<=sum(str(i))<=b:

    ans+=i

print(ans)

def findSumDigit(num):

    global total

    total = 0

    while num > 0:

        total += num % 10

        num //= 10

    return total

def main():

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

    ans = 0

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

        tmp = findSumDigit(i)

        if a <= tmp <= b:

            ans += i

    print(ans)

if __name__ == '__main__':

    main()

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

def sum(k):
    s = 0
    for j in range(len(k)):
        s += int(k[j])
    return s

for i in range(1, n + 1):
    if a <= sum(str(i)) <= b:
        ans += i
print(ans)

def findSumDigit(num):
    global total
    total = 0
    while num > 0:
        total += num % 10
        num //= 10
    return total

def main():
    n, a, b = list(map(int, input().split()))
    ans = 0
    for i in range(1, n + 1):
        tmp = findSumDigit(i)
        if a <= tmp <= b:
            ans += i
    print(ans)

if __name__ == "__main__":
    main()

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

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


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

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

s = set(l)

if len(s)==3:

  print('Three')

else:

  print('Four')

n = int(eval(input()))

l = list(input().split())

if len(set(l)) == 4:

    print('Four')

else:

    print('Three')

N = int(eval(input()))
l = list(map(str, input().split()))
s = set(l)
if len(s) == 3:
    print("Three")
else:
    print("Four")

n = int(eval(input()))
l = list(input().split())
if len(set(l)) == 4:
    print("Four")
else:
    print("Three")

-N = int(eval(input()))
-l = list(map(str, input().split()))
-s = set(l)
-if len(s) == 3:
+n = int(eval(input()))
+l = list(input().split())
+if len(set(l)) == 4:
+    print("Four")
+else:
-else:
-    print("Four")


Input:
import itertools

import numpy as np

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

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

count = 0

for ph in itertools.product([0, 1], repeat=h):

    for pw in itertools.product([0, 1], repeat=w):

        squares = np.array([[1 if cell == '#' else -1 for cell in row] for row in c])

        squares[np.array(ph) == 1, :] *= 0

        squares[:, np.array(pw) == 1] *= 0

        count += np.count_nonzero(squares == 1) == k

print(count)

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

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

count = 0

for binh in range(2**h):

    for binw in range(2**w):

        redh, redw = bin(binh)[2:].zfill(h), bin(binw)[2:].zfill(w)  # remove suffix '0x'

        squares = [list(row) for row in c]

        for i, rh in enumerate(redh):

            for wh in range(w):

                if rh == '1':

                    squares[i][wh] = '*'

        for j, rw in enumerate(redw):

            for hw in range(h):

                if rw == '1':

                    squares[hw][j] = '*'

        count += sum(row.count('#') for row in squares) == k

print(count)

import itertools
import numpy as np

h, w, k = list(map(int, input().split()))
c = [eval(input()) for _ in range(h)]
count = 0
for ph in itertools.product([0, 1], repeat=h):
    for pw in itertools.product([0, 1], repeat=w):
        squares = np.array([[1 if cell == "#" else -1 for cell in row] for row in c])
        squares[np.array(ph) == 1, :] *= 0
        squares[:, np.array(pw) == 1] *= 0
        count += np.count_nonzero(squares == 1) == k
print(count)

h, w, k = list(map(int, input().split()))
c = [eval(input()) for _ in range(h)]
count = 0
for binh in range(2**h):
    for binw in range(2**w):
        redh, redw = bin(binh)[2:].zfill(h), bin(binw)[2:].zfill(
            w
        )  # remove suffix '0x'
        squares = [list(row) for row in c]
        for i, rh in enumerate(redh):
            for wh in range(w):
                if rh == "1":
                    squares[i][wh] = "*"
        for j, rw in enumerate(redw):
            for hw in range(h):
                if rw == "1":
                    squares[hw][j] = "*"
        count += sum(row.count("#") for row in squares) == k
print(count)

-for ph in itertools.product([0, 1], repeat=h):

-    for pw in itertools.product([0, 1], repeat=w):

-        squares = np.array([[1 if cell == "#" else -1 for cell in row] for row in c])

-        squares[np.array(ph) == 1, :] *= 0

-        squares[:, np.array(pw) == 1] *= 0

-        count += np.count_nonzero(squares == 1) == k

+        redh, redw = bin(binh)[2:].zfill(h), bin(binw)[2:].zfill(

+        squares = [list(row) for row in c]

+                    squares[i][wh] = "*"

+                    squares[hw][j] = "*"

+        count += sum(row.count("#") for row in squares) == k


Input:
def f(array):

    temp = 'abcdefghijklmnopqrstuvwxyz'

    res = [0] * len(temp)

    cnt = 0

    for x in array:

        res[temp.index(x)] += 1

        cnt += 1

        if cnt == 10:

            break

    return ''.join([str(i) for i in res])

N = int(eval(input()))

s = [''.join(f(eval(input()))) for i in range(N)]

dic = {}

for i in range(N):

    if s[i] in dic:

        dic[s[i]] += 1

    else:

        dic[s[i]] = 1

cnt = 0

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

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

print(cnt)

N = int(eval(input()))

s = [''.join(sorted(eval(input()))) for i in range(N)]

dic = {}

cnt = 0

for i in range(N):

    if s[i] in dic:

        cnt += dic[s[i]]

        dic[s[i]] += 1

    else:

        dic[s[i]] = 1

print(cnt)

def f(array):
    temp = "abcdefghijklmnopqrstuvwxyz"
    res = [0] * len(temp)
    cnt = 0
    for x in array:
        res[temp.index(x)] += 1
        cnt += 1
        if cnt == 10:
            break
    return "".join([str(i) for i in res])

N = int(eval(input()))
s = ["".join(f(eval(input()))) for i in range(N)]
dic = {}
for i in range(N):
    if s[i] in dic:
        dic[s[i]] += 1
    else:
        dic[s[i]] = 1
cnt = 0
for v in list(dic.values()):
    cnt += v * (v - 1) // 2
print(cnt)

N = int(eval(input()))
s = ["".join(sorted(eval(input()))) for i in range(N)]
dic = {}
cnt = 0
for i in range(N):
    if s[i] in dic:
        cnt += dic[s[i]]
        dic[s[i]] += 1
    else:
        dic[s[i]] = 1
print(cnt)

-    temp = "abcdefghijklmnopqrstuvwxyz"

-    return "".join([str(i) for i in res])

-s = ["".join(f(eval(input()))) for i in range(N)]

+s = ["".join(sorted(eval(input()))) for i in range(N)]


Input:
'''

　 ∧_,,∧    究極奥義「WAがACになーれ！！」

　（`・ω・)つ━☆・*。

　⊂　　 ノ 　　　・゜+.

　 し’´Ｊ　　*・

'''

import sys

input = sys.stdin.readline

def sieve(n):

    is_prime = [True for _ in range(n+1)]

    is_prime[0] = False

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

        if is_prime[i-1]:

            j = 2 * i

            while j <= n:

                is_prime[j-1] = False

                j += i

    #table = [ i for i in range(1, n+1) if is_prime[i-1]]

    return is_prime

n=10**5+2

a=sieve(n)

ans=[0]*(n//2)

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

    if a[i] and a[i//2]:

        ans[i//2]=1

#print(ans[:20])

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

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

#print(ans[:20])

q=int(eval(input()))

for i in range(q):

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

    if l==1:

        l=2

    if r==1:

        r=2

    print((ans[r//2]-ans[l//2 -1]))

import sys

input = sys.stdin.readline

from math import sqrt

def Eratosthenes(n):

    """n(>=6)未満の素数列挙 """

    n, correction = n - n % 6 + 6, 2 - (n % 6 > 1)

    sieve = [True] * (n // 3)

    for i in range(1, int(sqrt(n)) // 3 + 1):

        if sieve[i]:

            k = 3 * i + 1 | 1

            sieve[k * k // 3::2 * k] = [False] * ((n // 6 - k * k // 6 - 1) // k + 1)

            sieve[k * (k - 2 * (i & 1) + 4) // 3::2 * k] = [False] * ((n // 6 - k * (k - 2 * (i & 1) + 4) // 6 - 1) // k + 1)

    # return [2, 3] + [3 * i + 1 | 1 for i in range(1, n // 3 - correction) if sieve[i]]

    # x が素数か判定したいとき

    return {2, 3}.union({3 * i + 1 | 1 for i in range(1, n // 3 - correction) if sieve[i]})

sieve = Eratosthenes(10 ** 5 + 1)

ans = [0] * (10 ** 5 + 1)

for i in range(3, 10 ** 5, 2):

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

        ans[i] += 1

for i in range(3, 10 ** 5):

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

q = int(eval(input()))

for i in range(q):

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

    print((ans[r] - ans[l - 1]))

"""
　 ∧_,,∧    究極奥義「WAがACになーれ！！」
　（`・ω・)つ━☆・*。
　⊂　　 ノ 　　　・゜+.
　 し’´Ｊ　　*・
"""
import sys

input = sys.stdin.readline

def sieve(n):
    is_prime = [True for _ in range(n + 1)]
    is_prime[0] = False
    for i in range(2, n + 1):
        if is_prime[i - 1]:
            j = 2 * i
            while j <= n:
                is_prime[j - 1] = False
                j += i
    # table = [ i for i in range(1, n+1) if is_prime[i-1]]
    return is_prime

n = 10**5 + 2
a = sieve(n)
ans = [0] * (n // 2)
for i in range(0, n, 2):
    if a[i] and a[i // 2]:
        ans[i // 2] = 1
# print(ans[:20])
for i in range(1, n // 2):
    ans[i] += ans[i - 1]
# print(ans[:20])
q = int(eval(input()))
for i in range(q):
    l, r = list(map(int, input().split()))
    if l == 1:
        l = 2
    if r == 1:
        r = 2
    print((ans[r // 2] - ans[l // 2 - 1]))

import sys

input = sys.stdin.readline
from math import sqrt

def Eratosthenes(n):
    """n(>=6)未満の素数列挙"""
    n, correction = n - n % 6 + 6, 2 - (n % 6 > 1)
    sieve = [True] * (n // 3)
    for i in range(1, int(sqrt(n)) // 3 + 1):
        if sieve[i]:
            k = 3 * i + 1 | 1
            sieve[k * k // 3 :: 2 * k] = [False] * ((n // 6 - k * k // 6 - 1) // k + 1)
            sieve[k * (k - 2 * (i & 1) + 4) // 3 :: 2 * k] = [False] * (
                (n // 6 - k * (k - 2 * (i & 1) + 4) // 6 - 1) // k + 1
            )
    # return [2, 3] + [3 * i + 1 | 1 for i in range(1, n // 3 - correction) if sieve[i]]
    # x が素数か判定したいとき
    return {2, 3}.union(
        {3 * i + 1 | 1 for i in range(1, n // 3 - correction) if sieve[i]}
    )

sieve = Eratosthenes(10**5 + 1)
ans = [0] * (10**5 + 1)
for i in range(3, 10**5, 2):
    if i in sieve and (i + 1) // 2 in sieve:
        ans[i] += 1
for i in range(3, 10**5):
    ans[i + 1] += ans[i]
q = int(eval(input()))
for i in range(q):
    l, r = list(map(int, input().split()))
    print((ans[r] - ans[l - 1]))

-　 ∧_,,∧    究極奥義「WAがACになーれ！！」

-　（`・ω・)つ━☆・*。

-　⊂　　 ノ 　　　・゜+.

-    is_prime = [True for _ in range(n + 1)]

-                is_prime[j - 1] = False

-    # table = [ i for i in range(1, n+1) if is_prime[i-1]]

+    for i in range(1, int(sqrt(n)) // 3 + 1):

+    # return [2, 3] + [3 * i + 1 | 1 for i in range(1, n // 3 - correction) if sieve[i]]

+    # x が素数か判定したいとき

+        {3 * i + 1 | 1 for i in range(1, n // 3 - correction) if sieve[i]}

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


Input:
from math import pi

r = float(eval(input()))

s = pi * r * r

p = 2 * pi * r

print((s,p))

from math import pi

r = float(eval(input()))

s = pi * (r ** 2)

p = 2 * pi * r

print((s,p))

from math import pi

r = float(eval(input()))
s = pi * r * r
p = 2 * pi * r
print((s, p))

from math import pi

r = float(eval(input()))
s = pi * (r**2)
p = 2 * pi * r
print((s, p))


Input:
import sys

input = sys.stdin.buffer.readline

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

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

for _ in range(M):

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

  d[u][v] = c

  d[v][u] = c

Q = int(eval(input()))

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

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

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

      if d[i][j] > d[i][k] + d[k][j]:

        d[i][j] = d[i][k] + d[k][j]

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

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

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

    if d[i][j] <= L:

      nd[i][j] = 1

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

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

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

      if nd[i][j] > nd[i][k] + nd[k][j]:

        nd[i][j] = nd[i][k] + nd[k][j]

for _ in range(Q):

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

  if nd[s][t] == float("inf"):

    print((-1))

  else:

    print((nd[s][t] - 1))

import sys

input = sys.stdin.readline

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

d = [[10 ** 16 * (i != j) for j in range(N + 1)] for i in range(N + 1)]

for _ in range(M):

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

  d[x][y] = c

  d[y][x] = c

for k in range(N + 1):

  for i in range(N + 1):

    for j in range(N + 1): d[i][j] = min(d[i][j], d[i][k] + d[k][j])

dd = [[(d[i][j] <= L) + (d[i][j] > L) * 10 ** 16 for j in range(N + 1)] for i in range(N + 1)]

for k in range(N + 1):

  for i in range(N + 1):

    for j in range(N + 1): dd[i][j] = min(dd[i][j], dd[i][k] + dd[k][j])

for _ in range(int(eval(input()))):

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

  if dd[s][t] != 10 ** 16: print((dd[s][t] - 1))

  else: print((-1))

import sys

input = sys.stdin.readline
N, M, L = list(map(int, input().split()))
d = [[10**16 * (i != j) for j in range(N + 1)] for i in range(N + 1)]
for _ in range(M):
    x, y, c = list(map(int, input().split()))
    d[x][y] = c
    d[y][x] = c
for k in range(N + 1):
    for i in range(N + 1):
        for j in range(N + 1):
            d[i][j] = min(d[i][j], d[i][k] + d[k][j])
dd = [
    [(d[i][j] <= L) + (d[i][j] > L) * 10**16 for j in range(N + 1)]
    for i in range(N + 1)
]
for k in range(N + 1):
    for i in range(N + 1):
        for j in range(N + 1):
            dd[i][j] = min(dd[i][j], dd[i][k] + dd[k][j])
for _ in range(int(eval(input()))):
    s, t = list(map(int, input().split()))
    if dd[s][t] != 10**16:
        print((dd[s][t] - 1))
    else:
        print((-1))

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

+d = [[10**16 * (i != j) for j in range(N + 1)] for i in range(N + 1)]

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

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

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


Input:
lis = []

for i in range(10):

 lis.append(eval(input()))

for a in sorted(lis,reverse=True)[:3]:

 print(a)

def main():

    arr = []

    for i in range(0,10):

       arr.append(eval(input()))

    arr.sort()

    arr.reverse()

    for i in range(0,3):

        print(arr[i])

if __name__ == '__main__':

    main()

lis = []
for i in range(10):
    lis.append(eval(input()))
for a in sorted(lis, reverse=True)[:3]:
    print(a)

def main():
    arr = []
    for i in range(0, 10):
        arr.append(eval(input()))
    arr.sort()
    arr.reverse()
    for i in range(0, 3):
        print(arr[i])

if __name__ == "__main__":
    main()

-for a in sorted(lis, reverse=True)[:3]:


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

ans = 1

t = min(X, 100)

for b in range(1, t):

    for p in range(1, t):

        if b**p > ans and b**p <= X:

            ans = b**p

print(ans)

X = int(eval(input()))

ans = 1

for b in range(1, X+1):

    for p in range(2, X+1):

        if b**p > X:

            break

        if b**p > ans and b**p <= X:

            ans = b**p

print(ans)

X = int(eval(input()))
ans = 1
for b in range(1, X + 1):
    for p in range(2, X + 1):
        if b**p > X:
            break
        if b**p > ans and b**p <= X:
            ans = b**p
print(ans)

-t = min(X, 100)
-for b in range(1, t):
-    for p in range(1, t):
+for b in range(1, X + 1):
+    for p in range(2, X + 1):
+        if b**p > X:
+            break


Input:
from itertools import permutations

from functools import reduce

from operator import mul

def solve(string):

    n, *xy = list(map(int, string.split()))

    *xy, = list(zip(*[iter(xy)] * 2))

    return str(

        sum(

            sum(((xy[p0][0] - xy[p1][0])**2 + (xy[p0][1] - xy[p1][1])**2)**0.5

                for p0, p1 in zip(list(i),

                                  list(i)[1:]))

            for i in permutations(list(range(n)), n)) / reduce(mul, list(range(1, n + 1))))

if __name__ == '__main__':

    n = int(eval(input()))

    print((solve('{}\n'.format(n)+'\n'.join([eval(input()) for _ in range(n)]))))

from itertools import product

def solve(string):

    n, *xy = list(map(int, string.split()))

    *xy, = list(zip(*[iter(xy)] * 2))

    return str(

        sum(((xy[i][0] - xy[j][0])**2 + (xy[i][1] - xy[j][1])**2)**0.5

            for i, j in product(list(range(n)), repeat=2)) / n)

if __name__ == '__main__':

    n = int(eval(input()))

    print((solve('{}\n'.format(n) + '\n'.join([eval(input()) for _ in range(n)]))))

from itertools import permutations
from functools import reduce
from operator import mul

def solve(string):
    n, *xy = list(map(int, string.split()))
    (*xy,) = list(zip(*[iter(xy)] * 2))
    return str(
        sum(
            sum(
                ((xy[p0][0] - xy[p1][0]) ** 2 + (xy[p0][1] - xy[p1][1]) ** 2) ** 0.5
                for p0, p1 in zip(list(i), list(i)[1:])
            )
            for i in permutations(list(range(n)), n)
        )
        / reduce(mul, list(range(1, n + 1)))
    )

if __name__ == "__main__":
    n = int(eval(input()))
    print((solve("{}\n".format(n) + "\n".join([eval(input()) for _ in range(n)]))))

from itertools import product

def solve(string):
    n, *xy = list(map(int, string.split()))
    (*xy,) = list(zip(*[iter(xy)] * 2))
    return str(
        sum(
            ((xy[i][0] - xy[j][0]) ** 2 + (xy[i][1] - xy[j][1]) ** 2) ** 0.5
            for i, j in product(list(range(n)), repeat=2)
        )
        / n
    )

if __name__ == "__main__":
    n = int(eval(input()))
    print((solve("{}\n".format(n) + "\n".join([eval(input()) for _ in range(n)]))))

-                for p0, p1 in zip(list(i), list(i)[1:])

-            for i in permutations(list(range(n)), n)

+            for i, j in product(list(range(n)), repeat=2)

-        / reduce(mul, list(range(1, n + 1)))


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

H = [int(c) for c in input().split()]

prv1 = prv2 = cur = 0

for i in range(1, N):

    j1 = abs(H[i] - H[i-1])

    cur = min(j1 + prv1, abs(H[i] - H[i-2]) + prv2) if i > 1 else j1

    prv2 = prv1

    prv1 = cur

print(cur)

N = int(eval(input()))

H = [int(c) for c in input().split()]

cur = abs(H[1] - H[0])

prv1 = cur

prv2 = 0

for i in range(2, N):

    cur = min(abs(H[i] - H[i-1]) + prv1, abs(H[i] - H[i-2]) + prv2)

    prv2 = prv1

    prv1 = cur

print(cur)

N = int(eval(input()))
H = [int(c) for c in input().split()]
prv1 = prv2 = cur = 0
for i in range(1, N):
    j1 = abs(H[i] - H[i - 1])
    cur = min(j1 + prv1, abs(H[i] - H[i - 2]) + prv2) if i > 1 else j1
    prv2 = prv1
    prv1 = cur
print(cur)

N = int(eval(input()))
H = [int(c) for c in input().split()]
cur = abs(H[1] - H[0])
prv1 = cur
prv2 = 0
for i in range(2, N):
    cur = min(abs(H[i] - H[i - 1]) + prv1, abs(H[i] - H[i - 2]) + prv2)
    prv2 = prv1
    prv1 = cur
print(cur)

-    cur = min(j1 + prv1, abs(H[i] - H[i - 2]) + prv2) if i > 1 else j1


Input:
import sys

from heapq import heappush, heappop

buf = sys.stdin.buffer

def main():

    n = int(buf.readline())

    XY = list(map(int, buf.read().split()))

    Xs = []

    Ys = []

    for i, (x, y) in enumerate(zip(XY, XY)):

        Xs.append((x-1, i))

        Ys.append((y-1, i))

    Xs.sort()

    Ys.sort()

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

    for i, ((x, node), (nx, new_node)) in enumerate(zip(Xs[:-1], Xs[1:])):

        edges[node].append((nx-x, new_node))

        edges[new_node].append((nx-x, node))

    for i, ((y, node), (ny, new_node)) in enumerate(zip(Ys[:-1], Ys[1:])):

        edges[node].append((ny-y, new_node))

        edges[new_node].append((ny-y, node))

    seen = [False] * n

    dist = [float('INF')] * n

    todo = [(0, 0)]

    while todo:

        d, node = heappop(todo)

        if seen[node]:

            continue

        seen[node] = True

        dist[node] = d

        while edges[node]:

            edge = edges[node].pop()

            nd, to = edge

            if dist[to] <= nd:

                continue

            heappush(todo, (nd, to))

    print((sum(dist)))

if __name__ == "__main__":

    main()

import sys

buf = sys.stdin.buffer

class UnionFind:

    def __init__(self, num_of_node):

        self.roots = [-1] * num_of_node

        self.ranks = [1] * num_of_node

        self.groups = num_of_node

    def get_root(self, node):

        root = self.roots[node]

        if root == -1:

            return node

        else:

            root = self.get_root(root)

            self.roots[node] = root

            return root

    def is_same_group(self, node1, node2):

        return self.get_root(node1) == self.get_root(node2)

    def unite(self, node1, node2):

        self.groups -= 1

        root1, root2 = self.get_root(node1), self.get_root(node2)

        rank1, rank2 = self.ranks[root1], self.ranks[root2]

        if rank1 < rank2:

            root1, root2 = root2, root1

        self.roots[root2] = root1

        self.ranks[root2] += self.ranks[root1]

def main():

    n = int(buf.readline())

    XY = list(map(int, buf.read().split()))

    Xs = []

    Ys = []

    for i, (x, y) in enumerate(zip(XY, XY)):

        Xs.append((x-1, i))

        Ys.append((y-1, i))

    Xs.sort()

    Ys.sort()

    edges = []

    for i, ((x, node), (nx, new_node)) in enumerate(zip(Xs[:-1], Xs[1:])):

        edges.append((nx-x, node, new_node))

    for i, ((y, node), (ny, new_node)) in enumerate(zip(Ys[:-1], Ys[1:])):

        edges.append((ny-y, node, new_node))

    edges.sort(reverse=True)

    ans = 0

    uf = UnionFind(n)

    while uf.groups != 1:

        d, node1, node2 = edges.pop()

        if uf.is_same_group(node1, node2):

            continue

        uf.unite(node1, node2)

        ans += d

    print(ans)

if __name__ == "__main__":

    main()

import sys
from heapq import heappush, heappop

buf = sys.stdin.buffer

def main():
    n = int(buf.readline())
    XY = list(map(int, buf.read().split()))
    Xs = []
    Ys = []
    for i, (x, y) in enumerate(zip(XY, XY)):
        Xs.append((x - 1, i))
        Ys.append((y - 1, i))
    Xs.sort()
    Ys.sort()
    edges = [[] for _ in range(n)]
    for i, ((x, node), (nx, new_node)) in enumerate(zip(Xs[:-1], Xs[1:])):
        edges[node].append((nx - x, new_node))
        edges[new_node].append((nx - x, node))
    for i, ((y, node), (ny, new_node)) in enumerate(zip(Ys[:-1], Ys[1:])):
        edges[node].append((ny - y, new_node))
        edges[new_node].append((ny - y, node))
    seen = [False] * n
    dist = [float("INF")] * n
    todo = [(0, 0)]
    while todo:
        d, node = heappop(todo)
        if seen[node]:
            continue
        seen[node] = True
        dist[node] = d
        while edges[node]:
            edge = edges[node].pop()
            nd, to = edge
            if dist[to] <= nd:
                continue
            heappush(todo, (nd, to))
    print((sum(dist)))

if __name__ == "__main__":
    main()

import sys

buf = sys.stdin.buffer

class UnionFind:
    def __init__(self, num_of_node):
        self.roots = [-1] * num_of_node
        self.ranks = [1] * num_of_node
        self.groups = num_of_node

    def get_root(self, node):
        root = self.roots[node]
        if root == -1:
            return node
        else:
            root = self.get_root(root)
            self.roots[node] = root
            return root

    def is_same_group(self, node1, node2):
        return self.get_root(node1) == self.get_root(node2)

    def unite(self, node1, node2):
        self.groups -= 1
        root1, root2 = self.get_root(node1), self.get_root(node2)
        rank1, rank2 = self.ranks[root1], self.ranks[root2]
        if rank1 < rank2:
            root1, root2 = root2, root1
        self.roots[root2] = root1
        self.ranks[root2] += self.ranks[root1]

def main():
    n = int(buf.readline())
    XY = list(map(int, buf.read().split()))
    Xs = []
    Ys = []
    for i, (x, y) in enumerate(zip(XY, XY)):
        Xs.append((x - 1, i))
        Ys.append((y - 1, i))
    Xs.sort()
    Ys.sort()
    edges = []
    for i, ((x, node), (nx, new_node)) in enumerate(zip(Xs[:-1], Xs[1:])):
        edges.append((nx - x, node, new_node))
    for i, ((y, node), (ny, new_node)) in enumerate(zip(Ys[:-1], Ys[1:])):
        edges.append((ny - y, node, new_node))
    edges.sort(reverse=True)
    ans = 0
    uf = UnionFind(n)
    while uf.groups != 1:
        d, node1, node2 = edges.pop()
        if uf.is_same_group(node1, node2):
            continue
        uf.unite(node1, node2)
        ans += d
    print(ans)

if __name__ == "__main__":
    main()

+        self.roots = [-1] * num_of_node

+    def is_same_group(self, node1, node2):

+        return self.get_root(node1) == self.get_root(node2)

+        root1, root2 = self.get_root(node1), self.get_root(node2)

+        rank1, rank2 = self.ranks[root1], self.ranks[root2]

+            root1, root2 = root2, root1

+        self.ranks[root2] += self.ranks[root1]

-        edges[node].append((nx - x, new_node))

-        edges[new_node].append((nx - x, node))

+        edges.append((nx - x, node, new_node))

-        edges[node].append((ny - y, new_node))

-        edges[new_node].append((ny - y, node))

+        edges.append((ny - y, node, new_node))

+        if uf.is_same_group(node1, node2):


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

K=int(eval(input()))

s=str(N)

N=len(s)

dp=[[[0]*2 for j in range(K+1)] for i in range(N+1)]

dp[0][0][0]=1

for i in range(N):

    for j in range(K+1):

        for k in range(2):

            cd=int(s[i])

            for nd in range(10):

                ni=i+1

                nj=j

                nk=k

                if nd!=0:nj+=1

                if nj>K:continue

                if k==0:

                    if nd>cd:continue

                    if nd<cd:nk=1

                dp[ni][nj][nk]+=dp[i][j][k]

print((dp[N][K][0]+dp[N][K][1]))

N=int(eval(input()))

K=int(eval(input()))

s=str(N)

N=len(s)

# dp[i][smaller][k] :=i桁目までで0以外の数を使用したのがk個である数の個数。

# smallerが1ならNより小さく、0ならNと等しい数であるとする。

dp=[[[0]*(K+2) for j in range(2)] for i in range(N+1)]

dp[0][0][0]=1

for i in range(N):

  for k in range(K+1):

    ni=int(s[i])

    # i桁目まででNより小さいならi+1桁目は何でも良い

    dp[i+1][1][k+1]+=dp[i][1][k]*9 # i+1桁目が0以外

    dp[i+1][1][k]+=dp[i][1][k]     # i+1桁目が0

    # i桁目まででNと同じで、i+1桁目はNより小さい時

    if ni>0:

      dp[i+1][1][k+1]+=dp[i][0][k]*(ni-1) # i+1桁目が0以外

      dp[i+1][1][k]+=dp[i][0][k]          # i+1桁目が0以外

    # i桁目までNと同じで、i+1桁目もNと同じ数の時

    if ni>0:

      dp[i+1][0][k+1]=dp[i][0][k] # i+1桁目が0以外

    else:

      dp[i+1][0][k]=dp[i][0][k]   # i+1桁目が0

print((dp[N][0][K]+dp[N][1][K]))

N = int(eval(input()))
K = int(eval(input()))
s = str(N)
N = len(s)
dp = [[[0] * 2 for j in range(K + 1)] for i in range(N + 1)]
dp[0][0][0] = 1
for i in range(N):
    for j in range(K + 1):
        for k in range(2):
            cd = int(s[i])
            for nd in range(10):
                ni = i + 1
                nj = j
                nk = k
                if nd != 0:
                    nj += 1
                if nj > K:
                    continue
                if k == 0:
                    if nd > cd:
                        continue
                    if nd < cd:
                        nk = 1
                dp[ni][nj][nk] += dp[i][j][k]
print((dp[N][K][0] + dp[N][K][1]))

N = int(eval(input()))
K = int(eval(input()))
s = str(N)
N = len(s)
# dp[i][smaller][k] :=i桁目までで0以外の数を使用したのがk個である数の個数。
# smallerが1ならNより小さく、0ならNと等しい数であるとする。
dp = [[[0] * (K + 2) for j in range(2)] for i in range(N + 1)]
dp[0][0][0] = 1
for i in range(N):
    for k in range(K + 1):
        ni = int(s[i])
        # i桁目まででNより小さいならi+1桁目は何でも良い
        dp[i + 1][1][k + 1] += dp[i][1][k] * 9  # i+1桁目が0以外
        dp[i + 1][1][k] += dp[i][1][k]  # i+1桁目が0
        # i桁目まででNと同じで、i+1桁目はNより小さい時
        if ni > 0:
            dp[i + 1][1][k + 1] += dp[i][0][k] * (ni - 1)  # i+1桁目が0以外
            dp[i + 1][1][k] += dp[i][0][k]  # i+1桁目が0以外
        # i桁目までNと同じで、i+1桁目もNと同じ数の時
        if ni > 0:
            dp[i + 1][0][k + 1] = dp[i][0][k]  # i+1桁目が0以外
        else:
            dp[i + 1][0][k] = dp[i][0][k]  # i+1桁目が0
print((dp[N][0][K] + dp[N][1][K]))

-dp = [[[0] * 2 for j in range(K + 1)] for i in range(N + 1)]

+# dp[i][smaller][k] :=i桁目までで0以外の数を使用したのがk個である数の個数。

+# smallerが1ならNより小さく、0ならNと等しい数であるとする。

+dp = [[[0] * (K + 2) for j in range(2)] for i in range(N + 1)]

+        # i桁目まででNより小さいならi+1桁目は何でも良い

+        # i桁目まででNと同じで、i+1桁目はNより小さい時

+        # i桁目までNと同じで、i+1桁目もNと同じ数の時


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

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

for i in range(n-1):

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

    print("Possible")

    for j in range(i):print((j+1))

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

    exit()

print("Impossible")

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

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

if a[0]+a[1]>=l:

  print("Possible")

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

  exit()

if a[-2]+a[-1]>=l:

  print("Possible")

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

  exit()

ans=-1

for i in range(1,n):

  if a[i-1]+a[i]>=l:

    ans=i

    break

if ans==-1:print("Impossible")

else:

  print("Possible")

  for i in range(1,ans):print(i)

  for i in range(n-1,ans,-1):print(i)

  print(ans)

n, l = list(map(int, input().split()))
a = list(map(int, input().split()))
for i in range(n - 1):
    if a[i] + a[i + 1] >= l:
        print("Possible")
        for j in range(i):
            print((j + 1))
        for j in range(n - 1, i, -1):
            print(j)
        exit()
print("Impossible")

n, l = list(map(int, input().split()))
a = list(map(int, input().split()))
if a[0] + a[1] >= l:
    print("Possible")
    for i in range(n - 1, 0, -1):
        print(i)
    exit()
if a[-2] + a[-1] >= l:
    print("Possible")
    for i in range(1, n):
        print(i)
    exit()
ans = -1
for i in range(1, n):
    if a[i - 1] + a[i] >= l:
        ans = i
        break
if ans == -1:
    print("Impossible")
else:
    print("Possible")
    for i in range(1, ans):
        print(i)
    for i in range(n - 1, ans, -1):
        print(i)
    print(ans)

-for i in range(n - 1):
-    if a[i] + a[i + 1] >= l:
-        print("Possible")
-        for j in range(i):
-            print((j + 1))
-        for j in range(n - 1, i, -1):
-            print(j)
-        exit()
-print("Impossible")
+if a[0] + a[1] >= l:
+    print("Possible")
+    for i in range(n - 1, 0, -1):
+        print(i)
+    exit()
+if a[-2] + a[-1] >= l:
+    print("Possible")
+    for i in range(1, n):
+        print(i)
+    exit()
+ans = -1
+for i in range(1, n):
+    if a[i - 1] + a[i] >= l:
+        ans = i
+        break
+if ans == -1:
+    print("Impossible")
+else:
+    print("Possible")
+    for i in range(1, ans):
+        print(i)
+    for i in range(n - 1, ans, -1):
+        print(i)
+    print(ans)


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

if R-L>=2019:

    minimum=0

else:

    left,right=L%2019,R%2019

    minimum=2018**2

    for i in range(left,right+1):

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

            minimum=min(minimum,i*j%2019)

print(minimum)

import itertools

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

if R-L>=2019:

    print((0))

    exit()

b = 2018

for i in range(L,R+1):

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

        a = (i*j)%2019

        b = min(b,a)

        if b == 0:

            break

print(b)

L, R = list(map(int, input().split()))
if R - L >= 2019:
    minimum = 0
else:
    left, right = L % 2019, R % 2019
    minimum = 2018**2
    for i in range(left, right + 1):
        for j in range(i + 1, right + 1):
            minimum = min(minimum, i * j % 2019)
print(minimum)

import itertools

L, R = list(map(int, input().split()))
if R - L >= 2019:
    print((0))
    exit()
b = 2018
for i in range(L, R + 1):
    for j in range(i + 1, R + 1):
        a = (i * j) % 2019
        b = min(b, a)
        if b == 0:
            break
print(b)

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

-            minimum = min(minimum, i * j % 2019)


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

num = 0

for i in range(1000001):

    num += 7 * pow(10, i, K)

    num %= K

    if num == 0:

        print((i + 1))

        break

else:

    print((-1))

def solve(K):

    cur = 0

    tens = 1

    for i in range(1_000_001):

        cur += 7 * tens

        cur %= K

        if cur == 0:

            return i + 1

        tens *= 10

        tens %= K

    else:

        return -1

print((solve(int(eval(input())))))

-K = int(eval(input()))
-num = 0
-for i in range(1000001):
-    num += 7 * pow(10, i, K)
-    num %= K
-    if num == 0:
-        print((i + 1))
-        break
-else:
-    print((-1))
+def solve(K):
+    cur = 0
+    tens = 1
+    for i in range(1_000_001):
+        cur += 7 * tens
+        cur %= K
+        if cur == 0:
+            return i + 1
+        tens *= 10
+        tens %= K
+    else:
+        return -1
+
+
+print((solve(int(eval(input())))))


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

flag = S[0]

flag_num = 0

ans = 0

for i in range(len(S)):

    if flag != S[flag_num]:

        ans += 1

        flag = S[flag_num]

    flag_num += 1

print(ans)

S = eval(input())

now = S[0]

ans = 0

for i in S:

    if now != i:

        ans += 1

        now = i

print(ans)

-S = list(eval(input()))
-flag = S[0]
-flag_num = 0
+S = eval(input())
+now = S[0]
-for i in range(len(S)):
-    if flag != S[flag_num]:
+for i in S:
+    if now != i:
-        flag = S[flag_num]
-    flag_num += 1
+        now = i


Input:
import sys

input = sys.stdin.readline

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

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

cnt = [0] * (N + 1)

for i in range(N - 1):

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

    graph[a].append(b)

    graph[b].append(a)

for i in range(Q):

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

    cnt[p] += x

wait = [1]

parent = [0] * (N + 1)

while wait:

    temp = wait.pop()

    # 頂点tempについて

    for i in graph[temp]:

        if i != parent[temp]:

            parent[i] = temp

            wait.append(i)

            cnt[i] += cnt[temp]

print((' '.join(map(str, cnt[1:]))))

import sys

readline = sys.stdin.readline

read = sys.stdin.read

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

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

cnt = [0] * (N + 1)

for _ in range(N - 1):

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

    graph[a].append(b)

    graph[b].append(a)

px = list(map(int, read().split()))

for p, x in zip(*[px] * 2):

    cnt[p] += x

stack = [1]

checked = [False] * (N + 1)

checked[1] = True

while stack:

    V = stack.pop()

    for i in graph[V]:

        if checked[i]:

            continue

        checked[i] = True

        stack.append(i)

        cnt[i] += cnt[V]

print((' '.join(map(str, cnt[1:]))))

import sys

input = sys.stdin.readline
N, Q = list(map(int, input().split()))
graph = [[] for _ in range(N + 1)]
cnt = [0] * (N + 1)
for i in range(N - 1):
    a, b = list(map(int, input().split()))
    graph[a].append(b)
    graph[b].append(a)
for i in range(Q):
    p, x = list(map(int, input().split()))
    cnt[p] += x
wait = [1]
parent = [0] * (N + 1)
while wait:
    temp = wait.pop()
    # 頂点tempについて
    for i in graph[temp]:
        if i != parent[temp]:
            parent[i] = temp
            wait.append(i)
            cnt[i] += cnt[temp]
print((" ".join(map(str, cnt[1:]))))

import sys

readline = sys.stdin.readline
read = sys.stdin.read
N, Q = list(map(int, readline().split()))
graph = [[] for _ in range(N + 1)]
cnt = [0] * (N + 1)
for _ in range(N - 1):
    a, b = list(map(int, readline().split()))
    graph[a].append(b)
    graph[b].append(a)
px = list(map(int, read().split()))
for p, x in zip(*[px] * 2):
    cnt[p] += x
stack = [1]
checked = [False] * (N + 1)
checked[1] = True
while stack:
    V = stack.pop()
    for i in graph[V]:
        if checked[i]:
            continue
        checked[i] = True
        stack.append(i)
        cnt[i] += cnt[V]
print((" ".join(map(str, cnt[1:]))))

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

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

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

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

-    # 頂点tempについて


c = eval(input())
print((chr(ord(c) + 1)))

-print((chr(ord(eval(input())) + 1)))
+c = eval(input())
+print((chr(ord(c) + 1)))


Input:
import re

n = eval(input())

if re.findall('[7]', n):

  print("Yes")

else:

  print("No")

n = eval(input())

print(("Yes" if n.find("7") >= 0 else "No"))

import re

n = eval(input())
if re.findall("[7]", n):
    print("Yes")
else:
    print("No")

+print(("Yes" if n.find("7") >= 0 else "No"))


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

def count(val1, val2):

    digit = 1

    while val1 >= (val2 ** digit):

        digit += 1

    res = 0

    while digit!=0:

        cnt = int(val1 // val2 ** digit)

        val1 -= (val2 ** digit)*cnt

        res += cnt

        digit -= 1

    return res,val1

N = int(eval(input()))

ans = N

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

    n = i

    m = N - i

    res = 0

    cnt, nn = count(n, 9)

    n = nn

    res += cnt

    cnt, mm = count(m, 6)

    m = mm

    res += cnt

    res += n + m

    ans = min(ans, res)

print(ans)

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

def count(val1, val2):

    digit = 1

    while digit*val2 <= val1:

        digit *= val2

    res = 0

    while digit!=1:

        cnt = int(val1 // digit)

        val1 -= digit*cnt

        res += cnt

        digit /= val2

    return res,val1

N = int(eval(input()))

ans = N

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

    n = i

    m = N - i

    res = 0

    cnt, nn = count(n, 9)

    n = nn

    res += cnt

    cnt, mm = count(m, 6)

    m = mm

    res += cnt

    res += n + m

    ans = min(ans, int(res))

print(ans)

# -*- coding: utf-8 -*-
def count(val1, val2):
    digit = 1
    while val1 >= (val2**digit):
        digit += 1
    res = 0
    while digit != 0:
        cnt = int(val1 // val2**digit)
        val1 -= (val2**digit) * cnt
        res += cnt
        digit -= 1
    return res, val1

N = int(eval(input()))
ans = N
for i in range(0, N + 1):
    n = i
    m = N - i
    res = 0
    cnt, nn = count(n, 9)
    n = nn
    res += cnt
    cnt, mm = count(m, 6)
    m = mm
    res += cnt
    res += n + m
    ans = min(ans, res)
print(ans)

# -*- coding: utf-8 -*-
def count(val1, val2):
    digit = 1
    while digit * val2 <= val1:
        digit *= val2
    res = 0
    while digit != 1:
        cnt = int(val1 // digit)
        val1 -= digit * cnt
        res += cnt
        digit /= val2
    return res, val1

N = int(eval(input()))
ans = N
for i in range(0, N + 1):
    n = i
    m = N - i
    res = 0
    cnt, nn = count(n, 9)
    n = nn
    res += cnt
    cnt, mm = count(m, 6)
    m = mm
    res += cnt
    res += n + m
    ans = min(ans, int(res))
print(ans)

-    while val1 >= (val2**digit):
-        digit += 1
+    while digit * val2 <= val1:
+        digit *= val2
-    while digit != 0:
-        cnt = int(val1 // val2**digit)
-        val1 -= (val2**digit) * cnt
+    while digit != 1:
+        cnt = int(val1 // digit)
+        val1 -= digit * cnt
-        digit -= 1
+        digit /= val2
-    ans = min(ans, res)
+    ans = min(ans, int(res))


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

m=1e18

for i in range(n):m=min(m,sum(a)+x*i);a=[min(t)for t in zip(a,a[-1:]+a)]

print(m)

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

m=1e18

for i in range(n):m=min(m,sum(a)+x*i);*a,=list(map(min,list(zip(a,a[-1:]+a))))

print(m)

n, x, *a = list(map(int, open(0).read().split()))
m = 1e18
for i in range(n):
    m = min(m, sum(a) + x * i)
    a = [min(t) for t in zip(a, a[-1:] + a)]
print(m)

n, x, *a = list(map(int, open(0).read().split()))
m = 1e18
for i in range(n):
    m = min(m, sum(a) + x * i)
    (*a,) = list(map(min, list(zip(a, a[-1:] + a))))
print(m)

-    a = [min(t) for t in zip(a, a[-1:] + a)]


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

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

t = [(x + l, x - l) for x, l in XL]

t.sort()

max_r = -float('inf')

result = 0

for i in range(N):

    r, l = t[i]

    if max_r <= l:

        result += 1

        max_r = r

print(result)

from operator import itemgetter

def solve():

    N = int(eval(input()))

    X = []

    for i in range(N):

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

        X.append((xx-ll, xx+ll))

    X.sort(key=itemgetter(1))

    count = 0

    cur = -float('inf')

    for i in range(N):

        c, d = X[i]

        if cur <= c:

            count += 1

            cur = d

    return count

print((solve()))

N = int(eval(input()))
XL = [list(map(int, input().split())) for _ in range(N)]
t = [(x + l, x - l) for x, l in XL]
t.sort()
max_r = -float("inf")
result = 0
for i in range(N):
    r, l = t[i]
    if max_r <= l:
        result += 1
        max_r = r
print(result)

from operator import itemgetter

def solve():
    N = int(eval(input()))
    X = []
    for i in range(N):
        xx, ll = list(map(int, input().split()))
        X.append((xx - ll, xx + ll))
    X.sort(key=itemgetter(1))
    count = 0
    cur = -float("inf")
    for i in range(N):
        c, d = X[i]
        if cur <= c:
            count += 1
            cur = d
    return count

print((solve()))

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

+        xx, ll = list(map(int, input().split()))


Input:
import numpy as np

from collections import Counter

import collections

import numpy as np

from scipy import sqrt, power, exp, log10

from scipy.fftpack import fft, ifft, fftfreq

import tarfile

import re

import os

import glob

from datetime import datetime

import time

import numpy.linalg as LA

round = lambda x:(x*2+1)//2

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

S = eval(input())

sub= "AC"

l = np.zeros(len(S)+1)

for i in range(len(S)):

  l[i+1] = l[i] + (1 if S[i:i+2]=="AC" else 0)

for i in range(b):

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

    n = l[t-1]-l[r-1]

    print((int(n)))

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

S = eval(input())

L = [0]*Q

R = [0]*Q

for q in range(Q):

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

    L[q] = l

    R[q] = r

ans = [0]*Q

accumulative_count = [0]*(N)

accumulative_count[0] = 0

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

    accumulative_count[i] = accumulative_count[i-1]

    if (S[i-1:i] == 'A') & (S[i:i+1] == 'C'):

        accumulative_count[i] = accumulative_count[i-1] + 1

for q in range(Q):

    print((accumulative_count[R[q]-1] - accumulative_count[L[q]-1]))

import numpy as np
from collections import Counter
import collections
import numpy as np
from scipy import sqrt, power, exp, log10
from scipy.fftpack import fft, ifft, fftfreq
import tarfile
import re
import os
import glob
from datetime import datetime
import time
import numpy.linalg as LA

round = lambda x: (x * 2 + 1) // 2
a, b = list(map(int, input().split()))
S = eval(input())
sub = "AC"
l = np.zeros(len(S) + 1)
for i in range(len(S)):
    l[i + 1] = l[i] + (1 if S[i : i + 2] == "AC" else 0)
for i in range(b):
    r, t = list(map(int, input().split()))
    n = l[t - 1] - l[r - 1]
    print((int(n)))

N, Q = list(map(int, input().split()))
S = eval(input())
L = [0] * Q
R = [0] * Q
for q in range(Q):
    l, r = list(map(int, input().split()))
    L[q] = l
    R[q] = r
ans = [0] * Q
accumulative_count = [0] * (N)
accumulative_count[0] = 0
for i in range(1, N, 1):
    accumulative_count[i] = accumulative_count[i - 1]
    if (S[i - 1 : i] == "A") & (S[i : i + 1] == "C"):
        accumulative_count[i] = accumulative_count[i - 1] + 1
for q in range(Q):
    print((accumulative_count[R[q] - 1] - accumulative_count[L[q] - 1]))

-from scipy import sqrt, power, exp, log10

-from scipy.fftpack import fft, ifft, fftfreq

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

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

+        accumulative_count[i] = accumulative_count[i - 1] + 1

+    print((accumulative_count[R[q] - 1] - accumulative_count[L[q] - 1]))


Input:
from collections import Counter

def check(a, b):

    return (abs(a - b) <= 1)

C = Counter(eval(input()))

a, b, c = (C[s] for s in "abc")

if check(a, b) and check(b, c) and check(c, a):

    print("YES")

else:

    print("NO")

S = eval(input())

L = [S.count(s) for s in "abc"]

if max(L) - min(L) <= 1:

    print("YES")

else:

    print("NO")

from collections import Counter

def check(a, b):
    return abs(a - b) <= 1

C = Counter(eval(input()))
a, b, c = (C[s] for s in "abc")
if check(a, b) and check(b, c) and check(c, a):
    print("YES")
else:
    print("NO")

-if check(a, b) and check(b, c) and check(c, a):


Input:
import sys

input=sys.stdin.readline

def get_candidate(K):

    l = []

    b = 0

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

        if (K&(1<<i)):

            l.append(b + (1<<i) - 1)

            b += (1<<i)

    return l+[K]

def get_ans(K, l):

    bit = [None]*30

    for i in range(30):

        bit[i] = (K&(1<<i))>>i

    ans = 0

    for i, j in l:

        for k in range(30):

            b = (i&(1<<k))>>k

            if not ((bit[k]==1) or (b==0 and bit[k]==0)):

                break

        else:

            ans += j

    return ans

def solve():

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

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

    ans = 0

    for k in get_candidate(K):

        ans = max(ans, get_ans(k, l))

    print(ans)

if __name__ == "__main__":

    solve()

import sys

input=sys.stdin.readline

def get_candidate(K):

    l = []

    b = 0

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

        if K&(1<<i):

            l.append(b + (1<<i) - 1)

            b += (1<<i)

    return l+[K]

def get_ans(K, l):

    ans = 0

    for i, j in l:

        if i|K==K:

            ans += j

    return ans

def solve():

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

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

    ans = 0

    for k in get_candidate(K):

        ans = max(ans, get_ans(k, l))

    print(ans)

if __name__ == "__main__":

    solve()

import sys

input = sys.stdin.readline

def get_candidate(K):
    l = []
    b = 0
    for i in range(30)[::-1]:
        if K & (1 << i):
            l.append(b + (1 << i) - 1)
            b += 1 << i
    return l + [K]

def get_ans(K, l):
    bit = [None] * 30
    for i in range(30):
        bit[i] = (K & (1 << i)) >> i
    ans = 0
    for i, j in l:
        for k in range(30):
            b = (i & (1 << k)) >> k
            if not ((bit[k] == 1) or (b == 0 and bit[k] == 0)):
                break
        else:
            ans += j
    return ans

def solve():
    N, K = list(map(int, input().split()))
    l = [tuple(map(int, input().split())) for _ in range(N)]
    ans = 0
    for k in get_candidate(K):
        ans = max(ans, get_ans(k, l))
    print(ans)

if __name__ == "__main__":
    solve()

import sys

input = sys.stdin.readline

def get_candidate(K):
    l = []
    b = 0
    for i in range(30)[::-1]:
        if K & (1 << i):
            l.append(b + (1 << i) - 1)
            b += 1 << i
    return l + [K]

def get_ans(K, l):
    ans = 0
    for i, j in l:
        if i | K == K:
            ans += j
    return ans

def solve():
    N, K = list(map(int, input().split()))
    l = [tuple(map(int, input().split())) for _ in range(N)]
    ans = 0
    for k in get_candidate(K):
        ans = max(ans, get_ans(k, l))
    print(ans)

if __name__ == "__main__":
    solve()


Input:
import itertools

N = int(eval(input()))

NL = [str(i) for i in range(1,N+1)]

P = input().replace(' ', '')

Q = input().replace(' ', '')

NLL = sorted(list(itertools.permutations(NL,N)))

a = 0

b = 0

for i in range(len(NLL)):

    if ''.join(list(NLL[i])) == P:

        a = i+1

    if ''.join(list(NLL[i])) == Q:

        b = i+1

print((abs(a-b)))

import itertools

import math

N = int(eval(input()))

P = ''.join(input().split())

Q = ''.join(input().split())

np = sorted(list([''.join(x) for x in itertools.permutations([str(i+1) for i in range(N)])]))

print((abs((np.index(P)+1)-(np.index(Q)+1))))

import itertools

N = int(eval(input()))
NL = [str(i) for i in range(1, N + 1)]
P = input().replace(" ", "")
Q = input().replace(" ", "")
NLL = sorted(list(itertools.permutations(NL, N)))
a = 0
b = 0
for i in range(len(NLL)):
    if "".join(list(NLL[i])) == P:
        a = i + 1
    if "".join(list(NLL[i])) == Q:
        b = i + 1
print((abs(a - b)))

import itertools
import math

N = int(eval(input()))
P = "".join(input().split())
Q = "".join(input().split())
np = sorted(
    list(["".join(x) for x in itertools.permutations([str(i + 1) for i in range(N)])])
)
print((abs((np.index(P) + 1) - (np.index(Q) + 1))))

-NLL = sorted(list(itertools.permutations(NL, N)))

+    list(["".join(x) for x in itertools.permutations([str(i + 1) for i in range(N)])])

+print((abs((np.index(P) + 1) - (np.index(Q) + 1))))


Input:
def resolve():

    import numpy as np

    import sys

    readline = sys.stdin.readline    # 1行だけ文字列にする

    H, W, K = list(map(int, readline().split()))

    c = [list(readline().strip()) for _ in [0] * H]

    # matrixは文字列#とそれ以外でなる時，#を1に，それ以外を0にする

    c = np.array([[1 if c[i][j] == "#" else 0

                 for j in range(W)]

                 for i in range(H)], dtype=np.int64)

    ans = 0

    for bit_i in range(1 << H):

        lst_y = []

        for i in range(H):

            if bit_i & (1 << i):

                lst_y.append(i)

        for bit_j in range(1 << W):

            lst_x = []

            for j in range(W):

                if bit_j & (1 << j):

                    lst_x.append(j)

            fig = c[:]

            fig = np.delete(fig, lst_y, axis=0)

            fig = np.delete(fig, lst_x, axis=1)

            if np.count_nonzero(fig == 1) == K:

                ans += 1

    print(ans)

if __name__ == "__main__":

    resolve()

import sys

def resolve():

    """

    全パターンは2**12=4096通りだからbit全探索

    消さない行列だけ判定するコードの方がスマート？(解説動画より)

    """

    readline = sys.stdin.readline    # 1行だけ文字列にする

    H, W, K = list(map(int, readline().split()))

    c = [list(readline().strip()) for _ in [0] * H]

    ans = 0

    # bit全探索

    for bit_i in range(1 << H):

        for bit_j in range(1 << W):

            cnt = 0

            for i in range(H):

                for j in range(W):

                    if (1

                            and bit_i & (1 << i)

                            and bit_j & (1 << j)

                            and c[i][j] == '#'):

                        cnt += 1

            if cnt == K:

                ans += 1

    print(ans)

resolve()

def resolve():
    import numpy as np
    import sys

    readline = sys.stdin.readline  # 1行だけ文字列にする
    H, W, K = list(map(int, readline().split()))
    c = [list(readline().strip()) for _ in [0] * H]
    # matrixは文字列#とそれ以外でなる時，#を1に，それ以外を0にする
    c = np.array(
        [[1 if c[i][j] == "#" else 0 for j in range(W)] for i in range(H)],
        dtype=np.int64,
    )
    ans = 0
    for bit_i in range(1 << H):
        lst_y = []
        for i in range(H):
            if bit_i & (1 << i):
                lst_y.append(i)
        for bit_j in range(1 << W):
            lst_x = []
            for j in range(W):
                if bit_j & (1 << j):
                    lst_x.append(j)
            fig = c[:]
            fig = np.delete(fig, lst_y, axis=0)
            fig = np.delete(fig, lst_x, axis=1)
            if np.count_nonzero(fig == 1) == K:
                ans += 1
    print(ans)

if __name__ == "__main__":
    resolve()

import sys

def resolve():
    """
    全パターンは2**12=4096通りだからbit全探索
    消さない行列だけ判定するコードの方がスマート？(解説動画より)
    """
    readline = sys.stdin.readline  # 1行だけ文字列にする
    H, W, K = list(map(int, readline().split()))
    c = [list(readline().strip()) for _ in [0] * H]
    ans = 0
    # bit全探索
    for bit_i in range(1 << H):
        for bit_j in range(1 << W):
            cnt = 0
            for i in range(H):
                for j in range(W):
                    if 1 and bit_i & (1 << i) and bit_j & (1 << j) and c[i][j] == "#":
                        cnt += 1
            if cnt == K:
                ans += 1
    print(ans)

resolve()

+    全パターンは2**12=4096通りだからbit全探索

+    消さない行列だけ判定するコードの方がスマート？(解説動画より)

-    # matrixは文字列#とそれ以外でなる時，#を1に，それ以外を0にする

-        [[1 if c[i][j] == "#" else 0 for j in range(W)] for i in range(H)],

-            fig = np.delete(fig, lst_y, axis=0)

-            fig = np.delete(fig, lst_x, axis=1)

-            if np.count_nonzero(fig == 1) == K:


Input:
import sys, re

from collections import deque, defaultdict, Counter

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians

from itertools import permutations, combinations, product, accumulate

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from fractions import gcd

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

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

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

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

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10 ** 9 + 7

def solve():

	N, Q = MAP()

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

	tree = defaultdict(list)

	par = [-1]*N

	par[0] = 0

	for a, b in ab:

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

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

		par[b-1] = a-1

	px = [LIST() for _ in range(Q)]

	ans = [0] * N  # 答え入れる

	for p, x in px:

		ans[p-1] += x

	for i in range(1, N):

		ans[i] += ans[par[i]]

	print(*ans, sep=" ")

if  __name__ == "__main__":

	solve()

import sys, re

from collections import deque, defaultdict, Counter

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians

from itertools import permutations, combinations, product

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from fractions import gcd

from bisect import bisect

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

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10 ** 9 + 7

N, Q = MAP()

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

px = [LIST() for _ in range(Q)]

tree = defaultdict(list)

for a, b in ab:

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

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

dic = defaultdict(int)

for p, x in px:

	dic[p-1] += x

ans = [0]*N

checked = [0]*N

checked[0] = 1

q = deque([])

q.append(0)

while q:

	n = q.popleft()

	ans[n] += dic[n]

	for node in tree[n]:

		if checked[node]:

			continue

		ans[node] += ans[n]

		checked[node] = 1

		q.append(node)

print((*ans))

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

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

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

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

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

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

def solve():
    N, Q = MAP()
    ab = [LIST() for _ in range(N - 1)]
    tree = defaultdict(list)
    par = [-1] * N
    par[0] = 0
    for a, b in ab:
        tree[a - 1].append(b - 1)
        tree[b - 1].append(a - 1)
        par[b - 1] = a - 1
    px = [LIST() for _ in range(Q)]
    ans = [0] * N  # 答え入れる
    for p, x in px:
        ans[p - 1] += x
    for i in range(1, N):
        ans[i] += ans[par[i]]
    print(*ans, sep=" ")

if __name__ == "__main__":
    solve()

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect

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

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
N, Q = MAP()
ab = [LIST() for _ in range(N - 1)]
px = [LIST() for _ in range(Q)]
tree = defaultdict(list)
for a, b in ab:
    tree[a - 1].append(b - 1)
    tree[b - 1].append(a - 1)
dic = defaultdict(int)
for p, x in px:
    dic[p - 1] += x
ans = [0] * N
checked = [0] * N
checked[0] = 1
q = deque([])
q.append(0)
while q:
    n = q.popleft()
    ans[n] += dic[n]
    for node in tree[n]:
        if checked[node]:
            continue
        ans[node] += ans[n]
        checked[node] = 1
        q.append(node)
print((*ans))

-from itertools import permutations, combinations, product, accumulate

+from itertools import permutations, combinations, product

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

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


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

print((N*M))

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

a = int(a)

b = int(b*1000)

print((int(a*b)//1000))

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

a, b = list(map(float, input().split()))
a = int(a)
b = int(b * 1000)
print((int(a * b) // 1000))

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


Input:
# https://atcoder.jp/contests/abc106/tasks/abc106_d

# どうやったら高速に区間[p,q]に完全に入っている区間の数を取得できるか？

# p,qを二次元座標として捉えると電車1本の線は二次元平面上の1点として表せる

# このときp,qの区間に完全に入っている電車の本数というのは、x軸、y軸の両方において[p,q]となる四角形内にある電車の本数

# queryに高速に答えるために二次元累積和を構築する

import sys

read = sys.stdin.readline

def read_ints():

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

def read_tuple(H):

    '''

    H is number of rows

    '''

    ret = []

    for _ in range(H):

        ret.append(tuple(map(int, read().split())))

    return ret

import numpy as np

N, M, Q = read_ints()

LR = read_tuple(M)

pq = read_tuple(Q)

# numpy使わずに再実装 #入れるときはpythonのほうが速いので

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

for L, R in LR:

    LR2d[L][R] += 1

LR2d = np.array(LR2d, np.int64)

LR2d_accum = np.zeros((N + 2, N + 2), np.int64)

LR2d_accum[1:, 1:] = LR2d.cumsum(axis=0).cumsum(axis=1)  # 1次元累積和同様半開区間で考える

# つまりインデックスi,jとはもとの配列においてi,jを含まない四角形の領域の合計を出す

# queryに答えていく

for p, q in pq:

    print((LR2d_accum[q + 1, q + 1] - LR2d_accum[q + 1, p] -

          LR2d_accum[p, q + 1] + LR2d_accum[p, p]))

# https://atcoder.jp/contests/abc106/tasks/abc106_d

# どうやったら高速に区間[p,q]に完全に入っている区間の数を取得できるか？

# p,qを二次元座標として捉えると電車1本の線は二次元平面上の1点として表せる

# このときp,qの区間に完全に入っている電車の本数というのは、x軸、y軸の両方において[p,q]となる四角形内にある電車の本数

# queryに高速に答えるために二次元累積和を構築する

import sys

read = sys.stdin.readline

def read_ints():

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

def read_tuple(H):

    '''

    H is number of rows

    '''

    ret = []

    for _ in range(H):

        ret.append(tuple(map(int, read().split())))

    return ret

import numpy as np

N, M, Q = read_ints()

LR = read_tuple(M)

pq = read_tuple(Q)

# numpy使わずに再実装 #入れるときはpythonのほうが速いので

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

for L, R in LR:

    LR2d[L][R] += 1

LR2d = np.array(LR2d, np.int64)

LR2d_accum = np.zeros((N + 2, N + 2), np.int64)

LR2d_accum[1:, 1:] = LR2d.cumsum(axis=0).cumsum(axis=1)  # 1次元累積和同様半開区間で考える

# つまりインデックスi,jとはもとの配列においてi,jを含まない四角形の領域の合計を出す

# queryに答えていく

ans = []

for p, q in pq:

    ans.append(LR2d_accum[q + 1, q + 1] - LR2d_accum[q + 1, p] -

               LR2d_accum[p, q + 1] + LR2d_accum[p, p])

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

# https://atcoder.jp/contests/abc106/tasks/abc106_d
# どうやったら高速に区間[p,q]に完全に入っている区間の数を取得できるか？
# p,qを二次元座標として捉えると電車1本の線は二次元平面上の1点として表せる
# このときp,qの区間に完全に入っている電車の本数というのは、x軸、y軸の両方において[p,q]となる四角形内にある電車の本数
# queryに高速に答えるために二次元累積和を構築する
import sys

read = sys.stdin.readline

def read_ints():
    return list(map(int, read().split()))

def read_tuple(H):
    """
    H is number of rows
    """
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret

import numpy as np

N, M, Q = read_ints()
LR = read_tuple(M)
pq = read_tuple(Q)
# numpy使わずに再実装 #入れるときはpythonのほうが速いので
LR2d = [[0] * (N + 1) for _ in range(N + 1)]
for L, R in LR:
    LR2d[L][R] += 1
LR2d = np.array(LR2d, np.int64)
LR2d_accum = np.zeros((N + 2, N + 2), np.int64)
LR2d_accum[1:, 1:] = LR2d.cumsum(axis=0).cumsum(axis=1)  # 1次元累積和同様半開区間で考える
# つまりインデックスi,jとはもとの配列においてi,jを含まない四角形の領域の合計を出す
# queryに答えていく
for p, q in pq:
    print(
        (
            LR2d_accum[q + 1, q + 1]
            - LR2d_accum[q + 1, p]
            - LR2d_accum[p, q + 1]
            + LR2d_accum[p, p]
        )
    )

# https://atcoder.jp/contests/abc106/tasks/abc106_d
# どうやったら高速に区間[p,q]に完全に入っている区間の数を取得できるか？
# p,qを二次元座標として捉えると電車1本の線は二次元平面上の1点として表せる
# このときp,qの区間に完全に入っている電車の本数というのは、x軸、y軸の両方において[p,q]となる四角形内にある電車の本数
# queryに高速に答えるために二次元累積和を構築する
import sys

read = sys.stdin.readline

def read_ints():
    return list(map(int, read().split()))

def read_tuple(H):
    """
    H is number of rows
    """
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret

import numpy as np

N, M, Q = read_ints()
LR = read_tuple(M)
pq = read_tuple(Q)
# numpy使わずに再実装 #入れるときはpythonのほうが速いので
LR2d = [[0] * (N + 1) for _ in range(N + 1)]
for L, R in LR:
    LR2d[L][R] += 1
LR2d = np.array(LR2d, np.int64)
LR2d_accum = np.zeros((N + 2, N + 2), np.int64)
LR2d_accum[1:, 1:] = LR2d.cumsum(axis=0).cumsum(axis=1)  # 1次元累積和同様半開区間で考える
# つまりインデックスi,jとはもとの配列においてi,jを含まない四角形の領域の合計を出す
# queryに答えていく
ans = []
for p, q in pq:
    ans.append(
        LR2d_accum[q + 1, q + 1]
        - LR2d_accum[q + 1, p]
        - LR2d_accum[p, q + 1]
        + LR2d_accum[p, p]
    )
print(*ans, sep="\n")

+ans = []
-    print(
-        (
-            LR2d_accum[q + 1, q + 1]
-            - LR2d_accum[q + 1, p]
-            - LR2d_accum[p, q + 1]
-            + LR2d_accum[p, p]
-        )
+    ans.append(
+        LR2d_accum[q + 1, q + 1]
+        - LR2d_accum[q + 1, p]
+        - LR2d_accum[p, q + 1]
+        + LR2d_accum[p, p]
+print(*ans, sep="\n")


Input:
import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array

# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall

# from decimal import Decimal

# from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

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

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

fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))

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

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

sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))

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

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7

INF = float('inf')

def main():

    if os.getenv("LOCAL"):

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

    N = ii()

    ret = 0

    for a in range(1, N):

        b = N // a

        if N - (a * b) <= 0:

            ret += b - 1

        else:

            ret += b

    print(ret)

if __name__ == '__main__':

    main()

import sys

import os

import math

import bisect

import itertools

import collections

import heapq

import queue

import array

# 時々使う

# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall

# from decimal import Decimal

# from collections import defaultdict, deque

# 再帰の制限設定

sys.setrecursionlimit(10000000)

def ii(): return int(sys.stdin.buffer.readline().rstrip())

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

def fl(): return list(map(float, sys.stdin.buffer.readline().split()))

def iln(n): return [int(sys.stdin.buffer.readline().rstrip())

                    for _ in range(n)]

def iss(): return sys.stdin.buffer.readline().decode().rstrip()

def sl(): return list(map(str, sys.stdin.buffer.readline().decode().split()))

def isn(n): return [sys.stdin.buffer.readline().decode().rstrip()

                    for _ in range(n)]

def lcm(x, y): return (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7

INF = float('inf')

def main():

    if os.getenv("LOCAL"):

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

    N = ii()

    ret = 0

    for i in range(1, N):

        ret += (N - 1) // i

    print(ret)

if __name__ == '__main__':

    main()

import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array

# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque
sys.setrecursionlimit(10000000)
ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]
iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]
lcm = lambda x, y: (x * y) // math.gcd(x, y)
MOD = 10**9 + 7
INF = float("inf")

def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")
    N = ii()
    ret = 0
    for a in range(1, N):
        b = N // a
        if N - (a * b) <= 0:
            ret += b - 1
        else:
            ret += b
    print(ret)

if __name__ == "__main__":
    main()

import sys
import os
import math
import bisect
import itertools
import collections
import heapq
import queue
import array

# 時々使う
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque
# 再帰の制限設定
sys.setrecursionlimit(10000000)

def ii():
    return int(sys.stdin.buffer.readline().rstrip())

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

def fl():
    return list(map(float, sys.stdin.buffer.readline().split()))

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

def iss():
    return sys.stdin.buffer.readline().decode().rstrip()

def sl():
    return list(map(str, sys.stdin.buffer.readline().decode().split()))

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

def lcm(x, y):
    return (x * y) // math.gcd(x, y)

MOD = 10**9 + 7
INF = float("inf")

def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")
    N = ii()
    ret = 0
    for i in range(1, N):
        ret += (N - 1) // i
    print(ret)

if __name__ == "__main__":
    main()

-import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array

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

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

-fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))

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

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

-sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))

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

-lcm = lambda x, y: (x * y) // math.gcd(x, y)

+    return int(sys.stdin.buffer.readline().rstrip())

+    return list(map(int, sys.stdin.buffer.readline().split()))

+    return list(map(float, sys.stdin.buffer.readline().split()))

+    return [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

+    return sys.stdin.buffer.readline().decode().rstrip()

+    return list(map(str, sys.stdin.buffer.readline().decode().split()))

+    return [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]


Input:
A = int(eval(input())) #500

B = int(eval(input())) #100

C = int(eval(input())) #50

X = int(eval(input())) #sum

count = 0

for a in range(A + 1):

    for b in range(B + 1):

        for c in range(C + 1):

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

                count += 1

print(count)

import sys

input = sys.stdin.readline

A = int(eval(input())) #500

B = int(eval(input())) #100

C = int(eval(input())) #50

X = int(eval(input())) #sum

count = 0

for a in range(A + 1):

    for b in range(B + 1):

        if 500 * a + 100 * b <= X <= 500 * a + 100 * b + 50 * C:

            count += 1

print(count)

A = int(eval(input()))  # 500
B = int(eval(input()))  # 100
C = int(eval(input()))  # 50
X = int(eval(input()))  # sum
count = 0
for a in range(A + 1):
    for b in range(B + 1):
        for c in range(C + 1):
            if 500 * a + 100 * b + 50 * c == X:
                count += 1
print(count)

import sys

input = sys.stdin.readline
A = int(eval(input()))  # 500
B = int(eval(input()))  # 100
C = int(eval(input()))  # 50
X = int(eval(input()))  # sum
count = 0
for a in range(A + 1):
    for b in range(B + 1):
        if 500 * a + 100 * b <= X <= 500 * a + 100 * b + 50 * C:
            count += 1
print(count)


Input:
s = eval(input())

odd_string = ""

for i, c in enumerate(s):

    if i % 2 == 0:

        odd_string += c

print(odd_string)

s = eval(input())

odd_string = s[::2]

print(odd_string)

-odd_string = ""
-for i, c in enumerate(s):
-    if i % 2 == 0:
-        odd_string += c
+odd_string = s[::2]


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

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

ans = 0

x_ = 0

for x in T:

    if x-x_ >= t:

        ans += t

    else:

        ans += x-x_

    x_ = x

ans += t

print(ans)

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

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

ans = 0

Y = []

for i in range(n-1):

    Y.append(X[i+1]-X[i])

ans = 0

for y in Y:

    ans += min(T, y)

ans += T

print(ans)

n, t = list(map(int, input().split()))
T = list(map(int, input().split()))
ans = 0
x_ = 0
for x in T:
    if x - x_ >= t:
        ans += t
    else:
        ans += x - x_
    x_ = x
ans += t
print(ans)

n, T = list(map(int, input().split()))
X = list(map(int, input().split()))
ans = 0
Y = []
for i in range(n - 1):
    Y.append(X[i + 1] - X[i])
ans = 0
for y in Y:
    ans += min(T, y)
ans += T
print(ans)

-n, t = list(map(int, input().split()))
-T = list(map(int, input().split()))
+n, T = list(map(int, input().split()))
+X = list(map(int, input().split()))
-x_ = 0
-for x in T:
-    if x - x_ >= t:
-        ans += t
-    else:
-        ans += x - x_
-    x_ = x
-ans += t
+Y = []
+for i in range(n - 1):
+    Y.append(X[i + 1] - X[i])
+ans = 0
+for y in Y:
+    ans += min(T, y)
+ans += T


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

print((len(list([x for x in range(1,n+1) if len(str(x))%2 == 1]))))

n = int(eval(input()))

gen = (x for x in range(1,n+1) if len(str(x))%2 == 1)

print((len(list(gen))))

n = int(eval(input()))
print((len(list([x for x in range(1, n + 1) if len(str(x)) % 2 == 1]))))

n = int(eval(input()))
gen = (x for x in range(1, n + 1) if len(str(x)) % 2 == 1)
print((len(list(gen))))

-print((len(list([x for x in range(1, n + 1) if len(str(x)) % 2 == 1]))))

+gen = (x for x in range(1, n + 1) if len(str(x)) % 2 == 1)


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

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

    print('Alice')

else:

    print('Borys')

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

print(('Alice' if (b - a) % 2 == 0 else 'Borys'))

n, a, b = list(map(int, input().split()))
if (b - a) % 2 == 0:
    print("Alice")
else:
    print("Borys")

n, a, b = list(map(int, input().split()))
print(("Alice" if (b - a) % 2 == 0 else "Borys"))

+print(("Alice" if (b - a) % 2 == 0 else "Borys"))


Input:
import sys

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

sys.setrecursionlimit(max(1000, 10**9))

write = lambda x: sys.stdout.write(x+"\n")

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

lx = [None] * n

ly = [None] * m

sx = set([-10**10, 0, 10**10])

sy = set([-10**10, 0, 10**10])

ix = 0

iy = 0

for i in range(n):

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

    lx[i] = t

    sx.add(t[0])

    sx.add(t[1])

    sy.add(t[2])

for i in range(m):

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

    ly[i] = t

    sx.add(t[0])

    sy.add(t[1])

    sy.add(t[2])

xs = list(sx)

ys = list(sy)

xs.sort(); ys.sort()

wx = len(xs)*2

wy = len(ys)*2

bs = [[1]*wy for _ in range(wx)]

import bisect

for i, (x0, x1, y) in enumerate(lx):

    ix0 = bisect.bisect_left(xs, x0)*2

    ix1 = bisect.bisect_left(xs, x1)*2

    iy = bisect.bisect_left(ys, y)*2

    for ii in range(ix0, ix1):

        bs[ii][iy] = -1

for i, (x, y0, y1) in enumerate(ly):

    ix = bisect.bisect_left(xs, x)*2

    iy0 = bisect.bisect_left(ys, y0)*2

    iy1 = bisect.bisect_left(ys, y1)*2

    for ii in range(iy0, iy1):

        bs[ix][ii] = -1

xx = bisect.bisect_left(xs, 0)*2+1

yy = bisect.bisect_left(ys, 0)*2+1

s = [(xx,yy)]

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

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

ans = 0

end = False

while s:

    ix,iy = s.pop()

    for x, y in zip(dx,dy):

        ixx = ix + x

        iyy = iy + y

        if bs[ixx][iyy]!=1:

            continue

        ixx += x

        iyy += y

        if bs[ixx][iyy]!=1:

            continue

        if ixx<0 or ixx>=wx-1 or iyy<0 or iyy>=wy-1:

            print("INF")

            s = []

            end = True

            break

        bs[ixx][iyy] = 2

        ans += (xs[ixx//2+1] - xs[ixx//2]) * (ys[iyy//2+1] - ys[iyy//2])

        s.append((ixx, iyy))

if not end:

    print(ans)

def main():

    import sys

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

    sys.setrecursionlimit(max(1000, 10**9))

    write = lambda x: sys.stdout.write(x+"\n")

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

    lx = [None] * n

    ly = [None] * m

    sx = set([-10**10, 0, 10**10])

    sy = set([-10**10, 0, 10**10])

    ix = 0

    iy = 0

    for i in range(n):

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

        lx[i] = t

        sx.add(t[0])

        sx.add(t[1])

        sy.add(t[2])

    for i in range(m):

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

        ly[i] = t

        sx.add(t[0])

        sy.add(t[1])

        sy.add(t[2])

    xs = list(sx)

    ys = list(sy)

    xs.sort(); ys.sort()

    wx = len(xs)*2

    wy = len(ys)*2

    bs = [[1]*wy for _ in range(wx)]

    import bisect

    for i, (x0, x1, y) in enumerate(lx):

        ix0 = bisect.bisect_left(xs, x0)*2

        ix1 = bisect.bisect_left(xs, x1)*2

        iy = bisect.bisect_left(ys, y)*2

        for ii in range(ix0+1, ix1, 2):

            bs[ii][iy] = -1

    for i, (x, y0, y1) in enumerate(ly):

        ix = bisect.bisect_left(xs, x)*2

        iy0 = bisect.bisect_left(ys, y0)*2

        iy1 = bisect.bisect_left(ys, y1)*2

        for ii in range(iy0+1, iy1, 2):

            bs[ix][ii] = -1

    xx = bisect.bisect_left(xs, 0)*2+1

    yy = bisect.bisect_left(ys, 0)*2+1

    s = [(xx,yy)]

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

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

    ans = 0

    end = False

    while s:

        ix,iy = s.pop()

        for x, y in zip(dx,dy):

            ixx = ix + x

            iyy = iy + y

            if bs[ixx][iyy]!=1:

                continue

            ixx += x

            iyy += y

            if bs[ixx][iyy]!=1:

                continue

            if ixx<0 or ixx>=wx-1 or iyy<0 or iyy>=wy-1:

                print("INF")

                s = []

                end = True

                break

            bs[ixx][iyy] = 2

            ans += (xs[ixx//2+1] - xs[ixx//2]) * (ys[iyy//2+1] - ys[iyy//2])

            s.append((ixx, iyy))

    if not end:

        print(ans)

main()

import sys

input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x + "\n")
n, m = list(map(int, input().split()))
lx = [None] * n
ly = [None] * m
sx = set([-(10**10), 0, 10**10])
sy = set([-(10**10), 0, 10**10])
ix = 0
iy = 0
for i in range(n):
    t = tuple(map(int, input().split()))
    lx[i] = t
    sx.add(t[0])
    sx.add(t[1])
    sy.add(t[2])
for i in range(m):
    t = tuple(map(int, input().split()))
    ly[i] = t
    sx.add(t[0])
    sy.add(t[1])
    sy.add(t[2])
xs = list(sx)
ys = list(sy)
xs.sort()
ys.sort()
wx = len(xs) * 2
wy = len(ys) * 2
bs = [[1] * wy for _ in range(wx)]
import bisect

for i, (x0, x1, y) in enumerate(lx):
    ix0 = bisect.bisect_left(xs, x0) * 2
    ix1 = bisect.bisect_left(xs, x1) * 2
    iy = bisect.bisect_left(ys, y) * 2
    for ii in range(ix0, ix1):
        bs[ii][iy] = -1
for i, (x, y0, y1) in enumerate(ly):
    ix = bisect.bisect_left(xs, x) * 2
    iy0 = bisect.bisect_left(ys, y0) * 2
    iy1 = bisect.bisect_left(ys, y1) * 2
    for ii in range(iy0, iy1):
        bs[ix][ii] = -1
xx = bisect.bisect_left(xs, 0) * 2 + 1
yy = bisect.bisect_left(ys, 0) * 2 + 1
s = [(xx, yy)]
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
ans = 0
end = False
while s:
    ix, iy = s.pop()
    for x, y in zip(dx, dy):
        ixx = ix + x
        iyy = iy + y
        if bs[ixx][iyy] != 1:
            continue
        ixx += x
        iyy += y
        if bs[ixx][iyy] != 1:
            continue
        if ixx < 0 or ixx >= wx - 1 or iyy < 0 or iyy >= wy - 1:
            print("INF")
            s = []
            end = True
            break
        bs[ixx][iyy] = 2
        ans += (xs[ixx // 2 + 1] - xs[ixx // 2]) * (ys[iyy // 2 + 1] - ys[iyy // 2])
        s.append((ixx, iyy))
if not end:
    print(ans)

def main():
    import sys

    input = lambda: sys.stdin.readline().rstrip()
    sys.setrecursionlimit(max(1000, 10**9))
    write = lambda x: sys.stdout.write(x + "\n")
    n, m = list(map(int, input().split()))
    lx = [None] * n
    ly = [None] * m
    sx = set([-(10**10), 0, 10**10])
    sy = set([-(10**10), 0, 10**10])
    ix = 0
    iy = 0
    for i in range(n):
        t = tuple(map(int, input().split()))
        lx[i] = t
        sx.add(t[0])
        sx.add(t[1])
        sy.add(t[2])
    for i in range(m):
        t = tuple(map(int, input().split()))
        ly[i] = t
        sx.add(t[0])
        sy.add(t[1])
        sy.add(t[2])
    xs = list(sx)
    ys = list(sy)
    xs.sort()
    ys.sort()
    wx = len(xs) * 2
    wy = len(ys) * 2
    bs = [[1] * wy for _ in range(wx)]
    import bisect

    for i, (x0, x1, y) in enumerate(lx):
        ix0 = bisect.bisect_left(xs, x0) * 2
        ix1 = bisect.bisect_left(xs, x1) * 2
        iy = bisect.bisect_left(ys, y) * 2
        for ii in range(ix0 + 1, ix1, 2):
            bs[ii][iy] = -1
    for i, (x, y0, y1) in enumerate(ly):
        ix = bisect.bisect_left(xs, x) * 2
        iy0 = bisect.bisect_left(ys, y0) * 2
        iy1 = bisect.bisect_left(ys, y1) * 2
        for ii in range(iy0 + 1, iy1, 2):
            bs[ix][ii] = -1
    xx = bisect.bisect_left(xs, 0) * 2 + 1
    yy = bisect.bisect_left(ys, 0) * 2 + 1
    s = [(xx, yy)]
    dx = [-1, 0, 1, 0]
    dy = [0, -1, 0, 1]
    ans = 0
    end = False
    while s:
        ix, iy = s.pop()
        for x, y in zip(dx, dy):
            ixx = ix + x
            iyy = iy + y
            if bs[ixx][iyy] != 1:
                continue
            ixx += x
            iyy += y
            if bs[ixx][iyy] != 1:
                continue
            if ixx < 0 or ixx >= wx - 1 or iyy < 0 or iyy >= wy - 1:
                print("INF")
                s = []
                end = True
                break
            bs[ixx][iyy] = 2
            ans += (xs[ixx // 2 + 1] - xs[ixx // 2]) * (ys[iyy // 2 + 1] - ys[iyy // 2])
            s.append((ixx, iyy))
    if not end:
        print(ans)

main()

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

-write = lambda x: sys.stdout.write(x + "\n")

-    t = tuple(map(int, input().split()))

-    t = tuple(map(int, input().split()))

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

+    sys.setrecursionlimit(max(1000, 10**9))

+    write = lambda x: sys.stdout.write(x + "\n")

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

+        t = tuple(map(int, input().split()))

+        t = tuple(map(int, input().split()))

-    ix0 = bisect.bisect_left(xs, x0) * 2

-    ix1 = bisect.bisect_left(xs, x1) * 2

-    iy0 = bisect.bisect_left(ys, y0) * 2

-    iy1 = bisect.bisect_left(ys, y1) * 2

-        if ixx < 0 or ixx >= wx - 1 or iyy < 0 or iyy >= wy - 1:

+    for i, (x0, x1, y) in enumerate(lx):

+        ix0 = bisect.bisect_left(xs, x0) * 2

+        ix1 = bisect.bisect_left(xs, x1) * 2

+        iy = bisect.bisect_left(ys, y) * 2

+        for ii in range(ix0 + 1, ix1, 2):

+    for i, (x, y0, y1) in enumerate(ly):

+        ix = bisect.bisect_left(xs, x) * 2

+        iy0 = bisect.bisect_left(ys, y0) * 2

+        iy1 = bisect.bisect_left(ys, y1) * 2

+        for ii in range(iy0 + 1, iy1, 2):

+    xx = bisect.bisect_left(xs, 0) * 2 + 1

+    yy = bisect.bisect_left(ys, 0) * 2 + 1

+            if ixx < 0 or ixx >= wx - 1 or iyy < 0 or iyy >= wy - 1:


Input:
from scipy.signal import*

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

b=[0]*2**17

for i in a:b[i]+=1

i=2**18-1

c=0

for a in(fftconvolve(b,b)+.5).astype(int)[::-1]:

  i-=1

  if a:

    t=min(m,a)

    c+=i*t

    m-=t

    if not m:break

print(c)

import cmath

pi = cmath.pi

exp = cmath.exp

N=2**18

def make_exp_t(N, base):

    exp_t = {0: 1}

    temp = N

    while temp:

        exp_t[temp] = exp(base / temp)

        temp >>= 1

    return exp_t

fft_exp_t = make_exp_t(N, -2j*pi)

ifft_exp_t = make_exp_t(N, 2j*pi)

def fft_dfs(f, s, N, st, exp_t):

    if N==2:

        a = f[s]; b = f[s+st]

        return [a+b, a-b]

    N2 = N//2; st2 = st*2

    F0 = fft_dfs(f, s   , N2, st2, exp_t)

    F1 = fft_dfs(f, s+st, N2, st2, exp_t)

    w = exp_t[N]; wk = 1.0

    for k in range(N2):

        U = F0[k]; V = wk * F1[k]

        F0[k] = U + V

        F1[k] = U - V

        wk *= w

    F0.extend(F1)

    return F0

def fft(f, N):

    if N==1:

        return f

    return fft_dfs(f, 0, N, 1, fft_exp_t)

def ifft(F, N):

    if N==1:

        return F

    f = fft_dfs(F, 0, N, 1, ifft_exp_t)

    for i in range(N):

        f[i] /= N

    return f

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

b=[0]*N

for i in a:b[i]+=1

i=N

c=0

for a in ifft([t*t for t in fft(b,N)],N)[::-1]:

  a=int(a.real+.5)

  i-=1

  if a:

    t=min(m,a)

    c+=i*t

    m-=t

    if not m:break

print(c)

from scipy.signal import *

n, m, *a = list(map(int, open(0).read().split()))
b = [0] * 2**17
for i in a:
    b[i] += 1
i = 2**18 - 1
c = 0
for a in (fftconvolve(b, b) + 0.5).astype(int)[::-1]:
    i -= 1
    if a:
        t = min(m, a)
        c += i * t
        m -= t
        if not m:
            break
print(c)

import cmath

pi = cmath.pi
exp = cmath.exp
N = 2**18

def make_exp_t(N, base):
    exp_t = {0: 1}
    temp = N
    while temp:
        exp_t[temp] = exp(base / temp)
        temp >>= 1
    return exp_t

fft_exp_t = make_exp_t(N, -2j * pi)
ifft_exp_t = make_exp_t(N, 2j * pi)

def fft_dfs(f, s, N, st, exp_t):
    if N == 2:
        a = f[s]
        b = f[s + st]
        return [a + b, a - b]
    N2 = N // 2
    st2 = st * 2
    F0 = fft_dfs(f, s, N2, st2, exp_t)
    F1 = fft_dfs(f, s + st, N2, st2, exp_t)
    w = exp_t[N]
    wk = 1.0
    for k in range(N2):
        U = F0[k]
        V = wk * F1[k]
        F0[k] = U + V
        F1[k] = U - V
        wk *= w
    F0.extend(F1)
    return F0

def fft(f, N):
    if N == 1:
        return f
    return fft_dfs(f, 0, N, 1, fft_exp_t)

def ifft(F, N):
    if N == 1:
        return F
    f = fft_dfs(F, 0, N, 1, ifft_exp_t)
    for i in range(N):
        f[i] /= N
    return f

n, m, *a = list(map(int, open(0).read().split()))
b = [0] * N
for i in a:
    b[i] += 1
i = N
c = 0
for a in ifft([t * t for t in fft(b, N)], N)[::-1]:
    a = int(a.real + 0.5)
    i -= 1
    if a:
        t = min(m, a)
        c += i * t
        m -= t
        if not m:
            break
print(c)

+    F1 = fft_dfs(f, s + st, N2, st2, exp_t)

+    return fft_dfs(f, 0, N, 1, fft_exp_t)

+    f = fft_dfs(F, 0, N, 1, ifft_exp_t)

-for a in (fftconvolve(b, b) + 0.5).astype(int)[::-1]:

+for a in ifft([t * t for t in fft(b, N)], N)[::-1]:


Input:
M=10**9+7

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

a=0

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

    l=i*~-i//2

    r=n*-~n//2-(n-i)*(n-i+1)//2

    a=(a+r+1-l)%M

print(a)

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

print((sum(-~i+i*(n-i)for i in range(k,n+2))%(10**9+7)))

n, k = list(map(int, input().split()))
print((sum(-~i + i * (n - i) for i in range(k, n + 2)) % (10**9 + 7)))


Input:
s = eval(input())

l = ['Sunny', 'Cloudy', 'Rainy']

print((l[l.index(s)-2]))

s = eval(input())
l = ["Sunny", "Cloudy", "Rainy"]
print((l[l.index(s) - 2]))

L = ["Sunny", "Cloudy", "Rainy"]
print((L[(L.index(eval(input())) + 1) % 3]))

+print((L[(L.index(eval(input())) + 1) % 3]))


Input:
from heapq import heappop, heappush

n = int(eval(input()))

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

def biggest(grid, start, cost=0):

    dist = [[0 for _ in range(n)] for _ in range(2)]

    dx = [1, 0]

    dy = [0, 1]

    st = [(cost, start)]

    dist[start[0]][start[1]] = grid[start[0]][start[1]] + cost

    while(st):

        c, [sx, sy] = heappop(st)

        for a, b in zip(dx, dy):

            x = sx + a

            y = sy + b

            if x >= 2 or y >= n:

              continue

            dxy = dist[sx][sy] + grid[x][y]

            if dist[x][y] >= dxy:

                continue

            dist[x][y] = dxy

            heappush(st, (dist[x][y], [x, y]))

    return dist[-1][-1]

dist = biggest(grid, [0, 0], cost=0)

print(dist)

n = int(eval(input()))

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

dist = [[0 for _ in range(n)] for _ in range(2)]

dist[0][0] = grid[0][0]

for i in range(2):

  for j in range(n):

    if j < n - 1:

      dist[i][j + 1] = max(dist[i][j + 1], dist[i][j] + grid[i][j + 1])

    if i == 0:

      dist[1][j] = max(dist[1][j], dist[0][j] + grid[1][j])

print((dist[-1][-1]))

from heapq import heappop, heappush

n = int(eval(input()))
grid = [list(map(int, input().split())), list(map(int, input().split()))]

def biggest(grid, start, cost=0):
    dist = [[0 for _ in range(n)] for _ in range(2)]
    dx = [1, 0]
    dy = [0, 1]
    st = [(cost, start)]
    dist[start[0]][start[1]] = grid[start[0]][start[1]] + cost
    while st:
        c, [sx, sy] = heappop(st)
        for a, b in zip(dx, dy):
            x = sx + a
            y = sy + b
            if x >= 2 or y >= n:
                continue
            dxy = dist[sx][sy] + grid[x][y]
            if dist[x][y] >= dxy:
                continue
            dist[x][y] = dxy
            heappush(st, (dist[x][y], [x, y]))
    return dist[-1][-1]

dist = biggest(grid, [0, 0], cost=0)
print(dist)

-    dist = [[0 for _ in range(n)] for _ in range(2)]

-    dist[start[0]][start[1]] = grid[start[0]][start[1]] + cost

-            dxy = dist[sx][sy] + grid[x][y]

-            heappush(st, (dist[x][y], [x, y]))

+dist = [[0 for _ in range(n)] for _ in range(2)]