#[allow(unused_imports)] use std::cmp::{max, min, Ordering}; #[allow(unused_imports)] use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque}; #[allow(unused_imports)] use std::iter::FromIterator; #[allow(unused_imports)] use std::io::stdin; mod util { use std::io::stdin; use std::str::FromStr; use std::fmt::Debug; #[allow(dead_code)] pub fn line() -> String { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); line.trim().to_string() } #[allow(dead_code)] pub fn gets() -> Vec where ::Err: Debug, { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|t| t.parse().unwrap()) .collect() } } #[allow(unused_macros)] macro_rules ! get { ( $ t : ty ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,* ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; let mut iter = line . split_whitespace ( ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; ( $ t : ty ; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ ( $ t : ty ) ,*; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ ( $ t ) ,* ) ) . collect ::< Vec < _ >> ( ) } ; ( $ t : ty ;; ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . split_whitespace ( ) . map ( | t | t . parse ::<$ t > ( ) . unwrap ( ) ) . collect ::< Vec < _ >> ( ) } } ; } #[allow(unused_macros)] macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { println ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) ; } } fn main() { let (n, m, k, s, t) = get!(usize, usize, i64, i64, i64); let abc = get!(usize, i64, i64; m); let mut edges = vec![Vec::new(); n - 1]; for &(a, b, c) in &abc { edges[a - 1].push((b, c)); } let mut dp = BTreeMap::new(); dp.insert(s, 0); for es in edges.iter_mut() { if es.is_empty() { println!("-1"); return; } es.sort(); let v: Vec<(i64, i64)> = dp.into_iter().collect(); dp = BTreeMap::new(); let mut i = v.len(); let mut cost = i64::max_value() / 4; for &(b, c) in es.iter().rev() { while i > 0 && v[i - 1].0 >= b { i -= 1; cost = min(cost, v[i].0 + v[i].1); } dp.insert(c, cost - b); } let mut i = 0; let mut cost = i64::max_value() / 4; for &(b, c) in es.iter().rev() { while i < v.len() && v[i].0 <= b { cost = min(cost, v[i].1 - v[i].0); i += 1; } let nc = cost + b; let v = dp.entry(c).or_insert(nc); *v = min(*v, nc); } } println!( "{}", dp.into_iter() .map(|(p, c)| c + (t - p).abs()) .min() .unwrap() ); }