Skip to content

Commit ef131a7

Browse files
authored
Merge pull request #1536 from AlgorithmWithGod/LiiNi-coder
[20251128] BOJ / G4 / 전력난 / 이인희
2 parents 174d664 + 79ffc6f commit ef131a7

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.*;
6+
7+
public class Main{
8+
private static int M;
9+
private static int N;
10+
private static List<int[]> Edges;
11+
private static int sumEdge;
12+
public static void main(String[] args) throws IOException {
13+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
14+
String[] temp;
15+
while(true){
16+
temp = br.readLine().split(" ");
17+
M = Integer.parseInt(temp[0]);
18+
N = Integer.parseInt(temp[1] );
19+
if(M == 0 && N == 0){
20+
break;
21+
}
22+
Edges = new ArrayList<>();
23+
sumEdge = 0;
24+
int n = N;
25+
while(n-->0){
26+
temp = br.readLine().split(" ");
27+
sumEdge += Integer.parseInt(temp[2]);
28+
Edges.add(new int[]{
29+
Integer.parseInt(temp[0]),
30+
Integer.parseInt(temp[1]),
31+
Integer.parseInt(temp[2])
32+
});
33+
}
34+
solve();
35+
System.out.println(sumEdge);
36+
}
37+
}
38+
39+
private static void solve() {
40+
List<List<int[]>> graph = new ArrayList<>();
41+
for(int i = 0; i < M; i++)
42+
graph.add(new ArrayList<>());
43+
for(int[] edge : Edges){
44+
graph.get(edge[0]).add(new int[]{edge[1], edge[2]});
45+
graph.get(edge[1]).add(new int[]{edge[0], edge[2]});
46+
}
47+
//프림
48+
Queue<int[]> q = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]);
49+
boolean[] visited = new boolean[M];
50+
int visitedCount = 1;
51+
visited[0] = true;
52+
for(int[] next : graph.get(0)){
53+
int nv = next[0];
54+
int w = next[1];
55+
q.offer(new int[]{nv, w});
56+
}
57+
while(visitedCount < M){
58+
// -- 최소힙에서 팝
59+
int[] temp = q.poll();
60+
int nv = temp[0];
61+
int w = temp[1];
62+
// -- 만약 다음 정점번호가 방문이면 컨티뉴
63+
if(visited[nv])
64+
continue;
65+
// 방문여부 표시
66+
visited[nv] =true;
67+
visitedCount++;
68+
// -- 스패닝 트리 간선 처리
69+
sumEdge -= w;
70+
for(int[] next : graph.get(nv)){
71+
int nnv = next[0];
72+
if(visited[nnv])
73+
continue;
74+
int nw = next[1];
75+
q.offer(new int[]{nnv, nw});
76+
}
77+
// -- 최소힙에 푸시
78+
}
79+
}
80+
}
81+
```

0 commit comments

Comments
 (0)