ADT 最大优先队列的抽象数据类型描述抽象数据类型
MaxPriorityQueue{
实例 有限的元素集合,每个元素都有一个优先权
操作
Create ( ):创建一个空的优先队列
Size ( ):返回队列中的元素数目
Max ( ):返回具有最大优先权的元素
I n s e rt (x):将x插入队列
DeleteMax (x):从队列中删除具有最大优先权的元素,并将该元素返回至x
}
优先队列插入和删除元素的复杂度都是O(lgn),所以很快。
另一种描述方法是采用有序线性表,当元素按递增次序排列,使用链表时则按递减次序排列,这两种描述方法的删除时间均为( 1 ),插入操作所需时间为(n).
优先队列是不同于先进先出队列的另一种队列。
每次从队列中取出的是具有最高优先权的元素
优先对列是0个或多个元素的集合,每个元素都有一个优先权或值,对优先队列执行的操作
有:
1.查找
2.插入一个新元素
在最小优先队列中,查找操作用来搜索优先权最小的元素,删除删除也一样。
在最大优先队列中,查找操作用来搜索优先权最大的元素,删除也一样。
STL 中优先队列的使用方法(priority_queu)
基本操作:
empty() 如果队列为空返回真
pop() 删除对顶元素
push() 加入一个元素
size() 返回优先队列中拥有的元素个数
top() 返回优先队列对顶元素
在默认的优先队列中,优先级高的先出队。在默认的int型中先出队的为较大的数。
使用方法:
头文件:
#include <queue>
声明方式:
1、普通方法:
priority_queue<int>q;
//通过操作,按照元素从大到小的顺序出队
2、自定义优先级:
struct cmp
{
operator bool ()(int x, int y)
{
return x > y; // x小的优先级高
//也可以写成其他方式,如: return p[x] > p[y];表示p[i]小的优先级高
}
};
priority_queue<int, vector<int>, cmp>q;//定义方法
//其中,第二个参数为容器类型。第三个参数为比较函数。
3、结构体声明方式:
struct node
{
int x, y;
friend bool operator < (node a, node b)
{
return a.x > b.x; //结构体中,x小的优先级高
}
};
priority_queue<node>q;//定义方法
//在该结构中,y为值, x为优先级。
//通过自定义operator<操作符来比较元素中的优先级。
//在重载”<”时,最好不要重载”>”,可能会发生编译错误
#include<stdlib.h>
using namespace std;
int main( )
{
priority_queue<int>q; //元素从大到小,默认的。
int t,i;
for(i=1;i<=5;i++)
{
scanf("%d",&t);
q.push(t);
}
while(!q.empty())
{
cout<<q.top()<<" ";
q.pop();
}
system("pause");
return 0;
}
#include<queue>
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<functional>
using namespace std;
int main( )
{
//priority_queue<int>q;
//从小到大,需要传入一个比较函数,使用functional.h函数对像作为比较函数
//第二个参数为容器类型 ,greater比较函数 ,改为less后就为从大到小了。
priority_queue<int, vector<int>, greater<int> >q;
int t,i;
for(i=1;i<=5;i++)
{
scanf("%d",&t);
q.push(t);
}
while(!q.empty())
{
cout<<q.top()<<" ";
q.pop();
}
system("pause");
return 0;
}
//自定义类型。。
#include<queue>
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<functional>
using namespace std;
struct node
{
friend bool operator<(node a,node b)
{
return a.priority<b.priority;
}
int priority;
int value;
};
int main( )
{
priority_queue<node>q;
node b[5];
b[0].priority = 6; b[0].value = 1;
b[1].priority = 9; b[1].value = 5;
b[2].priority = 2; b[2].value = 3;
b[3].priority = 8; b[3].value = 2;
b[4].priority = 1; b[4].value = 4;
int t,i;
for(i=0;i<5;i++)
{
q.push(b[i]);
}
for(i=0;i<5;i++)
{
cout<<q.top().priority<<'\t'<<q.top().value<<endl;
q.pop();
}
system("pause");
return 0;
}