#include <bits/stdc++.h>
using namespace std;
struct Node {
string name; // 当前站点名称
int cost; // 起点到当前站点的总耗时
vector<string> path; // 起点到当前站点的路径
};
int main() {
int n;
cin >> n;
string start, end;
cin >> start >> end;
// 图的邻接表
unordered_map<string, vector<pair<string, int>>> graph;
string u, v;
int time;
while (cin >> u && u != "0000") {
cin >> v >> time;
graph[u].push_back({v, time});
graph[v].push_back({u, time}); // 双向图
}
// Lambda 比较器
auto cmp = [](const Node& n1, const Node& n2) {
return n1.cost > n2.cost;
};
// 优先队列,使用 lambda 初始化
priority_queue<Node, vector<Node>, decltype(cmp)> pq(cmp);
// 起点初始化
pq.push({start, 0, {start}});
// 最短路径记录
unordered_map<string, int> minCost;
for (auto& it : graph) {
minCost[it.first] = INT_MAX;
}
minCost[start] = 0;
// Dijkstra 算法
while (!pq.empty()) {
Node cur = pq.top();
pq.pop();
string currStation = cur.name;
int currCost = cur.cost;
// 到达终点,输出路径
if (currStation == end) {
for (int i = 0; i < cur.path.size(); i++) {
if (i > 0) cout << " ";
cout << cur.path[i];
}
cout << endl;
return 0;
}
// 遍历邻居
for (auto& neighbor : graph[currStation]) {
string nextStation = neighbor.first;
int nextCost = neighbor.second;
if (currCost + nextCost < minCost[nextStation]) {
minCost[nextStation] = currCost + nextCost;
vector<string> newPath = cur.path;
newPath.push_back(nextStation);
pq.push({nextStation, minCost[nextStation], newPath});
}
}
}
return 0;
}
地铁耗时最短的线路
最新推荐文章于 2025-04-24 17:12:27 发布