blob: db20c411b6848c30c19c0433f4e9049ac5a010d4 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
use std::io::{BufRead};
fn cost(positions: & [i64], dest: i64) -> i64 {
positions.into_iter().map(|x| (x - dest).abs()).sum()
}
fn median<T: Copy + Ord>(mut x: Vec<T>) -> T {
let n = x.len();
*x.select_nth_unstable(n/2).1
}
pub fn main() {
let mut stdin = std::io::stdin();
let mut handle = stdin.lock();
let input: String = {
let mut buf = String::new();
handle.read_line(&mut buf).unwrap();
String::from(buf.trim_end())
};
let positions: Vec<i64> = input.split(',').map(|w| w.parse().expect("Malformed input")).collect();
let median = median(positions.clone());
let cost = cost(& positions, median);
println!("Align at {} for a cost of {}.", median, cost);
}
|