[백준] 18352번 특정 거리의 도시 찾기

JaeYeop·2022년 4월 11일
0

백준

목록 보기
8/19

[문제]

https://www.acmicpc.net/problem/18352

[코드]

import sys
import heapq
INF = int(1e9)
input = sys.stdin.readline

n, m, k, x = map(int, input().split())
graph = [[] for i in range(n + 1)]
for i in range(m):
    a, b = map(int, input().split())
    graph[a].append(b)

def dijkstra():
    heap = []
    distance = [INF] * (n + 1)

    heapq.heappush(heap, [0, x])
    distance[x] = 0
    while heap:
        dist, now = heapq.heappop(heap)

        if distance[now] < dist:
            continue

        for i in graph[now]:
            cost = dist + 1
            if cost < distance[i]:
                distance[i] = cost
                heapq.heappush(heap, [cost, i])

    return distance


distance = dijkstra()
if k not in distance:
    print(-1)
else:
    for i in range(len(distance)):
        if distance[i] == k:
            print(i)

[풀이]

다익스트라 알고리즘을 통해서 먼저 시작점에서의 최단거리 테이블을 만든다

그리고 만든 테이블에서 이동 비용이 k인 값이 없으면 -1을 출력하고, 아니라면 인덱스 값을 출력한다

profile
이게 왜 틀리지... (나의 메모용 블로그)

0개의 댓글