heap - changicho/algorithm-training GitHub Wiki
๊ฐ๋ค์ ๋์ ๊ด๊ณ๋ ๋ถ๋ชจ์ ์์ ๋ ธ๋ ๊ฐ์๋ง ์กด์ฌํ๋ค.
์๊ฐ ๋ณต์ก๋๋ log(n) ์ด๋ค.
heap ์๋ฃ๊ตฌ์กฐ
long long heap[100002];
int heap_size = 0;๋ฃจํธ ๋ ธ๋์ ๊ฐ์ ์ญ์ ํ๊ณ , ํ์ ๋งจ ๋ง์ง๋ง ๋ ธ๋์ ๊ฐ์ ๋ฃจํธ์ ๋ฃ์ ๋ค ๊ฐฑ์ ํ๋ค.
void heap_delete() {
int current, left, right;
heap[1] = heap[heap_size];
heap[heap_size] = 0;
heap_size -= 1;
if (heap_size == 0) {
return;
}
current = 1;
while (true) {
left = current * 2;
right = current * 2 + 1;
if (left > heap_size) {
break;
}
// if it has only left node
if (right > heap_size) {
if (heap[left] < heap[current]) { // ๋ณ๊ฒฝ์
swap(heap[left], heap[current]);
current = left;
continue;
}
}
// if it has two node
else {
if (heap[left] <= heap[right]) { // ๋ณ๊ฒฝ์
if (heap[left] < heap[current]) { // ๋ณ๊ฒฝ์
swap(heap[left], heap[current]);
current = left;
continue;
}
}
else {
if (heap[right] < heap[current]) { // ๋ณ๊ฒฝ์
swap(heap[right], heap[current]);
current = right;
continue;
}
}
}
if (current == left / 2) {
break;
}
}
return;
}ํ์ ๋งจ ๋ง์ง๋ง์ ์๋ก์ด ๊ฐ์ ๋ฃ๊ณ , ๋ถ๋ชจ๋ ธ๋์ ๋น๊ตํ๋ฉฐ ๊ฐฑ์ ํ๋ค.
void heap_push(int input) {
heap_size += 1;
heap[heap_size] = input;
int current = heap_size, parent;
while (true) {
if (current == 1) break;
parent = current / 2;
if (heap[current] < heap[parent]) { // ๋ณ๊ฒฝ์
swap(heap[parent], heap[current]);
}
else {
break;
}
current = parent;
}
}์ ์์์ ์ฃผ์์ฒ๋ฆฌํ ๋ถ๋ถ์ ๋ฑํธ๋ฅผ ๋ณ๊ฒฝํ๋ฉด ์ต๋ ํ์ด ๋๋ค.
์ฐ์ ์์ ํ์ ๊ฒฝ์ฐ heap์ผ๋ก ์ด๋ฃจ์ด์ ธ ์๋ค.
priority_queue<int> pq; // ์ฐ์ ์์ ํ ์ ์ธ
cin >> input;
switch(input){
case 0:{
if (pq.empty()) { // queue๊ฐ ๋น์ด์์ ๊ฒฝ์ฐ 0 ์ถ๋ ฅ
cout << "0\n";
} else {
// ๊ฐ์ฅ ์์ ๋ค์ด๊ฐ์๋ ๊ฐ์ ์ถ๋ ฅ
cout << pq.top() << "\n";
pq.pop();
}
}
case 1:{
pq.push(x); // ์
๋ ฅํ ์ซ์ queue์ ์ฝ์
}
}STL queue ์ priority_queue๋ฅผ ์ด์ฉํ ๋ฐฉ๋ฒ์ ๋ค์๋๊ฐ์ง๊ฐ ์กด์ฌํ๋ค.
๊ตฌ์กฐ์ฒด๋ฅผ ๊ตฌํํด ์ฌ์ฉํ๋ ๊ฒฝ์ฐ operator๋ฅผ ์ง์ ๊ตฌํํด์ผ ํ๋ค.
๋ฐฉ๋ฒ 1 : compare ๊ตฌ์กฐ์ฒด ์ฌ์ฉ
struct Data {
int abs, value;
};
struct compare {
bool operator()(Data a, Data b) {
if (a.abs != b.abs) {
return a.abs > b.abs;
}
return a.value > b.value;
}
};
priority_queue<Data, vector<Data>, compare> pq;๋ฐฉ๋ฒ 2 : operator๋ฅผ ์ค๋ฒ๋ก๋ฉ
struct Data {
int abs, value;
};
bool operator<(Data a, Data b) {
if (a.abs != b.abs) {
return a.abs > b.abs;
}
return a.value > b.value;
}
priority_queue<Data> pq;๋ฐฉ๋ฒ 3 : ๊ตฌ์กฐ์ฒด์ ์ง์ operator ์ ์ธ
struct Data {
int abs, value;
bool operator<(const Data &b) const {
if (abs != b.abs) {
return abs > b.abs;
}
return value > b.value;
}
};
priority_queue<Data> pq;