|
| 1 | +``` |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | +
|
| 5 | +public class Main { |
| 6 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + private static PriorityQueue<Edge> pq; |
| 9 | + private static int[] uf, size; |
| 10 | + private static int N, M, S; |
| 11 | +
|
| 12 | + public static void main(String[] args) throws IOException { |
| 13 | + init(); |
| 14 | +
|
| 15 | + int answer = kruskal(); |
| 16 | +
|
| 17 | + bw.write(answer + "\n"); |
| 18 | + bw.flush(); |
| 19 | + bw.close(); |
| 20 | + br.close(); |
| 21 | + } |
| 22 | +
|
| 23 | + private static void init() throws IOException { |
| 24 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 25 | + N = Integer.parseInt(st.nextToken()); |
| 26 | + M = Integer.parseInt(st.nextToken()); |
| 27 | + S = Integer.parseInt(st.nextToken()); |
| 28 | +
|
| 29 | + pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o1.w, o2.w)); |
| 30 | + uf = new int[N+1]; |
| 31 | + size = new int[N+1]; |
| 32 | +
|
| 33 | + for (int i = 1; i <= N; i++) { |
| 34 | + uf[i] = i; |
| 35 | + size[i] = 1; |
| 36 | + } |
| 37 | +
|
| 38 | + for (int i = 1; i <= M; i++) { |
| 39 | + st = new StringTokenizer(br.readLine()); |
| 40 | + int u = Integer.parseInt(st.nextToken()); |
| 41 | + int v = Integer.parseInt(st.nextToken()); |
| 42 | + int w = Integer.parseInt(st.nextToken()); |
| 43 | +
|
| 44 | + pq.add(new Edge(u, v, w)); |
| 45 | + } |
| 46 | +
|
| 47 | + st = new StringTokenizer(br.readLine()); |
| 48 | + } |
| 49 | +
|
| 50 | + private static int kruskal() { |
| 51 | + int cost = 0; |
| 52 | + int count = 0; |
| 53 | +
|
| 54 | + while (!pq.isEmpty() && count < N-1) { |
| 55 | + Edge current = pq.poll(); |
| 56 | +
|
| 57 | + int root1 = find(current.u); |
| 58 | + int root2 = find(current.v); |
| 59 | + if (root1 == root2) continue; |
| 60 | + union(root1, root2); |
| 61 | + cost += current.w; |
| 62 | + count++; |
| 63 | + } |
| 64 | +
|
| 65 | + return cost; |
| 66 | + } |
| 67 | +
|
| 68 | + private static void union(int x, int y) { |
| 69 | + if (size[x] < size[y]) { |
| 70 | + uf[x] = y; |
| 71 | + size[y] += size[x]; |
| 72 | + } else { |
| 73 | + uf[y] = x; |
| 74 | + size[x] += size[y]; |
| 75 | + } |
| 76 | + } |
| 77 | +
|
| 78 | + private static int find(int x) { |
| 79 | + if (uf[x] == x) return x; |
| 80 | +
|
| 81 | + return uf[x] = find(uf[x]); |
| 82 | + } |
| 83 | +
|
| 84 | + static class Edge { |
| 85 | + int u; |
| 86 | + int v; |
| 87 | + int w; |
| 88 | +
|
| 89 | + public Edge(int u, int v, int w) { |
| 90 | + this.u = u; |
| 91 | + this.v = v; |
| 92 | + this.w = w; |
| 93 | + } |
| 94 | + } |
| 95 | +} |
| 96 | +``` |
0 commit comments