Skip to content

Commit 58960cb

Browse files
authored
[20251029] PGM / LV2 / 전력망을 둘로 나누기 / 강신지
1 parent 3141625 commit 58960cb

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
```java
2+
import java.util.*;
3+
4+
class Solution {
5+
public int solution(int n, int[][] wires) {
6+
List<List<Integer>> g = new ArrayList<>();
7+
for (int i = 0; i <= n; i++) g.add(new ArrayList<>());
8+
9+
for (int[] w : wires) {
10+
g.get(w[0]).add(w[1]);
11+
g.get(w[1]).add(w[0]);
12+
}
13+
14+
int answer = Integer.MAX_VALUE;
15+
16+
for (int[] cut : wires) {
17+
int a = cut[0];
18+
int b = cut[1];
19+
20+
int sizeA = bfsCount(n, g, a, b);
21+
int sizeB = n - sizeA;
22+
int diff = Math.abs(sizeA - sizeB);
23+
24+
if (diff < answer) answer = diff;
25+
}
26+
27+
return answer;
28+
}
29+
30+
private int bfsCount(int n, List<List<Integer>> g, int a, int b) {
31+
boolean[] visited = new boolean[n + 1];
32+
Queue<Integer> q = new LinkedList<>();
33+
q.add(a);
34+
visited[a] = true;
35+
36+
int cnt = 0;
37+
38+
while (!q.isEmpty()) {
39+
int cur = q.poll();
40+
cnt++;
41+
42+
for (int nxt : g.get(cur)) {
43+
if (isCutEdge(cur, nxt, a, b)) continue;
44+
if (!visited[nxt]) {
45+
visited[nxt] = true;
46+
q.add(nxt);
47+
}
48+
}
49+
}
50+
return cnt;
51+
}
52+
53+
private boolean isCutEdge(int u, int v, int a, int b) {
54+
return (u == a && v == b) || (u == b && v == a);
55+
}
56+
}
57+
58+
```

0 commit comments

Comments
 (0)