1 //===- llvm/Analysis/MaximumSpanningTree.h - Interface ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This module privides means for calculating a maximum spanning tree for a
11 // given set of weighted edges. The type parameter T is the type of a node.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_MAXIMUMSPANNINGTREE_H
16 #define LLVM_ANALYSIS_MAXIMUMSPANNINGTREE_H
18 #include "llvm/ADT/EquivalenceClasses.h"
24 /// MaximumSpanningTree - A MST implementation.
25 /// The type parameter T determines the type of the nodes of the graph.
27 class MaximumSpanningTree
{
29 // A comparing class for comparing weighted edges.
30 template <typename CT
>
31 struct EdgeWeightCompare
{
32 bool operator()(typename MaximumSpanningTree
<CT
>::EdgeWeight X
,
33 typename MaximumSpanningTree
<CT
>::EdgeWeight Y
) const {
34 if (X
.second
> Y
.second
) return true;
35 if (X
.second
< Y
.second
) return false;
41 typedef std::pair
<const T
*, const T
*> Edge
;
42 typedef std::pair
<Edge
, double> EdgeWeight
;
43 typedef std::vector
<EdgeWeight
> EdgeWeights
;
45 typedef std::vector
<Edge
> MaxSpanTree
;
50 static char ID
; // Class identification, replacement for typeinfo
52 /// MaximumSpanningTree() - Takes a vector of weighted edges and returns a
54 MaximumSpanningTree(EdgeWeights
&EdgeVector
) {
56 std::stable_sort(EdgeVector
.begin(), EdgeVector
.end(), EdgeWeightCompare
<T
>());
58 // Create spanning tree, Forest contains a special data structure
59 // that makes checking if two nodes are already in a common (sub-)tree
61 EquivalenceClasses
<const T
*> Forest
;
62 for (typename
EdgeWeights::iterator EWi
= EdgeVector
.begin(),
63 EWe
= EdgeVector
.end(); EWi
!= EWe
; ++EWi
) {
64 Edge e
= (*EWi
).first
;
66 Forest
.insert(e
.first
);
67 Forest
.insert(e
.second
);
70 // Iterate over the sorted edges, biggest first.
71 for (typename
EdgeWeights::iterator EWi
= EdgeVector
.begin(),
72 EWe
= EdgeVector
.end(); EWi
!= EWe
; ++EWi
) {
73 Edge e
= (*EWi
).first
;
75 if (Forest
.findLeader(e
.first
) != Forest
.findLeader(e
.second
)) {
76 Forest
.unionSets(e
.first
, e
.second
);
77 // So we know now that the edge is not already in a subtree, so we push
78 // the edge to the MST.
84 typename
MaxSpanTree::iterator
begin() {
88 typename
MaxSpanTree::iterator
end() {
93 } // End llvm namespace