您的位置:首页 > 编程语言 > C语言/C++

heap

2015-11-25 16:51 405 查看
1002. heap   

实现一个小根堆用以做优先队列。

给定如下数据类型的定义:

class array {

    private:

    int elem[MAXN];

    public:

    int &operator[](int i) { return elem[i]; }

};

class heap {

    private:

    int n;

    array h;

    public:

    void clear() { n = 0; }

    int top() { return h[1]; }

    int size() { return n; }

    void push(int);

    void pop();

};

要求实现:

void heap::push(int x) {

    // your code

}

void heap::pop() {

    // your code

}

// Problem#: 16344
// Submission#: 4171675
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University
void heap::push(int input ) {
h[++n] = input ; int pos = n / 2 , last = n ;
while(pos >= 1 ){
if(h[pos] <= h[last]){
break ;
}
swap(h[pos] , h[last]);
last = pos ;
pos = pos / 2;
}
}

void heap::pop() {
h[1] = h[n--] ;
int pos = 1 ;
while(1){
if(2 * pos > n) break ;
if(2 * pos == n && h
>= h[pos]) break ;
if(2 * pos < n && h[pos] <= h[pos * 2 ] && h[pos] <= h[pos * 2 + 1]) break;

if(2 * pos == n && h
< h[pos]){
swap(h
, h[pos]) ;
break ;
}
else{
if(h[pos * 2] < h[pos * 2 + 1]){
swap(h[pos] , h[pos * 2]) ;
pos = pos * 2 ;
}
else {
swap(h[pos] , h[pos * 2 + 1]) ;
pos = pos * 2 + 1 ;
}
}
}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ sicily 小根堆 heap