Submission #19308696


Source Code Expand

Copy
#[allow(unused_imports)]
use ngtio::prelude::*;
use ordtools::Ordtools;

fn main() {
    let mut buf = ngtio::with_stdin();
    let n = buf.usize();
    let m = buf.usize();
    let mut g = vec![Vec::new(); n];
    for i in 1..n {
        let p = buf.usize();
        g[p].push(i);
    }
    let mut a = vec![std::u32::MAX; n];
    for _ in 0..m {
        let i = buf.usize();
        let x = buf.u32();
        a[i] = x;
    }
    let ord = tree_preorder(0, &g);
    for &x in ord.iter().rev() {
        for &y in &g[x] {
            let ay = a[y];
            a[x].change_min(ay);
        }
    }
    a[0] = 0;
    let ans = (0..n)
        .map(|i| g[i].iter().map(|&j| a[j] - a[i]).sum::<u32>())
        .sum::<u32>();
    println!("{}", ans);
}

pub fn tree_preorder(root: usize, g: &[Vec<usize>]) -> Vec<usize> {
    let mut ord = Vec::new();
    fn dfs(x: usize, g: &[Vec<usize>], ord: &mut Vec<usize>) {
        ord.push(x);
        for &y in &g[x] {
            dfs(y, g, ord);
        }
    }
    dfs(root, g, &mut ord);
    ord
}

// ordtools {{{
#[allow(dead_code)]
mod ordtools {
    #![warn(missing_docs)]
    #![warn(missing_doc_code_examples)]

    pub trait Ordtools: PartialOrd + Sized {
        fn change_min(&mut self, mut rhs: Self) {
            if self > &mut rhs {
                *self = rhs;
            }
        }

        fn change_max(&mut self, mut rhs: Self) {
            if self < &mut rhs {
                *self = rhs;
            }
        }
    }

    impl<T: PartialOrd + Sized> Ordtools for T {}
}
// }}}
// ngtio {{{
#[allow(dead_code)]
mod ngtio {
    #![warn(missing_docs)]

    mod i {
        use std::{
            io::{self, BufRead},
            iter,
        };

        pub use self::{
            multi_token::{Leaf, Parser, ParserTuple, RawTuple, Tuple, VecLen},
            token::{Token, Usize1},
        };

        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) => {
#[allow(missing_docs)]
                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,
                <T as str::FromStr>::Err: fmt::Debug,
            {
                type Output = T;
                fn parse(s: &str) -> Self::Output {
                    s.parse().unwrap_or_else(|_| {
                        panic!("Parse error!: ({}: {})", s, any::type_name::<T>(),)
                    })
                }
            }

            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};

    pub mod prelude {
        pub use super::i::{Parser, ParserTuple, RawTuple, Token, Usize1};
    }
}
// }}}

Submission Info

Submission Time
Task B - PackDrop
User ngtkana
Language Rust (1.42.0)
Score 300
Code Size 11248 Byte
Status AC
Exec Time 4 ms
Memory 2260 KB

Judge Result

Set Name All
Score / Max Score 300 / 300
Status
AC × 27
Set Name Test Cases
All 00_sample_1, 00_sample_2, 00_sample_3, 10_random_00_n_5, 10_random_01_n_10, 10_random_02_n_2, 10_random_03_n_7, 10_random_04_n_6, 20_random_00_n_64, 20_random_01_n_95, 20_random_02_n_20, 20_random_03_n_33, 20_random_04_n_91, 30_random_00_n_793, 30_random_01_n_611, 30_random_02_n_852, 40_random_00_n_1000, 40_random_01_n_1000, 50_edge_one_00_n_11, 50_edge_one_01_n_101, 50_edge_one_02_n_999, 98_almost_straight_00_n_1000, 98_almost_straight_01_n_1000, 98_almost_straight_02_n_1000, 99_straight_00_n_10, 99_straight_01_n_100, 99_straight_02_n_1000
Case Name Status Exec Time Memory
00_sample_1 AC 4 ms 1964 KB
00_sample_2 AC 2 ms 2136 KB
00_sample_3 AC 2 ms 1980 KB
10_random_00_n_5 AC 2 ms 2056 KB
10_random_01_n_10 AC 2 ms 2080 KB
10_random_02_n_2 AC 4 ms 1984 KB
10_random_03_n_7 AC 2 ms 2156 KB
10_random_04_n_6 AC 3 ms 2080 KB
20_random_00_n_64 AC 2 ms 2088 KB
20_random_01_n_95 AC 2 ms 2032 KB
20_random_02_n_20 AC 4 ms 2080 KB
20_random_03_n_33 AC 2 ms 2028 KB
20_random_04_n_91 AC 2 ms 2124 KB
30_random_00_n_793 AC 2 ms 2008 KB
30_random_01_n_611 AC 2 ms 2160 KB
30_random_02_n_852 AC 2 ms 2096 KB
40_random_00_n_1000 AC 2 ms 2140 KB
40_random_01_n_1000 AC 2 ms 2216 KB
50_edge_one_00_n_11 AC 1 ms 2092 KB
50_edge_one_01_n_101 AC 2 ms 2140 KB
50_edge_one_02_n_999 AC 3 ms 2196 KB
98_almost_straight_00_n_1000 AC 2 ms 2260 KB
98_almost_straight_01_n_1000 AC 3 ms 2176 KB
98_almost_straight_02_n_1000 AC 3 ms 2192 KB
99_straight_00_n_10 AC 3 ms 2168 KB
99_straight_01_n_100 AC 1 ms 2172 KB
99_straight_02_n_1000 AC 3 ms 2220 KB