-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinal_lab3.cpp
More file actions
70 lines (55 loc) · 1.36 KB
/
Copy pathfinal_lab3.cpp
File metadata and controls
70 lines (55 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <bits/stdc++.h>
using namespace std;
class DSU{
vector<int> parent, rank;
public:
DSU(int n){
parent.resize(n);
rank.resize(n);
for(int i = 0; i < n; i++){
parent[i] = i;
rank[i] = 1;
}
}
int find(int i){
if(parent[i] == i){
return i;
}
else{
parent[i] = find(parent[i]);
return parent[i];
}
}
void unite(int x, int y){
int s1 = find(x), s2 = find(y);
if(s1 != s2){
if (rank[s1] < rank[s2]) parent[s1] = s2;
else if (rank[s1] > rank[s2]) parent[s2] = s1;
else parent[s2] = s1, rank[s1]++;
}
}
};
bool comparator(vector<int> &a,vector<int> &b){
return a[2] < b[2];
}
int kruskalsMST(int V, vector<vector<int>> &edges){
sort(edges.begin(), edges.end(),comparator);
DSU dsu(V);
int cost = 0, count = 0;
for(auto &e : edges){
int x = e[0], y = e[1], w = e[2];
if(dsu.find(x) != dsu.find(y)){
dsu.unite(x, y);
cost += w;
if (++count == V - 1) break;
}
}
return cost;
}
int main(){
vector<vector<int>> edges ={
{0, 1, 10}, {1, 3, 15}, {2, 3, 4}, {2, 0, 6}, {0, 3, 5}
};
cout << kruskalsMST(4, edges);
return 0;
}