use std::{ cmp::Reverse, collections::{BinaryHeap, HashMap}, }; use proconio::{ input, marker::{Chars, Usize1}, }; fn main() { input! { n: usize, m: usize, edges: [(Usize1, Usize1, usize); m], s: Chars, } let mut graph = vec![vec![]; n]; for &(u, v, w) in &edges { graph[u].push((v, w)); } let mut dist = HashMap::new(); let mut heap: BinaryHeap<(Reverse, usize, Vec)> = BinaryHeap::new(); dist.insert((0, vec![]), 0); heap.push((Reverse(0), 0, vec![])); let kcpc = ['K', 'C', 'P', 'C']; while let Some((Reverse(d), current, history)) = heap.pop() { let i = history.len(); if d != dist[&(current, history.clone())] { continue; } let target = kcpc[history.len()]; if target == s[current] && !history.contains(¤t) { if i == 3 { println!("{}", d); return; } else { let mut nhistory = history.clone(); nhistory.push(current); if !dist.contains_key(&(current, nhistory.clone())) { dist.insert((current, nhistory.clone()), d); heap.push((Reverse(d), current, nhistory)); } } } for &(next, w) in &graph[current] { if dist .get(&(next, history.clone())) .copied() .unwrap_or(!0usize) > d + w { dist.insert((next, history.clone()), d + w); heap.push((Reverse(d + w), next, history.clone())); } } } println!("-1"); }