-
Notifications
You must be signed in to change notification settings - Fork 0
/
170104093kruskal.cpp
72 lines (59 loc) · 1.07 KB
/
170104093kruskal.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
#include<bits/stdc++.h>
using namespace std;
int node,edge;
int par[100];
pair < int ,pair < int ,int > > adj[100];
int findpar(int i)
{
if(par[i]==i)
{
return i;
}
else
findpar(par[i]);
}
int cost=0;
void unionn(int x,int y)
{
int x1=findpar(x);
int y1=findpar(y);
par[x1]=par[y1];
}
void kruskal()
{
for(int i=0;i<edge;i++)
{
int x=adj[i].second.first;
int y=adj[i].second.second;
int z=adj[i].first;
if(findpar(x)!=findpar(y))
{
cout<<x<<"---"<<y<<endl;
cost+=z;
unionn(x,y);
}
}
}
void creategraph()
{
int a,b,c;
for(int i=0;i<edge;i++)
{
cin>>a>>b>>c;
adj[i]=make_pair(c,make_pair(a,b));
}
}
int main()
{
cout<<"Enter vertex and edge no : "<<endl;
cin>>node>>edge;
cout<<"Enter two vertices and cost :"<<endl;
creategraph();
for(int i=0;i<node;i++)
{
par[i]=i;
}
sort(adj,adj+edge);
kruskal();
cout<<"cost is "<<cost;
}