From 8745be138f85e89a1a64824052f7558fa84fd493 Mon Sep 17 00:00:00 2001 From: yenru0 Date: Mon, 8 Apr 2024 17:20:19 +0900 Subject: [PATCH] complete aloha dijkstra4(28707.py) --- zeta_python/28707.py | 24 ------------- zeta_python/completed/28707.py | 62 ++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 24 deletions(-) delete mode 100644 zeta_python/28707.py create mode 100644 zeta_python/completed/28707.py diff --git a/zeta_python/28707.py b/zeta_python/28707.py deleted file mode 100644 index 2bba7ca..0000000 --- a/zeta_python/28707.py +++ /dev/null @@ -1,24 +0,0 @@ -import heapq - -INF = 10 ** 9 + 1 - - -def solve(N, A, Ops): - pass - - -if __name__ == '__main__': - N = int(input()) - A = list(map(int, input().split())) - M = int(input()) - Ops: list[list[tuple]] = [[] for _ in range(N)] - for _ in range(M): - l, r, c = map(int, input().split()) - Ops[l].append((r, c)) - Ops[r].append((l, c)) - - -""" -문자가 배열된 상태 S_k를 정의할 수 있음. -이에 따라 S_0에서 S_k로 가는 distance를 구할 수 있고, 이로 dijkstra를 전개하면 됨. -""" \ No newline at end of file diff --git a/zeta_python/completed/28707.py b/zeta_python/completed/28707.py new file mode 100644 index 0000000..3f83314 --- /dev/null +++ b/zeta_python/completed/28707.py @@ -0,0 +1,62 @@ +import sys +import heapq + +input = sys.stdin.readline +INF = 10 ** 9 + 1 + +sorted_one = None + + +def is_sorted(arr): + return arr == sorted(arr) + + +def swap(a, l, r): + arr = a.copy() + arr[l - 1], arr[r - 1] = arr[r - 1], arr[l - 1] + return arr + + +def dijkstra(operators, start: list) -> dict: + heap = [] + distance = {tuple(start): 0} + heapq.heappush(heap, (0, start,)) + while heap: + cost, now, = heapq.heappop(heap) + if is_sorted(now): + return distance + + if distance[tuple(now)] < cost: + continue + + for l, r, weight in operators: + new = swap(now, l, r) + new_cost = cost + weight + if tuple(new) not in distance: + distance[tuple(new)] = INF + if new_cost < distance[tuple(new)]: + distance[tuple(new)] = new_cost + heapq.heappush(heap, (new_cost, new)) + distance[tuple(sorted_one)] = -1 + return distance + + +def solve(N, A, Ops): + distance = dijkstra(Ops, A) + return distance[tuple(sorted_one)] + + +if __name__ == '__main__': + N = int(input()) + A = list(map(int, input().split())) + sorted_one = sorted(A) + M = int(input()) + Ops: list = [] + for _ in range(M): + l, r, c = map(int, input().split()) + Ops.append((l, r, c)) + print(solve(N, A, Ops)) +""" +문자가 배열된 상태 S_k를 정의할 수 있음. +이에 따라 S_0에서 S_k로 가는 distance를 구할 수 있고, 이로 dijkstra를 전개하면 됨. +"""