Dijkstra?
Problem - 20C - Codeforces
思路:
用dijkstra算法,在更新最短距离的时候在加一个存点的步骤,最后输出就可以了
p[i]是i的上一个点
完整代码:
cpp
#include <bits/stdc++.h>
#define int long long
#define PII std::pair<int,int>
const int N = 1e5 + 10;
int p[N];
signed main() {
int n, m;
int k = 0;
std::cin >> n >> m;
std::vector<std::vector<PII>> g(n + 1);
std::vector<int> dist(n + 1, LLONG_MAX);
std::vector<bool> vis(n + 1);
dist[1] = 0;
for (int i = 1; i <= m; i++) {
int u, v, w;
std::cin >> u >> v >> w;
g[u].push_back({v, w});
g[v].push_back({u, w});
}
std::priority_queue<PII, std::vector<PII >, std::greater<>> q;
q.push({0, 1});//存dist和点
while (!q.empty()) {
auto node = q.top();
q.pop();
int cur = node.second;
if (vis[cur] == true)
continue;
vis[cur] = true;
for (int i = 0; i < g[cur].size(); i++) {
int e = g[cur][i].first;
int w = g[cur][i].second;
if (dist[e] > dist[cur] + w) {
p[e] = cur;//从cur走到e
dist[e] = dist[cur] + w;
q.push({dist[e], e});
}
}
}
if(dist[n]==LLONG_MAX)
std::cout<<-1;
else {
std::vector<int> a(n + 1);
for (int i = n; i != 1; i = p[i]) {
a[k++] = i;
}
std::cout << 1 << " ";
for (int i = k - 1; i >= 0; i--) {
std::cout << a[i] << " ";
}
}
// std::cout<<dist[n];
return 0;
}