[백준] 최단경로

이정연·2023년 3월 28일
0

CodingTest

목록 보기
136/165

[Gold IV] 최단경로 - 1753

문제 링크

성능 요약

메모리: 149508 KB, 시간: 704 ms

분류

그래프 이론, 데이크스트라

문제 설명

방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다.

입력

첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가 주어진다. 셋째 줄부터 E개의 줄에 걸쳐 각 간선을 나타내는 세 개의 정수 (u, v, w)가 순서대로 주어진다. 이는 u에서 v로 가는 가중치 w인 간선이 존재한다는 뜻이다. u와 v는 서로 다르며 w는 10 이하의 자연수이다. 서로 다른 두 정점 사이에 여러 개의 간선이 존재할 수도 있음에 유의한다.

출력

첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i번 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF를 출력하면 된다.

설계

main

if __name__ == '__main__':
    V,E = map(int,input().split())
    K = int(input())
    graph = defaultdict(list)

    for _ in range(E):
        u,v,w = map(int,input().split())
        graph[u].append((w,v))

    for answer in dijkstra(graph,K,V)[1:]:
        if answer == INF:
            print('INF')
        else:
            print(answer)
  • input을 받는다.
  • 다익스트라 결과를 출력한다.

dijkstra

def dijkstra(graph,start,V):
    heap = []
    distance = [INF]*(V+1)
    distance[start] = 0
    h.heappush(heap,(distance[start],start))

    while heap:
        cur_dist, cur_node = h.heappop(heap)
        for next_dist,next_node in graph[cur_node]:
            if distance[next_node] > cur_dist + next_dist:
                distance[next_node] = cur_dist + next_dist
                h.heappush(heap,(distance[next_node],next_node))
    
    return distance

다익스트라 함수!

자세한 내용은 본 포스팅 참고!

전체 코드

import heapq as h
from collections import defaultdict
INF = int(1e9)

def dijkstra(graph,start,V):
    heap = []
    distance = [INF]*(V+1)
    distance[start] = 0
    h.heappush(heap,(distance[start],start))

    while heap:
        cur_dist, cur_node = h.heappop(heap)
        for next_dist,next_node in graph[cur_node]:
            if distance[next_node] > cur_dist + next_dist:
                distance[next_node] = cur_dist + next_dist
                h.heappush(heap,(distance[next_node],next_node))
    
    return distance

if __name__ == '__main__':
    V,E = map(int,input().split())
    K = int(input())
    graph = defaultdict(list)

    for _ in range(E):
        u,v,w = map(int,input().split())
        graph[u].append((w,v))

    for answer in dijkstra(graph,K,V)[1:]:
        if answer == INF:
            print('INF')
        else:
            print(answer)

🚨그래프를 딕셔너리가 아닌 이중 리스트로 구현하면 메모리 초과 발생!🚨

profile
0x68656C6C6F21

0개의 댓글