본문 바로가기
Study/Coding Test

[백준] 1504 - 특정한 최단 경로 Python

by 들숨날숨흡 2023. 10. 12.
728x90

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

 

1504번: 특정한 최단 경로

첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존

www.acmicpc.net

import sys
from collections import defaultdict
import heapq

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

def dijkstra(start, end):
    distance = [INF] * (N + 1)
    queue = []
    heapq.heappush(queue, (0, start))
    distance[start] = 0
    while queue:
        dist, current = heapq.heappop(queue)
        if distance[current] < dist:
            continue
        for i in graph[current]:
            next_dist = i[1] + dist
            if next_dist < distance[i[0]]:
                distance[i[0]] = next_dist
                heapq.heappush(queue, (next_dist, i[0]))
    if distance[end] == INF:
        flag = 0
    # print(distance)
    return distance[end]

def check(flag, path):
    if flag == 0:
        flag = 1
        return INF
    return path

N, M = map(int, input().split(" "))
graph = defaultdict(list)
flag = 1
for i in range(M):
    a, b, c = map(int, input().split(" "))
    graph[a].append((b, c))
    graph[b].append((a, c))
V1, V2 = map(int, input().split(" "))

path1 = dijkstra(1, V1) + dijkstra(V1, V2) + dijkstra(V2, N)

path2 = dijkstra(1, V2) + dijkstra(V1, V2) + dijkstra(V1, N)

if path1 >= INF and path2 >= INF:
    print(-1)
else:
    print(min(path1, path2))

큰 어려움 없이 풀어서.. 짧게 작성하겠습니당.. :)

 

 


https://github.com/sumini0516

 

sumini0516 - Overview

sumini0516 has 6 repositories available. Follow their code on GitHub.

github.com

 

728x90