-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskal.cpp
More file actions
73 lines (56 loc) · 825 Bytes
/
kruskal.cpp
File metadata and controls
73 lines (56 loc) · 825 Bytes
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
#include<bits/stdc++.h>
using namespace std;
struct edge
{
int a;
int b;
int w;
};
edge arr[100000];
int par[100000];
bool comp(edge a, edge b)
{
if(a.w < b.w)
{
return true;
}
return false;
}
int find(int a)
{
if(par[a] == -1)
{
return a;
}
return par[a] = find(par[a]);
}
void merge(int a,int b)
{
par[a] = b;
}
int main()
{
int n,m,a,b;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
par[i] = -1;
}
for(int i=0;i<m;i++)
{
cin>>arr[i].a>>arr[i].b>>arr[i].w;
}
int sum = 0;
sort(arr,arr+m,comp);
for(int i=0;i<m;i++)
{
a = find(arr[i].a);
b = find(arr[i].b);
if(a!=b)
{
sum+=arr[i].w;
merge(a,b);
}
}
cout<<sum<<endl;
}