1. 程式人生 > 實用技巧 >【堆合併】左式堆

【堆合併】左式堆

  1 #include <iostream>
  2 #include <cstdlib>
  3 #include <cstdio>
  4 #include <cstring>
  5 #include <string>
  6 #include <vector>
  7 #include <iterator>
  8 #include <stack>
  9 #include <algorithm>
 10 
 11 using namespace std;
 12 
 13 const
int N = 100010; 14 15 typedef struct LeftHeap *Lefh; 16 17 Lefh Merge_node(Lefh, Lefh); 18 static Lefh Merge(Lefh, Lefh); 19 Lefh inst(int, Lefh); 20 21 struct LeftHeap 22 { 23 int val; 24 Lefh l; 25 Lefh r; 26 int npl; 27 }; 28 29 Lefh q[N]; 30 31 Lefh Merge_node(Lefh h1, Lefh h2)
32 { 33 if (h1 == NULL) return h2; 34 if (h2 == NULL) return h1; 35 if (h1 -> val < h2 -> val) 36 return Merge(h1, h2); 37 else 38 return Merge(h2, h1); 39 } 40 41 static Lefh Merge(Lefh h1, Lefh h2) 42 { 43 if (h1 -> l == NULL) h1 -> l = h2; //
h1 為單節點堆 44 else 45 { 46 h1 -> r = Merge_node(h1 -> r, h2); 47 if (h1 -> l -> npl < h1 -> r -> npl) 48 { 49 Lefh tmp = h1 -> l; 50 h1 -> l = h1 -> r; 51 h1 -> r = tmp; 52 } 53 54 h1 -> npl = h1 -> r -> npl + 1; // 左式堆:根節點及其左右兒子中,必定是 右兒子的npl最小,則根的npl 多1 55 } 56 57 return h1; 58 } 59 60 Lefh inst(int x, Lefh h) 61 { 62 Lefh t = (struct LeftHeap*) malloc(sizeof (LeftHeap)); 63 64 t -> val = x; 65 t -> npl = 0; 66 t -> l = t -> r = NULL; 67 h = Merge_node(t, h); // 單節點當成一棵子樹插入 68 69 return h; 70 } 71 72 void print(Lefh h) 73 { 74 // bfs遍歷樹 75 76 // 標記法:方便判斷節點的順序,不存在的節點標記為-1 77 Lefh ept = (struct LeftHeap*) malloc(sizeof (LeftHeap)); 78 ept -> val = -1; 79 ept -> l = ept -> r = NULL; 80 ept -> npl = -1; 81 82 int hh = 1, tt = 0; 83 q[++ tt] = h; 84 85 while (hh <= tt) 86 { 87 Lefh t = q[hh ++]; 88 printf("(%d,%d) ", t -> val, t -> npl); 89 90 if (t -> val == -1) continue; 91 if (t -> l) q[++ tt] = t -> l; else q[++ tt] = ept; 92 if (t -> r) q[++ tt] = t -> r; else q[++ tt] = ept; 93 }puts(""); 94 } 95 96 int main() 97 { 98 int n, m, x; 99 cin >> n >> m; 100 Lefh h1 = NULL, h2 = NULL; 101 for (int i = 0; i < n; i ++) 102 { 103 scanf("%d", &x); 104 h1 = inst(x, h1); 105 } 106 for (int i = 0; i < m; i ++) 107 { 108 scanf("%d", &x); 109 h2 = inst(x, h2); 110 } 111 print(h1); 112 print(h2); 113 114 Lefh H = Merge_node(h1, h2); 115 print(H); 116 117 118 return 0; 119 }