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()); }
// 书中算法 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); } }