Explanation of Binary Heap

Explanation of Binary Heap

Large and small top piles

Starting from the structure of the binary heap, it is a binary tree, and it is a complete binary tree, each node stores an element (or, in other words, has a weight).
Heap property: the weight of the father is not less than the weight of the son (big root heap). Similarly, we can define small root heaps. This article takes Dagendui as an example.

Due to the nature of the heap, the root of the tree stores the maximum value.
insert image description here
As long as the operation complexity involved in changing the heap structure is O ( log ( n ) ) O(log(n))O ( l o g ( n ))
query operationO ( 1 ) O(1)O(1)

application

greedy

Merge Fruit
Building Repair

Maintain a fixed-size monotonic sequence

Assuming that for a given sequence, the k-minimum value is to be output in the end, then use the big top heap to maintain it.
The specific steps are:

  • If the number of elements in the heap does not exceed k, continue to add
  • If the number of elements in the heap exceeds k, add it and then pop the top element of the heap
  • Finally, take a reverse order.

Minimal Function Valued
Sequence Merging

Maintain a monotonic sequence of variable size

Introduction to the top pile The top
pile consists of a large root pile and a small root pile. The small root pile maintains a large value, that is, the value that is larger than the first k (including the kth number), and the large root pile maintains a small value, that is, a value that is smaller than the kth largest number. other numbers.
The data structure formed by these two heaps supports the following operations:

  • Insert element: if the inserted element is greater than or equal to the top element of the small root heap, insert it into the small root heap, otherwise insert it into the large root heap, and then maintain the top heap;
  • Query the kth largest element: the top element of the small root heap is the desired element; (if the kth smallest element is queried, the large root heap maintains the k smaller value before the small value, and the small root heap maintains other numbers whose maximum value is larger than the kth decimal )
  • Delete the kth largest element: delete the top element of the small root heap, and then maintain the top heap;
  • Maintenance: When the size of the small root heap is less than k, the top element of the large root heap is continuously taken out and inserted into the small root heap until the size of the small root heap is equal to k; when the size of the small root heap is greater than k, the small root heap is continuously The top element of the heap is taken out and inserted into the large root heap until the size of the small root heap is equal to k;
  • When the value of k changes, the top heap should be maintained according to the new value.
    black box
    median

Guess you like

Origin blog.csdn.net/qq_57150526/article/details/130725689