Advertisement
smatskevich

Seminar9

Apr 7th, 2022
822
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <set>
  4. #include <vector>
  5.  
  6. struct Edge {
  7.   int Vertex = 0;
  8.   int Weight = 0;
  9. };
  10.  
  11. std::pair<std::vector<int>, std::vector<int>> Dijkstra(const std::vector<std::vector<Edge>>& graph, int start) {
  12.   auto result = std::make_pair(std::vector(graph.size(), std::numeric_limits<int>::max()),
  13.                                std::vector(graph.size(), -1));
  14.   auto& distance = result.first;
  15.   auto& prev = result.second;
  16.   // Для каждой вершины: расстояние и номер вершины
  17.   std::set<std::pair<int, int>> q;
  18. //  std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<>> q;
  19.   q.insert({0, start});
  20.   distance[start] = 0;
  21.   while (!q.empty()) {
  22.     auto it = q.begin();
  23.     int u = it->second;
  24.     q.erase(it);
  25.  
  26.     for (auto e : graph[u]) {
  27.       int v = e.Vertex;
  28.       if (distance[u] + e.Weight < distance[v]) {
  29.         auto itv = q.find({distance[v], v});
  30.         if (itv != q.end()) q.erase(itv);
  31.  
  32.         distance[v] = distance[u] + e.Weight;
  33.         prev[v] = u;
  34.         q.insert({distance[v], v});
  35.       }
  36.     }
  37.   }
  38.   return result;
  39. }
  40.  
  41. /*
  42. 7
  43. 10
  44. 1 6 14
  45. 1 3 9
  46. 1 2 7
  47. 2 3 10
  48. 3 6 2
  49. 6 5 9
  50. 2 4 15
  51. 3 4 11
  52. 4 5 6
  53. 5 4 6
  54. */
  55.  
  56. int main1() {
  57.   int n = 0; std::cin >> n;
  58.   // Для каждой вершины храним пару
  59.   std::vector<std::vector<Edge>> graph(n);
  60.   int edges_count = 0; std::cin >> edges_count;
  61.   for (int i = 0; i < edges_count; ++i) {
  62.     int u, v, weight; std::cin >> u >> v >> weight;
  63.     graph[u].push_back({v, weight});
  64.   }
  65.  
  66.   auto [d, prev] = Dijkstra(graph, 1);
  67.   for (int value : d) std::cout << value << " ";
  68.   std::cout << std::endl;
  69.   for (int value : prev) std::cout << value << " ";
  70.   std::cout << std::endl;
  71.   return 0;
  72. }
  73.  
  74. class DSU {
  75.  public:
  76.   explicit DSU(size_t n) : parent(n) {
  77.     for (int i = 0; i < n; ++i) parent[i] = i;
  78.   }
  79.   int Find(int v) {
  80.     return (parent[v] == v) ? v : (parent[v] = Find(parent[v]));
  81.   }
  82.   void Union(int u, int v) {
  83.     parent[v] = u;
  84.   }
  85.  private:
  86.   std::vector<int> parent;
  87. };
  88.  
  89. int main() {
  90.  
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement