알고리즘(python)/기본
[Python]트리에서의 동적 계획법 백준 15681
개발일기
2020. 3. 27. 23:52
반응형
문제
https://www.acmicpc.net/problem/15681
친절하게 사이트에 가보면 아래 풀이까지 나와있다.
참고하지 않아도 될정도로 간단하긴 하지만 기본적인 부분부터 잘 설명되어 있다.
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 | import sys sys.setrecursionlimit(10**9) N,R,Q=map(int,sys.stdin.readline().split()) Tree=[[] for _ in range(N+1)]#트리 구성 node_count=[0] * (N+1)#노드 개수 check=[True for _ in range(N+1)]#방문여부 for _ in range(N-1): U,V=map(int,sys.stdin.readline().split()) Tree[U].append(V) Tree[V].append(U) def count_node(r): node_count[r]=1 for node in Tree[r]:#연결된 노드 탐색 if not node_count[node]:#방문가능하면 count_node(node) node_count[r]+=node_count[node] return count_node(R) for _ in range(Q): q=int(sys.stdin.readline()) print(node_count[q]) | cs |
반응형