-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskal.cpp
More file actions
75 lines (61 loc) · 1.08 KB
/
kruskal.cpp
File metadata and controls
75 lines (61 loc) · 1.08 KB
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
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
typedef pair<int, int> pii;
vector<pii> A;
int p[200005], rank[200005];
int nE, nV;
struct graph{
int u, v, c;
}edges[200005];
void make_set(int x){
p[x] = x;
rank[x] = 0;
}
int find_set(int x){
if( x != p[x] )
p[x] = find_set(p[x]);
return p[x];
}
void link(int x, int y){
if( rank[x] > rank[y] ){
p[y] = x;
}else{
p[x] = y;
if( rank[x] == rank[y] )
rank[y]++;
}
}
void Union(int x, int y){
link(find_set(x), find_set(y));
}
bool comp( graph a, graph b ){
return a.c<b.c;
}
int MSTKruskal(){
int i, ret=0;
pii node;
for(i=0; i<nV; i++)
make_set(i);
sort(edges, edges+nE, comp);
for(i=0; i<nE; i++){
node.first = edges[i].u;
node.second= edges[i].v;
if( find_set(node.first) != find_set(node.second) ){
A.push_back(node);
ret += edges[i].c;
Union(node.first, node.second);
}
}
return ret;
}
int main(){
int i;
scanf("%d%d", &nV, &nE);
for(i=0; i<nE; i++){
scanf("%d%d%d", &edges[i].u, &edges[i].v, &edges[i].c);
}
printf("%d\n", MSTKruskal());
return 0;
}