Input:
n = int(input())

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

p = 10000000

for i in range(100):

    pi = 0

    for j in range(n):

        pi += (x[j] - (i + 1))**2

    if pi < p:

        p = pi

    # else:

    #     break

        # p[i] += (x[j]-(i+1))**2

print(p)

n = int(input())

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

p = 10000000

for i in range(100):

    pi = 0

    for j in range(n):

        pi += (x[j] - (i + 1))**2

    if pi < p:

        p = pi

    else:

        break

        # p[i] += (x[j]-(i+1))**2

print(p)

n = int(input())
x = [int(i) for i in input().split()]
p = 10000000
for i in range(100):
    pi = 0
    for j in range(n):
        pi += (x[j] - (i + 1)) ** 2
    if pi < p:
        p = pi
    # else:
    #     break
    # p[i] += (x[j]-(i+1))**2
print(p)

n = int(input())
x = [int(i) for i in input().split()]
p = 10000000
for i in range(100):
    pi = 0
    for j in range(n):
        pi += (x[j] - (i + 1)) ** 2
    if pi < p:
        p = pi
    else:
        break
        # p[i] += (x[j]-(i+1))**2
print(p)


Input:
def solve():

    N = int(input())

    numss = [[0]*(10) for _ in range(10)]

    for x in range(1, 10):

        for y in range(1, 10):

            num = 0

            for d in range(1, 5):

                for i in range(10**d):

                    j = x*10**(d+1) + i*10 + y

                    if 1 <= j <= N:

                        num += 1

                    else:

                        break

            j = x*10 + y

            if 1 <= j <= N:

                num += 1

            if x == y:

                j = x

                if 1 <= j <= N:

                    num += 1

            numss[x][y] = num

    ans = 0

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

        ss = str(A)

        ans += numss[int(ss[-1])][int(ss[0])]

    print(ans)

solve()

def solve():

    strN = input()

    N = int(strN)

    maxD = len(strN)

    numss = [[0]*(10) for _ in range(10)]

    for x in range(1, 10):

        for y in range(1, 10):

            num = 0

            for d in range(1, maxD-2):

                num += 10**d

            if maxD-2 > 0:

                if x < int(strN[0]):

                    num += 10**(maxD-2)

                elif x == int(strN[0]):

                    num += int(strN[1:-1]) + 1

                    if y > int(strN[-1]):

                        num -= 1

            j = x*10 + y

            if 1 <= j <= N:

                num += 1

            if x == y:

                j = x

                if 1 <= j <= N:

                    num += 1

            numss[x][y] = num

    ans = 0

    for i in range(1, 10):

        for j in range(1, 10):

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

    print(ans)

solve()

def solve():
    N = int(input())
    numss = [[0] * (10) for _ in range(10)]
    for x in range(1, 10):
        for y in range(1, 10):
            num = 0
            for d in range(1, 5):
                for i in range(10**d):
                    j = x * 10 ** (d + 1) + i * 10 + y
                    if 1 <= j <= N:
                        num += 1
                    else:
                        break
            j = x * 10 + y
            if 1 <= j <= N:
                num += 1
            if x == y:
                j = x
                if 1 <= j <= N:
                    num += 1
            numss[x][y] = num
    ans = 0
    for A in range(1, N + 1):
        ss = str(A)
        ans += numss[int(ss[-1])][int(ss[0])]
    print(ans)

solve()

def solve():
    strN = input()
    N = int(strN)
    maxD = len(strN)
    numss = [[0] * (10) for _ in range(10)]
    for x in range(1, 10):
        for y in range(1, 10):
            num = 0
            for d in range(1, maxD - 2):
                num += 10**d
            if maxD - 2 > 0:
                if x < int(strN[0]):
                    num += 10 ** (maxD - 2)
                elif x == int(strN[0]):
                    num += int(strN[1:-1]) + 1
                    if y > int(strN[-1]):
                        num -= 1
            j = x * 10 + y
            if 1 <= j <= N:
                num += 1
            if x == y:
                j = x
                if 1 <= j <= N:
                    num += 1
            numss[x][y] = num
    ans = 0
    for i in range(1, 10):
        for j in range(1, 10):
            ans += numss[i][j] * numss[j][i]
    print(ans)

solve()

+            for d in range(1, maxD - 2):

+                elif x == int(strN[0]):

+                    if y > int(strN[-1]):

-        ans += numss[int(ss[-1])][int(ss[0])]

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


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

from collections import deque

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

S = input()

A = set("ATCG")

ans = 0

mode = 0

for i, s in enumerate(S):

    if s in A:

        if mode == 0:

            mode = 1

            start = i

    else:

        if mode == 1:

            ans = max(i - start, ans)

            mode = 0

if mode == 1:

    ans = max(len(S) - start, ans)

print(ans)

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

S = input()

C = set("ACGT")

tmp = 0

ans = 0

for s in S:

    if s in C:

        tmp += 1

    else:

        ans = max(ans, tmp)

        tmp = 0

ans = max(ans, tmp)

print(ans)

-# -*- coding: utf-8 -*-
-from collections import deque
-A = set("ATCG")
+C = set("ACGT")
+tmp = 0
-mode = 0
-for i, s in enumerate(S):
-    if s in A:
-        if mode == 0:
-            mode = 1
-            start = i
+for s in S:
+    if s in C:
+        tmp += 1
-        if mode == 1:
-            ans = max(i - start, ans)
-            mode = 0
-if mode == 1:
-    ans = max(len(S) - start, ans)
+        ans = max(ans, tmp)
+        tmp = 0
+ans = max(ans, tmp)


Input:
N = int(input())

ans = 0

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

    if len(str(i)) % 2 == 1:

        ans += 1

print(ans)

N = int(input())

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

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


Input:
S = input()

k = int(input())

A = set()

for l in range(k+1):

	for i in range(len(S)-l):

			A.add(S[i:i+l+1])

A = sorted(list(A))

print((A[k-1]))

S = input()

l = len(S)

d = set()

K = int(input())

for i in range(5):

    for j in range(l-i):

        d.add(S[j:j+i+1])

D = sorted(list(d))

print((D[K-1]))

S = input()
k = int(input())
A = set()
for l in range(k + 1):
    for i in range(len(S) - l):
        A.add(S[i : i + l + 1])
A = sorted(list(A))
print((A[k - 1]))

S = input()
l = len(S)
d = set()
K = int(input())
for i in range(5):
    for j in range(l - i):
        d.add(S[j : j + i + 1])
D = sorted(list(d))
print((D[K - 1]))

-k = int(input())
-A = set()
-for l in range(k + 1):
-    for i in range(len(S) - l):
-        A.add(S[i : i + l + 1])
-A = sorted(list(A))
-print((A[k - 1]))
+l = len(S)
+d = set()
+K = int(input())
+for i in range(5):
+    for j in range(l - i):
+        d.add(S[j : j + i + 1])
+D = sorted(list(d))
+print((D[K - 1]))


Input:
import sys

input = sys.stdin.readline

from collections import *

K = int(input())

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

for i in range(A, B+1):

    if i%K==0:

        print('OK')

        exit()

print('NG')

K = int(input())

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

if (A-1)//K!=B//K:

    print('OK')

else:

    print('NG')

import sys

input = sys.stdin.readline
from collections import *

K = int(input())
A, B = list(map(int, input().split()))
for i in range(A, B + 1):
    if i % K == 0:
        print("OK")
        exit()
print("NG")

K = int(input())
A, B = list(map(int, input().split()))
if (A - 1) // K != B // K:
    print("OK")
else:
    print("NG")

-import sys
-input = sys.stdin.readline
-from collections import *
-for i in range(A, B + 1):
-    if i % K == 0:
-        print("OK")
-        exit()
-print("NG")
+if (A - 1) // K != B // K:
+    print("OK")
+else:
+    print("NG")


Input:
from heapq import heappush, heappop

k = int(input())

heap = [(1,1)]

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

while heap:

    cost, cur = heappop(heap)

    if dist[cur] <= cost:

        continue

    dist[cur] = cost

    # +1

    nxt = (cur+1)%k

    heappush(heap, (cost+1, nxt))

    # *10

    nxt = cur*10 % k

    heappush(heap, (cost, nxt))

print((dist[0]))

from collections import deque

k = int(input())

que = deque()

que.append((1,1))

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

while que:

    cost, cur = que.popleft()

    if dist[cur] <= cost:

        continue

    dist[cur] = cost

    # +1

    nxt = (cur+1)%k

    que.append((cost+1,nxt))

    # *10

    nxt = cur*10 % k

    que.appendleft((cost, nxt))

print((dist[0]))

from heapq import heappush, heappop

k = int(input())
heap = [(1, 1)]
dist = [float("inf")] * k
while heap:
    cost, cur = heappop(heap)
    if dist[cur] <= cost:
        continue
    dist[cur] = cost
    # +1
    nxt = (cur + 1) % k
    heappush(heap, (cost + 1, nxt))
    # *10
    nxt = cur * 10 % k
    heappush(heap, (cost, nxt))
print((dist[0]))

from collections import deque

k = int(input())
que = deque()
que.append((1, 1))
dist = [float("inf")] * k
while que:
    cost, cur = que.popleft()
    if dist[cur] <= cost:
        continue
    dist[cur] = cost
    # +1
    nxt = (cur + 1) % k
    que.append((cost + 1, nxt))
    # *10
    nxt = cur * 10 % k
    que.appendleft((cost, nxt))
print((dist[0]))

-from heapq import heappush, heappop
+from collections import deque
-heap = [(1, 1)]
+que = deque()
+que.append((1, 1))
-while heap:
-    cost, cur = heappop(heap)
+while que:
+    cost, cur = que.popleft()
-    heappush(heap, (cost + 1, nxt))
+    que.append((cost + 1, nxt))
-    heappush(heap, (cost, nxt))
+    que.appendleft((cost, nxt))


Input:
S = input()

T = input()

l = len(S)

res = 0

for n in range(l):

    if S[n] == T[n]:

        res += 1

print(res)

S = input()

T = input()

l = len(S)

ans = 0

for n in range(l):

    if S[n] == T[n]:

        ans += 1

print(ans)

-res = 0
+ans = 0
-        res += 1
-print(res)
+        ans += 1
+print(ans)


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

max_iter = max(X, Y) * 2

ans = float("inf")

for i in range(max_iter):

    a = max(X - i, 0)

    b = max(Y - i, 0)

    price = 2*C * i + A * a + B * b

    ans = min(ans, price)

print(ans)

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

ans = float("inf")

for i in range(max(X, Y)+1):

    x = max(X - i, 0)

    y = max(Y - i, 0)

    cost = 2*C * i + A * x + B * y

    ans = min(ans, cost)

print(ans)

A, B, C, X, Y = list(map(int, input().split()))
max_iter = max(X, Y) * 2
ans = float("inf")
for i in range(max_iter):
    a = max(X - i, 0)
    b = max(Y - i, 0)
    price = 2 * C * i + A * a + B * b
    ans = min(ans, price)
print(ans)

A, B, C, X, Y = list(map(int, input().split()))
ans = float("inf")
for i in range(max(X, Y) + 1):
    x = max(X - i, 0)
    y = max(Y - i, 0)
    cost = 2 * C * i + A * x + B * y
    ans = min(ans, cost)
print(ans)

-max_iter = max(X, Y) * 2
-for i in range(max_iter):
-    a = max(X - i, 0)
-    b = max(Y - i, 0)
-    price = 2 * C * i + A * a + B * b
-    ans = min(ans, price)
+for i in range(max(X, Y) + 1):
+    x = max(X - i, 0)
+    y = max(Y - i, 0)
+    cost = 2 * C * i + A * x + B * y
+    ans = min(ans, cost)


Input:
import math

import statistics

n = int(input())

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

a = [aa-i-1 for i, aa in enumerate(a)]

answer = n*10**20

median_low = statistics.median_low(a)

median_high = statistics.median_high(a)

for m in (median_low,median_high):

  ans=0

  for aa in a:

    ans += abs(aa-m)

  answer = min(ans,answer)

print(answer)

#!/usr/bin/env python3

import sys

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

    difA = [0]*N

    for i in range(N):

        difA[i] = A[i]-(i+1)

    difA.sort()

    if N%2 == 0:

        g1 = difA[N//2]

        g2 = difA[N//2-1]

        a1 = 0

        a2 = 0

        for i in range(N):

            a1 += abs(difA[i]-g1)

            a2 += abs(difA[i]-g2)

        print((min(a1,a2)))

    else:

        g = difA[N//2]

        a = 0

        for i in range(N):

            a += abs(difA[i]-g)

        print(a)

    return

def main():

    def iterate_tokens():

        for line in sys.stdin:

            for word in line.split():

                yield word

    tokens = iterate_tokens()

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

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

    solve(N, A)

if __name__ == '__main__':

    main()

import math
import statistics

n = int(input())
a = list(map(int, input().split()))
a = [aa - i - 1 for i, aa in enumerate(a)]
answer = n * 10**20
median_low = statistics.median_low(a)
median_high = statistics.median_high(a)
for m in (median_low, median_high):
    ans = 0
    for aa in a:
        ans += abs(aa - m)
    answer = min(ans, answer)
print(answer)

#!/usr/bin/env python3
import sys

def solve(N: int, A: "List[int]"):
    difA = [0] * N
    for i in range(N):
        difA[i] = A[i] - (i + 1)
    difA.sort()
    if N % 2 == 0:
        g1 = difA[N // 2]
        g2 = difA[N // 2 - 1]
        a1 = 0
        a2 = 0
        for i in range(N):
            a1 += abs(difA[i] - g1)
            a2 += abs(difA[i] - g2)
        print((min(a1, a2)))
    else:
        g = difA[N // 2]
        a = 0
        for i in range(N):
            a += abs(difA[i] - g)
        print(a)
    return

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

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

if __name__ == "__main__":
    main()

-a = [aa - i - 1 for i, aa in enumerate(a)]

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


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

ans = a*x + b*y

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

	money = max(0,(x-i)*a) + max(0,(y-i)*b) + 2*i*c

	if money <= ans:

		ans = money

print(ans)

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

if a + b >= 2*c:

	if x >= y:

		ans = 2*y*c + (x-y)*min(a,2*c)

	else:

		ans = 2*x*c + (y-x)*min(b,2*c)

else:

	ans = (x*a + y*b)

print(ans)

a, b, c, x, y = list(map(int, input().split()))
ans = a * x + b * y
for i in range(max(x, y) + 1):
    money = max(0, (x - i) * a) + max(0, (y - i) * b) + 2 * i * c
    if money <= ans:
        ans = money
print(ans)

a, b, c, x, y = list(map(int, input().split()))
if a + b >= 2 * c:
    if x >= y:
        ans = 2 * y * c + (x - y) * min(a, 2 * c)
    else:
        ans = 2 * x * c + (y - x) * min(b, 2 * c)
else:
    ans = x * a + y * b
print(ans)


Input:
import sys

# from itertools import chain, accumulate

n, m, *abcdef = list(map(int, sys.stdin.buffer.read().split()))

ver_lines = []

hor_lines = []

x_list = set()

y_list = set()

n3 = n * 3

for a, b, c in zip(abcdef[0:n3:3], abcdef[1:n3:3], abcdef[2:n3:3]):

    y_list.add(a)

    y_list.add(b)

    x_list.add(c)

    ver_lines.append((a, b, c))

for d, e, f in zip(abcdef[n3 + 0::3], abcdef[n3 + 1::3], abcdef[n3 + 2::3]):

    y_list.add(d)

    x_list.add(e)

    x_list.add(f)

    hor_lines.append((d, e, f))

x_list.add(0)

y_list.add(0)

x_list = sorted(x_list)

y_list = sorted(y_list)

x_dict = {x: i for i, x in enumerate(x_list, start=1)}

y_dict = {y: i for i, y in enumerate(y_list, start=1)}

row_real = len(x_list)

col_real = len(y_list)

row = row_real + 2

col = col_real + 2

banned_up_ij = [[0] * row for _ in range(col)]

banned_down_ij = [[0] * row for _ in range(col)]

banned_left_ij = [[0] * col for _ in range(row)]

banned_right_ij = [[0] * col for _ in range(row)]

for a, b, c in ver_lines:

    if a > b:

        a, b = b, a

    ai = y_dict[a]

    bi = y_dict[b]

    j = x_dict[c]

    banned_left_ij[j][ai] += 1

    banned_left_ij[j][bi] -= 1

    banned_right_ij[j - 1][ai] += 1

    banned_right_ij[j - 1][bi] -= 1

for d, e, f in hor_lines:

    if e > f:

        e, f = f, e

    i = y_dict[d]

    ej = x_dict[e]

    fj = x_dict[f]

    banned_up_ij[i][ej] += 1

    banned_up_ij[i][fj] -= 1

    banned_down_ij[i - 1][ej] += 1

    banned_down_ij[i - 1][fj] -= 1

banned_up = [0] * (row * col)

banned_down = [0] * (row * col)

banned_left = [0] * (row * col)

banned_right = [0] * (row * col)

for i in range(col):

    ru = banned_up_ij[i]

    rd = banned_down_ij[i]

    ri = row * i

    banned_up[ri] = ru[0]

    banned_down[ri] = rd[0]

    for j in range(1, row):

        banned_up[ri + j] = banned_up[ri + j - 1] + ru[j]

        banned_down[ri + j] = banned_down[ri + j - 1] + rd[j]

for j in range(row):

    rl = banned_left_ij[j]

    rr = banned_right_ij[j]

    banned_left[j] = rl[0]

    banned_right[j] = rr[0]

    for i in range(1, col):

        ri0 = (i - 1) * row

        ri1 = i * row

        banned_left[ri1 + j] = banned_left[ri0 + j] + rl[i]

        banned_right[ri1 + j] = banned_right[ri0 + j] + rr[i]

# banned_up = list(chain.from_iterable(map(accumulate, banned_up_ij)))

# banned_down = list(chain.from_iterable(map(accumulate, banned_down_ij)))

# banned_left = list(chain.from_iterable(zip(*map(accumulate, banned_left_ij))))

# banned_right = list(chain.from_iterable(zip(*map(accumulate, banned_right_ij))))

# for i in range(col):

#     print(walls[i * row:(i + 1) * row])

s = row * y_dict[0] + x_dict[0]

enable = [-1] * row + ([-1] + [0] * (row - 2) + [-1]) * (col - 2) + [-1] * row

# for i in range(col):

#     print(enable[i * row:(i + 1) * row])

q = [s]

moves = [(-row, banned_up), (-1, banned_left), (1, banned_right), (row, banned_down)]

while q:

    c = q.pop()

    if enable[c] == 1:

        continue

    elif enable[c] == -1:

        print('INF')

        exit()

    enable[c] = 1

    for dc, banned in moves:

        if banned[c]:

            continue

        nc = c + dc

        if enable[nc] == 1:

            continue

        q.append(nc)

# for i in range(col):

#     print(enable[i * row:(i + 1) * row])

ans = 0

for i in range(col):

    ri = i * row

    for j in range(row):

        if enable[ri + j] != 1:

            continue

        t = y_list[i - 1]

        b = y_list[i]

        l = x_list[j - 1]

        r = x_list[j]

        ans += (b - t) * (r - l)

print(ans)

import sys

# from itertools import chain, accumulate

n, m, *abcdef = list(map(int, sys.stdin.buffer.read().split()))

ver_lines = []

hor_lines = []

x_list = set()

y_list = set()

n3 = n * 3

for a, b, c in zip(abcdef[0:n3:3], abcdef[1:n3:3], abcdef[2:n3:3]):

    y_list.add(a)

    y_list.add(b)

    x_list.add(c)

    ver_lines.append((a, b, c))

for d, e, f in zip(abcdef[n3 + 0::3], abcdef[n3 + 1::3], abcdef[n3 + 2::3]):

    y_list.add(d)

    x_list.add(e)

    x_list.add(f)

    hor_lines.append((d, e, f))

x_list.add(0)

y_list.add(0)

x_list = sorted(x_list)

y_list = sorted(y_list)

x_dict = {x: i for i, x in enumerate(x_list, start=1)}

y_dict = {y: i for i, y in enumerate(y_list, start=1)}

row_real = len(x_list)

col_real = len(y_list)

row = row_real + 2

col = col_real + 2

banned_up = [0] * (row * col)

banned_down = [0] * (row * col)

banned_left = [0] * (row * col)

banned_right = [0] * (row * col)

for a, b, c in ver_lines:

    if a > b:

        a, b = b, a

    ai = y_dict[a] * row

    bi = y_dict[b] * row

    j = x_dict[c]

    banned_left[ai + j] += 1

    banned_left[bi + j] -= 1

    banned_right[ai + j - 1] += 1

    banned_right[bi + j - 1] -= 1

for d, e, f in hor_lines:

    if e > f:

        e, f = f, e

    ri = y_dict[d] * row

    ej = x_dict[e]

    fj = x_dict[f]

    banned_up[ri + ej] += 1

    banned_up[ri + fj] -= 1

    banned_down[ri - row + ej] += 1

    banned_down[ri - row + fj] -= 1

for i in range(1, col):

    ri0 = row * (i - 1)

    ri1 = row * i

    for j in range(1, row):

        banned_up[ri1 + j] += banned_up[ri1 + j - 1]

        banned_down[ri1 + j] += banned_down[ri1 + j - 1]

        banned_left[ri1 + j] += banned_left[ri0 + j]

        banned_right[ri1 + j] += banned_right[ri0 + j]

# banned_up = list(chain.from_iterable(map(accumulate, banned_up_ij)))

# banned_down = list(chain.from_iterable(map(accumulate, banned_down_ij)))

# banned_left = list(chain.from_iterable(zip(*map(accumulate, banned_left_ij))))

# banned_right = list(chain.from_iterable(zip(*map(accumulate, banned_right_ij))))

# for i in range(col):

#     print(walls[i * row:(i + 1) * row])

s = row * y_dict[0] + x_dict[0]

enable = [-1] * row + ([-1] + [0] * (row - 2) + [-1]) * (col - 2) + [-1] * row

# for i in range(col):

#     print(enable[i * row:(i + 1) * row])

q = [s]

moves = [(-row, banned_up), (-1, banned_left), (1, banned_right), (row, banned_down)]

while q:

    c = q.pop()

    if enable[c] == 1:

        continue

    elif enable[c] == -1:

        print('INF')

        exit()

    enable[c] = 1

    for dc, banned in moves:

        if banned[c]:

            continue

        nc = c + dc

        if enable[nc] == 1:

            continue

        q.append(nc)

# for i in range(col):

#     print(enable[i * row:(i + 1) * row])

ans = 0

for i in range(col):

    ri = i * row

    for j in range(row):

        if enable[ri + j] != 1:

            continue

        t = y_list[i - 1]

        b = y_list[i]

        l = x_list[j - 1]

        r = x_list[j]

        ans += (b - t) * (r - l)

print(ans)

import sys

# from itertools import chain, accumulate
n, m, *abcdef = list(map(int, sys.stdin.buffer.read().split()))
ver_lines = []
hor_lines = []
x_list = set()
y_list = set()
n3 = n * 3
for a, b, c in zip(abcdef[0:n3:3], abcdef[1:n3:3], abcdef[2:n3:3]):
    y_list.add(a)
    y_list.add(b)
    x_list.add(c)
    ver_lines.append((a, b, c))
for d, e, f in zip(abcdef[n3 + 0 :: 3], abcdef[n3 + 1 :: 3], abcdef[n3 + 2 :: 3]):
    y_list.add(d)
    x_list.add(e)
    x_list.add(f)
    hor_lines.append((d, e, f))
x_list.add(0)
y_list.add(0)
x_list = sorted(x_list)
y_list = sorted(y_list)
x_dict = {x: i for i, x in enumerate(x_list, start=1)}
y_dict = {y: i for i, y in enumerate(y_list, start=1)}
row_real = len(x_list)
col_real = len(y_list)
row = row_real + 2
col = col_real + 2
banned_up_ij = [[0] * row for _ in range(col)]
banned_down_ij = [[0] * row for _ in range(col)]
banned_left_ij = [[0] * col for _ in range(row)]
banned_right_ij = [[0] * col for _ in range(row)]
for a, b, c in ver_lines:
    if a > b:
        a, b = b, a
    ai = y_dict[a]
    bi = y_dict[b]
    j = x_dict[c]
    banned_left_ij[j][ai] += 1
    banned_left_ij[j][bi] -= 1
    banned_right_ij[j - 1][ai] += 1
    banned_right_ij[j - 1][bi] -= 1
for d, e, f in hor_lines:
    if e > f:
        e, f = f, e
    i = y_dict[d]
    ej = x_dict[e]
    fj = x_dict[f]
    banned_up_ij[i][ej] += 1
    banned_up_ij[i][fj] -= 1
    banned_down_ij[i - 1][ej] += 1
    banned_down_ij[i - 1][fj] -= 1
banned_up = [0] * (row * col)
banned_down = [0] * (row * col)
banned_left = [0] * (row * col)
banned_right = [0] * (row * col)
for i in range(col):
    ru = banned_up_ij[i]
    rd = banned_down_ij[i]
    ri = row * i
    banned_up[ri] = ru[0]
    banned_down[ri] = rd[0]
    for j in range(1, row):
        banned_up[ri + j] = banned_up[ri + j - 1] + ru[j]
        banned_down[ri + j] = banned_down[ri + j - 1] + rd[j]
for j in range(row):
    rl = banned_left_ij[j]
    rr = banned_right_ij[j]
    banned_left[j] = rl[0]
    banned_right[j] = rr[0]
    for i in range(1, col):
        ri0 = (i - 1) * row
        ri1 = i * row
        banned_left[ri1 + j] = banned_left[ri0 + j] + rl[i]
        banned_right[ri1 + j] = banned_right[ri0 + j] + rr[i]
# banned_up = list(chain.from_iterable(map(accumulate, banned_up_ij)))
# banned_down = list(chain.from_iterable(map(accumulate, banned_down_ij)))
# banned_left = list(chain.from_iterable(zip(*map(accumulate, banned_left_ij))))
# banned_right = list(chain.from_iterable(zip(*map(accumulate, banned_right_ij))))
# for i in range(col):
#     print(walls[i * row:(i + 1) * row])
s = row * y_dict[0] + x_dict[0]
enable = [-1] * row + ([-1] + [0] * (row - 2) + [-1]) * (col - 2) + [-1] * row
# for i in range(col):
#     print(enable[i * row:(i + 1) * row])
q = [s]
moves = [(-row, banned_up), (-1, banned_left), (1, banned_right), (row, banned_down)]
while q:
    c = q.pop()
    if enable[c] == 1:
        continue
    elif enable[c] == -1:
        print("INF")
        exit()
    enable[c] = 1
    for dc, banned in moves:
        if banned[c]:
            continue
        nc = c + dc
        if enable[nc] == 1:
            continue
        q.append(nc)
# for i in range(col):
#     print(enable[i * row:(i + 1) * row])
ans = 0
for i in range(col):
    ri = i * row
    for j in range(row):
        if enable[ri + j] != 1:
            continue
        t = y_list[i - 1]
        b = y_list[i]
        l = x_list[j - 1]
        r = x_list[j]
        ans += (b - t) * (r - l)
print(ans)

import sys

# from itertools import chain, accumulate
n, m, *abcdef = list(map(int, sys.stdin.buffer.read().split()))
ver_lines = []
hor_lines = []
x_list = set()
y_list = set()
n3 = n * 3
for a, b, c in zip(abcdef[0:n3:3], abcdef[1:n3:3], abcdef[2:n3:3]):
    y_list.add(a)
    y_list.add(b)
    x_list.add(c)
    ver_lines.append((a, b, c))
for d, e, f in zip(abcdef[n3 + 0 :: 3], abcdef[n3 + 1 :: 3], abcdef[n3 + 2 :: 3]):
    y_list.add(d)
    x_list.add(e)
    x_list.add(f)
    hor_lines.append((d, e, f))
x_list.add(0)
y_list.add(0)
x_list = sorted(x_list)
y_list = sorted(y_list)
x_dict = {x: i for i, x in enumerate(x_list, start=1)}
y_dict = {y: i for i, y in enumerate(y_list, start=1)}
row_real = len(x_list)
col_real = len(y_list)
row = row_real + 2
col = col_real + 2
banned_up = [0] * (row * col)
banned_down = [0] * (row * col)
banned_left = [0] * (row * col)
banned_right = [0] * (row * col)
for a, b, c in ver_lines:
    if a > b:
        a, b = b, a
    ai = y_dict[a] * row
    bi = y_dict[b] * row
    j = x_dict[c]
    banned_left[ai + j] += 1
    banned_left[bi + j] -= 1
    banned_right[ai + j - 1] += 1
    banned_right[bi + j - 1] -= 1
for d, e, f in hor_lines:
    if e > f:
        e, f = f, e
    ri = y_dict[d] * row
    ej = x_dict[e]
    fj = x_dict[f]
    banned_up[ri + ej] += 1
    banned_up[ri + fj] -= 1
    banned_down[ri - row + ej] += 1
    banned_down[ri - row + fj] -= 1
for i in range(1, col):
    ri0 = row * (i - 1)
    ri1 = row * i
    for j in range(1, row):
        banned_up[ri1 + j] += banned_up[ri1 + j - 1]
        banned_down[ri1 + j] += banned_down[ri1 + j - 1]
        banned_left[ri1 + j] += banned_left[ri0 + j]
        banned_right[ri1 + j] += banned_right[ri0 + j]
# banned_up = list(chain.from_iterable(map(accumulate, banned_up_ij)))
# banned_down = list(chain.from_iterable(map(accumulate, banned_down_ij)))
# banned_left = list(chain.from_iterable(zip(*map(accumulate, banned_left_ij))))
# banned_right = list(chain.from_iterable(zip(*map(accumulate, banned_right_ij))))
# for i in range(col):
#     print(walls[i * row:(i + 1) * row])
s = row * y_dict[0] + x_dict[0]
enable = [-1] * row + ([-1] + [0] * (row - 2) + [-1]) * (col - 2) + [-1] * row
# for i in range(col):
#     print(enable[i * row:(i + 1) * row])
q = [s]
moves = [(-row, banned_up), (-1, banned_left), (1, banned_right), (row, banned_down)]
while q:
    c = q.pop()
    if enable[c] == 1:
        continue
    elif enable[c] == -1:
        print("INF")
        exit()
    enable[c] = 1
    for dc, banned in moves:
        if banned[c]:
            continue
        nc = c + dc
        if enable[nc] == 1:
            continue
        q.append(nc)
# for i in range(col):
#     print(enable[i * row:(i + 1) * row])
ans = 0
for i in range(col):
    ri = i * row
    for j in range(row):
        if enable[ri + j] != 1:
            continue
        t = y_list[i - 1]
        b = y_list[i]
        l = x_list[j - 1]
        r = x_list[j]
        ans += (b - t) * (r - l)
print(ans)

-banned_up_ij = [[0] * row for _ in range(col)]

-banned_down_ij = [[0] * row for _ in range(col)]

-banned_left_ij = [[0] * col for _ in range(row)]

-banned_right_ij = [[0] * col for _ in range(row)]

-        banned_up[ri + j] = banned_up[ri + j - 1] + ru[j]

-        banned_down[ri + j] = banned_down[ri + j - 1] + rd[j]

-        banned_left[ri1 + j] = banned_left[ri0 + j] + rl[i]

-        banned_right[ri1 + j] = banned_right[ri0 + j] + rr[i]

+        banned_up[ri1 + j] += banned_up[ri1 + j - 1]

+        banned_down[ri1 + j] += banned_down[ri1 + j - 1]

+        banned_left[ri1 + j] += banned_left[ri0 + j]

+        banned_right[ri1 + j] += banned_right[ri0 + j]


Input:
def main():

    s = int(input())

    mod = 10**9 + 7

    dp = [0] * (s+1)

    dp[0] = 1

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

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

            dp[i] += dp[j]

            dp[i] %= mod

    print((dp[-1]))

if __name__ == "__main__":

    main()

def main():

    s = int(input())

    mod = 10**9 + 7

    dp = [0] * (s+1)

    dp[0] = 1

#    for i in range(1, s+1):

#        for j in range(0, (i-3)+1):

#            dp[i] += dp[j]

#            dp[i] %= mod

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

        if i < 3:

            dp[i] = 0

        else:

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

            dp[i] %= mod

    print((dp[-1]))

if __name__ == "__main__":

    main()

def main():
    s = int(input())
    mod = 10**9 + 7
    dp = [0] * (s + 1)
    dp[0] = 1
    for i in range(1, s + 1):
        for j in range(0, (i - 3) + 1):
            dp[i] += dp[j]
            dp[i] %= mod
    print((dp[-1]))

if __name__ == "__main__":
    main()

def main():
    s = int(input())
    mod = 10**9 + 7
    dp = [0] * (s + 1)
    dp[0] = 1
    #    for i in range(1, s+1):
    #        for j in range(0, (i-3)+1):
    #            dp[i] += dp[j]
    #            dp[i] %= mod
    for i in range(1, s + 1):
        if i < 3:
            dp[i] = 0
        else:
            dp[i] = dp[i - 1] + dp[i - 3]
            dp[i] %= mod
    print((dp[-1]))

if __name__ == "__main__":
    main()

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


Input:
def slove():

    import sys

    import heapq

    import collections

    input = sys.stdin.readline

    x, y, z, k = list(map(int, input().rstrip('\n').split()))

    a = list(map(int, input().rstrip('\n').split()))

    a.sort(reverse=True)

    b = list(map(int, input().rstrip('\n').split()))

    b.sort(reverse=True)

    c = list(map(int, input().rstrip('\n').split()))

    c.sort(reverse=True)

    q = [[-(a[0] + b[0] + c[0]), 0, 0, 0]]

    heapq.heapify(q)

    fq = collections.defaultdict(list)

    fq[(-(a[0] + b[0] + c[0]), 0, 0, 0), 1] = 1

    t = 0

    for _ in range(k):

        if len(q) != 0:

            p = heapq.heappop(q)

            t = p[0]

            aq = p[1]

            bq = p[2]

            cq = p[3]

            if aq + 1 < len(a):

                if (-(a[aq+1] + b[bq] + c[cq]), aq+1, bq, cq) not in fq:

                    heapq.heappush(q, [-(a[aq+1] + b[bq] + c[cq]), aq+1, bq, cq])

                    fq[(-(a[aq+1] + b[bq] + c[cq]), aq+1, bq, cq)] = 1

            if bq + 1 < len(b):

                if (-(a[aq] + b[bq+1] + c[cq]), aq, bq+1, cq) not in fq:

                    heapq.heappush(q, [-(a[aq] + b[bq+1] + c[cq]), aq, bq+1, cq])

                    fq[(-(a[aq] + b[bq+1] + c[cq]), aq, bq+1, cq)] = 1

            if cq + 1 < len(c):

                if (-(a[aq] + b[bq] + c[cq+1]), aq, bq, cq+1) not in fq:

                    heapq.heappush(q, [-(a[aq] + b[bq] + c[cq+1]), aq, bq, cq+1])

                    fq[(-(a[aq] + b[bq] + c[cq+1]), aq, bq, cq+1)] = 1

        print((-t))

if __name__ == '__main__':

    slove()

import sys

import collections

import heapq

def solve():

    input = sys.stdin.readline

    mod = 10 ** 9 + 7

    x, y, z, k = list(map(int, input().rstrip('\n').split()))

    a = list(map(int, input().rstrip('\n').split()))

    b = list(map(int, input().rstrip('\n').split()))

    c = list(map(int, input().rstrip('\n').split()))

    a.sort(reverse=True)

    b.sort(reverse=True)

    c.sort(reverse=True)

    ql = [[-(a[0] + b[0] + c[0]), 0, 0, 0]]

    heapq.heapify(ql)

    fq = collections.defaultdict(int)

    fq[0, 0, 0]

    for i in range(k):

        s, ap, bp, cp = heapq.heappop(ql)

        for app, bpp, cpp in ([[ap+1, bp, cp], [ap, bp+1, cp], [ap, bp, cp+1]]):

            if app < x and bpp < y and cpp < z:

                if (app, bpp, cpp) not in fq:

                    heapq.heappush(ql, [-(a[app] + b[bpp] + c[cpp]), app, bpp, cpp])

                    fq[app, bpp, cpp]

        print((-s))

if __name__ == '__main__':

    solve()

def slove():
    import sys
    import heapq
    import collections

    input = sys.stdin.readline
    x, y, z, k = list(map(int, input().rstrip("\n").split()))
    a = list(map(int, input().rstrip("\n").split()))
    a.sort(reverse=True)
    b = list(map(int, input().rstrip("\n").split()))
    b.sort(reverse=True)
    c = list(map(int, input().rstrip("\n").split()))
    c.sort(reverse=True)
    q = [[-(a[0] + b[0] + c[0]), 0, 0, 0]]
    heapq.heapify(q)
    fq = collections.defaultdict(list)
    fq[(-(a[0] + b[0] + c[0]), 0, 0, 0), 1] = 1
    t = 0
    for _ in range(k):
        if len(q) != 0:
            p = heapq.heappop(q)
            t = p[0]
            aq = p[1]
            bq = p[2]
            cq = p[3]
            if aq + 1 < len(a):
                if (-(a[aq + 1] + b[bq] + c[cq]), aq + 1, bq, cq) not in fq:
                    heapq.heappush(q, [-(a[aq + 1] + b[bq] + c[cq]), aq + 1, bq, cq])
                    fq[(-(a[aq + 1] + b[bq] + c[cq]), aq + 1, bq, cq)] = 1
            if bq + 1 < len(b):
                if (-(a[aq] + b[bq + 1] + c[cq]), aq, bq + 1, cq) not in fq:
                    heapq.heappush(q, [-(a[aq] + b[bq + 1] + c[cq]), aq, bq + 1, cq])
                    fq[(-(a[aq] + b[bq + 1] + c[cq]), aq, bq + 1, cq)] = 1
            if cq + 1 < len(c):
                if (-(a[aq] + b[bq] + c[cq + 1]), aq, bq, cq + 1) not in fq:
                    heapq.heappush(q, [-(a[aq] + b[bq] + c[cq + 1]), aq, bq, cq + 1])
                    fq[(-(a[aq] + b[bq] + c[cq + 1]), aq, bq, cq + 1)] = 1
        print((-t))

if __name__ == "__main__":
    slove()

import sys
import collections
import heapq

def solve():
    input = sys.stdin.readline
    mod = 10**9 + 7
    x, y, z, k = list(map(int, input().rstrip("\n").split()))
    a = list(map(int, input().rstrip("\n").split()))
    b = list(map(int, input().rstrip("\n").split()))
    c = list(map(int, input().rstrip("\n").split()))
    a.sort(reverse=True)
    b.sort(reverse=True)
    c.sort(reverse=True)
    ql = [[-(a[0] + b[0] + c[0]), 0, 0, 0]]
    heapq.heapify(ql)
    fq = collections.defaultdict(int)
    fq[0, 0, 0]
    for i in range(k):
        s, ap, bp, cp = heapq.heappop(ql)
        for app, bpp, cpp in [[ap + 1, bp, cp], [ap, bp + 1, cp], [ap, bp, cp + 1]]:
            if app < x and bpp < y and cpp < z:
                if (app, bpp, cpp) not in fq:
                    heapq.heappush(ql, [-(a[app] + b[bpp] + c[cpp]), app, bpp, cpp])
                    fq[app, bpp, cpp]
        print((-s))

if __name__ == "__main__":
    solve()

+    b = list(map(int, input().rstrip("\n").split()))

+    c = list(map(int, input().rstrip("\n").split()))

-    b = list(map(int, input().rstrip("\n").split()))

-    c = list(map(int, input().rstrip("\n").split()))

-                if (-(a[aq + 1] + b[bq] + c[cq]), aq + 1, bq, cq) not in fq:

-                    heapq.heappush(q, [-(a[aq + 1] + b[bq] + c[cq]), aq + 1, bq, cq])

-                if (-(a[aq] + b[bq + 1] + c[cq]), aq, bq + 1, cq) not in fq:

-                    heapq.heappush(q, [-(a[aq] + b[bq + 1] + c[cq]), aq, bq + 1, cq])

-                if (-(a[aq] + b[bq] + c[cq + 1]), aq, bq, cq + 1) not in fq:

-                    heapq.heappush(q, [-(a[aq] + b[bq] + c[cq + 1]), aq, bq, cq + 1])

+        s, ap, bp, cp = heapq.heappop(ql)

+        for app, bpp, cpp in [[ap + 1, bp, cp], [ap, bp + 1, cp], [ap, bp, cp + 1]]:

+            if app < x and bpp < y and cpp < z:

+                if (app, bpp, cpp) not in fq:

+                    heapq.heappush(ql, [-(a[app] + b[bpp] + c[cpp]), app, bpp, cpp])


Input:
N = int(input())

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

players = [0 for _ in range(N)]

for play in list(zip(*score)):

    for i, p in enumerate(play):

        if play.count(p) == 1:

            players[i] += p

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

N = int(input())

score = [input().split() for _ in range(N)]

players = [0]*N

for play in list(zip(*score)):

    for i, p in enumerate(play):

        if play.count(p) == 1:

            players[i] += int(p)

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

N = int(input())
score = [list(map(int, input().split())) for _ in range(N)]
players = [0 for _ in range(N)]
for play in list(zip(*score)):
    for i, p in enumerate(play):
        if play.count(p) == 1:
            players[i] += p
print(*players, sep="\n")

N = int(input())
score = [input().split() for _ in range(N)]
players = [0] * N
for play in list(zip(*score)):
    for i, p in enumerate(play):
        if play.count(p) == 1:
            players[i] += int(p)
print(*players, sep="\n")

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

+score = [input().split() for _ in range(N)]


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

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

dp = [False]*(k+1)

for stones in range(k+1):

    for x in arr:

        if stones >= x and dp[stones-x] == False:

            dp[stones] = True

if dp[k]:

    print("First")

else:

    print("Second")

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

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

dp = [False]*(K+1)

for i in range(K+1):

    for j in range(N):

        if i-A[j]>=0 and dp[i-A[j]] == False:

            dp[i] = True

if dp[K]:

    print("First")

else:

    print("Second")

n, k = list(map(int, input().split()))
arr = list(map(int, input().split()))
dp = [False] * (k + 1)
for stones in range(k + 1):
    for x in arr:
        if stones >= x and dp[stones - x] == False:
            dp[stones] = True
if dp[k]:
    print("First")
else:
    print("Second")

N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
dp = [False] * (K + 1)
for i in range(K + 1):
    for j in range(N):
        if i - A[j] >= 0 and dp[i - A[j]] == False:
            dp[i] = True
if dp[K]:
    print("First")
else:
    print("Second")

-        if stones >= x and dp[stones - x] == False:

+        if i - A[j] >= 0 and dp[i - A[j]] == False:


Input:
W = input().lower()

s = []

while True:

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

    if(T[0] == "END_OF_TEXT"):

        break

    else:

        for i in range(len(T)):

            s.append(T[i].lower())

ans = 0

for i in range(len(s)):

    if(s[i] == W):

        ans += 1

print(ans)

W = input().lower()

s = []

ans = 0

while True:

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

    if(T[0] == "END_OF_TEXT"):

        break

    else:

        for i in range(len(T)):

            if(W == T[i].lower()):

                ans += 1

print(ans)

W = input().lower()
s = []
while True:
    T = list(map(str, input().split()))
    if T[0] == "END_OF_TEXT":
        break
    else:
        for i in range(len(T)):
            s.append(T[i].lower())
ans = 0
for i in range(len(s)):
    if s[i] == W:
        ans += 1
print(ans)

W = input().lower()
s = []
ans = 0
while True:
    T = list(map(str, input().split()))
    if T[0] == "END_OF_TEXT":
        break
    else:
        for i in range(len(T)):
            if W == T[i].lower():
                ans += 1
print(ans)

+ans = 0
-            s.append(T[i].lower())
-ans = 0
-for i in range(len(s)):
-    if s[i] == W:
-        ans += 1
+            if W == T[i].lower():
+                ans += 1


Input:
import math

print((math.factorial(int(input()))%(10**9+7)))

n=int(input())

ans=1

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

    ans*=i

    ans%=10**9+7

print(ans)

import math

print((math.factorial(int(input())) % (10**9 + 7)))

n = int(input())
ans = 1
for i in range(1, n + 1):
    ans *= i
    ans %= 10**9 + 7
print(ans)

-print((math.factorial(int(input())) % (10**9 + 7)))


Input:
import sys

read = sys.stdin.buffer.read

readline = sys.stdin.buffer.readline

readlines = sys.stdin.buffer.readlines

N = int(readline())

S = read().split()

S = sorted(S)

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

max_num = 0

left = 0

right = 0

while right < N:

    while right < N and S[left] == S[right]:

        right += 1

    if (right  - left) >= max_num:

        ls[right - left].append(S[left].decode())

        max_num = right - left

    left = right

print(('\n'.join(ls[max_num])))

from collections import Counter

import sys

read = sys.stdin.buffer.read

readline = sys.stdin.buffer.readline

readlines = sys.stdin.buffer.readlines

N = int(readline())

S = read().split()

res = []

c = Counter(S)

max_num = c.most_common(1)[0][1]

for i, j in list(c.items()):

    if j == max_num:

        res.append(i)

res.sort()

print(('\n'.join(list([x.decode() for x in res]))))

import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
S = read().split()
S = sorted(S)
ls = [[] for i in range(N + 1)]
max_num = 0
left = 0
right = 0
while right < N:
    while right < N and S[left] == S[right]:
        right += 1
    if (right - left) >= max_num:
        ls[right - left].append(S[left].decode())
        max_num = right - left
    left = right
print(("\n".join(ls[max_num])))

from collections import Counter
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
S = read().split()
res = []
c = Counter(S)
max_num = c.most_common(1)[0][1]
for i, j in list(c.items()):
    if j == max_num:
        res.append(i)
res.sort()
print(("\n".join(list([x.decode() for x in res]))))

-    while right < N and S[left] == S[right]:

-        ls[right - left].append(S[left].decode())

+print(("\n".join(list([x.decode() for x in res]))))


Input:
# temp

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

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

dp = [0] + [float("inf")]*(10**5)

for i in range(n):

    for j in range(10**5,wv[i][1]-1,-1):

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

res = 0

for v,e in enumerate(dp):

    if e <= w:

        res = v

print(res)

# dpE - Knapsack 2

import sys

input = sys.stdin.readline

def main():

    n, W = tuple(map(int, input().rstrip().split()))

    A = tuple(tuple(map(int, input().rstrip().split())) for _ in range(n))

    _, v = list(zip(*A))

    lim = sum(v)

    dp = [0] + [float("inf")] * lim

    for i in range(n):

        for j in range(lim, A[i][1] - 1, -1):

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

    ans = max(v for v, w in enumerate(dp) if w <= W)

    print(ans)

if __name__ == "__main__":

    main()

# temp
n, w = list(map(int, input().split()))
wv = [tuple(map(int, input().split())) for i in range(n)]
dp = [0] + [float("inf")] * (10**5)
for i in range(n):
    for j in range(10**5, wv[i][1] - 1, -1):
        dp[j] = min(dp[j], dp[j - wv[i][1]] + wv[i][0])
res = 0
for v, e in enumerate(dp):
    if e <= w:
        res = v
print(res)

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

+    n, W = tuple(map(int, input().rstrip().split()))

+    A = tuple(tuple(map(int, input().rstrip().split())) for _ in range(n))

+        for j in range(lim, A[i][1] - 1, -1):

+    ans = max(v for v, w in enumerate(dp) if w <= W)


Input:
def main():

  n = int(input())

  dp = [0]*(n+1)

  dp[0] = 1

  mod = pow(10, 9) + 7

  for i in range(n+1):

    for j in range(i-2):

      dp[i] += dp[j]

      dp[i] %= mod

  print((dp[n]))

if __name__ == "__main__":

  main()

def main():

  n = int(input())

  dp = [0]*(n+1)

  dp[0] = 1

  mod = pow(10, 9) + 7

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

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

    dp[i] %= mod

  print((dp[n]))

if __name__ == "__main__":

  main()

def main():
    n = int(input())
    dp = [0] * (n + 1)
    dp[0] = 1
    mod = pow(10, 9) + 7
    for i in range(n + 1):
        for j in range(i - 2):
            dp[i] += dp[j]
            dp[i] %= mod
    print((dp[n]))

if __name__ == "__main__":
    main()

def main():
    n = int(input())
    dp = [0] * (n + 1)
    dp[0] = 1
    mod = pow(10, 9) + 7
    for i in range(3, n + 1):
        dp[i] = dp[i - 1] + dp[i - 3]
        dp[i] %= mod
    print((dp[n]))

if __name__ == "__main__":
    main()

-    for i in range(n + 1):
-        for j in range(i - 2):
-            dp[i] += dp[j]
-            dp[i] %= mod
+    for i in range(3, n + 1):
+        dp[i] = dp[i - 1] + dp[i - 3]
+        dp[i] %= mod


Input:
class Queue:

    def __init__(self,values):

        self.values = values

    def empty(self):

        if len(self.values) == 0:

            return True

        else:

            return False

    def enqueue(self,v):

        self.values.append(v)

    def dequeue(self):

        if len(self.values) <= 0:

            raise

        else:

            v = self.values[0]

            del self.values[0]

            return v

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

processes = []

for i in range(n):

    n,t = input().split(' ')

    processes.append((n,int(t)))

queue = Queue(processes)

clock = 0

done = []

while not queue.empty():

    p = queue.dequeue()

    n = p[0]

    t = p[1]

    if t <= q:

        clock+=t

        done.append((n,clock))

    else:

        queue.enqueue((n,t-q))

        clock+=q

for p in done:

    print(p[0],p[1])

class Queue:

    def __init__(self,l):

        self.values = []

        self.l = l

        for _ in range(l):

            self.values.append(None)

        self.head = 0

        self.tail = 0

    def inc(self,n):

        if n+1 >= self.l:

            return 0

        else:

            return n+1

    def enqueue(self,v):

        if self.inc(self.head) == self.tail:

            print('overflow')

            exit()

        self.values[self.head] = v

        self.head = self.inc(self.head)

    def dequeue(self):

        if self.head == self.tail:

            print('underflow')

            exit()

        v = self.values[self.tail]

        self.tail = self.inc(self.tail)

        return v

    def size(self):

        if self.head >= self.tail:

            return self.head-self.tail

        else:

            self.head + (self.l-self.tail)

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

queue = Queue(200000)

for _ in range(n):

    n,t = input().split(' ')

    t = int(t)

    queue.enqueue((n,t))

c = 0

while queue.size()>0:

    n,t = queue.dequeue()

    if t <= q:

        c += t

        print(n,c)

    else:

        queue.enqueue((n,t-q))

        c += q

class Queue:
    def __init__(self, values):
        self.values = values

    def empty(self):
        if len(self.values) == 0:
            return True
        else:
            return False

    def enqueue(self, v):
        self.values.append(v)

    def dequeue(self):
        if len(self.values) <= 0:
            raise
        else:
            v = self.values[0]
            del self.values[0]
            return v

n, q = list(map(int, input().split(" ")))
processes = []
for i in range(n):
    n, t = input().split(" ")
    processes.append((n, int(t)))
queue = Queue(processes)
clock = 0
done = []
while not queue.empty():
    p = queue.dequeue()
    n = p[0]
    t = p[1]
    if t <= q:
        clock += t
        done.append((n, clock))
    else:
        queue.enqueue((n, t - q))
        clock += q
for p in done:
    print(p[0], p[1])

class Queue:
    def __init__(self, l):
        self.values = []
        self.l = l
        for _ in range(l):
            self.values.append(None)
        self.head = 0
        self.tail = 0

    def inc(self, n):
        if n + 1 >= self.l:
            return 0
        else:
            return n + 1

    def enqueue(self, v):
        if self.inc(self.head) == self.tail:
            print("overflow")
            exit()
        self.values[self.head] = v
        self.head = self.inc(self.head)

    def dequeue(self):
        if self.head == self.tail:
            print("underflow")
            exit()
        v = self.values[self.tail]
        self.tail = self.inc(self.tail)
        return v

    def size(self):
        if self.head >= self.tail:
            return self.head - self.tail
        else:
            self.head + (self.l - self.tail)

n, q = list(map(int, input().split(" ")))
queue = Queue(200000)
for _ in range(n):
    n, t = input().split(" ")
    t = int(t)
    queue.enqueue((n, t))
c = 0
while queue.size() > 0:
    n, t = queue.dequeue()
    if t <= q:
        c += t
        print(n, c)
    else:
        queue.enqueue((n, t - q))
        c += q

+        if self.inc(self.head) == self.tail:

+        self.head = self.inc(self.head)

+        self.tail = self.inc(self.tail)

+            return self.head - self.tail

+            self.head + (self.l - self.tail)


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

if r - l > 2019:

    print((0))

else:

    tres = 2019

    for i in range(l,r):

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

            mod = (i % 2019) * (j % 2019) % 2019

            tres = min(tres,mod)

    print(tres)

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

if r - l > 2019:

    print((0))

else:

    tres = 2019

    for i in range(l,r):

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

            mod = (i % 2019) * (j % 2019) % 2019

            tres = min(tres,mod)

            if tres == 0:

                break

        if tres == 0:

            break

    print(tres)

l, r = list(map(int, input().split()))
if r - l > 2019:
    print((0))
else:
    tres = 2019
    for i in range(l, r):
        for j in range(i + 1, r + 1):
            mod = (i % 2019) * (j % 2019) % 2019
            tres = min(tres, mod)
    print(tres)

l, r = list(map(int, input().split()))
if r - l > 2019:
    print((0))
else:
    tres = 2019
    for i in range(l, r):
        for j in range(i + 1, r + 1):
            mod = (i % 2019) * (j % 2019) % 2019
            tres = min(tres, mod)
            if tres == 0:
                break
        if tres == 0:
            break
    print(tres)

+            if tres == 0:
+                break
+        if tres == 0:
+            break


Input:
# 2019-11-12 22:21:08(JST)

import sys

# import collections

# import math

# from string import ascii_lowercase, ascii_uppercase, digits

# from bisect import bisect_left as bi_l, bisect_right as bi_r

import itertools

# from functools import reduce

# import operator as op

# from scipy.misc import comb # float

# import numpy as np

def main():

    s = sys.stdin.readline().rstrip()

    all_words = []

    for i in range(1, len(s) + 1):

        for letters in itertools.product('ATCG', repeat=i):

            word = ''.join(letters)

            all_words.append(word)

    for i in range(len(all_words)-1, 0-1, -1):

        if all_words[i] in s:

            print((len(all_words[i])))

            sys.exit()

    print((0))

if __name__ == "__main__":

    main()

# 2019-11-12 22:21:08(JST)

import sys

# import collections

# import math

# from string import ascii_lowercase, ascii_uppercase, digits

# from bisect import bisect_left as bi_l, bisect_right as bi_r

# import itertools

# from functools import reduce

# import operator as op

# from scipy.misc import comb # float

# import numpy as np

def main():

    s = sys.stdin.readline().rstrip()

    permitted = 'ACGT'

    continuous_count = []

    count = 0

    for i in range(len(s)):

        char = s[i]

        if char in permitted:

            count += 1

        else:

            continuous_count.append(count)

            count = 0

        if i == len(s) - 1:

            continuous_count.append(count)

    if not continuous_count:

        print((len(s)))

    else:

        print((max(continuous_count)))

if __name__ == "__main__":

    main()

# 2019-11-12 22:21:08(JST)
import sys

# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
import itertools

# from functools import reduce
# import operator as op
# from scipy.misc import comb # float
# import numpy as np
def main():
    s = sys.stdin.readline().rstrip()
    all_words = []
    for i in range(1, len(s) + 1):
        for letters in itertools.product("ATCG", repeat=i):
            word = "".join(letters)
            all_words.append(word)
    for i in range(len(all_words) - 1, 0 - 1, -1):
        if all_words[i] in s:
            print((len(all_words[i])))
            sys.exit()
    print((0))

if __name__ == "__main__":
    main()

# 2019-11-12 22:21:08(JST)
import sys

# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# from scipy.misc import comb # float
# import numpy as np
def main():
    s = sys.stdin.readline().rstrip()
    permitted = "ACGT"
    continuous_count = []
    count = 0
    for i in range(len(s)):
        char = s[i]
        if char in permitted:
            count += 1
        else:
            continuous_count.append(count)
            count = 0
        if i == len(s) - 1:
            continuous_count.append(count)
    if not continuous_count:
        print((len(s)))
    else:
        print((max(continuous_count)))

if __name__ == "__main__":
    main()

-        for letters in itertools.product("ATCG", repeat=i):

-    for i in range(len(all_words) - 1, 0 - 1, -1):

+            continuous_count.append(count)

+            continuous_count.append(count)


Input:
#                         author:  kagemeka

#                         created: 2019-11-08 14:51:29(JST)

## internal modules

import sys

# import collections

# import math

# import string

# import bisect

# import re

# import itertools

import statistics

# import functools

# import operator

## external modules

# import scipy.special   # if use comb function on AtCoder,

# import scipy.misc      # select scipy.misc.comb (old version)

def main():

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

    for i in range(n):

        a[i] -= (i + 1)

    if n % 2 != 0:

        b = statistics.median(a)

    else:

        if a.count(statistics.median_high(a)) >= a.count(statistics.median_low(a)):

            b = statistics.median_high(a)

        else:

            b = statistics.median_low(a)

    ans = sum([abs(a[i] - b) for i in range(n)])

    print(ans)

if __name__ == "__main__":

    # execute only if run as a script

    main()

import sys

n, *a = list(map(int, sys.stdin.read().split()))

def main():

    for i in range(n):

        a[i] -= (i + 1)

    a.sort()

    b = a[n // 2]

    res = 0

    for i in range(n):

        res += abs(a[i] - b)

    return res

if __name__ == '__main__':

    ans = main()

    print(ans)

#                         author:  kagemeka
#                         created: 2019-11-08 14:51:29(JST)
## internal modules
import sys

# import collections
# import math
# import string
# import bisect
# import re
# import itertools
import statistics

# import functools
# import operator
## external modules
# import scipy.special   # if use comb function on AtCoder,
# import scipy.misc      # select scipy.misc.comb (old version)
def main():
    n, *a = (int(x) for x in sys.stdin.read().split())
    for i in range(n):
        a[i] -= i + 1
    if n % 2 != 0:
        b = statistics.median(a)
    else:
        if a.count(statistics.median_high(a)) >= a.count(statistics.median_low(a)):
            b = statistics.median_high(a)
        else:
            b = statistics.median_low(a)
    ans = sum([abs(a[i] - b) for i in range(n)])
    print(ans)

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

import sys

n, *a = list(map(int, sys.stdin.read().split()))

def main():
    for i in range(n):
        a[i] -= i + 1
    a.sort()
    b = a[n // 2]
    res = 0
    for i in range(n):
        res += abs(a[i] - b)
    return res

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

-#                         author:  kagemeka

+n, *a = list(map(int, sys.stdin.read().split()))

-# import scipy.special   # if use comb function on AtCoder,

-# import scipy.misc      # select scipy.misc.comb (old version)

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

-        if a.count(statistics.median_high(a)) >= a.count(statistics.median_low(a)):

-            b = statistics.median_high(a)

-            b = statistics.median_low(a)

-    ans = sum([abs(a[i] - b) for i in range(n)])


Input:
def findSumDigit(num):

    global total

    total = ""

    while num > 0:

        total += str(num % 10)

        num //= 10

    return total

def main():

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

    ans = 0

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

        tmp = str(findSumDigit(i))

        if tmp == str(i):

            ans += 1

    print(ans)

if __name__ == '__main__':

    main()

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

ans = 0

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

    seki_gyaku = str(i)

    if seki_gyaku == seki_gyaku[::-1]:

        ans += 1

print(ans)

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

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

if __name__ == "__main__":
    main()

a, b = list(map(int, input().split()))
ans = 0
for i in range(a, b + 1):
    seki_gyaku = str(i)
    if seki_gyaku == seki_gyaku[::-1]:
        ans += 1
print(ans)

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


Input:
N = int(input())

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

now = a[0]

count = 1

c = 0

for i in range(10**6):

    if now != 2:

        count += 1

        now = a[now - 1]

    else:

        print(count)

        c = 1

        break

if c == 0:

    print((-1))

N = int(input())

a = [0] + [int(input()) for _ in range(N)]

x = 1

visited = set([1])

answer = 0

while True:

  x = a[x]

  if x in visited:

    answer = -1

    break

  visited.add(x)

  answer += 1

  if x == 2:

    break

print(answer)

+a = [0] + [int(input()) for _ in range(N)]


Input:
n=int(input())

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

def f():

 for i in range(n-1):

  d=a[i][:];d[3],d[4]=d[4],d[3]

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

   e=a[j][:];e[3],e[4]=e[4],e[3]

   for p in([0,1,2,3,4,5],[1,5,2,0,4,3],[2,1,5,3,0,4],[3,0,2,5,4,1],[4,1,0,3,5,2],[5,1,4,3,2,0]):

    f=[d[k]for k in p]

    if f[0]==e[0]and f[5]==e[5]:

     f=f[1:5]*2

     for k in range(4):

      if f[k:k+4]==e[1:5]:return'No'

 return'Yes'

print((f()))

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

+a = [[int(s) for s in input().split()] for _ in range(n)]


Input:
N = int(input())

ans = 0

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

    if len(str(i))%2==1:

        ans += 1

print(ans)

import sys

def rec(length):

    if length == 1:

        return 9

    else:

        return 9 * 10**(length - 1) + rec(length - 2)

n = input()

length = len(n)

if length == 1:

    print(n)

    sys.exit()

if length % 2 == 0:

    ans = rec(length - 1)

else:

    ans = rec(length - 2) + int(n) - int("1" + "0" * (length - 1)) + 1

print(ans)

N = int(input())
ans = 0
for i in range(1, N + 1):
    if len(str(i)) % 2 == 1:
        ans += 1
print(ans)

import sys

def rec(length):
    if length == 1:
        return 9
    else:
        return 9 * 10 ** (length - 1) + rec(length - 2)

n = input()
length = len(n)
if length == 1:
    print(n)
    sys.exit()
if length % 2 == 0:
    ans = rec(length - 1)
else:
    ans = rec(length - 2) + int(n) - int("1" + "0" * (length - 1)) + 1
print(ans)

+        return 9 * 10 ** (length - 1) + rec(length - 2)


Input:
import itertools

from collections import Counter

N = int(input())

src = [input() for i in range(N)]

ctr = Counter()

for s in src:

    ctr[s[0]] += 1

ans = 0

for ptn in itertools.combinations('MARCH',3):

    a,b,c = ptn

    ans += ctr[a]*ctr[b]*ctr[c]

print(ans)

N = int(input())

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

from collections import Counter

ctr = Counter([s[0] for s in S])

ans = 0

import itertools

for ptn in itertools.combinations('MARCH', 3):

    t = 1

    for c in ptn:

        t *= ctr[c]

    ans += t

print(ans)

import itertools
from collections import Counter

N = int(input())
src = [input() for i in range(N)]
ctr = Counter()
for s in src:
    ctr[s[0]] += 1
ans = 0
for ptn in itertools.combinations("MARCH", 3):
    a, b, c = ptn
    ans += ctr[a] * ctr[b] * ctr[c]
print(ans)

N = int(input())
S = [input() for i in range(N)]
from collections import Counter

ctr = Counter([s[0] for s in S])
ans = 0
import itertools

for ptn in itertools.combinations("MARCH", 3):
    t = 1
    for c in ptn:
        t *= ctr[c]
    ans += t
print(ans)

-import itertools
+N = int(input())
+S = [input() for i in range(N)]
-N = int(input())
-src = [input() for i in range(N)]
-ctr = Counter()
-for s in src:
-    ctr[s[0]] += 1
+ctr = Counter([s[0] for s in S])
+import itertools
+
-    a, b, c = ptn
-    ans += ctr[a] * ctr[b] * ctr[c]
+    t = 1
+    for c in ptn:
+        t *= ctr[c]
+    ans += t


Input:
N = int(input())

count = 0

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

    num_dig = 0

    ii = i

    while ii > 0:

        ii = int(ii / 10)

        num_dig += 1

    if num_dig % 2 != 0:

        count += 1

print(count)

N = int(input())

count = 0

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

    if len(str(i)) % 2 != 0:

        count += 1

print(count)

-    num_dig = 0
-    ii = i
-    while ii > 0:
-        ii = int(ii / 10)
-        num_dig += 1
-    if num_dig % 2 != 0:
+    if len(str(i)) % 2 != 0:


Input:
from string import ascii_lowercase as lower

print((lower[lower.find(input())+1]))

from string import ascii_lowercase as lower

print((lower[lower.find(input()) + 1]))

-from string import ascii_lowercase as lower


Input:
#!usr/bin/env python3

from collections import defaultdict

from collections import deque

from heapq import heappush, heappop

import sys

import math

import bisect

import random

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

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

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

def S(): return list(sys.stdin.readline())[:-1]

def IR(n):

    l = [None for i in range(n)]

    for i in range(n):l[i] = I()

    return l

def LIR(n):

    l = [None for i in range(n)]

    for i in range(n):l[i] = LI()

    return l

def SR(n):

    l = [None for i in range(n)]

    for i in range(n):l[i] = S()

    return l

def LSR(n):

    l = [None for i in range(n)]

    for i in range(n):l[i] = SR()

    return l

mod = 1000000007

#A

"""

def gcd(a,b):

    if a == 0:

        return b

    return gcd(b%a,a)

n = I()

a = IR(n)

l = a[0]

for i in range(1,n):

    g = gcd(l,a[i])

    l *= a[i]//g

print(l)

"""

#B

n = I()

v = [[] for i in range(n)]

for i in range(n-1):

    a,b,c = LI()

    a -= 1

    b -= 1

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

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

Q,k = LI()

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

d[k-1] = 0

q = deque()

q.append(k-1)

while q:

    x = q.pop()

    for y,c in v[x]:

        if d[y] == -1:

            d[y] = d[x]+c

            q.append(y)

for i in range(Q):

    x,y = LI()

    x -= 1

    y -= 1

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

#C

#D

#E

#F

#G

#H

#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T

#!usr/bin/env python3

from collections import defaultdict

from collections import deque

from heapq import heappush, heappop

import sys

import math

import bisect

import random

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

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

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

def S(): return list(sys.stdin.readline())[:-1]

def IR(n):

    l = [None for i in range(n)]

    for i in range(n):l[i] = I()

    return l

def LIR(n):

    l = [None for i in range(n)]

    for i in range(n):l[i] = LI()

    return l

def SR(n):

    l = [None for i in range(n)]

    for i in range(n):l[i] = S()

    return l

def LSR(n):

    l = [None for i in range(n)]

    for i in range(n):l[i] = SR()

    return l

mod = 1000000007

#A

"""

def gcd(a,b):

    if a == 0:

        return b

    return gcd(b%a,a)

n = I()

a = IR(n)

l = a[0]

for i in range(1,n):

    g = gcd(l,a[i])

    l *= a[i]//g

print(l)

"""

#B

n = I()

v = [[] for i in range(n)]

for i in range(n-1):

    a,b,c = LI()

    a -= 1

    b -= 1

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

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

Q,k = LI()

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

d[k-1] = 0

q = deque()

q.append(k-1)

while q:

    x = q.popleft()

    for y,c in v[x]:

        if d[y] == -1:

            d[y] = d[x]+c

            q.append(y)

for i in range(Q):

    x,y = LI()

    x -= 1

    y -= 1

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

#C

#D

#E

#F

#G

#H

#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T

#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random

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

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

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

def S():
    return list(sys.stdin.readline())[:-1]

def IR(n):
    l = [None for i in range(n)]
    for i in range(n):
        l[i] = I()
    return l

def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):
        l[i] = LI()
    return l

def SR(n):
    l = [None for i in range(n)]
    for i in range(n):
        l[i] = S()
    return l

def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):
        l[i] = SR()
    return l

mod = 1000000007
# A
"""
def gcd(a,b):
    if a == 0:
        return b
    return gcd(b%a,a)
n = I()
a = IR(n)
l = a[0]
for i in range(1,n):
    g = gcd(l,a[i])
    l *= a[i]//g
print(l)
"""
# B
n = I()
v = [[] for i in range(n)]
for i in range(n - 1):
    a, b, c = LI()
    a -= 1
    b -= 1
    v[a].append([b, c])
    v[b].append([a, c])
Q, k = LI()
d = [-1 for i in range(n)]
d[k - 1] = 0
q = deque()
q.append(k - 1)
while q:
    x = q.pop()
    for y, c in v[x]:
        if d[y] == -1:
            d[y] = d[x] + c
            q.append(y)
for i in range(Q):
    x, y = LI()
    x -= 1
    y -= 1
    print((d[x] + d[y]))
# C
# D
# E
# F
# G
# H
# I
# J
# K
# L
# M
# N
# O
# P
# Q
# R
# S
# T

#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random

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

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

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

def S():
    return list(sys.stdin.readline())[:-1]

def IR(n):
    l = [None for i in range(n)]
    for i in range(n):
        l[i] = I()
    return l

def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):
        l[i] = LI()
    return l

def SR(n):
    l = [None for i in range(n)]
    for i in range(n):
        l[i] = S()
    return l

def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):
        l[i] = SR()
    return l

mod = 1000000007
# A
"""
def gcd(a,b):
    if a == 0:
        return b
    return gcd(b%a,a)
n = I()
a = IR(n)
l = a[0]
for i in range(1,n):
    g = gcd(l,a[i])
    l *= a[i]//g
print(l)
"""
# B
n = I()
v = [[] for i in range(n)]
for i in range(n - 1):
    a, b, c = LI()
    a -= 1
    b -= 1
    v[a].append([b, c])
    v[b].append([a, c])
Q, k = LI()
d = [-1 for i in range(n)]
d[k - 1] = 0
q = deque()
q.append(k - 1)
while q:
    x = q.popleft()
    for y, c in v[x]:
        if d[y] == -1:
            d[y] = d[x] + c
            q.append(y)
for i in range(Q):
    x, y = LI()
    x -= 1
    y -= 1
    print((d[x] + d[y]))
# C
# D
# E
# F
# G
# H
# I
# J
# K
# L
# M
# N
# O
# P
# Q
# R
# S
# T


Input:
import string

w = input()

for a in string.ascii_lowercase:

    cnt = 0

    for t in w:

        if t == a:

            cnt = cnt + 1

    if cnt % 2 == 1:

        print("No")

        exit()

print("Yes")

w = input()

m = [0] * 26

for t in w:

    m[ord(t) - ord('a')] += 1

for cnt in m:

    if cnt % 2 == 1:

        print("No")

        exit()

print("Yes")

w = input()
m = [0] * 26
for t in w:
    m[ord(t) - ord("a")] += 1
for cnt in m:
    if cnt % 2 == 1:
        print("No")
        exit()
print("Yes")

-import string
-for a in string.ascii_lowercase:
-    cnt = 0
-    for t in w:
-        if t == a:
-            cnt = cnt + 1
+m = [0] * 26
+for t in w:
+    m[ord(t) - ord("a")] += 1
+for cnt in m:


Input:
mod = 10**9+7

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

l = [0]*n

for _ in range(m):

  l[int(input())-1] = 1

s = 0

t = 1

for i in range(n):

  if l[i] > 0:

    t, s = 0, t

  else:

    t, s = (s+t)%mod, t

print(t)

import sys

input = sys.stdin.readline

mod = 10**9+7

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

l = [0]*n

for _ in range(m):

  l[int(input())-1] = 1

t, s = 1, 0

for i in range(n):

  if l[i]:

    t, s = 0, t

  else:

    t, s = (s+t)%mod, t

print(t)

mod = 10**9 + 7
n, m = list(map(int, input().split()))
l = [0] * n
for _ in range(m):
    l[int(input()) - 1] = 1
s = 0
t = 1
for i in range(n):
    if l[i] > 0:
        t, s = 0, t
    else:
        t, s = (s + t) % mod, t
print(t)

import sys

input = sys.stdin.readline
mod = 10**9 + 7
n, m = list(map(int, input().split()))
l = [0] * n
for _ in range(m):
    l[int(input()) - 1] = 1
t, s = 1, 0
for i in range(n):
    if l[i]:
        t, s = 0, t
    else:
        t, s = (s + t) % mod, t
print(t)

+import sys
+
+input = sys.stdin.readline
-s = 0
-t = 1
+t, s = 1, 0
-    if l[i] > 0:
+    if l[i]:


Input:
N,M = [int(c) for c in input().split()]

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

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

for i in range(N):

    mi = 2*10**9

    for j in range(M):

        tmp = abs(ab[i][0]-cd[j][0])+abs(ab[i][1]-cd[j][1])

        if mi > tmp:

            mi = tmp

            ans = j+1

    print(ans)

N,M = [int(c) for c in input().split()]

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

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

for i in range(N):

    mi = 10**9

    for j in range(M):

        tmp = abs(ab[i][0]-cd[j][0])+abs(ab[i][1]-cd[j][1])

        if mi > tmp:

            mi = tmp

            ans = j+1

    print(ans)

N, M = [int(c) for c in input().split()]
ab = [list(map(int, input().split())) for c in range(N)]
cd = [list(map(int, input().split())) for c in range(M)]
for i in range(N):
    mi = 2 * 10**9
    for j in range(M):
        tmp = abs(ab[i][0] - cd[j][0]) + abs(ab[i][1] - cd[j][1])
        if mi > tmp:
            mi = tmp
            ans = j + 1
    print(ans)

N, M = [int(c) for c in input().split()]
ab = [list(map(int, input().split())) for c in range(N)]
cd = [list(map(int, input().split())) for c in range(M)]
for i in range(N):
    mi = 10**9
    for j in range(M):
        tmp = abs(ab[i][0] - cd[j][0]) + abs(ab[i][1] - cd[j][1])
        if mi > tmp:
            mi = tmp
            ans = j + 1
    print(ans)


Input:
def test():

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

    count = 0

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

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

        if j[0] == j[4] and j[1] == j[3]:

            count += 1

    print(count)

if __name__ == "__main__":

    test()

def test():

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

    count = 0

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

        if str(i)[0] == str(i)[4] and str(i)[1] == str(i)[3]:

            count += 1

    print(count)

if __name__ == "__main__":

    test()

def test():
    a, b = list(map(int, input().split()))
    count = 0
    for i in range(a, b + 1):
        j = list(map(int, list(str(i))))
        if j[0] == j[4] and j[1] == j[3]:
            count += 1
    print(count)

if __name__ == "__main__":
    test()

def test():
    a, b = list(map(int, input().split()))
    count = 0
    for i in range(a, b + 1):
        if str(i)[0] == str(i)[4] and str(i)[1] == str(i)[3]:
            count += 1
    print(count)

if __name__ == "__main__":
    test()

-        j = list(map(int, list(str(i))))


Input:
from bisect import bisect_left

from bisect import bisect_right

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

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

a = sorted(a)

a_count = [0]*100010

a_sum = [0]*100010

for i in range(n):

    a_count[a[i]] += 1

    a_sum[a[i]] += a[i]

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

    a_count[i] += a_count[i+1]

    a_sum[i] += a_sum[i+1]

def chk(x):

    case = 0

    for i in range(n):

        if 0<= x-a[i]<= 10**5+5:

            case += a_count[x-a[i]]

        elif x-a[i] < 0:

            case += n

    if case >= m:

        ch = True

    else:

        ch = False

    return ch

l = 2*a[-1]+1    #NG

r = 1 #OK

while abs(r-l) > 1:

    kk = (r+l)//2

    if chk(kk):

        r = kk

    else:

        l = kk

ans = 0

sm = sum(a)

l = r

case = 0

for i in range(n):

    num = n-bisect_right(a,l-a[i]-1)

    case += num

    ans += num*a[i]*2

ans -= (case-m)*l

print(ans)

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

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

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

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

for x in a:

    aa[x] += 1

    aa_sum[x] += x

for i in range(10**5)[::-1]:

    aa[i] = aa[i] + aa[i+1]

    aa_sum[i] = aa_sum[i] + aa_sum[i+1]

def count(x):

    cnt = 0

    sm = 0

    for i in range(n):

        if x-a[i] < 0:

            cnt += n

            sm += aa_sum[0]+n*a[i]

        elif x-a[i] > 10**5:

            continue

        else:

            cnt += aa[x-a[i]]

            sm += aa_sum[x-a[i]]+aa[x-a[i]]*a[i]

    return cnt, sm

bottom = 0

top = 10**6

while top - bottom > 1:

    mid = (top+bottom) // 2

    cnt, sm = count(mid)

    if cnt < m:

        top = mid

    else:

        bottom = mid

cnt, sm = count(bottom)

ans = sm - (cnt-m)*bottom

print(ans)

from bisect import bisect_left
from bisect import bisect_right

n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
a = sorted(a)
a_count = [0] * 100010
a_sum = [0] * 100010
for i in range(n):
    a_count[a[i]] += 1
    a_sum[a[i]] += a[i]
for i in range(100005, -1, -1):
    a_count[i] += a_count[i + 1]
    a_sum[i] += a_sum[i + 1]

def chk(x):
    case = 0
    for i in range(n):
        if 0 <= x - a[i] <= 10**5 + 5:
            case += a_count[x - a[i]]
        elif x - a[i] < 0:
            case += n
    if case >= m:
        ch = True
    else:
        ch = False
    return ch

l = 2 * a[-1] + 1  # NG
r = 1  # OK
while abs(r - l) > 1:
    kk = (r + l) // 2
    if chk(kk):
        r = kk
    else:
        l = kk
ans = 0
sm = sum(a)
l = r
case = 0
for i in range(n):
    num = n - bisect_right(a, l - a[i] - 1)
    case += num
    ans += num * a[i] * 2
ans -= (case - m) * l
print(ans)

n, m = list(map(int, input().split()))
a = [int(x) for x in input().split()]
aa = [0] * (10**5 + 1)
aa_sum = [0] * (10**5 + 1)
for x in a:
    aa[x] += 1
    aa_sum[x] += x
for i in range(10**5)[::-1]:
    aa[i] = aa[i] + aa[i + 1]
    aa_sum[i] = aa_sum[i] + aa_sum[i + 1]

def count(x):
    cnt = 0
    sm = 0
    for i in range(n):
        if x - a[i] < 0:
            cnt += n
            sm += aa_sum[0] + n * a[i]
        elif x - a[i] > 10**5:
            continue
        else:
            cnt += aa[x - a[i]]
            sm += aa_sum[x - a[i]] + aa[x - a[i]] * a[i]
    return cnt, sm

bottom = 0
top = 10**6
while top - bottom > 1:
    mid = (top + bottom) // 2
    cnt, sm = count(mid)
    if cnt < m:
        top = mid
    else:
        bottom = mid
cnt, sm = count(bottom)
ans = sm - (cnt - m) * bottom
print(ans)

+    aa_sum[i] = aa_sum[i] + aa_sum[i + 1]

-    num = n - bisect_right(a, l - a[i] - 1)


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

for n in range(10 ** 5, 0, -1):

    if X >= n * (Y + Z) + Z:

        break

print(n)

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

print(((X - Z) // (Y + Z)))

X, Y, Z = list(map(int, input().split()))
for n in range(10**5, 0, -1):
    if X >= n * (Y + Z) + Z:
        break
print(n)


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

if array[0] % array[1] > 0:

    print(((array[0] // array[1] + 1) * array[2]))

else:

    print(((array[0] // array[1]) * array[2]))

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

print((0--n//x*t))

n, x, t = list(map(int, input().split()))
print((0 - -n // x * t))

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

-    print(((array[0] // array[1]) * array[2]))

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


Input:
N = int(input())

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

Q = int(input())

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

def binary_search(target_num, head, tail):

    idx = int((head+tail)/2)

    if target_num == S[idx]:

        return True

    elif target_num < S[idx]:

        if head == idx:

            return False

        return binary_search(target_num, head, idx-1)

    else:

        if tail == idx:

            return False

        return binary_search(target_num, idx+1, tail)

match_count = 0

for target_num in T:

    if binary_search(target_num, 0, len(S)-1):

        match_count += 1

print((str(match_count)))

N = int(input())

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

Q = int(input())

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

def binary_search(target_num, head, tail):

    while head <= tail:

        idx = int((head+tail)/2)

        if target_num == S[idx]:

            return True

        elif target_num < S[idx]:

            tail = idx - 1

        else:

            head = idx + 1

    return False

match_count = 0

for target_num in T:

    if binary_search(target_num, 0, len(S)-1):

        match_count += 1

print((str(match_count)))

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

def binary_search(target_num, head, tail):
    idx = int((head + tail) / 2)
    if target_num == S[idx]:
        return True
    elif target_num < S[idx]:
        if head == idx:
            return False
        return binary_search(target_num, head, idx - 1)
    else:
        if tail == idx:
            return False
        return binary_search(target_num, idx + 1, tail)

match_count = 0
for target_num in T:
    if binary_search(target_num, 0, len(S) - 1):
        match_count += 1
print((str(match_count)))

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

def binary_search(target_num, head, tail):
    while head <= tail:
        idx = int((head + tail) / 2)
        if target_num == S[idx]:
            return True
        elif target_num < S[idx]:
            tail = idx - 1
        else:
            head = idx + 1
    return False

match_count = 0
for target_num in T:
    if binary_search(target_num, 0, len(S) - 1):
        match_count += 1
print((str(match_count)))

-        return binary_search(target_num, head, idx - 1)

-        return binary_search(target_num, idx + 1, tail)


Input:
n=input()

n=int(n)

a=1

for i in range(n):

    a=a*(i+1)

    if a>=pow(10,9)+7:

        a=a%(pow(10,9)+7)

print(a)

n=int(input())

a=1

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

    a*=i

    a %= (10**9+7)

print(a)

n = input()
n = int(n)
a = 1
for i in range(n):
    a = a * (i + 1)
    if a >= pow(10, 9) + 7:
        a = a % (pow(10, 9) + 7)
print(a)

n = int(input())
a = 1
for i in range(1, n + 1):
    a *= i
    a %= 10**9 + 7
print(a)


Input:
import sys

r = []

n = int(input())

l = sys.stdin.readlines()

for i in l:

  x, y, z = sorted([x*x for x in list(map(int, i.split()))])

  if x + y == z:

      print("YES")

  else:

      print("NO")

import sys

n = int(input())

l = sys.stdin.readlines()

s = ""

for i in l:

  x, y, z = sorted(map(lambda x:x*x,map(int, i.split())))

  if x + y == z:

      s += "YES\n"

  else:

      s += "NO\n"

print(s,end="")

import sys

r = []
n = int(input())
l = sys.stdin.readlines()
for i in l:
    x, y, z = sorted([x * x for x in list(map(int, i.split()))])
    if x + y == z:
        print("YES")
    else:
        print("NO")

import sys

n = int(input())
l = sys.stdin.readlines()
s = ""
for i in l:
    x, y, z = sorted(map(lambda x: x * x, map(int, i.split())))
    if x + y == z:
        s += "YES\n"
    else:
        s += "NO\n"
print(s, end="")

-    x, y, z = sorted([x * x for x in list(map(int, i.split()))])

+    x, y, z = sorted(map(lambda x: x * x, map(int, i.split())))


Input:
import re

ptn = re.compile(r"(A|C|G|T)*")

S = input()

ans = 0

for i in range(len(S)):

  for j in range(len(S)):

    x = ptn.match(S[i:i+j+1]).group(0)

    if(x):

      ans = max(ans, len(x))

print(ans)

import sys

stdin = sys.stdin

ns = lambda : stdin.readline().rstrip()

ni = lambda : int(ns())

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

sys.setrecursionlimit(10 ** 7)

def check(In):

    return In != "A" and In != "C" and In != "G" and In != "T"

def main():

    s = ns()

    count = 0

    ans = 0

    for i in range(len(s)):

        if check(s[i]):

            count = 0

        else:

            count += 1

            ans = max(ans, count)

    print(ans)

if __name__ == '__main__':

    main()

import re

ptn = re.compile(r"(A|C|G|T)*")
S = input()
ans = 0
for i in range(len(S)):
    for j in range(len(S)):
        x = ptn.match(S[i : i + j + 1]).group(0)
        if x:
            ans = max(ans, len(x))
print(ans)

import sys

stdin = sys.stdin
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
sys.setrecursionlimit(10**7)

def check(In):
    return In != "A" and In != "C" and In != "G" and In != "T"

def main():
    s = ns()
    count = 0
    ans = 0
    for i in range(len(s)):
        if check(s[i]):
            count = 0
        else:
            count += 1
            ans = max(ans, count)
    print(ans)

if __name__ == "__main__":
    main()

-        x = ptn.match(S[i : i + j + 1]).group(0)

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

+    return In != "A" and In != "C" and In != "G" and In != "T"


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

ab = c * 2

res = float("inf")

if a + b <= ab:

    res = x * a + y * b

else:

    if x == y:

        res = x * ab

    elif x > y:

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

            cost = i * ab + (x - i) * a

            res = min(res, cost)

    else:

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

            cost = i * ab + (y - i) * b

            res = min(res, cost)

print(res)

import sys

sys.setrecursionlimit(10 ** 7)

input = sys.stdin.readline

f_inf = float('inf')

mod = 10 ** 9 + 7

def resolve():

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

    c *= 2

    if a + b > c:

        cost1 = max(x, y) * c

        cost2 = min(x, y) * c

        plus = ((y - x) * b) if x < y else (x - y) * a

        res = min(cost1, cost2 + plus)

    else:

        res = x * a + y * b

    print(res)

if __name__ == '__main__':

    resolve()

import sys

sys.setrecursionlimit(10**7)
input = sys.stdin.readline
f_inf = float("inf")
mod = 10**9 + 7

def resolve():
    a, b, c, x, y = list(map(int, input().split()))
    c *= 2
    if a + b > c:
        cost1 = max(x, y) * c
        cost2 = min(x, y) * c
        plus = ((y - x) * b) if x < y else (x - y) * a
        res = min(cost1, cost2 + plus)
    else:
        res = x * a + y * b
    print(res)

if __name__ == "__main__":
    resolve()

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

-            cost = i * ab + (x - i) * a

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

+        plus = ((y - x) * b) if x < y else (x - y) * a

-            cost = i * ab + (y - i) * b


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

ans=a*x+b*y

for ci in range(max(x,y)+1):

    sumc = 2*ci*c

    sumc += (x-ci)*a if (x-ci)>0 else 0

    sumc += (y-ci)*b if (y-ci)>0 else 0

    ans=min(ans,sumc)

print(ans)

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

ans=a*x+b*y

if x==y:

    ans=min(ans,2*x*c)

elif x>y:

    ans=min(ans,a*(x-y)+2*y*c)

    ans=min(ans,2*x*c)

else:

    ans=min(ans,b*(y-x)+2*x*c)

    ans=min(ans,2*y*c)

print(ans)

a, b, c, x, y = list(map(int, input().split()))
ans = a * x + b * y
for ci in range(max(x, y) + 1):
    sumc = 2 * ci * c
    sumc += (x - ci) * a if (x - ci) > 0 else 0
    sumc += (y - ci) * b if (y - ci) > 0 else 0
    ans = min(ans, sumc)
print(ans)

a, b, c, x, y = list(map(int, input().split()))
ans = a * x + b * y
if x == y:
    ans = min(ans, 2 * x * c)
elif x > y:
    ans = min(ans, a * (x - y) + 2 * y * c)
    ans = min(ans, 2 * x * c)
else:
    ans = min(ans, b * (y - x) + 2 * x * c)
    ans = min(ans, 2 * y * c)
print(ans)

-    sumc += (x - ci) * a if (x - ci) > 0 else 0

-    sumc += (y - ci) * b if (y - ci) > 0 else 0

+    ans = min(ans, a * (x - y) + 2 * y * c)

+    ans = min(ans, b * (y - x) + 2 * x * c)


Input:
a=65280; b=61680; c=52428; d=43690; e=65535

from heapq import heappush, heappop

base = [a, b, c, d, e, 0]

Q = [(1, el) for el in base]

L = {el: 1 for el in base}

H = []

get = L.get

push = H.append

while Q:

    l, p = heappop(Q)

    if L[p] < l: continue

    if l+1 < get(p ^ e, 17):

        L[p ^ e] = l+1

        if l+1 < 16: heappush(Q, (l+1, p ^ e))

    if l+3 < 16:

        for q, r in H:

            if l+r+3 <= 16:

                if l+r+3 < get(p & q, 17):

                    L[p & q] = l+r+3

                    if l+r+3 < 16: heappush(Q, (l+r+3, p & q))

                if l+r+3 < get(p ^ q, 17):

                    L[p ^ q] = l+r+3

                    if l+r+3 < 16: heappush(Q, (l+r+3, p ^ q))

            else: break

    if l < 7: push((p, l))

print(*map(L.__getitem__, eval("e&%s"%",e&".join(open(0).read().replace(*"-~").replace(*"*&").replace(*"1e").split()[:-1]))),sep='\n')

a=65280; b=61680; c=52428; d=43690; e=65535

from heapq import heappush, heappop

Q = [(1, a), (1, b), (1, c), (1, d)]

L = {a: 1, b: 1, c: 1, d: 1, e: 1, e: 1, 0: 1}

H = []

get = L.get

push = H.append

while Q:

    l, p = heappop(Q)

    if L[p] < l: continue

    if l+1 < get(p ^ e, 17):

        L[p ^ e] = l+1

        l < 15 and heappush(Q, (l+1, p ^ e))

    if l < 13:

        li = 13-l; l3 = 3+l

        for q, r in H:

            if r <= li:

                k = p & q

                if r < get(k, 17)-l3:

                    L[k] = l3+r

                    r < li and heappush(Q, (l3+r, k))

                k = p ^ q

                if r < get(k, 17)-l3:

                    L[k] = l3+r

                    r < li and heappush(Q, (l3+r, k))

            else: break

    if l < 7: push((p, l))

print(*map(L.__getitem__, eval("e&"+",e&".join(open(0).read().replace(*"-~").replace(*"*&").replace(*"1e").split()[:-1]))),sep='\n')

a = 65280
b = 61680
c = 52428
d = 43690
e = 65535
from heapq import heappush, heappop

base = [a, b, c, d, e, 0]
Q = [(1, el) for el in base]
L = {el: 1 for el in base}
H = []
get = L.get
push = H.append
while Q:
    l, p = heappop(Q)
    if L[p] < l:
        continue
    if l + 1 < get(p ^ e, 17):
        L[p ^ e] = l + 1
        if l + 1 < 16:
            heappush(Q, (l + 1, p ^ e))
    if l + 3 < 16:
        for q, r in H:
            if l + r + 3 <= 16:
                if l + r + 3 < get(p & q, 17):
                    L[p & q] = l + r + 3
                    if l + r + 3 < 16:
                        heappush(Q, (l + r + 3, p & q))
                if l + r + 3 < get(p ^ q, 17):
                    L[p ^ q] = l + r + 3
                    if l + r + 3 < 16:
                        heappush(Q, (l + r + 3, p ^ q))
            else:
                break
    if l < 7:
        push((p, l))
print(
    *map(
        L.__getitem__,
        eval(
            "e&%s"
            % ",e&".join(
                open(0).read().replace(*"-~").replace(*"*&").replace(*"1e").split()[:-1]
            )
        ),
    ),
    sep="\n"
)

a = 65280
b = 61680
c = 52428
d = 43690
e = 65535
from heapq import heappush, heappop

Q = [(1, a), (1, b), (1, c), (1, d)]
L = {a: 1, b: 1, c: 1, d: 1, e: 1, e: 1, 0: 1}
H = []
get = L.get
push = H.append
while Q:
    l, p = heappop(Q)
    if L[p] < l:
        continue
    if l + 1 < get(p ^ e, 17):
        L[p ^ e] = l + 1
        l < 15 and heappush(Q, (l + 1, p ^ e))
    if l < 13:
        li = 13 - l
        l3 = 3 + l
        for q, r in H:
            if r <= li:
                k = p & q
                if r < get(k, 17) - l3:
                    L[k] = l3 + r
                    r < li and heappush(Q, (l3 + r, k))
                k = p ^ q
                if r < get(k, 17) - l3:
                    L[k] = l3 + r
                    r < li and heappush(Q, (l3 + r, k))
            else:
                break
    if l < 7:
        push((p, l))
print(
    *map(
        L.__getitem__,
        eval(
            "e&"
            + ",e&".join(
                open(0).read().replace(*"-~").replace(*"*&").replace(*"1e").split()[:-1]
            )
        ),
    ),
    sep="\n"
)

-            heappush(Q, (l + 1, p ^ e))

+        l < 15 and heappush(Q, (l + 1, p ^ e))

-                        heappush(Q, (l + r + 3, p & q))

-                        heappush(Q, (l + r + 3, p ^ q))

+                    r < li and heappush(Q, (l3 + r, k))

+                    r < li and heappush(Q, (l3 + r, k))


Input:
def examB():

    N = I(); A = [I() for _ in range(N)]

    ans = 0; cur= 0

    for i in A:

        if i==0:

            ans += cur//2

            cur = 0

        else:

            cur += i

    ans += cur // 2

    print(ans)

    return

import sys,copy,bisect,itertools,heapq,math

from heapq import heappop,heappush,heapify

from collections import Counter,defaultdict,deque

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

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

def LSI(): return list(map(str,sys.stdin.readline().split()))

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

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

mod = 10**9 + 7

inf = float('inf')

if __name__ == '__main__':

    examB()

def examA():

    S = SI()

    if "W" in S and not "E" in S:

        print("No")

    elif "E" in S and not "W" in S:

        print("No")

    elif "N" in S and not "S" in S:

        print("No")

    elif "S" in S and not "N" in S:

        print("No")

    else:

        print("Yes")

    return

def examB():

    N = I()

    A = [I()for _ in range(N)]

    ans = 0

    for i in range(N-1):

        ans += A[i]//2

        if A[i]%2 and A[i+1]>=1:

            ans += 1

            A[i+1] -= 1

    ans += A[N-1]//2

    print(ans)

    return

def examC():

    ans = 0

    print(ans)

    return

def examD():

    N = I()

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

    ans = 0

    print(ans)

    return

def examE():

    ans = 0

    print(ans)

    return

def examF():

    ans = 0

    print(ans)

    return

import sys,bisect,itertools,heapq,math,random

from copy import deepcopy

from heapq import heappop,heappush,heapify

from collections import Counter,defaultdict,deque

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

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

def LSI(): return list(map(str,sys.stdin.readline().split()))

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

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

global mod,mod2,inf,alphabet,_ep

mod = 10**9 + 7

mod2 = 998244353

inf = 10**18

_ep = 10**(-12)

alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**6)

if __name__ == '__main__':

    examB()

"""

"""

def examB():
    N = I()
    A = [I() for _ in range(N)]
    ans = 0
    cur = 0
    for i in A:
        if i == 0:
            ans += cur // 2
            cur = 0
        else:
            cur += i
    ans += cur // 2
    print(ans)
    return

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

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

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

def LSI():
    return list(map(str, sys.stdin.readline().split()))

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

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

mod = 10**9 + 7
inf = float("inf")
if __name__ == "__main__":
    examB()

def examA():
    S = SI()
    if "W" in S and not "E" in S:
        print("No")
    elif "E" in S and not "W" in S:
        print("No")
    elif "N" in S and not "S" in S:
        print("No")
    elif "S" in S and not "N" in S:
        print("No")
    else:
        print("Yes")
    return

def examB():
    N = I()
    A = [I() for _ in range(N)]
    ans = 0
    for i in range(N - 1):
        ans += A[i] // 2
        if A[i] % 2 and A[i + 1] >= 1:
            ans += 1
            A[i + 1] -= 1
    ans += A[N - 1] // 2
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    N = I()
    S = [I() for _ in range(N)]
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

import sys, bisect, itertools, heapq, math, random
from copy import deepcopy
from heapq import heappop, heappush, heapify
from collections import Counter, defaultdict, deque

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

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

def LSI():
    return list(map(str, sys.stdin.readline().split()))

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

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

global mod, mod2, inf, alphabet, _ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10 ** (-12)
alphabet = [chr(ord("a") + i) for i in range(26)]
sys.setrecursionlimit(10**6)
if __name__ == "__main__":
    examB()
"""
"""

-import sys, copy, bisect, itertools, heapq, math

+import sys, bisect, itertools, heapq, math, random

+alphabet = [chr(ord("a") + i) for i in range(26)]


Input:
N = int(input())

L = [ 0 ] * 1000000

L[0] = 2

L[1] = 1

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

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

print((L[N]))


Input:
import sys

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

S=set(map(int,sys.stdin))

a,b=0,1

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

    if i in S:

        a,b=b,0

    else:

        a,b=b,a+b

print((b%(10**9+7)))

import sys

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

bad=set(map(int,sys.stdin))

MOD=10**9+7

a,b=0,1

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

    if i in bad:

        a,b=b,0

        if a==0:

            break

    else:

        a,b=b,(a+b)%MOD

print(b)

import sys

N, M = list(map(int, input().split()))
S = set(map(int, sys.stdin))
a, b = 0, 1
for i in range(1, N + 1):
    if i in S:
        a, b = b, 0
    else:
        a, b = b, a + b
print((b % (10**9 + 7)))

import sys

N, M = list(map(int, input().split()))
bad = set(map(int, sys.stdin))
MOD = 10**9 + 7
a, b = 0, 1
for i in range(1, N + 1):
    if i in bad:
        a, b = b, 0
        if a == 0:
            break
    else:
        a, b = b, (a + b) % MOD
print(b)

-S = set(map(int, sys.stdin))
+bad = set(map(int, sys.stdin))
+MOD = 10**9 + 7
-    if i in S:
+    if i in bad:
+        if a == 0:
+            break
-        a, b = b, a + b
-print((b % (10**9 + 7)))
+        a, b = b, (a + b) % MOD
+print(b)


Input:
import re

while True:

    n = int(input())

    if n == 0:

        break

    l = [0] * (24*60*60+1)

    for _ in range(n):

        h1,m1,s1,h2,m2,s2 = list(map(int, re.split(':| ', input())))

        l[h1*60*60 + m1*60 + s1] += 1

        l[h2*60*60 + m2*60 + s2] -= 1

    r = 0

    for i in range(24*60*60):

        l[i+1] += l[i]

        r = max(r, l[i+1])

    print(r)

while True:

    n = int(input())

    if n == 0:

        break

    l = []

    for _ in range(n):

        hms1, hms2 = input().split()

        l.append((hms1, True))

        l.append((hms2, False))

    l.sort()

    r, t = 0, 0

    for i in range(len(l)):

        if l[i][1]:

            t += 1

        else:

            t -= 1

        r = max(r, t)

    print(r)

-        h1, m1, s1, h2, m2, s2 = list(map(int, re.split(":| ", input())))


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

S = input()

nums = []

now = 1

cnt = 0

for i in range(N):

    if S[i] == str(now):

        cnt += 1

    else:

        nums.append(cnt)

        now = 1 - now

        cnt = 1

if cnt != 0:

    nums.append(cnt)

if len(nums) % 2 == 0:

    nums.append(0)

add = 2 * K + 1

ans = 0

left = 0

right = 0

tmp = 0

for i in range(0, len(nums), 2):

    next_left = i

    next_right = min(i + add, len(nums))

    while next_left > left:

        tmp -= nums[left]

        left += 1

    while next_right > right:

        tmp += nums[right]

        right += 1

    ans = max(ans, tmp)

print(ans)

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

S = input()

nums = []

now = 1

cnt = 0

for i in range(N):

    if S[i] == str(now):

        cnt += 1

    else:

        nums.append(cnt)

        now = 1 - now

        cnt = 1

if cnt != 0:

    nums.append(cnt)

if len(nums) % 2 == 0:

    nums.append(0)

csum = [0] * (len(nums) + 1)

for i in range(len(nums)):

    csum[i + 1] = csum[i] + nums[i]

add = 2 * K + 1

ans = 0

tmp = 0

for i in range(0, len(nums), 2):

    left = i

    right = min(i + add, len(nums))

    tmp = csum[right] - csum[left]

    ans = max(ans, tmp)

print(ans)

-    next_right = min(i + add, len(nums))


Input:
n=int(input())

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

total=[]

for i in range(n):

    if s[i] not in total:

        total.append(s[i])

print(('Three' if len(total)==3 else 'Four'))

input()

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

print(('Three' if len(set(l))==3 else 'Four'))

n = int(input())
s = list(map(str, input().split()))
total = []
for i in range(n):
    if s[i] not in total:
        total.append(s[i])
print(("Three" if len(total) == 3 else "Four"))

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

-print(("Three" if len(total) == 3 else "Four"))

+print(("Three" if len(set(l)) == 3 else "Four"))