Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

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

N = int(input())
INF = float("inf")
adj = [[] for _ in range(N)]

for n in range(N):
    inp = tuple(map(int, input().split()))
    for i in range(inp[1]):
        adj[n] = list(zip(inp[2::2], inp[3::2]))


def dijkstra(adj):
    d = [INF for n in range(N)]
    d[0] = 0
    heap = [[0, 0]]
    while len(heap):
        pcost, p = heappop(heap)
    
        for v, c in adj[p]:
            new_cost = pcost + c
            if new_cost < d[v]:
                d[v] = new_cost
                heappush(heap, [new_cost, v])
    for n in range(N):
        print("{} {}".format(n, d[n]))

dijkstra(adj)

### FIXED CODE ###

# -*- coding: utf-8 -*-
from heapq import heappop, heappush
def inpl(): return list(map(int, input().split()))
INF = float("inf")
N = int(input())
G = []
for _ in range(N):
    I = inpl()
    G.append(zip(*[I[3::2], I[2::2]]))

def dijkstra(G):
    C = [INF]*(N)
    C[0] = 0
    visited = [False] * (N)
    Q = [[0, 0]]

    while Q:
        c, u = heappop(Q)
        if C[u] < c:
            continue
        visited[u] = True
        for d, v in G[u]:
            if visited[v]:
                continue
            e = c + d
            if e < C[v]:
                C[v] = e
                heappush(Q, [e, v])
    return C

for i, c in enumerate(dijkstra(G)):
    print(i, c)
### BUGGY CODE ###

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


arr = []
for i in range(1, n+1):
    arr.append(a.count(i))


for x in arr:
    if k - q + x > 0:
        print("Yes")
    else:
        print("No")


### FIXED CODE ###

from collections import defaultdict
d = defaultdict(int)

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


for _ in range(q):
    d[int(input())] += 1

for x in range(1, n+1):
    if k - q + d[x] > 0:
        print("Yes")
    else:
        print("No")
### BUGGY CODE ###

def main():
    import sys
    input = sys.stdin.readline

    n = int(input())
    l1 = l2 = l3 = 0
    l = [int(i) for i in input().split()]
    for i in l:
        if i == 1:
            l1 += 1
        elif i == 2:
            l2 += 1
        else:
            l3 += 1

    dp = [[[0]*(l3+1) for i in range(l2+l3+1)] for j in range(n+1)]

    for i in range(1,n+1):
        for j in range(min(i,l2+l3)+1):
            for k in range(min(j,l3)+1):
                s = i-j
                t = j-k
                count = n
                if s > 0:
                    count += dp[s-1][t][k]*s     
                if t > 0 :
                    count += dp[s+1][t-1][k]*t
                if k > 0 :
                    count += dp[s][t+1][k-1]*k

                count /= (s+t+k)
                dp[s][t][k] = count

    print(dp[l1][l2][l3])
if __name__ == "__main__":
    main()



### FIXED CODE ###

N=int(input())
A=[int(i) for i in input().split()]
I,J,K=0,0,0
for a in A:
    if a==1:
        I+=1
    if a==2:
        J+=1
    if a==3:
        K+=1
L=I+J+K
M=J+K
dp=[[[0.0]*(K+1) for i in range(M+1)] for i in range(L+1)]
for n in range(1,L+1):#n=i+j+k
    for m in range(min(n,M)+1):#m=j+k
        for k in range(min(m,K)+1):
            j=m-k
            i=n-m
            #print(i,j,k)
            ret=N/(i+j+k)
            if i>0:
                ret+=dp[i-1][j][k]*(i/(i+j+k))
            if j>0:
                ret+=dp[i+1][j-1][k]*(j/(i+j+k))
            if k>0:
                ret+=dp[i][j+1][k-1]*(k/(i+j+k))
            dp[i][j][k]=ret
print(dp[I][J][K])
### BUGGY CODE ###


n = input()
a = list(input().split(' '))
# print(n, a)
def doit(a):
  m = 1
  for ai in a:
    # print(ai)
    m = m*int(ai)

  if m > 1000000000000000000:
    return -1
  return m
 
print(doit(a))

### FIXED CODE ###


n = int(input())
a = list(input().split(' '))
# print(n, a)
def doit(n,a):
  m = 1
  for i in range(n):
    m = m*int(a[i])
    if m > 1000000000000000000:
        for y in range(i+1, n):
            if a[y] == '0':
                return 0
        return -1
    elif m==0:
        return 0

#   if m > 1000000000000000000:
#     return -1
  return m
 
print(doit(n,a))
### BUGGY CODE ###

def main():
    N = int(input())
    A = [int(i) for i in input().split()]
    B = [int(i) for i in input().split()]
    C = [int(i) for i in input().split()]
    A.sort()
    B.sort()
    C.sort()

    ans = 0
    left = 0
    for a in A:
        right = left
        while left < N and a >= B[left]:
            left += 1
        for b in B[left:]:
            while right < N and b >= C[right]:
                right += 1
            ans += N-right
    print(ans)


if __name__ == '__main__':
    main()


### FIXED CODE ###

def main():
    N = int(input())
    A = [int(i) for i in input().split()]
    B = [int(i) for i in input().split()]
    C = [int(i) for i in input().split()]
    A.sort()
    B.sort()
    C.sort()

    def is_ok1(mid, S, K):
        if K <= S[mid]:
            return True
        else:
            return False

    def is_ok2(mid, S, K):
        if K < S[mid]:
            return True
        else:
            return False

    def binary_search_meguru(S, K, is_ok):
        left = -1
        right = N
        while right - left > 1:
            mid = left + ((right - left) // 2)
            if is_ok(mid, S, K):
                right = mid
            else:
                left = mid
        return right

    ans = 0
    for b in B:
        a = binary_search_meguru(A, b, is_ok1)
        c = binary_search_meguru(C, b, is_ok2)
        ans += a * (N-c)
    print(ans)


if __name__ == '__main__':
    main()
### BUGGY CODE ###

import sys
x = int(input())


number = int(x/100)
xn = x-number*100
number = number+1

for i in range(0,number):
    for j in range(0,number-i):
        for k in  range (0,number-i-j):
            for l in range(0,number-i-j-k):
                for m in range(0,number-i-j-k-l):
                    for n in range(0,number-i-j-k-l-m):
                        if j*1+k*2+l*3+m*4+n*5==xn:
                            if i*100+j*101+k*102+l*103+m*104+n*105==x:
                                print(1)
                                sys.exit()
print(0)

### FIXED CODE ###

import sys
x = int(input())


number = int(x/100)
number = number+1

for i in range(0,number):
    for j in range(0,number-i):
        for k in  range (0,number-i-j):
            for l in range(0,number-i-j-k):
                for m in range(0,number-i-j-k-l):
                    for n in range(0,number-i-j-k-l-m):
                        if i*100+j*101+k*102+l*103+m*104+n*105==x:
                            print(1)
                            sys.exit()
print(0)
### BUGGY CODE ###

import sys

sys.setrecursionlimit(4100000)

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

already_reach = [-1]*(N+1)
graph = [[] for _ in range(N+1)]
for _ in range(M):
    u,v = map(int,input().split(' '))
    graph[u].append(v)
S,T = map(int,input().split(' '))

def search(S_list,current_count=0):
    next_list = []
    for s in S_list:
        for i1 in graph[s]:
            for i2 in graph[i1]:
                for i3 in graph[i2]:
                    if already_reach[i3] == -1: #はじめての到達
                        already_reach[i3] = current_count+1
                        next_list.append(i3)
    if len(next_list) > 0:
        search(next_list,current_count+1)
search([S])
print(already_reach[T])


### FIXED CODE ###

import sys

sys.setrecursionlimit(4100000)

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

already_reach = [-1]*(N+1)
already_reach_1st = [-1]*(N+1)
already_reach_2nd = [-1]*(N+1)
graph = [[] for _ in range(N+1)]
for _ in range(M):
    u,v = map(int,input().split(' '))
    graph[u].append(v)
S,T = map(int,input().split(' '))

next_list = []
def search(S_list,current_count=0):
    next_list = []
    for s in S_list:
        for i1 in graph[s]:
            #print(already_reach_1st)
            if already_reach_1st[i1] != -1:
                continue
            already_reach_1st[i1] = 0
            for i2 in graph[i1]:
                #print(already_reach_2nd)
                if already_reach_2nd[i2] != -1:
                    continue
                already_reach_2nd[i2] = 0
                for i3 in graph[i2]:
                    if already_reach[i3] == -1: #はじめての到達
                        already_reach[i3] = current_count+1
                        next_list.append(i3)
    if len(next_list) > 0:
        search(next_list,current_count+1)
search([S])
print(already_reach[T])
### BUGGY CODE ###

# -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 18:23:54 2018
ITP22C
@author: maezawa
"""

from collections import deque

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

for i in range(q):
    c = list(map(int, input().split()))
    if c[0] == 0:
        if a[c[1]]:
            if a[c[1]][-1] < c[2]:
                a[c[1]].append(c[2])
            elif a[c[1]][0] > c[2]:
                a[c[1]].appendleft(c[2])
            else:
                left = 0
                right = len(a[c[1]])-1
                while right - left > 1:
                    mid = (right + left)//2
                    if a[c[1]][mid] < c[2]:
                        left = mid
                    else:
                        right = mid
                a[c[1]].insert(right, c[2])
        else:
            a[c[1]].append(c[2])
    elif c[0] == 1:
        if a[c[1]]:
            print(a[c[1]][-1])
    else:
        if a[c[1]]:
            a[c[1]].pop()




### FIXED CODE ###

import heapq

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

for i in range(q):
    c = list(map(int, input().split()))
    if c[0] == 0:
        heapq.heappush(a[c[1]],-c[2])
    elif c[0] == 1:
        if a[c[1]]:
            print(-a[c[1]][0])
    else:
        if a[c[1]]:
            heapq.heappop(a[c[1]])
### BUGGY CODE ###

import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


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


def dfs(vec):
    i = 0
    zero_only = True
    for j in range(len(vec)):
        if vec[j] > 0:
            zero_only = False
            i += 1
            if vec[j] == i:
                vec[j] = 0
                ret = dfs(vec)
                vec[j] = i
                if ret != False:
                    ret.append(i)
                    return ret
    if zero_only:
        return []
    else:
        return False


ans = dfs(B)
if ans == False:
    print(-1)
else:
    print(*ans, sep='\n')


### FIXED CODE ###

import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


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


def main():
    ans = []
    while B:
        found = False
        for i in range(len(B), 0, -1):
            if i == B[i - 1]:
                ans.append(i)
                del B[i - 1]
                found = True
                break
        if not found:
            print(-1)
            return
    print(*reversed(ans), sep='\n')


if __name__ == '__main__':
    main()
### BUGGY CODE ###

N = int(input())
S = list(input())

import numpy as np

r = (np.array(S) == "R").sum()
g = (np.array(S) == "G").sum()
b = (np.array(S) == "B").sum()

cnt = 0
for i in range(N):
    for j in range(i+1, N):
        k = j + j - i
        if 0 <= k < N:
            if S[i] != S[j] and S[j] != S[k] and S[k] != S[i]:
                cnt += 1

print(r*g*b - cnt)

### FIXED CODE ###

N = int(input())
S = input()

r = S.count("R")
g = S.count("G")
b = S.count("B")

cnt = 0
for i in range(N):
    for j in range(i+1, N):
        k = j + j - i
        if 0 <= k < N:
            if S[i] != S[j] and S[j] != S[k] and S[k] != S[i]:
                cnt += 1

print(r*g*b - cnt)
### BUGGY CODE ###

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

xmax=max(max(x),a)
    
nx=n*xmax
dp=[[[0]*(nx+1) for ii in range(n+1)] for i in range(n+1)]

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

for j in range(1,n+1):
    jj=j-1
    for k in range(n+1):
        for s in range(nx+1):
            if s<x[jj]:
                dp[j][k][s]=dp[j-1][k][s]
            elif 1<=k and  x[jj]<=s:
                dp[j][k][s]=dp[j-1][k][s]+dp[j-1][k-1][s-x[jj]]
            else:
                dp[j][k][s]=0
#            if dp[j][k][s]!=0:
#                print(j,k,s,dp[j][k][s])
dpsum=0
for k in range(1,n+1):
    dpsum=dpsum+dp[n][k][k*a]
                
print(dpsum)
        


### FIXED CODE ###

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

for i in range(n):
    x[i]=x[i]-a
    
nx=n*n
dp=[[0]*(2*nx+1) for i in range(n+1)]

#print(dp)

dp[0][nx]=1

for j in range(1,n+1):
    jj=j-1
    for t in range(2*nx+1):
        if t-x[jj]<0 or 2*nx<t-x[jj]:
            dp[j][t]=dp[j-1][t]
        elif 0<t-x[jj] and  t-x[jj]<2*nx:
            dp[j][t]=dp[j-1][t]+dp[j-1][t-x[jj]]
        else:
            dp[j][t]=0

print(dp[n][nx]-1)
### BUGGY CODE ###

def roooot(arr, i):
    tmp = i
    while len(arr[i]) != 1:
        i = list(arr[i])[0]-1
        arr[tmp].add(i+1)

def pt(st):
    ret = 0
    for i in list(st):
        ret += cnt[i-1]
    print(ret, end=" ")

n, q = map(int, input().split())
cnt = [0]*n
root = [set([i+1]) for i in range(n)]

for i in range(n-1):
    a, b = map(int, input().split())
    root[b-1].add(a)
    roooot(root, b-1)

for i in range(q):
    p, x = map(int, input().split())
    cnt[p-1] += x

for i in root: pt(list(i))
print("")

### FIXED CODE ###

from sys import stdin
n, q = map(int, input().split())
cnt = [0]*n
root = [[] for i in range(n)]

for i in range(n-1):
    a, b = map(int, stdin.readline().split())
    root[a-1].append(b-1)

for i in range(q):
    p, x = map(int, stdin.readline().split())
    cnt[p-1] += x

tmparr = [0]
while tmparr:
    tmpi = tmparr.pop()
    for i in root[tmpi]:
        cnt[i] += cnt[tmpi]
    tmparr += root[tmpi]
print(*cnt)
### BUGGY CODE ###

n = int(input())
s = [input() for i in range(n)]

chofuku = []
count = 0
for shohin in s:
	if shohin not in chofuku:
		count += 1
		chofuku.append(shohin)
print(count)

### FIXED CODE ###

n = int(input())
s = [input() for i in range(n)]
print(len(set(s)))
### BUGGY CODE ###

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


def gcd(a, b):
    if a < b:
        return gcd(b, a)
    else:
        return a if b == 0 else gcd(b, a % b)


def lcm(a, b):
    return a * b // gcd(b, a%b)


L = lcm(N, M)

r = ["*" for i in range(L)]
s = 0
t = 0
f = False

s_step = L // N
t_step = L // M
j = 0
m = 0

for i in range(L):
    if i == 0:
        if S[0] == T[0]:
            r[i] = S[i]
            j += 1
            m += 1
            continue
        else:
            f = True
            break

    if i % s_step == 0 and j < N:
        if r[i] == "*":
            r[i] = S[j]
            j += 1
        else:
            if r[i] != S[j]:
                f = True
                break
            else:
                j += 1

    if i % t_step == 0 and m < M:
        if r[i] == "*":
            r[i] = T[m]
            m += 1
        else:
            if r[i] != T[m]:
                f = True
                break
            else:
                m += 1

if f:
    print(-1)
else:
    print(L)


### FIXED CODE ###

N, M = map(int, input().split())
S = input()
T = input()
# def gcd(a, b):
#     if a < b:
#         return gcd(b, a)
#     else:
#         return a if b == 0 else gcd(b, a % b)

import fractions
def lcm(a, b):
    return a * b // fractions.gcd(b, a % b)


L = lcm(N, M)

f = False

s_step = L // N
t_step = L // M
sL = lcm(s_step, t_step)
s = 0
t = 0

for i in range(0, L, sL):
    if i == 0:
        if S[i] == T[i]:
            continue
        else:
            f = True
            break
    else:
        s = i // s_step
        t = i // t_step
        if s > N - 1:
            break
        if t > M - 1:
            break
        if S[s] == T[t]:
            continue
        else:
            f = True
            break

if f:
    print(-1)
else:
    print(L)
### BUGGY CODE ###

import numpy as np
N = int(input())
A = np.array(list(map(int,input().split())))
argmn = np.argmin(A)
mn = A[argmn]
for m in range(mn+1):
  B = np.zeros(len(A))
  B[argmn] = m * 2
  for i in range(len(A)):
    idx = (i + argmn)%len(A)
    B[(idx+1)%len(A)]  += A[idx] * 2  - B[idx]
  B[argmn] -= m * 2
  if (B[argmn]+B[(argmn+1)%len(A)]==(A[argmn]*2)):
    print (" ".join(B.astype(np.int).astype(np.str)))
    exit()

### FIXED CODE ###

N = int(input())
A = list(map(int, input().split()))
sm = sum(A)
x = sm-2*sum(A[1::2])
X = []
X.append(str(x))
for i in range(N-1):
   x = 2*A[i]-x
   X.append(str(x))
print (" ".join(X))
### BUGGY CODE ###

n,m,l=map(int,input().split())
abc=[list(map(int,input().split())) for i in range(m)]
q=int(input())
st=[list(map(int,input().split())) for i in range(q)]
inf=float("inf")
dp=[[inf]*(n+1) for i in range(n+1)]
for i in range(1,n+1):
    dp[i][i]=0
for u in abc:
    a,b,c=u
    dp[a][b]=c
    dp[b][a]=c
for k in range(n+1):
    for i in range(n+1):
        for j in range(n+1):
            dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j])
data=[[inf]*(n+1) for i in range(n+1)]
for i in range(1,n+1):
    for j in range(1,n+1):
        if 0<dp[i][j]<=l:
            data[i][j]=1
        elif dp[i][j]==0:
            data[i][j]=0
for k in range(n+1):
    for i in range(n+1):
        for j in range(n+1):
            data[i][j]=min(data[i][j],data[i][k]+data[k][j])
for u in st:
    s,t=u
    if data[s][t]!=inf:
        print(data[s][t]-1)
    else:
        print(-1)

### FIXED CODE ###

def warshal(d):
    n=len(d)
    for k in range(1,n):
        for i in range(1,n):
            for j in range(1,n):
                d[i][j]=min(d[i][j],d[i][k]+d[k][j])
    return d
n,m,l=map(int,input().split())
abc=[list(map(int,input().split())) for i in range(m)]
q=int(input())
st=[list(map(int,input().split())) for i in range(q)]
inf=float("inf")
dp=[[inf]*(n+1) for i in range(n+1)]
for i in range(1,n+1):
    dp[i][i]=0
for u in abc:
    a,b,c=u
    dp[a][b]=c
    dp[b][a]=c
dp=warshal(dp)
data=[[inf]*(n+1) for i in range(n+1)]
for i in range(1,n+1):
    for j in range(1,n+1):
        if 0<dp[i][j]<=l:
            data[i][j]=1
        elif dp[i][j]==0:
            data[i][j]=0
data=warshal(data)
for u in st:
    s,t=u
    if data[s][t]!=inf:
        print(data[s][t]-1)
    else:
        print(-1)
### BUGGY CODE ###

import sys
input = sys.stdin.readline
from collections import deque
sys.setrecursionlimit(10 ** 7)

N = int(input())
# i-indexed
A = [deque() for _ in range(N+1)]
for i in range(1,N+1):
    for j in input().split():
        A[i].append(int(j))

def is_not_empty():
    for x in A:
        if len(x) != 0:
            return True
    return False

answer = 0
while is_not_empty():
    played = []
    append = played.append
    for i in range(1,N+1):
        if i in played:
            continue
        if len(A[i]) == 0:
            continue
        enemy = A[i].popleft()
        ME = A[enemy].popleft()
        if ME == i and not(enemy in played):
            append(ME)
            append(enemy)
        else:
            A[i].appendleft(enemy)
            A[enemy].appendleft(ME)
    if len(played) == 0:
        print(-1)
        exit()
    answer += 1

print(answer)

### FIXED CODE ###

# O(N)
def is_not_empty(A):
    for x in A:
        if x:
            return True
    return False

def main():
    import sys
    input = sys.stdin.readline
    from collections import deque

    N = int(input())
    # 1-indexed
    A = [deque() for _ in range(N+1)]
    # O(N^2)
    for i in range(1,N+1):
        for j in input().split():
            A[i].append(int(j))

    # 当日の参加者
    today = set()
    # 初日
    for i in range(1,N+1):
        # 既に参加した人はダメ
        if i in today:
            continue
        enemy = A[i].popleft()
        ME = A[enemy].popleft()
        if ME == i and not(enemy in today):
            today.add(ME)
            today.add(enemy)
        else:
            A[i].appendleft(enemy)
            A[enemy].appendleft(ME)
    # 初日に誰も試合できなかったとき
    if not today:
        print(-1)
        exit()

    # 前日の参加者
    yesterday = today
    # 日数
    answer = 1
    while is_not_empty(A):
        today = set()
        # 前日に試合した人は必ず次の日に試合する
        for i in yesterday:
            if not A[i]:
                continue
            if i in today:
                continue
            enemy = A[i].popleft()
            ME = A[enemy].popleft()
            if ME == i and not(enemy in today):
                today.add(ME)
                today.add(enemy)
            else:
                A[i].appendleft(enemy)
                A[enemy].appendleft(ME)
        if not today:
            print(-1)
            exit()
        answer += 1
        yesterday = today

    print(answer)

if __name__ == '__main__':
    main()
### BUGGY CODE ###

n=int(input())
a=[int(x) for x in input().split()]
ans =[]
mm=1
for i in range(n):
  ans.append(a.index(mm)+1)
  mm+=1
print(*ans)

### FIXED CODE ###

n=int(input())
a=[int(x) for x in input().split()]
vl =[]
tmp =[]
ans=[0]*n
for i,value in enumerate(a):
  tmp.append(i)
  vl.append(value)
for i in range(n):
  ans[vl[i]-1]=tmp[i]+1
print(*ans)
### BUGGY CODE ###

from heapq import heappush, heappop
from math import isinf


class Edge(object):

    def __init__(self, src, dst, cost):
        self.src = src
        self.dst = dst
        self.cost = cost


class Dijkstra(object):

    def __init__(self, v_len, edges, start, directed=False):
        """
        ダイクストラ法で最短経路を求める。

        :param v_len: グラフのノード数 通常は|V|、1-indexedなグラフなら |V| + 1
        :param edges: グラフの構造
        :param start: 始点 単一視点最短経路問題として解くので必要
        :param directed: 有向グラフの場合True 隣接行列を対称行列にするかが変わる
        """

        # 隣接行列 (adjacency matrix)
        # adj[i][j] でi番目の頂点からj番目の頂点へのコストを示す パスがなければINF
        self._adj = [[float('inf') for _ in range(v_len)] for _ in range(v_len)]
        for e in edges:
            self._adj[e.src][e.dst] = e.cost
            if not directed:
                self._adj[e.dst][e.src] = e.cost
        self._dist = [float('inf') for i in range(v_len)]  # 始点から各頂点までの最短距離
        self._prev = [float('inf') for i in range(v_len)]  # 最短経路における，その頂点の前の頂点のIDを格納する

        self._solve(start)

    def _solve(self, start):
        # 「最短距離が確定した頂点」に隣接する点からBFSするにあたり、それをどう探すかが問題になる
        # 安直に実装すればここで O(|V|) かかってしまうが、優先度キューを使えば O(log|V|) になる
        self._dist[start] = 0
        q = list()
        heappush(q, (0, start))  # キューの要素は (始点から頂点v_iへの仮の距離, v_iのID)

        while len(q) != 0:
            c, src = heappop(q)
            if self._dist[src] < c:
                continue

            # 隣接行列から隣接するノードを全て調べる = BFS
            for dst in range(len(self._adj)):
                cost = self._adj[src][dst]
                if isinf(cost):
                    continue
                if self._dist[src] + cost < self._dist[dst]:
                    self._dist[dst] = self._dist[src] + cost
                    heappush(q, (self._dist[dst], dst))
                    self._prev[dst] = src

    def distance(self, goal):
        return self._dist[goal]

    def path(self, goal):
        path = list()
        path.append(goal)
        cursor = goal

        while not isinf(self._prev[cursor]):
            path.append(self._prev[cursor])
            cursor = self._prev[cursor]

        return list(reversed(path))


N = int(input())
edges = list()
for _ in range(N - 1):
    a, b, c = map(int, input().split())
    edges.append(Edge(a, b, c))

Q, K = map(int, input().split())
dijkstra = Dijkstra(N + 1, edges, K)
for x, y in [tuple(map(int, input().split())) for _ in range(Q)]:
    print(dijkstra.distance(x) + dijkstra.distance(y))


### FIXED CODE ###

N = int(input())
nl = [list() for _ in range(N + 1)]
for _ in range(N - 1):
    a, b, c = map(int, input().split())
    nl[a].append((b, c))
    nl[b].append((a, c))
Q, K = map(int, input().split())

ans = [-1 for _ in range(N + 1)]
stack = [(K, -1, 0)]  # v, p, c
while len(stack) > 0:
    v, p, c = stack.pop()
    ans[v] = c
    for next_v, next_c in nl[v]:
        if next_v == p:
            continue
        stack.append((next_v, v, c + next_c))
for x, y in [tuple(map(int, input().split())) for _ in range(Q)]:
    print(ans[x] + ans[y])