use std::io::Write; use std::collections::*; fn run() { input! { t: usize, ask: [[(i64, i64); 2]; t], } let out = std::io::stdout(); let mut out = std::io::BufWriter::new(out.lock()); for ask in ask { let (s, t) = (ask[0], ask[1]); let mut z = vec![0]; for &v in [s.0, s.1, t.0, t.1].iter() { z.push(v - 1); z.push(v); z.push(v); } z.sort(); z.dedup(); let inf = std::i64::MAX / 10; let mut dp = vec![vec![inf; z.len()]; z.len()]; let a = z.iter().position(|z| *z == s.0).unwrap(); let b = z.iter().position(|z| *z == s.1).unwrap(); dp[a][b] = 0; let mut h = std::collections::BinaryHeap::new(); h.push((0, a, b)); while let Some((d, a, b)) = h.pop() { let d = -d; if d > dp[a][b] { continue; } if a > 0 && b > 0 { for &(x, y) in [(0, b), (a, 0)].iter() { if dp[x][y].chmin(d + 1) { h.push((-dp[x][y], x, y)); } } } if a + 1 < z.len() && a + 1 != b && dp[a + 1][b].chmin(d + z[a + 1] - z[a]) { h.push((-dp[a + 1][b], a + 1, b)); } if b + 1 < z.len() && b + 1 != a && dp[a][b + 1].chmin(d + z[b + 1] - z[b]) { h.push((-dp[a][b + 1], a, b + 1)); } } let a = z.iter().position(|z| *z == t.0).unwrap(); let b = z.iter().position(|z| *z == t.1).unwrap(); writeln!(out, "{}", dp[a][b]).ok(); } } fn main() { run(); } // ---------- begin input macro ---------- // reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 #[macro_export] macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let s = { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); s }; let mut iter = s.split_whitespace(); input_inner!{iter, $($r)*} }; } #[macro_export] macro_rules! input_inner { ($iter:expr) => {}; ($iter:expr, ) => {}; ($iter:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($iter, $t); input_inner!{$iter $($r)*} }; } #[macro_export] macro_rules! read_value { ($iter:expr, ( $($t:tt),* )) => { ( $(read_value!($iter, $t)),* ) }; ($iter:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($iter, $t)).collect::>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::>() }; ($iter:expr, bytes) => { read_value!($iter, String).bytes().collect::>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } // ---------- end input macro ---------- // ---------- begin chmin, chmax ---------- pub trait ChangeMinMax { fn chmin(&mut self, x: Self) -> bool; fn chmax(&mut self, x: Self) -> bool; } impl ChangeMinMax for T { fn chmin(&mut self, x: Self) -> bool { *self > x && { *self = x; true } } fn chmax(&mut self, x: Self) -> bool { *self < x && { *self = x; true } } } // ---------- end chmin, chmax ----------