Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <algorithm>
- using namespace std;
- const int maxn = 1e5 + 10;
- const int INF = 2e9;
- int n, m;
- vector<pair<int, pair<int, int>>> 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
- **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement