#include using namespace std; typedef long long ll; typedef long double ld; #define REP(i, n) for (int i = 0; i < (n); ++i) #define REPR(i, n) for (int i = n - 1; i >= 0; --i) #define FOR(i, m, n) for (int i = m; i < n; ++i) #define FORR(i, m, n) for (int i = m; i >= n; --i) #define ALL(v) (v).begin(),(v).end() templatebool chmax(T &a, const T &b) { if (abool chmin(T &a, const T &b) { if (b> n >> m; vector> c(n,vector(n)); REP(i,m){ int h,w,C;cin >> h >> w >> C; h--,w--; c[h][w]=C; } vector>> d(n,vector>(n,vector(2,INF))); d[0][0][0]=0; queue,int>> q; q.push({{0,0},0}); while(!q.empty()){ auto p=q.front();q.pop(); int u=p.first.first,v=p.first.second,w=p.second; REP(i,4){ int x=u+dx[i],y=v+dy[i]; if(x<0||x>=n||y<0||y>=n) continue; if(c[x][y]){ if(chmin(d[x][y][w],d[u][v][w]+c[x][y]+1)){ q.push({{x,y},w}); } if(!w&&chmin(d[x][y][1],d[u][v][0]+1)){ q.push({{x,y},1}); } } else{ if(chmin(d[x][y][w],d[u][v][w]+1)){ q.push({{x,y},w}); } } } } cout << min(d[n-1][n-1][0],d[n-1][n-1][1]) << endl; }