There is exactly one path between any two cities, so the road network forms a tree. Let us root it at the capital — vertex . Denote by the distance from the capital to vertex , that is, its depth in the tree.
Each hero has to get to the root. Turning off one's own path to the capital is never profitable: any detour only increases the hero's own expenses. Therefore, Chip travels along the unique path from to the root, and Dale along the path from to the root.
The paths from and to the root merge at the lowest common ancestor \mathit{lca} = \mathit{LCA}(c, d) and coincide from there on. Up to vertex each of them rides alone and pays the full fare, and from to the capital they ride together and split the fare in half. We get:
The formulas also hold in special cases:
if is an ancestor of , then \mathit{lca} = c: Dale picks Chip up on the way;
if c = d, then \mathit{lca} = c, and the heroes ride the whole way together;
if \mathit{lca} = 1, there is no shared part, and each hero pays \mathit{dist}[v] \cdot \mathit{Price}.
We find the lowest common ancestor using the binary lifting method. A 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][k] — the ancestor of vertex located 2^k levels higher. Then the LCA of two vertices is found in O(\log n).
Complexity. Building the ancestor table takes O(n \log n) time and memory, and each query is processed in O(\log n). The total complexity is O((n + q) \log n).
Recursion depth. If the tree is a chain, the recursion depth of the dfs function reaches 10^5. The stack is usually large enough for this.
Example
In the sample, the tree consists of the capital and cities and connected to it by roads, \mathit{Price} = 2. We have \mathit{dist}[1] = 0, \mathit{dist}[2] = \mathit{dist}[3] = 1.
Query : \mathit{lca} = 1, there is no shared part. Each hero travels km and pays 1 \cdot 2 = 2. The answer is .
Query : \mathit{lca} = 1, Chip is already in the capital and pays nothing, Dale pays 1 \cdot 2 = 2. The answer is . Query is handled in the same way.
In the sample from the statement, the heroes never ride together. Consider a tree with a shared part: Chip is in city , Dale is in city , \mathit{Price} = 2.
The lowest common ancestor is \mathit{lca} = 2, \mathit{dist}[\mathit{lca}] = 1. Chip rides km alone, Dale rides km alone, and then they ride the remaining km to the capital together. Chip's expenses are (1 + 1 / 2) \cdot 2 = 3, Dale's expenses are (2 + 1 / 2) \cdot 2 = 5.
Algorithm Implementation
To find the lowest common ancestor (LCA), we use the binary lifting method. The tree is stored as adjacency lists . Declare the global arrays:
— the entry time of vertex during the depth-first search;
— the exit time of vertex during the depth-first search;
— the distance from the root to vertex ;
\mathit{up}[v][k] — the 2^k-th ancestor of vertex .
#define MAX 100010
#define LOGMAX 18
vector<int> g[MAX];
int timer, d[MAX], f[MAX], dist[MAX];
int up[MAX][LOGMAX];The dfs function performs a depth-first search from vertex . The parameter is the parent of vertex , and is the distance from the capital to . On entering the vertex, we record its entry time .
void dfs (int v, int p = 1, int len = 0)
{
d[v] = timer++;Store the immediate parent of vertex .
up[v][0] = p;Store the distance from the root (the capital) to vertex .
dist[v] = len;Fill the binary ancestor table: the 2^i-th ancestor of vertex is the 2^{i-1}-th ancestor of its 2^{i-1}-th ancestor. For the root, the parameter equals by default, so the capital is its own parent. Therefore, any jump above the root stops at vertex .
for (int i = 1; i <= l; i++)
up[v][i] = up[up[v][i-1]][i-1];Iterate over the neighbors of vertex . All of them except the parent are children of and lie at distance \mathit{len} + 1 from the capital. After all children are processed, record the exit time .
for (int to : g[v])
if (to != p) dfs (to, v, len + 1);
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 . If one of the vertices is an ancestor of the other, it is the answer. Otherwise, we 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 cities and the cost of one kilometer.
scanf("%d %d",&n,&Price);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 10^5 we get l \le 17 < \mathit{LOGMAX}.
l = 1;
while ((1 << l) <= n) l++;Read the roads and build an undirected graph, which is a tree by the problem statement.
for(i = 0; i < n - 1; i++)
{
scanf("%d %d",&x,&y);
g[x].push_back(y);
g[y].push_back(x);
}Run a depth-first search from the capital — vertex . It computes the distances , the timestamps , , and the ancestor table . Time is counted starting from .
timer = 1;
dfs(1);Read and process the queries one by one. For each query, find the lowest common ancestor of cities and .
scanf("%d",&q);
for(i = 0; i < q; i++)
{
scanf("%d %d",&x,&y);
lca = LCA(x, y);Vertex is the city where Chip and Dale meet. Before the meeting, Chip rides \mathit{dist}[x] - \mathit{dist}[\mathit{lca}] km alone, and Dale rides \mathit{dist}[y] - \mathit{dist}[\mathit{lca}] km alone. They ride the remaining km to the capital together.
Chip = dist[x] - dist[lca];
Deil = dist[y] - dist[lca];Each hero pays the full cost of his own part and half the cost of the shared part. Print the expenses of Chip and Dale with five digits after the decimal point.
printf("%.5lf %.5lf\n", (Chip + dist[lca] / 2.0) * Price,
(Deil + dist[lca] / 2.0) * Price);
}