[BOJ] 15681번 트리와 쿼리 - C++

"트리에서의 동적 계획법"

Posted by Yongmin on August 30, 2021

문제

트리와 쿼리

풀이

DFS를 이용한 문제이다. 루트 번호가 주어졌기 때문에, DFS를 통해서 call이 되는 수만큼을 dp배열에 저장해준다.

소스 코드

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
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <vector>

using namespace std;

vector<int> map[100001];
//int parent[100001];
bool visited[100001];
int dp[100001];

int candidate(int start){
    visited[start] = true;
    for(int i = 0; i<map[start].size(); i++){
        int next = map[start][i];
        if(visited[next] == false){
            dp[start] += candidate(next);
        }
    }
    
    
    return dp[start];
}

int main(){
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);
    
    for(int i = 0; i<a-1; i++){
        int from, to;
        scanf("%d %d", &from, &to);
        
        map[from].push_back(to);
        map[to].push_back(from);
    }
    
    for(int i = 0; i<=a; i++){
        dp[i] = 1;
    }
    
    candidate(b);
    
    
    for(int i = 0; i<c; i++){
        int u;
        scanf("%d", &u);
        
        printf("%d\n", dp[u]);
    }
     
    
}


# # #