Koala - 11기/코딩테스트 준비 스터디

[백준/Python] 18223 민준이와 마산 그리고 건우

긍살:D 2023. 8. 28. 03:47

문제링크

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

 

18223번: 민준이와 마산 그리고 건우

입력의 첫 번째 줄에 정점의 개수 V와 간선의 개수 E, 그리고 건우가 위치한 정점 P가 주어진다. (2 ≤ V  ≤ 5,000, 1 ≤ E ≤ 10,000, 1 ≤ P  ≤ V) 두 번째 줄부터 E개의 줄에 걸쳐 각 간선의 정보

www.acmicpc.net


 

코드

import heapq
input = __import__('sys').stdin.readline
v,e,p = map(int,input().split())
graph = [[]*(v+1) for _ in range(v+1)]
INF = float('inf')
for _ in range(e):
    a,b,c = map(int,input().split())
    graph[a].append((b,c))
    graph[b].append((a,c))
def dijkstra(start):
    distance = [INF for _ in range(v+1)]
    distance[start] = 0
    q = []
    heapq.heappush(q,(0,start))
    while q:
        dist, node = heapq.heappop(q)
        if dist>distance[node]:continue
        for nextNode, nextDist in graph[node]:
            cost = nextDist + dist
            if cost<distance[nextNode]:
                distance[nextNode] = cost
                heapq.heappush(q,(cost,nextNode))
    return distance
d = dijkstra(1)
a,c = d[p], d[v]
nd = dijkstra(p)
b = nd[v]
if a+b==c:print("SAVE HIM")
else:print("GOOD BYE")

문제풀이

기본적인 다익스트라에서 시작점과 끝점을 달리하여 최단거리를 구해서 풀면 된다.

민준->건우 최단거리 + 건우->마산 최단거리  == 건우-> 마산 최단거리이면, 민준이는 마산을 가면서 건우를 도와줄 수 있다.