반응형
https://programmers.co.kr/learn/courses/30/lessons/12978
코딩테스트 연습 - 배달
5 [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]] 3 4 6 [[1,2,1],[1,3,2],[2,3,2],[3,4,3],[3,5,2],[3,5,3],[5,6,1]] 4 4
programmers.co.kr
해결 방법 : 다익스트라
- 다익스트라로 최소비용만 구하면 된다.
from collections import defaultdict
import heapq # 우선순위큐
def solution(N, road, K):
graph = defaultdict(list)
for f, t, c in road: # 그래프 초기화
graph[f].append((t, c))
graph[t].append((f, c))
fees = [float('inf')] * (N + 1) # 1번 마을 기준 최소비용
fees[1] = 0
Q = [(fees[1], 1)] # 현재 cost, 현재 마을
while Q: # 다익스트라
cur_f, cur_n = heapq.heappop(Q)
if fees[cur_n] < cur_f: continue
for next_n, fee in graph[cur_n]:
if cur_f + fee < fees[next_n]:
fees[next_n] = cur_f + fee
heapq.heappush(Q, (cur_f + fee, next_n))
return len([0 for f in fees if f <= K])반응형
'IT study > 알고리즘 문제 풀이' 카테고리의 다른 글
| 프로그래머스 : 2개 이하로 다른 비트 (0) | 2021.06.21 |
|---|---|
| 프로그래머스 : 쿼드압축 후 개수 세기 (0) | 2021.06.21 |
| 백준 2800 : 괄호 제거 (0) | 2021.06.19 |
| 백준 18352 : 특정 거리의 도시 찾기 (0) | 2021.06.18 |
| 백준 3079 : 입국심사 (0) | 2021.06.18 |