백준 1967 트리의 지름 풀이 ( 파이썬 )
1967번: 트리의 지름
파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연
www.acmicpc.net
한 노드를 정하고 가장 깊은 노드를 탐색한 후 그 노드에서 다시 가장 깊은 노드를 탐색했다.
import sys
sys.setrecursionlimit(10**9)
input=sys.stdin.readline
n=int(input())
result1=[0 for _ in range(n+1)]
result2=[0 for _ in range(n+1)]
tree=[[] for _ in range(n+1)]
def dfs(cur,result):
for i in range(len(tree[cur])):
end,dis=tree[cur][i]
if result[end] == 0:
result[end]=result[cur]+dis
dfs(end,result)
for _ in range(n-1):
a,b,c=map(int,input().split())
tree[a].append((b,c))
tree[b].append((a,c))
dfs(1,result1)
result1[1]=0
maxi=0
index=0
for i in range(len(result1)):
if maxi<result1[i]:
maxi=result1[i]
index=i
dfs(index,result2)
result2[index]=0
print(max(result2))
[ baekjoon ] 문자열 복사 2195번 ( python ) (0) | 2021.05.15 |
---|---|
[ baekjoon ] 트리의 지름 1167번 ( python ) (0) | 2021.05.09 |
[ baekjoon ] 트리의 부모 찾기 11725번 ( python ) (0) | 2021.05.07 |
[ baekjoon ] 두 배열의 합 2143번 ( python ) (0) | 2021.04.27 |
[ baekjoon ] 신기한 소수 2023번 ( python ) (0) | 2021.04.14 |