一、题目链接
二、题目分析
(一)算法标签
最短路 优先队列 堆优化版Dijkstra
(二)解题思路
出队时修改st数组
三、AC代码
解法一:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <climits>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
#define x first
#define y second
const int N = 1e5 + 10, M = 2e5 + 10;
int h[N], w[M], e[M], ne[M], idx;
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
int n, m, s;
int a, b, c;
bool st[N];
int dist[N];
void dijkstra()
{
// 两种方式都行
// memset(dist, 0x3f, sizeof dist);
for (int i = 1; i <= n; i ++ )
dist[i] = INT_MAX;
dist[s] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, s});
while (!heap.empty())
{
auto t = heap.top();
heap.pop();
int ver = t.y, distance = t.x;
if (st[ver]) continue;
st[ver] = true;
for (int i = h[ver]; ~i; i = ne[i])
{
int j = e[i];
if (!st[j] && dist[j] > distance + w[i])
{
dist[j] = distance + w[i];
heap.push({dist[j], j});
}
}
}
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m >> s;
for (int i = 0; i < m; i ++ )
{
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
dijkstra();
for (int i = 1; i <= n; i ++ )
// if (dist[i] == 0x3f3f3f3f) cout << INT_MAX << endl;
cout << dist[i] << ' ';
return 0;
}