#define _USE_MATH_DEFIMES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include const int MOD = 1'000'000'007; const int MOD2 = 998'244'353; const int INF = 1'000'000'000; //1e9 const int NIL = -1; const long long LINF = 1'000'000'000'000'000'000; // 1e18 const long double EPS = 1E-10L; template inline bool chmax(T &a, const S &b){ if(a < b){a = b; return true;} return false; } template inline bool chmin(T &a, const S &b){ if(b < a){a = b; return true;} return false; } template inline bool exist(Container &s, const T &e){ return (s.find(e) != std::end(s)); } template inline bool inside(T x, T lx, T rx){ return (std::clamp(x, lx, rx) == x); } template inline bool inside(T x, T y, T lx, T rx, T ly, T ry){ return inside(x, lx, rx) && inside(y, ly, ry); } struct edge{ int to, cost; edge(int To, int Cost): to(To), cost(Cost){} }; void dijkstra(int s, std::vector> &G, std::vector &d, std::vector &prv){ //pair first: 距離 second: 頂点 std::priority_queue, std::vector>, std::greater>> que; int V{int(G.size())}; d.resize(V, LINF+3); prv.resize(V, NIL); d[s] = 0; que.emplace(0, s); while(!que.empty()){ std::pair p{que.top()}; que.pop(); int v{p.second}; if(d[v] < p.first) continue; for(edge &e: G[v]){ if(d[e.to] > d[v] + e.cost){ d[e.to] = d[v] + e.cost; prv[e.to] = v; que.emplace(d[e.to], e.to); } } } } int vertex(int h, int w, int N){ return h*N + w; } int dx[4] = {0, -1, 0, 1}; int dy[4] = {1, 0, -1, 0}; int main(){ int N, M; std::cin >> N >> M; int n{N * N}; std::vector> G(2*n); std::vector cst(N, std::vector(N, 1)); { int h, w, c; for(int i{0}; i < M; ++i){ std::cin >> h >> w >> c; cst[h-1][w-1] += c; } } for(int i{0}; i < N; ++i){ for(int j{0}; j < N; ++j){ int vtx{vertex(i, j, N)}; for(int d{0}; d < 4; ++d){ int ni{i + dx[d]}, nj{j + dy[d]}; if(!inside(ni, nj, 0, N-1, 0, N-1)) continue; int nvtx{vertex(ni, nj, N)}; G[vtx].emplace_back(nvtx, cst[ni][nj]); G[n+vtx].emplace_back(n+nvtx, cst[ni][nj]); if(cst[ni][nj] > 1) G[vtx].emplace_back(n+nvtx, 1); } } } std::vector d; std::vector prv; dijkstra(0, G, d, prv); std::cout << std::min(d[n-1], d[2*n-1]) << std::endl; return 0; }