/* -*- coding: utf-8 -*- * * 1283.cc: No.1283 Extra Fee - yukicoder */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_N = 500; const long long LINF = 1LL << 62; const int dxs[] = { 1, 0, -1, 0 }, dys[] = { 0, -1, 0, 1 }; /* typedef */ typedef long long ll; typedef pair pli; /* global variables */ int fs[MAX_N][MAX_N]; ll ds0[MAX_N][MAX_N], ds1[MAX_N][MAX_N]; /* subroutines */ inline int xy2p(int x, int y, int n) { return n * y + x; } inline void p2xy(int p, int &x, int &y, int n) { x = p % n, y = p / n; } void dijkstra(int n, int sx, int sy, ll ds[MAX_N][MAX_N]) { for (int y = 0; y < n; y++) fill(ds[y], ds[y] + n, LINF); ds[sy][sx] = 0; priority_queue q; q.push(pli(0, xy2p(sx, sy, n))); while (! q.empty()) { pli u = q.top(); q.pop(); ll ud = -u.first; int ux, uy; p2xy(u.second, ux, uy, n); if (ds[uy][ux] != ud) continue; for (int di = 0; di < 4; di++) { int vx = ux + dxs[di], vy = uy + dys[di]; if (vx >= 0 && vx < n && vy >= 0 && vy < n) { ll vd = ud + 1 + fs[vy][vx]; if (ds[vy][vx] > vd) { ds[vy][vx] = vd; q.push(pli(-vd, xy2p(vx, vy, n))); } } } } } /* main */ int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { int y, x, c; scanf("%d%d%d", &y, &x, &c); y--, x--; fs[y][x] = c; } if (false) for (int y = 0; y < n; y++) { for (int x = 0; x < n; x++) printf("%d ", fs[y][x]); putchar('\n'); } dijkstra(n, 0, 0, ds0); dijkstra(n, n - 1, n - 1, ds1); ll mind = LINF; for (int y = 0; y < n; y++) for (int x = 0; x < n; x++) { ll d = ds0[y][x] + ds1[y][x] - (ll)fs[y][x] * 2; if (mind > d) mind = d; } printf("%lld\n", mind); return 0; }