26 using System.Collections.Generic;
55 public sealed
class Prim<TCost>
56 where TCost : IComparable<TCost>
58 public IGraph Graph {
get;
private set; }
59 public Func<Arc, TCost> Cost {
get;
private set; }
62 public HashSet<Arc> Forest {
get;
private set; }
64 public Subgraph ForestGraph {
get;
private set; }
66 public Prim(
IGraph graph, Func<Arc, TCost> cost)
70 Forest =
new HashSet<Arc>();
72 ForestGraph.EnableAllArcs(
false);
77 public Prim(
IGraph graph, Dictionary<Arc, TCost> cost)
78 : this(graph, arc => cost[arc])
85 PriorityQueue<Node, TCost> priorityQueue =
new PriorityQueue<Node, TCost>();
86 HashSet<Node> processed =
new HashSet<Node>();
87 Dictionary<Node, Arc> parentArc =
new Dictionary<Node, Arc>();
91 foreach (var c
in components.Components)
93 Node root = c.First();
95 foreach (var arc
in Graph.Arcs(root))
97 Node v = Graph.Other(arc, root);
99 priorityQueue[v] = Cost(arc);
104 while (priorityQueue.Count != 0)
106 Node n = priorityQueue.Peek();
109 Arc arcToAdd = parentArc[n];
110 Forest.Add(arcToAdd);
111 ForestGraph.Enable(arcToAdd,
true);
113 foreach (var arc
in Graph.Arcs(n))
116 if (processed.Contains(v))
continue;
118 TCost arcCost = Cost(arc);
120 bool vInPriorityQueue = priorityQueue.TryGetPriority(v, out vCost);
121 if (!vInPriorityQueue || arcCost.CompareTo(vCost) < 0)
123 priorityQueue[v] = arcCost;
152 public sealed
class Kruskal<TCost>
153 where TCost : IComparable<TCost>
156 public IGraph Graph {
get;
private set; }
158 public Func<Arc, TCost> Cost {
get;
private set; }
164 public Func<Node, int> MaxDegree {
get;
private set; }
169 public HashSet<Arc> Forest {
get;
private set; }
173 public Dictionary<Node, int> Degree {
get;
private set; }
175 private IEnumerator<Arc> arcEnumerator;
176 private int arcsToGo;
177 private DisjointSet<Node> components;
179 public Kruskal(
IGraph graph, Func<Arc, TCost> cost, Func<Node, int> maxDegree = null)
183 MaxDegree = maxDegree;
185 Forest =
new HashSet<Arc>();
187 ForestGraph.EnableAllArcs(
false);
188 Degree =
new Dictionary<Node, int>();
189 foreach (var node
in Graph.Nodes()) Degree[node] = 0;
191 List<Arc> arcs = Graph.Arcs().ToList();
192 arcs.Sort((a, b) => Cost(a).CompareTo(Cost(b)));
193 arcEnumerator = arcs.GetEnumerator();
195 components =
new DisjointSet<Node>();
198 public Kruskal(
IGraph graph, Dictionary<Arc, TCost> cost)
199 : this(graph, arc => cost[arc], null)
208 if (arcsToGo <= 0 || arcEnumerator == null || !arcEnumerator.MoveNext())
210 arcEnumerator = null;
214 AddArc(arcEnumerator.Current);
228 public bool AddArc(
Arc arc)
230 var u = Graph.U(arc);
231 if (MaxDegree != null && Degree[u] >= MaxDegree(u))
return false;
232 DisjointSetSet<Node> x = components.WhereIs(u);
234 var v = Graph.V(arc);
235 if (MaxDegree != null && Degree[v] >= MaxDegree(v))
return false;
236 DisjointSetSet<Node> y = components.WhereIs(v);
238 if (x == y)
return false;
241 ForestGraph.Enable(arc,
true);
242 components.Union(x, y);