A Tree Problem

0

0 votes
Problem

You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N1 edges, where N is the number of its vertices.
The i -th edge (1iN1) connects Vertices ai and bi, and has a length of ci.

You are also given Q queries and an integer K. In the j -th query (1jQ) :

find the length of the shortest path from Vertex xj and Vertex yj via Vertex K.

Constraints

3N105

1ai,biN  (1iN1)

1ci109     (1iN1)

The given graph is a tree.

1Q105

1KN

1xj,yjN  (1jQ)

xjyj  (1jQ)

xjK,yjK   (1jQ)

Input

Input is given from Standard Input in the following format:

N
a1 b1 c1 
:
aN−1 bN−1 cN−1
Q K
x1 y1
:
xQ yQ

Output

Print the responses to the queries in Q lines.
In the j -th line (1jQ), print the response to the j -th query.

Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

The shortest paths for the three queries are as follows:

Query 1: Vertex 2 → Vertex 1 → Vertex 2 → Vertex 4 : Length 1+1+1=3

Query 2: Vertex 2 → Vertex 1 → Vertex 3 : Length 1+1=2

Query 3: Vertex 4 → Vertex 2 → Vertex 1 → Vertex 3 → Vertex 5 : Length 1+1+1+1=4

Editor Image

?