V
- the graph vertex typeE
- the graph edge typepublic class TarjanLCAFinder<V,E> extends Object implements LowestCommonAncestorAlgorithm<V>
See the article on wikipedia for more information on the algorithm.
The original algorithm can be found in Gabow, H. N.; Tarjan, R. E. (1983), "A linear-time algorithm for a special case of disjoint set union", Proceedings of the 15th ACM Symposium on Theory of Computing (STOC), pp. 246–251, doi:10.1145/800061.808753
Preprocessing Time complexity: $O(1)$
Preprocessing Space complexity: $O(1)$
Query Time complexity: $O(|V| log^{*}(|V|) + |Q|)$ where $|Q|$ is the number of queries
Query Space complexity: $O(|V| + |Q|)$ where $|Q|$ is the number of queries
For small (i.e. less than 100 vertices) trees or forests, all implementations behave similarly.
For larger trees/forests with less than 50,000 queries you can use either
BinaryLiftingLCAFinder
, HeavyPathLCAFinder
or EulerTourRMQLCAFinder
. Fo
more than that use EulerTourRMQLCAFinder
since it provides $O(1)$ per query.
Space-wise, HeavyPathLCAFinder
and TarjanLCAFinder
only use a linear amount while
BinaryLiftingLCAFinder
and EulerTourRMQLCAFinder
require linearithmic space.
For DAGs, use NaiveLCAFinder
.
Constructor and Description |
---|
TarjanLCAFinder(Graph<V,E> graph,
Set<V> roots)
Construct a new instance of the algorithm.
|
TarjanLCAFinder(Graph<V,E> graph,
V root)
Construct a new instance of the algorithm.
|
Modifier and Type | Method and Description |
---|---|
List<V> |
getBatchLCA(List<Pair<V,V>> queries)
Return a list of LCAs for a batch of queries
|
V |
getLCA(V a,
V b)
Return the LCA of a and b
|
Set<V> |
getLCASet(V a,
V b)
Note: This operation is not supported.
Return the computed set of LCAs of a and b |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
getBatchLCASet
public TarjanLCAFinder(Graph<V,E> graph, V root)
Note: The constructor will NOT check if the input graph is a valid tree.
graph
- the input graphroot
- the root of the graphpublic TarjanLCAFinder(Graph<V,E> graph, Set<V> roots)
Note: If two roots appear in the same tree, an error will be thrown.
Note: The constructor will NOT check if the input graph is a valid forest.
graph
- the input graphroots
- the set of roots of the graphpublic V getLCA(V a, V b)
getLCA
in interface LowestCommonAncestorAlgorithm<V>
a
- the first element to find LCA forb
- the other element to find the LCA forpublic List<V> getBatchLCA(List<Pair<V,V>> queries)
getBatchLCA
in interface LowestCommonAncestorAlgorithm<V>
queries
- a list of pairs of verticespublic Set<V> getLCASet(V a, V b)
getLCASet
in interface LowestCommonAncestorAlgorithm<V>
a
- the first element to find LCA forb
- the other element to find the LCA forUnsupportedOperationException
- if the method is calledCopyright © 2018. All rights reserved.