728x90
300x250
https://www.acmicpc.net/problem/11725
package algorithm.boj;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Boj11725 {
public static List<Integer> graph[];
public static int N;
public static int ans[];
public static boolean visit[];
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
System.setIn(new FileInputStream("Test.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
ans = new int[N+1];
visit = new boolean[N+1];
graph = new ArrayList[N+1];
for (int i = 0; i < N+1; i++) {
graph[i] = new ArrayList<Integer>();
}
for (int i = 0; i < N-1; i++) {
st = new StringTokenizer(br.readLine());
int n1 = Integer.parseInt(st.nextToken());
int n2 = Integer.parseInt(st.nextToken());
//무방향 그래프이므로 양쪽 다 넣어줌
graph[n1].add(n2);
graph[n2].add(n1);
}
visit[1] = true;
fun(1);
for (int i = 2; i < ans.length; i++) {
System.out.println(ans[i]);
}
}
public static void fun(int idx) {
if(graph[idx].size() == 1)
return;
for (int i = 0; i < graph[idx].size(); i++) {
if(visit[graph[idx].get(i)])
continue;
visit[graph[idx].get(i)] = true;
ans[graph[idx].get(i)] = idx; //부모 답
fun(graph[idx].get(i));
}
}
}
728x90
'알고리즘 > 그래프' 카테고리의 다른 글
백준 10971번: 외판원 순회 2 [재귀][백트래킹][브루트포스] - Java (0) | 2024.01.15 |
---|---|
백준 14267번: 회사 문화 1 [트리][그래프][재귀] - Java (0) | 2024.01.03 |
백준 15681번: 트리와 쿼리 [그래프][트리][재귀] -Java (0) | 2024.01.02 |