Advertisement
den4ik2003

Untitled

Nov 7th, 2023
535
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <set>
  4.  
  5. using std::vector;
  6. using std::pair;
  7.  
  8. namespace constants {
  9. int kInf = 1e9;
  10. }
  11.  
  12. class Graph {
  13.  public:
  14.   explicit Graph() = default;
  15.  
  16.   explicit Graph(int n, int m) : num_of_vertexes_(n), num_of_edges_(m),
  17.                                  neighbours_(vector<vector<pair<int, int>>>(n)) {
  18.     for (int i = 0; i < m; ++i) {
  19.       int first;
  20.       int second;
  21.       int weight;
  22.       std::cin >> first >> second >> weight;
  23.       AddEdge(first, second, weight);
  24.     }
  25.   }
  26.  
  27.   void AddEdge(int first, int second, int weight) {
  28.     neighbours_[first - 1].push_back({second - 1, weight});
  29.     neighbours_[second - 1].push_back({first - 1, weight});
  30.   }
  31.  
  32.   int GetNumOfVertexes() const {
  33.     return num_of_vertexes_;
  34.   }
  35.  
  36.   vector<vector<pair<int, int>>> GetNeighbours() const {
  37.     return neighbours_;
  38.   }
  39.  
  40.  private:
  41.   int num_of_vertexes_;
  42.   int num_of_edges_;
  43.   vector<vector<pair<int, int>>> neighbours_;
  44. };
  45.  
  46. struct MSTBuilder {
  47.   virtual void GetMST(Graph&)  = 0;
  48. };
  49.  
  50. struct PrimoBuildMST : MSTBuilder {
  51.   int result = 0;
  52.  
  53.   void GetMST(Graph& graph) override {
  54.     int n = graph.GetNumOfVertexes();
  55.     vector<int> min_e (n, constants::kInf);
  56.     vector<vector<std::pair<int, int>>> g = graph.GetNeighbours();
  57.     min_e[0] = 0;
  58.     vector<bool> used(n, false);
  59.     std::set<pair<int, int>> q;
  60.     q.insert({0, 0});
  61.     while (!q.empty()) {
  62.       int v = q.begin()->second;
  63.       used[v] = true;
  64.       result += q.begin()->first;
  65.       q.erase(q.begin());
  66.       for (auto e : g[v]) {
  67.         int u = e.first;
  68.         int w = e.second;
  69.         if (w < min_e[u] and !used[u]) {
  70.           q.erase({min_e[u], u});
  71.           min_e[u] = w;
  72.           q.insert({min_e[u], u});
  73.         }
  74.       }
  75.     }
  76.   }
  77. };
  78.  
  79. int main() {
  80.   int n;
  81.   int m;
  82.   std::cin >> n >> m;
  83.   Graph graph(n, m);
  84.   PrimoBuildMST primo;
  85.   primo.GetMST(graph);
  86.   std::cout << primo.result << "\n";
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement