import heapq def main(): import sys input = sys.stdin.read data = input().split() idx = 0 N = int(data[idx]) idx += 1 M = int(data[idx]) idx += 1 fee = [[0]*(N+1) for _ in range(N+1)] for _ in range(M): h = int(data[idx]) idx += 1 w = int(data[idx]) idx += 1 c = int(data[idx]) idx += 1 fee[h][w] = c INF = float('inf') dist = [[[INF]*(N+1) for _ in range(N+1)] for _ in range(2)] dist[0][1][1] = 0 heap = [] heapq.heappush(heap, (0, 1, 1, 0)) dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)] while heap: cost, h, w, used = heapq.heappop(heap) if h == N and w == N: print(cost) return if cost > dist[used][h][w]: continue for dh, dw in dirs: nh = h + dh nw = w + dw if 1 <= nh <= N and 1 <= nw <= N: current_fee = fee[nh][nw] new_cost_base = cost + 1 if current_fee > 0: if used == 0: # Pay the fee new_cost = new_cost_base + current_fee if new_cost < dist[0][nh][nw]: dist[0][nh][nw] = new_cost heapq.heappush(heap, (new_cost, nh, nw, 0)) # Skip the fee new_cost_skip = new_cost_base if new_cost_skip < dist[1][nh][nw]: dist[1][nh][nw] = new_cost_skip heapq.heappush(heap, (new_cost_skip, nh, nw, 1)) else: # Must pay the fee new_cost = new_cost_base + current_fee if new_cost < dist[1][nh][nw]: dist[1][nh][nw] = new_cost heapq.heappush(heap, (new_cost, nh, nw, 1)) else: new_cost = new_cost_base if new_cost < dist[used][nh][nw]: dist[used][nh][nw] = new_cost heapq.heappush(heap, (new_cost, nh, nw, used)) # If exit not reached inside loop, check both states for (N,N) print(min(dist[0][N][N], dist[1][N][N])) if __name__ == '__main__': main()