#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+10,INF = 0x3f3f3f3f;
int w[N],ne[N],e[N],h[N],idx;
int n,m,dist[N];
bool st[N];
typedef pair<int,int>PII;
priority_queue<PII,vector<PII>,greater<PII>>heap;
void add(int x,int y,int z){
ne[idx] = h[x];e[idx] = y;
w[idx] = z;h[x] = idx++;
}
int main(){
memset(h,-1,sizeof h);
memset(dist,INF,sizeof dist);
scanf("%d%d",&n,&m);
for(int i = 1;i<=m;i++){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
}
dist[1] = 0;
heap.push({0,1});
while(heap.size()){
auto t = heap.top();
heap.pop();
int pos = t.second;int d = t.first;
if(st[pos]==true)continue;
st[pos] = true;
for(int i = h[pos];i!=-1;i = ne[i]){
int j = e[i];
if(dist[j]>d+w[i]){
dist[j] = d+w[i];
heap.push({dist[j],j});
}
}
}
if(dist[n]==INF)cout<<-1;
else cout<<dist[n];
}
堆优化dijkstra
于 2024-07-30 15:16:12 首次发布