[BOJ] 11725번 트리의 부모 찾기 - C++

"트리"

Posted by Yongmin on August 17, 2021

문제

트리의 부모 찾기

풀이

트리의 부모를 찾는 문제이다. 인접리스트에서 dfs방식으로 부모와 자식 노드들을 result 배열에 담아 출력하였다.

소스 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <vector>

using namespace std;

vector<int> map[100001];
bool visited[1000001];
int result[1000001];

int N;

void dfs(int start){
    if(visited[start] == true){
        return;
    }
    //vistied == false
    visited[start] = true;
    for(int i = 0; i<map[start].size(); i++){
        int next = map[start][i];
        if(visited[next] == false){
            result[next] = start;
            dfs(next);
        }
        
    }
    
}
int main(){
    scanf("%d", &N);
    for(int i = 0; i<N-1; i++){
        int from, to;
        scanf("%d %d", &from, &to);
        
        map[from].push_back(to);
        map[to].push_back(from);
    }
    
    dfs(1);
    for(int i = 2; i<=N; i++){
        printf("%d\n", result[i]);
    }
}


# # #