-
Notifications
You must be signed in to change notification settings - Fork 153
/
kruskal_min_spanning_tree.cpp
91 lines (83 loc) · 1.52 KB
/
kruskal_min_spanning_tree.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
/**
* Description: Kruskal Algorithm (Minimum Spanning Tree).
* Usage: See below O((V + E) lg(E))
* Source: https://github.com/dragonslayerx
*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
class Disjoint_Set {
private:
vector<int> P;
vector<int> rank;
public:
Disjoint_Set(int n){
P.resize(n);
rank.resize(n);
for (int i = 0; i < n; i++) {
P[i] = i;
}
}
void merge(int node_x, int node_y){
int rep_x = find(node_x);
int rep_y = find(node_y);
if (rank[rep_x] > rank[rep_y])
P[rep_y] = rep_x;
else {
P[rep_x] = rep_y;
if (rank[rep_x] == rank[rep_y])
rank[rep_y]++;
}
}
int find(int node){
int tmp = node;
while (node != P[node]) {
node = P[tmp];
tmp = node;
}
return node;
}
};
struct edge {
int a, b;
long long w;
int index;
};
bool compare(const edge &a, const edge &b){
return a.w < b.w;
}
#define MAX 505
int main(){
ios::sync_with_stdio(false);
int v, e;
cin >> v >> e;
vector<edge> E(e);
for (int i = 0; i < e; i++) {
cin >> E[i].a;
cin >> E[i].b;
E[i].a-- , E[i].b--;
cin >> E[i].w;
E[i].index = i;
}
int u;
cin >> u;
sort(E.begin(), E.end(), compare);
Disjoint_Set D(v);
int selected = 0;
cout << v-1 << endl;
for (int i = 0; i < E.size(); i++) {
int w = E[i].w;
int a = E[i].a;
int b = E[i].b;
if (D.find(a) != D.find(b)) {
cout << E[i].index + 1 << endl;
selected++;
D.merge(a, b);
}
if (selected == v - 1) {
break;
}
}
}