|
| 1 | +import heapq |
| 2 | +import sys |
| 3 | + |
| 4 | +read = lambda: sys.stdin.readline().rstrip() |
| 5 | + |
| 6 | + |
| 7 | +class Problem: |
| 8 | + def __init__(self): |
| 9 | + self.n = int(read()) |
| 10 | + self.array = tuple(map(int, read().split())) |
| 11 | + self.target = tuple(sorted(self.array)) |
| 12 | + self.m = int(read()) |
| 13 | + self.graph = {x: [] for x in range(self.n)} |
| 14 | + |
| 15 | + for _ in range(self.m): |
| 16 | + left, right, weight = map(int, read().split()) |
| 17 | + self.graph[left - 1].append((weight, right - 1)) |
| 18 | + self.graph[right - 1].append((weight, left - 1)) |
| 19 | + |
| 20 | + def solve(self) -> None: |
| 21 | + print(self.dijkstra()) |
| 22 | + |
| 23 | + def dijkstra(self) -> int: |
| 24 | + heap, visited, costs = [(0, self.array)], set(), {self.array: 0} |
| 25 | + |
| 26 | + while heap: |
| 27 | + cost, array = heapq.heappop(heap) |
| 28 | + if array == self.target: |
| 29 | + return cost |
| 30 | + |
| 31 | + if array in visited: |
| 32 | + continue |
| 33 | + |
| 34 | + visited.add(array) |
| 35 | + for src in range(self.n): |
| 36 | + for weight, dest in self.graph[src]: |
| 37 | + if src >= dest: |
| 38 | + continue |
| 39 | + |
| 40 | + new_array = list(array) |
| 41 | + new_array[src], new_array[dest] = new_array[dest], new_array[src] |
| 42 | + new_array = tuple(new_array) |
| 43 | + |
| 44 | + if new_array not in costs or cost + weight < costs[new_array]: |
| 45 | + costs[new_array] = cost + weight |
| 46 | + heapq.heappush(heap, (cost + weight, new_array)) |
| 47 | + |
| 48 | + return -1 |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == "__main__": |
| 52 | + Problem().solve() |
0 commit comments