堆的初識

幻燈片 6幻燈片 6
堆的一個最大特點就是,它的每個節點的值都比它的子節點的值小,但是左右子節點值的大小不分。所以給定一個堆,我們能直接找出最小的值,但是我們無法直接找出所有值的從小到大序列。
3個操作:插入,刪除,更新
1.插入
與父節點比較,進行dfs
2.刪除,把heap[0]與最後一個元素交換以後,更新
3.更新,把該節點和其字節點比較盡心DFS
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int heap[1000000],hsize=0;
  5. //root is 0
  6. string o;
  7. void dfs(int x)
  8. {
  9.     if(x>=hsize)return;
  10.     if(2*x+1<hsize)cout<<heap[2*x+1]<<' ';
  11.     if(2*x+2<hsize)cout<<heap[2*x+2]<<' ';
  12.     dfs(2*x+1);
  13.     dfs(2*x+2);
  14. }
  15. void insert(int n)
  16. {
  17.     int p,c=hsize;
  18.     heap[hsize++]=n;
  19.     p=(c-1)/2;
  20.     while(c)
  21.         {
  22.             if(heap[p]>heap[c])
  23.                 {
  24.                     swap(heap[p],heap[c]);
  25.                     c=p;
  26.                     p=(c-1)/2;
  27.                 }
  28.             else return;
  29.         }
  30. }
  31. void update(int p)
  32. {
  33.     if(2*p+1<hsize)//左節點
  34.         {
  35.             if(heap[p]>heap[2*p+1])
  36.                 {
  37.                     swap(heap[p],heap[2*p+1]);
  38.                     update(2*p+1);
  39.                 }
  40.         }
  41.     if(2*p+2<hsize)//右節點
  42.         {
  43.             if(heap[p]>heap[2*p+2])
  44.                 {
  45.                     swap(heap[p],heap[2*p+2]);
  46.                     update(2*p+2);
  47.                 }
  48.         }
  49.     if((p-1)/2>=0&&heap[(p-1)/2]>heap[p])//比父節點還小
  50.         {
  51.             swap(heap[(p-1)/2],heap[p]);
  52.             update((p-1)/2);
  53.         }
  54. }
  55. int del()
  56. {
  57.     int p=0,c,ret=heap[0];
  58.     swap(heap[0],heap[--hsize]);
  59.     update(0);
  60.     return ret;
  61. }
  62. int main()
  63. {
  64.     int n,i,t,tmp;
  65.     //freopen("D://in.txt","r",stdin);
  66.     while(cin>>o)
  67.         {
  68.             //cout<<o<<':'<<endl;
  69.             if(o=="add")cin>>n,insert(n);
  70.             if(o=="display")cout<<heap[0]<<' ',dfs(0),cout<<endl;
  71.             if(o=="delete")cout<<del()<<endl;
  72.             if(o=="update")cin>>n,update(n);
  73.             if(o=="heap")cin>>n>>tmp,heap[n]=tmp;
  74.         }
  75.     return 0;
  76. }
  77. /*
  78. add 2
    add 10
    add 4
    add -7
    add 5
    add -9
    display
    delete
    display
    heap 3 -100000
    update 3
    display
    heap 2 1000000
    update 2
    display
    heap 5 -10000000
    update 5
    display
  79. */

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章