Input:
def main():

  while True:

    n = int(eval(input()))

    if not n:

      break

    start = int(eval(input())) - 1 #開始の位置

    goal = int(eval(input())) - 1  #あたりの位置

    d = int(eval(input()))

    nums = [[i for i in range(n)]] #各段での数字の並び

    bars = [] #横棒リスト

    for i in range(d):

      s = eval(input())

      bars.append(s)

      new = nums[-1][:]

      for j in range(n - 1):

        if s[j] == "1": #横棒があれば入れ替え

          new[j], new[j + 1] = new[j + 1], new[j]

      nums.append(new)

    to_goal = nums[-1][goal] #あたりにたどり着く初期位置

    if to_goal == start: #元からあたりにたどり着く場合

      print((0))

    else: #各段について、to_goalとスタートが隣り合うかチェック

      for i, status in enumerate(nums[1:]):

        to_goal_ind = status.index(to_goal) #to_goalの位置

        start_ind = status.index(start)     #startの位置

        ind1, ind2 = min(to_goal_ind, start_ind), max(to_goal_ind, start_ind)

        if ind2 - ind1 == 1:  #隣あっていた場合

          if (bars[i][ind1] == "0") and (ind1 == 0 or bars[i][ind1 - 1] == "0") and (ind2 == n - 1 or bars[i][ind2] == "0"):  #隣り合う横棒がなければ(入れ替え可能ならば)出力

            print((i + 1, ind1 + 1))

            break

      else:

        print((1))

main()

while True:

  n = int(eval(input()))

  if not n:

    break

  start = int(eval(input())) - 1 #開始の位置

  goal = int(eval(input())) - 1  #あたりの位置

  d = int(eval(input()))

  nums = [[i for i in range(n)]] #各段での数字の並び

  bars = [] #横棒リスト

  for i in range(d):

    s = eval(input())

    bars.append(s)

    new = nums[-1][:]

    for j in range(n - 1):

      if s[j] == "1": #横棒があれば入れ替え

        new[j], new[j + 1] = new[j + 1], new[j]

    nums.append(new)

  to_goal = nums[-1][goal] #あたりにたどり着く初期位置

  if to_goal == start: #元からあたりにたどり着く場合

    print((0))

  else: #各段について、to_goalとスタートが隣り合うかチェック

    for i, status in enumerate(nums[1:]):

      to_goal_ind = status.index(to_goal) #to_goalの位置

      start_ind = status.index(start)     #startの位置

      ind1, ind2 = min(to_goal_ind, start_ind), max(to_goal_ind, start_ind)

      if (ind2 - ind1 == 1                               #隣り合っていて、

          and bars[i][ind1] == "0"                       #該当位置と

          and (ind1 == 0 or bars[i][ind1 - 1] == "0")    #左と

          and (ind2 == n - 1 or bars[i][ind2] == "0")):  #右に、辺がなければ出力

          print((i + 1, ind1 + 1))

          break

    else:

      print((1))

def main():
    while True:
        n = int(eval(input()))
        if not n:
            break
        start = int(eval(input())) - 1  # 開始の位置
        goal = int(eval(input())) - 1  # あたりの位置
        d = int(eval(input()))
        nums = [[i for i in range(n)]]  # 各段での数字の並び
        bars = []  # 横棒リスト
        for i in range(d):
            s = eval(input())
            bars.append(s)
            new = nums[-1][:]
            for j in range(n - 1):
                if s[j] == "1":  # 横棒があれば入れ替え
                    new[j], new[j + 1] = new[j + 1], new[j]
            nums.append(new)
        to_goal = nums[-1][goal]  # あたりにたどり着く初期位置
        if to_goal == start:  # 元からあたりにたどり着く場合
            print((0))
        else:  # 各段について、to_goalとスタートが隣り合うかチェック
            for i, status in enumerate(nums[1:]):
                to_goal_ind = status.index(to_goal)  # to_goalの位置
                start_ind = status.index(start)  # startの位置
                ind1, ind2 = min(to_goal_ind, start_ind), max(to_goal_ind, start_ind)
                if ind2 - ind1 == 1:  # 隣あっていた場合
                    if (
                        (bars[i][ind1] == "0")
                        and (ind1 == 0 or bars[i][ind1 - 1] == "0")
                        and (ind2 == n - 1 or bars[i][ind2] == "0")
                    ):  # 隣り合う横棒がなければ(入れ替え可能ならば)出力
                        print((i + 1, ind1 + 1))
                        break
            else:
                print((1))

main()

while True:
    n = int(eval(input()))
    if not n:
        break
    start = int(eval(input())) - 1  # 開始の位置
    goal = int(eval(input())) - 1  # あたりの位置
    d = int(eval(input()))
    nums = [[i for i in range(n)]]  # 各段での数字の並び
    bars = []  # 横棒リスト
    for i in range(d):
        s = eval(input())
        bars.append(s)
        new = nums[-1][:]
        for j in range(n - 1):
            if s[j] == "1":  # 横棒があれば入れ替え
                new[j], new[j + 1] = new[j + 1], new[j]
        nums.append(new)
    to_goal = nums[-1][goal]  # あたりにたどり着く初期位置
    if to_goal == start:  # 元からあたりにたどり着く場合
        print((0))
    else:  # 各段について、to_goalとスタートが隣り合うかチェック
        for i, status in enumerate(nums[1:]):
            to_goal_ind = status.index(to_goal)  # to_goalの位置
            start_ind = status.index(start)  # startの位置
            ind1, ind2 = min(to_goal_ind, start_ind), max(to_goal_ind, start_ind)
            if (
                ind2 - ind1 == 1  # 隣り合っていて、
                and bars[i][ind1] == "0"  # 該当位置と
                and (ind1 == 0 or bars[i][ind1 - 1] == "0")  # 左と
                and (ind2 == n - 1 or bars[i][ind2] == "0")
            ):  # 右に、辺がなければ出力
                print((i + 1, ind1 + 1))
                break
        else:
            print((1))

-        start = int(eval(input())) - 1  # 開始の位置

-        goal = int(eval(input())) - 1  # あたりの位置

-        nums = [[i for i in range(n)]]  # 各段での数字の並び

-                if s[j] == "1":  # 横棒があれば入れ替え

-                    new[j], new[j + 1] = new[j + 1], new[j]

-        to_goal = nums[-1][goal]  # あたりにたどり着く初期位置

-        if to_goal == start:  # 元からあたりにたどり着く場合

-        else:  # 各段について、to_goalとスタートが隣り合うかチェック

-            for i, status in enumerate(nums[1:]):

-                to_goal_ind = status.index(to_goal)  # to_goalの位置

-                start_ind = status.index(start)  # startの位置

-                ind1, ind2 = min(to_goal_ind, start_ind), max(to_goal_ind, start_ind)

-                if ind2 - ind1 == 1:  # 隣あっていた場合

-                    ):  # 隣り合う横棒がなければ(入れ替え可能ならば)出力

+    start = int(eval(input())) - 1  # 開始の位置

+    goal = int(eval(input())) - 1  # あたりの位置

+    nums = [[i for i in range(n)]]  # 各段での数字の並び

+            if s[j] == "1":  # 横棒があれば入れ替え

+                new[j], new[j + 1] = new[j + 1], new[j]

+    to_goal = nums[-1][goal]  # あたりにたどり着く初期位置

+    if to_goal == start:  # 元からあたりにたどり着く場合

+    else:  # 各段について、to_goalとスタートが隣り合うかチェック

+        for i, status in enumerate(nums[1:]):

+            to_goal_ind = status.index(to_goal)  # to_goalの位置

+            start_ind = status.index(start)  # startの位置

+            ind1, ind2 = min(to_goal_ind, start_ind), max(to_goal_ind, start_ind)

+                ind2 - ind1 == 1  # 隣り合っていて、

+                and bars[i][ind1] == "0"  # 該当位置と

+            ):  # 右に、辺がなければ出力


Input:
import math

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

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

m = a.index(min(a))

print((math.ceil((len(a)-1)/(k-1))))

import math

print(((lambda x:math.ceil((int(x[0])-1)/(int(x[1])-1)))(input().split())))

import math

n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
m = a.index(min(a))
print((math.ceil((len(a) - 1) / (k - 1))))

import math

print(((lambda x: math.ceil((int(x[0]) - 1) / (int(x[1]) - 1)))(input().split())))

+print(((lambda x: math.ceil((int(x[0]) - 1) / (int(x[1]) - 1)))(input().split())))


Input:
from sys import stdin

from bisect import bisect

input = stdin.readline

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

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

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

for i in range(1, N):

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

for i in range(1, M):

    B[i] += B[i - 1]

ans = 0

for i, a in enumerate(A):

    time = K - a

    if time < 0:

        break

    cnt = i + 1

    if time != 0:

        tmp = bisect(B, time)

        cnt += tmp

    ans = max(ans, cnt)

for i, b in enumerate(B):

    time = K - b

    if time < 0:

        break

    cnt = i + 1

    if time != 0:

        tmp = bisect(A, time)

        cnt += tmp

    ans = max(ans, cnt)

print(ans)

from sys import stdin

input = stdin.readline

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

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

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

sumA = [0]

sumB = [0]

for i in range(N):

    sumA.append(sumA[i] + A[i])

for i in range(M):

    sumB.append(sumB[i] + B[i])

ans = 0

t = M

for i in range(N + 1):

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

        if K < sumA[i] + sumB[j]:

            t -= 1

            continue

        else:

            ans = max(ans, i + j)

            break

print(ans)

-from bisect import bisect
-for i in range(1, N):
-    A[i] += A[i - 1]
-for i in range(1, M):
-    B[i] += B[i - 1]
+sumA = [0]
+sumB = [0]
+for i in range(N):
+    sumA.append(sumA[i] + A[i])
+for i in range(M):
+    sumB.append(sumB[i] + B[i])
-for i, a in enumerate(A):
-    time = K - a
-    if time < 0:
-        break
-    cnt = i + 1
-    if time != 0:
-        tmp = bisect(B, time)
-        cnt += tmp
-    ans = max(ans, cnt)
-for i, b in enumerate(B):
-    time = K - b
-    if time < 0:
-        break
-    cnt = i + 1
-    if time != 0:
-        tmp = bisect(A, time)
-        cnt += tmp
-    ans = max(ans, cnt)
+t = M
+for i in range(N + 1):
+    for j in range(t, -1, -1):
+        if K < sumA[i] + sumB[j]:
+            t -= 1
+            continue
+        else:
+            ans = max(ans, i + j)
+            break


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

x=set()

for i in range(n):

    x.add(int(eval(input())))

print((len(x)))

n=int(eval(input()))

print((len(set(eval(input()) for i in range(n)))))

n = int(eval(input()))
x = set()
for i in range(n):
    x.add(int(eval(input())))
print((len(x)))

n = int(eval(input()))
print((len(set(eval(input()) for i in range(n)))))

+print((len(set(eval(input()) for i in range(n)))))


Input:
eval(input())

r = 1

for x in input().split():

  r = max(-1, r * int(x))

  if r > 1e18:

    r = -1

print(r)

eval(input())

r = 1

for x in map(int, input().split()):

  if x == 0:

    r = 0

    break

  if r > 0:

    r *= x

    if r > 1e18:

      r = -1

print(r)

-for x in input().split():
-    r = max(-1, r * int(x))
-    if r > 1e18:
-        r = -1
+for x in map(int, input().split()):
+    if x == 0:
+        r = 0
+        break
+    if r > 0:
+        r *= x
+        if r > 1e18:
+            r = -1


Input:
from collections import Counter

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

X -= 1

Y -= 1

L = []

for i in range(N-1):

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

    L.append(min(abs(i-j),abs(X-i)+abs(Y-j)+1,abs(Y-i)+abs(X-j)+1))

D = Counter(L)

for k in range(1,N):

  print((D[k]))

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

D = [0] * N

for i in range(1,N):

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

    D[min(abs(i-j),abs(X-i)+abs(Y-j)+1,abs(Y-i)+abs(X-j)+1)] += 1

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

from collections import Counter

N, X, Y = list(map(int, input().split()))
X -= 1
Y -= 1
L = []
for i in range(N - 1):
    for j in range(i + 1, N):
        L.append(
            min(abs(i - j), abs(X - i) + abs(Y - j) + 1, abs(Y - i) + abs(X - j) + 1)
        )
D = Counter(L)
for k in range(1, N):
    print((D[k]))

N, X, Y = map(int, input().split())
D = [0] * N
for i in range(1, N):
    for j in range(i + 1, N + 1):
        D[
            min(abs(i - j), abs(X - i) + abs(Y - j) + 1, abs(Y - i) + abs(X - j) + 1)
        ] += 1
print(*D[1:], sep="\n")

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


Input:
mod = 10**9+7

frac = [1]*200001

for i in range(2,200001):

    frac[i] = i * frac[i-1]%mod

fraci = [None]*200001

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

for i in range(-2, -200001-1, -1):

    fraci[i] = fraci[i+1] * (200001 + i + 1) % mod

def comb(a, b):

    if not a >= b >= 0:

        return 0

    return frac[a]*fraci[b]*fraci[a-b]%mod

def count(a, b):

    (r1, c1), (r2, c2) = RC[a], RC[b]

    if c2 < c1:

        return 0

    return comb(r2-r1 + c2-c1, r2-r1)

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

RC = [list(map(int, input().split())) for _ in range(N)] + [[1, 1], [H, W]]

RC.sort()

dpe = [0]*(N+2)

dpo = [0]*(N+2)

dpe[0] += 1

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

    rese = 0

    reso = 0

    for k in range(i):

        t = count(k, i)

        if not t:

            continue

        rese = (rese + t*dpo[k]) % mod

        reso = (reso + t*dpe[k]) % mod

    dpe[i] = rese

    dpo[i] = reso

print(((dpo[-1] - dpe[-1]) % mod))

mod = 10**9+7

frac = [1]*200001

for i in range(2,200001):

    frac[i] = i * frac[i-1]%mod

fraci = [None]*200001

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

for i in range(-2, -200001-1, -1):

    fraci[i] = fraci[i+1] * (200001 + i + 1) % mod

def comb(a, b):

    if not a >= b >= 0:

        return 0

    return frac[a]*fraci[b]*fraci[a-b]%mod

def count(a, b):

    (r1, c1), (r2, c2) = RC[a], RC[b]

    if c2 < c1:

        return 0

    return comb(r2-r1 + c2-c1, r2-r1)

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

RC = [list(map(int, input().split())) for _ in range(N)] + [[1, 1], [H, W]]

RC.sort()

dp = [0]*(N+2)

dp[0] += 1

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

    res = count(0, i)

    for k in range(1, i):

        res = (res - count(k, i)*dp[k]) % mod

    dp[i] = res

print((dp[-1]))

mod = 10**9 + 7
frac = [1] * 200001
for i in range(2, 200001):
    frac[i] = i * frac[i - 1] % mod
fraci = [None] * 200001
fraci[-1] = pow(frac[-1], mod - 2, mod)
for i in range(-2, -200001 - 1, -1):
    fraci[i] = fraci[i + 1] * (200001 + i + 1) % mod

def comb(a, b):
    if not a >= b >= 0:
        return 0
    return frac[a] * fraci[b] * fraci[a - b] % mod

def count(a, b):
    (r1, c1), (r2, c2) = RC[a], RC[b]
    if c2 < c1:
        return 0
    return comb(r2 - r1 + c2 - c1, r2 - r1)

H, W, N = list(map(int, input().split()))
RC = [list(map(int, input().split())) for _ in range(N)] + [[1, 1], [H, W]]
RC.sort()
dpe = [0] * (N + 2)
dpo = [0] * (N + 2)
dpe[0] += 1
for i in range(1, N + 2):
    rese = 0
    reso = 0
    for k in range(i):
        t = count(k, i)
        if not t:
            continue
        rese = (rese + t * dpo[k]) % mod
        reso = (reso + t * dpe[k]) % mod
    dpe[i] = rese
    dpo[i] = reso
print(((dpo[-1] - dpe[-1]) % mod))

mod = 10**9 + 7
frac = [1] * 200001
for i in range(2, 200001):
    frac[i] = i * frac[i - 1] % mod
fraci = [None] * 200001
fraci[-1] = pow(frac[-1], mod - 2, mod)
for i in range(-2, -200001 - 1, -1):
    fraci[i] = fraci[i + 1] * (200001 + i + 1) % mod

def comb(a, b):
    if not a >= b >= 0:
        return 0
    return frac[a] * fraci[b] * fraci[a - b] % mod

def count(a, b):
    (r1, c1), (r2, c2) = RC[a], RC[b]
    if c2 < c1:
        return 0
    return comb(r2 - r1 + c2 - c1, r2 - r1)

H, W, N = list(map(int, input().split()))
RC = [list(map(int, input().split())) for _ in range(N)] + [[1, 1], [H, W]]
RC.sort()
dp = [0] * (N + 2)
dp[0] += 1
for i in range(1, N + 2):
    res = count(0, i)
    for k in range(1, i):
        res = (res - count(k, i) * dp[k]) % mod
    dp[i] = res
print((dp[-1]))

-        rese = (rese + t * dpo[k]) % mod

-        reso = (reso + t * dpe[k]) % mod

+        res = (res - count(k, i) * dp[k]) % mod


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

t = 0

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

 if c%n == 0:

 	t += 1

print(t)

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

t = 0

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

 if c%n == 0:

 	t += 1

print(str(t))

a, b, c = list(map(int, input().split()))
t = 0
for n in range(a, b + 1):
    if c % n == 0:
        t += 1
print(t)

a, b, c = list(map(int, input().split()))
t = 0
for n in range(a, b + 1):
    if c % n == 0:
        t += 1
print(str(t))


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

items = []

for i in range(N):

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

    items.append((b, l, u, u * (X - b), - b * l))

items = sorted(items, key=lambda x: -(x[3] - x[4]))

def f(num):

    cnt = num // X

    mod = num % X

    point = 0

    for i in range(cnt):

        point += items[i][3]

    for i in range(cnt, N):

        point += items[i][4]

    if mod == 0:

        if point >= 0:

            return True

        else:

            return False

    else:

        tmp = -float("inf")

        for i, tmp2 in enumerate(items):

            b, l, u, d1, d2 = tmp2

            if mod >= b:

                mul = u * (mod - b)

            else:

                mul = l * (mod - b)

            if i < cnt:

                tmp = max(tmp, point - d1 + mul + items[cnt][3] - items[cnt][4])

            else:

                tmp = max(tmp, point - d2 + mul)

        if tmp >= 0:

            return True

        else:

            return False

ok = N * X + 1

ng = - 1

while (ok - ng) > 1:

    mid = (ok + ng) // 2

    if f(mid):

        ok = mid

    else:

        ng = mid

print(ok)

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

items = []

for i in range(N):

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

    items.append((b, l, u, u * (X - b), - b * l))

items = sorted(items, key=lambda x: -(x[3] - x[4]))

def f(num):

    cnt = num // X

    mod = num % X

    point = 0

    for i in range(cnt):

        point += items[i][3]

    for i in range(cnt, N):

        point += items[i][4]

    if mod == 0:

        if point >= 0:

            return True

        else:

            return False

    else:

        tmp = -float("inf")

        for i in range(N):

            b, l, u, d1, d2 = items[i]

            if mod >= b:

                mul = u * (mod - b)

            else:

                mul = l * (mod - b)

            if i < cnt:

                tmp = max(tmp, point - d1 + mul + items[cnt][3] - items[cnt][4])

            else:

                tmp = max(tmp, point - d2 + mul)

        if tmp >= 0:

            return True

        else:

            return False

ok = N * X + 1

ng = - 1

while (ok - ng) > 1:

    mid = (ok + ng) // 2

    if f(mid):

        ok = mid

    else:

        ng = mid

print(ok)

N, X = list(map(int, input().split()))
items = []
for i in range(N):
    b, l, u = list(map(int, input().split()))
    items.append((b, l, u, u * (X - b), -b * l))
items = sorted(items, key=lambda x: -(x[3] - x[4]))

def f(num):
    cnt = num // X
    mod = num % X
    point = 0
    for i in range(cnt):
        point += items[i][3]
    for i in range(cnt, N):
        point += items[i][4]
    if mod == 0:
        if point >= 0:
            return True
        else:
            return False
    else:
        tmp = -float("inf")
        for i, tmp2 in enumerate(items):
            b, l, u, d1, d2 = tmp2
            if mod >= b:
                mul = u * (mod - b)
            else:
                mul = l * (mod - b)
            if i < cnt:
                tmp = max(tmp, point - d1 + mul + items[cnt][3] - items[cnt][4])
            else:
                tmp = max(tmp, point - d2 + mul)
        if tmp >= 0:
            return True
        else:
            return False

ok = N * X + 1
ng = -1
while (ok - ng) > 1:
    mid = (ok + ng) // 2
    if f(mid):
        ok = mid
    else:
        ng = mid
print(ok)

N, X = list(map(int, input().split()))
items = []
for i in range(N):
    b, l, u = list(map(int, input().split()))
    items.append((b, l, u, u * (X - b), -b * l))
items = sorted(items, key=lambda x: -(x[3] - x[4]))

def f(num):
    cnt = num // X
    mod = num % X
    point = 0
    for i in range(cnt):
        point += items[i][3]
    for i in range(cnt, N):
        point += items[i][4]
    if mod == 0:
        if point >= 0:
            return True
        else:
            return False
    else:
        tmp = -float("inf")
        for i in range(N):
            b, l, u, d1, d2 = items[i]
            if mod >= b:
                mul = u * (mod - b)
            else:
                mul = l * (mod - b)
            if i < cnt:
                tmp = max(tmp, point - d1 + mul + items[cnt][3] - items[cnt][4])
            else:
                tmp = max(tmp, point - d2 + mul)
        if tmp >= 0:
            return True
        else:
            return False

ok = N * X + 1
ng = -1
while (ok - ng) > 1:
    mid = (ok + ng) // 2
    if f(mid):
        ok = mid
    else:
        ng = mid
print(ok)

-        for i, tmp2 in enumerate(items):


Input:
from collections import deque

import sys

def main():

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

  e=[[]for i in range(a)]

  for i in range(a-1):

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

    e[c1-1].append(c2-1)

    e[c2-1].append(c1-1)

  g=[[]for i in range(a)]

  f=deque([(0,-1)])

  ans=[0 for _ in range(a)]

  for i in range(b):

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

    ans[ten-1]+=p

  i=0

  while len(f)!=0:

    i,fr=f.pop()

    for j in e[i]:

      if j==fr:

        continue

      else:

        ans[j]+=ans[i]

        f.append((j,i))

  print((*ans))

if __name__ == '__main__':

  main()

from collections import deque

import sys

input=sys.stdin.readline

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

e=[[]for i in range(a)]

for i in range(a-1):

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

  e[c1-1].append(c2-1)

  e[c2-1].append(c1-1)

g=[[]for i in range(a)]

f=deque([(0,-1)])

ans=[0 for _ in range(a)]

for i in range(b):

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

  ans[ten-1]+=p

i=0

while len(f)!=0:

  i,fr=f.pop()

  for j in e[i]:

    if j==fr:

      continue

    else:

      ans[j]+=ans[i]

      f.append((j,i))

print((*ans))

from collections import deque
import sys

def main():
    a, b = list(map(int, sys.stdin.readline().split()))
    e = [[] for i in range(a)]
    for i in range(a - 1):
        c1, c2 = list(map(int, sys.stdin.readline().split()))
        e[c1 - 1].append(c2 - 1)
        e[c2 - 1].append(c1 - 1)
    g = [[] for i in range(a)]
    f = deque([(0, -1)])
    ans = [0 for _ in range(a)]
    for i in range(b):
        ten, p = list(map(int, input().split()))
        ans[ten - 1] += p
    i = 0
    while len(f) != 0:
        i, fr = f.pop()
        for j in e[i]:
            if j == fr:
                continue
            else:
                ans[j] += ans[i]
                f.append((j, i))
    print((*ans))

if __name__ == "__main__":
    main()

from collections import deque
import sys

input = sys.stdin.readline
a, b = list(map(int, input().split()))
e = [[] for i in range(a)]
for i in range(a - 1):
    c1, c2 = list(map(int, input().split()))
    e[c1 - 1].append(c2 - 1)
    e[c2 - 1].append(c1 - 1)
g = [[] for i in range(a)]
f = deque([(0, -1)])
ans = [0 for _ in range(a)]
for i in range(b):
    ten, p = list(map(int, input().split()))
    ans[ten - 1] += p
i = 0
while len(f) != 0:
    i, fr = f.pop()
    for j in e[i]:
        if j == fr:
            continue
        else:
            ans[j] += ans[i]
            f.append((j, i))
print((*ans))

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

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

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

+    c1, c2 = list(map(int, input().split()))

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


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

s=eval(input())

happy=0

seq=[]

cur=s[0]

seq.append(cur)

for i in range(1,n):

  if s[i]!=cur:

    seq.append(s[i])

    cur=s[i]

  else:

    happy=happy+1

if len(seq)%2==1:

  rev=len(seq)//2

  print((happy+min(rev,k)*2))

else:

  rev=len(seq)//2

  if rev>k:

    print((happy+k*2))

  else:

    print((happy+(rev-1)*2+1))

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

s=eval(input())

happy=0

cur=s[0]

for i in range(1,n):

  if s[i]==cur:

    happy=happy+1

  else:

    cur=s[i]

print((min(happy+2*k,n-1)))

n, k = list(map(int, input().split()))
s = eval(input())
happy = 0
seq = []
cur = s[0]
seq.append(cur)
for i in range(1, n):
    if s[i] != cur:
        seq.append(s[i])
        cur = s[i]
    else:
        happy = happy + 1
if len(seq) % 2 == 1:
    rev = len(seq) // 2
    print((happy + min(rev, k) * 2))
else:
    rev = len(seq) // 2
    if rev > k:
        print((happy + k * 2))
    else:
        print((happy + (rev - 1) * 2 + 1))

n, k = list(map(int, input().split()))
s = eval(input())
happy = 0
cur = s[0]
for i in range(1, n):
    if s[i] == cur:
        happy = happy + 1
    else:
        cur = s[i]
print((min(happy + 2 * k, n - 1)))


Input:
from heapq import heappush, heappop

from itertools import permutations, accumulate, combinations

import math

import bisect

import numpy as np

from collections import defaultdict, deque

import sys

input = sys.stdin.readline

sys.setrecursionlimit(10 ** 6)

# MOD = 10 ** 9 + 7

INF = float("inf")

class UnionFind:

    def __init__(self, n):

        self.n = n

        self.parents = [-1] * n  # 各要素の親要素の番号を格納するリスト

    def find(self, x):  # 要素xが属するグループの根を返す

        if self.parents[x] < 0:

            return x

        else:

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

            return self.parents[x]

    def union(self, x, y):  # 要素xが属するグループと要素yが属するグループとを併合する

        x = self.find(x)

        y = self.find(y)

        if x == y:

            return

        if self.parents[x] > self.parents[y]:

            x, y = y, x

        self.parents[x] += self.parents[y]

        self.parents[y] = x

    def size(self, x):  # 要素xが属するグループのサイズ（要素数）を返す

        return -self.parents[self.find(x)]

    def same(self, x, y):  # 要素x, yが同じグループに属するかどうかを返す

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

    def members(self, x):  # 要素xが属するグループに属する要素をリストで返す

        root = self.find(x)

        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):  # すべての根の要素をリストで返す

        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):  # グループの数を返す

        return len(self.roots())

    def all_group_members(self):  # {ルート要素: [そのグループに含まれる要素のリスト], ...}の辞書を返す

        return {r: self.members(r) for r in self.roots()}

    def __str__(self):

        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def main():

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

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

    uf_friends = UnionFind(N)

    for _ in range(M):

        a, b = [int(i) - 1 for i in input().split()]

        graph_friends[a].append(b)

        graph_friends[b].append(a)

        uf_friends.union(a, b)

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

    for _ in range(K):

        c, d = [int(i) - 1 for i in input().split()]

        graph_block[c].append(d)

        graph_block[d].append(c)

    ans = [0] * N

    for i in range(N):

        size = uf_friends.size(i) - 1

        for f in graph_friends[i]:  # 「友達関係」の時は外す

            if uf_friends.same(i, f):  # 隣接して絵いるかつ親が同じ

                size -= 1

        for b in graph_block[i]:  # 「ブラック関係」の時は外す

            if uf_friends.same(i, b):  # 隣接してるかつ親が同じ

                size -= 1

        ans[i] = size

    print((*ans))

if __name__ == '__main__':

    main()

from collections import defaultdict, deque

import sys

input = sys.stdin.readline

sys.setrecursionlimit(10 ** 6)

def main():

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

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

    gb = []

    for _ in range(M):

        a, b = [int(i) - 1 for i in input().split()]

        gf[a].append(b)

        gf[b].append(a)

    for _ in range(K):

        c, d = [int(i) - 1 for i in input().split()]

        gb.append((c, d))

    friend = defaultdict(int)

    ans = [0] * N

    par = [None] * N

    def dfs(v):

        if par[v] is None:  # 孤立している時は自分が親になる

            par[v] = v

            friend[par[v]] += 1

        for u in gf[v]:  # 隣接頂点の探索

            if par[u] is None:  # 孤立していたら親を一緒にする

                par[u] = par[v]

                friend[par[v]] += 1

                dfs(u)  # 再度探索する

    for i in range(N):

        if par[i] is None:

            dfs(i)

    for i in range(N):  # グラフサイズ - 隣接頂点数 - 自分自身

        ans[i] += friend[par[i]] - len(gf[i]) - 1

    for c, d in gb:

        if par[c] == par[d]:  # 「ブロック関係」で親が一緒の時は-1

            ans[c] -= 1

            ans[d] -= 1

    print((*ans))

if __name__ == '__main__':

    main()

from heapq import heappush, heappop
from itertools import permutations, accumulate, combinations
import math
import bisect
import numpy as np
from collections import defaultdict, deque
import sys

input = sys.stdin.readline
sys.setrecursionlimit(10**6)
# MOD = 10 ** 9 + 7
INF = float("inf")

class UnionFind:
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n  # 各要素の親要素の番号を格納するリスト

    def find(self, x):  # 要素xが属するグループの根を返す
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):  # 要素xが属するグループと要素yが属するグループとを併合する
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):  # 要素xが属するグループのサイズ（要素数）を返す
        return -self.parents[self.find(x)]

    def same(self, x, y):  # 要素x, yが同じグループに属するかどうかを返す
        return self.find(x) == self.find(y)

    def members(self, x):  # 要素xが属するグループに属する要素をリストで返す
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):  # すべての根の要素をリストで返す
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):  # グループの数を返す
        return len(self.roots())

    def all_group_members(self):  # {ルート要素: [そのグループに含まれる要素のリスト], ...}の辞書を返す
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return "\n".join("{}: {}".format(r, self.members(r)) for r in self.roots())

def main():
    N, M, K = list(map(int, input().split()))
    graph_friends = [[] for _ in range(N)]
    uf_friends = UnionFind(N)
    for _ in range(M):
        a, b = [int(i) - 1 for i in input().split()]
        graph_friends[a].append(b)
        graph_friends[b].append(a)
        uf_friends.union(a, b)
    graph_block = [[] for _ in range(N)]
    for _ in range(K):
        c, d = [int(i) - 1 for i in input().split()]
        graph_block[c].append(d)
        graph_block[d].append(c)
    ans = [0] * N
    for i in range(N):
        size = uf_friends.size(i) - 1
        for f in graph_friends[i]:  # 「友達関係」の時は外す
            if uf_friends.same(i, f):  # 隣接して絵いるかつ親が同じ
                size -= 1
        for b in graph_block[i]:  # 「ブラック関係」の時は外す
            if uf_friends.same(i, b):  # 隣接してるかつ親が同じ
                size -= 1
        ans[i] = size
    print((*ans))

if __name__ == "__main__":
    main()

from collections import defaultdict, deque
import sys

input = sys.stdin.readline
sys.setrecursionlimit(10**6)

def main():
    N, M, K = list(map(int, input().split()))
    gf = [[] for _ in range(N)]
    gb = []
    for _ in range(M):
        a, b = [int(i) - 1 for i in input().split()]
        gf[a].append(b)
        gf[b].append(a)
    for _ in range(K):
        c, d = [int(i) - 1 for i in input().split()]
        gb.append((c, d))
    friend = defaultdict(int)
    ans = [0] * N
    par = [None] * N

    def dfs(v):
        if par[v] is None:  # 孤立している時は自分が親になる
            par[v] = v
            friend[par[v]] += 1
        for u in gf[v]:  # 隣接頂点の探索
            if par[u] is None:  # 孤立していたら親を一緒にする
                par[u] = par[v]
                friend[par[v]] += 1
                dfs(u)  # 再度探索する

    for i in range(N):
        if par[i] is None:
            dfs(i)
    for i in range(N):  # グラフサイズ - 隣接頂点数 - 自分自身
        ans[i] += friend[par[i]] - len(gf[i]) - 1
    for c, d in gb:
        if par[c] == par[d]:  # 「ブロック関係」で親が一緒の時は-1
            ans[c] -= 1
            ans[d] -= 1
    print((*ans))

if __name__ == "__main__":
    main()

-from itertools import permutations, accumulate, combinations

-        self.parents = [-1] * n  # 各要素の親要素の番号を格納するリスト

-    def find(self, x):  # 要素xが属するグループの根を返す

-            self.parents[x] = self.find(self.parents[x])

-    def union(self, x, y):  # 要素xが属するグループと要素yが属するグループとを併合する

-        if self.parents[x] > self.parents[y]:

-        self.parents[x] += self.parents[y]

-    def size(self, x):  # 要素xが属するグループのサイズ（要素数）を返す

-        return -self.parents[self.find(x)]

-    def same(self, x, y):  # 要素x, yが同じグループに属するかどうかを返す

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

-    def members(self, x):  # 要素xが属するグループに属する要素をリストで返す

-        return [i for i in range(self.n) if self.find(i) == root]

-    def roots(self):  # すべての根の要素をリストで返す

-        return [i for i, x in enumerate(self.parents) if x < 0]

-    def group_count(self):  # グループの数を返す

-    def all_group_members(self):  # {ルート要素: [そのグループに含まれる要素のリスト], ...}の辞書を返す

-        return {r: self.members(r) for r in self.roots()}

-        return "\n".join("{}: {}".format(r, self.members(r)) for r in self.roots())

-    graph_friends = [[] for _ in range(N)]

-    graph_block = [[] for _ in range(N)]

+        if par[v] is None:  # 孤立している時は自分が親になる

+            if par[u] is None:  # 孤立していたら親を一緒にする

-        for f in graph_friends[i]:  # 「友達関係」の時は外す

-            if uf_friends.same(i, f):  # 隣接して絵いるかつ親が同じ

-        for b in graph_block[i]:  # 「ブラック関係」の時は外す

-            if uf_friends.same(i, b):  # 隣接してるかつ親が同じ

+    for i in range(N):  # グラフサイズ - 隣接頂点数 - 自分自身

+        ans[i] += friend[par[i]] - len(gf[i]) - 1

+        if par[c] == par[d]:  # 「ブロック関係」で親が一緒の時は-1


Input:
NN = 19

X = [0] * ((1<<NN+1)-1)

def popcount(x):

    x -= (x >> 1) & 0x55555555

    x = (x & 0x33333333) + ((x >> 2) & 0x33333333)

    x = (x + (x >> 4)) & 0x0f0f0f0f

    x += x >> 8

    x += x >> 16

    return x & 0x3f

def update(a, x):

    i = (1<<NN) - 1 + a

    X[i] = x

    while True:

        i = (i-1) // 2

        X[i] = X[2*i+1] | X[2*i+2]

        if i == 0:

            break

def rangeor(a, b):

    l = a + (1<<NN)

    r = b + (1<<NN)

    x = 0

    while l < r:

        if l%2:

            x |= X[l-1]

            l += 1

        if r%2:

            r -= 1

            x |= X[r-1]

        l >>= 1

        r >>= 1

    return x

N = int(eval(input()))

A = [ord(a) - 97 for a in eval(input())]

for i, a in enumerate(A):

    X[(1<<NN) + i] = 1 << a

for i in range((1<<NN)-1)[::-1]:

    X[i] = X[i*2+1] | X[i*2+2]

Q = int(eval(input()))

for _ in range(Q):

    a, b, c = input().rstrip().split()

    if a == "1":

        b = int(b)

        c = ord(c) - 97

        update(b, 1<<c)

    else:

        b, c = int(b), int(c)

        print((popcount(rangeor(b, c+1))))

-    while True:
+    while i:
-        if i == 0:
-            break


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

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

ma = sum(As)

o = dict()

INF = 10**19

from itertools import accumulate

aa = [0] + list(accumulate(As))

for i in range(N):

    for j in range(N-i):

        span = i*N+j

        # 長さi+1, 開始位置jの合成コスト+構成要素の和

        if i == 0:

            o[span] = As[j]

            continue

        C = INF

#        print(i,j,o)

        for k in range(i):

            # 長さk+1とi+1-(k+1)=i-kに分割

#            print(i,j,k*N+j, (i-k-1)*N+j+k, o)

            C = min(C, o[k*N+j]+o[(i-k-1)*N+j+k+1])

#        o[span] = C + sum(As[j:j+i+1])

        o[span] = C + aa[j+i+1] - aa[j]

print((o[span]-ma))

N = int(eval(input()))

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

o = [0]*(N**2)

INF = 10**19

from itertools import accumulate

aa = [0] + list(accumulate(As))

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

    for j in range(N-i+1):

        span = (i-1)*N+j

        # 長さi, 開始位置jの合成コスト+構成要素の和

        if i == 1:

            o[span] = As[j]

            continue

        C = INF

        for k in range(1, i):

            # 長さ,開始位置=(k,j)と(i-k,j+k)

            span1, span2 = (k-1)*N+j, (i-k-1)*N+j+k

            C = min(C, o[span1]+o[span2])

        o[span] = C + aa[(j+i-1)+1] - aa[(j-1)+1]

print((o[span]-aa[-1]))

N = int(eval(input()))
As = list(map(int, input().split()))
ma = sum(As)
o = dict()
INF = 10**19
from itertools import accumulate

aa = [0] + list(accumulate(As))
for i in range(N):
    for j in range(N - i):
        span = i * N + j
        # 長さi+1, 開始位置jの合成コスト+構成要素の和
        if i == 0:
            o[span] = As[j]
            continue
        C = INF
        #        print(i,j,o)
        for k in range(i):
            # 長さk+1とi+1-(k+1)=i-kに分割
            #            print(i,j,k*N+j, (i-k-1)*N+j+k, o)
            C = min(C, o[k * N + j] + o[(i - k - 1) * N + j + k + 1])
        #        o[span] = C + sum(As[j:j+i+1])
        o[span] = C + aa[j + i + 1] - aa[j]
print((o[span] - ma))

N = int(eval(input()))
As = list(map(int, input().split()))
o = [0] * (N**2)
INF = 10**19
from itertools import accumulate

aa = [0] + list(accumulate(As))
for i in range(1, N + 1):
    for j in range(N - i + 1):
        span = (i - 1) * N + j
        # 長さi, 開始位置jの合成コスト+構成要素の和
        if i == 1:
            o[span] = As[j]
            continue
        C = INF
        for k in range(1, i):
            # 長さ,開始位置=(k,j)と(i-k,j+k)
            span1, span2 = (k - 1) * N + j, (i - k - 1) * N + j + k
            C = min(C, o[span1] + o[span2])
        o[span] = C + aa[(j + i - 1) + 1] - aa[(j - 1) + 1]
print((o[span] - aa[-1]))

-        # 長さi+1, 開始位置jの合成コスト+構成要素の和

+        # 長さi, 開始位置jの合成コスト+構成要素の和

-        #        o[span] = C + sum(As[j:j+i+1])

-        o[span] = C + aa[j + i + 1] - aa[j]

+            C = min(C, o[span1] + o[span2])


Input:
from bisect import bisect_left, bisect_right

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

inf = 10**18

shrine = [-inf] + [int(eval(input())) for _ in range(a)] + [inf]

temple = [-inf] + [int(eval(input())) for _ in range(b)] + [inf]

for _ in range(q):

    ans = inf

    x = int(eval(input()))

    index_s = bisect_left(shrine, x)

    index_t = bisect_right(temple, x)

    for i in range(index_s-1, index_s+1):

        s = shrine[i]

        i_t = index_t

        t0, t1 = temple[i_t-1], temple[i_t]

        ans = min(

            ans,

            abs(x - s) + abs(s - t0),

            abs(x - s) + abs(s - t1),

        )

    for i in range(index_t-1, index_t+1):

        t = temple[i]

        i_s = index_s

        s0 = shrine[i_s - 1]

        s1 = shrine[i_s]

        ans = min(

            ans,

            abs(x - t) + abs(t - s0),

            abs(x - t) + abs(t - s1),

        )

    print(ans)

from bisect import bisect_left, bisect_right

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

inf = 10**18

shrine = [-inf] + [int(eval(input())) for _ in range(a)] + [inf]

temple = [-inf] + [int(eval(input())) for _ in range(b)] + [inf]

for _ in range(q):

    ans = inf

    x = int(eval(input()))

    index_s = bisect_left(shrine, x)

    index_t = bisect_right(temple, x)

    for s in [shrine[index_s-1], shrine[index_s]]:

        for t in [temple[index_t-1], temple[index_t]]:

            ans = min(

                ans,

                abs(x-s) + abs(s-t),

                abs(x-t) + abs(s-t)

            )

    print(ans)

from bisect import bisect_left, bisect_right

a, b, q = list(map(int, input().split()))
inf = 10**18
shrine = [-inf] + [int(eval(input())) for _ in range(a)] + [inf]
temple = [-inf] + [int(eval(input())) for _ in range(b)] + [inf]
for _ in range(q):
    ans = inf
    x = int(eval(input()))
    index_s = bisect_left(shrine, x)
    index_t = bisect_right(temple, x)
    for i in range(index_s - 1, index_s + 1):
        s = shrine[i]
        i_t = index_t
        t0, t1 = temple[i_t - 1], temple[i_t]
        ans = min(
            ans,
            abs(x - s) + abs(s - t0),
            abs(x - s) + abs(s - t1),
        )
    for i in range(index_t - 1, index_t + 1):
        t = temple[i]
        i_s = index_s
        s0 = shrine[i_s - 1]
        s1 = shrine[i_s]
        ans = min(
            ans,
            abs(x - t) + abs(t - s0),
            abs(x - t) + abs(t - s1),
        )
    print(ans)

from bisect import bisect_left, bisect_right

a, b, q = list(map(int, input().split()))
inf = 10**18
shrine = [-inf] + [int(eval(input())) for _ in range(a)] + [inf]
temple = [-inf] + [int(eval(input())) for _ in range(b)] + [inf]
for _ in range(q):
    ans = inf
    x = int(eval(input()))
    index_s = bisect_left(shrine, x)
    index_t = bisect_right(temple, x)
    for s in [shrine[index_s - 1], shrine[index_s]]:
        for t in [temple[index_t - 1], temple[index_t]]:
            ans = min(ans, abs(x - s) + abs(s - t), abs(x - t) + abs(s - t))
    print(ans)

-    for i in range(index_s - 1, index_s + 1):

-        t0, t1 = temple[i_t - 1], temple[i_t]

-    for i in range(index_t - 1, index_t + 1):

+    for s in [shrine[index_s - 1], shrine[index_s]]:

+        for t in [temple[index_t - 1], temple[index_t]]:

+            ans = min(ans, abs(x - s) + abs(s - t), abs(x - t) + abs(s - t))


Input:
def mod_inv(n,p):

    if n<0:

        return - mod_inv(-n,p) % p

    if n>p:

        return mod_inv(n % p, p)

    def mod_inv_calc(a,b):

        if b==0:

            return (a,1)

        else:

            s,t = mod_inv_calc(b, a % b)

            d = a//b

            return (t, -t*d+s)

    return mod_inv_calc(p,n)[1] % p

N = int(eval(input()))

A = [int(a) for a in input().split()]

p = 10**9+7

inv_list = [mod_inv(i+1,p) for i in range(N+2)]

fact_list = [1]

for i in range(N):

    fact_list.append(fact_list[i] * (i+1) % p)

s = 0

sum_list = [inv_list[i] * fact_list[N] % p for i in range(N+2)]

for i in range(N):

    s += inv_list[i]

s *= fact_list[N]

s %= p

ans = 0

for i in range(N):

    ans += A[i]*s

    ans %= p

    s += (sum_list[i+1] - sum_list[N-i-1])

    s %= p

print (ans)

N = int(eval(input()))

A = [int(a) for a in input().split()]

P = 10**9+7

def inv(a):

    return pow(a, P-2, P)

s = 0

for i in range(N):

    s += inv(i+1)

ans = 0

for i in range(N):

    ans += s * A[i]

    ans %= P

    s += inv(i+2) - inv(N-i)

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

    ans = ans * i % P

print(ans)

def mod_inv(n, p):
    if n < 0:
        return -mod_inv(-n, p) % p
    if n > p:
        return mod_inv(n % p, p)

    def mod_inv_calc(a, b):
        if b == 0:
            return (a, 1)
        else:
            s, t = mod_inv_calc(b, a % b)
            d = a // b
            return (t, -t * d + s)

    return mod_inv_calc(p, n)[1] % p

N = int(eval(input()))
A = [int(a) for a in input().split()]
p = 10**9 + 7
inv_list = [mod_inv(i + 1, p) for i in range(N + 2)]
fact_list = [1]
for i in range(N):
    fact_list.append(fact_list[i] * (i + 1) % p)
s = 0
sum_list = [inv_list[i] * fact_list[N] % p for i in range(N + 2)]
for i in range(N):
    s += inv_list[i]
s *= fact_list[N]
s %= p
ans = 0
for i in range(N):
    ans += A[i] * s
    ans %= p
    s += sum_list[i + 1] - sum_list[N - i - 1]
    s %= p
print(ans)

N = int(eval(input()))
A = [int(a) for a in input().split()]
P = 10**9 + 7

def inv(a):
    return pow(a, P - 2, P)

s = 0
for i in range(N):
    s += inv(i + 1)
ans = 0
for i in range(N):
    ans += s * A[i]
    ans %= P
    s += inv(i + 2) - inv(N - i)
for i in range(1, N + 1):
    ans = ans * i % P
print(ans)

-            s, t = mod_inv_calc(b, a % b)

-inv_list = [mod_inv(i + 1, p) for i in range(N + 2)]

-    fact_list.append(fact_list[i] * (i + 1) % p)

-sum_list = [inv_list[i] * fact_list[N] % p for i in range(N + 2)]

-    s += sum_list[i + 1] - sum_list[N - i - 1]


Input:
import sys

f = sys.stdin

while True:

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

    if n == 0:

        break

    vegitables = sorted(map(int, f.readline().split()), reverse=True)

    discount = sum(vi for i, vi in enumerate(vegitables) if (i + 1) % m == 0)

    print((sum(vegitables) - discount))

while True:

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

    if n == 0:

        break

    price = sorted(map(int, input().split()), reverse=True)

    print((sum(price) - sum(price[m - 1::m])))

while True:
    n, m = list(map(int, input().split()))
    if n == 0:
        break
    price = sorted(map(int, input().split()), reverse=True)
    print((sum(price) - sum(price[m - 1 :: m])))

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

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

-    vegitables = sorted(map(int, f.readline().split()), reverse=True)

-    discount = sum(vi for i, vi in enumerate(vegitables) if (i + 1) % m == 0)

-    print((sum(vegitables) - discount))

+    price = sorted(map(int, input().split()), reverse=True)

+    print((sum(price) - sum(price[m - 1 :: m])))


Input:
from collections import deque

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

a = []

aindex = 0

for _ in range(M):

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

before1 = 1

before2 = 0

ai=0

if len(a)>0:

    ai = a[aindex]

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

    if i == ai:

        before2 = before1

        before1 = 0

        if aindex < len(a)-1:

            aindex += 1

            ai = a[aindex]

    else:

        current = divmod(before1 + before2, 10**9+7)[1]

        before2 = before1

        before1 = current

print(before1)

from collections import deque

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

a = deque([int(eval(input())) for _ in range(M)])

before1 = 1

before2 = 0

ai = a.popleft() if len(a) else 0

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

    if i == ai:

        before2 = before1

        before1 = 0

        ai = a.popleft() if len(a) else ai

    else:

        current = divmod(before1 + before2, 10**9+7)[1]

        before2 = before1

        before1 = current

print(before1)

from collections import deque

N, M = list(map(int, input().split()))
a = []
aindex = 0
for _ in range(M):
    a.append(int(eval(input())))
before1 = 1
before2 = 0
ai = 0
if len(a) > 0:
    ai = a[aindex]
for i in range(1, N + 1):
    if i == ai:
        before2 = before1
        before1 = 0
        if aindex < len(a) - 1:
            aindex += 1
            ai = a[aindex]
    else:
        current = divmod(before1 + before2, 10**9 + 7)[1]
        before2 = before1
        before1 = current
print(before1)

from collections import deque

N, M = list(map(int, input().split()))
a = deque([int(eval(input())) for _ in range(M)])
before1 = 1
before2 = 0
ai = a.popleft() if len(a) else 0
for i in range(1, N + 1):
    if i == ai:
        before2 = before1
        before1 = 0
        ai = a.popleft() if len(a) else ai
    else:
        current = divmod(before1 + before2, 10**9 + 7)[1]
        before2 = before1
        before1 = current
print(before1)

+a = deque([int(eval(input())) for _ in range(M)])

+        ai = a.popleft() if len(a) else ai


Input:
import sys

sys.setrecursionlimit(10**7)

def I(): return int(sys.stdin.readline().rstrip())

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

def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり

def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし

def S(): return sys.stdin.readline().rstrip()

def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり

def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

D,T,S = MI()

print(('Yes' if S*T >= D else 'No'))

import sys

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

D,T,S = MI()

print(('Yes' if S*T >= D else 'No'))

import sys

sys.setrecursionlimit(10**7)

def I():
    return int(sys.stdin.readline().rstrip())

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

def LI():
    return list(map(int, sys.stdin.readline().rstrip().split()))  # 空白あり

def LI2():
    return list(map(int, sys.stdin.readline().rstrip()))  # 空白なし

def S():
    return sys.stdin.readline().rstrip()

def LS():
    return list(sys.stdin.readline().rstrip().split())  # 空白あり

def LS2():
    return list(sys.stdin.readline().rstrip())  # 空白なし

D, T, S = MI()
print(("Yes" if S * T >= D else "No"))

import sys

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

D, T, S = MI()
print(("Yes" if S * T >= D else "No"))

-    return int(sys.stdin.readline().rstrip())

-    return list(map(int, sys.stdin.readline().rstrip().split()))  # 空白あり

-    return list(map(int, sys.stdin.readline().rstrip()))  # 空白なし

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

-    return list(sys.stdin.readline().rstrip().split())  # 空白あり

-    return list(sys.stdin.readline().rstrip())  # 空白なし


Input:
import sys

sys.setrecursionlimit(2**31-1)

input = sys.stdin.readline

write = lambda x: sys.stdout.write(str(x))

LMIIS = lambda : list(map(int,input().split()))

II = lambda : int(input())

dbg = lambda *something : print(*something) if DEBUG is True else 0

DEBUG = False

def main():

    N = II()

    t = [-1] * N

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

    reached = [False] * N

    for _ in range(N-1):

        u,v,w = LMIIS()

        u -=1

        v -=1

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

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

    dbg(E)

    t[E[0][0][0]] = 0

    def search(u):

        for v,w in E[u]:

            if t[v] == -1:

                t[v] = t[u] if w % 2 == 0 else t[u]^1

                search(v)

    search(E[0][0][0])

    for i in t:

        write(i)

        write(' ')

    pass

if __name__ == '__main__':

    main()

import sys

sys.setrecursionlimit(2**31-1)

input = sys.stdin.readline

write = lambda x: sys.stdout.write(str(x))

LMIIS = lambda : list(map(int,input().split()))

II = lambda : int(input())

dbg = lambda *something : print(*something) if DEBUG is True else 0

DEBUG = False

def main():

    N = II()

    t = [-1] * N

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

    reached = [False] * N

    for _ in range(N-1):

        u,v,w = LMIIS()

        u -=1

        v -=1

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

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

    dbg(E)

    t[E[0][0][0]] = 0

    # def search(u):

    #     for v,w in E[u]:

    #         if t[v] == -1:

    #             t[v] = t[u] if w % 2 == 0 else t[u]^1

    #             search(v)

    # search(E[0][0][0])

    reached = [False] * N

    q = [E[0][0][0]]

    while q:

        u = q.pop()

        reached[u] = True

        for v,w in E[u]:

            if reached[v] != True and  t[v] == -1:

                t[v] = t[u] if w % 2 == 0 else t[u]^1

                q.append(v)

    for i in t:

        write(i)

        write(' ')

    pass

if __name__ == '__main__':

    main()

import sys

sys.setrecursionlimit(2**31 - 1)
input = sys.stdin.readline
write = lambda x: sys.stdout.write(str(x))
LMIIS = lambda: list(map(int, input().split()))
II = lambda: int(input())
dbg = lambda *something: print(*something) if DEBUG is True else 0
DEBUG = False

def main():
    N = II()
    t = [-1] * N
    E = [[] for _ in range(N)]
    reached = [False] * N
    for _ in range(N - 1):
        u, v, w = LMIIS()
        u -= 1
        v -= 1
        E[u].append((v, w))
        E[v].append((u, w))
    dbg(E)
    t[E[0][0][0]] = 0

    def search(u):
        for v, w in E[u]:
            if t[v] == -1:
                t[v] = t[u] if w % 2 == 0 else t[u] ^ 1
                search(v)

    search(E[0][0][0])
    for i in t:
        write(i)
        write(" ")
    pass

if __name__ == "__main__":
    main()

import sys

sys.setrecursionlimit(2**31 - 1)
input = sys.stdin.readline
write = lambda x: sys.stdout.write(str(x))
LMIIS = lambda: list(map(int, input().split()))
II = lambda: int(input())
dbg = lambda *something: print(*something) if DEBUG is True else 0
DEBUG = False

def main():
    N = II()
    t = [-1] * N
    E = [[] for _ in range(N)]
    reached = [False] * N
    for _ in range(N - 1):
        u, v, w = LMIIS()
        u -= 1
        v -= 1
        E[u].append((v, w))
        E[v].append((u, w))
    dbg(E)
    t[E[0][0][0]] = 0
    # def search(u):
    #     for v,w in E[u]:
    #         if t[v] == -1:
    #             t[v] = t[u] if w % 2 == 0 else t[u]^1
    #             search(v)
    # search(E[0][0][0])
    reached = [False] * N
    q = [E[0][0][0]]
    while q:
        u = q.pop()
        reached[u] = True
        for v, w in E[u]:
            if reached[v] != True and t[v] == -1:
                t[v] = t[u] if w % 2 == 0 else t[u] ^ 1
                q.append(v)
    for i in t:
        write(i)
        write(" ")
    pass

if __name__ == "__main__":
    main()

+            if reached[v] != True and t[v] == -1:


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

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

from collections import deque

X=deque(X)

cost=0

now=X.popleft()

while len(X)>0:

    if (X[0]-now)*A<=B:

        cost+=(X[0]-now)*A

    else:cost+=B

    now=X.popleft()

print(cost)

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

now=0

ans=0

for x in map(int,input().split()):

    if now!=0:

        if (x-now)*A>B:

            ans+=B

        else:

            ans+=(x-now)*A

    now=x

print(ans)

N, A, B = list(map(int, input().split()))
X = list(map(int, input().split()))
from collections import deque

X = deque(X)
cost = 0
now = X.popleft()
while len(X) > 0:
    if (X[0] - now) * A <= B:
        cost += (X[0] - now) * A
    else:
        cost += B
    now = X.popleft()
print(cost)

N, A, B = list(map(int, input().split()))
now = 0
ans = 0
for x in map(int, input().split()):
    if now != 0:
        if (x - now) * A > B:
            ans += B
        else:
            ans += (x - now) * A
    now = x
print(ans)

-X = list(map(int, input().split()))
-from collections import deque
-X = deque(X)
-cost = 0
-now = X.popleft()
-while len(X) > 0:
-    if (X[0] - now) * A <= B:
-        cost += (X[0] - now) * A
-    else:
-        cost += B
-    now = X.popleft()
-print(cost)
+now = 0
+ans = 0
+for x in map(int, input().split()):
+    if now != 0:
+        if (x - now) * A > B:
+            ans += B
+        else:
+            ans += (x - now) * A
+    now = x
+print(ans)


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

dist = [0]*(H*W+1)#dist[i]はiからi+Dまでの距離

pos = [[0,0] for i in range(H*W+1)]

for i in range(H):

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

  for j in range(W):

    pos[A[j]] = [i+1, j+1]

for i in range(H*W+1-D):

  dist[i] = abs(pos[i][0]-pos[i+D][0])+abs(pos[i][1]-pos[i+D][1])

distances = [[] for i in range(D)]#あまりがiの距離

for i in range(1,H*W+1-D):

  d = dist[i]

  distances[i%D]+=[d]

distances2 = [[0] for i in range(D)]#累積和に直す

for i in range(D):

  for j in range(len(distances[i])):

    distances2[i]+=[distances2[i][-1]+distances[i][j]]

Q = int(eval(input()))

for i in range(Q):

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

  q = L%D

  l, r = (L-1)//D, (R-1)//D

  print((distances2[q][r]-distances2[q][l]))

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

dist = [0]*(H*W+1)#dist[i]はiからi+Dまでの距離

pos = [[0,0] for i in range(H*W+1)]

for i in range(H):

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

  for j in range(W):

    pos[A[j]] = [i+1, j+1]

for i in range(H*W+1-D):

  dist[i] = abs(pos[i][0]-pos[i+D][0])+abs(pos[i][1]-pos[i+D][1])

distances = [[] for i in range(D)]#あまりがiの距離

for i in range(1,H*W+1-D):

  distances[i%D]+=[dist[i]]

distances2 = [[0] for i in range(D)]#累積和に直す

for i in range(D):

  for j in range(len(distances[i])):

    distances2[i]+=[distances2[i][-1]+distances[i][j]]

Q = int(eval(input()))

for i in range(Q):

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

  l, r = (L-1)//D, (R-1)//D

  print((distances2[L%D][r]-distances2[L%D][l]))

H, W, D = list(map(int, input().split()))
dist = [0] * (H * W + 1)  # dist[i]はiからi+Dまでの距離
pos = [[0, 0] for i in range(H * W + 1)]
for i in range(H):
    A = list(map(int, input().split()))
    for j in range(W):
        pos[A[j]] = [i + 1, j + 1]
for i in range(H * W + 1 - D):
    dist[i] = abs(pos[i][0] - pos[i + D][0]) + abs(pos[i][1] - pos[i + D][1])
distances = [[] for i in range(D)]  # あまりがiの距離
for i in range(1, H * W + 1 - D):
    d = dist[i]
    distances[i % D] += [d]
distances2 = [[0] for i in range(D)]  # 累積和に直す
for i in range(D):
    for j in range(len(distances[i])):
        distances2[i] += [distances2[i][-1] + distances[i][j]]
Q = int(eval(input()))
for i in range(Q):
    L, R = list(map(int, input().split()))
    q = L % D
    l, r = (L - 1) // D, (R - 1) // D
    print((distances2[q][r] - distances2[q][l]))

H, W, D = list(map(int, input().split()))
dist = [0] * (H * W + 1)  # dist[i]はiからi+Dまでの距離
pos = [[0, 0] for i in range(H * W + 1)]
for i in range(H):
    A = list(map(int, input().split()))
    for j in range(W):
        pos[A[j]] = [i + 1, j + 1]
for i in range(H * W + 1 - D):
    dist[i] = abs(pos[i][0] - pos[i + D][0]) + abs(pos[i][1] - pos[i + D][1])
distances = [[] for i in range(D)]  # あまりがiの距離
for i in range(1, H * W + 1 - D):
    distances[i % D] += [dist[i]]
distances2 = [[0] for i in range(D)]  # 累積和に直す
for i in range(D):
    for j in range(len(distances[i])):
        distances2[i] += [distances2[i][-1] + distances[i][j]]
Q = int(eval(input()))
for i in range(Q):
    L, R = list(map(int, input().split()))
    l, r = (L - 1) // D, (R - 1) // D
    print((distances2[L % D][r] - distances2[L % D][l]))

-    print((distances2[q][r] - distances2[q][l]))

+    print((distances2[L % D][r] - distances2[L % D][l]))


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

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

ans = 0

c = 0

def dfs(i, dis, passed):

    if len(passed) == N:

        global c, ans

        c += 1

        ans += dis

        return

    x = P[i][0]

    y = P[i][1]

    for ii in range(N):

        if P[ii] in passed:

            continue

        xx = P[ii][0]

        yy = P[ii][1]

        passed.append([xx, yy])

        dfs(ii, dis + ((x - xx)**2 + (y - yy)**2)**0.5, passed)

        passed.pop(-1)

for i in range(N):

    dfs(i, 0, [P[i]])

print((ans / c))

import math

N = int(eval(input()))

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

dis = 0

c = 0

for i in range(N):

    xi = P[i][0]

    yi = P[i][1]

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

        xj = P[ii][0]

        yj = P[ii][1]

        dis += ((xi - xj)**2 + (yi - yj)**2)**0.5

        c += 1

print((dis / c * (N - 1)))

N = int(eval(input()))
P = [list(map(int, input().split())) for _ in range(N)]
ans = 0
c = 0

def dfs(i, dis, passed):
    if len(passed) == N:
        global c, ans
        c += 1
        ans += dis
        return
    x = P[i][0]
    y = P[i][1]
    for ii in range(N):
        if P[ii] in passed:
            continue
        xx = P[ii][0]
        yy = P[ii][1]
        passed.append([xx, yy])
        dfs(ii, dis + ((x - xx) ** 2 + (y - yy) ** 2) ** 0.5, passed)
        passed.pop(-1)

for i in range(N):
    dfs(i, 0, [P[i]])
print((ans / c))

import math

N = int(eval(input()))
P = [list(map(int, input().split())) for _ in range(N)]
dis = 0
c = 0
for i in range(N):
    xi = P[i][0]
    yi = P[i][1]
    for ii in range(i + 1, N):
        xj = P[ii][0]
        yj = P[ii][1]
        dis += ((xi - xj) ** 2 + (yi - yj) ** 2) ** 0.5
        c += 1
print((dis / c * (N - 1)))


Input:
while 1:

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

    if n==a==b==0:break

    c=0;d=[1]+[0]*2000000

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

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

        else:c+=1

    print(c)

while 1:

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

    if n==a==b==0:break

    c=0;d=[1]*(n+1)

    for x in range(a):

        for i in range(x*b,n+1,a):d[i]=0

    print((sum(d)))

while 1:
    n, a, b = list(map(int, input().split()))
    if n == a == b == 0:
        break
    c = 0
    d = [1] + [0] * 2000000
    for i in range(0, n + 1):
        if d[i]:
            d[i + a] = d[i + b] = 1
        else:
            c += 1
    print(c)

while 1:
    n, a, b = list(map(int, input().split()))
    if n == a == b == 0:
        break
    c = 0
    d = [1] * (n + 1)
    for x in range(a):
        for i in range(x * b, n + 1, a):
            d[i] = 0
    print((sum(d)))

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


Input:
inf = float('inf')

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

ans = inf

X = []

Y = []

XY = []

for _ in range(N):

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

    X.append(x)

    Y.append(y)

    XY.append((x,y))

X = sorted(X)

Y = sorted(Y)

for i in range(N):

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

        for k in range(N):

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

                cnt = 0

                for x, y in XY:

                    if X[i] <= x <= X[j] and Y[k] <= y <= Y[l]:

                        cnt += 1

                if cnt < K: continue

                S = (Y[l]-Y[k])*(X[j]-X[i])

                if S < ans:

                    ans = S

print(ans)

inf = float('inf')

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

ans = inf

X = []

Y = []

XY = []

for _ in range(N):

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

    X.append(x)

    Y.append(y)

    XY.append((x,y))

X = sorted(X)

Y = sorted(Y)

for i, left in enumerate(X):

    for right in X[i+1:]:

        for j, bottom in enumerate(Y):

            for top in Y[j+1:]:

                cnt = 0

                for x, y in XY:

                    if left <= x <= right and bottom <= y <= top:

                        cnt += 1

                if cnt < K: continue

                S = (right-left)*(top-bottom)

                if S < ans:

                    ans = S

print(ans)

inf = float("inf")
N, K = list(map(int, input().split()))
ans = inf
X = []
Y = []
XY = []
for _ in range(N):
    x, y = list(map(int, input().split()))
    X.append(x)
    Y.append(y)
    XY.append((x, y))
X = sorted(X)
Y = sorted(Y)
for i in range(N):
    for j in range(i + 1, N):
        for k in range(N):
            for l in range(k + 1, N):
                cnt = 0
                for x, y in XY:
                    if X[i] <= x <= X[j] and Y[k] <= y <= Y[l]:
                        cnt += 1
                if cnt < K:
                    continue
                S = (Y[l] - Y[k]) * (X[j] - X[i])
                if S < ans:
                    ans = S
print(ans)

inf = float("inf")
N, K = list(map(int, input().split()))
ans = inf
X = []
Y = []
XY = []
for _ in range(N):
    x, y = list(map(int, input().split()))
    X.append(x)
    Y.append(y)
    XY.append((x, y))
X = sorted(X)
Y = sorted(Y)
for i, left in enumerate(X):
    for right in X[i + 1 :]:
        for j, bottom in enumerate(Y):
            for top in Y[j + 1 :]:
                cnt = 0
                for x, y in XY:
                    if left <= x <= right and bottom <= y <= top:
                        cnt += 1
                if cnt < K:
                    continue
                S = (right - left) * (top - bottom)
                if S < ans:
                    ans = S
print(ans)

+                    if left <= x <= right and bottom <= y <= top:

+                S = (right - left) * (top - bottom)


Input:
import itertools,sys

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

N,W = LI()

wv = [LI() for _ in range(N)]

V = 10**5

dp = [[float('INF')]*(V+1) for _ in range(N+1)]

dp[0][0] = 0

for i,j in itertools.product(list(range(1,N+1)),list(range(V+1))):

    w,v = wv[i-1]

    if j-v>=0 and dp[i-1][j-v]+w<=W:

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

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

print((max([i for i in range(V+1) if dp[-1][i]<=W])))

import sys

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

N,W = LI()

wv = [LI() for _ in range(N)]

V = N*10**3

dp = [[float('INF')]*(V+1) for _ in range(N+1)]

dp[0][0] = 0

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

    w,v = wv[i-1]

    for j in range(V+1):

        if j-v>=0 and dp[i-1][j-v]+w<=W:

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

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

print((max([i for i in range(V+1) if dp[-1][i]<=W])))

import itertools, sys

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

N, W = LI()
wv = [LI() for _ in range(N)]
V = 10**5
dp = [[float("INF")] * (V + 1) for _ in range(N + 1)]
dp[0][0] = 0
for i, j in itertools.product(list(range(1, N + 1)), list(range(V + 1))):
    w, v = wv[i - 1]
    if j - v >= 0 and dp[i - 1][j - v] + w <= W:
        dp[i][j] = min(dp[i][j], dp[i - 1][j - v] + w)
    dp[i][j] = min(dp[i][j], dp[i - 1][j])
print((max([i for i in range(V + 1) if dp[-1][i] <= W])))

import sys

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

N, W = LI()
wv = [LI() for _ in range(N)]
V = N * 10**3
dp = [[float("INF")] * (V + 1) for _ in range(N + 1)]
dp[0][0] = 0
for i in range(1, N + 1):
    w, v = wv[i - 1]
    for j in range(V + 1):
        if j - v >= 0 and dp[i - 1][j - v] + w <= W:
            dp[i][j] = min(dp[i][j], dp[i - 1][j - v] + w)
        dp[i][j] = min(dp[i][j], dp[i - 1][j])
print((max([i for i in range(V + 1) if dp[-1][i] <= W])))

-for i, j in itertools.product(list(range(1, N + 1)), list(range(V + 1))):


Input:
from collections import Counter

N = int(eval(input()))

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

C = Counter(A)

ans = len(C)

if (N-ans) % 2 == 1:

    ans -= 1

print(ans)

N = int(eval(input()))

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

S = set(A)

ans = len(S)

if (N-ans) % 2 == 1:

    ans -= 1

print(ans)

from collections import Counter

N = int(eval(input()))
A = list(map(int, input().split()))
C = Counter(A)
ans = len(C)
if (N - ans) % 2 == 1:
    ans -= 1
print(ans)

N = int(eval(input()))
A = list(map(int, input().split()))
S = set(A)
ans = len(S)
if (N - ans) % 2 == 1:
    ans -= 1
print(ans)

-from collections import Counter
-C = Counter(A)
-ans = len(C)
+S = set(A)
+ans = len(S)


Input:
#!/usr/bin/env python3

from functools import reduce

from operator import mul

from collections import defaultdict, Counter

from heapq import heappush, heappop

import sys

from math import sqrt, floor

sys.setrecursionlimit(10**6)

input = sys.stdin.buffer.readline

INF = 10 ** 9 + 1  # sys.maxsize # float("inf")

def debug(*x):

    print((*x))

def solve(N):

    ret = 0

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

        num = N // i

        end = num * i

        ret += (i + end) * num // 2

    print(ret)

def main():

    N = int(eval(input()))

    solve(N)

def _test():

    """

    >>> solve(4)

    23

    >>> solve(100)

    26879

    >>> solve(10000000)

    838627288460105

    """

    import doctest

    doctest.testmod()

def as_input(s):

    "use in test, use given string as input file"

    import io

    global read, input

    f = io.StringIO(s.strip())

    input = f.readline

    read = f.read

USE_NUMBA = False

if (USE_NUMBA and sys.argv[-1] == 'ONLINE_JUDGE') or sys.argv[-1] == '-c':

    print("compiling")

    from numba.pycc import CC

    cc = CC('my_module')

    cc.export('solve', solve.__doc__.strip().split()[0])(solve)

    cc.compile()

    exit()

else:

    input = sys.stdin.buffer.readline

    read = sys.stdin.buffer.read

    if (USE_NUMBA and sys.argv[-1] != '-p') or sys.argv[-1] == "--numba":

        # -p: pure python mode

        # if not -p, import compiled module

        from my_module import solve  # pylint: disable=all

    elif sys.argv[-1] == "-t":

        _test()

        sys.exit()

    elif sys.argv[-1] != '-p' and len(sys.argv) == 2:

        # input given as file

        input_as_file = open(sys.argv[1])

        input = input_as_file.buffer.readline

        read = input_as_file.buffer.read

    main()

#!/usr/bin/env python3

from functools import reduce

from operator import mul

from collections import defaultdict, Counter

from heapq import heappush, heappop

import sys

from math import sqrt, floor

sys.setrecursionlimit(10**6)

input = sys.stdin.buffer.readline

INF = 10 ** 9 + 1  # sys.maxsize # float("inf")

def debug(*x):

    print((*x))

def solve(N):

    ret = 0

    i = 2

    while True:

        step = i // 2

        start = (i + 1) // 2 * step

        if start > N:

            break

        end = N // step * step

        ret += (start + end) * ((end - start) // step + 1) // 2

        i += 1

    print(ret)

def main():

    N = int(eval(input()))

    solve(N)

def _test():

    """

    >>> solve(4)

    23

    >>> solve(100)

    26879

    >>> solve(10000000)

    838627288460105

    """

    import doctest

    doctest.testmod()

def as_input(s):

    "use in test, use given string as input file"

    import io

    global read, input

    f = io.StringIO(s.strip())

    input = f.readline

    read = f.read

USE_NUMBA = False

if (USE_NUMBA and sys.argv[-1] == 'ONLINE_JUDGE') or sys.argv[-1] == '-c':

    print("compiling")

    from numba.pycc import CC

    cc = CC('my_module')

    cc.export('solve', solve.__doc__.strip().split()[0])(solve)

    cc.compile()

    exit()

else:

    input = sys.stdin.buffer.readline

    read = sys.stdin.buffer.read

    if (USE_NUMBA and sys.argv[-1] != '-p') or sys.argv[-1] == "--numba":

        # -p: pure python mode

        # if not -p, import compiled module

        from my_module import solve  # pylint: disable=all

    elif sys.argv[-1] == "-t":

        _test()

        sys.exit()

    elif sys.argv[-1] != '-p' and len(sys.argv) == 2:

        # input given as file

        input_as_file = open(sys.argv[1])

        input = input_as_file.buffer.readline

        read = input_as_file.buffer.read

    main()

#!/usr/bin/env python3
from functools import reduce
from operator import mul
from collections import defaultdict, Counter
from heapq import heappush, heappop
import sys
from math import sqrt, floor

sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
INF = 10**9 + 1  # sys.maxsize # float("inf")

def debug(*x):
    print((*x))

def solve(N):
    ret = 0
    for i in range(1, N + 1):
        num = N // i
        end = num * i
        ret += (i + end) * num // 2
    print(ret)

def main():
    N = int(eval(input()))
    solve(N)

def _test():
    """
    >>> solve(4)
    23
    >>> solve(100)
    26879
    >>> solve(10000000)
    838627288460105
    """
    import doctest

    doctest.testmod()

def as_input(s):
    "use in test, use given string as input file"
    import io

    global read, input
    f = io.StringIO(s.strip())
    input = f.readline
    read = f.read

USE_NUMBA = False
if (USE_NUMBA and sys.argv[-1] == "ONLINE_JUDGE") or sys.argv[-1] == "-c":
    print("compiling")
    from numba.pycc import CC

    cc = CC("my_module")
    cc.export("solve", solve.__doc__.strip().split()[0])(solve)
    cc.compile()
    exit()
else:
    input = sys.stdin.buffer.readline
    read = sys.stdin.buffer.read
    if (USE_NUMBA and sys.argv[-1] != "-p") or sys.argv[-1] == "--numba":
        # -p: pure python mode
        # if not -p, import compiled module
        from my_module import solve  # pylint: disable=all
    elif sys.argv[-1] == "-t":
        _test()
        sys.exit()
    elif sys.argv[-1] != "-p" and len(sys.argv) == 2:
        # input given as file
        input_as_file = open(sys.argv[1])
        input = input_as_file.buffer.readline
        read = input_as_file.buffer.read
    main()

#!/usr/bin/env python3
from functools import reduce
from operator import mul
from collections import defaultdict, Counter
from heapq import heappush, heappop
import sys
from math import sqrt, floor

sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
INF = 10**9 + 1  # sys.maxsize # float("inf")

def debug(*x):
    print((*x))

def solve(N):
    ret = 0
    i = 2
    while True:
        step = i // 2
        start = (i + 1) // 2 * step
        if start > N:
            break
        end = N // step * step
        ret += (start + end) * ((end - start) // step + 1) // 2
        i += 1
    print(ret)

def main():
    N = int(eval(input()))
    solve(N)

def _test():
    """
    >>> solve(4)
    23
    >>> solve(100)
    26879
    >>> solve(10000000)
    838627288460105
    """
    import doctest

    doctest.testmod()

def as_input(s):
    "use in test, use given string as input file"
    import io

    global read, input
    f = io.StringIO(s.strip())
    input = f.readline
    read = f.read

USE_NUMBA = False
if (USE_NUMBA and sys.argv[-1] == "ONLINE_JUDGE") or sys.argv[-1] == "-c":
    print("compiling")
    from numba.pycc import CC

    cc = CC("my_module")
    cc.export("solve", solve.__doc__.strip().split()[0])(solve)
    cc.compile()
    exit()
else:
    input = sys.stdin.buffer.readline
    read = sys.stdin.buffer.read
    if (USE_NUMBA and sys.argv[-1] != "-p") or sys.argv[-1] == "--numba":
        # -p: pure python mode
        # if not -p, import compiled module
        from my_module import solve  # pylint: disable=all
    elif sys.argv[-1] == "-t":
        _test()
        sys.exit()
    elif sys.argv[-1] != "-p" and len(sys.argv) == 2:
        # input given as file
        input_as_file = open(sys.argv[1])
        input = input_as_file.buffer.readline
        read = input_as_file.buffer.read
    main()

+        ret += (start + end) * ((end - start) // step + 1) // 2


Input:
inf = 2019

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

ans = 0

df = R - L

if df < 2019:

    L = L % inf

    R = L + df

    ans = 2019

    for i in range(L, R):

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

            tmp = int((i * j) % inf)

            ans = min(ans, tmp)

print(ans)

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

MOD = 2019

diff = r - l

ans = 0

if diff < 2019:

    l = l % MOD

    r = l + diff

    ans = 2018

    for i in range(l, r):

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

            ans = min(ans, (i % MOD * j % MOD) % MOD)

print(ans)

+            ans = min(ans, (i % MOD * j % MOD) % MOD)


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

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

diff = [0] * (M - 1)

for i in range(M - 1):

    diff[i] = X[i + 1] - X[i]

print((sum(sorted(diff)[: max(0, M - N)])))

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

if N >= M:

    print((0))

    exit()

X.sort()

diff = []

for i in range(M - 1):

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

diff.sort()

print((sum(diff[: M - N])))

+N, M, *X = list(map(int, open(0).read().split()))

-print((sum(sorted(diff)[: max(0, M - N)])))


Input:
import numpy as np

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

X = np.zeros(h*w, dtype=int)

Y = np.zeros(h*w, dtype=int)

score = np.zeros(h*w, dtype=int)

for x in range(h):

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

    for y in range(w):

        i = int(inp[y]) - 1

        X[i] = x

        Y[i] = y

score[d:] += np.abs(X[d:] - X[:-d]) + np.abs(Y[d:] - Y[:-d])

for i in range(len(score) - d):

    score[i+d] += score[i]

q = int(input())

ans = []

for _ in range(q):

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

    l -= 1

    r -= 1

    ans.append(score[r]-score[l])

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

import sys

read = sys.stdin.buffer.read

readline = sys.stdin.buffer.readline

readlines = sys.stdin.buffer.readlines

sys.setrecursionlimit(10 ** 7)

H, W, D = map(int, readline().split())

A = [list(map(int, readline().split())) for _ in range(H)]

Q = int(readline())

query = [tuple(map(int, readline().split())) for _ in range(Q)]

path = [[(-1, -1)]*((H*W)//D+1) for _ in range(D)]

for i in range(H):

    for j in range(W):

        a = A[i][j]

        div, mod = divmod(a, D)

        path[mod][div] = (i, j)

path[0][0] = path[0][1]

cost = []

for i in range(D):

    tmp = [0]

    for l, r in zip(path[i][:-1], path[i][1:]):

        x, y = l

        z, w = r

        tmp.append(tmp[-1] + abs(z - x) + abs(w - y))

    cost.append(tmp)

ans = []

for L, R in query:

    vl, md = divmod(L, D)

    vr = R // D

    tmp = cost[md][vr] - cost[md][vl]

    ans.append(tmp)

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

import numpy as np

h, w, d = map(int, input().split())
X = np.zeros(h * w, dtype=int)
Y = np.zeros(h * w, dtype=int)
score = np.zeros(h * w, dtype=int)
for x in range(h):
    inp = tuple(map(int, input().split()))
    for y in range(w):
        i = int(inp[y]) - 1
        X[i] = x
        Y[i] = y
score[d:] += np.abs(X[d:] - X[:-d]) + np.abs(Y[d:] - Y[:-d])
for i in range(len(score) - d):
    score[i + d] += score[i]
q = int(input())
ans = []
for _ in range(q):
    l, r = map(int, input().split())
    l -= 1
    r -= 1
    ans.append(score[r] - score[l])
print(*ans, sep="\n")

import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10**7)
H, W, D = map(int, readline().split())
A = [list(map(int, readline().split())) for _ in range(H)]
Q = int(readline())
query = [tuple(map(int, readline().split())) for _ in range(Q)]
path = [[(-1, -1)] * ((H * W) // D + 1) for _ in range(D)]
for i in range(H):
    for j in range(W):
        a = A[i][j]
        div, mod = divmod(a, D)
        path[mod][div] = (i, j)
path[0][0] = path[0][1]
cost = []
for i in range(D):
    tmp = [0]
    for l, r in zip(path[i][:-1], path[i][1:]):
        x, y = l
        z, w = r
        tmp.append(tmp[-1] + abs(z - x) + abs(w - y))
    cost.append(tmp)
ans = []
for L, R in query:
    vl, md = divmod(L, D)
    vr = R // D
    tmp = cost[md][vr] - cost[md][vl]
    ans.append(tmp)
print(*ans, sep="\n")

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

+A = [list(map(int, readline().split())) for _ in range(H)]

+query = [tuple(map(int, readline().split())) for _ in range(Q)]

+    for l, r in zip(path[i][:-1], path[i][1:]):

+        tmp.append(tmp[-1] + abs(z - x) + abs(w - y))


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

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

m = max(2, max(A))

P = {p: True for p in range(2, m + 1)}

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

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

        P[j] = False

Pmap = {p: 0 for p in P if P[p]}

Amap = {a: 0 for a in range(1, m + 1)}

for a in A:

    Amap[a] += 1

for p in Pmap:

    for a in range(p, m + 1, p):

        Pmap[p] += Amap[a]

s = max(Pmap.values())

if s < 2:

    print('pairwise coprime')

elif s < n:

    print('setwise coprime')

else:

    print('not coprime')

n = int(eval(input()))

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

m = max(A)

C = [0 for a in range(m + 1)]

for a in A:

    C[a] += 1

s = 0

for a in range(2, m + 1):

    s = max(s, sum(C[a::a]))

if s < 2:

    print('pairwise coprime')

elif s < n:

    print('setwise coprime')

else:

    print('not coprime')

n = int(eval(input()))
(*A,) = list(map(int, input().split()))
m = max(2, max(A))
P = {p: True for p in range(2, m + 1)}
for i in range(2, m + 1):
    for j in range(2 * i, m + 1, i):
        P[j] = False
Pmap = {p: 0 for p in P if P[p]}
Amap = {a: 0 for a in range(1, m + 1)}
for a in A:
    Amap[a] += 1
for p in Pmap:
    for a in range(p, m + 1, p):
        Pmap[p] += Amap[a]
s = max(Pmap.values())
if s < 2:
    print("pairwise coprime")
elif s < n:
    print("setwise coprime")
else:
    print("not coprime")

n = int(eval(input()))
(*A,) = list(map(int, input().split()))
m = max(A)
C = [0 for a in range(m + 1)]
for a in A:
    C[a] += 1
s = 0
for a in range(2, m + 1):
    s = max(s, sum(C[a::a]))
if s < 2:
    print("pairwise coprime")
elif s < n:
    print("setwise coprime")
else:
    print("not coprime")

-m = max(2, max(A))
-P = {p: True for p in range(2, m + 1)}
-for i in range(2, m + 1):
-    for j in range(2 * i, m + 1, i):
-        P[j] = False
-Pmap = {p: 0 for p in P if P[p]}
-Amap = {a: 0 for a in range(1, m + 1)}
+m = max(A)
+C = [0 for a in range(m + 1)]
-    Amap[a] += 1
-for p in Pmap:
-    for a in range(p, m + 1, p):
-        Pmap[p] += Amap[a]
-s = max(Pmap.values())
+    C[a] += 1
+s = 0
+for a in range(2, m + 1):
+    s = max(s, sum(C[a::a]))


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

ans = -1

for i in range(10,12501):

    if int(i*0.08) == a and int(i * 0.1) == b:

        ans = i

        break

print(ans)

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

import math

if math.ceil((a+1)*12.5) <= math.ceil(b*10) or math.ceil(a*12.5) >= math.ceil((b+1)*10):

    print((-1))

else:

    print((max(math.ceil(a*12.5),math.ceil(b*10))))

a, b = list(map(int, input().split()))
ans = -1
for i in range(10, 12501):
    if int(i * 0.08) == a and int(i * 0.1) == b:
        ans = i
        break
print(ans)

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

if math.ceil((a + 1) * 12.5) <= math.ceil(b * 10) or math.ceil(a * 12.5) >= math.ceil(
    (b + 1) * 10
):
    print((-1))
else:
    print((max(math.ceil(a * 12.5), math.ceil(b * 10))))

+if math.ceil((a + 1) * 12.5) <= math.ceil(b * 10) or math.ceil(a * 12.5) >= math.ceil(

+    print((max(math.ceil(a * 12.5), math.ceil(b * 10))))


Input:
from collections import defaultdict as dd

from itertools import accumulate as ac

from itertools import product as pr

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

d=dd(list)

for _ in range(N):

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

  d[w].extend([v])

d=dict(d)

for i in list(d.keys()):

  d[i].sort(reverse=True)

  d[i]=[0]+list(ac(d[i]))

l=[]

key=list(d.keys())

for val in pr(*list(map(enumerate,list(d.values())))):

  weight=sum(map(lambda x,y:x*y[0],key,val))

  value=sum([x[1] for x in val])

  if weight<=W:

    l.extend([value])

print((max(l)))

from collections import defaultdict

from itertools import accumulate,product

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

d={}

for i in range(N):

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

    if not i:

        for j in range(w,w+4):

            d[j]=[]

    d[w].append(v)

for i in list(d.keys()):

    d[i].sort(reverse=True)

    *d[i],=accumulate([0]+d[i])

ans=0

i,j,k,l=list(d.keys())

for ai,bi in enumerate(d[i]):

    for aj,bj in enumerate(d[j]):

        for ak,bk in enumerate(d[k]):

            for al,bl in enumerate(d[l]):

                if i*ai+j*aj+k*ak+l*al<=W:

                    ans=max(ans,bi+bj+bk+bl)

print(ans)

from collections import defaultdict as dd
from itertools import accumulate as ac
from itertools import product as pr

N, W = list(map(int, input().split()))
d = dd(list)
for _ in range(N):
    w, v = list(map(int, input().split()))
    d[w].extend([v])
d = dict(d)
for i in list(d.keys()):
    d[i].sort(reverse=True)
    d[i] = [0] + list(ac(d[i]))
l = []
key = list(d.keys())
for val in pr(*list(map(enumerate, list(d.values())))):
    weight = sum(map(lambda x, y: x * y[0], key, val))
    value = sum([x[1] for x in val])
    if weight <= W:
        l.extend([value])
print((max(l)))

from collections import defaultdict
from itertools import accumulate, product

N, W = list(map(int, input().split()))
d = {}
for i in range(N):
    w, v = list(map(int, input().split()))
    if not i:
        for j in range(w, w + 4):
            d[j] = []
    d[w].append(v)
for i in list(d.keys()):
    d[i].sort(reverse=True)
    (*d[i],) = accumulate([0] + d[i])
ans = 0
i, j, k, l = list(d.keys())
for ai, bi in enumerate(d[i]):
    for aj, bj in enumerate(d[j]):
        for ak, bk in enumerate(d[k]):
            for al, bl in enumerate(d[l]):
                if i * ai + j * aj + k * ak + l * al <= W:
                    ans = max(ans, bi + bj + bk + bl)
print(ans)

-from collections import defaultdict as dd

+from itertools import accumulate, product

-for val in pr(*list(map(enumerate, list(d.values())))):

-    weight = sum(map(lambda x, y: x * y[0], key, val))

+            for al, bl in enumerate(d[l]):

+                if i * ai + j * aj + k * ak + l * al <= W:

+                    ans = max(ans, bi + bj + bk + bl)


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

ans = 9999999

for a in range(1,N):

    b = N-a

    tmp = 0

    for ac in str(a):

        tmp += int(ac)

    for bc in str(b):

        tmp += int(bc)

    ans = min(ans, tmp)

print(ans)

N = int(eval(input()))

ans = 9999

for a in range(1,N):

    b = N-a

    x = sum(map(int,str(a)))

    y = sum(map(int,str(b)))

    ans = min(ans, x+y)

print(ans)

N = int(eval(input()))
ans = 9999999
for a in range(1, N):
    b = N - a
    tmp = 0
    for ac in str(a):
        tmp += int(ac)
    for bc in str(b):
        tmp += int(bc)
    ans = min(ans, tmp)
print(ans)

N = int(eval(input()))
ans = 9999
for a in range(1, N):
    b = N - a
    x = sum(map(int, str(a)))
    y = sum(map(int, str(b)))
    ans = min(ans, x + y)
print(ans)

-ans = 9999999
+ans = 9999
-    tmp = 0
-    for ac in str(a):
-        tmp += int(ac)
-    for bc in str(b):
-        tmp += int(bc)
-    ans = min(ans, tmp)
+    x = sum(map(int, str(a)))
+    y = sum(map(int, str(b)))
+    ans = min(ans, x + y)


Input:
(a, b) = [int(x) for x in input().split()]

x = a // b

y = a % b

z = a / b

print(('{0} {1} {2:.6f}'.format(x,y,z)))

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

d = a // b

r = a % b

f = a / b

print(("{0} {1} {2:.5f}".format(d, r, f)))

(a, b) = [int(x) for x in input().split()]
x = a // b
y = a % b
z = a / b
print(("{0} {1} {2:.6f}".format(x, y, z)))

-(a, b) = [int(x) for x in input().split()]

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


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

s = eval(input())

if len(s) <= k:

  print(s)

else:

  print((s[:k] + '...'))

k = int(eval(input()))

s = eval(input())

l = len(s)

if l<=k:

  print (s)

else :

  print((s[:k] + '...'))

k = int(eval(input()))
s = eval(input())
if len(s) <= k:
    print(s)
else:
    print((s[:k] + "..."))

k = int(eval(input()))
s = eval(input())
l = len(s)
if l <= k:
    print(s)
else:
    print((s[:k] + "..."))

-if len(s) <= k:
+l = len(s)
+if l <= k:


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

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

lastOn = t[0]

ans = 0

for i in range(1,N):

    ti = t[i]

    ans += min(T, ti-lastOn)

    lastOn = ti

ans += T

print(ans)

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

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

ans = 0

last = -10**10

for a in t:

    ans += T - max(last + T - a, 0)

    last = a

print(ans)

N, T = list(map(int, input().split()))
t = list(map(int, input().split()))
lastOn = t[0]
ans = 0
for i in range(1, N):
    ti = t[i]
    ans += min(T, ti - lastOn)
    lastOn = ti
ans += T
print(ans)

N, T = list(map(int, input().split()))
(*t,) = list(map(int, input().split()))
ans = 0
last = -(10**10)
for a in t:
    ans += T - max(last + T - a, 0)
    last = a
print(ans)

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


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

key = ['A','T','G','C']

count = 0

flag = False

ans = 0

for i in range(len(s)):

  if s[i] in key:

    count += 1

    flag = True

  if flag==True and (s[i] not in key):

    ans = max(ans,count)

    count = 0

    flag = False

ans = max(ans,count)

print(ans)

s = list(eval(input()))

key = ['A','T','G','C']

count = 0

ans = 0

for i in range(len(s)):

  if s[i] in key: count += 1

  else: count = 0

  ans = max(ans,count)

print(ans)

s = list(eval(input()))
key = ["A", "T", "G", "C"]
count = 0
flag = False
ans = 0
for i in range(len(s)):
    if s[i] in key:
        count += 1
        flag = True
    if flag == True and (s[i] not in key):
        ans = max(ans, count)
        count = 0
        flag = False
ans = max(ans, count)
print(ans)

s = list(eval(input()))
key = ["A", "T", "G", "C"]
count = 0
ans = 0
for i in range(len(s)):
    if s[i] in key:
        count += 1
    else:
        count = 0
    ans = max(ans, count)
print(ans)

-    if flag == True and (s[i] not in key):


Input:
#from statistics import median

import collections

#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]

#from fractions import gcd

#from itertools import combinations # (string,3) 3回

#from collections import deque

#from collections import deque,defaultdict

#import bisect

#

#    d = m - k[i] - k[j]

#    if kk[bisect.bisect_right(kk,d) - 1] == d:

#

#

#

# pythonで無理なときは、pypyでやると正解するかも！！

#

#

import sys

sys.setrecursionlimit(10000000)

mod = 10**9 + 7

#mod = 9982443453

def readInts():

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

def I():

  return int(eval(input()))

S = eval(input())

ln = len(S)

ans = [0] * (ln+1)

# 前から

for i in range(ln):

    if S[i] == '<':

        ans[i+1] = max(ans[i+1],ans[i]+1)

#print(ans)

# 後ろから

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

    if S[i] == '>':

        ans[i] = max(ans[i],ans[i+1]+1)

#print(ans)

print((sum(ans)))

#from statistics import median

#import collections

#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]

from math import gcd

from itertools import combinations,permutations,accumulate, product # (string,3) 3回

#from collections import deque

from collections import deque,defaultdict,Counter

import decimal

import re

import math

import bisect

import heapq

#

#

#

# pythonで無理なときは、pypyでやると正解するかも！！

#

#

# my_round_int = lambda x:np.round((x*2 + 1)//2)

# 四捨五入g

#

# インデックス系

# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);

# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);

#

#

import sys

sys.setrecursionlimit(10000000)

mod = 10**9 + 7

#mod = 9982443453

#mod = 998244353

INF = float('inf')

from sys import stdin

readline = stdin.readline

def readInts():

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

def readTuples():

    return tuple(map(int,readline().split()))

def I():

    return int(readline())

S = eval(input())

n = len(S)

lis = [0] * (len(S)+1)

for i in range(n):

    if S[i] == '<':

        lis[i+1] = max(lis[i+1],lis[i] + 1)

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

    if S[i] == '>':

        lis[i] = max(lis[i], lis[i+1]+1)

print((sum(lis)))

# from statistics import median
import collections

# aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
# from fractions import gcd
# from itertools import combinations # (string,3) 3回
# from collections import deque
# from collections import deque,defaultdict
# import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
import sys

sys.setrecursionlimit(10000000)
mod = 10**9 + 7
# mod = 9982443453
def readInts():
    return list(map(int, input().split()))

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

S = eval(input())
ln = len(S)
ans = [0] * (ln + 1)
# 前から
for i in range(ln):
    if S[i] == "<":
        ans[i + 1] = max(ans[i + 1], ans[i] + 1)
# print(ans)
# 後ろから
for i in range(ln - 1, -1, -1):
    if S[i] == ">":
        ans[i] = max(ans[i], ans[i + 1] + 1)
# print(ans)
print((sum(ans)))

# from statistics import median
# import collections
# aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from math import gcd
from itertools import combinations, permutations, accumulate, product  # (string,3) 3回

# from collections import deque
from collections import deque, defaultdict, Counter
import decimal
import re
import math
import bisect
import heapq

#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys

sys.setrecursionlimit(10000000)
mod = 10**9 + 7
# mod = 9982443453
# mod = 998244353
INF = float("inf")
from sys import stdin

readline = stdin.readline

def readInts():
    return list(map(int, readline().split()))

def readTuples():
    return tuple(map(int, readline().split()))

def I():
    return int(readline())

S = eval(input())
n = len(S)
lis = [0] * (len(S) + 1)
for i in range(n):
    if S[i] == "<":
        lis[i + 1] = max(lis[i + 1], lis[i] + 1)
for i in range(n - 1, -1, -1):
    if S[i] == ">":
        lis[i] = max(lis[i], lis[i + 1] + 1)
print((sum(lis)))

+# aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]

+from itertools import combinations, permutations, accumulate, product  # (string,3) 3回

-# aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]

-# from itertools import combinations # (string,3) 3回

-# from collections import deque,defaultdict

-#    if kk[bisect.bisect_right(kk,d) - 1] == d:

+from collections import deque, defaultdict, Counter

+# my_round_int = lambda x:np.round((x*2 + 1)//2)

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

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

+    return tuple(map(int, readline().split()))

-        ans[i] = max(ans[i], ans[i + 1] + 1)

+        lis[i] = max(lis[i], lis[i + 1] + 1)


Input:
import math

a,b=input().split()

a=int(a)

c=int(b[0]+b[2]+b[3])

print((int(a*c)//100))

#print(a*b)

import math

a,b=input().split()

a=int(a)

c=int(b[0]+b[2]+b[3])

print((a*c//100))

#print(a*b)

import math

a, b = input().split()
a = int(a)
c = int(b[0] + b[2] + b[3])
print((int(a * c) // 100))
# print(a*b)

import math

a, b = input().split()
a = int(a)
c = int(b[0] + b[2] + b[3])
print((a * c // 100))
# print(a*b)


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

ab = []

for _ in range(n):

    a=int(eval(input()))

    ab.append(a)

ans = 0

for i in range(n):

    ans += ab[i]//2

    if i == n-1:

        break

    elif ab[i]%2 == 1 and ab[i+1] > 0:

        ans += 1

        ab[i+1] -= 1

print(ans)

N = int(eval(input()))

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

ans = 0

for key,val in enumerate(A):

    ans += int(val/2)

    if key < N-1 and int(val/2)*2 != val and A[key+1] != 0:

        A[key+1] -= 1

        ans += 1

print(ans)

n = int(eval(input()))
ab = []
for _ in range(n):
    a = int(eval(input()))
    ab.append(a)
ans = 0
for i in range(n):
    ans += ab[i] // 2
    if i == n - 1:
        break
    elif ab[i] % 2 == 1 and ab[i + 1] > 0:
        ans += 1
        ab[i + 1] -= 1
print(ans)

N = int(eval(input()))
A = [int(eval(input())) for _ in range(N)]
ans = 0
for key, val in enumerate(A):
    ans += int(val / 2)
    if key < N - 1 and int(val / 2) * 2 != val and A[key + 1] != 0:
        A[key + 1] -= 1
        ans += 1
print(ans)

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

+    if key < N - 1 and int(val / 2) * 2 != val and A[key + 1] != 0:


Input:
import numpy as np

import sys

N = int(eval(input()))

I = np.array(sys.stdin.read().split(), np.int64)

A = I[:N]

B = I[N:2*N]

C = I[2*N:]

A.sort()

C.sort()

ans = 0

for i in range(N):

	b = B[i]

	A_cnt = np.searchsorted(A, b, side='left')

	C_cnt = np.searchsorted(C, b, side='right')

	ans += A_cnt * (N-C_cnt)

print(ans)

import numpy as np

import sys

N = int(eval(input()))

#I = np.array(sys.stdin.read().split(), np.int64)

#A = I[:N]

#B = I[N:2*N]

#C = I[2*N:]

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

B = np.array(list(map(int,input().split())))

C = np.array(list(map(int,input().split())))

A.sort()

C.sort()

ans = 0

for i in range(N):

	b = B[i]

	A_cnt = np.searchsorted(A, b, side='left')

	C_cnt = np.searchsorted(C, b, side='right')

	ans += A_cnt * (N-C_cnt)

print(ans)

import numpy as np
import sys

N = int(eval(input()))
I = np.array(sys.stdin.read().split(), np.int64)
A = I[:N]
B = I[N : 2 * N]
C = I[2 * N :]
A.sort()
C.sort()
ans = 0
for i in range(N):
    b = B[i]
    A_cnt = np.searchsorted(A, b, side="left")
    C_cnt = np.searchsorted(C, b, side="right")
    ans += A_cnt * (N - C_cnt)
print(ans)

import numpy as np
import sys

N = int(eval(input()))
# I = np.array(sys.stdin.read().split(), np.int64)
# A = I[:N]
# B = I[N:2*N]
# C = I[2*N:]
A = np.array(list(map(int, input().split())))
B = np.array(list(map(int, input().split())))
C = np.array(list(map(int, input().split())))
A.sort()
C.sort()
ans = 0
for i in range(N):
    b = B[i]
    A_cnt = np.searchsorted(A, b, side="left")
    C_cnt = np.searchsorted(C, b, side="right")
    ans += A_cnt * (N - C_cnt)
print(ans)

-I = np.array(sys.stdin.read().split(), np.int64)

+# I = np.array(sys.stdin.read().split(), np.int64)

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

+B = np.array(list(map(int, input().split())))

+C = np.array(list(map(int, input().split())))


Input:
import sys

input = sys.stdin.readline

def main():

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

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

    sm_mx = sum(x)

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

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

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

        for j in range(n + 1):

            for sm in range(sum(x[:i]) + 1):

                if sm < e:

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

                elif j >= 1 and sm >= e:

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

    ans = 0

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

        if i > sm_mx / a:

            break

        ans += dp[n][i][i*a]

    print(ans)

if __name__ == "__main__":

    main()

def main():

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

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

    mx = max(x + [a])

    for i in range(n):

        x[i] -= a

    sm = 2 * n * mx

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

    dp[0][n*mx] = 1

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

        for j in range(sm + 1):

            if 0 <= j - e <= sm:

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

            else:

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

    ans = dp[n][n*mx] - 1

    print(ans)

if __name__ == "__main__":

    main()

import sys

input = sys.stdin.readline

def main():
    n, a = list(map(int, input().split()))
    x = tuple(map(int, input().split()))
    sm_mx = sum(x)
    dp = [[[0] * (sm_mx + 1) for _ in range(n + 1)] for _ in range(n + 1)]
    dp[0][0][0] = 1
    for i, e in enumerate(x, 1):
        for j in range(n + 1):
            for sm in range(sum(x[:i]) + 1):
                if sm < e:
                    dp[i][j][sm] = dp[i - 1][j][sm]
                elif j >= 1 and sm >= e:
                    dp[i][j][sm] = dp[i - 1][j][sm] + dp[i - 1][j - 1][sm - e]
    ans = 0
    for i in range(1, n + 1):
        if i > sm_mx / a:
            break
        ans += dp[n][i][i * a]
    print(ans)

if __name__ == "__main__":
    main()

def main():
    n, a = list(map(int, input().split()))
    x = list(map(int, input().split()))
    mx = max(x + [a])
    for i in range(n):
        x[i] -= a
    sm = 2 * n * mx
    dp = [[0] * (sm + 1) for _ in range(n + 1)]
    dp[0][n * mx] = 1
    for i, e in enumerate(x, 1):
        for j in range(sm + 1):
            if 0 <= j - e <= sm:
                dp[i][j] = dp[i - 1][j] + dp[i - 1][j - e]
            else:
                dp[i][j] = dp[i - 1][j]
    ans = dp[n][n * mx] - 1
    print(ans)

if __name__ == "__main__":
    main()

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

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

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

-            for sm in range(sum(x[:i]) + 1):

-                elif j >= 1 and sm >= e:


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

r = N % 1000

if r == 0:

  print((0))

else:

  q = (N // 1000) + 1

  print((q*1000 - N))