Advertisement
maxim_shlyahtin

modified_A

May 4th, 2024
694
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <utility>
  5. #include <string>
  6. #include <limits>
  7.  
  8. // граф - ориентированный
  9. struct Vertex {
  10.     bool visited = false;
  11.     int neighbors_num;
  12. };
  13.  
  14. std::vector<char> greedy_alg(std::map<char, std::vector<std::pair<char, double>>>& graph, char start, char end) {
  15.     std::vector<char> path = {start};
  16.     std::map<char, Vertex> vertices;
  17.     double inf = std::numeric_limits<double>::max();
  18.     double minWeight = inf;
  19.     char current = start;
  20.     vertices[start].visited = true;
  21.     vertices[start].neighbors_num = graph[current].size();
  22.     while (current != end) {
  23.         if (!vertices[current].visited) {
  24.             vertices[current].neighbors_num = graph[current].size();
  25.             vertices[current].visited = true;
  26.         }
  27.         if (vertices[current].neighbors_num == 0) {
  28.             path.pop_back();
  29.             current = path[path.size() - 1];
  30.         }
  31.         char next;
  32.         for (const auto& vert : graph[current]) {
  33.             if (graph[vert.first].size() == 0 && vert.first != end) {
  34.                 vertices[current].neighbors_num--;
  35.                 continue;
  36.             }
  37.             else if (graph[vert.first].size() == 0 && vert.first == end) {
  38.                 path.push_back(end);
  39.                 return path;
  40.             }
  41.             if (vert.second < minWeight && graph[vert.first].size() > 0) {
  42.                 minWeight = vert.second;
  43.                 next = vert.first;
  44.             }
  45.         }
  46.         path.push_back(next);
  47.         minWeight = inf;
  48.         current = next;
  49.        
  50.     }
  51.     return path;
  52. }
  53.  
  54. int main() {
  55.     std::map<char, std::vector<std::pair<char, double>>> graph;
  56.     char start, end;
  57.     std::cin >> start >> end;
  58.     char from, to;
  59.     double weight;
  60.  
  61.     while (std::cin >> from >> to >> weight) {
  62.         graph[from].insert(graph[from].end(), { std::make_pair(to, weight) });
  63.     }
  64.     std::vector<char> res = greedy_alg(graph, start, end);
  65.     for (const auto& it : res) {
  66.         std::cout << it;
  67.     }
  68.     std::cout << '\n';
  69.     return 0;
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement