|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + public static void main(String[] args) throws IOException { |
| 7 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 8 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 9 | + |
| 10 | + int N = Integer.parseInt(st.nextToken()); |
| 11 | + int M = Integer.parseInt(st.nextToken()); |
| 12 | + |
| 13 | + boolean[] canStep = new boolean[N + 1]; |
| 14 | + Arrays.fill(canStep, true); |
| 15 | + |
| 16 | + for (int i = 0; i < M; i++) { |
| 17 | + int small = Integer.parseInt(br.readLine()); |
| 18 | + canStep[small] = false; |
| 19 | + } |
| 20 | + |
| 21 | + int maxSpeed = 200; |
| 22 | + int[][] dist = new int[N + 1][maxSpeed + 1]; |
| 23 | + for (int i = 0; i <= N; i++) { |
| 24 | + Arrays.fill(dist[i], Integer.MAX_VALUE); |
| 25 | + } |
| 26 | + |
| 27 | + PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[2] - b[2]); |
| 28 | + pq.offer(new int[]{1, 0, 0}); |
| 29 | + dist[1][0] = 0; |
| 30 | + |
| 31 | + while (!pq.isEmpty()) { |
| 32 | + int[] cur = pq.poll(); |
| 33 | + int pos = cur[0]; |
| 34 | + int speed = cur[1]; |
| 35 | + int jumps = cur[2]; |
| 36 | + |
| 37 | + if (pos == N) { |
| 38 | + System.out.println(jumps); |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + if (dist[pos][speed] < jumps) { |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + for (int nextSpeed = Math.max(1, speed - 1); nextSpeed <= speed + 1; nextSpeed++) { |
| 47 | + int nextPos = pos + nextSpeed; |
| 48 | + |
| 49 | + if (nextPos > N || nextPos < 1 || !canStep[nextPos] || nextSpeed > maxSpeed) { |
| 50 | + continue; |
| 51 | + } |
| 52 | + |
| 53 | + if (dist[nextPos][nextSpeed] > jumps + 1) { |
| 54 | + dist[nextPos][nextSpeed] = jumps + 1; |
| 55 | + pq.offer(new int[]{nextPos, nextSpeed, jumps + 1}); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + System.out.println(-1); |
| 61 | + } |
| 62 | +} |
| 63 | +``` |
0 commit comments