-
Notifications
You must be signed in to change notification settings - Fork 0
/
testing_kruskal.cpp
102 lines (83 loc) · 1.19 KB
/
testing_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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include<iostream>
using namespace std;
struct Set
{
int nodes;
int *parent,*rank;
Set(int node){
nodes=node;
parent = new int[node];
rank = new int[node];
for (int i = 0; i < node; ++i)
{
parent[i]=-1;
rank[i]=0;
}
}
int findParent(int x)
{
if (parent[x]!=-1)
{
return findParent(parent[x]);
}
return x;
}
void mergeTrees(int x,int y)
{
if (rank[x]>rank[y])
{
parent[y]=x;
}
else
parent[x]=y;
if (rank[x]==rank[y])
{
rank[x]++;
}
}
};
void Kruskal(int w[],int s[],int d[],int edges,int nodes)
{
int mcst=0;
Set myset(nodes);
for (int i = 0; i < edges; ++i)
{
int p1 = myset.findParent(s[i]);
int p2 = myset.findParent(d[i]);
if (p1 == p2)
{
continue;
}
myset.mergeTrees(p1,p2);
mcst+=w[i];
}
cout<<"\nminimum = "<<mcst<<endl;
}
void Sort(int w[],int s[],int d[],int n)
{
for (int i = 0; i <n; ++i)
{
for (int j = 0; j<n-i-1; ++j)
{
if (w[j] > w[j+1])
{
swap(w[j],w[j+1]);
swap(s[j],s[j+1]);
swap(d[j],d[j+1]);
}
}
}
}
int main()
{
int n,e;
cin>>n>>e;
int w[e],s[e],d[e];
for (int i = 0; i < e; ++i)
{
cin>>w[i]>>s[i]>>d[i];
}
Sort(w,s,d,e);
Kruskal(w,s,d,e,n);
return 0;
}