#include #include #include #include #include #include using namespace std; typedef tuple P; int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1}; int main(){ int N, M; cin >> N >> M; vector h(M), w(M); vector c(M); vector> cost(N, vector (N, 1)); for(int i = 0; i < M; i++) { cin >> h[i] >> w[i] >> c[i]; cost[h[i] - 1][w[i] - 1] += c[i]; } long long INF = 1e18; vector> d(2, vector(N * N, INF)); priority_queue, greater

> q; d[0][0] = 0; q.push(P(0, 0, 0)); while(!q.empty()){ P v = q.top(); q.pop(); long long temp = get<0>(v); int s = get<1>(v), t = get<2>(v); if(d[s][t] < temp) continue; if(s == 0 && cost[t / N][t % N] > 1){ if(d[1][t] > d[0][t] - cost[t / N][t % N] + 1){ d[1][t] = d[0][t] - cost[t / N][t % N] + 1; q.push(P(d[1][t], 1, t)); } } for(int i = 0; i < 4; i++){ int x = t / N, y = t % N; int nx = x + dx[i], ny = y + dy[i]; if(0 <= nx && nx < N && 0 <= ny && ny < N){ int nt = nx * N + ny; if(d[s][nt] > d[s][t] + cost[nx][ny]){ d[s][nt] = d[s][t] + cost[nx][ny]; q.push(P(d[s][nt], s, nt)); } } } } cout << min(d[1][N * N - 1], d[0][N * N - 1]) << endl; }