• pta 编程题12 堆中的路径


    其它pta数据结构编程题请参见:pta

    这道题考察的是最小堆。

    堆是一个完全二叉树,因此可用数组表示,一个下标为 i 的结点的父节点下标为 i / 2,子结点下标为 2i 和 2i + 1。

    插入元素:先把元素放到数组的最后面,然后不断循环和父节点比较,如果小于父节点则交换。

    数组的下标为0存放一个很小的值作为哨兵,当进行插入操作时,如果插入的元素需要放到下标为1的位置时,和下标为0的值比较时会大于这个很小的值,因而会停止。

     1 #include <iostream>
     2 #include <vector>
     3 using namespace std;
     4 
     5 int heap[1001];
     6 int size = 0;
     7 void insert(int x);
     8 void printTrace(int i);
     9 
    10 int main()
    11 {
    12     int n, m, i, t;
    13     cin >> n >> m;
    14     heap[0] = -10001;//哨兵
    15     for (i = 0; i < n; i++)
    16     {
    17         cin >> t;
    18         insert(t);
    19     }
    20     for (i = 0; i < m; i++)
    21     {
    22         cin >> t;
    23         printTrace(t);
    24     }
    25     return 0;
    26 }
    27 
    28 void insert(int x)
    29 {
    30     int i;
    31     for (i = ++size; heap[i / 2] > x; i /= 2)
    32         heap[i] = heap[i / 2];
    33     heap[i] = x;
    34 }
    35 
    36 void printTrace(int i)
    37 {
    38     vector<int> v;
    39     while (i)
    40     {
    41         v.push_back(heap[i]);
    42         i /= 2;
    43     }
    44     for (int j = 0; j < v.size(); j++)
    45     {
    46         if (j) cout << " ";
    47         cout << v[j];
    48     }
    49     cout << endl;
    50 }
  • 相关阅读:
    The Sixth Assignment
    The fifth assigiment
    网络编程
    面向对象
    python数据类型之集合
    python数据类型之列表
    python数据类型之字符串
    python数据类型之字典
    python数据类型之元组
    常用模块
  • 原文地址:https://www.cnblogs.com/lxc1910/p/8811168.html
Copyright © 2020-2023  润新知