4485-g4 성공
This commit is contained in:
55
workbook_8708/gold/4485-g4.py
Normal file
55
workbook_8708/gold/4485-g4.py
Normal file
@@ -0,0 +1,55 @@
|
||||
# 녹색 옷 입은 애가 젤다지?
|
||||
|
||||
import sys
|
||||
import heapq
|
||||
|
||||
input = sys.stdin.readline
|
||||
|
||||
def solution():
|
||||
move = [(1,0), (-1, 0), (0, 1), (0, -1)]
|
||||
num = 1
|
||||
while 1:
|
||||
n = int(input().rstrip())
|
||||
if n == 0:
|
||||
break
|
||||
|
||||
grid = [list(map(int, input().rstrip().split())) for _ in range(n)]
|
||||
result = [[float('inf') for _ in range(n)] for _ in range(n)]
|
||||
|
||||
h = []
|
||||
heapq.heappush(h, (grid[0][0], 0, 0))
|
||||
result[0][0] = grid[0][0]
|
||||
|
||||
while h:
|
||||
v, x, y = heapq.heappop(h)
|
||||
|
||||
for dx, dy in move:
|
||||
now_x, now_y = x+dx, y+dy
|
||||
if now_x >= n or now_x < 0 or now_y >= n or now_y < 0:
|
||||
continue
|
||||
now_v = result[x][y] + grid[now_x][now_y]
|
||||
if now_v < result[now_x][now_y]:
|
||||
result[now_x][now_y] = now_v
|
||||
heapq.heappush(h, (now_v, now_x, now_y))
|
||||
|
||||
print(f"Problem {num}: {result[n-1][n-1]}")
|
||||
num += 1
|
||||
|
||||
|
||||
return
|
||||
|
||||
|
||||
solution()
|
||||
|
||||
"""
|
||||
걸린 시간: 25분
|
||||
|
||||
시간 복잡도: 모든 정점을 다 들렸다가 가는 경우에 n^2만큼 봐야하고, 정점 하나를 볼때마다 힙 정렬에 의해 logn만큼 걸린다.
|
||||
따라서 전체 시간복잡도는 O(n^2logn)이다.
|
||||
|
||||
해설: dp로 하려고 했지만 어디서 시작해서 어느 방향으로 채워야 확정인지 나오질 않기 때문에 dp는 불가능 하다.
|
||||
그렇다면 결국 (0,0)에서 (n-1,n-1)로 가는 최단거리를 구해야하고 그 와중에 가중치가 있기 때문에 다익스트라로 풀 수 있다.
|
||||
기본 구현 방식대로 진행하되, 정점간의 연결을 상하좌우로 하면 된다.
|
||||
내가 푼 방식에서 힙에서 꺼냈을 때 v가 result[x][y]보다 크다면 더 볼 필요 없고, (n-1,n-1)이 점이 꺼내졌다면 거기서 다른
|
||||
곳으로 더 갈 필요는 없기 때문에 끝내는 로직을 추가하면 좀 더 빨라질 수 있다.
|
||||
"""
|
||||
Reference in New Issue
Block a user