#include using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) begin(v),end(v) template inline bool chmax(A & a, const B & b) { if (a < b) { a = b; return true; } return false; } template inline bool chmin(A & a, const B & b) { if (a > b) { a = b; return true; } return false; } using ll = long long; using pii = pair; constexpr ll INF = 1ll<<30; constexpr ll longINF = 1ll<<60; constexpr ll MOD = 1000000007; constexpr bool debug = false; //---------------------------------// int main() { int N, M; cin >> N >> M; vector C(N, vector(N)); REP(i, M) { int h, w, c; scanf("%d %d %d", &h, &w, &c); C[h - 1][w - 1] = c; } vector dp(N, vector(N, vector(2, longINF))); using tup = tuple; priority_queue, greater> pq; dp[0][0][0] = 0; pq.emplace(0, 0, 0); while (!pq.empty()) { auto [c, p, f] = pq.top(); pq.pop(); int y = p / N, x = p % N; if (c != dp[y][x][f]) continue; int dx[] {1,0,-1,0}, dy[] {0,1,0,-1}; REP(dir, 4) { const int ny = y + dy[dir], nx = x + dx[dir]; if (ny < 0 || ny >= N || nx < 0 || nx >= N) continue; if (chmin(dp[ny][nx][f], dp[y][x][f] + C[ny][nx] + 1)) pq.emplace(dp[ny][nx][f], ny * N + nx, f); if (!f && chmin(dp[ny][nx][1], dp[y][x][f] + 1)) pq.emplace(dp[ny][nx][1], ny * N + nx, 1); } } cout << dp[N - 1][N - 1][1] << endl; }