如果你像我一样,直接用INT_MAX来初始化dist,那你可别再加weight了
// Dijkstra algorithm
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <unordered_map>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
#include <numeric>
#include <iomanip>
#include <limits>
#include <climits>
#include <functional>
#include <utility>
using namespace std;
struct edge
{
int to;
int weight;
};
struct node
{
int id;
vector<edge> edges;
int dist;
};
#define ll long long
#define ar array
#define all(x) (x).begin(), (x).end()
#define rep(i, a, b) for (int i = (a); i < (b); ++i)
#define repr(i, a, b) for (int i = (b)-1; i >= (a); --i)
#define FAST_IO \
ios::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
int main()
{
FAST_IO;
int n, m, s;
cin >> n >> m >> s;
vector<node> nodes(n + 1);
for (int i = 1; i <= n; i++)
{
nodes[i].id = i;
}
for (int i = 0; i < m; i++)
{
int u, v, w;
cin >> u >> v >> w;
nodes[u].edges.push_back({v, w});
}
for (int i = 1; i <= n; i++)
{
nodes[i].dist = INT_MAX;
}
nodes[s].dist = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
for (int i = 1; i <= n; i++)
{
pq.push({nodes[i].dist, i});
}
while (!pq.empty())
{
auto [d, u] = pq.top();
pq.pop();
if (d != nodes[u].dist)
{
continue;
}
for (auto &edge : nodes[u].edges)
{
// 只有当 u 可达时才尝试更新
// HERE!!!
if (nodes[u].dist != INT_MAX && nodes[edge.to].dist > nodes[u].dist + edge.weight)
{
nodes[edge.to].dist = nodes[u].dist + edge.weight;
pq.push({nodes[edge.to].dist, edge.to});
}
}
}
for (int i = 1; i <= n; i++)
{
cout << nodes[i].dist << " ";
}
cout << endl;
return 0;
}