Advertisement
maxim_shlyahtin

A*_1

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