https://www.acmicpc.net/problem/1068
1068번: 트리
첫째 줄에 트리의 노드의 개수 N이 주어진다. N은 50보다 작거나 같은 자연수이다. 둘째 줄에는 0번 노드부터 N-1번 노드까지, 각 노드의 부모가 주어진다. 만약 부모가 없다면 (루트) -1이 주어진다
www.acmicpc.net
ArrayList에 관계를 저장 후DFS를 통해 탐색하며
리프노드인지 확인하는데 delete된 노드인지 확인하는 프로세스를 추가한다.
리프노드일 경우 전역변수 count를 증가시킨다.
import java.util.*;
public class Main {
static int count = 0;
static int n, del;
static int start;
static ArrayList<Integer>[] arr = new ArrayList[50];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int i=0; i<50; i++)
arr[i] = new ArrayList<>();
int k;
for (int i=0; i<n; i++) {
k = sc.nextInt();
if (k == -1)
start = i;
else
arr[k].add(i);
}
del = sc.nextInt();
if (del != start)
search(start);
System.out.println(count);
}
public static void search(int index) {
if (arr[index].size() == 0){
count++;
return;
}
for (int i=0; i<arr[index].size(); i++){
int next = arr[index].get(i);
if (arr[index].size() == 1 && next == del) {
count++;
return;
}
if (next < n && next != del)
search(next);
}
}
}
'백준(BOJ)' 카테고리의 다른 글
[Python/파이썬] - 백준(BOJ) 1027번 : 고층 건물 (0) | 2022.05.31 |
---|---|
[Python/파이썬] - 백준(BOJ) 1781번 : 컵라면 (0) | 2022.05.28 |
[Python/파이썬] - 백준(BOJ) 1092번 : 배 (0) | 2022.05.26 |
[Python/파이썬] - 백준(BOJ) 8972번 : 미친 아두이노 (0) | 2022.05.20 |
[Python/파이썬] - 백준(BOJ) 2217번 : 로프 (0) | 2022.05.19 |