|
| 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.List; |
| 7 | +import java.util.PriorityQueue; |
| 8 | + |
| 9 | +public class Main{ |
| 10 | + // 크루스칼 -> 간선 중심 -> 간선이 적을때 쓰면 좋음 -> disjoint set알고리즘 구현 필요 |
| 11 | + // 프림 -> 정점 중심 -> MST와 우선숭위큐에 정점을 넣어가며 그 예비 MST의 간선을 선택해나가는것 |
| 12 | + static int N, M; |
| 13 | + static List<List<int[]>> Graph; |
| 14 | + public static void main(String[] args) throws IOException { |
| 15 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 16 | + String[] tokens = br.readLine().split(" "); |
| 17 | + N = Integer.parseInt(tokens[0]); |
| 18 | + M = Integer.parseInt(tokens[1]); |
| 19 | + int m = M; |
| 20 | + Graph = new ArrayList<>(); |
| 21 | + for(int i = 0; i <= N; i++){ |
| 22 | + Graph.add(new ArrayList<>()); |
| 23 | + } |
| 24 | + long overSum = 0L; |
| 25 | + while(m-->0){ |
| 26 | + tokens = br.readLine().split(" "); |
| 27 | + int s = Integer.parseInt(tokens[0]); |
| 28 | + int e = Integer.parseInt(tokens[1]); |
| 29 | + int w = Integer.parseInt(tokens[2]); |
| 30 | + overSum += w; |
| 31 | + Graph.get(s).add(new int[]{e, w}); |
| 32 | + Graph.get(e).add(new int[]{s, w}); |
| 33 | + } |
| 34 | + |
| 35 | + boolean[] visited = new boolean[N+1]; |
| 36 | + var q = new PriorityQueue<int[]>((o1, o2)->o1[1] - o2[1]); |
| 37 | + q.add(new int[]{1, 0}); |
| 38 | + long mstSum = 0L; |
| 39 | + |
| 40 | + while(!q.isEmpty()){ |
| 41 | + var qItem = q.poll(); |
| 42 | + int v = qItem[0]; int w = qItem[1]; |
| 43 | + if(visited[v]) continue; |
| 44 | + visited[v] = true; |
| 45 | + mstSum += w; |
| 46 | + for(int[] nextInfo : Graph.get(v)){ |
| 47 | + int nv = nextInfo[0]; int nw = nextInfo[1]; |
| 48 | + if(visited[nv]) continue; |
| 49 | + q.add(new int[]{nv, nw}); |
| 50 | + } |
| 51 | + } |
| 52 | + for(int i = 1; i < N+1; i++){ |
| 53 | + if(!visited[i]){ |
| 54 | + System.out.println(-1); |
| 55 | + return; |
| 56 | + } |
| 57 | + } |
| 58 | + System.out.println(overSum - mstSum); |
| 59 | + br.close(); |
| 60 | + } |
| 61 | +} |
| 62 | +``` |
0 commit comments