Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 공공데이터 포털
- 꿀팁 환영
- 훈수 가능
- 사업계획서
- apk 빌드
- expo
- url 랜더링
- Redux
- 창업 300
- 티스토리챌린지
- 보안
- web-view
- Dreamhack
- 코딩테스트
- php-1
- React
- python
- 개발
- 프로그래머스
- 오블완
- redux state값 유지
- API 활용 신청
- level3
- react-router-dom
- 블로그 뉴비
- 부산 맛집 OPEN API
- 새로고침
- 드림핵
- 고고학 최고의 발견
Archives
- Today
- Total
1223v
[BOJ] Python 택배(1719) 본문
https://www.acmicpc.net/problem/1719
플로이드 워셜로 푸는 대표적인 문제이다.
거리 배열 외에도 정답배열을 통해 최단 경로시 가장 먼저 접근해야하는 노드의 값을 테이블로 만들어야 한다.
import sys
input = sys.stdin.readline
N,M = map(int,input().split())
distance = [[float('inf')] * (N+1) for _ in range(N+1)]
graph = [[0] * (N+1) for _ in range(N+1)]
for _ in range(M):
s,e,cost = map(int,input().split())
if distance[s][e] > cost:
distance[s][e] = cost
graph[s][e] = e
if distance[e][s] > cost:
distance[e][s] = cost
graph[e][s] = s
def floyid():
for k in range(1,N+1):
for i in range(1,N+1):
for j in range(1,N+1):
if distance[i][j] > distance[i][k] + distance[k][j]:
distance[i][j] = distance[i][k] + distance[k][j]
graph[i][j] = graph[i][k]
floyid()
for i in range(1,N+1):
for j in range(1,N+1):
if float('inf') <= distance[i][j] or i==j:
print('-',end=' ')
else:
print(graph[i][j],end=' ')
print()
dijkstra 풀이
import sys
import heapq
input = sys.stdin.readline
N,M = map(int,input().split())
distance = [[float('inf')] * (N+1) for _ in range(N+1)]
graph = [[] for _ in range(N+1)]
result = [[0] * (N+1) for _ in range(N+1)]
for _ in range(M):
s,e,cost = map(int,input().split())
graph[s].append((e,cost))
graph[e].append((s,cost))
result[s][e] = e
result[e][s] = s
def dijkstra(start):
hq = []
distance[start][start] = 0
heapq.heappush(hq,(0,start))
while hq:
dist, now_node = heapq.heappop(hq)
if distance[start][now_node] > dist:
continue
for next_node, cost in graph[now_node]:
if distance[start][next_node] > dist + cost:
distance[start][next_node] = dist + cost
if now_node == start:
result[start][next_node] = next_node
else:
result[start][next_node] = result[start][now_node]
heapq.heappush(hq,(dist+cost, next_node))
for i in range(1,N+1):
dijkstra(i)
for i in range(1,N+1):
for j in range(1,N+1):
if i == j:
print('-',end=' ')
else:
print(result[i][j], end= ' ')
print()
회고.
가장 먼저 접근해야하는 노드 테이블을 갱신할 때, 노드 테이블을 참조해서 갱신( graph[i][j] = graph[i][k] )해야하는데
(graph[i][j] = k) k값을 그냥 때려박는 발상으로 좀 헤맷던 것 같다..
728x90
'PS' 카테고리의 다른 글
[Programmers] Python 합승 택시 요금 (72413) (0) | 2025.02.22 |
---|---|
[BOJ] Python 회문(17609) (0) | 2025.02.20 |
[BOJ] Python 플로이드(11404) (0) | 2025.02.18 |
[Programmers] Python 파괴되지 않은 건물 (92344) (0) | 2025.02.17 |
[BOJ] Python, Ruby 백준 최소 회의실 개수 (19598) (0) | 2025.02.17 |