题解
2026-08-13 13:59:38
发布于:江苏
1阅读
0回复
0点赞
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const long long INF = 1e18;
vector<vector<pair<int, int>>> adj;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
if (!(cin >> n >> m)) return 0;
adj.resize(n + 1);
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
vector<long long> dist(n + 1, INF);
vector<int> pre(n + 1, -1);
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;
dist[1] = 0;
pq.push({0, 1});
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
if (d > dist[u]) continue;
for (auto [v, w] : adj[u]) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pre[v] = u;
pq.push({dist[v], v});
}
}
}
if (dist[n] == INF) {
cout << -1 << endl;
} else {
vector<int> path;
int curr = n;
while (curr != -1) {
path.push_back(curr);
curr = pre[curr];
}
reverse(path.begin(), path.end());
for (int i = 0; i < path.size(); i++) {
cout << path[i] << " ";
}
cout << endl;
}
return 0;
}
这里空空如也




有帮助,赞一个