直接裸迪杰斯特拉啊, 看看数据就那么点, 把每个节点扩充m个不就完了?
#include <bits/stdc++.h>
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define per(i,a,b) for(int i=(a);i>=(b);--i)
using namespace std;
const int N = 2e4 + 5;
int n, m, _, k;
vector<pair<int, int>> h[N];
int d[N], s, t, a[21];
bool v[N];
void dji(int s) {
priority_queue<pair<int, int>> q;
memset(d, 0x3f, sizeof d); q.push({ d[s] = 0, s });
while (!q.empty()) {
int x = q.top().second; q.pop();
if (v[x]) continue; v[x] = 1;
for (auto &[y, c] : h[x]) if (d[y] > d[x] + c) q.push({-(d[y] = d[x] + c), y});
}
}
int main() {
cin >> n >> m;
rep (i, 1, m) { cin >> a[i]; if (!a[i]) k = i; }
memset(d, 0x3f, sizeof d);
rep (i, 1, n) rep(j, 1, m) rep(t, 1, m) if (a[t] && i + a[t] > 0 && i + a[t] <= n)
h[(i - 1) * m + j].emplace_back((i + a[t] - 1) * m + t, abs(a[t]) * 2 + abs(j - t));
dji(k);
int ans = d[0];
rep(i, (n - 1) * m + 1, n * m) ans = min(ans, d[i]);
cout << (ans == d[0]? - 1 : ans);
return 0;
}