c_cpp 堆
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 堆相关的知识,希望对你有一定的参考价值。
#include <iostream>
#include <vector>
using namespace std;
// Max Heap impl
struct PriorityQueue {
private:
vector<int> A;
int parent(int i) {
return (i - 1) /2;
}
size_t left(int i) {
return (2*i + 1);
}
size_t right(int i) {
return (2*i + 2);
}
void print() {
for (auto it = A.begin(); it != A.end(); it++) {
cout << *it << ", ";
}
cout << endl;
}
//node at index i and it's two children
//violates heap property
void heapify_down(int i) {
//get left and right children
int largest = i;
size_t l = left(i);
size_t r = right(i);
//compare A[i] with left and right child
//to find max value
if (l < size() && A[l] > A[i]) {
largest = l;
}
if (r < size() && A[r] > largest) {
largest = r;
}
//swap with child having greatest value
// and hepify down the child
if (largest != i) {
swap(A[i], A[largest]);
}
}
//recursive heapify_up algo
void heapify_up(int i) {
//check if node at i and it's parent violates heap property
int p = parent(i);
if (i && (A[p] < A[i])) {
cout << "parent:" << p << " for: " << i << " violates \n";
swap(A[i], A[p]);
heapify_up(p);
}
}
public:
size_t size() const {
return A.size();
}
bool empty() {
return A.size() == 0;
}
void push(int key) {
A.push_back(key);
heapify_up(size() - 1);
print();
}
void pop() {
if (empty())
return;
A[0] = A.back();
A.pop_back();
heapify_down(0);
}
int max() {
if (empty())
return -1;
return A.at(0);
}
};
// To execute C++, please define "int main()"
int main() {
PriorityQueue pq;
pq.push(1);
pq.push(10);
pq.push(-11);
pq.push(4);
pq.push(6);
while (!pq.empty()) {
cout << pq.max() << ", ";
pq.pop();
}
cout << endl;
return 0;
}
以上是关于c_cpp 堆的主要内容,如果未能解决你的问题,请参考以下文章