본문 바로가기
PS/프로그래머스

프로그래머스 합승 택시 요금 파이썬

by 지기_ 2021. 8. 14.
반응형

1. 문제

https://programmers.co.kr/learn/courses/30/lessons/72413

 

코딩테스트 연습 - 합승 택시 요금

6 4 6 2 [[4, 1, 10], [3, 5, 24], [5, 6, 2], [3, 1, 41], [5, 1, 24], [4, 6, 50], [2, 4, 66], [2, 3, 22], [1, 6, 25]] 82 7 3 4 1 [[5, 7, 9], [4, 6, 4], [3, 6, 1], [3, 2, 3], [2, 1, 6]] 14 6 4 5 6 [[2,6,6], [6,3,7], [4,6,7], [6,5,11], [2,5,12], [5,3,20], [2,4

programmers.co.kr

 

 

2. 풀이

다익스트라

 

3. 구현

import math
import heapq
    
def solution(n, s, a, b, fares):
    answer = 0
    
    gph=[[] for _ in range(n+2)]
    for f in fares:
        [curs,cure,curw] = f
        gph[curs].append((cure,curw))
        gph[cure].append((curs,curw))
    
    answer_lis=[]
    for i in range(1, n+1):
        dist=[math.inf for _ in range(n+2)]
        edges=[]
        
        dist[i] = 0
        heapq.heappush(edges, (dist[i], i))
        
        while edges:
            cost,pos = heapq.heappop(edges)
            if dist[pos]<cost:
                continue
            for p,c in gph[pos]:
                c+=cost
                if dist[p]>c:
                    dist[p]=c
                    heapq.heappush(edges, (c,p))
        
        answer_lis.append(dist[a]+dist[b]+dist[s])
        
    return(min(answer_lis))

 

4. 테스트케이스 추가

 

 

반응형

댓글