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: Accepted)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace ABC070D
{
    class Program
    {
        static void Solve(Input input)
        {
            var n = input.NextInt();
            var dj = new Dijkstra(n);

            for (int i = 0; i < n - 1; i++)
            {
                var a = input.NextInt() - 1;
                var b = input.NextInt() - 1;
                var c = input.NextInt();

                dj.AddPath(a, b, c);
                dj.AddPath(b, a, c);
            }

            var q = input.NextInt();
            var k = input.NextInt() - 1;

            var sp = dj.ShortestPath(k);
            for (int i = 0; i < q; i++)
            {
                var x = input.NextInt() - 1;
                var y = input.NextInt() - 1;

                Console.WriteLine(sp[x] + sp[y]);
            }
        }

        /// <summary>
        /// 重み付き・有向グラフの単一始点最短経路
        /// 辺の重みは非負数だけ
        /// </summary>
        class Dijkstra
        {
            class PriorityQueue<T> where T : IComparable<T>
            {
                List<T> Heap;
                Func<T, T, bool> compare;

                public PriorityQueue(int capacity, bool isMinHeap = true)
                {
                    this.Heap = new List<T>(capacity);

                    if (isMinHeap)
                    {
                        compare = (x, y) => x.CompareTo(y) < 0;
                    }
                    else
                    {
                        compare = (x, y) => x.CompareTo(y) > 0;
                    }
                }

                public PriorityQueue() : this(0) { }

                static void pushHeap(List<T> heap, Func<T, T, bool> compare, T item)
                {
                    var n = heap.Count();
                    heap.Add(item);

                    while (n != 0)
                    {
                        var parent = (n - 1) / 2;

                        if (compare(heap[n], heap[parent]))
                        {
                            var temp = heap[n];
                            heap[n] = heap[parent];
                            heap[parent] = temp;
                        }

                        n = parent;
                    }
                }

                static T popHeap(List<T> heap, Func<T, T, bool> compare)
                {
                    if (!heap.Any())
                    {
                        throw new Exception();
                    }
                    var item = heap[0];

                    var n = heap.Count() - 1;
                    heap[0] = heap.Last();
                    heap.RemoveAt(n);

                    var parent = 0;
                    var child = 2 * parent + 1;
                    while (child < n)
                    {
                        if ((child != n - 1) && compare(heap[child + 1], heap[child]))
                        {
                            child++;
                        }

                        if (compare(heap[child], heap[parent]))
                        {
                            var temp = heap[parent];
                            heap[parent] = heap[child];
                            heap[child] = temp;
                        }

                        parent = child;
                        child = 2 * parent + 1;
                    }

                    return item;
                }

                /// <summary>
                /// 要素追加
                /// </summary>
                /// <param name="item"></param>
                public void Push(T item)
                {
                    pushHeap(this.Heap, this.compare, item);
                }

                /// <summary>
                /// 先頭の値取得し削除する
                /// </summary>
                /// <returns></returns>
                public T Pop()
                {
                    return popHeap(this.Heap, this.compare);
                }

                /// <summary>
                /// 先頭の値取得（削除はしない）
                /// </summary>
                /// <returns></returns>
                public T Peek()
                {
                    if (!this.Heap.Any())
                    {
                        throw new Exception();
                    }

                    return this.Heap[0];
                }

                /// <summary>
                /// ヒープに格納されているアイテム数
                /// </summary>
                /// <returns></returns>
                public int Count() => this.Heap.Count();

                /// <summary>
                /// 一つでの値が格納されているか
                /// </summary>
                /// <returns></returns>
                public bool Any() => this.Heap.Any();
            }

            struct Edge : IComparable<Edge>
            {
                public int To;
                public long Cost;

                public Edge(int to, long cost)
                {
                    this.To = to;
                    this.Cost = cost;
                }

                public int CompareTo(Edge other)
                {
                    return this.Cost.CompareTo(other.Cost);
                }
            }

            static readonly long INF = long.MaxValue / 5;

            // 接続情報
            List<List<Edge>> es;
            // ノード数
            int V;
            // 経路復元用情報
            int[] Prev;

            /// <summary>
            /// 
            /// </summary>
            /// <param name="v">ノード数</param>
            public Dijkstra(int v)
            {
                es = Enumerable.Repeat(0, v)
                    .Select(_ => new List<Edge>())
                    .ToList();
                V = v;
            }

            /// <summary>
            /// 経路追加
            /// </summary>
            /// <param name="from"></param>
            /// <param name="to"></param>
            /// <param name="cost"></param>
            public void AddPath(int from, int to, int cost)
                => es[from].Add(new Edge(to, cost));

            /// <summary>
            /// 各ノードへの最短経路
            /// </summary>
            /// <param name="s"></param>
            /// <returns>nullなら負経路がある</returns>
            public long[] ShortestPath(int s)
            {
                var d = Enumerable.Repeat<long>(INF, V).ToArray();
                var pq = new PriorityQueue<Edge>();
                Prev = Enumerable.Repeat(-1, V).ToArray();

                d[s] = 0;
                pq.Push(new Edge(s, 0));

                while (pq.Any())
                {
                    var p = pq.Pop();
                    var v = p.To;

                    // 他の経路の方がコストが低い
                    if (d[v] < p.Cost) continue;

                    foreach (var e in es[v])
                    {
                        if (d[e.To] > d[v] + e.Cost)
                        {
                            // こっちの経路の方が効率的
                            d[e.To] = d[v] + e.Cost;
                            Prev[e.To] = v;
                            pq.Push(new Edge(e.To, d[e.To]));
                        }
                    }
                }

                return d;
            }

            /// <summary>
            /// 最後に探索した経路を復元する
            /// </summary>
            /// <param name="t">目的ノード</param>
            /// <returns>探索したことがないときはnull</returns>
            public int[] Path(int t)
            {
                if (this.Prev == null) return null;

                var stack = new Stack<int>();
                while (t >= 0)
                {
                    stack.Push(t);
                    t = Prev[t];
                }

                return stack.ToArray();
            }
        }

        #region Competitive Template
        static readonly int MOD = (int)1e9 + 7;

        public static void Main(string[] args)
        {
            // 出力が少ないときはこれをセットする方が時間かかるけれど
            // その場合は出力がボトルネックになっていないので、まあ良しとする
            var needsFlushOutput = true;
            if (needsFlushOutput)
            {
                // 細かく出力しないようにする
                var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
                Console.SetOut(sw);
            }

            // 通常は引数無しで、ファイルから読み出したい場合はpath指定する
            var input = new Input();
            // 仮想的に標準入力をセットする
            //input.SetText("");

            Solve(input);

            Console.Out.Flush();
        }

        class Input
        {
            // 変な改行コードがたまに混じっているので、一応セパレート指定する
            // スペース単独指定の方がもちろん早い
            static readonly char[] separator = { ' ', '\r', '\n' };
            Queue<string> q { get; set; }
            StreamReader sr;

            /// <summary>
            /// 特定のファイルから読み出したい場合はpath指定する
            /// </summary>
            /// <param name="path"></param>
            public Input(string path = "")
            {
                q = new Queue<string>();

                if (string.IsNullOrEmpty(path))
                {
                    sr = new StreamReader(Console.OpenStandardInput());
                }
                else
                {
                    sr = new StreamReader(path);
                }
            }

            /// <summary>
            /// 入力予約
            /// </summary>
            /// <param name="items"></param>
            public void SetText(IEnumerable<string> items)
            {
                foreach (var item in items)
                {
                    SetText(item);
                }
            }

            /// <summary>
            /// 入力予約
            /// </summary>
            /// <param name="s"></param>
            /// <returns></returns>
            public bool SetText(string s)
            {
                if (s == null) return false;

                foreach (var elem in s.Trim().Split(separator, StringSplitOptions.RemoveEmptyEntries))
                {
                    q.Enqueue(elem);
                }

                return true;
            }

            /// <summary>
            /// 内部queueに入力からの値をsplitして格納する
            /// </summary>
            /// <returns></returns>
            bool read()
            {
                var s = sr.ReadLine();
                if (s == null) return false;

                foreach (var elem in s.Trim().Split(separator, StringSplitOptions.RemoveEmptyEntries))
                {
                    q.Enqueue(elem);
                }

                if (!q.Any()) return read();

                return true;
            }

            /// <summary>
            /// 次のstringを一つ読み込む
            /// </summary>
            /// <returns></returns>
            public string Next()
            {
                if (!q.Any())
                {
                    if (!read())
                    {
                        return "";
                    }
                }

                return q.Dequeue();
            }

            /// <summary>
            /// 指定個数queueにたまるまでenqueueし続ける
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            bool accumulate(int n)
            {
                while (q.Count() < n)
                {
                    if (!read()) return false;
                }

                return true;
            }

            public int NextInt() => int.Parse(Next());
            public long NextLong() => long.Parse(Next());
            public double NextDouble() => double.Parse(Next());

            /// <summary>
            /// n個の要素をparseして、それぞれにoffsetをaddした配列を返す
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="n"></param>
            /// <param name="offset"></param>
            /// <param name="parse"></param>
            /// <param name="add"></param>
            /// <returns></returns>
            T[] NextT<T>(int n, T offset, Func<string, T> parse, Func<T, T, T> add)
            {
                if (!accumulate(n)) return null;

                var a = new T[n];

                for (int i = 0; i < n; i++)
                    a[i] = add(parse(q.Dequeue()), offset);

                return a;
            }

            public string[] Next(int n) => NextT(n, "", x => x, (x, y) => x);
            public int[] NextInt(int n, int offset = 0) => NextT(n, offset, int.Parse, (x, y) => x + y);
            public long[] NextLong(int n, long offset = 0) => NextT(n, offset, long.Parse, (x, y) => x + y);
            public double[] NextDouble(int n, double offset = 0.0) => NextT(n, offset, double.Parse, (x, y) => x + y);
        }

        static class Utils
        {
            public static void Print<T>(IEnumerable<T> ie, string sep = " ") => Console.WriteLine(string.Join(sep, ie));
            public static void Print<T>(params T[] objs) => Print(objs);
            public static T Max<T>(params T[] objs) => objs.Max();
            public static T Min<T>(params T[] objs) => objs.Min();

            public static void Swap<T>(ref T x, ref T y) where T : struct { var t = x; x = y; y = t; }
            public static void Swap<T>(IList<T> list, int i, int j) where T : struct { var t = list[i]; list[i] = list[j]; list[j] = t; }

            /// <summary>
            /// vでfillされたT[d1][d2]配列を作成する
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="d1"></param>
            /// <param name="d2"></param>
            /// <param name="v"></param>
            /// <returns></returns>
            public static T[][] Create2DArray<T>(int d1, int d2, T v = default(T))
            {
                return
                    Enumerable.Repeat(0, d1).Select(_ =>
                    Enumerable.Repeat(v, d2).ToArray()).ToArray();
            }

            /// <summary>
            /// vでfillされたT[d1][d2][d3]配列を作成する
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="d1"></param>
            /// <param name="d2"></param>
            /// <param name="d3"></param>
            /// <param name="v"></param>
            /// <returns></returns>
            public static T[][][] Create3DArray<T>(int d1, int d2, int d3, T v = default(T))
            {
                return
                    Enumerable.Repeat(0, d1).Select(_ =>
                    Enumerable.Repeat(0, d2).Select(__ =>
                     Enumerable.Repeat(v, d3).ToArray()).ToArray()).ToArray();
            }
        }
        #endregion
    }
}