TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
kruskal.cpp
1
#include <algorithm>
2
#include <array>
3
#include <iostream>
4
#include <vector>
5
//#include <boost/multiprecision/cpp_int.hpp>
6
// using namespace boost::multiprecision;
7
const
int
mx = 1e6 + 5;
8
using
ll
= int64_t;
9
10
std::array<ll, mx> parent;
11
ll
node
, edge;
12
std::vector<std::pair<ll, std::pair<ll, ll>>> edges;
13
void
initial() {
14
for
(
int
i = 0; i <
node
+ edge; ++i) {
15
parent[i] = i;
16
}
17
}
18
19
int
root(
int
i) {
20
while
(parent[i] != i) {
21
parent[i] = parent[parent[i]];
22
i = parent[i];
23
}
24
return
i;
25
}
26
27
void
join(
int
x,
int
y) {
28
int
root_x = root(x);
// Disjoint set union by rank
29
int
root_y = root(y);
30
parent[root_x] = root_y;
31
}
32
33
ll
kruskal() {
34
ll
mincost = 0;
35
for
(
int
i = 0; i < edge; ++i) {
36
ll
x = edges[i].second.first;
37
ll
y = edges[i].second.second;
38
if
(root(x) != root(y)) {
39
mincost += edges[i].first;
40
join(x, y);
41
}
42
}
43
return
mincost;
44
}
45
46
int
main
() {
47
while
(
true
) {
48
int
from = 0, to = 0, cost = 0, totalcost = 0;
49
std::cin >>
node
>> edge;
// Enter the nodes and edges
50
if
(
node
== 0 && edge == 0) {
51
break
;
// Enter 0 0 to break out
52
}
53
initial();
// Initialise the parent array
54
for
(
int
i = 0; i < edge; ++i) {
55
std::cin >> from >> to >> cost;
56
edges.emplace_back(make_pair(cost, std::make_pair(from, to)));
57
totalcost += cost;
58
}
59
sort(edges.begin(), edges.end());
60
std::cout << kruskal() << std::endl;
61
edges.clear();
62
}
63
return
0;
64
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
ll
#define ll
Definition
matrix_exponentiation.cpp:33
node
Definition
binary_search_tree.cpp:11
graph
kruskal.cpp
Generated by
1.18.0