|
| 1 | +import itertools |
| 2 | +import math |
| 3 | +import sys |
| 4 | + |
| 5 | +read = lambda: sys.stdin.readline().rstrip() |
| 6 | + |
| 7 | + |
| 8 | +class Problem: |
| 9 | + def __init__(self): |
| 10 | + self.n, self.w = int(read()), int(read()) |
| 11 | + self.coords = [(0, 0)] |
| 12 | + for _ in range(self.w): |
| 13 | + y, x = map(int, read().split()) |
| 14 | + self.coords.append((x - 1, y - 1)) |
| 15 | + |
| 16 | + def solve(self) -> None: |
| 17 | + dp, path, parent = ( |
| 18 | + [[math.inf for _ in range(self.w + 1)] for _ in range(self.w + 1)], |
| 19 | + [[0 for _ in range(self.w + 1)] for _ in range(self.w + 1)], |
| 20 | + [[(0, 0)] * (self.w + 1) for _ in range(self.w + 1)], |
| 21 | + ) |
| 22 | + dp[0][0] = 0 |
| 23 | + |
| 24 | + for x, y in itertools.product(range(self.w + 1), repeat=2): |
| 25 | + event = max(x, y) + 1 |
| 26 | + if event > self.w: |
| 27 | + continue |
| 28 | + |
| 29 | + cost_x = dp[x][y] + self.calc_distance((0, 0) if x == 0 else self.coords[x], event) |
| 30 | + if cost_x < dp[event][y]: |
| 31 | + dp[event][y], path[event][y], parent[event][y] = cost_x, 1, (x, y) |
| 32 | + |
| 33 | + cost_y = dp[x][y] + self.calc_distance((self.n - 1, self.n - 1) if y == 0 else self.coords[y], event) |
| 34 | + if cost_y < dp[x][event]: |
| 35 | + dp[x][event], path[x][event], parent[x][event] = cost_y, 2, (x, y) |
| 36 | + |
| 37 | + minimum, x, y = math.inf, 0, 0 |
| 38 | + for idx in range(self.w + 1): |
| 39 | + if dp[idx][self.w] < minimum: |
| 40 | + minimum, x, y = dp[idx][self.w], idx, self.w |
| 41 | + if dp[self.w][idx] < minimum: |
| 42 | + minimum, x, y = dp[self.w][idx], self.w, idx |
| 43 | + |
| 44 | + sequence = [] |
| 45 | + for _ in range(self.w): |
| 46 | + sequence.append(path[x][y]) |
| 47 | + x, y = parent[x][y] |
| 48 | + |
| 49 | + print(minimum) |
| 50 | + print(*reversed(sequence), sep="\n") |
| 51 | + |
| 52 | + def calc_distance(self, src: tuple[int, int], dist_idx: int) -> int: |
| 53 | + return abs(src[0] - self.coords[dist_idx][0]) + abs(src[1] - self.coords[dist_idx][1]) |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + Problem().solve() |
0 commit comments