#![allow(unused_imports)] use std::cmp::*; use std::collections::*; use std::io::Write; use std::ops::Bound::*; #[allow(unused_macros)] macro_rules! debug { ($($e:expr),*) => { #[cfg(debug_assertions)] $({ let (e, mut err) = (stringify!($e), std::io::stderr()); writeln!(err, "{} = {:?}", e, $e).unwrap() })* }; } fn main() { let v = read_vec::(); let (n, m) = (v[0], v[1]); let mut cost_dict = HashMap::new(); for i in 0..m { let v = read_vec::(); let (h, w, c) = (v[0] as usize - 1, v[1] as usize - 1, v[2]); cost_dict.insert((h, w), c); } let mut dp = vec![vec![vec![std::i64::MAX; n]; n]; 2]; dp[0][0][0] = 0; dp[1][0][0] = 0; for h in 0..n { for w in 0..n { let cur_cost; if cost_dict.contains_key(&(h, w)) { cur_cost = cost_dict[&(h, w)]; } else { cur_cost = 0; } for k in 0..2 { if h > 0 { dp[k][h][w] = min(dp[k][h][w], dp[k][h - 1][w] + 1 + cur_cost); } if w > 0 { dp[k][h][w] = min(dp[k][h][w], dp[k][h][w - 1] + 1 + cur_cost); } } if h > 0 { dp[1][h][w] = min(dp[1][h][w], dp[0][h - 1][w] + 1); } if w > 0 { dp[1][h][w] = min(dp[1][h][w], dp[0][h][w - 1] + 1); } } } println!("{}", dp[1][n - 1][n - 1]); } fn read() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_vec() -> Vec { read::() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() }