문제 풀이/백준(BOJ)
[Python] 백준 17396번 : 백도어
희조당
2023. 2. 25. 21:56
728x90
https://www.acmicpc.net/problem/17396
17396번: 백도어
첫 번째 줄에 분기점의 수와 분기점들을 잇는 길의 수를 의미하는 두 자연수 N과 M이 공백으로 구분되어 주어진다.(1 ≤ N ≤ 100,000, 1 ≤ M ≤ 300,000) 두 번째 줄에 각 분기점이 적의 시야에 보이는
www.acmicpc.net
💡 문제 풀이
기본적인 다익스트라 문제이다.
추가적으로 특정 조건에 값을 추가할지 말지 확인하는 로직만 추가하면 된다.
✔️ 느낀 점
오타 나서 한참 찾았다..
💻 코드
import heapq, sys
INF = int(1e9)
input = sys.stdin.readline
def dijkstra(start):
q = []
heapq.heappush(q, (0, start))
distance[start] = 0
while q:
currentCost, currentNode = heapq.heappop(q)
if distance[currentNode] < currentCost: continue
for nextCost, nextNode in graph[currentNode]:
newCost = currentCost + nextNode
if newCost < distance[nextCost] and wards[nextCost] == 0:
distance[nextCost] = newCost
heapq.heappush(q, (newCost, nextCost))
N, M = map(int, input().split())
distance = [INF]*(N+1)
wards = list(map(int, input().split()))
wards[-1] = 0
graph = [[] for _ in range(N+1)]
for _ in range(M):
start, end, cost = map(int, input().split())
graph[start].append((end, cost))
graph[end].append((start, cost))
dijkstra(0)
print(distance[N-1] if distance[N-1] != INF else -1)