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

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

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

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

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

a.sort(reverse=True)

b.sort(reverse=True)

c.sort(reverse=True)

abc = []

for i, _a in enumerate(a):

    for j, _b in enumerate(b):

        if (i+1) * (j+1) > k:

            break

        for l, _c in enumerate(c):

            if (i+1) * (j+1) * (l+1) > k:

                break

            abc.append(_a + _b + _c)

abc.sort(reverse=True)

for x in abc[:k]:

    print(x)

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

import heapq

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

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

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

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

la, lb, lc = len(a), len(b), len(c)

a.sort(reverse=True)

b.sort(reverse=True)

c.sort(reverse=True)

fix = set()

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

for _ in range(k):

    abc, i, j, l = heapq.heappop(q)

    print((-abc))

    if i+1 < la and (i+1, j, l) not in fix:

        heapq.heappush(q, (-(a[i+1]+b[j]+c[l]), i+1, j, l))

        fix.add((i+1, j, l))

    if j+1 < lb and (i, j+1, l) not in fix:

        heapq.heappush(q, (-(a[i]+b[j+1]+c[l]), i, j+1, l))

        fix.add((i, j+1, l))

    if l+1 < lc and (i, j, l+1) not in fix:

        heapq.heappush(q, (-(a[i]+b[j]+c[l+1]), i, j, l+1))

        fix.add((i, j, l+1))

# -*- coding: utf-8 -*-
x, y, z, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)
abc = []
for i, _a in enumerate(a):
    for j, _b in enumerate(b):
        if (i + 1) * (j + 1) > k:
            break
        for l, _c in enumerate(c):
            if (i + 1) * (j + 1) * (l + 1) > k:
                break
            abc.append(_a + _b + _c)
abc.sort(reverse=True)
for x in abc[:k]:
    print(x)

# -*- coding: utf-8 -*-
import heapq

x, y, z, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
la, lb, lc = len(a), len(b), len(c)
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)
fix = set()
q = [(-(a[0] + b[0] + c[0]), 0, 0, 0)]
for _ in range(k):
    abc, i, j, l = heapq.heappop(q)
    print((-abc))
    if i + 1 < la and (i + 1, j, l) not in fix:
        heapq.heappush(q, (-(a[i + 1] + b[j] + c[l]), i + 1, j, l))
        fix.add((i + 1, j, l))
    if j + 1 < lb and (i, j + 1, l) not in fix:
        heapq.heappush(q, (-(a[i] + b[j + 1] + c[l]), i, j + 1, l))
        fix.add((i, j + 1, l))
    if l + 1 < lc and (i, j, l + 1) not in fix:
        heapq.heappush(q, (-(a[i] + b[j] + c[l + 1]), i, j, l + 1))
        fix.add((i, j, l + 1))

+    if i + 1 < la and (i + 1, j, l) not in fix:

+    if j + 1 < lb and (i, j + 1, l) not in fix:

+    if l + 1 < lc and (i, j, l + 1) not in fix:


Input:
def main():

    from itertools import permutations

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

    to = x[:r]

    dis = [[float("Inf")] * (n + 1) for _ in range(n + 1)]

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

        dis[i][i] = 0

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

        dis[a][b] = c

        dis[b][a] = c

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

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

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

                dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j])

    ans = float("Inf")

    for p in permutations(to):

        tmp = 0

        nw = p[0]

        for nx in p[1:]:

            tmp += dis[nw][nx]

            nw = nx

        ans = min(ans, tmp)

    print(ans)

if __name__ == '__main__':

    main()

def main():

    from itertools import permutations

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

    to = x[:r]

    dis = [[10 ** 8] * (n + 1) for _ in range(n + 1)]

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

        dis[i][i] = 0

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

        dis[a][b] = c

        dis[b][a] = c

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

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

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

                dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j])

    ans = 10 ** 8

    for p in permutations(to):

        tmp = 0

        nw = p[0]

        for nx in p[1:]:

            tmp += dis[nw][nx]

            nw = nx

        ans = min(ans, tmp)

    print(ans)

if __name__ == '__main__':

    main()

def main():
    from itertools import permutations

    n, m, r, *x = list(map(int, open(0).read().split()))
    to = x[:r]
    dis = [[float("Inf")] * (n + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        dis[i][i] = 0
    for a, b, c in zip(*[iter(x[r:])] * 3):
        dis[a][b] = c
        dis[b][a] = c
    for k in range(1, n + 1):
        for i in range(1, n + 1):
            for j in range(1, n + 1):
                dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j])
    ans = float("Inf")
    for p in permutations(to):
        tmp = 0
        nw = p[0]
        for nx in p[1:]:
            tmp += dis[nw][nx]
            nw = nx
        ans = min(ans, tmp)
    print(ans)

if __name__ == "__main__":
    main()

def main():
    from itertools import permutations

    n, m, r, *x = list(map(int, open(0).read().split()))
    to = x[:r]
    dis = [[10**8] * (n + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        dis[i][i] = 0
    for a, b, c in zip(*[iter(x[r:])] * 3):
        dis[a][b] = c
        dis[b][a] = c
    for k in range(1, n + 1):
        for i in range(1, n + 1):
            for j in range(1, n + 1):
                dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j])
    ans = 10**8
    for p in permutations(to):
        tmp = 0
        nw = p[0]
        for nx in p[1:]:
            tmp += dis[nw][nx]
            nw = nx
        ans = min(ans, tmp)
    print(ans)

if __name__ == "__main__":
    main()

-    dis = [[float("Inf")] * (n + 1) for _ in range(n + 1)]


Input:
import sys, re

from collections import deque, defaultdict, Counter

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

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

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left

from heapq import heappush, heappop

from functools import reduce, lru_cache

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

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

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

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

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

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10 ** 9 + 7

S = INT()

@lru_cache(maxsize=None)

def rec(x):

    if x == 0: return 1

    ret = 0

    for i in range(x-2):

        ret += rec(i)

        ret %= mod

    return ret

print((rec(S)))

import sys, re

from collections import deque, defaultdict, Counter

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

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

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left

from heapq import heappush, heappop

from functools import reduce, lru_cache

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

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

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

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

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

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10 ** 9 + 7

S = INT()

@lru_cache(maxsize=None)

def rec(x):

    if x == 0: return 1

    ret = 0

    if x >= 3:

        return (rec(x-1)+rec(x-3))%mod

    else:

        return 0

print((rec(S)))

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import (
    accumulate,
    permutations,
    combinations,
    product,
    groupby,
    combinations_with_replacement,
)
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce, lru_cache

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

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

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

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

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

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

@lru_cache(maxsize=None)
def rec(x):
    if x == 0:
        return 1
    ret = 0
    for i in range(x - 2):
        ret += rec(i)
        ret %= mod
    return ret

print((rec(S)))

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import (
    accumulate,
    permutations,
    combinations,
    product,
    groupby,
    combinations_with_replacement,
)
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce, lru_cache

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

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

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

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

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

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

@lru_cache(maxsize=None)
def rec(x):
    if x == 0:
        return 1
    ret = 0
    if x >= 3:
        return (rec(x - 1) + rec(x - 3)) % mod
    else:
        return 0

print((rec(S)))

+        return (rec(x - 1) + rec(x - 3)) % mod


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

anss=0

u-=1

v-=1

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

inf=float('inf')

aoki=[inf]*n

for i in range(n-1):

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

  a-=1

  b-=1

  d[a].append(b)

  d[b].append(a)

Q=d[v]

aoki[v]=0

dis=1

visited={v}

while Q:

  P=[]

  for i in Q:

    visited.add(i)

    for j in d[i]:

      if j not in visited:P.append(j)

    aoki[i]=dis

  dis+=1

  Q=P

Q=d[u]

chokudai=[-1]*n

chokudai[u]=0

dis=1

visited={u}

point=-1

while Q:

  P=[]

  for i in Q:

    visited.add(i)

    for j in d[i]:

      if aoki[j]<=dis+1:

        if aoki[j]==dis+1:anss=1

        if point<0:point=i

        continue

      if j not in visited:P.append(j)

    chokudai[i]=dis

  dis+=1

  Q=P

Q=d[point]

dis=chokudai[point]+1

visited={point}

while Q:

  P=[]

  for i in Q:

    visited.add(i)

    if chokudai[i]==-1:continue

    chokudai[i]=max(dis,chokudai[i])

    for j in d[i]:

      if j not in visited:P.append(j)

  dis+=1

  Q=P

ans=0

for i in range(n):

  if aoki[i]>chokudai[i]:ans=max(ans,chokudai[i])

print((ans+anss))

#print(aoki)

#print(chokudai)

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

u-=1

v-=1

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

for i in range(n-1):

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

  a-=1

  b-=1

  e[a].append(b)

  e[b].append(a)

cho=[u]

cho_dis=[10**7]*n

cho_dis[u]=0

cho_visited={u}

countt=1

while cho:

  CHO=[]

  for i in cho:

    for j in e[i]:

      if j in cho_visited:continue

      cho_visited.add(j)

      CHO.append(j)

      cho_dis[j]=countt

  countt+=1

  cho=CHO

aok=[v]

aok_dis=[10**7]*n

aok_dis[v]=0

aok_visited={v}

countt=1

while aok:

  AOK=[]

  for i in aok:

    for j in e[i]:

      if j in aok_visited:continue

      aok_visited.add(j)

      AOK.append(j)

      aok_dis[j]=countt

  countt+=1

  aok=AOK

ans=0

for i in range(n):

  if cho_dis[i]<aok_dis[i]:ans=max(ans,aok_dis[i]-1)

print(ans)

n, u, v = list(map(int, input().split()))
anss = 0
u -= 1
v -= 1
d = [[] for _ in range(n)]
inf = float("inf")
aoki = [inf] * n
for i in range(n - 1):
    a, b = list(map(int, input().split()))
    a -= 1
    b -= 1
    d[a].append(b)
    d[b].append(a)
Q = d[v]
aoki[v] = 0
dis = 1
visited = {v}
while Q:
    P = []
    for i in Q:
        visited.add(i)
        for j in d[i]:
            if j not in visited:
                P.append(j)
        aoki[i] = dis
    dis += 1
    Q = P
Q = d[u]
chokudai = [-1] * n
chokudai[u] = 0
dis = 1
visited = {u}
point = -1
while Q:
    P = []
    for i in Q:
        visited.add(i)
        for j in d[i]:
            if aoki[j] <= dis + 1:
                if aoki[j] == dis + 1:
                    anss = 1
                if point < 0:
                    point = i
                continue
            if j not in visited:
                P.append(j)
        chokudai[i] = dis
    dis += 1
    Q = P
Q = d[point]
dis = chokudai[point] + 1
visited = {point}
while Q:
    P = []
    for i in Q:
        visited.add(i)
        if chokudai[i] == -1:
            continue
        chokudai[i] = max(dis, chokudai[i])
        for j in d[i]:
            if j not in visited:
                P.append(j)
    dis += 1
    Q = P
ans = 0
for i in range(n):
    if aoki[i] > chokudai[i]:
        ans = max(ans, chokudai[i])
print((ans + anss))
# print(aoki)
# print(chokudai)

n, u, v = list(map(int, input().split()))
u -= 1
v -= 1
e = [[] for _ in range(n)]
for i in range(n - 1):
    a, b = list(map(int, input().split()))
    a -= 1
    b -= 1
    e[a].append(b)
    e[b].append(a)
cho = [u]
cho_dis = [10**7] * n
cho_dis[u] = 0
cho_visited = {u}
countt = 1
while cho:
    CHO = []
    for i in cho:
        for j in e[i]:
            if j in cho_visited:
                continue
            cho_visited.add(j)
            CHO.append(j)
            cho_dis[j] = countt
    countt += 1
    cho = CHO
aok = [v]
aok_dis = [10**7] * n
aok_dis[v] = 0
aok_visited = {v}
countt = 1
while aok:
    AOK = []
    for i in aok:
        for j in e[i]:
            if j in aok_visited:
                continue
            aok_visited.add(j)
            AOK.append(j)
            aok_dis[j] = countt
    countt += 1
    aok = AOK
ans = 0
for i in range(n):
    if cho_dis[i] < aok_dis[i]:
        ans = max(ans, aok_dis[i] - 1)
print(ans)

-        chokudai[i] = max(dis, chokudai[i])


Input:
def segfunc(x, y): return max(x, y)

class SegmentTree:

    def __init__(self, arr):

        size = len(arr)

        n = 2 ** (size - 1).bit_length()

        self.n = n

        self.node = [0] * (2*n)

        for i in range(size):

            self.node[i+n-1] = arr[i]

        for i in reversed(list(range(n-2))):

            self.node[i] = segfunc(self.node[2*i+1], self.node[2*i+2])

    def update(self, i, x):

        i += self.n - 1

        self.node[i] = x

        while i > 0:

            i = (i - 1) // 2

            self.node[i] = segfunc(self.node[i * 2 + 1], self.node[i * 2 + 2])

    def update(self, x, val):

        x += (self.n - 1)

        self.node[x] = val

        while x > 0:

            x = (x - 1) // 2

            self.node[x] = segfunc(self.node[2 * x + 1], self.node[2 * x + 2])

    def query(self, a, b):

        res = 0

        l = self.n - 1 + a

        r = self.n - 1 + (b - 1)

        while l <= r:

            if l == r:

                res = segfunc(res, self.node[l])

                break

            if l % 2 == 0:

                res = segfunc(res, self.node[l])

            if r % 2 == 1:

                res = segfunc(res, self.node[r])

            l = l // 2

            r = r // 2 - 1

        return res

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

INF = 0

seg = SegmentTree([0] * 300000)

for i in range(N):

    a = int(input())

    tmp = seg.query(max(a - K, 0), min(a + K, 300000) + 1) + 1

    seg.update(a, tmp)

print((seg.query(0, 300000)))

def segfunc(x, y): return max(x, y)

def update(i, x):

    i += MAX_N-1

    node[i] = x

    while i:

        i = (i-1)//2

        node[i] = segfunc(node[i*2+1], node[i*2+2])

def query(l, r):

    L = l + MAX_N

    R = r + MAX_N

    s = INF

    while L < R:

        if R & 1:

            R -= 1

            s = segfunc(s, node[R - 1])

        if L & 1:

            s = segfunc(s, node[L - 1])

            L += 1

        L >>= 1

        R >>= 1

    return s

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

MAX_N = 2**(300005).bit_length()

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

node = [0] * (2 * MAX_N)

INF = 0

ans = 0

#for i in range(N):

#    update(i, a[i])

for i in a:

    tmp = query(max(i - K, 0), min(300005, i + K) + 1)

    update(i, tmp + 1)

    ans = max(ans, tmp + 1)

print(ans)

def segfunc(x, y):
    return max(x, y)

class SegmentTree:
    def __init__(self, arr):
        size = len(arr)
        n = 2 ** (size - 1).bit_length()
        self.n = n
        self.node = [0] * (2 * n)
        for i in range(size):
            self.node[i + n - 1] = arr[i]
        for i in reversed(list(range(n - 2))):
            self.node[i] = segfunc(self.node[2 * i + 1], self.node[2 * i + 2])

    def update(self, i, x):
        i += self.n - 1
        self.node[i] = x
        while i > 0:
            i = (i - 1) // 2
            self.node[i] = segfunc(self.node[i * 2 + 1], self.node[i * 2 + 2])

    def update(self, x, val):
        x += self.n - 1
        self.node[x] = val
        while x > 0:
            x = (x - 1) // 2
            self.node[x] = segfunc(self.node[2 * x + 1], self.node[2 * x + 2])

    def query(self, a, b):
        res = 0
        l = self.n - 1 + a
        r = self.n - 1 + (b - 1)
        while l <= r:
            if l == r:
                res = segfunc(res, self.node[l])
                break
            if l % 2 == 0:
                res = segfunc(res, self.node[l])
            if r % 2 == 1:
                res = segfunc(res, self.node[r])
            l = l // 2
            r = r // 2 - 1
        return res

N, K = list(map(int, input().split()))
INF = 0
seg = SegmentTree([0] * 300000)
for i in range(N):
    a = int(input())
    tmp = seg.query(max(a - K, 0), min(a + K, 300000) + 1) + 1
    seg.update(a, tmp)
print((seg.query(0, 300000)))

def segfunc(x, y):
    return max(x, y)

def update(i, x):
    i += MAX_N - 1
    node[i] = x
    while i:
        i = (i - 1) // 2
        node[i] = segfunc(node[i * 2 + 1], node[i * 2 + 2])

def query(l, r):
    L = l + MAX_N
    R = r + MAX_N
    s = INF
    while L < R:
        if R & 1:
            R -= 1
            s = segfunc(s, node[R - 1])
        if L & 1:
            s = segfunc(s, node[L - 1])
            L += 1
        L >>= 1
        R >>= 1
    return s

N, K = list(map(int, input().split()))
MAX_N = 2 ** (300005).bit_length()
a = [int(input()) for _ in range(N)]
node = [0] * (2 * MAX_N)
INF = 0
ans = 0
# for i in range(N):
#    update(i, a[i])
for i in a:
    tmp = query(max(i - K, 0), min(300005, i + K) + 1)
    update(i, tmp + 1)
    ans = max(ans, tmp + 1)
print(ans)

-        n = 2 ** (size - 1).bit_length()

-            self.node[i + n - 1] = arr[i]

-        for i in reversed(list(range(n - 2))):

-            self.node[i] = segfunc(self.node[2 * i + 1], self.node[2 * i + 2])

+        node[i] = segfunc(node[i * 2 + 1], node[i * 2 + 2])

-            self.node[i] = segfunc(self.node[i * 2 + 1], self.node[i * 2 + 2])

-            self.node[x] = segfunc(self.node[2 * x + 1], self.node[2 * x + 2])

-                res = segfunc(res, self.node[l])

-                res = segfunc(res, self.node[l])

-                res = segfunc(res, self.node[r])

+            s = segfunc(s, node[R - 1])

+            s = segfunc(s, node[L - 1])


Input:
import sys

sys.setrecursionlimit(10 ** 6)

# input = sys.stdin.readline    ####

int1 = lambda x: int(x) - 1

def II(): return int(input())

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

def MI1(): return list(map(int1, input().split()))

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

def LI1(): return list(map(int1, input().split()))

def LLI(rows_number): return [LI() for _ in range(rows_number)]

def printlist(lst, k='\n'): print((k.join(list(map(str, lst)))))

INF = float('inf')

def solve():

    a, b, c, x, y = MI()

    ans = INF

    for k in range(100001):

        yen = 2 * c * k + max(0, x-k) * a + max(0, y-k) * b

        ans = min(ans, yen)

    print(ans)

if __name__ == '__main__':

    solve()

import sys

sys.setrecursionlimit(10 ** 6)

# input = sys.stdin.readline    ####

int1 = lambda x: int(x) - 1

def II(): return int(input())

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

def MI1(): return list(map(int1, input().split()))

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

def LI1(): return list(map(int1, input().split()))

def LLI(rows_number): return [LI() for _ in range(rows_number)]

def printlist(lst, k='\n'): print((k.join(list(map(str, lst)))))

INF = float('inf')

def solve():

    a, b, c, x, y = MI()

    ans = 0

    if a + b <= 2 * c:

        mn = min(x, y)

        ans = a * mn + b * mn + max(0, x-mn) * min(a, 2*c) + max(0, y-mn) * min(b, 2*c)

    else:

        mn = min(x, y)

        ans = mn * 2 * c + max(0, x-mn) * min(a, 2*c) + max(0, y-mn) * min(b, 2*c)

    print(ans)

if __name__ == '__main__':

    solve()

import sys

sys.setrecursionlimit(10**6)
# input = sys.stdin.readline    ####
int1 = lambda x: int(x) - 1

def II():
    return int(input())

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

def MI1():
    return list(map(int1, input().split()))

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

def LI1():
    return list(map(int1, input().split()))

def LLI(rows_number):
    return [LI() for _ in range(rows_number)]

def printlist(lst, k="\n"):
    print((k.join(list(map(str, lst)))))

INF = float("inf")

def solve():
    a, b, c, x, y = MI()
    ans = INF
    for k in range(100001):
        yen = 2 * c * k + max(0, x - k) * a + max(0, y - k) * b
        ans = min(ans, yen)
    print(ans)

if __name__ == "__main__":
    solve()

import sys

sys.setrecursionlimit(10**6)
# input = sys.stdin.readline    ####
int1 = lambda x: int(x) - 1

def II():
    return int(input())

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

def MI1():
    return list(map(int1, input().split()))

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

def LI1():
    return list(map(int1, input().split()))

def LLI(rows_number):
    return [LI() for _ in range(rows_number)]

def printlist(lst, k="\n"):
    print((k.join(list(map(str, lst)))))

INF = float("inf")

def solve():
    a, b, c, x, y = MI()
    ans = 0
    if a + b <= 2 * c:
        mn = min(x, y)
        ans = (
            a * mn
            + b * mn
            + max(0, x - mn) * min(a, 2 * c)
            + max(0, y - mn) * min(b, 2 * c)
        )
    else:
        mn = min(x, y)
        ans = (
            mn * 2 * c + max(0, x - mn) * min(a, 2 * c) + max(0, y - mn) * min(b, 2 * c)
        )
    print(ans)

if __name__ == "__main__":
    solve()


Input:
#!/usr/bin/env python3

import sys, math, math, itertools

def solve(A: int, B: int, C: int, X: int, Y: int):

    mn = 1e9

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

        mn = min(mn, C*i+A*max(X-i//2, 0)+B*max(Y-i//2, 0))

    print((int(mn)))

    return

# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)

def main():

    def iterate_tokens():

        for line in sys.stdin:

            for word in line.split():

                yield word

    tokens = iterate_tokens()

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

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

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

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

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

    solve(A, B, C, X, Y)

if __name__ == '__main__':

    main()

#!/usr/bin/env python3

import sys

def solve(A: int, B: int, C: int, X: int, Y: int):

    c = 0

    if (A + B < 2 * C):

        c += min(X, Y) * (A + B)

    else:

        c += min(X, Y) * 2 * C

    if X > Y:

        c += (X - Y) * min(A, 2 * C)

    else:

        c += (Y - X) * min(B, 2 * C)

    print(c)

    return

# Generated by 1.1.5 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)

def main():

    def iterate_tokens():

        for line in sys.stdin:

            for word in line.split():

                yield word

    tokens = iterate_tokens()

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

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

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

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

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

    solve(A, B, C, X, Y)

if __name__ == '__main__':

    main()

#!/usr/bin/env python3
import sys, math, math, itertools

def solve(A: int, B: int, C: int, X: int, Y: int):
    mn = 1e9
    for i in range(0, 2 * (max(X, Y) + 1), 2):
        mn = min(mn, C * i + A * max(X - i // 2, 0) + B * max(Y - i // 2, 0))
    print((int(mn)))
    return

# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    X = int(next(tokens))  # type: int
    Y = int(next(tokens))  # type: int
    solve(A, B, C, X, Y)

if __name__ == "__main__":
    main()

#!/usr/bin/env python3
import sys

def solve(A: int, B: int, C: int, X: int, Y: int):
    c = 0
    if A + B < 2 * C:
        c += min(X, Y) * (A + B)
    else:
        c += min(X, Y) * 2 * C
    if X > Y:
        c += (X - Y) * min(A, 2 * C)
    else:
        c += (Y - X) * min(B, 2 * C)
    print(c)
    return

# Generated by 1.1.5 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    X = int(next(tokens))  # type: int
    Y = int(next(tokens))  # type: int
    solve(A, B, C, X, Y)

if __name__ == "__main__":
    main()

-# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)

+# Generated by 1.1.5 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)


Input:
import queue

INF = 123456789

def main():

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

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

    for _ in range(m):

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

        a -= 1

        b -= 1

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

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

    used = set()

    for i in range(n):

        d = [INF for _ in range(n)]

        par = [-1 for _ in range(n)]

        # dijkstra

        que = queue.PriorityQueue()

        d[i] = 0

        que.put((0,i))

        while not que.empty():

            p = que.get()

            v = p[1]

            if d[v] < p[0]:

                continue

            for (to,cost) in G[v]:

                if d[to] > d[v]+cost:

                    d[to] = d[v]+cost

                    par[to] = v

                    que.put((d[to],to))

        for j in range(n):

            if i != j:

                a,b = j,par[j]

                if a>b:

                    a,b = b,a

                used.add((a,b))

    print((m - len(used)))

if __name__ == '__main__':

    main()

INF = 123456789

def main():

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

    d = [ [INF for i in range(n)] for j in range(n) ]

    for i in range(n):

        d[i][i] = 0

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

    b = [0 for _ in range(m)]

    c = [0 for _ in range(m)]

    for i in range(m):

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

        a[i] -= 1

        b[i] -= 1

        d[a[i]][b[i]] = min(d[a[i]][b[i]], c[i])

        d[b[i]][a[i]] = min(d[b[i]][a[i]], c[i])

    # Warshall-Floyd

    for k in range(n):

        for i in range(n):

            for j in range(n):

                d[i][j] = min(d[i][j], d[i][k]+d[k][j])

    ans = 0

    for i in range(m):

        found = 1

        for j in range(n):

            if d[j][a[i]] + c[i] == d[j][b[i]]:

                found = 0

                break

        ans += found

    print(ans)

if __name__ == '__main__':

    main()

import queue

INF = 123456789

def main():
    n, m = list(map(int, input().split()))
    G = [[] for _ in range(n)]
    for _ in range(m):
        a, b, c = list(map(int, input().split()))
        a -= 1
        b -= 1
        G[a].append((b, c))
        G[b].append((a, c))
    used = set()
    for i in range(n):
        d = [INF for _ in range(n)]
        par = [-1 for _ in range(n)]
        # dijkstra
        que = queue.PriorityQueue()
        d[i] = 0
        que.put((0, i))
        while not que.empty():
            p = que.get()
            v = p[1]
            if d[v] < p[0]:
                continue
            for (to, cost) in G[v]:
                if d[to] > d[v] + cost:
                    d[to] = d[v] + cost
                    par[to] = v
                    que.put((d[to], to))
        for j in range(n):
            if i != j:
                a, b = j, par[j]
                if a > b:
                    a, b = b, a
                used.add((a, b))
    print((m - len(used)))

if __name__ == "__main__":
    main()

INF = 123456789

def main():
    n, m = list(map(int, input().split()))
    d = [[INF for i in range(n)] for j in range(n)]
    for i in range(n):
        d[i][i] = 0
    a = [0 for _ in range(m)]
    b = [0 for _ in range(m)]
    c = [0 for _ in range(m)]
    for i in range(m):
        a[i], b[i], c[i] = list(map(int, input().split()))
        a[i] -= 1
        b[i] -= 1
        d[a[i]][b[i]] = min(d[a[i]][b[i]], c[i])
        d[b[i]][a[i]] = min(d[b[i]][a[i]], c[i])
    # Warshall-Floyd
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])
    ans = 0
    for i in range(m):
        found = 1
        for j in range(n):
            if d[j][a[i]] + c[i] == d[j][b[i]]:
                found = 0
                break
        ans += found
    print(ans)

if __name__ == "__main__":
    main()

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

+    d = [[INF for i in range(n)] for j in range(n)]

-                if d[to] > d[v] + cost:

-                    d[to] = d[v] + cost

-                    que.put((d[to], to))

+        a[i], b[i], c[i] = list(map(int, input().split()))


Input:
def kmpTable(w):

    lw = len(w)

    nx = [-1] * (lw + 1)

    j = -1

    for i in range(lw):

        while j >= 0 and w[i] != w[j]:

            j = nx[j]

        j += 1

        nx[i + 1] = j

    return nx

def kmpSearch(s, w):

    ls = len(s)

    start = 0

    w_idx = 0

    ret = []

    nx = kmpTable(w)

    while start + w_idx < ls:

        if s[start + w_idx] == w[w_idx]:

            w_idx += 1

            if w_idx == len(w):

                ret.append(start)

                start = start + w_idx - nx[w_idx]

                w_idx = nx[w_idx]

        else:

            if w_idx == 0:

                start += 1

            else:

                start = start + w_idx - nx[w_idx]

                w_idx = nx[w_idx]

    return ret

T = input()

P = input()

ans = kmpSearch(T, P)

if ans:

    print(("\n".join(map(str, ans))))

def kmpTable(w):

    lw = len(w)

    nx = [-1] * (lw + 1)

    j = -1

    for i in range(lw):

        while j >= 0 and w[i] != w[j]:

            j = nx[j]

        j += 1

        nx[i + 1] = j

    return tuple(nx)

def kmpSearch(s, w):

    ls = len(s)

    start = 0

    w_idx = 0

    ret = []

    nx = kmpTable(w)

    while start + w_idx < ls:

        if s[start + w_idx] == w[w_idx]:

            w_idx += 1

            if w_idx == len(w):

                ret.append(start)

                start = start + w_idx - nx[w_idx]

                w_idx = nx[w_idx]

        else:

            if w_idx == 0:

                start += 1

            else:

                start = start + w_idx - nx[w_idx]

                w_idx = nx[w_idx]

    return ret

T = input()

P = input()

ans = kmpSearch(T, P)

if ans:

    print(("\n".join(map(str, ans))))


Input:
import sys, re

from collections import deque, defaultdict, Counter

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

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

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from heapq import heappush, heappop

from functools import reduce, lru_cache

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

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

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

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

def TUPLE(): return tuple(map(int, input().split()))

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

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10 ** 9 + 7

#mod = 998244353

from decimal import *

#import numpy as np

#decimal.getcontext().prec = 10

X, Y, Z, K = MAP()

A = sorted(LIST(), reverse = True)

B = sorted(LIST(), reverse = True)

C = sorted(LIST(), reverse = True)

AB = []

for i in range(X):

	for j in range(Y):

		AB.append(A[i]+B[j])

AB.sort(reverse = True)

AB = AB[:3000]

ABC = sorted([C[0]+AB[i] for i in range(min(3000, X*Y))], reverse = True)

for j in range(1, Z):

	ABC_tmp = sorted([C[j]+AB[i] for i in range(min(3000, X*Y))])

	ABC += ABC_tmp

	ABC.sort(reverse = True)

	ABC = ABC[:3000]

print(*ABC[:K], sep= "\n")

import sys, re

from collections import deque, defaultdict, Counter

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

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

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from heapq import heappush, heappop

from functools import reduce, lru_cache

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

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

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

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

def TUPLE(): return tuple(map(int, input().split()))

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

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10 ** 9 + 7

#mod = 998244353

from decimal import *

#import numpy as np

#decimal.getcontext().prec = 10

X, Y, Z, K = MAP()

A = sorted(LIST(), reverse = True)

B = sorted(LIST(), reverse = True)

C = sorted(LIST(), reverse = True)

ans = []

for i in range(X):

	for j in range(Y):

		for k in range(Z):

			if (i+1)*(j+1)*(k+1) <= K:

				ans.append(A[i]+B[j]+C[k])

			else:

				break

for a in sorted(ans)[::-1][:K]:

	print(a)

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

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

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

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

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

def TUPLE():
    return tuple(map(int, input().split()))

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

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

# import numpy as np
# decimal.getcontext().prec = 10
X, Y, Z, K = MAP()
A = sorted(LIST(), reverse=True)
B = sorted(LIST(), reverse=True)
C = sorted(LIST(), reverse=True)
AB = []
for i in range(X):
    for j in range(Y):
        AB.append(A[i] + B[j])
AB.sort(reverse=True)
AB = AB[:3000]
ABC = sorted([C[0] + AB[i] for i in range(min(3000, X * Y))], reverse=True)
for j in range(1, Z):
    ABC_tmp = sorted([C[j] + AB[i] for i in range(min(3000, X * Y))])
    ABC += ABC_tmp
    ABC.sort(reverse=True)
    ABC = ABC[:3000]
print(*ABC[:K], sep="\n")

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

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

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

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

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

def TUPLE():
    return tuple(map(int, input().split()))

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

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

# import numpy as np
# decimal.getcontext().prec = 10
X, Y, Z, K = MAP()
A = sorted(LIST(), reverse=True)
B = sorted(LIST(), reverse=True)
C = sorted(LIST(), reverse=True)
ans = []
for i in range(X):
    for j in range(Y):
        for k in range(Z):
            if (i + 1) * (j + 1) * (k + 1) <= K:
                ans.append(A[i] + B[j] + C[k])
            else:
                break
for a in sorted(ans)[::-1][:K]:
    print(a)

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

-    return zip(*(MAP() for _ in range(n)))

+    return list(zip(*(MAP() for _ in range(n))))

-ABC = sorted([C[0] + AB[i] for i in range(min(3000, X * Y))], reverse=True)

-    ABC_tmp = sorted([C[j] + AB[i] for i in range(min(3000, X * Y))])

+                ans.append(A[i] + B[j] + C[k])


Input:
import sys, re

from collections import deque, defaultdict, Counter

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

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

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from math import gcd

from heapq import heappush, heappop

from functools import reduce

from decimal import Decimal

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

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

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

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

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

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10**9 + 7

from decimal import *

N = INT()

xy = []

for i in range(N):

	A = INT()

	xy.append([LIST() for _ in range(A)])

ans = 0

for i in range(1<<N):

	i = list("{:b}".format(i).zfill(N))

	for j in range(N):

		if i[j] == "1":

			for x, y in xy[j]:

				if y != int(i[x-1]):

					break

			else:

				continue

			break

	else:

		tmp = sum([int(x) for x in i])

		ans = max(ans, tmp)

print(ans)

import sys, re

from collections import deque, defaultdict, Counter

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

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

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from math import gcd

from heapq import heappush, heappop

from functools import reduce

from decimal import Decimal

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

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

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

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

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

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10**9 + 7

from decimal import *

N = INT()

xy = []

for i in range(N):

	A = INT()

	xy.append([LIST() for _ in range(A)])

ans = 0

for X in product((0, 1), repeat=N):

	for j in range(N):

		if X[j] == 1:

			for x, y in xy[j]:

				if X[x-1] != y:

					break

			else:

				continue

			break

	else:

		ans = max(ans, sum(X))

print(ans)

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

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

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

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

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

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

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

N = INT()
xy = []
for i in range(N):
    A = INT()
    xy.append([LIST() for _ in range(A)])
ans = 0
for i in range(1 << N):
    i = list("{:b}".format(i).zfill(N))
    for j in range(N):
        if i[j] == "1":
            for x, y in xy[j]:
                if y != int(i[x - 1]):
                    break
            else:
                continue
            break
    else:
        tmp = sum([int(x) for x in i])
        ans = max(ans, tmp)
print(ans)

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

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

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

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

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

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

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

N = INT()
xy = []
for i in range(N):
    A = INT()
    xy.append([LIST() for _ in range(A)])
ans = 0
for X in product((0, 1), repeat=N):
    for j in range(N):
        if X[j] == 1:
            for x, y in xy[j]:
                if X[x - 1] != y:
                    break
            else:
                continue
            break
    else:
        ans = max(ans, sum(X))
print(ans)

-    i = list("{:b}".format(i).zfill(N))


Input:
from collections import deque

from copy import deepcopy, copy

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

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

N = 3

def g(i, j, a):

    t = a // (10 ** j) % 10

    return a - t * (10 ** j) + t * (10 ** i)

def MAIN():

    m = {8:{7, 5}, 7:{8, 6, 4}, 6:{7, 3}, 5:{8, 4, 2}, 4:{7, 5, 3, 1}, 3:{6, 4, 0}, 2:{5, 1}, 1:{4, 2, 0}, 0:{3, 1}}

    MAP = "".join(input().replace(" ", "") for _ in range(N))

    start = 8 - MAP.find("0")

    MAP = int(MAP)

    goal = ('1', '2', '3', '4', '5', '6', '7', '8', '0')

    goal = 123456780

    dp = deque([(0, start, MAP)])

    LOG = {MAP}

    while dp:

        cnt, yx, M = dp.popleft()

        if M == goal:

            print(cnt)

            break

        cnt += 1

        for nyx in m[yx]:

            CM = g(yx, nyx, M)

            if not CM in LOG:

                dp.append((cnt, nyx, CM))

                LOG.add(CM)

MAIN()

from collections import deque

from copy import deepcopy, copy

N = 3

def g(i, j, a):

    if i > j:

        i, j = j, i

    return a[:i] + a[j] + a[i + 1:j] + a[i] + a[j + 1:]

def MAIN():

    m = {8:{7, 5}, 7:{8, 6, 4}, 6:{7, 3}, 5:{8, 4, 2}, 4:{7, 5, 3, 1}, 3:{6, 4, 0}, 2:{5, 1}, 1:{4, 2, 0}, 0:{3, 1}}

    MAP = "".join(input().replace(" ", "") for _ in range(N))

    start = MAP.find("0")

    goal = "123456780"

    dp = deque([(0, start, MAP)])

    LOG = {MAP}

    while dp:

        cnt, yx, M = dp.popleft()

        if M == goal:

            print(cnt)

            break

        cnt += 1

        for nyx in m[yx]:

            CM = g(yx, nyx, M)

            if not CM in LOG:

                dp.append((cnt, nyx, CM))

                LOG.add(CM)

MAIN()

from collections import deque
from copy import deepcopy, copy

N = 3

def g(i, j, a):
    if i > j:
        i, j = j, i
    return a[:i] + a[j] + a[i + 1 : j] + a[i] + a[j + 1 :]

def MAIN():
    m = {
        8: {7, 5},
        7: {8, 6, 4},
        6: {7, 3},
        5: {8, 4, 2},
        4: {7, 5, 3, 1},
        3: {6, 4, 0},
        2: {5, 1},
        1: {4, 2, 0},
        0: {3, 1},
    }
    MAP = "".join(input().replace(" ", "") for _ in range(N))
    start = MAP.find("0")
    goal = "123456780"
    dp = deque([(0, start, MAP)])
    LOG = {MAP}
    while dp:
        cnt, yx, M = dp.popleft()
        if M == goal:
            print(cnt)
            break
        cnt += 1
        for nyx in m[yx]:
            CM = g(yx, nyx, M)
            if not CM in LOG:
                dp.append((cnt, nyx, CM))
                LOG.add(CM)

MAIN()


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

import sys

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

def list2d(a, b, c): return [[c] * b for i in range(a)]

def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]

def ceil(x, y=1): return int(-(-x // y))

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

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

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

def Yes(): print('Yes')

def No(): print('No')

def YES(): print('YES')

def NO(): print('NO')

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

MOD = 10 ** 9 + 7

X,Y,Z,K=MAP()

A=sorted(LIST(), reverse=True)

B=sorted(LIST(), reverse=True)

C=sorted(LIST(), reverse=True)

ABC=[]

for i in range(X):

    for j in range(Y):

        if (i+1)*(j+1)>K:

            break

        for k in range(Z):

            if (i+1)*(j+1)*(k+1)>K:

                break

            ABC.append(A[i]+B[j]+C[k])

ABC.sort(reverse=True)

for i in range(K):

    print((ABC[i]))

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

import sys

from heapq import heappush, heappop

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

def list2d(a, b, c): return [[c] * b for i in range(a)]

def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]

def ceil(x, y=1): return int(-(-x // y))

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

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

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

def Yes(): print('Yes')

def No(): print('No')

def YES(): print('YES')

def NO(): print('NO')

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

MOD = 10 ** 9 + 7

X,Y,Z,K=MAP()

A=sorted(LIST(), reverse=True)

B=sorted(LIST(), reverse=True)

C=sorted(LIST(), reverse=True)

que=[]

heappush(que, (-(A[0]+B[0]+C[0]), 0, 0, 0))

S={(0,0,0)}

for i in range(K):

    ans=heappop(que)

    print((-ans[0]))

    a,b,c=ans[1:]

    if a+1<X and (a+1,b,c) not in S:

        heappush(que, (-(A[a+1]+B[b]+C[c]), a+1, b, c))

        S.add((a+1,b,c))

    if b+1<Y and (a,b+1,c) not in S:

        heappush(que, (-(A[a]+B[b+1]+C[c]), a, b+1, c))

        S.add((a,b+1,c))

    if c+1<Z and (a,b,c+1) not in S:

        heappush(que, (-(A[a]+B[b]+C[c+1]), a, b, c+1))

        S.add((a,b,c+1))

# -*- coding: utf-8 -*-
import sys

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

def list2d(a, b, c):
    return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
    return [[[d] * c for j in range(b)] for i in range(a)]

def ceil(x, y=1):
    return int(-(-x // y))

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

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

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

def Yes():
    print("Yes")

def No():
    print("No")

def YES():
    print("YES")

def NO():
    print("NO")

sys.setrecursionlimit(10**9)
INF = float("inf")
MOD = 10**9 + 7
X, Y, Z, K = MAP()
A = sorted(LIST(), reverse=True)
B = sorted(LIST(), reverse=True)
C = sorted(LIST(), reverse=True)
ABC = []
for i in range(X):
    for j in range(Y):
        if (i + 1) * (j + 1) > K:
            break
        for k in range(Z):
            if (i + 1) * (j + 1) * (k + 1) > K:
                break
            ABC.append(A[i] + B[j] + C[k])
ABC.sort(reverse=True)
for i in range(K):
    print((ABC[i]))

# -*- coding: utf-8 -*-
import sys
from heapq import heappush, heappop

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

def list2d(a, b, c):
    return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
    return [[[d] * c for j in range(b)] for i in range(a)]

def ceil(x, y=1):
    return int(-(-x // y))

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

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

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

def Yes():
    print("Yes")

def No():
    print("No")

def YES():
    print("YES")

def NO():
    print("NO")

sys.setrecursionlimit(10**9)
INF = float("inf")
MOD = 10**9 + 7
X, Y, Z, K = MAP()
A = sorted(LIST(), reverse=True)
B = sorted(LIST(), reverse=True)
C = sorted(LIST(), reverse=True)
que = []
heappush(que, (-(A[0] + B[0] + C[0]), 0, 0, 0))
S = {(0, 0, 0)}
for i in range(K):
    ans = heappop(que)
    print((-ans[0]))
    a, b, c = ans[1:]
    if a + 1 < X and (a + 1, b, c) not in S:
        heappush(que, (-(A[a + 1] + B[b] + C[c]), a + 1, b, c))
        S.add((a + 1, b, c))
    if b + 1 < Y and (a, b + 1, c) not in S:
        heappush(que, (-(A[a] + B[b + 1] + C[c]), a, b + 1, c))
        S.add((a, b + 1, c))
    if c + 1 < Z and (a, b, c + 1) not in S:
        heappush(que, (-(A[a] + B[b] + C[c + 1]), a, b, c + 1))
        S.add((a, b, c + 1))

-            ABC.append(A[i] + B[j] + C[k])

+    if a + 1 < X and (a + 1, b, c) not in S:

+    if b + 1 < Y and (a, b + 1, c) not in S:

+    if c + 1 < Z and (a, b, c + 1) not in S:


Input:
mod = 998244353

N = int(input())

X = []

for _ in range(N):

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

    X.append((x, x + d))

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

L = [(0, -(10**9+1), 10**9+1)]

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

for i, (x, y) in enumerate(X):

    while L[-1][2] <= y:

        if L[-1][2] > x and P[i+1] < 0:

            P[i+1] = L[-1][0]

        L.pop()

    if P[i+1] < 0:

        P[i+1] = L[-1][0]

    L.append((i+1, x, y))

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

for i, p in enumerate(P):

    if p >= 0:

        C[p].append(i)

Y = [1] * (N+1)

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

    s = 1

    for j in C[i]:

        s = s * (Y[j] + 1) % mod

    Y[i] = s

print((Y[0]))

import sys

input = sys.stdin.readline

mod = 998244353

N = int(input())

X = []

for _ in range(N):

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

    X.append((x, x + d))

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

L = [(0, -(10**9+1), 10**9+1)]

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

for i, (x, y) in enumerate(X):

    while L[-1][2] <= y:

        if L[-1][2] > x and P[i+1] < 0:

            P[i+1] = L[-1][0]

        L.pop()

    if P[i+1] < 0:

        P[i+1] = L[-1][0]

    L.append((i+1, x, y))

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

for i, p in enumerate(P):

    if p >= 0:

        C[p].append(i)

Y = [1] * (N+1)

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

    s = 1

    for j in C[i]:

        s = s * (Y[j] + 1) % mod

    Y[i] = s

print((Y[0]))

import sys

input = sys.stdin.readline
mod = 998244353
N = int(input())
X = []
for _ in range(N):
    x, d = list(map(int, input().split()))
    X.append((x, x + d))
X = sorted(X, key=lambda x: x[0])
L = [(0, -(10**9 + 1), 10**9 + 1)]
P = [-1] * (N + 1)
for i, (x, y) in enumerate(X):
    while L[-1][2] <= y:
        if L[-1][2] > x and P[i + 1] < 0:
            P[i + 1] = L[-1][0]
        L.pop()
    if P[i + 1] < 0:
        P[i + 1] = L[-1][0]
    L.append((i + 1, x, y))
C = [[] for _ in range(N + 1)]
for i, p in enumerate(P):
    if p >= 0:
        C[p].append(i)
Y = [1] * (N + 1)
for i in range(N + 1)[::-1]:
    s = 1
    for j in C[i]:
        s = s * (Y[j] + 1) % mod
    Y[i] = s
print((Y[0]))

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


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:
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:
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:
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:
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:
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:
import sys

from collections import Counter, deque, defaultdict

from itertools import accumulate, permutations, combinations, takewhile, compress, cycle

from functools import reduce

from math import ceil, floor, log10, log2, factorial

from pprint import pprint

sys.setrecursionlimit(1000000)

# MOD = 10 ** 9 + 7

# N = int(input())

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

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

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

N, W = [int(x) for x in input().split()]

dp = [float('inf')] * 1000 * 100*10

vs = set()

vs.add(0)

dp[0] = 0

for i in range(N):

    w, v = [int(x) for x in input().split()]

    tmpDP = dp.copy()

    for vv in list(vs):

        if dp[vv + v] > dp[vv] + w:

            tmpDP[vv + v] = dp[vv] + w

            vs.add(vv + v)

    dp = tmpDP

ans = 0

for v in list(vs):

    if dp[v] <= W:

        ans = max(ans, v)

print(ans)

import sys

from collections import Counter, deque, defaultdict

from itertools import accumulate, permutations, combinations, takewhile, compress, cycle

from functools import reduce

from math import ceil, floor, log10, log2, factorial

from pprint import pprint

sys.setrecursionlimit(1000000)

# MOD = 10 ** 9 + 7

# N = int(input())

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

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

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

N, W = [int(x) for x in input().split()]

dp = defaultdict(lambda: float('inf'))

dp[0] = 0

for i in range(N):

    w, v = [int(x) for x in input().split()]

    add = defaultdict(lambda: float('inf'))

    for vv in list(dp.keys()):

        if dp[vv + v] > dp[vv] + w:

            add[vv + v] = dp[vv] + w

    dp.update(add)

print((max([i for i in list(dp.items()) if i[1] <= W], key=lambda x:x[0])[0]))

import sys
from collections import Counter, deque, defaultdict
from itertools import accumulate, permutations, combinations, takewhile, compress, cycle
from functools import reduce
from math import ceil, floor, log10, log2, factorial
from pprint import pprint

sys.setrecursionlimit(1000000)
# MOD = 10 ** 9 + 7
# N = int(input())
# A = [int(x) for x in input().split()]
# V = [[0] * 100 for _ in range(100)]
# A = [int(input()) for _ in range(N)]
N, W = [int(x) for x in input().split()]
dp = [float("inf")] * 1000 * 100 * 10
vs = set()
vs.add(0)
dp[0] = 0
for i in range(N):
    w, v = [int(x) for x in input().split()]
    tmpDP = dp.copy()
    for vv in list(vs):
        if dp[vv + v] > dp[vv] + w:
            tmpDP[vv + v] = dp[vv] + w
            vs.add(vv + v)
    dp = tmpDP
ans = 0
for v in list(vs):
    if dp[v] <= W:
        ans = max(ans, v)
print(ans)

import sys
from collections import Counter, deque, defaultdict
from itertools import accumulate, permutations, combinations, takewhile, compress, cycle
from functools import reduce
from math import ceil, floor, log10, log2, factorial
from pprint import pprint

sys.setrecursionlimit(1000000)
# MOD = 10 ** 9 + 7
# N = int(input())
# A = [int(x) for x in input().split()]
# V = [[0] * 100 for _ in range(100)]
# A = [int(input()) for _ in range(N)]
N, W = [int(x) for x in input().split()]
dp = defaultdict(lambda: float("inf"))
dp[0] = 0
for i in range(N):
    w, v = [int(x) for x in input().split()]
    add = defaultdict(lambda: float("inf"))
    for vv in list(dp.keys()):
        if dp[vv + v] > dp[vv] + w:
            add[vv + v] = dp[vv] + w
    dp.update(add)
print((max([i for i in list(dp.items()) if i[1] <= W], key=lambda x: x[0])[0]))

+    add = defaultdict(lambda: float("inf"))

+print((max([i for i in list(dp.items()) if i[1] <= W], key=lambda x: x[0])[0]))


Input:
def main():

	n, ma, mb, *L = list(map(int, open(0).read().split()))

	M = 1<<30

	dp = [[M] * 420 for _ in range(420)]

	dp[0][0] = 0

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

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

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

				t = dp[i][j] + c

				if dp[i + a][j + b] > t:

					dp[i + a][j + b] = t

	ans = M

	_ma, _mb = ma, mb

	while _ma < 410 > _mb:

		ans = min(ans, dp[_ma][_mb])

		_ma += ma

		_mb += mb

	print((ans if ans < M else -1))

if __name__=="__main__":

	main()

def main():

	n, ma, mb, *L = list(map(int, open(0).read().split()))

	M = 1 << 30

	dp = [[M] * 420 for _ in range(420)]

	dp[0][0] = 0

	ua = ub = 15

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

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

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

				t = dp[i][j] + c

				if dp[i + a][j + b] > t:

					dp[i + a][j + b] = t

					if ua < i + a:

						ua = i + a

					if ub < j + b:

						ub = j + b

	ans = M

	_ma, _mb = ma, mb

	while _ma < 410 > _mb:

		ans = min(ans, dp[_ma][_mb])

		_ma += ma

		_mb += mb

	print((ans if ans < M else -1))

if __name__ == "__main__":

	main()

def main():
    n, ma, mb, *L = list(map(int, open(0).read().split()))
    M = 1 << 30
    dp = [[M] * 420 for _ in range(420)]
    dp[0][0] = 0
    for a, b, c in zip(*[iter(L)] * 3):
        for i in range(400, -1, -1):
            for j in range(400, -1, -1):
                t = dp[i][j] + c
                if dp[i + a][j + b] > t:
                    dp[i + a][j + b] = t
    ans = M
    _ma, _mb = ma, mb
    while _ma < 410 > _mb:
        ans = min(ans, dp[_ma][_mb])
        _ma += ma
        _mb += mb
    print((ans if ans < M else -1))

if __name__ == "__main__":
    main()

+            for j in range(ub, -1, -1):


Input:
import sys

sys.setrecursionlimit(10**6)

def dfs(v,p,d):

    for i, j in tree[v]:

        if i != p:

            depth[i] = d + j

            dfs(i,v,d+j)

N = int(input())

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

for i in range(N-1):

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

    a -= 1

    b -= 1

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

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

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

depth = [0 for i in range(N)]

depth[K-1] = 0

dfs(K-1,-1,0)

for _ in range(Q):

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

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

import heapq

import sys

input = sys.stdin.readline

def dijkstra(s, edge, N):

    d = [float('inf')] * N

    used = [True] * N

    d[s] = 0

    used[s] = False

    edgelist = []

    for a, b in edge[s]:

        heapq.heappush(edgelist, a * (10 ** 6) + b)

    while len(edgelist):

        minedge = heapq.heappop(edgelist)

        if not used[minedge%(10 ** 6)]:

            continue

        v = minedge % (10 ** 6)

        d[v] = minedge // (10 ** 6)

        used[v] = False

        for e in edge[v]:

            if used[e[1]]:

                heapq.heappush(edgelist, (e[0] + d[v]) * (10 ** 6) + e[1])

    return d

def main():

    N = int(input())

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

    for _ in range(N-1):

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

        a -= 1

        b -= 1

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

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

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

    K -= 1

    d = dijkstra(K, edge, N)

    for _ in range(Q):

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

        x -= 1

        y -= 1

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

if __name__ == "__main__":

    main()

import sys

sys.setrecursionlimit(10**6)

def dfs(v, p, d):
    for i, j in tree[v]:
        if i != p:
            depth[i] = d + j
            dfs(i, v, d + j)

N = int(input())
tree = [[] for _ in range(N)]
for i in range(N - 1):
    a, b, c = list(map(int, input().split()))
    a -= 1
    b -= 1
    tree[a].append((b, c))
    tree[b].append((a, c))
Q, K = list(map(int, input().split()))
depth = [0 for i in range(N)]
depth[K - 1] = 0
dfs(K - 1, -1, 0)
for _ in range(Q):
    x, y = list(map(int, input().split()))
    print((depth[x - 1] + depth[y - 1]))

import heapq
import sys

input = sys.stdin.readline

def dijkstra(s, edge, N):
    d = [float("inf")] * N
    used = [True] * N
    d[s] = 0
    used[s] = False
    edgelist = []
    for a, b in edge[s]:
        heapq.heappush(edgelist, a * (10**6) + b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        if not used[minedge % (10**6)]:
            continue
        v = minedge % (10**6)
        d[v] = minedge // (10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist, (e[0] + d[v]) * (10**6) + e[1])
    return d

def main():
    N = int(input())
    edge = [[] for _ in range(N)]
    for _ in range(N - 1):
        a, b, c = list(map(int, input().split()))
        a -= 1
        b -= 1
        edge[a].append([c, b])
        edge[b].append([c, a])
    Q, K = list(map(int, input().split()))
    K -= 1
    d = dijkstra(K, edge, N)
    for _ in range(Q):
        x, y = list(map(int, input().split()))
        x -= 1
        y -= 1
        print((d[x] + d[y]))

if __name__ == "__main__":
    main()

+        heapq.heappush(edgelist, a * (10**6) + b)

+        minedge = heapq.heappop(edgelist)

+        if not used[minedge % (10**6)]:

+                heapq.heappush(edgelist, (e[0] + d[v]) * (10**6) + e[1])

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

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

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

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

+    Q, K = list(map(int, input().split()))

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