概述
#include < algorithm >
// 本例程演示了STL heap的一个最重要的应用——实现优先队列。并将其方法封装到一个PQ类中
const int maxLen = 100 ;
template < class T >
#define DEAP // 浅复制还是深复制
struct PQ { // 最大堆
T h[maxLen];
int e;
void clear() { e = 0 ;}
bool empty() { return e == 0 ; }
int size() { return e;}
void push( const T & item) { // O(logN)
h[e ++ ] = item;
push_heap(h,h + e);
}
T & pop() { // O(logN)
pop_heap(h,h + e);
return h[ -- e];
}
const T & top() {
return h[ 0 ];
}
void make(T * bgn, T * end) { // O(N)
#ifdef DEAP // 深复制
for (e = 0 ; bgn != end; ++ e, ++ bgn)
h[e] =* bgn;
#else // 浅复制
e = end - bgn;
memcpy(h,bgn,e * sizeof ( * bgn));
#endif
make_heap(h,h + e);
}
void sort(T * bgn) { // O(NlogN)
#ifdef DEAP // 深复制
int i; T * end = bgn;
for (i = 0 ; i < e; ++ i, ++ end)
* end = h[i];
#else // 浅复制
T * end = bgn + e;
memcpy(bgn,h,e * sizeof ( * bgn));
#endif
sort_heap(bgn, end);
}
friend bool isHeap(T * bgn, T * end) { // debug用, O(N)
T * h = bgn - 1 ; int i,e = end - bgn + 1 ;
for (i = 2 ; i < e; ++ i)
if (h[i / 2 ] < h[i]) return false ;
return true ;
}
PQ() { clear();}
} ;
#include < cassert >
#include < iostream >
using namespace std;
template < class T >
inline void show(T a[], int n) {
int i;
for (i = 0 ; i < n; ++ i)
cout << a[i] << ' ' ;
cout << endl;
}
// 简单测试
int main() {
PQ < int > pq;
int a[] = { 3 , 6 , 5 , 4 , 2 , 7 , 9 } ;
cout << (pq.empty() ? " Empty/n " : " Not empty/n " );
pq.make(a,a + sizeof (a) / sizeof ( * a));
show(pq.h,pq.size());
cout << " Top: " << pq.top() << endl;
cout << ( isHeap(pq.h, pq.h + pq.e) ? " Is heap/n " : " Not a heap/n " );
pq.push( 3 );
pq.push( 1 );
pq.push( 10 );
show(pq.h,pq.size());
cout << " Top: " << pq.top() << endl;
cout << ( isHeap(pq.h, pq.h + pq.e) ? " Is heap/n " : " Not a heap/n " );
cout << " Pop: " << pq.pop() << endl;
cout << " Pop: " << pq.pop() << endl;
cout << " Pop: " << pq.pop() << endl;
pq.sort(a);
show(a,pq.size());
return 0 ;
}
最后
以上就是复杂芹菜为你收集整理的标程:优先队列类的全部内容,希望文章能够帮你解决标程:优先队列类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复