#include #include #include #include using namespace std; #define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \ << " " << __FILE__ << endl; int main() { int w, h; cin >> w >> h; vector a(h); for (int &x : a) cin >> x; // アリスが 席 p のプレゼントを受け取ったと仮定する。 // a を逆にして a に従って最短経路を求めることは、アリスが受け取ったプレゼントを席 p に戻すことに対応 // 受け取る最短経路と、戻す最短経路は一致(自明)なので、これは正しい reverse(a.begin(), a.end()); vector > dist(h + 3, vector(w, 1e9)); dist[0][0] = 0; // 最初は 0 deque q; q.push_front(0 * w + 0); while (!q.empty()) { int now = q.front(); q.pop_front(); int x = now % w; int y = now / w; if (y >= h + 2) continue; pair freeswap = {-1, -1}; if (1 <= y && y <= h) freeswap = {a[y - 1] - 1, a[y - 1]}; if (y == 0 || y == h + 1) { if (dist[y + 1][x] > dist[y][x]) { dist[y + 1][x] = dist[y][x]; q.push_front((y + 1) * w + x); } } if (x + 1 < w) { if (freeswap.second == x + 1) { if (dist[y + 1][x + 1] > dist[y][x]) { dist[y + 1][x + 1] = dist[y][x]; q.push_front((y + 1) * w + x + 1); } } else { if (dist[y][x + 1] > dist[y][x] + 1) { dist[y][x + 1] = dist[y][x] + 1; q.push_back((y)*w + x + 1); } } } if (x > 0) { if (freeswap.first == x - 1) { if (dist[y + 1][x - 1] > dist[y][x]) { dist[y + 1][x - 1] = dist[y][x]; q.push_front((y + 1) * w + x - 1); } } else { if (dist[y][x - 1] > dist[y][x] + 1) { dist[y][x - 1] = dist[y][x] + 1; q.push_back((y)*w + x - 1); } } } if (freeswap.first != x && freeswap.second != x) { if (dist[y + 1][x] > dist[y][x]) { dist[y + 1][x] = dist[y][x]; q.push_front((y + 1) * w + x); } } } for (int x = 1; x < w; x++) { cout << dist[h + 2][x]; if (x != w - 1) cout << " "; } cout << endl; return 0; }