public void TestIndexMinHeap() { int n = 1000000; Random random = new Random(); var heap = new IndexMinHeap <int>(n); for (int i = 0; i < n; i++) { heap.Add((int)(random.Next() * n)); } var arr = new int[n]; for (var i = 0; i < n; i++) { arr[i] = heap.ExtractMin(); } var success = true; for (var i = 1; i < n; i++) { if (arr[i - 1] > arr[i]) { success = false; } } Assert.AreEqual(true, success); }
public PrimMST(IGraph <TWeight> graph) { G = graph; ipq = new IndexMinHeap <TWeight>(G.V); marked = new bool[G.V]; MSTEdges = new List <Edge <TWeight> >(); EdgeTo = new Edge <TWeight> [G.V]; // Prim Visit(0); while (!ipq.IsEmpty()) { var v = ipq.ExtractMinIndex(); if (EdgeTo[v] == null) { continue; } MSTEdges.Add(EdgeTo[v]); Visit(v); } var value = 0.0; var converter = TypeDescriptor.GetConverter(typeof(TWeight)); foreach (var edge in MSTEdges) { value += (double)converter.ConvertTo(edge.Weight, typeof(double)); } MSTWeight = (TWeight)converter.ConvertTo(value, typeof(TWeight)); }
public void IndexMinHeap_RemoveFirst(IntHeapItem[] items) { //Create the heap and add the items. var heap = new IndexMinHeap <IntHeapItem>(items); for (var i = 0; i < items.Length; i++) { heap.Add(i); } //Check if the items are in the correct order. var previousValue = int.MinValue; for (var i = 0; i < items.Length; i++) { var value = items[heap.RemoveFirst()].Value; if (value >= previousValue) { previousValue = value; } else { Assert.Fail($"Value {value} is smaller than previous value {previousValue}"); } } }
public void SetupAdd() { _values = new IntHeapItem[Capacity]; for (int i = 0; i < _values.Length; i++) { _values[i] = new IntHeapItem(i * 2); } _addMinHeap = new IndexMinHeap <IntHeapItem>(_values); }
public void SetupContains() { _values = new IntHeapItem[Capacity]; for (int i = 0; i < _values.Length; i++) { _values[i] = new IntHeapItem(i * 2); } _containsMinHeap = new IndexMinHeap <IntHeapItem>(_values); _containsMinHeap.Add(5); }
public void IndexMinHeap_CorrectCapacity(IntHeapItem[] items) { //Create the heap and add the items. var heap = new IndexMinHeap <IntHeapItem>(items); for (var i = 0; i < items.Length; i++) { heap.Add(i); } Assert.AreEqual(items.Length, heap.Capacity); }
//测试是否改变某个堆中某个数字只需要,对该数字ShiftUP 和shiftDown即可 public void testChangeInIndexHeap(IndexMinHeap <int> minIndexHeap) { print("改变前"); minIndexHeap.print(); int index = Random.Range(1, minIndexHeap.Size()); int item = 10; minIndexHeap.Change(index, 10); print("改变后,改变第" + index + "元素,改为" + item); minIndexHeap.print(); }
public void SetupRemoveFirst() { _values = new IntHeapItem[Capacity]; for (int i = 0; i < _values.Length; i++) { _values[i] = new IntHeapItem(i * 2); } _removeFirstMinHeap = new IndexMinHeap <IntHeapItem>(_values); for (int i = 0; i < _removeFirstMinHeap.Capacity; i++) { _removeFirstMinHeap.Add(i); } }
public Dijkstra(WeightSpareGraph <float> graph, int src) { Debug.Assert(src >= 0 && src < graph.V()); this.src = src; this.graph = graph; this.n = graph.V(); this.m = graph.E(); shortPath = new float[n]; book = new bool[n]; from = new int[n]; for (int i = 0; i != n; i++) { book [i] = false; from [i] = -1; //假设都是可达的 } from [src] = -1; shortPath [src] = 0f; IndexMinHeap <float> indexMinHeap = new IndexMinHeap <float> (n); indexMinHeap.Insert(src, shortPath[src]); while (indexMinHeap.Size() != 0) { int u = indexMinHeap.ExtraMinItemIndex(); book [u] = true; WeightSpareGraph <float> .adjIterator iter = new WeightSpareGraph <float> .adjIterator(graph, u); for (Edge <float> e = iter.begin(); !iter.isEnd(); e = iter.Next()) { int v = e.Other(u); if (!book[v]) { if (from [v] == -1 || shortPath [v] > shortPath [u] + e.weight) { from [v] = u; shortPath [v] = shortPath [u] + e.weight; if (indexMinHeap.isContain(v)) { indexMinHeap.Change(v, shortPath [v]); } else { indexMinHeap.Insert(v, shortPath[v]); } } } } } }
public void IndexMinHeap_Contains_False(IntHeapItem[] items) { //Create the heap and add the items except the last one. var heap = new IndexMinHeap <IntHeapItem>(items); for (var i = 0; i < items.Length - 1; i++) { heap.Add(i); } //Check if the last one returns false var item = items[items.Length - 1]; Assert.IsFalse(heap.Contains(items.Length - 1), $"Contains returned true for item {item}"); }
public DijkstraSP(EdgeWeightDirectedGraph g, int s) { m_edgeTo = new DirectedEdge[g.V()]; m_distTo = new double[g.V()]; m_pq = new IndexMinHeap <double>(g.V()); for (int v = 0; v < g.V(); ++v) { m_distTo[v] = Double.PositiveInfinity; } m_distTo[s] = 0; m_pq.insert(s, 0); while (!m_pq.isEmpty()) { Relax(g, m_pq.delMin()); } }
public void IndexMinHeap_Contains_True(IntHeapItem[] items) { //Create the heap and add the items. var heap = new IndexMinHeap <IntHeapItem>(items); for (var i = 0; i < items.Length; i++) { heap.Add(i); } //Check if all added items are contained in the heap. for (var i = 0; i < items.Length; i++) { Assert.IsTrue(heap.Contains(i), $"Contains returned false for item {items[i]}"); } }
public void IndexMinHeap_CheckHeapCondition(IntHeapItem[] items) { //Create the heap and add the items. var heap = new IndexMinHeap <IntHeapItem>(items); for (int i = 0; i < items.Length; i++) { heap.Add(i); } var indexes = heap.Select(i => items[i]).ToArray(); for (int i = 0; i < items.Length; i++) { CheckHeapCondition(indexes, i); } }
public PrimMST(EdgeWeightedGraph g) { m_edgeTo = new Edge[g.V()]; m_distTo = new double[g.V()]; m_marked = new bool[g.V()]; for (int v = 0; v < g.V(); ++v) { m_distTo[v] = Double.PositiveInfinity; } m_pq = new IndexMinHeap <double>(g.V()); m_distTo[0] = 0.0d; m_pq.insert(0, 0.0d); while (!m_pq.isEmpty()) { Visit(g, m_pq.delMin()); } }
public void IndexMinHeap_RemoveFirst_LIFO() { var items = new[] { new IntHeapItem(1), new IntHeapItem(1), new IntHeapItem(1) }; //Create the heap and add the items. var heap = new IndexMinHeap <IntHeapItem>(items); for (var i = 0; i < items.Length; i++) { heap.Add(i); } //Check if the elements are returned in LIFO order for (var i = items.Length - 1; i >= 0; i--) { var index = heap.RemoveFirst(); Assert.IsTrue(index == i); } }
public void IndexMinHeap_Enumerate(IntHeapItem[] items) { //Create the heap and add the items. var heap = new IndexMinHeap <IntHeapItem>(items); var addedIndexes = new List <int>(); for (var i = 0; i < items.Length; i++) { heap.Add(i); addedIndexes.Add(i); } Assert.AreEqual(items.Length, heap.Count); //Check if the added indexes are returned when enumerating var enumeratedHeap = heap.ToArray(); Assert.AreEqual(items.Length, enumeratedHeap.Length); CollectionAssert.AreEquivalent(addedIndexes, enumeratedHeap); }
public void IndexMinHeap_Contains_AddAndRemoveAll(IntHeapItem[] items) { //Create the heap and add the items except the last one. var heap = new IndexMinHeap <IntHeapItem>(items); for (var i = 0; i < items.Length; i++) { heap.Add(i); } while (heap.Count > 0) { heap.RemoveFirst(); } for (var i = 0; i < items.Length; i++) { Assert.IsFalse(heap.Contains(i), $"Contains returned true for index {i}"); } }
// X - set of explored vertices of graph G // V-X - set of unexplored vertices of graph G // // Invariant. // The key of a vertex w belongs to V-X is the min Dijkstra score of an edge with tail v belongs to X // and head w, or +infinity if no such edge exists. // key(w) = min len(v) + l(vw) // // DijkstraSearch(graph G, vertex s): // // Initialization // X = empty set // H = empty min heap // key(s) = 0 // for each vertex V in G.vertices do: key(V) = +infinity // for each vertex V in G.vertices do: H.Insert(V) // // Main loop // while H is not empty do: // w* = H.ExtractMin() // X.Add(w*) // len(w*) = key(w*) // // Update Heap to maintain Invariant // for every edge(w*, y) do: // H.Delete(y) // Delete: given a heap H and a pointer to an object y in H, delete y from H. // key(y) = min {key(y), len(w*) + l(w*y)} // H.Insert(y) public static int[] DijkstraMinHeap(IDirectedWeightedGraph <int> weightedGraph, int startVertex) { var minHeap = new IndexMinHeap <int>(weightedGraph.VerticesCount); var exploredVertices = new HashSet <int> { startVertex }; var len = new int[weightedGraph.VerticesCount + 1]; for (int i = 1; i <= weightedGraph.VerticesCount; i++) { var score = i == startVertex ? 0 : 1000000; len[i] = score; minHeap.Insert(i, score); } while (!minHeap.IsEmpty()) { int u = minHeap.GetMin(); len[u] = minHeap.GetItemKey(u); minHeap.ExtractMin(); exploredVertices.Add(u); foreach ((int v, int weight) in weightedGraph.GetAdjacentVertices(u)) { if (!exploredVertices.Contains(v)) { if (len[v] > len[u] + weight) { int vKey = minHeap.GetItemKey(v); int newScore = Math.Min(len[u] + weight, vKey); // can use (minHeap.Delete + minHeap.Insert) instead of DecreaseKey // but this would be less effective minHeap.DecreaseKey(v, newScore); len[v] = newScore; } } } } return(len); }
public PrimMST(WeightSpareGraph <float> graph) { this.graph = graph; this.n = graph.V(); this.m = graph.E(); minSpanTreeValue = 0; book = new bool[n]; toEdgeArr = new List <Edge <float> >(); for (int i = 0; i != n; i++) { toEdgeArr.Add(null); } for (int i = 0; i != n; i++) { book [i] = false; } indexMinHeap = new IndexMinHeap <float> (m); book [0] = true; visit(0); while (indexMinHeap.Size() != 0) { int index = indexMinHeap.ExtraMinItemIndex(); Debug.Assert(toEdgeArr[index] != null); book[index] = true; visit(index); // int u = toEdgeArr [index].U (); // int v = toEdgeArr [index].V (); // if (book [u] && !book [v]) { // book [v] = true; // visit (v); // } else if(!book [u] && book [v]){ // book [u] = true; // visit (u); // } } for (int i = 1; i != n; i++) { minSpanTreeValue += toEdgeArr [i].weight; } }
public KruskalMST(IGraph <TWeight> graph) { G = graph; ipq = new IndexMinHeap <Edge <TWeight> >(2 * G.E); marked = new bool[G.V]; MSTEdges = new List <Edge <TWeight> >(); for (var i = 0; i < G.V; i++) { foreach (Edge <TWeight> e in G.GetAdjIterator(i)) { ipq.Add(e); } } var uf = new UnionFind(G.V); while (!ipq.IsEmpty() && MSTEdges.Count < graph.V - 1) { var e = ipq.ExtractMin(); if (uf.IsConnected(e.V, e.W)) { continue; } MSTEdges.Add(e); uf.UnionElements(e.V, e.W); } var value = 0.0; var converter = TypeDescriptor.GetConverter(typeof(TWeight)); foreach (var edge in MSTEdges) { value += (double)converter.ConvertTo(edge.Weight, typeof(double)); } MSTWeight = (TWeight)converter.ConvertTo(value, typeof(TWeight)); }
public DijkstraAlgorithm(int amountOfNodes) { _openSet = new IndexMinHeap <DijkstraNode>(amountOfNodes); _closedSet = new LookupArray(amountOfNodes); }
static void Main(string[] args) { // 使用两种图的储存方式来读取文件 string fileName = "TextG1.txt"; SparseGraph graph = new SparseGraph(13, false); ReadGraph readGraph = new ReadGraph(graph, fileName); Console.WriteLine("test g1 in sparse graph "); graph.Show(); Console.WriteLine(); DenseGraph graph1 = new DenseGraph(13, false); ReadGraph readGraph1 = new ReadGraph(graph1, fileName); Console.WriteLine("test g1 in dense graph "); graph1.Show(); Console.WriteLine("==========================================="); DenseGraph graph2 = new DenseGraph(13, false); ReadGraph readGraph2 = new ReadGraph(graph2, fileName); Path path = new Path(graph2, 0); Console.WriteLine("test path g1 in dense graph "); path.ShowPath(4); Console.WriteLine("==========================================="); WeightedDenseGraph <double> wgraph3 = new WeightedDenseGraph <double>(8, false); ReadWeightedGraph readGraph3 = new ReadWeightedGraph(wgraph3, "testG1.txt"); Console.WriteLine("test in weighted dense graph "); wgraph3.Show(); Console.WriteLine("==========================================="); SparseWeightedGraph <double> wgraph4 = new SparseWeightedGraph <double>(8, false); ReadWeightedGraph readGraph4 = new ReadWeightedGraph(wgraph4, "testG1.txt"); Console.WriteLine("test in weighted sparse graph "); wgraph4.Show(); Console.WriteLine("Test MinHeap"); int n = 100000; MinHeap <int> heap = new MinHeap <int>(n); Random rand = new Random(); for (int i = 0; i < n; i++) { heap.Add(rand.Next(n)); } List <int> list = new List <int>(); for (int i = 0; i < n; i++) { list.Add(heap.ExtractMin()); } for (int i = 0; i < n - 1; i++) { if (list[i] > list[i + 1]) { throw new Exception("MinHeap error"); } } Console.WriteLine("==========================================="); Console.WriteLine("Test MST"); SparseWeightedGraph <double> wgraph5 = new SparseWeightedGraph <double>(8, false); ReadWeightedGraph readGraph5 = new ReadWeightedGraph(wgraph5, "testG1.txt"); LazyPrimeMST <double> mst = new LazyPrimeMST <double>(wgraph5); List <Edge <double> > mstPath = mst.MstEdges(); for (int i = 0; i < mstPath.Count; i++) { Console.WriteLine(mstPath[i]); } Console.WriteLine("Test Index MinHeap"); IndexMinHeap <int> heap1 = new IndexMinHeap <int>(n); for (int i = 0; i < n; i++) { heap1.Add(i, rand.Next(n)); } for (int i = 0; i < n / 2; i++) { heap1.Update(i, rand.Next(n)); } List <int> list1 = new List <int>(); for (int i = 0; i < n; i++) { list1.Add(heap1.ExtractMin()); } for (int i = 0; i < n - 1; i++) { if (list1[i] > list1[i + 1]) { throw new Exception("IndexMinHeap error"); } } Console.WriteLine("==========================================="); Console.WriteLine("Test MST Optimization"); SparseWeightedGraph <double> wgraph6 = new SparseWeightedGraph <double>(8, false); ReadWeightedGraph readGraph6 = new ReadWeightedGraph(wgraph6, "testG1.txt"); PrimMST <double> mst1 = new PrimMST <double>(wgraph6); List <Edge <double> > mstPath1 = mst1.MstEdges(); for (int i = 0; i < mstPath1.Count; i++) { Console.WriteLine(mstPath1[i]); } }
// Use this for initialization void Start() { //测试极小堆 print("------------------测试极小堆------------------"); int capicity = 100; int n = 10; int[] arr = AlgorithmsHelp.generateRandomArray(n, 1, 20); MinHeap <int> minHeap = new MinHeap <int> (100); MinHeap <int> minarrHeap = new MinHeap <int> (arr, 100); for (int i = 0; i != n; i++) { minHeap.Insert(arr[i]); } minHeap.print(); minarrHeap.print(); string str = ""; while (minHeap.Size() > 0) { str += minHeap.ExtraMinItem() + " "; } Debug.Log(str); testChangeInNormalHeap(minarrHeap); print("------------------------------------------"); print("------------------测试极小索引堆------------------"); //测试极小索引堆 arr = AlgorithmsHelp.generateRandomArray(n, 1, 20); IndexMinHeap <int> minIndexHeap = new IndexMinHeap <int>(100); IndexMinHeap <int> minarrIndexHeap = new IndexMinHeap <int>(arr, 100); for (int i = 0; i != n; i++) { minIndexHeap.Insert(arr[i]); } minIndexHeap.print(); minarrIndexHeap.print(); str = ""; while (minIndexHeap.Size() > 0) { str += minIndexHeap.ExtraMinItem() + " "; } print("从小到大排序 " + str); testChangeInIndexHeap(minarrIndexHeap); // 测试极大堆 // int capicity = 100; // int n = 10; // Heap<int> maxHeap = new Heap<int> (100); // int[] arr = AlgorithmsHelp.generateRandomArray (n,1,20); // for (int i = 0; i != n; i++) { // maxHeap.Insert (arr[i]); // } // maxHeap.printData (); // // string str = ""; // for (int i = 0; i != n; i++) { // str +=maxHeap.ExtractBigItem()+" "; // } // print ("data[] : " +str); }
public AStarAlgorithm(int amountOfNodes, IDistanceHeuristic heuristic) { _openSet = new IndexMinHeap <AstarNode>(amountOfNodes); _closedSet = new LookupArray(amountOfNodes); _heuristic = heuristic; }