#![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 t = read::(); let v = read_vec::(); let (n, m) = (v[0], v[1]); let mut edges = vec![vec![]; n]; let mut edge_list = vec![]; for _ in 0..m { let v = read_vec::(); let (a, b, c) = (v[0] as usize - 1, v[1] as usize - 1, v[2]); edges[a].push(Edge { to: b, cost: c }); if t == 0 { edges[b].push(Edge { to: a, cost: c }); } edge_list.push((a, b)); } let mut ans = INF; for (a, b) in edge_list { let mut idx = 0; let mut cost = 0; for i in 0..edges[a].len() { if edges[a][i].to == b { idx = i; cost = edges[a][i].cost; } } edges[a].remove(idx); if t == 0 { let mut idx2 = 0; for i in 0..edges[b].len() { if edges[b][i].to == a { idx2 = i; } } edges[b].remove(idx2); } let d = solve(&edges, b); edges[a].push(Edge { to: b, cost: cost }); if t == 0 { edges[b].push(Edge { to: a, cost: cost }); } ans = min(ans, d[a] + cost); } if ans == INF { println!("-1"); return; } println!("{}", ans); } use std::cmp::Ordering; use std::collections::BinaryHeap; type Cost = i64; const INF: Cost = 100000_00000_00000; #[derive(PartialEq, Debug)] struct MinInt { value: Cost, } impl Eq for MinInt {} impl PartialOrd for MinInt { fn partial_cmp(&self, other: &Self) -> Option { other.value.partial_cmp(&self.value) } } impl Ord for MinInt { fn cmp(&self, other: &MinInt) -> Ordering { other.value.partial_cmp(&self.value).unwrap() } } fn make_pair(x: Cost, y: usize) -> (MinInt, usize) { (MinInt { value: x }, y) } #[derive(Debug, Clone)] struct Edge { to: usize, cost: Cost, } fn solve(edges: &Vec>, start_idx: usize) -> Vec { let num_apexes = edges.len(); let mut d = vec![INF; num_apexes]; d[start_idx] = 0; let mut que = BinaryHeap::new(); que.push(make_pair(0, start_idx)); while let Some((u, v)) = que.pop() { if d[v] < u.value { continue; } for e in &edges[v] { if d[v] != INF && d[e.to] > d[v] + e.cost { d[e.to] = d[v] + e.cost; que.push(make_pair(d[e.to], e.to)); } } } d } 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() }