Let us root the tree at vertex and denote by the distance from the root to vertex — the sum of the edge weights on the path from the root to . All values of are computed by a single depth-first search: if an edge of weight leads from vertex to its child , then \mathit{dist}[\mathit{to}] = \mathit{dist}[v] + w.
Consider a query . Let l = \mathit{LCA}(u, v) be the lowest common ancestor of vertices and . The path between and is unique: it goes up from to and then goes down from to . The length of the ascent is \mathit{dist}[u] - \mathit{dist}[l], and the length of the descent is \mathit{dist}[v] - \mathit{dist}[l]. Therefore
In other words, the sum \mathit{dist}[u] + \mathit{dist}[v] counts the shared part from the root to twice, so it must be subtracted twice.
Finding the LCA. We find the lowest common ancestor using the binary lifting method. The depth-first search computes for each vertex the entry time and the exit time : vertex is an ancestor of if and only if d[a] \le d[b] and f[b] \le f[a]. In addition, we store \mathit{up}[v][i] — the ancestor of vertex located 2^i levels higher. Then the LCA of two vertices is found in O(\log n).
Edge weights do not exceed , and a path contains at most edges, so the distance does not exceed 1.5 \cdot 10^8 and fits into the int type.
Complexity. The depth-first search together with filling the table runs in O(n \log n), and each query takes O(\log n). The total complexity is O((n + m) \log n). The recursion depth can reach n = 150000 if the tree is a chain.
Example
The tree from the problem statement looks as follows:
The root is vertex , \mathit{dist}[0] = 0, \mathit{dist}[1] = \mathit{dist}[2] = 1.
Query : vertex is an ancestor of vertex , so l = 0 and the distance equals 0 + 1 - 2 \cdot 0 = 1.
Query : similarly, the distance equals .
Query : l = \mathit{LCA}(1, 2) = 0, the distance equals 1 + 1 - 2 \cdot 0 = 2.
Consider a larger example. Let the weight of each edge be ; then is the depth of vertex . The value is written next to each vertex .
Let us find the distance between vertices and . Their lowest common ancestor is vertex , so the distance equals
Indeed, the path — — — — consists of four edges.
Consider an example where the edges have different weights. Let us find the distance between vertices u = 3 and v = 5. Their lowest common ancestor is l = 1, \mathit{dist}[3] = 6, \mathit{dist}[5] = 6, \mathit{dist}[1] = 2.
Both and include the edge — of weight , but it does not belong to the path between vertices and . Subtracting 2 \cdot \mathit{dist}[1], we get 6 + 6 - 2 \cdot 2 = 8. Indeed, the path — — — has length 4 + 1 + 3 = 8.
Algorithm Implementation
The tree is stored as a weighted graph in the adjacency list . For an undirected edge of weight , stores the pair (v, w), and stores the pair .
The timestamps and (the entry and exit times of a vertex during the depth-first search) make it possible to check in whether one vertex is an ancestor of another.
The cell stores the distance from the root to vertex .
The array is used to find the LCA by binary lifting: \mathit{up}[v][i] is the ancestor of vertex located 2^i levels higher.
#define MAX 500001
vector<pair<int,int> > g[MAX];
int d[MAX], f[MAX], dist[MAX];
int up[MAX][20];The dfs function performs a depth-first search from vertex . The parameter is the parent of vertex , and is the distance from the root to . An array of visited vertices is not needed: a tree has no cycles, so it is enough not to return from to its parent . On entering the vertex, we record its entry time , its immediate parent \mathit{up}[v][0], and the distance . For the root p = 0, that is, the root is its own parent, and any jump above the root stops at it.
void dfs (int v, int p = 0, int len = 0)
{
d[v] = timer++;
up[v][0] = p; dist[v] = len;Fill the row of the binary lifting table: the ancestor 2^i levels higher is the ancestor 2^{i-1} levels higher of the ancestor 2^{i-1} levels higher. All ancestors of vertex have already been visited, so their rows of the table are filled by this moment.
for(i = 1; i <= l; i++)
up[v][i] = up[up[v][i-1]][i-1];Iterate over the neighbors of vertex . Every neighbor except the parent is a child of : run the depth-first search from it; the distance to it equals \mathit{len} + w. Note that the edge weight is stored in the local variable , which hides the global array inside the loop. This is allowed, since the array is not used in the loop, but such name clashes are better avoided.
for (auto x : g[v])
{
int to = x.first;
int dist = x.second;
if (to != p) dfs(to, v, len + dist);
}After all children are processed, record the exit time .
f[v] = timer++;
}The Parent function returns true if vertex is an ancestor of vertex (a vertex is considered an ancestor of itself). This holds if and only if the interval [d[b]; f[b]] is nested in the interval [d[a]; f[a]].
int Parent(int a, int b)
{
return (d[a] <= d[b]) && (f[a] >= f[b]);
}The LCA function finds the lowest common ancestor of vertices and using binary lifting. If one of the vertices is an ancestor of the other, it is the answer. Otherwise, lift vertex with jumps of length 2^l, 2^{l-1}, \ldots, 1, making a jump only if the new vertex is still not an ancestor of . After the loop, is the highest vertex on the path from to the root that is not an ancestor of . Its parent is the LCA.
int LCA (int a, int b)
{
if (Parent(a, b)) return a;
if (Parent(b, a)) return b;
for (int i = l; i >= 0; i--)
if (!Parent(up[a][i], b)) a = up[a][i];
return up[a][0];
}The main part of the program. Read the number of vertices in the tree.
scanf("%d",&n);Compute — the smallest number such that 2^l > n. The depth of any vertex is less than , so jumps of length 2^l, 2^{l-1}, \ldots, 1 are enough to lift to any height. For n \le 150000 we get l \le 18, and each row of the array has enough room for columns 0, 1, \ldots, l.
l = 1;
while ((1 << l) <= n) l++;Read the edges and store the tree in the adjacency list .
for(i = 0; i < n - 1; i++)
{
scanf("%d %d %d",&u,&v,&w);
g[u].push_back({v,w});
g[v].push_back({u,w});
}Run the depth-first search from the root of the tree — vertex . Time is counted starting from .
timer = 1;
dfs(0);Process the queries. For each pair of vertices and , find their lowest common ancestor and print the distance \mathit{res} = \mathit{dist}[u] - \mathit{dist}[\mathit{lca}] + \mathit{dist}[v] - \mathit{dist}[\mathit{lca}].
scanf("%d",&m);
for(i = 0; i < m; i++)
{
scanf("%d %d",&u,&v);
lca = LCA(u, v);
res = dist[u] - dist[lca] + dist[v] - dist[lca];
printf("%d\n",res);
}