forked from MohitR1999/cpp-store
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskal_algo.cpp
More file actions
147 lines (121 loc) · 1.6 KB
/
kruskal_algo.cpp
File metadata and controls
147 lines (121 loc) · 1.6 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include <bits/stdc++.h>
using namespace std;
struct edge
{
int first;
int second;
int w;
};
struct node_
{
node_ *parent;
int key;
int height;
};
void merge(edge *E,int from, int to)
{
int n;
n = to-from+1;
edge A[n];
for(int i=0;i<n;i++)
{
A[i] = E[from+i];
}
int i,j;
i=0;
j= (n%2==0)? (n/2) : (n/2)+1;
int count=from,mid=j;
while(i!=mid && j!=(n))
{
if(A[i].w < A[j].w)
{
E[count++] = A[i];
i++;
}
else
{
E[count++] = A[j];
j++;
}
}
if(i==mid)
{
while(j!=(n))
{
E[count++] = A[j];
j++;
}
}
else
{
while(i!=mid)
{
E[count++] = A[i];
i++;
}
}
}
void merge_sort(edge *E,int from,int to)
{
if(to == from)
return;
merge_sort(E,from, (from+to)/2);
merge_sort(E,(from+to)/2 +1,to);
merge(E,from,to);
}
int find_set(node_ E)
{
while((E.parent)->key != E.key)
{
E = *(E.parent);
}
return E.key;
}
void union_set(node_ *A, node_ *B)
{
if(A->height > B->height)
{
B->parent = A;
}
else if(A->height < B->height)
{
A->parent = B;
}
else
{
A->parent = B;
(B->height)++;
}
}
int main()
{
int n,e;
cout<<"No. of Nodes and no. of edges"<<endl;
cin>>n>>e;
cout<<"Describe edges : from to weight"<<endl;
edge E[e];
for (int i = 0; i < e; ++i)
{
cin>>E[i].first>>E[i].second>>E[i].w;
}
merge_sort(E,0,e-1);
//
node_ N[n];
for(int i=0;i<n;i++)
{
N[i].parent = &N[i];
N[i].key = i;
N[i].height = 1;
}
for(int i=0;i<e;i++)
{
int a,b;
a = find_set(N[E[i].first]);
b = find_set(N[E[i].second]);
if(a!=b)
{
cout<<E[i].first<<" "<<E[i].second<<endl;
union_set(&N[a],&N[b]);
}
}
}