Chapter 10 alds1 ﹣ 9 ﹣ B: maximum heap

Posted by Misery_Kitty on Sun, 03 May 2020 04:28:52 +0200

Knowledge points

Maximum heap: for all nodes i, the key value is less than or equal to the key value of the parent node

Question link

ALDS1_9_B: Maximum Heap

Question content

For sequence A, the maximum heap is realized by using the property of the maximum heap

thinking

For A sequence A containing n elements. i starts from n/2 and traverses at 1. Each execution of maxHeapify is A comparison between the left and right nodes. If it is larger than the child node, it will be exchanged until it cannot be compared.

Code

Realize the function of maximum heap

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxx = 2000000;

int A[maxx + 1];
int n;
void maxHeapify(int i) {

    int left = 2 * i, right = 2 * i + 1;
    int largest;

    // Select the node with the largest value from the left sub node, self and right sub node, and continue to recurse
    if (left <= n && A[left] > A[i])
        largest = left;
    else
        largest = i;

    if (right <= n && A[right] > A[largest])
        largest = right;

    if (largest != i) {
        swap(A[i], A[largest]);
        maxHeapify(largest);
    }

}
int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &A[i]);

    for (int i = n / 2; i >= 1; i--)
        maxHeapify(i);
    for (int i = 1; i <= n; i++)
        printf(" %d", A[i]);
    printf("\n");
    return 0;
}

Using vector and make'heap() of STL

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int maxx = 200000;

int main()
{
    int n, k;
    vector<int> ve;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &k);
        ve.push_back(k);
    }

    make_heap(ve.begin(), ve.end());

    for (vector<int>::iterator it = ve.begin(); it != ve.end(); it++)
        printf(" %d", *it);
    printf("\n");
    return 0;
}

Topics: less