1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| #include <iostream> #include <fstream> #include <vector> #include <unordered_map> #include <set> #include <limits>
using namespace std;
// 城市结构 struct City { string name; unordered_map<string, pair<int, int>> neighbors; // 与该城市相邻的其他城市 -> {费用, 距离} };
// 图类 class Graph { public: // 向图中添加城市 void addCity(const string& cityName) { if (cities.find(cityName) == cities.end()) { cities[cityName] = City{cityName, unordered_map<string, pair<int, int>>()}; } }
// 向图中添加路线 void addRoute(const string& city1, const string& city2, int cost, int distance) { cities[city1].neighbors[city2] = {cost, distance}; cities[city2].neighbors[city1] = {cost, distance}; }
// 使用Dijkstra算法找到两个城市之间的最低费用路径 pair<int, string> shortestPath(const string& start, const string& end) { unordered_map<string, int> dist; // 距离映射 unordered_map<string, string> prev; // 前一个城市映射 set<pair<int, string>> queue; // 用于排序的队列
for (auto& pair : cities) { if (pair.first == start) { dist[pair.first] = 0; } else { dist[pair.first] = numeric_limits<int>::max(); } queue.insert({dist[pair.first], pair.first}); }
while (!queue.empty()) { string current = queue.begin()->second; queue.erase(queue.begin());
for (auto& neighbor : cities[current].neighbors) { int alt = dist[current] + neighbor.second.first; // 以费用为优先级 if (alt < dist[neighbor.first]) { queue.erase({dist[neighbor.first], neighbor.first}); dist[neighbor.first] = alt; prev[neighbor.first] = current; queue.insert({dist[neighbor.first], neighbor.first}); } } }
// 构建路径 string city = end; string path = end; while (prev.find(city) != prev.end()) { path = prev[city] + " -> " + path; city = prev[city]; }
return {dist[end], path}; }
private: unordered_map<string, City> cities; // 城市映射 };
int main() { Graph graph;
// 从文件中读取城市数据 ifstream infile("D:\\Learn\\CPP2\\services.txt"); string city1, city2; int cost, distance;
while (infile >> city1 >> city2 >> cost >> distance) { graph.addCity(city1); graph.addCity(city2); graph.addRoute(city1, city2, cost, distance); } infile.close();
// 输入起始城市和目标城市 string start, end; cout << "Enter a start and destination city: "; cin >> start >> end;
// 查找最短路径并打印 auto result = graph.shortestPath(start, end); cout << "The cheapest route from " << start << " to " << end << " costs " << result.first << " euros." << endl; cout << "Route: " << result.second << endl;
return 0; }
|