#include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; #define rep(i, j, n) for (int i = j; i < (n); ++i) #define rrep(i, j, n) for (int i = (n)-1; j <= i; --i) [[maybe_unused]] constexpr ll MOD = 1000000007; [[maybe_unused]] constexpr int INF = 0x3f3f3f3f; [[maybe_unused]] constexpr ll INFL = 0x3f3f3f3f3f3f3f3fLL; const int MAX = 505; ll cost[MAX]; ll dp[MAX][2]; int main() { int n, m; cin >> n >> m; rep(i, 0, m) { int h, w, c; cin >> h >> w >> c; --w, --h; cost[n * h + w] = c; } rep(i, 0, n * n + 1) rep(j, 0, 2) dp[i][j] = INFL; dp[0][0] = 0; int dw[4] = {0, 0, -1, 1}; int dh[4] = {1, -1, 0, 0}; using ili = tuple; priority_queue, greater> pq; pq.emplace(0, 0, 0); // vertex, cost, bool while (pq.size()) { auto [v, c, b] = pq.top(); pq.pop(); if (dp[v][b] < c) continue; // b == 0かつ料金じょふぁあればb == 1にも遷移する int ch = v / n; int cw = v % n; rep(i, 0, 4) { int nh = ch + dh[i]; int nw = cw + dw[i]; int nv = nh * n + nw; if (0 <= nh && nh < n && 0 <= nw && nw < n) { if (dp[nv][b] > c + 1 + cost[nv]) { dp[nv][b] = c + 1 + cost[nv]; pq.emplace(nv, dp[nv][b], b); } if (b == 0 && dp[nv][1] > c + 1) { dp[nv][1] = c + 1; pq.emplace(nv, dp[nv][1], 1); } } } } cout << min(dp[n * n - 1][0], dp[n * n - 1][1]) << '\n'; return 0; }