ACM-ICPC 2015 Changchun Preliminary Contest A题即用到优先队列,所以要想做出相关题,必须得掌握优先队列。
在c++中,队列是一种先进先出的数据结构:在队列中插入一个队列元素称为入队,从队列中删除一个队列元素称为出队。因为队列只允许在一端插入,在另一端删除,所以只有最早进入队列的元素才能最先从队列中删除,故队列又称为先进先出(FIFO—first in first out)
C++队列queue模板类的定义在<queue头文件中。C++队列Queue类成员函数有:
back()返回最后一个元素
empty()如果队列空则返回真
front()返回第一个元素
pop()删除第一个元素
push()在末尾加入一个元素
size()返回队列中元素的个数
代码例:
#include<queue>
#include<cstdio>
using namespace std;
int main()
{
queue <int> myQ;
printf("现在队列中元素个数%d\n\n",myQ.size());
for(int i =0; i<5 ; i++)
{
myQ.push(i);//入队
}
for(int i=0; !myQ.empty(); i++)
{
printf("队列剩余元素个数为:%d\n\n",myQ.size());
printf("队列的第一个元素为:%d 队列最后一个元素为:%d\n\n",myQ.front(),myQ.back());
myQ.pop();//出队
}
myQ.push(8);//在队列的最后一位添加一个元素
printf("队列压入的元素为:%d\n",myQ.back());
return 0;
}
优先队列:C++优先队列类似队列,但是在这个数据结构中的元素按照一定顺序排列
成员函数:
1.empty() 如果优先队列为空,则返回真
2.pop() 删除第一个元素
3.push() 加入一个元素
4.size() 返回优先队列中拥有的元素的个数
5.top() 返回优先队列中有最高优先级的元素
代码例:
#include<cstdio>
#include<queue>
using namespace std;
int main()
{
priority_queue<int>Q;
for(int i=1;i<=5;i++)
{
int x;
scanf("%d",&x);//压入输入的元素
Q.push(x);
}
for(int i=1;i<=5;i++)
{
printf("优先队列中最大元素为:%d\n\n",Q.top());//由于没有定义优先级,优先队列将按照元素大小来确定优先级
Q.pop();
}
return 0;
}
对优先队列进行自定义安排优先级:
代码例:
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
struct node
{
int time;
friend bool operator < (node n1, node n2) //friend:友元函数 operator < :重载操作符< 返回类型:bool
{
return n1.time<n2.time;//自定义优先级从大到小
}
} a;
struct node1
{
int time;
friend bool operator <(node1 n1,node1 n2)
{
return n1.time>n2.time;//从小到大
}
} b;
int main()
{
priority_queue<node>Q;
priority_queue<node1>Q1;
int i;
for(i=0; i<5; i++)
{
int x;
scanf("%d",&x);
a.time=x;
b.time=x;
Q.push(a);
Q1.push(b);
}
printf("队列1中优先级输出顺序为:\n");
while(!Q.empty())
{
a=Q.top();
Q.pop();
printf("%d ",a);
}
printf("\n");
printf("队列2中优先级输出顺序为:\n");
while(!Q1.empty())
{
b=Q1.top();
Q1.pop();
printf("%d ",b);
}
return 0;
}
上述代码通过定义友元函数(友元函数是指某些虽然不是类成员却能够访问类的所有成员的函数,类授予它的友元特别的访问权)可以在结构体内部重载操作符,用起来很方便,可以直接 priority_queue<结构体名>队列名;还有一种是比较运算符外置,这种用起来稍微麻烦一点,所以就不记录了。