-
Notifications
You must be signed in to change notification settings - Fork 0
/
kruskalsalgo.cpp
73 lines (68 loc) · 1.27 KB
/
kruskalsalgo.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
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
const int N = INT_MAX;
vector<int> parent(N);
vector<int> size(N);
void make_set(int v)
{
parent[v] = v;
size[v] = 1;
}
int find_set(int v)
{
if(v == parent[v])
return v;
return parent[v] = find_set(parent[v]);
}
void union_sets(int a, int b)
{
a = find_set(a);
b = find_set(b);
if(a != b)
{
if(size[a] < size[b])
swap(a,b);
parent[b] = a;
size[a] += size[b];
}
}
int main()
{
for(int i=0; i<N; i++)
{
make_set(i);
}
int vertex, edge;
cin >> vertex >> edge;
vector<vector<int>> edges;
for(int i=0; i<edge; i++)
{
int u, v, w;
cin >> u >> v >> w; // u=edge1 v=edge2 w=cost
edges.push_back({w, u, v});
}
cout << endl;
sort(edges.begin(), edges.end());
int cost = 0;
for(auto i : edges)
{
int w = i[0];
int u = i[1];
int v = i[2];
int x = find_set(u);
int y = find_set(v);
if(x == y)
continue;
else
{
cout << u << " " << v << "\n";
cost += w;
union_sets(u,v);
}
}
cout << cost;
return 0;
}