https://atcoder.jp/contests/math-and-algorithm/tasks/abc140_c
Bの小さいところから、それを挟むAがまだ定まっていなければBと同じ値にします。
// Maximal Value #![allow(non_snake_case)] //////////////////// 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() } //////////////////// process //////////////////// fn read_input() -> Vec<i32> { let _N: usize = read(); let B: Vec<i32> = read_vec(); B } fn f(B: Vec<i32>) -> i32 { let N = B.len() + 1; let mut ks: Vec<usize> = (0..N-1).collect(); ks.sort_by_key(|&k| B[k]); let mut A: Vec<i32> = vec![-1; N]; for k in ks.into_iter() { if A[k] == -1 { A[k] = B[k] } if A[k+1] == -1 { A[k+1] = B[k] } } A.into_iter().sum::<i32>() } fn main() { let B = read_input(); println!("{}", f(B)) }