#[allow(unused_imports)] use std::cmp::*; // https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 macro_rules! input { ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char) .skip_while(|c|c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .collect() }; input_inner!{next, $($r)*} }; } macro_rules! input_inner { ($next:expr) => {}; ($next:expr,) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; } macro_rules! read_value { ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error")); } trait Change { fn chmax(&mut self, x: Self); fn chmin(&mut self, x: Self); } impl Change for T { fn chmax(&mut self, x: T) { if *self < x { *self = x; } } fn chmin(&mut self, x: T) { if *self > x { *self = x; } } } fn calc(n: usize, acc: &[i64], m: usize, x: i64) -> (i64, usize) { let mut dp = vec![(0, 0); n + 1]; for i in 1..n + 1 { let mut me = (dp[i - 1].0 + acc[i] - acc[i - 1] - x, dp[i - 1].1 + 1); for j in 1..min(i, m) + 1 { me.chmax((dp[i - j].0 + (acc[i] - acc[i - j]).abs() - x, dp[i - j].1 + 1)); } dp[i] = me; } dp[n] } fn main() { input! { n: usize, k: usize, m: usize, a: [i64; n], } let mut acc = vec![0; n + 1]; for i in 0..n { acc[i + 1] = acc[i] + a[i]; } let mut fail = 3i64 << 40; let mut pass = 0; while fail - pass > 1 { let mid = (fail + pass) / 2; let val = calc(n, &acc, m, mid); if val.1 >= k { pass = mid; } else { fail = mid; } } eprintln!("pass = {:?}", pass); let val = calc(n, &acc, m, pass); eprintln!("val = {:?}", val); println!("{}", val.0 + pass * k as i64); }