-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskals.cpp
More file actions
52 lines (44 loc) · 1 KB
/
kruskals.cpp
File metadata and controls
52 lines (44 loc) · 1 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
#include <bits/stdc++.h>
using namespace std;
class Edges {
public:
int src;
int dest;
int weight;
};
bool compare(Edges w1, Edges w2){
return w1.weight < w2.weight;
}
int unionfind(int v, int* parent){
if(parent[v] == v){
return v;
}
return unionFind(parent[v], parent);
}
int main(){
int v, e;
cin >> v >> e;
Edges* edges = new Edges[e];
for(int i = 0; i < e; i++){
int src, dest, weight;
cin >> src >> dest >> weight;
edges[i].src = src;
edges[i].dest = dest;
edges[i].weight = weight;
}
sort(edges, edges+e, compare);
int* parent = new int[v];
for(int i = 0; i < v; i++){
parent[i] = i;
}
int count = 0, x = 0;
while(count != v-1){
int srcParent = unionFind(edges[x].src, parent);
int destParent = unionFind(edges[x].dest, parent);
if(srcParent != destParent){
parent[srcParent] = destParent;
count++;
}
x++;
}
}