#include <iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
#define INF 0xfffffff
int inline parent(int i){return i>>1;}
int inline left(int i){return 2*i;}
int inline right(int i){return 2*i+1;}
template<typename T>
void inline exchange(T &a,T &b){T t=a;a=b;b=t;}
template<typename T>
void max_heap(T*A,int n,int i)///维护以节点i为根节点的最大堆(O(logn))
{
if(i>n)return;
int l=left(i),r=right(i),M=i;
if(l<=n&&A[l]>A[M])M=l;
if(r<=n&&A[r]>A[M])M=r;
if(M!=i)
{
exchange(A[i],A[M]);
max_heap(A,n,M);
}
}
template<typename T>
void build_max_heap(T*A,int n)///构建最大堆(O(n))
{
for(int i=n/2;i>=1;i--)max_heap(A,n,i);
}
template<typename T>
T get_max(T*A,int &n)///取出优先级最大的元素
{
if(n<1){cout<<"error"<<endl;exit(0);}
exchange(A[1],A[n]);
n-=1;
max_heap(A,n,1);///维护最大堆(O(n))
return A[n+1];
}
template<typename T>
void heap_increase(T*A,int n,int i,T e)///把A[i]的值变为e(O(logn))
{
if(A[i]>e)max_heap(A,n,i);///若改变后的值比以前小,只需向下维护,否则向上维护
else
{
while(i>1&&A[parent(i)]<e)
{
A[i]=A[parent(i)];
i=parent(i);
}
A[i]=e;
}
}
template<typename T>
void heap_insert(T*A,int &n,T e)///插入元素e(O(logn))
{
A[++n]=-INF;
heap_increase(A,n,n,e);
}
template<typename T>
void print(T*A,int n)///打印二叉堆
{
for(int i=1;i<=n;i++)cout<<A[i]<<' ';
cout<<endl;
}
int A[100005];
int main()
{
int n;
cout<<"请输入元素个数\n";
cin>>n;
for(int i=1;i<=n;i++)cin>>A[i];
build_max_heap(A,n);
int m,cho;
cout<<"请输入要执行的操作次数\n";
cin>>m;
cout<<"开始进行操作:\n输入1表示取出优先级最高的元素,2表示改变元素值,3插入元素\n\n";
while(m--)
{
cin>>cho;
switch (cho)
{
case 1:cout<<get_max(A,n)<<endl;print(A,n);break;
case 2:cout<<"请输入要改变的元素和要变成的值"<<endl;
int a,b;cin>>a>>b;heap_increase(A,n,a,b);print(A,n);break;
case 3:cout<<"请输入要插入的元素值"<<endl;int e;cin>>e;heap_insert(A,n,e);print(A,n);break;
}
}
return 0;
}
二叉堆维护优先队列
最新推荐文章于 2021-01-21 20:15:43 发布