博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
堆的各种操作
阅读量:4035 次
发布时间:2019-05-24

本文共 2281 字,大约阅读时间需要 7 分钟。

一、描述:

A priority queue is a data structure formaintaining a set S of elements, each with an associated value called a key. A max-priorityqueue supports the following operations.

. INSERT(S, x) inserts the element x into the set S. This operation could be written as S S∪ {

x}.

. MAXIMUM(S) returns the element of S with the largest key.

. EXTRACT-MAX(S) removes and returns the element of S with the largest key.

. which is assumed to be atleast as large as x's current key value.

二、 数据输入

A=<15,13,9,5,12,8,7,4,0,6,2,1>

三、 结果输出

执行INSERT(A, 10),EXTRACT-MAX(A),将结果输出到文件output.txt。

 

四、代码:

#include
#include
#define N 15int a[N],size,for_size;void up_down_maxHeap(int i){ int l=2*i; int r=2*i+1; int maxx=i; if(l<=size && a[l]>a[i]) maxx=l; else if(r<=size && a[r]>a[maxx]) maxx=r; if(maxx!=i) { int tmp=a[maxx]; a[maxx]=a[i]; a[i]=tmp; up_down_maxHeap(maxx); }}void buildMaxHeap(){ for(int i=1;i<=for_size;i++) { up_down_maxHeap(i); } printf("建好的大顶堆序列:"); for(int i=1;i<=size;i++) printf("%d ",a[i]); printf("\n");}void down_up_maxHeap(int i){ int father=i/2; if(a[father]
0) { int tmp=a[father]; a[father]=a[i]; a[i]=tmp; down_up_maxHeap(father); }}void insert(int x){ size++; a[size]=x; down_up_maxHeap(size); printf("插入元素%d后的堆序列:",x); for(int i=1;i<=size;i++) printf("%d ",a[i]); printf("\n");}void maximum(){ printf("堆中最大的元素是:%d\n",a[1]);}void extract_max(){ int tmp=a[1]; a[1]=a[size]; a[size]=tmp; up_down_maxHeap(1); size--; printf("删除最大元素%d后的堆序列:",tmp); for(int i=1;i<=size;i++) printf("%d ",a[i]); printf("\n");}void increase_key(int x,int k){ int tmp=a[x]; a[x]=k; down_up_maxHeap(x); printf("将%d位置的元素%d增加到%d后的堆序列:",x,tmp,k); for(int i=1;i<=size;i++) printf("%d ",a[i]); printf("\n");}int main(){ int x,k; freopen("heapInput.txt","r",stdin); freopen("heapOutput.txt","w",stdout); scanf("%d",&size); for(int i=1;i<=size;i++) scanf("%d",&a[i]); for_size=(size%2==0)?size/2:size/2+1; buildMaxHeap(); scanf("%d",&x); insert(x); maximum(); extract_max(); scanf("%d%d",&x,&k); increase_key(x,k); return 0;}

 

转载地址:http://nhddi.baihongyu.com/

你可能感兴趣的文章
retext出现Could not parse file contents, check if you have the necessary module installed解决方案
查看>>
pyQt不同窗体间的值传递(一)——对话框关闭时返回值给主窗口
查看>>
linux mint下使用外部SMTP(如网易yeah.net)发邮件
查看>>
北京联通华为光猫HG8346R破解改桥接
查看>>
python使用win32*模块模拟人工操作——城通网盘下载器(一)
查看>>
python append 与浅拷贝
查看>>
Matlab与CUDA C的混合编程配置出现的问题及解决方案
查看>>
python自动化工具之pywinauto(零)
查看>>
python一句话之利用文件对话框获取文件路径
查看>>
PaperDownloader——文献命名6起来
查看>>
PaperDownloader 1.5.1——更加人性化的文献下载命名解决方案
查看>>
如何将PaperDownloader下载的文献存放到任意位置
查看>>
C/C++中关于动态生成一维数组和二维数组的学习
查看>>
JVM最简生存指南
查看>>
漂亮的代码,糟糕的行为——解决Java运行时的内存问题
查看>>
Java的对象驻留
查看>>
logback高级特性使用(二) 自定义Pattern模板
查看>>
JVM并发机制探讨—内存模型、内存可见性和指令重排序
查看>>
可扩展、高可用服务网络设计方案
查看>>
如何构建高扩展性网站
查看>>