백준 11725

Genie·2021년 11월 7일
1

백준

목록 보기
4/12

백준 11725 트리의 부모 찾기

🔍 문제 설명

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

✔ 입력

첫째 줄에 노드의 개수 N (2 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N-1개의 줄에 트리 상에서 연결된 두 정점이 주어진다.

✔ 출력

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

💡 풀이

  1. 트리를 인접리스트를 이용하여 값을 저장한다.
  2. adj 를 순환하여 살펴보면서, parent 가 아닌것들만 다시 탐색하는 과정을 통해 parent 들을 다 찾아준다.

📝 소스코드

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

public class Main {

    static FastReader scan = new FastReader();
    static StringBuilder sb = new StringBuilder();

    static int N;
    // 인접리스트로 트리를 표현해보자.
    static ArrayList<Integer>[] adj;
    static int[] parent;

    static void input() {
        N = scan.nextInt();
        adj = new ArrayList[N+1];
        parent = new int[N+1];
        for(int i=1; i<=N; i++) {
            adj[i] = new ArrayList<>();
        }
        for(int i=1; i<N; i++) {
            int x = scan.nextInt(), y = scan.nextInt();
            adj[x].add(y); // x -> y 로 가는 것
            adj[y].add(x);
        }
    }

    static void dfs(int x, int par) {
        for(int y : adj[x]) {
            if(y == par) continue;
            parent[y] = x;
            dfs(y, x);
        }
    }

    static void pro() {
        // 1번 노드 부터 시작
        dfs(1, -1);

        for(int i=2; i<=N; i++) {
            sb.append(parent[i]).append('\n');
        }
        System.out.println(sb);
    }

    public static void main(String[] args) {
        input();
        pro();
    }


    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while(st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        Integer nextInt() {
            return Integer.parseInt(next());
        }

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}
profile
차근차근

0개의 댓글