public void TwoValueTest() { PairingHeap <int> pairingHeap = new PairingHeap <int>((x, y) => x > y); pairingHeap.Insert(10); pairingHeap.Insert(-2); var value = pairingHeap.ExtractMinimum(); Assert.Equal(-2, value.value); value = pairingHeap.ExtractMinimum(); Assert.Equal(10, value.value); }
public static (bool connected, Graph tree) Prim(this Graph g, int startingVertex = 0) { if (g.Directed) { throw new WrongGraphException("Graph must be an undirected graph"); } if (startingVertex < 0 || startingVertex >= g.VerticesCount) { throw new ArgumentOutOfRangeException("startingVertex"); } Graph tree = g.IsolatedGraph(g.Directed); PairingHeap <Edge> queue = new PairingHeap <Edge>((x, y) => x.Weight > y.Weight); UnionFind unionFind = new UnionFind(g.VerticesCount); foreach (var e in g.GetEdgesFrom(startingVertex)) { queue.Insert(e); } int c = 0; while (true) { if (queue.IsEmpty() || c == g.VerticesCount - 1) { return(c == g.VerticesCount - 1 ? true : false, tree); } var e = queue.ExtractMinimum(); if (unionFind.FindParent(e.value.From) != unionFind.FindParent(e.value.To)) { tree.AddEdge(e.value); unionFind.Union(e.value.From, e.value.To); foreach (var f in g.GetEdgesFrom(e.value.To)) { queue.Insert(f); } c++; } } }
public void NValueTest(int n) { PairingHeap <int> pairingHeap = new PairingHeap <int>((x, y) => x > y); List <int> lista = new List <int>(); Random random = new Random(); for (int i = 0; i < n; i++) { int value = random.Next() % n * (0 == random.Next() % 2 ? -1 : 1); lista.Add(value); pairingHeap.Insert(value); } lista.Sort(); for (int i = 0; i < n; i++) { var value = pairingHeap.ExtractMinimum(); Assert.Equal(lista[i], value.value); } }
public static (bool connected, Graph tree) Kruskal(this Graph g) { if (g.Directed) { throw new WrongGraphException("Graph must be an undirected graph"); } Graph tree = g.IsolatedGraph(g.Directed); PairingHeap <Edge> queue = new PairingHeap <Edge>((x, y) => x.Weight > y.Weight); UnionFind unionFind = new UnionFind(g.VerticesCount); for (int i = 0; i < g.VerticesCount; i++) { foreach (var e in g.GetEdgesFrom(i)) { queue.Insert(e); } } int c = 0; while (true) { if (queue.IsEmpty() || c == g.VerticesCount - 1) { return(c == g.VerticesCount - 1 ? true : false, tree); } var e = queue.ExtractMinimum(); if (unionFind.FindParent(e.value.From) != unionFind.FindParent(e.value.To)) { tree.AddEdge(e.value); unionFind.Union(e.value.From, e.value.To); c++; } } }