CCCPaste

Untitled

#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 1e5 + 10;
const int INF = 2e9;
int n, m;
vector>> graph;
int idx[maxn], sz[maxn];
int root(int x) {
    while(x != idx[x]) {
        idx[x] = idx[idx[x]];
        x = idx[x];
    }
    return x;
}
void join(int a, int b) {
    int root_a = root(a), root_b = 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() {
    cin >> n >> m;
    for(int i = 1; i <= n; i++) {
        sz[i] = 1;
        idx[i] = i;
    }
    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 a = graph[i].second.first;
        int b = graph[i].second.second;
        int c = graph[i].first;
        
        if(root(a) != root(b)) {
            join(a, b);
            mst += c;
        }
    }
    cout << mst << endl;
    return 0;
}
/*
 6 9
 5 4 9
 5 1 4
 1 4 1
 1 2 2
 2 4 3
 2 3 3
 2 6 7
 3 6 8
 4 3 5
 
 **/