typedef struct heapstruct *maxheap; struct heapstruct{ int *elements;/* 存储堆元素的数组 */ int size;/* 堆的当前元素个数 */ int capacity;/* 堆的最大容量 */ }; maxheap create(int maxsize){ /* 创建容量为maxsize的空的最大堆 */ maxheap h = malloc(sizeof(struct heapstruct)); h->elements = malloc((maxsize+1) * sizeof(int)); h->size = 0; h->capacity = maxsize; h->elements[0] = maxdata; /* 定义“哨兵”为大于堆中所有可能元素的值,便于以后更快操作 */ return h; } void insert(maxheap h,int item){ int i; if(isfull(h)){ cout<<"堆满了"<<endl; return; } i = ++h->size; for(; h->elements[i/2] < item; i/=2){ h->elements[i] = h->elements[i/2]; } h->elements[i] = item; } int deletemax(maxheap h){ int parent,child; int maxitem,temp; if(isempty(h)){ cout<<"最大堆空"<<endl; return; } maxitem = h->elements[1]; temp = h->elements[h->size--]; for(parent = 1; parent*2 <= h->size; parent = child){ child = parent * 2; if((child != h->size)&& (h->elements[child] < h->elements[child+1])) child++; if(temp >= h->elements[child])break; else h->elements[parent] = h->elements[child]; } h->elements[parent] = temp; return maxitem; }
最大堆(升序大顶堆, 降序小顶堆)
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e7 + 5; int n, m, k, sum, a[maxn]; string s; queue<int> q; void up(int p){ while(p > 1 && a[p] > a[p / 2]){ swap(a[p], a[p / 2]); p = p / 2; } } void down(int p){ while(p * 2 <= n){ int u = p * 2; if(u + 1 <= n && a[u + 1] > a[u]){ u++; } if(a[u] > a[p]){ swap(a[u], a[p]); p = u; } else break; } } void makeheap(){ for(int i = n / 2; i >= 1; i--){ down(i); } } void push(int x){ a[++n] = x; up(n); } int top(){ return a[1]; } void pop(){ swap(a[1], a[n--]); down(1); } int main(){ //ios_base::sync_with_stdio(0); //cin.tie(); cout.tie(); n = 10; for(int i = 1; i <= n; i++) a[i] = i; makeheap(); for(int i = 1; i <= 10; i++){ push(i + 10); } while(n > 0){ cout<<top()<<endl; pop(); } return 0; }
c++
0 条评论