20.08.31 - [백준] 2606번 바이러스
guswns1659 opened this issue · comments
HYUNJUN SON commented
문제 풀이 핵심 아이디어
- union-find 이용. 두 수 중 작은 수로 네트워크를 만드는 방법
- 관계의 수만큼 반복문을 돌면서 입력받은 두 노드를 union한다.
- 작은 숫자로 방향이 갈 수 있게 설정한다.
public static void union(int x, int y) {
int x2 = find(x);
int y2 = find(y);
if (x2 != y2) {
if (x < y) {
parent.put(y2, x2);
} else {
parent.put(x2, y2);
}
}
}
- union이 완료되면 parent를 반복문 돌면서 find()를 사용해 각 노드의 네트워크를 제대로 조정한다.
- parent.values()를 반복문 돌면서 타겟과 같다면 sum++ 한 뒤 마지막에 sum -1을 리턴한다. 이유는 자기 자신을 제외하고 오염되는 컴퓨터의 숫자이기 때문이다.
어려운점 및 실수
- static 메서드에서는 static 변수만 사용할 수 있다.
- union 끝나고 find() 반복문 돌 때 매직넘버를 지정해서 런타임 에러 발생..!! 주의
풀이
package backjun.sorting;
import java.util.*;
import java.io.*;
public class N2606 {
private static Map<Integer, Integer> parent = new HashMap<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int comCount = Integer.parseInt(br.readLine());
int edgeCount = Integer.parseInt(br.readLine());
for (int computer = 1; computer < comCount + 1; computer++) {
parent.put(computer, computer);
}
for (int loop = 0; loop < edgeCount; loop++) {
String[] relations = br.readLine().split(" ");
int x = Integer.parseInt(relations[0]);
int y = Integer.parseInt(relations[1]);
union(x,y);
}
for (int computer = 1; computer < comCount + 1; computer++) {
find(computer);
}
int target = parent.get(1);
int sum = 0;
for (int value : parent.values()) {
if (value == target) {
sum++;
}
}
System.out.println(sum - 1);
}
public static void union(int x, int y) {
int x2 = find(x);
int y2 = find(y);
if (x2 != y2) {
if (x < y) {
parent.put(y2, x2);
} else {
parent.put(x2, y2);
}
}
}
public static int find(int x) {
if (x == parent.get(x)) {
return x;
}
int p = find(parent.get(x));
parent.put(x, p);
return p;
}
}