Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <set>
- using std::vector;
- using std::pair;
- namespace constants {
- int kInf = 1e9;
- }
- class Graph {
- public:
- explicit Graph() = default;
- explicit Graph(int n, int m) : num_of_vertexes_(n), num_of_edges_(m),
- neighbours_(vector<vector<pair<int, int>>>(n)) {
- for (int i = 0; i < m; ++i) {
- int first;
- int second;
- int weight;
- std::cin >> first >> second >> weight;
- AddEdge(first, second, weight);
- }
- }
- void AddEdge(int first, int second, int weight) {
- neighbours_[first - 1].push_back({second - 1, weight});
- neighbours_[second - 1].push_back({first - 1, weight});
- }
- int GetNumOfVertexes() const {
- return num_of_vertexes_;
- }
- vector<vector<pair<int, int>>> GetNeighbours() const {
- return neighbours_;
- }
- private:
- int num_of_vertexes_;
- int num_of_edges_;
- vector<vector<pair<int, int>>> neighbours_;
- };
- struct MSTBuilder {
- virtual void GetMST(Graph&) = 0;
- };
- struct PrimoBuildMST : MSTBuilder {
- int result = 0;
- void GetMST(Graph& graph) override {
- int n = graph.GetNumOfVertexes();
- vector<int> min_e (n, constants::kInf);
- vector<vector<std::pair<int, int>>> g = graph.GetNeighbours();
- min_e[0] = 0;
- vector<bool> used(n, false);
- std::set<pair<int, int>> q;
- q.insert({0, 0});
- while (!q.empty()) {
- int v = q.begin()->second;
- used[v] = true;
- result += q.begin()->first;
- q.erase(q.begin());
- for (auto e : g[v]) {
- int u = e.first;
- int w = e.second;
- if (w < min_e[u] and !used[u]) {
- q.erase({min_e[u], u});
- min_e[u] = w;
- q.insert({min_e[u], u});
- }
- }
- }
- }
- };
- int main() {
- int n;
- int m;
- std::cin >> n >> m;
- Graph graph(n, m);
- PrimoBuildMST primo;
- primo.GetMST(graph);
- std::cout << primo.result << "\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement