复习一下有关于堆的函数, 好久不打都快忘了。

//最小堆
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f//无穷大
#define N 20200
using namespace std;
typedef struct heap
{
    int weight[N];//存权值
    int size;//堆大小
}Heap;
Heap *Creat(int n)//建立一个大小为n的最小堆
{
    Heap *head;
    head = (Heap *)malloc(sizeof(Heap));
    head -> size = 0;
    head -> weight[0] = -INF;//如果建最大堆吧-INF改为INF就行了,初始化weight[0]起到一个哨兵的作用,这样插入的时候就不用一直判断堆是否到顶了
    int i;
    for(i = 1; i <= n; i++)
    {
        int x;
        scanf("%d", &x);
        Insert(head, x);
    }
    return head;
}
void Insert(Heap *head, int n)//插入操作
{
    int i = ++head -> size;//假设最初把新数据n插入堆的最后面,然后一次往上给n找到一个合适的位置
    for( ; head -> weight[i / 2] > n; i /= 2)//直到找到一个位置,这个位置的权值不小于n
    {
        head -> weight[i] = head -> weight[i / 2];
    }
    head -> weight[i] = n;//将n值赋到合适的位置上
}
int Del(Heap *head)//删除操作
{
    int last = head -> weight[head -> size--];//存最后一个位置的权值,并给它找一个合适的位置
    int first = head -> weight[1];//存堆顶元素,并将其返回
    int parent, child;
    for(parent = 1; parent * 2 <= head -> size; parent = child)//类似一个插入操作, 只不过是从下往上查找变为从上往下查找
    {
        child = parent * 2;
        if(head -> weight[child] > head -> weight[child + 1])
        child ++;
        if(head -> weight[child] > last)//如果last小于它权值最小的儿子,那么将last插入这个位置
        break;
        else
        head -> weight[parent] = head -> weight[child];
    }
    head -> weight[parent] = last;
    return first;//返回堆顶元素
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值