[백준] 트리의 부모 찾기
문제
루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 노드의 개수 N (2 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N-1개의 줄에 트리 상에서 연결된 두 정점이 주어진다.
출력
첫째 줄부터 N-1개의 줄에 각 노드의 부모 노드 번호를 2번 노드부터 순서대로 출력한다.
문제풀이
- BFS로 접근하였고. 루트는 1로 정해주니까 1부터 차근차근 내려가면 되겠다고 생각했다.
- 문제를 풀면서 ArrayList에 division을 더 넣는 것은 처음해봤다. 앞으로 유용하게 써먹을 수 있을 것 같다.
- 차근차근 내려가면서 이미 검색된 내용은 제외하고 BFS로 접근하면 끝!
코드
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main {
static int[] parent;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
ArrayList<Integer>[] list = new ArrayList[n+1];
boolean[] check = new boolean[n+1];
parent = new int[n+1];
for(int i=1; i<n+1; i++){
list[i] = new ArrayList<>();
}
for(int i=1; i<n; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
list[a].add(b);
list[b].add(a);
}
dp(list,1,check,parent);
for(int i=2;i<n+1;i++){
System.out.println(parent[i]);
}
}
public static void dp(ArrayList<Integer>[] list, int index, boolean[] check, int[] parent){
if(check[index]) return;
int size = list[index].size();
check[index] = true;
for(int i=0; i<size; i++){
if(!check[list[index].get(i)]) {
parent[list[index].get(i)] = index;
dp(list, list[index].get(i), check, parent);
}
}
}
}