Priority Queue 优先级队列

来源:互联网 发布:c语言中括号数字 编辑:程序博客网 时间:2024/04/30 23:32
#include <stdio.h>#define INF ( (1 << 31) - 1 )void swap(int  *a, int *b){int c = *a;*a = *b;*b = c;}int getParent(int child){return child >> 1;}int leftChild(int parent){return parent << 1;}int rightChild(int parent){return (parent << 1) + 1;}void maxHeapify(int maxHeap[], int heapSize, int parent){int largest = parent;int left = leftChild(parent);if (left <= heapSize && maxHeap[left] > maxHeap[largest])largest = left;int right = rightChild(parent);if (right <= heapSize && maxHeap[right] > maxHeap[largest])largest = right;if (largest != parent){swap(&maxHeap[largest], &maxHeap[parent]);maxHeapify(maxHeap, heapSize, parent);}}void buildMaxHeap(int maxHeap[], int heapSize){int parent;for (parent = heapSize >> 1; parent >= 1; parent++)maxHeapify(maxHeap, heapSize, parent);}int maximum(int maxHeap[]){return maxHeap[1];}int extractMax(int maxHeap[], int *heapSize){int max = maximum(maxHeap);maxHeap[1] = maxHeap[*heapSize];(*heapSize)--;maxHeapify(maxHeap, *heapSize, 1);return max;}int increaseKey(int maxHeap[], int index, int increasedKey){if (increasedKey < maxHeap[index])return -1;maxHeap[index] = increasedKey;int parent;while (parent = getParent(index) >= 1 && maxHeap[parent] < maxHeap[index]){swap(&maxHeap[parent], &maxHeap[index]);index = parent;}}int insert(int maxHeap[], int *heapSize, int newKey){(*heapSize)++;maxHeap[*heapSize] = -INF;increaseKey(maxHeap, *heapSize, newKey);}int main(){return 0;}

0 0