-
Notifications
You must be signed in to change notification settings - Fork 2
/
7.kruskal's algorithm.cpp
60 lines (53 loc) · 1.15 KB
/
7.kruskal's algorithm.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
#include<bits/stdc++.h>
using namespace std;
int parent[100];
int Find(int r)
{
if(parent[r]== r)
return r;
return parent[r] = Find(parent[r]);
}
void Union(int a, int b)
{
int u = Find(a);
int v = Find(b);
parent[v] = u;
}
int main()
{
for (int i = 1; i <= 100; i++)
{
parent[i] = i;
}
int n, m;
cout << "Enter nodes and edges number: "<< endl;
cin >> n >> m;
vector<pair<int, pair<int,int> > > edge;
cout << "Enter nodes and weight"<< endl;
for (int i = 0; i < m; i++)
{
int p, q, w;
cin >> p >>q >> w;
edge.push_back(make_pair(w,make_pair(p,q)));
}
sort(edge.begin(),edge.end());
int weight = 0, ed = 0, ni = 0;
while(ed < n-1)
{
int a = edge[ni].second.first;
int b = edge[ni].second.second;
int w = edge[ni].first;
if(Find(a)!=Find(b))
{
Union(a,b);
cout << "shortage path and weight ";
cout << a << " " << b << " " << w << endl;
weight+=w;
ed++;
}
ni++;
}
cout << endl;
cout << "Weight is: " << weight;
return 0;
}