on
[java 백준] 실버 2/ 11725번 트리의 부모 찾기
[java 백준] 실버 2/ 11725번 트리의 부모 찾기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Main {
public static int N;
public static void main( String [] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader( new InputStreamReader( System . in ));
N = Integer. parseInt (br.readLine());
List < Integer > list[] = new ArrayList[N + 1 ];
for ( int i = 0 ; i < N + 1 ; i + + ) {
list[i] = new ArrayList < Integer > ();
}
for ( int i = 0 ; i < N - 1 ; i + + ) {
String s = br.readLine();
String [] str = s. split ( " " );
int a = Integer. parseInt (str[ 0 ]);
int b = Integer. parseInt (str[ 1 ]);
list[a]. add (b);
list[b]. add (a);
}
boolean visit[] = new boolean [N + 1 ];
Queue < Integer > queue = new LinkedList < Integer > ();
queue. add ( 1 );
visit[ 1 ] = true ;
int ans[] = new int [N + 1 ];
while ( ! queue.isEmpty()) {
int num = queue.poll();
for ( int i : list[num]) {
if ( ! visit[i]) {
visit[i] = true ;
ans[i] = num; // i가 노드값 num이 부모값
queue. add (i);
}
}
}
for ( int i = 2 ; i < ans. length ; i + + ) {
System . out . println (ans[i]);
}
}
}
from http://we1cometomeanings.tistory.com/192 by ccl(A) rewrite - 2021-12-24 10:00:57