Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- struct Edge {
- int weight;
- int from;
- int to;
- };
- class CGraph {
- public:
- CGraph(int size) : rank(size, 0), cheapest(size, -1), size(size) {
- parent.resize(size);
- for (int i = 0; i < size; ++i) {
- parent[i] = i;
- }
- components_num = size;
- };
- ~CGraph() {};
- void add(Edge temp) {
- edges.push_back(temp);
- }
- int find_root(int vertex) {
- if (parent[vertex] == vertex) {
- return vertex;
- }
- return parent[vertex] = find_root(parent[vertex]);
- }
- void union_set(int a, int b) {
- a = find_root(a);
- b = find_root(b);
- if (a != b) {
- if (rank[a] < rank[b]) {
- swap(a, b);
- }
- parent[b] = a;
- if (rank[a] == rank[b]) {
- ++rank[a];
- }
- }
- }
- int count_mst_weight() {
- while (components_num > 1) {
- for (int i = 0; i < edges.size(); ++i) {
- int pupa = find_root(edges[i].from);
- int lupa = find_root(edges[i].to);
- if (pupa != lupa) { //вроде это должно работать но сэмпл выдает 5
- if (cheapest[pupa] == -1 || (edges[cheapest[pupa]].weight >= edges[i].weight && edges[cheapest[pupa]].to < cheapest[pupa])) {
- cheapest[pupa] = i;
- }
- if (cheapest[lupa] == -1 || (edges[cheapest[lupa]].weight >= edges[i].weight && edges[cheapest[lupa]].to < cheapest[lupa])) {
- cheapest[lupa] = i;
- }
- }
- }
- for (int i = 0; i < size; ++i) {
- if (cheapest[i] != -1) {
- int pupa = find_root(edges[cheapest[i]].from);
- int lupa = find_root(edges[cheapest[i]].to);
- if (pupa != lupa) {
- mst_weight += edges[cheapest[i]].weight;
- union_set(pupa, lupa);
- --components_num;
- }
- }
- }
- }
- return mst_weight;
- }
- private:
- vector<int> cheapest;
- vector<Edge> edges;
- vector<int> parent;
- vector<int> rank;
- int components_num;
- int size;
- int mst_weight = 0;
- };
- int main() {
- int n, m;
- cin >> n >> m;
- CGraph graph(n);
- for (int i = 0; i < m; ++i) {
- Edge temp;
- cin >> temp.from >> temp.to >> temp.weight;
- --temp.from;
- --temp.to;
- graph.add(temp);
- }
- cout << graph.count_mst_weight();
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement