-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskalEdge.java
More file actions
70 lines (61 loc) · 1.24 KB
/
KruskalEdge.java
File metadata and controls
70 lines (61 loc) · 1.24 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
package algorithm;
import java.util.*;
public class KruskalEdge {
static class Edge implements Comparable<Edge> {
int from, to, weight;
Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
@Override
public int compareTo(Edge o) {
return Integer.compare(this.weight, o.weight);
}
}
static int N;
static Edge[] edges;
static int[] p;
static void make() {
p = new int[N];
for (int i = 0; i < N; i++)
p[i] = i;
}
static int find(int a) {
if (p[a] == a)
return a;
return p[a] = find(p[a]);
}
static boolean union(int a, int b) {
int ar = find(a);
int br = find(b);
if (ar == br)
return false;
p[br] = p[ar];
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
int E = sc.nextInt();
edges = new Edge[E];
for (int i = 0; i < E; i++) {
int from = sc.nextInt();
int to = sc.nextInt();
int weight = sc.nextInt();
edges[i] = new Edge(from, to, weight);
}
Arrays.sort(edges);
make();
int res = 0, cnt = 0;
for (Edge edge : edges) {
if (union(edge.from, edge.to)) {
res += edge.weight;
if (++cnt == N - 1)
break;
}
}
System.out.println(res);
sc.close();
}
}