-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKruskal_MST.cpp
More file actions
85 lines (64 loc) · 1.16 KB
/
Kruskal_MST.cpp
File metadata and controls
85 lines (64 loc) · 1.16 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// problem: "https://www.hackerrank.com/challenges/kruskalmstrsub/problem"
// Kruskal (MST): Really Special Subtree
#include<iostream>
#include<algorithm>
#include<vector>
#define ll long long int
using namespace std;
struct edge
{
int u,v,w;
};
bool func(edge edge1,edge edge2)
{
return (edge1.w<edge2.w);
}
int Parent(vector<int>&P,int p)
{
while(P[p]!=-1)
p = P[p];
return p;
}
ll Kruskal(vector<edge>&Edges,int n,int m)
{
vector<int>P(n+1,-1);
int i,c;
c = 0;
ll t = 0;
for(i=0;i!=Edges.size();i++)
{
if(c == n-1)
break;
int p1 = Parent(P,Edges[i].u);
int p2 = Parent(P,Edges[i].v);
if(p1 != p2)
{
P[p1] = p2;
c++;
t += Edges[i].w;
}
}
return t;
}
int main()
{
int n,m;
cin>>n>>m;
int M;
M = m;
vector<edge>Edges;
while(M--)
{
int u,v,w;
cin>>u>>v>>w;
edge E;
E.u = u;
E.v = v;
E.w = w;
Edges.push_back(E);
}
sort(Edges.begin(),Edges.end(),func);
ll min_wt = Kruskal(Edges,n,m);
cout<<min_wt;
return 0;
}