fork download
  1.  
  2. #include <iostream>
  3. #include <vector>
  4. #include <queue>
  5. #include <map>
  6. #include <string>
  7. #include <climits>
  8.  
  9. using namespace std;
  10.  
  11. map<string, vector<string>> listG;
  12. map<string, int> color;
  13. map<string, int> dis;
  14. map<string, string> parent;
  15. vector<string> points;
  16.  
  17. void addPoint(string name) {
  18. if (listG.find(name) == listG.end()) {
  19. listG[name] = vector<string>();
  20. points.push_back(name);
  21. color[name] = -1;
  22. dis[name] = INT_MAX;
  23. }
  24. }
  25.  
  26. void listInput(int e) {
  27. string u, v;
  28. for (int i = 0; i < e; i++) {
  29. cin >> u >> v;
  30. addPoint(u);
  31. addPoint(v);
  32. listG[u].push_back(v);
  33. listG[v].push_back(u);
  34. }
  35. }
  36.  
  37. void BFS(string s) {
  38. queue<string> Q;
  39. Q.push(s);
  40. color[s] = 0;
  41. dis[s] = 0;
  42.  
  43. while (!Q.empty()) {
  44. string u = Q.front();
  45. Q.pop();
  46.  
  47. for (int i = 0; i < listG[u].size(); i++) {
  48. string v = listG[u][i];
  49. if (color[v] == -1) {
  50. Q.push(v);
  51. color[v] = 0;
  52. dis[v] = dis[u] + 1;
  53. parent[v] = u;
  54. }
  55. }
  56. color[u] = 1;
  57. }
  58. }
  59.  
  60. void printRoute(string point, string source) {
  61. vector<string> route;
  62. string current = point;
  63.  
  64. while (current != source) {
  65. route.push_back(current);
  66. current = parent[current];
  67. }
  68. route.push_back(source);
  69.  
  70. for (int i = 0; i < route.size(); i++) {
  71. cout << route[i];
  72. if (i != route.size() - 1) {
  73. cout << " -> ";
  74. }
  75. }
  76. }
  77.  
  78. int main() {
  79. int n, e;
  80.  
  81.  
  82. cout << "Enter total points and edges: ";
  83. if (!(cin >> n >> e)) return 0;
  84.  
  85. listInput(e);
  86.  
  87. while (points.size() < (size_t)n) {
  88. string name;
  89. cin >> name;
  90. addPoint(name);
  91. }
  92.  
  93. string word, source;
  94. cin >> word >> source;
  95. addPoint(source);
  96.  
  97. BFS(source);
  98.  
  99. cout << "\n--------------------------------------------------\n";
  100. cout << "Campus Emergency Route Results\n";
  101. cout << "Assembly Point: " << source << "\n";
  102. cout << "--------------------------------------------------\n";
  103.  
  104. for (int i = 0; i < points.size(); i++) {
  105. string point = points[i];
  106.  
  107. if (point == source) {
  108. continue;
  109. }
  110.  
  111. cout << "Point: " << point << " ";
  112.  
  113. if (color[point] == -1) {
  114. cout << "Reachable: No Steps: - Route: No path exists" << endl;
  115. } else {
  116. cout << "Reachable: Yes Steps: " << dis[point] << " Route: ";
  117. printRoute(point, source);
  118. cout << endl;
  119. }
  120. }
  121.  
  122. return 0;
  123. }
  124.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Enter total points and edges: