#![allow(non_snake_case, unused_imports, unused_must_use)] use std::io::{self, prelude::*}; use std::str; fn main() { let (stdin, stdout) = (io::stdin(), io::stdout()); let mut scan = Scanner::new(stdin.lock()); let mut out = io::BufWriter::new(stdout.lock()); macro_rules! input { ($T: ty) => { scan.token::<$T>() }; ($T: ty, $N: expr) => { (0..$N).map(|_| scan.token::<$T>()).collect::>() }; } let H = input!(isize); let W = input!(isize); let N = input!(usize); let dist = |y1: isize, x1: isize, y2: isize, x2: isize| (y2 - y1).abs() + (x2 - x1).abs(); let mut edges = vec![]; edges.push((2 * N, 2 * N + 1, dist(H, W, 1, 1))); let mut warp_points = vec![]; for _ in 0..N { let a = input!(isize); let b = input!(isize); let c = input!(isize); let d = input!(isize); warp_points.push((a, b, c, d)); } for i in 0..N { let (a, b, c, d) = warp_points[i]; edges.push((2 * N, 2 * i, dist(a, b, 1, 1))); edges.push((2 * i + 1, 2 * N + 1, dist(c, d, H, W))); edges.push((2 * i, 2 * i + 1, 1)); } for i in 0..N { for j in 0..N { let (a1, b1, c1, d1) = warp_points[i]; let (a2, b2, c2, d2) = warp_points[j]; edges.push((2 * i + 1, 2 * j, dist(c1, d1, a2, b2))); } } let dist = dijkstras_algorithm(2 * N + 2, &edges, 2 * N)[2 * N + 1].unwrap(); writeln!(out, "{}", dist); } pub fn dijkstras_algorithm< W: Sized + std::ops::Add + PartialOrd + Ord + Default + Clone + Copy, >( size: usize, edges: &[(usize, usize, W)], start: usize, ) -> Vec> { assert!(start < size); let graph = { let mut g = vec![vec![]; size]; for &(from, to, weight) in edges.iter() { assert!(from < size && to < size); g[from].push((to, weight)); } g }; let mut dist = vec![None; size]; dist[start] = Some(W::default()); let mut hq = std::collections::BinaryHeap::new(); hq.push((std::cmp::Reverse(W::default()), start)); while let Some((_, now)) = hq.pop() { for &(nxt, weight) in graph[now].iter() { match dist[nxt] { Some(prev_dist) => { if dist[now].unwrap() + weight < prev_dist { let d = dist[now].unwrap() + weight; dist[nxt] = Some(d); hq.push((std::cmp::Reverse(d), nxt)); } } None => { let d = dist[now].unwrap() + weight; dist[nxt] = Some(d); hq.push((std::cmp::Reverse(d), nxt)); } } } } dist } struct Scanner { reader: R, buf_str: Vec, buf_iter: str::SplitWhitespace<'static>, } impl Scanner { fn new(reader: R) -> Self { Self { reader, buf_str: vec![], buf_iter: "".split_whitespace(), } } fn token(&mut self) -> T { loop { if let Some(token) = self.buf_iter.next() { return token.parse().ok().expect("Failed parse"); } self.buf_str.clear(); self.reader .read_until(b'\n', &mut self.buf_str) .expect("Failed read"); self.buf_iter = unsafe { let slice = str::from_utf8_unchecked(&self.buf_str); std::mem::transmute(slice.split_whitespace()) } } } }