67 lines
1.5 KiB
C++
67 lines
1.5 KiB
C++
|
/**
|
|||
|
* File: heap.cpp
|
|||
|
* Created Time: 2023-01-19
|
|||
|
* Author: LoneRanger(836253168@qq.com)
|
|||
|
*/
|
|||
|
|
|||
|
#include "../utils/common.hpp"
|
|||
|
|
|||
|
void testPush(priority_queue<int> &heap, int val) {
|
|||
|
heap.push(val); // Ԫ<><D4AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
cout << "\nԪ<EFBFBD><EFBFBD> " << val << " <20><><EFBFBD>Ѻ<EFBFBD>" << endl;
|
|||
|
printHeap(heap);
|
|||
|
}
|
|||
|
|
|||
|
void testPop(priority_queue<int> &heap) {
|
|||
|
int val = heap.top();
|
|||
|
heap.pop();
|
|||
|
cout << "\n<EFBFBD>Ѷ<EFBFBD>Ԫ<EFBFBD><EFBFBD> " << val << " <20><><EFBFBD>Ѻ<EFBFBD>" << endl;
|
|||
|
printHeap(heap);
|
|||
|
}
|
|||
|
|
|||
|
/* Driver Code */
|
|||
|
int main() {
|
|||
|
/* <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD> */
|
|||
|
// <20><>ʼ<EFBFBD><CABC>С<EFBFBD><D0A1><EFBFBD><EFBFBD>
|
|||
|
// priority_queue<int, vector<int>, greater<int>> minHeap;
|
|||
|
// <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD>
|
|||
|
priority_queue<int, vector<int>, less<int>> maxHeap;
|
|||
|
|
|||
|
cout << "\n<EFBFBD><EFBFBD><EFBFBD>²<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><EFBFBD>" << endl;
|
|||
|
|
|||
|
/* Ԫ<><D4AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
|
|||
|
testPush(maxHeap, 1);
|
|||
|
testPush(maxHeap, 3);
|
|||
|
testPush(maxHeap, 2);
|
|||
|
testPush(maxHeap, 5);
|
|||
|
testPush(maxHeap, 4);
|
|||
|
|
|||
|
/* <20><>ȡ<EFBFBD>Ѷ<EFBFBD>Ԫ<EFBFBD><D4AA> */
|
|||
|
int peek = maxHeap.top();
|
|||
|
cout << "\n<EFBFBD>Ѷ<EFBFBD>Ԫ<EFBFBD><EFBFBD>Ϊ " << peek << endl;
|
|||
|
|
|||
|
/* <20>Ѷ<EFBFBD>Ԫ<EFBFBD>س<EFBFBD><D8B3><EFBFBD> */
|
|||
|
testPop(maxHeap);
|
|||
|
testPop(maxHeap);
|
|||
|
testPop(maxHeap);
|
|||
|
testPop(maxHeap);
|
|||
|
testPop(maxHeap);
|
|||
|
|
|||
|
/* <20><>ȡ<EFBFBD>Ѵ<EFBFBD>С */
|
|||
|
int size = maxHeap.size();
|
|||
|
cout << "\n<EFBFBD><EFBFBD>Ԫ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ " << size << endl;
|
|||
|
|
|||
|
/* <20>ж϶<D0B6><CFB6>Ƿ<EFBFBD>Ϊ<EFBFBD><CEAA> */
|
|||
|
bool isEmpty = maxHeap.empty();
|
|||
|
cout << "\n<EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD>Ϊ<EFBFBD><EFBFBD> " << isEmpty << endl;
|
|||
|
|
|||
|
/* <20><><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD><D0B1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
|
|||
|
// ʱ<>临<EFBFBD>Ӷ<EFBFBD>Ϊ O(n) <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> O(nlogn)
|
|||
|
vector<int> input{1, 3, 2, 5, 4};
|
|||
|
priority_queue<int, vector<int>, greater<int>> minHeap(input.begin(), input.end());
|
|||
|
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>С<EFBFBD><EFBFBD><EFBFBD>Ѻ<EFBFBD>" << endl;
|
|||
|
printHeap(minHeap);
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|