|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.PriorityQueue; |
| 7 | +import java.util.StringTokenizer; |
| 8 | + |
| 9 | +public class Main { |
| 10 | + private static BufferedReader br; |
| 11 | + private static int V, E; |
| 12 | + private static ArrayList<Edge>[] adj; |
| 13 | + private static boolean[] visited; |
| 14 | + private static class Edge implements Comparable<Edge> { |
| 15 | + int to, weight; |
| 16 | + public Edge(int to, int weight) { |
| 17 | + this.to = to; |
| 18 | + this.weight = weight; |
| 19 | + } |
| 20 | + @Override |
| 21 | + public int compareTo(Edge other) { |
| 22 | + return this.weight - other.weight; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + public static void main(String[] args) throws IOException { |
| 27 | + br = new BufferedReader(new InputStreamReader(System.in)); |
| 28 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 29 | + V = Integer.parseInt(st.nextToken()); |
| 30 | + E = Integer.parseInt(st.nextToken()); |
| 31 | + adj = new ArrayList[V + 1]; |
| 32 | + for (int i = 1; i <= V; i++) { |
| 33 | + adj[i] = new ArrayList<>(); |
| 34 | + } |
| 35 | + |
| 36 | + for (int i = 0; i < E; i++) { |
| 37 | + st = new StringTokenizer(br.readLine()); |
| 38 | + int u = Integer.parseInt(st.nextToken()); |
| 39 | + int v = Integer.parseInt(st.nextToken()); |
| 40 | + int w = Integer.parseInt(st.nextToken()); |
| 41 | + |
| 42 | + adj[u].add(new Edge(v, w)); |
| 43 | + adj[v].add(new Edge(u, w)); |
| 44 | + } |
| 45 | + |
| 46 | + System.out.println(prim()); |
| 47 | + } |
| 48 | + |
| 49 | + private static long prim() { |
| 50 | + boolean[] visited = new boolean[V + 1]; |
| 51 | + PriorityQueue<Edge> pq = new PriorityQueue<>(); |
| 52 | + long totalWeight = 0; |
| 53 | + int visitedCount = 0; |
| 54 | + |
| 55 | + visited[1] = true; |
| 56 | + visitedCount++; |
| 57 | + for (Edge e : adj[1]) { |
| 58 | + pq.add(e); |
| 59 | + } |
| 60 | + |
| 61 | + while (!pq.isEmpty()) { |
| 62 | + Edge edge = pq.poll(); |
| 63 | + if (visited[edge.to]) continue; |
| 64 | + visited[edge.to] = true; |
| 65 | + totalWeight += edge.weight; |
| 66 | + visitedCount++; |
| 67 | + for (Edge e : adj[edge.to]) { |
| 68 | + if (!visited[e.to]) { |
| 69 | + pq.add(e); |
| 70 | + } |
| 71 | + } |
| 72 | + if (visitedCount == V) break; |
| 73 | + } |
| 74 | + |
| 75 | + return totalWeight; |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +``` |
0 commit comments