#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int, int> iPair;
struct Graph {
int V, E;//V:the number of the vertices
//E:the number of edges
vector<pair<int, iPair>> edges;
Graph(int V, int E) {
this->V = V;
this->E = E;
}
void addEdge(int x, int y, int w) {
edges.push_back({w,{x,y}});
}
int caculate_mst();
};
struct disjointSets {
vector<int> parent, rank;
int n;
disjointSets(int n){
this->n = n;
parent = vector<int>(n, -1);
rank = vector<int>(n, -1);
}
int find_root(int x) {
int x_root = x;
while (parent[x_root] != -1)
x_root = parent[x_root];
return x_root;
}
bool union_vertices(int x, int y) {
int x_root = find_root(x);
int y_root = find_root(y);
if (x_root == y_root)
return false;
else {
if (rank[x_root] > rank[y_root])
parent[y_root] = x_root;
else if (rank[y_root] > rank[x_root])
parent[x_root] = y_root;
else {
parent[x_root] = y_root;
rank[y_root] += 1;
}
}
return true;
}
};
int Graph::caculate_mst() {
int mst = 0;
disjointSets ds(V);
sort(edges.begin(), edges.end());
for (auto it = edges.begin(); it != edges.end(); it++) {
int x = it->second.first;
int y = it->second.second;
int x_root = ds.find_root(x);
int y_root = ds.find_root(y);
if (ds.union_vertices(x_root, y_root)) {
cout << x << "-" << y << endl;
mst += it->first;
}
}
return mst;
}
int main() {
int V = 9, E = 14;
Graph g(V, E);
g.addEdge(0, 1, 4);
g.addEdge(0, 7, 8);
g.addEdge(1, 2, 8);
g.addEdge(1, 7, 11);
g.addEdge(2, 3, 7);
g.addEdge(2, 8, 2);
g.addEdge(2, 5, 4);
g.addEdge(3, 4, 9);
g.addEdge(3, 5, 14);
g.addEdge(4, 5, 10);
g.addEdge(5, 6, 2);
g.addEdge(6, 7, 1);
g.addEdge(6, 8, 6);
g.addEdge(7, 8, 7);
int mst = g.caculate_mst();
cout << "mst=" << mst;
return 0;
}