카테고리 없음

Heap 구현

fw93 2018. 4. 15. 21:23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "stdafx.h"
#include <vector>
#include <iostream>
 
using namespace std;
 
void swap(int & a, int & b) {
    int tmp = a;
    a = b;
    b = tmp;
}
 
int hleft(vector<int>&heap, int i) {
    return (i * 2 + 1 < heap.size()) ? 2 * i+1 : -1;
}
 
int hright(vector<int>&heap, int i) {
    return (i * 2 + 2 < heap.size()) ? 2 * i + 2 : -1;
}
 
int parent(vector<int>&heap, int i) {
    return i / 2;
}
 
void maxheapify(vector<int>&heap,int i) {
    cout << "hpfy at " << i << endl;
    if (i > heap.size() - 1) return;
    int left = hleft(heap, i);
    int right = hright(heap, i);
    int change = i;
    if (left != -1 && heap[left] > heap[i]) {
        change = left;
    }
    if (right != -1 && heap[right] > heap[change]) {
        change = right;
    }
    if (change != i) {
        swap(heap[i], heap[change]);
        maxheapify(heap, change);
    }
}
 
void buildheap(vector<int>&heap) {
    for (int i = heap.size() / 2; i >= 0; i--) {
        for (int x : heap) cout << x << " ";
        cout << endl;
        maxheapify(heap, i);
    }
}
 
void insert(vector<int> & heap, int k) {
    heap.push_back(k);
    int curr = heap.size() - 1;
    while (curr != 0 && heap[parent(heap, curr)] < heap[curr]) {
        swap(heap[parent(heap, curr)], heap[curr]);
        curr = parent(heap, curr);
    }
}
 
int pop(vector<int> & heap) {
    if (heap.size() == 0) return -9999;
    int ret = heap[0];
    heap[0] = heap[heap.size() - 1];
    heap.pop_back();
    maxheapify(heap, 0);
    return ret;
}
 
int main() {
    vector<int> sam = { 5,4,7,18,4,7,6,4,2,13,14,1 };
    buildheap(sam);
    for (int x : sam) cout << x << " ";
    cout <<endl << pop(sam) << endl;
    for (int x : sam) cout << x << " ";
    cout << endl;
    insert(sam, 9);
    for (int x : sam) cout << x << " ";
    cout << endl;
    while(1){}
    return 0;
}
cs