堆的建立

int heap[MAX_N], sz = 0;
void push(int x)
{
    int i = sz++;
    while (i>0) {
        int p = (i-1)/2;
        i f(heap(p)<=x) break;
        heap[i] = heap[p];
        i = p;
    }
    heap[i] = x;    
}

int pop() 
{
    int ret = heap[0];
    
    int x = heap[--sz];
    int i = 0;
    while (2*i+1<sz) {
        int a = 2*i+1, b = 2*i+2;
        if (b<sz && heap[b]<heap[a]) a = b;
        if (heap[a]<=x) break;
        heap[i] = heap[a];
        i = a;
    }
    heap[i] = x;
    
    return ret; 
} 
posted @ 2019-06-27 08:28  sparkyen  阅读(191)  评论(0编辑  收藏  举报