https://atcoder.jp/contests/abc325/tasks/abc325_e
ダイクストラ法ですが、社用車と電車の2つのテーブルが必要です。
// Our clients, please wait a moment #![allow(non_snake_case)] use std::cmp::min; use std::collections::BinaryHeap; //////////////////// library //////////////////// fn read<T: std::str::FromStr>() -> T { let mut line = String::new(); std::io::stdin().read_line(&mut line).ok(); line.trim().parse().ok().unwrap() } fn read_vec<T: std::str::FromStr>() -> Vec<T> { read::<String>().split_whitespace() .map(|e| e.parse().ok().unwrap()).collect() } //////////////////// Item //////////////////// #[derive(PartialEq, Eq, Clone)] enum Transportation { Car, Train } type City = usize; #[derive(Clone, Eq, PartialEq)] struct Item(City, u64, Transportation); impl Ord for Item { fn cmp(&self, other: &Self) -> std::cmp::Ordering { other.1.cmp(&self.1) } } impl PartialOrd for Item { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } //////////////////// process //////////////////// fn read_input() -> (u64, u64, u64, Vec<Vec<u64>>) { let v = read_vec(); let (N, A, B, C) = (v[0], v[1], v[2], v[3]); let D: Vec<Vec<u64>> = (0..N).map(|_| read_vec::<u64>()).collect(); (A, B, C, D) } fn F(A: u64, B: u64, C: u64, D: Vec<Vec<u64>>) -> u64 { let N = D.len(); let mut car_times: Vec<Option<u64>> = vec![None; N]; let mut train_times: Vec<Option<u64>> = vec![None; N]; let mut heap = BinaryHeap::new(); heap.push(Item(0, 0, Transportation::Car)); while let Some(item) = heap.pop() { let (city, time, trans) = (item.0, item.1, item.2); if trans == Transportation::Car { match car_times[city] { None => car_times[city] = Some(time), _ => continue } } if trans == Transportation::Train { match train_times[city] { None => train_times[city] = Some(time), _ => continue } } for neighbor in (0..N).filter(|&c| c != city) { if trans == Transportation::Car && car_times[neighbor].is_none() { let t = time + D[city][neighbor] * A; heap.push(Item(neighbor, t, Transportation::Car)) } if train_times[neighbor].is_none() { let t = time + D[city][neighbor] * B + C; heap.push(Item(neighbor, t, Transportation::Train)) } } } min(car_times[N-1].unwrap(), train_times[N-1].unwrap()) } fn main() { let (A, B, C, D) = read_input(); println!("{}", F(A, B, C, D)) }