CodeEff/ECCO huggingface dataset:
# Original solution
import sys
sys.setrecursionlimit(2147483647)


n=int(eval(input()))

c={}
tree=[[] for _ in range(n)]

for _ in range(n-1):
    i,j,k=list(map(int,input().split()))
    i-=1
    j-=1
    tree[i].append(j)
    tree[j].append(i)
    c[(i,j)]=k
    c[(j,i)]=k

result=[]
q,k=list(map(int,input().split()))

#初期値が0の辞書
from collections import defaultdict
memo = defaultdict(lambda: -1) 

def DEF(z,cnt):
    global memo,tree,c
    memo[z]=cnt
    for item in tree[z]:
        if memo[item]==-1:
            DEF(item,cnt+c[(item,z)])

DEF(k-1,0)
result=[]
for item in range(q):
    a,b=list(map(int,input().split()))
    result.append(memo[a-1]+memo[b-1])

for item in result:
    print(item)







# Optimized solution
import sys
sys.setrecursionlimit(2147483647)


n=int(eval(input()))

c={}
tree=[[] for _ in range(n)]

for _ in range(n-1):
    i,j,k=list(map(int,input().split()))
    i-=1
    j-=1
    tree[i].append(j)
    tree[j].append(i)
    c[(i,j)]=k
    c[(j,i)]=k

result=[]
q,k=list(map(int,input().split()))

memo=[-1]*n

def DEF(z,cnt):
    global memo,tree,c
    memo[z]=cnt
    for item in tree[z]:
        if memo[item]==-1:
            DEF(item,cnt+c[(item,z)])

DEF(k-1,0)
result=[]
for item in range(q):
    a,b=list(map(int,input().split()))
    result.append(memo[a-1]+memo[b-1])

for item in result:
    print(item)
# Original solution
import sys
sys.setrecursionlimit(2147483647)


n=int(eval(input()))

c={}
tree=[[] for _ in range(n)]

for _ in range(n-1):
    i,j,k=list(map(int,input().split()))
    i-=1
    j-=1
    tree[i].append(j)
    tree[j].append(i)
    c[(i,j)]=k
    c[(j,i)]=k

result=[]
q,k=list(map(int,input().split()))

memo=[-1]*n

def DEF(z,cnt):
    global memo,tree,c
    memo[z]=cnt
    for item in tree[z]:
        if memo[item]==-1:
            DEF(item,cnt+c[(item,z)])

DEF(k-1,0)
result=[]
for item in range(q):
    a,b=list(map(int,input().split()))
    result.append(memo[a-1]+memo[b-1])

for item in result:
    print(item)







# Optimized solution
import sys
sys.setrecursionlimit(2147483647)


n=int(eval(input()))

c={}
tree=[set([]) for _ in range(n)]

for _ in range(n-1):
    i,j,k=list(map(int,input().split()))
    i-=1
    j-=1
    tree[i].add(j)
    tree[j].add(i)
    c[(min(i,j),max(i,j))]=k

result=[]
q,k=list(map(int,input().split()))

memo=[-1]*n

def DEF(z,cnt):
    global memo,tree,c
    memo[z]=cnt
    for item in tree[z]:
        if memo[item]==-1:
            DEF(item,cnt+c[(min(item,z),max(item,z))])

DEF(k-1,0)
result=[]
for item in range(q):
    a,b=list(map(int,input().split()))
    result.append(memo[a-1]+memo[b-1])

for item in result:
    print(item)
# Original solution
def dijkstra(s, n, cost):
    d = [float("inf")] * (n+1)
    used = [False] * (n+1)
    d[s] = 0

    while True:
        v = -1
        for i in range(1, n+1):
            if (not used[i]) and (v == -1):
                v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
            break
        used[v] = True
        for j in range(1, n+1):
            d[j] = min(d[j], d[v] + cost[v][j])
    return d


n = int(eval(input()))
inf = float("inf")
cost = [[inf]*(n+1) for _ in range(n+1)]
for _ in range(n-1):
    a, b, c = list(map(int, input().split()))
    cost[a][b] = c
    cost[b][a] = c
q, k = list(map(int, input().split()))
ans = dijkstra(k, n, cost)
for _ in range(q):
    x, y = list(map(int, input().split()))
    print((ans[x] + ans[y]))

# Optimized solution
n = int(eval(input()))
inf = float("inf")
tree = [[] for _ in range(n+1)]
for _ in range(n-1):
    a, b, c = list(map(int, input().split()))
    tree[a].append([b, c])
    tree[b].append([a, c])
q, k = list(map(int, input().split()))

depth = [inf] * (n+1)
visited = [False] * (n+1)
depth[k] = 0
stack = [k]
while stack:
    now = stack.pop()
    visited[now] = True
    for i, v in tree[now]:
        if visited[i]:
            pass
        else:
            stack.append(i)
            depth[i] = min(depth[i], depth[now] + v)
for _ in range(q):
    x, y = list(map(int, input().split()))
    ans = depth[x] + depth[y]
    print(ans)
# Original solution
import sys

 
from collections import defaultdict
import heapq
import sys


        
def dijkstra(startvertex,V,graph):
    distances=[sys.maxsize]*V
    distances[startvertex]=0
    heap=[(0,startvertex)]
    while heap:
        current_distance,current_vertex=heapq.heappop(heap)
        if current_distance>distances[current_vertex]:
            continue
        for neighbor in range(len(graph[current_vertex])):
            if graph[current_vertex][neighbor]>0:
                distance=current_distance+graph[current_vertex][neighbor]
                
                
                if distance<distances[neighbor]:
                    distances[neighbor]=distance
                    heapq.heappush(heap,(distance,neighbor))
                    
    return distances
n=int(eval(input()))   
sys.setrecursionlimit(10**9)
    
graph=[[0 for i in range(n)]for j in range(n)]
for i in range(n-1):
    a=[int(x) for x in input().split()]
    # print(a)
    graph[a[0]-1][a[1]-1]=a[2]
    graph[a[1]-1][a[0]-1]=a[2]

# print(graph)
w=[int(x) for x in input().split()]
m=dijkstra(w[1]-1,n,graph)
# print(m)
c=0
for i in range(w[0]):
    s=[int(x) for x in input().split()]
    # print(s)
    c=abs(m[s[0]-1])+abs(m[s[1]-1])
    print(c)

# Optimized solution
N=int(eval(input()))
import sys
sys.setrecursionlimit(10**6)
T=[[] for _ in range(N)]
for i in range(N-1):
    a,b,c=list(map(int, input().split()))
    T[a-1].append((b-1,c))
    T[b-1].append((a-1,c))

Q,K=list(map(int, input().split()))
D=[-1]*N
D[K-1]=0
def dfs(start, nowd):
    to=T[start]
    for t in to:
        next_node,c=t
        if D[next_node]!=-1:
            continue
        nextd=nowd+c
        D[next_node]=nextd
        dfs(next_node, nextd)
dfs(K-1,0)
# print(D)
for i in range(Q):
    x,y=list(map(int, input().split()))
    print((D[x-1]+D[y-1]))
# Original solution
import sys
from collections import deque

def dfs(start, dest, pre, d):
    if d[start][dest] > 0:
        return d[start][dest]

    for i in range(len(d)):
        if d[start][i] > 0 and i != pre:
            c = dfs(i, dest, start, d)
            if c > 0:
                return d[start][i] + dfs(i, dest, start, d)

    return 0

def main():
    input = sys.stdin.readline
    N = int(eval(input()))
    
    d = [[] for _ in range(N)]
    for _ in range(N-1):
        a, b, c = list(map(int, input().split()))
        a, b = a - 1, b - 1
        
        d[a].append((b, c))
        d[b].append((a, c))

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

    k_dist = [0 for _ in range(N)]
    start = deque()
    start.append(K)
    while len(start) > 0:
        s = start.popleft()
        for dest, cost in d[s]:
            if k_dist[dest] > 0:
                continue

            k_dist[dest] = k_dist[s] + cost
            start.append(dest)

    for _ in range(Q):
        x, y = list(map(int, input().split()))
        x, y = x - 1, y - 1

        print((int(k_dist[x] + k_dist[y])))


if __name__ == '__main__':
    main()


# Optimized solution
import sys
from collections import deque

def main():
    input = sys.stdin.readline
    N = int(eval(input()))
    
    d = [[] for _ in range(N)]
    for _ in range(N-1):
        a, b, c = list(map(int, input().split()))
        a, b = a - 1, b - 1
        
        d[a].append((b, c))
        d[b].append((a, c))

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

    k_dist = [0 for _ in range(N)]
    start = deque()
    start.append(K)
    while len(start) > 0:
        s = start.popleft()
        for dest, cost in d[s]:
            if k_dist[dest] > 0:
                continue

            k_dist[dest] = k_dist[s] + cost
            start.append(dest)

    for _ in range(Q):
        x, y = list(map(int, input().split()))
        print((k_dist[x-1] + k_dist[y-1]))


if __name__ == '__main__':
    main()
# Original solution
# -*- coding: utf-8 -*-
#幅優先探索
import sys

N=eval(input())

a=[[] for i in range(N+1)]
#隣接リスト
for i in range(N-1):
	x,y,z=list(map(int,input().split()))
	a[x].append((y,z))
	a[y].append((x,z))

#print a

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


b=[]
for i in range(Q):
	b.append(list(map(int, input().split())))
#print b



#訪問判別フラグ
F=(N+1)*[0]

#Queue
queue=[]

#距離
dist=[0 for i in range(N+1)]

#先頭から幅優先探索
queue.append(K)
while len(queue) != 0:
	#print queue
	v= queue.pop(0)
	#print "v::"+str(v)
	if F[v]==0:
		F[v]=1

		for u,length in a[v]:
			if F[u]==0:
				queue.append(u)
				dist[u]=dist[v]+length
				#print dist

#print dist


for x in range(len(b)):
	print(dist[ b[x][0] ]+ dist[ b[x][1] ])




# Optimized solution
# -*- coding: utf-8 -*-
#深さ優先探索　再帰
#
import sys
sys.setrecursionlimit(200000)

N=eval(input())


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

#隣接リスト
for i in range(N-1):
	x,y,z=list(map(int,input().split()))
	a[x].append((y,z))
	a[y].append((x,z))

#print a
	

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


b=[]
for i in range(Q):
	b.append(list(map(int, input().split())))
#print b



#訪問判別フラグ
F=(N+1)*[0]

#距離
dist=[0 for i in range(N+1)]

#深さ優先探索　再帰
#現在の頂点 v, v の親 p, スタート地点Kから現在の頂点vまでの距離 d
def dfs(v,p,d):
	F[v]=1
	dist[v]=d
	for i,j in a[v]:
		#頂点 v に隣接しているかつ未訪問 
		if F[i]==0:
			#DFS(次の頂点i, 次に親となる頂点v, d+ 頂点vと頂点iの間の辺のコスト)
			dfs(i,v,d+j)


dfs(K,-1,0)

for x in range(len(b)):
	print(dist[ b[x][0] ]+ dist[ b[x][1] ])
# Original solution
import sys
stdin = sys.stdin

def li(): return list(map(int, stdin.readline().split()))
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return list(map(float, stdin.readline().split()))
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from heapq import heappush, heappop

def dijkstra(graph:list, node:int, start:int) -> list:
    # 未探索のノードは距離INF
    INF = float("inf")
    dist = [INF]*node
    
    # 始点ノードの距離を0とし、dfsのためのpriority queを作成
    dist[start] = 0
    heap = [(0,start)]
    
    # 未探索のノードをpriority queueに入れる
    while heap:
        cost, cur_node = heappop(heap)
        
        for nex_cost, nex_node in graph[cur_node]:
            dist_cand = dist[cur_node] + nex_cost
            if dist_cand < dist[nex_node]:
                dist[nex_node] = dist_cand
                heappush(heap, (dist[nex_node], nex_node))
    
    return dist

n = ni()
abc = []
for _ in range(n-1):
    a,b,c = li()
    a -= 1
    b -= 1
    abc.append((a,b,c))
q,k = li()
k -= 1
query = [li_() for _ in range(q)]

# 隣接リストつくる
graph = [[] for _ in range(n)]
for frm,to,cost in abc:
    graph[frm].append((cost,to))
    graph[to].append((cost,frm))

# 頂点Kをスタートとするダイクストラ
dist = dijkstra(graph, n, k)

# クエリ処理
for frm,to in query:
    print((dist[frm] + dist[to]))

# Optimized solution
import sys
stdin = sys.stdin

sys.setrecursionlimit(10**5)

def li(): return list(map(int, stdin.readline().split()))
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return list(map(float, stdin.readline().split()))
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from heapq import heappush, heappop

def dijkstra(graph:list, node:int, start:int) -> list:
    # 未探索のノードは距離INF
    INF = float("inf")
    dist = [INF]*node
    
    # 始点ノードの距離を0とし、dfsのためのpriority queを作成
    dist[start] = 0
    heap = [(0,start)]
    
    # 未探索のノードをpriority queueに入れる
    while heap:
        cost, cur_node = heappop(heap)
        
        for nex_cost, nex_node in graph[cur_node]:
            dist_cand = dist[cur_node] + nex_cost
            if dist_cand < dist[nex_node]:
                dist[nex_node] = dist_cand
                heappush(heap, (dist[nex_node], nex_node))
    
    return dist

n = ni()
graph = [[] for _ in range(n)]
for _ in range(n-1):
    a,b,c = li()
    a -= 1
    b -= 1
    graph[a].append((c,b))
    graph[b].append((c,a))
    
q,k = li()

dist = dijkstra(graph,n,k-1)

xy = [tuple(li_()) for _ in range(q)]

for x,y in xy:
    print((dist[x]+dist[y]))
# Original solution
import sys
stdin = sys.stdin

sys.setrecursionlimit(10**5)

def li(): return list(map(int, stdin.readline().split()))
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return list(map(float, stdin.readline().split()))
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from heapq import heappush, heappop

def dijkstra(graph:list, node:int, start:int) -> list:
    # 未探索のノードは距離INF
    INF = float("inf")
    dist = [INF]*node
    
    # 始点ノードの距離を0とし、dfsのためのpriority queを作成
    dist[start] = 0
    heap = [(0,start)]
    
    # 未探索のノードをpriority queueに入れる
    while heap:
        cost, cur_node = heappop(heap)
        
        for nex_cost, nex_node in graph[cur_node]:
            dist_cand = dist[cur_node] + nex_cost
            if dist_cand < dist[nex_node]:
                dist[nex_node] = dist_cand
                heappush(heap, (dist[nex_node], nex_node))
    
    return dist

n = ni()
graph = [[] for _ in range(n)]
for _ in range(n-1):
    a,b,c = li()
    a -= 1
    b -= 1
    graph[a].append((c,b))
    graph[b].append((c,a))
    
q,k = li()

dist = dijkstra(graph,n,k-1)

xy = [tuple(li_()) for _ in range(q)]

for x,y in xy:
    print((dist[x]+dist[y]))

# Optimized solution
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return list(map(int, stdin.readline().split()))
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return list(map(float, stdin.readline().split()))
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from heapq import heappush, heappop

def dijkstra(graph:list, node:int, start:int) -> list:
    # 未探索のノードは距離INF
    INF = float("inf")
    dist = [INF]*node
    
    # 始点ノードの距離を0とし、dfsのためのpriority queを作成
    dist[start] = 0
    heap = [(0,start)]
    
    # 未探索のノードをpriority queueに入れる
    while heap:
        cost, cur_node = heappop(heap)
        
        for nex_cost, nex_node in graph[cur_node]:
            dist_cand = dist[cur_node] + nex_cost
            if dist_cand < dist[nex_node]:
                dist[nex_node] = dist_cand
                heappush(heap, (dist[nex_node], nex_node))
    
    return dist

n = ni()

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

for _ in range(n-1):
    a,b,c = li()
    a -= 1
    b -= 1
    graph[a].append((c, b))
    graph[b].append((c, a))

q,k = li()
k -= 1

query = []
for _ in range(q):
    x, y = li_()
    query.append((x, y))
    
dist = dijkstra(graph, n, k)
    
for qx, qy in query:
    print((dist[qx] + dist[qy]))
# Original solution
from heapq import heappush, heappop


class Dijkstra:
    def __init__(self, route_map, start_point, goal_point=None):
        self.route_map = route_map
        self.start_point = start_point
        self.goal_point = goal_point

    def execute(self):
        num_of_vertex = len(self.route_map)
        dist = [float('inf') for _ in range(num_of_vertex)]
        prev = [float('inf') for _ in range(num_of_vertex)]
        dist[self.start_point] = 0
        heap_q = []
        heappush(heap_q, (0, self.start_point))
        while len(heap_q) != 0:
            prev_cost, src = heappop(heap_q)
            if dist[src] < prev_cost:
                continue
            for dest in range(num_of_vertex):
                cost = route_map[src][dest]
                if cost != float('inf') and dist[dest] > dist[src] + cost:
                    dist[dest] = dist[src] + cost
                    heappush(heap_q, (dist[dest], dest))
                    prev[dest] = src
        if self.goal_point is not None:
            return self.get_path(prev)
        else:
            return dist

        def get_path(prev):
            path = [self.goal_point]
            dest = self.goal_point
            while prev[dest] != float('inf'):
                dest = prev[dest]
            return list(reversed(path))


N = int(eval(input()))
route_map = [[float('inf') for _ in range(N)] for _ in range(N)]
for _ in range(N - 1):
    a, b, c = list(map(int, input().split()))
    route_map[a - 1][b - 1] = c
    route_map[b - 1][a - 1] = c
Q, K = list(map(int, input().split()))
K -= 1
dijakstra_result = Dijkstra(route_map, K).execute()
for _ in range(Q):
    x, y = list(map(int, input().split()))
    print((dijakstra_result[x - 1] + dijakstra_result[y - 1]))

# Optimized solution
import sys
sys.setrecursionlimit(10 ** 8)


class Solve():
    def __init__(self):
        self.N = int(eval(input()))
        self.route = [dict() for _ in range(self.N)]
        for _ in range(self.N - 1):
            a, b, c = list(map(int, input().split()))
            self.route[a - 1][b - 1] = c
            self.route[b - 1][a - 1] = c
        self.Q, self.K = list(map(int, input().split()))
        self.K -= 1
        self.query = []
        for _ in range(self.Q):
            x, y = list(map(int, input().split()))
            self.query.append([x - 1, y - 1])
        self.depth = [0 for _ in range(self.N)]

    def DFS(self, v, p, d):
        self.depth[v] = d
        for dest, cost in list(self.route[v].items()):
            if dest == p:
                continue
            self.DFS(dest, v, d + cost)

    def execute(self):
        self.DFS(self.K, -1, 0)
        for x, y in self.query:
            print((self.depth[x] + self.depth[y]))


if __name__ == '__main__':
    Solve().execute()
# Original solution
def BFS(K, edges, N):
    roots = [[] for i in range(N)]
    for a, b, c in edges:
        roots[a - 1] += [(b - 1, c)]
        roots[b - 1] += [(a - 1, c)]
    dist = [-1] * N
    stack = []
    stack.append(K)
    dist[K] = 0
    while stack:
        label = stack.pop(-1)
        for i, c in roots[label]:
            if dist[i] == -1:
                dist[i] = dist[label] + c
                stack += [i]
    return dist


N = int(eval(input()))
edges = []
for i in range(N - 1):
    edges += [list(map(int, input().split()))]
Q, K = list(map(int, input().split()))
xy = [list(map(int, input().split())) for i in range(Q)]
distance = BFS(K-1, edges, N)
for i in range(Q):
    print((distance[xy[i][0] - 1] + distance[xy[i][1] - 1]))

# Optimized solution
def getDis(k, abc, n):
    r = [[] for i in range(n)]
    for a, b, c in abc:
        r[a-1] += [(b-1, c)]
        r[b-1] += [(a-1, c)]
    dis = [-1] * n
    stack = [k]
    dis[k] = 0
    while stack:
        label = stack.pop(-1)
        for i, c in r[label]:
            if dis[i] == -1:
                dis[i] = dis[label] + c
                stack.append(i)
    return dis


N = int(eval(input()))
abc = [[int(i) for i in input().split()] for i in range(N-1)]
Q, K = list(map(int, input().split()))
xy = [[int(i) for i in input().split()] for i in range(Q)]
d = getDis(K-1, abc, N)
for i in range(Q):
    print((d[xy[i][0] - 1] + d[xy[i][1] - 1]))
# Original solution
N = int(eval(input()))
treedic = {}
for i in range(1, N+1):
    treedic[i] = {}
for i in range(N-1):
    a, b, c = list(map(int, input().split()))
    treedic[a][b] = c
    treedic[b][a] = c

Q, K = list(map(int, input().split()))
checked = set([K])
length = [0]*(N+1)
check = set([K])

while len(checked) < N:
    nextcheck = set()
    for i in check:
        for j in list(treedic[i].keys()):
            if j not in checked:
                length[j] = length[i] + treedic[i][j]
                checked.add(j)
                nextcheck.add(j)
    check = nextcheck

for i in range(Q):
    x, y = list(map(int, input().split()))
    print((length[x] + length[y]))


# Optimized solution
def main():
    N = int(eval(input()))
    treedic = {}
    for i in range(1, N+1):
        treedic[i] = {}
    for i in range(N-1):
        a, b, c = list(map(int, input().split()))
        treedic[a][b] = c
        treedic[b][a] = c

    Q, K = list(map(int, input().split()))
    checked = set([K])
    length = [0]*(N+1)
    check = set([K])

    while len(checked) < N:
        nextcheck = set()
        for i in check:
            for j in list(treedic[i].keys()):
                if j not in checked:
                    length[j] = length[i] + treedic[i][j]
                    checked.add(j)
                    nextcheck.add(j)
        check = nextcheck

    for i in range(Q):
        x, y = list(map(int, input().split()))
        print((length[x] + length[y]))


if __name__ == "__main__":
    main()
# Original solution
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
mod2 = 998244353
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n = inp()
g = [[] for i in range(n)]
cc = dict()
for i in range(n-1):
    a,b,c = inpl()
    a -= 1
    b -= 1
    g[a].append(b)
    g[b].append(a)
    cc[(a,b)] = c
    cc[(b,a)] = c
q,k = inpl()
k -= 1
cost = [INF] * n
cost[k] = 0
def dfs(node,c):
    for next in g[node]:
        if cost[next] == INF:
            cost[next] = c + cc[(node,next)]
            dfs(next,cost[next])

dfs(k,0)
res = [0] * q
for i in range(q):
    x,y = inpl()
    x -= 1
    y -= 1
    res[i] = cost[x] + cost[y]
for z in res:
    print(z)


# Optimized solution
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions
from decimal import Decimal
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n = inp()
co = dict()
g = [[] for _ in range(n)]
cost = [-1] * n
for i in range(n-1):
    a,b,c = inpl()
    a -= 1; b -= 1
    g[a] += [b]; g[b] += [a]
    co[(a,b)] = c; co[(b,a)] = c
Q,k = inpl()
k -= 1; cost[k] = 0
q = deque()
q.append(k)
while q:
    nv = q.popleft()
    for v in g[nv]:
        if cost[v] > 0:
            continue
        cost[v] = cost[nv] + co[(v,nv)]
        q.append(v)
for _ in range(Q):
    a,b = inpl()
    a -= 1; b -= 1
    print((cost[a] + cost[b]))
# Original solution
import sys
input = sys.stdin.readline

def main():
    N = int(eval(input()))
    X = [list(map(int,input().split())) for _ in range(N-1)]
    Q,K = list(map(int,input().split()))
    Y = [list(map(int,input().split())) for _ in range(Q)]

    tree = [[] for _ in range(N)]
    dif = [10**15 for _ in range(N)]
    dif[K-1] = 0
    for i in range(N-1):
        tree[X[i][0]-1].append(X[i][1])
        tree[X[i][1]-1].append(X[i][0])

    queue = [K]
    while queue:
        a = queue.pop()
        for i in range(N-1):
            if X[i][0] == a:
                dif[X[i][1]-1] = min(dif[X[i][1]-1],dif[a-1]+X[i][2])
                tree[X[i][1]-1].remove(a)
                queue[0:0] = tree[a-1]
            if X[i][1] == a:
                dif[X[i][0]-1] = min(dif[X[i][0]-1],dif[a-1]+X[i][2])
                tree[X[i][0]-1].remove(a)
                queue[0:0] = tree[a-1]
        queue = list(set(queue))

    for i in range(Q):
        print((dif[Y[i][0]-1]+dif[Y[i][1]-1]))

if __name__ == "__main__":
    main()

# Optimized solution
import sys
input = sys.stdin.readline

def main():
    N = int(eval(input()))
    X = [list(map(int,input().split())) for _ in range(N-1)]
    Q,K = list(map(int,input().split()))
    Y = [list(map(int,input().split())) for _ in range(Q)]

    tree = [[] for _ in range(N)]
    dif = [10**15 for _ in range(N)]
    dif[K-1] = 0
    for i in range(N-1):
        tree[X[i][0]-1].append((X[i][1]-1,X[i][2]))
        tree[X[i][1]-1].append((X[i][0]-1,X[i][2]))

    queue = [K-1]
    while queue:
        a = queue.pop()
        for i in tree[a]:
            s,t = i[0],i[1]
            if dif[s] == 10**15:
                dif[s] = dif[a]+t
                queue.append(s)

    for i in range(Q):
        print((dif[Y[i][0]-1]+dif[Y[i][1]-1]))

if __name__ == "__main__":
    main()