dijkstra算法用来处理无负权边的图,是单源最短路的算法
对于自环,因为是非负权边,所以不用考虑,不会走的
对于重边,在加入数组时,应仅加入最小的那条边
朴素版dijkstra算法一般用在稠密图,时间复杂度是O(n^2 + m),稠密图也就是边数m ~ 点数n^2级别的图
#pragma optimize(2)
#include<bits/stdc++.h>
#include<unordered_map>
#define endl '\n'
#define int int64_t
using namespace std;
const int N = 1e4 + 10;
struct edge { int v, w; };
vector<edge>e[N];
int d[N],vis[N],m,n,s;
void dijkstra(int s) {
for (int i = 0; i <= n; ++i) d[i] = INT_MAX;
d[s] = 0;
for (int i = 0; i < n; ++i) {
int u = 0;
for (int j = 1; j <= n; ++j)
if (!vis[j] && d[u] > d[j]) u = j;
vis[u] = 1;//出圈
for (auto k : e[u]) {
int v = k.v, w = k.w;
d[v] = min(d[v], d[u] + w);
}
}
}
signed main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m >> s;
for (int i = 1; i <= m; ++i) {
int a, b, c; cin >> a >> b >> c;
e[a].push_back({ b,c });
}
dijkstra(s);
for (int i = 1; i <= n; ++i) cout << d[i] << " ";
return 0;
}