-
Notifications
You must be signed in to change notification settings - Fork 1
/
minimal_spanning_tree_krustal.c
162 lines (145 loc) · 2.41 KB
/
minimal_spanning_tree_krustal.c
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#include <stdio.h>
#include <stdlib.h>
#define MAXV 1000
typedef int DisjSet[MAXV+1];
typedef int Vertex;
struct EdgeType{
Vertex V2,V2;
int W;
};
DisjSet VSet;
struct EdgeType *ESet;
void InitializeVSet(int N)
{
while(N)
{
VSet[N--] = -1;
}
}
Vertex Find(Vertex V)
{
Vertex root,trail,lead;
for(root = V;Vset[root]>0;root=VSet[root])
{
;
}
for(trail = v;trail != root;trail = lead)
{
lead = VSet[trail];
VSet[trail] = root;
}
return root;
}
void SetUnion(Vertex Root1,Vertex Root2)
{
if(VSet[Root2] < VSet[Root1])
{
VSet[Root2] += VSet(Root1);
VSet[Root1] = Root2;
}
else
{
VSet[Root1] += VSet[Root2];
VSet[Root2] = Root1;
}
}
void MinHeap(int i;int M)
{
int child = 0;
struct EdgeType temp;
temp = ESet[i];
for(;((i<<1)+1) < M;i++)
{
child = (i << 1) + 1;
if(child != M-1 && ESet[child+1].W < ESet[child].W)
{
child++;
}
if(temp.W > ESet[child].W)
{
ESet[i] = ESet[child];
}
else
{
break;
}
}
ESet[i] = temp;
}
void InitializeESet(int M)
{
int i = 0;
for(i= M/2;i >= 0;i--)
{
MinHeap(i,M);
}
}
int GetEdge(int CurrentSize)
{
struct EdgeType temp;
temp = ESet[0];
ESet[0] = ESet[CurrentSize-1];
ESet[CurrentSize-1] = temp;
MinHeap(0,CurrentSize-1);
return CurrentSize-1;
}
int checkCycle(Vertex V1,Vertex V2)
{
Vertex Root1 = Find(V1);
Vertex Root2 = Find(V2);
if(Root1 == Root2)
{
return 0;
}
else
{
SetUnion(Root1,Root2);
return 1;
}
}
int Krustal(int N,int M)
{
int EdgeN = 0;
int Cost = 0;
int NextEdge = M;
InitializeVSet(N);
InitializeESet(M);
while(EdgeN < N-1)
{
if(NextEdge <= 0 )
{
break;
}
NextEdge = GetEdge(NextEdge);
if(checkCycle(ESet[NextEdge].V1,ESet[NextEdge].V2))
{
cost += ESet[NextEdge].W;
EdgeN++;
}
}
if(EdgeN < N-1)
{
Cost = -1;
}
return Cost;
}
int main()
{
int N = 0;
int M = 0;
scanf("%d %d",&N,&M);
if(M < N-1)
{
printf("-1\n");
}
else
{
ESet = malloc(sizeof(struct EdgeType) * M);
for(i=0;i<M;i++)
{
scanf("%d %d %d",&ESet[i].V1,&ESet[i].V2;&ESet[i].W);
}
printf("%d\n",Krustal(N,M));
}
return 0;
}