#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int N = 150000,M=N*2;
typedef pair<int, int> PII;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
bool st[N];
int n,m;
void add(int a, int b, int c) // 添加一条边a->b,边权为c
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
int dijkstra()
{
memset(dist,0x3f,sizeof dist);
priority_queue<PII,vector<PII>,greater<PII>> ans;//建立小根堆,减少搜索过程
ans.push({0,1});//first存储当前节点到源点的距离,second存储当前节点,从源点开始遍历
dist[1]=0;
while(ans.size())
{
auto az=ans.top();//堆的顶部是最小节点
ans.pop();
int x=az.second,y=az.first;
if(st[x]) continue;//如果该节点被遍历过则返回
st[x]=true;
for(int i=h[x];i!=-1;i=ne[i])
{
int t=e[i];
if(dist[t]>y+w[i])//与朴素版dijkstra算法同理
{
dist[t]=y+w[i];
ans.push({dist[t],t});//拓展点
}
}
}
if(dist[n]==0x3f3f3f3f)return -1;
return dist[n];
}
int main()
{
cin>>n>>m;
memset(h,-1,sizeof h);
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
int t=dijkstra();
cout<<t<<endl;
return 0;
}
最短路径之dijkstra算法(单源最短路)(堆优化,适用于稀疏图)
于 2022-04-18 22:37:20 首次发布