Академический Документы
Профессиональный Документы
Культура Документы
tree, no parent pointers are given. The distance between two nodes is the minimum
number of edges to be traversed to reach one node from other.
It has been already discussed in this for a single query in O(logn) time, here the
task is to reduce multiple queries time to O(1) by compromising with space
complexity to O(Nlogn). In this post, we will use Sparse table instead of segment
tree for finding the minimum in given range, which uses dynamic programming and bit
manipulation to achieve O(1) query time.
A sparse table will preprocess the minimum values given for an array in Nlogn space
i.e. each node will contain chain of values of log(i) length where i is the index
of the ith node in L array. Each entry in the sparse table says M[i][j] will
represent the index of the minimum value in the subarray starting at i having
length 2^j.
The distance between two nodes can be obtained in terms of lowest common ancestor.
Finally, apply distance formula discussed above to get the distance between two
nodes.
#include <bits/stdc++.h>
#define MAX 100001
using namespace std;
// Mark it visited
vis[Euler[i]] = 1;
}
}
}
else
return M[b - (1 << j) + 1][j];
}
// Swap if low>high
if (n2 < n1)
swap(n1, n2);
// Store Levels
FindLevels(root);
return 0;
}