From 64cefd05b4018ce0db10bd9763ca17fffa68eab1 Mon Sep 17 00:00:00 2001 From: tgyuuAn Date: Wed, 21 Aug 2024 02:12:46 +0900 Subject: [PATCH] 71-tgyuuAn --- tgyuuAn/README.md | 1 + ...41\353\213\250\353\263\264\353\217\204.py" | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 "tgyuuAn/\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274/\355\232\241\353\213\250\353\263\264\353\217\204.py" diff --git a/tgyuuAn/README.md b/tgyuuAn/README.md index 73034d56..6e403df7 100644 --- a/tgyuuAn/README.md +++ b/tgyuuAn/README.md @@ -77,4 +77,5 @@ | 68차시 | 2024.08.06 | 그리디 | 가희와 탑 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/226 | 69차시 | 2024.08.10 | 누적합, 수학 | 1의 개수 세기 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/228 | 70차시 | 2024.08.16 | 스택 | 탑 보기 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/232 +| 71차시 | 2024.08.20 | 다익스트라 | 다익스트라 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/235 --- diff --git "a/tgyuuAn/\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274/\355\232\241\353\213\250\353\263\264\353\217\204.py" "b/tgyuuAn/\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274/\355\232\241\353\213\250\353\263\264\353\217\204.py" new file mode 100644 index 00000000..a7cec57d --- /dev/null +++ "b/tgyuuAn/\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274/\355\232\241\353\213\250\353\263\264\353\217\204.py" @@ -0,0 +1,40 @@ +from collections import defaultdict +from heapq import * +import sys + +def input(): return sys.stdin.readline().rstrip() +MAX = 100_000 * 700_000 + 1 +N, M = map(int, input().split()) + +graph = defaultdict(lambda : defaultdict(list)) + +for idx in range(1,M+1): + start, destination = map(int, input().split()) + graph[start][destination].append(idx) + graph[destination][start].append(idx) + +costs = [MAX for _ in range(N+1)] +visited = set() +heap = [(0, 1)] +while heap: + now_cost, now_idx = heappop(heap) + + if now_idx in visited: continue + visited.add(now_idx) + + if costs[now_idx] <= now_cost: continue + costs[now_idx] = now_cost + + if now_idx == N: break + + for neighbor in graph[now_idx]: + if neighbor in visited: continue + + for neighbor_idx in graph[now_idx][neighbor]: + + real_idx = now_cost % M + if real_idx < neighbor_idx: + heappush(heap, (neighbor_idx - real_idx + now_cost, neighbor)) + else: + heappush(heap, (now_cost + M - real_idx + neighbor_idx, neighbor)) +print(costs[-1]) \ No newline at end of file