アルゴリズムと数学 076

https://atcoder.jp/contests/math-and-algorithm/tasks/abc186_d

この問題のポイントは、各要素間の距離の総和だからAを並べ替えても値が同じということですね。

// Sum of difference
#![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> {
    let _N: usize = read();
    let A = read_vec();
    A
}

fn f(mut A: Vec<i64>) -> i64 {
    A.sort();
    let N = A.len();
    let mut s: i64 = 0;
    for i in 0..N {
        s += (1 - (N as i64) + 2 * (i as i64)) * A[i]
    }
    s
}

fn main() {
    let A = read_input();
    println!("{}", f(A))
}