/// <summary> /// Dijkstra algorithm (longest path) based on graph g for start vertice s. Positive cycles are NOT allowed in longest path algorithm /// </summary> /// <param name="g">Graph for search</param> /// <param name="s">Start vertice</param> public static PathStats LongestPath(GraphBase g, int s) { var ps = new PathStats(g.V); for (var i = 0; i < ps.Dist.Length; i++) { ps.Dist[i] = int.MinValue; ps.Prev[i] = -1; } ps.Dist[s] = 0;//start vertice var pq = new IndexMaxPQ<Distance>(ps.Dist.Length); for (int i = 0; i < ps.Dist.Length; i++) { pq.Insert(i, new Distance { V = i, Dist = ps.Dist[i] }); } while (!pq.IsEmpty()) { var v = pq.DelRoot(); foreach (var e in g.Adjacent(v)) { if (ps.Dist[e.V2] < ps.Dist[v] + e.Weight) //longest path { ps.Dist[e.V2] = ps.Dist[v] + e.Weight; ps.Prev[e.V2] = v; pq.ChangeKey(e.V2, new Distance { V = e.V2, Dist = ps.Dist[e.V2] }); } } } return ps; }
public void Initialize() { _target = new IndexMaxPQ<Distance>(4); _target.Insert(2, new Distance { V = 2, Dist = 1 }); _target.Insert(1, new Distance { V = 1, Dist = 3 }); _target.Insert(0, new Distance { V = 0, Dist = 2 }); }
public void EnumeratorMaxPQTest() { // Expected: same as sorting the input and inserting it in a regular queue Queue<string> expectedItems = new Queue<string>(this.testStrings.OrderByDescending(s => s)); IndexMaxPQ<string> pq = new IndexMaxPQ<string>(this.testStrings.Length); CommonIndexPQUnitTests.EnumerationPQTest(this.testStrings, pq, expectedItems); }
public void IndexedMaxPQIncreaseKeyTest() { // arrange var pq = new IndexMaxPQ <string>(array); // act + assert initial Assert.False(pq.IsEmpty); Assert.Equal(10, pq.Size); Assert.Equal(9, pq.Index); Assert.Equal(9, pq.MaxIndex); Assert.Equal("worst", pq.Max); Assert.Equal("worst", pq.TopKey); // act + assert ex try { pq.increaseKey(9, "exception"); } catch (Exception ex) { Assert.IsType <ArgumentException>(ex); Assert.Equal("Calling increaseKey() with given argument would not strictly increase the key", ex.Message); } // act + assert increase pq.increaseKey(9, "worst even"); Assert.Equal("worst even", pq.Max); Assert.Equal("worst even", pq.TopKey); }
public void IndexMaxPQIteratorTest() { var pq = new IndexMaxPQ <String>(array); var actual = Strings(pq).ToList(); Assert.Equal(indexedMax, actual); }
public void Merge3WayMaxPQTest() { string[] inputFiles = { "Algs4-Data\\m1r.txt", "Algs4-Data\\m2r.txt", "Algs4-Data\\m3r.txt" }; Queue<string> expectedItems = new Queue<string>( "A B C F G I I Z B D H P Q Q A B E F J N".Split(" ".ToCharArray()).OrderByDescending(s => s)); IndexMaxPQ<string> pq = new IndexMaxPQ<string>(expectedItems.Count); CommonIndexPQUnitTests.MergeMultiWay(inputFiles, pq, expectedItems); }
public void Run() { Console.WriteLine("Choose file:"); // Prompt Console.WriteLine("1 - tinyPQ.txt"); // Prompt Console.WriteLine("or quit"); // Prompt var fileNumber = Console.ReadLine(); var fieName = string.Empty; switch (fileNumber) { case "1": fieName = "tinyIndexPQ.txt"; break; case "quit": return; default: return; } var @in = new In($"Files\\Sorting\\{fieName}"); var words = @in.ReadAllStrings(); //var list = words.Select(word => new StringComparable(word)).ToList(); //var listComparable = list.Cast<IComparable>().ToList(); //var arrayComparable = list.Cast<IComparable>().ToArray(); var listStrings = words.ToList(); var pq = new IndexMaxPQ <string>(listStrings.Count); //Fill Priority Queue for (var i = 0; i < listStrings.Count; i++) { pq.Insert(i, listStrings[i]); } // print results foreach (var item in pq) { Console.WriteLine(pq.KeyOf(item)); } Console.ReadLine(); }
public void IndexMaxPQTest1() { const int MaxSize = 8; const double MinValue = 3.9; const double MaxValue = MinValue * MaxSize + 32; int index; // MaxValue index == 3, MinValue index == 4 double[] items = { MinValue * 2, MinValue * 3, MinValue * 4, MaxValue, MinValue, MinValue * 5, MinValue * 6, MinValue * 7 }; StdRandom.Seed = 101; IndexMaxPQ <double> pq = new IndexMaxPQ <double>(MaxSize); index = StdRandom.Uniform(items.Length); Assert.IsFalse(pq.Contains(index)); Assert.IsTrue(pq.IsEmpty); Assert.AreEqual(0, pq.Count); try { index = pq.DelMax(); Assert.Fail("Failed to catch exception"); } catch (InvalidOperationException) { } for (int i = 0; i < items.Length; i++) { pq.Insert(i, items[i]); } Assert.AreEqual(items.Length, pq.Count); Assert.AreEqual(MaxValue, pq.MaxKey); Assert.AreEqual(3, pq.MaxIndex); Assert.AreEqual(MinValue, pq.KeyOf(4)); index = StdRandom.Uniform(items.Length); Assert.AreEqual(items[index], pq.KeyOf(index)); pq.ChangeKey(1, pq.MaxKey * 1.9); // make it the largest item Assert.AreEqual(1, pq.MaxIndex); pq.IncreaseKey(3, pq.MaxKey * 1.87); Assert.AreEqual(3, pq.MaxIndex); pq.Delete(3); Assert.AreNotEqual(3, pq.MaxIndex); Assert.AreEqual(1, pq.DelMax()); }
public void IndexPQDeleteAtIndexTest() { var pq = new IndexMaxPQ <String>(array); Assert.True(pq.Contains(5)); pq.Delete(5); Assert.False(pq.Contains(5)); try { pq.Delete(5); } catch (Exception ex) { Assert.IsType <InvalidOperationException>(ex); Assert.Equal("index is not in the priority queue", ex.Message); } }
public void Run() { Console.WriteLine("Choose file:"); // Prompt Console.WriteLine("1 - tinyPQ.txt"); // Prompt Console.WriteLine("or quit"); // Prompt var fileNumber = Console.ReadLine(); var fieName = string.Empty; switch (fileNumber) { case "1": fieName = "tinyIndexPQ.txt"; break; case "quit": return; default: return; } var @in = new In($"Files\\Sorting\\{fieName}"); var words = @in.ReadAllStrings(); //var list = words.Select(word => new StringComparable(word)).ToList(); //var listComparable = list.Cast<IComparable>().ToList(); //var arrayComparable = list.Cast<IComparable>().ToArray(); var listStrings = words.ToList(); var pq = new IndexMaxPQ<string>(listStrings.Count); //Fill Priority Queue for (var i = 0; i < listStrings.Count; i++) { pq.Insert(i, listStrings[i]); } // print results foreach (var item in pq) { Console.WriteLine(pq.KeyOf(item)); } Console.ReadLine(); }
/** * Returns the cut-of-the-phase. The cut-of-the-phase is a minimum s-t-cut * in the current graph, where {@code s} and {@code t} are the two vertices * added last in the phase. This algorithm is known in the literature as * <em>maximum adjacency search</em> or <em>maximum cardinality search</em>. * * @param G the edge-weighted graph * @param marked the array of contracted vertices, where {@code marked[v]} * is {@code true} if the vertex {@code v} was already * contracted; or {@code false} otherwise * @param cp the previous cut-of-the-phase * @return the cut-of-the-phase */ private CutPhase minCutPhase(EdgeWeightedGraph G, boolean[] marked, CutPhase cp) { IndexMaxPQ<Double> pq = new IndexMaxPQ<Double>(G.V()); for (int v = 0; v < G.V(); v++) { if (v != cp.s && !marked[v]) pq.insert(v, 0.0); } pq.insert(cp.s, Double.POSITIVE_INFINITY); while (!pq.isEmpty()) { int v = pq.delMax(); cp.s = cp.t; cp.t = v; for (Edge e : G.adj(v)) { int w = e.other(v); if (pq.contains(w)) pq.increaseKey(w, pq.keyOf(w) + e.weight()); } } cp.weight = 0.0; for (Edge e : G.adj(cp.t)) { cp.weight += e.weight(); } return cp; }
// 书中算法 2.6 给出的是最大堆,但本题自带的部分解答是最小堆形式的。 // 这里和官网保持一致,实现最大堆。 // 官网答案:https://algs4.cs.princeton.edu/24pq/IndexMaxPQ.java.html static void Main(string[] args) { string[] input = new string[] { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" }; IndexMaxPQ <string> pq = new IndexMaxPQ <string>(input.Length); for (int i = 0; i < input.Length; i++) { pq.Insert(input[i], i); } foreach (var i in pq) { Console.WriteLine(i + ". " + input[i]); } Console.WriteLine(); Random random = new Random(); for (int i = 0; i < input.Length; i++) { if (random.NextDouble() < 0.5) { pq.IncreaseKey(i, input[i] + input[i]); } else { pq.DecreaseKey(i, input[i].Substring(0, 1)); } } while (!pq.IsEmpty()) { string key = pq.MaxKey(); int i = pq.DelMax(); Console.WriteLine(i + "." + key); } Console.WriteLine(); for (int i = 0; i < input.Length; i++) { pq.Insert(input[i], i); } int[] param = new int[input.Length]; for (int i = 0; i < input.Length; i++) { param[i] = i; } Shuffle(param); for (int i = 0; i < param.Length; i++) { string key = pq.KeyOf(param[i]); pq.Delete(param[i]); Console.WriteLine(param[i] + "." + key); } }
// Use this for initialization void Start() { // insert a bunch of strings string[] strings = { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" }; IndexMaxPQ <string> pq = new IndexMaxPQ <string>(strings.Length); for (int i = 0; i < strings.Length; i++) { pq.insert(i, strings[i]); } // print each key using the iterator foreach (string i in pq) { print(i + " " + strings[int.Parse(i)]); } // increase or decrease the key for (int i = 0; i < strings.Length; i++) { if (Random.Range(0.0f, 1.0f) < 0.5) // Random.uniform() 返回一个随机的范围在[0,1)之间的double类型的数 { pq.increaseKey(i, strings[i] + strings[i]); } else { pq.decreaseKey(i, strings[i].Substring(0, 1)); } } // delete and print each key while (!pq.isEmpty()) { string key = pq.maxKey(); int i = pq.delMax(); print(i + " " + key); } // reinsert the same strings for (int i = 0; i < strings.Length; i++) { pq.insert(i, strings[i]); } // delete them in random order int[] perm = new int[strings.Length]; for (int i = 0; i < strings.Length; i++) { perm[i] = i; } UnSort(perm); // StdRandom.shuffle() 随机打乱指定的object型数组 for (int i = 0; i < perm.Length; i++) { string key = pq.keyOf(perm[i]); pq.delete(perm[i]); print(perm[i] + " " + key); } }