一、priority_pueue队列
优先队列是一种容器,保证容器中的第一个元素一定是所有元素中最大的。这样就可以很方便的动态维护序列的最大值问题。底层实现方法:是使用数据结构——堆来的优先队列,默认为大根堆。优先队列不提供迭代器,不提供遍历功能。
主要函数:
#include <queue> //开库
priority_queue<int>a;//声明
a.empty() //返回1,表示堆为空
a.size() //返回堆的元素个数
a.top() //返回堆顶元素值
a.pop() //删除堆顶元素
a.push() //堆中插入一个元素k
由于不提供迭代器,也不允许遍历,所以并没有begin()、end()等成员函数。默认情况下优先队列中维护的是最大值。
二、priority_queue队列——示例
#include <bits/stdc++.h>
using namespace std;
priority_queue<int>q;
int main()
{
for(int i=1;i<=5;i++)
q.push(i);
while(!q.empty())
{
cout<<q.top()<<' ';
q.pop();
}
return 0;
}
/*
output:
5 4 3 2 1
*/#include <bits/stdc++.h>
using namespace std;
priority_queue<int>q;
int main()
{
for(int i=1;i<=5;i++)
q.push(-i);
while(!q.empty())
{
cout<<-q.top()<<' ';
q.pop();
}
return 0;
}
/*
output:
1 2 3 4 5
*/小根堆的实验方法:
1、如上例中把数值乘以-1
2、使用c++提供的比较方法:
priority_queue<int,vector<int>,greater<int> >q;三、priority_queue队列——堆维护结构体
#include <bits/stdc++.h>
using namespace std;
struct rec
{
int x,y;
};
priority_queue<rec>q;
bool operator <(rec a,rec b)//操作符重载
{
return a.x<b.x;
}
int main()
{
for(int i=1;i<=5;i++)
q.push((rec){i,i*i});
while(!q.empty())
{
cout<<q.top().x<<' '<<q.top().y<<endl;
q.pop();
}
return 0;
}
/*
output:
5 25
4 16
3 9
2 4
1 1
*/四、操作符重载
C++有许多内置的数据类型,包括int,char,double等,他们之间可以进行算数运算和比较大小。 但两个结构体之间是不能进行这些操作的,比如结构体a+b,这样的语句如果没有重载+运算符就会出错。C++允许用户把这些运算符(包括关系运算符或者位运算符)进行重载,就像sort中的比较函数cmp一样。 竞赛中使用最多的还是结构体之间比较大小,需要重载小于号即可。例如上一页PPT的中的例子。其实就是一种告诉C++结构体之间比较大小的规则。
#include <bits/stdc++.h>
using namespace std;
struct rec
{
int x,y;
}a,b;
int operator +(rec a,rec b)
{
return a.x+b.x+a.y+b.y;
}
int main()
{
a.x=1;
a.y=2;
b.x=3;
b.y=4;
cout<<a+b<<endl;
return 0;
}
/*
output:
10
*/五、数据结构——堆
堆(heap)是计算机科学中一类数据结构的统称,堆总是满足下列性质:
- 堆中某个节点的值总是不大于或者不小于父节点的值;
- 堆总是一颗完全二叉树
根节点最大的堆叫做大根堆,根节点最小的堆叫做小根堆。
注:对于深度为k的,有n个结单的二叉树,当且仅当每一个结点都与深度为k的满二叉树中编号从1到n结点——对应时称之为完全二叉树。
插入元素
删除堆顶元素






