Skip to content

Instantly share code, notes, and snippets.

@hjroh0315
Last active April 23, 2022 02:30
Show Gist options
  • Save hjroh0315/5ddfbfb6e920357d9eccab15139fc2a8 to your computer and use it in GitHub Desktop.
Save hjroh0315/5ddfbfb6e920357d9eccab15139fc2a8 to your computer and use it in GitHub Desktop.
힙을 구현하려고 했고, 구현했는데, 고장이네요. 엉엉ㅇㅇㅇ어어어어어어어ㅓㅇㅇㅇㅇㅇ
#include <iostream>
#include <vector>
using namespace std;
template<class T, class Comp=greater<T> >
struct heap{
vector<T> data;
Comp cmp;
heap(){data.push_back({});}
void push(T t){
data.push_back(t);
int idx=data.size()-1;
while(idx>1){
int up=idx>>1;
if(cmp(data[idx],data[up]))
swap(data[idx],data[up]);
else break;
idx=up;
}
}
T top(){if(data.size()==1)return T{};else return data[1];}
void pop(){
if(data.size()==1)return;
else if(data.size()==2){data.pop_back();return;}
swap(data[1],data.back());
data.pop_back();
int ch;
for(int idx=1;idx<<2<=data.size();idx=ch)
{
ch=idx<<1;
if(ch+1!=data.size()&&cmp(data[ch|1],data[ch]))ch|=1;
if(!cmp(data[idx],data[ch]))swap(data[idx],data[ch]);
else break;
}
}
bool empty(){return data.size()==1;}
};
int main() {
heap<int> hp;
for(int i=1;i<17;i++)hp.push(i);
for(int i=1;i<17;i++){cout<<hp.top()<<endl;hp.pop();}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment