Skip to content

Instantly share code, notes, and snippets.

@limabeans
Created November 5, 2018 05:02
Show Gist options
  • Save limabeans/0697dd1746a25e9d8d3d447e04c90043 to your computer and use it in GitHub Desktop.
Save limabeans/0697dd1746a25e9d8d3d447e04c90043 to your computer and use it in GitHub Desktop.
generic priority queue with functor comparator template argument
#include <bits/stdc++.h>
using namespace std;
namespace my {
template<class T, class F = less<T>>
struct priority_queue {
vector<T> v = {0};
T i=0; // index if last elem
F cmp = F();
priority_queue() {}
int size() {
return i;
}
bool empty() {
return size() == 0;
}
void bubbleup(int ind) {
if (ind<=1) return;
if (cmp(v[ind],v[ind>>1])) {
swap(v[ind],v[ind>>1]);
bubbleup(ind>>1);
}
}
void push(int x) {
++i;
if (i>=(int)v.size()) {
v.push_back(x);
} else {
v[i]=x;
}
bubbleup(i);
}
void bubbledown(int ind) {
while (ind<<1 <= i) {
if ((ind<<1|1) <= i) {
if (cmp(v[ind<<1|1], v[ind<<1])) {
if (cmp(v[ind<<1|1], v[ind])) {
swap(v[ind<<1|1], v[ind]);
ind = ind<<1|1;
} else {
break;
}
} else {
if (cmp(v[ind<<1], v[ind])) {
swap(v[ind<<1], v[ind]);
ind<<=1;
} else {
break;
}
}
} else {
if (cmp(v[ind<<1], v[ind])) {
swap(v[ind<<1], v[ind]);
ind<<=1;
} else {
break;
}
}
}
}
T pop() {
if (size()==0) return 0;
swap(v[1],v[i]);
T ret = v[i--];
bubbledown(1);
return ret;
}
T top() {
if (empty()) return -1; // bad way to handle error
return v[1];
}
};
}
int main() {
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment