use std::{cmp::Reverse, collections::{BinaryHeap, BTreeSet, HashMap}}; const INF: usize = 1usize << 60; #[derive(Debug, Clone)] struct Dijkstra { n: usize, pathcosts: Vec>, pathcostsrev: Vec>, costs: Vec } impl Dijkstra { fn new(n: usize) -> Self { Self { n: n , pathcosts: vec![vec![]; n] , pathcostsrev: vec![vec![]; n] , costs: vec![INF; n] } } fn pusha2b(&mut self, a: usize, b: usize, cost: usize) { self.pathcosts[a].push((cost, b)); self.pathcostsrev[b].push((cost, a)); } fn get_cost(&self, idx: usize) -> usize { self.costs[idx] } fn solve(&mut self, startpoint: usize) { let mut que = BinaryHeap::new(); que.push(Reverse((0, startpoint))); self.costs[startpoint] = 0; while let Some(Reverse(p)) = que.pop() { let cost = p.0; let dest = p.1; if cost > self.costs[dest] { continue; } for &p2 in self.pathcosts[dest].iter() { if self.costs[dest] + p2.0 < self.costs[p2.1] { self.costs[p2.1] = self.costs[dest] + p2.0; que.push(Reverse((self.costs[p2.1], p2.1))); } } } } fn reconstruct(&self, startpoint: usize, endpoint: usize) -> Vec<(usize, usize)> { let mut ret = vec![]; if self.costs[endpoint] == INF { return ret; } let mut current = endpoint; while current != startpoint { for &(cost, u) in self.pathcostsrev[current].iter() { if self.costs[current] == self.costs[u] + cost { let prev = current; current = u; ret.push((current, prev)); break; } } } ret.reverse(); ret } } fn main() { let mut nm = String::new(); std::io::stdin().read_line(&mut nm).ok(); let nm: Vec = nm.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let n = nm[0]; let m = nm[1]; let mut lines = Vec::with_capacity(m); let mut used = BTreeSet::new(); used.insert(n-1); for _ in 0..m { let mut ab = String::new(); std::io::stdin().read_line(&mut ab).ok(); let ab: Vec = ab.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let a = ab[0]; let b = ab[1]; let dist = 2*b - 2*a - 1; let a = a-1; let b = b-1; lines.push((a, b, dist)); used.insert(a); used.insert(b); } let mut mapping = HashMap::new(); for (i, &v) in used.iter().enumerate() { mapping.insert(v, i); } let mut paths = Dijkstra::new(used.len()); for &(u, v, w) in lines.iter() { paths.pusha2b(*mapping.get(&u).unwrap(), *mapping.get(&v).unwrap(), w) } let used = used.into_iter().collect::>(); for i in 0..used.len()-1 { let u = used[i]; let v = used[i+1]; let dist = (v - u) * 2; paths.pusha2b(i, i+1, dist); } paths.solve(0); println!("{}", paths.get_cost(used.len()-1)); }