-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement_Kruskal.cpp
83 lines (67 loc) · 1.5 KB
/
Implement_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
//
// Created by rajat joshi on 17-06-2022.
//
#include<bits/stdc++.h>
using namespace std;
const int M=1e6-1;
int parent[M];
int find(int a)
{
while(parent[a]!=a)
{
parent[a]=parent[parent[a]];
a=parent[a];
}
return a;
}
void unionFind(int a,int b)
{
int d = find(a);
int e = find(b);
parent[d]=parent[e];
}
int main()
{
int vertices;
cout<<"Enter the vertices:"<<"\n";
cin>>vertices;
int edges;
cout<<"Enter the edges:"<<"\n";
cin>>edges;
vector<pair<int,pair<int,int>>>adj;
for(int i=0;i<edges;++i)
{
int source, destination, weight;
cout << "Enter the : \n Source - Destination \n";
cin >> source >> destination >> weight;
adj.push_back({weight, {source, destination}});
}
sort(adj.begin(),adj.end());
for(int i=0;i<M;++i)
{
parent[i]=i;
}
vector<pair<int,int>>TreeEdge;
int totalWeight=0;
for(auto x : adj)
{
int a=x.second.first;
int b=x.second.second;
int cost=x.first;
if(find(a) != find(b))
{
totalWeight=totalWeight+cost;
unionFind(a,b);
TreeEdge.push_back({a,b});
}
}
cout<<"Edges are :"<<"\n";
for(auto x : TreeEdge)
{
cout<<x.first<<" -> "<<x.second<<" "<<"\n";
}
cout<<"Total weight of MST is :";
cout<<"\n";
cout<<totalWeight<<" ";
return 0;
}