堆的各种操作

一、描述:

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.

. INCREASE-KEY(S, x, k) increases the value ofelement x's key to the new value k,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<stdio.h>
#include<queue>
#define N 15
int 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]<a[i] && 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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值