-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMST_Krushkal.cpp
More file actions
77 lines (69 loc) · 1.41 KB
/
MST_Krushkal.cpp
File metadata and controls
77 lines (69 loc) · 1.41 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
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 7;
int cost[N][N];
int parent[N];
int find(int i)
{
while (parent[i] != i)
i = parent[i];
return i;
}
void unionset(int i, int j)
{
int a = find(i);
int b = find(j);
parent[a] = b;
}
void kruskal(int n)
{
for (int i = 1; i <= n; i++)
{
parent[i] = i;
}
int count = 0, mincost=0;
cout <<"Edges taken: " <<endl;
while (count < n - 1)
{
int min = INT_MAX, a = -1, b = -1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (find(i) != find(j) && cost[i][j] < min)
{
min = cost[i][j];
a = i;
b = j;
}
}
}
unionset(a, b);
cout << "Vertices: " << a << " " << b << ", Cost: " << cost[a][b] <<endl;
mincost += min;
count++;
}
cout << "Minimum cost is " << mincost << endl;
}
int main()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
int v1, v2, w;
cin >> v1 >> v2 >> w;
cost[v1][v2] = w;
cost[v2][v1] = w;
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i != j && cost[i][j] == 0)
cost[i][j] = INT_MAX;
}
}
kruskal(n);
return 0;
}