dijkstra模板
适用于稠密图的dijkstra算法模板:
朴素Dijkstra算法 复杂度O(n^2) 适用于稠密图
算法实现思路:
将所有点距离设置为无穷大,并将第一个点距离设置为 0;
for(0~n-1){
将距离当前点最近的点添加到路径中;
并用该点更新所有点距离起点的距离;
}
代码实现:
#include <iostream>
#include <cstring>
using namespace std;
const int N = 510;
int n, m; //n个点,m条边
int g[N][N]; //存储图的二维数组
int dist[N]; //存储所有点距起始点的最短距离
bool st[N]; //存储该点是否已经在最短路中
int dijkstra(){
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for(int i=0; i<n; i++){
int t = -1;
//寻找不在最短路径中的且距离最小的点
for(int j=0; j<n; j++){
//未被确认的点 && (第一个点直接加入 || 第j个点距离小于第t个点)
if(!st[j] && (t==-1 || dist[t]>dist[j]))
t = j;
}
//将该点标记为已在路径中
st[t] == true;
//用当前点更新所有点的距离
for(int j=0; j<n; j++){
dist[j] = min(dist[j], dist[t]+g[t][j]);
}
}
if(dist[n] = 0x3f3f3f3f) return -1;
return dist[n];
}
int main(){
scanf("%d%d", &n, &m);
memset(g, 0x3f, sizeof g);
while(m--){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
//将重复边的最小权值加入当前图中
g[a][b] = min(g[a][b], c);
}
int d = dijkstra();
printf("%d", d);
return 0;
}
适用于稀疏图的jijkstra算法模板:
堆优化版Dijkstra算法 时间复杂度O(nm) 适用于稀疏图
算法实现思想:
利用朴素版Dijkstra算法的思路
将"每次遍历寻找距离当前点最近的点"利用小根堆的特性省去了遍历的步骤
代码实现:
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 10010;
int n, m; //n个结点,m条边
// h:N个链表的表头,w:存的是当前边的权重,e:存的是所有结点的值,ne:存的是所有结点的next,idx表示当前使用到的数组下标
int h[N], w[N], e[N], ne[N], idx;
int dist[N]; //存储所有点距离起点的最短距离
bool st[N]; //存储该点是否已在最短路
//邻接表存储图添加边的方法
void add(int a, int b, int c){
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int dijkstra(){
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
//定义小根堆的语法
priority_queue<PII, vector<PII>, greater<PII>> heap;
//直接加入第一条边
heap.push({0, 1});
//当堆不空
while(heap.size()){
//取出当前队列中最小值
auto t = heap.top();
heap.pop();
//ver存储当前点的序号,dis存储当前点距起点的距离
int ver = t.second(), dis = t.first();
//若当前点已在路径中,则跳过循环
if(st(ver)) continue;
//遍历所有ver结点的相邻结点,并更新距离
for(int i = h[ver]; i != -1; i = ne[i]){
int j = e[i];
if(dist[j] > dis+w[i]){
dist[j] = dis+w[i];
heap.push({dist[j], j});
}
}
}
if(dist[n] == 0x3f3f3f3f) return 0;
return dist[n];
}
int main(){
int a, b, c;
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while(m--){
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
int t = dijkstra();
printf("%d", t);
return 0;
}