[Summary] binary heap

a brief introdction

Minimum stack: the stack is a critical minimum code sequence {K1, K2, ..., Kn}, which has the following characteristics:

K[i] <= K[2i]

K[i] <= K[2i+1]

Similarly you can define the maximum heap.

nature

Complete binary tree of hierarchical sequence, can be represented as an array.

The number of local storage heap is ordered, the heap is not unique.

There is a limit between the value of the node and its children's values.

Have no direct restrictions between any node with his brother.

From a logical perspective, the stack is actually a tree structure.

Basic Operations

top

Direct return root

The time complexity of O (1)

pop

Eject the current minimum

Deletion root nodes into the lowermost position of the root node

Then pass under the root node

void pop()
{
    cout << "pop" << endl;
    heap[1] = heap[n]; n--; downdate(1); //直接删除堆顶,把最后一个元素放到堆顶,下滤 
    //print();
}
void downdate(int x){
    while(x*2<=n){
        int y=x*2;
        if(x*2<n&&heap[x*2+1]<heap[x*2]){
            y=x*2+1;
        }
        if(heap[x]<=heap[y])break;
        swap(heap[x],heap[y]);
        x=y;
    }
} 

push

Insert a number

Position after insertion into, compared to its parent node, upload

void insert(int x){
    heap[++n]=x;
    update(n);

}
void update(int x){//上滤操作qwq 
    while(x!=1){
        if(heap[x/2]<=heap[x])break;
        swap(heap[x/2],heap[x]);
        x/=2;
    }
}

size

priority_queue the equivalent of a stack, in fact, more stl also usually use heap emm

Definitions: priority_queue a;

Inserting the tail: a.push (x);

Delete the first team: a.pop ();

The first inquiry team: a.top ();

Empty only slowly pop.

Example: sequence merger

Detailed explanation see Solution: Portal

analysis

Fixing A [i], and every n are ordered:

A[1] + B[1] <= A[1] + B[2] <= … <= A[1] + B[n]

A[2] + B[1] <= A[2] + B[2] <= … <= A[2] + B[n]

A[n] + B[1] <= A[n] + B[2] <= … <= A[n] + B[n]

Each number can only be considered a first line has not been taken into account

Example: ugly number

It refers to the number of prime factors ugly in the set {2, 3, 5, 7} integer, the first number is an ugly one.

Now type n, the number of n-th largest output ugly.

n <= 10000.

analysis

And the problem is a very, very similar, the only difference is a problem with the tuple, and we now consider is a four-tuple

Represents 2a3b5c7d, 1 is (0, 0, 0, 0) by a four-tuple (a, b, c, d)

With a minimum stockpiling 2a3b5c7d, takes out a minimum value (a, b, c, d).

Then (a + 1, b, c, d) (a, b + 1, c, d) (a, b, c + 1, d) (a, b, c, d + 1) is inserted into the stack.

Note that if the top of the stack elements and a number of outputs equal to the need to pop out.

Guess you like

Origin www.cnblogs.com/huixinxinw/p/12242339.html