#define rep(i,n) for(int i=0;i<(int)(n);i++) #define ALL(v) v.begin(),v.end() typedef long long ll; #include using namespace std; const ll INF=1LL<<60; struct Edge{ int to; ll w; Edge(int to,ll w) : to(to),w(w) {} }; using Graph=vector>; using pli=pair; ll A[510][510]; template bool chmin(T& a,T b){ if(a>b){ a=b; return true; } return false; } int main(){ int n,m; cin>>n>>m; Graph G(n*n); rep(i,m){ int h,w; ll c; cin>>h>>w>>c; h--,w--; A[h][w]=c; } for(int i=0;i0){ G[(i-1)*n+j].push_back(Edge(i*n+j,A[i][j]+1)); G[i*n+j].push_back(Edge((i-1)*n+j,A[i-1][j]+1)); } if(i0){ G[i*n+j-1].push_back(Edge(i*n+j,A[i][j]+1)); G[i*n+j].push_back(Edge(i*n+j-1,A[i][j-1]+1)); } if(j dist(n*n,INF),dist1(n*n,INF); dist[0]=0,dist1[n*n-1]=0; priority_queue,greater> que,que1; que.push({dist[0],0}); que1.push({dist1[n*n-1],n*n-1}); while(!que.empty()){ int v=que.top().second; ll d=que.top().first; que.pop(); if(d>dist[v]) continue; for(auto e:G[v]){ if(chmin(dist[e.to],dist[v]+e.w)){ que.push({dist[e.to],e.to}); } } } while(!que1.empty()){ int v=que1.top().second; ll d=que1.top().first; que1.pop(); if(d>dist1[v]) continue; for(auto e:G[v]){ if(chmin(dist1[e.to],dist1[v]+e.w)){ que1.push({dist1[e.to],e.to}); } } } ll mi=INF; rep(i,n){ rep(j,n){ mi=min(mi,dist[i*n+j]+dist1[i*n+j]-2*A[i][j]); } } cout<