1103. Town Distance Queries

A mountain kingdom has n towns numbered 0 to n - 1, joined by exactly n - 1 roads so that every town can be reached from every other town in exactly one way (the road map is a tree). Each entry [u, v, w] of edges is a two-way road of length w between towns u and v.

A courier asks q questions. Question queries[i] = [a, b] asks for the total length of the roads on the one route from town a to town b; the two towns may be given in either order and may be the same town. Return a long[] answer with answer[i] equal to the distance for queries[i].

Example 1

Input:
n = 6edges = [[0,1,4],[1,2,3],[1,3,5],[0,4,2],[4,5,7]]queries = [[2,3],[3,5],[0,0]]
Output:
[8,18,0]
Explanation:

Towns 2 and 3 meet at town 1 (3 + 5 = 8); town 3 to town 5 goes 5 + 4 + 2 + 7 = 18; a town is at distance 0 from itself.

Example 2

Input:
n = 3edges = [[0,1,1000000000],[1,2,1000000000]]queries = [[0,2],[2,0]]
Output:
[2000000000,2000000000]
Explanation:

The only route uses both roads, so the distance is 2000000000 in either direction, which does not fit in 32 bits.

Example 3

Input:
n = 5edges = [[3,0,2],[3,1,6],[3,2,1],[3,4,9]]queries = [[0,1],[2,4],[4,3]]
Output:
[8,10,9]
Explanation:

Town 3 is the centre, so the distance between two outer towns is the sum of their spokes: 2 + 6, 1 + 9 and 9.

Constraints

1 ≤ n ≤ 100000

edges.length == n - 1, each edge is [u, v, w] with 0 ≤ u, v < n and 1 ≤ w ≤ 109; the roads form a tree

0 ≤ queries.length ≤ 100000, each query is [a, b] with 0 ≤ a, b < n

Distances can exceed the 32-bit range.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 3,200 msC++ 800 msJava 1,600 msJavaScript 1,600 msTypeScript 1,600 ms

Expected complexity

Time
O((n + q) log n)
Space
O(n log n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…