pub mod procon_input { use std::{str::FromStr, iter::FromIterator}; pub fn read_line() -> String { let mut input = String::new(); std::io::stdin().read_line(&mut input).ok(); input } pub fn parse(s: &str) -> T { s.parse().ok().unwrap() } pub fn read() -> T { parse(read_line().trim_end()) } pub fn read_collection>() -> C { read_line().split_whitespace().map(parse).collect() } #[macro_export] macro_rules! read_tuple { ( $( $t:ty ),* ) => {{ let input = read_line(); let mut iter = input.split_whitespace(); ( $( parse::<$t>(iter.next().unwrap()) ),* ) }}; } } use procon_input::*; fn dijkstra( graph: &Vec>, tolls: &Vec, s: usize ) -> Vec { use std::collections::BinaryHeap; use std::cmp::Reverse; let n = graph.len(); let mut heap = BinaryHeap::new(); let mut dist = vec![1 << 60; n]; heap.push((Reverse(tolls[s]), s)); dist[s] = tolls[s]; while let Some((Reverse(cost), from)) = heap.pop() { for &to in &graph[from] { let next_cost = cost + 1 + tolls[to]; if next_cost < dist[to] { heap.push((Reverse(next_cost), to)); dist[to] = next_cost; } } } dist } fn solve(writer: &mut std::io::BufWriter) { use std::io::Write; let (n, m) = read_tuple!(usize, usize); let mut graph = vec![vec![]; n * n]; for h in 0..n { for w in 0..n { let u = h * n + w; if w + 1 < n { let v = h * n + (w + 1); graph[u].push(v); graph[v].push(u); } if h + 1 < n { let v = (h + 1) * n + w; graph[u].push(v); graph[v].push(u); } } } let mut tolls = vec![0; n * n]; for _ in 0..m { let (h, w, c) = read_tuple!(usize, usize, i64); tolls[(h - 1) * n + (w - 1)] = c; } let dist_start = dijkstra(&graph, &tolls, 0); let dist_goal = dijkstra(&graph, &tolls, n * n - 1); let mut ans = dist_start[n * n - 1]; for x in 0..(n * n) { if tolls[x] == 0 { continue; } use std::cmp::min; let mut prev = std::i64::MAX; if x % n > 0 { prev = min(prev, dist_start[x - 1]); } if x / n > 0 { prev = min(prev, dist_start[x - n]) } let mut next = std::i64::MAX; if x % n + 1 < n { next = min(next, dist_goal[x + 1]); } if x / n + 1 < n { next = min(next, dist_goal[x + n]); } ans = min(ans, prev + next + 2); } writeln!(writer, "{}", ans).ok(); } fn main() { let stdout = std::io::stdout(); let mut writer = std::io::BufWriter::new(stdout.lock()); solve(&mut writer); }