-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkruskalsAlgo.cpp
98 lines (70 loc) · 1.26 KB
/
kruskalsAlgo.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//Bismillahir Rahman-ir Rahim
#include <bits/stdc++.h>
using namespace std;
#define debug(x) cout << '>' << #x << " : " << x << endl;
#define all(c) c.begin(), c.end()
#define F first
#define S second
typedef unsigned long long ull;
typedef long long ll;
vector <int> parent, siz;
void makeSet(int v){
parent[v] = v;
siz[v] = 1;
}
int findSet(int v){
if(parent[v] == v){
return v;
}
return parent[v] = findSet(parent[v]);
}
void unionSet(int a, int b){
a = findSet(a);
b = findSet(b);
if(a!=b){
if(siz[a] < siz[b]){
swap(a, b);
}
parent[b] = a;
siz[a] += siz[b];
}
}
struct Edge
{
int u, v, w;
Edge(int uu, int vv, int ww): u(uu), v(vv), w(ww){}
// same as
// Edge(int uu, int vv, int ww){
// uu = u;
// vv = v;
// ww = w;
// }
bool operator < (const Edge& other) const{
return w < other.w;
}
};
vector <Edge> graph;
int mst(int numberOfNode){
sort(graph.begin(), graph.end());
for(int i = 1; i <= numberOfNode; i++){
makeSet(i);
}
int cost = 0;
for(int i = 0; i < graph.size(); i++){
int t = 0;
int u = findSet(graph[i].u);
int v = findSet(graph[i].v);
if(v != u){
unionSet(u, v);
cost += graph[i].w;
t++;
}
if(t == numberOfNode-1){
return cost;
}
}
return cost;
}
int main(){
return 0;
}