优先队列是由堆实现的。
1 #include <iostream> 2 #include <fstream> 3 #include <string> 4 5 template<typename T> 6 void swap(T &x, T &y) { 7 T temp = x; 8 x = y; 9 y = temp; 10 } 11 12 const int inf = (1LL << 31) - 1; 13 const int maxn = 10005; 14 int arr[maxn]; 15 int size; 16 17 18 void max_heapinf(int *arr, int i, int length) // 维护堆的性质 19 { 20 int l = 2 * i, r = l + 1; 21 int largest = i; 22 if (l <= length && arr[l] > arr[largest]) 23 largest = l; 24 if (r <= length && arr[r] > arr[largest]) 25 largest = r; 26 if (largest != i) 27 { 28 swap(arr[largest], arr[i]); 29 max_heapinf(arr, largest, length); 30 } 31 } 32 33 // 优先队列部分 34 int heap_maximum(int *arr) // 返回队列中具有最大关键字的元素 35 { 36 return arr[1]; 37 } 38 39 int heap_extract_max(int *arr) // 去掉并返回队列中最大关键字的元素 40 { 41 if (size < 1) 42 { 43 std::cout << "heap underflow" << std::endl; 44 return 0; 45 } 46 int ret = arr[1]; 47 arr[1] = arr[size--]; 48 max_heapinf(arr, 1, size); 49 return ret; 50 } 51 52 void heap_increase_key(int *arr, int i, int key) //要求 key >= arr[i] 53 { 54 if (key < arr[i]) 55 { 56 std::cout << "new key is smaller than current key" << std::endl; 57 return; 58 } 59 arr[i] = key; 60 while (i > 1 && arr[i] > arr[i/2]) 61 { 62 swap(arr[i], arr[i / 2]); 63 i /= 2; 64 } 65 } 66 67 void heap_insert(int *arr, int key) 68 { 69 arr[++size] = -inf; 70 heap_increase_key(arr, size, key); 71 } 72 73 void print_arr(const int *arr,int l, int r) 74 { 75 for (int i = l; i <= r; ++i) 76 std::cout << arr[i] << " "; 77 std::cout << std::endl; 78 } 79 int main() 80 { 81 for (int i = 1; i <= 10; ++i) 82 heap_insert(arr, i); 83 for (int i = 1; i <= 10; ++i) 84 heap_insert(arr, -i); 85 std::cout << heap_extract_max(arr) << std::endl; 86 heap_increase_key(arr, 3, 100); 87 std::cout << heap_extract_max(arr) << std::endl; 88 return 0; 89 }