#include #include #include #include #include using namespace std; const int maxn = 1e5 + 10; int idx[maxn], sz[maxn]; int find_root(int x) { while(idx[x] != x) { idx[x] = idx[idx[x]]; x = idx[x]; } return x; } bool is_in_the_same_union(int a, int b) { if(find_root(a) == find_root(b)) { return true; } return false; } void union_two_elems(int a, int b) { int root_a = find_root(a); int root_b = find_root(b); if(root_a != root_b) { if(sz[root_a] < sz[root_b]) { sz[root_b] += sz[root_a]; idx[root_a] = idx[root_b]; } else { sz[root_a] += sz[root_b]; idx[root_b] = idx[root_a]; } } } int main() { for(int i = 0; i < maxn; i++) { sz[i] = 1; idx[i] = i; } int n, m; cin >> n >> m; vector > > graph; for(int i = 0; i < m; i++) { int a, b, c; cin >> a >> b >> c; graph.push_back(make_pair(c, make_pair(a, b))); } sort(graph.begin(), graph.end()); int MST = 0; for(int i = 0; i < m; i++) { int c = graph[i].first; int a = graph[i].second.first; int b = graph[i].second.second; if(!is_in_the_same_union(a, b)) { union_two_elems(a, b); cout << a << " " << b << endl; MST += c; } } cout << MST << endl; return 0; }