#include <bits/stdc++.h>
#define MAXNODENUMBER 100
using namespace std;
typedef pair<int, int> PII; // 第一个int保存顶点编号 第二个int保存距离
struct edge {
int destination;
int weight;
edge(int destination_, int weight_) {
destination = destination_;
weight = weight_;
}
};
struct compare {
bool operator()(PII lhs, PII rhs) {
return lhs.second > rhs.second;
}
};
vector<edge> graph[MAXNODENUMBER];
vector<int> Dist(MAXNODENUMBER, -1);
vector<int> State(MAXNODENUMBER, 0);
void djikstra(int s) {
priority_queue<PII, vector<PII>, compare> pq;
pq.push({s, 0});
Dist[s] = 0;
while (!pq.empty()) {
PII cur = pq.top();
pq.pop();
if (State[cur.first] == 1) continue;
else State[cur.first] = 1;
for (edge nextEdge: graph[cur.first]) {
if (Dist[nextEdge.destination] > Dist[cur.first] + nextEdge.weight || Dist[nextEdge.destination] == -1) {
Dist[nextEdge.destination] = Dist[cur.first] + nextEdge.weight;
pq.push({nextEdge.destination, Dist[nextEdge.destination]});
}
}
}
}
int main() {
int n, m, s;
cin >> n >> m >> s;
// 建图
for (int i = 0; i < m; ++i) {
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back(edge(v, w));
graph[v].push_back(edge(u, w));
}
djikstra(s);
for (int i = 0; i < n; ++i) {
cout << Dist[i];
if (i != n - 1) cout << " ";
}
return 0;
}
算法—Dijkstra
Dijkstra算法介绍
最新推荐文章于 2025-11-07 13:33:06 发布
3530

被折叠的 条评论
为什么被折叠?



