[파이썬] 백준 1595 : 북쪽나라의 도로 (골드4)
풀이
방향성 생각
BFS를 통해서 한 점에서 가장 끝 점으로 간 후 BFS를 돌려준다.
트리의 지름을 구하는 문제와 동일한 발상
전체코드
from collections import deque, defaultdict as dd
import sys
input = lambda: sys.stdin.readline().rstrip()
graphs = dd(list)
while True:
try:
a,b,c = map(int,input().split())
graphs[a].append((b,c))
graphs[b].append((a,c))
except:
break
def bfs(x):
visit = dd(int)
visit[x] = 0
q = deque([(x,0)])
while q:
x,c = q.popleft()
for nx,cost in graphs[x]:
nc = c + cost
if nx not in visit:
visit[nx] = nc
q.append((nx,nc))
return visit
if not graphs:
print(0)
else:
a,c = max(bfs(b).items(),key = lambda x:x[1])
print(max(bfs(a).values()))
코멘트
- 예전에 10트해서 못풀었었는데, strip 대신 stip써서 통과 안됐음...
'Algorithm > Graph' 카테고리의 다른 글
[파이썬] 백준 1753 : 최단경로 (골드4) (0) | 2024.11.18 |
---|---|
[파이썬] 백준 2479 : 경로찾기 (골드4) (0) | 2024.11.16 |
[파이썬] 백준 1240 : 노드 사이의 거리 (골드5) (0) | 2024.11.15 |
[파이썬] 백준 1368 : 물대기 (골드2) (0) | 2024.09.21 |
[파이썬] 백준 1197 : 최소 스패닝 트리 (골드4) (0) | 2024.09.03 |
[파이썬] 백준 11404 : 플로이드 (골드4) (0) | 2024.08.01 |
[파이썬] 백준 1967 : 트리의 지름 (골드4) (0) | 2024.08.01 |
댓글