-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1135.cpp
More file actions
68 lines (64 loc) · 1.66 KB
/
1135.cpp
File metadata and controls
68 lines (64 loc) · 1.66 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
class Solution {
public:
struct DSU{
int *parent, *rank;
int n;
DSU(int n){
this->n = n;
parent = new int[n+1];
rank = new int[n+1];
for(int i=0;i<=n; i++){
rank[i] = 0;
parent[i] = i;
}
}
int Find(int u){
if(u!=parent[u])
parent[u] = Find(parent[u]);
return parent[u];
}
void Union(int u, int v){
u = Find(u);
v = Find(v);
if(u==v)
return;
if(rank[u]<rank[v])
swap(u,v);
parent[v] = u;
if(rank[u]==rank[v])
rank[u]++;
return;
}
bool check(){
for(int i=2; i<=n; i++){
if(Find(1)!=Find(i))
return false;
}
return true;
}
};
vector<pair<int,pair<int,int>>> edges;
int kruskal(int n){
int res = 0;
sort(edges.begin(),edges.end());
DSU ds(n);
for(auto it = edges.begin(); it!=edges.end(); it++){
int u = it->second.first;
int v = it->second.second;
u = ds.Find(u);
v = ds.Find(v);
if(u!=v){
res += it->first;
ds.Union(u,v);
}
}
if(ds.check())
return res;
return -1;
}
int minimumCost(int N, vector<vector<int>>& connections) {
for(auto arr: connections)
edges.push_back({arr[2],{arr[0],arr[1]}});
return kruskal(N);
}
};