관리 메뉴

NineTwo meet you

[백준/자바] 11725 트리의 부모 찾기 본문

프로그래밍 문제/백준

[백준/자바] 11725 트리의 부모 찾기

NineTwo 2021. 2. 9. 15:52
반응형

11725 트리의 부모 찾기 사진 클릭시 문제로 이동


문제

루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 노드의 개수 N (2 ≤ N ≤ 100,000)이 주어진다.

둘째 줄부터 N-1개의 줄에 트리 상에서 연결된 두 정점이 주어진다.

출력

첫째 줄부터 N-1개의 줄에 각 노드의 부모 노드 번호를 2번 노드부터 순서대로 출력한다.

예제 입력 1

7
1 6
6 3
3 5
4 1
2 4
4 7

예제 출력 1

4
6
1
3
1
4

예제 입력 2

12
1 2
1 3
2 4
3 5
3 6
4 7
4 8
5 9
5 10
6 11
6 12

예제 출력 2

1
1
2
3
3
4
4
5
5
6
6

설명

트리의 부모를 찾는 문제이다.

입력의 경우 예제 1번의 4 1을 보더라도 앞에 나온 수가 뒤의 수의 부모라고 보장할 수 없다.

양 방향 그래프를 활용해 1번 노드부터 연결된 노드를 따라가며 부모를 구해야 한다. 

 

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class BOJ11725 {
static int parents[];
static ArrayList<Integer>[] al;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
parents = new int[n+1];
al = new ArrayList[n+1];
for(int i = 0; i < n+1; i++) {
al[i] = new ArrayList<>();
}
for(int i = 0; i < n-1; i++) {
String str[] = br.readLine().split(" ");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
al[a].add(b);
al[b].add(a);
}
SearchParents();
for(int i = 2; i < n+1; i++) {
System.out.println(parents[i]);
}
}
static void SearchParents() {
Queue<Integer> q = new LinkedList<>();
q.offer(1);
parents[1] = 1;
while(!q.isEmpty()) {
int cur = q.poll();
for(int next: al[cur]) {
if(parents[next] == 0) {
q.offer(next);
parents[next] = cur;
}
}
}
}
}
view raw BOJ11725.java hosted with ❤ by GitHub
반응형
Comments