항해99, 5주차 운동

Jang Seok Woo·2022년 2월 13일
0

알고리즘

목록 보기
64/74

Today I learned
2022/02/08

회고록


2/08

항해 99, 알고리즘 4주차(항해 5주차)

교재 : 파이썬 알고리즘 인터뷰 / 이것이 코딩테스트다(동빈좌)

최단경로

1. 이론

이론 정리 포스팅 글(내 벨로그)

https://velog.io/@jsw4215/%ED%95%AD%ED%95%B499-5%EC%A3%BC%EC%B0%A8-%ED%94%8C%EB%A1%9C%EC%9D%B4%EB%93%9C%EC%9B%8C%EC%85%9C-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98

2. 문제

문제

방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 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를 출력하면 된다.

입력

3 4
1 2 1
3 2 1
1 3 5
2 3 2

출력

3

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

3. MySol

  • 다익스트라 알고리즘
import collections
import heapq  # 우선순위 큐 구현을 위함
import sys


def dijkstra(graph, start):
    distances = {node: float('inf') for node in graph}  # start로 부터의 거리 값을 저장하기 위함
    distances[start] = 0  # 시작 값은 0이어야 함
    queue = []
    heapq.heappush(queue, [distances[start], start])  # 시작 노드부터 탐색 시작 하기 위함.

    while queue:  # queue에 남아 있는 노드가 없으면 끝
        current_distance, current_destination = heapq.heappop(queue)  # 탐색 할 노드, 거리를 가져옴.

        if distances[current_destination] < current_distance:  # 기존에 있는 거리보다 길다면, 볼 필요도 없음
            continue

        for new_destination, new_distance in graph[current_destination]:
            distance = current_distance + new_distance  # 해당 노드를 거쳐 갈 때 거리
            if new_destination == start:
                lst.append(distance)

            if distance < distances[new_destination]:  # 알고 있는 거리 보다 작으면 갱신
                distances[new_destination] = distance
                heapq.heappush(queue, [distance, new_destination])  # 다음 인접 거리를 계산 하기 위해 큐에 삽입

    pass


if __name__ == '__main__':

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

    n, m = map(int, input().split())

    graph = collections.defaultdict(list)

    nodeList = set()

    lst = []

    for _ in range(m):
        a, b, c = map(int, input().split())
        graph[a].append((b, c))
        nodeList.add(a)

    for start in nodeList:
        dijkstra(graph, start)

    if lst:
        print(f'{min(lst)}')
    else:
        print(-1)

4. 배운 점

  • 다익스트라 알고리즘을 구현하여 문제를 해결하였다.
  • heapq를 사용하지 않으면 시간초과가 발생하는 문제

5. 총평

다익스트라 알고리즘 익히기

profile
https://github.com/jsw4215

0개의 댓글