堆的初识
来源:互联网 发布:防范网络电信诈骗 编辑:程序博客网 时间:2024/05/20 07:14
堆的一个最大特点就是,它的每个节点的值都比它的子节点的值小,但是左右子节点值的大小不分。所以给定一个堆,我们能直接找出最小的值,但是我们无法直接找出所有值的从小到大序列。
3个操作:插入,删除,更新
1.插入
与父节点比较,进行dfs
2.删除,把heap[0]与最后一个元素交换以后,更新
3.更新,把该节点和其字节点比较尽心DFS
3个操作:插入,删除,更新
1.插入
与父节点比较,进行dfs
2.删除,把heap[0]与最后一个元素交换以后,更新
3.更新,把该节点和其字节点比较尽心DFS
- #include <iostream>
- #include <string>
- using namespace std;
- int heap[1000000],hsize=0;
- //root is 0
- string o;
- void dfs(int x)
- {
- if(x>=hsize)return;
- if(2*x+1<hsize)cout<<heap[2*x+1]<<' ';
- if(2*x+2<hsize)cout<<heap[2*x+2]<<' ';
- dfs(2*x+1);
- dfs(2*x+2);
- }
- void insert(int n)
- {
- int p,c=hsize;
- heap[hsize++]=n;
- p=(c-1)/2;
- while(c)
- {
- if(heap[p]>heap[c])
- {
- swap(heap[p],heap[c]);
- c=p;
- p=(c-1)/2;
- }
- else return;
- }
- }
- void update(int p)
- {
- if(2*p+1<hsize)//左节点
- {
- if(heap[p]>heap[2*p+1])
- {
- swap(heap[p],heap[2*p+1]);
- update(2*p+1);
- }
- }
- if(2*p+2<hsize)//右节点
- {
- if(heap[p]>heap[2*p+2])
- {
- swap(heap[p],heap[2*p+2]);
- update(2*p+2);
- }
- }
- if((p-1)/2>=0&&heap[(p-1)/2]>heap[p])//比父节点还小
- {
- swap(heap[(p-1)/2],heap[p]);
- update((p-1)/2);
- }
- }
- int del()
- {
- int p=0,c,ret=heap[0];
- swap(heap[0],heap[--hsize]);
- update(0);
- return ret;
- }
- int main()
- {
- int n,i,t,tmp;
- //freopen("D://in.txt","r",stdin);
- while(cin>>o)
- {
- //cout<<o<<':'<<endl;
- if(o=="add")cin>>n,insert(n);
- if(o=="display")cout<<heap[0]<<' ',dfs(0),cout<<endl;
- if(o=="delete")cout<<del()<<endl;
- if(o=="update")cin>>n,update(n);
- if(o=="heap")cin>>n>>tmp,heap[n]=tmp;
- }
- return 0;
- }
- /*
- 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 - */
- 堆的初识
- 初识---JVM之堆,栈,方法区
- JVM进阶(二)——初识JAVA堆
- JVM进阶(二)——初识JAVA堆
- 堆的建立&堆排序
- 初识Python的感想
- Ajax的初识
- SOA的初识
- 初识STL的强大
- 迟来的初识
- Normap的初识
- 初识android的project
- Binder的初识
- 初识linux的shell
- Proxy代理的初识
- html 的初识
- wget的初识
- NoSQL的初识
- VS2005 SP1安装问题
- ex66104.cpp
- ex65104.cpp
- ex64104.cpp
- ex63104.cpp
- 堆的初识
- How_To_Build_WebKit_With_VS2005
- 黑屏-是保护我们的饭碗
- 爆笑口误 娱乐大家
- 从注册表切断一切黑客入侵的路径
- 开博FDAY
- RBAC 图
- 模拟键盘按键
- 模拟鼠标移动和左键单击