#include #include #include #include #include #include #include using namespace std; typedef long long ll; const ll INF = 1e+17; typedef pair> P; struct edge{ int to; ll cost; }; int H, W; int dh[4] = {0, 0, -1, 1}; int dw[4] = {-1, 1, 0, 0}; bool is_in_field(int i, int j){ return i >= 0 && i < H && j >= 0 && j < W; } ll dist[500][500][2]; ll cost[500][500]; void input(){ int M; cin >> H >> M; W = H; for(int i = 0; i < M; i++) { int h, w; cin >> h >> w; h--; w--; ll c; cin >> c; cost[h][w] = c; } } void dijkstra(){ priority_queue, greater

> que; for(int i = 0; i < H; i++){ for(int j = 0; j < W; j++){ dist[i][j][0] = INF; dist[i][j][1] = INF; } } dist[0][0][0] = 0; vector v = {0, 0, 0}; que.push(P(0, v)); while(!que.empty()){ P p = que.top();que.pop(); auto v = p.second; int h = v[0]; int w = v[1]; int s = v[2]; ll d = p.first; if(dist[h][w][s] < d) continue; for(int i = 0; i < 4; i++){ int h_to = h + dh[i]; int w_to = w + dw[i]; if(!is_in_field(h_to, w_to)) continue; if(d+cost[h_to][w_to]+1 < dist[h_to][w_to][s]){ dist[h_to][w_to][s] = d+cost[h_to][w_to]+1; vector v = {h_to, w_to, s}; que.push(P(dist[h_to][w_to][s], v)); } if(s == 0 && d+1 < dist[h_to][w_to][1]){ dist[h_to][w_to][1] = d+1; vector v = {h_to, w_to, 1}; que.push(P(dist[h_to][w_to][1], v)); } } } } void solve(){ dijkstra(); cout << min(dist[H-1][W-1][0], dist[H-1][W-1][1]) << endl; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; input(); solve(); }