priority_queue
今天的算法题没有遇到比较难的,所以今天就不总结算法题目了。
今天总结一个用堆实现的priority_queue,蛮好的。
priority_queue的声明模板很简单:priority_queue<Type, Container, Functional>。Type是数据类型(int,float。。),Container是容器必须是用数组实现的容器,比如 vector, deque 但不能用 list。最后一个是比较函数。STL里面容器默认用的是 vector. 比较方式默认operator< , 所以如果你把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大。
#include <iostream>
#include <queue>
using namespace std;
int main(){
priority_queue<int> pq;
for( int i= 0; i< 10; ++i ) pq.push( i );
while( !pq.empty() ){
cout << pq.top() << endl;
pq.pop();
}
getchar();
return 0;
}
如果要使用小顶堆那么根据C++规则,三个参数都要写。STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆
#include <iostream>
#include <queue>
using namespace std;
int main(){
priority_queue<int, vector<int>, greater<int> > pq;
for( int i= 0; i< 10; ++i ) pq.push( i );
while( !pq.empty() ){
cout << pq.top() << endl;//0,1,2,3....
pq.pop();
}
getchar();
return 0;
}
在升级一下就是自定义类型,必须自己重载 operator< 或者自己写仿函数
#include <iostream>
#include <queue>
using namespace std;
struct mNode{//定义数据类型
int x, y;
Node( int a= 0, int b= 0 ):
x(a), y(b) {}
};
bool operator<( mNodea, mNodeb ){//重载<
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x;
}
int main(){
priority_queue<mNode> pq;
for( int i= 0; i< 10; ++i )
pq.push( mNode( rand(), i) );
while( !pq.empty() ){
cout << pq.top().x << ' ' << pq.top().y << endl;
pq.pop();
}
getchar();
return 0;
}
此时可以只带一个参数声明变量,但是不可以使用类似greater进行声明,(因为没定义呀)。那怎么定义呢?
#include <iostream>
#include <queue>
using namespace std;
struct mNode{
int x, y;
Node( int a= 0, int b= 0 ):
x(a), y(b) {}
};
struct cmp{
bool operator() ( mNode a, mNode b ){
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x; }
};
int main(){
priority_queue<mNode, vector<mNode>, cmp> pq;
for( int i= 0; i< 10; ++i )
pq.push( mNode( rand(), rand() ) );
while( !pq.empty() ){
cout << pq.top().x << ' ' << pq.top().y << endl;
pq.pop();
}
getchar();
return 0;
}