forked from VivekDubey9/Competitive-Programming-Algos
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkruskal.cpp
68 lines (66 loc) · 1.16 KB
/
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
65
66
67
#include <iostream>
#include <tuple>
#include <queue>
using namespace std;
int link[5000];
int size[5000];
int fun(int k)
{
while(k!=link[k])
{
k=link[k];
} return k;
}
int main()
{
priority_queue<tuple<int,int,int> > q;
tuple<int,int,int> t;
int N; int M;
cin>>N>>M;
int x; int y; int z;
for(int i=0; i<M; i++)
{
cin>>x>>y>>z;
q.push(make_tuple(-z,x,y));
}
for(int i=0; i<N+1; i++)
{
link[i]=i;
size[i]=1;
}
int aa;
int bb;
int result=0;
while(!q.empty())
{
t=q.top(); q.pop();
x=abs(get<0>(t));
y=get<1>(t);
z=get<2>(t);
aa=fun(y);
bb=fun(z);
if(aa==bb)
{
continue;
}
else if(size[aa]>size[bb])
{
link[bb]=aa;
}
else if(size[bb]>size[aa])
{
link[aa]=bb;
}
else if(size[bb]==size[aa])
{
if(aa>bb)
{
link[bb]=aa;
}
else if(aa<bb)
{
link[aa]=bb;
}
} result+=x;
} cout<<result;
}