#include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; #define int long long #define double long double typedef vector VI; typedef pair pii; typedef vector VP; typedef vector VS; typedef priority_queue PQ; templatebool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } templatebool chmin(T &a, const T &b) { if (b < a) { a = b; return 1; } return 0; } #define fore(i,a) for(auto &i:a) #define REP(i,n) for(int i=0;i, greater > q2; struct edge { int to, cost; }; #define LLINF 922337203685477580 int N, M; vector > G; VI d; int t[510][510][2]; int co[510][510]; void dikstra(int s) { priority_queue, greater >que; REP(i, N)d[i] = LLINF; d[s] = 0; que.push(pii(0, s)); while (!que.empty()) { pii p = que.top(); que.pop(); int v = p.second; if (d[v] < p.first)continue; REP(i, G[v].size()) { edge e = G[v][i]; if (d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; que.push(pii(d[e.to], e.to)); } } } } signed main() { cin.tie(0); ios::sync_with_stdio(false); int pt = 0; cin >> N >> M; int n = N; REP(i, N)REP(j, N) { REP(k, 2)t[i][j][k] = pt++; co[i][j] = 1; } N = N * N * 2; G.resize(N); d.resize(N); REP(i, M) { int x, y, c; cin >> x >> y >> c; x--; y--; co[x][y] += c; } REP(i, n)REP(j, n) { int now = t[i][j][0]; int to; if (i + 1 < n) { to = t[i + 1][j][0]; G[now].push_back((edge) { to, co[i + 1][j] }); if (co[i + 1][j] > 1) { to = t[i + 1][j][1]; G[now].push_back((edge) { to, 1 }); } } if (i - 1 >= 0) { to = t[i - 1][j][0]; G[now].push_back((edge) { to, co[i - 1][j] }); if (co[i - 1][j] > 1) { to = t[i - 1][j][1]; G[now].push_back((edge) { to, 1 }); } } if (j + 1 < n) { to = t[i][j + 1][0]; G[now].push_back((edge) { to, co[i][j + 1] }); if (co[i][j + 1] > 1) { to = t[i][j + 1][1]; G[now].push_back((edge) { to, 1 }); } } if (j - 1 >= 0) { to = t[i][j - 1][0]; G[now].push_back((edge) { to, co[i][j - 1] }); if (co[i][j - 1] > 1) { to = t[i][j - 1][1]; G[now].push_back((edge) { to, 1 }); } } now = t[i][j][1]; if (i + 1 < n) { to = t[i + 1][j][1]; G[now].push_back((edge) { to, co[i + 1][j] }); } if (i - 1 >= 0) { to = t[i - 1][j][1]; G[now].push_back((edge) { to, co[i - 1][j] }); } if (j + 1 < n) { to = t[i][j + 1][1]; G[now].push_back((edge) { to, co[i][j + 1] }); } if (j - 1 >= 0) { to = t[i][j - 1][1]; G[now].push_back((edge) { to, co[i][j - 1] }); } } dikstra(t[0][0][0]); cout << d[t[n - 1][n - 1][1]] << endl; return 0; }