Advertisement
maxim_shlyahtin

A

May 2nd, 2024
643
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 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. using Graph = std::map<std::pair<char, char>, double>;
  10. using Neighbors = std::map<char, std::vector<char>>;
  11. Graph edges;
  12. Neighbors vertices;
  13.  
  14. std::vector<char> greedy_alg(char start, char end) {
  15.     std::vector<char> previous;
  16.     std::vector<char> path;
  17.     previous.push_back(start);
  18.     char current = start;
  19.     double inf = std::numeric_limits<double>::infinity();
  20.     double minWeight = inf;
  21.     while(current != end){
  22.         if (vertices[current].empty()) {
  23.             previous.pop_back();
  24.             char tmp = current;
  25.             current = previous[previous.size() - 1];
  26.             vertices[current].erase(std::remove(vertices[current].begin(), vertices[current].end(), tmp), vertices[current].end());
  27.             continue;
  28.         }
  29.         char tmp_v;
  30.         for (const auto& vert : vertices[current]) {
  31.             if (edges[std::make_pair(current, vert)] < minWeight) {
  32.                 minWeight = edges[std::make_pair(current, vert)];
  33.                 tmp_v = vert;
  34.             }
  35.         }
  36.         previous.push_back(tmp_v);
  37.         minWeight = inf;
  38.         current = previous[previous.size() - 1];
  39.         path.push_back(current);
  40.     }
  41.     return previous;
  42. }
  43.  
  44. int  main() {
  45.     char start, end;
  46.     std::cin >> start >> end;
  47.     char v_st, v_end;
  48.     double weight;
  49.     while (std::cin >> v_st >> v_end >> weight) {
  50.         edges[std::make_pair(v_st, v_end)] = weight;
  51.        
  52.         vertices[v_st].insert(vertices[v_st].end(), { v_end });
  53.     }
  54.     std::vector<char> res = greedy_alg(start, end);
  55.     for (const auto& it : res) {
  56.         std::cout << it;
  57.     }
  58.     std::cout << '\n';
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement