업데이트:


카테고리:

태그: , ,


느낀점

  • 내가 충분히 고민하면 할 만한 문제



문제

트리의 부모 찾기(백준: 11725번)

image



풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Main {
    static int nodeCnt;
    static ArrayList<ArrayList<Integer>> list = new ArrayList<>();
    static boolean[] visited;
    static int[] parent;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        nodeCnt = Integer.parseInt(br.readLine());
        visited = new boolean[nodeCnt + 1];
        parent = new int[nodeCnt + 1];
        for (int i = 0; i <= nodeCnt; i++) {
            list.add(new ArrayList<>());
        }

        for (int i = 0; i < nodeCnt - 1; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());

            list.get(a).add(b);
            list.get(b).add(a);
        }

        dfs(1);

        for (int i = 2; i <= nodeCnt; i++)
            System.out.println(parent[i]);
    }

    private static void dfs(int now) {
        visited[now] = true;

        for (int next : list.get(now)) {
            if (!visited[next]) {
                parent[next] = now;
                dfs(next);
            }
        }
    }

}