版本比较
堆(优先队列)
正文
增加 16 行删除 18 行
1223445667889101011121213141415161718192021222320212223242527262728293024 行未改动55565758605960616225 行未改动8889909194929394959649 行未改动146147148149152150151152153154138 行未改动全部展开29329429529629929729830130229930030130230330463 行未改动# 堆的定义及性质## 1.堆即优先队列,也是二叉树**堆即优先队列,也是二叉树**
## 2.优先队列的创建(STL)## 优先队列的创建(STL)
### 1.大根堆(普通写法)$1.$大根堆(普通写法) #### ``` priority_queue<int>q;```**``` priority_queue<int>q;```** ### 2.小根堆(正确写法) $2.$小根堆(正确写法) #### ``` priority_queue<int,vector<int>,greater<int> >q;```**```priority_queue<int,vector<int>,greater<int> >q;```** ### 3.小根堆(错误写法)$ 3.$小根堆(错误写法)```priority_queue<int,vector<int>,greater<int>>q;//可能CE```
### 4.大根堆(标准写法) ``` priority_queue<int,vector<int>,less<int> >q;```$4.$大根堆(标准写法)
**```priority_queue<int,vector<int>,less<int> >q;```** # 堆排序(从小到大)
原理:小根堆保证父节点<子节点,且在priority_queue<int,vector<int>,greater<int> >q;中会排序,时间复杂度$O(n*lb n)$ 原理:小根堆保证父节点<子节点,且在priority_queue<int,vector<int>,greater<int> >q;中会排序,时间复杂度$O(n*log_2\ n)$代码
[P1177](https://www.luogu.com.cn/problem/P1177)```cpp24 行未改动
[模板堆](https://www.luogu.com.cn/problem/P3378)
# 重载运算符## 重新定义运算符的含义,一般重载<
### 以[序列合并](https://www.luogu.com.cn/problem/P1631)为例:本题需要实时维护a数组与b数组的下标以及和,为了降低时间复杂度,用一个priority_queue<int>q来维护。因为priority_queue<int>q会排序,所以需要在struct内重载<25 行未改动[Facer帮父亲——考虑每一元收益最大值](https://www.luogu.com.cn/problem/P2707)
# 迪杰斯特拉的堆优化
## dijkstra原版:dijkstra原版:
```cpp#include <bits/stdc++.h>using namespace std;49 行未改动 cout<<dis[i]<<" "; }}```## dij在找最小值时,用堆可直接为堆顶(队首):**dij在找最小值时,用堆可直接为堆顶(队首):**
```cpp#include <bits/stdc++.h>using namespace std;138 行未改动全部展开 cout<<ans; return 0;}```~~十年OI一场空,不开long long见祖宗~~~~十年OI一场空,不开long long见祖宗。~~
## [不直接建边而是通过插入点O(n)建边的经典题P7100团](https://www.luogu.com.cn/problem/P7100)
## [P7100团](https://www.luogu.com.cn/problem/P7100)不直接建边而是通过插入点O(n)建边的经典题。 可以看出,用$O(k*s_i^2)$的时间复杂度一条条建边会$TLE$,所以,对于第$i$个集合,建立一个点$x_i$联结在该集合内的所有点,权值为$W_i$
code:
63 行未改动