Skip to content

Commit a2488c1

Browse files
committed
[BOJ] 트리와 쿼리 / 골드5 / 70분
https://www.acmicpc.net/problem/15681
1 parent d653d5b commit a2488c1

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
'''
2+
1. 트리 정보 입력받기. 무방향 그래프이기 때문에 간선을 잇는 두 노드에 다 저장.
3+
2. 부모 노드의 서브 트리의 수는 모든 자식 노드의 서브 트리 수의 합으로 분할 할 수 있다.
4+
즉 분할 & 정복 가능하며 그래프를 순회하며 각 정점에서 서브트리의 수를 메모이제이션 해야 한다.
5+
6+
'''
7+
8+
import sys
9+
10+
inp = sys.stdin.readline
11+
sys.setrecursionlimit(10 ** 6)
12+
13+
N, R, Q = map(int, inp().split())
14+
15+
subtree = [0] * (N + 1)
16+
graph = [[] for _ in range(N + 1)]
17+
18+
for _ in range(N - 1):
19+
first_node, second_node = map(int, inp().split())
20+
graph[first_node].append(second_node)
21+
graph[second_node].append(first_node)
22+
23+
24+
# node_num: 현재 노드 번호
25+
def count_subtree(graph, subtree, node_num):
26+
# 방문 체크
27+
subtree[node_num] = 1
28+
29+
for child_node in graph[node_num]:
30+
if subtree[child_node] == 0:
31+
count_subtree(graph, subtree, child_node)
32+
subtree[node_num] += subtree[child_node]
33+
34+
35+
count_subtree(graph, subtree, R)
36+
37+
for i in range(Q):
38+
node_num = int(inp())
39+
print(subtree[node_num])

0 commit comments

Comments
 (0)