CSES Solutions - Distance Queries
Last Updated :
03 Dec, 2024
Given a tree consisting of n nodes. The task is to process q queries of the form: What is the distance between nodes a and b?
Examples:
Input: n = 5, q = 2, edges = {{1, 2}, {1, 3}, {3, 4}, {3, 5}}, queries = {{1, 3}, {2, 5}}
Output: 1 3 2
Explanation:
- The distance between node 1 and 3 is 1.
- The distance between node 2 and 5 is 3.
Input: n = 3, q = 2, edges = {{1, 2}, {1, 3}}, queries = {{1, 2}, {2, 3}}
Output: 1 2
Explanation:
- The distance between node 1 and 2 is 1.
- The distance between node 2 and 3 is 2.
Approach: To solve the problem, follow the idea below:
The idea is in the observation that there is exactly one path between any two nodes a and b in the tree, and this path goes through the Lowest Common Ancestor (LCA) of the two nodes. The first step is to calculate the depth of all nodes in the tree. This can be done using a Depth-First Search (DFS) algorithm. The depth of each node is stored in an array called level. The next step is to calculate the LCA of the two nodes. This can be done by Binary Lifting. The idea is to precompute an array up[][] where up[i][j] is the 2j-th ancestor of node i. With this precomputed array, the LCA of two nodes can be found in logarithmic time.
Finally, the distance between two nodes a and b can be calculated using the formula: level[a] + level[b] - 2 * level[LCA(a,b)]. This formula works because the sum of the depths of nodes a and b includes the depth of their LCA twice, so we subtract it out to get the correct distance.
Below is the implementation of the algorithm:
C++
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 200111;
const int N = 20;
vector<int> adj[MAXN];
// up[i][j] is the 2^j-th ancestor of node i, level[i] is
// the depth of node i
int up[MAXN][N], level[MAXN];
// Depth-First Search (DFS) to calculate the depth of each
// node and initialize the first ancestor
void dfs(int node, int parent, int lv)
{
// Set the level (depth) of the current node
level[node] = lv;
// Set the first ancestor of the current node
up[node][0] = parent;
for (auto child : adj[node]) {
if (child != parent) {
// If the child is not the parent, continue the
// DFS
dfs(child, node, lv + 1);
}
}
}
// Preprocess to calculate the 2^j-th ancestor for each node
// using binary lifting
void prep(int n)
{
// Start DFS from node 1 (assuming 1-based index)
dfs(1, -1, 0);
for (int j = 1; j < N; j++) {
for (int i = 1; i <= n; i++) {
// If the (j-1)-th ancestor exists
if (up[i][j - 1] != -1) {
// Set the j-th ancestor using (j-1)-th
// ancestors
up[i][j] = up[up[i][j - 1]][j - 1];
}
else {
up[i][j] = -1;
}
}
}
}
// Function to find the Lowest Common Ancestor (LCA) of
// nodes a and b
int LCA(int a, int b){
// Ensure b is the deeper node
if (level[b] < level[a])
swap(a, b);
int d = level[b] - level[a];
// Bring b to the same level as a
while (d) {
int i = log2(d);
b = up[b][i];
d -= (1 << i);
}
if (a == b)
return a;
// Binary lifting to find the LCA
for (int i = N - 1; i >= 0; i--) {
if (up[a][i] != -1 && up[a][i] != up[b][i]) {
a = up[a][i];
b = up[b][i];
}
}
// Return the parent of a (or b) which is the LCA
return up[a][0];
}
vector<int> distance(vector<pair<int, int> >& edges,
vector<pair<int, int> >& queries,
int n, int q)
{
vector<int> dist;
for (int i = 0; i < n - 1; i++) {
int a = edges[i].first, b = edges[i].second;
// Add edge a-b
adj[a].push_back(b);
// Add edge b-a (since the tree is undirected)
adj[b].push_back(a);
}
// Root's parent is set to -
up[1][0] = -1;
// Root's level is set to 0
level[1] = 0;
// Preprocess the tree for LCA queries
prep(n);
for (int i = 0; i < q; i++) {
int a = queries[i].first, b = queries[i].second;
// Calculate the distance between a and b
dist.push_back(level[a] + level[b]
- 2 * level[LCA(a, b)]);
}
return dist;
}
int main()
{
int n = 5, q = 3;
vector<pair<int, int> > edges
= { { 1, 2 }, { 1, 3 }, { 3, 4 }, { 3, 5 } };
vector<pair<int, int> > queries
= { { 1, 3 }, { 2, 5 } };
vector<int> dist = distance(edges, queries, n, q);
for (int i = 0; i < q; i++)
cout << dist[i] << " ";
return 0;
}
Time Complexity: O(q * log(n)), where n is the number of nodes and q is the number of queries.
Auxiliary Space: O(n * log(n)), where n is the number of nodes.
Similar Reads
CSES Solutions â Tree Distances I Given a tree consisting of n nodes (1,2,...,n) and n-1 lines describing the edges between nodes u and v. The task is to determine for each node the maximum distance to another node. Example: Input: n= 5, v= {{1,2}, {1,3}, {3,4}, {3,5}} Output: 2 3 2 3 3 Explanation: TreeThe farthest node from node 1
11 min read
CSES Solutions - Minimum Euclidean Distance Given a set of points in the two-dimensional plane, your task is to find the minimum Euclidean distance between two distinct points.The Euclidean distance of points (x1,y1) and (x2,y2) is sqrt( (x1-x2)2 + (y1-y2)2 )Example:Input: points = {{2, 1} ,{4, 4} ,{1, 2} ,{6, 3}};Output: 2Input: points = {{2
7 min read
Distance Between Two Points Distance Between Two Points is the length of line segment that connects any two points in a coordinate plane in coordinate geometry. It can be calculated using a distance formula for 2D or 3D. It represents the shortest path between two locations in a given space.In this article, we will learn how t
6 min read
How to Calculate Distance Distance is a fundamental concept in mathematics and physics, representing the extent of space between two points, lines, or planes. It's a crucial metric used in various fields, including navigation, physics, engineering, and everyday life. Calculating distance accurately is essential for solving p
6 min read
POTD Solutions | 02 Novâ 23 | Minimum distance between two numbers View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Arrays but will also help you build up problem-solving
5 min read