Lowest Common Ancestor (boost graph)
Is there a built-in method in boost to find the lowest common ancestor of two or more nodes in a tree (which is a boost::graph instance)?
If not, I would appreciate suggestions on the best way to do this. Wikipedia claims there are efficient algorithm to achieve this in O(1)开发者_运维百科 time (with O(n) pre-processing), but it doesn't describe the algorithms.
Found the algorithm in Wikipedia:
function TarjanOLCA(u)
MakeSet(u);
u.ancestor := u;
for each v in u.children do
TarjanOLCA(v);
Union(u,v);
Find(u).ancestor := u;
u.colour := black;
for each v such that {u,v} in P do
if v.colour == black
print "Tarjan's Least Common Ancestor of " + u +
" and " + v + " is " + Find(v).ancestor + ".";
I have found the following site which may answer your question : http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=lowestCommonAncestor#Lowest%20Common%20Ancestor%20%28LCA%29
The basic idea is to convert the "Lowest Common Ancestor" question into another one, "Range Minimum Query", then to use a O(N)+O(1) approach to solve the problem. I have not looked into it thoroughly but it seems pretty well documented and worth having a look.
精彩评论