题目
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int N = 100010;
typedef pair<int,int> PII;
int n,m;
int e[N],h[N],ne[N],w[N],idx = 0;//用链表的形式来定义图
int dist[N];//表示从一到当前节点的最小值
bool st[N];//判断当前节点是否被访问过
void add(int a,int b,int c)//插入边
{
w[idx] = c;
e[idx] = b;
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())
{
PII t = heap.top();
heap.pop();
int distance = t.first;//当前节点最小距离
int ver = t.second;//当前结点编号
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的值
{
dist[j] = distance + w[i];
heap.push({dist[j],j});
}
}
st[ver] = true;//标记访问过的节点
}
if(dist[n] == 0x3f3f3f3f)return -1;
else return dist[n];//返回节点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);
}
cout<<dijkstra();
return 0;
}