[프로그래머스] Level3, 합승 택시 요금 (Python)

2021. 8. 10. 14:49·알고리즘/프로그래머스
728x90
반응형

문제

https://programmers.co.kr/learn/courses/30/lessons/72413?language=python3 

 

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

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

 

코드

import heapq
import sys

def solution(n, s, a, b, fares):
    answer = sys.maxsize
    
    def dijkstra(start):
        INF = sys.maxsize
        distance = [INF for _ in range(n+1)]
        distance[start] = 0
        heap = []
        heapq.heappush(heap, (0, start))

        while heap:
            wei, now = heapq.heappop(heap)
            if distance[now] < wei:
                continue
            for w, next_node in graph[now]:
                next_wei = w + wei
                if next_wei < distance[next_node]:
                    distance[next_node] = next_wei
                    heapq.heappush(heap, (next_wei, next_node))
        return distance
    
    graph = [[] for _ in range(n+1)]
    for i in range(len(fares)):
        graph[fares[i][0]].append((fares[i][2], fares[i][1]))
        graph[fares[i][1]].append((fares[i][2], fares[i][0]))
    
    
    for i in range(1, n+1): 
        distance_1 = dijkstra(s)
        distance_2 = dijkstra(i)
        answer = min(answer, distance_1[i] + distance_2[a] + distance_2[b])
    return answer

fares를 우선순위 큐에 넣기 편하게 graph로 새로 리스트를 만들어서 저장해주고 dijkstra를 돌린다.

 

맨처음 출발점 s일때 다익스트라를 돌려 s부터 모든 정점에 최단거리를 구하고

 

a,b 목적지 까지에 최소비용을 찾기위해서 비용이 가장 적게드는 환승 지점을 찾기 위해 for문을 돌려 1부터 n 정점까지 모두 다익스트라를 돌려본다.

 

출발지점 s에서 환승지점 i 까지 비용 + i 환승지점에서 a 목적지 까지 비용 + i 환승지점에서 b 목적지 까지 비용이

가장 작은 값을 구한다.

 

플로이드 풀이

import sys

def floyd(distance, n):
    for k in range(1, n+1):
        for i in range(1, n+1):
            for j in range(1, n+1):
                if distance[i][j] > distance[i][k] + distance[k][j]:
                    distance[i][j] = distance[i][k] + distance[k][j]
    return distance
    
def solution(n, s, a, b, fares):
    INF = sys.maxsize
    answer = INF
    distance = [[INF for _ in range(n+1)] for _ in range(n+1)]
    
    for edge in fares:
        distance[edge[0]][edge[1]] = edge[2]
        distance[edge[1]][edge[0]] = edge[2]
    
    for i in range(1, n+1):
        distance[i][i] = 0
    
    distance = floyd(distance, n)
    
    for k in range(1, n+1): # 합승지점 k 까지 간후 a,b 목적지 갈때 제일 작은값
        answer = min(answer, distance[s][k] + distance[k][a] + distance[k][b])
    
    return answer
반응형
저작자표시 (새창열림)

'알고리즘 > 프로그래머스' 카테고리의 다른 글

[프로그래머스] Level2, 거리두기 확인하기 (Python)  (0) 2021.08.25
[프로그래머스] Level3, 자물쇠와 열쇠 (Python)  (0) 2021.08.10
[프로그래머스] Level 2, 메뉴 리뉴얼 (Python)  (0) 2021.08.05
[프로그래머스] Level 1, 신규 아이디 추천 (Python)  (0) 2021.08.05
[프로그래머스] Level3, 가장 먼 노드 (Python)  (0) 2021.07.26
'알고리즘/프로그래머스' 카테고리의 다른 글
  • [프로그래머스] Level2, 거리두기 확인하기 (Python)
  • [프로그래머스] Level3, 자물쇠와 열쇠 (Python)
  • [프로그래머스] Level 2, 메뉴 리뉴얼 (Python)
  • [프로그래머스] Level 1, 신규 아이디 추천 (Python)
wookcode
wookcode
공부한 내용들을 정리하고 기록하는 블로그입니다.
    반응형
  • wookcode
    wookcode
    wookcode
  • 전체
    오늘
    어제
    • 카테고리 (196) N
      • study (1) N
        • 아파치 카프카 애플리케이션 프로그래밍 with 자.. (0)
        • 인프런 (1) N
      • Live Study (15)
      • Programming (14)
        • Java (8)
        • Python (1)
        • Springboot (5)
        • MSA (0)
      • 알고리즘 (117)
        • 백준 (58)
        • 프로그래머스 (59)
      • 에러로그 (5)
      • 항해99 (23)
      • 면접 (1)
      • 프로젝트 (1)
      • CS (19)
        • 네트워크 (2)
        • 운영체제 (2)
        • 데이터베이스 (2)
        • 컴퓨터구조 (1)
        • Java (8)
        • Spring (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    후기
    스파르타코딩클럽
    java
    SpringBoot
    실전프로젝트
    jpa
    항해99
    SFlash
    조합
    버그
    인프런
    백준
    알고리즘
    정리
    프로그래머스
    해결
    항해마켓
    괄호
    코딩테스트
    orm
    파이썬
    spring
    브루트포스
    카카오인턴
    김영한
    그리디
    미니프로젝트
    회고
    카카오코딩테스트
    에러
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
wookcode
[프로그래머스] Level3, 합승 택시 요금 (Python)
상단으로

티스토리툴바