对于稀疏图。
#include <cstring>
#include <iostream>
#include <algorithm>
#include<queue>
using namespace std;
typedef pair<int,int> PII;//距离,点
const int N = 2e5;
int n, m;
//邻接表
int h[N],w[N],e[N],ne[N],idx;//w是距离权重
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();
int ver=t.second,distance=t.first;
if(st[ver]) continue;//ver已经出来过了,说明当前这个点是冗余备份,就跳过。
st[ver]=true;
for(int i=h[ver];i!=-1;i=ne[i]){
int j=e[i];
if(dist[j]>dist[ver]+w[i]){
dist[j]=dist[ver]+w[i];
heap.push({dist[j],j});//类似于宽搜
}
}
}
if (dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m -- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a,b,c);//重边无所谓,也会找最短的
}
printf("%d\n", dijkstra());
return 0;
}