private IndexMinPQ <double> pq; // priority queue of vertices /// <summary> /// Computes a shortest-paths tree from the source vertex <c>s</c> to every /// other vertex in the edge-weighted graph <c>G</c>.</summary> /// <param name="G">the edge-weighted digraph</param> /// <param name="s">the source vertex</param> /// <exception cref="ArgumentException">if an edge weight is negative</exception> /// <exception cref="ArgumentException">unless 0 <= <c>s</c> <= <c>V</c> - 1</exception> /// public DijkstraUndirectedSP(EdgeWeightedGraph G, int s) { foreach (Edge e in G.Edges()) { if (e.Weight < 0) { throw new ArgumentException("edge " + e + " has negative weight"); } } distTo = new double[G.V]; edgeTo = new Edge[G.V]; for (int v = 0; v < G.V; v++) { distTo[v] = double.PositiveInfinity; } distTo[s] = 0.0; // relax vertices in order of distance from s pq = new IndexMinPQ <double>(G.V); pq.Insert(s, distTo[s]); while (!pq.IsEmpty) { int v = pq.DelMin(); foreach (Edge e in G.Adj(v)) { relax(e, v); } } // check optimality conditions Debug.Assert(check(G, s)); }
/// <summary>merge together the sorted input streams and write the sorted /// result to standard output.</summary> /// <param name="streams">opened stream from user</param> public static void Merge(TextInput[] streams) { int N = streams.Length; IndexMinPQ <string> pq = new IndexMinPQ <string>(N); for (int i = 0; i < N; i++) { if (!streams[i].IsEmpty) { string s = streams[i].ReadString(); if (!s.Equals("")) { pq.Insert(i, s); } } } // Extract and print min and read next from its stream. while (!pq.IsEmpty) { Console.Write(pq.MinKey + " "); int i = pq.DelMin(); if (!streams[i].IsEmpty) { string s = streams[i].ReadString(); if (!s.Equals("")) { pq.Insert(i, s); } } } Console.WriteLine(); }
// run Prim's algorithm in graph G, starting from vertex s private void prim(EdgeWeightedGraph G, int s) { distTo[s] = 0.0; pq.Insert(s, distTo[s]); while (!pq.IsEmpty) { int v = pq.DelMin(); scan(G, v); } }
public static void MainTest(string[] args) { // insert a bunch of strings string[] strings = { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" }; IndexMinPQ <string> pq = new IndexMinPQ <string>(strings.Length); for (int i = 0; i < strings.Length; i++) { pq.Insert(i, strings[i]); } // delete and print each key while (!pq.IsEmpty) { int i = pq.DelMin(); Console.WriteLine(i + " " + strings[i]); } Console.WriteLine(); // reinsert the same strings for (int i = 0; i < strings.Length; i++) { pq.Insert(i, strings[i]); } // print each key using the iterator foreach (int i in pq) { Console.WriteLine(i + " " + strings[i]); } while (!pq.IsEmpty) { Console.WriteLine("Min k={0} at {1}", pq.MinKey, pq.MinIndex); Console.WriteLine("Removed {0}", pq.DelMin()); } }