結果

問題 No.738 平らな農地
ユーザー ngtkanangtkana
提出日時 2022-01-02 11:24:15
言語 Rust
(1.77.0 + proconio)
結果
AC  
実行時間 38 ms / 2,000 ms
コード長 17,999 bytes
コンパイル時間 13,406 ms
コンパイル使用メモリ 390,920 KB
実行使用メモリ 8,560 KB
最終ジャッジ日時 2024-10-11 09:05:34
合計ジャッジ時間 18,660 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,816 KB
testcase_01 AC 1 ms
6,816 KB
testcase_02 AC 1 ms
6,820 KB
testcase_03 AC 1 ms
6,816 KB
testcase_04 AC 1 ms
6,816 KB
testcase_05 AC 2 ms
6,820 KB
testcase_06 AC 2 ms
6,820 KB
testcase_07 AC 2 ms
6,816 KB
testcase_08 AC 1 ms
6,820 KB
testcase_09 AC 1 ms
6,820 KB
testcase_10 AC 1 ms
6,816 KB
testcase_11 AC 1 ms
6,820 KB
testcase_12 AC 1 ms
6,816 KB
testcase_13 AC 2 ms
6,816 KB
testcase_14 AC 1 ms
6,816 KB
testcase_15 AC 31 ms
7,680 KB
testcase_16 AC 29 ms
7,752 KB
testcase_17 AC 30 ms
7,588 KB
testcase_18 AC 34 ms
7,748 KB
testcase_19 AC 34 ms
8,044 KB
testcase_20 AC 33 ms
7,756 KB
testcase_21 AC 38 ms
7,980 KB
testcase_22 AC 34 ms
7,784 KB
testcase_23 AC 31 ms
7,768 KB
testcase_24 AC 36 ms
7,668 KB
testcase_25 AC 1 ms
6,816 KB
testcase_26 AC 1 ms
6,816 KB
testcase_27 AC 1 ms
6,820 KB
testcase_28 AC 1 ms
6,820 KB
testcase_29 AC 2 ms
6,820 KB
testcase_30 AC 1 ms
6,816 KB
testcase_31 AC 1 ms
6,816 KB
testcase_32 AC 1 ms
6,816 KB
testcase_33 AC 1 ms
6,816 KB
testcase_34 AC 1 ms
6,820 KB
testcase_35 AC 1 ms
6,820 KB
testcase_36 AC 1 ms
6,816 KB
testcase_37 AC 1 ms
6,816 KB
testcase_38 AC 1 ms
6,820 KB
testcase_39 AC 1 ms
6,816 KB
testcase_40 AC 1 ms
6,816 KB
testcase_41 AC 1 ms
6,820 KB
testcase_42 AC 1 ms
6,816 KB
testcase_43 AC 1 ms
6,816 KB
testcase_44 AC 1 ms
6,816 KB
testcase_45 AC 33 ms
8,020 KB
testcase_46 AC 28 ms
7,416 KB
testcase_47 AC 33 ms
7,976 KB
testcase_48 AC 28 ms
7,652 KB
testcase_49 AC 28 ms
7,732 KB
testcase_50 AC 29 ms
7,956 KB
testcase_51 AC 33 ms
8,012 KB
testcase_52 AC 31 ms
7,736 KB
testcase_53 AC 32 ms
7,832 KB
testcase_54 AC 33 ms
8,024 KB
testcase_55 AC 34 ms
7,880 KB
testcase_56 AC 30 ms
7,924 KB
testcase_57 AC 28 ms
7,504 KB
testcase_58 AC 32 ms
7,768 KB
testcase_59 AC 30 ms
8,028 KB
testcase_60 AC 29 ms
7,972 KB
testcase_61 AC 29 ms
8,048 KB
testcase_62 AC 31 ms
7,516 KB
testcase_63 AC 34 ms
8,152 KB
testcase_64 AC 33 ms
8,048 KB
testcase_65 AC 18 ms
7,484 KB
testcase_66 AC 19 ms
7,824 KB
testcase_67 AC 34 ms
7,680 KB
testcase_68 AC 29 ms
7,936 KB
testcase_69 AC 23 ms
8,560 KB
testcase_70 AC 23 ms
8,064 KB
testcase_71 AC 23 ms
8,192 KB
testcase_72 AC 19 ms
7,808 KB
testcase_73 AC 20 ms
7,936 KB
testcase_74 AC 20 ms
7,936 KB
testcase_75 AC 30 ms
7,640 KB
testcase_76 AC 28 ms
7,936 KB
testcase_77 AC 29 ms
7,896 KB
testcase_78 AC 36 ms
8,340 KB
testcase_79 AC 28 ms
8,320 KB
testcase_80 AC 25 ms
7,936 KB
testcase_81 AC 28 ms
7,680 KB
testcase_82 AC 22 ms
8,064 KB
testcase_83 AC 31 ms
8,164 KB
testcase_84 AC 31 ms
7,972 KB
testcase_85 AC 22 ms
8,064 KB
testcase_86 AC 24 ms
7,552 KB
testcase_87 AC 27 ms
7,808 KB
testcase_88 AC 25 ms
7,552 KB
testcase_89 AC 1 ms
6,820 KB
testcase_90 AC 1 ms
6,816 KB
testcase_91 AC 1 ms
6,820 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
warning: unused imports: `Leaf`, `Tuple`, `VecLen`
   --> src/main.rs:293:27
    |
293 |             multi_token::{Leaf, Parser, ParserTuple, RawTuple, Tuple, VecLen},
    |                           ^^^^                                 ^^^^^  ^^^^^^
    |
    = note: `#[warn(unused_imports)]` on by default

warning: unused import: `with_str`
   --> src/main.rs:531:35
    |
531 |     pub use self::i::{with_stdin, with_str};
    |                                   ^^^^^^^^

warning: unused imports: `ParserTuple`, `Parser`, `RawTuple`, `Token`, `Usize1`
   --> src/main.rs:533:28
    |
533 |         pub use super::i::{Parser, ParserTuple, RawTuple, Token, Usize1};
    |                            ^^^^^^  ^^^^^^^^^^^  ^^^^^^^^  ^^^^^  ^^^^^^

ソースコード

diff #

use std::u64::MAX;

#[allow(unused_imports)]
#[cfg(feature = "dbg")]
use dbg::lg;
use removable_heap::{Handler, MedianHeap};

fn main() {
    let mut buf = ngtio::with_stdin();
    let n = buf.usize();
    let k = buf.usize();
    let a = buf.vec::<u64>(n);
    let mut heap = MedianHeap::new(Sum { left: 0, right: 0 });
    for &x in &a[..k] {
        heap.push(x);
    }
    let mut ans = MAX;
    for (i, j) in (0..).zip(k..) {
        let med = heap.median().unwrap();
        let cost = (med * heap.left_len() as u64 - heap.handler().left)
            + (heap.handler().right - med * heap.right_len() as u64);
        ans = ans.min(cost);
        if j == n {
            break;
        }
        heap.push(a[j]);
        heap.remove_unchecked(a[i]);
    }
    println!("{}", ans)
}

#[derive(Clone, Debug, Default, Hash, PartialEq, Copy)]
struct Sum {
    left: u64,
    right: u64,
}
impl Handler for Sum {
    type Value = u64;
    fn pop_left(&mut self, value: Self::Value) {
        self.left -= value;
    }
    fn push_left(&mut self, value: Self::Value) {
        self.left += value;
    }
    fn pop_right(&mut self, value: Self::Value) {
        self.right -= value;
    }
    fn push_right(&mut self, value: Self::Value) {
        self.right += value;
    }
}

// removable_heap {{{
#[allow(dead_code)]
mod removable_heap {
    use std::{
        cmp::Reverse, collections::BinaryHeap, fmt::Debug, hash::Hash, iter::FromIterator,
        marker::PhantomData,
    };
    pub trait Handler {
        type Value;
        fn push_left(&mut self, value: Self::Value);
        fn pop_left(&mut self, value: Self::Value);
        fn push_right(&mut self, value: Self::Value);
        fn pop_right(&mut self, value: Self::Value);
    }
    impl<T> Handler for PhantomData<T> {
        type Value = T;
        fn push_left(&mut self, _value: Self::Value) {}
        fn pop_left(&mut self, _value: Self::Value) {}
        fn push_right(&mut self, _value: Self::Value) {}
        fn pop_right(&mut self, _value: Self::Value) {}
    }
    #[derive(Clone)]
    pub struct MedianHeap<T, H> {
        left: RemovableHeap<T>,
        right: RemovableHeap<Reverse<T>>,
        handler: H,
    }
    impl<T, H> Debug for MedianHeap<T, H>
    where
        T: Copy + Ord + Hash + Debug,
        H: Handler<Value = T> + Debug,
    {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("MedianHeap")
                .field(
                    "elm",
                    &[
                        self.left.collect_sorted_vec(),
                        self.right
                            .collect_sorted_vec()
                            .into_iter()
                            .rev()
                            .map(|rev| rev.0)
                            .collect::<Vec<_>>(),
                    ],
                )
                .field("handler", &self.handler)
                .finish()
        }
    }
    impl<T> Default for MedianHeap<T, PhantomData<T>>
    where
        T: Copy + Ord + Hash,
    {
        fn default() -> Self {
            Self {
                left: RemovableHeap::default(),
                right: RemovableHeap::default(),
                handler: PhantomData,
            }
        }
    }
    impl<T: Copy + Ord + Hash, H: Handler> MedianHeap<T, H>
    where
        T: Copy + Ord + Hash,
        H: Handler<Value = T>,
    {
        pub fn new(handler: H) -> Self {
            Self {
                left: RemovableHeap::default(),
                right: RemovableHeap::default(),
                handler,
            }
        }
        pub fn is_empty(&self) -> bool {
            self.left.is_empty() && self.right.is_empty()
        }
        pub fn len(&self) -> usize {
            self.left.len() + self.right.len()
        }
        pub fn push(&mut self, elm: T) {
            self.handler.push_left(elm);
            self.left.push(elm);
            self.balance();
        }
        pub fn remove_unchecked(&mut self, elm: T) {
            if self.left.peek().map_or(false, |lmax| elm <= lmax) {
                self.handler.pop_left(elm);
                self.left.remove_unchecked(elm);
            } else {
                self.handler.pop_right(elm);
                self.right.remove_unchecked(Reverse(elm));
            }
            self.balance();
        }
        pub fn median(&self) -> Option<T> {
            self.left.peek()
        }
        pub fn upper_median(&self) -> Option<T> {
            if self.left.len() == self.right.len() {
                self.right.peek().map(|rev| rev.0)
            } else {
                self.left.peek()
            }
        }
        pub fn left_len(&self) -> usize {
            self.left.len()
        }
        pub fn right_len(&self) -> usize {
            self.right.len()
        }
        pub fn handler(&self) -> &H {
            &self.handler
        }
        pub fn collect_sorted_vec(&self) -> Vec<T> {
            let mut left = self.left.collect_sorted_vec();
            let right = self.right.collect_sorted_vec();
            left.extend(right.into_iter().rev().map(|rev| rev.0));
            left
        }
        fn balance(&mut self) {
            if !self.left.is_empty()
                && !self.right.is_empty()
                && self.left.peek() > self.right.peek().map(|rev| rev.0)
            {
                self.move_left();
                self.move_right();
            }
            while self.left.len() < self.right.len() {
                self.move_left();
            }
            while self.left.len() > 1 + self.right.len() {
                self.move_right();
            }
        }
        fn move_left(&mut self) {
            let elm = self.right.pop().unwrap().0;
            self.handler.pop_right(elm);
            self.handler.push_left(elm);
            self.left.push(elm);
        }
        fn move_right(&mut self) {
            let elm = self.left.pop().unwrap();
            self.handler.pop_left(elm);
            self.handler.push_right(elm);
            self.right.push(Reverse(elm));
        }
    }
    #[derive(Clone)]
    pub struct RemovableHeap<T> {
        heap: BinaryHeap<T>,
        removed: BinaryHeap<T>,
        len: usize,
    }
    impl<T: Copy + Ord + Hash + Debug> Debug for RemovableHeap<T> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_list().entries(self.collect_sorted_vec()).finish()
        }
    }
    impl<T: Copy + Ord + Hash> FromIterator<T> for RemovableHeap<T> {
        fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
            let heap = BinaryHeap::from_iter(iter);
            Self {
                len: heap.len(),
                heap,
                removed: BinaryHeap::default(),
            }
        }
    }
    impl<T: Copy + Ord + Hash> Default for RemovableHeap<T> {
        fn default() -> Self {
            Self {
                heap: BinaryHeap::default(),
                removed: BinaryHeap::default(),
                len: 0,
            }
        }
    }
    impl<T: Copy + Ord + Hash> RemovableHeap<T> {
        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.heap.push(x);
        }
        pub fn remove_unchecked(&mut self, x: T) {
            self.len -= 1;
            self.removed.push(x);
            self.settle();
        }
        pub fn pop(&mut self) -> Option<T> {
            let ans = self.heap.pop()?;
            self.len -= 1;
            self.settle();
            Some(ans)
        }
        pub fn peek(&self) -> Option<T> {
            self.heap.peek().copied()
        }
        pub fn collect_sorted_vec(&self) -> Vec<T> {
            let mut heap = self.heap.clone();
            let mut removed = self.removed.clone();
            let mut ans = Vec::new();
            while let Some(x) = heap.pop() {
                if removed.peek() == Some(&x) {
                    removed.pop().unwrap();
                } else {
                    ans.push(x);
                }
            }
            ans.reverse();
            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<io::Stdin>> {
            io::BufReader::new(io::stdin()).tokenizer()
        }
        pub fn with_str(src: &str) -> Tokenizer<&[u8]> {
            src.as_bytes().tokenizer()
        }
        pub struct Tokenizer<S: BufRead> {
            queue: Vec<String>, // 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<S: BufRead> Tokenizer<S> {
            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<T: Token>(&mut self) -> T::Output {
                T::parse(&self.token())
            }
            pub fn parse_collect<T: Token, B>(&mut self, n: usize) -> B
            where
                B: iter::FromIterator<T::Output>,
            {
                iter::repeat_with(|| self.parse::<T>()).take(n).collect()
            }
            pub fn tuple<T: RawTuple>(&mut self) -> <T::LeafTuple as Parser>::Output {
                T::leaf_tuple().parse(self)
            }
            pub fn vec<T: Token>(&mut self, len: usize) -> Vec<T::Output> {
                T::leaf().vec(len).parse(self)
            }
            pub fn vec_tuple<T: RawTuple>(
                &mut self,
                len: usize,
            ) -> Vec<<T::LeafTuple as Parser>::Output> {
                T::leaf_tuple().vec(len).parse(self)
            }
            pub fn vec2<T: Token>(&mut self, height: usize, width: usize) -> Vec<Vec<T::Output>> {
                T::leaf().vec(width).vec(height).parse(self)
            }
            pub fn vec2_tuple<T>(
                &mut self,
                height: usize,
                width: usize,
            ) -> Vec<Vec<<T::LeafTuple as Parser>::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<Self> {
                    Leaf(marker::PhantomData)
                }
            }
            impl<T> Token for T
            where
                T: str::FromStr,
                <Self as 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::<Self>(),)
                    })
                }
            }
            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<S: BufRead>(&self, server: &mut Tokenizer<S>) -> Self::Output;
                fn vec(self, len: usize) -> VecLen<Self> {
                    VecLen { len, elem: self }
                }
            }
            pub struct Leaf<T>(pub(super) marker::PhantomData<T>);
            impl<T: Token> Parser for Leaf<T> {
                type Output = T::Output;
                fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> T::Output {
                    server.parse::<T>()
                }
            }
            pub struct VecLen<T> {
                pub len: usize,
                pub elem: T,
            }
            impl<T: Parser> Parser for VecLen<T> {
                type Output = Vec<T::Output>;
                fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> 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<T>(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<S: BufRead >(&self, server: &mut Tokenizer<S>) -> 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<Self> {
                Tokenizer::new(self)
            }
        }
        impl<R: BufRead> Scanner for R {}
    }
    pub use self::i::{with_stdin, with_str};
    mod prelude {
        pub use super::i::{Parser, ParserTuple, RawTuple, Token, Usize1};
    }
}
// }}}
0