본문 바로가기
코딩테스트 파이썬/백준

트리의 지름 ( 1967번 )

by 세용용용용 2025. 3. 19.

1967번: 트리의 지름

 

나의 풀이

from collections import deque
import sys

def _make_conn_dict(n):
    conn_dict = {i: [] for i in range(1, n + 1)}
    for _ in range(n - 1):
        a, b, c = map(int, sys.stdin.readline().rstrip().split())
        conn_dict[a].append((b, c))
        conn_dict[b].append((a, c))
    return conn_dict

def _route_info(n, start, conn_dict):
    route_info = [False] * n
    route_info[start - 1], queue =0, deque([(start, 0)])
    while queue:
        now_point, now_lenth = queue.popleft()
        for next_point, next_lenth in conn_dict[now_point]:
            if (route_info[next_point - 1] is False):
                route_info[next_point - 1] = (now_lenth + next_lenth)
                queue.append((next_point, (now_lenth + next_lenth)))
    return (route_info, max(route_info)) 

def _result_max_value(n, conn_dict, route_info, max_value):
    answer = 0
    for idx in range(len(route_info)):
        if (route_info[idx] == max_value):
            answer = max(answer, _route_info(n, idx + 1, conn_dict)[1])
    return answer

n = int(sys.stdin.readline().rstrip())
conn_dict = _make_conn_dict(n)
route_info, max_value = _route_info(n, 1, conn_dict)
print(_result_max_value(n, conn_dict, route_info, max_value))

 

시간 복잡도

for idx in range(len(route_info)) : 노드를 순회 ( 선형 시간 )
	if (route_info[idx] == max_value) : 조건 맞는 노드 bfs 함수 실행 ( 선형 시간 ) 
		answer = max(answer, _route_info(n, idx + 1, conn_dict)[1])
해당 알고리즘 시간 복잡도 : 이차형 시간 복잡도 ( O(n ** 2) )

'코딩테스트 파이썬 > 백준' 카테고리의 다른 글

트리의 지름 ( 1167번 )  (0) 2025.03.23
알파벳 ( 1987번 )  (0) 2025.03.19
최단경로 ( 1753번 )  (0) 2025.03.12
특정한 최단 경로 ( 1504번 )  (0) 2025.03.11
벽 부수고 이동하기 ( 2206번 )  (0) 2025.03.09