#include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; const int MAX_N = 500; ll costs[MAX_N][MAX_N]; const int DY[4] = {-1, 0, 1, 0}; const int DX[4] = {0, 1, 0, -1}; struct Node { int y; int x; ll cost; bool canIgnoreFee; Node(int y = -1, int x = -1, ll cost = -1, bool canIgnoreFee = true) { this->y = y; this->x = x; this->cost = cost; this->canIgnoreFee = canIgnoreFee; } bool operator>(const Node &n) const { return cost > n.cost; } }; int main() { memset(costs, 0, sizeof(costs)); int N, M; cin >> N >> M; ll h, w, c; for (int i = 0; i < M; ++i) { cin >> h >> w >> c; costs[h - 1][w - 1] = c; } priority_queue , greater> pque; pque.push(Node(0, 0, 0, true)); bool visited[2][N][N]; memset(visited, false, sizeof(visited)); while (!pque.empty()) { Node node = pque.top(); pque.pop(); if (visited[node.canIgnoreFee][node.y][node.x]) continue; visited[node.canIgnoreFee][node.y][node.x] = true; if (node.y == N - 1 && node.x == N - 1) { cout << node.cost << endl; return 0; } for (int i = 0; i < 4; ++i) { int ny = node.y + DY[i]; int nx = node.x + DX[i]; if (ny < 0 || nx < 0 || N <= ny || N <= nx) continue; pque.push(Node(ny, nx, node.cost + costs[ny][nx] + 1, node.canIgnoreFee)); if (costs[ny][nx] != 0 && node.canIgnoreFee) { pque.push(Node(ny, nx, node.cost + 1, false)); } } } return 0; }