写在前面

整个项目都托管在了 Github 上:https://github.com/ikesnowy/Algorithms-4th-Edition-in-Csharp

查找更方便的版本见:https://alg4.ikesnowy.com/

这一节内容可能会用到的库文件有 SortApplication,同样在 Github 上可以找到。

善用 Ctrl + F 查找题目。

习题&题解

2.5.1

解答

如果比较的两个 String 引用的是同一个对象,那么就直接返回相等,不必再逐字符比较。

一个例子:

  1. string s = "abcabc";
  2. string p = s;
  3. Console.WriteLine(s.CompareTo(p));

2.5.2

解答

将字符串数组 keywords 按照长度排序,于是 keywords[0] 就是最短的字符串。

组合词的最短长度 minLength = 最短字符串的长度 * 2 = keywords[0] * 2

先找到第一个长度大于等于 minLength 的字符串,下标为 canCombine

我们从 canCombine 开始,一个个检查是否是组合词。

如果 keywords[canCombine] 是一个组合词,那么它一定是由位于它之前的某两个字符串组合而成的。

组合词的长度一定等于被组合词的长度之和,因此我们可以通过长度快速判断有可能的组合词。

现在题目转化为了如何解决 ThreeSum 问题,即求 a + b = c 型问题,根据 1.4.41 中的解法求解。

keywords[canCombine] 的长度已知,i 从 0 到 canCombine 之间循环,

用二分查找确认 icanCombine 之间有没有符合条件的字符串,注意多个字符串可能长度相等。

代码
  1. using System;
  2. using System.Collections.Generic;
  3. namespace _2._5._2
  4. {
  5. /*
  6. * 2.5.2
  7. *
  8. * 编写一段程序,从标准输入读入一列单词并打印出其中所有由两个单词组成的组合词。
  9. * 例如,如果输入的单词为 after、thought 和 afterthought,
  10. * 那么 afterthought 就是一个组合词。
  11. *
  12. */
  13. class Program
  14. {
  15. /// <summary>
  16. /// 根据字符串长度进行比较。
  17. /// </summary>
  18. class StringLengthComparer : IComparer<string>
  19. {
  20. public int Compare(string x, string y)
  21. {
  22. return x.Length.CompareTo(y.Length);
  23. }
  24. }
  25. /// <summary>
  26. /// 二分查找,返回符合条件的最小下标。
  27. /// </summary>
  28. /// <param name="keys">搜索范围。</param>
  29. /// <param name="length">搜索目标。</param>
  30. /// <param name="lo">起始下标。</param>
  31. /// <param name="hi">终止下标。</param>
  32. /// <returns></returns>
  33. static int BinarySearch(string[] keys, int length, int lo, int hi)
  34. {
  35. while (lo <= hi)
  36. {
  37. int mid = lo + (hi - lo) / 2;
  38. if (keys[mid].Length == length)
  39. {
  40. while (mid >= lo && keys[mid].Length == length)
  41. mid--;
  42. return mid + 1;
  43. }
  44. else if (length > keys[mid].Length)
  45. lo = mid + 1;
  46. else
  47. hi = mid - 1;
  48. }
  49. return -1;
  50. }
  51. static void Main(string[] args)
  52. {
  53. string[] keywords = Console.ReadLine().Split(' ');
  54. Array.Sort(keywords, new StringLengthComparer());
  55. int minLength = keywords[0].Length * 2;
  56. // 找到第一个大于 minLength 的字符串
  57. int canCombine = 0;
  58. while (keywords[canCombine].Length < minLength &&
  59. canCombine < keywords.Length)
  60. canCombine++;
  61. // 依次测试是否可能
  62. while (canCombine < keywords.Length)
  63. {
  64. int sum = keywords[canCombine].Length;
  65. for (int i = 0; i < canCombine; i++)
  66. {
  67. int start = BinarySearch(keywords, sum - keywords[i].Length, i, canCombine);
  68. if (start != -1)
  69. {
  70. while (keywords[start].Length + keywords[i].Length == sum)
  71. {
  72. if (keywords[start] + keywords[i] == keywords[canCombine])
  73. Console.WriteLine(keywords[canCombine] + " = " + keywords[start] + " + " + keywords[i]);
  74. else if (keywords[i] + keywords[start] == keywords[canCombine])
  75. Console.WriteLine(keywords[canCombine] + " = " + keywords[i] + " + " + keywords[start]);
  76. start++;
  77. }
  78. }
  79. }
  80. canCombine++;
  81. }
  82. }
  83. }
  84. }

2.5.3

解答

这样会破坏相等的传递性。

例如 a = 0.005, b=0.000, c=-0.005,则 a == b, c == b,但是 a != c。

2.5.4

解答

先排序,然后用书中的代码进行去重。

  1. static string[] Dedup(string[] a)
  2. {
  3. if (a.Length == 0)
  4. return a;
  5. string[] sorted = new string[a.Length];
  6. for (int i = 0; i < a.Length; i++)
  7. {
  8. sorted[i] = a[i];
  9. }
  10. Array.Sort(sorted);
  11. // sorted = sorted.Distinct().ToArray();
  12. string[] distinct = new string[sorted.Length];
  13. distinct[0] = sorted[0];
  14. int j = 1;
  15. for (int i = 1; i < sorted.Length; i++)
  16. {
  17. if (sorted[i].CompareTo(sorted[i - 1]) != 0)
  18. distinct[j++] = sorted[i];
  19. }
  20. return distinct;
  21. }

2.5.5

解答

因为选择排序会交换不相邻的元素。

例如:

  1. B1 B2 A
  2. A B2 B1

此时 B1 和 B2 的相对位置被改变,如果将交换限定在相邻元素之间(插入排序)。

  1. B1 B2 A
  2. B1 A B2
  3. A B2 B2

此时排序就是稳定的了。

2.5.6

解答

非递归官网实现见:https://algs4.cs.princeton.edu/23quicksort/QuickPedantic.java.html

原本是和快速排序一块介绍的,将数组重新排列,使得 a[k] 正好是第 k 小的元素,k0 开始。

具体思路类似于二分查找,

先切分,如果切分位置小于 k,那么在右半部分继续切分,否则在左半部分继续切分。

直到切分位置正好等于 k,直接返回 a[k]

代码
  1. /// <summary>
  2. /// 使 a[k] 变为第 k 小的数,k 从 0 开始。
  3. /// a[0] ~ a[k-1] 都小于等于 a[k], a[k+1]~a[n-1] 都大于等于 a[k]
  4. /// </summary>
  5. /// <typeparam name="T">元素类型。</typeparam>
  6. /// <param name="a">需要调整的数组。</param>
  7. /// <param name="k">序号。</param>
  8. /// <param name="lo">起始下标。</param>
  9. /// <param name="hi">终止下标。</param>
  10. /// <returns></returns>
  11. static T Select<T>(T[] a, int k, int lo, int hi) where T : IComparable<T>
  12. {
  13. if (k > a.Length || k < 0)
  14. throw new ArgumentOutOfRangeException("select out of bound");
  15. if (lo >= hi)
  16. return a[lo];
  17. int i = Partition(a, lo, hi);
  18. if (i > k)
  19. return Select(a, k, lo, i - 1);
  20. else if (i < k)
  21. return Select(a, k, i + 1, hi);
  22. else
  23. return a[i];
  24. }
另请参阅

SortApplication 库

2.5.7

解答

参考书中给出的快速排序性能分析方法(中文版 P186,英文版 P293)。

设 $ C_n $ 代表找出 $ n $ 个元素中的最小值所需要的比较次数。

一次切分需要 $ n+1 $ 次比较,下一侧的元素个数从 $ 0 $ 到 $ n-1 $ 都有可能,

于是根据全概率公式,有:

\[\begin{eqnarray*}
C_n&=&\frac {1}{n} (n+1) +\frac{1}{n} (n+1+C_1)+ \cdots + \frac{1}{n}(n+1+C_{n-1}) \\
C_n&=&n+1+\frac{1}{n}(C_1+C_2+\cdots+C_{n-1}) \\
nC_n&=&n(n+1)+(C_1+C_2+\cdots+C_{n-1}) \\
nC_n-(n-1)C_{n-1}&=&2n+C_{n-1} \\
nC_n&=&2n+nC_{n-1} \\
C_n&=&2+C_{n-1} \\
C_n &=& C_1+2(n-1) \\
C_n &=& 2n-2 < 2n
\end{eqnarray*}
\]

测试结果符合我们的预期。

附加:找出第 $ k $ 小的数平均需要的比较次数。

类似的方法也在计算快速排序的平均比较次数时使用,见题 2.3.14。

首先和快速排序类似,select 方法的所有元素比较都发生在切分过程中。

接下来考虑第 $ i $ 小和第 $ j $ 小的元素($ x_i $ ,$ x_j $),

当枢轴选为 $ x_i $ 或 $ x_j $ 时,它们会发生比较;

如果枢轴选为 $ x_i $ 和 $ x_j $ 之间的元素,那么它们会被切分到两侧,不可能发生比较;

如果枢轴选为小于 $ x_i $ 或大于 $ x_j $ 的元素,它们会被切分到同一侧,进入下次切分。

但要注意的是,select 只会对切分的一侧进行再切分,另一侧会被抛弃(快速排序则是两侧都会再切分)。

因此我们需要将第 $ k $ 小的数 $ x_k $ 纳入考虑。

如果 $ x_k>x_j>x_i $ ,且枢轴选了 $ x_k $ 到 $ x_j $ 之间的元素,切分后 $ x_i $ 和 $ x_j $ 会被一起抛弃,不发生比较。

如果 $ x_j > x_k > x_i $ ,枢轴的选择情况和快速排序一致。

如果 $ x_j > x_i > x_k $ ,且枢轴选了 $ x_i $ 到 $ x_k $ 之间的元素,切分后 $ x_i $ 和 $ x_j $ 会被一起抛弃,不发生比较。

综上我们可以得到 $ x_i $ 和 $ x_j $ 之间发生比较的概率 $ \frac{2}{\max(j-i+1, k-i+1,j-k+1)} $ 。

我们利用线性规划的知识把最大值函数的区域画出来,如下图所示:



对蓝色区域积分得:

\[\begin{eqnarray*}
&&\int_{0}^{k} dj \int_{0}^{j} \frac{2}{j-k+1}\ di \\
&=& 2 \int_{0}^{k} \frac{j}{j-k+1} \ dj \\
&<& 2 k
\end{eqnarray*}
\]

对红色区域积分得:

\[\begin {eqnarray*}
&& \int_{k}^{n} di \int_{i}^{n} \frac{2}{k-i+1} dj \\
&=& 2\int_{k}^{n} \frac{n-i}{k-i+1} di \\
&<& 2(n-k)
\end {eqnarray*}
\]

对绿色区域积分得:

\[\begin{eqnarray*}
&& \int_{0}^{k}di\int_{k}^{n} \frac{2}{j-i+1} dj \\
&<& \int_{0}^{k}di\int_{k}^{n} \frac{2}{j-i} dj \\
&=& 2\int_{0}^{k} \ln (n-i) di - 2\int_{0}^{k} \ln(k-i)di \\
&=& 2i\ln(n-i) \bigg|_{0}^{k} + 2\int_{0}^{k}\frac{i}{n-i} di -
\left[ i\ln(k-i) \bigg|_{0}^{k} + 2\int_{0}^{k} \frac{i}{k-i} di \right] \\
&=& 2k\ln(n-k)+2\int_{0}^{k}\frac{n}{n-i}-1 \ di -2\int_{0}^{k} \frac{k}{k-i}-1 \ di \\
&=& 2k\ln(n-k)+2\int_{0}^{k}\frac{n}{n-i} \ di -2k - 2\int_{0}^{k} \frac{k}{k-i} \ di +2k \\
&=& 2k\ln(n-k) -2n\ln(n-i) \bigg|_{0}^{k} +2k\ln(k-i)\bigg|_{0}^{k} \\
&=& 2k\ln(n-k)-2n\ln(n-k)+2n\ln n -2k\ln k
\end{eqnarray*}
\]

全部相加得到:

\[\begin{eqnarray*}
&& 2k+2(n-k)+2k\ln(n-k)-2n\ln(n-k)+2n\ln n -2k\ln k \\
&=& 2n + 2k\ln(n-k)-2n\ln(n-k)+2n\ln n -2k\ln k \\
&=& 2n + 2k\ln(n-k)-2n\ln(n-k)+2n\ln n-2k\ln k +2k\ln n-2k\ln n \\
&=& 2n + 2k\ln n-2k\ln k+2n\ln n-2n\ln(n-k) - 2k\ln n + 2k\ln(n-k) \\
&=& 2n + 2k\ln \left(\frac{n}{k} \right)+2n\ln\left(\frac{n}{n-k} \right) - 2k\ln\left(\frac{n}{n-k} \right) \\
&=& 2n+2k\ln\left(\frac{n}{k}\right)+2(n-k)\ln\left(\frac{n}{n-k} \right)
\end{eqnarray*}
\]

于是得到了命题 U 中的结果(中文版 P221,英文版 P347)。

另请参阅

Blum-style analysis of Quickselect

2.5.8

解答

官网实现见:https://algs4.cs.princeton.edu/25applications/Frequency.java.html

用到的数据来自(右键另存为):https://introcs.cs.princeton.edu/java/data/tale.txt

先把所有单词读入,然后排序,一样的单词会被放在一起,

接下来遍历一遍记录每个单词出现的次数。

然后按照频率排序,倒序输出即可。

定义了一个嵌套类 Record 来记录单词及出现次数,实现的比较器按照出现次数排序。

  1. class Record : IComparable<Record>
  2. {
  3. public string Key { get; set; } // 单词
  4. public int Value { get; set; } // 频率
  5. public Record(string key, int value)
  6. {
  7. this.Key = key;
  8. this.Value = value;
  9. }
  10. public int CompareTo(Record other)
  11. {
  12. return this.Value.CompareTo(other.Value);
  13. }
  14. }

测试结果(前 1% 的单词):

代码
  1. using System;
  2. using System.IO;
  3. namespace _2._5._8
  4. {
  5. class Program
  6. {
  7. class Record : IComparable<Record>
  8. {
  9. public string Key { get; set; } // 单词
  10. public int Value { get; set; } // 频率
  11. public Record(string key, int value)
  12. {
  13. this.Key = key;
  14. this.Value = value;
  15. }
  16. public int CompareTo(Record other)
  17. {
  18. return this.Value.CompareTo(other.Value);
  19. }
  20. }
  21. static void Main(string[] args)
  22. {
  23. string filename = "tale.txt";
  24. StreamReader sr = new StreamReader(File.OpenRead(filename));
  25. string[] a = sr.ReadToEnd().Split(new char[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
  26. Array.Sort(a);
  27. Record[] records = new Record[a.Length];
  28. string word = a[0];
  29. int freq = 1;
  30. int m = 0;
  31. for (int i = 0; i < a.Length; i++)
  32. {
  33. if (!a[i].Equals(word))
  34. {
  35. records[m++] = new Record(word, freq);
  36. word = a[i];
  37. freq = 0;
  38. }
  39. freq++;
  40. }
  41. records[m++] = new Record(word, freq);
  42. Array.Sort(records, 0, m);
  43. // 只显示频率为前 1% 的单词
  44. for (int i = m - 1; i >= m * 0.99; i--)
  45. Console.WriteLine(records[i].Value + " " + records[i].Key);
  46. }
  47. }
  48. }

2.5.9

解答

右侧给出的是道琼斯指数,官方数据(右键另存为):DJI

设计一个类保存日期和交易量,然后按照交易量排序即可。

  1. /// <summary>
  2. /// 道琼斯指数。
  3. /// </summary>
  4. class DJIA : IComparable<DJIA>
  5. {
  6. public string Date { get; set; }
  7. public long Volume { get; set; }
  8. public DJIA(string date, long vol)
  9. {
  10. this.Date = date;
  11. this.Volume = vol;
  12. }
  13. public int CompareTo(DJIA other)
  14. {
  15. return this.Volume.CompareTo(other.Volume);
  16. }
  17. }

2.5.10

解答

用一个 int 数组来保存版本号,按顺序进行比较。

如果两个版本号不等长且前缀相同,那么较长的版本号比较高,例如:1.2.1 和 1.2。

  1. using System;
  2. namespace _2._5._10
  3. {
  4. /// <summary>
  5. /// 版本号。
  6. /// </summary>
  7. class Version : IComparable<Version>
  8. {
  9. private int[] versionNumber;
  10. public Version(string version)
  11. {
  12. string[] versions = version.Split('.');
  13. this.versionNumber = new int[versions.Length];
  14. for (int i = 0; i < versions.Length; i++)
  15. {
  16. this.versionNumber[i] = int.Parse(versions[i]);
  17. }
  18. }
  19. public int CompareTo(Version other)
  20. {
  21. for (int i = 0; i < this.versionNumber.Length && i < other.versionNumber.Length; i++)
  22. {
  23. if (this.versionNumber[i].CompareTo(other.versionNumber[i]) != 0)
  24. return this.versionNumber[i].CompareTo(other.versionNumber[i]);
  25. }
  26. return this.versionNumber.Length.CompareTo(other.versionNumber.Length);
  27. }
  28. public override string ToString()
  29. {
  30. string result = "";
  31. for (int i = 0; i < this.versionNumber.Length - 1; i++)
  32. {
  33. result += this.versionNumber[i] + ".";
  34. }
  35. result += this.versionNumber[this.versionNumber.Length - 1].ToString();
  36. return result;
  37. }
  38. }
  39. }

2.5.11

解答

结果如下,其中快速排序去掉了一开始打乱数组的步骤:

只有快速排序和堆排序会进行交换,剩下四种排序都不会进行交换。

插入排序在排序元素完全相同的数组时只会进行一次遍历,不会交换。

选择排序第 i 次找到的最小值就是 a[i] ,只会让 a[i]a[i] 交换,不会影响顺序。

希尔排序和插入排序类似,每轮排序都不会进行交换。

归并排序是稳定的,就本例而言,只会从左到右依次归并,不会发生顺序变化。

快速排序在遇到相同元素时会交换,因此顺序会发生变化,且每次都是对半切分。

堆排序在删除最大元素时会将第一个元素和最后一个元素交换,使元素顺序发生变化。

代码
  1. using System;
  2. using SortApplication;
  3. namespace _2._5._11
  4. {
  5. class Program
  6. {
  7. /// <summary>
  8. /// 用来排序的元素,记录有自己的初始下标。
  9. /// </summary>
  10. /// <typeparam name="T"></typeparam>
  11. class Item<T> : IComparable<Item<T>> where T : IComparable<T>
  12. {
  13. public int Index;
  14. public T Key;
  15. public Item(int index, T key)
  16. {
  17. this.Index = index;
  18. this.Key = key;
  19. }
  20. public int CompareTo(Item<T> other)
  21. {
  22. return this.Key.CompareTo(other.Key);
  23. }
  24. }
  25. static void Main(string[] args)
  26. {
  27. // 插入排序
  28. Console.WriteLine("Insertion Sort");
  29. Test(new InsertionSort(), 7, 1);
  30. // 选择排序
  31. Console.WriteLine("Selection Sort");
  32. Test(new SelectionSort(), 7, 1);
  33. // 希尔排序
  34. Console.WriteLine("Shell Sort");
  35. Test(new ShellSort(), 7, 1);
  36. // 归并排序
  37. Console.WriteLine("Merge Sort");
  38. Test(new MergeSort(), 7, 1);
  39. // 快速排序
  40. Console.WriteLine("Quick Sort");
  41. QuickSortAnalyze quick = new QuickSortAnalyze
  42. {
  43. NeedShuffle = false,
  44. NeedPath = false
  45. };
  46. Test(quick, 7, 1);
  47. // 堆排序
  48. Console.WriteLine("Heap Sort");
  49. Item<int>[] array = new Item<int>[7];
  50. for (int i = 0; i < 7; i++)
  51. array[i] = new Item<int>(i, 1);
  52. Heap.Sort(array);
  53. for (int i = 0; i < 7; i++)
  54. Console.Write(array[i].Index + " ");
  55. Console.WriteLine();
  56. }
  57. static void Test(BaseSort sort, int n, int constant)
  58. {
  59. Item<int>[] array = new Item<int>[n];
  60. for (int i = 0; i < n; i++)
  61. array[i] = new Item<int>(i, constant);
  62. sort.Sort(array);
  63. for (int i = 0; i < n; i++)
  64. Console.Write(array[i].Index + " ");
  65. Console.WriteLine();
  66. }
  67. }
  68. }
另请参阅

SortApplication 库

2.5.12

解答

官方解答:https://algs4.cs.princeton.edu/25applications/SPT.java.html

把任务按照处理时间升序排序即可。

建立 Job 类,保存任务的名称和处理时间,并实现了 IConparable<Job> 接口。

  1. class Job : IComparable<Job>
  2. {
  3. public string Name;
  4. public double Time;
  5. public Job(string name, double time)
  6. {
  7. this.Name = name;
  8. this.Time = time;
  9. }
  10. public int CompareTo(Job other)
  11. {
  12. return this.Time.CompareTo(other.Time);
  13. }
  14. }
代码
  1. using System;
  2. namespace _2._5._12
  3. {
  4. class Program
  5. {
  6. class Job : IComparable<Job>
  7. {
  8. public string Name;
  9. public double Time;
  10. public Job(string name, double time)
  11. {
  12. this.Name = name;
  13. this.Time = time;
  14. }
  15. public int CompareTo(Job other)
  16. {
  17. return this.Time.CompareTo(other.Time);
  18. }
  19. }
  20. static void Main(string[] args)
  21. {
  22. // 官方解答:https://algs4.cs.princeton.edu/25applications/SPT.java.html
  23. int n = int.Parse(Console.ReadLine());
  24. Job[] jobs = new Job[n];
  25. for (int i = 0; i < n; i++)
  26. {
  27. string[] input = Console.ReadLine().Split(' ');
  28. jobs[i] = new Job(input[0], double.Parse(input[1]));
  29. }
  30. Array.Sort(jobs);
  31. for (int i = 0; i < jobs.Length; i++)
  32. {
  33. Console.WriteLine(jobs[i].Name + " " + jobs[i].Time);
  34. }
  35. }
  36. }
  37. }

2.5.13

解答

官方解答见:https://algs4.cs.princeton.edu/25applications/LPT.java.html

使用上题的 Job 类,在本题建立 Processor 类来代表处理器,定义如下:

  1. class Processor : IComparable<Processor>
  2. {
  3. private List<Job> jobs = new List<Job>();
  4. private double busyTime = 0;
  5. public Processor() { }
  6. public void Add(Job job)
  7. {
  8. this.jobs.Add(job);
  9. this.busyTime += job.Time;
  10. }
  11. public int CompareTo(Processor other)
  12. {
  13. return this.busyTime.CompareTo(other.busyTime);
  14. }
  15. public override string ToString()
  16. {
  17. StringBuilder sb = new StringBuilder();
  18. Job[] nowList = this.jobs.ToArray();
  19. for (int i = 0; i < nowList.Length; i++)
  20. {
  21. sb.AppendLine(nowList[i].Name + " " + nowList[i].Time);
  22. }
  23. return sb.ToString();
  24. }
  25. }

按照读入所有的任务并排序,再将所有的处理器放进一个最小堆里。

从最小堆取出任务最轻的处理器,按取耗时最长的任务分配给它,再将它放回最小堆中。

最后依次打印处理器的任务分配即可。

代码
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using SortApplication;
  5. namespace _2._5._13
  6. {
  7. class Program
  8. {
  9. class Job : IComparable<Job>
  10. {
  11. public string Name;
  12. public double Time;
  13. public Job(string name, double time)
  14. {
  15. this.Name = name;
  16. this.Time = time;
  17. }
  18. public int CompareTo(Job other)
  19. {
  20. return this.Time.CompareTo(other.Time);
  21. }
  22. }
  23. class Processor : IComparable<Processor>
  24. {
  25. private List<Job> jobs = new List<Job>();
  26. private double busyTime = 0;
  27. public Processor() { }
  28. public void Add(Job job)
  29. {
  30. this.jobs.Add(job);
  31. this.busyTime += job.Time;
  32. }
  33. public int CompareTo(Processor other)
  34. {
  35. return this.busyTime.CompareTo(other.busyTime);
  36. }
  37. public override string ToString()
  38. {
  39. StringBuilder sb = new StringBuilder();
  40. Job[] nowList = this.jobs.ToArray();
  41. for (int i = 0; i < nowList.Length; i++)
  42. {
  43. sb.AppendLine(nowList[i].Name + " " + nowList[i].Time);
  44. }
  45. return sb.ToString();
  46. }
  47. }
  48. static void Main(string[] args)
  49. {
  50. int processorNum = int.Parse(Console.ReadLine());
  51. int jobNum = int.Parse(Console.ReadLine());
  52. Job[] jobs = new Job[jobNum];
  53. for (int i = 0; i < jobNum; i++)
  54. {
  55. string[] jobDesc = Console.ReadLine().Split(' ');
  56. jobs[i] = new Job(jobDesc[0], double.Parse(jobDesc[1]));
  57. }
  58. Array.Sort(jobs);
  59. MinPQ<Processor> processors = new MinPQ<Processor>(processorNum);
  60. for (int i = 0; i < processorNum; i++)
  61. {
  62. processors.Insert(new Processor());
  63. }
  64. for (int i = jobs.Length - 1; i >= 0; i--)
  65. {
  66. Processor min = processors.DelMin();
  67. min.Add(jobs[i]);
  68. processors.Insert(min);
  69. }
  70. while (!processors.IsEmpty())
  71. {
  72. Console.WriteLine(processors.DelMin());
  73. }
  74. }
  75. }
  76. }
另请参阅

SortApplication 库

2.5.14

解答

官方解答:https://algs4.cs.princeton.edu/25applications/Domain.java.html

按照逆域名排序,例如输入的是 com.googlecom.apple

比较的时候是按照 google.comapple.com 进行比较的。

排序结果自然是 apple.com, google.com

编写的 Domain 类,CompareTo() 中是按照倒序进行比较的。

  1. using System;
  2. using System.Text;
  3. namespace _2._5._14
  4. {
  5. /// <summary>
  6. /// 域名类。
  7. /// </summary>
  8. class Domain : IComparable<Domain>
  9. {
  10. private string[] fields;
  11. private int n;
  12. /// <summary>
  13. /// 构造一个域名。
  14. /// </summary>
  15. /// <param name="url">域名的 url。</param>
  16. public Domain(string url)
  17. {
  18. this.fields = url.Split('.');
  19. this.n = this.fields.Length;
  20. }
  21. public int CompareTo(Domain other)
  22. {
  23. int minLength = Math.Min(this.n, other.n);
  24. for (int i = 0; i < minLength; i++)
  25. {
  26. int c = this.fields[minLength - i - 1].CompareTo(other.fields[minLength - i - 1]);
  27. if (c != 0)
  28. return c;
  29. }
  30. return this.n.CompareTo(other.n);
  31. }
  32. public override string ToString()
  33. {
  34. StringBuilder sb = new StringBuilder();
  35. for (int i = 0; i < this.fields.Length; i++)
  36. {
  37. if (i != 0)
  38. sb.Append('.');
  39. sb.Append(this.fields[i]);
  40. }
  41. return sb.ToString();
  42. }
  43. }
  44. }
代码
  1. using System;
  2. namespace _2._5._14
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Domain[] domains = new Domain[5];
  9. domains[0] = new Domain("edu.princeton.cs");
  10. domains[1] = new Domain("edu.princeton.ee");
  11. domains[2] = new Domain("com.google");
  12. domains[3] = new Domain("edu.princeton");
  13. domains[4] = new Domain("com.apple");
  14. Array.Sort(domains);
  15. for (int i = 0; i < domains.Length; i++)
  16. {
  17. Console.WriteLine(domains[i]);
  18. }
  19. }
  20. }
  21. }

2.5.15

解答

利用上一题的逆域名排序将域名相同的电子邮件分在一起。

代码
  1. using System;
  2. namespace _2._5._15
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. // 利用上一题的逆域名排序,将相同的域名放在一起。
  9. Domain[] emails = new Domain[5];
  10. emails[0] = new Domain("wayne@cs.princeton.edu");
  11. emails[1] = new Domain("windy@apple.com");
  12. emails[2] = new Domain("rs@cs.princeton.edu");
  13. emails[3] = new Domain("ike@ee.princeton.edu");
  14. emails[4] = new Domain("admin@princeton.edu");
  15. Array.Sort(emails);
  16. for (int i = 0; i < emails.Length; i++)
  17. {
  18. Console.WriteLine(emails[i]);
  19. }
  20. }
  21. }
  22. }

2.5.16

解答

官方解答:https://algs4.cs.princeton.edu/25applications/California.java.html

数据来源:https://introcs.cs.princeton.edu/java/data/california-gov.txt

建立一个 string 的比较器,按照题目给定的顺序比较。

  1. private class CandidateComparer : IComparer<string>
  2. {
  3. private static readonly string order = "RWQOJMVAHBSGZXNTCIEKUPDYFL";
  4. public int Compare(string x, string y)
  5. {
  6. int n = Math.Min(x.Length, y.Length);
  7. for (int i = 0; i < n; i++)
  8. {
  9. int a = order.IndexOf(x[i]);
  10. int b = order.IndexOf(y[i]);
  11. if (a != b)
  12. return a.CompareTo(b);
  13. }
  14. return x.Length.CompareTo(y.Length);
  15. }
  16. }
代码
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. namespace _2._5._16
  5. {
  6. class Program
  7. {
  8. // 官方解答:https://algs4.cs.princeton.edu/25applications/California.java.html
  9. private class CandidateComparer : IComparer<string>
  10. {
  11. private static readonly string order = "RWQOJMVAHBSGZXNTCIEKUPDYFL";
  12. public int Compare(string x, string y)
  13. {
  14. int n = Math.Min(x.Length, y.Length);
  15. for (int i = 0; i < n; i++)
  16. {
  17. int a = order.IndexOf(x[i]);
  18. int b = order.IndexOf(y[i]);
  19. if (a != b)
  20. return a.CompareTo(b);
  21. }
  22. return x.Length.CompareTo(y.Length);
  23. }
  24. }
  25. static void Main(string[] args)
  26. {
  27. // 数据来源:https://introcs.cs.princeton.edu/java/data/california-gov.txt
  28. StreamReader sr = new StreamReader(File.OpenRead("california-gov.txt"));
  29. string[] names =
  30. sr.ReadToEnd()
  31. .ToUpper()
  32. .Split
  33. (new char[] { '\n', '\r' },
  34. StringSplitOptions.RemoveEmptyEntries);
  35. Array.Sort(names, new CandidateComparer());
  36. for (int i = 0; i < names.Length; i++)
  37. {
  38. Console.WriteLine(names[i]);
  39. }
  40. }
  41. }
  42. }

2.5.17

解答

用一个 Wrapper 类包装准备排序的元素,在排序前同时记录元素的内容和下标。

随后对 Wrapper 数组排序,相同的元素会被放在一起,检查它们的下标是否是递增的。

如果不是递增的,则排序算法就是不稳定的;否则排序算法就有可能是稳定的。

(不稳定的排序算法也可能不改变相同元素的相对位置,比如用选择排序对有序数组排序)

代码
  1. using System;
  2. using SortApplication;
  3. namespace _2._5._17
  4. {
  5. class Program
  6. {
  7. class Wrapper<T> : IComparable<Wrapper<T>> where T : IComparable<T>
  8. {
  9. public int Index;
  10. public T Key;
  11. public Wrapper(int index, T elements)
  12. {
  13. this.Index = index;
  14. this.Key = elements;
  15. }
  16. public int CompareTo(Wrapper<T> other)
  17. {
  18. return this.Key.CompareTo(other.Key);
  19. }
  20. }
  21. static void Main(string[] args)
  22. {
  23. int[] data = new int[] { 7, 7, 4, 8, 8, 5, 1, 7, 7 };
  24. MergeSort merge = new MergeSort();
  25. InsertionSort insertion = new InsertionSort();
  26. ShellSort shell = new ShellSort();
  27. SelectionSort selection = new SelectionSort();
  28. QuickSort quick = new QuickSort();
  29. Console.WriteLine("Merge Sort: " + CheckStability(data, merge));
  30. Console.WriteLine("Insertion Sort: " + CheckStability(data, insertion));
  31. Console.WriteLine("Shell Sort: " + CheckStability(data, shell));
  32. Console.WriteLine("Selection Sort: " + CheckStability(data, selection));
  33. Console.WriteLine("Quick Sort: " + CheckStability(data, quick));
  34. }
  35. static bool CheckStability<T>(T[] data, BaseSort sort) where T : IComparable<T>
  36. {
  37. Wrapper<T>[] items = new Wrapper<T>[data.Length];
  38. for (int i = 0; i < data.Length; i++)
  39. items[i] = new Wrapper<T>(i, data[i]);
  40. sort.Sort(items);
  41. int index = 0;
  42. while (index < data.Length - 1)
  43. {
  44. while (index < data.Length - 1 && items[index].Key.Equals(items[index + 1].Key))
  45. {
  46. if (items[index].Index > items[index + 1].Index)
  47. return false;
  48. index++;
  49. }
  50. index++;
  51. }
  52. return true;
  53. }
  54. }
  55. }
另请参阅

SortApplication 库

2.5.18

解答

用和上题一样的 Wrapper 类进行排序。

排序之后,相同的元素会被放在一起,形成一个个子数组。

根据事先保存的原始下标对它们进行排序,即可将不稳定的排序稳定化。

结果:

代码
  1. using System;
  2. using SortApplication;
  3. namespace _2._5._18
  4. {
  5. class Program
  6. {
  7. class Wrapper<T> : IComparable<Wrapper<T>> where T : IComparable<T>
  8. {
  9. public int Index;
  10. public T Key;
  11. public Wrapper(int index, T elements)
  12. {
  13. this.Index = index;
  14. this.Key = elements;
  15. }
  16. public int CompareTo(Wrapper<T> other)
  17. {
  18. return this.Key.CompareTo(other.Key);
  19. }
  20. }
  21. static void Main(string[] args)
  22. {
  23. int[] data = new int[] { 5, 7, 3, 4, 7, 3, 6, 3, 3 };
  24. QuickSort quick = new QuickSort();
  25. ShellSort shell = new ShellSort();
  26. Console.WriteLine("Quick Sort");
  27. Stabilize(data, quick);
  28. Console.WriteLine();
  29. Console.WriteLine("Shell Sort");
  30. Stabilize(data, shell);
  31. }
  32. static void Stabilize<T>(T[] data, BaseSort sort) where T : IComparable<T>
  33. {
  34. Wrapper<T>[] items = new Wrapper<T>[data.Length];
  35. for (int i = 0; i < data.Length; i++)
  36. {
  37. items[i] = new Wrapper<T>(i, data[i]);
  38. }
  39. sort.Sort(items);
  40. Console.Write("Index:\t");
  41. for (int i = 0; i < items.Length; i++)
  42. {
  43. Console.Write(items[i].Index + " ");
  44. }
  45. Console.WriteLine();
  46. Console.Write("Elem:\t");
  47. for (int i = 0; i < items.Length; i++)
  48. {
  49. Console.Write(items[i].Key + " ");
  50. }
  51. Console.WriteLine();
  52. Console.WriteLine();
  53. int index = 0;
  54. while (index < items.Length - 1)
  55. {
  56. while (index < items.Length - 1 &&
  57. items[index].Key.Equals(items[index + 1].Key))
  58. {
  59. // 插入排序
  60. for (int j = index + 1; j > 0 && items[j].Index < items[j - 1].Index; j--)
  61. {
  62. if (!items[j].Key.Equals(items[j - 1].Key))
  63. break;
  64. Wrapper<T> temp = items[j];
  65. items[j] = items[j - 1];
  66. items[j - 1] = temp;
  67. }
  68. index++;
  69. }
  70. index++;
  71. }
  72. Console.Write("Index:\t");
  73. for (int i = 0; i < items.Length; i++)
  74. {
  75. Console.Write(items[i].Index + " ");
  76. }
  77. Console.WriteLine();
  78. Console.Write("Elem:\t");
  79. for (int i = 0; i < items.Length; i++)
  80. {
  81. Console.Write(items[i].Key + " ");
  82. }
  83. Console.WriteLine();
  84. }
  85. }
  86. }
另请参阅

SortApplication 库

2.5.19

解答

官方解答:

Kendall Tau:https://algs4.cs.princeton.edu/25applications/KendallTau.java.html

Inversion:https://algs4.cs.princeton.edu/22mergesort/Inversions.java.html

由书中 2.5.3.2 节得,两个数组之间的 Kendall Tau 距离即为两数组之间顺序不同的数对数目。

如果能够把其中一个数组变成标准排列(即 1,2,3,4... 这样的数组),

那么此时 Kendall Tau 距离就等于另一个数组中的逆序对数量。

现在我们来解决如何把一个数组 a 变成标准排列的方法。

也就是找到函数 $ f(x) ​$,使得 $ f(a[i])=i ​$ ,这样的函数其实就是数组 a 的逆数组。

如下图所示,逆数组 ainv 即为满足 ainv[a[i]] = i 的数组。



获得逆数组之后,对另一个数组 b 做同样的变换,令数组 bnew[i] = ainv[b[i]]

ainv[a[i]] = i, ainv[b[i]] = bnew[i]

于是问题转化为了 bnew 和标准排列之间的 Kendall Tau 距离,即 bnew 的逆序对数量。

逆序对数量的求法见题 2.2.19。

代码
  1. using System;
  2. namespace _2._5._19
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. // 官方解答:
  9. // https://algs4.cs.princeton.edu/25applications/KendallTau.java.html
  10. // https://algs4.cs.princeton.edu/22mergesort/Inversions.java.html
  11. int[] testA = { 0, 3, 1, 6, 2, 5, 4 };
  12. int[] testB = { 1, 0, 3, 6, 4, 2, 5 };
  13. Console.WriteLine(Distance(testA, testB));
  14. }
  15. public static long Distance(int[] a, int[] b)
  16. {
  17. if (a.Length != b.Length)
  18. throw new ArgumentException("Array dimensions disagree");
  19. int n = a.Length;
  20. int[] ainv = new int[n];
  21. for (int i = 0; i < n; i++)
  22. {
  23. ainv[a[i]] = i;
  24. }
  25. int[] bnew = new int[n];
  26. for (int i = 0; i < n; i++)
  27. {
  28. bnew[i] = ainv[b[i]];
  29. }
  30. Inversions inversions = new Inversions();
  31. inversions.Count(bnew);
  32. return inversions.Counter;
  33. }
  34. }
  35. }

2.5.20

解答

我们以事件为单位进行处理,每个事件包含任务名,记录时刻和开始/结束标记。

随后按照时间从小到大排序,遍历事件数组。

设开始的时候机器空闲,设置计数器,作为当前正在运行的任务数量。

当遇到开始事件时,计数器加一;遇到结束事件时,计数器减一。

如果计数器加一之前计数器为 0,说明空闲状态结束,记录并更新空闲时间,当前时间为忙碌开始的时间。

如果计数器减一之后计数器为 0,说明忙碌状态结束,记录并更新忙碌时间,当前时间为空闲开始的时间。

测试结果:

代码
  1. using System;
  2. namespace _2._5._20
  3. {
  4. class Program
  5. {
  6. /// <summary>
  7. /// 任务变化事件。
  8. /// </summary>
  9. class JobEvent : IComparable<JobEvent>
  10. {
  11. public string JobName;
  12. public int Time;
  13. public bool IsFinished = false; // false = 开始,true = 结束
  14. public int CompareTo(JobEvent other)
  15. {
  16. return this.Time.CompareTo(other.Time);
  17. }
  18. }
  19. static void Main(string[] args)
  20. {
  21. // 输入格式: JobName 15:02 17:02
  22. int nowRunning = 0; // 正在运行的程序数量
  23. int maxIdle = 0;
  24. int maxBusy = 0;
  25. int items = int.Parse(Console.ReadLine());
  26. JobEvent[] jobs = new JobEvent[items * 2];
  27. for (int i = 0; i < jobs.Length; i += 2)
  28. {
  29. jobs[i] = new JobEvent();
  30. jobs[i + 1] = new JobEvent();
  31. jobs[i].IsFinished = false; // 开始事件
  32. jobs[i + 1].IsFinished = true; // 停止事件
  33. string[] record = Console.ReadLine().Split(new char[] { ' ', ':' }, StringSplitOptions.RemoveEmptyEntries);
  34. jobs[i].JobName = record[0];
  35. jobs[i + 1].JobName = record[0];
  36. jobs[i].Time = int.Parse(record[1]) * 60 + int.Parse(record[2]);
  37. jobs[i + 1].Time = int.Parse(record[3]) * 60 + int.Parse(record[4]);
  38. }
  39. Array.Sort(jobs);
  40. // 事件处理
  41. int idleStart = 0;
  42. int busyStart = 0;
  43. for (int i = 0; i < jobs.Length; i++)
  44. {
  45. // 启动事件
  46. if (!jobs[i].IsFinished)
  47. {
  48. // 空闲状态结束
  49. if (nowRunning == 0)
  50. {
  51. int idle = jobs[i].Time - idleStart;
  52. if (idle > maxIdle)
  53. maxIdle = idle;
  54. // 开始忙碌
  55. busyStart = jobs[i].Time;
  56. }
  57. nowRunning++;
  58. }
  59. else
  60. {
  61. nowRunning--;
  62. // 忙碌状态结束
  63. if (nowRunning == 0)
  64. {
  65. int busy = jobs[i].Time - busyStart;
  66. if (busy > maxBusy)
  67. maxBusy = busy;
  68. // 开始空闲
  69. idleStart = jobs[i].Time;
  70. }
  71. }
  72. }
  73. Console.WriteLine("Max Idle: " + maxIdle);
  74. Console.WriteLine("Max Busy: " + maxBusy);
  75. }
  76. }
  77. }

2.5.21

解答

与之前的版本号比较十分类似,对数组进行包装,然后按照次序依次比较即可。

  1. using System;
  2. using System.Text;
  3. namespace _2._5._21
  4. {
  5. class Vector : IComparable<Vector>
  6. {
  7. private int[] data;
  8. public int Length { get; set; }
  9. public Vector(int[] data)
  10. {
  11. this.data = data;
  12. this.Length = data.Length;
  13. }
  14. public int CompareTo(Vector other)
  15. {
  16. int maxN = Math.Max(this.Length, other.Length);
  17. for (int i = 0; i < maxN; i++)
  18. {
  19. int comp = this.data[i].CompareTo(other.data[i]);
  20. if (comp != 0)
  21. return comp;
  22. }
  23. return this.Length.CompareTo(other.Length);
  24. }
  25. public override string ToString()
  26. {
  27. StringBuilder sb = new StringBuilder();
  28. for (int i = 0; i < this.Length; i++)
  29. {
  30. if (i != 0)
  31. sb.Append(' ');
  32. sb.Append(this.data[i]);
  33. }
  34. return sb.ToString();
  35. }
  36. }
  37. }

2.5.22

解答

建立最小堆和最大堆,最小堆保存卖家的报价,最大堆保存买家的报价。

如果最小堆中的最低卖出价低于最大堆的最高买入价,交易达成,交易份额较大的一方需要重新回到堆内。

测试结果:

代码
  1. using System;
  2. using SortApplication;
  3. namespace _2._5._22
  4. {
  5. class Program
  6. {
  7. class Ticket : IComparable<Ticket>
  8. {
  9. public double Price;
  10. public int Share;
  11. public int CompareTo(Ticket other)
  12. {
  13. return this.Price.CompareTo(other.Price);
  14. }
  15. }
  16. static void Main(string[] args)
  17. {
  18. // 输入格式: buy 20.05 100
  19. MaxPQ<Ticket> buyer = new MaxPQ<Ticket>();
  20. MinPQ<Ticket> seller = new MinPQ<Ticket>();
  21. int n = int.Parse(Console.ReadLine());
  22. for (int i = 0; i < n; i++)
  23. {
  24. Ticket ticket = new Ticket();
  25. string[] item = Console.ReadLine().Split(' ');
  26. ticket.Price = double.Parse(item[1]);
  27. ticket.Share = int.Parse(item[2]);
  28. if (item[0] == "buy")
  29. buyer.Insert(ticket);
  30. else
  31. seller.Insert(ticket);
  32. }
  33. while (!buyer.IsEmpty() && !seller.IsEmpty())
  34. {
  35. if (buyer.Max().Price < seller.Min().Price)
  36. break;
  37. Ticket buy = buyer.DelMax();
  38. Ticket sell = seller.DelMin();
  39. Console.Write("sell $" + sell.Price + " * " + sell.Share);
  40. if (buy.Share > sell.Share)
  41. {
  42. Console.WriteLine(" -> " + sell.Share + " -> $" + buy.Price + " * " + buy.Share + " buy");
  43. buy.Share -= sell.Share;
  44. buyer.Insert(buy);
  45. }
  46. else if (buy.Share < sell.Share)
  47. {
  48. sell.Share -= buy.Share;
  49. seller.Insert(sell);
  50. Console.WriteLine(" -> " + buy.Share + " -> $" + buy.Price + " * " + buy.Share + " buy");
  51. }
  52. else
  53. {
  54. Console.WriteLine(" -> " + sell.Share + " -> $" + buy.Price + " * " + buy.Share + " buy");
  55. }
  56. }
  57. }
  58. }
  59. }
另请参阅

SortApplication 库

2.5.23

解答

这里我们使用 Floyd-Rivest 算法进行优化,大致思想是:

我们期望第 $ k $ 大的元素位于 a[k] 附近,因此优先对 a[k] 附近的区域进行选择。

每次切分时枢轴都选择 a[k],先递归对样本区域选择,再对整个数组进行选择。

运行示意图:

测试结果:

代码
  1. /// <summary>
  2. /// Floyd–Rivest 方法优化,令 a[k] 变成第 k 小的元素。
  3. /// </summary>
  4. /// <typeparam name="T">元素类型。</typeparam>
  5. /// <param name="a">需要排序的数组。</param>
  6. /// <param name="k">序号</param>
  7. /// <returns></returns>
  8. static T Select<T>(T[] a, int lo, int hi, int k) where T : IComparable<T>
  9. {
  10. if (k < 0 || k > a.Length)
  11. throw new IndexOutOfRangeException("Select elements out of bounds");
  12. while (hi > lo)
  13. {
  14. if (hi - lo > 600)
  15. {
  16. int n = hi - lo + 1;
  17. int i = k - lo + 1;
  18. int z = (int)Math.Log(n);
  19. int s = (int)(Math.Exp(2 * z / 3) / 2);
  20. int sd = (int)Math.Sqrt(z * s * (n - s) / n) * Math.Sign(i - n / 2) / 2;
  21. int newLo = Math.Max(lo, k - i * s / n + sd);
  22. int newHi = Math.Min(hi, k + (n - i) * s / n + sd);
  23. Select(a, newLo, newHi, k);
  24. }
  25. Exch(a, lo, k);
  26. int j = Partition(a, lo, hi);
  27. if (j > k)
  28. hi = j - 1;
  29. else if (j < k)
  30. lo = j + 1;
  31. else
  32. return a[j];
  33. }
  34. return a[lo];
  35. }
另请参阅

Floyd–Rivest algorithm - Wikipedia

2.5.24

解答

官方解答:https://algs4.cs.princeton.edu/25applications/StableMinPQ.java.html

在元素插入的同时记录插入顺序,比较的时候把插入顺序也纳入比较。

对于值一样的元素,插入顺序在前的的元素比较小。

交换的时候需要同时交换插入次序。

代码
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace SortApplication
  5. {
  6. /// <summary>
  7. /// 稳定的最小堆。(数组实现)
  8. /// </summary>
  9. /// <typeparam name="Key">最小堆中保存的元素类型。</typeparam>
  10. public class MinPQStable<Key> : IMinPQ<Key>, IEnumerable<Key> where Key : IComparable<Key>
  11. {
  12. protected Key[] pq; // 保存元素的数组。
  13. protected int n; // 堆中的元素数量。
  14. private long[] time; // 元素的插入次序。
  15. private long timeStamp = 1; // 元素插入次序计数器。
  16. /// <summary>
  17. /// 默认构造函数。
  18. /// </summary>
  19. public MinPQStable() : this(1) { }
  20. /// <summary>
  21. /// 建立指定容量的最小堆。
  22. /// </summary>
  23. /// <param name="capacity">最小堆的容量。</param>
  24. public MinPQStable(int capacity)
  25. {
  26. this.time = new long[capacity + 1];
  27. this.pq = new Key[capacity + 1];
  28. this.n = 0;
  29. }
  30. /// <summary>
  31. /// 删除并返回最小元素。
  32. /// </summary>
  33. /// <returns></returns>
  34. public Key DelMin()
  35. {
  36. if (IsEmpty())
  37. throw new ArgumentOutOfRangeException("Priority Queue Underflow");
  38. Key min = this.pq[1];
  39. Exch(1, this.n--);
  40. Sink(1);
  41. this.pq[this.n + 1] = default(Key);
  42. this.time[this.n + 1] = 0;
  43. if ((this.n > 0) && (this.n == this.pq.Length / 4))
  44. Resize(this.pq.Length / 2);
  45. Debug.Assert(IsMinHeap());
  46. return min;
  47. }
  48. /// <summary>
  49. /// 向堆中插入一个元素。
  50. /// </summary>
  51. /// <param name="v">需要插入的元素。</param>
  52. public void Insert(Key v)
  53. {
  54. if (this.n == this.pq.Length - 1)
  55. Resize(2 * this.pq.Length);
  56. this.pq[++this.n] = v;
  57. this.time[this.n] = ++this.timeStamp;
  58. Swim(this.n);
  59. //Debug.Assert(IsMinHeap());
  60. }
  61. /// <summary>
  62. /// 检查堆是否为空。
  63. /// </summary>
  64. /// <returns></returns>
  65. public bool IsEmpty() => this.n == 0;
  66. /// <summary>
  67. /// 获得堆中最小元素。
  68. /// </summary>
  69. /// <returns></returns>
  70. public Key Min() => this.pq[1];
  71. /// <summary>
  72. /// 获得堆中元素的数量。
  73. /// </summary>
  74. /// <returns></returns>
  75. public int Size() => this.n;
  76. /// <summary>
  77. /// 获取堆的迭代器,元素以降序排列。
  78. /// </summary>
  79. /// <returns></returns>
  80. public IEnumerator<Key> GetEnumerator()
  81. {
  82. MaxPQ<Key> copy = new MaxPQ<Key>(this.n);
  83. for (int i = 1; i <= this.n; i++)
  84. copy.Insert(this.pq[i]);
  85. while (!copy.IsEmpty())
  86. yield return copy.DelMax(); // 下次迭代的时候从这里继续执行。
  87. }
  88. /// <summary>
  89. /// 获取堆的迭代器,元素以降序排列。
  90. /// </summary>
  91. /// <returns></returns>
  92. IEnumerator IEnumerable.GetEnumerator()
  93. {
  94. return GetEnumerator();
  95. }
  96. /// <summary>
  97. /// 使元素上浮。
  98. /// </summary>
  99. /// <param name="k">需要上浮的元素。</param>
  100. private void Swim(int k)
  101. {
  102. while (k > 1 && Greater(k / 2, k))
  103. {
  104. Exch(k, k / 2);
  105. k /= 2;
  106. }
  107. }
  108. /// <summary>
  109. /// 使元素下沉。
  110. /// </summary>
  111. /// <param name="k">需要下沉的元素。</param>
  112. private void Sink(int k)
  113. {
  114. while (k * 2 <= this.n)
  115. {
  116. int j = 2 * k;
  117. if (j < this.n && Greater(j, j + 1))
  118. j++;
  119. if (!Greater(k, j))
  120. break;
  121. Exch(k, j);
  122. k = j;
  123. }
  124. }
  125. /// <summary>
  126. /// 重新调整堆的大小。
  127. /// </summary>
  128. /// <param name="capacity">调整后的堆大小。</param>
  129. private void Resize(int capacity)
  130. {
  131. Key[] temp = new Key[capacity];
  132. long[] timeTemp = new long[capacity];
  133. for (int i = 1; i <= this.n; i++)
  134. {
  135. temp[i] = this.pq[i];
  136. timeTemp[i] = this.time[i];
  137. }
  138. this.pq = temp;
  139. this.time = timeTemp;
  140. }
  141. /// <summary>
  142. /// 判断堆中某个元素是否大于另一元素。
  143. /// </summary>
  144. /// <param name="i">判断是否较大的元素。</param>
  145. /// <param name="j">判断是否较小的元素。</param>
  146. /// <returns></returns>
  147. private bool Greater(int i, int j)
  148. {
  149. int cmp = this.pq[i].CompareTo(this.pq[j]);
  150. if (cmp == 0)
  151. return this.time[i].CompareTo(this.time[j]) > 0;
  152. return cmp > 0;
  153. }
  154. /// <summary>
  155. /// 交换堆中的两个元素。
  156. /// </summary>
  157. /// <param name="i">要交换的第一个元素下标。</param>
  158. /// <param name="j">要交换的第二个元素下标。</param>
  159. protected virtual void Exch(int i, int j)
  160. {
  161. Key swap = this.pq[i];
  162. this.pq[i] = this.pq[j];
  163. this.pq[j] = swap;
  164. long temp = this.time[i];
  165. this.time[i] = this.time[j];
  166. this.time[j] = temp;
  167. }
  168. /// <summary>
  169. /// 检查当前二叉树是不是一个最小堆。
  170. /// </summary>
  171. /// <returns></returns>
  172. private bool IsMinHeap() => IsMinHeap(1);
  173. /// <summary>
  174. /// 确定以 k 为根节点的二叉树是不是一个最小堆。
  175. /// </summary>
  176. /// <param name="k">需要检查的二叉树根节点。</param>
  177. /// <returns></returns>
  178. private bool IsMinHeap(int k)
  179. {
  180. if (k > this.n)
  181. return true;
  182. int left = 2 * k;
  183. int right = 2 * k + 1;
  184. if (left <= this.n && Greater(k, left))
  185. return false;
  186. if (right <= this.n && Greater(k, right))
  187. return false;
  188. return IsMinHeap(left) && IsMinHeap(right);
  189. }
  190. }
  191. }
另请参阅

SortApplication 库

2.5.25

解答

官方解答见:https://algs4.cs.princeton.edu/25applications/Point2D.java.html

这些比较器都以嵌套类的形式在 Point2D 中定义。

静态比较器直接在类中以静态成员的方式声明。

非静态比较器则需要提供工厂方法,该方法新建并返回对应的比较器对象。

代码
  1. /// <summary>
  2. /// 按照 X 顺序比较。
  3. /// </summary>
  4. private class XOrder : Comparer<Point2D>
  5. {
  6. public override int Compare(Point2D x, Point2D y)
  7. {
  8. if (x.X < y.X)
  9. return -1;
  10. if (x.X > y.X)
  11. return 1;
  12. return 0;
  13. }
  14. }
  15. /// <summary>
  16. /// 按照 Y 顺序比较。
  17. /// </summary>
  18. private class YOrder : Comparer<Point2D>
  19. {
  20. public override int Compare(Point2D x, Point2D y)
  21. {
  22. if (x.Y < y.Y)
  23. return -1;
  24. if (x.Y > y.Y)
  25. return 1;
  26. return 0;
  27. }
  28. }
  29. /// <summary>
  30. /// 按照极径顺序比较。
  31. /// </summary>
  32. private class ROrder : Comparer<Point2D>
  33. {
  34. public override int Compare(Point2D x, Point2D y)
  35. {
  36. double delta = (x.X * x.X + x.Y * x.Y) - (y.X * y.X + y.Y * y.Y);
  37. if (delta < 0)
  38. return -1;
  39. if (delta > 0)
  40. return 1;
  41. return 0;
  42. }
  43. }
  44. /// <summary>
  45. /// 按照 atan2 值顺序比较。
  46. /// </summary>
  47. private class Atan2Order : Comparer<Point2D>
  48. {
  49. private Point2D parent;
  50. public Atan2Order() { }
  51. public Atan2Order(Point2D parent)
  52. {
  53. this.parent = parent;
  54. }
  55. public override int Compare(Point2D x, Point2D y)
  56. {
  57. double angle1 = this.parent.AngleTo(x);
  58. double angle2 = this.parent.AngleTo(y);
  59. if (angle1 < angle2)
  60. return -1;
  61. if (angle1 > angle2)
  62. return 1;
  63. return 0;
  64. }
  65. }
  66. /// <summary>
  67. /// 按照极角顺序比较。
  68. /// </summary>
  69. private class PolorOrder : Comparer<Point2D>
  70. {
  71. private Point2D parent;
  72. public PolorOrder() { }
  73. public PolorOrder(Point2D parent)
  74. {
  75. this.parent = parent;
  76. }
  77. public override int Compare(Point2D q1, Point2D q2)
  78. {
  79. double dx1 = q1.X - this.parent.X;
  80. double dy1 = q1.Y - this.parent.Y;
  81. double dx2 = q2.X - this.parent.X;
  82. double dy2 = q2.Y - this.parent.Y;
  83. if (dy2 >= 0 && dy2 < 0)
  84. return -1;
  85. else if (dy2 >= 0 && dy1 < 0)
  86. return 1;
  87. else if (dy1 == 0 && dy2 == 0)
  88. {
  89. if (dx1 >= 0 && dx2 < 0)
  90. return -1;
  91. else if (dx2 >= 0 && dx1 < 0)
  92. return 1;
  93. return 0;
  94. }
  95. else
  96. return -CCW(this.parent, q1, q2);
  97. }
  98. }
  99. /// <summary>
  100. /// 按照距离顺序比较。
  101. /// </summary>
  102. private class DistanceToOrder : Comparer<Point2D>
  103. {
  104. private Point2D parent;
  105. public DistanceToOrder() { }
  106. public DistanceToOrder(Point2D parent)
  107. {
  108. this.parent = parent;
  109. }
  110. public override int Compare(Point2D p, Point2D q)
  111. {
  112. double dist1 = this.parent.DistanceSquareTo(p);
  113. double dist2 = this.parent.DistanceSquareTo(q);
  114. if (dist1 < dist2)
  115. return -1;
  116. else if (dist1 > dist2)
  117. return 1;
  118. else
  119. return 0;
  120. }
  121. }
  122. /// <summary>
  123. /// 提供到当前点极角的比较器。
  124. /// </summary>
  125. /// <returns></returns>
  126. public Comparer<Point2D> Polor_Order()
  127. {
  128. return new PolorOrder(this);
  129. }
  130. /// <summary>
  131. /// 提供到当前点 Atan2 值的比较器。
  132. /// </summary>
  133. /// <returns></returns>
  134. public Comparer<Point2D> Atan2_Order()
  135. {
  136. return new Atan2Order(this);
  137. }
  138. /// <summary>
  139. /// 提供到当前点距离的比较器。
  140. /// </summary>
  141. /// <returns></returns>
  142. public Comparer<Point2D> DistanceTo_Order()
  143. {
  144. return new DistanceToOrder(this);
  145. }
另请参阅

SortApplication 库

2.5.26

解答

提示中已经给出了方法,使用上一题编写的比较器进行排序即可。

效果演示:

代码

绘图部分代码:

  1. using System.Collections.Generic;
  2. using System.Drawing;
  3. using System.Windows.Forms;
  4. using SortApplication;
  5. namespace _2._5._26
  6. {
  7. public partial class Form2 : Form
  8. {
  9. Graphics panel;
  10. List<Point2D> points;
  11. Point2D startPoint;
  12. double maxX = 0, maxY = 0;
  13. public Form2()
  14. {
  15. InitializeComponent();
  16. }
  17. /// <summary>
  18. /// 显示并初始化绘图窗口。
  19. /// </summary>
  20. public void Init()
  21. {
  22. Show();
  23. this.panel = CreateGraphics();
  24. this.points = new List<Point2D>();
  25. this.startPoint = null;
  26. }
  27. /// <summary>
  28. /// 向画板中添加一个点。
  29. /// </summary>
  30. /// <param name="point"></param>
  31. public void Add(Point2D point)
  32. {
  33. this.points.Add(point);
  34. if (this.startPoint == null)
  35. {
  36. this.startPoint = point;
  37. this.maxX = point.X * 1.1;
  38. this.maxY = point.Y * 1.1;
  39. }
  40. else if (this.startPoint.Y > point.Y)
  41. this.startPoint = point;
  42. else if (this.startPoint.Y == point.Y && this.startPoint.X > point.X)
  43. this.startPoint = point;
  44. if (point.X > this.maxX)
  45. this.maxX = point.X * 1.1;
  46. if (point.Y > this.maxY)
  47. this.maxY = point.Y * 1.1;
  48. this.points.Sort(this.startPoint.Polor_Order());
  49. RefreashPoints();
  50. }
  51. public void RefreashPoints()
  52. {
  53. double unitX = this.ClientRectangle.Width / this.maxX;
  54. double unitY = this.ClientRectangle.Height / this.maxY;
  55. double left = this.ClientRectangle.Left;
  56. double bottom = this.ClientRectangle.Bottom;
  57. this.panel.Clear(this.BackColor);
  58. Pen line = (Pen)Pens.Red.Clone();
  59. line.Width = 6;
  60. Point2D before = this.startPoint;
  61. foreach (var p in this.points)
  62. {
  63. this.panel.FillEllipse(Brushes.Black,
  64. (float)(left + p.X * unitX - 5.0),
  65. (float)(bottom - p.Y * unitY - 5.0),
  66. (float)10.0,
  67. (float)10.0);
  68. this.panel.DrawLine(line,
  69. (float)(left + before.X * unitX),
  70. (float)(bottom - before.Y * unitY),
  71. (float)(left + p.X * unitX),
  72. (float)(bottom - p.Y * unitY));
  73. before = p;
  74. }
  75. this.panel.DrawLine(line,
  76. (float)(left + before.X * unitX),
  77. (float)(bottom - before.Y * unitY),
  78. (float)(left + this.startPoint.X * unitX),
  79. (float)(bottom - this.startPoint.Y * unitY));
  80. }
  81. }
  82. }
另请参阅

SortApplication 库

2.5.27

解答

类似于索引排序的做法,访问数组都通过一层索引来间接实现。

首先创建一个数组 index,令 index[i] = i

排序时的交换变成 index 数组中元素的交换,

读取元素时使用 a[index[i]] 而非 a[i]

代码
  1. /// <summary>
  2. /// 间接排序。
  3. /// </summary>
  4. /// <typeparam name="T"></typeparam>
  5. /// <param name="keys"></param>
  6. /// <returns></returns>
  7. static int[] IndirectSort<T>(T[] keys) where T : IComparable<T>
  8. {
  9. int n = keys.Length;
  10. int[] index = new int[n];
  11. for (int i = 0; i < n; i++)
  12. index[i] = i;
  13. for (int i = 0; i < n; i++)
  14. for (int j = i; j > 0 && keys[index[j]].CompareTo(keys[index[j - 1]]) < 0; j--)
  15. {
  16. int temp = index[j];
  17. index[j] = index[j - 1];
  18. index[j - 1] = temp;
  19. }
  20. return index;
  21. }

2.5.28

解答

官方解答:https://algs4.cs.princeton.edu/25applications/FileSorter.java.html

先获得目录里的所有文件名,然后排序输出即可。

代码
  1. using System;
  2. using System.IO;
  3. namespace _2._5._28
  4. {
  5. class Program
  6. {
  7. // 官方解答:https://algs4.cs.princeton.edu/25applications/FileSorter.java.html
  8. static void Main(string[] args)
  9. {
  10. // 输入 ./ 获得当前目录文件。
  11. string directoryName = Console.ReadLine();
  12. if (!Directory.Exists(directoryName))
  13. {
  14. Console.WriteLine(directoryName + " doesn't exist or isn't a directory");
  15. return;
  16. }
  17. string[] directoryFiles = Directory.GetFiles(directoryName);
  18. Array.Sort(directoryFiles);
  19. for (int i = 0; i < directoryFiles.Length; i++)
  20. Console.WriteLine(directoryFiles[i]);
  21. }
  22. }
  23. }

2.5.29

解答

首先定义一系列比较器,分别根据文件大小、文件名和最后修改日期比较。

然后修改 Less 的实现,接受一个比较器数组,使用数组中的比较器依次比较,直到比较结果为两者不相同。

最后使用插入排序作为稳定排序,传入比较器数组用于 Less 函数。

代码
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. namespace _2._5._29
  5. {
  6. class Program
  7. {
  8. class FileSizeComparer : Comparer<FileInfo>
  9. {
  10. public override int Compare(FileInfo x, FileInfo y)
  11. {
  12. return x.Length.CompareTo(y.Length);
  13. }
  14. }
  15. class FileNameComparer : Comparer<FileInfo>
  16. {
  17. public override int Compare(FileInfo x, FileInfo y)
  18. {
  19. return x.FullName.CompareTo(y.FullName);
  20. }
  21. }
  22. class FileTimeStampComparer : Comparer<FileInfo>
  23. {
  24. public override int Compare(FileInfo x, FileInfo y)
  25. {
  26. return x.LastWriteTime.CompareTo(y.LastWriteTime);
  27. }
  28. }
  29. static void InsertionSort<T>(T[] keys, Comparer<T>[] comparers)
  30. {
  31. for (int i = 0; i < keys.Length; i++)
  32. for (int j = i; j > 0 && Less(keys, j, j - 1, comparers); j--)
  33. {
  34. T temp = keys[j];
  35. keys[j] = keys[j - 1];
  36. keys[j - 1] = temp;
  37. }
  38. }
  39. static bool Less<T>(T[] keys, int x, int y, Comparer<T>[] comparables)
  40. {
  41. int cmp = 0;
  42. for (int i = 0; i < comparables.Length && cmp == 0; i++)
  43. {
  44. cmp = comparables[i].Compare(keys[x], keys[y]);
  45. }
  46. return cmp < 0;
  47. }
  48. static void Main(string[] args)
  49. {
  50. string[] arguments = Console.ReadLine().Split(' ');
  51. string directoryPath = arguments[0];
  52. string[] filenames = Directory.GetFiles(directoryPath);
  53. FileInfo[] fileInfos = new FileInfo[filenames.Length];
  54. for (int i = 0; i < filenames.Length; i++)
  55. fileInfos[i] = new FileInfo(filenames[i]);
  56. List<Comparer<FileInfo>> comparers = new List<Comparer<FileInfo>>();
  57. for (int i = 1; i < arguments.Length; i++)
  58. {
  59. string command = arguments[i];
  60. switch (command)
  61. {
  62. case "-t":
  63. comparers.Add(new FileTimeStampComparer());
  64. break;
  65. case "-s":
  66. comparers.Add(new FileSizeComparer());
  67. break;
  68. case "-n":
  69. comparers.Add(new FileNameComparer());
  70. break;
  71. }
  72. }
  73. InsertionSort(fileInfos, comparers.ToArray());
  74. for (int i = 0; i < fileInfos.Length; i++)
  75. {
  76. Console.WriteLine(fileInfos[i].Name + "\t" + fileInfos[i].Length + "\t" + fileInfos[i].LastWriteTime);
  77. }
  78. }
  79. }
  80. }

2.5.30

解答

不妨按照升序排序,$ x_{ij} $ 代表第 $ i $ 行第 $ j $ 列的元素。

首先保证每列都是有序的。

对第一行排序,对于第一行的元素 $ x_{1i} $ ,排序结果无非两种。

要么 $ x_{1i} $ 不改变,要么和更小的元素进行交换。

显然,无论哪种情况,第 $ i $ 列都是有序的。

因此对第一行排序之后,第一行有序,每一列都分别有序。

之后我们对第二行排序,考虑元素 $ x_{11} $。

此时 $ x_{11} $ 小于第一列的所有其他元素,也小于第一行的所有其他元素。

又每一列都分别有序,因此 $ x_{11} $ 是整个矩阵的最小值,第二行不存在比它小的元素。

考虑使用选择排序,我们把第二行的最小值和 $ x_{21} $ 交换,第一列仍然有序。

现在去掉第一列,对剩下的矩阵做一样的操作,可以将第二行依次排序。

同时保证第二行的元素都小于同列的第一行元素。

接下来的行都可以依次类推,最终将整个矩阵的所有行排序,定理得证。

2.5.31

解答

编写代码进行实验即可,实验结果如下,可以发现十分接近:

代码
  1. using System;
  2. namespace _2._5._31
  3. {
  4. class Program
  5. {
  6. /// <summary>
  7. /// 计算数组中重复元素的个数。
  8. /// </summary>
  9. /// <typeparam name="T"></typeparam>
  10. /// <param name="a">需要计算重复元素的数组。</param>
  11. /// <returns></returns>
  12. static int Distinct<T>(T[] a) where T : IComparable<T>
  13. {
  14. if (a.Length == 0)
  15. return 0;
  16. Array.Sort(a);
  17. int distinct = 1;
  18. for (int i = 1; i < a.Length; i++)
  19. if (a[i].CompareTo(a[i - 1]) != 0)
  20. distinct++;
  21. return distinct;
  22. }
  23. static void Main(string[] args)
  24. {
  25. int T = 10; // 重复次数
  26. int n = 1000; // 数组初始大小
  27. int nMultipleBy10 = 4; // 数组大小 ×10 的次数
  28. int mMultipleBy2 = 3; // 数据范围 ×2 的次数
  29. Random random = new Random();
  30. for (int i = 0; i < nMultipleBy10; i++)
  31. {
  32. Console.WriteLine("n=" + n);
  33. Console.WriteLine("\tm\temprical\ttheoretical");
  34. int m = n / 2;
  35. for (int j = 0; j < mMultipleBy2; j++)
  36. {
  37. int distinctSum = 0;
  38. for (int k = 0; k < T; k++)
  39. {
  40. int[] data = new int[n];
  41. for (int l = 0; l < n; l++)
  42. data[l] = random.Next(m);
  43. distinctSum += Distinct(data);
  44. }
  45. double empirical = (double)distinctSum / T;
  46. double alpha = (double)n / m;
  47. double theoretical = m * (1 - Math.Exp(-alpha));
  48. Console.WriteLine("\t" + m + "\t" + empirical + "\t" + theoretical);
  49. m *= 2;
  50. }
  51. n *= 10;
  52. }
  53. }
  54. }
  55. }

2.5.32

解答

(前置知识:提前了解 Dijkstra 算法能够降低理解 A* 算法的难度。)

A* 算法是 Dijkstra 算法和最佳优先算法的一种结合。

Dijkstra 算法需要遍历所有结点来找到最短路径,唯一的优化条件就是路径长度。

建立队列 queue ,把所有的结点加入 queue 中;建立数组 dd[v] 代表起点到点 v 的距离。

开始时只有起点到起点的距离为 0,其他都为无穷大,然后重复如下步骤:

从队列中取出已知距离最短的结点 u,检查该结点的所有边。

如果通过这个点能够以更近的距离到达 v,更新起点到 v 的距离 d[v] = d[u] + distance(u, v)

等到队列为空之后数组 d 中就存放着起点到其他所有结点的最短距离。

Dijkstra 算法会计算起点到所有点的最短路径,因此会均匀的遍历所有结点,效率较低。

很多时候,我们只需要找到起点到某一终点的最短路径即可,为此遍历整个图显然是不必要的。

通过修改算法,使得比较接近终点的结点优先得到搜索,我们就可能在遍历完全部结点之前获得结果。

在 Dijkstra 算法中,离起点最近的点会被优先搜索,记结点离起点的距离为 g[n]

现在引入新的条件,用于估计结点和终点的接近程度,记结点离终点的估计距离为 h[n]

f[n] = g[n] + h[n],我们按照 f[n] 对等待搜索的结点进行排序。

同时令 h[n] 始终小于 g[n] ,保证离起点的距离 g[n] 权重大于离终点的估计距离 h[n]

h[n]也被称之为容许估计

于是在离起点距离接近的条件下,离终点比较近的点会被优先搜索,减少搜索范围。

接下来就是算法的具体内容,与 Dijkstra 算法不同,A* 算法不一定需要访问所有结点,

因此 A* 算法需要维护两个集合,openSet 保存等待搜索的结点,closeSet 保存已经搜索过的结点。

和 Dijkstra 算法类似,一开始 openSet 中只有起点,closeSet 则是空的。

然后重复执行如下步骤,直到 openSet 为空:

openSet 中取出 f[n] 最小的结点 u ,放入 closeSet。(标记为已访问)

如果 u 就是终点,算法结束。

计算结点 u 直接可达的周围结点,放入集合 neighbors

遍历 neighbors 中的所有结点 v,做如下判断:

如果 v 已经存在于 closeSet ,忽略之。(防止走回头路)

如果经过 u 不能缩短起点到 v 的路径长度 g[v],忽略之。(和 Dijkstra 算法一样的做法)

否则将 v 放入 openSet,更新 g[v] = g[u] + distance(u, v) ,计算 f[v] = g[v] + h[v]。(更新结点)

以上是 A* 算法的核心逻辑,

为了结合具体问题,我们需要自定义计算 g[n]h[n] 的方法,以及获得某个结点周围结点的方法。

这里有个问题,openSetcloseSet 应该用什么数据结构?

closeSet 比较简单,只需要添加和查找即可,哈希表 HashSet 是不二选择。

openSet 需要读取并删除最小元素,以及添加和查找元素,用最小堆 MinPQ 会是比较方便的方法。

书中给出的最小堆 MinPQ 没有实现 Contains 方法,需要自己实现一个,简单顺序查找就够用了。

同时 MinPQGreater 比较方法也需要重新实现,需要使用基于 f[n] 进行比较的比较器。

现在我们考虑 8 字谜题如何用 A* 算法实现。

棋盘的每一个状态就是一个结点,每走一步就能进入下一个状态,结点可以这么定义:

  1. class SearchNode
  2. {
  3. int[] Board; // 棋盘状态
  4. int Steps; // 已经使用的步数
  5. }

g(start, goal) 直接就是 goal.Steps - start.Stepsh(start, goal) 则根据题意有不同的实现。

获得周围结点的方法 GetNeighbors(current),会返回一个数组,其中有从 current 上下左右走获得的棋盘状态。

运行结果,初始状态为:

  1. 0 1 3
  2. 4 2 5
  3. 7 9 6

代码

A* 算法的泛型实现

  1. using System;
  2. using System.Collections.Generic;
  3. namespace SortApplication
  4. {
  5. /// <summary>
  6. /// A* 搜索器。
  7. /// </summary>
  8. /// <typeparam name="T"></typeparam>
  9. public abstract class AStar<T> where T : IComparable<T>
  10. {
  11. /// <summary>
  12. /// 相等比较器。
  13. /// </summary>
  14. private readonly IEqualityComparer<T> equalityComparer;
  15. /// <summary>
  16. /// 默认相等比较器。
  17. /// </summary>
  18. class DefaultEqualityComparer : IEqualityComparer<T>
  19. {
  20. public bool Equals(T x, T y)
  21. {
  22. return x.Equals(y);
  23. }
  24. public int GetHashCode(T obj)
  25. {
  26. return obj.GetHashCode();
  27. }
  28. }
  29. /// <summary>
  30. /// 根据 FScore 进行比较的比较器。
  31. /// </summary>
  32. class FScoreComparer : IComparer<T>
  33. {
  34. Dictionary<T, int> fScore;
  35. public FScoreComparer(Dictionary<T, int> fScore)
  36. {
  37. this.fScore = fScore;
  38. }
  39. public int Compare(T x, T y)
  40. {
  41. if (!this.fScore.ContainsKey(x))
  42. this.fScore[x] = int.MaxValue;
  43. if (!this.fScore.ContainsKey(y))
  44. this.fScore[y] = int.MaxValue;
  45. return this.fScore[x].CompareTo(this.fScore[y]);
  46. }
  47. }
  48. /// <summary>
  49. /// 新建一个 Astar 寻路器,使用元素默认相等比较器。
  50. /// </summary>
  51. protected AStar() : this(new DefaultEqualityComparer()) { }
  52. /// <summary>
  53. /// 新建一个 AStar 寻路器。
  54. /// </summary>
  55. /// <param name="equalityComparer">用于确定状态之间相等的比较器。</param>
  56. protected AStar(IEqualityComparer<T> equalityComparer)
  57. {
  58. this.equalityComparer = equalityComparer;
  59. }
  60. /// <summary>
  61. /// 获得最短路径。
  62. /// </summary>
  63. /// <param name="start">起始状态。</param>
  64. /// <param name="goal">终止状态。</param>
  65. /// <returns></returns>
  66. public T[] GetPath(T start, T goal)
  67. {
  68. Dictionary<T, T> comeFrom = new Dictionary<T, T>(this.equalityComparer);
  69. Dictionary<T, int> gScore = new Dictionary<T, int>(this.equalityComparer);
  70. Dictionary<T, int> fScore = new Dictionary<T, int>(this.equalityComparer);
  71. MinPQ<T> openSet = new MinPQ<T>(new FScoreComparer(fScore), this.equalityComparer);
  72. HashSet<T> closeSet = new HashSet<T>(this.equalityComparer);
  73. openSet.Insert(start);
  74. gScore.Add(start, 0);
  75. fScore.Add(start, HeuristicDistance(start, goal));
  76. while (!openSet.IsEmpty())
  77. {
  78. T current = openSet.DelMin();
  79. if (this.equalityComparer.Equals(current, goal))
  80. return ReconstructPath(comeFrom, current);
  81. closeSet.Add(current);
  82. T[] neighbors = GetNeighbors(current);
  83. foreach (T neighbor in neighbors)
  84. {
  85. if (closeSet.Contains(neighbor))
  86. continue;
  87. int gScoreTentative = gScore[current] + ActualDistance(current, neighbor);
  88. // 新状态
  89. if (!openSet.Contains(neighbor))
  90. openSet.Insert(neighbor);
  91. else if (gScoreTentative >= gScore[neighbor])
  92. continue;
  93. // 记录新状态
  94. comeFrom[neighbor] = current;
  95. gScore[neighbor] = gScoreTentative;
  96. fScore[neighbor] = gScore[neighbor] + HeuristicDistance(neighbor, goal);
  97. }
  98. }
  99. return null;
  100. }
  101. /// <summary>
  102. /// 倒回重建最佳路径。
  103. /// </summary>
  104. /// <param name="status">包含所有状态的数组。</param>
  105. /// <param name="from">记载了状态之间顺序的数组。</param>
  106. /// <param name="current">当前状态位置。</param>
  107. /// <returns></returns>
  108. private T[] ReconstructPath(Dictionary<T, T> comeFrom, T current)
  109. {
  110. Stack<T> pathReverse = new Stack<T>();
  111. while (comeFrom.ContainsKey(current))
  112. {
  113. pathReverse.Push(current);
  114. current = comeFrom[current];
  115. }
  116. T[] path = new T[pathReverse.Count];
  117. for (int i = 0; i < path.Length; i++)
  118. {
  119. path[i] = pathReverse.Pop();
  120. }
  121. return path;
  122. }
  123. /// <summary>
  124. /// 计算两个状态之间的估计距离,即 h(n)。
  125. /// </summary>
  126. /// <param name="start">初始状态。</param>
  127. /// <param name="goal">目标状态。</param>
  128. /// <returns></returns>
  129. protected abstract int HeuristicDistance(T start, T goal);
  130. /// <summary>
  131. /// 计算两个状态之间的实际距离,即 g(n)。
  132. /// </summary>
  133. /// <param name="start">初始状态。</param>
  134. /// <param name="goal">目标状态。</param>
  135. /// <returns></returns>
  136. protected abstract int ActualDistance(T start, T goal);
  137. /// <summary>
  138. /// 获得当前状态的周围状态。
  139. /// </summary>
  140. /// <param name="current">当前状态。</param>
  141. /// <returns></returns>
  142. protected abstract T[] GetNeighbors(T current);
  143. }
  144. }
另请参阅

A* search algorithm-Wikipedia

SortApplication 库

2.5.33

解答

编写代码实验即可,结果如下:

代码

随机交易生成器 TransactionGenerator

  1. using System;
  2. using System.Text;
  3. using SortApplication;
  4. namespace _2._5._33
  5. {
  6. /// <summary>
  7. /// 随机交易生成器。
  8. /// </summary>
  9. class TransactionGenerator
  10. {
  11. private static Random random = new Random();
  12. /// <summary>
  13. /// 生成 n 条随机交易记录。
  14. /// </summary>
  15. /// <param name="n">交易记录的数量。</param>
  16. /// <returns></returns>
  17. public static Transaction[] Generate(int n)
  18. {
  19. Transaction[] trans = new Transaction[n];
  20. for (int i = 0; i < n; i++)
  21. {
  22. trans[i] = new Transaction
  23. (GenerateName(),
  24. GenerateDate(),
  25. random.NextDouble() * 1000);
  26. }
  27. return trans;
  28. }
  29. /// <summary>
  30. /// 获取随机姓名。
  31. /// </summary>
  32. /// <returns></returns>
  33. private static string GenerateName()
  34. {
  35. int nameLength = random.Next(4, 7);
  36. StringBuilder sb = new StringBuilder();
  37. sb.Append(random.Next('A', 'Z' + 1));
  38. for (int i = 1; i < nameLength; i++)
  39. sb.Append(random.Next('a', 'z' + 1));
  40. return sb.ToString();
  41. }
  42. /// <summary>
  43. /// 获取随机日期。
  44. /// </summary>
  45. /// <returns></returns>
  46. private static Date GenerateDate()
  47. {
  48. int year = random.Next(2017, 2019);
  49. int month = random.Next(1, 13);
  50. int day;
  51. if (month == 2)
  52. day = random.Next(1, 29);
  53. else if ((month < 8 && month % 2 == 1) ||
  54. (month > 7 && month % 2 == 0))
  55. day = random.Next(1, 32);
  56. else
  57. day = random.Next(1, 31);
  58. Date date = new Date(month, day, year);
  59. return date;
  60. }
  61. }
  62. }
另请参阅

SortApplication 库

算法(第四版)C# 习题题解——2.5的更多相关文章

  1. 算法(第四版)C#题解——2.1

    算法(第四版)C#题解——2.1   写在前面 整个项目都托管在了 Github 上:https://github.com/ikesnowy/Algorithms-4th-Edition-in-Csh ...

  2. 算法第四版 在Eclipse中调用Algs4库

    首先下载Eclipse,我选择的是Eclipse IDE for Java Developers64位版本,下载下来之后解压缩到喜欢的位置然后双击Eclipse.exe启动 然后开始新建项目,File ...

  3. 算法第四版jar包下载地址

    算法第四版jar包下载地址:https://algs4.cs.princeton.edu/code/

  4. 算法第四版-文字版-下载地址-Robert Sedgewick

    下载地址:https://download.csdn.net/download/moshenglv/10777447 算法第四版,文字版,可复制,方便copy代码 目录: 第1章 基 础 ...... ...

  5. 二项分布。计算binomial(100,50,0.25)将会产生的递归调用次数(算法第四版1.1.27)

    算法第四版35页问题1.1.27,估计用一下代码计算binomial(100,50,0.25)将会产生的递归调用次数: public static double binomial(int n,int ...

  6. 算法第四版学习笔记之优先队列--Priority Queues

    软件:DrJava 参考书:算法(第四版) 章节:2.4优先队列(以下截图是算法配套视频所讲内容截图) 1:API 与初级实现 2:堆得定义 3:堆排序 4:事件驱动的仿真 优先队列最重要的操作就是删 ...

  7. 算法第四版学习笔记之快速排序 QuickSort

    软件:DrJava 参考书:算法(第四版) 章节:2.3快速排序(以下截图是算法配套视频所讲内容截图) 1:快速排序 2:

  8. C程序设计(第四版)课后习题完整版 谭浩强编著

    //复习过程中,纯手打,持续更新,觉得好就点个赞吧. 第一章:程序设计和C语言 习题 1.什么是程序?什么是程序设计? 答:程序就是一组计算机能识别和执行的指令.程序设计是指从确定任务到得到结果,写出 ...

  9. 算法第四版 coursera公开课 普林斯顿算法 ⅠⅡ部分 Robert Sedgewick主讲《Algorithms》

    这是我在网上找到的资源,下载之后上传到我的百度网盘了. 包含两部分:1:算法视频的种子 2:字幕 下载之后,请用迅雷播放器打开,因为迅雷可以直接在线搜索字幕. 如果以下链接失效,请在下边留言,我再更新 ...

  10. 相似度分析,循环读入文件(加入了HanLP,算法第四版的库)

    相似度分析的,其中的分词可以采用HanLP即可: http://www.open-open.com/lib/view/open1421978002609.htm /****************** ...

随机推荐

  1. Digest of Overview of Linux Kernel Security Features

    Linux kernel Security: I. DAC: Discretionary Access Control, the core security model of UNIX. II. PO ...

  2. TNS-12560: TNS: 协议适配器错误同时伴有TNS-00584: 有效节点检查配置错误的解决方法

    :修改/home/oracle/app/product/11.2.0/db_1/network/admin/sqlnet.ora(与listener.ora同一目录) 增加白名单: tcp.valid ...

  3. ADB——keyevent命令

    基本格式 adb shell input keyevent xxx # xxx为具体操作对应的数字 keycode 官方 KEYCODE 链接:戳这里 0 KEYCODE_UNKNOWN 未知按键 1 ...

  4. mysql表类型导致的 setRollbackOnly() 事务不回滚

    在SpringBoot 中,使用事务非常简单,只需在方法上面加入 @Transactional  注解就可以实现.也可加在类上,此时则类中所有方法都支持事务. 而当我使用下面代码时,发现事务却没有回滚 ...

  5. PHP防CC攻击代码

    PHP防CC攻击代码: empty($_SERVER['HTTP_VIA']) or exit('Access Denied'); //代理IP直接退出 session_start(); $secon ...

  6. 实验吧MD5之守株待兔解题思路

    解题链接 http://ctf5.shiyanbar.com/misc/keys/keys.php 解题思路 首先我们多打开几次解题链接,发现系统密钥大约在一秒钟左右变一次,所以联想到时间戳. 解题过 ...

  7. 杂记:解决Android扫描BLE设备名称不刷新问题

    背景 个人开发过一种BLE设备有这样一种需求:当设备处于状态A时,广播设备名称A:处于状态B时,广播设备名称B. 问题 我们发现,当Android在进行Ble扫描的时候,扫描回调函数onScanRes ...

  8. 1、写在开头的话——Tinking in Java 绪论之我见

    新兵道歉!版式不懂,技术若有错误,请指正,或发我邮箱1300431700@qq.com 不胜感激! 本文力图通过文章总结的形式,阐述自己的观点,迫使自己思考书中精髓,即使跟技术无关! 正文开始! “上 ...

  9. java中进程与线程的区别

    进程是一个正在运行的应用程序.一个进程包含一个或多个线程.它可以是一段完整的代码或部分程序的动态执行.系统资源分配与调度的基本单位.而线程是CPU调度与运行的基本单位,它是一组指令的集合或是程序的特殊 ...

  10. Halcon一维运算相关算子整理

    Halcon一维离散函数算子 1.      abs_funct_1d  计算一维数组的绝对值 2.      compose_funct_1将两个离散的一维函数合并为一个函数 3.      cre ...