堆是徹底二叉樹,樹中每一個結點的值不小於(或不大於)其左右子結點的值,稱之爲大頂堆(或小頂堆)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; }