Problem:
Score : 400 points

Problem Statement

You are given a tree with N vertices.

Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.

The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.

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

find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.

Constraints

3≤N≤10^5

1≤a_i,b_i≤N (1≤i≤N-1)

1≤c_i≤10^9 (1≤i≤N-1)

The given graph is a tree.

1≤Q≤10^5

1≤K≤N

1≤x_j,y_j≤N (1≤j≤Q)

x_j≠y_j (1≤j≤Q)

x_j≠K,y_j≠K (1≤j≤Q)

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}

Output

Print the responses to the queries in Q lines.

In the j-th line j(1≤j≤Q), print the response to the j-th query.

Sample Input 1

5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5

Sample Output 1

3
2
4

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

Sample Input 2

7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7

Sample Output 2

5
14
22

The path for each query must pass Vertex K=2.

Sample Input 3

10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10

Sample Output 3

17000000000

Solution in C# (Mono 4.6.2.0) (judge verdict: Runtime Error)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using static System.Console;
using static System.Convert;
using static System.Math;
using static Extentions;

class IO
{
    int idx;
    string[] input = In.ReadToEnd().Split(new[] { " ", "\n", "\r" },
        StringSplitOptions.RemoveEmptyEntries);

    T Get<T>(Func<string, T> parser) => parser(input[idx++]);

    public string S => Get(s => s);
    public char C => Get(char.Parse);
    public int I => Get(int.Parse);
    public long L => Get(long.Parse);
    public double F => Get(double.Parse);
    public decimal D => Get(decimal.Parse);
    public BigInteger B => Get(BigInteger.Parse);

    T[] Gets<T>(int n, Func<string, T> parser)
        => input.Skip((idx += n) - n).Take(n).Select(parser).ToArray();

    public string[] Ss(int n) => Gets(n, s => s);
    public char[] Cs(int n) => Gets(n, char.Parse);
    public int[] Is(int n) => Gets(n, int.Parse);
    public long[] Ls(int n) => Gets(n, long.Parse);
    public double[] Fs(int n) => Gets(n, double.Parse);
    public decimal[] Ds(int n) => Gets(n, decimal.Parse);
    public BigInteger[] Bs(int n) => Gets(n, BigInteger.Parse);

    public void Write<T>(params T[] xs) => WriteLine(string.Join(" ", xs));
    public void Write(params object[] xs) => WriteLine(string.Join(" ", xs));
}

class PriorityQueue<T>
{
    List<T> heap;
    int size;
    Comparison<T> compare;

    public PriorityQueue()
        : this(Enumerable.Empty<T>(), Comparer<T>.Default.Compare) { }

    public PriorityQueue(IEnumerable<T> collection)
        : this(collection, Comparer<T>.Default.Compare) { }

    public PriorityQueue(Comparison<T> comparsion)
        : this(Enumerable.Empty<T>(), comparsion) { }

    public PriorityQueue(IEnumerable<T> collection, Comparison<T> comparsion)
    {
        var array = collection.ToArray();
        Array.Sort(array, comparsion);
        heap = new List<T>(array);
        size = array.Length;
        compare = comparsion;
    }

    public int Count => size;

    public bool Any() => size > 0;

    public void Clear() => size = 0;

    public void Enqueue(T item)
    {
        var i = size++;
        while (i > 0)
        {
            var p = (i - 1) >> 1;
            if (compare(heap[p], item) <= 0) break;
            if (i == heap.Count) heap.Add(heap[p]);
            else heap[i] = heap[p];
            i = p;
        }
        if (i == heap.Count) heap.Add(item);
        else heap[i] = item;
    }

    public T Dequeue()
    {
        if (size == 0) throw new InvalidOperationException();
        var r = heap[0];
        var x = heap[--size];
        var i = 0;
        while ((i << 1) + 1 < size)
        {
            var a = (i << 1) + 1;
            var b = (i << 1) + 2;
            if (b < size && compare(heap[b], heap[a]) < 0) a = b;
            if (compare(heap[a], x) >= 0) break;
            heap[i] = heap[a];
            i = a;
        }
        heap[i] = x;
        return r;
    }

    public T Peek()
    {
        if (size == 0) throw new InvalidOperationException();
        return heap[0];
    }
}

#region http://yambe2002.hatenablog.com/entry/2015/11/05/030545
/// <summary>
/// Get min cost between two points
/// </summary>
public class Dijkstra
{
    private int maxIndex = -1;
    private const long INF = Int64.MaxValue;

    private long[,] _edgeArray;

    /// <summary>
    /// Dijkstra, get min cost between two points
    /// should not contain negatie cost path
    /// </summary>
    /// <param name="size">max index of vertices</param>
    public Dijkstra(int size)
    {
        maxIndex = size + 1;
        _edgeArray = new long[maxIndex, maxIndex];

        for (int i = 0; i < _edgeArray.GetLength(0); i++)
        {
            for (int j = 0; j < _edgeArray.GetLength(1); j++)
            {
                _edgeArray[i, j] = INF;
                if (i == j) _edgeArray[i, j] = 0;
            }
        }
    }

    // Add a path(no direction) with its cost
    public void AddPath(int s, int t, int cost)
    {
        _edgeArray[s, t] = Math.Min(_edgeArray[s, t], cost);
        _edgeArray[t, s] = _edgeArray[s, t];
    }

    //Get the min cost between s and t
    //return Int32.MaxValue if no path
    public long GetMinCost(int s, int t)
    {
        long[] cost = new long[maxIndex];
        for (int i = 0; i < cost.Length; i++) cost[i] = INF;
        cost[s] = 0;

        var priorityQueue = new PriorityQueue<ComparablePair<long, long>>();
        priorityQueue.Enqueue(new ComparablePair<long, long>(0, s));

        while (priorityQueue.Count > 0)
        {
            var costDestinationPair = priorityQueue.Dequeue();
            if (cost[costDestinationPair.Item2] < costDestinationPair.Item1) continue;

            for (int i = 0; i < maxIndex; i++)
            {
                long newCostToi = _edgeArray[costDestinationPair.Item2, i] == INF ? INF :
                    costDestinationPair.Item1 + _edgeArray[costDestinationPair.Item2, i];
                if (newCostToi < cost[i])
                {
                    cost[i] = newCostToi;
                    priorityQueue.Enqueue(new ComparablePair<long, long>(newCostToi, i));
                }
            }
        }

        return cost[t];
    }
}

public class ComparablePair<T, U> : IComparable where T : IComparable<T>
{
    public readonly T Item1;
    public readonly U Item2;

    public int CompareTo(object obj)
    {
        ComparablePair<T, U> castedObj = (ComparablePair<T, U>)obj;
        return this.Item1.CompareTo(castedObj.Item1);
    }

    public ComparablePair(T t, U u)
    {
        Item1 = t;
        Item2 = u;
    }
}
#endregion

static class Extentions
{
}

static class Program
{
    public static void Main()
    {
        var sw = new StreamWriter(OpenStandardOutput()) { NewLine = "\n" };
#if DEBUG
        sw.AutoFlush = true;
#else
        sw.AutoFlush = false;
#endif
        SetOut(sw);
        Solve(new IO());
        Out.Flush();
    }

    static void Solve(IO io)
    {
        var n = io.I;
        var dijkstra = new Dijkstra(n);

        for (var i = 0; i < n - 1; i++)
        {
            var a = io.I;
            var b = io.I;
            var c = io.I;
            dijkstra.AddPath(a, b, c);
        }

        var q = io.I;
        var k = io.I;

        for (var i = 0; i < q; i++)
        {
            var x = io.I;
            var y = io.I;
            var d = dijkstra.GetMinCost(x, k) + dijkstra.GetMinCost(k, y);
            io.Write(d);
        }
    }
}