15681 (트리와 쿼리)
15681 (트리와 쿼리)
어떤 걸 사용하나요?
DP를 활용한다. 트리 구조에서 미리 탐색을 통해 배열에 각 노드의 정점 개수를 채워두고, 쿼리는 배열에 저장된 값으로 응답하여 시간 복잡도를 줄인다.
어떻게 구현하나요?
DP 상태: dp[i]는 i를 루트로 하는 서브트리의 정점 개수를 의미한다.
- DFS로 트리를 모두 순회한다.
dp[root]는 자기 자신(root)을 포함하여 모든 자식 노드들의 서브트리 정점 개수의 합이다.
- Query에 응답한다.
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
52
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> graph;
vector<int> dp;
int solve(int root, int parent){
// 채워져있으면 리턴
if(dp[root] != -1) return dp[root];
// 1로 초기화
dp[root] = 1;
// root는 모든 하위 노드들이 가진 정점의 합
for(int val : graph[root]){
if(parent == val) continue;
dp[root] += solve(val, root);
}
return dp[root];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, r, q;
cin >> n >> r >> q;
graph = vector<vector<int>>(n+1, vector<int>());
dp = vector<int>(n+1, -1);
for(int i = 0; i < n-1; i++){
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
solve(r, 0);
for(int i = 0; i < q; i++){
int a;
cin >> a;
cout << dp[a] << '\n';
}
return 0;
}
This post is licensed under CC BY 4.0 by the author.
