use std::{cmp::Reverse, usize::MAX}; #[allow(unused_imports)] #[cfg(feature = "dbg")] use dbg::lg; use removable_heap::RemovableHeap; fn main() { let mut buf = ngtio::with_stdin(); let n = buf.usize(); let k = buf.usize(); let a = buf.vec::(n); let mut queue = Queue::default(); for &x in &a[..k] { queue.insert(x); } let mut ans = MAX; for (i, j) in (0..).zip(k..) { let med = queue.left.peek().unwrap(); let cost = (med * queue.left.len() - queue.left_sum) + (queue.right_sum - med * queue.right.len()); ans = ans.min(cost); if j == n { break; } queue.remove(a[i]); queue.insert(a[j]); } println!("{}", ans); } #[derive(Clone, Debug, Default)] struct Queue { left: RemovableHeap, right: RemovableHeap>, left_sum: usize, right_sum: usize, } impl Queue { fn insert(&mut self, x: usize) { if self.left.len() > self.right.len() { self.move_right(); } self.left.push(x); self.left_sum += x; if self.is_reversed() { self.move_right(); self.move_left(); } } fn remove(&mut self, x: usize) { if self.left.peek().map_or(false, |&lmax| x <= lmax) { self.left_sum -= x; if self.left.len() < self.right.len() { self.move_left(); } self.left.remove(x); } else { self.right_sum -= x; if self.left.len() > self.right.len() + 1 { self.move_right(); } self.right.remove(Reverse(x)); } } fn is_reversed(&self) -> bool { !self.left.is_empty() && !self.right.is_empty() && self.left.peek().unwrap() > &self.right.peek().unwrap().0 } fn move_left(&mut self) { let x = self.right.pop().unwrap().0; self.right_sum -= x; self.left_sum += x; self.left.push(x); } fn move_right(&mut self) { let x = self.left.pop().unwrap(); self.left_sum -= x; self.right_sum += x; self.right.push(Reverse(x)); } } // removable_heap {{{ #[allow(dead_code)] mod removable_heap { use std::{ collections::{BinaryHeap, HashMap}, fmt::Debug, hash::Hash, iter::{repeat, FromIterator}, }; #[derive(Clone)] pub struct RemovableHeap { heap: BinaryHeap, removed: BinaryHeap, map: HashMap, len: usize, } impl Debug for RemovableHeap { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_list().entries(self.collect_sorted_vec()).finish() } } impl FromIterator for RemovableHeap { fn from_iter>(iter: I) -> Self { let heap = BinaryHeap::from_iter(iter); let mut map = HashMap::default(); for &x in &heap { *map.entry(x).or_insert(0) += 1; } Self { len: heap.len(), heap, removed: BinaryHeap::default(), map, } } } impl Default for RemovableHeap { fn default() -> Self { Self { heap: BinaryHeap::default(), removed: BinaryHeap::default(), map: HashMap::new(), len: 0, } } } impl RemovableHeap { pub fn new() -> Self { Self::default() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn len(&self) -> usize { self.len } pub fn push(&mut self, x: T) { self.len += 1; *self.map.entry(x).or_insert(0) += 1; self.heap.push(x); } pub fn remove(&mut self, x: T) -> Option { if self.map.contains_key(&x) { self.len -= 1; if self.map[&x] == 1 { self.map.remove(&x).unwrap(); } else { *self.map.entry(x).or_insert(0) -= 1; } self.removed.push(x); self.settle(); Some(x) } else { None } } pub fn pop(&mut self) -> Option { let ans = self.heap.pop()?; self.len -= 1; if self.map[&ans] == 1 { self.map.remove(&ans).unwrap(); } else { *self.map.entry(ans).or_insert(0) -= 1; } self.settle(); Some(ans) } pub fn peek(&self) -> Option<&T> { self.heap.peek() } pub fn collect_sorted_vec(&self) -> Vec { let mut ans = self .map .iter() .flat_map(|(&k, &v)| repeat(k).take(v)) .collect::>(); ans.sort(); ans } fn settle(&mut self) { while !self.heap.is_empty() && self.heap.peek() <= self.removed.peek() { self.heap.pop().unwrap(); self.removed.pop().unwrap(); } } } } // }}} // template {{{ #[cfg(not(feature = "dbg"))] #[allow(unused_macros)] #[macro_export] macro_rules! lg { ($($expr:expr),*) => {}; } #[allow(dead_code)] mod ngtio { mod i { pub use self::{ multi_token::{Leaf, Parser, ParserTuple, RawTuple, Tuple, VecLen}, token::{Token, Usize1}, }; use std::{ io::{self, BufRead}, iter, }; pub fn with_stdin() -> Tokenizer> { io::BufReader::new(io::stdin()).tokenizer() } pub fn with_str(src: &str) -> Tokenizer<&[u8]> { src.as_bytes().tokenizer() } pub struct Tokenizer { queue: Vec, // FIXME: String のみにすると速そうです。 scanner: S, } macro_rules! prim_method { ($name:ident: $T:ty) => { pub fn $name(&mut self) -> $T { <$T>::leaf().parse(self) } }; ($name:ident) => { prim_method!($name: $name); }; } macro_rules! prim_methods { ($name:ident: $T:ty; $($rest:tt)*) => { prim_method!($name:$T); prim_methods!($($rest)*); }; ($name:ident; $($rest:tt)*) => { prim_method!($name); prim_methods!($($rest)*); }; () => () } impl Tokenizer { pub fn token(&mut self) -> String { self.load(); self.queue.pop().expect("入力が終了したのですが。") } pub fn new(scanner: S) -> Self { Self { queue: Vec::new(), scanner, } } fn load(&mut self) { while self.queue.is_empty() { let mut s = String::new(); let length = self.scanner.read_line(&mut s).unwrap(); // 入力が UTF-8 でないときにエラーだそうです。 if length == 0 { break; } self.queue = s.split_whitespace().rev().map(str::to_owned).collect(); } } pub fn skip_line(&mut self) { assert!( self.queue.is_empty(), "行の途中で呼ばないでいただきたいです。現在のトークンキュー: {:?}", &self.queue ); self.load(); } pub fn end(&mut self) { self.load(); assert!(self.queue.is_empty(), "入力はまだあります!"); } pub fn parse(&mut self) -> T::Output { T::parse(&self.token()) } pub fn parse_collect(&mut self, n: usize) -> B where B: iter::FromIterator, { iter::repeat_with(|| self.parse::()).take(n).collect() } pub fn tuple(&mut self) -> ::Output { T::leaf_tuple().parse(self) } pub fn vec(&mut self, len: usize) -> Vec { T::leaf().vec(len).parse(self) } pub fn vec_tuple( &mut self, len: usize, ) -> Vec<::Output> { T::leaf_tuple().vec(len).parse(self) } pub fn vec2(&mut self, height: usize, width: usize) -> Vec> { T::leaf().vec(width).vec(height).parse(self) } pub fn vec2_tuple( &mut self, height: usize, width: usize, ) -> Vec::Output>> where T: RawTuple, { T::leaf_tuple().vec(width).vec(height).parse(self) } prim_methods! { u8; u16; u32; u64; u128; usize; i8; i16; i32; i64; i128; isize; f32; f64; char; string: String; } } mod token { use super::multi_token::Leaf; use std::{any, fmt, marker, str}; pub trait Token: Sized { type Output; fn parse(s: &str) -> Self::Output; fn leaf() -> Leaf { Leaf(marker::PhantomData) } } impl Token for T where T: str::FromStr, ::Err: fmt::Debug, { type Output = Self; fn parse(s: &str) -> Self::Output { s.parse().unwrap_or_else(|_| { panic!("Parse error!: ({}: {})", s, any::type_name::(),) }) } } pub struct Usize1 {} impl Token for Usize1 { type Output = usize; fn parse(s: &str) -> Self::Output { usize::parse(s) .checked_sub(1) .expect("Parse error! (Zero substruction error of Usize1)") } } } mod multi_token { use super::{Token, Tokenizer}; use std::{io::BufRead, iter, marker}; pub trait Parser: Sized { type Output; fn parse(&self, server: &mut Tokenizer) -> Self::Output; fn vec(self, len: usize) -> VecLen { VecLen { len, elem: self } } } pub struct Leaf(pub(super) marker::PhantomData); impl Parser for Leaf { type Output = T::Output; fn parse(&self, server: &mut Tokenizer) -> T::Output { server.parse::() } } pub struct VecLen { pub len: usize, pub elem: T, } impl Parser for VecLen { type Output = Vec; fn parse(&self, server: &mut Tokenizer) -> Self::Output { iter::repeat_with(|| self.elem.parse(server)) .take(self.len) .collect() } } pub trait RawTuple { type LeafTuple: Parser; fn leaf_tuple() -> Self::LeafTuple; } pub trait ParserTuple { type Tuple: Parser; fn tuple(self) -> Self::Tuple; } pub struct Tuple(pub T); macro_rules! impl_tuple { ($($t:ident: $T:ident),*) => { impl<$($T),*> Parser for Tuple<($($T,)*)> where $($T: Parser,)* { type Output = ($($T::Output,)*); #[allow(unused_variables)] fn parse(&self, server: &mut Tokenizer) -> Self::Output { match self { Tuple(($($t,)*)) => { ($($t.parse(server),)*) } } } } impl<$($T: Token),*> RawTuple for ($($T,)*) { type LeafTuple = Tuple<($(Leaf<$T>,)*)>; fn leaf_tuple() -> Self::LeafTuple { Tuple(($($T::leaf(),)*)) } } impl<$($T: Parser),*> ParserTuple for ($($T,)*) { type Tuple = Tuple<($($T,)*)>; fn tuple(self) -> Self::Tuple { Tuple(self) } } }; } impl_tuple!(); impl_tuple!(t1: T1); impl_tuple!(t1: T1, t2: T2); impl_tuple!(t1: T1, t2: T2, t3: T3); impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4); impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5); impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6); impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7); impl_tuple!( t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8 ); } trait Scanner: BufRead + Sized { fn tokenizer(self) -> Tokenizer { Tokenizer::new(self) } } impl Scanner for R {} } pub use self::i::{with_stdin, with_str}; mod prelude { pub use super::i::{Parser, ParserTuple, RawTuple, Token, Usize1}; } } // }}}