#include <iostream> #include <algorithm> #include <stdio.h> using namespace std; class Heap{ private: int r[100],length; public: Heap(int n){ length = n; for(int i = 0 ; i < n ; i++) cin>>r[i]; } void SiftHeap (int now , int n){ int i,j; i = now ; j = i * 2 + 1; while(j < n){ if(j < n - 1 && r[j] < r[j+1]) j++; if(r[i] > r[j])break; else{ swap(r[i],r[j]); i = j ; j = j * 2 + 1; } } } void BuildHeap(){ for(int i = (length - 1)/2 ; i >= 0 ; i--) SiftHeap(i,length); } void Addone(int newval){ r[length++]=newval; int i,j;i=length-1,j=(i+1)/2 - 1; while(i>=0){ if(r[j]>r[i])break; else{ swap(r[i],r[j]); i=j;j=(j+1)/2 -1; } } } void Deleteone(int pos){ swap(r[pos],r[--length]); int i,j; i = pos; j = (i+1)/2 -1; while(r[i]>r[j]){ swap(r[i],r[j]); i = j; j = (j+1)/2 -1; } SiftHeap(pos,length); } void show(){ for(int i = 0 ; i < length; i++)cout<<r[i]<<" "; puts(""); } }; int main(){ int n,tmp; cin>>n; Heap h(n); h.BuildHeap(); h.show(); cout<<"insert a number"<<endl; cin>>tmp; h.Addone(tmp); h.show(); cout<<"delete a number at position"<<endl; cin>>tmp; h.Deleteone(tmp); h.show(); return 0; }
|