堆是彻底二叉树,树中每一个结点的值不小于(或不大于)其左右子结点的值,称之为大顶堆(或小顶堆)ios
const int maxn = 100; int heap[maxn], n = 10; // heap 为堆,n 为元素个数
// 对 heap 数组在 [low,high] 范围进行向下调整 // 其中 low 为欲调整结点的数组下标, high 通常为堆的最后一个元素的数组下标 void downAdjust(int low, int high){ int i = low, j = i * 2; // i 为欲调整结点,j 为其左子结点 while (j <= high){ // 存在子结点时进行循环 if (j + 1 <= high && heap[j+1] > heap[j) // 若右子结点存在且值大于左子结点 j = j + 1; if (heap[j] > heap[i]){ // 若子结点中最大的值比欲调整结点 i 的值大 swap(heap[j], heap[i]); i = j; j = i * 2; // 保持 i 为欲调整结点,j 为其左子结点 } else break; } }
void createHeap(){ for (int i = n / 2; i >= 1; i--) downAdjust(i,n); }
用最后一个元素覆盖堆顶元素,再对根结点进行调整算法
void deleteTop(){ heap[1] == heap[n--]; // 覆盖后元素个数 -- downAdjust(1,n); }
// 对 heap 数组在 [low,high] 范围进行向上调整 // 其中 low 通常设置为 1, high 为欲调整结点的数组下标 void upAdjust(int low, int high){ int i = high, j = i / 2; // i 为欲调整结点,j 为其父结点 while (j >= low){ // 父结点在 [low,high] 范围内 if (heap[j] < heap[i]){ // 父结点值小于欲调整结点值 swap(heap[j],heap[i]); i = j; j = i / 2; // 保持i 为欲调整结点,j 为其父结点 } else break; } }
void insert(int x){ heap[++n] = x; upAdjust(1,n); }
void heapSort(){ createHeap(); for (int i = n; i > 1; i++){ swap(heap[i], heap[1]); downAdjust(1, i-1); } }
bool isMax = true, isMin = true; for (int i = 2; i <= n; i++) { if (tree[i/2] > tree[i]) isMin = false; if (tree[i/2] < tree[i]) isMax = false; } printf("%s\n", isMax ? "Max Heap" : isMin ? "Min Heap" : "Not Heap");
post.clear()
#include<iostream> #include<vector> using namespace std; int n; vector<int> tree, post; void postorder(int index){ if (index > n) return; postorder(index * 2); postorder(index * 2 + 1); post.push_back(tree[index]); } int main() { int m, data; scanf("%d%d", &m, &n); tree.resize(n+1); for (int i = 0; i < m; i++){ for (int j = 1; j < n + 1; j++) scanf("%d", &tree[j]); bool isMax = true, isMin = true; for (int j = 2; j < n + 1; j++){ if (tree[j/2] > tree[j]) isMin = false; if (tree[j/2] < tree[j]) isMax = false; } printf("%s\n", isMax ? "Max Heap" : isMin ? "Min Heap" : "Not Heap"); post.clear(); postorder(1); for (int j = 0; j < post.size(); j++) printf("%d%c", post[j], j + 1 == post.size() ? '\n' : ' '); } return 0; }
2 * index > n
),输出路径#include<iostream> #include<vector> using namespace std; int n, tree[1001];; bool isMax = true, isMin = true; vector<int> path; void DFS(int index){ if (index > 1){ if (tree[index] > tree[index/2]) isMax = false; if (tree[index] < tree[index/2]) isMin = false; } if (2 * index > n){ for (int i = 0; i < path.size(); i++) printf("%d%c", tree[path[i]], i == path.size()-1 ? '\n' : ' '); return; } if (2 * index + 1 <= n){ path.push_back(2 * index + 1); DFS(2 * index + 1); path.pop_back(); } path.push_back(2 * index); DFS(2 * index); path.pop_back(); } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &tree[i+1]); path.push_back(1); DFS(1); printf("%s\n", isMax ? "Max Heap" : isMin ? "Min Heap" : "Not Heap"); return 0; }