728x90
반응형
https://www.acmicpc.net/problem/20188
문제 해결
트리와 DFS를 사용해야한다는 것은 쉽게 알 수 있지만 어떻게 활용할지 매우 어려운 문제
다음 동영상을 봐도 어렵다...
CODE
import sys
input = sys.stdin.readline
from collections import deque, defaultdict
sys.setrecursionlimit(10**8)
def dfs(cur, parent):
global ans
for child in graph[cur]:
if child != parent:
dfs(child, cur)
dp[cur] += dp[child] + 1
val = (dp[cur] + 1) * (n - dp[cur] - 1) + (dp[cur]*(dp[cur] + 1)//2)
if cur != 1:
ans += val
if __name__ == "__main__":
n = int(input())
dp = [0]*(n+1)
graph = defaultdict(list)
for _ in range(n-1):
a, b= map(int, input().split())
graph[a].append(b)
graph[b].append(a)
ans = 0
dfs(1,0)
print(ans)
728x90
반응형
'알고리즘 > [python] 백준 BOJ' 카테고리의 다른 글
[python] 백준 4811 알약 (0) | 2024.06.02 |
---|---|
[python] 백준 16565 N 포커 (1) | 2024.05.23 |
[python] 백준 2150 Strongly Connected Component (0) | 2024.05.09 |
[python] 백준 2635 수 이어가기 (0) | 2024.04.18 |
[python] 백준 6986 절사평균 (0) | 2024.04.17 |
댓글