Skip to content

Commit 4aaaf76

Browse files
authored
Merge pull request #118 from YoonYn9915/main
YoonYn9915 / 1월 1주차 / 3문제
2 parents b8ae06a + b9d0e26 commit 4aaaf76

File tree

3 files changed

+87
-0
lines changed

3 files changed

+87
-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])
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import sys, collections
2+
3+
sys.setrecursionlimit(10 ** 6)
4+
5+
6+
def dfs(cur):
7+
visited[cur] = 1
8+
for u in g[cur]:
9+
if not visited[u]:
10+
dfs(u)
11+
dp[cur][1] += dp[u][0]
12+
dp[cur][0] += max(dp[u][0], dp[u][1])
13+
14+
15+
n = int(sys.stdin.readline().strip())
16+
cost = [0] + [int(x) for x in sys.stdin.readline().split()]
17+
18+
visited = [0 for _ in range(n + 1)]
19+
dp = [[0, cost[i]] * 2 for i in range(n + 1)]
20+
g = collections.defaultdict(list)
21+
22+
for _ in range(n - 1):
23+
v, u = map(int, sys.stdin.readline().split())
24+
g[v].append(u)
25+
g[u].append(v)
26+
27+
dfs(1)
28+
print(max(dp[1][1], dp[1][0]))
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
t = int(input())
2+
3+
for i in range(t):
4+
col = int(input())
5+
graph=[]
6+
for j in range(2):
7+
graph.append(list(map(int, input().split())))
8+
9+
if col == 1:
10+
print(max(graph[0][0], graph[1][0]))
11+
continue
12+
13+
graph[0][1] += graph[1][0]
14+
graph[1][1] += graph[0][0]
15+
16+
for k in range(2, col):
17+
graph[0][k] += max(graph[1][k-1], graph[1][k-2])
18+
graph[1][k] += max(graph[0][k-1], graph[0][k-2])
19+
20+
print(max(graph[0][col-1], graph[1][col-1]))

0 commit comments

Comments
 (0)