happy318
팽도리블로그
happy318
전체 방문자
오늘
어제
  • 전체글 (252)
    • 공부 (5)
      • Algorithm 정리 (0)
      • 논문리뷰 (1)
      • C++ (2)
      • Python (2)
      • Java (0)
      • Back-end (0)
      • Front-end (0)
      • Embedded (0)
    • 코딩테스트 (218)
      • Python 문제풀이 (100)
      • C++ 문제풀이 (108)
      • Python template (9)
      • C++ template (1)
    • 일상 (20)
      • 맛집 (13)
      • 쇼핑 (5)
      • 아무 일상 (2)
    • 게임 (9)
      • 메이플스토리 (9)

최근 글

인기 글

hELLO · Designed By 정상우.
happy318

팽도리블로그

코딩테스트/Python 문제풀이

[백준] 최소비용 구하기 2

2022. 9. 6. 16:29

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

 

11779번: 최소비용 구하기 2

첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스

www.acmicpc.net

다익스트라 알고리즘을 사용하는 문제입니다.

 

우선 문제부터 간단하게 요약하면,

도시의 개수, 버스의 개수가 주어지고 버스들의 cost가 주어집니다. 이 때, 출발 도시에서 도착 도시까지의 최단 cost를 구하고, 이때의 path 정보 또한 구해야 하는 문제입니다.

 

<Solution>

기존의 다익스트라 알고리즘에 추가적으로 최단 거리로 가는 경로 또한 구해야 하는 문제입니다.

 

최단 cost는 인접 리스트와, heap을 이용한 fast dijkstra 알고리즘으로 구현이 가능합니다. 여기에 추가적으로 최단 경로에 대해 생각을 해보면, 다익스트라 알고리즘 진행 중 최단 경로가 갱신이 될 때, parent를 저장하는 형태로 구현 할 수 있습니다. 

https://stackoverflow.com/questions/28998597/how-to-save-shortest-path-in-dijkstra-algorithm

 

how to save shortest path in dijkstra algorithm

So first let's define Dijkstra algorithm: Dijkstra's algorithm finds single-source shortest paths in a directed graph with non-negative edge weights. I want to know how can I save the shortest path...

stackoverflow.com

 

 

코드 진행중 아래의 한줄 코드를 추가함으로써 path정보를 저장할 수 있습니다. 

            # update parent
            parent[e_dst] = city

실제 구현은 아래와 같습니다.

import sys
import heapq

n = int(sys.stdin.readline()) # city
m = int(sys.stdin.readline()) # bus

array = [[] for _ in range(n+1)]

for _ in range(m):
    src, dst, cost = list(map(int, sys.stdin.readline().rstrip().split()))
    array[src].append([dst, cost])
    
f_src, f_dst = list(map(int, sys.stdin.readline().rstrip().split()))
### done with input ###
    
# dijkstra with path
parent = list(range(n+1)) # [0,1,2,...n]
distance = [int(2e9)]*(n+1)
distance[f_src] = 0
heap = [(0, f_src)]

while(heap):
    dist, city = heapq.heappop(heap)
    
    if distance[city] < dist:
        continue
    
    for e_dst, e_cost in array[city]:
        new_cost = dist + e_cost
        if distance[e_dst] > new_cost:
            # update parent
            parent[e_dst] = city
            distance[e_dst] = new_cost
            heapq.heappush(heap, (new_cost, e_dst))
        
# find path
path = []
tmp = f_dst
while(1):
    path.append(tmp)
    if tmp == parent[tmp]:
        break
    tmp = parent[tmp]
    
    
# print answers
print(distance[f_dst])
print(len(path))
print(' '.join(list(map(str, path[::-1]))))
반응형

'코딩테스트 > Python 문제풀이' 카테고리의 다른 글

[백준] 미세먼지 안녕!  (2) 2022.09.07
[백준] 숨바꼭질 2  (0) 2022.09.06
[백준] 감시  (0) 2022.07.28
[백준] 톱니바퀴  (0) 2022.07.26
[백준] 경사로  (0) 2022.07.26
    '코딩테스트/Python 문제풀이' 카테고리의 다른 글
    • [백준] 미세먼지 안녕!
    • [백준] 숨바꼭질 2
    • [백준] 감시
    • [백준] 톱니바퀴
    happy318
    happy318

    티스토리툴바