Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- using namespace std;
- const int maxn = 105;
- int sz[maxn], idx[maxn];
- void init() {
- for(int i = 0; i < maxn; i++) {
- idx[i] = i;
- sz[i] = 1;
- }
- }
- int root(int x) {
- while(x != idx[x]) {
- idx[x] = idx[idx[x]];
- x = idx[x];
- }
- return x;
- }
- void unite(int A, int B) {
- int rootA = root(A);
- int rootB = root(B);
- if(rootA != rootB) {
- if(sz[rootA] < sz[rootB]) {
- idx[rootA] = idx[rootB];
- sz[rootB] += sz[rootA];
- }
- else {
- idx[rootB] = idx[rootA];
- sz[rootA] += sz[rootB];
- }
- }
- }
- bool check(int A, int B) {
- return root(A) == root(B);
- }
- int main() {
- ios_base::sync_with_stdio(false);
- int n, m;
- cin >> n >> m;
- vector<pair<int, pair<int, int>>> graph;
- for(int i = 0; i < m; i++) {
- int a, b, c;
- cin >> a >> b >> c;
- graph.push_back({c, {a, b}});
- }
- sort(graph.begin(), graph.end());
- int mst = 0;
- init();
- 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(!check(A, B)) {
- unite(A, B);
- mst += C;
- }
- }
- cout << mst << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment