/** * @FileName a.cpp * @Author kanpurin * @Created 2020.11.06 23:10:25 **/ #include "bits/stdc++.h" using namespace std; typedef long long ll; template struct Dijkstra { private: int V; struct edge { int to; T cost; }; vector> G; public: const T inf = numeric_limits::max(); vector d; Dijkstra() {} Dijkstra(int V) : V(V) { G.resize(V); } Dijkstra& operator=(const Dijkstra& obj) { this->V = obj.V; this->G = obj.G; this->d = obj.d; return *this; } void add_edge(int from, int to, T weight, bool directed = false) { G[from].push_back({to,weight}); if (!directed) G[to].push_back({from,weight}); } int add_vertex() { G.push_back(vector()); return V++; } void build(int s) { d.assign(V, inf); typedef tuple P; priority_queue, greater

> pq; d[s] = 0; pq.push(P(d[s], s)); while (!pq.empty()) { P p = pq.top(); pq.pop(); int v = get<1>(p); if (d[v] < get<0>(p)) continue; for (const edge &e : G[v]) { if (d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; pq.push(P(d[e.to], e.to)); } } } } }; int n; int id(int h,int w,int used) { return h * n + w + n*n*used; } int main() { int m;cin >> n >> m; Dijkstra g(2*n*n+1); int goal = 2*n*n; int dx[] = {0,1,0,-1}, dy[] = {1,0,-1,0}; vector> ryoukin(n,vector(n,0)); for (int i = 0; i < m; i++) { int h,w,c;cin >> h >> w >> c; ryoukin[h-1][w-1] = c; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < 4; k++) { int x = dx[k] + i, y = dy[k] + j; if (x < 0 || x >= n || y < 0 || y >= n) continue; if (ryoukin[x][y] > 0) { g.add_edge(id(i,j,0),id(x,y,0),ryoukin[x][y]+1,true); g.add_edge(id(i,j,1),id(x,y,1),ryoukin[x][y]+1,true); g.add_edge(id(i,j,0),id(x,y,1),1,true); } else { g.add_edge(id(i,j,0),id(x,y,0),1,true); g.add_edge(id(i,j,1),id(x,y,1),1,true); } } } } g.add_edge(id(n-1,n-1,0),goal,0,true); g.add_edge(id(n-1,n-1,1),goal,0,true); g.build(id(0,0,0)); cout << g.d[goal] << endl; return 0; }