堆的初识

来源:互联网 发布:防范网络电信诈骗 编辑:程序博客网 时间:2024/05/20 07:14
幻灯片 6.O{color:white;font-size:149%;}a:link{color:red !important;}a:active{color:yellow !important;}a:visited{color:#969696 !important;}幻灯片 6.O{color:white;font-size:149%;}a:link{color:red !important;}a:active{color:yellow !important;}a:visited{color:#969696 !important;}
堆的一个最大特点就是,它的每个节点的值都比它的子节点的值小,但是左右子节点值的大小不分。所以给定一个堆,我们能直接找出最小的值,但是我们无法直接找出所有值的从小到大序列。
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. */