https://atcoder.jp/contests/math-and-algorithm/tasks/math_and_algorithm_ak
西の端から累積の距離を計算しておくだけですね。
// Travel #![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<i64>, Vec<usize>) { let _N: usize = read(); let A: Vec<i64> = read_vec(); let M: usize = read(); let B = (0..M).map(|_| read::<usize>() - 1).collect::<Vec<usize>>(); (A, B) } fn accumulate(A: Vec<i64>) -> Vec<i64> { let mut acc = (0..A.len()+1).map(|_| 0).collect::<Vec<i64>>(); for (i, a) in A.into_iter().enumerate() { acc[i+1] = acc[i] + a } acc } fn f(A: Vec<i64>, B: Vec<usize>) -> i64 { let acc = accumulate(A); (0..B.len()-1).map(|i| (acc[B[i+1]] - acc[B[i]]).abs()).sum() } fn main() { let (A, B) = read_input(); println!("{}", f(A, B)) }