-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathKruskal.cpp
More file actions
72 lines (72 loc) · 1.11 KB
/
Kruskal.cpp
File metadata and controls
72 lines (72 loc) · 1.11 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
#include<bits/stdc++.h>
using namespace std;
bool vis[100];
int arr[100],size[100];
#define piii pair<int,pair<int,int> >
class mycmp{
public:
bool operator()(piii p1,piii p2)
{
return p1.first>p2.first;
}
};
int root(int x)
{
while(arr[x]!=x)
{
arr[x]=arr[arr[x]];
x=arr[x];
}
return x;
}
bool find(int x,int y)
{
int rootx=root(x),rooty=root(y);
return rootx==rooty;
}
void union1(int x,int y)
{
int rootx=root(x);
int rooty=root(y);
if(size[rootx]<size[rooty])
{
arr[rootx]=rooty;
size[rooty]+=size[rootx];
}
else
{
arr[rooty]=rootx;
size[rootx]+=size[rooty];
}
}
int main()
{
printf("Enter no of vertices and no of edges\n");
int n,m,i;cin>>n>>m;
for(i=1;i<=n;i++)
{
arr[i]=i;
size[i]=1;
}
printf("Enter\nsrc dest weight\n");
priority_queue<piii,vector<piii>,mycmp>pq;
for(i=1;i<=m;i++)
{
int u,v,w;cin>>u>>v>>w;
pq.push({w,{u,v}});
}
int sum=0;
while(!pq.empty())
{
piii p=pq.top();
pq.pop();
int w=p.first,fir=p.second.first,sec=p.second.second;
if(find(fir,sec)==false)
{
sum+=w;
union1(fir,sec);
}
}
printf("weight of MST\n");
cout<<sum<<endl;
}