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 - */