1. 문제
8347번: Bug
The first line of input contains two integers n and m (2 ≤ n ≤ 200 000, 0 ≤ m ≤ 500 000), separated by a single space and denoting the number of cities and the number of roads in Byteland. The cities are numbered from 1 to n; Bytetown has number
www.acmicpc.net
2. 풀이
목적지까지 최단경로를 구해야하는데
문제는 홀수길이를 가지는 최단 경로를 구해야한다

그냥 사용하면 2를 답을 내는데.. 문제에서 원하는건 7로 가는 경로이다
쉬운 문제인데 이게 생각하기가 힘드네
너무 오랜만에 다익스트라 사용해서 그런가
어떻게 하냐면.. distance를 2차원으로 만들면 된다
짝수 최단경로 길이를 가지는 칸과 홀수 최단 경로 길이를 가지는 칸
그래서 다익스트라 알고리즘을 사용하는 중에, 길이가 짝수이면 짝수인 칸에 저장하고
홀수이면 홀수인 칸에 저장하도록 하면 된다
import heapq
from sys import stdin
INF = 100000000000000000000000000000
def dijkstra(start,n):
q = []
distance = [[INF,INF] for _ in range(n+1)]
distance[start][0] = 0
distance[start][1] = 0
heapq.heappush(q,(0,start))
while q:
dist,v = heapq.heappop(q)
if distance[v][dist%2] < dist:
continue
for b,c in graph[v]:
cost = dist + c
if distance[b][cost%2] > cost:
distance[b][cost%2] = cost
heapq.heappush(q,(cost,b))
return distance
n,m = map(int,stdin.readline().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
a,b,c = map(int,stdin.readline().split())
graph[a].append((b,c))
graph[b].append((a,c))
distance = dijkstra(1,n)
if distance[n][1] == INF:
print(0)
else:
print(distance[n][1])
728x90
'알고리즘 > 최단거리 알고리즘' 카테고리의 다른 글
다익스트라 알고리즘 조금 어려운 문제로 오랜만에 재활하기1 (0) | 2023.04.16 |
---|---|
다익스트라 알고리즘 응용 - 다른 정점에서 목적지로 되돌아오는 최단거리 구하는 방법 (0) | 2023.04.16 |
가중치가 음수인 경우에 최단거리를 구하는 벨만 포드 알고리즘 익히기 (0) | 2022.12.01 |
다익스트라 알고리즘에서 실제 최단 경로 구하기 (0) | 2022.10.10 |
최단 거리를 구하는 2번째 알고리즘 플로이드 워셜 알고리즘 파헤치기 (0) | 2022.10.09 |