MinHeap (poj2388)

//by zxfx100
//(sizeof a = n) && (heap = a[1..n]) && (a[0] is null) && (range is int)
class MinHeap
{
public:
int a[32768], n;
void build()
{
    n = 0;
}
void insert(int element)
{
    a[++n] = element;
    int i = n;
    while(i > 1)
    {
        int j = i >> 1;
        if(a[i] < a[j])
            swap(a[i], a[j]);
        i = j;
    }
}
int get()
{
    return a[1];
}
void extract()
{
    a[1] = a[n--];
    int i = 1, l = 2, r = 3;
    while(l <= n)
    {
        int index = i;
        if(a[l] < a[i])
            index = l;
        if(r <= n && a[r] < a[index])
            index = r;
        if(index == i)
            break;
        swap(a[i], a[index]);
        r = (l = (i = index) << 1) + 1;
    }
}
};

 

posted @ 2013-04-03 23:58  zxfx100  阅读(198)  评论(0编辑  收藏  举报