850. Dijkstra求最短路 II (堆优化版dijkstra)
作者:
闪回
,
2024-03-24 19:37:44
,
所有人可见
,
阅读 3
每次取出堆顶进行更新
#include<bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef pair<int,int> PII;
const int N = 1e6+10;
int head[N],val[N],ne[N],weight[N],idx;
bool st[N];
int dist[N];
int n,m;
void add(int a,int b,int w)
{
val[idx] = b;
ne[idx] = head[a];
weight[idx] = w;
head[a] = idx++;
}
int heap_dijkstra()
{
memset(dist,0x3f,sizeof dist);
dist[1] = 0;
priority_queue<PII,vector<PII>,greater<PII>> q;
q.push({0,1});
while(q.size())
{
auto t = q.top();
q.pop();
if(st[t.y])continue;
st[t.y] = true;
int ver = t.y;
for(int i = head[ver];~i;i = ne[i])
{
int j = val[i];
if(dist[j] > dist[ver] + weight[i])
{
dist[j] = dist[ver] + weight[i];
q.push({dist[j],j});
}
}
}
if(dist[n] == 0x3f3f3f3f)return -1;
else return dist[n];
}
int main()
{
cin>>n>>m;
memset(head,-1,sizeof head);
while(m--)
{
int x,y,z;
cin>>x>>y>>z;
add(x,y,z);
}
cout<<heap_dijkstra()<<endl;
return 0;
}