結果

問題 No.2677 Minmax Independent Set
ユーザー ngtkanangtkana
提出日時 2024-03-02 01:38:29
言語 Rust
(1.83.0 + proconio)
結果
AC  
実行時間 231 ms / 2,000 ms
コード長 8,398 bytes
コンパイル時間 14,049 ms
コンパイル使用メモリ 379,164 KB
実行使用メモリ 107,932 KB
最終ジャッジ日時 2024-09-30 00:12:11
合計ジャッジ時間 20,267 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 61
権限があれば一括ダウンロードができます

ソースコード

diff #

use input::input;
use input::input_array;
use tree_fold::Ops;

fn main() {
    let n = input::<usize>();
    let mut g = vec![Vec::new(); n];
    for _ in 0..n - 1 {
        let [i, j] = input_array::<usize, 2>();
        let i = i - 1;
        let j = j - 1;
        g[i].push(j);
        g[j].push(i);
    }
    let dp = O {}.two_way_tree_fold(0, &g);
    let ans = dp.iter().map(|value| value.black).min().unwrap();
    println!("{ans}");
}

#[derive(Clone, Copy)]
struct Acc {
    pwhite: usize,
    pblack: usize,
}
impl std::fmt::Debug for Acc {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("")
            .field(&self.pwhite)
            .field(&self.pblack)
            .finish()
    }
}
#[derive(Clone, Copy, Default)]
struct Value {
    white: usize,
    black: usize,
}
impl std::fmt::Debug for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("")
            .field(&self.white)
            .field(&self.black)
            .finish()
    }
}

struct O {}
impl tree_fold::Ops for O {
    type Acc = Acc;
    type Value = Value;

    fn identity(&self) -> Self::Acc {
        Acc {
            pwhite: 0,
            pblack: 0,
        }
    }

    fn proj(&self, value: Self::Value) -> Self::Acc {
        Acc {
            pwhite: value.white.max(value.black),
            pblack: value.white,
        }
    }

    fn mul(&self, acc: Self::Acc, value: Self::Acc) -> Self::Acc {
        Acc {
            pwhite: acc.pwhite + value.pwhite,
            pblack: acc.pblack + value.pblack,
        }
    }

    fn finish(&self, acc: Self::Acc, _index: usize) -> Self::Value {
        Value {
            white: acc.pwhite,
            black: acc.pblack + 1,
        }
    }
}

// tree_fold {{{
#[allow(dead_code)]
mod tree_fold {
    use std::fmt::Debug;
    pub trait Ops: Sized {
        type Value: Clone + Debug + Default;
        type Acc: Clone + Debug;
        fn identity(&self) -> Self::Acc;
        fn proj(&self, value: Self::Value) -> Self::Acc;
        fn mul(&self, acc: Self::Acc, value: Self::Acc) -> Self::Acc;
        fn finish(&self, acc: Self::Acc, index: usize) -> Self::Value;
        fn tree_fold(&self, root: usize, g: &[Vec<usize>]) -> Vec<Self::Value> {
            self.tree_fold_by_iter(root, g.len(), |x| g[x].iter().copied())
        }
        fn tree_fold_by_iter<I, A>(
            &self,
            root: usize,
            n: usize,
            g: impl Fn(usize) -> A,
        ) -> Vec<Self::Value>
        where
            I: Iterator<Item = usize>,
            A: IntoIterator<Item = usize, IntoIter = I>,
        {
            let sort_tree = sort_tree(root, n, &g);
            fold_up(self, &sort_tree)
        }
        fn two_way_tree_fold(&self, root: usize, g: &[Vec<usize>]) -> Vec<Self::Value> {
            self.two_way_tree_fold_by_iter(root, g.len(), |x| g[x].iter().copied())
        }
        fn two_way_tree_fold_by_iter<I, A>(
            &self,
            root: usize,
            n: usize,
            g: impl Fn(usize) -> A,
        ) -> Vec<Self::Value>
        where
            I: Iterator<Item = usize>,
            A: IntoIterator<Item = usize, IntoIter = I>,
        {
            let sort_tree = sort_tree(root, n, &g);
            let dp = fold_up_without_finish(self, &sort_tree);
            fold_down(self, &sort_tree, &dp)
        }
    }
    fn fold_up<O: Ops>(ops: &O, sort_tree: &SortedTree) -> Vec<O::Value> {
        let n = sort_tree.len();
        let mut dp = vec![O::Value::default(); n];
        for &x in sort_tree.ord.iter().rev() {
            dp[x] = ops.finish(
                sort_tree.child[x].iter().fold(ops.identity(), |acc, &y| {
                    ops.mul(acc, ops.proj(dp[y].clone()))
                }),
                x,
            );
        }
        dp
    }
    fn fold_up_without_finish<O: Ops>(ops: &O, sort_tree: &SortedTree) -> Vec<O::Acc> {
        let n = sort_tree.len();
        let mut dp = vec![ops.identity(); n];
        for &x in sort_tree.ord.iter().rev() {
            dp[x] = sort_tree.child[x].iter().fold(ops.identity(), |acc, &y| {
                ops.mul(acc, ops.proj(ops.finish(dp[y].clone(), y)))
            })
        }
        dp
    }
    fn fold_down<O: Ops>(ops: &O, sort_tree: &SortedTree, dp: &[O::Acc]) -> Vec<O::Value> {
        let n = sort_tree.len();
        let mut ep = vec![ops.identity(); n];
        let g = &sort_tree.child;
        for &x in &sort_tree.ord {
            if !g[x].is_empty() {
                let mut acc_rev = vec![ops.identity()];
                for &y in g[x].iter().rev().take(g[x].len() - 1) {
                    let aug = ops.mul(
                        acc_rev.last().unwrap().clone(),
                        ops.proj(ops.finish(dp[y].clone(), y)),
                    );
                    acc_rev.push(aug);
                }
                let mut acc = ep[x].clone();
                for (&y, acc_rev) in g[x].iter().zip(acc_rev.iter().rev().cloned()) {
                    ep[y] = ops.proj(ops.finish(ops.mul(acc.clone(), acc_rev), y));
                    acc = ops.mul(acc.clone(), ops.proj(ops.finish(dp[y].clone(), y)));
                }
            }
        }
        dp.iter()
            .zip(&ep)
            .enumerate()
            .map(|(x, (dp_x, ep_x))| ops.finish(ops.mul(dp_x.clone(), ep_x.clone()), x))
            .collect::<Vec<_>>()
    }
    fn sort_tree<I, A>(root: usize, n: usize, g: impl Fn(usize) -> A) -> SortedTree
    where
        I: Iterator<Item = usize>,
        A: IntoIterator<Item = usize, IntoIter = I>,
    {
        fn dfs<I, A>(
            x: usize,
            p: usize,
            g: &impl Fn(usize) -> A,
            child: &mut [Vec<usize>],
            parent: &mut [usize],
            ord: &mut Vec<usize>,
        ) where
            I: Iterator<Item = usize>,
            A: IntoIterator<Item = usize, IntoIter = I>,
        {
            parent[x] = p;
            ord.push(x);
            child[x] = g(x)
                .into_iter()
                .filter(|&y| y != p)
                .inspect(|&y| dfs(y, x, g, child, parent, ord))
                .collect::<Vec<_>>()
        }
        let mut parent = vec![!0; n];
        let mut child = vec![Vec::new(); n];
        let mut ord = Vec::new();
        dfs(root, root, &g, &mut child, &mut parent, &mut ord);
        SortedTree { child, parent, ord }
    }
    #[derive(Clone, Debug, Default, Hash, PartialEq)]
    struct SortedTree {
        child: Vec<Vec<usize>>,
        parent: Vec<usize>,
        ord: Vec<usize>,
    }
    impl SortedTree {
        fn len(&self) -> usize {
            self.child.len()
        }
    }
}
// }}}
// input {{{
#[allow(dead_code)]
mod input {
    use std::cell::Cell;
    use std::convert::TryFrom;
    use std::io::stdin;
    use std::io::BufRead;
    use std::io::BufReader;
    use std::io::Lines;
    use std::io::Stdin;
    use std::str::FromStr;
    use std::sync::Mutex;
    use std::sync::Once;
    type Server = Mutex<Lines<BufReader<Stdin>>>;
    static ONCE: Once = Once::new();
    pub struct Lazy(Cell<Option<Server>>);
    unsafe impl Sync for Lazy {}
    fn line() -> String {
        static SYNCER: Lazy = Lazy(Cell::new(None));
        ONCE.call_once(|| {
            SYNCER
                .0
                .set(Some(Mutex::new(BufReader::new(stdin()).lines())));
        });
        unsafe {
            (*SYNCER.0.as_ptr())
                .as_ref()
                .unwrap()
                .lock()
                .unwrap()
                .next()
                .unwrap()
                .unwrap()
        }
    }
    pub trait ForceFromStr: FromStr {
        fn force_from_str(s: &str) -> Self;
    }
    impl<T, E> ForceFromStr for T
    where
        T: FromStr<Err = E>,
        E: std::fmt::Debug,
    {
        fn force_from_str(s: &str) -> Self {
            s.parse().unwrap()
        }
    }
    pub fn input_array<T: ForceFromStr, const N: usize>() -> [T; N]
    where
        T: std::fmt::Debug,
    {
        <[_; N]>::try_from(input_vec()).unwrap()
    }
    pub fn input_vec<T: ForceFromStr>() -> Vec<T> {
        line()
            .split_whitespace()
            .map(T::force_from_str)
            .collect::<Vec<_>>()
    }
    pub fn input<T: ForceFromStr>() -> T {
        T::force_from_str(&line())
    }
}
// }}}
0