Skip to content

Commit 5c9ae36

Browse files
committed
[BOJ] #1949. 우수마을 / 골드2 / 60분 / 힌트, 성공
1 parent 07837c1 commit 5c9ae36

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import sys
2+
input = sys.stdin.readline
3+
sys.setrecursionlimit(10 ** 6) # 재귀 깊이 설정 (10만)
4+
5+
# 1. 입력 받기
6+
N = int(input()) # 마을 개수
7+
people = [0] + list(map(int, input().split())) # 각 마을 주민 수 (인덱스 맞추기 위해 0 추가)
8+
9+
# 2. 마을 연결 (트리 구성)
10+
town = [[] for _ in range(N + 1)]
11+
12+
for _ in range(N - 1):
13+
u, v = map(int, input().split())
14+
town[u].append(v)
15+
town[v].append(u)
16+
17+
# 3. DP 테이블 초기화 및 방문 리스트
18+
dp = [[0, 0] for _ in range(N + 1)] # dp[i][0]: 우수 마을 X, dp[i][1]: 우수 마을 O
19+
visited = [False] * (N + 1)
20+
21+
22+
# 4. DFS를 통한 서브트리 탐색 및 DP 계산
23+
def dfs(current):
24+
visited[current] = True # 현재 노드 방문 처리
25+
dp[current][1] += people[current] # 현재 마을을 우수 마을로 선정한 경우 (자기 자신 포함)
26+
27+
for child in town[current]:
28+
if not visited[child]:
29+
dfs(child) # 자식 노드로 DFS 진행
30+
dp[current][1] += dp[child][0] # 자식 노드가 우수 마을이 아닌 경우 주민 수 더하기
31+
dp[current][0] += max(dp[child][0], dp[child][1]) # 자식 노드에서 우수 마을이거나 아닌 경우 중 최대값 선택
32+
33+
34+
# 5. DFS 호출 (루트 노드 1부터 시작)
35+
dfs(1)
36+
37+
# 6. 결과 출력
38+
print(max(dp[1][0], dp[1][1]))

0 commit comments

Comments
 (0)