复习一下有关于堆的函数, 好久不打都快忘了。
//最小堆
#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;//返回堆顶元素
}