문제링크 : https://www.acmicpc.net/problem/1068
1068번: 트리
첫째 줄에 트리의 노드의 개수 N이 주어진다. N은 50보다 작거나 같은 자연수이다. 둘째 줄에는 0번 노드부터 N-1번 노드까지, 각 노드의 부모가 주어진다. 만약 부모가 없다면 (루트) -1이 주어진다
www.acmicpc.net
접근 과정 :
- 트리에 속한 노드 중 하나를 삭제했을 때, 남아있는 리프노드의 갯수를 구하는 문제이다.
- 노드를 삭제하면 그 노드의 자식 노드들도 같이 삭제된다.
- 우선 자식노드를 저장하는 List<List<Integer>> 를 생성했다.
- 그리고 삭제할 노드부터 그 이하 자식노드를 모두 boolen[] removed에 체크했다.
- 이제 0번 노드부터 N-1번 노드까지 순회하면서, 현재 리프노드인 것만 계산했다.
소스 코드 및 결과 :
package BOJ;
/*
트리
*/
import java.io.*;
import java.util.*;
public class BOJ1068 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
children = new ArrayList<>();
for (int i = 0; i < N; i++) {
children.add(new ArrayList<>());
}
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
int parent = Integer.parseInt(st.nextToken());
if (parent != -1) {
children.get(parent).add(i);
}
}
removed = new boolean[N];
int x = Integer.parseInt(br.readLine());
removeNode(x);
int count = 0;
for (int i = 0; i < N; i++) {
if (removed[i]) {
continue;
}
if (children.get(i).isEmpty()||(children.get(i).size() == 1 && removed[children.get(i).get(0)])) {
count++;
}
}
System.out.println(count);
}
static List<List<Integer>> children;
static boolean[] removed;
static void removeNode(int x) {
removed[x] = true;
for (int child : children.get(x)) {
removeNode(child);
}
}
}
P.S
어떤 노드를 기준으로 해당 노드의 부모와 자식을 모두 저장할 수 있는 자료구조를 사용한다면 더 좋지 않을까??
'Algorithm' 카테고리의 다른 글
[백준 Gold 2] 4195 친구 네트워크 - Java (0) | 2021.12.28 |
---|---|
[백준 Gold 4] 17142 연구소 3 - Java (0) | 2021.12.27 |
[백준 Gold 5] 15683 감시 - Java (0) | 2021.12.26 |
[백준 Gold 2] 17143 낚시왕 - Java (0) | 2021.12.26 |
[백준 Silver 4] 11652 카드 - Java (0) | 2021.12.25 |