题目描述
给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环,所有边权均为非负值。
请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 −1。
输入格式
第一行包含整数 n 和 m。
接下来 m 行每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。
输出格式
输出一个整数,表示 1 号点到 n 号点的最短距离。
如果路径不存在,则输出 −1。
数据范围
1
≤
n
,
m
≤
1.5
×
1
0
5
1≤n,m≤1.5×10^5
1≤n,m≤1.5×105,
图中涉及边长均不小于 0,且不超过 10000。
数据保证:如果最短路存在,则最短路的长度不超过 109。
输入样例:
3 3
1 2 2
2 3 1
1 3 4
输出样例:
3
思路
本题和上面一题的区别是这里节点数变多了,存储方式采用的邻接表的存储方式。
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
这个堆优化的Dijkstra算法也是比较常用的求最短路径的算法,对比之前的Dijkstra算法。
朴素的Dijkstra算法时间复杂度:
O
(
n
2
)
O(n^2)
O(n2)
for(int i = 1; i <= n; i ++)
{
int t = -1;
// 遍历所有节点 找到当前没访问过且最小距离的节点
for(int j = 1; j <= n; j ++)
{
if(!st[j] && (t == -1 || dist[t] > dist[j])) t = j;
}
st[t] = true; // 标记已经遍历过的节点
// 更新其他点距离
for(int j = 1; j <= n; j ++)
{
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
}
堆优化的Dijkstra算法时间故复杂度: O ( m l o g n ) O(mlogn) O(mlogn)
while(heap.size())// 这里存放时节点 logn
{
auto t = heap.top();
heap.pop();
int ver = t.second, distance = t.first;
if(st[ver]) continue;
for(int i = h[ver]; i != -1; i = ne[i])// 这里遍历所有的子节点 m个点
{
int j = e[i];
if(dist[j] > distance + w[i])
{
dist[j] = distance + w[i];
heap.push({dist[j],j});
}
}
}
代码示例
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 200010;
typedef pair<int, int> PII;
int h[N], w[N], e[N], ne[N], idx; // 稀疏图 -- 邻接表存储
int dist[N];
bool st[N];
int n, m;
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;
//PII: 优先队列存放元素类型为PII —— <int, int>
//vector<PII>: 将PII设置为向量
//greater<PII>: 按照PII第一个位置元素升序排列 所以这里要把dist放在前面
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, 1});
// 遍历和更新节点
while(heap.size())
{
auto t = heap.top();
heap.pop();
int ver = t.second, distance = t.first;
if(st[ver]) continue;
for(int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if(dist[j] > distance + w[i])
{
dist[j] = distance + w[i];
heap.push({dist[j],j});// 堆的插入操作时间复杂度是 O(log(n))
}
}
}
if(dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
for(int i = 0; i < m; i ++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
cout << dijkstra() << endl;
return 0;
}