【模板】堆

小根堆

int n;
int h[MAX_N];

inline void Insert(int x)
{
    h[++n] = x;
    int now = n;
    while(now ^ 1)
    {
        if(h[now] >= h[now >> 1]) break;
        swap(h[now], h[now >> 1]);
        now >>= 1;
    }
    return;
}

inline void Delete()
{
    if(!n) return;
    swap(h[1], h[n--]);
    int now = 1, next = 2;
    while(next <= n)
    {
        if(next < n && h[next] > h[next | 1]) next |= 1;
        if(h[now] <= h[next]) break;
        swap(h[now], h[next]);
        now = next;
        next <<= 1;
    }
    return;
}

 

大根堆

int n;
int h[MAX_N];

inline void Insert(int x)
{
    h[++n] = x;
    int now = n;
    while(now ^ 1)
    {
        if(h[now] <= h[now >> 1]) break;
        swap(h[now], h[now >> 1]);
        now >>= 1;
    }
    return;
}

inline void Delete()
{
    swap(h[1], h[n--]);
    int now = 1, next = 2;
    while(next <= n)
    {
        if(next < n && h[next] < h[next | 1]) next |= 1;
        if(h[now] >= h[next]) break;
        swap(h[now], h[next]);
        now = next;
        next <<= 1;
    }
    return;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章