-
Notifications
You must be signed in to change notification settings - Fork 1
/
Krushkal Algorithm.cpp
115 lines (92 loc) · 1.91 KB
/
Krushkal 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define ll long long int
#define mod 100000
vector <int> *adj;
int xcent;
int ycent;
int n;
int *vis;
int *path;
class Test
{
public:
int w;
int u;
int v;
bool operator < ( Test const &rhs)const {
return (w < rhs.w);
}
bool operator > ( Test const &rhs)const {
return (w > rhs.w);
}
};
int find_set(int i)
{ if (i == path[i])
return i;
else
return find_set(path[i]);
}
void union_set(int u, int v)
{
path[u] = path[v];
}
int main()
{
clock_t tStart = clock();
ios_base:: sync_with_stdio(false);
cin.tie(0);
//////////////////////////////////////start...............
int n;
cin >> n; //number of nodes.......
path = new int [n];
adj = new vector <int> [n];
int e;
cin >> e;
vector <pair<int, pair<int, int>>> s;
int u, v, w;
for (int i = 0; i < e; i++)
{
cin >> w >> u >> v;
s.pb({w, { u, v}});
}
for (int i = 0; i < n; i++)
{
path[i] = i;
}
int sum = 0;
sort(s.begin(), s.end());
for (int i = 0; i < s.size(); i++)
{ u = s[i].second.first; w = s[i].first; v = s[i].second.second;
int uk = find_set(u);
int vk = find_set(v);
if (uk != vk )
{
adj[u].pb(v);
//adj[v].pb(u);
union_set(uk, vk);
sum = sum + w;
cout << u << " " << v << endl;
}
}
cout << endl << "minimum spanning tree weight is" << sum << endl;
/*for(auto i : s)
{ w=i.w;
u=i.u;
v=i.v;
if()
}*/
/////////////////////////////end................................... ....
#ifndef ONLINE_JUDGE
printf("\nRun Time -> %.10fs\n", (double)(clock() - tStart) / CLOCKS_PER_SEC);
#endif
return 0;
}
//c v a s selecting text or x for selecting cut
//ctrl+d after selecting text to select same type
//ctrl+shift+d for copy and paste the line below it
//ctrl+del to delete a text
//ctrl+left to jump left of line or vice versa
//ctrl+shift+"/" to comment whole block and vice versa for undo
//ctrl+"/" for commenting a line