https://atcoder.jp/contests/math-and-algorithm/tasks/typical90_n
AとBの両方をソートして距離を取ります。
// We Used to Sing a Song Together #![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<i64>) { let _N: usize = read(); let A = read_vec(); let B = read_vec(); (A, B) } fn f(mut A: Vec<i64>, mut B: Vec<i64>) -> i64 { A.sort(); B.sort(); A.into_iter().zip(B.into_iter()).map(|(a, b)| (a-b).abs()).sum::<i64>() } fn main() { let (A, B) = read_input(); println!("{}", f(A, B)) }