第 2 章 经典入门

一 排序

例 2.1 排序

  • 代码 2.1

    冒泡排序(时间复杂度 \(O(n^2)\))

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <vector>
    4. using std::vector;
    5. #include <algorithm>
    6. using std::swap;
    7. bool bubble(int lo, int hi, vector<int> &ivec) {
    8. bool sorted = true; // 整体有序标志
    9. while (++lo < hi) // 自左向右,逐一检查各对相邻元素
    10. if (ivec[lo - 1] > ivec[lo]) { // 若逆序,则
    11. sorted = false; // 意味着尚未整体有序,并需要
    12. swap(ivec[lo - 1], ivec[lo]); // 交换
    13. }
    14. return sorted;
    15. }
    16. void bubbleSort(int lo, int hi, vector<int> &ivec) {
    17. while (!bubble(lo, hi--, ivec)); // 逐趟做扫描交换,直至全序
    18. }
    19. int main() {
    20. int n;
    21. vector<int> ivec;
    22. cin >> n;
    23. while (n--) {
    24. int temp;
    25. cin >> temp;
    26. ivec.push_back(temp);
    27. }
    28. bubbleSort(0, ivec.size(), ivec); // 对区间 [0, ivec.size()) 冒泡排序
    29. for (auto e : ivec)
    30. cout << e << " " << endl;
    31. return 0;
    32. }

    冒泡排序改进版:

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <vector>
    4. using std::vector;
    5. #include <algorithm>
    6. using std::swap;
    7. int bubble(int lo, int hi, vector<int> &ivec) {
    8. int last = lo; // 最右侧的逆序对初始化为 [lo - 1, lo]
    9. while (++lo < hi) // 自左向右,逐一检查各对相邻元素
    10. if (ivec[lo - 1] > ivec[lo]) { // 若逆序,则
    11. last = lo; // 更新最右侧逆序对位置记录,并
    12. swap(ivec[lo - 1], ivec[lo]); // 交换
    13. }
    14. return last;
    15. } // 前一版本中的逻辑型标志 sorted,改为秩 last
    16. void bubbleSort(int lo, int hi, vector<int> &ivec) {
    17. while (lo < (hi = bubble(lo, hi, ivec))); // 逐趟做扫描交换,直至全序
    18. }
    19. int main() {
    20. int n;
    21. vector<int> ivec;
    22. cin >> n;
    23. while (n--) {
    24. int temp;
    25. cin >> temp;
    26. ivec.push_back(temp);
    27. }
    28. bubbleSort(0, ivec.size(), ivec); // 对区间 [0, ivec.size()) 冒泡排序
    29. for (auto e : ivec)
    30. cout << e << " " << endl;
    31. return 0;
    32. }
  • 代码 2.2

    快速排序(时间复杂度 \(O(nlogn)\))

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <vector>
    4. using std::vector;
    5. #include <algorithm>
    6. using std::sort;
    7. int main() {
    8. int n;
    9. vector<int> ivec;
    10. cin >> n;
    11. while (n--) {
    12. int temp;
    13. cin >> temp;
    14. ivec.push_back(temp);
    15. }
    16. sort(ivec.begin(), ivec.end()); // C++ sort 底层实现是快速排序
    17. // sort(ivec.begin(), ivec.end(), less<int>()); // 也可以自己指定第三个参数
    18. for (auto e : ivec)
    19. cout << e << " " << endl;
    20. return 0;
    21. }

    Standard library header

    也可以自定义 sort 的第三个参数

    比如将该例题降序排列:

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <vector>
    4. using std::vector;
    5. #include <algorithm>
    6. using std::sort;
    7. #include <functional>
    8. using std::greater;
    9. bool cmp(int x, int y) {
    10. return x > y;
    11. }
    12. int main() {
    13. int n;
    14. vector<int> ivec;
    15. cin >> n;
    16. while (n--) {
    17. int temp;
    18. cin >> temp;
    19. ivec.push_back(temp);
    20. }
    21. // sort(ivec.begin(), ivec.end(), greater<int>());
    22. sort(ivec.begin(), ivec.end(), cmp);
    23. for (auto e : ivec)
    24. cout << e << " " << endl;
    25. return 0;
    26. }

    各种排序算法(选择排序+有序向量合并+归并排序+快速排序

    1. template <typename T>
    2. Rank Vector<T>::max(Rank lo, Rank hi) { // 在 [lo, hi] 内找出最大者
    3. Rank mx = hi;
    4. while (lo < hi--) // 逆向扫描
    5. if (_elem[hi] > _elem[mx]) // 且严格比较
    6. mx = hi; // 故能在 max 有多个时保证后者有先,进而保证 selectionSort 稳定
    7. return mx;
    8. }
    9. template <typename T> // 向量选择排序
    10. void Vector<T>::selectionSort(Rank lo, Rank hi) { // 0 <= lo < hi <= size
    11. cout << "\tSELECTIONsort [" << lo << ", " << hi << "]" << endl;
    12. while (lo < hi) {
    13. swap(_elem[max(lo, hi)], _elem[hi]); // 将 [hi] 与 [lo, hi] 中的最大者交换
    14. --hi;
    15. }
    16. }
    17. template <typename T> // 有序向量(区间)的归并
    18. void Vector<T>::merge(Rank lo, Rank mi, Rank hi) { // 各自有序的子向量 [lo, mi) 和 [mi, hi)
    19. T* A = _elem + lo; // 合并后的向量 A[0, hi - lo) = _elem[lo, hi)
    20. int lb = mi - lo; T* B = new T[lb]; // 前子向量B[0, lb) = _elem[lo, mi)
    21. for (Rank i = 0; i < lb; B[i] = A[i++]); // 复制前子向量B[0, lb) = _elem[lo, mi)
    22. int lc = hi - mi; T* C = _elem + mi; // 后子向量C[0, lc) = _elem[mi, hi)
    23. for (Rank i = 0, j = 0, k = 0; j < lb || k < lc; ) { // B[j]和C[k]中小者转至A的末尾
    24. if (j < lb && (lc <= k || B[j] <= C[k])) A[i++] = B[j++]; // C[k]已无或不小
    25. if (k < lc && (lb <= j || C[k] < B[j])) A[i++] = C[k++]; // B[j]已无或更大
    26. }
    27. delete [] B; // 释放临时空间B
    28. }
    29. template <typename T> // 向量归并排序
    30. void Vector<T>::mergeSort(Rank lo, Rank hi) { // 0 <= lo < hi <= size
    31. cout << "\tMERGEsort [" << lo << ", " << hi << ")\n";
    32. if (hi - lo < 2) return; // 单元素区间自然有序,否则...
    33. int mi = (lo + hi) / 2; // 以中点为界
    34. mergeSort(lo, mi); mergeSort(mi, hi); // 分别排序
    35. merge(lo, mi, hi); // 归并
    36. }
    37. template <typename T> // 轴点构造算法:通过调整元素位置构造区间[lo, hi)的轴点,并返回其秩
    38. Rank Vector<T>::partition(Rank lo, Rank hi) { // 版本A:基本形式
    39. swap(_elem[lo], _elem[lo + rand() % (hi - lo)]); // 任选一个元素与首元素交换
    40. hi--; // [lo, hi)
    41. T pivot = _elem[lo]; // 以首元素为候选轴点(经以上swap函数交换,等效于随机选取
    42. while (lo < hi) { // 从向量的两端交替地向中间扫描
    43. while ((lo < hi) && (pivot <= _elem[hi])) // 在不小于pivot的前提下
    44. hi--; // 向左拓展右端子向量
    45. _elem[lo] = _elem[hi]; // 小于pivot者归入左侧子序列
    46. while ((lo < hi) && (_elem[lo] <= pivot)) // 在不大于pivot的前提下
    47. lo++; // 向右拓展左端子序列
    48. _elem[hi] = _elem[lo]; // 大于pivot者归入右侧子序列
    49. } // assert: lo == hi
    50. _elem[lo] = pivot; // 将备份的轴点记录置于前、后子向量之间
    51. return lo; // 返回轴点的秩
    52. }
    53. template <typename T> // 向量快速排序
    54. void Vector<T>::quickSort(Rank lo, Rank hi) { // 0 <= lo < hi <= size
    55. cout << "\tQUICKsort [" << lo << ", " << hi << ")\n";
    56. if (hi - lo < 2) return; // 单个元素区间自然有序,否则...
    57. Rank mi = partition(lo, hi); // 在[lo, hi)内构造轴点
    58. quickSort(lo, mi); // 对前缀递归排序
    59. quickSort(mi + 1, hi); // 对后缀递归排序
    60. }

例 2.2 成绩排序

  • 代码 2.4

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <vector>
    4. using std::vector;
    5. #include <algorithm>
    6. using std::sort;
    7. #include <string>
    8. using std::string;
    9. class Students {
    10. private:
    11. string _name;
    12. unsigned _age;
    13. unsigned _score;
    14. public:
    15. bool operator<(const Students &b) const; // C++ 运算符重载
    16. void setName(string studentName) { _name = studentName; }
    17. string getName() { return _name; }
    18. void setAge(unsigned studentAge) { _age = studentAge; }
    19. unsigned getAge() { return _age; }
    20. void setScore(unsigned studentScore) { _score = studentScore; }
    21. unsigned getScore() { return _score; }
    22. };
    23. bool Students::operator<(const Students &b) const {
    24. if (_score != b._score) // 若分数不相同则分数低者在前
    25. return _score < b._score;
    26. int tmp = _name.string::compare(b._name);
    27. if (!tmp) // 若分数相同则名字字典序小者在前
    28. return tmp < 0;
    29. else // 若名字也相同则年龄小者在前
    30. return _age < b._age;
    31. }
    32. int main() {
    33. int n;
    34. cin >> n;
    35. // Create a vector of Students objects
    36. vector<Students> v;
    37. string name;
    38. unsigned age, score;
    39. Students *p;
    40. while (n--) {
    41. cin >> name >> age >> score;
    42. p = new Students;
    43. p->setName(name), p->setAge(age), p->setScore(score);
    44. v.push_back(*p);
    45. }
    46. sort (v.begin(), v.end()); // 使用类 Students 自定义的 < 重载运算符
    47. for (auto e : v)
    48. cout << e.getName() << " "
    49. << e.getAge() << " "
    50. << e.getScore() << endl;
    51. return 0;
    52. }

    std::string::compare() in C++

二 日期类问题

例 2.3 日期差值

  • 代码 2.6

    1. #include <stdio.h>
    2. // 定义宏判断是否是闰年,方便计算每月天数
    3. #define ISYEAP(y) y % 100 != 0 && y % 4 == 0 || y % 400 == 0 ? 1 : 0
    4. int dayOfMonth[13][2] = {
    5. {0, 0}, {31, 31}, {28, 29}, {31, 31}, {30, 30}, {31, 31},
    6. {30, 30}, {31, 31}, {31, 31}, {30, 30}, {31, 31}, {30, 30}, {31, 31}
    7. }; // 预存每月的天数,注意二月配合宏定义做特殊处理
    8. struct Date { // 日期类,方便日期的推移
    9. int Day, Month, Year;
    10. void nextDay(); // 计算下一天的日期
    11. };
    12. void Date::nextDay() {
    13. Day++;
    14. if (Day > dayOfMonth[Month][ISYEAP(Year)]) { // 若日数超过了当月最大日数
    15. Day = 1;
    16. Month++; // 进入下一月
    17. if (Month > 12) { // 月数超过 12
    18. Month = 1;
    19. Year++; // 进入下一年
    20. }
    21. }
    22. }
    23. int buf[3001][13][32]; // 保存预处理的天数
    24. int Abs(int x) { // 求绝对值
    25. return x < 0 ? -x : x;
    26. }
    27. int main() {
    28. Date tmp;
    29. int cnt = 0; // 天数计算
    30. tmp.Day = 1;
    31. tmp.Month = 1;
    32. tmp.Year = 0; // 初始化日期类对象为 0 年 1 月 1 日
    33. while (tmp.Year != 3001) { // 日期不超过 3000 年
    34. // 将该日期与 0 年 1 月 1 日的天数差保存起来
    35. buf[tmp.Year][tmp.Month][tmp.Day] = cnt;
    36. tmp.nextDay(); // 计算下一天日期
    37. // 计数器累加,每经过一天计数器即+1,代表与原点日期的间隔又增加一天
    38. cnt++;
    39. }
    40. int d1, m1, y1;
    41. int d2, m2, y2;
    42. while (scanf("%4d%2d%2d", &y1, &m1, &d1) != EOF) {
    43. scanf("%4d%2d%2d", &y2, &m2, &d2); // 读入要计算的两个日期
    44. // 用预处理的数据计算两个日期差值,注意需对其求绝地值
    45. printf("%d\n", Abs(buf[y2][m2][d2] - buf[y1][m1][d1]) + 1);
    46. }
    47. return 0;
    48. }

    样例输入:

    1. 20110412
    2. 20110422

    样例输出:

    1. 11

例 2.4 Day of week

  • 代码 2.7

    1. #include <stdio.h>
    2. #include <cstring> // using strcmp function
    3. // 定义宏判断是否是闰年,方便计算每月天数
    4. #define ISYEAP(y) y % 100 != 0 && y % 4 == 0 || y % 400 == 0 ? 1 : 0
    5. int dayOfMonth[13][2] = {
    6. {0, 0}, {31, 31}, {28, 29}, {31, 31}, {30, 30}, {31, 31},
    7. {30, 30}, {31, 31}, {31, 31}, {30, 30}, {31, 31}, {30, 30}, {31, 31}
    8. }; // 预存每月的天数,注意二月配合宏定义做特殊处理
    9. struct Date { // 日期类,方便日期的推移
    10. int Day, Month, Year;
    11. void nextDay(); // 计算下一天的日期
    12. };
    13. void Date::nextDay() {
    14. Day++;
    15. if (Day > dayOfMonth[Month][ISYEAP(Year)]) { // 若日数超过了当月最大日数
    16. Day = 1;
    17. Month++; // 进入下一月
    18. if (Month > 12) { // 月数超过 12
    19. Month = 1;
    20. Year++; // 进入下一年
    21. }
    22. }
    23. }
    24. int buf[3001][13][32]; // 保存预处理的天数
    25. char monthOfName[13][20] = { // 下标1~12对应月名
    26. "", "January", "February", "March", "April", "May", "June",
    27. "July", "August", "September", "October", "November", "December"
    28. };
    29. char weekName[7][20] = { // 下标0~6对应周名
    30. "Sunday", "Monday", "Tuesday", "Wednesday",
    31. "Thursday", "Friday", "Saturday"
    32. };
    33. int main() {
    34. Date tmp;
    35. int cnt = 0; // 天数计算
    36. tmp.Day = 1;
    37. tmp.Month = 1;
    38. tmp.Year = 0; // 初始化日期类对象为 0 年 1 月 1 日
    39. while (tmp.Year != 3001) { // 日期不超过 3000 年
    40. // 将该日期与 0 年 1 月 1 日的天数差保存起来
    41. buf[tmp.Year][tmp.Month][tmp.Day] = cnt;
    42. tmp.nextDay(); // 计算下一天日期
    43. // 计数器累加,每经过一天计数器即+1,代表与原点日期的间隔又增加一天
    44. cnt++;
    45. }
    46. int d, m, y;
    47. char s[20];
    48. while (scanf("%d%s%d", &d, s, &y) != EOF) {
    49. for (m = 1; m <= 12; m++) {
    50. if (strcmp(s, monthOfName[m]) == 0) {
    51. break; // 将输入字符串与月名比较得出月数
    52. }
    53. }
    54. // 计算给定日期与今日日期的天数间隔(注意可能为负)
    55. int days = buf[y][m][d] - buf[2019][12][6];
    56. // 今天(2019.12.06)为星期一,对应数组下标为 5,则计算 5 经过 days 天后的下标
    57. days += 5;
    58. // 将计算后得出的下标用 7 对其取模,并且保证其为非负数,则该下标即为答案所对应的下标,输出即可
    59. puts(weekName[(days % 7 + 7) % 7]);
    60. }
    61. return 0;
    62. }

    样例输入:

    1. 1 December 2019 10 December 2019

    样例输出:

    1. Sunday
    2. Tuesday

三 Hash 的应用

例 2.5 统计相同成绩学生人数

  • 代码 2.8

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <map>
    4. using std::map;
    5. int main() {
    6. int n;
    7. while (cin >> n && n != 0) { // 输入判断增加对 n 是否等于零进行判断
    8. map<unsigned, unsigned> score_count;
    9. unsigned score;
    10. // 不能写为 cin >> score && n--,否则循环结束时,&& 短路求值,cin >> score 得到 x 的值
    11. while (n-- && cin >> score)
    12. ++score_count[score];
    13. unsigned x;
    14. cin >> x;
    15. cout << score_count[x] << endl;
    16. }
    17. return 0;
    18. }

    样例输入:

    1. 3
    2. 80 60 90
    3. 60
    4. 2
    5. 85 66
    6. 0
    7. 5
    8. 60 75 90 55 75 75
    9. 0

    样例输出:

    1. 1
    2. 0
    3. 2

例 2.6 Sort

  • 代码 2.9

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <map>
    4. using std::map;
    5. #define OFFSET 500000 // 偏移量,用于补偿实际数字与数组下标之间偏移
    6. int main() {
    7. int n, m;
    8. cin >> n >> m;
    9. map<unsigned, unsigned> h;
    10. for (int i = 500000; i >= -500000; i--) {
    11. h[i + OFFSET] = 0;
    12. } // 初始化,将每个数字都标记为未出现,即 0
    13. for (int i = 0; i < n; i++) {
    14. int x; cin >> x;
    15. ++h[x + OFFSET]; // 凡是出现过的数字,累计加 1
    16. }
    17. for (int i = 500000; i >= -500000; i--) { // 输出前 m 大的数
    18. if (h[i + OFFSET]) {
    19. cout << i << " ";
    20. m--;
    21. }
    22. if (!m) { // 若 m 个数已经输出完毕,则在输出的数字后面紧跟一个换行,并跳出循环
    23. cout << "\n";
    24. break;
    25. }
    26. }
    27. return 0;
    28. }

四 排版题

例 2.7 输出梯形

  • 代码 2.10(规律性强,直接按规律输出)

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. int main() {
    4. // 每行 ' ' 和 '*' 总个数 s = h + 2 * (h - 1)
    5. // 第一行 '*' 有 h 个,以后每行 '*' 的个数较前一行加 2
    6. // 第一行 ' ' 有 s - h 个,以后每行 ' ' 的个数较前一行减 2
    7. // 总共输出 h 行
    8. int h;
    9. while (cin >> h) {
    10. int s = h + 2 * (h - 1);
    11. int row = h;
    12. for (int i = 0; i < row; i++) { // 依次输出每行信息
    13. for (int j = 0; j < s; j++) { // 依次输出每行当中的空格或星号
    14. if (j < s - h - 2 * i) // 输出空格
    15. cout << " ";
    16. else // 输出星号
    17. cout << "*";
    18. }
    19. cout << endl; // 输出换行
    20. }
    21. }
    22. return 0;
    23. }

例 2.8 叠筐

  • 代码 2.11(规律性不若,先排版后输出)

    1. #include <iostream>
    2. using std::cin; using std::cout;
    3. #define N 80
    4. int main() {
    5. int outPutBuf[N][N]; // 用于预排版的输出缓存
    6. char a, b; // 输入的两个字符
    7. int n; // 叠筐大小
    8. bool firstCase = true; // 是否为第一组数据标志,初始值为 true
    9. while (cin >> n >> a >> b) {
    10. if (firstCase == true) { // 若是第一组数据
    11. firstCase = false; // 将第一组数据标志记成 false
    12. } else // 否则输出换行
    13. cout << "\n";
    14. // i 表示每圈边长长度
    15. // j 的奇偶性确定每圈字符,以及用来辅助动态确定每圈左上角坐标
    16. for (int i = 1, j = 1; i <= n; i += 2, j++) { // 从里到外
    17. int x = n / 2 + 1, y = x;
    18. x -= j - 1; y = x; // 计算每个圈左上角点的坐标
    19. char c = j % 2 == 1 ? a : b; // 计算当前圈的字符
    20. for (int k = 1; k <= i; k++) { // 对当前圈进行赋值
    21. outPutBuf[x + k - 1][y] = c; // 左边赋值
    22. outPutBuf[x][y + k - 1] = c; // 上边赋值
    23. outPutBuf[x + i - 1][y + k - 1] = c; // 右边赋值
    24. outPutBuf[x + k - 1][y + i - 1] = c; // 下边赋值
    25. }
    26. }
    27. if (n != 1) { // 注意,当 n 为 1 时,不需要此步骤
    28. outPutBuf[1][1] = ' ';
    29. outPutBuf[1][n] = ' ';
    30. outPutBuf[n][1] = ' ';
    31. outPutBuf[n][n] = ' '; // 将四角置为空格
    32. }
    33. for (int i = 1; i <= n; i++) { // 输出经过排版的在输出缓存中的数据
    34. for (int j = 1; j <= n; j++)
    35. cout << (char)outPutBuf[i][j];
    36. cout << "\n";
    37. }
    38. }
    39. return 0;
    40. }

五 查找

例 2.9 找 x

  • 代码 2.12

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. int main() {
    4. int n; cin >> n;
    5. int* A = new int[n];
    6. for (int i = 0; i < n; ++i) {
    7. int tmp; cin >> tmp;
    8. A[i] = tmp;
    9. }
    10. int x, ans = -1; // 初始化答案为 -1,以期在找不到答案时能正确的输出 -1
    11. cin >> x;
    12. for (int j = 0; j < n; ++j) { // 依次遍历数组元素
    13. if (x == A[j]) { // 目标数字与数组元素依次比较
    14. ans = j;
    15. break; // 找到答案后跳出
    16. }
    17. }
    18. cout << ans << endl;
    19. delete [] A;
    20. return 0;
    21. }

例 2.10 查找学生信息

  • 代码 2.13

    1. #include <iostream>
    2. using std::cin; using std::cout;
    3. #include <string>
    4. using std::string;
    5. #include <algorithm>
    6. using std::sort;
    7. class Student { // 用于表示学生个体的类
    8. private:
    9. string _no; // 学号
    10. string _name; // 姓名
    11. unsigned _age; // 年龄
    12. string _sex; // 性别
    13. public:
    14. void setNo(string no) { _no = no; }
    15. string getNo() { return _no; }
    16. void setName(string name) { _name = name; }
    17. string getName() { return _name; }
    18. void setSex(string sex) { _sex = sex; }
    19. string getSex() { return _sex; }
    20. void setAge(unsigned age) { _age = age; }
    21. unsigned getAge() { return _age; }
    22. bool operator<(const Student & b) const; // 重载小于运算符使其能使用 sort 函数排序
    23. };
    24. bool Student::operator<(const class Student & b) const {
    25. return _no.string::compare(b._no) < 0;
    26. }
    27. int main () {
    28. int n; cin >> n;
    29. Student* stu = new Student[n];
    30. for (int i = 0; i < n; ++i) {
    31. string no, name, sex;
    32. unsigned age;
    33. cin >> no >> name >> sex >> age;
    34. stu[i].setNo(no); stu[i].setName(name);
    35. stu[i].setSex(sex); stu[i].setAge(age);
    36. } // 输入
    37. sort(stu, stu + n); // 对数组排序使其按学号升序排列
    38. int m; cin >> m; // 有 m 组询问
    39. while (m--) { // while 循环保证查询次数 m
    40. int ans = -1; // 目标元素下标,初始化为 -1
    41. string tmp; // 待查找学号
    42. cin >> tmp;
    43. int hi = n, lo = 0; // Student 对象数组 stu 的 [lo, hi) 区间二分查找 tmp
    44. while (lo < hi) { // 每步迭代可能要做两次比较判断,有三个分支
    45. int mi = (lo + hi) >> 1; // 以中点为轴点
    46. if (tmp < stu[mi].getNo())
    47. hi = mi; // 深入前半段 [lo, mi) 继续查找
    48. else if (stu[mi].getNo() < tmp)
    49. lo = mi + 1; // 深入后半段 (mi, hi) 继续查找
    50. else {
    51. ans = mi; // 在 mi 处命中
    52. cout << stu[ans].getNo() << ' ' << stu[ans].getName() << ' '
    53. << stu[ans].getSex() << ' ' << stu[ans].getAge() << "\n";
    54. break; // 查找成功则终止本轮查找
    55. }
    56. } // 成功查找可以提前终止
    57. if (ans == -1) // 若查找失败
    58. cout << "No Answer!\n";
    59. }
    60. delete [] stu;
    61. return 0;
    62. }

六 贪心算法

例 2.11 FatMouse' Trade

  • 代码 2.14

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <algorithm>
    4. using std::sort;
    5. #include <iomanip>
    6. using std::fixed; using std::setprecision;
    7. struct goods { // 表示可买物品的结构体
    8. double j; // 该物品总重
    9. double f; // 该物品总价值
    10. double s; // 该物品性价比
    11. // 重载小于运算符,确保可用 sort 函数将数组按照性价比降序排列
    12. bool operator<(const goods &b) const {
    13. return s > b.s;
    14. }
    15. } buf[1000];
    16. int main() {
    17. double m;
    18. int n;
    19. while (cin >> m >> n) {
    20. if (m == -1 && n == -1)
    21. break; // 当 m、n 为 -1 时,跳出循环,程序运行结束
    22. for (int i = 0; i < n; i++) {
    23. double j, f;
    24. cin >> buf[i].j >> buf[i].f; // 输入
    25. buf[i].s = buf[i].j / buf[i].f; // 计算性价比
    26. }
    27. sort(buf, buf + n); // 使各物品按照性价比降序排列
    28. int idx = 0; // 当前货物下标
    29. double ans = 0.0; // 累加所能得到的总重量
    30. while (0 < m && idx < n) { // 各类物品有剩余(idx < n)还有钱剩余(m > 0)时继续循环
    31. if (m > buf[idx].f) { // 若能买下全部该种类物品
    32. ans += buf[idx].j;
    33. m -= buf[idx].f;
    34. } else { // 若只能买下部分该物品
    35. ans += m * buf[idx].j / buf[idx].f;
    36. m = 0;
    37. }
    38. ++idx; // 继续下一种类物品
    39. }
    40. cout << fixed << setprecision(3) << ans << endl;
    41. }
    42. return 0;
    43. }

    C++数字的输出处理问题(保留几位小数,或保留几位有效数字)

例 2.12 今年暑假不 AC

  • 代码 2.15

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <algorithm>
    4. using std::sort;
    5. struct program { // 电视节目结构体
    6. int _startTime; // 节目开始时间
    7. int _endTime; // 节目结束时间
    8. // 重载小于号,保证 sort 函数能够按照结束时间升序排列
    9. bool operator<(const program &second) const {
    10. return _endTime < second._endTime;
    11. }
    12. };
    13. program buf[100];
    14. int main() {
    15. int n;
    16. while (cin >> n) {
    17. if (n == 0)
    18. break;
    19. for (int i = 0; i < n; i++) { // 输入
    20. cin >> buf[i]._startTime >> buf[i]._endTime;
    21. }
    22. sort (buf, buf + n); // 按照结束时间升序排列
    23. // 记录当前时间,初始化为 0;所求能看的节目个数,初始化为 0
    24. int currentTime = 0, ans = 0;
    25. for (int i = 0; i < n; i++) { // 按照结束时间升序遍历所有节目
    26. // 若当前时间小于等于该节目开始时间,那么收看该在剩余节目里结束时间最早的节目
    27. if (currentTime <= buf[i]._startTime) {
    28. currentTime = buf[i]._endTime; // 当前时间变为该节目结束时间
    29. ++ans; // 又收看了一个节目
    30. }
    31. }
    32. cout << ans << endl; // 输出
    33. }
    34. }

第 3 章 数据结构

一 栈的应用

例 3.1 括号匹配问题

  • 代码 3.1

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <stack>
    4. using std::stack;
    5. #include <string>
    6. using std::string;
    7. int main() {
    8. stack<int> S; // 定义一个堆栈
    9. string str; // 保存输入字符串
    10. while (cin >> str) {
    11. string ans(str.size(), ' '); // 保存输出字符串,初始化为与输入等长的空字符串
    12. int i;
    13. for (i = 0; i < str.size(); i++) { // 从左到右遍历输入字符串
    14. if (str[i] == '(') { // 若遇到左括号
    15. S.push(i); // 将其下标放入堆栈中
    16. // ans[i] += ' '; // 暂且将对应的输出字符串位置字符改为空格
    17. } else if (str[i] == ')') { // 若遇到右括号
    18. if (S.empty() == false) { // 若此时堆栈非空
    19. S.pop(); // 栈顶位置左括号与其匹配,从栈中弹出该已经匹配的左括号下标
    20. } else { // 若堆栈为空,则无法找到左括号与其匹配,修改输出字符串该位为 '?'
    21. ans[i] = '?';
    22. }
    23. }
    24. }
    25. while (S.empty() == false) { // 当字符串遍历完成后,尚留在堆栈中的左括号无法匹配
    26. ans[S.top()] = '$'; // 修改其在输出中的位置为 '$'
    27. S.pop(); // 弹出栈顶元素
    28. }
    29. cout << str << '\n' << ans << endl; // 输出原字符串与答案字符串
    30. }
    31. return 0;
    32. }

例 3.2 简单计算器

  • 代码 3.2

    1. #include <stack>
    2. #include <stdio.h>
    3. using namespace std;
    4. char str[220]; // 保存表达式字符串
    5. /*
    6. * 优先级矩阵,若mat[i][j] == 1,则表示i号运算符优先级大于j号
    7. * 运算符,运算符编码规则为+为1号,-为2号,*为3号,/为4号,我们
    8. * 人为添加在表达式首尾的标记运算符为0号
    9. */
    10. int mat[][5] = {
    11. 1, 0, 0, 0, 0,
    12. 1, 0, 0, 0, 0,
    13. 1, 0, 0, 0, 0,
    14. 1, 1, 1, 0, 0,
    15. 1, 1, 1, 0, 0
    16. };
    17. stack<int> op; // 运算符栈,保存运算符编号
    18. stack<double> in; // 数字栈,运算结果可能存在浮点数,所以保存元素为double
    19. /*
    20. * 该函数获得表达式下一个元素,若函数运行结束时,引用变量reto为true,则表示该元
    21. * 素为一个运算符,其编号保存在引用变量retn中; 否则,表示该元素为一个数字,其
    22. * 值保存在引用变量retn中.引用变量i表示遍历到的字符串下标
    23. */
    24. void getOp(bool &reto, int &retn, int &i) {
    25. // 若此时遍历字符串第一个字符,且运算符栈为空,我们人为添加编号为0的标记字符
    26. if (i == 0 && op.empty() == true) {
    27. reto = true; // 为运算符
    28. retn = 0; // 编号为0
    29. return; // 返回
    30. }
    31. if (str[i] == 0) { // 若此时遍历字符为空字符,则表示字符串已经被遍历完
    32. reto = true; // 为运算符
    33. retn = 0; // 编号为0的标记字符
    34. return; // 返回
    35. }
    36. if (str[i] >= '0' && str[i] <= '9') { // 若当前字符为数字
    37. reto = false; // 返回为数字
    38. } else { // 否则
    39. reto = true; // 返回为运算符
    40. if (str[i] == '+') // 加号返回1
    41. retn = 1;
    42. else if (str[i] == '-') // 减号返回2
    43. retn = 2;
    44. else if (str[i] == '*') // 乘号返回3
    45. retn = 3;
    46. else if (str[i] == '/') // 除号返回4
    47. retn = 4;
    48. i += 2; // i递增,跳过该运算符和紧邻的空格字符
    49. return; // 返回
    50. }
    51. retn = 0; // 返回结果为数字
    52. // 若字符串未被遍历完,且下一个字符不是空格,则依次遍历其后数字,计算当前连续数字字符表示的数值
    53. for ( ; str[i] != ' ' && str[i] != 0; i++) {
    54. retn *= 10;
    55. retn += str[i] - '0';
    56. }
    57. if (str[i] == ' ') // 若其后字符为空格,则表示字符串未被遍历完
    58. ++i; // i递增.跳过该空格
    59. return; // 返回
    60. }
    61. int main() {
    62. while (gets(str)) { // 输入字符串,当其位于文件尾时,gets返回0
    63. if (str[0] == '0' && str[1] == 0) break; // 若输入只有一个0,则退出
    64. bool retop; int retnum; // 定义函数所需的引用变量
    65. int idx = 0; // 定义遍历到的字符串下标,初始值为0
    66. while (!op.empty()) op.pop();
    67. while (!in.empty()) in.pop(); // 清空数字栈,和运算符栈
    68. while (true) { // 循环遍历表达式字符串
    69. getOp(retop, retnum, idx); // 获取表达式中下一个元素
    70. if (retop == false) { // 若该元素为数字
    71. in.push((double)retnum); // 将其压入数字栈中
    72. } else { // 否则
    73. // 若运算符堆栈为空或者当前遍历到的运算符优先级大于栈顶运算符,将该运
    74. // 算符压入运算符堆栈
    75. double tmp;
    76. if (op.empty() == true || mat[retnum][op.top()] == 1) {
    77. op.push(retnum);
    78. } else { // 否则
    79. // 只要当前运算符优先级小于栈顶元素运算符,则重复循环
    80. while (mat[retnum][op.top()] == 0) {
    81. int ret = op.top(); // 保存栈顶运算符
    82. op.pop(); // 弹出
    83. double b = in.top();
    84. in.pop();
    85. double a = in.top();
    86. in.pop(); // 从数字堆栈栈顶弹出两个数字,依次保存在a、b中
    87. if (ret == 1) tmp = a + b;
    88. else if (ret == 2) tmp = a - b;
    89. else if (ret == 3) tmp = a * b;
    90. else if (ret == 4) tmp = a / b;
    91. in.push(tmp); // 将结果压回数字堆栈
    92. }
    93. op.push(retnum); // 将当前运算符压入运算符堆栈
    94. }
    95. }
    96. // 若运算符堆栈只有两个元素,且其栈顶元素为标记运算符,则表示表达式求值结束
    97. if (op.size() == 2 && op.top() == 0)
    98. break;
    99. }
    100. printf("%.2f\n", in.top()); // 输出数字栈中唯一的数字,即为答案
    101. }
    102. return 0;
    103. }

二 哈夫曼树

例 3.3 哈夫曼树

  • 代码 3.3

    1. #include <queue>
    2. using std::priority_queue;
    3. #include <vector>
    4. using std::vector;
    5. #include <iostream>
    6. using std::cin; using std::cout; using std::endl;
    7. #include <functional>
    8. using std::greater;
    9. priority_queue<int, vector<int>, greater<int>> Q; // 建立一个小顶堆
    10. int main() {
    11. int n;
    12. while (cin >> n) {
    13. while (Q.empty() == false)
    14. Q.pop(); // 清空堆中元素
    15. for (int i = 1; i <= n; i++) { // 输入n个叶子节点权值
    16. int x;
    17. cin >> x;
    18. Q.push(x); // 将权值放入堆中
    19. }
    20. int ans = 0; // 保存答案
    21. while (Q.size() > 1) { // 当堆中元素大于1个
    22. // 取出堆中两个最小元素,他们为同一节点的左右儿子,且该双亲节点的权值为他们的和
    23. int a = Q.top(); Q.pop();
    24. int b = Q.top(); Q.pop();
    25. ans += a + b; // 该父节点必为非叶子节点,故累加其权值
    26. Q.push(a + b); // 将该双亲节点的权值放回堆中
    27. }
    28. cout << ans << endl; // 输出
    29. }
    30. return 0;
    31. }

三 二叉树

例 3.4 二叉树遍历

  • 代码 3.4

    1. #include <stdio.h>
    2. #include <string.h>
    3. struct Node { // 树结点结构体
    4. Node *lChild; // 左儿子指针
    5. Node *rChild; // 右儿子指针
    6. char c; // 结点字符信息
    7. } Tree[50]; // 静态内存分配数组
    8. int loc; // 静态数组中已经分配的结点个数
    9. Node *creat() { // 申请一个结点空间,返回指向其的指针
    10. Tree[loc].lChild = Tree[loc].rChild = nullptr; // 初始化左右儿子为空
    11. return &Tree[loc++]; // 返回指针,且loc累加
    12. }
    13. char str1[30], str2[30]; // 保存前序和中序遍历结果字符串
    14. void postOrder(Node *T) { // 后序遍历
    15. if (T->lChild != nullptr) { // 若左子树不为空
    16. postOrder(T->lChild); // 递归遍历其左子树
    17. }
    18. if (T->rChild != nullptr) { // 若右子树不为空
    19. postOrder(T->rChild); // 递归遍历其右子树
    20. }
    21. printf("%c", T->c); // 遍历该结点,输出其字符信息
    22. }
    23. Node *build(int s1, int e1, int s2, int e2) {
    24. // 由字符串的前序遍历和中序遍历还原树,并返回其根节点,其中前序遍历结果
    25. // 为由str1[s1]到str2[e1],中序遍历结果为str2[s2]到str2[e2]
    26. Node* ret = creat(); // 为该树根结点申请空间
    27. ret->c = str1[s1]; // 该节点字符为前序遍历中第一个字符
    28. int rootIdx;
    29. for (int i = s2; i <= e2; i++) { // 查找该根结点字符在中序遍历中的位置
    30. if (str2[i] == str1[s1]) {
    31. rootIdx = i;
    32. break;
    33. }
    34. }
    35. if (rootIdx != s2) { // 若左子树不为空
    36. // 递归还原其左子树
    37. ret->lChild = build(s1 + 1, s1 + (rootIdx - s2), s2, rootIdx - 1);
    38. }
    39. if (rootIdx != e2) { // 若右子树不为空
    40. // 递归还原其右子树
    41. ret->rChild = build(s1 + (rootIdx - s2) + 1, e1, rootIdx + 1, e2);
    42. }
    43. return ret; // 返回根结点指针
    44. }
    45. int main() {
    46. while (scanf("%s", str1) != EOF) {
    47. scanf("%s", str2); // 输入
    48. loc = 0; // 初始化静态内存空间中已经使用结点个数为0
    49. int L1 = strlen(str1);
    50. int L2 = strlen(str2); // 计算两个字符串长度
    51. // 还原整棵树,其根结点指针保存在T中
    52. Node *T = build(0, L1 - 1, 0, L2 - 1);
    53. postOrder(T); // 后序遍历
    54. printf("\n"); // 输出后换行
    55. }
    56. return 0;
    57. }

四 二叉排序树

例 3.5 二叉排序树

  • 代码 3.5

    1. #include <cstdio>
    2. struct Node { // 二叉树结构体
    3. Node* lChild; // 左儿子指针
    4. Node* rChild; // 右儿子指针
    5. int c; // 保存数字
    6. } Tree[110]; // 静态数组
    7. int loc; // 静态数组中被使用的元素个数
    8. Node* creat() { // 申请未使用的结点
    9. Tree[loc].lChild = Tree[loc].rChild = nullptr;
    10. return &Tree[loc++];
    11. }
    12. // 后序遍历
    13. void postOrder(Node* T) {
    14. if (T->lChild != nullptr) { // 左子树不空,则
    15. postOrder(T->lChild); // 递归遍历左子树
    16. }
    17. if (T->rChild != nullptr) { // 右子树不空,则
    18. postOrder(T->rChild); // 递归遍历右子树
    19. }
    20. printf("%d ", T->c); // 访问当前结点(根)
    21. }
    22. // 中序遍历
    23. void inOrder(Node* T) {
    24. if (T->lChild != nullptr) {
    25. inOrder(T->lChild);
    26. }
    27. printf("%d ", T->c);
    28. if (T->rChild != nullptr) {
    29. inOrder(T->rChild);
    30. }
    31. }
    32. // 前序遍历
    33. void preOrder(Node* T) {
    34. printf("%d ", T->c);
    35. if (T->lChild != nullptr) {
    36. preOrder(T->lChild);
    37. }
    38. if (T->rChild != nullptr) {
    39. preOrder(T->rChild);
    40. }
    41. }
    42. // 二叉排序树插入结点
    43. Node* Insert(Node* T, int x) {
    44. if (T == nullptr) { // 若当前树为空
    45. T = creat(); // 建立结点
    46. T->c = x; // 数字直接插入其根结点
    47. return T; // 返回根结点指针
    48. } else if (x < T->c) // 若 x 小于根结点数值
    49. T->lChild = Insert(T->lChild, x); // 插入到左子树上
    50. else if (x > T->c) // 若 x 大于根结点数值
    51. T->rChild = Insert(T->rChild, x); // 插入到右子
    52. // 树上,若根结点数值与 x 一样,根据题目要求直接忽略
    53. return T; // 返回根结点指针
    54. }
    55. int main() {
    56. int n;
    57. while (scanf("%d", &n) != EOF) {
    58. loc = 0;
    59. Node* T = nullptr; // 二叉排序树树根结点为空
    60. for (int i = 0; i < n; i++) { // 依次输入 n 个数字
    61. int x; scanf("%d", &x);
    62. T = Insert(T, x); // 插入到排序树中
    63. }
    64. preOrder(T); // 前序遍历
    65. printf("\n"); // 输出空行
    66. inOrder(T); // 中序遍历
    67. printf("\n");
    68. postOrder(T); // 后序遍历
    69. printf("\n");
    70. }
    71. return 0;
    72. }

例 3.6 二叉搜索树

  • 代码 3.6

    1. #include <cstdio>
    2. #include <cstring>
    3. struct Node { // 二叉树结构体
    4. Node* lChild; // 左儿子指针
    5. Node* rChild; // 右儿子指针
    6. int c; // 保存数字
    7. } Tree[110]; // 静态数组
    8. int loc; // 静态数组中被使用的元素个数
    9. Node* creat() { // 申请未使用的结点
    10. Tree[loc].lChild = Tree[loc].rChild = nullptr;
    11. return &Tree[loc++];
    12. }
    13. char str1[25], str2[25]; // 保存二叉排序树的遍历结果,将每
    14. // 一棵树的前序遍历得到的字符串与中序遍历得到的字符串连接,得到遍历结果字符串
    15. int size1, size2; // 保存在字符数组中的遍历得到字符个数
    16. char* currStr; // 当前正在保存字符串
    17. int* currSize; // 当前正在保存字符串中字符个数
    18. // 中序遍历
    19. void inOrder(Node* T) {
    20. if (T->lChild != nullptr) {
    21. inOrder(T->lChild);
    22. }
    23. currStr[(*currSize)++] = T->c + '0'; // 将结点中的字符放入正在保存的字符串中
    24. if (T->rChild != nullptr) {
    25. inOrder(T->rChild);
    26. }
    27. }
    28. // 前序遍历
    29. void preOrder(Node* T) {
    30. currStr[(*currSize)++] = T->c + '0';
    31. if (T->lChild != nullptr) {
    32. preOrder(T->lChild);
    33. }
    34. if (T->rChild != nullptr) {
    35. preOrder(T->rChild);
    36. }
    37. }
    38. // 二叉排序树插入结点
    39. Node* Insert(Node* T, int x) {
    40. if (T == nullptr) { // 若当前树为空
    41. T = creat(); // 建立结点
    42. T->c = x; // 数字直接插入其根结点
    43. return T; // 返回根结点指针
    44. } else if (x < T->c) // 若 x 小于根结点数值
    45. T->lChild = Insert(T->lChild, x); // 插入到左子树上
    46. else if (x > T->c) // 若 x 大于根结点数值
    47. T->rChild = Insert(T->rChild, x); // 插入到右子
    48. // 树上,若根结点数值与 x 一样,根据题目要求直接忽略
    49. return T; // 返回根结点指针
    50. }
    51. int main() {
    52. int n;
    53. char tmp[12];
    54. while (scanf("%d", &n) != EOF && n != 0) {
    55. loc = 0; // 初始化静态空间为未使用
    56. Node* T = nullptr;
    57. scanf("%s", tmp); // 输入字符串
    58. for (int i = 0; tmp[i] != '\0'; i++) {
    59. T = Insert(T, tmp[i] - '0'); // 按顺序将数字插入二叉排序树
    60. }
    61. size1 = 0; // 保存在第一个字符串中的字符,初始化为0
    62. currStr = str1; // 将正在保存字符串设定为第一个字符串
    63. currSize = &size1; // 将正在保存字符串中的字符个数指针指向 size1
    64. preOrder(T); // 前序遍历
    65. inOrder(T); // 中序遍历
    66. str1[size1] = '\0'; // 向第一个字符串的最后一个字符后添加字符串结束符,方便使用字符串函数
    67. while (n-- != 0) { // 输入 n 个其它字符串
    68. scanf("%s", tmp); // 输入
    69. Node* T2 = nullptr;
    70. for (int i = 0; tmp[i] != '\0'; i++) { // 建立二叉排序树
    71. T2 = Insert(T2, tmp[i] - '0');
    72. }
    73. size2 = 0; // 保存在第二个字符串中的字符,初始化为0
    74. currStr = str2; // 将正在保存字符串设定为第二个字符串
    75. currSize = &size2; // 正在保存字符串中字符数量指针指向 size2
    76. preOrder(T2); // 前序遍历
    77. inOrder(T2); // 中序遍历
    78. str2[size2] = '\0'; // 字符串最后添加字符串结束符
    79. // 比较两个遍历字符串,若相同则输出YES,否则输出NO
    80. puts(strcmp(str1, str2) == 0 ? "YES" : "NO");
    81. }
    82. }
    83. return 0;
    84. }

    C++ 运算符优先级

  • 代码 3.6(迭代版)

    1. #include <cstdio>
    2. #include <stack>
    3. using std::stack;
    4. #include <utility>
    5. using std::pair;
    6. struct Node { // 二叉树结构体
    7. Node* lChild; // 左儿子指针
    8. Node* rChild; // 右儿子指针
    9. int c; // 保存数字
    10. } Tree[110]; // 静态数组
    11. int loc; // 静态数组中被使用的元素个数
    12. Node* creat() { // 申请未使用的结点
    13. Tree[loc].lChild = Tree[loc].rChild = nullptr;
    14. return &Tree[loc++];
    15. }
    16. // 后序遍历迭代版
    17. void postOrder_I(Node* T) { // 二叉树的后序遍历(迭代版)
    18. stack<pair<Node*, bool>> S; // 辅助栈
    19. do{
    20. while (T) {
    21. S.push({T, false});
    22. T = T->lChild;
    23. }
    24. while (!S.empty()) {
    25. pair<Node*, bool> tmp = S.top(); // 当前栈顶元素
    26. if (tmp.second) {
    27. printf("%d ", tmp.first->c);
    28. S.pop();
    29. } else {
    30. T = tmp.first->rChild;
    31. // 修改栈顶元素 pair<Node*, bool> 的 bool 域为 true
    32. S.top().second = true;
    33. break;
    34. }
    35. }
    36. } while (!S.empty());
    37. }
    38. // 中序遍历迭代版#1(借助一个辅助栈,若当前结点为根结点,则根结点入栈)
    39. static void goAlongLeftBranch (Node* T, stack<Node*> &S) {
    40. // 从当前结点出发,沿左分支不断深入,直至没有左分支的结点
    41. while (T) {
    42. S.push(T); // 当前结点入栈后
    43. // 随即向左侧分支深入,迭代直到无左孩子
    44. T = T->lChild;
    45. }
    46. }
    47. void inOrder_I1(Node* T) { // 二叉树中序遍历算法(迭代版#1)
    48. stack<Node*> S; // 辅助栈
    49. while (true) {
    50. goAlongLeftBranch(T, S); // 从当前结点出发,逐批入栈
    51. if (S.empty()) // 直至所有节点处理完毕
    52. break;
    53. T = S.top();
    54. S.pop();
    55. printf("%d ", T->c); // 访问当前结点
    56. T = T->rChild; // 转向右子树
    57. }
    58. }
    59. // 中序遍历迭代版#2(版本2只不过是版本1的等价形式,但借助它可便捷地设计和实现版本3)
    60. void inOrder_I2(Node* T) { // 二叉树中序遍历算法(迭代版#2)
    61. stack<Node*> S; // 辅助栈;
    62. while (true)
    63. if (T) {
    64. S.push(T); // 根结点入栈
    65. T = T->lChild; // 深入遍历左子树
    66. } else if (!S.empty()) {
    67. T = S.top(); // 将 T 更新为尚未访问的最低祖先结点
    68. S.pop(); // 并退栈该节点
    69. printf("%d ", T->c); // 访问当前结点
    70. T = T->rChild; // 遍历祖先的右子树
    71. } else
    72. break; // 遍历完成
    73. }
    74. // 中序遍历迭代版#3(因引入父结点指针和判断左右孩子函数,实现稍复杂。
    75. // 可参考邓俊辉老师《数据结构与算法》P130、P131实现,这里省略)
    76. // 前序遍历迭代版(借助一个辅助栈,若当前结点右孩子非空,则右孩子入栈)
    77. static void visitAlongLeftBranch(Node* T, stack<Node*> &S) {
    78. // 从当前结点出发,沿左分支不断深入,直至没有左分支的结点;沿途结点遇到后立即访问
    79. while (T) {
    80. printf("%d ", T->c); // 访问当前结点
    81. S.push(T->rChild); // 右孩子入栈暂存(可优化:通过判断,避免空的右孩子入栈)
    82. T = T->lChild; // 沿左分支深入一层
    83. }
    84. }
    85. void preOrder_I(Node* T) {
    86. stack<Node*> S; // 辅助栈
    87. while (true) {
    88. visitAlongLeftBranch(T, S);
    89. if (S.empty()) // 直到栈空
    90. break;
    91. T = S.top(); // 更新结点指针 T 为下一批的起点
    92. S.pop(); // 弹出下一批的起点
    93. }
    94. }
    95. // 二叉排序树插入结点
    96. Node* Insert(Node* T, int x) {
    97. if (T == nullptr) { // 若当前树为空
    98. T = creat(); // 建立结点
    99. T->c = x; // 数字直接插入其根结点
    100. return T; // 返回根结点指针
    101. } else if (x < T->c) // 若 x 小于根结点数值
    102. T->lChild = Insert(T->lChild, x); // 插入到左子树上
    103. else if (x > T->c) // 若 x 大于根结点数值
    104. T->rChild = Insert(T->rChild, x); // 插入到右子
    105. // 树上,若根结点数值与 x 一样,根据题目要求直接忽略
    106. return T; // 返回根结点指针
    107. }
    108. int main() {
    109. int n;
    110. while (scanf("%d", &n) != EOF) {
    111. loc = 0;
    112. Node* T = nullptr; // 二叉排序树树根结点为空
    113. for (int i = 0; i < n; i++) { // 依次输入 n 个数字
    114. int x; scanf("%d", &x);
    115. T = Insert(T, x); // 插入到排序树中
    116. }
    117. printf("********** 前序遍历迭代版 ************\n");
    118. preOrder_I(T); // 前序遍历
    119. printf("\n"); // 输出空行
    120. printf("********** 中遍历迭代版#1 ************\n");
    121. inOrder_I1(T); // 中序遍历
    122. printf("\n");
    123. printf("********** 中遍历迭代版#2 ************\n");
    124. inOrder_I2(T); // 中序遍历
    125. printf("\n");
    126. printf("********** 后遍历迭代版 ************\n");
    127. postOrder_I(T); // 后序遍历
    128. printf("\n");
    129. }
    130. return 0;
    131. }

第 4 章 数学问题

一 %运算

二 数位拆解

例 4.1 特殊乘法

  • 代码 4.1

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <vector>
    4. using std::vector;
    5. int main() {
    6. int a, b;
    7. while (cin >> a >> b) {
    8. vector<int> ivec_a, ivec_b;
    9. while (a != 0) {
    10. ivec_a.push_back(a % 10); // 取得当前个位上的数字,将其保存
    11. a /= 10; // 将所有数位上的数字右移一位
    12. }
    13. while (b != 0) {
    14. ivec_b.push_back(b % 10);
    15. b /= 10;
    16. }
    17. int ans = 0; // 计算答案
    18. for (auto elemOfA : ivec_a) {
    19. for (auto elemOfB : ivec_b)
    20. ans += elemOfA * elemOfB;
    21. }
    22. cout << ans << endl;
    23. }
    24. return 0;
    25. }
  • 代码 4.2

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <string>
    4. using std::string;
    5. int main() {
    6. string a, b;
    7. while (cin >> a >> b) {
    8. int ans = 0; // 累加变量
    9. for (char elemOfA : a) { // char 改为 auto 也可
    10. for (char elemOfB : b) {
    11. ans += (elemOfA - '0') * (elemOfB - '0');
    12. // char - '0' 实现将字符转为整型
    13. }
    14. }
    15. cout << ans << endl;
    16. }
    17. return 0;
    18. }

三 进制转换

例 4.2 又一版 A+B

  • 代码 4.3

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <stack>
    4. using std::stack;
    5. int main() {
    6. long long a, b;
    7. int m;
    8. while (cin >> m && m) { // 当 m 等于 0 时退出
    9. cin >> a >> b;
    10. a += b; // 计算 a + b,结果放到 a 中
    11. stack<int> S;
    12. do { // 即使被转换数字是 0,程序也能正常工作
    13. S.push(a % m);
    14. a /= m;
    15. } while (a); // a 非零,重复该过程
    16. while (!S.empty()) {
    17. cout << S.top();
    18. S.pop();
    19. }
    20. cout << endl;
    21. }
    22. return 0;
    23. }

例 4.3 数制转换

  • 代码 4.4

    1. #include <iostream>
    2. using std::cin; using std::cout; using std::endl;
    3. #include <string>
    4. using std::string;
    5. #include <algorithm>
    6. using std::reverse;
    7. int main() {
    8. int a, b;
    9. string str;
    10. while (cin >> a >> str >> b) {
    11. // tmp为我们将要计算的 a 进制对应的十进制数;w 为各个数位的权重,初
    12. // 始化为1,表示最低位数位权重为1,之后每位权重都是前一位权重的a倍
    13. int tmp = 0, w = 1;
    14. for (string::reverse_iterator riter = str.rbegin(); riter != str.rend(); ++riter) {
    15. int x; // 计算该位上的数字
    16. if (*riter >= '0' && *riter <= '9')
    17. x = *riter - '0'; // 当字符在0到9之间,计算其代表的数字
    18. else if (*riter >= 'a' && *riter <= 'z')
    19. x = *riter - 'a' + 10; // 当字符为小写字母时,计算其代表的数字
    20. else
    21. x = *riter - 'A' + 10; // 当字符为大写字母时,计算其代表的数字
    22. tmp += x * w; // 累加该位数字与该数位权重的积
    23. w *= a; // 计算下一位数位权重
    24. }
    25. string ans; // 用 ans 保存转换到 b 进制的各个数位数字
    26. do { // do-while 保证 0 也能实现转换
    27. int x = tmp % b;
    28. ans += (x < 10) ? x + '0' : x - 10 + 'A'; // 将数字转换为大写字符
    29. tmp /= b;
    30. } while (tmp);
    31. reverse(ans.begin(), ans.end()); // 也可将转换结果保存在栈中
    32. cout << ans << endl;
    33. }
    34. return 0;
    35. }

四 最大公约数(GCD)

例 4.4 最大公约数

  • 代码 4.5

    1. #include <iostream>
    2. using std::cin; using std::endl; using std::cout;
    3. int gcd(int x1, int x2) {
    4. if (x2 == 0)
    5. return x1;
    6. else
    7. return gcd(x2, x1 % x2);
    8. }
    9. int gcd_I(int x1, int x2) {
    10. while (x2 != 0) {
    11. int tmp = x1 % x2;
    12. x1 = x2;
    13. x2 = tmp;
    14. }
    15. return x1;
    16. }
    17. int main() {
    18. int a, b;
    19. while (cin >> a >> b) {
    20. cout << "****** 递归版 ******\n" << gcd(a, b) << endl;
    21. cout << "****** 迭代版 ******\n" << gcd_I(a, b) << endl;
    22. }
    23. return 0;
    24. }

五 最小公倍数(LCM)

  • 代码 4.7

    1. #include <iostream>
    2. using std::cin; using std::endl; using std::cout;
    3. int gcd(int x1, int x2) { // 求 x1 和 x2 的最大公约数
    4. return x2 == 0 ? x1 : gcd(x2, x1 % x2);
    5. }
    6. int main() {
    7. int a, b;
    8. while (cin >> a >> b) {
    9. cout << a * b / gcd(a, b) << endl; // 输出最小公倍数
    10. }
    11. return 0;
    12. }

六 素数筛法

例 4.6 素数判定

  • 代码 4.8

    1. #include <iostream>
    2. #include <cmath>
    3. bool judge(int x) { // 判断一个数是否为素数
    4. if (x <= 1) // 若其小于等于1,必不是
    5. return false;
    6. // 计算枚举上界,为防止 double 值带来的精度损失, 所以采用根号值取整后再
    7. // 加 1,即宁愿多枚举一个数也不能少枚举一个数
    8. int bound = static_cast<int>(sqrt(x)) + 1;
    9. for (int i = 2; i < bound; ++i)
    10. if (x % i == 0)
    11. return false;
    12. return true;
    13. }
    14. int main() {
    15. int x;
    16. while (std::cin >> x)
    17. std::cout << (judge(x) ? "yes" : "no") << std::endl;
    18. return 0;
    19. }

例 4.7 素数

  • 代码 4.9

    1. #include <iostream>
    2. #include <map>
    3. #include <vector>
    4. std::map<int, bool> M; // 若 bool 值为 true,则表示该数 int 已被标记成非素数
    5. std::vector<int> ivec; // 保存 1~10000 的素数
    6. void init() { // 素数筛法
    7. for (int i = 1; i <= 10000; ++i) // 初始化,所有数字标记为 false(素数)
    8. M.insert({i, false});
    9. for (int i = 2; i <= 10000; ++i) { // 依次遍历 2~10000 所有数字
    10. if (M[i] == true) // 若该数字已经被标记为非素数,则跳过
    11. continue;
    12. else // 否则得到一个素数
    13. ivec.push_back(i); // 保存到 ivec 中
    14. for (int j = i * i; j <= 10000; j += i) { // 并将该数的所有倍数均标记成非素数
    15. M[j] = true;
    16. }
    17. }
    18. }
    19. int main() {
    20. init(); // 在程序一开始首先取得2到10000中所有素数
    21. int n;
    22. while (std::cin >> n) {
    23. bool isFirstOutPut = false; // 表示是否输出了一个符合条件的数
    24. for (int i = 0; i < ivec.size(); ++i) { // 依次遍历得到的所有素数
    25. if (ivec[i] < n && ivec[i] % 10 == 1) { // 测试当前素数是否符合条件
    26. // 若当前输出为第一个输出的数字,则标记已经输出了符合条件的数字,且该数字前不输出空格
    27. if (isFirstOutPut == false) {
    28. isFirstOutPut = true;
    29. std::cout << ivec[i];
    30. } else { // 否则在输出这个数字前输出一个空格
    31. std::cout << " " << ivec[i];
    32. }
    33. }
    34. }
    35. if (isFirstOutPut == false) // 若始终不存在符合条件的数字
    36. std::cout << "-1\n"; // 输出-1并换行
    37. else // 否则
    38. std::cout << "\n"; // 换行
    39. }
    40. return 0;
    41. }

七 分解素因数

例 4.8 质因数的个数

  • 代码 4.10

    1. #include <iostream>
    2. #include <map>
    3. #include <vector>
    4. std::map<int, bool> M; // 若 bool 值为 true,则表示该数 int 已被标记成非素数
    5. std::vector<int> ivec; // 保存 1~100000 的素数
    6. void init() { // 素数筛法
    7. for (int i = 1; i <= 100000; ++i) // 初始化,所有数字标记为 false(素数)
    8. M.insert({i, false});
    9. for (int i = 2; i <= 100000; ++i) { // 依次遍历 2~100000 所有数字
    10. if (M[i] == true) // 若该数字已经被标记为非素数,则跳过
    11. continue;
    12. else // 否则得到一个素数
    13. ivec.push_back(i); // 保存到 ivec 中
    14. if (i >= 1000) continue;
    15. for (int j = i * i; j <= 100000; j += i) { // 并将该数的所有倍数均标记成非素数
    16. M[j] = true;
    17. }
    18. }
    19. } // 以上与上例一致,用素数筛法筛选出2到100000内的所有素数
    20. int main() {
    21. init(); // 在程序一开始首先取得2到100000中所有素数
    22. int n;
    23. while (std::cin >> n) {
    24. std::vector<int> ansPrime; // 按顺序保存分解出的素因数
    25. int ansSize = 0; // 分解出素因数的个数
    26. std::vector<int> ansNum; // 保存分解出的素因数对应的幂指数
    27. // 注意 i 与 ansSize 并不同步增加
    28. for (int i = 0; i < ivec.size(); ++i) { // 依次测试每一个素数
    29. if (n % ivec[i] == 0) { // 若该素数ivec[i]能整除被分解数n
    30. ansPrime.push_back(ivec[i]); // 则该素数为其素因数
    31. ansNum.push_back(0); // 初始化幂指数为0
    32. while (n % ivec[i] == 0) { // 从被测试数中将该素数分解出来,并统计其幂指数
    33. ++ansNum[ansSize];
    34. n /= ivec[i];
    35. }
    36. ++ansSize; // 素因数个数增加
    37. if (n == 1) break; // 若已被分解成1,则分解提前终止
    38. }
    39. }
    40. if (n != 1) { // 若测试完2到100000内所有素因数,n仍未被分解至1,则剩余的因
    41. // 数一定一个大于100000的素因数
    42. ansPrime.push_back(n); // 记录该大素因数
    43. ansNum.push_back(1); // 其幂指数只能为1
    44. }
    45. int ans = 0;
    46. for (auto e : ansNum) // 统计各个素因数的幂指数
    47. ans += e;
    48. std::cout << ans << std::endl;
    49. }
    50. return 0;
    51. }

例 4.9 整除问题

  • 代码 4.9

    1. #include <iostream>
    2. #include <map>
    3. #include <vector>
    4. std::map<int, bool> M; // 若 bool 值为 true,则表示该数 int 已被标记成非素数
    5. std::vector<int> ivec; // 保存 1~1000 的素数
    6. void init() { // 素数筛法
    7. for (int i = 1; i <= 1000; ++i) // 初始化,所有数字标记为 false(素数)
    8. M.insert({i, false});
    9. for (int i = 2; i <= 1000; ++i) { // 依次遍历 2~1000 所有数字
    10. if (M[i] == true) // 若该数字已经被标记为非素数,则跳过
    11. continue;
    12. else // 否则得到一个素数
    13. ivec.push_back(i); // 保存到 ivec 中
    14. for (int j = i * i; j <= 1000; j += i) { // 并将该数的所有倍数均标记成非素数
    15. M[j] = true;
    16. }
    17. }
    18. } // 以上与上例一致,用素数筛法筛选出2到1000内的所有素数
    19. int main() {
    20. init(); // 在程序一开始首先取得2到1000中所有素数
    21. int n, a;
    22. while (std::cin >> n >> a) {
    23. // 统计 n! 分解素因子后,素因子 ivec[i] 所对应的幂指数,可能为 0
    24. // 因为我们是以 2~1000 内从小到大的素数 ivec[i],依次统计 ivec[i]
    25. // 可整除 n! 的累计次数存入 cntExpN,故某个 ivec[i] 素数可能不
    26. // 是 n! 的素因子,其累计次数为 0
    27. std::vector<int> cntExpN;
    28. std::vector<int> cntExpA; // 同理
    29. for (int i = 0; i < ivec.size(); ++i) {
    30. cntExpN.push_back(0); // 初始化ivec[i]的幂指数为0
    31. int tmp = n; // 用临时变量保存 n 的值
    32. // 依次计算 tmp / ivec[i]^k,累加其值,直到 tmp / ivec[i]^k 变为 0
    33. while (tmp) {
    34. cntExpN[i] += tmp / ivec[i];
    35. tmp /= ivec[i];
    36. }
    37. }
    38. int ans = INT_MAX; // 答案初始值为一个大整数,为取最小值做准备
    39. for (int i = 0; i < ivec.size(); ++i) { // 对 a 分解素因数
    40. cntExpA.push_back(0); // 同理
    41. // 计算 a 中素因数 ivec[i] 对应的幂指数
    42. while (a % ivec[i] == 0) {
    43. ++cntExpA[i];
    44. a /= ivec[i];
    45. }
    46. // 若素数 ivec[i] 不能从 a 分解到,即 ivec[i] 对应的幂指数为 0,则
    47. // 其不影响整除性,跳过
    48. if (cntExpA[i] == 0)
    49. continue;
    50. else {
    51. if (cntExpN[i] / cntExpA[i] < ans) // 计算素数ivec[i]在两个数中幂指数的商
    52. ans = cntExpN[i] / cntExpA[i]; // 统计这些商的最小值
    53. } // 根据题意 cntExpN[i] / cntExpA[i] 能够保证整除(不会出现商为小数)
    54. }
    55. std::cout << ans << std::endl;
    56. }
    57. return 0;
    58. }

八 二分求幂

例 4.10 人见人爱 \(A^B\)

  • 代码 4.10

    1. #include <iostream>
    2. int main() {
    3. int a, b;
    4. while (std::cin >> a >> b) {
    5. if (a == 0 && b == 0)
    6. break;
    7. int ans = 1; // 保存最终结果变量,初始值为1
    8. // 一边计算b的二进制值,一边计算a的2^k次,并将需要的部分累乘到变量ans上
    9. while (b != 0) { // 若b不为0,即对b转换二进制过程未结束
    10. if (b % 2 == 1) { // 若当前二进制位为1,则需要累乘a的2^k次至变量ans,其
    11. // 中2^k次为当前二进制位的权重
    12. ans *= a; // 最终结果累乘a
    13. ans %= 1000; // 求其后三位数
    14. }
    15. b /= 2; // b除以2
    16. a *= a; // 求下一位二进制位的权重,a求其平方,即从a的1次开始,依次求的a的2次,a的4次...
    17. a %= 1000; // 求a的后三位
    18. }
    19. std::cout << ans << std::endl;
    20. }
    21. return 0;
    22. }

九 高精度整数

例 4.11 a+b

  • 代码 4.11

    1. #include <iostream>
    2. #include <string>
    3. #include <iomanip>
    4. struct bigInteger { // 高精度整数结构体
    5. int digit[1000]; // 按四位数一个单位保存数值
    6. int size; // 下一个我们未使用的数组单元
    7. void init() { // 对结构体的初始化
    8. for (int i = 0; i < 1000; i++)
    9. digit[i] = 0; // 所有数位清0
    10. size = 0; // 下一个未使用数组单元为0,即没有一个单元被使用
    11. }
    12. void set(std::string str); // 从字符串中提取整数
    13. void output(); // 将该高精度整数输出
    14. bigInteger operator+(const bigInteger &B) const; // 重载加法运算符
    15. } a, b, c;
    16. void bigInteger::set(std::string str) {
    17. init(); // 对结构体初始化
    18. int L = str.size(); // 计算字符串长度
    19. for (int i = L - 1, j = 0, t = 0, c = 1; 0 <= i; --i) {
    20. // 从最后一个字符开始倒序遍历字符串,j控制每4个字符转换为一个数字存入数组,t临
    21. // 时保存字符转换为数字的中间值,c表示当前位的权重,按1,10,100,1000顺序变化
    22. t += (str[i] - '0') * c; // 计算这个四位数中当前字符代表的数字,即数字乘以当前位权重
    23. ++j; // 当前转换字符数增加
    24. c *= 10; // 计算下一位权重
    25. if (j == 4 || i == 0) { // 若已经连续转换四个字符,或者已经到达最后一个字符
    26. digit[size++] = t; // 将这四个字符代表的四位数存入数组,size移动到下一个数组单元
    27. j = 0; // 重新开始计算下4个字符
    28. t = 0; // 临时变量清0
    29. c = 1; // 权重重置为1(个位数)
    30. }
    31. }
    32. }
    33. void bigInteger::output() {
    34. for (int i = size - 1; i >= 0; --i) {
    35. if (i != size - 1) // 若当前输出的数字不是最高位数字,当前数字不足4位时高位由0补充
    36. std::cout << std::setw(4) << std::setfill('0') << digit[i];
    37. else
    38. std::cout << digit[i]; // 若是最高位,则无需输出前导零
    39. }
    40. std::cout << "\n"; // 换行
    41. }
    42. bigInteger bigInteger::operator+(const bigInteger & B) const {
    43. bigInteger ret; // 返回值,即两数相加的结果
    44. ret.init(); // 对其初始化
    45. int carry = 0; // 进位,初始化为0
    46. for (int i = 0; i < B.size || i < size; ++i) {
    47. int tmp = B.digit[i] + digit[i] + carry; // 计算两个整数当前位以及来自低位的进位和
    48. carry = tmp / 10000; // 计算该位的进位
    49. tmp %= 10000; // 去除进位部分,取后四位
    50. ret.digit[ret.size++] = tmp; // 保存该位结果
    51. }
    52. if (carry != 0) { // 计算结束后若最高位有进位
    53. ret.digit[ret.size++] = carry; // 保存该进位
    54. }
    55. return ret;
    56. }
    57. int main() {
    58. std::string str1, str2;
    59. while (std::cin >> str1 >> str2) {
    60. a.set(str1); b.set(str2); // 用两个字符串分别设置两个高精度整数
    61. c = a + b; // 计算它们的和
    62. c.output(); // 输出结果
    63. }
    64. return 0;
    65. }

例 4.12 N 的阶乘

  • 代码 4.12

    1. #include <iostream>
    2. #include <iomanip>
    3. struct bigInteger { // 高精度整数结构体
    4. int digit[1000]; // 按四位数一个单位保存数值
    5. int size; // 下一个我们未使用的数组单元
    6. void init() { // 对结构体的初始化
    7. for (int i = 0; i < 1000; i++)
    8. digit[i] = 0; // 所有数位清0
    9. size = 0; // 下一个未使用数组单元为0,即没有一个单元被使用
    10. }
    11. void set(int x); // 用一个小整数设置高精度整数
    12. void output(); // 将该高精度整数输出
    13. bigInteger operator*(const int x) const; // 重载乘法运算符
    14. } a;
    15. void bigInteger::set(int x) {
    16. init(); // 对结构体初始化
    17. do { // 对小整数4位为一个单位分解依次存入digit当中
    18. digit[size++] = x % 10000;
    19. x /= 10000;
    20. } while (x != 0);
    21. }
    22. void bigInteger::output() {
    23. for (int i = size - 1; i >= 0; --i) {
    24. if (i != size - 1) // 若当前输出的数字不是最高位数字,当前数字不足4位时高位由0补充
    25. std::cout << std::setw(4) << std::setfill('0') << digit[i];
    26. else
    27. std::cout << digit[i]; // 若是最高位,则无需输出前导零
    28. }
    29. std::cout << "\n"; // 换行
    30. }
    31. bigInteger bigInteger::operator*(const int x) const {
    32. bigInteger ret; // 返回值,即两数相乘的结果
    33. ret.init(); // 对其初始化
    34. int carry = 0; // 进位,初始化为0
    35. for (int i = 0; i < size; ++i) {
    36. int tmp = x * digit[i] + carry; // 用小整数x乘以当前位数字并加上来自低位的进位
    37. carry = tmp / 10000; // 计算进位
    38. tmp %= 10000; // 去除进位部分,取后四位
    39. ret.digit[ret.size++] = tmp; // 保存该位结果
    40. }
    41. if (carry != 0) { // 计算结束后若最高位有进位
    42. ret.digit[ret.size++] = carry; // 保存该进位
    43. }
    44. return ret;
    45. }
    46. int main() {
    47. int n;
    48. while (std::cin >> n) {
    49. a.init(); // 初始化a
    50. a.set(1); // a初始值为1
    51. for (int i = 1; i <= n; ++i) {
    52. a = a * i;
    53. }
    54. a.output(); // 输出a
    55. }
    56. return 0;
    57. }

例 4.13 进制转换

  • 代码 4.13

    1. #include <stdio.h>
    2. #include <string.h>
    3. #define maxDigits 100
    4. struct bigInteger { // 高精度整数结构体
    5. int digit[maxDigits]; // 按四位数一个单位保存数值
    6. int size; // 下一个我们未使用的数组单元
    7. void init() { // 对结构体的初始化
    8. for (int i = 0; i < maxDigits; i++)
    9. digit[i] = 0; // 所有数位清0
    10. size = 0; // 下一个未使用数组单元为0,即没有一个单元被使用
    11. }
    12. void set(int x); // 用一个普通整数初始化高精度整数
    13. void output(); // 将该高精度整数输出
    14. bigInteger operator*(const int x) const; // 重载乘法运算符
    15. bigInteger operator+(const bigInteger &B) const;
    16. bigInteger operator/(const int x) const;
    17. int operator%(const int x) const;
    18. } a, b;
    19. void bigInteger::set(int x) {
    20. init(); // 对结构体初始化
    21. do { // 将该普通整数4位为一个单位分解依次存入digit当中
    22. digit[size++] = x % 10000;
    23. x /= 10000;
    24. } while (x != 0);
    25. }
    26. void bigInteger::output() {
    27. for (int i = size - 1; i >= 0; --i) {
    28. if (i != size - 1) // 若当前输出的数字不是最高位数字,当前数字不足4位时高位由0补充
    29. printf("%04d", digit[i]);
    30. else
    31. printf("%d", digit[i]); // 若是最高位,则无需输出前导零
    32. }
    33. printf("\n"); // 换行
    34. }
    35. bigInteger bigInteger::operator*(const int x) const {
    36. bigInteger ret; // 返回值,即两数相乘的结果
    37. ret.init(); // 对其初始化
    38. int carry = 0; // 进位,初始化为0
    39. for (int i = 0; i < size; ++i) {
    40. int tmp = x * digit[i] + carry;
    41. carry = tmp / 10000; // 计算进位
    42. tmp %= 10000; // 去除进位部分,取后四位
    43. ret.digit[ret.size++] = tmp; // 保存该位结果
    44. }
    45. if (carry != 0) { // 计算结束后若最高位有进位
    46. ret.digit[ret.size++] = carry; // 保存该进位
    47. }
    48. return ret;
    49. }
    50. bigInteger bigInteger::operator+(const bigInteger &B) const {
    51. bigInteger ret;
    52. ret.init();
    53. int carry = 0;
    54. for (int i = 0; i < B.size || i < size; ++i) {
    55. int tmp = B.digit[i] + digit[i] + carry;
    56. carry = tmp / 10000;
    57. tmp %= 10000;
    58. ret.digit[ret.size++] = tmp;
    59. }
    60. if (carry != 0) {
    61. ret.digit[ret.size++] = carry;
    62. }
    63. return ret;
    64. }
    65. bigInteger bigInteger::operator/(const int x) const { // 高精度整数除以普通整数
    66. bigInteger ret; // 返回的高精度整数
    67. ret.init(); // 返回值初始化
    68. int remainder = 0; // 余数
    69. for (int i = size - 1; 0 <= i; --i) { // 从最高位至最低位依次完成计算
    70. // 计算当前位数值加上高位剩余的余数的和对x求得的商
    71. int t = (remainder * 10000 + digit[i]) / x;
    72. // 计算当前位数值加上高位剩余的余数的和对x求模后得的余数
    73. int r = (remainder * 10000 + digit[i]) % x;
    74. ret.digit[i] = t; // 保存本位的值
    75. remainder = r; // 保存至本位为止的余数
    76. }
    77. // 返回高精度整数的size初始值为0,即当所有位数字都为0 时,digit[0]代表数字0,作为最高
    78. // 有效位,高精度整数即为数字0
    79. ret.size = 0;
    80. // 若存在非0位,确定最高的非0位,作为最高有效位
    81. for (int i = 0; i < maxDigits; ++i) {
    82. if (digit[i] != 0)
    83. ret.size = i;
    84. }
    85. ++ret.size; // 最高有效位的下一位即为下一个我们不曾使用的digit数组单元,确定为size的值
    86. return ret;
    87. }
    88. int bigInteger::operator%(const int x) const { // 高精度整数对普通整数求余数
    89. int remainder = 0; // 余数
    90. // 过程同高精度整数对普通整数求商
    91. for (int i = size - 1; 0 <= i; --i) {
    92. // int t = (remainder * 10000 + digit[i]) / x;
    93. int r = (remainder * 10000 + digit[i]) % x;
    94. remainder = r;
    95. }
    96. return remainder; // 返回余数
    97. }
    98. char str[10000];
    99. char ans[10000];
    100. int main() {
    101. int m, n;
    102. while (scanf("%d%d", &m, &n) != EOF) {
    103. scanf("%s", str); // 输入m进制数
    104. int L = strlen(str);
    105. a.set(0); // a初始值为0,用来保存转换成10进制的m进制数
    106. b.set(1); // b初始值为1,在m进制向10进制转换的过程中,依次代表每一位的权重
    107. // 由低位至高位转换m进制数至相应的10进制数
    108. for (int i = L - 1; 0 <= i; --i) {
    109. int t;
    110. if (str[i] >= '0' && str[i] <= '9') {
    111. t = str[i] - '0';
    112. } else {
    113. t = str[i] - 'A' + 10; // 确定当前位字符代表的数字
    114. }
    115. a = a + b * t; // 累加当前数字乘当前位权重的积
    116. b = b * m; // 计算下一位权重
    117. }
    118. int size = 0; // 代表转换为n进制后的字符个数
    119. do { // 对转换后的10进制数求其n进制值
    120. int t = a % n; // 求余数
    121. if (t >= 10)
    122. ans[size++] = t - 10 + 'a';
    123. else
    124. ans[size++] = t + '0'; // 确定当前位字符
    125. a = a / n; // 求商
    126. } while (a.digit[0] != 0 || a.size != 1); // 当a不为0时重复该过程
    127. for (int i = size - 1; 0 <= i; --i)
    128. printf("%c", ans[i]);
    129. printf("\n");
    130. }
    131. return 0;
    132. }

第 5 章 图论

一 预备知识

二 并查集

例 5.1 畅通工程

  • 代码 5.1

    1. #include <iostream>
    2. #define N 1000
    3. int Tree[N];
    4. int findRoot(int x) { // 查找某个结点所在树的根结点,并压缩路径
    5. if (Tree[x] == -1)
    6. return x;
    7. else {
    8. int tmp = findRoot(Tree[x]);
    9. Tree[x] = tmp; // 将当前结点的双亲结点设置为查找返回的根结点编号
    10. return tmp;
    11. }
    12. }
    13. int main() {
    14. int n, m;
    15. while (std::cin >> n && n) { // n 非零
    16. // 初始时,所有结点都是孤立的集合,即其所在集合只有一个结点,其本身就是所在树根结点
    17. for (int i = 1; i <= n; ++i) Tree[i] = -1;
    18. std::cin >> m;
    19. while (m--) { // 读入边信息
    20. int a, b;
    21. std::cin >> a >> b;
    22. // 查找边的两个顶点所在集合信息
    23. a = findRoot(a); b = findRoot(b);
    24. // 若两个顶点不在同一个集合则合并这两个集合
    25. if (a != b) Tree[a] = b;
    26. }
    27. int ans = 0;
    28. for (int i = 1; i <=n; ++i) {
    29. if (Tree[i] == -1) // 统计所有结点中根结点的个数
    30. ++ans;
    31. }
    32. std::cout << ans - 1 << std::endl;
    33. }
    34. return 0;
    35. }

例 5.2 More is better

  • 代码 5.2

    1. #include <iostream>
    2. #define N 10000001
    3. int Tree[N];
    4. int findRoot(int x) { // 查找某个结点 x 所在树的根结点,并压缩路径
    5. if (Tree[x] == -1)
    6. return x;
    7. else {
    8. int tmp = findRoot(Tree[x]);
    9. Tree[x] = tmp; // 将当前结点的双亲结点设置为查找返回的根结点编号
    10. return tmp;
    11. }
    12. }
    13. // 用sum[i]表示以结点i为根的树的结点个数,其中保存数据仅当Tree[i]为-1即该结点为树的根结点时有效
    14. int sum[N];
    15. int main() {
    16. int n;
    17. while (std::cin >> n) {
    18. for (int i = 1; i < N; ++i) { // 初始化结点信息
    19. Tree[i] = -1; // 所有结点为孤立集合
    20. sum[i] = 1; // 所有集合的元素个数为1
    21. }
    22. while (n--) {
    23. int a, b;
    24. std::cin >> a >> b;
    25. a = findRoot(a); b = findRoot(b);
    26. if (a != b) {
    27. Tree[a] = b;
    28. // 合并两集合时,将成为子树的树根结点上保存的该集合元素个数的数字累加到合并后新树的树根
    29. sum[b] += sum[a];
    30. }
    31. }
    32. int ans = 1; // 答案,答案至少为1。固这里先出初始化为1
    33. for (int i = 1; i <= N; ++i) {
    34. if (Tree[i] == -1 && sum[i] > ans)
    35. ans = sum[i]; // 统计最大值
    36. }
    37. std::cout << ans << std::endl; // 输出
    38. }
    39. return 0;
    40. }

三 最小生成树(MST)

例 5.3 还是畅通工程

  • 代码 5.3

    1. #include <iostream>
    2. #include <algorithm>
    3. #define N 101
    4. int Tree[N];
    5. int findRoot(int x) { // 查找某个结点 x 所在树的根结点,并压缩路径
    6. if (Tree[x] == -1)
    7. return x;
    8. else {
    9. int tmp = findRoot(Tree[x]);
    10. Tree[x] = tmp; // 将当前结点的双亲结点设置为查找返回的根结点编号
    11. return tmp;
    12. }
    13. }
    14. struct Edge { // 边结构体
    15. int a, b; // 边两个顶点的编号
    16. int cost; // 该边的的权值
    17. bool operator<(const Edge &B) const { // 重载小于号,方便边权值从小到大排列
    18. return cost < B.cost;
    19. }
    20. } edge[6000];
    21. int main() {
    22. int n;
    23. while (std::cin >> n && n != 0) {
    24. for (int i = 1; i <= n * (n - 1) / 2; ++i) { // 输入
    25. std::cin >> edge[i].a >> edge[i].b >> edge[i].cost;
    26. }
    27. // 按照边权值递增排列所有的边
    28. std::sort(edge + 1, edge + 1 + n * (n - 1) / 2);
    29. for (int i = 1; i <= n; ++i)
    30. Tree[i] = -1; // 初始时所有的结点都属于孤立的集合
    31. int ans = 0; // 最小生成树上边权的和,初始值为0
    32. for (int i = 1; i <= n * (n - 1) / 2; ++i) { // 按照边权值递增顺序遍历所边
    33. // 查找该边两个顶点的集合信息
    34. int a = findRoot(edge[i].a), b = findRoot(edge[i].b);
    35. if (a != b) { // 若它们属于不同集合,则选用该边
    36. Tree[a] = b; // 合并两个集合
    37. ans += edge[i].cost; // 累加该边权值
    38. }
    39. }
    40. std::cout << ans << std::endl; // 输出
    41. }
    42. return 0;
    43. }

例 5.4 Freckles

  • 代码 5.4

    1. #include <iostream>
    2. #include <algorithm>
    3. #include <cmath>
    4. #define N 101
    5. int Tree[N];
    6. int findRoot(int x) { // 查找某个结点 x 所在树的根结点,并压缩路径
    7. if (Tree[x] == -1)
    8. return x;
    9. else {
    10. int tmp = findRoot(Tree[x]);
    11. Tree[x] = tmp; // 将当前结点的双亲结点设置为查找返回的根结点编号
    12. return tmp;
    13. }
    14. }
    15. struct Edge { // 边结构体
    16. int a, b; // 边两个顶点的编号
    17. double cost; // 该边的的权值(两点之间的距离)
    18. bool operator<(const Edge &B) const { // 重载小于号,方便边权值从小到大排列
    19. return cost < B.cost;
    20. }
    21. } edge[6000];
    22. struct Point { // 点结构体
    23. double x, y; // 点横纵坐标
    24. double getDistance(Point B) { // 计算点之间的距离
    25. double tmp = (x - B.x) * (x - B.x) + (y - B.y) * (y - B.y);
    26. return sqrt(tmp);
    27. }
    28. } list[101];
    29. int main() {
    30. int n;
    31. while (std::cin >> n) {
    32. for (int i = 1; i <= n; ++i) { // 输入
    33. std::cin >> list[i].x >> list[i].y;
    34. }
    35. int size = 0; // 抽象出的边的总数
    36. // 遍历所有两两点
    37. for (int i = 1; i <= n; ++i) {
    38. for (int j = i + 1; j <= n; ++j) { // 连接两点的线段抽象成边
    39. // 该边的两个顶点编号
    40. edge[size].a = i; edge[size].b = j;
    41. // 边权值为两点之间的长度
    42. edge[size].cost = list[i].getDistance(list[j]);
    43. ++size; // 边的总数增加
    44. }
    45. }
    46. std::sort(edge, edge + size); // 对边按权值递增排序
    47. for (int i = 1; i <= n; ++i)
    48. Tree[i] = -1;
    49. double ans = 0;
    50. // 最小生成树
    51. for (int i = 0; i < size; ++i) {
    52. int a = findRoot(edge[i].a), b = findRoot(edge[i].b);
    53. if (a != b) {
    54. Tree[a] = b;
    55. ans += edge[i].cost;
    56. }
    57. }
    58. std::cout << ans << std::endl;
    59. }
    60. return 0;
    61. }

四 最短路径

两种常见的最短路径问题:

  • 单源最短路径算法(Dijkstra:适用于图用邻接链表表示):某个顶点到其它所有顶点的最短路径,时间复杂度\(O{(n^2)}\);

  • 所有顶点对之间的最短路径(Floyd:适用于图用邻接矩阵表示)

    • 方法一:每次以一个顶点为源点,重复执行 Dijkstra 算法 n 次,时间复杂度\(O{(n^3)}\);
    • 方法二:Floyd算法

例 5.5 最短路

  • 代码 5.5(Floyd)

    1. #include <iostream>
    2. int ans[101][101]; // 二维数组,其初始值即为该图的邻接矩阵
    3. int main() {
    4. int n, m;
    5. while (std::cin >> n >> m) {
    6. if (n == 0 && m == 0) break;
    7. // 对邻接矩阵初始化,我们用-1代表无穷
    8. for (int i = 1; i <= n; ++i) {
    9. for (int j = 1; j <= n; ++j) {
    10. ans[i][j] = -1;
    11. }
    12. ans[i][i] = 0; // 自己到自己的路径长度设为0
    13. }
    14. while (m--) {
    15. int a, b, c;
    16. std::cin >> a >> b >> c;
    17. // 对邻接矩阵赋值,由于是无向图,该赋值操作要进行两次
    18. ans[a][b] = ans[b][a] = c;
    19. }
    20. // k从1到N循环,依次代表允许经过的中间结点编号小于等于k
    21. for (int k = 1; k <= n; ++k) {
    22. for (int i = 1; i <= n; ++i) {
    23. // 遍历所有ans[i][j],判断其值保持原值还是将要被更新
    24. for (int j = 1; j <= n; ++j) {
    25. // 若两值中有一个值为无穷,则ans[i][j]不能由于经过结点k而被更新,跳过循环,保持原值
    26. if (ans[i][k] == -1 || ans[k][j] == -1) continue;
    27. // 当由于经过k可以获得更短的最短路径时,更新该值
    28. if (ans[i][j] == -1 || ans[i][k] + ans[k][j] < ans[i][j])
    29. ans[i][j] = ans[i][k] + ans[k][j];
    30. }
    31. }
    32. }
    33. std::cout << ans[1][n] << std::endl; // 循环结束后输出答案
    34. }
    35. return 0;
    36. }
  • 代码 5.6

    1. #include <iostream>
    2. #include <vector>
    3. struct E { // 邻接链表中的链表元素结构体
    4. int next; // 代表直接相邻的结点
    5. int c; // 代表该边的权值(长度)
    6. };
    7. std::vector<E> edge[101]; // 邻接链表
    8. bool mark[101]; // 标记,当mark[j]为true时表示结点j的最短路
    9. // 径长度已经得到,该结点已经加入集合K
    10. int Dis[101]; // 距离向量,当mark[i]为true时,表示已得的最
    11. // 短路径长度;否则,表示所有从结点1出发,经过已知的最短路径达到
    12. // 集合K中的某结点,再经过一条边到达结点i的路径中最短的距离
    13. int main() {
    14. int n, m;
    15. while (std::cin >> n >> m) {
    16. if (n == 0 && m == 0) break;
    17. for (int i = 1; i <= n; ++i)
    18. edge[i].clear(); // 初试化邻接链表
    19. while (m--) {
    20. int a, b, c;
    21. std::cin >> a >> b >> c;
    22. E tmp;
    23. tmp.c = c;
    24. // 将邻接信息加入邻接链表,由于原图为无向图,固每条边信息
    25. // 都要添加到其两个顶点的两条单链表中
    26. tmp.next = b;
    27. edge[a].push_back(tmp);
    28. tmp.next = a;
    29. edge[b].push_back(tmp);
    30. }
    31. for (int i = 1; i <= n; ++i) { // 初始化
    32. Dis[i] = -1; // 所有距离为-1,即不可达
    33. mark[i] = false; // 所有结点不属于集合K
    34. }
    35. Dis[1] = 0; // 得到最近的点为结点1,长度为0
    36. mark[1] = true; // 将结点1加入集合K
    37. int newP = 1; // 集合K中新加入的点为结点1
    38. // 循环n-1次,按照最短路径递增的顺序确定其他n-1个点的最短路径长度
    39. for (int i = 1; i < n; ++i) {
    40. // 遍历与该新加入集合K中的结点直接相邻的边
    41. for (int j = 0; j < edge[newP].size(); ++j) {
    42. int t = edge[newP][j].next; // 该边的另一个结点
    43. int c = edge[newP][j].c; // 该边的长度
    44. if (mark[t] == true)
    45. continue; // 若另一个结点也属于集合K,则跳过
    46. // 若该结点尚不可达,或者该结点从新加入的结点经过一条边到
    47. // 达时比以往距离更短
    48. if (Dis[t] == -1 || Dis[t] > Dis[newP] + c)
    49. Dis[t] = Dis[newP] + c; // 更新其距离信息
    50. }
    51. int min = INT_MAX; // 最小值初始化为一个大整数,为找最小值做准备
    52. for (int j = 1; j <= n; ++j) { // 遍历所有结点
    53. if (mark[j] == true) continue; // 若其属于集合K则跳过
    54. if (Dis[j] == -1) continue; // 若该结点仍不可达则跳过
    55. if (Dis[j] < min) { // 若该结点经由结点1至集合K中的某点再
    56. // 经过一条边到达时距离小于当前最小值
    57. min = Dis[j]; // 更新其为最小值
    58. newP = j; // 新加入的点暂定为该点
    59. }
    60. }
    61. mark[newP] = true; // 将新加入的点加入集合K,Dis[newP]虽然数值
    62. // 不变,但意义发生变化,由所有经过集合K中的结点再经过一条边到达时
    63. // 的距离中的最小值变为从结点1到结点newP的最短距离
    64. }
    65. std::cout << Dis[n] << std::endl; // 输出
    66. }
    67. return 0;
    68. }

例 5.6 最短路径问题

  • 代码 5.7

    1. #include <iostream>
    2. #include <vector>
    3. struct E { // 邻接链表中的链表元素结构体
    4. int next; // 代表直接相邻的结点
    5. int c; // 代表该边的权值(长度)
    6. int cost;
    7. };
    8. std::vector<E> edge[1001]; // 邻接链表
    9. bool mark[1001]; // 是否属于集合K数组
    10. int Dis[1001]; // 距离数组
    11. int cost[1001]; // 花费数组
    12. // 短路径长度;否则,表示所有从结点1出发,经过已知的最短路径达到
    13. // 集合K中的某结点,再经过一条边到达结点i的路径中最短的距离
    14. int main() {
    15. int n, m;
    16. int S, T; // 起点,终点
    17. while (std::cin >> n >> m) {
    18. if (n == 0 && m == 0) break;
    19. for (int i = 1; i <= n; ++i)
    20. edge[i].clear(); // 初试化邻接链表
    21. while (m--) {
    22. int a, b, c, cost;
    23. std::cin >> a >> b >> c >> cost;
    24. E tmp;
    25. tmp.c = c;
    26. tmp.cost = cost; // 邻接链表中增加了该边的花费信息
    27. // 将邻接信息加入邻接链表,由于原图为无向图,固每条边信息
    28. // 都要添加到其两个顶点的两条单链表中
    29. tmp.next = b;
    30. edge[a].push_back(tmp);
    31. tmp.next = a;
    32. edge[b].push_back(tmp);
    33. }
    34. std::cin >> S >> T; // 输入起点终点信息
    35. for (int i = 1; i <= n; ++i) { // 初始化
    36. Dis[i] = -1;
    37. mark[i] = false;
    38. }
    39. Dis[S] = 0;
    40. mark[S] = true;
    41. int newP = S; // 起点为S,将其加入集合K,且其最短距离确定为0
    42. // 循环n-1次,按照最短路径递增的顺序确定其他n-1个点的最短路径长度
    43. for (int i = 1; i < n; ++i) {
    44. // 遍历与该新加入集合K中的结点直接相邻的边
    45. for (int j = 0; j < edge[newP].size(); ++j) {
    46. int t = edge[newP][j].next;
    47. int c = edge[newP][j].c;
    48. int co = edge[newP][j].cost; // 花费
    49. if (mark[t] == true)
    50. continue;
    51. // 比较大小时,将距离相同但花费更短也作为更新的条件之一
    52. if (Dis[t] == -1 || Dis[t] > Dis[newP] + c
    53. || Dis[t] == Dis[newP] + c && cost[t] > cost[newP] + co) {
    54. Dis[t] = Dis[newP] + c;
    55. cost[t] = cost[newP] + co; // 更新花费
    56. }
    57. }
    58. int min = INT_MAX; // 最小值初始化为一个大整数,为找最小值做准备
    59. for (int j = 1; j <= n; ++j) { // 遍历所有结点。选择最小值,选择时
    60. // 不用考虑花费的因素,因为距离最近的点的花费已经不可能由于经过其它
    61. // 点而发生改变了
    62. if (mark[j] == true) continue;
    63. if (Dis[j] == -1) continue;
    64. if (Dis[j] < min) {
    65. min = Dis[j];
    66. newP = j;
    67. }
    68. }
    69. mark[newP] = true;
    70. }
    71. std::cout << Dis[T] << " " << cost[T] << std::endl; // 输出
    72. }
    73. return 0;
    74. }

五 拓扑排序

例 5.7

  • 代码 5.8

    1. #include <stdio.h>
    2. #include <vector>
    3. #include <queue>
    4. using namespace std;
    5. vector<int> edge[501]; // 邻接链表,因为边不存在权值,只需保存与
    6. // 其邻接的结点编号即可,所以vector中的元素为int
    7. queue<int> Q; // 保存入度为0的结点的队列
    8. int main() {
    9. int inDegree[501]; // 统计每个结点的入度
    10. int n, m;
    11. while (scanf("%d%d", &n, &m) != EOF) {
    12. if (n == 0 && m == 0) break;
    13. for (int i = 0; i < n; i++) { // 初始化所有结点,注意本题结点编号由0到n-1
    14. inDegree[i] = 0; // 初始化入度信息,所有结点入度均为0
    15. edge[i].clear(); // 清空邻接链表
    16. }
    17. while (m--) {
    18. int a, b;
    19. scanf("%d%d", &a, &b); // 读入一条由a指向b的有向边
    20. inDegree[b]++; // 又出现了一条弧头指向b的边,累加结点b的入度
    21. edge[a].push_back(b); // 将b加入a的邻接链表
    22. }
    23. while (Q.empty() == false) Q.pop(); // 若队列非空,则一直弹出队头元素,该操
    24. // 作的目的为清空队列中所有的元素(可
    25. // 能为上一组测试数据中遗留的数据)
    26. for (int i = 0; i < n; i++) { // 统计所有结点的入度
    27. if (inDegree[i] == 0) Q.push(i); // 若结点入度为0,则将其放入队列
    28. }
    29. int cnt = 0; // 计数器,初始值为0,用于累加已经确定拓扑序列的结点个数
    30. while (Q.empty() == false) { // 当队列中入度为0的结点未被取完时,重复
    31. int nowP = Q.front(); // 读出队头结点编号,本例不需要求出确定的拓扑序列,
    32. // 固不做处理;若要求求出确定的拓扑次序,则将该结点
    33. // 紧接着放在已经确定的拓扑序列之后
    34. Q.pop(); // 弹出对头元素
    35. cnt++; // 被确定的结点个数加一
    36. // 将该结点以及以其为弧尾的所有边去除
    37. for (int i = 0; i < edge[nowP].size(); i++) {
    38. inDegree[edge[nowP][i]]--; // 去除某条边后,该边所指后继结点入度减一
    39. if (inDegree[edge[nowP][i]] == 0) { // 若该结点入度变为0
    40. Q.push(edge[nowP][i]); // 将其放入队列当中
    41. }
    42. }
    43. }
    44. if (cnt == n)
    45. puts("YES"); // 若所有结点都能被确定拓扑序列,则原图为有向无环图
    46. else
    47. puts("NO"); // 否则,原图为非有向无环图
    48. }
    49. return 0;
    50. }

第 6 章 搜索

一 枚举

例 6.1 百鸡问题

  • 代码 6.1

    1. #include <iostream>
    2. int main() {
    3. int n;
    4. while (std::cin >> n) {
    5. for (int x = 0; x <= 100; ++x) // 枚举x的值
    6. for (int y = 0; y <= 100 - x; ++y) { // 枚举y的值,注意它们的和不可能超过100
    7. int z = 100 - x - y;
    8. // 考虑到一只小小鸡 的价格为1/3,为避免除法带来的精度损失,这里采用了对不等式两端
    9. // 所有数字都乘3的操作,这也是 避免除法的常用技巧
    10. if (x * 5 * 3 + y * 3 * 3 + z <= n * 3)
    11. std::cout << x << " " << y << " " << z << std::endl;
    12. }
    13. }
    14. return 0;
    15. }

王道机试指南题解(C/C++版)的更多相关文章

  1. 机试指南第二章-经典入门-Hash的应用自解

    Hash的应用: Hash即散列,不像数据结构与算法中讲的各种Hash方法和冲突处理等过多的阐述,以下主要介绍Hash在机试试题解答中的作用. 例2.5 统计同成绩学生人数 Hash解法AC代码:(一 ...

  2. 《N诺机试指南》(三)STL使用

    1.vector 2.queue 3.stack 4.map 5.set 6.多组输入输出问题 详解见代码以及注释: //学习STL的使用 #include <bits/stdc++.h> ...

  3. 《N诺机试指南》(二)C++自带实用函数

    1.排序sort函数: 2.查找:  实例:  3. 队列:

  4. 《N诺机试指南》(五)进制转化

    进制转化类题目类型: 代码详解及注释解答:  //进制转化问题 #include <bits/stdc++.h> using namespace std; int main(){ // 1 ...

  5. 《N诺机试指南》(七)排版类问题

    1.菱形问题: 解析: 主要通过打印空格和星形来打印整个图形,将整体分为=上三角形+下三角形 首先观察上三角形可以发现:第一行2个空格1个星.第二行1个空格3个星.第三行0个空格5个星     空格数 ...

  6. 《N诺机试指南》(一)数组妙用

    题目A: 大家思路有可能是这样: 将输入数据全部存储到一个数组里,然后可以冒泡排序一波,从小到大排序 那么怎么找到重复次数呢:我是这样想的,新定义数组b,原数组a,首先b[0] = a[0],定义指针 ...

  7. 《N诺机试指南》(八)日期、字符串、排序问题

    1.日期问题: 输入: 例题: 代码: #include <stdio.h> #include <bits/stdc++.h> struct node{ int year, m ...

  8. 剑指offer题解(Java版)

    剑指offer题解(Java版) 从尾到头打印链表 题目描述 输入一个链表,按从尾到头的顺序返回一个ArrayList. 方法1:用一个栈保存从头到尾访问链表的每个结点的值,然后按出栈顺序将各个值存入 ...

  9. 《Netty 权威指南(第2 版)》目录

    图书简介:<Netty 权威指南(第2 版)>是异步非阻塞通信领域的经典之作,基于最新版本的Netty 5.0 编写,是国内很难得一见的深入介绍Netty 原理和架构的书籍,也是作者多年实 ...

随机推荐

  1. sql普通语句

    select DISTINCT t_id from nrc_newsDISTINCT不会输出相同的值select top 5 * from nrc_news;检索前五行select * from nr ...

  2. Stream系列(八)Reduce方法使用

    裁减计算 视频讲解:  https://www.bilibili.com/video/av77715582/ EmployeeTest.java package com.example.demo; i ...

  3. poj2299(归并排序求逆序对)

    题目链接:https://vjudge.net/problem/POJ-2299 题意:给定一个序列,每次只能交换邻近的两个元素,问要交换多少次才能使序列按升序排列. 思路:本质就是求逆序对.我们用归 ...

  4. IDEA连接 Oracle数据库

    package com.zxx.util;import org.apache.commons.dbutils.DbUtils;import java.sql.Connection;import jav ...

  5. SQLServer启动和关闭bat脚本

    原文:SQLServer启动和关闭bat脚本   安装完毕SQL SERVER 2005后,会默认自动启动SQL Server等几个服务,这几个服务比较占用系统资源.当不运行SQL Server时,最 ...

  6. linux内核钩子--khook

    简介 本文介绍github上的一个项目khook,一个可以在内核中增加钩子函数的框架,支持x86.项目地址在这里:https://github.com/milabs/khook 本文先简单介绍钩子函数 ...

  7. Spring 容器中 Bean 的生命周期

    Spring 容器中 Bean 的生命周期 1. init-method 和 destory-method 方法 Spring 初始化 bean 或销毁 bean 时,有时需要作一些处理工作,因此 s ...

  8. 怎样安装 cnpm 并切换到淘宝镜像?

    如果不使用 vpn , 在国内直接使用 npm 的官方镜像会很慢,这里推荐使用淘宝 NPM 镜像.淘宝 NPM 镜像是一个完整的 npmjs.org 镜像,可以用此代替官方版本(只读). 操作方法如下 ...

  9. jvm调试相关:jmap失效下找到alternatives神器

    1.使用 jmap <pid>出现的错误日志:很明显是版本问题 Error attaching to process: sun.jvm.hotspot.runtime.VMVersionM ...

  10. Datetime 在C#中的用法 获取当前时间的各种格式

    DateTime 获得当前系统时间: DateTime dt = DateTime.Now; Environment.TickCount可以得到“系统启动到现在”的毫秒值 DateTime now = ...