全部评论 2

  • 注:大根堆的父节点最大(根结点最大),小根堆的父节点最小(根结点最小)。根据此特性可以更改函数中的大于或小于符号实现大根堆和小根堆的操作

    5天前 来自 四川

    0
  • 补一下get的完整代码

    /*
    堆操作:get
    使用get删除元素;
    step1 取出堆的根节点的值
    step2 把堆的最后一个结点len放在根的位置上,把根覆盖掉。把堆的长度减一。
    step3 把根节点置为当前父节点parent
    step4 如果parent无儿子结束  否则把parent的两个或一个儿子中的最小值设置为当前子节点son
    step5 比较parent和son的值 若parent小于son结束,否则交换二者的值,让pa指向son,继续执行step4 
    */
    
    #include<bits/stdc++.h>
    using namespace std; 
    int get(){
    	int pa,son,res;
    	res=heap[1];//存储堆顶元素 
    	heap[1]=heap[heap_size--];//用最后一个元素覆盖堆顶元素 
    	pa = 1;
    	//向下做调整(重新构造) 
    	while(pa*2<=heap_size){
    		son=pa*2;//左儿子 
    		if(son<heap_size&&heap[son+1]<heap[son]) son++;//比较左儿子和右儿子(找到存在儿子中最大的一个) 
    		if(heap[pa]<=heap[son]) break;//比较父节点和子节点大小(是否需要交换) 
    		swap(heap[pa],heap[son]);
    		pa=son;
    	}
    	return res;
    }
    
    int main(){
    	int n;
    	cin>>n;
    	for(int i=1;i<=n;++i){
    		int x;
    		cin>>x;
    		put(x);
    	} 
    	while(heap_size) cout<<get()<<" ";
    	
    	return 0;
    }
    

    5天前 来自 四川

    0

热门讨论