-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKruskal.cpp
64 lines (55 loc) · 994 Bytes
/
Kruskal.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
#include<bits/stdc++.h>
using namespace std;
const int MAX=1e6+5;
pair<long long,pair<long long,long long>>adj[MAX];
int id[MAX],nodes,edges;
void initialize()
{
for(int i=0;i<MAX;i++)
{
id[i]=i;
}
}
int root(int x)
{
if(x==id[x])
return x;
return id[x]=root(id[x]);
}
void join(int x,int y)
{
int p=root(x);
int q=root(y);
id[p]=id[q];
}
long long Kruskal()
{
int x,y;
long long cost=0,mincost=0;
for(int i=0;i<edges;i++)
{
x=adj[i].second.first;
y=adj[i].second.second;
cost=adj[i].first;
//cout<<cost<<endl;
if(root(x)!=root(y))
{
mincost+=cost;
join(x,y);
}
}
return mincost;
}
int main(void)
{
initialize();
cin>>nodes>>edges;
for(int i=0;i<edges;i++)
{
int x,y,weight;
cin>>x>>y>>weight;
adj[i]=make_pair(weight,make_pair(x,y));
}
sort(adj,adj+edges);
cout<<Kruskal();
}