#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 1e6 + 10;
int n, m, s;
int e[N], ne[N], hh[N], idx, we[N];
int d[N]; //存储最短路
bool f[N]; //表示最短路已经确定
void add(int x, int y, int z)
{
e[idx] = y;
we[idx] = z;
ne[idx] = hh[x];
hh[x] = idx++;
}
void dijkstra()
{
memset(d, 0x3f3f3f3f, sizeof d);
d[s] = 0;
priority_queue<PII, vector<PII>, greater<PII>> h;
h.push({0, s}); //first 距离 second 点
while (!h.empty())
{
auto t = h.top();
h.pop();
int dd = t.first, vv = t.second;
if (f[vv])
continue;
f[vv] = 1;
for (int i = hh[vv]; i != -1; i = ne[i])
{
int j = e[i];
if (d[j] > dd + we[i])
{
d[j] = dd + we[i];
h.push({d[j], j});
}
}
}
}
void run()
{
int u, v, w;
memset(hh, -1, sizeof hh);
cin >> n >> m >> s;
while (m--)
{
cin >> u >> v >> w;
add(u, v, w);
}
dijkstra();
for(int i = 1; i <= n; i ++)
{
if(d[i] == 0x3f3f3f3f) cout << 2147483647 << " ";
else cout << d[i] << " ";
}
}
int main()
{
freopen("in.in", "r", stdin);
freopen("out.out", "w", stdout);
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
run();
return 0;
}
洛谷 P4779 【模板】单源最短路径
最新推荐文章于 2022-07-17 16:55:19 发布
该博客介绍了如何使用C++实现Dijkstra算法,解决带权重的图中从源点到其他节点的最短路径问题。通过`std`库和自定义数据结构,博主展示了如何构建图、添加边和权重,并详细解释了Dijkstra算法的工作原理和优先队列的使用。
摘要由CSDN通过智能技术生成