728x90
반응형
https://www.acmicpc.net/problem/19238
19238번: 스타트 택시
첫 줄에 N, M, 그리고 초기 연료의 양이 주어진다. (2 ≤ N ≤ 20, 1 ≤ M ≤ N2, 1 ≤ 초기 연료 ≤ 500,000) 연료는 무한히 많이 담을 수 있기 때문에, 초기 연료의 양을 넘어서 충전될 수도 있다. 다
www.acmicpc.net
<풀이>
어렵다.
해당 문제는 '다익스트라 알고리즘(Dijkstra)'을 응용하여 풀었다.
2021.03.18 - [# Coding/# Algorithm] - [보기 쉬운 Algorithm] 다익스트라(Dijkstra) 알고리즘 - Python
[보기 쉬운 Algorithm] 다익스트라(Dijkstra) 알고리즘 - Python
'다익스트라(Dijkstra) 알고리즘'은 비용(가중치) 간선이 있는 노드 그래프의 최단 거리를 구하는 알고리즘 시간을 줄이기 위해서 파이썬 모듈 중 최소 힙을 구현할 수 있는 heapq를 사용한다. ↳ list
joinmycode.tistory.com
<전체 코드>
import sys
import heapq
def dijkstra(graph, n, row, col):
temp_visit = [[float('inf') for _ in range(n)] for _ in range(n)]
temp_visit[row][col] = 0
queue = [[0, [row, col]]]
drow = [-1, 0, 1, 0]
dcol = [0, 1, 0, -1]
while queue:
cur_distance, cur = heapq.heappop(queue)
cur_row, cur_col = cur
if temp_visit[cur_row][cur_col] < cur_distance:
continue
for i in range(4):
new_row = cur_row+drow[i]
new_col = cur_col+dcol[i]
if new_col == n or new_row == n:
continue
elif new_row == -1 or new_col == -1:
continue
if graph[new_row][new_col] == 1:
continue
if cur_distance+1 < temp_visit[new_row][new_col]:
temp_visit[new_row][new_col] = cur_distance+1
heapq.heappush(queue, [cur_distance+1, [new_row, new_col]])
return temp_visit
N, M, fuel = map(int, sys.stdin.readline().split())
graph = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
row, col = map(int, sys.stdin.readline().split())
client = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]
client.sort()
fail = False
while client:
table = dijkstra(graph, N, row-1, col-1)
min_dis = float('inf')
min_per = -1
for i in range(M):
cur_row, cur_col, des_row, des_col = client[i]
if table[cur_row-1][cur_col-1] < min_dis:
min_dis = table[cur_row-1][cur_col-1]
min_per = i
if min_dis == float('inf'):
fail = True
break
cur_row, cur_col, row, col = client.pop(min_per)
M -= 1
drive = dijkstra(graph, N, cur_row-1,
cur_col-1)[row-1][col-1]
if drive == float('inf'):
fail = True
break
elif min_dis + drive > fuel:
fail = True
break
else:
fuel += drive - min_dis
if fail:
print(-1)
else:
print(fuel)
728x90
반응형
'# Coding > # 백준' 카테고리의 다른 글
[백준 / 11724] 연결 요소의 개수 - Python (0) | 2021.07.07 |
---|---|
[백준 / 11725] 트리의 부모 찾기 - Python (0) | 2021.07.07 |
[백준 / 1476] 날짜 계산 - Python (0) | 2021.05.26 |
[백준 / 1504] 특정한 최단 경로 - Python (0) | 2021.05.26 |
[백준 / 1834] 나머지와 몫이 같은 수 - Python (0) | 2021.04.06 |