1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include <bits/stdc++.h> using namespace std;
const int N = 3e5 + 66, inf = 214748364;
inline int read() { int s(0), w(1); char ch = getchar(); while (ch < '0' || ch > '9') {if (ch == '-') w = -1; ch = getchar();} while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar(); return s * w; }
inline void put(int x) { if (! x) putchar('0'); if (x < 0) putchar('-'), x = -x; int num(0); char c[66]; while (x) c[++ num] = x % 10 + 48, x /= 10; while (num) putchar(c[num --]); putchar('\n'); }
int n, m; int res(inf), c[66];
struct yhm { int d, x, y; yhm(int D = 0, int X = 0, int Y = 0) : d(D), x(X), y(Y) {} bool operator > (const yhm &a) const { return d > a.d; } };
int vis[N][66], dis[N][66];
inline void fuck(int src) { int x, y; priority_queue<yhm, vector<yhm>, greater<yhm> >q; q.push(yhm(0, 1, src)); memset(dis, 0x3f, sizeof dis); dis[1][src] = 0; vis[1][src] = 1; while (! q.empty()) { x = q.top().x, y = q.top().y; q.pop(); vis[x][y] = 0; if (y != 1) { int ny = y - 1; if (dis[x][ny] > dis[x][y] + 1) { dis[x][ny] = dis[x][y] + 1; if (! vis[x][ny]) { vis[x][ny] = 1; q.push(yhm(dis[x][ny], x, ny)); } } } if (y != m) { int ny = y + 1; if (dis[x][ny] > dis[x][y] + 1) { dis[x][ny] = dis[x][y] + 1; if (! vis[x][ny]) { vis[x][ny] = 1; q.push(yhm(dis[x][ny], x, ny)); } } } int nx = x + c[y]; if (nx < 1 || nx > n) continue; if (dis[nx][y] > dis[x][y] + abs(c[y]) * 2) { dis[nx][y] = dis[x][y] + abs(c[y] * 2); if (! vis[nx][y]) { vis[nx][y] = 1; q.push(yhm(dis[nx][y], nx, y)); } } } return; }
signed main() { int i, src; n = read(), m = read(); for (i = 1; i <= m; ++ i) { c[i] = read(); if (c[i] == 0) src = i; } fuck(src);
for (i = 1; i <= m; ++ i) res = res > dis[n][i] ? dis[n][i] : res; res == inf ? put(-1) : put(res); return 0; }
|