aoj

ALDS1_9_B Maximum Heap

ALDS1_9_B Maximum Heap
Feb. 2, 2020, 1:52 p.m.

目次

解答

 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
#define loop(x, start, end) for(int x = start; x < end; x++)
#define loopdown(x, start, end) for(int x = start; x > end; x--)

#define left(x) (x * 2)
#define right(x) (x * 2 + 1)

void heapify(vector<int> &vec, int index) {
    int l = left(index);
    int r = right(index);

    int largest;
    if (l < vec.size() && vec[l] > vec[index]) largest = l;
    else largest = index;
    if (r < vec.size() && vec[r] > vec[largest]) largest = r;

    bool childLarger = largest != index;
    if (childLarger) {
        swap(vec[largest], vec[index]);
        heapify(vec, largest);
    }
}

int main(void){
    int n, x;
    cin >> n;
    vector<int> vec(n+1);

    loop(i, 1, n+1) cin >> vec[i];

    loopdown(i, vec.size() / 2, 0) heapify(vec, i);

    loop(i, 1, n+1) cout << " " << vec[i];
    cout << endl;
    return 0;
}