-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKruskal.cpp
62 lines (51 loc) · 1.1 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
#include <iostream>
using namespace std;
const int N=1e5;
int parent[N];
struct edge{
int a,b,c;
}edges[N];
bool cmp(const edge &a,const edge &b){return a.c<=b.c;}
void init(int n)
{
for(int i=0;i<=n;i++)
parent[i]=i;
}
int get_parent(int n)
{
if(n==parent[n])
return n;
return parent[n]=get_parent(parent[n]);
}
void merge(int a,int b)
{
a=get_parent(a);
b=get_parent(b);
if(a==b)
return;
parent[b]=a;
}
bool same_parent(int a,int b){return get_parent(a)==get_parent(b);}
int main()
{
int n,m;
cin>>n>>m;
init(n);
for(int i=0;i<m;i++)
{
cin>>edges[i].a>>edges[i].b>>edges[i].c;
}
for(int i=1;i<=n;i++)
cout<<i<<' '<<parent[i]<<endl;
sort(edges,edges+m,cmp);
cout<<endl;
for(int i=0;i<m;i++)
{
cout<<edges[i].a<<' '<<edges[i].b<<' '<<edges[i].c<<endl;
if(!same_parent(edges[i].a,edges[i].b))
{merge(edges[i].a,edges[i].b);cout<<edges[i].a<<"--->"<<edges[i].b<<' '<<edges[i].c<<endl;}
}
cout<<endl;
for(int i=1;i<=n;i++)
cout<<i<<' '<<parent[i]<<endl;
}