use std::{collections::BTreeMap, cmp::Reverse}; fn main() { let mut nk = String::new(); std::io::stdin().read_line(&mut nk).ok(); let nk: Vec = nk.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let n = nk[0]; let mut k = nk[1]; let mut a = String::new(); std::io::stdin().read_line(&mut a).ok(); let a: Vec = a.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let mut stock = BTreeMap::new(); let mut a = a.into_iter().skip(1).enumerate().collect::>(); a.sort_by_key(|&(i, v)| (Reverse(v), i % 2, i)); a.reverse(); let mut result = 0usize; let mut minidx = n; while k > 0 { let (idx, val) = a.pop().unwrap(); if idx % 2 == 0 { minidx = idx.min(minidx); result += val; k -= 1; let mut targets = stock.range(idx..).map(|(&idx, &v)| (idx, v)).collect::>(); targets.sort_by_key(|&(_, v)| Reverse(v)); let limit = k.min(targets.len()); for i in 0..limit { let (idx, v) = targets[i]; stock.remove(&idx); result += v; k -= 1; } } else if idx > minidx { k -= 1; result += val; } else { stock.insert(idx, val); } } println!("{}", result); }