#![allow(unused_imports, unused_macros)] use kyoproio::*; use std::{ collections::*, io::{self, prelude::*}, iter, mem::{replace, swap}, }; fn run(mut kin: I, mut out: O) { const INF: i64 = 1 << 60; let (t, n, m): (i32, usize, usize) = kin.input(); let mut g = LabeledGraph::builder(n + 1); for (u, v, w) in kin.iter::<(usize, usize, i64)>().take(m) { g.edge(u, v, w); if t == 0 { g.edge(v, u, w); } } let g = g.build(); let mut dist = vec![vec![INF; n + 1]; n + 1]; let mut par = vec![vec![0; n + 1]; n + 1]; for s in 1..=n { dist[s][s] = 0; let mut que = BinaryHeap::new(); que.push((0, s)); while let Some((d, u)) = que.pop() { let d = -d; if d > dist[s][u] { continue; } for &(v, w) in &g[u] { let dc = dist[s][u] + w; if dc < dist[s][v] { dist[s][v] = dc; par[s][v] = u; que.push((-dc, v)); } } } } let mut ans = INF; if t == 0 { for s in 1..=n { for u in 1..=n { for &(v, w) in &g[u] { if par[s][u] == v || par[s][v] == u { continue; } ans = ans.min(dist[s][u] + w + dist[s][v]); } } } } else { for s in 1..=n { for t in 1..=n { if s != t { ans = ans.min(dist[s][t] + dist[t][s]); } } } } if ans == INF { ans = -1; } outln!(out, "{}", ans); } pub struct Graph(LabeledGraph<()>); impl Graph { pub fn builder(n: usize) -> GraphBuilder { GraphBuilder(LabeledGraph::builder(n)) } pub fn len(&self) -> usize { self.0.len() } } impl std::ops::Index for Graph { type Output = [usize]; fn index(&self, u: usize) -> &Self::Output { unsafe { std::mem::transmute(self.0.index(u)) } } } pub struct GraphBuilder(LabeledGraphBuilder<()>); impl GraphBuilder { pub fn edge(&mut self, u: usize, v: usize) { self.0.edge(u, v, ()); } pub fn build(&mut self) -> Graph { Graph(self.0.build()) } } pub struct LabeledGraph { edges: Box<[(usize, T)]>, heads: Box<[usize]>, } impl LabeledGraph { pub fn builder(n: usize) -> LabeledGraphBuilder { LabeledGraphBuilder { nodes: Vec::new(), heads: vec![!0; n], } } pub fn len(&self) -> usize { self.heads.len() - 1 } } impl std::ops::Index for LabeledGraph { type Output = [(usize, T)]; fn index(&self, u: usize) -> &Self::Output { &self.edges[self.heads[u]..self.heads[u + 1]] } } pub struct LabeledGraphBuilder { nodes: Vec<((usize, T), usize)>, heads: Vec, } impl LabeledGraphBuilder { pub fn edge(&mut self, u: usize, v: usize, l: T) { self.nodes.push(((v, l), self.heads[u])); self.heads[u] = self.nodes.len() - 1; } pub fn build(&mut self) -> LabeledGraph { let mut edges = Vec::with_capacity(self.nodes.len()); let mut heads = Vec::with_capacity(self.heads.len() + 1); for &(mut h) in &self.heads { heads.push(edges.len()); while let Some((e, next)) = self.nodes.get(h) { edges.push(e.clone()); h = *next; } } heads.push(edges.len()); LabeledGraph { edges: edges.into(), heads: heads.into(), } } } // ----------------------------------------------------------------------------- fn main() -> io::Result<()> { std::thread::Builder::new() .stack_size(64 * 1024 * 1024) .spawn(|| { run( KInput::new(io::stdin().lock()), io::BufWriter::new(io::stdout().lock()), ) })? .join() .unwrap(); Ok(()) } #[macro_export] macro_rules! out { ($($arg:tt)*) => { write!($($arg)*).unwrap(); } } #[macro_export] macro_rules! outln { ($dst:expr $(, $($arg:tt)*)?) => {{ writeln!($dst $(, $($arg)*)?).unwrap(); if cfg!(debug_assertions) { $dst.flush().unwrap(); } }} } #[macro_export] macro_rules! eout { ($($arg:tt)*) => { if cfg!(debug_assertions) { eprintln!($($arg)*); } } } #[macro_export] macro_rules! kdbg { ($($v:expr),*) => { if cfg!(debug_assertions) { dbg!($($v),*) } else { ($($v),*) } } } pub mod kyoproio { use std::{ io::prelude::*, iter::FromIterator, marker::PhantomData, mem::{self, MaybeUninit}, str, }; pub trait Input { fn bytes(&mut self) -> &[u8]; fn str(&mut self) -> &str { str::from_utf8(self.bytes()).unwrap() } fn input(&mut self) -> T { T::input(self) } fn iter(&mut self) -> Iter { Iter(self, PhantomData) } fn seq>(&mut self, n: usize) -> B { self.iter().take(n).collect() } } pub struct KInput { src: R, buf: Vec, pos: usize, len: usize, } impl KInput { pub fn new(src: R) -> Self { Self { src, buf: vec![0; 1 << 16], pos: 0, len: 0, } } fn read(&mut self) -> usize { if self.pos > 0 { self.buf.copy_within(self.pos..self.len, 0); self.len -= self.pos; self.pos = 0; } else if self.len >= self.buf.len() { self.buf.resize(2 * self.buf.len(), 0); } let n = self.src.read(&mut self.buf[self.len..]).unwrap(); self.len += n; n } } impl Input for KInput { fn bytes(&mut self) -> &[u8] { loop { while let Some(d) = self.buf[self.pos..self.len] .iter() .position(u8::is_ascii_whitespace) { let p = self.pos; self.pos += d + 1; if d > 0 { return &self.buf[p..p + d]; } } if self.read() == 0 { return &self.buf[mem::replace(&mut self.pos, self.len)..self.len]; } } } } pub struct Iter<'a, T, I: ?Sized>(&'a mut I, PhantomData<*const T>); impl<'a, T: InputItem, I: Input + ?Sized> Iterator for Iter<'a, T, I> { type Item = T; fn next(&mut self) -> Option { Some(self.0.input()) } fn size_hint(&self) -> (usize, Option) { (!0, None) } } pub trait InputItem: Sized { fn input(src: &mut I) -> Self; } impl InputItem for Vec { fn input(src: &mut I) -> Self { src.bytes().to_owned() } } macro_rules! from_str { ($($T:ty)*) => { $(impl InputItem for $T { fn input(src: &mut I) -> Self { src.str().parse::<$T>().unwrap() } })* } } from_str!(String char bool f32 f64); macro_rules! parse_int { ($($I:ty: $U:ty)*) => { $(impl InputItem for $I { fn input(src: &mut I) -> Self { let f = |s: &[u8]| s.iter().fold(0, |x, b| 10 * x + (b & 0xf) as $I); let s = src.bytes(); if let Some((&b'-', t)) = s.split_first() { -f(t) } else { f(s) } } } impl InputItem for $U { fn input(src: &mut I) -> Self { src.bytes().iter().fold(0, |x, b| 10 * x + (b & 0xf) as $U) } })* } } parse_int!(isize:usize i8:u8 i16:u16 i32:u32 i64:u64 i128:u128); macro_rules! tuple { ($H:ident $($T:ident)*) => { impl<$H: InputItem, $($T: InputItem),*> InputItem for ($H, $($T),*) { fn input(src: &mut I) -> Self { ($H::input(src), $($T::input(src)),*) } } tuple!($($T)*); }; () => {} } tuple!(A B C D E F G); macro_rules! array { ($($N:literal)*) => { $(impl InputItem for [T; $N] { fn input(src: &mut I) -> Self { let mut arr = MaybeUninit::uninit(); let ptr = arr.as_mut_ptr() as *mut T; unsafe { for i in 0..$N { ptr.add(i).write(src.input()); } arr.assume_init() } } })* } } array!(1 2 3 4 5 6 7 8); }