Files
Data-Structure/Exercise/Homework7/Q3Dij.cpp
2025-12-08 22:54:52 +08:00

71 lines
1.9 KiB
C++

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int INF = 1e9;
vector<vector<pair<int, int>>> adj;
vector<int> dist;
vector<bool> vis;
vector<vector<int>> path;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
bool lessthan(vector<int> a, vector<int> b) {
for(int i = 0; i < min(a.size(), b.size()); i++) {
if(a[i] < b[i]) return true;
if(a[i] > b[i]) return false;
}
return a.size() < b.size();
}
int main() {
int n, m;
cin >> n >> m;
adj.resize(n + 1);
dist.resize(n + 1, INF);
vis.resize(n + 1, false);
path.resize(n + 1);
for(int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
adj[a].push_back(make_pair(b, c));
}
dist[0] = 0;
path[0].push_back(0);
pq.push(make_pair(0, 0));
while(!pq.empty()) {
int u = pq.top().second;
pq.pop();
if(vis[u]) continue;
vis[u] = true;
for(auto [v, w] : adj[u]) {
if(dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
path[v] = path[u];
path[v].push_back(v);
pq.push(make_pair(dist[v], v));
}
else if(dist[v] == dist[u] + w) {
vector<int> new_path = path[u];
new_path.push_back(v);
if(path[v].empty() || path[v].size() > new_path.size() ||
(path[v].size() == new_path.size() && lessthan(new_path, path[v]))) {
path[v] = new_path;
pq.push(make_pair(dist[v], v));
}
}
}
}
for(int i = 1; i < n; i++) {
if(dist[i] != INF && !path[i].empty()) {
for(int j = 0; j < path[i].size(); j++) {
if(j > 0) cout << "->";
cout << path[i][j];
}
cout << endl;
}
}
return 0;
}