实现一个小根堆用以做优先队列。
给定如下数据类型的定义:
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[n] >= h[pos]) break ;
if(2 * pos < n && h[pos] <= h[pos * 2 ] && h[pos] <= h[pos * 2 + 1]) break;
if(2 * pos == n && h[n] < h[pos]){
swap(h[n] , 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 ;
}
}
}
}