#include using namespace std; typedef long long int ll; typedef pair P; typedef vector VI; typedef vector VVI; #define REP(i,n) for(int i=0;i another.d;}; }; int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 }; int n; VVI c(510,VI(510,0)); ll bfs(int sx, int sy, int gx, int gy){ priority_queue q; q.push({sx,sy,0,0}); VVI dis0(n, VI(n, INF)); VVI dis1(n, VI(n, INF)); dis0[0][0]=0; while (!q.empty()) { int x=q.top().x, y=q.top().y; ll d=q.top().d; bool f=q.top().f; q.pop(); if(!f&&d>dis0[x][y]) continue; if(f&&d>dis1[x][y]) continue; REP(k,4){ int tox=x+dx[k], toy=y+dy[k]; if(tox<0||tox>=n||toy<0||toy>=n) continue; if(!f){ if(dis0[tox][toy]>d+1+c[tox][toy]){ dis0[tox][toy]=d+1+c[tox][toy]; q.push({tox,toy,d+1+c[tox][toy],0}); } if(dis1[tox][toy]>d+1){ dis1[tox][toy]=d+1; q.push({tox,toy,d+1,1}); } } else{ if(dis1[tox][toy]>d+1+c[tox][toy]){ dis1[tox][toy]=d+1+c[tox][toy]; q.push({tox,toy,d+1+c[tox][toy],1}); } } } } return dis1[gx][gy]; } int main(){ int m; cin >> n >> m; int h, w, x; REP(i,m){ cin >> h >> w >> x; h--, w--; c[h][w]=x; } cout << bfs(0,0,n-1,n-1) << endl; return 0; }