/*堆优化版dijkstra算法*/
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
#include <vector>
using namespace std;
const int maxsize = 150005;
int n, m;
/*在邻接表里:第一个int为结点编号,第二个为边值*/
typedef pair<int, int> PII;
/*在队列里:第一个int为起点到该点的最短距离,第二个int为结点编号*/
vector<PII> graph[maxsize]; //邻接表
int dist[maxsize]; //最短距离
bool st[maxsize]; //访问flag
int dijkstra(int u)
{
priority_queue<PII, vector<PII>, greater<PII>> heap; //优先队列,距离小的在前
memset(dist, 0x3f, sizeof dist);
dist[u] = 0;
heap.push({0, 1});
while(heap.size())
{
PII temp = heap.top();
heap.pop();
int val = temp.first, vex = temp.second;
if(st[vex]) continue; //该点已经访问过了,直接重新循环
st[vex] = true;
for(int i = 0; i < graph[vex].size(); i++)
{
int j = graph[vex][i].first; //获取邻接表的顶点
if(dist[j] > val + graph[vex][i].second) //新引入点的距离+边值 小于 邻接顶点的最小距离
{
dist[j] = val + graph[vex][i].second;
heap.push({dist[j], j});
}
}
}
if(dist[n] == 0x3f3f3f3f) return -1;
else return dist[n];
}
int main()
{
int a, b, c;
ios::sync_with_stdio(false); //关掉输入输出同步
cin >> n >> m;
for(int i = 0; i < m; i++)
{
cin >> a >> b >> c;
graph[a].push_back({b, c});
}
cout << dijkstra(1) << endl;
return 0;
}
AcWing:堆优化版dijkstra算法
最新推荐文章于 2024-07-25 12:55:52 发布