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 {
- const long long kInf = 1e18;
- }
- class Graph {
- public:
- explicit Graph() = default;
- explicit Graph(int n, int m) : num_of_vertexes_(n), num_of_edges_(m), cheapest_vertex(0),
- neighbours_(vector<vector<pair<int, long long>>>(n)) {
- vector<long long> input_vertexes(n);
- for (int i = 0; i < n; ++i) {
- std::cin >> input_vertexes[i];
- if (input_vertexes[i] < input_vertexes[cheapest_vertex]) {
- cheapest_vertex = i;
- }
- }
- for (int i = 0; i < n; ++i) {
- if (i != cheapest_vertex) {
- AddEdge(cheapest_vertex + 1, i + 1, input_vertexes[cheapest_vertex] + input_vertexes[i]);
- }
- }
- for (int i = 0; i < m; ++i) {
- int first, second;
- long long weight;
- std::cin >> first >> second >> weight;
- AddEdge(first, second, weight);
- }
- }
- int GetCheapestVertex() {
- return cheapest_vertex;
- }
- void AddEdge(int first, int second, long long 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, long long>>> GetNeighbours() const {
- return neighbours_;
- }
- private:
- int num_of_vertexes_;
- int num_of_edges_;
- int cheapest_vertex;
- vector<vector<pair<int, long long>>> neighbours_;
- };
- struct MSTBuilder {
- virtual void GetMST(Graph&) = 0;
- };
- struct PrimoBuildMST : MSTBuilder {
- long long result = 0;
- void GetMST(Graph& graph) override { // часть этого кода позаимствована с e-maxx.ru, но там была неработающая версия + исрпавил ошибку
- int n = graph.GetNumOfVertexes();
- std::set<std::pair<long long, int>> s;
- s.insert({0, graph.GetCheapestVertex()});
- vector<vector<pair<int, long long>>> neighbours = graph.GetNeighbours();
- vector<bool> used(n, false);
- vector<long long> cheapest_edge(n, constants::kInf);
- cheapest_edge[graph.GetCheapestVertex()] = 0;
- for (int i = 0; i < n; ++i) {
- int open_v = s.begin()->second;
- used[open_v] = true;
- result += s.begin()->first;
- s.erase(s.begin());
- for (auto neigh : neighbours[open_v]) {
- int to = neigh.first;
- long long edge = neigh.second;
- if (edge < cheapest_edge[to] and !used[to]) {
- s.erase({cheapest_edge[to], to});
- cheapest_edge[to] = edge;
- s.insert({edge, to});
- }
- }
- }
- }
- };
- 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