/* * Author: BigBallon * Note: Max_priority_queue * Date: 2013.11.21 */
一篇好文章:http://blog.csdn.net/xihuanqiqi/article/details/7098909 #include<iostream> using namespace std; void My_swap(int& x, int& y) { int t = x; x = y; y = t; } void Max_Heapify(int* A, int i, int len) { int lt = i<<1; int rt = (i<<1)+1; int largest = 0; if(lt <= len && A[lt] > A[i]) largest = lt; else largest = i; if(rt <= len && A[rt] > A[largest]) largest = rt; if(largest != i) { My_swap(A[i],A[largest]); Max_Heapify(A,largest,len); } } void Build_Max_Heap(int* A, int len) { for(int i = len/2;i>=1;i--) Max_Heapify(A,i,len); } void Heap_Sort(int* A,int len) { Build_Max_Heap(A,len); int size = len; for( ; size>=2; ) { My_swap(A[1],A[size]); size--; Max_Heapify(A,1,size); } } int Heap_Max(int* A) { return A[1]; } int Heap_Extract_Max(int* A,int& len) { if(len < 1) { cout<<"Heap underflow"<<endl; } int max = A[1]; A[1] = A[len]; len--; Max_Heapify(A,1,len); return max; } void Heap_Increase_Key(int* A, int i, int key) { if(key < A[i]) { cout<<"new key is smaller than current key."<<endl; } A[i] = key; while(i > 1 && A[i>>1] < A[i]) { My_swap(A[i],A[i>>1]); i >>= 1; } } void Max_Heap_Insert(int* A,int key,int& len) { len+=1; A[len] = 0xf0000000; Heap_Increase_Key(A,len,key);//A,len,key,注意參數 } void PrintArray(int *A, int size) { for (int i=1; i<=size; ++i) cout<<A[i]<<ends; cout<<endl; } int main() { //數組下標從1開始. int len, heapsize; int arr[100] = {0, 15, 13, 9, 5, 12, 8, 7, 4, 0, 6, 2, 1}; // 區別len 和 heapsize // heapsize是堆的大小,而len是初始數組的總大小。 len = heapsize = 12; // 首先建堆 Build_Max_Heap(arr, len); cout << "建堆後: " << endl; PrintArray(arr, len); // 使用HeapMaximum cout << "當前最大的元素是: " << endl; cout << Heap_Max(arr) << endl << endl; // 使用HeapExtractMax cout << "使用HeapExtractMax後: " << endl; Heap_Extract_Max(arr,heapsize); PrintArray(arr, heapsize); // 再次使用HeapExtractMax cout << "再次使用HeapExtractMax後: " << endl; Heap_Extract_Max(arr,heapsize); PrintArray(arr, heapsize); // 使用HeapIncreaseKey cout << "使用HeapIncreaseKey後: " << endl; Heap_Increase_Key(arr, 2, 15); PrintArray(arr, heapsize); // 使用MaxHeapInsert cout << "使用MaxHeapInsert後: " << endl; Max_Heap_Insert(arr, 28, heapsize); PrintArray(arr, heapsize); } /* 什麼是最大優先級隊列 它不是一種普通的先進先出隊列(隊列是什麼?天啊!),它維護的元素有個優先級屬性, 無論如何進隊列,出列隊的都是優先級最大的元素! 應用在哪裏 計算機的分時調度啊 最小生成樹的Prim算法 ... 操做有: INSERT(S,x):將元素x插入到集合S MAXIMUM(S):返回S中具備最大關鍵字的元素 EXTRACT-MAX(S):去掉並返回S中的具備最大關鍵字的元素 INCREASE-KEY(S,x,k):將元素x的關鍵字的值增到k,這裏k值不能小於x的原關鍵字的值 */